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
//! Error subsystem (§21, §85 Phase 1).
//!
//! Implements the libxml2 error reporting infrastructure:
//!
//! - `xmlError` struct management
//! - Error domain/code registry
//! - Structured error callbacks (thread-local storage)
//! - Generic error callbacks (thread-local storage)
//! - Last-error tracking (thread-local `xmlGetLastError`, `xmlResetLastError`, `xmlCopyError`)
//! - Error message formatting
//! - `xmlRaiseError()` — the central error reporting function
//!
//! # UPSTREAM-PARITY
//!
//! libxml2 has a two-tier error system:
//!
//! 1. **Structured errors** — `xmlStructuredErrorFunc` receives an `xmlErrorPtr`
//!    with all structured fields (domain, code, level, line, etc.)
//!
//! 2. **Generic errors** — `xmlGenericErrorFunc` receives a formatted string
//!    (printf-style). This is the older system, still widely used.
//!
//! Both systems coexist. When both handlers are set, both are called.
//! The last error is stored thread-locally for retrieval via `xmlGetLastError`.
//!
//! # Phase 1 status
//!
//! Complete — all error functions are implemented.
//! Variadic message formatting will be enhanced in Phase 2+.
//!
//! # Upstream contract
//!
//! Mirrors upstream error.c (SRC-LIBXML2-2.15.0-ERROR-C, oracle tree
//! `oracle/historical/src/libxml2-2.15.0/error.c`): xmlRaiseError /
//! xmlVRaiseError routing, xmlFormatError, xmlGenericErrorDefaultFunc,
//! xmlGetLastError / xmlCtxtGetLastError / xmlResetLastError, xmlCopyError
//! and the legacy xmlParserError / xmlParserWarning SAX handlers.
//!
//! # Conceptual behavior
//!
//! Two-tier error system: structured errors (xmlStructuredErrorFunc with the
//! full xmlError) and generic errors (printf-style fragments). The 11.1-M/K
//! rework routes each raise through ONE channel: a structured handler, else
//! the custom SAX channel (channel(data, msg) once), else the legacy default
//! streaming the xmlFormatError fragments (file/line, domain, level, message,
//! source window, caret) as 6 variadic calls (R-000161).
//!
//! # Ownership & safety invariants
//!
//! Ownership: the thread-local last error owns its file/str1-3 copies;
//! raise_error_streamed copies transient CStrings (R-000163: dangling
//! pointers were the bug). The exported xmlLastError mirror is synced under
//! lock (R-000170). SAFETY: the variadic xmlGenericErrorDefaultFunc and
//! xmlParserError legacy handlers are x86_64 SysV inline-asm va_list shims —
//! stable Rust cannot define variadic extern fns.
//!
//! # Historical quirks & epochs
//!
//! E-005: fatal parser errors are reported twice from 2.13.0 (attr-markup-
//! entity); the xmlFormatError fragment stream and the 80-column source
//! window cap are 2.15 semantics (xmlParserInputGetWindow, caret clamp).
//! R-000163 pinned all XML_ERR_* 64-96 constants to upstream numbering
//! (SPACE_REQUIRED 65, NAME_REQUIRED 68, GT_REQUIRED 73, TAG_NAME_MISMATCH
//! 76, TAG_NOT_FINISHED 77 — not the synthetic renumbering).
//!
//! # Deliberate oddities
//!
//! Deliberate oddities: warnings only bump nbWarnings while other levels
//! update errNo / nbErrors / wellFormed per xmlCtxtVErr; the source window
//! replicates the 80-char cap, continuation-byte skip, UTF-8 forward scan and
//! the 2.15 caret clamp (col >= n maps to size-1).
//!
//! # Proving courts
//!
//! ERROR and CALLBACK court families; ERROR-001 (48 deterministic malformed
//! inputs x 4 passes, byte-identical), GLOBALS-THREADING, DATA-GLOBALS-001,
//! and `cargo test --lib` (ASan-clean).
//!
//! # Tempting simplifications that would break parity
//!
//! The tempting simplification is one generic call plus a direct stderr write
//! — a counting handler would observe 1 call instead of the 6 xmlFormatError
//! fragments the oracle emits (R-000161). Do not route errors to stderr when a
//! handler is installed. Never renumber the XML_ERR_* constants (R-000163).

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

use crate::abi::callbacks::{errorSAXFunc, xmlGenericErrorFunc, xmlStructuredErrorFunc};
use crate::abi::structs::_xmlError;
use crate::abi::types::xmlErrorLevel::*;
use crate::abi::types::*;
use crate::xml::globals;

// ═══════════════════════════════════════════════════════════════════════════════
// Error Management Functions
// ═══════════════════════════════════════════════════════════════════════════════

/// Set the generic error handler.
///
/// # UPSTREAM-PARITY
///
/// ```c
/// void xmlSetGenericErrorFunc(void *ctx, xmlGenericErrorFunc handler);
/// ```
///
/// # SAFETY
///
/// - `handler` must be a valid function pointer or NULL (to reset to default).
/// - If non-NULL, the handler may be called at any time with `ctx`.
pub unsafe fn set_generic_error_func(ctx: *mut c_void, handler: Option<xmlGenericErrorFunc>) {
    // SAFETY: Delegates to globals with same safety contract.
    unsafe { globals::set_generic_error_func(ctx, handler) };
}

/// Set the structured error handler.
///
/// # UPSTREAM-PARITY
///
/// ```c
/// void xmlSetStructuredErrorFunc(void *ctx, xmlStructuredErrorFunc handler);
/// ```
///
/// # SAFETY
///
/// - `handler` must be a valid function pointer or NULL.
pub unsafe fn set_structured_error_func(ctx: *mut c_void, handler: Option<xmlStructuredErrorFunc>) {
    // SAFETY: Delegates to globals with same safety contract.
    unsafe { globals::set_structured_error_func(ctx, handler) };
}

/// Get the last error for the current thread.
///
/// # UPSTREAM-PARITY
///
/// ```c
/// xmlErrorPtr xmlGetLastError(void);
/// ```
///
/// Returns a pointer to the last error, or NULL if no error occurred.
/// The returned pointer is valid until the next libxml2 call in this thread.
pub fn get_last_error() -> *mut _xmlError {
    globals::get_last_error()
}

/// Copy an error from one location to another.
///
/// # UPSTREAM-PARITY
///
/// ```c
/// xmlErrorPtr xmlCopyError(xmlErrorPtr from, xmlErrorPtr to);
/// ```
///
/// Copies `from` into `to`. Returns 0 on success, -1 on error.
///
/// # SAFETY
///
/// - `from` and `to` must be valid pointers to `_xmlError` structs, or NULL.
pub unsafe fn copy_error(from: *const _xmlError, to: *mut _xmlError) -> c_int {
    if from.is_null() || to.is_null() {
        return -1;
    }
    // UPSTREAM-PARITY (error.c xmlCopyError): every string field is
    // deep-copied with xmlStrdup — the destination owns its strings
    // independently of the source. PHP's libxml error list (php_list_set_
    // error_structure -> xmlCopyError) stores these copies at raise time and
    // reads them later; a shallow copy would leave list entries pointing at
    // the parser context's lastError strings, which the NEXT raise frees
    // (free_error_strings) — the recorded message then reads as garbage
    // (php bug64230: "Internal: uY\uFFFD\uFFFDU").
    unsafe {
        let dup = |p: *const c_char| -> *mut c_char {
            if p.is_null() {
                ptr::null_mut()
            } else {
                crate::abi::allocator::xmlMemStrdupImpl(p) as *mut c_char
            }
        };
        let src = &*from;
        let message = if src.message.is_null() {
            ptr::null_mut()
        } else {
            crate::abi::allocator::xmlMemStrdupImpl(src.message as *const c_char) as *mut c_char
        };
        let file = if src.file.is_null() {
            ptr::null_mut()
        } else {
            crate::abi::allocator::xmlMemStrdupImpl(src.file) as *mut c_char
        };
        let str1 = if src.str1.is_null() {
            ptr::null_mut()
        } else {
            crate::abi::allocator::xmlMemStrdupImpl(src.str1) as *mut c_char
        };
        let str2 = if src.str2.is_null() {
            ptr::null_mut()
        } else {
            crate::abi::allocator::xmlMemStrdupImpl(src.str2) as *mut c_char
        };
        let str3 = if src.str3.is_null() {
            ptr::null_mut()
        } else {
            crate::abi::allocator::xmlMemStrdupImpl(src.str3) as *mut c_char
        };
        ptr::write(
            to,
            _xmlError {
                domain: src.domain,
                code: src.code,
                message,
                level: src.level,
                file,
                line: src.line,
                str1,
                str2,
                str3,
                int1: src.int1,
                int2: src.int2,
                ctxt: src.ctxt,
                node: src.node,
            },
        );
    }
    0
}

/// Reset an error structure to its default state.
///
/// # UPSTREAM-PARITY
///
/// ```c
/// void xmlResetError(xmlErrorPtr err);
/// ```
///
/// # SAFETY
///
/// - `err` must be a valid pointer to `_xmlError`, or NULL.
pub const unsafe fn reset_error(err: *mut _xmlError) {
    if err.is_null() {
        return;
    }
    // SAFETY: Caller guarantees pointer is valid.
    unsafe {
        ptr::write(
            err,
            _xmlError {
                domain: XML_FROM_NONE,
                code: XML_ERR_OK as c_int,
                message: ptr::null_mut(),
                level: XML_ERR_NONE as c_int,
                file: ptr::null_mut(),
                line: 0,
                str1: ptr::null_mut(),
                str2: ptr::null_mut(),
                str3: ptr::null_mut(),
                int1: 0,
                int2: 0,
                ctxt: ptr::null_mut(),
                node: ptr::null_mut(),
            },
        );
    }
}

/// Reset the last error for the current thread.
///
/// # UPSTREAM-PARITY
///
/// ```c
/// void xmlResetLastError(void);
/// ```
pub fn reset_last_error() {
    globals::reset_last_error();
}

/// Format an error message.
///
/// This function creates a formatted error message from the component parts.
/// In Phase 1, this is a basic implementation. In Phase 2+, variadic
/// printf-style formatting will be added.
///
/// Returns a C string pointer (allocated with xmlMalloc) that the caller
/// must free with xmlFreeImpl, or NULL on allocation failure.
///
/// # UPSTREAM-PARITY
///
/// Upstream libxml2 uses `vsnprintf` internally for message formatting.
/// We use a simple formatting approach that produces compatible output
/// for the common error patterns.
///
/// # Safety
///
/// - `msg` must be NULL or a valid NUL-terminated C string; `str1`, `str2`
///   and `str3` must be NULL or valid NUL-terminated C strings; the
///   returned buffer is allocator-owned and must be freed with
///   `xmlFreeImpl`, or is NULL on allocation failure.
pub fn format_error_message(
    _domain: c_int,
    _code: c_int,
    msg: *const c_char,
    str1: *const c_char,
    str2: *const c_char,
    str3: *const c_char,
) -> *mut c_char {
    // Phase 1: basic message construction.
    // If a direct message string is provided, use it.
    if !msg.is_null() {
        // SAFETY: Caller guarantees msg is a valid C string.
        let msg_str = unsafe { crate::abi::allocator::xmlMemStrdupImpl(msg) };
        return msg_str as *mut c_char;
    }

    // Build a message from the component strings.
    // This matches upstream behavior where domain/code are combined
    // with str1/str2/str3 into a diagnostic message.
    let mut buf: [u8; 1024] = [0; 1024];
    let mut pos = 0;

    // Write domain prefix
    let domain_str = match _domain {
        XML_FROM_PARSER => "parser",
        XML_FROM_TREE => "tree",
        XML_FROM_NAMESPACE => "namespace",
        XML_FROM_DTD => "dtd",
        XML_FROM_HTML => "html",
        XML_FROM_MEMORY => "memory",
        XML_FROM_OUTPUT => "output",
        XML_FROM_IO => "io",
        XML_FROM_XPATH => "xpath",
        XML_FROM_XPOINTER => "xpointer",
        XML_FROM_XINCLUDE => "xinclude",
        XML_FROM_CATALOG => "catalog",
        XML_FROM_C14N => "c14n",
        XML_FROM_XSLT => "xslt",
        XML_FROM_VALID => "valid",
        XML_FROM_CHECK => "check",
        XML_FROM_WRITER => "writer",
        XML_FROM_MODULE => "module",
        XML_FROM_I18N => "i18n",
        XML_FROM_SCHEMATRONV => "schematron",
        XML_FROM_BUFFER => "buffer",
        XML_FROM_URI => "uri",
        XML_FROM_NONE => "",
        XML_FROM_FTP => "ftp",
        XML_FROM_HTTP => "http",
        XML_FROM_REGEXP => "regexp",
        XML_FROM_DATATYPE => "datatype",
        XML_FROM_SCHEMASP => "schema parser",
        XML_FROM_SCHEMASV => "schema validator",
        XML_FROM_RELAXNGP => "relaxng parser",
        XML_FROM_RELAXNGV => "relaxng validator",
        _ => "unknown",
    };

    if !domain_str.is_empty() {
        let bytes = domain_str.as_bytes();
        let len = bytes.len().min(buf.len().saturating_sub(pos + 2));
        buf[pos..pos + len].copy_from_slice(&bytes[..len]);
        pos += len;
        buf[pos] = b' ';
        pos += 1;
    }

    // Append str1 if present
    if !str1.is_null() {
        // SAFETY: Caller guarantees str1 is a valid C string.
        let s = unsafe { crate::abi::versioning::c_str_to_bytes(str1).unwrap_or_default() };
        if pos + s.len() + 3 <= buf.len() {
            buf[pos] = b'\'';
            pos += 1;
            buf[pos..pos + s.len()].copy_from_slice(s);
            pos += s.len();
            buf[pos] = b'\'';
            pos += 1;
            buf[pos] = b' ';
            pos += 1;
        }
    }

    // Append str2 if present
    if !str2.is_null() {
        let s = unsafe { crate::abi::versioning::c_str_to_bytes(str2).unwrap_or_default() };
        if pos + s.len() + 3 <= buf.len() {
            buf[pos] = b'\'';
            pos += 1;
            buf[pos..pos + s.len()].copy_from_slice(s);
            pos += s.len();
            buf[pos] = b'\'';
            pos += 1;
            buf[pos] = b' ';
            pos += 1;
        }
    }

    // Append str3 if present
    if !str3.is_null() {
        let s = unsafe { crate::abi::versioning::c_str_to_bytes(str3).unwrap_or_default() };
        if pos + s.len() + 3 <= buf.len() {
            buf[pos] = b'\'';
            pos += 1;
            buf[pos..pos + s.len()].copy_from_slice(s);
            pos += s.len();
            buf[pos] = b'\'';
            pos += 1;
            buf[pos] = b' ';
            pos += 1;
        }
    }

    // Null-terminate
    if pos < buf.len() {
        buf[pos] = 0;
    } else {
        buf[buf.len() - 1] = 0;
    }

    // Allocate and return
    let result = unsafe { crate::abi::allocator::xmlMallocImpl(pos + 1) };
    if result.is_null() {
        return ptr::null_mut();
    }
    unsafe {
        ptr::copy_nonoverlapping(buf.as_ptr(), result as *mut u8, pos + 1);
    }
    result as *mut c_char
}

/// Raise an error — the central error reporting function.
///
/// This is called internally when an error occurs. It:
/// 1. Updates the thread-local last error
/// 2. Invokes the structured error handler if one is set
/// 3. Invokes the generic error handler if one is set (for warnings/errors)
///
/// # UPSTREAM-PARITY
///
/// ```c
/// void xmlRaiseError(xmlErrorPtr ctxt,
///                    xmlErrorPtr ctxt2,
///                    xmlErrorPtr ctxt3,
///                    xmlErrorPtr ctxt4,
///                    xmlErrorPtr ctxt5,
///                    int domain,
///                    int code,
///                    xmlErrorLevel level,
///                    const char *file,
///                    int line,
///                    const char *str1,
///                    const char *str2,
///                    const char *str3,
///                    int int1,
///                    int int2,
///                    const char *msg,
///                    ...);
/// ```
///
/// # SAFETY
///
/// - `ctxt` may be NULL (context of the error).
/// - `domain`, `code`, `level`: valid error codes.
/// - `msg` must be a valid C string or NULL.
/// - `file` must be a valid C string or NULL.
/// - `str1`, `str2`, `str3`: error-related strings (may be NULL).
#[allow(clippy::too_many_arguments)]
pub unsafe fn raise_error(
    ctxt: *mut c_void,
    _ctxt2: *mut c_void,
    _ctxt3: *mut c_void,
    _ctxt4: *mut c_void,
    _ctxt5: *mut c_void,
    domain: c_int,
    code: c_int,
    level: c_int,
    file: *const c_char,
    line: c_int,
    str1: *const c_char,
    str2: *const c_char,
    str3: *const c_char,
    int1: c_int,
    _int2: c_int,
    msg: *const c_char,
) {
    // Format the error message
    let formatted_msg = format_error_message(domain, code, msg, str1, str2, str3);

    // UPSTREAM-PARITY (xmlVSetError): string fields are owned copies so the
    // stored error survives transient callers.
    let file_copy = if file.is_null() {
        ptr::null_mut()
    } else {
        crate::abi::allocator::xmlMemStrdupImpl(file) as *mut c_char
    };
    let str1_copy = if str1.is_null() {
        ptr::null_mut()
    } else {
        crate::abi::allocator::xmlMemStrdupImpl(str1) as *mut c_char
    };
    let str2_copy = if str2.is_null() {
        ptr::null_mut()
    } else {
        crate::abi::allocator::xmlMemStrdupImpl(str2) as *mut c_char
    };
    let str3_copy = if str3.is_null() {
        ptr::null_mut()
    } else {
        crate::abi::allocator::xmlMemStrdupImpl(str3) as *mut c_char
    };

    // Store the last error
    let err = _xmlError {
        domain,
        code,
        message: formatted_msg,
        level,
        file: file_copy,
        line,
        str1: str1_copy,
        str2: str2_copy,
        str3: str3_copy,
        int1,
        int2: 0,
        ctxt,
        node: ptr::null_mut(),
    };

    globals::set_last_error(err);

    // UPSTREAM-PARITY (xmlCtxtVErr): the structured handler wins; the
    // generic channel is only used when no structured handler is set. The
    // (handler, ctx) pairs are read atomically (11.1-X), then invoked
    // outside the lock so a handler that re-enters the library cannot
    // deadlock.
    let structured = globals::with_structured_error(|h, c| (h, c));
    if let Some(handler) = structured.0 {
        let err_ref = globals::get_last_error();
        if !err_ref.is_null() {
            handler(structured.1, err_ref as *const _xmlError);
        }
    } else if level != 0 {
        let generic = globals::with_generic_error(|h, c| (h, c));
        if let Some(handler) = generic.0 {
            let ctx = generic.1;
            if !formatted_msg.is_null() {
                handler(ctx, formatted_msg as *const core::ffi::c_char);
            } else if !msg.is_null() {
                handler(ctx, msg);
            }
        }
    }

    // Free the formatted message if it was allocated
    // Note: We keep it as the last error's message, so we don't free it here.
    // The next call to raise_error or reset_error will free the old message.
    // Actually, in Phase 1, we don't free because the message is the last error's.
    // A more complete implementation would free the old message when setting a new one.
}

/// Emit a legacy-format message through the generic error channel.
///
/// Upstream's `xmlGenericErrorDefaultFunc` writes the message to stderr;
/// when a custom generic handler is installed it receives the message. The
/// `level` prefix matches upstream `xmlVFormatLegacyError` (error.c 2.15).
unsafe fn emit_legacy_message(level: &str, msg: *const c_char) {
    if msg.is_null() {
        return;
    }
    let len = libc::strlen(msg) as usize;
    let text = core::slice::from_raw_parts(msg as *const u8, len);
    let mut full = Vec::with_capacity(level.len() + 2 + len);
    full.extend_from_slice(level.as_bytes());
    full.push(b':');
    full.push(b' ');
    full.extend_from_slice(text);
    if let Some(handler) = globals::get_generic_error_func() {
        let ctx = globals::get_generic_error_ctx();
        let mut cmsg = full.clone();
        cmsg.push(0);
        handler(ctx, cmsg.as_ptr() as *const c_char);
    } else {
        // Upstream default (xmlGenericErrorDefaultFunc): stderr.
        let _ = libc::write(2, full.as_ptr() as *const libc::c_void, full.len());
    }
}

/// System V AMD64 `__va_list_tag` (24 bytes) — same layout as the writer's
/// shims and `data_globals.rs`.
#[cfg(target_arch = "x86_64")]
#[repr(C)]
#[derive(Clone, Copy, Debug)]
pub struct VaListTag {
    gp_offset: c_uint,
    fp_offset: c_uint,
    overflow_arg_area: *mut c_void,
    reg_save_area: *mut c_void,
}

#[cfg(target_arch = "x86_64")]
unsafe extern "C" {
    /// Format `msg` with the caller's va_list into `s` (libc `vsnprintf`).
    ///
    /// # Safety
    ///
    /// - `s` must point to a writable buffer of at least `n` bytes;
    ///   `format` must be a valid NUL-terminated printf format string;
    ///   `ap` must be a valid va_list matching the format's specifiers.
    fn vsnprintf(s: *mut c_char, n: usize, format: *const c_char, ap: *mut VaListTag) -> c_int;
}

/// Format `msg` with the caller's varargs and emit `level + ": "` + the
/// formatted text through the generic channel (upstream error.c
/// `xmlVFormatLegacyError`: `xmlGenericError(ctx, "%s: ", level)` then the
/// `xmlStrVASPrintf`-formatted message).
///
/// # Safety
///
/// - `msg` must be NULL or a valid NUL-terminated printf format string;
///   `ap` must be a valid va_list matching the format's specifiers; the
///   format is consumed exactly once.
#[cfg(target_arch = "x86_64")]
unsafe fn emit_legacy_message_v(level: &str, msg: *const c_char, ap: *mut VaListTag) -> c_int {
    if msg.is_null() {
        return 0;
    }
    let mut buf = [0 as c_char; 4096];
    let n = unsafe { vsnprintf(buf.as_mut_ptr(), buf.len(), msg, ap) };
    let n = n.clamp(0, buf.len() as c_int - 1) as usize;
    buf[n] = 0;
    unsafe { emit_legacy_message(level, buf.as_ptr()) };
    0
}

/// x86_64 SysV variadic shim: captures the register save area exactly like
/// `va_start` (2 fixed args → `gp_offset` 16), builds the va_list at
/// rsp+176, passes it as the 3rd argument (rdx) to `receiver`, then restores
/// the stack and returns. Same technique as `xmlStrPrintf`
/// (exports_string.rs) and `xsltTransformError` (exports_xslt_util.rs).
///
/// Layout: reg_save_area = rsp+0 (6 GP + 8 SSE slots, 176 bytes); the
/// va_list struct lives at rsp+176; overflow varargs are above the return
/// address; a 240-byte frame keeps the `call` 16-aligned and the overflow
/// area at rsp+256 (= entry_rsp + 8); the alignment push is popped before
/// `ret`.
///
/// # Safety
///
/// - `receiver` must be a valid x86_64 SysV function pointer that accepts
///   `(ctx, msg, ap)` and consumes the va_list built in the fixed stack
///   slots; the frame layout described above must match the ABI.
#[cfg(target_arch = "x86_64")]
unsafe fn legacy_shim(
    receiver: unsafe extern "C" fn(*mut c_void, *const c_char, *mut VaListTag) -> c_int,
) -> c_int {
    unsafe {
        core::arch::asm!(
            "sub rsp, 240",
            "mov [rsp+0], rdi",
            "mov [rsp+8], rsi",
            "mov [rsp+16], rdx",
            "mov [rsp+24], rcx",
            "mov [rsp+32], r8",
            "mov [rsp+40], r9",
            "movaps [rsp+48], xmm0",
            "movaps [rsp+64], xmm1",
            "movaps [rsp+80], xmm2",
            "movaps [rsp+96], xmm3",
            "movaps [rsp+112], xmm4",
            "movaps [rsp+128], xmm5",
            "movaps [rsp+144], xmm6",
            "movaps [rsp+160], xmm7",
            "mov dword ptr [rsp+176], 16",
            "mov dword ptr [rsp+180], 48",
            "lea rax, [rsp+256]",
            "mov [rsp+184], rax",
            "lea rax, [rsp]",
            "mov [rsp+192], rax",
            "lea rdx, [rsp+176]",
            "call {receiver}",
            "add rsp, 240",
            "add rsp, 8",
            "ret",
            receiver = in(reg) receiver as usize,
            options(noreturn),
        );
    }
}

