Skip to content

ext/dom: Fix crash in named node map iterator key() without a current item - #471

Closed
iliaal wants to merge 1 commit into
PHP-8.4from
fix/dom-iterator-key
Closed

iliaal wants to merge 1 commit into
PHP-8.4from
fix/dom-iterator-key

Conversation

@iliaal

@iliaal iliaal commented Nov 19, 2026

Copy link
Copy Markdown
Owner

key() on the iterator of an attribute or DTD named node map reads the object out of the iterator's current item without checking that there is one. On an empty attribute map the object pointer is NULL, so $doc->documentElement->attributes->getIterator()->key() on <root/> segfaults. After next() moves past the last item it reads the wrapper that move_forward() has already released: valgrind with USE_ZEND_ALLOC=0 reports an invalid read of the freed object, and a debug build returned "".

php_dom_iterator_current_key() now returns null when there is no current object, as valid() and current() already treat that state as the end and as the SimpleXML and ArrayIterator key handlers do. Integer-keyed node lists are unaffected. The check is on IS_OBJECT rather than IS_UNDEF because on PHP-8.5 and later the end state is IS_NULL; that is from reading the code, as no 8.5 build with DOM was run.

Found while auditing DOM iterators during the registerNodeClass() fix. Both tests are red before and green after on a PHP-8.4 debug build; the exhausted case has its own file because it depends on reuse of the freed memory. The ext/dom suite passes, and both tests pass under valgrind.

… item

php_dom_iterator_current_key() read the object out of iterator->curobj
for attribute and DTD named node maps without checking that the iterator
has a current item. On an empty attribute map the object pointer is NULL
and InternalIterator::key() crashes; once the iterator has moved past the
last item it reads the wrapper move_forward() has already released.
Return null in that case, as valid() and current() already treat an
undefined curobj as the end. Integer-keyed node lists are unaffected.
@iliaal

iliaal commented Nov 19, 2026

Copy link
Copy Markdown
Owner Author

Moved to php#25595.

@iliaal iliaal closed this Nov 19, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant