libxml-rs 0.1.0-alpha.43

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
//! xmllint — XML validation and formatting tool (§36, §85 Phase 10).
//!
//! Faithful port of the upstream libxml2 `xmllint` command-line tool
//! (xmllint.c, libxml2 2.12..2.15 target; the current capability target is
//! the system oracle 2.15.3, see atlas/COMPATIBILITY_PROFILES.md). The
//! pipeline is entirely native Rust:
//!
//! ```text
//! Rust CLI → Rust libxml parser/validator/serializer → Rust XPath/C14N
//! ```
//!
//! # Exit codes (upstream parity, measured against libxml2 2.15.3)
//!
//! | Code | Meaning |
//! |------|---------|
//! | 0 | success |
//! | 1 | usage error (no arguments) |
//! | 3 | validity error (DTD validation failed) |
//! | 4 | parse error / cannot open file |
//! | 5 | schema compilation failure |
//! | 6 | schema validation failure |
//! | 7 | schematron validation failure |
//!
//! # Upstream contract
//!
//! Mirrors `xmllint.c` from SRC-LIBXML2-GIT (archaeology/libxml2-git), the
//! canonical reference implementation of the xmllint command-line tool. The
//! parity target is the upstream option surface (every `--option` printed by
//! `usage()`), the observable `xmllintReturnCode` enum declared in xmllint.c
//! (XMLLINT_ERR_UNCLASS=1, XMLLINT_ERR_VALID=3, XMLLINT_ERR_RDFILE=4,
//! XMLLINT_ERR_SCHEMACOMP=5, XMLLINT_ERR_OUT=6, XMLLINT_ERR_SCHEMAPAT=7,
//! XMLLINT_ERR_XPATH=10, XMLLINT_ERR_XPATH_EMPTY=11), the stderr
//! diagnostics, and the exit status. The CLI is not part of the C ABI; its
//! contract is the command line itself, verified byte-for-byte against the
//! 2.15.3 oracle.
//!
//! # Conceptual behavior
//!
//! The tool parses each input with the native Rust parser, then optionally
//! runs validation (DTD, WXS schema, RELAX NG, Schematron), XPath queries,
//! C14N, XInclude, pattern testing, and serialization, printing results in
//! upstream byte order. The implementation model follows xmllint.c: a state
//! struct (upstream `xmllintState` + `xmlLintOptions` bits) accumulates parse
//! options and app options; each input document goes through one
//! parse-and-process pass; the output dump is skipped only under --noout
//! (XPath implies --noout); --shell runs a navigating shell; the final exit
//! status is the worst error seen, and earlier errors are never downgraded
//! by later successes.
//!
//! # Ownership & safety invariants
//!
//! - The CLI owns its `Cli` state; each document is owned by the parser and
//!   freed with `free_doc` exactly once per file (process_file), never by
//!   the caller.
//! - Every `cstr_alloc` is paired with `free_cstr` (libc malloc/free), so
//!   the CLI never mixes Rust allocators with C-side memory.
//! - `doc->URL` is owned by the document. The CLI only installs it when the
//!   parser left it null, and always installs an owned duplicate — the
//!   R-000169 defect family (non-NUL-terminated `xml_strdup`) is closed and
//!   regressed by the TREE-001 structural probe.
//! - `CAPTURED_VALIDITY` is a thread_local buffer drained before rendering,
//!   so no borrowed message outlives its callback.
//! - The output FILE* from `get_output_file` is closed only when --output
//!   named a real file; the `fdopen(1, ...)` stdout handle is process-owned
//!   and never closed here.
//!
//! # Historical quirks & epochs
//!
//! The observable behavior of the CLI is a mosaic of semantic epochs measured by
//! the historical oracle matrix (atlas/SEMANTIC_EPOCHS.md):
//!
//! - E-001: `--xpath` node-set output became newline-separated in 2.9.10
//!   (commit da35eeae, an upstream-documented breaking change).
//! - E-003: an empty XPath node-set exits 10 → 0 (commit e85f9b98, 2.11.0)
//!   → 11 (commit 387a952b, 2.12.6); the crate targets the 2.12.6+ epoch.
//! - E-005: parser-error/undeclared exits moved 1 → 4 and valid-invalid
//!   4 → 3 in 2.13.0 (xmllint error/option-handling rework).
//! - E-006: `--valid` with no DTD exits 0 since 2.15.0 (was 3 in
//!   2.13.0..2.14.1, 4 before that).
//! - E-004: `--debug --noent` entity content dumps `TEXT compact` since
//!   2.13.0 (commit 8d04f0ee).
//! - E-007: `--html` dump is single-line since 2.15.0 (newline writes were
//!   removed from HTMLtree.c).
//!
//! # Deliberate oddities
//!
//! - Running with no arguments prints usage and exits 1
//!   (XMLLINT_ERR_UNCLASS), matching `if (argc <= 1)` in xmllint.c.
//! - The option pass does NOT stop at the first non-option argument: modern
//!   xmllint.c parses options and files in two passes (`continue` on
//!   non-option args in the option loop, `skipArgs` in the document loop),
//!   so options may interleave with filenames. This is a deliberate
//!   asymmetry with xmlcatalog/xsltproc, which do break at the first
//!   non-option argument — the CLI trio mirrors the asymmetry upstream itself has.
//! - Unknown options print `Unknown option` + usage to stderr and exit 1.
//! - `--xmlout` without `--html` prints a warning and continues.
//!
//! # Proving courts
//!
//! The CLI-XMLLINT-* differential court family
//! (courts/suites/cli/xmllint/, CLI-XMLLINT-0001..0047) compares the
//! candidate (exit, stdout, stderr) against the 2.15.3 system oracle; the
//! historical matrix (oracle/historical/run_matrix.sh, HIST-EPOCH-* casefiles
//! and receipts) pins every epoch boundary above. The C14N, DTD, HTML,
//! PARSER, RELAXNG, SCHEMATRON, XINCLUDE and XSD court families exercise the
//! engine paths this CLI drives; R-000121 and R-000169 are regressed by
//! CLI-XMLLINT-0034 and the TREE-001 probe.
//!
//! # Tempting simplifications that would break parity
//!
//! - Replacing the hand-rolled option loop with a general-purpose argument
//!   parser would change the unknown-option exit code and the exact usage
//!   text that courts compare.
//! - Collapsing the epoch exit codes into one generic error value would
//!   break E-003/E-005: scripts distinguish exit 3 (validity) from 4
//!   (parse/IO) and 11 (empty XPath node-set).
//! - Treating an empty XPath node-set as success would silently revert to
//!   the 2.11.0..2.12.5 epoch (E-003).
//! - Serializing XPath results with a naive `join` would break the E-001
//!   byte-identical newline placement (and the --xpath0 NUL separator).
//! - Copying the xmlcatalog break-at-first-non-option parsing here would
//!   reject interleaved `--option file.xml --option2` invocations that
//!   modern xmllint accepts.

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

use libxml_rs::abi::exports_xml2::*;
use libxml_rs::abi::structs::*;
use libxml_rs::abi::types::*;
use libxml_rs::abi::versioning::{xmlLibxmlVersion, xmlLibxmlVersionString};

// ── Parser option bits (upstream XML_PARSE_* values) ───────────────────────
const XML_PARSE_RECOVER: c_int = 1 << 0;
const XML_PARSE_NOENT: c_int = 1 << 1;
const XML_PARSE_DTDLOAD: c_int = 1 << 2;
const XML_PARSE_DTDATTR: c_int = 1 << 3;
const XML_PARSE_PEDANTIC: c_int = 1 << 7;
const XML_PARSE_NOBLANKS: c_int = 1 << 8;
const XML_PARSE_NONET: c_int = 1 << 11;
const XML_PARSE_NOCDATA: c_int = 1 << 14;
const XML_PARSE_COMPACT: c_int = 1 << 16;
const XML_PARSE_OLD10: c_int = 1 << 17;
const XML_PARSE_HUGE: c_int = 1 << 19;
const XML_PARSE_IGNORE_ENC: c_int = 1 << 21;
const XML_PARSE_BIG_LINES: c_int = 1 << 22;

// The remaining upstream XML_PARSE_* bits (DTDVALID, NOERROR, NOWARNING,
// SAX1, XINCLUDE, NODICT, NSCLEAN, NOXINCNODE, NOBASEFIX, OLDSAX) are not
// surfaced by this CLI; see archaeology/libxml2-git/parser.h for their
// values.

/// CLI state (mirrors upstream xmllint.c file-scope globals).
struct Cli {
    shell: bool,
    debug: bool,
    copy: bool,
    recover: bool,
    noout: bool,
    nonet: bool,
    nocompact: bool,
    loaddtd: bool,
    dtdattr: bool,
    loadtrace: bool,
    push: bool,
    memory: bool,
    timing: bool,
    repeat: bool,
    valid: bool,
    postvalid: bool,
    html: bool,
    xmlout: bool,
    nodefdtd: bool,
    dropdtd: bool,
    insert: bool,
    quiet: bool,
    nowarning: bool,
    noblanks: bool,
    nocdata: bool,
    nodict: bool,
    pedantic: bool,
    nsclean: bool,
    auto: bool,
    xinclude: bool,
    noxincludenode: bool,
    nofixup_base_uris: bool,
    catalogs: bool,
    nocatalogs: bool,
    stream: bool,
    walker: bool,
    sax1: bool,
    sax: bool,
    oldxml10: bool,
    strict_namespace: bool,
    encode: Option<String>,
    output: Option<String>,
    format: c_int, // -1 unset, 0 no, 1 yes
    pretty: c_int,
    compress: bool,
    c14n: c_int, // 0 none, 1 c14n, 2 c14n11, 3 exclusive
    pattern: Option<String>,
    schema: Option<String>,
    relaxng: Option<String>,
    schematron: Option<String>,
    xpath: Option<String>,
    xpath0: bool,
    paths: Vec<String>,
    dtdvalid: Option<String>,
    dtdvalidfpi: Option<String>,
    maxmem: Option<usize>,
    max_ampl: Option<f64>,
    options: c_int,
    return_code: c_int,
}

impl Default for Cli {
    fn default() -> Self {
        Cli {
            shell: false,
            debug: false,
            copy: false,
            recover: false,
            noout: false,
            nonet: false,
            nocompact: false,
            loaddtd: false,
            dtdattr: false,
            loadtrace: false,
            push: false,
            memory: false,
            timing: false,
            repeat: false,
            valid: false,
            postvalid: false,
            html: false,
            xmlout: false,
            nodefdtd: false,
            dropdtd: false,
            insert: false,
            quiet: false,
            nowarning: false,
            noblanks: false,
            nocdata: false,
            nodict: false,
            pedantic: false,
            nsclean: false,
            auto: false,
            xinclude: false,
            noxincludenode: false,
            nofixup_base_uris: false,
            catalogs: false,
            nocatalogs: false,
            stream: false,
            walker: false,
            sax1: false,
            sax: false,
            oldxml10: false,
            strict_namespace: false,
            encode: None,
            output: None,
            format: -1,
            pretty: -1,
            compress: false,
            c14n: 0,
            pattern: None,
            schema: None,
            relaxng: None,
            schematron: None,
            xpath: None,
            xpath0: false,
            paths: Vec::new(),
            dtdvalid: None,
            dtdvalidfpi: None,
            maxmem: None,
            max_ampl: None,
            // UPSTREAM-PARITY: xmllint defaults parseOptions to
            // XML_PARSE_COMPACT | XML_PARSE_BIG_LINES (xmllint.c:2579);
            // --nocompact clears the COMPACT bit.
            options: XML_PARSE_COMPACT | XML_PARSE_BIG_LINES,
            return_code: 0,
        }
    }
}

