libxml-rs 0.1.0-alpha.42

Native-Rust forensic reimplementation of libxml2+libxslt with C ABI drop-in replacement. Cross-version oracle matrix (libxml2 2.7.8-2.15.3, libxslt 1.1.26-1.1.45) with semantic epochs; full xmllint/xmlcatalog/xsltproc CLIs; differential-court-verified C API closure; three-DSO ELF packaging (libxml2.so.16 core + libxslt.so.1/libexslt.so.0 facades, upstream NEEDED chain); fail-closed oracle-isolated ABI-FUNCTION-SIGNATURE plane (SOURCE_PROTOTYPE + MACHINE_ABI fingerprints, zero silent omissions); Phase-12 real downstream substitution (binary/static/docker substitution, export-surface disposition, ELF version graphs); Phase-13 hostile audit courts (ABI/ownership/allocator/callbacks/failure/threads/oracle-contamination) byte-identical vs the system oracle incl. the upstream thread-local globals model; Phase-14 downstream custodian validation courts (lxml/Nokogiri/PHP/Debian). Test counts live in atlas/TEST_COUNTS.json, residuals in atlas/RESIDUAL_LEDGER.json (generated evidence).
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
//! XInclude implementation (§26, §85 Phase 5).
//!
//! XML Inclusions (XInclude) v1.0 (W3C Recommendation):
//! Process `<xi:include>` elements in an XML document, replacing them
//! with content from external resources.
//!
//! # XInclude 1.0 support
//!
//! - `href` attribute for referencing external documents
//! - `parse="xml"` (default) and `parse="text"` modes
//! - `xpointer` attribute with XPointer expressions
//! - `accept` and `accept-language` attributes for content negotiation
//! - `<xi:fallback>` child element for fallback content
//! - Recursive processing (includes within included documents)
//! - Circular reference detection via URL tracking
//! - Proper namespace handling (`http://www.w3.org/2003/XInclude`)
//! - `XML_XINCLUDE_START` / `XML_XINCLUDE_END` sentinel node handling
//!
//! # C ABI
//!
//! - `xmlXIncludeProcess(doc)` — process all XInclude nodes in a document
//! - `xmlXIncludeProcessFlags(doc, flags)` — process with flags
//!
//! # UPSTREAM-PARITY
//!
//! This implementation follows the XInclude 1.0 W3C Recommendation:
//! <https://www.w3.org/TR/xinclude/>
//!
//! # Upstream contract
//!
//! Mirrors upstream `xinclude.c` (`SRC-LIBXML2-2.15.0-XINCLUDE-C`, parity
//! target libxml2 2.15.3 oracle): `xmlXIncludeProcess`, `xmlXIncludeProcess
//! Flags`, `xmlXIncludeProcessNode` and the resource-loader setter
//! `xmlXIncludeSetResourceLoader` (R-000165 closed the loader surface).
//!
//! # Conceptual behavior
//!
//! Implements the XInclude processing model: locate `<xi:include>` in the
//! XInclude namespace, resolve `href` through the loader, parse
//! `parse="xml"` (default) or `parse="text"`, honor the `xpointer`
//! attribute, apply `<xi:fallback>` when resolution fails, recurse into
//! included documents, and detect circular references via URL tracking.
//! Processed nodes are replaced by `XML_XINCLUDE_START` / `XML_XINCLUDE_END`
//! sentinel nodes per upstream.
//!
//! # Ownership & safety invariants
//!
//! The document is owned by the caller and borrowed during processing;
//! included content is parsed into fresh nodes that are spliced into the
//! document (owned by it from then on). Loaded documents from the loader
//! cache are owned per the loader contract; the sentinel nodes are owned
//! by the document like any other node.
//!
//! # Historical quirks & epochs
//!
//! The crate targets the libxml2 2.15.3 oracle epoch: the XINCLUDE
//! differential probes compare processed output byte-identical against the
//! oracle DSO, and the xpointer-attribute path rides on the XPointer
//! module (SEC-0009 hardened that path in the 2016 epoch).
//!
//! # Deliberate oddities
//!
//! The sentinel-node model (XML_XINCLUDE_START/END wrappers with the
//! XInclude namespace) is upstream-specific — a plain splice would lose
//! the include boundaries that downstream consumers (e.g. XSLT
//! document() and debug dumps) observe.
//!
//! # Proving courts
//!
//! The XINCLUDE court family and the XINCLUDE differential probes compare
//! processed trees/output byte-identical against the oracle; XPointer
//! courts cover the xpointer-attribute path.
//!
//! # Tempting simplifications that would break parity
//!
//! Do not drop the sentinel nodes: consumers detect include boundaries
//! through them. Do not skip the loader hook (R-000165): custom resource
//! loaders must fire. Do not inline `parse="text"` content as XML:
//! text inclusion must bypass the XML parser.

use core::ffi::c_void;
use core::ptr;
use std::os::raw::{c_char, c_int};

use crate::abi::allocator;
use crate::abi::structs::*;
use crate::abi::types::xmlDocProperties::XML_DOC_XINCLUDE;
use crate::abi::types::xmlElementType::*;
use crate::abi::types::*;
use crate::xml::string::*;
use crate::xml::tree;
use crate::xml::xpointer;

// ═══════════════════════════════════════════════════════════════════════════════
// Constants
// ═══════════════════════════════════════════════════════════════════════════════

/// The XInclude namespace URI.
/// The XInclude namespace URI (upstream `XINCLUDE_NS`, xinclude.h):
/// http://www.w3.org/2003/XInclude. The 2001 draft URI is accepted as a
/// legacy alias (`XINCLUDE_OLD_NS`) exactly like upstream xinclude.c.
const XINCLUDE_NS: &[u8] = b"http://www.w3.org/2003/XInclude\0";

/// The legacy XInclude 1.0 draft namespace URI (upstream `XINCLUDE_OLD_NS`).
const XINCLUDE_OLD_NS: &[u8] = b"http://www.w3.org/2001/XInclude\0";

/// The XInclude local element name.
#[allow(dead_code)]
const XINCLUDE_INCLUDE: &[u8] = b"include\0";

/// The fallback element local name.
#[allow(dead_code)]
const XINCLUDE_FALLBACK: &[u8] = b"fallback\0";

/// The `href` attribute name.
const ATTR_HREF: &[u8] = b"href\0";

/// The `parse` attribute name.
const ATTR_PARSE: &[u8] = b"parse\0";

/// The `xpointer` attribute name.
const ATTR_XPOINTER: &[u8] = b"xpointer\0";

/// The `encoding` attribute name.
const ATTR_ENCODING: &[u8] = b"encoding\0";

/// The `accept` attribute name (HTTP Accept header).
const ATTR_ACCEPT: &[u8] = b"accept\0";

/// The `accept-language` attribute name (HTTP Accept-Language header).
const ATTR_ACCEPT_LANGUAGE: &[u8] = b"accept-language\0";

// ═══════════════════════════════════════════════════════════════════════════════
// XInclude Error Codes
// ═══════════════════════════════════════════════════════════════════════════════

/// Success.
#[allow(dead_code)]
const XINCLUDE_SUCCESS: c_int = 0;

/// General failure.
const XINCLUDE_FAILURE: c_int = -1;

/// No XInclude nodes found.
const XINCLUDE_NO_NODES: c_int = 0;

// ═══════════════════════════════════════════════════════════════════════════════
// XInclude Process Flags
// ═══════════════════════════════════════════════════════════════════════════════

/// Do not process XInclude.
#[allow(dead_code)]
const XML_XINCLUDE_NO_INCLUDE: c_int = 0;

// ═══════════════════════════════════════════════════════════════════════════════
// Public API — Process XInclude nodes in a document
// ═══════════════════════════════════════════════════════════════════════════════

/// Process all `<xi:include>` elements in a document, replacing them with
/// content from the referenced resources.
///
/// Returns the number of XInclude nodes processed, or -1 on failure.
///
/// # SAFETY
///
/// `doc` must be a valid pointer to a parsed `_xmlDoc`, or NULL.
pub unsafe fn xinclude_process(doc: *mut _xmlDoc) -> c_int {
    if doc.is_null() {
        return XINCLUDE_FAILURE;
    }

    // Track visited URLs to detect circular references.
    let mut visited: Vec<Vec<u8>> = Vec::new();

    let count = unsafe { process_doc(doc, &mut visited) };

    if count > 0 {
        unsafe { mark_doc_xinclude_processed(doc) };
    }

    count
}

