Skip to content

Commit 949fdc4

Browse files
committed
Merge branch 'PHP-8.5'
* PHP-8.5: ext/sysvshm: don't orphan the segment shm_attach() just created
2 parents a0d06f1 + af780bc commit 949fdc4

2 files changed

Lines changed: 39 additions & 0 deletions

File tree

ext/sysvshm/sysvshm.c

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -129,6 +129,7 @@ PHP_FUNCTION(shm_attach)
129129
zend_long shm_key_arg, shm_id, shm_size, shm_flag = 0666;
130130
key_t shm_key;
131131
bool shm_size_is_null = true;
132+
bool created = false;
132133

133134
if (SUCCESS != zend_parse_parameters(ZEND_NUM_ARGS(), "l|l!l", &shm_key_arg, &shm_size, &shm_size_is_null, &shm_flag)) {
134135
RETURN_THROWS();
@@ -159,10 +160,14 @@ PHP_FUNCTION(shm_attach)
159160
php_error_docref(NULL, E_WARNING, "Failed for key 0x" ZEND_XLONG_FMT ": %s", shm_key_arg, strerror(errno));
160161
RETURN_FALSE;
161162
}
163+
created = true;
162164
}
163165

164166
if ((shm_ptr = shmat(shm_id, NULL, 0)) == (void *) -1) {
165167
php_error_docref(NULL, E_WARNING, "Failed for key 0x" ZEND_XLONG_FMT ": %s", shm_key_arg, strerror(errno));
168+
if (created) {
169+
shmctl(shm_id, IPC_RMID, NULL);
170+
}
166171
RETURN_FALSE;
167172
}
168173

Lines changed: 34 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,34 @@
1+
--TEST--
2+
shm_attach() removes the segment it created when shmat() fails
3+
--EXTENSIONS--
4+
sysvshm
5+
posix
6+
--SKIPIF--
7+
<?php
8+
if (posix_geteuid() === 0) die('skip cannot run as root');
9+
?>
10+
--FILE--
11+
<?php
12+
$key = ftok(__FILE__, 't');
13+
14+
var_dump(shm_attach($key, 1024, 0));
15+
16+
$segment = shm_attach($key, 1024, 0600);
17+
18+
if (!$segment instanceof SysvSharedMemory) {
19+
die("the key is still held by the segment of the failed attach\n");
20+
}
21+
22+
try {
23+
var_dump(shm_put_var($segment, 1, 'value'));
24+
var_dump(shm_get_var($segment, 1));
25+
} finally {
26+
var_dump(shm_remove($segment));
27+
}
28+
?>
29+
--EXPECTF--
30+
Warning: shm_attach(): Failed for key 0x%x: %s in %s on line %d
31+
bool(false)
32+
bool(true)
33+
string(5) "value"
34+
bool(true)

0 commit comments

Comments
 (0)