fn usage() {
    let argv0 = std::env::args()
        .next()
        .unwrap_or_else(|| "xmllint".to_string());
    eprintln!("Usage : {} [options] XMLfiles ...", argv0);
    eprintln!("\tParse the XML files and output the result of the parsing");
    eprintln!("\t--version : display the version of the XML library used");
    eprintln!("\t--shell : run a navigating shell");
    eprintln!("\t--debug : show additional debug information");
    eprintln!("\t--copy : used to test the internal copy implementation");
    eprintln!("\t--recover : output what was parsable on broken XML documents");
    eprintln!("\t--huge : remove any internal arbitrary parser limits");
    eprintln!("\t--noent : substitute entity references by their value");
    eprintln!("\t--noenc : ignore any encoding specified inside the document");
    eprintln!("\t--noout : don't output the result tree");
    eprintln!("\t--path 'paths': provide a set of paths for resources");
    eprintln!("\t--load-trace : print trace of all external entities loaded");
    eprintln!("\t--nonet : refuse to fetch DTDs or entities over network");
    eprintln!("\t--nocompact : do not generate compact text nodes");
    eprintln!("\t--valid : validate the document in addition to std well-formed check");
    eprintln!("\t--postvalid : do a posteriori validation, i.e after parsing");
    eprintln!("\t--dtdvalid URL : do a posteriori validation against a given DTD");
    eprintln!("\t--dtdvalidfpi FPI : same but name the DTD with a Public Identifier");
    eprintln!("\t--insert : ad-hoc test for valid insertions");
    eprintln!(
        "\t--strict-namespace : Return application failure if document has any namespace errors"
    );
    eprintln!("\t--quiet : be quiet when succeeded");
    eprintln!("\t--timing : print some timings");
    eprintln!("\t--repeat : repeat 100 times, for timing or profiling");
    eprintln!("\t--dropdtd : remove the DOCTYPE of the input docs");
    eprintln!("\t--html : use the HTML parser");
    eprintln!("\t--nodefdtd : do not default HTML doctype");
    eprintln!("\t--xmlout : force to use the XML serializer when using --html");
    eprintln!("\t--push : use the push mode of the parser");
    eprintln!("\t--memory : parse from memory");
    eprintln!("\t--maxmem nbbytes : limits memory allocation to nbbytes bytes");
    eprintln!("\t--nowarning : do not emit warnings from parser/validator");
    eprintln!("\t--noblanks : drop (ignorable?) blanks spaces");
    eprintln!("\t--nocdata : replace cdata section with text nodes");
    eprintln!("\t--nodict : create document without dictionary");
    eprintln!("\t--pedantic : enable additional warnings");
    eprintln!("\t--output file or -o file: save to a given file");
    eprintln!("\t--format : reformat/reindent the output");
    eprintln!("\t--encode encoding : output in the given encoding");
    eprintln!("\t--pretty STYLE : pretty-print in a particular style");
    eprintln!("\t                 0 Do not pretty print");
    eprintln!("\t                 1 Format the XML content, as --format");
    eprintln!("\t                 2 Add whitespace inside tags, preserving content");
    eprintln!("\t--compress : turn on gzip compression of output");
    eprintln!("\t--c14n : save in W3C canonical format v1.0 (with comments)");
    eprintln!("\t--c14n11 : save in W3C canonical format v1.1 (with comments)");
    eprintln!("\t--exc-c14n : save in W3C exclusive canonical format (with comments)");
    eprintln!("\t--nsclean : remove redundant namespace declarations");
    eprintln!("\t--catalogs : use SGML catalogs from $SGML_CATALOG_FILES");
    eprintln!("\t             otherwise XML Catalogs starting from ");
    eprintln!("\t         file:///etc/xml/catalog are activated by default");
    eprintln!("\t--nocatalogs: deactivate all catalogs");
    eprintln!("\t--auto : generate a small doc on the fly");
    eprintln!("\t--xinclude : do XInclude processing");
    eprintln!("\t--noxincludenode : same but do not generate XInclude nodes");
    eprintln!("\t--nofixup-base-uris : do not fixup xml:base uris");
    eprintln!("\t--loaddtd : fetch external DTD");
    eprintln!("\t--dtdattr : loaddtd + populate the tree with inherited attributes ");
    eprintln!("\t--stream : use the streaming interface to process very large files");
    eprintln!("\t--walker : create a reader and walk though the resulting doc");
    eprintln!("\t--pattern pattern_value : test the pattern support");
    eprintln!("\t--relaxng schema : do RelaxNG validation against the schema");
    eprintln!("\t--schema schema : do validation against the WXS schema");
    eprintln!("\t--schematron schema : do validation against a schematron");
    eprintln!("\t--sax1: use the old SAX1 interfaces for processing");
    eprintln!("\t--sax: do not build a tree but work just at the SAX level");
    eprintln!("\t--oldxml10: use XML-1.0 parsing rules before the 5th edition");
    eprintln!("\t--xpath expr: evaluate the XPath expression, results are separated by \\n, imply --noout");
    eprintln!("\t--xpath0 expr: evaluate the XPath expression, results are separated by \\0, imply --noout");
    eprintln!("\t--max-ampl value: set maximum amplification factor");
    eprintln!();
    eprintln!("Libxml project home page: https://gitlab.gnome.org/GNOME/libxml2");
}

/// Write bytes to stdout.
///
/// # Safety
///
/// - `bytes` must be a valid slice readable for `bytes.len()` bytes; the
///   raw `libc::write` reads it without copying and the slice must stay
///   alive for the call.
fn write_stdout(bytes: &[u8]) {
    unsafe {
        libc::write(1, bytes.as_ptr() as *const c_void, bytes.len());
    }
}

/// Get the output FILE*: a file named by --output, or stdout.
unsafe fn get_output_file(cli: &Cli) -> *mut libc::FILE {
    match &cli.output {
        Some(name) => {
            let cname = cstr_alloc(name);
            let fp = libc::fopen(cname, c"w".as_ptr() as *const c_char);
            free_cstr(cname);
            fp
        }
        None => libc::fdopen(1, c"w".as_ptr() as *const c_char),
    }
}

unsafe fn close_output_file(cli: &Cli, fp: *mut libc::FILE) {
    if cli.output.is_some() && !fp.is_null() {
        libc::fclose(fp);
    }
}

/// Print the version banner on stderr (upstream format, exit 0).
///
/// # Safety
///
/// - `xmlLibxmlVersionString` returns a static NUL-terminated library
///   string; the pointer must be valid while `CStr::from_ptr` reads it,
///   and it must not be freed by the caller.
fn print_version() {
    let argv0 = std::env::args()
        .next()
        .unwrap_or_else(|| "xmllint".to_string());
    let num = xmlLibxmlVersion();
    let dotted = unsafe {
        let s = xmlLibxmlVersionString();
        std::ffi::CStr::from_ptr(s).to_string_lossy().into_owned()
    };
    eprintln!("{}: using libxml version {}-GITv{}", argv0, num, dotted);
    eprintln!(
        "   compiled with: Threads Tree Output Push Reader Patterns Writer SAXv1 DTDValid HTML C14N Catalog XPath XPointer XInclude Iconv ICU ISO8859X Regexps Automata RelaxNG Schemas Schematron Modules Debug Zlib "
    );
}

/// Parse one document (file or stdin `-`) honoring the CLI options.
unsafe fn parse_document(cli: &Cli, filename: &str) -> *mut _xmlDoc {
    let cname = cstr_alloc(filename);
    let mut options = cli.options;
    if cli.nocompact {
        // UPSTREAM-PARITY: --nocompact clears the COMPACT bit (xmllint.c).
        options &= !XML_PARSE_COMPACT;
    }
    if cli.nonet {
        options |= XML_PARSE_NONET;
    }
    if cli.loaddtd || cli.dtdattr {
        options |= XML_PARSE_DTDLOAD;
    }
    if cli.dtdattr {
        options |= XML_PARSE_DTDATTR;
    }
    if cli.recover {
        options |= XML_PARSE_RECOVER;
    }
    if cli.noblanks {
        options |= XML_PARSE_NOBLANKS;
    }
    if cli.nocdata {
        options |= XML_PARSE_NOCDATA;
    }
    if cli.pedantic {
        options |= XML_PARSE_PEDANTIC;
    }
    if cli.oldxml10 {
        options |= XML_PARSE_OLD10;
    }
    if cli.html {
        // HTML parse path.
        let doc = if filename == "-" {
            use std::io::Read;
            let mut buf = Vec::new();
            std::io::stdin().read_to_end(&mut buf).ok();
            buf.push(0);
            libxml_rs::xml::html::parse_memory(
                buf.as_ptr() as *const c_char,
                buf.len() as c_int - 1,
            )
        } else {
            libxml_rs::xml::html::parse_file(cname as *const c_char, ptr::null(), 0)
        };
        free_cstr(cname);
        return doc;
    }
    let doc = if filename == "-" {
        xmlReadFd(0, cname as *const c_char, ptr::null(), options)
    } else {
        xmlReadFile(cname as *const c_char, ptr::null(), options)
    };
    free_cstr(cname);
    doc
}

/// Dump a document to the output stream.
unsafe fn dump_document(cli: &mut Cli, doc: *mut _xmlDoc, filename: &str) {
    if doc.is_null() {
        return;
    }
    if cli.dropdtd
        || (cli.nodefdtd
            && (*doc).type_
                == libxml_rs::abi::types::xmlElementType::XML_HTML_DOCUMENT_NODE as c_int)
    {
        // Remove the internal subset (upstream xmlDtdRemove / HTML
        // --nodefdtd suppresses the default HTML DOCTYPE). UPSTREAM-PARITY
        // (xmllint.c parseAndPrintFile): the DTD is unlinked from the
        // children chain first — it is still linked there by
        // xmlCreateIntSubset, so freeing it while linked double-frees when
        // the document is released.
        let dtd = (*doc).intSubset;
        if !dtd.is_null() {
            libxml_rs::xml::tree::unlink_node(dtd as *mut _xmlNode);
            (*doc).intSubset = ptr::null_mut();
            xmlFreeDtd(dtd);
        }
    }
    // UPSTREAM-PARITY: --encode declares the requested output encoding in the
    // XML declaration (the serializer emits encoding="..." when doc->encoding
    // is set).
    if let Some(enc) = &cli.encode {
        let old = (*doc).encoding;
        let cname = cstr_alloc(enc);
        (*doc).encoding = cname as *mut xmlChar;
        if !old.is_null() {
            libxml_rs::abi::allocator::xmlFreeImpl(old as *mut c_void);
        }
    }
    if cli.c14n != 0 {
        let mut result: *mut xmlChar = ptr::null_mut();
        // Upstream xmllint maps its three flags onto the xmlC14NMode enum:
        // --c14n -> XML_C14N_1_0 (0), --c14n11 -> XML_C14N_1_1 (2),
        // --exc-c14n -> XML_C14N_EXCLUSIVE_1_0 (1).
        let mode = match cli.c14n {
            2 => 2,
            3 => 1,
            _ => 0,
        };
        let ret = libxml_rs::xml::c14n::xmlC14NDocDumpMemory(
            doc,
            ptr::null_mut(),
            mode,
            ptr::null_mut(),
            1, // with comments
            &mut result,
        );
        // UPSTREAM-PARITY: xmlC14NDocDumpMemory returns the length of the
        // canonical form on success (>= 0); xmllint writes exactly ret bytes.
        // On failure xmllint prints "Failed to canonicalize" and exits with
        // XMLLINT_ERR_OUT (6).
        if ret >= 0 && !result.is_null() {
            write_stdout(core::slice::from_raw_parts(result, ret as usize));
        } else {
            eprintln!("Failed to canonicalize");
            cli.return_code = 6;
        }
        if !result.is_null() {
            libxml_rs::abi::allocator::xmlFreeImpl(result as *mut c_void);
        }
        return;
    }
    let format = if cli.pretty == 1 || cli.format == 1 {
        1
    } else {
        0
    };
    // UPSTREAM-PARITY: --xmlout forces the XML serializer even for HTML
    // documents (xmlSaveFormatFile with XML_SAVE_AS_XML).
    let mut restore_type = false;
    if cli.xmlout
        && (*doc).type_ == libxml_rs::abi::types::xmlElementType::XML_HTML_DOCUMENT_NODE as c_int
    {
        (*doc).type_ = libxml_rs::abi::types::xmlElementType::XML_DOCUMENT_NODE as c_int;
        restore_type = true;
    }
    let mut mem: *mut xmlChar = ptr::null_mut();
    let mut size: c_int = 0;
    xmlDocDumpFormatMemory(doc, &mut mem, &mut size, format);
    if restore_type {
        (*doc).type_ = libxml_rs::abi::types::xmlElementType::XML_HTML_DOCUMENT_NODE as c_int;
    }
    if !mem.is_null() {
        write_stdout(core::slice::from_raw_parts(mem, size as usize));
        libxml_rs::abi::allocator::xmlFreeImpl(mem as *mut c_void);
    }
    let _ = filename;
}

// Capture validity messages reported through the error callback of the
// validation context so the CLI can render them in the upstream location format.
thread_local! {
    static CAPTURED_VALIDITY: std::cell::RefCell<Vec<Vec<u8>>> =
        const { std::cell::RefCell::new(Vec::new()) };
}

/// Capture a validity message into the thread-local `CAPTURED_VALIDITY`.
///
/// # Safety
///
/// - `msg` must be NULL or a valid NUL-terminated string that stays valid
///   for the duration of the call; the message bytes are copied out, so
///   the callback does not retain the pointer.
unsafe extern "C" fn capture_validity_msg(_ctx: *mut c_void, msg: *const c_char) {
    if msg.is_null() {
        return;
    }
    let bytes = std::ffi::CStr::from_ptr(msg).to_bytes().to_vec();
    CAPTURED_VALIDITY.with(|c| c.borrow_mut().push(bytes));
}

/// Print a validity diagnostic in the upstream format:
/// `file:line: element NAME: validity error : MSG` + source line + caret.
/// The source line is re-read from the file of the document (the caret column for
/// declaration errors points past the line end, matching the oracle; the
/// no-DTD notice caret is placed after the root start tag).
unsafe fn print_validity_error(
    cli: &Cli,
    filename: &str,
    doc: *mut _xmlDoc,
    msg: &[u8],
    caret_spaces: usize,
    element_prefix: bool,
) {
    if cli.nowarning {
        return;
    }
    // Root element name and line.
    let mut root = (*doc).children;
    while !root.is_null() && (*root).type_ != 1 {
        root = (*root).next;
    }
    let (name, line) = if root.is_null() {
        (b"".to_vec(), 1usize)
    } else {
        let n = if (*root).name.is_null() {
            b"".to_vec()
        } else {
            std::ffi::CStr::from_ptr((*root).name as *const c_char)
                .to_bytes()
                .to_vec()
        };
        let ln = (*root).line as usize;
        (n, if ln == 0 { 1 } else { ln })
    };
    // Re-read the source line for context.
    let context = if filename == "-" {
        Vec::new()
    } else {
        std::fs::read_to_string(filename)
            .ok()
            .and_then(|s| s.lines().nth(line - 1).map(|l| l.as_bytes().to_vec()))
            .unwrap_or_default()
    };
    let mut out: Vec<u8> = Vec::new();
    out.extend_from_slice(filename.as_bytes());
    out.push(b':');
    out.extend_from_slice(line.to_string().as_bytes());
    out.push(b':');
    if element_prefix && !name.is_empty() {
        out.extend_from_slice(b" element ");
        out.extend_from_slice(&name);
        out.push(b':');
    }
    out.extend_from_slice(b" validity error : ");
    out.extend_from_slice(msg);
    out.push(b'\n');
    out.extend_from_slice(&context);
    out.push(b'\n');
    out.extend(std::iter::repeat_n(b' ', caret_spaces));
    out.push(b'^');
    out.push(b'\n');
    libc::write(2, out.as_ptr() as *const c_void, out.len());
}

/// Perform DTD validation of a document.
unsafe fn validate_doc(cli: &mut Cli, doc: *mut _xmlDoc, filename: &str) -> c_int {
    if cli.valid || cli.postvalid {
        let vctxt = xmlNewValidCtxt();
        if vctxt.is_null() {
            return -1;
        }
        libxml_rs::xml::validation::set_valid_errors(
            vctxt,
            Some(capture_validity_msg),
            None,
            ptr::null_mut(),
        );
        let dtd_missing = (*doc).intSubset.is_null() && (*doc).extSubset.is_null();
        let ret = xmlValidateDocument(vctxt, doc);
        let msgs: Vec<Vec<u8>> = CAPTURED_VALIDITY.with(|c| c.borrow_mut().drain(..).collect());
        if dtd_missing {
            // UPSTREAM-PARITY: xmllint displays the parser-style message
            // "Validation failed: no DTD found !" and treats the document as
            // valid (exit 0). The xmlValidateDocument API reports the
            // different message "no DTD found!" and returns 0; xmllint
            // overrides both for display. The caret sits after the root
            // start tag and there is no element prefix (the upstream notice
            // has a NULL node).
            //
            // E-006 (2.15.0): --valid without a DTD exits 0 since 2.15.0;
            // 2.13.0..2.14.1 exited 3 and <= 2.12.6 exited 4. The exit code
            // epoch, not the notice text, is what the HIST-EPOCH matrix
            // distinguishes.
            let name = root_element_name(doc);
            let caret = name.len() + 1;
            print_validity_error(
                cli,
                filename,
                doc,
                b"Validation failed: no DTD found !",
                caret,
                false,
            );
            libxml_rs::xml::validation::free_valid_ctxt(vctxt);
            return 1; // validates (notice only)
        }
        if ret != 1 {
            // Declaration/content errors: the oracle caret is past the end of
            // the source line of the element.
            let context_len = source_line_len(filename, root_element_line(doc));
            for m in &msgs {
                print_validity_error(cli, filename, doc, m, context_len, true);
            }
        }
        libxml_rs::xml::validation::free_valid_ctxt(vctxt);
        return ret;
    }
    if let Some(dtd) = &cli.dtdvalid {
        let cname = cstr_alloc(dtd);
        let dtd_doc = xmlReadFile(cname as *const c_char, ptr::null(), 0);
        free_cstr(cname);
        if dtd_doc.is_null() {
            cli.return_code = 4;
            return -1;
        }
        let vctxt = xmlNewValidCtxt();
        if vctxt.is_null() {
            return -1;
        }
        let dtd_ptr = (*dtd_doc).intSubset;
        let ret = if dtd_ptr.is_null() {
            xmlValidateDocument(vctxt, doc)
        } else {
            xmlValidateDtd(vctxt, doc, dtd_ptr)
        };
        libxml_rs::xml::validation::free_valid_ctxt(vctxt);
        libxml_rs::xml::tree::free_doc(dtd_doc);
        return ret;
    }
    0
}

unsafe fn root_element_name(doc: *mut _xmlDoc) -> Vec<u8> {
    let mut root = (*doc).children;
    while !root.is_null() && (*root).type_ != 1 {
        root = (*root).next;
    }
    if root.is_null() || (*root).name.is_null() {
        Vec::new()
    } else {
        std::ffi::CStr::from_ptr((*root).name as *const c_char)
            .to_bytes()
            .to_vec()
    }
}

unsafe fn root_element_line(doc: *mut _xmlDoc) -> usize {
    let mut root = (*doc).children;
    while !root.is_null() && (*root).type_ != 1 {
        root = (*root).next;
    }
    if root.is_null() {
        1
    } else {
        let ln = (*root).line as usize;
        if ln == 0 {
            1
        } else {
            ln
        }
    }
}

fn source_line_len(filename: &str, line: usize) -> usize {
    std::fs::read_to_string(filename)
        .ok()
        .and_then(|s| s.lines().nth(line - 1).map(|l| l.len()))
        .unwrap_or(0)
}

/// Run WXS schema validation; returns 0 on success, 6 on failure.
unsafe fn validate_schema(schema_path: &str, doc: *mut _xmlDoc) -> c_int {
    let s = cstr_alloc(schema_path);
    let pctxt = libxml_rs::xml::schemas::xmlSchemaNewParserCtxt(s as *const c_char);
    free_cstr(s);
    if pctxt.is_null() {
        return 5;
    }
    let schema = libxml_rs::xml::schemas::xmlSchemaParse(pctxt);
    if schema.is_null() {
        libxml_rs::xml::schemas::xmlSchemaFreeParserCtxt(pctxt);
        return 5;
    }
    let vctxt = libxml_rs::xml::schemas::xmlSchemaNewValidCtxt(schema);
    if vctxt.is_null() {
        libxml_rs::xml::schemas::xmlSchemaFree(schema);
        libxml_rs::xml::schemas::xmlSchemaFreeParserCtxt(pctxt);
        return 6;
    }
    let ret = libxml_rs::xml::schemas::xmlSchemaValidateDoc(vctxt, doc);
    libxml_rs::xml::schemas::xmlSchemaFreeValidCtxt(vctxt);
    libxml_rs::xml::schemas::xmlSchemaFree(schema);
    libxml_rs::xml::schemas::xmlSchemaFreeParserCtxt(pctxt);
    if ret == 0 {
        0
    } else {
        6
    }
}

/// Run RELAX NG validation; returns 0 on success, 6 on failure.
unsafe fn validate_relaxng(schema_path: &str, doc: *mut _xmlDoc) -> c_int {
    let s = cstr_alloc(schema_path);
    let pctxt = libxml_rs::xml::relaxng::xmlRelaxNGNewParserCtxt(s as *const c_char);
    free_cstr(s);
    if pctxt.is_null() {
        return 5;
    }
    let schema = libxml_rs::xml::relaxng::xmlRelaxNGParse(pctxt);
    if schema.is_null() {
        libxml_rs::xml::relaxng::xmlRelaxNGFreeParserCtxt(pctxt);
        return 5;
    }
    let vctxt = libxml_rs::xml::relaxng::xmlRelaxNGNewValidCtxt(schema);
    if vctxt.is_null() {
        libxml_rs::xml::relaxng::xmlRelaxNGFree(schema);
        libxml_rs::xml::relaxng::xmlRelaxNGFreeParserCtxt(pctxt);
        return 6;
    }
    let ret = libxml_rs::xml::relaxng::xmlRelaxNGValidateDoc(vctxt, doc);
    libxml_rs::xml::relaxng::xmlRelaxNGFreeValidCtxt(vctxt);
    libxml_rs::xml::relaxng::xmlRelaxNGFree(schema);
    libxml_rs::xml::relaxng::xmlRelaxNGFreeParserCtxt(pctxt);
    if ret == 0 {
        0
    } else {
        6
    }
}

/// Run Schematron validation; returns 0 on success, 7 on failure.
unsafe fn validate_schematron(schema_path: &str, doc: *mut _xmlDoc) -> c_int {
    let s = cstr_alloc(schema_path);
    let pctxt = libxml_rs::xml::schematron::xmlSchematronNewParserCtxt(s as *const c_char);
    free_cstr(s);
    if pctxt.is_null() {
        return 5;
    }
    let schema = libxml_rs::xml::schematron::xmlSchematronParse(pctxt);
    if schema.is_null() {
        libxml_rs::xml::schematron::xmlSchematronFreeParserCtxt(pctxt);
        return 5;
    }
    let vctxt = libxml_rs::xml::schematron::xmlSchematronNewValidCtxt(schema, 0);
    if vctxt.is_null() {
        libxml_rs::xml::schematron::xmlSchematronFree(schema);
        libxml_rs::xml::schematron::xmlSchematronFreeParserCtxt(pctxt);
        return 7;
    }
    let valid = libxml_rs::xml::schematron::xmlSchematronValidateDoc(vctxt, doc);
    libxml_rs::xml::schematron::xmlSchematronFreeValidCtxt(vctxt);
    libxml_rs::xml::schematron::xmlSchematronFree(schema);
    libxml_rs::xml::schematron::xmlSchematronFreeParserCtxt(pctxt);
    if valid == 0 {
        0
    } else {
        7
    }
}

/// Evaluate an XPath expression and print the results (separator-aware).
///
/// Returns 0 on success, 10 on XPath error, 11 on empty node-set
/// (upstream exit codes).
unsafe fn eval_xpath_expr(cli: &Cli, expr: &str, doc: *mut _xmlDoc) -> c_int {
    let e = cstr_alloc(expr);
    let ctxt = xmlXPathNewContext(doc);
    if ctxt.is_null() {
        free_cstr(e);
        return 10;
    }
    // Register the core function library (needed for count(), etc.).
    let internal = (*ctxt).extra as *mut libxml_rs::xml::xpath::context::XPathContext;
    if !internal.is_null() {
        let funcs = libxml_rs::xml::xpath::functions::core_functions();
        for (name, func) in funcs {
            (*internal).register_function(&name, func);
        }
    }
    let obj = xmlXPathEvalExpression(e as *const xmlChar, ctxt);
    free_cstr(e);
    if obj.is_null() {
        // UPSTREAM-PARITY: compile failures print
        // "XPath error : Invalid expression" + "XPath compilation failure"
        // (exit 10); evaluation failures print the engine message + "XPath
        // evaluation failure" (exit 10). The per-expression context line and
        // caret are tracked as RESIDUAL R-XPATH-ERRMSG.
        let msg = if !internal.is_null() {
            let ic = &*internal;
            ic.error
                .as_deref()
                .unwrap_or("Invalid expression")
                .to_string()
        } else {
            "Invalid expression".to_string()
        };
        eprintln!("XPath error : {}", msg);
        if msg == "Invalid expression" {
            eprintln!("XPath compilation failure");
        } else {
            eprintln!("XPath evaluation failure");
        }
        xmlXPathFreeContext(ctxt);
        return 10;
    }
    // E-001 (2.9.10, commit da35eeae): nodes in a node-set are separated
    // by newlines with a trailing newline; --xpath0 swaps in NUL. The
    // concatenated form (<= 2.9.4) would match only the pre-2.9.10 oracle
    // and is pinned by the CLI-XMLLINT xpath courts.
    let sep: u8 = if cli.xpath0 { 0 } else { b'\n' };
    let typ = (*obj).type_;
    if typ == xmlXPathObjectType::XPATH_NODESET as c_int {
        let ns = (*obj).nodesetval as *mut _xmlNodeSet;
        if ns.is_null() || (*ns).nodeNr == 0 {
            // E-003 (2.12.6, commit 387a952b): an empty node-set is an error
            // (exit 11 = XMLLINT_ERR_XPATH_EMPTY). The pre-2.11 era exited 10,
            // and 2.11.0..2.12.5 exited 0 (commit e85f9b98) — both would be
            // wrong for the current 2.15.3 oracle.
            eprintln!("XPath set is empty");
            xmlXPathFreeObject(obj);
            xmlXPathFreeContext(ctxt);
            return 11;
        }
        if !(*ns).nodeTab.is_null() {
            let mut i = 0;
            while i < (*ns).nodeNr {
                let node = *(*ns).nodeTab.offset(i as isize);
                if !node.is_null() {
                    // Serialize the node.
                    let buf = xmlBufferCreate();
                    if !buf.is_null() {
                        xmlNodeDump(buf, doc, node, 0, 0);
                        let len = xmlBufferLength(buf);
                        let content = xmlBufferContent(buf);
                        if len > 0 && !content.is_null() {
                            write_stdout(core::slice::from_raw_parts(content, len as usize));
                        }
                        xmlBufferFree(buf);
                    }
                }
                write_stdout(&[sep]);
                i += 1;
            }
        }
    } else {
        let strv = xmlXPathCastToString(obj);
        if !strv.is_null() {
            let len = libc::strlen(strv as *const c_char);
            write_stdout(core::slice::from_raw_parts(strv, len));
            write_stdout(&[sep]);
            libxml_rs::abi::allocator::xmlFreeImpl(strv as *mut c_void);
        }
    }
    xmlXPathFreeObject(obj);
    xmlXPathFreeContext(ctxt);
    0
}