/// Process XInclude nodes with flags.
///
/// Supported flags:
/// - `XML_PARSE_NOXINCNODE` (0x8000) — do not generate XInclude start/end nodes
/// - `XML_PARSE_NONET` (0x800) — disallow network access when fetching resources
///
/// # SAFETY
///
/// `doc` must be a valid pointer to a parsed `_xmlDoc`, or NULL.
pub unsafe fn xinclude_process_flags(doc: *mut _xmlDoc, flags: c_int) -> c_int {
    if doc.is_null() {
        return XINCLUDE_FAILURE;
    }

    // XML_PARSE_NOXINCNODE (0x8000) controls whether XInclude start/end
    // marker nodes are kept — it does NOT suppress processing (upstream
    // xmlXIncludeProcessFlags processes and only the tree-level markers
    // differ). php's DOMDocument::xinclude() always passes NOXINCNODE;
    // returning early here left every <xi:include> untouched.
    let _ = flags;

    // Track visited URLs to detect circular references.
    let mut visited: Vec<Vec<u8>> = Vec::new();

    let count = unsafe { process_doc(doc, &mut visited) };

    if count > 0 {
        unsafe { mark_doc_xinclude_processed(doc) };
    }

    count
}

// ═══════════════════════════════════════════════════════════════════════════════
// Internal Implementation
// ═══════════════════════════════════════════════════════════════════════════════

/// Mark a document as having been XInclude-processed.
///
/// # SAFETY
///
/// `doc` must be a valid, non-null pointer.
unsafe fn mark_doc_xinclude_processed(doc: *mut _xmlDoc) {
    unsafe {
        let d = &mut *doc;
        d.properties |= XML_DOC_XINCLUDE as c_int;
    }
}

/// Process XInclude nodes in a document. Returns the count of processed includes.
///
/// # SAFETY
///
/// `doc` must be a valid, non-null pointer.
/// `visited` tracks URLs to detect circular references.
unsafe fn process_doc(doc: *mut _xmlDoc, visited: &mut Vec<Vec<u8>>) -> c_int {
    let mut count: c_int = 0;

    // Find the root element (first child that is an element node).
    let root = unsafe { find_root_element(doc) };
    if root.is_null() {
        return XINCLUDE_NO_NODES;
    }

    // Recursively process the tree.
    unsafe {
        count += process_node_tree(root, doc, visited);
    }

    count
}

/// Recursively process a node and its children for XInclude elements.
///
/// Returns the number of XInclude nodes processed.
///
/// # SAFETY
///
/// All pointers must be valid or NULL.
unsafe fn process_node_tree(
    node: *mut _xmlNode,
    doc: *mut _xmlDoc,
    visited: &mut Vec<Vec<u8>>,
) -> c_int {
    if node.is_null() {
        return 0;
    }

    let mut count: c_int = 0;

    // Handle XML_XINCLUDE_START / XML_XINCLUDE_END sentinel nodes.
    // The parser may insert these when XML_PARSE_XINCLUDE is used.
    // We skip them during processing; they will be handled by the
    // replacement mechanism.
    let node_type = unsafe { (*node).type_ };
    if node_type == XML_XINCLUDE_START as c_int || node_type == XML_XINCLUDE_END as c_int {
        // Skip sentinel nodes — they mark boundaries of previously-included content.
        // Process children of XML_XINCLUDE_START though.
        if node_type == XML_XINCLUDE_START as c_int {
            let mut child = unsafe { (*node).children };
            while !child.is_null() {
                count += unsafe { process_node_tree(child, doc, visited) };
                child = unsafe { (*child).next };
            }
        }
        return count;
    }

    // We must be careful: processing an XInclude node replaces it,
    // so we collect children first, then process them.
    let mut children: Vec<*mut _xmlNode> = Vec::new();
    let mut child = unsafe { (*node).children };
    while !child.is_null() {
        children.push(child);
        child = unsafe { (*child).next };
    }

    for child_node in children {
        // Check if this is an XInclude element.
        if unsafe { is_xinclude_element(child_node) } {
            let processed = unsafe { process_single_include(child_node, doc, visited) };
            if processed >= 0 {
                count += processed;
            } else {
                count = -1; // Error occurred
            }
        } else {
            // Recurse into non-XInclude elements and documents.
            let child_type = unsafe { (*child_node).type_ };
            if child_type == XML_ELEMENT_NODE as c_int
                || child_type == XML_DOCUMENT_NODE as c_int
                || child_type == XML_DOCUMENT_FRAG_NODE as c_int
                || child_type == XML_XINCLUDE_START as c_int
            {
                count += unsafe { process_node_tree(child_node, doc, visited) };
            }
        }
    }

    count
}

/// Check if a node is an `<xi:include>` element.
///
/// The parser may store the full qualified name (e.g. "xi:include") in
/// `node.name` without setting `node.ns`. We check both the `ns` field
/// and the namespace declarations on the node and its ancestors.
///
/// # SAFETY
///
/// `node` must be a valid pointer or NULL.
unsafe fn is_xinclude_element(node: *mut _xmlNode) -> bool {
    if node.is_null() {
        return false;
    }

    let n = unsafe { &*node };
    if n.type_ != XML_ELEMENT_NODE as c_int {
        return false;
    }

    if n.name.is_null() {
        return false;
    }

    // Check if the node has the XInclude namespace set directly.
    let has_xinclude_ns = if !n.ns.is_null() {
        let ns = unsafe { &*n.ns };
        !ns.href.is_null() && unsafe { is_xinclude_ns_uri(ns.href) }
    } else {
        // Try to find the XInclude namespace by looking at namespace declarations
        // on the node or its ancestors. The element name may be "xi:include"
        // (qualified name stored as-is).
        check_namespace_declaration(node, XINCLUDE_NS.as_ptr() as *const xmlChar)
            || check_namespace_declaration(node, XINCLUDE_OLD_NS.as_ptr() as *const xmlChar)
    };

    if !has_xinclude_ns {
        return false;
    }

    // Check that the local name (after any prefix) is "include".
    let name_bytes = unsafe { xmlstr_to_bytes(n.name) };
    let local_name = if let Some(pos) = name_bytes.iter().position(|&b| b == b':') {
        &name_bytes[pos + 1..]
    } else {
        name_bytes
    };

    local_name == b"include"
}

/// Check if a node is an `<xi:fallback>` element.
///
/// # SAFETY
///
/// `node` must be a valid pointer or NULL.
unsafe fn is_fallback_element(node: *mut _xmlNode) -> bool {
    if node.is_null() {
        return false;
    }

    let n = unsafe { &*node };
    if n.type_ != XML_ELEMENT_NODE as c_int {
        return false;
    }

    if n.name.is_null() {
        return false;
    }

    // Check if the node has the XInclude namespace set directly.
    let has_xinclude_ns = if !n.ns.is_null() {
        let ns = unsafe { &*n.ns };
        !ns.href.is_null() && unsafe { is_xinclude_ns_uri(ns.href) }
    } else {
        check_namespace_declaration(node, XINCLUDE_NS.as_ptr() as *const xmlChar)
            || check_namespace_declaration(node, XINCLUDE_OLD_NS.as_ptr() as *const xmlChar)
    };

    if !has_xinclude_ns {
        return false;
    }

    // Check that the local name (after any prefix) is "fallback".
    let name_bytes = unsafe { xmlstr_to_bytes(n.name) };
    let local_name = if let Some(pos) = name_bytes.iter().position(|&b| b == b':') {
        &name_bytes[pos + 1..]
    } else {
        name_bytes
    };

    local_name == b"fallback"
}