// ═══════════════════════════════════════════════════════════════════════════════
// Generic-channel fragment streaming (upstream error.c `xmlFormatError`)
// ═══════════════════════════════════════════════════════════════════════════════
//
// Upstream streams each error through the generic channel as a sequence of
// variadic calls (e.g. `channel(data, "%s:%d: ", file, line)` followed by the
// domain, level, message and source-context fragments). Custom handlers and the
// built-in default (an x86_64 SysV va_list shim, see data_globals.rs) both
// observe the same per-fragment calls. Stable Rust cannot express a variadic
// call, so each fragment goes through a tiny x86_64 trampoline that places the
// fixed arguments in the ABI registers and does an indirect call.

/// `channel(data, fmt)` — no variadic arguments.
#[cfg(target_arch = "x86_64")]
#[inline]
unsafe fn ch_call0(handler: xmlGenericErrorFunc, data: *mut c_void, fmt: *const c_char) {
    // SAFETY: `handler` is a C-compatible generic error callback; per the
    // SysV ABI the callee sees (data, fmt) with no additional registers
    // consumed (rdx/rcx zeroed so a va_list-reading callee finds nothing).
    // The compiler guarantees 16-byte stack alignment at the asm block, so
    // the `call` is correctly aligned.
    unsafe {
        core::arch::asm!(
            "xor edx, edx",
            "xor ecx, ecx",
            "call {h}",
            h = in(reg) handler as usize,
            in("rdi") data,
            in("rsi") fmt,
            out("rdx") _, out("rcx") _,
            lateout("rax") _, lateout("r8") _, lateout("r9") _, lateout("r10") _, lateout("r11") _,
        );
    }
}

/// `channel(data, fmt, a1)` — one pointer-sized variadic argument.
#[cfg(target_arch = "x86_64")]
#[inline]
unsafe fn ch_call1(handler: xmlGenericErrorFunc, data: *mut c_void, fmt: *const c_char, a1: usize) {
    // SAFETY: as ch_call0; `a1` lands in the va_list slot after the two
    // fixed args (rdx).
    unsafe {
        core::arch::asm!(
            "xor ecx, ecx",
            "call {h}",
            h = in(reg) handler as usize,
            in("rdi") data,
            in("rsi") fmt,
            in("rdx") a1,
            out("rcx") _,
            lateout("rax") _, lateout("r8") _, lateout("r9") _, lateout("r10") _, lateout("r11") _,
        );
    }
}

/// `channel(data, fmt, a1, a2)` — two pointer-sized variadic arguments.
#[cfg(target_arch = "x86_64")]
#[inline]
unsafe fn ch_call2(
    handler: xmlGenericErrorFunc,
    data: *mut c_void,
    fmt: *const c_char,
    a1: usize,
    a2: usize,
) {
    // SAFETY: as ch_call0; a1/a2 land in the va_list slots (rdx, rcx).
    unsafe {
        core::arch::asm!(
            "call {h}",
            h = in(reg) handler as usize,
            in("rdi") data,
            in("rsi") fmt,
            in("rdx") a1,
            in("rcx") a2,
            lateout("rax") _, lateout("r8") _, lateout("r9") _, lateout("r10") _, lateout("r11") _,
        );
    }
}

/// Emit one raise through the generic channel with upstream's
/// `xmlFormatError` fragment sequence (error.c 2.15): file/line prefix,
/// domain, level, message, then the source window and caret line.
///
/// `file`/`line` come from the raising site's input; `source_window` is the
/// current input line text plus the 0-based caret column (upstream
/// `xmlParserInputGetWindow`).
///
/// # SAFETY
///
/// - `file` and `message` must be valid C strings or NULL.
/// - `source_window` bytes must be valid for the duration of the call.
#[allow(clippy::too_many_arguments)]
#[cfg(target_arch = "x86_64")]
unsafe fn format_error_streamed(
    domain: c_int,
    code: c_int,
    level: c_int,
    message: *const c_char,
    file: *const c_char,
    line: c_int,
    source_window: Option<(&[u8], usize)>,
    enc_bytes: Option<[u8; 4]>,
    tail: Option<(c_int, Option<(&[u8], usize)>)>,
) {
    // SAFETY: reads the exported C globals (upstream reads the same).
    let Some(handler) = globals::get_generic_error_func() else {
        return;
    };
    let data = globals::get_generic_error_ctx();

    // 1. File/line prefix (xmlFormatError).
    if !file.is_null() {
        ch_call2(
            handler,
            data,
            c"%s:%d: ".as_ptr() as *const c_char,
            file as usize,
            line as usize,
        );
    } else if line != 0
        && (domain == XML_FROM_PARSER
            || domain == XML_FROM_SCHEMASV
            || domain == XML_FROM_SCHEMASP
            || domain == XML_FROM_DTD
            || domain == XML_FROM_RELAXNGP
            || domain == XML_FROM_RELAXNGV)
    {
        ch_call1(
            handler,
            data,
            c"Entity: line %d: ".as_ptr() as *const c_char,
            line as usize,
        );
    }

    // 2. Domain fragment (xmlFormatError switch).
    let dom: &[u8] = match domain {
        XML_FROM_PARSER => b"parser \0",
        XML_FROM_NAMESPACE => b"namespace \0",
        XML_FROM_DTD | XML_FROM_VALID => b"validity \0",
        XML_FROM_HTML => b"HTML parser \0",
        XML_FROM_MEMORY => b"memory \0",
        XML_FROM_OUTPUT => b"output \0",
        XML_FROM_IO => b"I/O \0",
        XML_FROM_XINCLUDE => b"XInclude \0",
        XML_FROM_XPATH => b"XPath \0",
        XML_FROM_XPOINTER => b"parser \0",
        XML_FROM_REGEXP => b"regexp \0",
        XML_FROM_MODULE => b"module \0",
        XML_FROM_SCHEMASV => b"Schemas validity \0",
        XML_FROM_SCHEMASP => b"Schemas parser \0",
        XML_FROM_RELAXNGP => b"Relax-NG parser \0",
        XML_FROM_RELAXNGV => b"Relax-NG validity \0",
        XML_FROM_CATALOG => b"Catalog \0",
        XML_FROM_C14N => b"C14N \0",
        XML_FROM_XSLT => b"XSLT \0",
        XML_FROM_I18N => b"encoding \0",
        XML_FROM_SCHEMATRONV => b"schematron \0",
        XML_FROM_BUFFER => b"internal buffer \0",
        XML_FROM_URI => b"URI \0",
        _ => b"\0",
    };
    if !dom.is_empty() && dom[0] != 0 {
        ch_call0(handler, data, dom.as_ptr() as *const c_char);
    }

    // 3. Level fragment (xmlFormatError switch).
    let lvl: &[u8] = if level == XML_ERR_NONE as c_int {
        b": \0"
    } else if level == XML_ERR_WARNING as c_int {
        b"warning : \0"
    } else if level == XML_ERR_ERROR as c_int || level == XML_ERR_FATAL as c_int {
        b"error : \0"
    } else {
        b"\0"
    };
    if !lvl.is_empty() && lvl[0] != 0 {
        ch_call0(handler, data, lvl.as_ptr() as *const c_char);
    }

    // 4. Message fragment.
    if !message.is_null() {
        let msg = message as *const u8;
        let mut len = 0usize;
        while unsafe { *msg.add(len) } != 0 {
            len += 1;
        }
        let ends_nl = len > 0 && unsafe { *msg.add(len - 1) } == b'\n';
        let fmt: &[u8] = if ends_nl { b"%s\0" } else { b"%s\n\0" };
        ch_call1(handler, data, fmt.as_ptr() as *const c_char, msg as usize);
    }

    // 4b. Invalid-encoding byte dump (upstream xmlFormatError: the first 4
    // bytes at the error position, only for XML_ERR_INVALID_ENCODING).
    if code == XML_ERR_INVALID_ENCODING {
        if let Some(bytes) = enc_bytes {
            ch_call0(handler, data, c"Bytes:".as_ptr() as *const c_char);
            for b in bytes {
                // " 0x%02X"
                let hex = format!(" 0x{:02X}\0", b);
                ch_call0(handler, data, hex.as_ptr() as *const c_char);
            }
            ch_call0(handler, data, c"\n".as_ptr() as *const c_char);
        }
    }

    // 5. Source window + caret (xmlParserPrintFileContextInternal).
    if let Some((window, caret)) = source_window {
        let mut win = window.to_vec();
        win.push(0);
        ch_call1(
            handler,
            data,
            c"%s\n".as_ptr() as *const c_char,
            win.as_ptr() as usize,
        );
        let mut caret_line = Vec::with_capacity(caret + 2);
        for &b in window.iter().take(caret) {
            caret_line.push(if b == b'\t' { b'\t' } else { b' ' });
        }
        caret_line.push(b'^');
        caret_line.push(0);
        ch_call1(
            handler,
            data,
            c"%s\n".as_ptr() as *const c_char,
            caret_line.as_ptr() as usize,
        );
    }

    // 5b. "cur input" tail (error.c xmlFormatError): after the parent
    // window, upstream prints the current (entity) input's info + window —
    // `Entity: line %d: \n` for a nameless nested input, then its context
    // and caret (HOSTILE-FAILURE F2 entity loops).
    if let Some((tline, twindow)) = tail {
        if tline != 0
            && (domain == XML_FROM_PARSER
                || domain == XML_FROM_SCHEMASV
                || domain == XML_FROM_SCHEMASP
                || domain == XML_FROM_DTD
                || domain == XML_FROM_RELAXNGP
                || domain == XML_FROM_RELAXNGV)
        {
            ch_call1(
                handler,
                data,
                c"Entity: line %d: \n".as_ptr() as *const c_char,
                tline as usize,
            );
        }
        if let Some((window, caret)) = twindow {
            let mut win = window.to_vec();
            win.push(0);
            ch_call1(
                handler,
                data,
                c"%s\n".as_ptr() as *const c_char,
                win.as_ptr() as usize,
            );
            let mut caret_line = Vec::with_capacity(caret + 2);
            for &b in window.iter().take(caret) {
                caret_line.push(if b == b'\t' { b'\t' } else { b' ' });
            }
            caret_line.push(b'^');
            caret_line.push(0);
            ch_call1(
                handler,
                data,
                c"%s\n".as_ptr() as *const c_char,
                caret_line.as_ptr() as usize,
            );
        }
    }
}

