`C14NFile()` on a `Dom\XMLDocument` leaves the document changed and leaks memory
Description
On a Dom\XMLDocument, a successful C14NFile() leaves the document changed and leaks memory.
The following code:
<?php
$doc = Dom\XMLDocument::createFromString('<root xmlns:p="urn:p"><p:a p:x="1"/></root>');
var_dump($doc->C14NFile(__DIR__ . '/out.xml'));
echo $doc->saveXml(), "\n";
Resulted in this output:
int(48)
<?xml version="1.0" encoding="UTF-8"?>
<root><p:a xmlns:p="urn:p" p:x="1"/></root>
The xmlns:p attribute is gone from <root>. With C14N() instead of C14NFile(), the document still prints as <root xmlns:p="urn:p"><p:a p:x="1"/></root>.
With AddressSanitizer (./configure --enable-debug --enable-address-sanitizer), it also reports:
[Thu Nov 12 10:50:06 2026] Script: '.../test.php'
Zend/zend_hash.c(191) : Freeing 0x... (320 bytes), script=.../test.php
=== Total 1 memory leaks detected ===
==ERROR: LeakSanitizer: detected memory leaks
Indirect leak of 120 byte(s) in 1 object(s) allocated from:
#0 in malloc
#1 in xmlNewText (libxml2.so.2)
Indirect leak of 96 byte(s) in 1 object(s) allocated from:
#0 in malloc
#1 in xmlSetNsProp (libxml2.so.2)
Indirect leak of 6 byte(s) in 1 object(s) allocated from:
#0 in malloc
#1 in xmlStrdup (libxml2.so.2)
SUMMARY: AddressSanitizer: 222 byte(s) leaked in 3 allocation(s).
Description
https://github.com/php/php-src/blob/b8499682c360b2262ffe8581168c24eac5645d74/ext/dom/node.c#L2342-L2355
- For a modern document,
dom_canonicalization()first takes eachxmlns:*attribute off its element and records this in a hash table,links(lines 2215-2219). Only theclean_links:code at lines 2351-2355 puts the attributes back and freeslinks. - When
C14NFile()succeeds, line 2347 returns withRETURN_LONG(bytes)and skipsclean_links:.C14N()reaches it.
So after a successful C14NFile(), the xmlns:* attributes stay off their elements, and they and links are never freed.
I found this with the Infer static analyzer (Pulse), reproduced it with AddressSanitizer, and used Claude Opus 5.5 to help read the code and write this issue.
PHP Version
PHP 8.7.0-dev (cli) (built: Nov 12 2026 07:37:43) (NTS)
Copyright © The PHP Group and Contributors
Zend Engine v4.7.0-dev, Copyright © Zend by Perforce
with Zend OPcache v8.7.0-dev, Copyright ©, by Zend by Perforce
Operating System
Debian GNU/Linux 13 (trixie), x86_64