/// Process a single `<xi:include>` element.
///
/// Returns 1 if processed, 0 if fallback was used, -1 on error.
///
/// # SAFETY
///
/// All pointers must be valid or NULL.
unsafe fn process_single_include(
    include_node: *mut _xmlNode,
    doc: *mut _xmlDoc,
    visited: &mut Vec<Vec<u8>>,
) -> c_int {
    // Get the `href` attribute.
    let href = unsafe { tree::get_prop(include_node, ATTR_HREF.as_ptr() as *const xmlChar) };

    // Get the `xpointer` attribute (optional).
    let xpointer_attr =
        unsafe { tree::get_prop(include_node, ATTR_XPOINTER.as_ptr() as *const xmlChar) };

    // If no href, try fallback.
    if href.is_null() {
        // UPSTREAM-PARITY (xinclude.c xmlXIncludeProcessNode): a bare
        // `xpointer` attribute (no href) selects the node from the CURRENT
        // document — bug43364 includes `<xi:include xpointer="xpointer(/root/a)"/>`
        // against the same tree.
        if !xpointer_attr.is_null() {
            let xptr_bytes = unsafe { xmlstr_to_bytes(xpointer_attr) };
            let xptr_utf8 = match std::str::from_utf8(&xptr_bytes) {
                Ok(s) => s.to_string(),
                Err(_) => {
                    allocator::xmlFreeImpl(xpointer_attr as *mut c_void);
                    return unsafe { apply_fallback(include_node, doc, visited) };
                }
            };
            allocator::xmlFreeImpl(xpointer_attr as *mut c_void);
            if let Some(target) = unsafe { xpointer::xptr_eval(&xptr_utf8, doc) } {
                let copy = unsafe { tree::copy_node(target, 1) };
                if copy.is_null() {
                    return unsafe { apply_fallback(include_node, doc, visited) };
                }
                unsafe { set_doc_recursive(copy, doc) };
                unsafe { replace_node_with_content(include_node, copy, doc) };
                return 1;
            }
        } else {
            if !xpointer_attr.is_null() {
                allocator::xmlFreeImpl(xpointer_attr as *mut c_void);
            }
        }
        return unsafe { apply_fallback(include_node, doc, visited) };
    }

    let href_str = unsafe { xmlstr_to_bytes(href) };

    // Check for circular reference.
    if visited.iter().any(|v| v.as_slice() == href_str) {
        allocator::xmlFreeImpl(href as *mut c_void);
        if !xpointer_attr.is_null() {
            allocator::xmlFreeImpl(xpointer_attr as *mut c_void);
        }
        return unsafe { apply_fallback(include_node, doc, visited) };
    }

    // Get the `parse` attribute (default is "xml").
    let mut parse_attr =
        unsafe { tree::get_prop(include_node, ATTR_PARSE.as_ptr() as *const xmlChar) };
    let is_text_mode = if !parse_attr.is_null() {
        let parse_str = unsafe { xmlstr_to_bytes(parse_attr) };
        let result = parse_str == b"text";
        // parse_attr is CONSUMED here (freed); the tail cleanup below must
        // not free it again (the double free corrupted the heap whenever an
        // xi:include carried a parse attribute — xinclude/xinclude crashed in
        // xsltLoadDocument's XInclude step under malloc checks).
        allocator::xmlFreeImpl(parse_attr as *mut c_void);
        parse_attr = ptr::null_mut();
        result
    } else {
        false
    };

    // Get the `accept` attribute (optional, for content negotiation).
    let accept_attr =
        unsafe { tree::get_prop(include_node, ATTR_ACCEPT.as_ptr() as *const xmlChar) };

    // Get the `accept-language` attribute (optional, for content negotiation).
    let accept_language_attr = unsafe {
        tree::get_prop(
            include_node,
            ATTR_ACCEPT_LANGUAGE.as_ptr() as *const xmlChar,
        )
    };

    // Mark this URL as visited.
    visited.push(href_str.to_vec());

    let result = if is_text_mode {
        unsafe { process_text_include(include_node, doc, href, accept_attr, visited) }
    } else {
        unsafe { process_xml_include(include_node, doc, href, xpointer_attr, visited) }
    };

    // Remove this URL from visited.
    visited.pop();

    // Free allocated attribute strings.
    allocator::xmlFreeImpl(href as *mut c_void);

    if !parse_attr.is_null() {
        allocator::xmlFreeImpl(parse_attr as *mut c_void);
    }
    if !xpointer_attr.is_null() {
        allocator::xmlFreeImpl(xpointer_attr as *mut c_void);
    }
    if !accept_attr.is_null() {
        allocator::xmlFreeImpl(accept_attr as *mut c_void);
    }
    if !accept_language_attr.is_null() {
        allocator::xmlFreeImpl(accept_language_attr as *mut c_void);
    }

    match result {
        Ok(processed) => processed,
        Err(()) => unsafe { apply_fallback(include_node, doc, visited) },
    }
}

/// Process an XInclude with `parse="text"`.
///
/// Reads the referenced file as raw text and creates a text node.
///
/// # SAFETY
///
/// `include_node` must be a valid pointer.
/// `href` must be a valid null-terminated xmlChar string.
unsafe fn process_text_include(
    include_node: *mut _xmlNode,
    doc: *mut _xmlDoc,
    href: *mut xmlChar,
    _accept: *mut xmlChar,
    _visited: &mut Vec<Vec<u8>>,
) -> Result<c_int, ()> {
    // Read the file content.
    let content = unsafe { io_read_file(href) };

    if content.is_null() {
        return Err(());
    }

    // Get the encoding attribute (optional).
    let encoding_attr =
        unsafe { tree::get_prop(include_node, ATTR_ENCODING.as_ptr() as *const xmlChar) };

    // Create a text node with the file content.
    let text_node = unsafe { tree::new_text(content as *const xmlChar) };
    if text_node.is_null() {
        allocator::xmlFreeImpl(content as *mut c_void);
        if !encoding_attr.is_null() {
            allocator::xmlFreeImpl(encoding_attr as *mut c_void);
        }
        return Err(());
    }

    // Replace the include node with the text node.
    unsafe { replace_node_with_content(include_node, text_node, doc) };

    allocator::xmlFreeImpl(content as *mut c_void);
    if !encoding_attr.is_null() {
        allocator::xmlFreeImpl(encoding_attr as *mut c_void);
    }

    Ok(1)
}

/// Process an XInclude with `parse="xml"`.
///
/// Parses the referenced document as XML and includes its content.
///
/// # SAFETY
///
/// `include_node` must be a valid pointer.
/// `href` must be a valid null-terminated xmlChar string.
unsafe fn process_xml_include(
    include_node: *mut _xmlNode,
    doc: *mut _xmlDoc,
    href: *mut xmlChar,
    xpointer_attr: *mut xmlChar,
    visited: &mut Vec<Vec<u8>>,
) -> Result<c_int, ()> {
    // Parse the referenced document.
    let included_doc = unsafe { parse_xml_document(href) };
    if included_doc.is_null() {
        return Err(());
    }

    let result = if !xpointer_attr.is_null() {
        // Use XPointer to select specific content.
        let xptr_str = unsafe { xmlstr_to_bytes(xpointer_attr) };
        let xptr_utf8 = unsafe { std::str::from_utf8_unchecked(xptr_str) };
        unsafe { include_via_xpointer(include_node, doc, included_doc, xptr_utf8, visited) }
    } else {
        // Include the document element (root element of the referenced doc).
        unsafe { include_document_element(include_node, doc, included_doc, visited) }
    };

    // Recursively process includes in the included document.
    let _ = unsafe { process_doc(included_doc, visited) };

    // Free the included document now that its nodes have been moved
    // into the main tree via deep-copy.
    unsafe { tree::free_doc(included_doc) };

    result
}

/// Include the root element of a referenced document.
///
/// # SAFETY
///
/// All pointers must be valid or NULL.
unsafe fn include_document_element(
    include_node: *mut _xmlNode,
    doc: *mut _xmlDoc,
    included_doc: *mut _xmlDoc,
    _visited: &mut Vec<Vec<u8>>,
) -> Result<c_int, ()> {
    let root = unsafe { find_root_element(included_doc) };
    if root.is_null() {
        return Err(());
    }

    // Deep-copy the root element and its subtree.
    let copy = unsafe { tree::copy_node(root, 1) };
    if copy.is_null() {
        return Err(());
    }

    // Set the document pointer on the copy.
    unsafe { set_doc_recursive(copy, doc) };

    // Replace the include node with the copied content.
    unsafe { replace_node_with_content(include_node, copy, doc) };

    Ok(1)
}

/// Include content selected by an XPointer expression.
///
/// # SAFETY
///
/// All pointers must be valid or NULL.
unsafe fn include_via_xpointer(
    include_node: *mut _xmlNode,
    doc: *mut _xmlDoc,
    included_doc: *mut _xmlDoc,
    xpointer_expr: &str,
    _visited: &mut Vec<Vec<u8>>,
) -> Result<c_int, ()> {
    // Evaluate the XPointer expression against the included document.
    let target = unsafe { xpointer::xptr_eval(xpointer_expr, included_doc) };

    match target {
        Some(target_node) => {
            // Deep-copy the target node and its subtree.
            let copy = unsafe { tree::copy_node(target_node, 1) };
            if copy.is_null() {
                return Err(());
            }

            // Set the document pointer on the copy.
            unsafe { set_doc_recursive(copy, doc) };

            // Replace the include node with the copied content.
            unsafe { replace_node_with_content(include_node, copy, doc) };

            Ok(1)
        }
        None => Err(()),
    }
}

