From 8c5e63825ba7da16a0ffa41c0014251ca694c722 Mon Sep 17 00:00:00 2001
From: "Christoph M. Becker" <cmbecker69@gmx.de>
Date: Fri, 11 Dec 2020 16:47:42 +0100
Subject: [PATCH] Fix #77322: PharData::addEmptyDir('/') Possible integer
 overflow

`phar_path_check()` already strips a leading slash, so we must not
attempt to strip the trailing slash from an now empty directory name.
---
 ext/phar/tests/bug77322.phpt | 24 ++++++++++++++++++++++++
 ext/phar/util.c              |  2 +-
 2 files changed, 25 insertions(+), 1 deletion(-)
 create mode 100644 ext/phar/tests/bug77322.phpt

diff --git a/ext/phar/tests/bug77322.phpt b/ext/phar/tests/bug77322.phpt
new file mode 100644
index 000000000000..b9e5ce4dba43
--- /dev/null
+++ b/ext/phar/tests/bug77322.phpt
@@ -0,0 +1,24 @@
+--TEST--
+Bug #77322 (PharData::addEmptyDir('/') Possible integer overflow)
+--SKIPIF--
+<?php
+if (!extension_loaded('phar')) die('skip phar extension not available');
+?>
+--FILE--
+<?php
+$zip = new PharData(__DIR__ . '/bug77322.zip');
+$zip->addEmptyDir('/');
+var_dump($zip->count());
+
+$tar = new PharData(__DIR__ . '/bug77322.tar');
+$tar->addEmptyDir('/');
+var_dump($tar->count());
+?>
+--EXPECT--
+int(1)
+int(1)
+--CLEAN--
+<?php
+unlink(__DIR__ . '/bug77322.zip');
+unlink(__DIR__ . '/bug77322.tar');
+?>
diff --git a/ext/phar/util.c b/ext/phar/util.c
index 53982b0f8520..354f0dbaacb8 100644
--- a/ext/phar/util.c
+++ b/ext/phar/util.c
@@ -567,7 +567,7 @@ phar_entry_data *phar_get_or_create_entry_data(char *fname, size_t fname_len, ch
 	} else {
 		etemp.flags = etemp.old_flags = PHAR_ENT_PERM_DEF_FILE;
 	}
-	if (is_dir) {
+	if (is_dir && path_len) {
 		etemp.filename_len--; /* strip trailing / */
 		path_len--;
 	}