Skip to content

Commit 2a2e0e8

Browse files
committed
Fix phpGH-20856: heap-use-after-free in SplDoublyLinkedList iterator when modifying during iteration
The element may be still in use in other places, so the linking pointers should be kept consistent. If not consistent, the "move forward" code in the sample test will read a stale, dangling pointer. Closes phpGH-20885.
1 parent f61b1fc commit 2a2e0e8

File tree

3 files changed

+35
-2
lines changed

3 files changed

+35
-2
lines changed

NEWS

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -20,6 +20,10 @@ PHP NEWS
2020
. Fixed bug GH-18139 (Memory leak when overriding some settings
2121
via readline_info()). (ndossche)
2222

23+
- SPL:
24+
. Fixed bug GH-20856 (heap-use-after-free in SplDoublyLinkedList iterator
25+
when modifying during iteration). (ndossche)
26+
2327
- Standard:
2428
. Fixed bug #74357 (lchown fails to change ownership of symlink with ZTS)
2529
(Jakub Zelenka)

ext/spl/spl_dllist.c

Lines changed: 5 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -764,11 +764,10 @@ PHP_METHOD(SplDoublyLinkedList, offsetUnset)
764764
element = spl_ptr_llist_offset(intern->llist, index, intern->flags & SPL_DLLIST_IT_LIFO);
765765

766766
if (element != NULL) {
767-
/* connect the neightbors */
767+
/* disconnect the neighbours */
768768
if (element->prev) {
769769
element->prev->next = element->next;
770770
}
771-
772771
if (element->next) {
773772
element->next->prev = element->prev;
774773
}
@@ -782,6 +781,10 @@ PHP_METHOD(SplDoublyLinkedList, offsetUnset)
782781
llist->tail = element->prev;
783782
}
784783

784+
/* Keep consistency if element is kept alive. */
785+
element->prev = NULL;
786+
element->next = NULL;
787+
785788
/* finally, delete the element */
786789
llist->count--;
787790

ext/spl/tests/gh20856.phpt

Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,26 @@
1+
--TEST--
2+
GH-20856 (heap-use-after-free in SplDoublyLinkedList iterator when modifying during iteration)
3+
--CREDITS--
4+
vi3tL0u1s
5+
iluuu1994
6+
--FILE--
7+
<?php
8+
$m = new SplStack;
9+
$m[] = new stdClass;
10+
$m[] = new stdClass;
11+
12+
foreach ($m as $l) {
13+
unset($m[0]);
14+
unset($m[0]);
15+
}
16+
17+
var_dump($m);
18+
?>
19+
--EXPECTF--
20+
object(SplStack)#%d (%d) {
21+
["flags":"SplDoublyLinkedList":private]=>
22+
int(6)
23+
["dllist":"SplDoublyLinkedList":private]=>
24+
array(0) {
25+
}
26+
}

0 commit comments

Comments
 (0)