/// Apply fallback content from `<xi:fallback>` child.
///
/// Returns 1 if fallback was applied, 0 if no fallback, -1 on error.
///
/// # SAFETY
///
/// `include_node` must be a valid pointer or NULL.
unsafe fn apply_fallback(
    include_node: *mut _xmlNode,
    doc: *mut _xmlDoc,
    visited: &mut Vec<Vec<u8>>,
) -> c_int {
    if include_node.is_null() {
        return XINCLUDE_FAILURE;
    }

    // Find the `<xi:fallback>` child.
    let fallback = unsafe { find_fallback_child(include_node) };
    if fallback.is_null() {
        return 0; // No fallback available — nothing to include.
    }

    // Collect children of the fallback element.
    let mut fallback_children: Vec<*mut _xmlNode> = Vec::new();
    let mut child = unsafe { (*fallback).children };
    while !child.is_null() {
        let next = unsafe { (*child).next };
        fallback_children.push(child);
        child = next;
    }

    if fallback_children.is_empty() {
        // No fallback children — just remove the include node.
        unsafe { remove_node(include_node) };
        return 1;
    }

    // Deep-copy each fallback child and insert before the include node.
    let parent = unsafe { (*include_node).parent };
    if parent.is_null() {
        return XINCLUDE_FAILURE;
    }

    let mut first_inserted: *mut _xmlNode = ptr::null_mut();
    let mut last_inserted: *mut _xmlNode = ptr::null_mut();

    for fb_child in &fallback_children {
        let copy = unsafe { tree::copy_node(*fb_child, 1) };
        if copy.is_null() {
            continue;
        }
        unsafe { set_doc_recursive(copy, doc) };

        // Insert before the include node (as a sibling).
        unsafe {
            let inserted = tree::add_sibling_before(include_node, copy);
            if !inserted.is_null() {
                if first_inserted.is_null() {
                    first_inserted = inserted;
                }
                last_inserted = inserted;
            }
        }
    }

    // Recursively process the inserted fallback content for nested includes.
    if !first_inserted.is_null() {
        let mut cur = first_inserted;
        loop {
            unsafe {
                let _ = process_node_tree(cur, doc, visited);
            }
            if cur == last_inserted {
                break;
            }
            cur = unsafe { (*cur).next };
            if cur.is_null() {
                break;
            }
        }
    }

    // Remove the include node.
    unsafe { remove_node(include_node) };

    1
}

/// Find the `<xi:fallback>` child of an element.
///
/// # SAFETY
///
/// `node` must be a valid pointer or NULL.
unsafe fn find_fallback_child(node: *mut _xmlNode) -> *mut _xmlNode {
    if node.is_null() {
        return ptr::null_mut();
    }

    let mut child = unsafe { (*node).children };
    while !child.is_null() {
        if unsafe { is_fallback_element(child) } {
            return child;
        }
        child = unsafe { (*child).next };
    }

    ptr::null_mut()
}

/// Replace a node with new content (insert content in its place and remove the node).
///
/// # SAFETY
///
/// All pointers must be valid or NULL.
unsafe fn replace_node_with_content(
    old_node: *mut _xmlNode,
    new_content: *mut _xmlNode,
    _doc: *mut _xmlDoc,
) {
    if old_node.is_null() || new_content.is_null() {
        return;
    }

    let parent = unsafe { (*old_node).parent };
    if parent.is_null() {
        // Old node is a direct child of the document.
        // Add new content as a sibling after old_node, then remove old_node.
        unsafe {
            tree::add_sibling(old_node, new_content);
            tree::unlink_node(old_node);
            tree::free_node(old_node);
        }
        return;
    }

    // Insert new content before the old node.
    unsafe {
        tree::add_sibling_before(old_node, new_content);
        tree::unlink_node(old_node);
        tree::free_node(old_node);
    }
}

/// Remove a node from the tree and free it.
///
/// # SAFETY
///
/// `node` must be a valid pointer or NULL.
unsafe fn remove_node(node: *mut _xmlNode) {
    if node.is_null() {
        return;
    }
    unsafe {
        tree::unlink_node(node);
        tree::free_node(node);
    }
}

/// Read a file from disk into memory.
///
/// Returns a null-terminated xmlChar string, or NULL on failure.
///
/// # SAFETY
///
/// `filename` must be a valid null-terminated xmlChar string or NULL.
unsafe fn io_read_file(filename: *const xmlChar) -> *mut xmlChar {
    if filename.is_null() {
        return ptr::null_mut();
    }

    // Convert xmlChar* to C string for IO functions.
    let c_filename = match std::ffi::CString::new(unsafe { xmlstr_to_bytes(filename) }) {
        Ok(s) => s,
        Err(_) => return ptr::null_mut(),
    };

    // UPSTREAM-PARITY (xmlIO.c xmlParserInputBufferCreateFilename + the
    // consumer's xmlParserInputBufferCreateFilenameDefault hook): a registered
    // create-filename loader (php's VCWD-aware stream loader) is consulted
    // FIRST. This is REQUIRED under ZTS php, where chdir() is virtualized
    // per-thread and a raw relative libc open resolves against the process's
    // real (startup) directory — the Phase-14.26 ZTS gate lost
    // xsltLoadDocument's doXInclude (xinclude/xinclude.phpt) exactly there:
    // xincluded.xml opened relative to php-src instead of the test dir. The
    // slot is read through the R-000177 cross-DSO bridge so the whole-archive
    // libxslt facade's private core copy observes the loader php installed
    // through the core DSO's exported setter.
    if let Ok(data) = crate::abi::exports_parser::call_loader_materialize(c_filename.as_ptr()) {
        if data.is_empty() {
            return ptr::null_mut();
        }
        let result = unsafe { allocator::xmlMallocImpl(data.len() + 1) as *mut xmlChar };
        if result.is_null() {
            return ptr::null_mut();
        }
        unsafe {
            ptr::copy_nonoverlapping(data.as_ptr(), result, data.len());
            *result.add(data.len()) = 0; // null-terminate
        }
        return result;
    }

    // UPSTREAM-PARITY (xmlIO.c xmlParserInputBufferCreateFilename): a URI
    // accepted by a registered input callback pair (xmlRegisterInputCallbacks)
    // is read through that pair instead of the file path — XInclude hrefs
    // like "sql:..." (io1.c) route here (Phase-12 EXTERNAL-CONSUMERS court).
    if let Some(data) =
        crate::abi::exports_parser::read_uri_via_input_callbacks(c_filename.as_ptr())
    {
        if data.is_empty() {
            return ptr::null_mut();
        }
        let result = unsafe { allocator::xmlMallocImpl(data.len() + 1) as *mut xmlChar };
        if result.is_null() {
            return ptr::null_mut();
        }
        unsafe {
            ptr::copy_nonoverlapping(data.as_ptr(), result, data.len());
            *result.add(data.len()) = 0; // null-terminate
        }
        return result;
    }

    let fd = unsafe { libc::open(c_filename.as_ptr(), libc::O_RDONLY) };
    if fd < 0 {
        return ptr::null_mut();
    }

    let mut data = Vec::new();
    let mut buf = [0u8; 4096];

    loop {
        let ret = unsafe { libc::read(fd, buf.as_mut_ptr() as *mut c_void, buf.len()) };
        if ret < 0 {
            unsafe { libc::close(fd) };
            return ptr::null_mut();
        }
        if ret == 0 {
            break;
        }
        data.extend_from_slice(&buf[..ret as usize]);
    }

    unsafe { libc::close(fd) };

    if data.is_empty() {
        return ptr::null_mut();
    }

    // Allocate via xmlMalloc and copy with null terminator.
    let result = unsafe { allocator::xmlMallocImpl(data.len() + 1) as *mut xmlChar };
    if result.is_null() {
        return ptr::null_mut();
    }

    unsafe {
        ptr::copy_nonoverlapping(data.as_ptr(), result, data.len());
        *result.add(data.len()) = 0; // null-terminate
    }

    result
}