/// How a raise delivers to the generic side of the error system (upstream
/// `xmlVRaiseError` channel selection, error.c 2.15).
#[derive(Clone, Copy, Debug)]
pub enum GenericDelivery {
    /// Custom SAX channel: single call `channel(ctx, msg)`.
    Custom(xmlGenericErrorFunc, *mut c_void),
    /// Legacy/default channel: stream the `xmlFormatError` fragments through
    /// the global generic handler.
    Stream,
    /// No channel (SAX slot NULL): no generic delivery.
    None,
}

/// Select the generic delivery for a parser error from the context's SAX
/// `error` slot (upstream `xmlCtxtVErr`: `channel = ctxt->sax->error`). Used
/// by the parser layer and by the SAX-layer depth error (HOSTILE-FAILURE F1).
///
/// # Safety
///
/// - `ctxt` must be a valid `_xmlParserCtxt` with a valid `sax` pointer.
pub unsafe fn parser_delivery(ctxt: *mut crate::abi::structs::_xmlParserCtxt) -> GenericDelivery {
    unsafe {
        let sax = &*((*ctxt).sax);
        match sax.error {
            None => GenericDelivery::None,
            Some(cb) if is_legacy_error_handler(cb) => GenericDelivery::Stream,
            Some(cb) => GenericDelivery::Custom(cb, (*ctxt).userData),
        }
    }
}

/// Whether a SAX `error` slot holds the candidate's legacy default handler
/// (the SAX1 shim or the default SAX2 handler) — those route through the
/// streamed `xmlFormatError` fragments like upstream's `xmlParserError`.
fn is_legacy_error_handler(cb: errorSAXFunc) -> bool {
    let ptr = cb as usize;
    ptr == XML_PARSER_ERROR_SAX1 as errorSAXFunc as usize
        || ptr == crate::xml::sax::default::default_sax_handler::error as errorSAXFunc as usize
}

/// Raise an error with upstream's full routing (error.c 2.15
/// `xmlVRaiseError`): update the last error, then deliver to the structured
/// handler **or** the selected generic channel — never both.
///
/// `file`/`line`/`source_window` feed the generic fragment stream (the
/// structured handler receives the complete `xmlError` instead). `col` is
/// the 1-based byte column (upstream `input->col` → `err->int2`); `str1`..
/// `str3`/`int1` are the upstream extra fields; `enc_bytes` feeds the
/// `XML_ERR_INVALID_ENCODING` "Bytes:" fragment.
///
/// # UPSTREAM-PARITY (ownership)
///
/// Like upstream `xmlVSetError`, every string field of the stored error is
/// owned (`xmlStrdup`): `file`/`str1`/`str2`/`str3` are heap copies, so the
/// caller may pass transient C strings.
///
/// # SAFETY
///
/// - `ctxt` may be NULL.
/// - `msg`, `file`, `str1`, `str2`, `str3` must be valid C strings or NULL.
/// - `source_window` bytes must be valid for the duration of the call.
#[allow(clippy::too_many_arguments)]
pub unsafe fn raise_error_streamed(
    ctxt: *mut c_void,
    domain: c_int,
    code: c_int,
    level: c_int,
    file: *const c_char,
    line: c_int,
    col: c_int,
    str1: *const c_char,
    str2: *const c_char,
    str3: *const c_char,
    int1: c_int,
    msg: *const c_char,
    source_window: Option<(&[u8], usize)>,
    enc_bytes: Option<[u8; 4]>,
    delivery: GenericDelivery,
    tail: Option<(c_int, Option<(&[u8], usize)>)>,
) {
    // The streamed generic-error channel below uses an x86_64 SysV va_list
    // trampoline (ch_call0/1/2 — register-based). Other ABIs (i686 cdecl,
    // ARM/aarch64 AAPCS, ...) fall back to the plain raise path; full
    // streamed-fragment parity there is an unexecuted platform obligation
    // (atlas/PLATFORM_SURFACE_ATLAS.md, OBLIG-WORDSIZE-32 / compiler-ABI).
    #[cfg(not(target_arch = "x86_64"))]
    {
        raise_error(
            ctxt,
            ptr::null_mut(),
            ptr::null_mut(),
            ptr::null_mut(),
            ptr::null_mut(),
            domain,
            code,
            level,
            file,
            line,
            str1,
            str2,
            str3,
            int1,
            col,
            msg,
        );
        return;
    }

    #[cfg(target_arch = "x86_64")]
    {
        // UPSTREAM-PARITY (xmlVRaiseError): warnings are suppressed when the
        // TLS global xmlGetWarningsDefaultValue is zero.
        if level == xmlErrorLevel::XML_ERR_WARNING as c_int
            && crate::xml::globals::get_get_warnings_default() == 0
        {
            return;
        }

        raise_error_streamed_x86_64(
            ctxt,
            domain,
            code,
            level,
            file,
            line,
            col,
            str1,
            str2,
            str3,
            int1,
            msg,
            source_window,
            enc_bytes,
            delivery,
            tail,
        );
    }
}