/// Parse and process one XML file.
unsafe fn process_file(cli: &mut Cli, filename: &str) {
    let start = std::time::Instant::now();
    let doc = parse_document(cli, filename);
    if doc.is_null() {
        // UPSTREAM-PARITY: the cannot-open message is printed only when the source file
        // itself cannot be opened. A hard parse error already printed the
        // parser diagnostic, so no extra message appears.
        if !cli.quiet && filename != "-" && !std::path::Path::new(filename).exists() {
            eprintln!("Can't open {}", filename);
        }
        cli.return_code = 4;
        // E-005 (2.13.0): unparsable input / unopenable file exits 4
        // (XMLLINT_ERR_RDFILE); <= 2.12.6 exited 1.
        return;
    }
    let parse_time = start.elapsed();

    // UPSTREAM-PARITY: the parsed doc carries the source URL so debug dumps
    // show `URL=<filename>` and error messages reference the source.
    if !doc.is_null() && (*doc).URL.is_null() {
        let cname = cstr_alloc(filename);
        (*doc).URL = cname as *mut libxml_rs::abi::types::xmlChar;
    }

    // Strict namespace check.
    if cli.strict_namespace {
        // nsWellFormed is tracked on the parser context; the document
        // properties XML_DOC_NSVALID reflects it.
        let props = (*doc).properties;
        if (props & (1 << 1)) == 0 {
            eprintln!("{}: document has namespace errors", filename);
            cli.return_code = 4;
        }
    }

    if cli.xinclude {
        let ret = xmlXIncludeProcessFlags(doc, cli.options);
        if ret < 0 {
            cli.return_code = 4;
        }
    }

    // XPath evaluation implies --noout and prints before validation.
    if let Some(expr) = &cli.xpath {
        let ret = eval_xpath_expr(cli, expr, doc);
        if ret != 0 && cli.return_code == 0 {
            cli.return_code = ret;
        }
    }

    // Validation.
    if cli.valid || cli.postvalid || cli.dtdvalid.is_some() || cli.dtdvalidfpi.is_some() {
        let ret = validate_doc(cli, doc, filename);
        // UPSTREAM-PARITY: xmlValidateDocument returns 1 when the document
        // validates, 0 when it does not.
        // E-005 (2.13.0): DTD-validity failure exits 3 (XMLLINT_ERR_VALID),
        // reworked from exit 4 in <= 2.12.6. Combined with the parse-error
        // exit 4 above, the two codes let scripts distinguish validity from
        // well-formedness failures.
        if ret == 0 && cli.return_code == 0 {
            cli.return_code = 3;
        }
    }
    if let Some(schema) = &cli.schema {
        let ret = validate_schema(schema, doc);
        if ret != 0 && cli.return_code < ret {
            cli.return_code = ret;
        }
    }
    if let Some(schema) = &cli.relaxng {
        let ret = validate_relaxng(schema, doc);
        if ret != 0 && cli.return_code < ret {
            cli.return_code = ret;
        }
    }
    if let Some(schema) = &cli.schematron {
        let ret = validate_schematron(schema, doc);
        if ret != 0 && cli.return_code < ret {
            cli.return_code = ret;
        }
    }

    if cli.pattern.is_some() {
        // Pattern testing: compile and report (minimal surface).
        eprintln!("{}: pattern support is limited in this build", filename);
    }

    if !cli.noout && cli.xpath.is_none() {
        if cli.debug {
            // Debug tree dump.
            let fp = get_output_file(cli);
            if !fp.is_null() {
                libxml_rs::xml::debug::xmlDebugDumpDocument(fp, doc);
                close_output_file(cli, fp);
            }
        } else if cli.copy {
            // Internal copy test: copy the doc and dump the copy.
            let copy = libxml_rs::xml::tree::copy_doc(doc, 1);
            if !copy.is_null() {
                dump_document(cli, copy, filename);
                libxml_rs::xml::tree::free_doc(copy);
            }
        } else {
            dump_document(cli, doc, filename);
        }
    }

    if cli.timing {
        let total = start.elapsed();
        eprintln!(
            "Parsing {} took {} ms, total {} ms",
            filename,
            parse_time.as_millis(),
            total.as_millis()
        );
    }

    libxml_rs::xml::tree::free_doc(doc);
}

/// Minimal interactive shell (upstream xmllint shell has many commands; the
/// core navigation commands are implemented).
unsafe fn shell_loop(_cli: &Cli, doc: *mut _xmlDoc) {
    use std::io::Write;
    let mut current: *mut _xmlNode = if doc.is_null() {
        ptr::null_mut()
    } else {
        (*doc).children
    };
    loop {
        print!("/ > ");
        std::io::stdout().flush().ok();
        let mut line = String::new();
        if std::io::stdin().read_line(&mut line).unwrap_or(0) == 0 {
            break;
        }
        let cmd = line.trim().to_string();
        if cmd.is_empty() {
            continue;
        }
        let mut parts = cmd.split_whitespace();
        let verb = parts.next().unwrap_or("");
        match verb {
            "quit" | "exit" | "bye" | "q" => break,
            "pwd" => {
                println!("/");
            }
            "ls" => {
                let mut child = if current.is_null() {
                    ptr::null_mut()
                } else {
                    (*current).children
                };
                while !child.is_null() {
                    let name = (*child).name;
                    if !name.is_null() {
                        println!(
                            "{}",
                            std::ffi::CStr::from_ptr(name as *const c_char).to_string_lossy()
                        );
                    }
                    child = (*child).next;
                }
            }
            "cd" => {
                let arg = parts.next().unwrap_or(".");
                if arg == ".." {
                    if !current.is_null() && !(*current).parent.is_null() {
                        current = (*current).parent;
                    }
                } else if arg == "/" || arg == "root" {
                    current = (*doc).children;
                } else {
                    let mut child = if current.is_null() {
                        ptr::null_mut()
                    } else {
                        (*current).children
                    };
                    while !child.is_null() {
                        let name = (*child).name;
                        if !name.is_null()
                            && std::ffi::CStr::from_ptr(name as *const c_char).to_string_lossy()
                                == arg
                        {
                            current = child;
                            break;
                        }
                        child = (*child).next;
                    }
                }
            }
            "dir" => {
                if !current.is_null() {
                    let fp = libc::fdopen(1, c"w".as_ptr() as *const c_char);
                    if !fp.is_null() {
                        libxml_rs::xml::debug::xmlDebugDumpNode(fp, current, 0);
                    }
                }
            }
            "print" => {
                if !current.is_null() {
                    let buf = xmlBufferCreate();
                    if !buf.is_null() {
                        xmlNodeDump(buf, doc, current, 0, 1);
                        let len = xmlBufferLength(buf);
                        let content = xmlBufferContent(buf);
                        if len > 0 && !content.is_null() {
                            write_stdout(core::slice::from_raw_parts(content, len as usize));
                        }
                        write_stdout(b"\n");
                        xmlBufferFree(buf);
                    }
                }
            }
            "help" | "?" => {
                println!("Commands: pwd, ls, cd, dir, print, quit");
            }
            _ => {
                println!("Unknown command {}", verb);
            }
        }
    }
}

/// Generate a small document on the fly (--auto).
unsafe fn make_auto_doc() -> *mut _xmlDoc {
    let src = b"<?xml version=\"1.0\"?>\n<doc><a>1</a><b>2</b><c>3</c></doc>\n\0";
    xmlReadMemory(
        src.as_ptr() as *const c_char,
        (src.len() - 1) as c_int,
        c"auto.xml".as_ptr() as *const c_char,
        ptr::null(),
        0,
    )
}

unsafe fn cstr_alloc(s: &str) -> *mut c_char {
    let bytes = s.as_bytes();
    let p = libc::malloc(bytes.len() + 1) as *mut c_char;
    if p.is_null() {
        return p;
    }
    libc::memcpy(
        p as *mut libc::c_void,
        bytes.as_ptr() as *const libc::c_void,
        bytes.len(),
    );
    *p.add(bytes.len()) = 0;
    p
}

unsafe fn free_cstr(p: *mut c_char) {
    if !p.is_null() {
        libc::free(p as *mut libc::c_void);
    }
}