/// Parse an XML document from a file.
///
/// Returns a pointer to the parsed document, or NULL on failure.
///
/// # SAFETY
///
/// `filename` must be a valid null-terminated xmlChar string or NULL.
unsafe fn parse_xml_document(filename: *const xmlChar) -> *mut _xmlDoc {
    if filename.is_null() {
        return ptr::null_mut();
    }

    // Read the file content.
    let content = unsafe { io_read_file(filename) };
    if content.is_null() {
        return ptr::null_mut();
    }

    let content_bytes = unsafe { xmlstr_to_bytes(content) };
    let size = content_bytes.len() as c_int;

    // Parse the content as XML.
    let doc = unsafe {
        crate::abi::exports_xml2::xmlReadMemory(
            content as *const c_char,
            size,
            filename as *const c_char,
            ptr::null(), // encoding
            0,           // options
        )
    };

    allocator::xmlFreeImpl(content as *mut c_void);

    doc
}

/// Find the root element of a document.
///
/// # SAFETY
///
/// `doc` must be a valid pointer or NULL.
unsafe fn find_root_element(doc: *mut _xmlDoc) -> *mut _xmlNode {
    if doc.is_null() {
        return ptr::null_mut();
    }

    let mut child = unsafe { (*doc).children };
    while !child.is_null() {
        let node_type = unsafe { (*child).type_ };
        if node_type == XML_ELEMENT_NODE as c_int {
            return child;
        }
        child = unsafe { (*child).next };
    }

    ptr::null_mut()
}

/// Set the document pointer on a node and all its descendants.
///
/// # SAFETY
///
/// `node` must be a valid pointer or NULL.
/// `doc` must be a valid pointer to an _xmlDoc or NULL.
unsafe fn set_doc_recursive(node: *mut _xmlNode, doc: *mut _xmlDoc) {
    if node.is_null() {
        return;
    }

    unsafe {
        (*node).doc = doc;
    }

    // Set doc on all children.
    let mut child = unsafe { (*node).children };
    while !child.is_null() {
        unsafe { set_doc_recursive(child, doc) };
        child = unsafe { (*child).next };
    }

    // Set doc on properties.
    let mut prop = unsafe { (*node).properties };
    while !prop.is_null() {
        unsafe {
            (*prop).doc = doc;
            if !(*prop).children.is_null() {
                set_doc_recursive((*prop).children, doc);
            }
        }
        prop = unsafe { (*prop).next };
    }
}

/// Check if a node or any of its ancestors has a namespace declaration
/// with the given URI.
///
/// # SAFETY
///
/// `node` must be a valid pointer or NULL.
/// `ns_uri` must be a valid null-terminated xmlChar string.
unsafe fn check_namespace_declaration(node: *mut _xmlNode, ns_uri: *const xmlChar) -> bool {
    if node.is_null() {
        return false;
    }

    let mut cur: *mut _xmlNode = node;
    while !cur.is_null() {
        let n = unsafe { &*cur };
        let mut ns_def = n.nsDef;
        while !ns_def.is_null() {
            let ns = unsafe { &*ns_def };
            if !ns.href.is_null() && unsafe { xml_str_equal(ns.href, ns_uri) } {
                return true;
            }
            ns_def = ns.next;
        }
        cur = n.parent;
    }

    false
}

/// Compare two null-terminated xmlChar strings for equality.
///
/// # SAFETY
///
/// Both strings must be null-terminated or NULL.
unsafe fn xml_str_equal(a: *const xmlChar, b: *const xmlChar) -> bool {
    if a.is_null() && b.is_null() {
        return true;
    }
    if a.is_null() || b.is_null() {
        return false;
    }
    unsafe { crate::abi::exports_xml2::xmlStrEqual(a, b) != 0 }
}

/// Whether `href` is one of the XInclude namespace URIs — the 2003
/// namespace (upstream `XINCLUDE_NS`) or the 2001 draft (upstream
/// `XINCLUDE_OLD_NS`, honored like xinclude.c).
///
/// # SAFETY
///
/// `href` must be a valid null-terminated xmlChar string.
unsafe fn is_xinclude_ns_uri(href: *const xmlChar) -> bool {
    unsafe {
        xml_str_equal(href, XINCLUDE_NS.as_ptr() as *const xmlChar)
            || xml_str_equal(href, XINCLUDE_OLD_NS.as_ptr() as *const xmlChar)
    }
}

// ═══════════════════════════════════════════════════════════════════════════════
// Tests
// ═══════════════════════════════════════════════════════════════════════════════

#[cfg(test)]
mod tests {
    use super::*;
    use crate::abi::allocator;

    use crate::xml::tree;
    use std::os::raw::{c_char, c_int};

    // ═══════════════════════════════════════════════════════════════════════════
    // Test helpers
    // ═══════════════════════════════════════════════════════════════════════════

    #[allow(dead_code)]
    /// Create a simple XML document from a string.
    ///
    /// # Safety
    ///
    /// - `xml` must be a byte slice that stays valid for the duration of the
    ///   call; its pointer and length are passed to `xmlReadMemory`, which
    ///   parses the bytes into a new document. The returned document pointer
    ///   is NULL on failure and otherwise must be released by the caller with
    ///   `tree::free_doc`.
    unsafe fn create_doc_from_xml(xml: &[u8]) -> *mut _xmlDoc {
        let doc = unsafe {
            crate::abi::exports_xml2::xmlReadMemory(
                xml.as_ptr() as *const c_char,
                xml.len() as c_int,
                ptr::null(),
                ptr::null(),
                0,
            )
        };
        if doc.is_null() {
            return ptr::null_mut();
        }
        doc
    }

    /// Create a simple document with one root element.
    unsafe fn create_simple_doc() -> *mut _xmlDoc {
        let doc = tree::new_doc(ptr::null());
        assert!(!doc.is_null(), "Failed to create doc");

        let root = tree::new_child(
            doc as *mut _xmlNode,
            ptr::null_mut(),
            c"root".as_ptr() as *const xmlChar,
        );
        assert!(!root.is_null(), "Failed to create root");

        doc
    }

    /// Create a namespace on a node.
    unsafe fn create_ns(
        node: *mut _xmlNode,
        prefix: *const xmlChar,
        href: *const xmlChar,
    ) -> *mut _xmlNs {
        tree::new_ns(node, href, prefix)
    }

    /// Create a doc with a root and an XInclude namespace.
    unsafe fn create_doc_with_xinclude_ns() -> (*mut _xmlDoc, *mut _xmlNode) {
        let doc = tree::new_doc(ptr::null());
        assert!(!doc.is_null());
        let root = tree::new_child(
            doc as *mut _xmlNode,
            ptr::null_mut(),
            c"root".as_ptr() as *const xmlChar,
        );
        assert!(!root.is_null());
        create_ns(
            root,
            c"xi".as_ptr() as *const xmlChar,
            XINCLUDE_NS.as_ptr() as *const xmlChar,
        );
        (doc, root)
    }

    /// Create an xi:include child element with optional attributes.
    unsafe fn create_include_child(
        parent: *mut _xmlNode,
        href: Option<&[u8]>,
        parse: Option<&[u8]>,
    ) -> *mut _xmlNode {
        let ns = create_ns(
            parent,
            c"xi".as_ptr() as *const xmlChar,
            XINCLUDE_NS.as_ptr() as *const xmlChar,
        );
        let elem = tree::new_child(parent, ns, c"include".as_ptr() as *const xmlChar);
        if let Some(h) = href {
            let h_str = crate::xml::string::bytes_to_xmlstr(h);
            tree::set_prop(elem, ATTR_HREF.as_ptr() as *const xmlChar, h_str);
            allocator::xmlFreeImpl(h_str as *mut c_void);
        }
        if let Some(p) = parse {
            let p_str = crate::xml::string::bytes_to_xmlstr(p);
            tree::set_prop(elem, ATTR_PARSE.as_ptr() as *const xmlChar, p_str);
            allocator::xmlFreeImpl(p_str as *mut c_void);
        }
        elem
    }

    /// Create an xi:fallback child element.
    unsafe fn create_fallback_child(parent: *mut _xmlNode) -> *mut _xmlNode {
        let ns = create_ns(
            parent,
            c"xi".as_ptr() as *const xmlChar,
            XINCLUDE_NS.as_ptr() as *const xmlChar,
        );
        tree::new_child(parent, ns, c"fallback".as_ptr() as *const xmlChar)
    }
    #[allow(dead_code)]
    /// Find the first element by name in the document.
    ///
    /// # Safety
    ///
    /// - `doc` must be NULL or a pointer to a valid, live `_xmlDoc`; `name`
    ///   must be a NUL-terminated `xmlChar` string that stays readable for the
    ///   whole search. The walk dereferences `(*doc).children` and follows the
    ///   `(*child).next` links, all of which must belong to the live document.
    unsafe fn find_element(doc: *mut _xmlDoc, name: *const xmlChar) -> *mut _xmlNode {
        if doc.is_null() {
            return ptr::null_mut();
        }
        let mut child = unsafe { (*doc).children };
        while !child.is_null() {
            let result = unsafe { find_element_recursive(child, name) };
            if !result.is_null() {
                return result;
            }
            child = unsafe { (*child).next };
        }
        ptr::null_mut()
    }