/// x86-64 streamed raise (SysV va_list channel). See `raise_error_streamed`.
///
/// # Safety
///
/// - `ctxt` may be NULL; `msg`, `file`, `str1`, `str2`, `str3` must be
///   valid NUL-terminated C strings or NULL; `source_window` bytes must be
///   valid for the duration of the call; every string field is duplicated
///   before being stored in the thread-local last error.
#[allow(clippy::too_many_arguments)]
#[cfg(target_arch = "x86_64")]
unsafe fn raise_error_streamed_x86_64(
    ctxt: *mut c_void,
    domain: c_int,
    code: c_int,
    level: c_int,
    file: *const c_char,
    line: c_int,
    col: c_int,
    str1: *const c_char,
    str2: *const c_char,
    str3: *const c_char,
    int1: c_int,
    msg: *const c_char,
    source_window: Option<(&[u8], usize)>,
    enc_bytes: Option<[u8; 4]>,
    delivery: GenericDelivery,
    tail: Option<(c_int, Option<(&[u8], usize)>)>,
) {
    // UPSTREAM-PARITY (xmlVRaiseError): warnings are suppressed when the
    // TLS global xmlGetWarningsDefaultValue is zero.
    if level == xmlErrorLevel::XML_ERR_WARNING as c_int
        && crate::xml::globals::get_get_warnings_default() == 0
    {
        return;
    }

    // Format the error message (same as raise_error).
    let formatted_msg = format_error_message(domain, code, msg, str1, str2, str3);
    let file_copy = if file.is_null() {
        ptr::null_mut()
    } else {
        crate::abi::allocator::xmlMemStrdupImpl(file) as *mut c_char
    };
    let str1_copy = if str1.is_null() {
        ptr::null_mut()
    } else {
        crate::abi::allocator::xmlMemStrdupImpl(str1) as *mut c_char
    };
    let str2_copy = if str2.is_null() {
        ptr::null_mut()
    } else {
        crate::abi::allocator::xmlMemStrdupImpl(str2) as *mut c_char
    };
    let str3_copy = if str3.is_null() {
        ptr::null_mut()
    } else {
        crate::abi::allocator::xmlMemStrdupImpl(str3) as *mut c_char
    };
    let err = _xmlError {
        domain,
        code,
        message: formatted_msg,
        level,
        file: file_copy,
        line,
        str1: str1_copy,
        str2: str2_copy,
        str3: str3_copy,
        int1,
        int2: col,
        ctxt,
        node: ptr::null_mut(),
    };

    // UPSTREAM-PARITY (xpath.c xmlXPathErrFmt -> error.c xmlVRaiseError): an
    // XPath-domain error stores in the TLS global (upstream `to = lastError`;
    // xmlXPathErrFmt separately pre-fills ctxt->lastError with the
    // message-less domain/code/str1 fields) and dispatches to the XPath
    // context's `error` handler with `userData`.
    let is_xpath_error = !ctxt.is_null() && domain == XML_FROM_XPATH;

    // UPSTREAM-PARITY (error.c xmlVRaiseError 2.15): parser-domain errors
    // with a context update the PER-CONTEXT lastError (to = &ctxt->lastError)
    // and then mirror into the TLS global (xmlCopyError); the callback
    // receives the per-context error. Non-parser domains keep the TLS global
    // as the single storage.
    let is_ctxt_error = !ctxt.is_null()
        && matches!(
            domain,
            XML_FROM_PARSER
                | XML_FROM_HTML
                | XML_FROM_DTD
                | XML_FROM_NAMESPACE
                | XML_FROM_IO
                | XML_FROM_VALID
        );
    let to: *const _xmlError = if is_ctxt_error {
        let c = &mut *(ctxt as *mut crate::abi::structs::_xmlParserCtxt);
        // Free the previous per-context strings (upstream xmlResetError in
        // xmlVUpdateError) before taking ownership of the new ones.
        globals::free_error_strings(&c.lastError);
        ptr::write(&mut c.lastError, err);
        // Mirror into the TLS global with owned copies (upstream
        // xmlCopyError(to, lastError)).
        globals::set_last_error(deep_copy_error(&c.lastError));
        &c.lastError
    } else {
        globals::set_last_error(err);
        globals::get_last_error()
    };

    // UPSTREAM-PARITY (parserInternals.c xmlCtxtVErr channel selection):
    // ctxt->errorHandler (xmlCtxtSetErrorHandler) wins, then the SAX2
    // `serror` slot (lxml installs this), then the legacy SAX generic
    // channel. The per-context structured handler is preferred over the
    // TLS global structured handler (error.c xmlVRaiseError order).
    let mut schannel: Option<xmlStructuredErrorFunc> = None;
    let mut sdata: *mut c_void = ptr::null_mut();
    if is_xpath_error {
        let xc = &*(ctxt as *const crate::abi::structs::_xmlXPathContext);
        if let Some(handler) = xc.error {
            schannel = Some(handler);
            sdata = xc.userData;
        }
    } else if is_ctxt_error {
        let c = &*(ctxt as *const crate::abi::structs::_xmlParserCtxt);
        if let Some(handler) = c.errorHandler {
            schannel = Some(handler);
            sdata = c.errorCtxt;
        } else if !c.sax.is_null() {
            let sax = &*c.sax;
            if sax.initialized == XML_SAX2_MAGIC as c_uint && sax.serror.is_some() {
                schannel = sax.serror;
                sdata = c.userData;
            }
        }
    }
    if let Some(handler) = schannel {
        // SAFETY: the selected structured callback and its data come from
        // the parser context (or the TLS install), valid per the C API.
        handler(sdata, to);
        return;
    }

    // Global structured handler (upstream `else if` chain); the (handler,
    // ctx) pair is read atomically and invoked outside the lock (11.1-X).
    let structured = globals::with_structured_error(|h, c| (h, c));
    if let Some(handler) = structured.0 {
        if !to.is_null() {
            handler(structured.1, to);
        }
        return;
    }

    match delivery {
        GenericDelivery::Custom(channel, ctx) => {
            if !msg.is_null() {
                // SAFETY: the caller provided a valid C callback.
                unsafe { channel(ctx, msg) };
            }
        }
        GenericDelivery::Stream => {
            if globals::get_generic_error_func().is_some() {
                unsafe {
                    format_error_streamed(
                        domain,
                        code,
                        level,
                        formatted_msg,
                        file,
                        line,
                        source_window,
                        enc_bytes,
                        tail,
                    )
                };
            }
        }
        GenericDelivery::None => {}
    }
}

/// Deep-copy an error's owned string fields (upstream `xmlCopyError`): the
/// destination takes freshly strdup'd copies so both errors own their
/// strings independently.
///
/// # Safety
///
/// - `err` must be a valid `_xmlError` whose string fields are NULL or
///   NUL-terminated.
unsafe fn deep_copy_error(err: &_xmlError) -> _xmlError {
    unsafe {
        let dup = |p: *mut c_char| -> *mut c_char {
            if p.is_null() {
                ptr::null_mut()
            } else {
                crate::abi::allocator::xmlMemStrdupImpl(p) as *mut c_char
            }
        };
        _xmlError {
            domain: err.domain,
            code: err.code,
            message: dup(err.message),
            level: err.level,
            file: dup(err.file),
            line: err.line,
            str1: dup(err.str1),
            str2: dup(err.str2),
            str3: dup(err.str3),
            int1: err.int1,
            int2: err.int2,
            ctxt: err.ctxt,
            node: err.node,
        }
    }
}

/// Default SAX v1 error handler — upstream `void xmlParserError(void *ctx,
/// const char *msg, ...)`. Variadic x86_64 SysV shim (11.1-Z.2, R-000176:
/// the previous fixed-arity body silently dropped the varargs; upstream
/// error.c formats them via `xmlVFormatLegacyError`).
///
/// 2 fixed args (ctx=rdi, msg=rsi) → `gp_offset` 16; the va_list pointer is
/// passed as the 3rd arg (rdx) to the `xmlParserErrorV` receiver.
///
/// # SAFETY
///
/// - `ctx` may be NULL (unused by the candidate's legacy path).
/// - `msg` must be a valid NUL-terminated printf format string.
#[cfg(target_arch = "x86_64")]
#[no_mangle]
pub unsafe extern "C" fn xmlParserError() -> c_int {
    unsafe { legacy_shim(xmlParserErrorV) }
}