/// Parse and process the files named on the command line, then exit.
///
/// # Safety
///
/// - The documents returned by `parse_document` are NULL or owned by the
///   caller and freed with `tree::free_doc` exactly once per path;
///   `make_auto_doc` owns its document the same way; every pointer passed
///   to the exported C API is a valid, static or allocator-owned buffer
///   valid for the call; the process exits before any returned pointer is
///   used afterwards.
fn main() {
    let args: Vec<String> = std::env::args().skip(1).collect();
    let mut cli = Cli::default();

    if args.is_empty() {
        // UPSTREAM-PARITY: xmllint.c `if (argc <= 1)` prints usage and
        // returns XMLLINT_ERR_UNCLASS (exit 1).
        usage();
        std::process::exit(1);
    }

    let mut files: Vec<String> = Vec::new();
    let mut i = 0;
    while i < args.len() {
        let arg = args[i].as_str();
        let mut need_value: Option<&str> = None;
        match arg {
            "--version" | "-version" => {
                print_version();
                std::process::exit(0);
            }
            "--shell" => cli.shell = true,
            "--debug" => cli.debug = true,
            "--copy" => cli.copy = true,
            "--recover" => cli.recover = true,
            "--huge" => cli.options |= XML_PARSE_HUGE,
            "--noent" => cli.options |= XML_PARSE_NOENT,
            "--noenc" => cli.options |= XML_PARSE_IGNORE_ENC,
            "--noout" => cli.noout = true,
            "--load-trace" => cli.loadtrace = true,
            "--nonet" => cli.nonet = true,
            "--nocompact" => cli.nocompact = true,
            "--valid" => cli.valid = true,
            "--postvalid" => cli.postvalid = true,
            "--insert" => cli.insert = true,
            "--strict-namespace" => cli.strict_namespace = true,
            "--quiet" => cli.quiet = true,
            "--timing" => cli.timing = true,
            "--repeat" => cli.repeat = true,
            "--dropdtd" => cli.dropdtd = true,
            "--html" => cli.html = true,
            "--nodefdtd" => cli.nodefdtd = true,
            "--xmlout" => cli.xmlout = true,
            "--push" => cli.push = true,
            "--memory" => cli.memory = true,
            "--nowarning" => cli.nowarning = true,
            "--noblanks" => cli.noblanks = true,
            "--nocdata" => cli.nocdata = true,
            "--nodict" => cli.nodict = true,
            "--pedantic" => cli.pedantic = true,
            "--nsclean" => cli.nsclean = true,
            "--auto" => cli.auto = true,
            "--xinclude" => cli.xinclude = true,
            "--noxincludenode" => cli.noxincludenode = true,
            "--nofixup-base-uris" => cli.nofixup_base_uris = true,
            "--catalogs" => cli.catalogs = true,
            "--nocatalogs" => cli.nocatalogs = true,
            "--stream" => cli.stream = true,
            "--walker" => cli.walker = true,
            "--sax1" => cli.sax1 = true,
            "--sax" => cli.sax = true,
            "--oldxml10" => cli.oldxml10 = true,
            "--format" => cli.format = 1,
            "--compress" => cli.compress = true,
            "--c14n" => cli.c14n = 1,
            "--c14n11" => cli.c14n = 2,
            "--exc-c14n" => cli.c14n = 3,
            "--xpath0" => {
                cli.xpath0 = true;
                cli.noout = true;
                need_value = Some("--xpath0");
            }
            "--xpath" => {
                cli.noout = true;
                need_value = Some("--xpath");
            }
            "--path" => need_value = Some("--path"),
            "--dtdvalid" => need_value = Some("--dtdvalid"),
            "--dtdvalidfpi" => need_value = Some("--dtdvalidfpi"),
            "--maxmem" => need_value = Some("--maxmem"),
            "--max-ampl" => need_value = Some("--max-ampl"),
            "--output" | "-o" => need_value = Some("--output"),
            "--encode" => need_value = Some("--encode"),
            "--pretty" => need_value = Some("--pretty"),
            "--pattern" => need_value = Some("--pattern"),
            "--relaxng" => need_value = Some("--relaxng"),
            "--schema" => need_value = Some("--schema"),
            "--schematron" => need_value = Some("--schematron"),
            "--loaddtd" => cli.loaddtd = true,
            "--dtdattr" => {
                cli.dtdattr = true;
                cli.loaddtd = true;
            }
            _ => {
                if arg.starts_with('-') && arg.len() > 1 {
                    // Unknown option (upstream prints a message + usage to
                    // stderr and exits 1).
                    eprintln!("Unknown option {}", arg);
                    usage();
                    std::process::exit(1);
                } else {
                    files.push(arg.to_string());
                }
            }
        }
        if let Some(opt) = need_value {
            if i + 1 < args.len() {
                let val = args[i + 1].clone();
                match opt {
                    "--xpath" | "--xpath0" => cli.xpath = Some(val),
                    "--path" => {
                        for p in val.split(':') {
                            cli.paths.push(p.to_string());
                        }
                    }
                    "--dtdvalid" => cli.dtdvalid = Some(val),
                    "--dtdvalidfpi" => cli.dtdvalidfpi = Some(val),
                    "--maxmem" => {
                        cli.maxmem = val.parse().ok();
                    }
                    "--max-ampl" => {
                        cli.max_ampl = val.parse().ok();
                    }
                    "--output" => cli.output = Some(val),
                    "--encode" => cli.encode = Some(val),
                    "--pretty" => {
                        cli.pretty = val.parse().unwrap_or(-1);
                    }
                    "--pattern" => cli.pattern = Some(val),
                    "--relaxng" => cli.relaxng = Some(val),
                    "--schema" => cli.schema = Some(val),
                    "--schematron" => cli.schematron = Some(val),
                    _ => {}
                }
                i += 1;
            }
        }
        i += 1;
    }

    unsafe {
        // UPSTREAM-PARITY: --xmlout without --html is a warning; processing
        // continues normally.
        if cli.xmlout && !cli.html {
            eprintln!("Warning: Option --xmlout requires --html");
        }
        if cli.auto {
            // Generate a small doc and process it.
            let doc = make_auto_doc();
            if !doc.is_null() {
                dump_document(&mut cli, doc, "auto");
                libxml_rs::xml::tree::free_doc(doc);
            }
            std::process::exit(cli.return_code);
        }
        if files.is_empty() {
            usage();
            std::process::exit(1);
        }
        for f in &files {
            if cli.repeat {
                for _ in 0..100 {
                    let doc = parse_document(&cli, f);
                    if !doc.is_null() {
                        libxml_rs::xml::tree::free_doc(doc);
                    }
                }
            }
            if cli.shell {
                let doc = parse_document(&cli, f);
                shell_loop(&cli, doc);
                if !doc.is_null() {
                    libxml_rs::xml::tree::free_doc(doc);
                }
                continue;
            }
            process_file(&mut cli, f);
        }
        std::process::exit(cli.return_code);
    }
}