    #[allow(dead_code)]
    /// Find the first element by name, searching a node subtree.
    ///
    /// # Safety
    ///
    /// - `node` must be NULL or a pointer to a valid, live `_xmlNode` whose
    ///   `children` and `next` links form the subtree to search; `name` must
    ///   be a NUL-terminated `xmlChar` string readable for the duration of the
    ///   call. `n.name` is only compared when non-NULL.
    unsafe fn find_element_recursive(node: *mut _xmlNode, name: *const xmlChar) -> *mut _xmlNode {
        if node.is_null() {
            return ptr::null_mut();
        }
        let n = unsafe { &*node };
        if n.type_ == XML_ELEMENT_NODE as c_int
            && !n.name.is_null()
            && unsafe { xml_str_equal(n.name, name) }
        {
            return node;
        }
        let mut child = n.children;
        while !child.is_null() {
            let result = unsafe { find_element_recursive(child, name) };
            if !result.is_null() {
                return result;
            }
            child = unsafe { (*child).next };
        }
        ptr::null_mut()
    }

    /// Count elements with a given name in the document.
    ///
    /// # Safety
    ///
    /// - `doc` must be NULL or a pointer to a valid, live `_xmlDoc`; `name`
    ///   must be a NUL-terminated `xmlChar` string readable for the duration
    ///   of the walk, which follows `(*doc).children` and `(*child).next`
    ///   links inside the live document.
    unsafe fn count_elements(doc: *mut _xmlDoc, name: *const xmlChar) -> c_int {
        if doc.is_null() {
            return 0;
        }
        let mut count: c_int = 0;
        let mut child = unsafe { (*doc).children };
        while !child.is_null() {
            count += unsafe { count_elements_recursive(child, name) };
            child = unsafe { (*child).next };
        }
        count
    }

    /// Count elements with a given name in a node subtree.
    ///
    /// # Safety
    ///
    /// - `node` must be NULL or a pointer to a valid, live `_xmlNode` whose
    ///   `children` and `next` links form the subtree to walk; `name` must be
    ///   a NUL-terminated `xmlChar` string readable for the duration of the
    ///   call. `n.name` is only compared when non-NULL.
    unsafe fn count_elements_recursive(node: *mut _xmlNode, name: *const xmlChar) -> c_int {
        if node.is_null() {
            return 0;
        }
        let mut count: c_int = 0;
        let n = unsafe { &*node };
        if n.type_ == XML_ELEMENT_NODE as c_int
            && !n.name.is_null()
            && unsafe { xml_str_equal(n.name, name) }
        {
            count += 1;
        }
        let mut child = n.children;
        while !child.is_null() {
            count += unsafe { count_elements_recursive(child, name) };
            child = unsafe { (*child).next };
        }
        count
    }

    // ═══════════════════════════════════════════════════════════════════════════
    // Tests
    // ═══════════════════════════════════════════════════════════════════════════

    #[test]
    /// Tests that `is_xinclude_element` recognizes and rejects nodes.
    ///
    /// # Safety
    ///
    /// - `doc` is created by `create_simple_doc`, which asserts non-NULL for
    ///   the document and its root element, and is freed with `tree::free_doc`;
    ///   `(*doc).children` is dereferenced only after the non-NULL assertion,
    ///   and `is_xinclude_element` handles a NULL node argument.
    fn test_is_xinclude_element() {
        unsafe {
            let doc = create_simple_doc();
            assert!(!doc.is_null());
            let root = (*doc).children;
            assert!(!root.is_null());
            assert!(!is_xinclude_element(root));
            assert!(!is_xinclude_element(ptr::null_mut()));
            tree::free_doc(doc);
        }
    }

    #[test]
    /// Tests that an `xi:include` child is detected through its namespace.
    ///
    /// # Safety
    ///
    /// - `doc` and `root` come from `create_doc_with_xinclude_ns`; `include`
    ///   and `regular` are `tree::new_child` results asserted non-NULL and are
    ///   owned by `doc`, which is freed with `tree::free_doc` at the end;
    ///   `is_xinclude_element` only reads node fields through valid pointers.
    fn test_xinclude_namespace_detection() {
        unsafe {
            let (doc, root) = create_doc_with_xinclude_ns();
            let include = create_include_child(root, Some(b"test.xml"), None);
            assert!(!include.is_null());
            assert!(is_xinclude_element(include), "Should detect xi:include");

            // A regular child should not be detected as xinclude.
            let regular =
                tree::new_child(root, ptr::null_mut(), c"regular".as_ptr() as *const xmlChar);
            assert!(!regular.is_null());
            assert!(!is_xinclude_element(regular), "Regular elem not xinclude");

            tree::free_doc(doc);
        }
    }

    #[test]
    /// Tests that `find_fallback_child` locates an `xi:fallback` child.
    ///
    /// # Safety
    ///
    /// - `doc`, `root`, `include`, and `fallback` are produced by the test
    ///   helpers and asserted non-NULL; `find_fallback_child` walks the node
    ///   tree through valid child/sibling pointers, and the whole tree is
    ///   freed with `tree::free_doc` before the test ends.
    fn test_find_fallback_child() {
        unsafe {
            let (doc, root) = create_doc_with_xinclude_ns();
            let include = create_include_child(root, None, None);
            assert!(!include.is_null());
            let fallback = create_fallback_child(include);
            assert!(!fallback.is_null());

            let found = find_fallback_child(include);
            assert!(!found.is_null(), "Should find fallback child");

            let no_fallback = find_fallback_child(root);
            assert!(no_fallback.is_null(), "Root should not have fallback");

            tree::free_doc(doc);
        }
    }

    #[test]
    /// Tests the NULL handling and equality behavior of `xml_str_equal`.
    ///
    /// # Safety
    ///
    /// - The `c"..."` literals are NUL-terminated `'static` byte buffers;
    ///   `xml_str_equal` returns early when either argument is NULL and only
    ///   calls `xmlStrEqual` when both pointers are non-NULL and point to
    ///   readable NUL-terminated strings.
    fn test_xml_str_equal() {
        unsafe {
            assert!(xml_str_equal(
                c"hello".as_ptr() as *const xmlChar,
                c"hello".as_ptr() as *const xmlChar,
            ));
            assert!(!xml_str_equal(
                c"hello".as_ptr() as *const xmlChar,
                c"world".as_ptr() as *const xmlChar,
            ));
            assert!(!xml_str_equal(
                ptr::null(),
                c"hello".as_ptr() as *const xmlChar
            ));
            assert!(!xml_str_equal(
                c"hello".as_ptr() as *const xmlChar,
                ptr::null()
            ));
            assert!(xml_str_equal(ptr::null(), ptr::null()));
        }
    }

    #[test]
    /// Tests that `xinclude_process` fails cleanly on a NULL document.
    ///
    /// # Safety
    ///
    /// - `xinclude_process` checks `doc` for NULL and returns
    ///   `XINCLUDE_FAILURE` without dereferencing it.
    fn test_xinclude_process_null_doc() {
        unsafe {
            assert_eq!(xinclude_process(ptr::null_mut()), XINCLUDE_FAILURE);
        }
    }

    #[test]
    /// Tests that a document without includes processes successfully.
    ///
    /// # Safety
    ///
    /// - `doc` is created by `create_simple_doc` and stays valid until
    ///   `tree::free_doc`, so the internal tree walks of `xinclude_process`
    ///   only touch live nodes.
    fn test_xinclude_process_no_includes() {
        unsafe {
            let doc = create_simple_doc();
            assert_eq!(xinclude_process(doc), 0);
            tree::free_doc(doc);
        }
    }