/// Variadic receiver for the `xmlParserError` shim: formats `msg` with the
/// caller's varargs and emits `"error: "` + formatted text through the
/// generic channel (upstream error.c `xmlVFormatLegacyError`).
///
/// x86_64-only: the va_list layout (`VaListTag`) is the SysV AMD64
/// `__va_list_tag`; other ABIs carry their own varargs representation and the
/// register-shim entry (`xmlParserError`) is x86_64-gated with it.
///
/// # Safety
///
/// - `msg` must be a valid NUL-terminated printf format string, `ap` a
///   valid va_list matching the format, `ctx` may be NULL.
#[cfg(target_arch = "x86_64")]
#[no_mangle]
pub unsafe extern "C" fn xmlParserErrorV(
    ctx: *mut c_void,
    msg: *const c_char,
    ap: *mut VaListTag,
) -> c_int {
    let _ = ctx;
    unsafe { emit_legacy_message_v("error", msg, ap) }
}

/// Default SAX v1 warning handler — upstream `void xmlParserWarning(void
/// *ctx, const char *msg, ...)`. Variadic shim as `xmlParserError`.
///
/// # SAFETY
///
/// - `ctx` may be NULL (unused by the candidate's legacy path).
/// - `msg` must be a valid NUL-terminated printf format string.
#[cfg(target_arch = "x86_64")]
#[no_mangle]
pub unsafe extern "C" fn xmlParserWarning() -> c_int {
    unsafe { legacy_shim(xmlParserWarningV) }
}

/// Variadic receiver for the `xmlParserWarning` shim.
///
/// x86_64-only: see `xmlParserErrorV`.
///
/// # Safety
///
/// - `msg` must be a valid NUL-terminated printf format string, `ap` a
///   valid va_list matching the format, `ctx` may be NULL.
#[cfg(target_arch = "x86_64")]
#[no_mangle]
pub unsafe extern "C" fn xmlParserWarningV(
    ctx: *mut c_void,
    msg: *const c_char,
    ap: *mut VaListTag,
) -> c_int {
    let _ = ctx;
    unsafe { emit_legacy_message_v("warning", msg, ap) }
}

/// Default validity error handler — upstream `void
/// xmlParserValidityError(void *ctx, const char *msg, ...)`. Variadic shim
/// as `xmlParserError`.
///
/// # SAFETY
///
/// - `ctx` may be NULL (unused by the candidate's legacy path).
/// - `msg` must be a valid NUL-terminated printf format string.
#[cfg(target_arch = "x86_64")]
#[no_mangle]
pub unsafe extern "C" fn xmlParserValidityError() -> c_int {
    unsafe { legacy_shim(xmlParserValidityErrorV) }
}

/// Variadic receiver for the `xmlParserValidityError` shim.
///
/// x86_64-only: see `xmlParserErrorV`.
///
/// # Safety
///
/// - `msg` must be a valid NUL-terminated printf format string, `ap` a
///   valid va_list matching the format, `ctx` may be NULL.
#[cfg(target_arch = "x86_64")]
#[no_mangle]
pub unsafe extern "C" fn xmlParserValidityErrorV(
    ctx: *mut c_void,
    msg: *const c_char,
    ap: *mut VaListTag,
) -> c_int {
    let _ = ctx;
    unsafe { emit_legacy_message_v("validity error", msg, ap) }
}

/// Default validity warning handler — upstream `void
/// xmlParserValidityWarning(void *ctx, const char *msg, ...)`. Variadic
/// shim as `xmlParserError`.
///
/// # SAFETY
///
/// - `ctx` may be NULL (unused by the candidate's legacy path).
/// - `msg` must be a valid NUL-terminated printf format string.
#[cfg(target_arch = "x86_64")]
#[no_mangle]
pub unsafe extern "C" fn xmlParserValidityWarning() -> c_int {
    unsafe { legacy_shim(xmlParserValidityWarningV) }
}

/// Variadic receiver for the `xmlParserValidityWarning` shim.
///
/// x86_64-only: see `xmlParserErrorV`.
///
/// # Safety
///
/// - `msg` must be a valid NUL-terminated printf format string, `ap` a
///   valid va_list matching the format, `ctx` may be NULL.
#[cfg(target_arch = "x86_64")]
#[no_mangle]
pub unsafe extern "C" fn xmlParserValidityWarningV(
    ctx: *mut c_void,
    msg: *const c_char,
    ap: *mut VaListTag,
) -> c_int {
    let _ = ctx;
    unsafe { emit_legacy_message_v("validity warning", msg, ap) }
}

/// The variadic `xmlParserError` shim, transmuted to the fixed-arity SAX v1
/// callback type. The shim's declared arity is a Rust-side fiction (stable
/// Rust cannot express `c_variadic`); the ABI is a plain code pointer and
/// the C variadic call contract is preserved (11.1-Z.2, R-000176).
#[cfg(target_arch = "x86_64")]
pub const XML_PARSER_ERROR_SAX1: errorSAXFunc = unsafe {
    // SAFETY: shim and SAX callback are both plain code pointers (same ABI);
    // the declared arity difference is the documented shim fiction.
    core::mem::transmute::<unsafe extern "C" fn() -> c_int, errorSAXFunc>(xmlParserError)
};

/// The variadic `xmlParserWarning` shim as the SAX v1 callback type.
#[cfg(target_arch = "x86_64")]
pub const XML_PARSER_WARNING_SAX1: errorSAXFunc = unsafe {
    // SAFETY: see XML_PARSER_ERROR_SAX1.
    core::mem::transmute::<unsafe extern "C" fn() -> c_int, errorSAXFunc>(xmlParserWarning)
};

/// The variadic `xmlParserValidityError` shim as the validation callback
/// type (`xmlValidityErrorFunc`-compatible fixed-arity pointer).
#[cfg(target_arch = "x86_64")]
pub const XML_PARSER_VALIDITY_ERROR_SAX1: unsafe extern "C" fn(*mut c_void, *const c_char) =
    // SAFETY: see XML_PARSER_ERROR_SAX1.
    unsafe {
        core::mem::transmute::<
            unsafe extern "C" fn() -> c_int,
            unsafe extern "C" fn(*mut c_void, *const c_char),
        >(xmlParserValidityError)
    };

/// The variadic `xmlParserValidityWarning` shim as the validation callback
/// type.
#[cfg(target_arch = "x86_64")]
pub const XML_PARSER_VALIDITY_WARNING_SAX1: unsafe extern "C" fn(*mut c_void, *const c_char) =
    // SAFETY: see XML_PARSER_ERROR_SAX1.
    unsafe {
        core::mem::transmute::<
            unsafe extern "C" fn() -> c_int,
            unsafe extern "C" fn(*mut c_void, *const c_char),
        >(xmlParserValidityWarning)
    };

#[cfg(not(target_arch = "x86_64"))]
mod legacy_plain {
    //! Non-x86_64 fallbacks for the default legacy error/warning handlers.
    //!
    //! The x86_64 implementations forward the CALLER's C varargs to
    //! `vsnprintf` through a SysV register-save-area asm shim (R-000176).
    //! Other ABIs carry their own va_list representation; building the
    //! matching shim per ABI is a documented platform obligation (R-000168,
    //! varargs family). On those (unexecuted) ABIs the default slots emit the
    //! caller's message text VERBATIM — the candidate's own error machinery
    //! always hands these slots pre-formatted text, so the emitted bytes are
    //! identical for every internal raise; only a C consumer that variadically
    //! calls the DEFAULT handler with format arguments would observe the
    //! difference (unexecuted, tracked in PLATFORM_SURFACE_ATLAS).
    use super::emit_legacy_message;
    use crate::abi::callbacks::errorSAXFunc;
    use core::ffi::{c_char, c_void};

    unsafe extern "C" fn error(ctx: *mut c_void, msg: *const c_char) {
        let _ = ctx;
        unsafe { emit_legacy_message("error", msg) };
    }
    unsafe extern "C" fn warning(ctx: *mut c_void, msg: *const c_char) {
        let _ = ctx;
        unsafe { emit_legacy_message("warning", msg) };
    }
    unsafe extern "C" fn validity_error(ctx: *mut c_void, msg: *const c_char) {
        let _ = ctx;
        unsafe { emit_legacy_message("validity error", msg) };
    }
    unsafe extern "C" fn validity_warning(ctx: *mut c_void, msg: *const c_char) {
        let _ = ctx;
        unsafe { emit_legacy_message("validity warning", msg) };
    }

