Commit edfc0da2dfd for php

commit edfc0da2dfd52b16137d128229c030a4418f14da
Author: David Carlier <devnexen@gmail.com>
Date:   Sun Nov 22 14:05:18 2026 +0000

    ext/phar: unset() of an entry with an open handle use-after-free.

    Flushing closed the archive stream while a handle on a deleted
    entry still referenced it. The open handle check now covers
    deleted entries.

    Close GH-25649

diff --git a/NEWS b/NEWS
index e05845aa30b..ab4b14dc13d 100644
--- a/NEWS
+++ b/NEWS
@@ -146,6 +146,8 @@ PHP                                                                        NEWS
 - Phar:
   . Fixed bug GH-25528 (Phar::setSignatureAlgorithm(): OpenSSL signing reads a
     freed private key). (Artem Ukrainskiy)
+  . Fixed use-after-free when unsetting an entry with an open handle.
+    (David Carlier)

 - POSIX:
   . Fixed bug GH-25530 (posix_get_last_error() returns an error from a
diff --git a/ext/phar/phar.c b/ext/phar/phar.c
index 5a51b25e288..1bdc2d80336 100644
--- a/ext/phar/phar.c
+++ b/ext/phar/phar.c
@@ -226,6 +226,21 @@ void phar_destroy_phar_data(phar_archive_data *phar) /* {{{ */

 	phar_metadata_tracker_free(&phar->metadata_tracker, phar->is_persistent);

+	if (phar->fp_refs) {
+		zend_ulong key;
+
+		ZEND_HASH_FOREACH_NUM_KEY(phar->fp_refs, key) {
+			php_stream *stream = (php_stream *) (uintptr_t) key;
+
+			if (stream != phar->fp && stream != phar->ufp) {
+				php_stream_close(stream);
+			}
+		} ZEND_HASH_FOREACH_END();
+		zend_hash_destroy(phar->fp_refs);
+		FREE_HASHTABLE(phar->fp_refs);
+		phar->fp_refs = NULL;
+	}
+
 	if (phar->fp) {
 		php_stream_close(phar->fp);
 		phar->fp = 0;
@@ -395,6 +410,59 @@ void destroy_phar_manifest_entry(zval *zv) /* {{{ */
 }
 /* }}} */

+void phar_fp_addref(phar_archive_data *phar, php_stream *fp) /* {{{ */
+{
+	zval *count, tmp;
+
+	if (!phar->fp_refs) {
+		ALLOC_HASHTABLE(phar->fp_refs);
+		zend_hash_init(phar->fp_refs, 2, NULL, NULL, 0);
+	}
+
+	count = zend_hash_index_find(phar->fp_refs, (zend_ulong) (uintptr_t) fp);
+	if (count) {
+		Z_LVAL_P(count)++;
+	} else {
+		ZVAL_LONG(&tmp, 1);
+		zend_hash_index_add_new(phar->fp_refs, (zend_ulong) (uintptr_t) fp, &tmp);
+	}
+}
+/* }}} */
+
+bool phar_fp_in_use(const phar_archive_data *phar, const php_stream *fp) /* {{{ */
+{
+	return phar->fp_refs && zend_hash_index_exists(phar->fp_refs, (zend_ulong) (uintptr_t) fp);
+}
+/* }}} */
+
+static void phar_entry_data_release_fp(phar_entry_data *idata) /* {{{ */
+{
+	phar_archive_data *phar = idata->phar;
+	php_stream *fp = idata->fp;
+	zval *count;
+
+	if (!fp) {
+		return;
+	}
+
+	count = phar->fp_refs ? zend_hash_index_find(phar->fp_refs, (zend_ulong) (uintptr_t) fp) : NULL;
+	if (count) {
+		if (--Z_LVAL_P(count) > 0) {
+			return;
+		}
+		zend_hash_index_del(phar->fp_refs, (zend_ulong) (uintptr_t) fp);
+		if (fp != phar->fp && fp != phar->ufp) {
+			php_stream_close(fp);
+		}
+		return;
+	}
+
+	if (fp != phar->fp && fp != phar->ufp && fp != idata->internal_file->fp) {
+		php_stream_close(fp);
+	}
+}
+/* }}} */
+
 void phar_entry_delref(phar_entry_data *idata) /* {{{ */
 {
 	if (idata->internal_file && !idata->internal_file->is_persistent) {
@@ -402,9 +470,7 @@ void phar_entry_delref(phar_entry_data *idata) /* {{{ */
 			idata->internal_file->fp_refcount = 0;
 		}

-		if (idata->fp && idata->fp != idata->phar->fp && idata->fp != idata->phar->ufp && idata->fp != idata->internal_file->fp) {
-			php_stream_close(idata->fp);
-		}
+		phar_entry_data_release_fp(idata);
 		/* if phar_get_or_create_entry_data returns a sub-directory, we have to free it */
 		if (idata->internal_file->is_temp_dir) {
 			destroy_phar_manifest_entry_int(idata->internal_file);
@@ -427,9 +493,7 @@ void phar_entry_remove(phar_entry_data *idata, char **error) /* {{{ */
 	phar = idata->phar;

 	if (idata->internal_file->fp_refcount < 2 && idata->internal_file->fileinfo_lock_count == 0) {
-		if (idata->fp && idata->fp != idata->phar->fp && idata->fp != idata->phar->ufp && idata->fp != idata->internal_file->fp) {
-			php_stream_close(idata->fp);
-		}
+		phar_entry_data_release_fp(idata);
 		zend_hash_str_del(&idata->phar->manifest, idata->internal_file->filename, idata->internal_file->filename_len);
 		idata->phar->refcount--;
 		efree(idata);
@@ -2534,8 +2598,6 @@ int phar_flush_ex(phar_archive_data *phar, zend_string *user_stub, bool is_defau
 	php_stream_filter *filter;
 	php_serialize_data_t metadata_hash;
 	smart_str main_metadata_str = {0};
-	bool free_fp = true;
-	bool free_ufp = true;
 	bool manifest_hack = false;
 	php_stream *shared_cfp = NULL;

@@ -2681,18 +2743,6 @@ int phar_flush_ex(phar_archive_data *phar, zend_string *user_stub, bool is_defau
 			/* remove this from the new phar */
 			continue;
 		}
-		if (entry->fp_refcount) {
-			/* open file pointers refer to this fp, do not free the stream */
-			switch (entry->fp_type) {
-				case PHAR_FP:
-					free_fp = false;
-					break;
-				case PHAR_UFP:
-					free_ufp = false;
-				default:
-					break;
-			}
-		}
 		/* after excluding deleted files, calculate manifest size in bytes and number of entries */
 		++new_manifest_count;
 		phar_add_virtual_dirs(phar, entry->filename, entry->filename_len);
@@ -3116,12 +3166,12 @@ int phar_flush_ex(phar_archive_data *phar, zend_string *user_stub, bool is_defau
 	/* finally, close the temp file, rename the original phar,
 	   move the temp to the old phar, unlink the old phar, and reload it into memory
 	*/
-	if (phar->fp && free_fp) {
+	if (phar->fp && !phar_fp_in_use(phar, phar->fp)) {
 		php_stream_close(phar->fp);
 	}

 	if (phar->ufp) {
-		if (free_ufp) {
+		if (!phar_fp_in_use(phar, phar->ufp)) {
 			php_stream_close(phar->ufp);
 		}
 		phar->ufp = NULL;
diff --git a/ext/phar/phar_internal.h b/ext/phar/phar_internal.h
index 4af29eaa460..996e8480dec 100644
--- a/ext/phar/phar_internal.h
+++ b/ext/phar/phar_internal.h
@@ -269,6 +269,8 @@ struct _phar_archive_data {
 	php_stream               *fp;
 	/* decompressed file contents are stored here */
 	php_stream               *ufp;
+	/* number of open entry handles per fp/ufp stream, current or replaced by a flush */
+	HashTable                *fp_refs;
 	int                      refcount;
 	uint32_t                 sig_flags;
 	uint32_t                 sig_len;
@@ -493,6 +495,8 @@ extern HashTable cached_alias;

 bool phar_archive_delref(phar_archive_data *phar);
 void phar_entry_delref(phar_entry_data *idata);
+void phar_fp_addref(phar_archive_data *phar, php_stream *fp);
+bool phar_fp_in_use(const phar_archive_data *phar, const php_stream *fp);

 phar_entry_info *phar_get_entry_info(phar_archive_data *phar, char *path, size_t path_len, char **error, int security);
 phar_entry_info *phar_get_entry_info_dir(phar_archive_data *phar, char *path, size_t path_len, char dir, char **error, int security);
diff --git a/ext/phar/stream.c b/ext/phar/stream.c
index dde8e375ad2..cc4ec672840 100644
--- a/ext/phar/stream.c
+++ b/ext/phar/stream.c
@@ -281,6 +281,7 @@ static php_stream * phar_wrapper_open_url(php_stream_wrapper *wrapper, const cha
 				idata->internal_file = entry;
 				if (!phar->is_persistent) {
 					++(entry->phar->refcount);
+					phar_fp_addref(phar, stream);
 				}
 				++(entry->fp_refcount);
 				php_url_free(resource);
diff --git a/ext/phar/tar.c b/ext/phar/tar.c
index 198f157ca1f..a976614bc18 100644
--- a/ext/phar/tar.c
+++ b/ext/phar/tar.c
@@ -776,8 +776,6 @@ zend_result phar_parse_tarfile(php_stream* fp, char *fname, size_t fname_len, ch
 struct _phar_pass_tar_info {
 	php_stream *old;
 	php_stream *new;
-	bool free_fp;
-	bool free_ufp;
 	char **error;
 };

@@ -904,19 +902,6 @@ static int phar_tar_writeheaders_int(phar_entry_info *entry, void *argument) /*
 		php_stream_write(fp->new, padding, ((entry->uncompressed_filesize +511)&~511) - entry->uncompressed_filesize);
 	}

-	if (entry->fp_refcount) {
-		/* open file pointers refer to this fp, do not free the stream */
-		switch (entry->fp_type) {
-			case PHAR_FP:
-				fp->free_fp = 0;
-				break;
-			case PHAR_UFP:
-				fp->free_ufp = 0;
-			default:
-				break;
-		}
-	}
-
 	entry->is_modified = 0;

 	if (entry->fp_type == PHAR_MOD && entry->fp != entry->phar->fp && entry->fp != entry->phar->ufp) {
@@ -1188,8 +1173,6 @@ int phar_tar_flush(phar_archive_data *phar, zend_string *user_stub, bool is_defa
 	pass.old = oldfile;
 	pass.new = newfile;
 	pass.error = error;
-	pass.free_fp = 1;
-	pass.free_ufp = 1;

 	if (phar_metadata_tracker_has_data(&phar->metadata_tracker, phar->is_persistent)) {
 		phar_entry_info *mentry;
@@ -1338,12 +1321,12 @@ int phar_tar_flush(phar_archive_data *phar, zend_string *user_stub, bool is_defa
 		return EOF;
 	}

-	if (phar->fp && pass.free_fp) {
+	if (phar->fp && !phar_fp_in_use(phar, phar->fp)) {
 		php_stream_close(phar->fp);
 	}

 	if (phar->ufp) {
-		if (pass.free_ufp) {
+		if (!phar_fp_in_use(phar, phar->ufp)) {
 			php_stream_close(phar->ufp);
 		}
 		phar->ufp = NULL;
diff --git a/ext/phar/tests/flush_open_handles.phpt b/ext/phar/tests/flush_open_handles.phpt
new file mode 100644
index 00000000000..80d9bcda90e
--- /dev/null
+++ b/ext/phar/tests/flush_open_handles.phpt
@@ -0,0 +1,40 @@
+--TEST--
+Phar: writing to an archive with open file handles
+--EXTENSIONS--
+phar
+--INI--
+phar.readonly=0
+phar.require_hash=0
+--FILE--
+<?php
+$fname = __DIR__ . '/' . basename(__FILE__, '.php') . '.phar';
+
+$phar = new Phar($fname);
+$phar['a'] = 'aaaa';
+$phar['b'] = 'bbbb';
+
+$fp = fopen('phar://' . $fname . '/a', 'r');
+$fp2 = fopen('phar://' . $fname . '/b', 'r');
+$phar['c'] = 'cccc';
+
+$streams = count(get_resources('stream'));
+for ($i = 0; $i < 5; $i++) {
+    $phar['d' . $i] = 'dddd';
+}
+var_dump(count(get_resources('stream')) === $streams);
+
+var_dump(fclose($fp));
+var_dump(fclose($fp2));
+var_dump(count($phar));
+var_dump($phar['c']->getContent());
+?>
+--CLEAN--
+<?php
+@unlink(__DIR__ . '/' . basename(__FILE__, '.clean.php') . '.phar');
+?>
+--EXPECT--
+bool(true)
+bool(true)
+bool(true)
+int(8)
+string(4) "cccc"
diff --git a/ext/phar/tests/flush_open_handles_compressed.phpt b/ext/phar/tests/flush_open_handles_compressed.phpt
new file mode 100644
index 00000000000..b8ba6a0b3bd
--- /dev/null
+++ b/ext/phar/tests/flush_open_handles_compressed.phpt
@@ -0,0 +1,46 @@
+--TEST--
+Phar: writing to an archive with open file handles on a compressed entry
+--EXTENSIONS--
+phar
+zlib
+--INI--
+phar.readonly=0
+phar.require_hash=0
+--FILE--
+<?php
+$fname = __DIR__ . '/' . basename(__FILE__, '.php') . '.phar';
+$copy = __DIR__ . '/' . basename(__FILE__, '.php') . '.copy.phar';
+
+$phar = new Phar($fname);
+$phar['a'] = 'aaaa';
+$phar['b'] = 'bbbb';
+$phar['a']->compress(Phar::GZ);
+$phar['b']->compress(Phar::GZ);
+
+$fp = fopen('phar://' . $fname . '/b', 'r');
+$fp2 = fopen('phar://' . $fname . '/b', 'r');
+var_dump(fread($fp, 4));
+$phar['c'] = 'cccc';
+unset($phar['b']);
+$phar['d'] = 'dddd';
+var_dump(fclose($fp));
+var_dump(fclose($fp2));
+
+copy($fname, $copy);
+$saved = new Phar($copy);
+var_dump(count($saved));
+var_dump($saved['a']->getContent());
+var_dump($saved['d']->getContent());
+?>
+--CLEAN--
+<?php
+@unlink(__DIR__ . '/' . basename(__FILE__, '.clean.php') . '.phar');
+@unlink(__DIR__ . '/' . basename(__FILE__, '.clean.php') . '.copy.phar');
+?>
+--EXPECT--
+string(4) "bbbb"
+bool(true)
+bool(true)
+int(3)
+string(4) "aaaa"
+string(4) "dddd"
diff --git a/ext/phar/tests/offsetunset_open_handle.phpt b/ext/phar/tests/offsetunset_open_handle.phpt
new file mode 100644
index 00000000000..23b1ac28083
--- /dev/null
+++ b/ext/phar/tests/offsetunset_open_handle.phpt
@@ -0,0 +1,43 @@
+--TEST--
+Phar: unsetting an entry with an open file handle
+--EXTENSIONS--
+phar
+--INI--
+phar.readonly=0
+phar.require_hash=0
+--FILE--
+<?php
+$fname = __DIR__ . '/' . basename(__FILE__, '.php') . '.phar';
+$copy = __DIR__ . '/' . basename(__FILE__, '.php') . '.copy.phar';
+
+$phar = new Phar($fname);
+$phar['a'] = 'aaaa';
+$phar['b'] = 'bbbb';
+
+$fp = fopen('phar://' . $fname . '/b', 'r');
+$fp2 = fopen('phar://' . $fname . '/b', 'r');
+unset($phar['b']);
+var_dump(fread($fp, 4));
+var_dump(fclose($fp));
+var_dump(fclose($fp2));
+var_dump(isset($phar['b']));
+var_dump($phar['a']->getContent());
+
+copy($fname, $copy);
+$saved = new Phar($copy);
+var_dump(count($saved));
+var_dump($saved['a']->getContent());
+?>
+--CLEAN--
+<?php
+@unlink(__DIR__ . '/' . basename(__FILE__, '.clean.php') . '.phar');
+@unlink(__DIR__ . '/' . basename(__FILE__, '.clean.php') . '.copy.phar');
+?>
+--EXPECT--
+bool(false)
+bool(true)
+bool(true)
+bool(false)
+string(4) "aaaa"
+int(1)
+string(4) "aaaa"
diff --git a/ext/phar/tests/rename_open_handle.phpt b/ext/phar/tests/rename_open_handle.phpt
new file mode 100644
index 00000000000..2bb6b1f45d0
--- /dev/null
+++ b/ext/phar/tests/rename_open_handle.phpt
@@ -0,0 +1,41 @@
+--TEST--
+Phar: renaming an entry with an open file handle
+--EXTENSIONS--
+phar
+--INI--
+phar.readonly=0
+phar.require_hash=0
+--FILE--
+<?php
+$fname = __DIR__ . '/' . basename(__FILE__, '.php') . '.phar';
+$copy = __DIR__ . '/' . basename(__FILE__, '.php') . '.copy.phar';
+$pname = 'phar://' . $fname;
+
+$phar = new Phar($fname);
+$phar['a'] = 'aaaa';
+$phar['b'] = 'bbbb';
+
+$fp = fopen($pname . '/b', 'r');
+$fp2 = fopen($pname . '/a', 'r');
+var_dump(rename($pname . '/b', $pname . '/c'));
+var_dump(fclose($fp));
+var_dump(fclose($fp2));
+
+copy($fname, $copy);
+$saved = new Phar($copy);
+var_dump(isset($saved['b']));
+var_dump($saved['a']->getContent());
+var_dump($saved['c']->getContent());
+?>
+--CLEAN--
+<?php
+@unlink(__DIR__ . '/' . basename(__FILE__, '.clean.php') . '.phar');
+@unlink(__DIR__ . '/' . basename(__FILE__, '.clean.php') . '.copy.phar');
+?>
+--EXPECT--
+bool(true)
+bool(true)
+bool(true)
+bool(false)
+string(4) "aaaa"
+string(4) "bbbb"
diff --git a/ext/phar/tests/tar/flush_open_handles.phpt b/ext/phar/tests/tar/flush_open_handles.phpt
new file mode 100644
index 00000000000..44f61b519c3
--- /dev/null
+++ b/ext/phar/tests/tar/flush_open_handles.phpt
@@ -0,0 +1,40 @@
+--TEST--
+Phar: writing to an archive with open file handles tar-based
+--EXTENSIONS--
+phar
+--INI--
+phar.readonly=0
+phar.require_hash=0
+--FILE--
+<?php
+$fname = __DIR__ . '/' . basename(__FILE__, '.php') . '.tar';
+
+$phar = new PharData($fname);
+$phar['a'] = 'aaaa';
+$phar['b'] = 'bbbb';
+
+$fp = fopen('phar://' . $fname . '/a', 'r');
+$fp2 = fopen('phar://' . $fname . '/b', 'r');
+$phar['c'] = 'cccc';
+
+$streams = count(get_resources('stream'));
+for ($i = 0; $i < 5; $i++) {
+    $phar['d' . $i] = 'dddd';
+}
+var_dump(count(get_resources('stream')) === $streams);
+
+var_dump(fclose($fp));
+var_dump(fclose($fp2));
+var_dump(count($phar));
+var_dump($phar['c']->getContent());
+?>
+--CLEAN--
+<?php
+@unlink(__DIR__ . '/' . basename(__FILE__, '.clean.php') . '.tar');
+?>
+--EXPECT--
+bool(true)
+bool(true)
+bool(true)
+int(8)
+string(4) "cccc"
diff --git a/ext/phar/tests/tar/offsetunset_open_handle.phpt b/ext/phar/tests/tar/offsetunset_open_handle.phpt
new file mode 100644
index 00000000000..77442e87d65
--- /dev/null
+++ b/ext/phar/tests/tar/offsetunset_open_handle.phpt
@@ -0,0 +1,43 @@
+--TEST--
+Phar: unsetting an entry with an open file handle tar-based
+--EXTENSIONS--
+phar
+--INI--
+phar.readonly=0
+phar.require_hash=0
+--FILE--
+<?php
+$fname = __DIR__ . '/' . basename(__FILE__, '.php') . '.tar';
+$copy = __DIR__ . '/' . basename(__FILE__, '.php') . '.copy.tar';
+
+$phar = new PharData($fname);
+$phar['a'] = 'aaaa';
+$phar['b'] = 'bbbb';
+
+$fp = fopen('phar://' . $fname . '/b', 'r');
+$fp2 = fopen('phar://' . $fname . '/b', 'r');
+unset($phar['b']);
+var_dump(fread($fp, 4));
+var_dump(fclose($fp));
+var_dump(fclose($fp2));
+var_dump(isset($phar['b']));
+var_dump($phar['a']->getContent());
+
+copy($fname, $copy);
+$saved = new PharData($copy);
+var_dump(count($saved));
+var_dump($saved['a']->getContent());
+?>
+--CLEAN--
+<?php
+@unlink(__DIR__ . '/' . basename(__FILE__, '.clean.php') . '.tar');
+@unlink(__DIR__ . '/' . basename(__FILE__, '.clean.php') . '.copy.tar');
+?>
+--EXPECT--
+bool(false)
+bool(true)
+bool(true)
+bool(false)
+string(4) "aaaa"
+int(1)
+string(4) "aaaa"
diff --git a/ext/phar/tests/zip/flush_mounted_count.phpt b/ext/phar/tests/zip/flush_mounted_count.phpt
new file mode 100644
index 00000000000..8eb8007488f
--- /dev/null
+++ b/ext/phar/tests/zip/flush_mounted_count.phpt
@@ -0,0 +1,32 @@
+--TEST--
+Phar: writing a zip-based archive with a mounted entry
+--EXTENSIONS--
+phar
+--INI--
+phar.readonly=0
+phar.require_hash=0
+--FILE--
+<?php
+$fname = __DIR__ . '/' . basename(__FILE__, '.php') . '.zip';
+$copy = __DIR__ . '/' . basename(__FILE__, '.php') . '.copy.zip';
+
+$phar = new PharData($fname);
+$phar['a'] = 'aaaa';
+Phar::mount('phar://' . $fname . '/mounted.txt', __FILE__);
+$phar['b'] = 'bbbb';
+
+copy($fname, $copy);
+$saved = new PharData($copy);
+var_dump(count($saved));
+var_dump(isset($saved['mounted.txt']));
+var_dump($saved['b']->getContent());
+?>
+--CLEAN--
+<?php
+@unlink(__DIR__ . '/' . basename(__FILE__, '.clean.php') . '.zip');
+@unlink(__DIR__ . '/' . basename(__FILE__, '.clean.php') . '.copy.zip');
+?>
+--EXPECT--
+int(2)
+bool(false)
+string(4) "bbbb"
diff --git a/ext/phar/tests/zip/flush_open_handles.phpt b/ext/phar/tests/zip/flush_open_handles.phpt
new file mode 100644
index 00000000000..1e79606e86d
--- /dev/null
+++ b/ext/phar/tests/zip/flush_open_handles.phpt
@@ -0,0 +1,40 @@
+--TEST--
+Phar: writing to an archive with open file handles zip-based
+--EXTENSIONS--
+phar
+--INI--
+phar.readonly=0
+phar.require_hash=0
+--FILE--
+<?php
+$fname = __DIR__ . '/' . basename(__FILE__, '.php') . '.zip';
+
+$phar = new PharData($fname);
+$phar['a'] = 'aaaa';
+$phar['b'] = 'bbbb';
+
+$fp = fopen('phar://' . $fname . '/a', 'r');
+$fp2 = fopen('phar://' . $fname . '/b', 'r');
+$phar['c'] = 'cccc';
+
+$streams = count(get_resources('stream'));
+for ($i = 0; $i < 5; $i++) {
+    $phar['d' . $i] = 'dddd';
+}
+var_dump(count(get_resources('stream')) === $streams);
+
+var_dump(fclose($fp));
+var_dump(fclose($fp2));
+var_dump(count($phar));
+var_dump($phar['c']->getContent());
+?>
+--CLEAN--
+<?php
+@unlink(__DIR__ . '/' . basename(__FILE__, '.clean.php') . '.zip');
+?>
+--EXPECT--
+bool(true)
+bool(true)
+bool(true)
+int(8)
+string(4) "cccc"
diff --git a/ext/phar/tests/zip/flush_open_handles_compressed.phpt b/ext/phar/tests/zip/flush_open_handles_compressed.phpt
new file mode 100644
index 00000000000..788ea7006e8
--- /dev/null
+++ b/ext/phar/tests/zip/flush_open_handles_compressed.phpt
@@ -0,0 +1,46 @@
+--TEST--
+Phar: writing to an archive with open file handles on a compressed entry zip-based
+--EXTENSIONS--
+phar
+zlib
+--INI--
+phar.readonly=0
+phar.require_hash=0
+--FILE--
+<?php
+$fname = __DIR__ . '/' . basename(__FILE__, '.php') . '.zip';
+$copy = __DIR__ . '/' . basename(__FILE__, '.php') . '.copy.zip';
+
+$phar = new PharData($fname);
+$phar['a'] = 'aaaa';
+$phar['b'] = 'bbbb';
+$phar['a']->compress(Phar::GZ);
+$phar['b']->compress(Phar::GZ);
+
+$fp = fopen('phar://' . $fname . '/b', 'r');
+$fp2 = fopen('phar://' . $fname . '/b', 'r');
+var_dump(fread($fp, 4));
+$phar['c'] = 'cccc';
+unset($phar['b']);
+$phar['d'] = 'dddd';
+var_dump(fclose($fp));
+var_dump(fclose($fp2));
+
+copy($fname, $copy);
+$saved = new PharData($copy);
+var_dump(count($saved));
+var_dump($saved['a']->getContent());
+var_dump($saved['d']->getContent());
+?>
+--CLEAN--
+<?php
+@unlink(__DIR__ . '/' . basename(__FILE__, '.clean.php') . '.zip');
+@unlink(__DIR__ . '/' . basename(__FILE__, '.clean.php') . '.copy.zip');
+?>
+--EXPECT--
+string(4) "bbbb"
+bool(true)
+bool(true)
+int(3)
+string(4) "aaaa"
+string(4) "dddd"
diff --git a/ext/phar/tests/zip/offsetunset_open_handle.phpt b/ext/phar/tests/zip/offsetunset_open_handle.phpt
new file mode 100644
index 00000000000..656d541db6c
--- /dev/null
+++ b/ext/phar/tests/zip/offsetunset_open_handle.phpt
@@ -0,0 +1,43 @@
+--TEST--
+Phar: unsetting an entry with an open file handle zip-based
+--EXTENSIONS--
+phar
+--INI--
+phar.readonly=0
+phar.require_hash=0
+--FILE--
+<?php
+$fname = __DIR__ . '/' . basename(__FILE__, '.php') . '.zip';
+$copy = __DIR__ . '/' . basename(__FILE__, '.php') . '.copy.zip';
+
+$phar = new PharData($fname);
+$phar['a'] = 'aaaa';
+$phar['b'] = 'bbbb';
+
+$fp = fopen('phar://' . $fname . '/b', 'r');
+$fp2 = fopen('phar://' . $fname . '/b', 'r');
+unset($phar['b']);
+var_dump(fread($fp, 4));
+var_dump(fclose($fp));
+var_dump(fclose($fp2));
+var_dump(isset($phar['b']));
+var_dump($phar['a']->getContent());
+
+copy($fname, $copy);
+$saved = new PharData($copy);
+var_dump(count($saved));
+var_dump($saved['a']->getContent());
+?>
+--CLEAN--
+<?php
+@unlink(__DIR__ . '/' . basename(__FILE__, '.clean.php') . '.zip');
+@unlink(__DIR__ . '/' . basename(__FILE__, '.clean.php') . '.copy.zip');
+?>
+--EXPECT--
+bool(false)
+bool(true)
+bool(true)
+bool(false)
+string(4) "aaaa"
+int(1)
+string(4) "aaaa"
diff --git a/ext/phar/util.c b/ext/phar/util.c
index 49932a8e384..d07c726fbe4 100644
--- a/ext/phar/util.c
+++ b/ext/phar/util.c
@@ -651,6 +651,9 @@ zend_result phar_get_entry_data(phar_entry_data **ret, char *fname, size_t fname
 	if (!phar->is_persistent) {
 		++(entry->fp_refcount);
 		++(entry->phar->refcount);
+		if ((*ret)->fp && ((*ret)->fp == phar->fp || (*ret)->fp == phar->ufp)) {
+			phar_fp_addref(phar, (*ret)->fp);
+		}
 	}

 	return SUCCESS;
diff --git a/ext/phar/zip.c b/ext/phar/zip.c
index fc95bd71b0f..de294c9cde7 100644
--- a/ext/phar/zip.c
+++ b/ext/phar/zip.c
@@ -866,8 +866,7 @@ struct _phar_zip_pass {
 	php_stream *centralfp;
 	php_stream *old;
 	char **error;
-	bool free_fp;
-	bool free_ufp;
+	uint32_t count;
 };
 /* perform final modification of zip contents for each file in the manifest before saving */
 static int phar_zip_changed_apply_int(phar_entry_info *entry, void *arg) /* {{{ */
@@ -1141,18 +1140,6 @@ static int phar_zip_changed_apply_int(phar_entry_info *entry, void *arg) /* {{{
 		entry->is_modified = 0;
 	} else {
 		entry->is_modified = 0;
-		if (entry->fp_refcount) {
-			/* open file pointers refer to this fp, do not free the stream */
-			switch (entry->fp_type) {
-				case PHAR_FP:
-					p->free_fp = 0;
-					break;
-				case PHAR_UFP:
-					p->free_ufp = 0;
-				default:
-					break;
-			}
-		}

 		if (!entry->is_dir && entry->compressed_filesize && (!p->old || SUCCESS != php_stream_copy_to_stream_ex(p->old, p->filefp, entry->compressed_filesize, NULL))) {
 			spprintf(p->error, 0, "unable to copy contents of file \"%s\" while creating zip-based phar \"%s\"", entry->filename, entry->phar->fname);
@@ -1171,6 +1158,8 @@ static int phar_zip_changed_apply_int(phar_entry_info *entry, void *arg) /* {{{
 		}
 	}

+	p->count++;
+
 	return ZEND_HASH_APPLY_KEEP;
 }
 /* }}} */
@@ -1428,20 +1417,13 @@ int phar_zip_flush(phar_archive_data *phar, zend_string *user_stub, bool is_defa
 		goto fperror;
 	}

-	pass.free_fp = pass.free_ufp = 1;
+	pass.count = 0;
 	memset(&eocd, 0, sizeof(eocd));

 	memcpy(eocd.signature, "PK\5\6", 4);
 	if (!phar->is_data && !phar->sig_flags) {
 		phar->sig_flags = PHAR_SIG_SHA256;
 	}
-	if (phar->sig_flags) {
-		PHAR_SET_16(eocd.counthere, zend_hash_num_elements(&phar->manifest) + 1);
-		PHAR_SET_16(eocd.count, zend_hash_num_elements(&phar->manifest) + 1);
-	} else {
-		PHAR_SET_16(eocd.counthere, zend_hash_num_elements(&phar->manifest));
-		PHAR_SET_16(eocd.count, zend_hash_num_elements(&phar->manifest));
-	}
 	zend_hash_apply_with_argument(&phar->manifest, phar_zip_changed_apply, (void *) &pass);

 	phar_metadata_tracker_try_ensure_has_serialized_data(&phar->metadata_tracker, phar->is_persistent);
@@ -1465,6 +1447,9 @@ int phar_zip_flush(phar_archive_data *phar, zend_string *user_stub, bool is_defa
 		goto temperror;
 	}

+	PHAR_SET_16(eocd.counthere, pass.count);
+	PHAR_SET_16(eocd.count, pass.count);
+
 	/* save zip */
 	cdir_size = php_stream_tell(pass.centralfp);
 	cdir_offset = php_stream_tell(pass.filefp);
@@ -1512,12 +1497,12 @@ int phar_zip_flush(phar_archive_data *phar, zend_string *user_stub, bool is_defa
 		}
 	}

-	if (phar->fp && pass.free_fp) {
+	if (phar->fp && !phar_fp_in_use(phar, phar->fp)) {
 		php_stream_close(phar->fp);
 	}

 	if (phar->ufp) {
-		if (pass.free_ufp) {
+		if (!phar_fp_in_use(phar, phar->ufp)) {
 			php_stream_close(phar->ufp);
 		}
 		phar->ufp = NULL;