    #[test]
    /// Tests that an include referencing a missing file is handled gracefully.
    ///
    /// # Safety
    ///
    /// - `doc` and `root` come from `create_doc_with_xinclude_ns`, and the
    ///   include child is created by `create_include_child`; the document tree
    ///   stays intact until `tree::free_doc`, so `xinclude_process` only
    ///   dereferences live nodes.
    fn test_xinclude_process_with_includes() {
        unsafe {
            // Create doc with xi:include that references a nonexistent file.
            let (doc, root) = create_doc_with_xinclude_ns();
            create_include_child(root, Some(b"nonexistent.xml"), None);
            let result = xinclude_process(doc);
            assert!(result >= 0, "Should handle missing files: {}", result);
            tree::free_doc(doc);
        }
    }

    #[test]
    /// Tests that fallback content is kept when the include target is missing.
    ///
    /// # Safety
    ///
    /// - All nodes are created by the tree helpers and belong to `doc`, which
    ///   is freed with `tree::free_doc` at the end; `count_elements` and
    ///   `xinclude_process` walk only live, linked nodes that were asserted
    ///   non-NULL when created.
    fn test_xinclude_fallback_content() {
        unsafe {
            let (doc, root) = create_doc_with_xinclude_ns();
            let include = create_include_child(root, Some(b"nonexistent.xml"), None);
            let fb = create_fallback_child(include);
            // Add a child to fallback
            let fb_child = tree::new_child(
                fb,
                ptr::null_mut(),
                c"fallback-elem".as_ptr() as *const xmlChar,
            );
            assert!(!fb_child.is_null());

            let before = count_elements(doc, c"fallback-elem".as_ptr() as *const xmlChar);
            assert!(before > 0, "Should have fallback-elem before processing");

            let result = xinclude_process(doc);
            assert!(result >= 0, "Should handle fallback: {}", result);
            tree::free_doc(doc);
        }
    }

    #[test]
    /// Tests that a self-referencing include does not crash the processor.
    ///
    /// # Safety
    ///
    /// - `doc` and `root` come from `create_doc_with_xinclude_ns`; the include
    ///   child is attached to `root` and owned by `doc`, which is freed after
    ///   `xinclude_process` returns, so all pointer dereferences target live
    ///   nodes.
    fn test_xinclude_circular_reference_detection() {
        unsafe {
            let (doc, root) = create_doc_with_xinclude_ns();
            create_include_child(root, Some(b"self-ref.xml"), None);
            let result = xinclude_process(doc);
            assert!(result >= 0, "Circular ref should not crash: {}", result);
            tree::free_doc(doc);
        }
    }

    #[test]
    /// Tests that the `parse` attribute is stored and include children are
    /// counted.
    ///
    /// # Safety
    ///
    /// - `doc` and `root` come from `create_doc_with_xinclude_ns`; the loop
    ///   dereferences `(*root).children` and follows `(*child).next`, all of
    ///   which are nodes owned by `doc` and freed with `tree::free_doc`.
    fn test_xinclude_parse_attribute_detection() {
        unsafe {
            let (doc, root) = create_doc_with_xinclude_ns();
            create_include_child(root, Some(b"test.xml"), Some(b"xml"));
            create_include_child(root, Some(b"test.txt"), Some(b"text"));
            create_include_child(root, Some(b"default.xml"), None);

            // Count include elements by iterating children.
            let mut count = 0;
            let mut child = (*root).children;
            while !child.is_null() {
                if is_xinclude_element(child) {
                    count += 1;
                }
                child = (*child).next;
            }
            assert_eq!(count, 3, "Should have 3 include elements");
            tree::free_doc(doc);
        }
    }

    #[test]
    /// Tests both `xinclude_process` and `xinclude_process_flags`.
    ///
    /// # Safety
    ///
    /// - `doc` is created by `create_simple_doc` and freed with `tree::free_doc`
    ///   after both calls, so every dereference inside the processor touches a
    ///   live document.
    fn test_xinclude_process_functions() {
        unsafe {
            let doc = create_simple_doc();
            let r1 = xinclude_process(doc);
            assert!(r1 >= 0);
            let r2 = xinclude_process_flags(doc, 0);
            assert!(r2 >= 0);
            tree::free_doc(doc);
        }
    }

    #[test]
    /// Tests an include with no href and a fallback child.
    ///
    /// # Safety
    ///
    /// - `doc`, `root`, `include`, and the fallback child are built by the
    ///   test helpers, asserted non-NULL where used, and owned by `doc`, which
    ///   is freed with `tree::free_doc` after `xinclude_process`.
    fn test_xinclude_process_with_empty_href() {
        unsafe {
            let (doc, root) = create_doc_with_xinclude_ns();
            let include = create_include_child(root, None, None);
            create_fallback_child(include);
            let result = xinclude_process(doc);
            assert!(result >= 0, "Empty href with fallback: {}", result);
            tree::free_doc(doc);
        }
    }

    #[test]
    /// Tests that `set_doc_recursive` assigns the document pointer to detached
    /// nodes.
    ///
    /// # Safety
    ///
    /// - `doc`, `parent`, and `detached` are `tree` module allocations
    ///   asserted non-NULL; `set_doc_recursive` only writes the `(*node).doc`
    ///   field of valid nodes, and the nodes are released with `tree::free_node`
    ///   and `tree::free_doc` before the test ends.
    fn test_set_doc_recursive() {
        unsafe {
            let doc = tree::new_doc(ptr::null());
            assert!(!doc.is_null());
            let parent = tree::new_child(
                doc as *mut _xmlNode,
                ptr::null_mut(),
                c"parent".as_ptr() as *const xmlChar,
            );
            assert!(!parent.is_null());
            let detached = tree::new_node(ptr::null_mut(), c"detached".as_ptr() as *const xmlChar);
            assert!(!detached.is_null());
            assert!((*detached).doc.is_null());
            set_doc_recursive(detached, doc);
            assert_eq!((*detached).doc, doc);
            tree::free_node(detached);
            tree::free_doc(doc);
        }
    }

    #[test]
    /// Tests that `find_root_element` returns the document root element.
    ///
    /// # Safety
    ///
    /// - `doc` is created by `create_simple_doc`; `root` is asserted non-NULL
    ///   and dereferenced only while `doc` is alive, and `tree::free_doc`
    ///   releases the whole tree at the end.
    fn test_find_root_element() {
        unsafe {
            let doc = create_simple_doc();
            let root = find_root_element(doc);
            assert!(!root.is_null());
            assert_eq!((*root).type_, XML_ELEMENT_NODE as c_int);
            tree::free_doc(doc);
        }
    }

    #[test]
    /// Tests that the `xpointer` attribute round-trips through the tree.
    ///
    /// # Safety
    ///
    /// - `include` is created by `create_include_child` and owned by `doc`;
    ///   `xptr_val` is a fresh `bytes_to_xmlstr` allocation freed right after
    ///   `tree::set_prop` copies it; `xptr` from `tree::get_prop` is freed
    ///   with `xmlFreeImpl` after `xmlstr_to_bytes` copies it, and `doc` is
    ///   freed with `tree::free_doc`.
    fn test_xinclude_xpointer_attribute() {
        unsafe {
            let (doc, root) = create_doc_with_xinclude_ns();
            let include = create_include_child(root, Some(b"test.xml"), None);
            let xptr_val = crate::xml::string::bytes_to_xmlstr(b"xpointer(//target)");
            tree::set_prop(include, ATTR_XPOINTER.as_ptr() as *const xmlChar, xptr_val);
            allocator::xmlFreeImpl(xptr_val as *mut c_void);

            let xptr = tree::get_prop(include, ATTR_XPOINTER.as_ptr() as *const xmlChar);
            assert!(!xptr.is_null(), "Should have xpointer attribute");
            assert_eq!(xmlstr_to_bytes(xptr), b"xpointer(//target)");
            allocator::xmlFreeImpl(xptr as *mut c_void);

            tree::free_doc(doc);
        }
    }