    pub const XML_PARSER_ERROR_SAX1: errorSAXFunc = error;
    pub const XML_PARSER_WARNING_SAX1: errorSAXFunc = warning;
    pub const XML_PARSER_VALIDITY_ERROR_SAX1: unsafe extern "C" fn(*mut c_void, *const c_char) =
        validity_error;
    pub const XML_PARSER_VALIDITY_WARNING_SAX1: unsafe extern "C" fn(*mut c_void, *const c_char) =
        validity_warning;
}

#[cfg(not(target_arch = "x86_64"))]
pub use legacy_plain::{
    XML_PARSER_ERROR_SAX1, XML_PARSER_VALIDITY_ERROR_SAX1, XML_PARSER_VALIDITY_WARNING_SAX1,
    XML_PARSER_WARNING_SAX1,
};

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

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

    /// Reset an error struct and verify the defaults are applied.
    ///
    /// # Safety
    ///
    /// - `err` is a stack `_xmlError` whose fields are all NULL/zero; it
    ///   is valid for `reset_error` to write and for the subsequent reads.
    #[test]
    fn test_error_default_reset() {
        unsafe {
            let mut err = _xmlError {
                domain: XML_FROM_PARSER,
                code: XML_ERR_NO_MEMORY,
                message: ptr::null_mut(),
                level: XML_ERR_ERROR as c_int,
                file: ptr::null_mut(),
                line: 42,
                str1: ptr::null_mut(),
                str2: ptr::null_mut(),
                str3: ptr::null_mut(),
                int1: 0,
                int2: 0,
                ctxt: ptr::null_mut(),
                node: ptr::null_mut(),
            };

            reset_error(&mut err);
            assert_eq!(err.domain, XML_FROM_NONE);
            assert_eq!(err.code, XML_ERR_OK as c_int);
            assert_eq!(err.level, XML_ERR_NONE as c_int);
            assert_eq!(err.line, 0);
        }
    }

    /// Copy one error struct into another and verify the fields.
    ///
    /// # Safety
    ///
    /// - `from` and `to` are stack `_xmlError` structs valid for the
    ///   `copy_error` copy and the subsequent field reads.
    #[test]
    fn test_copy_error() {
        unsafe {
            let from = _xmlError {
                domain: XML_FROM_PARSER,
                code: XML_ERR_NO_MEMORY,
                message: ptr::null_mut(),
                level: XML_ERR_FATAL as c_int,
                file: ptr::null_mut(),
                line: 100,
                str1: ptr::null_mut(),
                str2: ptr::null_mut(),
                str3: ptr::null_mut(),
                int1: 1,
                int2: 2,
                ctxt: ptr::null_mut(),
                node: ptr::null_mut(),
            };
            let mut to = _xmlError {
                domain: XML_FROM_NONE,
                code: XML_ERR_OK as c_int,
                message: ptr::null_mut(),
                level: XML_ERR_NONE as c_int,
                file: ptr::null_mut(),
                line: 0,
                str1: ptr::null_mut(),
                str2: ptr::null_mut(),
                str3: ptr::null_mut(),
                int1: 0,
                int2: 0,
                ctxt: ptr::null_mut(),
                node: ptr::null_mut(),
            };

            let result = copy_error(&from, &mut to);
            assert_eq!(result, 0);
            assert_eq!(to.domain, XML_FROM_PARSER);
            assert_eq!(to.code, XML_ERR_NO_MEMORY);
            assert_eq!(to.level, XML_ERR_FATAL as c_int);
            assert_eq!(to.line, 100);
            assert_eq!(to.int1, 1);
            assert_eq!(to.int2, 2);
        }
    }

    /// Raise an error and verify it is stored as the last error.
    ///
    /// # Safety
    ///
    /// - `file`/`str1` are static NUL-terminated strings valid for the
    ///   raise; `raise_error` duplicates them, so the test's later reads of
    ///   `last` only touch the thread-local copy; `reset_last_error`
    ///   releases the owned strings exactly once.
    #[test]
    fn test_raise_and_get_last_error() {
        unsafe {
            reset_last_error();
            assert!(get_last_error().is_null());

            let file = b"test.xml\0" as *const u8 as *const c_char;
            let str1 = b"element\0" as *const u8 as *const c_char;

            raise_error(
                ptr::null_mut(),
                ptr::null_mut(),
                ptr::null_mut(),
                ptr::null_mut(),
                ptr::null_mut(),
                XML_FROM_PARSER,
                XML_ERR_TAG_NAME_MISMATCH,
                XML_ERR_ERROR as c_int,
                file,
                10,
                str1,
                ptr::null(),
                ptr::null(),
                0,
                0,
                ptr::null(),
            );

            let last = get_last_error();
            assert!(!last.is_null());
            assert_eq!((*last).domain, XML_FROM_PARSER);
            assert_eq!((*last).code, XML_ERR_TAG_NAME_MISMATCH);
            assert_eq!((*last).level, XML_ERR_ERROR as c_int);
            assert_eq!((*last).line, 10);

            // Check file was stored
            let last_file = (*last).file;
            assert!(!last_file.is_null());

            reset_last_error();
            assert!(get_last_error().is_null());
        }
    }

    #[test]
    fn test_structured_error_callback() {
        // Serialized against the handler-slot tests in xml::globals (11.1-X):
        // the structured handler slot is shared global state.
        let _guard = crate::xml::globals::ERROR_HANDLER_TEST_LOCK.lock();
        unsafe {
            reset_last_error();

            // Set up a structured error handler that captures the error
            let mut captured_domain: c_int = 0;
            let captured_ptr = &mut captured_domain as *mut c_int as *mut c_void;

            // SAFETY: The callback writes to captured_ptr which lives on the stack
            // for the duration of this test.
            extern "C" fn test_handler(ctx: *mut c_void, _err: *const _xmlError) {
                // SAFETY: ctx is valid for the test duration.
                unsafe {
                    let captured = &mut *(ctx as *mut c_int);
                    *captured = 42;
                }
            }

            set_structured_error_func(captured_ptr, Some(test_handler as xmlStructuredErrorFunc));

            raise_error(
                ptr::null_mut(),
                ptr::null_mut(),
                ptr::null_mut(),
                ptr::null_mut(),
                ptr::null_mut(),
                XML_FROM_PARSER,
                XML_ERR_OK as c_int,
                XML_ERR_WARNING as c_int,
                ptr::null(),
                0,
                ptr::null(),
                ptr::null(),
                ptr::null(),
                0,
                0,
                ptr::null(),
            );

            assert_eq!(captured_domain, 42);

            // Reset
            set_structured_error_func(ptr::null_mut(), None);
            reset_last_error();
        }
    }

    /// Format messages with a direct `msg` and with domain plus `str1`.
    ///
    /// # Safety
    ///
    /// - `msg`/`str1` are static NUL-terminated strings valid for the
    ///   calls; each returned buffer is allocator-owned and freed with
    ///   `xmlFreeImpl` exactly once before the test ends.
    #[test]
    fn test_format_error_message() {
        unsafe {
            // Test with direct message
            let msg = b"test error\0" as *const u8 as *const c_char;
            let formatted = format_error_message(
                XML_FROM_NONE,
                XML_ERR_OK as c_int,
                msg,
                ptr::null(),
                ptr::null(),
                ptr::null(),
            );
            assert!(!formatted.is_null());
            let formatted_str = std::ffi::CStr::from_ptr(formatted);
            assert_eq!(formatted_str.to_bytes(), b"test error");

            // Free the allocated message
            allocator::xmlFreeImpl(formatted as *mut c_void);

            // Test with domain and str1
            let str1 = b"foo\0" as *const u8 as *const c_char;
            let formatted2 = format_error_message(
                XML_FROM_PARSER,
                XML_ERR_OK as c_int,
                ptr::null(),
                str1,
                ptr::null(),
                ptr::null(),
            );
            assert!(!formatted2.is_null());
            allocator::xmlFreeImpl(formatted2 as *mut c_void);
        }
    }
}