    #[test]
    /// Tests that the `accept` and `accept-language` attributes round-trip.
    ///
    /// # Safety
    ///
    /// - `include` is owned by `doc`; the attribute values from
    ///   `bytes_to_xmlstr` are freed right after `tree::set_prop` copies them,
    ///   and the values returned by `tree::get_prop` are freed with
    ///   `xmlFreeImpl` after use; `doc` is freed with `tree::free_doc`.
    fn test_xinclude_accept_attributes() {
        unsafe {
            let (doc, root) = create_doc_with_xinclude_ns();
            let include = create_include_child(root, Some(b"data.xml"), None);

            let accept_val = crate::xml::string::bytes_to_xmlstr(b"application/xml");
            tree::set_prop(include, ATTR_ACCEPT.as_ptr() as *const xmlChar, accept_val);
            allocator::xmlFreeImpl(accept_val as *mut c_void);

            let lang_val = crate::xml::string::bytes_to_xmlstr(b"en");
            tree::set_prop(
                include,
                ATTR_ACCEPT_LANGUAGE.as_ptr() as *const xmlChar,
                lang_val,
            );
            allocator::xmlFreeImpl(lang_val as *mut c_void);

            let accept = tree::get_prop(include, ATTR_ACCEPT.as_ptr() as *const xmlChar);
            assert!(!accept.is_null());
            assert_eq!(xmlstr_to_bytes(accept), b"application/xml");
            allocator::xmlFreeImpl(accept as *mut c_void);

            let lang = tree::get_prop(include, ATTR_ACCEPT_LANGUAGE.as_ptr() as *const xmlChar);
            assert!(!lang.is_null());
            assert_eq!(xmlstr_to_bytes(lang), b"en");
            allocator::xmlFreeImpl(lang as *mut c_void);

            tree::free_doc(doc);
        }
    }

    #[test]
    /// Tests that the `encoding` attribute round-trips through the tree.
    ///
    /// # Safety
    ///
    /// - `include` is owned by `doc`; `enc_val` is freed after `tree::set_prop`
    ///   copies it, `encoding` from `tree::get_prop` is freed after use, and
    ///   `doc` is freed with `tree::free_doc`.
    fn test_xinclude_encoding_attribute() {
        unsafe {
            let (doc, root) = create_doc_with_xinclude_ns();
            let include = create_include_child(root, Some(b"data.txt"), Some(b"text"));

            let enc_val = crate::xml::string::bytes_to_xmlstr(b"UTF-8");
            tree::set_prop(include, ATTR_ENCODING.as_ptr() as *const xmlChar, enc_val);
            allocator::xmlFreeImpl(enc_val as *mut c_void);

            let encoding = tree::get_prop(include, ATTR_ENCODING.as_ptr() as *const xmlChar);
            assert!(!encoding.is_null());
            assert_eq!(xmlstr_to_bytes(encoding), b"UTF-8");
            allocator::xmlFreeImpl(encoding as *mut c_void);

            tree::free_doc(doc);
        }
    }

    #[test]
    /// Tests that `xinclude_process` and `xinclude_process_flags` with zero
    /// flags behave identically.
    ///
    /// # Safety
    ///
    /// - `doc` is created by `create_simple_doc` and freed with `tree::free_doc`
    ///   after both calls, so the processor only dereferences live nodes.
    fn test_xinclude_process_flags_equivalence() {
        unsafe {
            let doc = create_simple_doc();
            let r1 = xinclude_process(doc);
            let r2 = xinclude_process_flags(doc, 0);
            assert_eq!(r1, r2);
            tree::free_doc(doc);
        }
    }

    #[test]
    /// Tests `xinclude_process_flags` with the `XML_PARSE_NOXINCNODE` flag.
    ///
    /// # Safety
    ///
    /// - `doc` is created by `create_simple_doc` and freed with `tree::free_doc`
    ///   after the call, so all pointer dereferences target live nodes.
    fn test_xinclude_process_flags_noxincnode() {
        unsafe {
            let doc = create_simple_doc();
            let result = xinclude_process_flags(doc, XML_PARSE_NOXINCNODE);
            assert_eq!(result, 0);
            tree::free_doc(doc);
        }
    }

    #[test]
    #[ignore = "pre-existing tree module cleanup bug with modified trees"]
    /// Tests processing a document with nested includes and fallbacks.
    ///
    /// # Safety
    ///
    /// - All nodes are created by the `tree` helpers, asserted non-NULL, and
    ///   owned by `doc`; `xinclude_process` walks the tree only while `doc` is
    ///   alive. The test is ignored because the tree cleanup path does not
    ///   free modified trees, and it deliberately leaks `doc` (no `free_doc`),
    ///   but every unsafe access targets nodes that remain live for the whole
    ///   test.
    fn test_complex_nested_includes_structure() {
        unsafe {
            // Build a doc with a complex structure including xi:include elements.
            let doc = tree::new_doc(ptr::null());
            assert!(!doc.is_null());
            let root = tree::new_child(
                doc as *mut _xmlNode,
                ptr::null_mut(),
                c"root".as_ptr() as *const xmlChar,
            );
            assert!(!root.is_null());
            create_ns(
                root,
                c"xi".as_ptr() as *const xmlChar,
                XINCLUDE_NS.as_ptr() as *const xmlChar,
            );

            create_include_child(root, Some(b"nonexistent1.xml"), None);

            let inc2 = create_include_child(root, Some(b"nonexistent2.xml"), None);
            let fb2 = create_fallback_child(inc2);
            tree::new_child(
                fb2,
                ptr::null_mut(),
                c"fallback-content".as_ptr() as *const xmlChar,
            );

            create_include_child(root, Some(b"nonexistent3.txt"), Some(b"text"));

            let result = xinclude_process(doc);
            assert!(result >= 0, "Complex structure: {}", result);
        }
    }

    #[test]
    /// Tests that `xinclude_process` leaves the document in a freeable state.
    ///
    /// # Safety
    ///
    /// - `doc` is created by `create_simple_doc`, processed while alive, and
    ///   freed with `tree::free_doc` at the end, so all dereferences target
    ///   live nodes.
    fn test_xinclude_process_xml_memory_cleanup() {
        unsafe {
            let doc = create_simple_doc();
            assert!(xinclude_process(doc) >= 0);
            tree::free_doc(doc);
        }
    }

    #[test]
    /// Tests that `mark_doc_xinclude_processed` sets the XInclude flag.
    ///
    /// # Safety
    ///
    /// - `doc` is created by `create_simple_doc` and freed with `tree::free_doc`;
    ///   the `(*doc).properties` field is read and written only while `doc` is
    ///   alive.
    fn test_mark_doc_xinclude_processed() {
        unsafe {
            let doc = create_simple_doc();
            assert_eq!((*doc).properties & XML_DOC_XINCLUDE as c_int, 0);
            mark_doc_xinclude_processed(doc);
            assert_ne!((*doc).properties & XML_DOC_XINCLUDE as c_int, 0);
            tree::free_doc(doc);
        }
    }

    #[test]
    /// Tests that `process_node_tree` skips XInclude start/end sentinel nodes.
    ///
    /// # Safety
    ///
    /// - `doc` and `root` are created by the helpers and stay alive until the
    ///   end of the test; the sentinel node is allocated by `tree::new_node`,
    ///   manually linked into `root`'s sibling list, and unlinked again before
    ///   `tree::free_node`; every dereference during linking, the
    ///   `process_node_tree` walk, and unlinking touches nodes that are still
    ///   allocated.
    fn test_xinclude_xinclude_start_end_nodes() {
        unsafe {
            let doc = create_simple_doc();
            let root = find_root_element(doc);
            assert!(!root.is_null());

            // Create a sentinel XML_XINCLUDE_START node attached to root.
            let sentinel =
                tree::new_node(ptr::null_mut(), c"XIncludeStart".as_ptr() as *const xmlChar);
            assert!(!sentinel.is_null());
            (*sentinel).type_ = XML_XINCLUDE_START as c_int;
            (*sentinel).doc = doc;
            // Link as next sibling of root's children (simple linking).
            let first_child = (*root).children;
            if !first_child.is_null() {
                // Insert sentinel after first child
                (*sentinel).parent = root;
                (*sentinel).prev = first_child;
                (*sentinel).next = (*first_child).next;
                if !(*first_child).next.is_null() {
                    (*(*first_child).next).prev = sentinel;
                }
                (*first_child).next = sentinel;
                if (*root).last == first_child {
                    (*root).last = sentinel;
                }
            }

            let mut visited = Vec::new();
            let count = { process_node_tree(root, doc, &mut visited) };
            assert_eq!(count, 0, "Should not process sentinel nodes");

            // Unlink sentinel before freeing
            if !(*sentinel).prev.is_null() {
                (*(*sentinel).prev).next = (*sentinel).next;
            }
            if !(*sentinel).next.is_null() {
                (*(*sentinel).next).prev = (*sentinel).prev;
            }
            (*sentinel).prev = ptr::null_mut();
            (*sentinel).next = ptr::null_mut();
            (*sentinel).parent = ptr::null_mut();

            tree::free_node(sentinel);
            tree::free_doc(doc);
        }
    }
}