libxml_rs/abi/exports_parser.rs
1//! exports_parser — C ABI exports for the XML parser family (§11.1-I).
2//!
3//! Implements the parser/parserInternals/xmlIO/encoding/tree export surface:
4//! parser-context creation and lifecycle, the `xmlCtxtRead*` family, parser
5//! input buffers and streams, encoding switches, the deprecated node-info
6//! sequence, global I/O callback registration, external-entity loaders, the
7//! `xmlFile*` I/O callbacks, low-level character scanning helpers and the
8//! SAX/DTD parse front-ends.
9//!
10//! Where an internal engine entry point exists (e.g. `crate::xml::parser::helpers`),
11//! the export wraps it; otherwise the function is ported from upstream
12//! `parser.c` / `parserInternals.c` / `xmlIO.c` / `error.c` / `encoding.c`
13//! (see `archaeology/libxml2-git`).
14//!
15//! # Upstream contract
16//!
17//! Parity target is upstream `parser.c`, `parserInternals.c`, `xmlIO.c`,
18//! `error.c` and `encoding.c` (libxml2 2.15.3) with the `parser.h`/
19//! `parserInternals.h`/`xmlIO.h` signatures. Residuals R-000164 (parser/tree
20//! structural parity), R-000165 (parser-context accessors and input
21//! constructors) and R-000169 (input filename ownership) all land here.
22//!
23//! # Conceptual behavior
24//!
25//! This module implements the parser export surface: parser-context
26//! creation/lifecycle, the `xmlCtxtRead*`/`xmlRead*` families, parser input
27//! buffers and streams, encoding switches, the deprecated node-info sequence,
28//! global I/O callback registration, external-entity loaders, the `xmlFile*`
29//! I/O callbacks and the SAX/DTD parse front-ends. Internal engine entry
30//! points are wrapped; the rest are ported from the upstream sources.
31//!
32//! # Ownership & safety invariants
33//!
34//! Parser contexts are caller-owned (freed with `xmlFreeParserCtxt`); docs
35//! returned by `xmlRead*` are caller-owned (freed with `xmlFreeDoc`); inputs
36//! created by `xmlNewInputFrom*` are owned by the context once pushed.
37//! Filenames stored in `_xmlParserInput.filename` and `doc->URL` are owned
38//! copies — R-000169 fixed xml_strndup on non-NUL-terminated Rust Strings
39//! (heap-buffer-overflow) and borrowed filename pointers.
40//!
41//! # Historical quirks & epochs
42//!
43//! QUIRK-0001/LORE-0001: since 2.9.0 (commit `52d8ade7`, 2012-07-30) default
44//! parser limits apply unless `XML_PARSE_HUGE` is set. E-002: parse-error
45//! diagnostics changed across 2.9.10 (non-recursive parser refactor) and
46//! 2.12.x (error-handling rework); E-005: exit codes reworked in 2.13.0.
47//! R-000164 (11.1-N) aligned the parse-time DOM construction with upstream
48//! (TREE-001 byte-identical).
49//!
50//! # Deliberate oddities
51//!
52//! The deprecated `xmlParse*` no-ops and the `xmlFileMatch`/
53//! `xmlParserInputRead` trivial bodies are deliberate (R-000138 set:
54//! upstreams own bodies are empty/trivial). `xmlReadMemory` accepts size-0
55//! input (R-000163) and applies options/URL on both success and recovery
56//! paths (R-000164).
57//!
58//! # Proving courts
59//!
60//! The PARSER court family, the ERROR-001 probe (error-family-probe.c, 48/48
61//! byte-identical), the TREE-001 structural probe and the DSO-LOADER/
62//! HEADER-COMPILE courts cover this module; the parser unit suite runs under
63//! cargo test.
64//!
65//! # Tempting simplifications that would break parity
66//!
67//! A tempting simplification is to store the input filename as a borrowed
68//! pointer into a Rust String — R-000169 proved that produces dangling
69//! `filename`/`doc->URL` pointers and heap-reuse garbage on the second parse;
70//! every construction path must own its filename copy. Another shortcut,
71//! skipping the `XML_PARSE_HUGE`/limits logic, would diverge from the 2.9.0+
72//! oracle on large documents (PARSER-LIMIT courts).
73
74#![allow(missing_docs)]
75#![allow(non_snake_case)]
76#![allow(non_camel_case_types)]
77#![allow(non_upper_case_globals)]
78
79// SAFETY-SCOPE: EXPORT-PARSER-MECHANICAL-001
80// (11.1-Z.3 proof scope, classified-generated) — this module is the
81// mechanical extern-"C" export surface: every `unsafe` block in it is
82// the documented indirection/registry-access pattern whose validity
83// rests on the upstream C contract, and the exported signatures are
84// machine-measured by the ABI-FUNCTION-SIGNATURE and DSO-LOADER
85// courts and the C-API differential probes. The safety contract of
86// each export is stated in its own doc comment; this scope covers the
87// mechanical wrappers' unsafe blocks.
88
89use core::ffi::CStr;
90use core::ptr;
91use std::os::raw::{c_char, c_int, c_long, c_uchar, c_uint, c_ulong, c_void};
92
93use parking_lot::Mutex;
94
95use crate::abi::allocator::{
96 xmlFreeImpl, xmlMallocImpl, xmlMallocZero, xmlMemStrdupImpl, xmlReallocImpl,
97};
98use crate::abi::callbacks::{
99 xmlGenericErrorFunc, xmlInputCloseCallback, xmlInputReadCallback, xmlOutputCloseCallback,
100 xmlOutputWriteCallback, xmlStructuredErrorFunc,
101};
102use crate::abi::structs::*;
103use crate::abi::types::*;
104use crate::xml::parser::helpers;
105use crate::xml::parser::input::InputBuffer;
106use crate::xml::{dtd, encoding, entities, errors, globals, io, string, tree};
107
108// ═══════════════════════════════════════════════════════════════════════════════
109// Local ABI types (upstream xmlIO.h / parser.h, not present in callbacks.rs)
110// ═══════════════════════════════════════════════════════════════════════════════
111
112/// `xmlInputMatchCallback` — decide whether a filename is handled by the
113/// registered input callback pair.
114type xmlInputMatchCallback = unsafe extern "C" fn(filename: *const c_char) -> c_int;
115
116/// `xmlInputOpenCallback` — open a resource and return an I/O context.
117type xmlInputOpenCallback = unsafe extern "C" fn(filename: *const c_char) -> *mut c_void;
118
119/// `xmlOutputMatchCallback` — decide whether a filename is handled by the
120/// registered output callback pair.
121type xmlOutputMatchCallback = unsafe extern "C" fn(filename: *const c_char) -> c_int;
122
123/// `xmlOutputOpenCallback` — open a resource for writing and return a context.
124type xmlOutputOpenCallback = unsafe extern "C" fn(filename: *const c_char) -> *mut c_void;
125
126/// `xmlExternalEntityLoader` — resolve an external entity to a parser input.
127type xmlExternalEntityLoader = unsafe extern "C" fn(
128 URL: *const c_char,
129 ID: *const c_char,
130 ctxt: *mut _xmlParserCtxt,
131) -> *mut _xmlParserInput;
132
133#[derive(Clone, Copy)]
134struct InputCallbackEntry {
135 matchcb: Option<xmlInputMatchCallback>,
136 opencb: Option<xmlInputOpenCallback>,
137 readcb: Option<xmlInputReadCallback>,
138 closecb: Option<xmlInputCloseCallback>,
139}
140
141#[allow(dead_code)]
142#[derive(Clone, Copy)]
143struct OutputCallbackEntry {
144 matchcb: Option<xmlOutputMatchCallback>,
145 opencb: Option<xmlOutputOpenCallback>,
146 writecb: Option<xmlOutputWriteCallback>,
147 closecb: Option<xmlOutputCloseCallback>,
148}
149
150static INPUT_CALLBACKS: Mutex<Vec<InputCallbackEntry>> = Mutex::new(Vec::new());
151static OUTPUT_CALLBACKS: Mutex<Vec<OutputCallbackEntry>> = Mutex::new(Vec::new());
152
153static EXTERNAL_ENTITY_LOADER: Mutex<Option<xmlExternalEntityLoader>> =
154 Mutex::new(Some(default_external_entity_loader));
155
156// Deprecated legacy function codes not present in types.rs (upstream xmlerror.h).
157const XML_ERR_USER_STOP: c_int = 111;
158#[allow(dead_code)]
159const XML_ERR_RESOURCE_LIMIT: c_int = 114;
160
161// XML_SCAN_* flags (upstream include/private/parser.h).
162const XML_SCAN_NC: c_int = 1;
163const XML_SCAN_NMTOKEN: c_int = 2;
164const XML_SCAN_OLD10: c_int = 4;
165
166// xmlParserLoadSubset bits (upstream parser.h).
167#[allow(dead_code)]
168const XML_DETECT_IDS: c_int = 1 << 0;
169const XML_COMPLETE_ATTRS: c_int = 1 << 1;
170
171/// Keep enough input around to show errors in context (parserInternals.c).
172const LINE_LEN: usize = 80;
173
174/// Minimal amount of data the parser expects in the buffer (parserInternals.c).
175#[allow(dead_code)]
176const INPUT_CHUNK: usize = 100;
177
178const XML_INVALID_CHAR: c_int = -1;
179
180// ═══════════════════════════════════════════════════════════════════════════════
181// Internal helpers
182// ═══════════════════════════════════════════════════════════════════════════════
183
184/// Shared context initialisation: zeroes `ctxt`, installs the SAX handler and
185/// sets the initial parser state (upstream `xmlInitSAXParserCtxt`).
186///
187/// # Safety
188///
189/// `ctxt` must be a valid, writable, freshly allocated parser context.
190unsafe fn init_sax_parser_ctxt(
191 ctxt: *mut _xmlParserCtxt,
192 sax: *const _xmlSAXHandler,
193 userData: *mut c_void,
194) -> c_int {
195 unsafe {
196 ptr::write_bytes(ctxt as *mut u8, 0, core::mem::size_of::<_xmlParserCtxt>());
197
198 let c = &mut *ctxt;
199
200 // SAX handler.
201 if c.sax.is_null() {
202 let new_sax =
203 xmlMallocZero(core::mem::size_of::<_xmlSAXHandler>()) as *mut _xmlSAXHandler;
204 if new_sax.is_null() {
205 return -1;
206 }
207 c.sax = new_sax;
208 }
209 if sax.is_null() {
210 crate::xml::sax::xmlSAX2InitDefaultSAXHandler(c.sax);
211 c.userData = ctxt as *mut c_void;
212 } else if (*sax).initialized == XML_SAX2_MAGIC as c_uint {
213 // Full SAX2 handler copy.
214 ptr::copy_nonoverlapping(sax, c.sax, 1);
215 c.userData = if userData.is_null() {
216 ctxt as *mut c_void
217 } else {
218 userData
219 };
220 } else {
221 // SAX1 handler: only the V1 prefix is meaningful.
222 ptr::write_bytes(c.sax as *mut u8, 0, core::mem::size_of::<_xmlSAXHandler>());
223 ptr::copy_nonoverlapping(
224 sax as *const u8,
225 c.sax as *mut u8,
226 core::mem::size_of::<_xmlSAXHandlerV1>(),
227 );
228 c.userData = if userData.is_null() {
229 ctxt as *mut c_void
230 } else {
231 userData
232 };
233 }
234
235 c.wellFormed = 1;
236 c.standalone = -1;
237 c.errNo = XML_ERR_OK;
238 c.valid = 1;
239 c.nsWellFormed = 1;
240 c.instate = xmlParserInputState::XML_PARSER_START as c_int;
241 c.keepBlanks = globals::get_keep_blanks_default();
242 c.replaceEntities = globals::get_substitute_entities_default();
243 c.linenumbers = 1;
244 c.charset = xmlCharEncoding::XML_CHAR_ENCODING_UTF8 as c_int;
245 c.pedantic = globals::get_pedantic_parser_default();
246 c.loadsubset = globals::get_load_ext_dtd_default();
247 c.docdict = 1;
248 c.options = 0;
249
250 c.vctxt.userData = ctxt as *mut c_void;
251 c.vctxt.valid = 1;
252 }
253 0
254}
255
256/// Mirror `options` into the parser context's historical struct members
257/// (upstream `xmlCtxtSetOptionsInternal`).
258///
259/// # Safety
260///
261/// `ctxt` must be a valid, writable parser context.
262pub(crate) unsafe fn apply_options(ctxt: *mut _xmlParserCtxt, options: c_int) {
263 unsafe {
264 let c = &mut *ctxt;
265 c.options = options;
266 c.recovery = (options & XML_PARSE_RECOVER != 0) as c_int;
267 c.replaceEntities = (options & XML_PARSE_NOENT != 0) as c_int;
268 c.loadsubset = ((options & XML_PARSE_DTDLOAD != 0) as c_int)
269 | if options & XML_PARSE_DTDATTR != 0 {
270 XML_COMPLETE_ATTRS
271 } else {
272 0
273 };
274 c.validate = (options & XML_PARSE_DTDVALID != 0) as c_int;
275 c.pedantic = (options & XML_PARSE_PEDANTIC != 0) as c_int;
276 c.keepBlanks = if options & XML_PARSE_NOBLANKS != 0 {
277 0
278 } else {
279 1
280 };
281 c.dictNames = if options & XML_PARSE_NODICT != 0 {
282 0
283 } else {
284 1
285 };
286 }
287}
288
289/// Find the registered encoding handler for an `xmlCharEncoding` value, or NULL.
290unsafe fn encoding_handler_for(enc: c_int) -> *mut _xmlCharEncodingHandler {
291 let e: xmlCharEncoding = unsafe { core::mem::transmute(enc) };
292 match encoding::encoding_name(e) {
293 Some(name) => {
294 let mut nul = name.to_vec();
295 nul.push(0);
296 encoding::find_encoding_handler(nul.as_ptr() as *const xmlChar)
297 }
298 None => ptr::null_mut(),
299 }
300}
301
302/// Build a `_xmlParserInput` that references the data owned by `buf` (an input
303/// buffer previously created by the xmlIO layer). The buffer keeps the data
304/// alive; the returned input must be freed with `helpers::free_parser_input`.
305///
306/// # Safety
307///
308/// `buf` must be a valid input buffer or NULL, and must outlive the returned
309/// input.
310unsafe fn parser_input_from_buf(buf: *mut _xmlParserInputBuffer) -> *mut _xmlParserInput {
311 let input =
312 unsafe { xmlMallocZero(core::mem::size_of::<_xmlParserInput>()) } as *mut _xmlParserInput;
313 if input.is_null() {
314 return ptr::null_mut();
315 }
316 unsafe {
317 (*input).buf = buf;
318 (*input).line = 1;
319 (*input).col = 1;
320 if !buf.is_null() {
321 let b = &*buf;
322 if !b.buffer.is_null() {
323 let xbuf = &*(b.buffer as *mut _xmlBuffer);
324 if !xbuf.content.is_null() {
325 (*input).base = xbuf.content;
326 (*input).cur = xbuf.content;
327 (*input).end = xbuf.content.add(xbuf.use_ as usize);
328 (*input).length = xbuf.use_ as c_int;
329 }
330 }
331 }
332 }
333 input
334}
335
336/// `pub(crate)` wrapper of [`parser_input_from_buf`] for the sibling
337/// xmlNewInputFrom* family (11.1-X R-000165 closure).
338pub(crate) unsafe fn parser_input_from_buf_pub(
339 buf: *mut _xmlParserInputBuffer,
340) -> *mut _xmlParserInput {
341 unsafe { parser_input_from_buf(buf) }
342}
343
344/// Materialise an `InputBuffer` (owned copy) from a raw `_xmlParserInput`,
345/// so the data survives the caller's input lifetime.
346///
347/// # Safety
348///
349/// `input` must be a valid pointer to a `_xmlParserInput`.
350unsafe fn input_buffer_from_parser_input(input: *mut _xmlParserInput) -> InputBuffer {
351 unsafe {
352 let pi = &*input;
353 if !pi.buf.is_null() {
354 let b = &*pi.buf;
355 if let Some(read) = b.readcallback {
356 return helpers::input_from_io(Some(read), b.closecallback, b.context);
357 }
358 }
359 if !pi.base.is_null() && !pi.end.is_null() && pi.end >= pi.base {
360 let len = (pi.end as usize).saturating_sub(pi.base as usize);
361 let slice = core::slice::from_raw_parts(pi.base, len);
362 return InputBuffer::from_memory(slice, None);
363 }
364 InputBuffer::from_memory(&[], None)
365 }
366}
367
368/// Core of `xmlCtxtRead*`: reset the context, wire an input buffer, parse,
369/// and return the resulting document (freed on hard error unless recovery).
370///
371/// # Safety
372///
373/// `ctxt` must be a valid parser context; `input` is consumed.
374unsafe fn ctxt_read_doc(
375 ctxt: *mut _xmlParserCtxt,
376 input: InputBuffer,
377 url: *const c_char,
378 options: c_int,
379) -> *mut _xmlDoc {
380 unsafe {
381 xmlCtxtReset(ctxt);
382 apply_options(ctxt, options);
383 helpers::setup_parser_input(ctxt, input);
384 if helpers::parse_document(ctxt) != 0 {
385 let doc = (*ctxt).myDoc;
386 (*ctxt).myDoc = ptr::null_mut();
387 if options & XML_PARSE_RECOVER != 0 {
388 return doc;
389 }
390 if !doc.is_null() {
391 tree::free_doc(doc);
392 }
393 return ptr::null_mut();
394 }
395 let doc = (*ctxt).myDoc;
396 if !doc.is_null() && !url.is_null() {
397 (*doc).URL = string::xml_strdup(url as *const xmlChar);
398 }
399 doc
400 }
401}
402
403/// Parse DTD declaration text using the internal engine by wrapping it in a
404/// synthetic document (`<!DOCTYPE none [ ... ]><none/>`) when the text is a
405/// bare DTD subset, or parsing it directly when it is already a document.
406///
407/// Returns a detached DTD (never owned by a document), or NULL.
408///
409/// # Safety
410///
411/// `ctxt` must be a valid parser context; `data` must be readable for `len`
412/// bytes.
413unsafe fn parse_dtd_text(
414 ctxt: *mut _xmlParserCtxt,
415 data: &[u8],
416 public_id: *const xmlChar,
417 system_id: *const xmlChar,
418) -> *mut _xmlDtd {
419 unsafe {
420 // If the content is already a full document (contains a DOCTYPE),
421 // parse it directly; otherwise wrap the declarations.
422 let has_doctype = data
423 .windows(9)
424 .any(|w| w.eq_ignore_ascii_case(b"<!DOCTYPE"));
425 let mut wrapped: Vec<u8>;
426 let parse_data: &[u8] = if has_doctype {
427 data
428 } else {
429 wrapped = Vec::with_capacity(data.len() + 32);
430 wrapped.extend_from_slice(b"<!DOCTYPE none [");
431 wrapped.extend_from_slice(data);
432 wrapped.extend_from_slice(b"]><none/>");
433 &wrapped
434 };
435
436 let input = InputBuffer::from_memory(parse_data, None);
437 helpers::setup_parser_input(ctxt, input);
438 let rc = helpers::parse_document(ctxt);
439 let doc = (*ctxt).myDoc;
440 (*ctxt).myDoc = ptr::null_mut();
441
442 if rc == 0 && !doc.is_null() && !(*doc).intSubset.is_null() {
443 let dtd = (*doc).intSubset;
444 (*doc).intSubset = ptr::null_mut();
445 (*dtd).parent = ptr::null_mut();
446 (*dtd).doc = ptr::null_mut();
447 if !public_id.is_null() {
448 (*dtd).ExternalID = string::xml_strdup(public_id);
449 }
450 if !system_id.is_null() {
451 (*dtd).SystemID = string::xml_strdup(system_id);
452 }
453 tree::free_doc(doc);
454 return dtd;
455 }
456
457 if !doc.is_null() {
458 tree::free_doc(doc);
459 }
460 // Fallback: an empty DTD carrying the identifiers.
461
462 dtd::new_dtd(
463 ptr::null_mut(),
464 c"none".as_ptr() as *const xmlChar,
465 public_id,
466 system_id,
467 )
468 }
469}
470
471// ═══════════════════════════════════════════════════════════════════════════════
472// Context creation / lifecycle
473// ═══════════════════════════════════════════════════════════════════════════════
474
475/// Create a new parser context with a default SAX2 handler.
476///
477/// # UPSTREAM-PARITY
478///
479/// ```c
480/// xmlParserCtxtPtr xmlNewParserCtxt(void);
481/// ```
482///
483/// # SAFETY
484///
485/// The function touches crate-global state only; it is safe
486/// as long as the caller respects the library's global
487/// initialization/cleanup ordering (xmlInitParser before use,
488/// xmlCleanupParser only after all users are done).
489///
490/// Violating the global lifecycle ordering, or calling this after
491/// teardown or from a signal handler, is undefined behavior.
492#[no_mangle]
493pub unsafe extern "C" fn xmlNewParserCtxt() -> *mut _xmlParserCtxt {
494 unsafe {
495 globals::init_parser();
496 let ctxt = xmlMallocZero(core::mem::size_of::<_xmlParserCtxt>()) as *mut _xmlParserCtxt;
497 if ctxt.is_null() {
498 return ptr::null_mut();
499 }
500 if init_sax_parser_ctxt(ctxt, ptr::null(), ptr::null_mut()) < 0 {
501 helpers::free_parser_ctxt(ctxt);
502 return ptr::null_mut();
503 }
504 ctxt
505 }
506}
507
508/// Create a new parser context using the given SAX handler (or the default
509/// SAX2 handler when `sax` is NULL).
510///
511/// # UPSTREAM-PARITY
512///
513/// ```c
514/// xmlParserCtxtPtr xmlNewSAXParserCtxt(const xmlSAXHandler *sax, void *userData);
515/// ```
516///
517/// # SAFETY
518///
519/// - `sax`, `userData` must be valid pointers (or NULL
520/// where the upstream C contract allows), obtained from the
521/// matching constructor/owner and not yet freed; the callee may
522/// take or keep ownership exactly as the C API specifies.
523///
524/// The caller must not race this call with concurrent mutation of the
525/// same objects from other threads (per-object state is not internally
526/// synchronized). Violating any of the above is undefined behavior.
527///
528/// Exercised by the C-API differential courts
529/// (courts/suites/data-abi/*-family-probe.c) and the CLI differential
530/// courts; those pass byte-for-byte against the upstream oracle.
531#[no_mangle]
532pub unsafe extern "C" fn xmlNewSAXParserCtxt(
533 sax: *const _xmlSAXHandler,
534 userData: *mut c_void,
535) -> *mut _xmlParserCtxt {
536 unsafe {
537 globals::init_parser();
538 let ctxt = xmlMallocZero(core::mem::size_of::<_xmlParserCtxt>()) as *mut _xmlParserCtxt;
539 if ctxt.is_null() {
540 return ptr::null_mut();
541 }
542 if init_sax_parser_ctxt(ctxt, sax, userData) < 0 {
543 helpers::free_parser_ctxt(ctxt);
544 return ptr::null_mut();
545 }
546 ctxt
547 }
548}
549
550/// Initialise a parser context (legacy API): zeroes the context, installs a
551/// default SAX2 handler and sets the initial parser state.
552///
553/// # UPSTREAM-PARITY
554///
555/// ```c
556/// int xmlInitParserCtxt(xmlParserCtxtPtr ctxt);
557/// ```
558///
559/// # SAFETY
560///
561/// - `ctxt` must be valid pointers (or NULL
562/// where the upstream C contract allows), obtained from the
563/// matching constructor/owner and not yet freed; the callee may
564/// take or keep ownership exactly as the C API specifies.
565///
566/// The caller must not race this call with concurrent mutation of the
567/// same objects from other threads (per-object state is not internally
568/// synchronized). Violating any of the above is undefined behavior.
569///
570/// Exercised by the C-API differential courts
571/// (courts/suites/data-abi/*-family-probe.c) and the CLI differential
572/// courts; those pass byte-for-byte against the upstream oracle.
573#[no_mangle]
574pub unsafe extern "C" fn xmlInitParserCtxt(ctxt: *mut _xmlParserCtxt) -> c_int {
575 unsafe { init_sax_parser_ctxt(ctxt, ptr::null(), ptr::null_mut()) }
576}
577
578/// Clear (reset) a parser context.
579///
580/// # UPSTREAM-PARITY
581///
582/// ```c
583/// void xmlClearParserCtxt(xmlParserCtxtPtr ctxt);
584/// ```
585///
586/// # SAFETY
587///
588/// - `ctxt` must be valid pointers (or NULL
589/// where the upstream C contract allows), obtained from the
590/// matching constructor/owner and not yet freed; the callee may
591/// take or keep ownership exactly as the C API specifies.
592///
593/// The caller must not race this call with concurrent mutation of the
594/// same objects from other threads (per-object state is not internally
595/// synchronized). Violating any of the above is undefined behavior.
596///
597/// Exercised by the C-API differential courts
598/// (courts/suites/data-abi/*-family-probe.c) and the CLI differential
599/// courts; those pass byte-for-byte against the upstream oracle.
600#[no_mangle]
601pub unsafe extern "C" fn xmlClearParserCtxt(ctxt: *mut _xmlParserCtxt) {
602 unsafe { xmlCtxtReset(ctxt) }
603}
604
605/// Reset a parser context: drop the input stack, node/name stacks, strings,
606/// document and error state so the context can be reused.
607///
608/// # UPSTREAM-PARITY
609///
610/// ```c
611/// void xmlCtxtReset(xmlParserCtxtPtr ctxt);
612/// ```
613///
614/// # SAFETY
615///
616/// - `ctxt` must be valid pointers (or NULL
617/// where the upstream C contract allows), obtained from the
618/// matching constructor/owner and not yet freed; the callee may
619/// take or keep ownership exactly as the C API specifies.
620///
621/// The caller must not race this call with concurrent mutation of the
622/// same objects from other threads (per-object state is not internally
623/// synchronized). Violating any of the above is undefined behavior.
624///
625/// Exercised by the C-API differential courts
626/// (courts/suites/data-abi/*-family-probe.c) and the CLI differential
627/// courts; those pass byte-for-byte against the upstream oracle.
628#[no_mangle]
629pub unsafe extern "C" fn xmlCtxtReset(ctxt: *mut _xmlParserCtxt) {
630 if ctxt.is_null() {
631 return;
632 }
633 unsafe {
634 let c = &mut *ctxt;
635
636 // Free all inputs on the stack.
637 let input_nr = c.inputNr;
638 let input_tab = c.inputTab;
639 if !input_tab.is_null() {
640 for i in 0..input_nr {
641 let input = *input_tab.add(i as usize);
642 if !input.is_null() {
643 helpers::free_parser_input(input);
644 }
645 }
646 xmlFreeImpl(input_tab as *mut c_void);
647 }
648 c.inputTab = ptr::null_mut();
649 c.inputMax = 0;
650 c.inputNr = 0;
651 c.input = ptr::null_mut();
652
653 // Free the stored InputBuffer (stashed by setup_parser_input; the
654 // side table keeps ctxt._private application data — 11.1-X).
655 helpers::free_stashed_input_buffer(ctxt);
656
657 // Node stack (array only; nodes are owned by the doc).
658 if !c.nodeTab.is_null() {
659 xmlFreeImpl(c.nodeTab as *mut c_void);
660 }
661 c.nodeTab = ptr::null_mut();
662 c.nodeMax = 0;
663 c.nodeNr = 0;
664 c.node = ptr::null_mut();
665
666 // Name stack.
667 if !c.nameTab.is_null() {
668 xmlFreeImpl(c.nameTab as *mut c_void);
669 }
670 c.nameTab = ptr::null_mut();
671 c.nameMax = 0;
672 c.nameNr = 0;
673 c.name = ptr::null();
674
675 // Space stack: keep the allocation, reset the counter.
676 c.spaceNr = 0;
677 c.space = ptr::null_mut();
678
679 // Namespaces.
680 c.nsNr = 0;
681
682 // Strings owned by the context.
683 if !c.version.is_null() {
684 xmlFreeImpl(c.version as *mut c_void);
685 c.version = ptr::null_mut();
686 }
687 if !c.encoding.is_null() {
688 xmlFreeImpl(c.encoding as *mut c_void);
689 c.encoding = ptr::null_mut();
690 }
691 if !c.extSubURI.is_null() {
692 xmlFreeImpl(c.extSubURI as *mut c_void);
693 c.extSubURI = ptr::null_mut();
694 }
695 if !c.extSubSystem.is_null() {
696 xmlFreeImpl(c.extSubSystem as *mut c_void);
697 c.extSubSystem = ptr::null_mut();
698 }
699 if !c.directory.is_null() {
700 xmlFreeImpl(c.directory as *mut c_void);
701 c.directory = ptr::null_mut();
702 }
703
704 // Document: the context owns it until reset/free.
705 if !c.myDoc.is_null() {
706 tree::free_doc(c.myDoc);
707 }
708 c.myDoc = ptr::null_mut();
709
710 // Parser state.
711 c.standalone = -1;
712 c.hasExternalSubset = 0;
713 c.hasPErefs = 0;
714 c.instate = xmlParserInputState::XML_PARSER_START as c_int;
715 c.wellFormed = 1;
716 c.nsWellFormed = 1;
717 c.disableSAX = 0;
718 c.valid = 1;
719 c.record_info = 0;
720 c.checkIndex = 0;
721 c.inSubset = 0;
722 c.errNo = XML_ERR_OK;
723 c.depth = 0;
724 c.nbentities = 0;
725 c.sizeentities = 0;
726 c.nbErrors = 0;
727 c.nbWarnings = 0;
728
729 xmlInitNodeInfoSeq(&mut c.node_seq);
730
731 if c.lastError.code != XML_ERR_OK {
732 errors::reset_error(&mut c.lastError);
733 }
734 }
735}
736
737/// Reset a push-parser context and set up a fresh input chunk.
738///
739/// # UPSTREAM-PARITY
740///
741/// ```c
742/// int xmlCtxtResetPush(xmlParserCtxtPtr ctxt, const char *chunk, int size,
743/// const char *filename, const char *encoding);
744/// ```
745///
746/// # SAFETY
747///
748/// - `ctxt` must be valid pointers (or NULL
749/// where the upstream C contract allows), obtained from the
750/// matching constructor/owner and not yet freed; the callee may
751/// take or keep ownership exactly as the C API specifies.
752///
753/// - `chunk`, `filename`, `encoding` must point to valid NUL-terminated
754/// strings (or NULL where the C contract allows) for the lifetime
755/// of the call.
756///
757/// The caller must not race this call with concurrent mutation of the
758/// same objects from other threads (per-object state is not internally
759/// synchronized). Violating any of the above is undefined behavior.
760///
761/// Exercised by the C-API differential courts
762/// (courts/suites/data-abi/*-family-probe.c) and the CLI differential
763/// courts; those pass byte-for-byte against the upstream oracle.
764#[no_mangle]
765pub unsafe extern "C" fn xmlCtxtResetPush(
766 ctxt: *mut _xmlParserCtxt,
767 chunk: *const c_char,
768 size: c_int,
769 filename: *const c_char,
770 encoding: *const c_char,
771) -> c_int {
772 if ctxt.is_null() {
773 return 1;
774 }
775 unsafe {
776 xmlCtxtReset(ctxt);
777
778 let slice = if size > 0 && !chunk.is_null() {
779 core::slice::from_raw_parts(chunk as *const u8, size as usize)
780 } else {
781 &[]
782 };
783 let uri = if filename.is_null() {
784 None
785 } else {
786 CStr::from_ptr(filename).to_str().ok()
787 };
788 let input = InputBuffer::from_memory(slice, uri);
789 helpers::setup_parser_input(ctxt, input);
790
791 if !encoding.is_null() {
792 let handler = encoding::find_encoding_handler(encoding as *const xmlChar);
793 if !handler.is_null() {
794 xmlSwitchToEncoding(ctxt, handler);
795 }
796 }
797 }
798 0
799}
800
801/// Apply a full set of parser options, clearing options not present.
802///
803/// # UPSTREAM-PARITY
804///
805/// ```c
806/// int xmlCtxtSetOptions(xmlParserCtxtPtr ctxt, int options);
807/// ```
808///
809/// # SAFETY
810///
811/// - `ctxt` must be valid pointers (or NULL
812/// where the upstream C contract allows), obtained from the
813/// matching constructor/owner and not yet freed; the callee may
814/// take or keep ownership exactly as the C API specifies.
815///
816/// The caller must not race this call with concurrent mutation of the
817/// same objects from other threads (per-object state is not internally
818/// synchronized). Violating any of the above is undefined behavior.
819///
820/// Exercised by the C-API differential courts
821/// (courts/suites/data-abi/*-family-probe.c) and the CLI differential
822/// courts; those pass byte-for-byte against the upstream oracle.
823#[no_mangle]
824pub unsafe extern "C" fn xmlCtxtSetOptions(ctxt: *mut _xmlParserCtxt, options: c_int) -> c_int {
825 if ctxt.is_null() {
826 return -1;
827 }
828 const ALL_MASK: c_int = XML_PARSE_RECOVER
829 | XML_PARSE_NOENT
830 | XML_PARSE_DTDLOAD
831 | XML_PARSE_DTDATTR
832 | XML_PARSE_DTDVALID
833 | XML_PARSE_NOERROR
834 | XML_PARSE_NOWARNING
835 | XML_PARSE_PEDANTIC
836 | XML_PARSE_NOBLANKS
837 | XML_PARSE_SAX1
838 | XML_PARSE_NONET
839 | XML_PARSE_NODICT
840 | XML_PARSE_NSCLEAN
841 | XML_PARSE_NOCDATA
842 | XML_PARSE_COMPACT
843 | XML_PARSE_OLD10
844 | XML_PARSE_HUGE
845 | XML_PARSE_OLDSAX
846 | XML_PARSE_IGNORE_ENC
847 | XML_PARSE_BIG_LINES;
848
849 unsafe {
850 apply_options(ctxt, options & ALL_MASK);
851 }
852 options & !ALL_MASK
853}
854
855/// Install a per-context structured error handler.
856///
857/// # UPSTREAM-PARITY
858///
859/// ```c
860/// void xmlCtxtSetErrorHandler(xmlParserCtxtPtr ctxt,
861/// xmlStructuredErrorFunc handler, void *data);
862/// ```
863///
864/// # SAFETY
865///
866/// - `ctxt`, `data` must be valid pointers (or NULL
867/// where the upstream C contract allows), obtained from the
868/// matching constructor/owner and not yet freed; the callee may
869/// take or keep ownership exactly as the C API specifies.
870///
871/// - `handler` must be a valid callback (or None);
872/// the callback is invoked with the documented context pointer and
873/// must itself uphold the same pointer invariants.
874///
875/// The caller must not race this call with concurrent mutation of the
876/// same objects from other threads (per-object state is not internally
877/// synchronized). Violating any of the above is undefined behavior.
878///
879/// Exercised by the C-API differential courts
880/// (courts/suites/data-abi/*-family-probe.c) and the CLI differential
881/// courts; those pass byte-for-byte against the upstream oracle.
882#[no_mangle]
883pub unsafe extern "C" fn xmlCtxtSetErrorHandler(
884 ctxt: *mut _xmlParserCtxt,
885 handler: Option<xmlStructuredErrorFunc>,
886 data: *mut c_void,
887) {
888 if ctxt.is_null() {
889 return;
890 }
891 unsafe {
892 (*ctxt).errorHandler = handler;
893 (*ctxt).errorCtxt = data;
894 }
895}
896
897/// Set the maximum entity expansion amplification factor.
898///
899/// # UPSTREAM-PARITY
900///
901/// ```c
902/// void xmlCtxtSetMaxAmplification(xmlParserCtxtPtr ctxt, unsigned maxAmpl);
903/// ```
904///
905/// # SAFETY
906///
907/// - `ctxt` must be valid pointers (or NULL
908/// where the upstream C contract allows), obtained from the
909/// matching constructor/owner and not yet freed; the callee may
910/// take or keep ownership exactly as the C API specifies.
911///
912/// The caller must not race this call with concurrent mutation of the
913/// same objects from other threads (per-object state is not internally
914/// synchronized). Violating any of the above is undefined behavior.
915///
916/// Exercised by the C-API differential courts
917/// (courts/suites/data-abi/*-family-probe.c) and the CLI differential
918/// courts; those pass byte-for-byte against the upstream oracle.
919#[no_mangle]
920pub unsafe extern "C" fn xmlCtxtSetMaxAmplification(ctxt: *mut _xmlParserCtxt, maxAmpl: c_uint) {
921 if ctxt.is_null() || maxAmpl == 0 {
922 return;
923 }
924 unsafe {
925 (*ctxt).maxAmpl = maxAmpl;
926 }
927}
928
929/// Get the last error raised on the context, or NULL.
930///
931/// # UPSTREAM-PARITY
932///
933/// ```c
934/// const xmlError *xmlCtxtGetLastError(void *ctx);
935/// ```
936///
937/// # SAFETY
938///
939/// - `ctx` must be valid pointers (or NULL
940/// where the upstream C contract allows), obtained from the
941/// matching constructor/owner and not yet freed; the callee may
942/// take or keep ownership exactly as the C API specifies.
943///
944/// The caller must not race this call with concurrent mutation of the
945/// same objects from other threads (per-object state is not internally
946/// synchronized). Violating any of the above is undefined behavior.
947///
948/// Exercised by the C-API differential courts
949/// (courts/suites/data-abi/*-family-probe.c) and the CLI differential
950/// courts; those pass byte-for-byte against the upstream oracle.
951#[no_mangle]
952pub unsafe extern "C" fn xmlCtxtGetLastError(ctx: *mut c_void) -> *const _xmlError {
953 if ctx.is_null() {
954 return ptr::null();
955 }
956 let ctxt = ctx as *mut _xmlParserCtxt;
957 unsafe {
958 if (*ctxt).lastError.code == XML_ERR_OK {
959 return ptr::null();
960 }
961 &(*ctxt).lastError
962 }
963}
964
965/// Reset the context's last-error state.
966///
967/// # UPSTREAM-PARITY
968///
969/// ```c
970/// void xmlCtxtResetLastError(void *ctx);
971/// ```
972///
973/// # SAFETY
974///
975/// - `ctx` must be valid pointers (or NULL
976/// where the upstream C contract allows), obtained from the
977/// matching constructor/owner and not yet freed; the callee may
978/// take or keep ownership exactly as the C API specifies.
979///
980/// The caller must not race this call with concurrent mutation of the
981/// same objects from other threads (per-object state is not internally
982/// synchronized). Violating any of the above is undefined behavior.
983///
984/// Exercised by the C-API differential courts
985/// (courts/suites/data-abi/*-family-probe.c) and the CLI differential
986/// courts; those pass byte-for-byte against the upstream oracle.
987#[no_mangle]
988pub unsafe extern "C" fn xmlCtxtResetLastError(ctx: *mut c_void) {
989 if ctx.is_null() {
990 return;
991 }
992 let ctxt = ctx as *mut _xmlParserCtxt;
993 unsafe {
994 (*ctxt).errNo = XML_ERR_OK;
995 if (*ctxt).lastError.code != XML_ERR_OK {
996 errors::reset_error(&mut (*ctxt).lastError);
997 }
998 }
999}
1000
1001/// Handle an out-of-memory error on a parser context.
1002///
1003/// # UPSTREAM-PARITY
1004///
1005/// ```c
1006/// void xmlCtxtErrMemory(xmlParserCtxtPtr ctxt);
1007/// ```
1008///
1009/// # SAFETY
1010///
1011/// - `ctxt` must be valid pointers (or NULL
1012/// where the upstream C contract allows), obtained from the
1013/// matching constructor/owner and not yet freed; the callee may
1014/// take or keep ownership exactly as the C API specifies.
1015///
1016/// The caller must not race this call with concurrent mutation of the
1017/// same objects from other threads (per-object state is not internally
1018/// synchronized). Violating any of the above is undefined behavior.
1019///
1020/// Exercised by the C-API differential courts
1021/// (courts/suites/data-abi/*-family-probe.c) and the CLI differential
1022/// courts; those pass byte-for-byte against the upstream oracle.
1023#[no_mangle]
1024pub unsafe extern "C" fn xmlCtxtErrMemory(ctxt: *mut _xmlParserCtxt) {
1025 if ctxt.is_null() {
1026 return;
1027 }
1028 unsafe {
1029 let c = &mut *ctxt;
1030 c.errNo = XML_ERR_NO_MEMORY;
1031 c.instate = xmlParserInputState::XML_PARSER_EOF as c_int;
1032 c.wellFormed = 0;
1033 c.disableSAX = 2;
1034
1035 c.lastError.domain = XML_FROM_PARSER;
1036 c.lastError.code = XML_ERR_NO_MEMORY;
1037 c.lastError.level = xmlErrorLevel::XML_ERR_FATAL as c_int;
1038 c.lastError.message = c"out of memory\n".as_ptr() as *mut c_char;
1039
1040 if let Some(handler) = c.errorHandler {
1041 handler(c.errorCtxt, &c.lastError);
1042 } else if !c.sax.is_null() {
1043 if let Some(serror) = (*c.sax).serror {
1044 serror(c.userData, &c.lastError);
1045 }
1046 }
1047 }
1048}
1049
1050/// Stop the parser: no further processing will happen.
1051///
1052/// # UPSTREAM-PARITY
1053///
1054/// ```c
1055/// void xmlStopParser(xmlParserCtxtPtr ctxt);
1056/// ```
1057///
1058/// # SAFETY
1059///
1060/// - `ctxt` must be valid pointers (or NULL
1061/// where the upstream C contract allows), obtained from the
1062/// matching constructor/owner and not yet freed; the callee may
1063/// take or keep ownership exactly as the C API specifies.
1064///
1065/// The caller must not race this call with concurrent mutation of the
1066/// same objects from other threads (per-object state is not internally
1067/// synchronized). Violating any of the above is undefined behavior.
1068///
1069/// Exercised by the C-API differential courts
1070/// (courts/suites/data-abi/*-family-probe.c) and the CLI differential
1071/// courts; those pass byte-for-byte against the upstream oracle.
1072#[no_mangle]
1073pub unsafe extern "C" fn xmlStopParser(ctxt: *mut _xmlParserCtxt) {
1074 if ctxt.is_null() {
1075 return;
1076 }
1077 unsafe {
1078 (*ctxt).disableSAX = 2;
1079 if (*ctxt).errNo == XML_ERR_OK {
1080 (*ctxt).errNo = XML_ERR_USER_STOP;
1081 (*ctxt).lastError.code = XML_ERR_USER_STOP;
1082 (*ctxt).wellFormed = 0;
1083 }
1084 }
1085}
1086
1087/// Return the byte offset of the current parse position within the current
1088/// entity, or -1 when it cannot be computed.
1089///
1090/// # UPSTREAM-PARITY
1091///
1092/// ```c
1093/// long xmlByteConsumed(xmlParserCtxtPtr ctxt);
1094/// ```
1095///
1096/// # SAFETY
1097///
1098/// - `ctxt` must be valid pointers (or NULL
1099/// where the upstream C contract allows), obtained from the
1100/// matching constructor/owner and not yet freed; the callee may
1101/// take or keep ownership exactly as the C API specifies.
1102///
1103/// The caller must not race this call with concurrent mutation of the
1104/// same objects from other threads (per-object state is not internally
1105/// synchronized). Violating any of the above is undefined behavior.
1106///
1107/// Exercised by the C-API differential courts
1108/// (courts/suites/data-abi/*-family-probe.c) and the CLI differential
1109/// courts; those pass byte-for-byte against the upstream oracle.
1110#[no_mangle]
1111pub unsafe extern "C" fn xmlByteConsumed(ctxt: *mut _xmlParserCtxt) -> c_long {
1112 if ctxt.is_null() {
1113 return -1;
1114 }
1115 unsafe {
1116 let input = (*ctxt).input;
1117 if input.is_null() {
1118 return -1;
1119 }
1120 if !(*input).buf.is_null() && !(*(*input).buf).encoder.is_null() {
1121 // With an encoder we cannot cheaply compute the original byte
1122 // position; report the raw consumed count.
1123 return (*(*input).buf).rawconsumed as c_long;
1124 }
1125 let consumed = (*input).consumed;
1126 if (*input).base.is_null() {
1127 return consumed as c_long;
1128 }
1129 (consumed + ((*input).cur as usize).saturating_sub((*input).base as usize) as c_ulong)
1130 as c_long
1131 }
1132}
1133
1134/// Extract the directory part of a filename (newly allocated).
1135///
1136/// # UPSTREAM-PARITY
1137///
1138/// ```c
1139/// char *xmlParserGetDirectory(const char *filename);
1140/// ```
1141///
1142/// # SAFETY
1143///
1144///
1145/// - `filename` must point to valid NUL-terminated
1146/// strings (or NULL where the C contract allows) for the lifetime
1147/// of the call.
1148///
1149/// The caller must not race this call with concurrent mutation of the
1150/// same objects from other threads (per-object state is not internally
1151/// synchronized). Violating any of the above is undefined behavior.
1152///
1153/// Exercised by the C-API differential courts
1154/// (courts/suites/data-abi/*-family-probe.c) and the CLI differential
1155/// courts; those pass byte-for-byte against the upstream oracle.
1156#[no_mangle]
1157pub unsafe extern "C" fn xmlParserGetDirectory(filename: *const c_char) -> *mut c_char {
1158 if filename.is_null() {
1159 return ptr::null_mut();
1160 }
1161 unsafe {
1162 let len = libc::strlen(filename);
1163 let mut last_sep: Option<usize> = None;
1164 for i in 0..len {
1165 if *filename.add(i) == b'/' as c_char {
1166 last_sep = Some(i);
1167 }
1168 }
1169 match last_sep {
1170 Some(0) => xmlMemStrdupImpl(c"/".as_ptr() as *const c_char) as *mut c_char,
1171 Some(pos) => {
1172 let slice = core::slice::from_raw_parts(filename as *const u8, pos);
1173 let mut v = slice.to_vec();
1174 v.push(0);
1175 xmlMemStrdupImpl(v.as_ptr() as *const c_char) as *mut c_char
1176 }
1177 None => xmlMemStrdupImpl(c".".as_ptr() as *const c_char) as *mut c_char,
1178 }
1179 }
1180}
1181
1182/// Check whether a file exists: 0 if stat fails, 2 if it is a directory,
1183/// 1 otherwise.
1184///
1185/// # UPSTREAM-PARITY
1186///
1187/// ```c
1188/// int xmlCheckFilename(const char *path);
1189/// ```
1190///
1191/// # SAFETY
1192///
1193///
1194/// - `path` must point to valid NUL-terminated
1195/// strings (or NULL where the C contract allows) for the lifetime
1196/// of the call.
1197///
1198/// The caller must not race this call with concurrent mutation of the
1199/// same objects from other threads (per-object state is not internally
1200/// synchronized). Violating any of the above is undefined behavior.
1201///
1202/// Exercised by the C-API differential courts
1203/// (courts/suites/data-abi/*-family-probe.c) and the CLI differential
1204/// courts; those pass byte-for-byte against the upstream oracle.
1205#[no_mangle]
1206pub unsafe extern "C" fn xmlCheckFilename(path: *const c_char) -> c_int {
1207 if path.is_null() {
1208 return 0;
1209 }
1210 unsafe {
1211 let mut st: libc::stat = core::mem::zeroed();
1212 if libc::stat(path, &mut st) != 0 {
1213 return 0;
1214 }
1215 if st.st_mode & libc::S_IFMT == libc::S_IFDIR {
1216 2
1217 } else {
1218 1
1219 }
1220 }
1221}
1222
1223/// Test whether a public/system ID pair is one of the XHTML DTDs.
1224///
1225/// # UPSTREAM-PARITY
1226///
1227/// ```c
1228/// int xmlIsXHTML(const xmlChar *systemID, const xmlChar *publicID);
1229/// ```
1230///
1231/// # SAFETY
1232///
1233///
1234/// - `systemID`, `publicID` must point to valid NUL-terminated
1235/// strings (or NULL where the C contract allows) for the lifetime
1236/// of the call.
1237///
1238/// The caller must not race this call with concurrent mutation of the
1239/// same objects from other threads (per-object state is not internally
1240/// synchronized). Violating any of the above is undefined behavior.
1241///
1242/// Exercised by the C-API differential courts
1243/// (courts/suites/data-abi/*-family-probe.c) and the CLI differential
1244/// courts; those pass byte-for-byte against the upstream oracle.
1245#[no_mangle]
1246pub unsafe extern "C" fn xmlIsXHTML(systemID: *const xmlChar, publicID: *const xmlChar) -> c_int {
1247 const XHTML_STRICT_PUBLIC_ID: &[u8] = b"-//W3C//DTD XHTML 1.0 Strict//EN\0";
1248 const XHTML_STRICT_SYSTEM_ID: &[u8] = b"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd\0";
1249 const XHTML_FRAME_PUBLIC_ID: &[u8] = b"-//W3C//DTD XHTML 1.0 Frameset//EN\0";
1250 const XHTML_FRAME_SYSTEM_ID: &[u8] = b"http://www.w3.org/TR/xhtml1/DTD/xhtml1-frameset.dtd\0";
1251 const XHTML_TRANS_PUBLIC_ID: &[u8] = b"-//W3C//DTD XHTML 1.0 Transitional//EN\0";
1252 const XHTML_TRANS_SYSTEM_ID: &[u8] =
1253 b"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd\0";
1254
1255 if systemID.is_null() && publicID.is_null() {
1256 return -1;
1257 }
1258 unsafe {
1259 if !publicID.is_null()
1260 && (string::xml_strcmp(publicID, XHTML_STRICT_PUBLIC_ID.as_ptr() as *const xmlChar)
1261 == 0
1262 || string::xml_strcmp(publicID, XHTML_FRAME_PUBLIC_ID.as_ptr() as *const xmlChar)
1263 == 0
1264 || string::xml_strcmp(publicID, XHTML_TRANS_PUBLIC_ID.as_ptr() as *const xmlChar)
1265 == 0)
1266 {
1267 return 1;
1268 }
1269 if !systemID.is_null()
1270 && (string::xml_strcmp(systemID, XHTML_STRICT_SYSTEM_ID.as_ptr() as *const xmlChar)
1271 == 0
1272 || string::xml_strcmp(systemID, XHTML_FRAME_SYSTEM_ID.as_ptr() as *const xmlChar)
1273 == 0
1274 || string::xml_strcmp(systemID, XHTML_TRANS_SYSTEM_ID.as_ptr() as *const xmlChar)
1275 == 0)
1276 {
1277 return 1;
1278 }
1279 }
1280 0
1281}
1282
1283// ═══════════════════════════════════════════════════════════════════════════════
1284// Context creation from sources
1285// ═══════════════════════════════════════════════════════════════════════════════
1286
1287/// Create a parser context for an in-memory document.
1288///
1289/// # UPSTREAM-PARITY
1290///
1291/// ```c
1292/// xmlParserCtxtPtr xmlCreateMemoryParserCtxt(const char *buffer, int size);
1293/// ```
1294///
1295/// # SAFETY
1296///
1297///
1298/// - `buffer` must point to valid NUL-terminated
1299/// strings (or NULL where the C contract allows) for the lifetime
1300/// of the call.
1301///
1302/// The caller must not race this call with concurrent mutation of the
1303/// same objects from other threads (per-object state is not internally
1304/// synchronized). Violating any of the above is undefined behavior.
1305///
1306/// Exercised by the C-API differential courts
1307/// (courts/suites/data-abi/*-family-probe.c) and the CLI differential
1308/// courts; those pass byte-for-byte against the upstream oracle.
1309#[no_mangle]
1310pub unsafe extern "C" fn xmlCreateMemoryParserCtxt(
1311 buffer: *const c_char,
1312 size: c_int,
1313) -> *mut _xmlParserCtxt {
1314 if buffer.is_null() || size < 0 {
1315 return ptr::null_mut();
1316 }
1317 unsafe {
1318 let ctxt = xmlNewParserCtxt();
1319 if ctxt.is_null() {
1320 return ptr::null_mut();
1321 }
1322 let input = helpers::input_from_memory(buffer, size);
1323 helpers::setup_parser_input(ctxt, input);
1324 ctxt
1325 }
1326}
1327
1328/// Create a parser context for push parsing.
1329///
1330/// # UPSTREAM-PARITY
1331///
1332/// ```c
1333/// xmlParserCtxtPtr xmlCreatePushParserCtxt(xmlSAXHandler *sax, void *user_data,
1334/// const char *chunk, int size,
1335/// const char *filename);
1336/// ```
1337///
1338/// # SAFETY
1339///
1340/// - `sax`, `user_data` must be valid pointers (or NULL
1341/// where the upstream C contract allows), obtained from the
1342/// matching constructor/owner and not yet freed; the callee may
1343/// take or keep ownership exactly as the C API specifies.
1344///
1345/// - `chunk`, `filename` must point to valid NUL-terminated
1346/// strings (or NULL where the C contract allows) for the lifetime
1347/// of the call.
1348///
1349/// The caller must not race this call with concurrent mutation of the
1350/// same objects from other threads (per-object state is not internally
1351/// synchronized). Violating any of the above is undefined behavior.
1352///
1353/// Exercised by the C-API differential courts
1354/// (courts/suites/data-abi/*-family-probe.c) and the CLI differential
1355/// courts; those pass byte-for-byte against the upstream oracle.
1356#[no_mangle]
1357pub unsafe extern "C" fn xmlCreatePushParserCtxt(
1358 sax: *mut _xmlSAXHandler,
1359 user_data: *mut c_void,
1360 chunk: *const c_char,
1361 size: c_int,
1362 filename: *const c_char,
1363) -> *mut _xmlParserCtxt {
1364 unsafe {
1365 let ctxt = xmlNewSAXParserCtxt(sax, user_data);
1366 if ctxt.is_null() {
1367 return ptr::null_mut();
1368 }
1369 let slice = if size > 0 && !chunk.is_null() {
1370 core::slice::from_raw_parts(chunk as *const u8, size as usize)
1371 } else {
1372 &[]
1373 };
1374 let uri = if filename.is_null() {
1375 None
1376 } else {
1377 CStr::from_ptr(filename).to_str().ok()
1378 };
1379 let input = InputBuffer::from_memory(slice, uri);
1380 helpers::setup_parser_input(ctxt, input);
1381 ctxt
1382 }
1383}
1384
1385/// Create a parser context for an I/O stream.
1386///
1387/// # UPSTREAM-PARITY
1388///
1389/// ```c
1390/// xmlParserCtxtPtr xmlCreateIOParserCtxt(xmlSAXHandler *sax, void *user_data,
1391/// xmlInputReadCallback ioread,
1392/// xmlInputCloseCallback ioclose,
1393/// void *ioctx, xmlCharEncoding enc);
1394/// ```
1395///
1396/// # SAFETY
1397///
1398/// - `sax`, `user_data`, `ioctx` must be valid pointers (or NULL
1399/// where the upstream C contract allows), obtained from the
1400/// matching constructor/owner and not yet freed; the callee may
1401/// take or keep ownership exactly as the C API specifies.
1402///
1403/// - `ioread`, `ioclose` must be a valid callback (or None);
1404/// the callback is invoked with the documented context pointer and
1405/// must itself uphold the same pointer invariants.
1406///
1407/// The caller must not race this call with concurrent mutation of the
1408/// same objects from other threads (per-object state is not internally
1409/// synchronized). Violating any of the above is undefined behavior.
1410///
1411/// Exercised by the C-API differential courts
1412/// (courts/suites/data-abi/*-family-probe.c) and the CLI differential
1413/// courts; those pass byte-for-byte against the upstream oracle.
1414#[no_mangle]
1415pub unsafe extern "C" fn xmlCreateIOParserCtxt(
1416 sax: *mut _xmlSAXHandler,
1417 user_data: *mut c_void,
1418 ioread: Option<xmlInputReadCallback>,
1419 ioclose: Option<xmlInputCloseCallback>,
1420 ioctx: *mut c_void,
1421 enc: c_int,
1422) -> *mut _xmlParserCtxt {
1423 unsafe {
1424 let ctxt = xmlNewSAXParserCtxt(sax, user_data);
1425 if ctxt.is_null() {
1426 return ptr::null_mut();
1427 }
1428 let input = helpers::input_from_io(ioread, ioclose, ioctx);
1429 helpers::setup_parser_input(ctxt, input);
1430 if enc != xmlCharEncoding::XML_CHAR_ENCODING_NONE as c_int {
1431 xmlSwitchEncoding(ctxt, enc);
1432 }
1433 ctxt
1434 }
1435}
1436
1437/// Create a parser context for a file or URL.
1438///
1439/// # UPSTREAM-PARITY
1440///
1441/// ```c
1442/// xmlParserCtxtPtr xmlCreateURLParserCtxt(const char *filename, int options);
1443/// ```
1444///
1445/// # SAFETY
1446///
1447///
1448/// - `filename` must point to valid NUL-terminated
1449/// strings (or NULL where the C contract allows) for the lifetime
1450/// of the call.
1451///
1452/// The caller must not race this call with concurrent mutation of the
1453/// same objects from other threads (per-object state is not internally
1454/// synchronized). Violating any of the above is undefined behavior.
1455///
1456/// Exercised by the C-API differential courts
1457/// (courts/suites/data-abi/*-family-probe.c) and the CLI differential
1458/// courts; those pass byte-for-byte against the upstream oracle.
1459#[no_mangle]
1460pub unsafe extern "C" fn xmlCreateURLParserCtxt(
1461 filename: *const c_char,
1462 options: c_int,
1463) -> *mut _xmlParserCtxt {
1464 if filename.is_null() {
1465 return ptr::null_mut();
1466 }
1467 unsafe {
1468 let ctxt = xmlNewParserCtxt();
1469 if ctxt.is_null() {
1470 return ptr::null_mut();
1471 }
1472 apply_options(ctxt, options);
1473 let input = match helpers::input_from_file(filename) {
1474 Ok(i) => i,
1475 Err(_) => {
1476 helpers::free_parser_ctxt(ctxt);
1477 return ptr::null_mut();
1478 }
1479 };
1480 helpers::setup_parser_input(ctxt, input);
1481 ctxt
1482 }
1483}
1484
1485/// Create a parser context for an external entity.
1486///
1487/// # UPSTREAM-PARITY
1488///
1489/// ```c
1490/// xmlParserCtxtPtr xmlCreateEntityParserCtxt(const xmlChar *URL,
1491/// const xmlChar *ID,
1492/// const xmlChar *base);
1493/// ```
1494///
1495/// # SAFETY
1496///
1497///
1498/// - `URL`, `ID`, `base` must point to valid NUL-terminated
1499/// strings (or NULL where the C contract allows) for the lifetime
1500/// of the call.
1501///
1502/// The caller must not race this call with concurrent mutation of the
1503/// same objects from other threads (per-object state is not internally
1504/// synchronized). Violating any of the above is undefined behavior.
1505///
1506/// Exercised by the C-API differential courts
1507/// (courts/suites/data-abi/*-family-probe.c) and the CLI differential
1508/// courts; those pass byte-for-byte against the upstream oracle.
1509#[no_mangle]
1510pub unsafe extern "C" fn xmlCreateEntityParserCtxt(
1511 URL: *const xmlChar,
1512 ID: *const xmlChar,
1513 base: *const xmlChar,
1514) -> *mut _xmlParserCtxt {
1515 let _ = base; // base URI resolution is a no-op here
1516 unsafe {
1517 let ctxt = xmlNewParserCtxt();
1518 if ctxt.is_null() {
1519 return ptr::null_mut();
1520 }
1521 let input = xmlLoadExternalEntity(URL as *const c_char, ID as *const c_char, ctxt);
1522 if input.is_null() {
1523 helpers::free_parser_ctxt(ctxt);
1524 return ptr::null_mut();
1525 }
1526 if xmlPushInput(ctxt, input) < 0 {
1527 helpers::free_parser_input(input);
1528 helpers::free_parser_ctxt(ctxt);
1529 return ptr::null_mut();
1530 }
1531 ctxt
1532 }
1533}
1534
1535// ═══════════════════════════════════════════════════════════════════════════════
1536// CtxtRead family
1537// ═══════════════════════════════════════════════════════════════════════════════
1538
1539/// Parse an XML in-memory document with a given context.
1540///
1541/// # UPSTREAM-PARITY
1542///
1543/// ```c
1544/// xmlDocPtr xmlCtxtReadDoc(xmlParserCtxtPtr ctxt, const xmlChar *cur,
1545/// const char *URL, const char *encoding, int options);
1546/// ```
1547///
1548/// # SAFETY
1549///
1550/// - `ctxt` must be valid pointers (or NULL
1551/// where the upstream C contract allows), obtained from the
1552/// matching constructor/owner and not yet freed; the callee may
1553/// take or keep ownership exactly as the C API specifies.
1554///
1555/// - `cur`, `URL`, `_encoding` must point to valid NUL-terminated
1556/// strings (or NULL where the C contract allows) for the lifetime
1557/// of the call.
1558///
1559/// The caller must not race this call with concurrent mutation of the
1560/// same objects from other threads (per-object state is not internally
1561/// synchronized). Violating any of the above is undefined behavior.
1562///
1563/// Exercised by the C-API differential courts
1564/// (courts/suites/data-abi/*-family-probe.c) and the CLI differential
1565/// courts; those pass byte-for-byte against the upstream oracle.
1566#[no_mangle]
1567pub unsafe extern "C" fn xmlCtxtReadDoc(
1568 ctxt: *mut _xmlParserCtxt,
1569 cur: *const xmlChar,
1570 URL: *const c_char,
1571 _encoding: *const c_char,
1572 options: c_int,
1573) -> *mut _xmlDoc {
1574 if ctxt.is_null() || cur.is_null() {
1575 return ptr::null_mut();
1576 }
1577 unsafe {
1578 let len = string::xml_strlen(cur);
1579 let input = helpers::input_from_memory(cur as *const c_char, len as c_int);
1580 ctxt_read_doc(ctxt, input, URL, options)
1581 }
1582}
1583
1584/// Parse an XML file with a given context.
1585///
1586/// # UPSTREAM-PARITY
1587///
1588/// ```c
1589/// xmlDocPtr xmlCtxtReadFile(xmlParserCtxtPtr ctxt, const char *filename,
1590/// const char *encoding, int options);
1591/// ```
1592///
1593/// # SAFETY
1594///
1595/// - `ctxt` must be valid pointers (or NULL
1596/// where the upstream C contract allows), obtained from the
1597/// matching constructor/owner and not yet freed; the callee may
1598/// take or keep ownership exactly as the C API specifies.
1599///
1600/// - `filename`, `_encoding` must point to valid NUL-terminated
1601/// strings (or NULL where the C contract allows) for the lifetime
1602/// of the call.
1603///
1604/// The caller must not race this call with concurrent mutation of the
1605/// same objects from other threads (per-object state is not internally
1606/// synchronized). Violating any of the above is undefined behavior.
1607///
1608/// Exercised by the C-API differential courts
1609/// (courts/suites/data-abi/*-family-probe.c) and the CLI differential
1610/// courts; those pass byte-for-byte against the upstream oracle.
1611#[no_mangle]
1612pub unsafe extern "C" fn xmlCtxtReadFile(
1613 ctxt: *mut _xmlParserCtxt,
1614 filename: *const c_char,
1615 _encoding: *const c_char,
1616 options: c_int,
1617) -> *mut _xmlDoc {
1618 if ctxt.is_null() || filename.is_null() {
1619 return ptr::null_mut();
1620 }
1621 unsafe {
1622 match helpers::input_from_file(filename) {
1623 Ok(input) => ctxt_read_doc(ctxt, input, filename, options),
1624 Err(_) => ptr::null_mut(),
1625 }
1626 }
1627}
1628
1629/// Parse an XML in-memory block with a given context.
1630///
1631/// # UPSTREAM-PARITY
1632///
1633/// ```c
1634/// xmlDocPtr xmlCtxtReadMemory(xmlParserCtxtPtr ctxt, const char *buffer,
1635/// int size, const char *URL, const char *encoding,
1636/// int options);
1637/// ```
1638///
1639/// # SAFETY
1640///
1641/// - `ctxt` must be valid pointers (or NULL
1642/// where the upstream C contract allows), obtained from the
1643/// matching constructor/owner and not yet freed; the callee may
1644/// take or keep ownership exactly as the C API specifies.
1645///
1646/// - `buffer`, `URL`, `_encoding` must point to valid NUL-terminated
1647/// strings (or NULL where the C contract allows) for the lifetime
1648/// of the call.
1649///
1650/// The caller must not race this call with concurrent mutation of the
1651/// same objects from other threads (per-object state is not internally
1652/// synchronized). Violating any of the above is undefined behavior.
1653///
1654/// Exercised by the C-API differential courts
1655/// (courts/suites/data-abi/*-family-probe.c) and the CLI differential
1656/// courts; those pass byte-for-byte against the upstream oracle.
1657#[no_mangle]
1658pub unsafe extern "C" fn xmlCtxtReadMemory(
1659 ctxt: *mut _xmlParserCtxt,
1660 buffer: *const c_char,
1661 size: c_int,
1662 URL: *const c_char,
1663 _encoding: *const c_char,
1664 options: c_int,
1665) -> *mut _xmlDoc {
1666 if ctxt.is_null() || buffer.is_null() || size < 0 {
1667 return ptr::null_mut();
1668 }
1669 unsafe {
1670 let input = helpers::input_from_memory(buffer, size);
1671 ctxt_read_doc(ctxt, input, URL, options)
1672 }
1673}
1674
1675/// Parse an XML document from a file descriptor with a given context.
1676///
1677/// # UPSTREAM-PARITY
1678///
1679/// ```c
1680/// xmlDocPtr xmlCtxtReadFd(xmlParserCtxtPtr ctxt, int fd, const char *URL,
1681/// const char *encoding, int options);
1682/// ```
1683///
1684/// # SAFETY
1685///
1686/// - `ctxt` must be valid pointers (or NULL
1687/// where the upstream C contract allows), obtained from the
1688/// matching constructor/owner and not yet freed; the callee may
1689/// take or keep ownership exactly as the C API specifies.
1690///
1691/// - `URL`, `_encoding` must point to valid NUL-terminated
1692/// strings (or NULL where the C contract allows) for the lifetime
1693/// of the call.
1694///
1695/// The caller must not race this call with concurrent mutation of the
1696/// same objects from other threads (per-object state is not internally
1697/// synchronized). Violating any of the above is undefined behavior.
1698///
1699/// Exercised by the C-API differential courts
1700/// (courts/suites/data-abi/*-family-probe.c) and the CLI differential
1701/// courts; those pass byte-for-byte against the upstream oracle.
1702#[no_mangle]
1703pub unsafe extern "C" fn xmlCtxtReadFd(
1704 ctxt: *mut _xmlParserCtxt,
1705 fd: c_int,
1706 URL: *const c_char,
1707 _encoding: *const c_char,
1708 options: c_int,
1709) -> *mut _xmlDoc {
1710 if ctxt.is_null() || fd < 0 {
1711 return ptr::null_mut();
1712 }
1713 unsafe {
1714 let mut buf = Vec::new();
1715 let mut tmp = [0u8; 4096];
1716 loop {
1717 let n = libc::read(fd, tmp.as_mut_ptr() as *mut c_void, tmp.len());
1718 if n <= 0 {
1719 break;
1720 }
1721 buf.extend_from_slice(&tmp[..n as usize]);
1722 }
1723 let input = helpers::input_from_memory(buf.as_ptr() as *const c_char, buf.len() as c_int);
1724 ctxt_read_doc(ctxt, input, URL, options)
1725 }
1726}
1727
1728/// Parse an XML document from I/O callbacks with a given context.
1729///
1730/// # UPSTREAM-PARITY
1731///
1732/// ```c
1733/// xmlDocPtr xmlCtxtReadIO(xmlParserCtxtPtr ctxt, xmlInputReadCallback ioread,
1734/// xmlInputCloseCallback ioclose, void *ioctx,
1735/// const char *URL, const char *encoding, int options);
1736/// ```
1737///
1738/// # SAFETY
1739///
1740/// - `ctxt`, `ioctx` must be valid pointers (or NULL
1741/// where the upstream C contract allows), obtained from the
1742/// matching constructor/owner and not yet freed; the callee may
1743/// take or keep ownership exactly as the C API specifies.
1744///
1745/// - `URL`, `_encoding` must point to valid NUL-terminated
1746/// strings (or NULL where the C contract allows) for the lifetime
1747/// of the call.
1748///
1749/// - `ioread`, `ioclose` must be a valid callback (or None);
1750/// the callback is invoked with the documented context pointer and
1751/// must itself uphold the same pointer invariants.
1752///
1753/// The caller must not race this call with concurrent mutation of the
1754/// same objects from other threads (per-object state is not internally
1755/// synchronized). Violating any of the above is undefined behavior.
1756///
1757/// Exercised by the C-API differential courts
1758/// (courts/suites/data-abi/*-family-probe.c) and the CLI differential
1759/// courts; those pass byte-for-byte against the upstream oracle.
1760#[no_mangle]
1761pub unsafe extern "C" fn xmlCtxtReadIO(
1762 ctxt: *mut _xmlParserCtxt,
1763 ioread: Option<xmlInputReadCallback>,
1764 ioclose: Option<xmlInputCloseCallback>,
1765 ioctx: *mut c_void,
1766 URL: *const c_char,
1767 _encoding: *const c_char,
1768 options: c_int,
1769) -> *mut _xmlDoc {
1770 if ctxt.is_null() {
1771 return ptr::null_mut();
1772 }
1773 unsafe {
1774 let input = helpers::input_from_io(ioread, ioclose, ioctx);
1775 ctxt_read_doc(ctxt, input, URL, options)
1776 }
1777}
1778
1779/// Parse a document from a raw parser input, taking ownership of `input`.
1780///
1781/// # UPSTREAM-PARITY
1782///
1783/// ```c
1784/// xmlDocPtr xmlCtxtParseDocument(xmlParserCtxtPtr ctxt, xmlParserInputPtr input);
1785/// ```
1786///
1787/// # SAFETY
1788///
1789/// - `ctxt`, `input` must be valid pointers (or NULL
1790/// where the upstream C contract allows), obtained from the
1791/// matching constructor/owner and not yet freed; the callee may
1792/// take or keep ownership exactly as the C API specifies.
1793///
1794/// The caller must not race this call with concurrent mutation of the
1795/// same objects from other threads (per-object state is not internally
1796/// synchronized). Violating any of the above is undefined behavior.
1797///
1798/// Exercised by the C-API differential courts
1799/// (courts/suites/data-abi/*-family-probe.c) and the CLI differential
1800/// courts; those pass byte-for-byte against the upstream oracle.
1801#[no_mangle]
1802pub unsafe extern "C" fn xmlCtxtParseDocument(
1803 ctxt: *mut _xmlParserCtxt,
1804 input: *mut _xmlParserInput,
1805) -> *mut _xmlDoc {
1806 if ctxt.is_null() || input.is_null() {
1807 return ptr::null_mut();
1808 }
1809 unsafe {
1810 // Determine whether the caller's input is already owned by the
1811 // context's input stack (pushed via xmlPushInput).
1812 let mut owned = false;
1813 let nr = (*ctxt).inputNr;
1814 let tab = (*ctxt).inputTab;
1815 if !tab.is_null() {
1816 for i in 0..nr {
1817 if *tab.add(i as usize) == input {
1818 owned = true;
1819 break;
1820 }
1821 }
1822 }
1823 if (*ctxt).input == input {
1824 owned = true;
1825 }
1826
1827 // Copy the data first so the context reset cannot invalidate it.
1828 let ib = input_buffer_from_parser_input(input);
1829
1830 xmlCtxtReset(ctxt);
1831 helpers::setup_parser_input(ctxt, ib);
1832 helpers::parse_document(ctxt);
1833
1834 if !owned {
1835 helpers::free_parser_input(input);
1836 }
1837
1838 (*ctxt).myDoc
1839 }
1840}
1841
1842// ═══════════════════════════════════════════════════════════════════════════════
1843// Parser input buffers / streams
1844// ═══════════════════════════════════════════════════════════════════════════════
1845
1846/// Allocate a parser input buffer for the given encoding.
1847///
1848/// # UPSTREAM-PARITY
1849///
1850/// ```c
1851/// xmlParserInputBufferPtr xmlAllocParserInputBuffer(xmlCharEncoding enc);
1852/// ```
1853///
1854/// # SAFETY
1855///
1856/// The function touches crate-global state only; it is safe
1857/// as long as the caller respects the library's global
1858/// initialization/cleanup ordering (xmlInitParser before use,
1859/// xmlCleanupParser only after all users are done).
1860///
1861/// Violating the global lifecycle ordering, or calling this after
1862/// teardown or from a signal handler, is undefined behavior.
1863#[no_mangle]
1864pub unsafe extern "C" fn xmlAllocParserInputBuffer(enc: c_int) -> *mut _xmlParserInputBuffer {
1865 unsafe {
1866 let buf = xmlMallocZero(core::mem::size_of::<_xmlParserInputBuffer>())
1867 as *mut _xmlParserInputBuffer;
1868 if buf.is_null() {
1869 return ptr::null_mut();
1870 }
1871 let b = &mut *buf;
1872 b.buffer = io::buf_create(crate::abi::data_globals::xmlDefaultBufferSize) as *mut c_void;
1873 b.raw = io::buf_create(crate::abi::data_globals::xmlDefaultBufferSize) as *mut c_void;
1874 if b.buffer.is_null() || b.raw.is_null() {
1875 io::buf_free(b.buffer as *mut _xmlBuffer);
1876 io::buf_free(b.raw as *mut _xmlBuffer);
1877 xmlFreeImpl(buf as *mut c_void);
1878 return ptr::null_mut();
1879 }
1880 b.compressed = -1;
1881
1882 if enc != xmlCharEncoding::XML_CHAR_ENCODING_NONE as c_int
1883 && enc != xmlCharEncoding::XML_CHAR_ENCODING_ERROR as c_int
1884 {
1885 let handler = encoding_handler_for(enc);
1886 if !handler.is_null() {
1887 b.encoder = handler as *mut c_void;
1888 }
1889 }
1890 buf
1891 }
1892}
1893
1894/// Grow an input buffer by reading up to `len` bytes from its source.
1895///
1896/// # UPSTREAM-PARITY
1897///
1898/// ```c
1899/// int xmlParserInputBufferGrow(xmlParserInputBufferPtr in, int len);
1900/// ```
1901///
1902/// # SAFETY
1903///
1904/// - `in_` must be valid pointers (or NULL
1905/// where the upstream C contract allows), obtained from the
1906/// matching constructor/owner and not yet freed; the callee may
1907/// take or keep ownership exactly as the C API specifies.
1908///
1909/// The caller must not race this call with concurrent mutation of the
1910/// same objects from other threads (per-object state is not internally
1911/// synchronized). Violating any of the above is undefined behavior.
1912///
1913/// Exercised by the C-API differential courts
1914/// (courts/suites/data-abi/*-family-probe.c) and the CLI differential
1915/// courts; those pass byte-for-byte against the upstream oracle.
1916#[no_mangle]
1917pub unsafe extern "C" fn xmlParserInputBufferGrow(
1918 in_: *mut _xmlParserInputBuffer,
1919 len: c_int,
1920) -> c_int {
1921 if in_.is_null() || len <= 0 {
1922 return 0;
1923 }
1924 unsafe {
1925 let b = &mut *in_;
1926 if b.error != 0 {
1927 return -1;
1928 }
1929 let Some(read_cb) = b.readcallback else {
1930 // Memory-based buffer: nothing to grow.
1931 return 0;
1932 };
1933 let mut tmp = vec![0u8; len as usize];
1934 let n = read_cb(b.context, tmp.as_mut_ptr() as *mut c_char, len);
1935 if n < 0 {
1936 b.error = 1;
1937 return -1;
1938 }
1939 if n == 0 {
1940 return 0;
1941 }
1942 io::input_buffer_push(in_, tmp.as_ptr() as *const c_char, n);
1943 n
1944 }
1945}
1946
1947/// Push `len` bytes into an input buffer (push parser).
1948///
1949/// # UPSTREAM-PARITY
1950///
1951/// ```c
1952/// int xmlParserInputBufferPush(xmlParserInputBufferPtr in, int len, const char *buf);
1953/// ```
1954///
1955/// # SAFETY
1956///
1957/// - `in_` must be valid pointers (or NULL
1958/// where the upstream C contract allows), obtained from the
1959/// matching constructor/owner and not yet freed; the callee may
1960/// take or keep ownership exactly as the C API specifies.
1961///
1962/// - `buf` must point to valid NUL-terminated
1963/// strings (or NULL where the C contract allows) for the lifetime
1964/// of the call.
1965///
1966/// The caller must not race this call with concurrent mutation of the
1967/// same objects from other threads (per-object state is not internally
1968/// synchronized). Violating any of the above is undefined behavior.
1969///
1970/// Exercised by the C-API differential courts
1971/// (courts/suites/data-abi/*-family-probe.c) and the CLI differential
1972/// courts; those pass byte-for-byte against the upstream oracle.
1973#[no_mangle]
1974pub unsafe extern "C" fn xmlParserInputBufferPush(
1975 in_: *mut _xmlParserInputBuffer,
1976 len: c_int,
1977 buf: *const c_char,
1978) -> c_int {
1979 if in_.is_null() {
1980 return -1;
1981 }
1982 if len < 0 || (len > 0 && buf.is_null()) {
1983 return -1;
1984 }
1985 if len == 0 {
1986 return 0;
1987 }
1988 io::input_buffer_push(in_, buf, len)
1989}
1990
1991/// Read up to `len` bytes from an input buffer's source.
1992///
1993/// # UPSTREAM-PARITY
1994///
1995/// ```c
1996/// int xmlParserInputBufferRead(xmlParserInputBufferPtr in, int len);
1997/// ```
1998///
1999/// # SAFETY
2000///
2001/// - `in_` must be valid pointers (or NULL
2002/// where the upstream C contract allows), obtained from the
2003/// matching constructor/owner and not yet freed; the callee may
2004/// take or keep ownership exactly as the C API specifies.
2005///
2006/// The caller must not race this call with concurrent mutation of the
2007/// same objects from other threads (per-object state is not internally
2008/// synchronized). Violating any of the above is undefined behavior.
2009///
2010/// Exercised by the C-API differential courts
2011/// (courts/suites/data-abi/*-family-probe.c) and the CLI differential
2012/// courts; those pass byte-for-byte against the upstream oracle.
2013#[no_mangle]
2014pub unsafe extern "C" fn xmlParserInputBufferRead(
2015 in_: *mut _xmlParserInputBuffer,
2016 len: c_int,
2017) -> c_int {
2018 xmlParserInputBufferGrow(in_, len)
2019}
2020
2021/// Deprecated: reading directly from an input stream is an error.
2022///
2023/// # UPSTREAM-PARITY
2024///
2025/// ```c
2026/// int xmlParserInputRead(xmlParserInputPtr in, int len);
2027/// ```
2028///
2029/// # SAFETY
2030///
2031/// - `_in_` must be valid pointers (or NULL
2032/// where the upstream C contract allows), obtained from the
2033/// matching constructor/owner and not yet freed; the callee may
2034/// take or keep ownership exactly as the C API specifies.
2035///
2036/// The caller must not race this call with concurrent mutation of the
2037/// same objects from other threads (per-object state is not internally
2038/// synchronized). Violating any of the above is undefined behavior.
2039///
2040/// Exercised by the C-API differential courts
2041/// (courts/suites/data-abi/*-family-probe.c) and the CLI differential
2042/// courts; those pass byte-for-byte against the upstream oracle.
2043#[no_mangle]
2044pub const unsafe extern "C" fn xmlParserInputRead(
2045 _in_: *mut _xmlParserInput,
2046 _len: c_int,
2047) -> c_int {
2048 -1
2049}
2050
2051/// Grow a parser input's buffer by reading more data from its source.
2052///
2053/// # UPSTREAM-PARITY
2054///
2055/// ```c
2056/// int xmlParserInputGrow(xmlParserInputPtr in, int len);
2057/// ```
2058///
2059/// # SAFETY
2060///
2061/// - `in_` must be valid pointers (or NULL
2062/// where the upstream C contract allows), obtained from the
2063/// matching constructor/owner and not yet freed; the callee may
2064/// take or keep ownership exactly as the C API specifies.
2065///
2066/// The caller must not race this call with concurrent mutation of the
2067/// same objects from other threads (per-object state is not internally
2068/// synchronized). Violating any of the above is undefined behavior.
2069///
2070/// Exercised by the C-API differential courts
2071/// (courts/suites/data-abi/*-family-probe.c) and the CLI differential
2072/// courts; those pass byte-for-byte against the upstream oracle.
2073#[no_mangle]
2074pub unsafe extern "C" fn xmlParserInputGrow(in_: *mut _xmlParserInput, len: c_int) -> c_int {
2075 if in_.is_null() || len < 0 {
2076 return -1;
2077 }
2078 unsafe {
2079 let pi = &*in_;
2080 if pi.base.is_null() || pi.cur.is_null() {
2081 return -1;
2082 }
2083 if pi.buf.is_null() {
2084 // Pure memory input: nothing to grow.
2085 return 0;
2086 }
2087 let b = &*pi.buf;
2088 // Memory buffers are not growable.
2089 if b.readcallback.is_none() && b.encoder.is_null() {
2090 return 0;
2091 }
2092 xmlParserInputBufferGrow(pi.buf, len)
2093 }
2094}
2095
2096/// Shrink a parser input, releasing already-consumed data from the buffer.
2097///
2098/// # UPSTREAM-PARITY
2099///
2100/// ```c
2101/// void xmlParserInputShrink(xmlParserInputPtr in);
2102/// ```
2103///
2104/// # SAFETY
2105///
2106/// - `in_` must be valid pointers (or NULL
2107/// where the upstream C contract allows), obtained from the
2108/// matching constructor/owner and not yet freed; the callee may
2109/// take or keep ownership exactly as the C API specifies.
2110///
2111/// The caller must not race this call with concurrent mutation of the
2112/// same objects from other threads (per-object state is not internally
2113/// synchronized). Violating any of the above is undefined behavior.
2114///
2115/// Exercised by the C-API differential courts
2116/// (courts/suites/data-abi/*-family-probe.c) and the CLI differential
2117/// courts; those pass byte-for-byte against the upstream oracle.
2118#[no_mangle]
2119pub unsafe extern "C" fn xmlParserInputShrink(in_: *mut _xmlParserInput) {
2120 if in_.is_null() {
2121 return;
2122 }
2123 unsafe {
2124 let pi = &mut *in_;
2125 if pi.buf.is_null() || pi.base.is_null() || pi.cur.is_null() {
2126 return;
2127 }
2128 let used = (pi.cur as usize).saturating_sub(pi.base as usize);
2129 if used > LINE_LEN {
2130 // The candidate's inputs are backed by stable memory buffers, so
2131 // the base pointer cannot move; account for the consumed bytes.
2132 pi.consumed = pi.consumed.saturating_add((used - LINE_LEN) as c_ulong);
2133 }
2134 }
2135}
2136
2137/// Create a new (empty) parser input stream.
2138///
2139/// # UPSTREAM-PARITY
2140///
2141/// ```c
2142/// xmlParserInputPtr xmlNewInputStream(xmlParserCtxtPtr ctxt);
2143/// ```
2144///
2145/// # SAFETY
2146///
2147/// - `ctxt` must be valid pointers (or NULL
2148/// where the upstream C contract allows), obtained from the
2149/// matching constructor/owner and not yet freed; the callee may
2150/// take or keep ownership exactly as the C API specifies.
2151///
2152/// The caller must not race this call with concurrent mutation of the
2153/// same objects from other threads (per-object state is not internally
2154/// synchronized). Violating any of the above is undefined behavior.
2155///
2156/// Exercised by the C-API differential courts
2157/// (courts/suites/data-abi/*-family-probe.c) and the CLI differential
2158/// courts; those pass byte-for-byte against the upstream oracle.
2159#[no_mangle]
2160pub unsafe extern "C" fn xmlNewInputStream(ctxt: *mut _xmlParserCtxt) -> *mut _xmlParserInput {
2161 unsafe {
2162 let input = xmlMallocZero(core::mem::size_of::<_xmlParserInput>()) as *mut _xmlParserInput;
2163 if input.is_null() {
2164 if !ctxt.is_null() {
2165 xmlCtxtErrMemory(ctxt);
2166 }
2167 return ptr::null_mut();
2168 }
2169 (*input).line = 1;
2170 (*input).col = 1;
2171 input
2172 }
2173}
2174
2175/// Wrap an input buffer in a parser input stream.
2176///
2177/// # UPSTREAM-PARITY
2178///
2179/// ```c
2180/// xmlParserInputPtr xmlNewIOInputStream(xmlParserCtxtPtr ctxt,
2181/// xmlParserInputBufferPtr input,
2182/// xmlCharEncoding enc);
2183/// ```
2184///
2185/// # SAFETY
2186///
2187/// - `ctxt`, `input` must be valid pointers (or NULL
2188/// where the upstream C contract allows), obtained from the
2189/// matching constructor/owner and not yet freed; the callee may
2190/// take or keep ownership exactly as the C API specifies.
2191///
2192/// The caller must not race this call with concurrent mutation of the
2193/// same objects from other threads (per-object state is not internally
2194/// synchronized). Violating any of the above is undefined behavior.
2195///
2196/// Exercised by the C-API differential courts
2197/// (courts/suites/data-abi/*-family-probe.c) and the CLI differential
2198/// courts; those pass byte-for-byte against the upstream oracle.
2199#[no_mangle]
2200pub unsafe extern "C" fn xmlNewIOInputStream(
2201 ctxt: *mut _xmlParserCtxt,
2202 input: *mut _xmlParserInputBuffer,
2203 enc: c_int,
2204) -> *mut _xmlParserInput {
2205 if ctxt.is_null() || input.is_null() {
2206 return ptr::null_mut();
2207 }
2208 unsafe {
2209 let pi = xmlNewInputStream(ctxt);
2210 if pi.is_null() {
2211 return ptr::null_mut();
2212 }
2213 (*pi).buf = input;
2214 if enc != xmlCharEncoding::XML_CHAR_ENCODING_NONE as c_int
2215 && enc != xmlCharEncoding::XML_CHAR_ENCODING_ERROR as c_int
2216 {
2217 let handler = encoding_handler_for(enc);
2218 if !handler.is_null() {
2219 io::input_buffer_set_encoder(input, handler);
2220 }
2221 }
2222 pi
2223 }
2224}
2225
2226/// Create a parser input stream from a zero-terminated string. The string
2227/// must remain valid for the lifetime of the input (static mode).
2228///
2229/// # UPSTREAM-PARITY
2230///
2231/// ```c
2232/// xmlParserInputPtr xmlNewStringInputStream(xmlParserCtxtPtr ctxt,
2233/// const xmlChar *buffer);
2234/// ```
2235///
2236/// # SAFETY
2237///
2238/// - `ctxt` must be valid pointers (or NULL
2239/// where the upstream C contract allows), obtained from the
2240/// matching constructor/owner and not yet freed; the callee may
2241/// take or keep ownership exactly as the C API specifies.
2242///
2243/// - `buffer` must point to valid NUL-terminated
2244/// strings (or NULL where the C contract allows) for the lifetime
2245/// of the call.
2246///
2247/// The caller must not race this call with concurrent mutation of the
2248/// same objects from other threads (per-object state is not internally
2249/// synchronized). Violating any of the above is undefined behavior.
2250///
2251/// Exercised by the C-API differential courts
2252/// (courts/suites/data-abi/*-family-probe.c) and the CLI differential
2253/// courts; those pass byte-for-byte against the upstream oracle.
2254#[no_mangle]
2255pub unsafe extern "C" fn xmlNewStringInputStream(
2256 ctxt: *mut _xmlParserCtxt,
2257 buffer: *const xmlChar,
2258) -> *mut _xmlParserInput {
2259 if ctxt.is_null() || buffer.is_null() {
2260 return ptr::null_mut();
2261 }
2262 unsafe {
2263 let input = xmlNewInputStream(ctxt);
2264 if input.is_null() {
2265 return ptr::null_mut();
2266 }
2267 let len = string::xml_strlen(buffer);
2268 (*input).base = buffer;
2269 (*input).cur = buffer;
2270 (*input).end = buffer.add(len);
2271 (*input).length = len as c_int;
2272 input
2273 }
2274}
2275
2276/// Setup the parser context to parse a new buffer (legacy API).
2277///
2278/// # UPSTREAM-PARITY
2279///
2280/// ```c
2281/// void xmlSetupParserForBuffer(xmlParserCtxtPtr ctxt, const xmlChar* buffer,
2282/// const char *filename);
2283/// ```
2284///
2285/// # SAFETY
2286///
2287/// - `ctxt` must be valid pointers (or NULL
2288/// where the upstream C contract allows), obtained from the
2289/// matching constructor/owner and not yet freed; the callee may
2290/// take or keep ownership exactly as the C API specifies.
2291///
2292/// - `buffer`, `filename` must point to valid NUL-terminated
2293/// strings (or NULL where the C contract allows) for the lifetime
2294/// of the call.
2295///
2296/// The caller must not race this call with concurrent mutation of the
2297/// same objects from other threads (per-object state is not internally
2298/// synchronized). Violating any of the above is undefined behavior.
2299///
2300/// Exercised by the C-API differential courts
2301/// (courts/suites/data-abi/*-family-probe.c) and the CLI differential
2302/// courts; those pass byte-for-byte against the upstream oracle.
2303#[no_mangle]
2304pub unsafe extern "C" fn xmlSetupParserForBuffer(
2305 ctxt: *mut _xmlParserCtxt,
2306 buffer: *const xmlChar,
2307 filename: *const c_char,
2308) {
2309 if ctxt.is_null() || buffer.is_null() {
2310 return;
2311 }
2312 unsafe {
2313 xmlCtxtReset(ctxt);
2314 let len = string::xml_strlen(buffer);
2315 let uri = if filename.is_null() {
2316 None
2317 } else {
2318 CStr::from_ptr(filename).to_str().ok()
2319 };
2320 let input = InputBuffer::from_memory(core::slice::from_raw_parts(buffer, len), uri);
2321 helpers::setup_parser_input(ctxt, input);
2322 }
2323}
2324
2325/// Push an input stream onto the context's input stack.
2326///
2327/// # UPSTREAM-PARITY
2328///
2329/// ```c
2330/// int xmlPushInput(xmlParserCtxtPtr ctxt, xmlParserInputPtr input);
2331/// ```
2332///
2333/// # SAFETY
2334///
2335/// - `ctxt`, `input` must be valid pointers (or NULL
2336/// where the upstream C contract allows), obtained from the
2337/// matching constructor/owner and not yet freed; the callee may
2338/// take or keep ownership exactly as the C API specifies.
2339///
2340/// The caller must not race this call with concurrent mutation of the
2341/// same objects from other threads (per-object state is not internally
2342/// synchronized). Violating any of the above is undefined behavior.
2343///
2344/// Exercised by the C-API differential courts
2345/// (courts/suites/data-abi/*-family-probe.c) and the CLI differential
2346/// courts; those pass byte-for-byte against the upstream oracle.
2347#[no_mangle]
2348pub unsafe extern "C" fn xmlPushInput(
2349 ctxt: *mut _xmlParserCtxt,
2350 input: *mut _xmlParserInput,
2351) -> c_int {
2352 if ctxt.is_null() || input.is_null() {
2353 return -1;
2354 }
2355 unsafe {
2356 let c = &mut *ctxt;
2357 if c.inputNr >= c.inputMax {
2358 let new_max = if c.inputMax == 0 { 5 } else { c.inputMax * 2 };
2359 let new_tab = xmlReallocImpl(
2360 c.inputTab as *mut c_void,
2361 (new_max as usize) * core::mem::size_of::<*mut _xmlParserInput>(),
2362 ) as *mut *mut _xmlParserInput;
2363 if new_tab.is_null() {
2364 return -1;
2365 }
2366 c.inputTab = new_tab;
2367 c.inputMax = new_max;
2368 }
2369 *c.inputTab.add(c.inputNr as usize) = input;
2370 c.input = input;
2371 (*input).id = c.input_id;
2372 c.input_id += 1;
2373 let idx = c.inputNr;
2374 c.inputNr += 1;
2375 idx
2376 }
2377}
2378
2379/// Pop the top input from the context's input stack and free it; returns the
2380/// current character after the pop (0 at end of input).
2381///
2382/// # UPSTREAM-PARITY
2383///
2384/// ```c
2385/// xmlChar xmlPopInput(xmlParserCtxtPtr ctxt);
2386/// ```
2387///
2388/// # SAFETY
2389///
2390/// - `ctxt` must be valid pointers (or NULL
2391/// where the upstream C contract allows), obtained from the
2392/// matching constructor/owner and not yet freed; the callee may
2393/// take or keep ownership exactly as the C API specifies.
2394///
2395/// The caller must not race this call with concurrent mutation of the
2396/// same objects from other threads (per-object state is not internally
2397/// synchronized). Violating any of the above is undefined behavior.
2398///
2399/// Exercised by the C-API differential courts
2400/// (courts/suites/data-abi/*-family-probe.c) and the CLI differential
2401/// courts; those pass byte-for-byte against the upstream oracle.
2402#[no_mangle]
2403pub unsafe extern "C" fn xmlPopInput(ctxt: *mut _xmlParserCtxt) -> xmlChar {
2404 if ctxt.is_null() || (*ctxt).inputNr <= 1 {
2405 return 0;
2406 }
2407 unsafe {
2408 let c = &mut *ctxt;
2409 c.inputNr -= 1;
2410 let popped = *c.inputTab.add(c.inputNr as usize);
2411 *c.inputTab.add(c.inputNr as usize) = ptr::null_mut();
2412 if c.inputNr > 0 {
2413 c.input = *c.inputTab.add((c.inputNr - 1) as usize);
2414 } else {
2415 c.input = ptr::null_mut();
2416 }
2417 if !popped.is_null() {
2418 helpers::free_parser_input(popped);
2419 }
2420 if c.input.is_null() {
2421 return 0;
2422 }
2423 let cur = (*c.input).cur;
2424 let end = (*c.input).end;
2425 if cur.is_null() || cur >= end {
2426 0
2427 } else {
2428 *cur
2429 }
2430 }
2431}
2432
2433// ═══════════════════════════════════════════════════════════════════════════════
2434// Encoding switching
2435// ═══════════════════════════════════════════════════════════════════════════════
2436
2437/// Switch the input encoding of the current input.
2438///
2439/// # UPSTREAM-PARITY
2440///
2441/// ```c
2442/// int xmlSwitchEncoding(xmlParserCtxtPtr ctxt, xmlCharEncoding enc);
2443/// ```
2444///
2445/// # SAFETY
2446///
2447/// - `ctxt` must be valid pointers (or NULL
2448/// where the upstream C contract allows), obtained from the
2449/// matching constructor/owner and not yet freed; the callee may
2450/// take or keep ownership exactly as the C API specifies.
2451///
2452/// The caller must not race this call with concurrent mutation of the
2453/// same objects from other threads (per-object state is not internally
2454/// synchronized). Violating any of the above is undefined behavior.
2455///
2456/// Exercised by the C-API differential courts
2457/// (courts/suites/data-abi/*-family-probe.c) and the CLI differential
2458/// courts; those pass byte-for-byte against the upstream oracle.
2459#[no_mangle]
2460pub unsafe extern "C" fn xmlSwitchEncoding(ctxt: *mut _xmlParserCtxt, enc: c_int) -> c_int {
2461 if ctxt.is_null() || (*ctxt).input.is_null() {
2462 return -1;
2463 }
2464 if enc == xmlCharEncoding::XML_CHAR_ENCODING_NONE as c_int {
2465 return 0;
2466 }
2467 unsafe {
2468 let handler = encoding_handler_for(enc);
2469 if handler.is_null() {
2470 return -1;
2471 }
2472 xmlSwitchToEncoding(ctxt, handler)
2473 }
2474}
2475
2476/// Switch the input encoding by name.
2477///
2478/// # UPSTREAM-PARITY
2479///
2480/// ```c
2481/// int xmlSwitchEncodingName(xmlParserCtxtPtr ctxt, const char *encoding);
2482/// ```
2483///
2484/// # SAFETY
2485///
2486/// - `ctxt` must be valid pointers (or NULL
2487/// where the upstream C contract allows), obtained from the
2488/// matching constructor/owner and not yet freed; the callee may
2489/// take or keep ownership exactly as the C API specifies.
2490///
2491/// - `encoding` must point to valid NUL-terminated
2492/// strings (or NULL where the C contract allows) for the lifetime
2493/// of the call.
2494///
2495/// The caller must not race this call with concurrent mutation of the
2496/// same objects from other threads (per-object state is not internally
2497/// synchronized). Violating any of the above is undefined behavior.
2498///
2499/// Exercised by the C-API differential courts
2500/// (courts/suites/data-abi/*-family-probe.c) and the CLI differential
2501/// courts; those pass byte-for-byte against the upstream oracle.
2502#[no_mangle]
2503pub unsafe extern "C" fn xmlSwitchEncodingName(
2504 ctxt: *mut _xmlParserCtxt,
2505 encoding: *const c_char,
2506) -> c_int {
2507 if ctxt.is_null() || encoding.is_null() {
2508 return -1;
2509 }
2510 unsafe {
2511 let handler = encoding::find_encoding_handler(encoding as *const xmlChar);
2512 if handler.is_null() {
2513 return -1;
2514 }
2515 xmlSwitchToEncoding(ctxt, handler)
2516 }
2517}
2518
2519/// Switch the encoding of a specific parser input using an encoding handler.
2520///
2521/// # UPSTREAM-PARITY
2522///
2523/// ```c
2524/// int xmlSwitchInputEncoding(xmlParserCtxtPtr ctxt, xmlParserInputPtr input,
2525/// xmlCharEncodingHandlerPtr handler);
2526/// ```
2527///
2528/// # SAFETY
2529///
2530/// - `ctxt`, `input`, `handler` must be valid pointers (or NULL
2531/// where the upstream C contract allows), obtained from the
2532/// matching constructor/owner and not yet freed; the callee may
2533/// take or keep ownership exactly as the C API specifies.
2534///
2535/// The caller must not race this call with concurrent mutation of the
2536/// same objects from other threads (per-object state is not internally
2537/// synchronized). Violating any of the above is undefined behavior.
2538///
2539/// Exercised by the C-API differential courts
2540/// (courts/suites/data-abi/*-family-probe.c) and the CLI differential
2541/// courts; those pass byte-for-byte against the upstream oracle.
2542#[no_mangle]
2543pub unsafe extern "C" fn xmlSwitchInputEncoding(
2544 ctxt: *mut _xmlParserCtxt,
2545 input: *mut _xmlParserInput,
2546 handler: *mut _xmlCharEncodingHandler,
2547) -> c_int {
2548 let _ = ctxt;
2549 if input.is_null() {
2550 return -1;
2551 }
2552 unsafe {
2553 if (*input).buf.is_null() {
2554 return -1;
2555 }
2556 io::input_buffer_set_encoder((*input).buf, handler);
2557 }
2558 0
2559}
2560
2561/// Switch the encoding of the current input using an encoding handler.
2562///
2563/// # UPSTREAM-PARITY
2564///
2565/// ```c
2566/// int xmlSwitchToEncoding(xmlParserCtxtPtr ctxt,
2567/// xmlCharEncodingHandlerPtr handler);
2568/// ```
2569///
2570/// # SAFETY
2571///
2572/// - `ctxt`, `handler` must be valid pointers (or NULL
2573/// where the upstream C contract allows), obtained from the
2574/// matching constructor/owner and not yet freed; the callee may
2575/// take or keep ownership exactly as the C API specifies.
2576///
2577/// The caller must not race this call with concurrent mutation of the
2578/// same objects from other threads (per-object state is not internally
2579/// synchronized). Violating any of the above is undefined behavior.
2580///
2581/// Exercised by the C-API differential courts
2582/// (courts/suites/data-abi/*-family-probe.c) and the CLI differential
2583/// courts; those pass byte-for-byte against the upstream oracle.
2584#[no_mangle]
2585pub unsafe extern "C" fn xmlSwitchToEncoding(
2586 ctxt: *mut _xmlParserCtxt,
2587 handler: *mut _xmlCharEncodingHandler,
2588) -> c_int {
2589 if ctxt.is_null() {
2590 return -1;
2591 }
2592 unsafe {
2593 let input = (*ctxt).input;
2594 if input.is_null() || (*input).buf.is_null() {
2595 return -1;
2596 }
2597 io::input_buffer_set_encoder((*input).buf, handler);
2598 }
2599 0
2600}
2601
2602// ═══════════════════════════════════════════════════════════════════════════════
2603// Node info sequence (deprecated, parser.h)
2604// ═══════════════════════════════════════════════════════════════════════════════
2605
2606/// Initialise a node info sequence.
2607///
2608/// # UPSTREAM-PARITY
2609///
2610/// ```c
2611/// void xmlInitNodeInfoSeq(xmlParserNodeInfoSeqPtr seq);
2612/// ```
2613///
2614/// # SAFETY
2615///
2616/// - `seq` must be valid pointers (or NULL
2617/// where the upstream C contract allows), obtained from the
2618/// matching constructor/owner and not yet freed; the callee may
2619/// take or keep ownership exactly as the C API specifies.
2620///
2621/// The caller must not race this call with concurrent mutation of the
2622/// same objects from other threads (per-object state is not internally
2623/// synchronized). Violating any of the above is undefined behavior.
2624///
2625/// Exercised by the C-API differential courts
2626/// (courts/suites/data-abi/*-family-probe.c) and the CLI differential
2627/// courts; those pass byte-for-byte against the upstream oracle.
2628#[no_mangle]
2629pub unsafe extern "C" fn xmlInitNodeInfoSeq(seq: *mut _xmlParserNodeInfoSeq) {
2630 if seq.is_null() {
2631 return;
2632 }
2633 unsafe {
2634 (*seq).block = ptr::null_mut();
2635 (*seq).index = ptr::null_mut();
2636 (*seq).block_max = 0;
2637 (*seq).size = 0;
2638 }
2639}
2640
2641/// Clear (release and reinitialise) a node info sequence.
2642///
2643/// # UPSTREAM-PARITY
2644///
2645/// ```c
2646/// void xmlClearNodeInfoSeq(xmlParserNodeInfoSeqPtr seq);
2647/// ```
2648///
2649/// # SAFETY
2650///
2651/// - `seq` must be valid pointers (or NULL
2652/// where the upstream C contract allows), obtained from the
2653/// matching constructor/owner and not yet freed; the callee may
2654/// take or keep ownership exactly as the C API specifies.
2655///
2656/// The caller must not race this call with concurrent mutation of the
2657/// same objects from other threads (per-object state is not internally
2658/// synchronized). Violating any of the above is undefined behavior.
2659///
2660/// Exercised by the C-API differential courts
2661/// (courts/suites/data-abi/*-family-probe.c) and the CLI differential
2662/// courts; those pass byte-for-byte against the upstream oracle.
2663#[no_mangle]
2664pub unsafe extern "C" fn xmlClearNodeInfoSeq(seq: *mut _xmlParserNodeInfoSeq) {
2665 if seq.is_null() {
2666 return;
2667 }
2668 unsafe {
2669 if !(*seq).block.is_null() {
2670 xmlFreeImpl((*seq).block as *mut c_void);
2671 }
2672 if !(*seq).index.is_null() {
2673 xmlFreeImpl((*seq).index as *mut c_void);
2674 }
2675 xmlInitNodeInfoSeq(seq);
2676 }
2677}
2678
2679/// Find the index where the info record for `node` is (or should be) in the
2680/// sorted sequence; binary search by node pointer.
2681///
2682/// # UPSTREAM-PARITY
2683///
2684/// ```c
2685/// unsigned long xmlParserFindNodeInfoIndex(xmlParserNodeInfoSeqPtr seq,
2686/// xmlNodePtr node);
2687/// ```
2688///
2689/// # SAFETY
2690///
2691/// - `seq`, `node` must be valid pointers (or NULL
2692/// where the upstream C contract allows), obtained from the
2693/// matching constructor/owner and not yet freed; the callee may
2694/// take or keep ownership exactly as the C API specifies.
2695///
2696/// The caller must not race this call with concurrent mutation of the
2697/// same objects from other threads (per-object state is not internally
2698/// synchronized). Violating any of the above is undefined behavior.
2699///
2700/// Exercised by the C-API differential courts
2701/// (courts/suites/data-abi/*-family-probe.c) and the CLI differential
2702/// courts; those pass byte-for-byte against the upstream oracle.
2703#[no_mangle]
2704pub unsafe extern "C" fn xmlParserFindNodeInfoIndex(
2705 seq: *mut _xmlParserNodeInfoSeq,
2706 node: *mut _xmlNode,
2707) -> c_ulong {
2708 if seq.is_null() || node.is_null() {
2709 return c_ulong::MAX;
2710 }
2711 unsafe {
2712 let s = &*seq;
2713 if s.block.is_null() || s.size == 0 {
2714 return 0;
2715 }
2716 let mut lower: usize = 0;
2717 let mut upper: usize = s.size as usize;
2718 while lower < upper {
2719 let middle = lower + (upper - lower) / 2;
2720 let cur_node = (*s.block.add(middle)).node;
2721 if cur_node == node {
2722 return middle as c_ulong;
2723 }
2724 if (cur_node as usize) < (node as usize) {
2725 lower = middle + 1;
2726 } else {
2727 upper = middle;
2728 }
2729 }
2730 lower as c_ulong
2731 }
2732}
2733
2734/// Find the node info record for a given node, or NULL.
2735///
2736/// # UPSTREAM-PARITY
2737///
2738/// ```c
2739/// const xmlParserNodeInfo *xmlParserFindNodeInfo(xmlParserCtxtPtr ctxt,
2740/// xmlNodePtr node);
2741/// ```
2742///
2743/// # SAFETY
2744///
2745/// - `ctxt`, `node` must be valid pointers (or NULL
2746/// where the upstream C contract allows), obtained from the
2747/// matching constructor/owner and not yet freed; the callee may
2748/// take or keep ownership exactly as the C API specifies.
2749///
2750/// The caller must not race this call with concurrent mutation of the
2751/// same objects from other threads (per-object state is not internally
2752/// synchronized). Violating any of the above is undefined behavior.
2753///
2754/// Exercised by the C-API differential courts
2755/// (courts/suites/data-abi/*-family-probe.c) and the CLI differential
2756/// courts; those pass byte-for-byte against the upstream oracle.
2757#[no_mangle]
2758pub unsafe extern "C" fn xmlParserFindNodeInfo(
2759 ctxt: *mut _xmlParserCtxt,
2760 node: *mut _xmlNode,
2761) -> *const _xmlParserNodeInfo {
2762 if ctxt.is_null() || node.is_null() {
2763 return ptr::null();
2764 }
2765 unsafe {
2766 let seq = &(*ctxt).node_seq;
2767 let seq_mut = seq as *const _ as *mut _xmlParserNodeInfoSeq;
2768 let pos = xmlParserFindNodeInfoIndex(seq_mut, node);
2769 if !seq.block.is_null() && (pos as usize) < (seq.size as usize) {
2770 let info = &*seq.block.add(pos as usize);
2771 if info.node == node {
2772 return info;
2773 }
2774 }
2775 ptr::null()
2776 }
2777}
2778
2779/// Insert a node info record into the context's sorted sequence.
2780///
2781/// # UPSTREAM-PARITY
2782///
2783/// ```c
2784/// void xmlParserAddNodeInfo(xmlParserCtxtPtr ctxt, xmlParserNodeInfoPtr info);
2785/// ```
2786///
2787/// # SAFETY
2788///
2789/// - `ctxt`, `info` must be valid pointers (or NULL
2790/// where the upstream C contract allows), obtained from the
2791/// matching constructor/owner and not yet freed; the callee may
2792/// take or keep ownership exactly as the C API specifies.
2793///
2794/// The caller must not race this call with concurrent mutation of the
2795/// same objects from other threads (per-object state is not internally
2796/// synchronized). Violating any of the above is undefined behavior.
2797///
2798/// Exercised by the C-API differential courts
2799/// (courts/suites/data-abi/*-family-probe.c) and the CLI differential
2800/// courts; those pass byte-for-byte against the upstream oracle.
2801#[no_mangle]
2802pub unsafe extern "C" fn xmlParserAddNodeInfo(
2803 ctxt: *mut _xmlParserCtxt,
2804 info: *mut _xmlParserNodeInfo,
2805) {
2806 if ctxt.is_null() || info.is_null() {
2807 return;
2808 }
2809 unsafe {
2810 let seq = &mut (*ctxt).node_seq;
2811 let node = (*info).node;
2812 let pos = xmlParserFindNodeInfoIndex(seq, node as *mut _xmlNode) as usize;
2813
2814 if !seq.block.is_null() && pos < seq.size as usize && (*seq.block.add(pos)).node == node {
2815 ptr::copy_nonoverlapping(info, seq.block.add(pos), 1);
2816 return;
2817 }
2818
2819 // Grow the block.
2820 if seq.size + 1 > seq.block_max {
2821 let new_max = if seq.block_max == 0 {
2822 4
2823 } else {
2824 seq.block_max * 2
2825 };
2826 let new_block = xmlReallocImpl(
2827 seq.block as *mut c_void,
2828 (new_max as usize) * core::mem::size_of::<_xmlParserNodeInfo>(),
2829 ) as *mut _xmlParserNodeInfo;
2830 if new_block.is_null() {
2831 xmlCtxtErrMemory(ctxt);
2832 return;
2833 }
2834 seq.block = new_block;
2835 seq.block_max = new_max;
2836 }
2837
2838 // Shift elements right to make room at `pos`.
2839 let size = seq.size as usize;
2840 for i in (pos + 1..=size).rev() {
2841 ptr::copy_nonoverlapping(seq.block.add(i - 1), seq.block.add(i), 1);
2842 }
2843 ptr::copy_nonoverlapping(info, seq.block.add(pos), 1);
2844 seq.size += 1;
2845 }
2846}
2847
2848// ═══════════════════════════════════════════════════════════════════════════════
2849// I/O callback registration (xmlIO.h)
2850// ═══════════════════════════════════════════════════════════════════════════════
2851
2852/// Register a new set of input I/O callbacks.
2853///
2854/// # UPSTREAM-PARITY
2855///
2856/// ```c
2857/// int xmlRegisterInputCallbacks(xmlInputMatchCallback matchFunc,
2858/// xmlInputOpenCallback openFunc,
2859/// xmlInputReadCallback readFunc,
2860/// xmlInputCloseCallback closeFunc);
2861/// ```
2862///
2863/// # SAFETY
2864///
2865///
2866/// - `matchFunc`, `openFunc`, `readFunc`, `closeFunc` must be a valid callback (or None);
2867/// the callback is invoked with the documented context pointer and
2868/// must itself uphold the same pointer invariants.
2869///
2870/// The caller must not race this call with concurrent mutation of the
2871/// same objects from other threads (per-object state is not internally
2872/// synchronized). Violating any of the above is undefined behavior.
2873///
2874/// Exercised by the C-API differential courts
2875/// (courts/suites/data-abi/*-family-probe.c) and the CLI differential
2876/// courts; those pass byte-for-byte against the upstream oracle.
2877#[no_mangle]
2878pub unsafe extern "C" fn xmlRegisterInputCallbacks(
2879 matchFunc: Option<xmlInputMatchCallback>,
2880 openFunc: Option<xmlInputOpenCallback>,
2881 readFunc: Option<xmlInputReadCallback>,
2882 closeFunc: Option<xmlInputCloseCallback>,
2883) -> c_int {
2884 unsafe {
2885 globals::init_parser();
2886 }
2887 let mut table = INPUT_CALLBACKS.lock();
2888 if table.len() >= 10 {
2889 return -1;
2890 }
2891 table.push(InputCallbackEntry {
2892 matchcb: matchFunc,
2893 opencb: openFunc,
2894 readcb: readFunc,
2895 closecb: closeFunc,
2896 });
2897 (table.len() - 1) as c_int
2898}
2899
2900/// Register the default compiled-in input callbacks (the `xmlFile*` pair).
2901///
2902/// # UPSTREAM-PARITY
2903///
2904/// ```c
2905/// void xmlRegisterDefaultInputCallbacks(void);
2906/// ```
2907///
2908/// # SAFETY
2909///
2910/// The function touches crate-global state only; it is safe
2911/// as long as the caller respects the library's global
2912/// initialization/cleanup ordering (xmlInitParser before use,
2913/// xmlCleanupParser only after all users are done).
2914///
2915/// Violating the global lifecycle ordering, or calling this after
2916/// teardown or from a signal handler, is undefined behavior.
2917#[no_mangle]
2918pub unsafe extern "C" fn xmlRegisterDefaultInputCallbacks() {
2919 unsafe {
2920 xmlRegisterInputCallbacks(
2921 Some(xmlFileMatch),
2922 Some(xmlFileOpen),
2923 Some(xmlFileRead),
2924 Some(xmlFileClose),
2925 );
2926 }
2927}
2928
2929/// Remove the top input callback from the stack.
2930///
2931/// # UPSTREAM-PARITY
2932///
2933/// ```c
2934/// int xmlPopInputCallbacks(void);
2935/// ```
2936///
2937/// # SAFETY
2938///
2939/// The function touches crate-global state only; it is safe
2940/// as long as the caller respects the library's global
2941/// initialization/cleanup ordering (xmlInitParser before use,
2942/// xmlCleanupParser only after all users are done).
2943///
2944/// Violating the global lifecycle ordering, or calling this after
2945/// teardown or from a signal handler, is undefined behavior.
2946#[no_mangle]
2947pub unsafe extern "C" fn xmlPopInputCallbacks() -> c_int {
2948 unsafe {
2949 globals::init_parser();
2950 }
2951 let mut table = INPUT_CALLBACKS.lock();
2952 if table.is_empty() {
2953 return -1;
2954 }
2955 table.pop();
2956 table.len() as c_int
2957}
2958
2959/// Clear the entire input callback table.
2960///
2961/// # UPSTREAM-PARITY
2962///
2963/// ```c
2964/// void xmlCleanupInputCallbacks(void);
2965/// ```
2966///
2967/// # SAFETY
2968///
2969/// The function touches crate-global state only; it is safe
2970/// as long as the caller respects the library's global
2971/// initialization/cleanup ordering (xmlInitParser before use,
2972/// xmlCleanupParser only after all users are done).
2973///
2974/// Violating the global lifecycle ordering, or calling this after
2975/// teardown or from a signal handler, is undefined behavior.
2976#[no_mangle]
2977pub unsafe extern "C" fn xmlCleanupInputCallbacks() {
2978 unsafe {
2979 globals::init_parser();
2980 }
2981 INPUT_CALLBACKS.lock().clear();
2982}
2983
2984/// Register a new set of output I/O callbacks.
2985///
2986/// # UPSTREAM-PARITY
2987///
2988/// ```c
2989/// int xmlRegisterOutputCallbacks(xmlOutputMatchCallback matchFunc,
2990/// xmlOutputOpenCallback openFunc,
2991/// xmlOutputWriteCallback writeFunc,
2992/// xmlOutputCloseCallback closeFunc);
2993/// ```
2994///
2995/// # SAFETY
2996///
2997///
2998/// - `matchFunc`, `openFunc`, `writeFunc`, `closeFunc` must be a valid callback (or None);
2999/// the callback is invoked with the documented context pointer and
3000/// must itself uphold the same pointer invariants.
3001///
3002/// The caller must not race this call with concurrent mutation of the
3003/// same objects from other threads (per-object state is not internally
3004/// synchronized). Violating any of the above is undefined behavior.
3005///
3006/// Exercised by the C-API differential courts
3007/// (courts/suites/data-abi/*-family-probe.c) and the CLI differential
3008/// courts; those pass byte-for-byte against the upstream oracle.
3009#[no_mangle]
3010pub unsafe extern "C" fn xmlRegisterOutputCallbacks(
3011 matchFunc: Option<xmlOutputMatchCallback>,
3012 openFunc: Option<xmlOutputOpenCallback>,
3013 writeFunc: Option<xmlOutputWriteCallback>,
3014 closeFunc: Option<xmlOutputCloseCallback>,
3015) -> c_int {
3016 unsafe {
3017 globals::init_parser();
3018 }
3019 let mut table = OUTPUT_CALLBACKS.lock();
3020 if table.len() >= 10 {
3021 return -1;
3022 }
3023 table.push(OutputCallbackEntry {
3024 matchcb: matchFunc,
3025 opencb: openFunc,
3026 writecb: writeFunc,
3027 closecb: closeFunc,
3028 });
3029 (table.len() - 1) as c_int
3030}
3031
3032/// Register the default compiled-in output callbacks.
3033///
3034/// # UPSTREAM-PARITY
3035///
3036/// ```c
3037/// void xmlRegisterDefaultOutputCallbacks(void);
3038/// ```
3039///
3040/// # SAFETY
3041///
3042/// The function touches crate-global state only; it is safe
3043/// as long as the caller respects the library's global
3044/// initialization/cleanup ordering (xmlInitParser before use,
3045/// xmlCleanupParser only after all users are done).
3046///
3047/// Violating the global lifecycle ordering, or calling this after
3048/// teardown or from a signal handler, is undefined behavior.
3049#[no_mangle]
3050pub unsafe extern "C" fn xmlRegisterDefaultOutputCallbacks() {
3051 unsafe {
3052 xmlRegisterOutputCallbacks(Some(xmlFileMatch), None, None, None);
3053 }
3054}
3055
3056/// Register the HTTP POST output callbacks (upstream: default output callbacks).
3057///
3058/// # UPSTREAM-PARITY
3059///
3060/// ```c
3061/// void xmlRegisterHTTPPostCallbacks(void);
3062/// ```
3063///
3064/// # SAFETY
3065///
3066/// The function touches crate-global state only; it is safe
3067/// as long as the caller respects the library's global
3068/// initialization/cleanup ordering (xmlInitParser before use,
3069/// xmlCleanupParser only after all users are done).
3070///
3071/// Violating the global lifecycle ordering, or calling this after
3072/// teardown or from a signal handler, is undefined behavior.
3073#[no_mangle]
3074pub unsafe extern "C" fn xmlRegisterHTTPPostCallbacks() {
3075 unsafe { xmlRegisterDefaultOutputCallbacks() }
3076}
3077
3078/// Remove the top output callback from the stack.
3079///
3080/// # UPSTREAM-PARITY
3081///
3082/// ```c
3083/// int xmlPopOutputCallbacks(void);
3084/// ```
3085///
3086/// # SAFETY
3087///
3088/// The function touches crate-global state only; it is safe
3089/// as long as the caller respects the library's global
3090/// initialization/cleanup ordering (xmlInitParser before use,
3091/// xmlCleanupParser only after all users are done).
3092///
3093/// Violating the global lifecycle ordering, or calling this after
3094/// teardown or from a signal handler, is undefined behavior.
3095#[no_mangle]
3096pub unsafe extern "C" fn xmlPopOutputCallbacks() -> c_int {
3097 unsafe {
3098 globals::init_parser();
3099 }
3100 let mut table = OUTPUT_CALLBACKS.lock();
3101 if table.is_empty() {
3102 return -1;
3103 }
3104 table.pop();
3105 table.len() as c_int
3106}
3107
3108/// Clear the entire output callback table.
3109///
3110/// # UPSTREAM-PARITY
3111///
3112/// ```c
3113/// void xmlCleanupOutputCallbacks(void);
3114/// ```
3115///
3116/// # SAFETY
3117///
3118/// The function touches crate-global state only; it is safe
3119/// as long as the caller respects the library's global
3120/// initialization/cleanup ordering (xmlInitParser before use,
3121/// xmlCleanupParser only after all users are done).
3122///
3123/// Violating the global lifecycle ordering, or calling this after
3124/// teardown or from a signal handler, is undefined behavior.
3125#[no_mangle]
3126pub unsafe extern "C" fn xmlCleanupOutputCallbacks() {
3127 unsafe {
3128 globals::init_parser();
3129 }
3130 OUTPUT_CALLBACKS.lock().clear();
3131}
3132
3133// ═══════════════════════════════════════════════════════════════════════════════
3134// External entity loaders (parser.h)
3135// ═══════════════════════════════════════════════════════════════════════════════
3136
3137/// Default external entity loader: resolve `url` against the filesystem,
3138/// honouring XML_PARSE_NONET.
3139///
3140/// # Safety
3141///
3142/// `url`/`publicId` must be valid C strings or NULL; `ctxt` may be NULL.
3143unsafe extern "C" fn default_external_entity_loader(
3144 url: *const c_char,
3145 public_id: *const c_char,
3146 ctxt: *mut _xmlParserCtxt,
3147) -> *mut _xmlParserInput {
3148 let _ = public_id;
3149 if url.is_null() {
3150 return ptr::null_mut();
3151 }
3152 unsafe {
3153 // Refuse network access when NONET is set.
3154 if !ctxt.is_null() && (*ctxt).options & XML_PARSE_NONET != 0 {
3155 let len = libc::strlen(url);
3156 if len >= 7 && libc::strncasecmp(url, c"http://".as_ptr() as *const c_char, 7) == 0 {
3157 return ptr::null_mut();
3158 }
3159 }
3160 // Try the registered input callbacks first.
3161 let table = INPUT_CALLBACKS.lock();
3162 for entry in table.iter() {
3163 if let (Some(match_cb), Some(open_cb)) = (entry.matchcb, entry.opencb) {
3164 if match_cb(url) != 0 {
3165 let ctx = open_cb(url);
3166 if !ctx.is_null() {
3167 let buf = helpers::alloc_parser_input_buffer();
3168 if buf.is_null() {
3169 if let Some(close_cb) = entry.closecb {
3170 close_cb(ctx);
3171 }
3172 return ptr::null_mut();
3173 }
3174 (*buf).context = ctx;
3175 (*buf).readcallback = entry.readcb;
3176 (*buf).closecallback = entry.closecb;
3177 return parser_input_from_buf(buf);
3178 }
3179 }
3180 }
3181 }
3182
3183 // Fall back to a plain file open.
3184 let buf =
3185 io::input_buffer_create_file(url, xmlCharEncoding::XML_CHAR_ENCODING_NONE as c_int);
3186 if buf.is_null() {
3187 return ptr::null_mut();
3188 }
3189 parser_input_from_buf(buf)
3190 }
3191}
3192
3193/// Set the application-wide external entity loader.
3194///
3195/// # UPSTREAM-PARITY
3196///
3197/// ```c
3198/// void xmlSetExternalEntityLoader(xmlExternalEntityLoader f);
3199/// ```
3200///
3201/// # SAFETY
3202///
3203///
3204/// - `f` must be a valid callback (or None);
3205/// the callback is invoked with the documented context pointer and
3206/// must itself uphold the same pointer invariants.
3207///
3208/// The caller must not race this call with concurrent mutation of the
3209/// same objects from other threads (per-object state is not internally
3210/// synchronized). Violating any of the above is undefined behavior.
3211///
3212/// Exercised by the C-API differential courts
3213/// (courts/suites/data-abi/*-family-probe.c) and the CLI differential
3214/// courts; those pass byte-for-byte against the upstream oracle.
3215#[no_mangle]
3216pub unsafe extern "C" fn xmlSetExternalEntityLoader(f: Option<xmlExternalEntityLoader>) {
3217 *EXTERNAL_ENTITY_LOADER.lock() = f;
3218}
3219
3220/// Get the current external entity loader.
3221///
3222/// # UPSTREAM-PARITY
3223///
3224/// ```c
3225/// xmlExternalEntityLoader xmlGetExternalEntityLoader(void);
3226/// ```
3227///
3228/// # SAFETY
3229///
3230/// The function touches crate-global state only; it is safe
3231/// as long as the caller respects the library's global
3232/// initialization/cleanup ordering (xmlInitParser before use,
3233/// xmlCleanupParser only after all users are done).
3234///
3235/// Violating the global lifecycle ordering, or calling this after
3236/// teardown or from a signal handler, is undefined behavior.
3237#[no_mangle]
3238pub unsafe extern "C" fn xmlGetExternalEntityLoader() -> Option<xmlExternalEntityLoader> {
3239 *EXTERNAL_ENTITY_LOADER.lock()
3240}
3241
3242/// External entity loader that disables network access.
3243///
3244/// # UPSTREAM-PARITY
3245///
3246/// ```c
3247/// xmlParserInputPtr xmlNoNetExternalEntityLoader(const char *URL,
3248/// const char *ID,
3249/// xmlParserCtxtPtr ctxt);
3250/// ```
3251///
3252/// # SAFETY
3253///
3254/// - `ctxt` must be valid pointers (or NULL
3255/// where the upstream C contract allows), obtained from the
3256/// matching constructor/owner and not yet freed; the callee may
3257/// take or keep ownership exactly as the C API specifies.
3258///
3259/// - `URL`, `ID` must point to valid NUL-terminated
3260/// strings (or NULL where the C contract allows) for the lifetime
3261/// of the call.
3262///
3263/// The caller must not race this call with concurrent mutation of the
3264/// same objects from other threads (per-object state is not internally
3265/// synchronized). Violating any of the above is undefined behavior.
3266///
3267/// Exercised by the C-API differential courts
3268/// (courts/suites/data-abi/*-family-probe.c) and the CLI differential
3269/// courts; those pass byte-for-byte against the upstream oracle.
3270#[no_mangle]
3271pub unsafe extern "C" fn xmlNoNetExternalEntityLoader(
3272 URL: *const c_char,
3273 ID: *const c_char,
3274 ctxt: *mut _xmlParserCtxt,
3275) -> *mut _xmlParserInput {
3276 unsafe {
3277 let old_options = if ctxt.is_null() { 0 } else { (*ctxt).options };
3278 if !ctxt.is_null() {
3279 (*ctxt).options |= XML_PARSE_NONET;
3280 }
3281 let input = default_external_entity_loader(URL, ID, ctxt);
3282 if !ctxt.is_null() {
3283 (*ctxt).options = old_options;
3284 }
3285 input
3286 }
3287}
3288
3289/// Load an external entity using the registered loader.
3290///
3291/// # UPSTREAM-PARITY
3292///
3293/// ```c
3294/// xmlParserInputPtr xmlLoadExternalEntity(const char *URL, const char *ID,
3295/// xmlParserCtxtPtr ctxt);
3296/// ```
3297///
3298/// # SAFETY
3299///
3300/// - `ctxt` must be valid pointers (or NULL
3301/// where the upstream C contract allows), obtained from the
3302/// matching constructor/owner and not yet freed; the callee may
3303/// take or keep ownership exactly as the C API specifies.
3304///
3305/// - `URL`, `ID` must point to valid NUL-terminated
3306/// strings (or NULL where the C contract allows) for the lifetime
3307/// of the call.
3308///
3309/// The caller must not race this call with concurrent mutation of the
3310/// same objects from other threads (per-object state is not internally
3311/// synchronized). Violating any of the above is undefined behavior.
3312///
3313/// Exercised by the C-API differential courts
3314/// (courts/suites/data-abi/*-family-probe.c) and the CLI differential
3315/// courts; those pass byte-for-byte against the upstream oracle.
3316#[no_mangle]
3317pub unsafe extern "C" fn xmlLoadExternalEntity(
3318 URL: *const c_char,
3319 ID: *const c_char,
3320 ctxt: *mut _xmlParserCtxt,
3321) -> *mut _xmlParserInput {
3322 let loader = *EXTERNAL_ENTITY_LOADER.lock();
3323 match loader {
3324 Some(f) => unsafe { f(URL, ID, ctxt) },
3325 None => unsafe { default_external_entity_loader(URL, ID, ctxt) },
3326 }
3327}
3328
3329/// Check an input for HTTP access; with XML_PARSE_NONET set, HTTP inputs are
3330/// refused and freed.
3331///
3332/// # UPSTREAM-PARITY
3333///
3334/// ```c
3335/// xmlParserInputPtr xmlCheckHTTPInput(xmlParserCtxtPtr ctxt,
3336/// xmlParserInputPtr ret);
3337/// ```
3338///
3339/// # SAFETY
3340///
3341/// - `ctxt`, `ret` must be valid pointers (or NULL
3342/// where the upstream C contract allows), obtained from the
3343/// matching constructor/owner and not yet freed; the callee may
3344/// take or keep ownership exactly as the C API specifies.
3345///
3346/// The caller must not race this call with concurrent mutation of the
3347/// same objects from other threads (per-object state is not internally
3348/// synchronized). Violating any of the above is undefined behavior.
3349///
3350/// Exercised by the C-API differential courts
3351/// (courts/suites/data-abi/*-family-probe.c) and the CLI differential
3352/// courts; those pass byte-for-byte against the upstream oracle.
3353#[no_mangle]
3354pub unsafe extern "C" fn xmlCheckHTTPInput(
3355 ctxt: *mut _xmlParserCtxt,
3356 ret: *mut _xmlParserInput,
3357) -> *mut _xmlParserInput {
3358 if ret.is_null() {
3359 return ptr::null_mut();
3360 }
3361 unsafe {
3362 if !ctxt.is_null() && (*ctxt).options & XML_PARSE_NONET != 0 {
3363 let filename = (*ret).filename;
3364 if !filename.is_null() {
3365 let len = libc::strlen(filename);
3366 if len >= 7
3367 && libc::strncasecmp(filename, c"http://".as_ptr() as *const c_char, 7) == 0
3368 {
3369 // free_parser_input now frees the owned buffer (upstream
3370 // xmlFreeInputStream semantics); no separate buf free.
3371 helpers::free_parser_input(ret);
3372 return ptr::null_mut();
3373 }
3374 }
3375 }
3376 ret
3377 }
3378}
3379
3380// ═══════════════════════════════════════════════════════════════════════════════
3381// xmlFile* I/O callbacks (xmlIO.c)
3382// ═══════════════════════════════════════════════════════════════════════════════
3383
3384/// Match callback: the file I/O handlers accept every filename.
3385///
3386/// # UPSTREAM-PARITY
3387///
3388/// ```c
3389/// int xmlFileMatch(const char *filename);
3390/// ```
3391///
3392/// # SAFETY
3393///
3394///
3395/// - `_filename` must point to valid NUL-terminated
3396/// strings (or NULL where the C contract allows) for the lifetime
3397/// of the call.
3398///
3399/// The caller must not race this call with concurrent mutation of the
3400/// same objects from other threads (per-object state is not internally
3401/// synchronized). Violating any of the above is undefined behavior.
3402///
3403/// Exercised by the C-API differential courts
3404/// (courts/suites/data-abi/*-family-probe.c) and the CLI differential
3405/// courts; those pass byte-for-byte against the upstream oracle.
3406#[no_mangle]
3407pub const unsafe extern "C" fn xmlFileMatch(_filename: *const c_char) -> c_int {
3408 1
3409}
3410
3411/// Open a file and return a `FILE *` I/O context (cast to `void *`).
3412///
3413/// # UPSTREAM-PARITY
3414///
3415/// ```c
3416/// void *xmlFileOpen(const char *filename);
3417/// ```
3418///
3419/// # SAFETY
3420///
3421///
3422/// - `filename` must point to valid NUL-terminated
3423/// strings (or NULL where the C contract allows) for the lifetime
3424/// of the call.
3425///
3426/// The caller must not race this call with concurrent mutation of the
3427/// same objects from other threads (per-object state is not internally
3428/// synchronized). Violating any of the above is undefined behavior.
3429///
3430/// Exercised by the C-API differential courts
3431/// (courts/suites/data-abi/*-family-probe.c) and the CLI differential
3432/// courts; those pass byte-for-byte against the upstream oracle.
3433#[no_mangle]
3434pub unsafe extern "C" fn xmlFileOpen(filename: *const c_char) -> *mut c_void {
3435 if filename.is_null() {
3436 return ptr::null_mut();
3437 }
3438 unsafe { libc::fopen(filename, c"rb".as_ptr() as *const c_char) as *mut c_void }
3439}
3440
3441/// Read up to `len` bytes from a `FILE *` I/O context.
3442///
3443/// # UPSTREAM-PARITY
3444///
3445/// ```c
3446/// int xmlFileRead(void *context, char *buffer, int len);
3447/// ```
3448///
3449/// # SAFETY
3450///
3451/// - `context`, `buffer` must be valid pointers (or NULL
3452/// where the upstream C contract allows), obtained from the
3453/// matching constructor/owner and not yet freed; the callee may
3454/// take or keep ownership exactly as the C API specifies.
3455///
3456/// The caller must not race this call with concurrent mutation of the
3457/// same objects from other threads (per-object state is not internally
3458/// synchronized). Violating any of the above is undefined behavior.
3459///
3460/// Exercised by the C-API differential courts
3461/// (courts/suites/data-abi/*-family-probe.c) and the CLI differential
3462/// courts; those pass byte-for-byte against the upstream oracle.
3463#[no_mangle]
3464pub unsafe extern "C" fn xmlFileRead(
3465 context: *mut c_void,
3466 buffer: *mut c_char,
3467 len: c_int,
3468) -> c_int {
3469 if context.is_null() || buffer.is_null() || len <= 0 {
3470 return -1;
3471 }
3472 unsafe {
3473 let n = libc::fread(
3474 buffer as *mut c_void,
3475 1,
3476 len as usize,
3477 context as *mut libc::FILE,
3478 );
3479 if n < len as usize && libc::ferror(context as *mut libc::FILE) != 0 {
3480 return -1;
3481 }
3482 n as c_int
3483 }
3484}
3485
3486/// Close a `FILE *` I/O context.
3487///
3488/// # UPSTREAM-PARITY
3489///
3490/// ```c
3491/// int xmlFileClose(void *context);
3492/// ```
3493///
3494/// # SAFETY
3495///
3496/// - `context` must be valid pointers (or NULL
3497/// where the upstream C contract allows), obtained from the
3498/// matching constructor/owner and not yet freed; the callee may
3499/// take or keep ownership exactly as the C API specifies.
3500///
3501/// The caller must not race this call with concurrent mutation of the
3502/// same objects from other threads (per-object state is not internally
3503/// synchronized). Violating any of the above is undefined behavior.
3504///
3505/// Exercised by the C-API differential courts
3506/// (courts/suites/data-abi/*-family-probe.c) and the CLI differential
3507/// courts; those pass byte-for-byte against the upstream oracle.
3508#[no_mangle]
3509pub unsafe extern "C" fn xmlFileClose(context: *mut c_void) -> c_int {
3510 if context.is_null() {
3511 return -1;
3512 }
3513 unsafe {
3514 let file = context as *mut libc::FILE;
3515 let fd = libc::fileno(file);
3516 if fd == 0 {
3517 // stdin must not be closed.
3518 return 0;
3519 }
3520 if fd == 1 || fd == 2 {
3521 // stdout/stderr are only flushed.
3522 return if libc::fflush(file) == 0 { 0 } else { -1 };
3523 }
3524 libc::fclose(file)
3525 }
3526}
3527
3528// ═══════════════════════════════════════════════════════════════════════════════
3529// Low-level character scanning (parserInternals.c)
3530// ═══════════════════════════════════════════════════════════════════════════════
3531
3532/// Return the current character (UTF-8 decoded, EOL normalised) and its byte
3533/// length in `*len`. Does not advance the input pointer.
3534///
3535/// # UPSTREAM-PARITY
3536///
3537/// ```c
3538/// int xmlCurrentChar(xmlParserCtxtPtr ctxt, int *len);
3539/// ```
3540///
3541/// # SAFETY
3542///
3543/// - `ctxt`, `len` must be valid pointers (or NULL
3544/// where the upstream C contract allows), obtained from the
3545/// matching constructor/owner and not yet freed; the callee may
3546/// take or keep ownership exactly as the C API specifies.
3547///
3548/// The caller must not race this call with concurrent mutation of the
3549/// same objects from other threads (per-object state is not internally
3550/// synchronized). Violating any of the above is undefined behavior.
3551///
3552/// Exercised by the C-API differential courts
3553/// (courts/suites/data-abi/*-family-probe.c) and the CLI differential
3554/// courts; those pass byte-for-byte against the upstream oracle.
3555#[no_mangle]
3556pub unsafe extern "C" fn xmlCurrentChar(ctxt: *mut _xmlParserCtxt, len: *mut c_int) -> c_int {
3557 if ctxt.is_null() || len.is_null() || (*ctxt).input.is_null() {
3558 return 0;
3559 }
3560 unsafe {
3561 let pi = &*((*ctxt).input);
3562 let cur = pi.cur;
3563 if cur.is_null() {
3564 *len = 0;
3565 return 0;
3566 }
3567 let avail = (pi.end as usize).saturating_sub(cur as usize);
3568 let c = *cur;
3569
3570 if c < 0x80 {
3571 if c == b'\r' {
3572 // EOL normalisation: CR (optionally CRLF) becomes LF.
3573 if avail >= 2 && *cur.add(1) == b'\n' {
3574 (*(*ctxt).input).cur = cur.add(1);
3575 }
3576 *len = 1;
3577 return b'\n' as c_int;
3578 }
3579 if c == 0 {
3580 if avail == 0 {
3581 *len = 0;
3582 } else {
3583 *len = 1;
3584 }
3585 return 0;
3586 }
3587 *len = 1;
3588 return c as c_int;
3589 }
3590
3591 // Multi-byte UTF-8.
3592 if avail < 2 || (*cur.add(1) & 0xc0) != 0x80 {
3593 *len = 1;
3594 return XML_INVALID_CHAR;
3595 }
3596 if c < 0xe0 {
3597 if c < 0xc2 {
3598 *len = 1;
3599 return XML_INVALID_CHAR;
3600 }
3601 let val = (((c & 0x1f) as c_int) << 6) | ((*cur.add(1) & 0x3f) as c_int);
3602 *len = 2;
3603 return val;
3604 }
3605 if avail < 3 || (*cur.add(2) & 0xc0) != 0x80 {
3606 *len = 1;
3607 return XML_INVALID_CHAR;
3608 }
3609 if c < 0xf0 {
3610 let val = (((c & 0x0f) as c_int) << 12)
3611 | (((*cur.add(1) & 0x3f) as c_int) << 6)
3612 | ((*cur.add(2) & 0x3f) as c_int);
3613 if val < 0x800 || (0xd800..0xe000).contains(&val) {
3614 *len = 1;
3615 return XML_INVALID_CHAR;
3616 }
3617 *len = 3;
3618 return val;
3619 }
3620 if avail < 4 || (*cur.add(3) & 0xc0) != 0x80 {
3621 *len = 1;
3622 return XML_INVALID_CHAR;
3623 }
3624 let val = (((c & 0x07) as c_int) << 18)
3625 | (((*cur.add(1) & 0x3f) as c_int) << 12)
3626 | (((*cur.add(2) & 0x3f) as c_int) << 6)
3627 | ((*cur.add(3) & 0x3f) as c_int);
3628 if !(0x10000..0x110000).contains(&val) {
3629 *len = 1;
3630 return XML_INVALID_CHAR;
3631 }
3632 *len = 4;
3633 val
3634 }
3635}
3636
3637/// Advance to the next character, updating line/column accounting.
3638///
3639/// # UPSTREAM-PARITY
3640///
3641/// ```c
3642/// void xmlNextChar(xmlParserCtxtPtr ctxt);
3643/// ```
3644///
3645/// # SAFETY
3646///
3647/// - `ctxt` must be valid pointers (or NULL
3648/// where the upstream C contract allows), obtained from the
3649/// matching constructor/owner and not yet freed; the callee may
3650/// take or keep ownership exactly as the C API specifies.
3651///
3652/// The caller must not race this call with concurrent mutation of the
3653/// same objects from other threads (per-object state is not internally
3654/// synchronized). Violating any of the above is undefined behavior.
3655///
3656/// Exercised by the C-API differential courts
3657/// (courts/suites/data-abi/*-family-probe.c) and the CLI differential
3658/// courts; those pass byte-for-byte against the upstream oracle.
3659#[no_mangle]
3660pub unsafe extern "C" fn xmlNextChar(ctxt: *mut _xmlParserCtxt) {
3661 if ctxt.is_null() || (*ctxt).input.is_null() {
3662 return;
3663 }
3664 unsafe {
3665 let pi = &mut *((*ctxt).input);
3666 let cur = pi.cur;
3667 if cur.is_null() {
3668 return;
3669 }
3670 let avail = (pi.end as usize).saturating_sub(cur as usize);
3671 if avail == 0 {
3672 return;
3673 }
3674 let c = *cur;
3675
3676 if c < 0x80 {
3677 if c == b'\n' {
3678 pi.cur = cur.add(1);
3679 pi.line += 1;
3680 pi.col = 1;
3681 } else if c == b'\r' {
3682 // CRLF is a single line break.
3683 pi.cur = cur.add(if avail >= 2 && *cur.add(1) == b'\n' {
3684 2
3685 } else {
3686 1
3687 });
3688 pi.line += 1;
3689 pi.col = 1;
3690 } else {
3691 pi.cur = cur.add(1);
3692 pi.col += 1;
3693 }
3694 return;
3695 }
3696
3697 pi.col += 1;
3698
3699 if avail < 2 || (*cur.add(1) & 0xc0) != 0x80 {
3700 pi.cur = cur.add(1);
3701 return;
3702 }
3703 if c < 0xe0 {
3704 if c < 0xc2 {
3705 pi.cur = cur.add(1);
3706 return;
3707 }
3708 pi.cur = cur.add(2);
3709 return;
3710 }
3711 if avail < 3 || (*cur.add(2) & 0xc0) != 0x80 {
3712 pi.cur = cur.add(1);
3713 return;
3714 }
3715 if c < 0xf0 {
3716 let val = (((c as c_int) << 8) as u32) | (*cur.add(1) as u32);
3717 if (val < 0xe0a0) || (0xeda0..0xee00).contains(&val) {
3718 pi.cur = cur.add(1);
3719 return;
3720 }
3721 pi.cur = cur.add(3);
3722 return;
3723 }
3724 if avail < 4 || (*cur.add(3) & 0xc0) != 0x80 {
3725 pi.cur = cur.add(1);
3726 return;
3727 }
3728 let val = (((c as c_int) << 8) as u32) | (*cur.add(1) as u32);
3729 if !(0xf090..0xf490).contains(&val) {
3730 pi.cur = cur.add(1);
3731 return;
3732 }
3733 pi.cur = cur.add(4);
3734 }
3735}
3736
3737/// Skip blank characters (space, tab, LF, CR), updating line/column.
3738/// Returns the number of blanks skipped.
3739///
3740/// # UPSTREAM-PARITY
3741///
3742/// ```c
3743/// int xmlSkipBlankChars(xmlParserCtxtPtr ctxt);
3744/// ```
3745///
3746/// # SAFETY
3747///
3748/// - `ctxt` must be valid pointers (or NULL
3749/// where the upstream C contract allows), obtained from the
3750/// matching constructor/owner and not yet freed; the callee may
3751/// take or keep ownership exactly as the C API specifies.
3752///
3753/// The caller must not race this call with concurrent mutation of the
3754/// same objects from other threads (per-object state is not internally
3755/// synchronized). Violating any of the above is undefined behavior.
3756///
3757/// Exercised by the C-API differential courts
3758/// (courts/suites/data-abi/*-family-probe.c) and the CLI differential
3759/// courts; those pass byte-for-byte against the upstream oracle.
3760#[no_mangle]
3761pub unsafe extern "C" fn xmlSkipBlankChars(ctxt: *mut _xmlParserCtxt) -> c_int {
3762 if ctxt.is_null() || (*ctxt).input.is_null() {
3763 return 0;
3764 }
3765 unsafe {
3766 let pi = &mut *((*ctxt).input);
3767 let mut cur = pi.cur;
3768 if cur.is_null() {
3769 return 0;
3770 }
3771 let end = pi.end;
3772 let mut res = 0;
3773 while cur < end && (*cur == 0x20 || *cur == 0x09 || *cur == 0x0a || *cur == 0x0d) {
3774 if *cur == b'\n' {
3775 pi.line += 1;
3776 pi.col = 1;
3777 } else {
3778 pi.col += 1;
3779 }
3780 cur = cur.add(1);
3781 res += 1;
3782 }
3783 pi.cur = cur;
3784 res
3785 }
3786}
3787
3788/// XML 1.0 5th-edition NameStartChar predicate (upstream `xmlIsNameStartCharNew`).
3789const fn is_name_start_char_new(c: c_int) -> bool {
3790 if c == b' ' as c_int || c == b'>' as c_int || c == b'/' as c_int {
3791 return false;
3792 }
3793 (c >= b'a' as c_int && c <= b'z' as c_int)
3794 || (c >= b'A' as c_int && c <= b'Z' as c_int)
3795 || c == b'_' as c_int
3796 || c == b':' as c_int
3797 || (c >= 0xC0 && c <= 0xD6)
3798 || (c >= 0xD8 && c <= 0xF6)
3799 || (c >= 0xF8 && c <= 0x2FF)
3800 || (c >= 0x370 && c <= 0x37D)
3801 || (c >= 0x37F && c <= 0x1FFF)
3802 || (c >= 0x200C && c <= 0x200D)
3803 || (c >= 0x2070 && c <= 0x218F)
3804 || (c >= 0x2C00 && c <= 0x2FEF)
3805 || (c >= 0x3001 && c <= 0xD7FF)
3806 || (c >= 0xF900 && c <= 0xFDCF)
3807 || (c >= 0xFDF0 && c <= 0xFFFD)
3808 || (c >= 0x10000 && c <= 0xEFFFF)
3809}
3810
3811/// XML 1.0 5th-edition NameChar predicate (upstream `xmlIsNameCharNew`).
3812const fn is_name_char_new(c: c_int) -> bool {
3813 if c == b' ' as c_int || c == b'>' as c_int || c == b'/' as c_int {
3814 return false;
3815 }
3816 (c >= b'a' as c_int && c <= b'z' as c_int)
3817 || (c >= b'A' as c_int && c <= b'Z' as c_int)
3818 || (c >= b'0' as c_int && c <= b'9' as c_int)
3819 || c == b'_' as c_int
3820 || c == b':' as c_int
3821 || c == b'-' as c_int
3822 || c == b'.' as c_int
3823 || c == 0xB7
3824 || (c >= 0xC0 && c <= 0xD6)
3825 || (c >= 0xD8 && c <= 0xF6)
3826 || (c >= 0xF8 && c <= 0x2FF)
3827 || (c >= 0x300 && c <= 0x36F)
3828 || (c >= 0x370 && c <= 0x37D)
3829 || (c >= 0x37F && c <= 0x1FFF)
3830 || (c >= 0x200C && c <= 0x200D)
3831 || (c >= 0x203F && c <= 0x2040)
3832 || (c >= 0x2070 && c <= 0x218F)
3833 || (c >= 0x2C00 && c <= 0x2FEF)
3834 || (c >= 0x3001 && c <= 0xD7FF)
3835 || (c >= 0xF900 && c <= 0xFDCF)
3836 || (c >= 0xFDF0 && c <= 0xFFFD)
3837 || (c >= 0x10000 && c <= 0xEFFFF)
3838}
3839
3840/// Scan an XML Name (or NCName/Nmtoken) at `ctxt->input->cur`, advancing the
3841/// input pointer. Returns a pointer to the end of the name, or NULL when the
3842/// name exceeds `max` bytes.
3843///
3844/// # UPSTREAM-PARITY
3845///
3846/// ```c
3847/// const xmlChar *xmlScanName(xmlParserCtxtPtr ctxt, int max, int flags);
3848/// ```
3849///
3850/// # SAFETY
3851///
3852/// - `ctxt` must be valid pointers (or NULL
3853/// where the upstream C contract allows), obtained from the
3854/// matching constructor/owner and not yet freed; the callee may
3855/// take or keep ownership exactly as the C API specifies.
3856///
3857/// The caller must not race this call with concurrent mutation of the
3858/// same objects from other threads (per-object state is not internally
3859/// synchronized). Violating any of the above is undefined behavior.
3860///
3861/// Exercised by the C-API differential courts
3862/// (courts/suites/data-abi/*-family-probe.c) and the CLI differential
3863/// courts; those pass byte-for-byte against the upstream oracle.
3864#[no_mangle]
3865pub unsafe extern "C" fn xmlScanName(
3866 ctxt: *mut _xmlParserCtxt,
3867 max: c_int,
3868 flags: c_int,
3869) -> *const xmlChar {
3870 if ctxt.is_null() || (*ctxt).input.is_null() || max <= 0 {
3871 return ptr::null();
3872 }
3873 unsafe {
3874 let pi = &mut *((*ctxt).input);
3875 let mut ptr = pi.cur;
3876 if ptr.is_null() {
3877 return ptr::null();
3878 }
3879 let end = pi.end;
3880 let mut remaining = max as usize;
3881 let stop: u8 = if flags & XML_SCAN_NC != 0 { b':' } else { 0 };
3882 let old10 = flags & XML_SCAN_OLD10 != 0;
3883 let mut f = flags;
3884
3885 loop {
3886 if ptr >= end {
3887 break;
3888 }
3889 let c = *ptr;
3890 let (cp, len) = if c < 0x80 {
3891 if stop != 0 && c == stop {
3892 break;
3893 }
3894 (c as c_int, 1usize)
3895 } else {
3896 // Decode a multi-byte UTF-8 character.
3897 let avail = (end as usize).saturating_sub(ptr as usize);
3898 let mut l = 4usize;
3899 let cp = decode_utf8_char(ptr, avail, &mut l);
3900 if cp < 0 {
3901 break;
3902 }
3903 (cp, l)
3904 };
3905
3906 let ok = if f & XML_SCAN_NMTOKEN != 0 {
3907 if old10 {
3908 is_name_char_old10(cp)
3909 } else {
3910 is_name_char_new(cp)
3911 }
3912 } else if old10 {
3913 is_name_start_char_old10(cp)
3914 } else {
3915 is_name_start_char_new(cp)
3916 };
3917 if !ok {
3918 break;
3919 }
3920 if len > remaining {
3921 return ptr::null();
3922 }
3923 ptr = ptr.add(len);
3924 remaining -= len;
3925 f |= XML_SCAN_NMTOKEN;
3926 }
3927
3928 pi.cur = ptr;
3929 ptr
3930 }
3931}
3932
3933/// Decode a UTF-8 character at `ptr` with `avail` bytes available; returns the
3934/// codepoint (or -1 on invalid/truncated input) and sets `*len` to its length.
3935const unsafe fn decode_utf8_char(ptr: *const u8, avail: usize, len: &mut usize) -> c_int {
3936 unsafe {
3937 let c = *ptr;
3938 if avail < 2 || (*ptr.add(1) & 0xc0) != 0x80 {
3939 return -1;
3940 }
3941 if c < 0xe0 {
3942 if c < 0xc2 {
3943 return -1;
3944 }
3945 *len = 2;
3946 return (((c & 0x1f) as c_int) << 6) | ((*ptr.add(1) & 0x3f) as c_int);
3947 }
3948 if avail < 3 || (*ptr.add(2) & 0xc0) != 0x80 {
3949 return -1;
3950 }
3951 if c < 0xf0 {
3952 let val = (((c & 0x0f) as c_int) << 12)
3953 | (((*ptr.add(1) & 0x3f) as c_int) << 6)
3954 | ((*ptr.add(2) & 0x3f) as c_int);
3955 if val < 0x800 || (val >= 0xd800 && val < 0xe000) {
3956 return -1;
3957 }
3958 *len = 3;
3959 return val;
3960 }
3961 if avail < 4 || (*ptr.add(3) & 0xc0) != 0x80 {
3962 return -1;
3963 }
3964 let val = (((c & 0x07) as c_int) << 18)
3965 | (((*ptr.add(1) & 0x3f) as c_int) << 12)
3966 | (((*ptr.add(2) & 0x3f) as c_int) << 6)
3967 | ((*ptr.add(3) & 0x3f) as c_int);
3968 if val < 0x10000 || val >= 0x110000 {
3969 return -1;
3970 }
3971 *len = 4;
3972 val
3973 }
3974}
3975
3976/// XML 1.0 (pre-revision-5) NameStartChar predicate: Letter, '_' or ':'.
3977const fn is_name_start_char_old10(c: c_int) -> bool {
3978 (c >= b'a' as c_int && c <= b'z' as c_int)
3979 || (c >= b'A' as c_int && c <= b'Z' as c_int)
3980 || c == b'_' as c_int
3981 || c == b':' as c_int
3982 || (c >= 0xC0 && c <= 0xD6)
3983 || (c >= 0xD8 && c <= 0xF6)
3984 || (c >= 0xF8 && c <= 0x2FF)
3985 || (c >= 0x370 && c <= 0x37D)
3986 || (c >= 0x37F && c <= 0x1FFF)
3987 || (c >= 0x200C && c <= 0x200D)
3988 || (c >= 0x2070 && c <= 0x218F)
3989 || (c >= 0x2C00 && c <= 0x2FEF)
3990 || (c >= 0x3001 && c <= 0xD7FF)
3991 || (c >= 0xF900 && c <= 0xFDCF)
3992 || (c >= 0xFDF0 && c <= 0xFFFD)
3993 || (c >= 0x10000 && c <= 0xEFFFF)
3994}
3995
3996/// XML 1.0 (pre-revision-5) NameChar predicate: NameStartChar, digits, '.',
3997/// '-', combining chars and extenders.
3998const fn is_name_char_old10(c: c_int) -> bool {
3999 is_name_start_char_old10(c)
4000 || (c >= b'0' as c_int && c <= b'9' as c_int)
4001 || c == b'.' as c_int
4002 || c == b'-' as c_int
4003 || c == 0xB7
4004 || (c >= 0x300 && c <= 0x36F)
4005 || c == 0x02D0
4006 || c == 0x02D1
4007 || c == 0x0387
4008 || c == 0x0640
4009 || c == 0x0E46
4010 || c == 0x0EC6
4011 || c == 0x3005
4012 || (c >= 0x3031 && c <= 0x3035)
4013 || (c >= 0x309D && c <= 0x309E)
4014 || (c >= 0x30FC && c <= 0x30FE)
4015}
4016
4017/// Decode entities from the current input position: char references and
4018/// (predefined and DTD-declared) entity references are substituted. Stops at
4019/// the first of `end`/`end2`/`end3`, or after `len` bytes (`len < 0` = rest).
4020///
4021/// # UPSTREAM-PARITY
4022///
4023/// ```c
4024/// xmlChar *xmlDecodeEntities(xmlParserCtxtPtr ctxt, int len, xmlChar end,
4025/// xmlChar end2, xmlChar end3);
4026/// ```
4027///
4028/// # SAFETY
4029///
4030/// - `ctxt` must be valid pointers (or NULL
4031/// where the upstream C contract allows), obtained from the
4032/// matching constructor/owner and not yet freed; the callee may
4033/// take or keep ownership exactly as the C API specifies.
4034///
4035/// The caller must not race this call with concurrent mutation of the
4036/// same objects from other threads (per-object state is not internally
4037/// synchronized). Violating any of the above is undefined behavior.
4038///
4039/// Exercised by the C-API differential courts
4040/// (courts/suites/data-abi/*-family-probe.c) and the CLI differential
4041/// courts; those pass byte-for-byte against the upstream oracle.
4042#[no_mangle]
4043pub unsafe extern "C" fn xmlDecodeEntities(
4044 ctxt: *mut _xmlParserCtxt,
4045 len: c_int,
4046 end: xmlChar,
4047 end2: xmlChar,
4048 end3: xmlChar,
4049) -> *mut xmlChar {
4050 if ctxt.is_null() || (*ctxt).input.is_null() {
4051 return ptr::null_mut();
4052 }
4053 unsafe {
4054 let pi = &*((*ctxt).input);
4055 let cur = pi.cur;
4056 if cur.is_null() {
4057 return ptr::null_mut();
4058 }
4059 let avail = (pi.end as usize).saturating_sub(cur as usize);
4060 let n = if len < 0 {
4061 avail
4062 } else {
4063 (len as usize).min(avail)
4064 };
4065
4066 let mut out: Vec<u8> = Vec::new();
4067 let mut i = 0usize;
4068
4069 while i < n {
4070 let c = *cur.add(i);
4071 if c == end || c == end2 || c == end3 {
4072 break;
4073 }
4074 if c != b'&' {
4075 out.push(c);
4076 i += 1;
4077 continue;
4078 }
4079
4080 // Character reference: &#...; or &#x...;
4081 if i + 1 < n && *cur.add(i + 1) == b'#' {
4082 let (value, consumed) = parse_char_ref(cur.add(i), n - i);
4083 if consumed == 0 {
4084 out.push(b'&');
4085 i += 1;
4086 continue;
4087 }
4088 let mut buf = [0u8; 4];
4089 let blen = copy_char_utf8(&mut buf, value);
4090 out.extend_from_slice(&buf[..blen]);
4091 i += consumed;
4092 continue;
4093 }
4094
4095 // Entity reference: &name;
4096 let mut j = i + 1;
4097 while j < n
4098 && ((*cur.add(j)).is_ascii_alphanumeric()
4099 || *cur.add(j) == b'_'
4100 || *cur.add(j) == b'-'
4101 || *cur.add(j) == b'.'
4102 || *cur.add(j) == b':')
4103 {
4104 j += 1;
4105 }
4106 if j < n && *cur.add(j) == b';' {
4107 let name = core::slice::from_raw_parts(cur.add(i + 1), j - i - 1);
4108 let mut replaced = false;
4109 // Predefined entities.
4110 let content: Option<&[u8]> = match name {
4111 b"amp" => Some(b"&"),
4112 b"lt" => Some(b"<"),
4113 b"gt" => Some(b">"),
4114 b"quot" => Some(b"\""),
4115 b"apos" => Some(b"'"),
4116 _ => None,
4117 };
4118 if let Some(c) = content {
4119 out.extend_from_slice(c);
4120 replaced = true;
4121 } else {
4122 // DTD-declared entity.
4123 let mut name_nul = name.to_vec();
4124 name_nul.push(0);
4125 let ent = entities::get_entity((*ctxt).myDoc, name_nul.as_ptr());
4126 if !ent.is_null() && !(*ent).content.is_null() {
4127 let clen = string::xml_strlen((*ent).content);
4128 out.extend_from_slice(core::slice::from_raw_parts((*ent).content, clen));
4129 replaced = true;
4130 }
4131 }
4132 if replaced {
4133 i = j + 1;
4134 continue;
4135 }
4136 }
4137 out.push(b'&');
4138 i += 1;
4139 }
4140
4141 out.push(0);
4142 let result = xmlMallocImpl(out.len()) as *mut xmlChar;
4143 if result.is_null() {
4144 return ptr::null_mut();
4145 }
4146 ptr::copy_nonoverlapping(out.as_ptr(), result, out.len());
4147 result
4148 }
4149}
4150
4151/// Parse a numeric character reference at `ptr` (starting at '&#'); returns
4152/// the value and total bytes consumed, or (0, 0) when malformed.
4153const unsafe fn parse_char_ref(ptr: *const u8, avail: usize) -> (c_int, usize) {
4154 unsafe {
4155 if avail < 3 || *ptr != b'&' || *ptr.add(1) != b'#' {
4156 return (0, 0);
4157 }
4158 let mut i = 2usize;
4159 let hex = i < avail && (*ptr.add(i) == b'x' || *ptr.add(i) == b'X');
4160 if hex {
4161 i += 1;
4162 }
4163 let start = i;
4164 let mut value: u32 = 0;
4165 while i < avail && *ptr.add(i) != b';' {
4166 let d = (*ptr.add(i) as char).to_digit(if hex { 16 } else { 10 });
4167 match d {
4168 Some(d) => {
4169 value = value
4170 .saturating_mul(if hex { 16 } else { 10 })
4171 .saturating_add(d);
4172 i += 1;
4173 }
4174 None => return (0, 0),
4175 }
4176 }
4177 if i == start || i >= avail || *ptr.add(i) != b';' {
4178 return (0, 0);
4179 }
4180 (value as c_int, i + 1)
4181 }
4182}
4183
4184/// Encode a codepoint into a UTF-8 byte sequence; returns the byte count.
4185const fn copy_char_utf8(out: &mut [u8; 4], val: c_int) -> usize {
4186 if val < 0x80 {
4187 out[0] = val as u8;
4188 1
4189 } else if val < 0x800 {
4190 out[0] = 0xC0 | ((val >> 6) as u8);
4191 out[1] = 0x80 | ((val & 0x3F) as u8);
4192 2
4193 } else if val < 0x10000 {
4194 out[0] = 0xE0 | ((val >> 12) as u8);
4195 out[1] = 0x80 | (((val >> 6) & 0x3F) as u8);
4196 out[2] = 0x80 | ((val & 0x3F) as u8);
4197 3
4198 } else if val < 0x110000 {
4199 out[0] = 0xF0 | ((val >> 18) as u8);
4200 out[1] = 0x80 | (((val >> 12) & 0x3F) as u8);
4201 out[2] = 0x80 | (((val >> 6) & 0x3F) as u8);
4202 out[3] = 0x80 | ((val & 0x3F) as u8);
4203 4
4204 } else {
4205 out[0] = 0;
4206 1
4207 }
4208}
4209
4210/// Detect the character encoding of a buffer from its initial bytes.
4211///
4212/// # UPSTREAM-PARITY
4213///
4214/// ```c
4215/// xmlCharEncoding xmlDetectCharEncoding(const unsigned char *in, int len);
4216/// ```
4217///
4218/// # SAFETY
4219///
4220/// - `in_` must be valid pointers (or NULL
4221/// where the upstream C contract allows), obtained from the
4222/// matching constructor/owner and not yet freed; the callee may
4223/// take or keep ownership exactly as the C API specifies.
4224///
4225/// The caller must not race this call with concurrent mutation of the
4226/// same objects from other threads (per-object state is not internally
4227/// synchronized). Violating any of the above is undefined behavior.
4228///
4229/// Exercised by the C-API differential courts
4230/// (courts/suites/data-abi/*-family-probe.c) and the CLI differential
4231/// courts; those pass byte-for-byte against the upstream oracle.
4232#[no_mangle]
4233pub const unsafe extern "C" fn xmlDetectCharEncoding(in_: *const c_uchar, len: c_int) -> c_int {
4234 if in_.is_null() {
4235 return xmlCharEncoding::XML_CHAR_ENCODING_NONE as c_int;
4236 }
4237 unsafe {
4238 if len >= 4 {
4239 if *in_ == 0x00 && *in_.add(1) == 0x00 && *in_.add(2) == 0x00 && *in_.add(3) == 0x3C {
4240 return xmlCharEncoding::XML_CHAR_ENCODING_UCS4BE as c_int;
4241 }
4242 if *in_ == 0x3C && *in_.add(1) == 0x00 && *in_.add(2) == 0x00 && *in_.add(3) == 0x00 {
4243 return xmlCharEncoding::XML_CHAR_ENCODING_UCS4LE as c_int;
4244 }
4245 if *in_ == 0x4C && *in_.add(1) == 0x6F && *in_.add(2) == 0xA7 && *in_.add(3) == 0x94 {
4246 return xmlCharEncoding::XML_CHAR_ENCODING_EBCDIC as c_int;
4247 }
4248 if *in_ == 0x3C && *in_.add(1) == 0x3F && *in_.add(2) == 0x78 && *in_.add(3) == 0x6D {
4249 return xmlCharEncoding::XML_CHAR_ENCODING_UTF8 as c_int;
4250 }
4251 if *in_ == 0x3C && *in_.add(1) == 0x00 && *in_.add(2) == 0x3F && *in_.add(3) == 0x00 {
4252 return xmlCharEncoding::XML_CHAR_ENCODING_UTF16LE as c_int;
4253 }
4254 if *in_ == 0x00 && *in_.add(1) == 0x3C && *in_.add(2) == 0x00 && *in_.add(3) == 0x3F {
4255 return xmlCharEncoding::XML_CHAR_ENCODING_UTF16BE as c_int;
4256 }
4257 }
4258 if len >= 3 && *in_ == 0xEF && *in_.add(1) == 0xBB && *in_.add(2) == 0xBF {
4259 return xmlCharEncoding::XML_CHAR_ENCODING_UTF8 as c_int;
4260 }
4261 if len >= 2 {
4262 if *in_ == 0xFE && *in_.add(1) == 0xFF {
4263 return xmlCharEncoding::XML_CHAR_ENCODING_UTF16BE as c_int;
4264 }
4265 if *in_ == 0xFF && *in_.add(1) == 0xFE {
4266 return xmlCharEncoding::XML_CHAR_ENCODING_UTF16LE as c_int;
4267 }
4268 }
4269 }
4270 xmlCharEncoding::XML_CHAR_ENCODING_NONE as c_int
4271}
4272
4273/// Convert the first line of `in` using the encoding handler, appending the
4274/// result to `out`.
4275///
4276/// # UPSTREAM-PARITY
4277///
4278/// ```c
4279/// int xmlCharEncFirstLine(xmlCharEncodingHandlerPtr handler,
4280/// struct _xmlBuffer *out, struct _xmlBuffer *in);
4281/// ```
4282///
4283/// # SAFETY
4284///
4285/// - `handler`, `out`, `in_` must be valid pointers (or NULL
4286/// where the upstream C contract allows), obtained from the
4287/// matching constructor/owner and not yet freed; the callee may
4288/// take or keep ownership exactly as the C API specifies.
4289///
4290/// The caller must not race this call with concurrent mutation of the
4291/// same objects from other threads (per-object state is not internally
4292/// synchronized). Violating any of the above is undefined behavior.
4293///
4294/// Exercised by the C-API differential courts
4295/// (courts/suites/data-abi/*-family-probe.c) and the CLI differential
4296/// courts; those pass byte-for-byte against the upstream oracle.
4297#[no_mangle]
4298pub unsafe extern "C" fn xmlCharEncFirstLine(
4299 handler: *mut _xmlCharEncodingHandler,
4300 out: *mut _xmlBuffer,
4301 in_: *mut _xmlBuffer,
4302) -> c_int {
4303 encoding::xmlCharEncInFunc(handler, out, in_)
4304}
4305
4306/// Check whether the current thread is the main thread.
4307///
4308/// # UPSTREAM-PARITY
4309///
4310/// ```c
4311/// int xmlIsMainThread(void);
4312/// ```
4313///
4314/// # SAFETY
4315///
4316/// The function touches crate-global state only; it is safe
4317/// as long as the caller respects the library's global
4318/// initialization/cleanup ordering (xmlInitParser before use,
4319/// xmlCleanupParser only after all users are done).
4320///
4321/// Violating the global lifecycle ordering, or calling this after
4322/// teardown or from a signal handler, is undefined behavior.
4323#[no_mangle]
4324pub const unsafe extern "C" fn xmlIsMainThread() -> c_int {
4325 1
4326}
4327
4328// ═══════════════════════════════════════════════════════════════════════════════
4329// Error reporting helpers (xmlerror.h)
4330// ═══════════════════════════════════════════════════════════════════════════════
4331
4332/// Print file and line information for a parser input to the generic error
4333/// channel.
4334///
4335/// # UPSTREAM-PARITY
4336///
4337/// ```c
4338/// void xmlParserPrintFileInfo(struct _xmlParserInput *input);
4339/// ```
4340///
4341/// # SAFETY
4342///
4343/// - `input` must be valid pointers (or NULL
4344/// where the upstream C contract allows), obtained from the
4345/// matching constructor/owner and not yet freed; the callee may
4346/// take or keep ownership exactly as the C API specifies.
4347///
4348/// The caller must not race this call with concurrent mutation of the
4349/// same objects from other threads (per-object state is not internally
4350/// synchronized). Violating any of the above is undefined behavior.
4351///
4352/// Exercised by the C-API differential courts
4353/// (courts/suites/data-abi/*-family-probe.c) and the CLI differential
4354/// courts; those pass byte-for-byte against the upstream oracle.
4355#[no_mangle]
4356pub unsafe extern "C" fn xmlParserPrintFileInfo(input: *mut _xmlParserInput) {
4357 if input.is_null() {
4358 return;
4359 }
4360 unsafe {
4361 let channel: Option<xmlGenericErrorFunc> = globals::get_generic_error_func();
4362 let data = globals::get_generic_error_ctx();
4363 let Some(ch) = channel else { return };
4364
4365 let msg = if !(*input).filename.is_null() {
4366 let file = CStr::from_ptr((*input).filename);
4367 let s = format!("{}:{}: ", file.to_string_lossy(), (*input).line);
4368 std::ffi::CString::new(s).unwrap_or_default()
4369 } else {
4370 let s = format!("Entity: line {}: ", (*input).line);
4371 std::ffi::CString::new(s).unwrap_or_default()
4372 };
4373 ch(data, msg.as_ptr());
4374 }
4375}
4376
4377/// Print the input context around the current error position to the generic
4378/// error channel.
4379///
4380/// # UPSTREAM-PARITY
4381///
4382/// ```c
4383/// void xmlParserPrintFileContext(struct _xmlParserInput *input);
4384/// ```
4385///
4386/// # SAFETY
4387///
4388/// - `input` must be valid pointers (or NULL
4389/// where the upstream C contract allows), obtained from the
4390/// matching constructor/owner and not yet freed; the callee may
4391/// take or keep ownership exactly as the C API specifies.
4392///
4393/// The caller must not race this call with concurrent mutation of the
4394/// same objects from other threads (per-object state is not internally
4395/// synchronized). Violating any of the above is undefined behavior.
4396///
4397/// Exercised by the C-API differential courts
4398/// (courts/suites/data-abi/*-family-probe.c) and the CLI differential
4399/// courts; those pass byte-for-byte against the upstream oracle.
4400#[no_mangle]
4401pub unsafe extern "C" fn xmlParserPrintFileContext(input: *mut _xmlParserInput) {
4402 if input.is_null() || (*input).cur.is_null() {
4403 return;
4404 }
4405 unsafe {
4406 let channel: Option<xmlGenericErrorFunc> = globals::get_generic_error_func();
4407 let data = globals::get_generic_error_ctx();
4408 let Some(ch) = channel else { return };
4409
4410 let pi = &*input;
4411 let cur = pi.cur;
4412 let base = pi.base;
4413 let end = pi.end;
4414
4415 // Build a window of up to 80 bytes ending at `cur`.
4416 let before = if base.is_null() {
4417 0
4418 } else {
4419 (cur as usize).saturating_sub(base as usize)
4420 };
4421 let take = before.min(LINE_LEN);
4422 let start = cur.sub(take);
4423 let n = (end as usize).saturating_sub(start as usize).min(LINE_LEN);
4424
4425 let mut content = vec![0u8; n];
4426 if n > 0 {
4427 ptr::copy_nonoverlapping(start, content.as_mut_ptr(), n);
4428 }
4429 let line = std::ffi::CString::new(content.clone()).unwrap_or_default();
4430 ch(data, line.as_ptr());
4431
4432 // Caret line pointing at the current character.
4433 let mut caret = vec![b' '; take];
4434 if take < LINE_LEN + 1 {
4435 caret.push(b'^');
4436 }
4437 let caret_c = std::ffi::CString::new(caret).unwrap_or_default();
4438 ch(data, caret_c.as_ptr());
4439 }
4440}
4441
4442// ═══════════════════════════════════════════════════════════════════════════════
4443// SAX/DTD parse front-ends
4444// ═══════════════════════════════════════════════════════════════════════════════
4445
4446/// Handle an entity reference by pushing the entity's content as a new input
4447/// stream (deprecated internal API).
4448///
4449/// # UPSTREAM-PARITY
4450///
4451/// ```c
4452/// void xmlHandleEntity(xmlParserCtxtPtr ctxt, xmlEntityPtr entity);
4453/// ```
4454///
4455/// # SAFETY
4456///
4457/// - `ctxt`, `entity` must be valid pointers (or NULL
4458/// where the upstream C contract allows), obtained from the
4459/// matching constructor/owner and not yet freed; the callee may
4460/// take or keep ownership exactly as the C API specifies.
4461///
4462/// The caller must not race this call with concurrent mutation of the
4463/// same objects from other threads (per-object state is not internally
4464/// synchronized). Violating any of the above is undefined behavior.
4465///
4466/// Exercised by the C-API differential courts
4467/// (courts/suites/data-abi/*-family-probe.c) and the CLI differential
4468/// courts; those pass byte-for-byte against the upstream oracle.
4469#[no_mangle]
4470pub unsafe extern "C" fn xmlHandleEntity(ctxt: *mut _xmlParserCtxt, entity: *mut c_void) {
4471 if ctxt.is_null() {
4472 return;
4473 }
4474 unsafe {
4475 let ent = entity as *mut _xmlEntity;
4476 if ent.is_null() {
4477 return;
4478 }
4479 // Unparsed entities cannot be included by reference.
4480 if (*ent).etype == xmlEntityType::XML_EXTERNAL_GENERAL_UNPARSED_ENTITY as c_int {
4481 return;
4482 }
4483
4484 let mut input = ptr::null_mut();
4485 if !(*ent).content.is_null() {
4486 // Internal entity: push its replacement text as a new stream.
4487 let content = (*ent).content;
4488 let pi = xmlNewInputStream(ctxt);
4489 if pi.is_null() {
4490 return;
4491 }
4492 let len = string::xml_strlen(content);
4493 (*pi).base = content;
4494 (*pi).cur = content;
4495 (*pi).end = content.add(len);
4496 (*pi).length = len as c_int;
4497 (*pi).entity = ent;
4498 input = pi;
4499 } else if !(*ent).URI.is_null() {
4500 // External parsed entity: load it through the entity loader.
4501 input = xmlLoadExternalEntity(
4502 (*ent).URI as *const c_char,
4503 (*ent).ExternalID as *const c_char,
4504 ctxt,
4505 );
4506 if !input.is_null() {
4507 (*input).entity = ent;
4508 }
4509 }
4510
4511 if input.is_null() {
4512 return;
4513 }
4514 xmlPushInput(ctxt, input);
4515 }
4516}
4517
4518/// Load and parse a DTD, returning the resulting `xmlDtd` (detached from any
4519/// document).
4520///
4521/// # UPSTREAM-PARITY
4522///
4523/// ```c
4524/// xmlDtdPtr xmlSAXParseDTD(xmlSAXHandlerPtr sax, const xmlChar *publicId,
4525/// const xmlChar *systemId);
4526/// ```
4527///
4528/// # SAFETY
4529///
4530/// - `sax` must be valid pointers (or NULL
4531/// where the upstream C contract allows), obtained from the
4532/// matching constructor/owner and not yet freed; the callee may
4533/// take or keep ownership exactly as the C API specifies.
4534///
4535/// - `publicId`, `systemId` must point to valid NUL-terminated
4536/// strings (or NULL where the C contract allows) for the lifetime
4537/// of the call.
4538///
4539/// The caller must not race this call with concurrent mutation of the
4540/// same objects from other threads (per-object state is not internally
4541/// synchronized). Violating any of the above is undefined behavior.
4542///
4543/// Exercised by the C-API differential courts
4544/// (courts/suites/data-abi/*-family-probe.c) and the CLI differential
4545/// courts; those pass byte-for-byte against the upstream oracle.
4546#[no_mangle]
4547pub unsafe extern "C" fn xmlSAXParseDTD(
4548 sax: *mut _xmlSAXHandler,
4549 publicId: *const xmlChar,
4550 systemId: *const xmlChar,
4551) -> *mut _xmlDtd {
4552 if publicId.is_null() && systemId.is_null() {
4553 return ptr::null_mut();
4554 }
4555 unsafe {
4556 let ctxt = xmlNewSAXParserCtxt(sax, ptr::null_mut());
4557 if ctxt.is_null() {
4558 return ptr::null_mut();
4559 }
4560 apply_options(ctxt, XML_PARSE_DTDLOAD);
4561
4562 // Resolve via the SAX resolveEntity callback when available, else
4563 // load the system ID directly.
4564 let mut input = ptr::null_mut();
4565 if !sax.is_null() {
4566 if let Some(resolve) = (*sax).resolveEntity {
4567 input = resolve((*ctxt).userData, publicId, systemId);
4568 }
4569 }
4570 if input.is_null() {
4571 if systemId.is_null() {
4572 helpers::free_parser_ctxt(ctxt);
4573 return ptr::null_mut();
4574 }
4575 input = xmlLoadExternalEntity(systemId as *const c_char, ptr::null(), ctxt);
4576 }
4577 if input.is_null() {
4578 helpers::free_parser_ctxt(ctxt);
4579 return ptr::null_mut();
4580 }
4581
4582 // Materialise the DTD text before freeing the input struct.
4583 let data: Vec<u8> = {
4584 let pi = &*input;
4585 if !pi.base.is_null() && !pi.end.is_null() && pi.end >= pi.base {
4586 let len = (pi.end as usize).saturating_sub(pi.base as usize);
4587 core::slice::from_raw_parts(pi.base, len).to_vec()
4588 } else if !pi.buf.is_null() {
4589 input_buffer_data(pi.buf)
4590 } else {
4591 Vec::new()
4592 }
4593 };
4594 helpers::free_parser_input(input);
4595
4596 let dtd = parse_dtd_text(ctxt, &data, publicId, systemId);
4597 helpers::free_parser_ctxt(ctxt);
4598 dtd
4599 }
4600}
4601
4602/// Load and parse a DTD from an input buffer.
4603///
4604/// # UPSTREAM-PARITY
4605///
4606/// ```c
4607/// xmlDtdPtr xmlIOParseDTD(xmlSAXHandlerPtr sax, xmlParserInputBufferPtr input,
4608/// xmlCharEncoding enc);
4609/// ```
4610///
4611/// # SAFETY
4612///
4613/// - `sax`, `input` must be valid pointers (or NULL
4614/// where the upstream C contract allows), obtained from the
4615/// matching constructor/owner and not yet freed; the callee may
4616/// take or keep ownership exactly as the C API specifies.
4617///
4618/// The caller must not race this call with concurrent mutation of the
4619/// same objects from other threads (per-object state is not internally
4620/// synchronized). Violating any of the above is undefined behavior.
4621///
4622/// Exercised by the C-API differential courts
4623/// (courts/suites/data-abi/*-family-probe.c) and the CLI differential
4624/// courts; those pass byte-for-byte against the upstream oracle.
4625#[no_mangle]
4626pub unsafe extern "C" fn xmlIOParseDTD(
4627 sax: *mut _xmlSAXHandler,
4628 input: *mut _xmlParserInputBuffer,
4629 enc: c_int,
4630) -> *mut _xmlDtd {
4631 if input.is_null() {
4632 return ptr::null_mut();
4633 }
4634 unsafe {
4635 let ctxt = xmlNewSAXParserCtxt(sax, ptr::null_mut());
4636 if ctxt.is_null() {
4637 io::input_buffer_free(input);
4638 return ptr::null_mut();
4639 }
4640 apply_options(ctxt, XML_PARSE_DTDLOAD);
4641 if enc != xmlCharEncoding::XML_CHAR_ENCODING_NONE as c_int {
4642 (*ctxt).charset = enc;
4643 }
4644
4645 // Materialise the data from the input buffer.
4646 let data: Vec<u8> = input_buffer_data(input);
4647 io::input_buffer_free(input);
4648
4649 let dtd = parse_dtd_text(ctxt, &data, ptr::null(), ptr::null());
4650 helpers::free_parser_ctxt(ctxt);
4651 dtd
4652 }
4653}
4654
4655/// Extract the buffered data of an input buffer as an owned byte vector.
4656unsafe fn input_buffer_data(buf: *mut _xmlParserInputBuffer) -> Vec<u8> {
4657 unsafe {
4658 if buf.is_null() {
4659 return Vec::new();
4660 }
4661 let b = &*buf;
4662 if let Some(read) = b.readcallback {
4663 let mut out = Vec::new();
4664 let mut tmp = [0u8; 4096];
4665 loop {
4666 let n = read(
4667 b.context,
4668 tmp.as_mut_ptr() as *mut c_char,
4669 tmp.len() as c_int,
4670 );
4671 if n <= 0 {
4672 break;
4673 }
4674 out.extend_from_slice(&tmp[..n as usize]);
4675 }
4676 return out;
4677 }
4678 if !b.buffer.is_null() {
4679 let xbuf = &*(b.buffer as *mut _xmlBuffer);
4680 if !xbuf.content.is_null() && xbuf.use_ > 0 {
4681 return core::slice::from_raw_parts(xbuf.content, xbuf.use_ as usize).to_vec();
4682 }
4683 }
4684 Vec::new()
4685 }
4686}
4687
4688/// Parse an external general entity and build a tree.
4689///
4690/// # UPSTREAM-PARITY
4691///
4692/// ```c
4693/// xmlDocPtr xmlSAXParseEntity(xmlSAXHandlerPtr sax, const char *filename);
4694/// ```
4695///
4696/// # SAFETY
4697///
4698/// - `sax` must be valid pointers (or NULL
4699/// where the upstream C contract allows), obtained from the
4700/// matching constructor/owner and not yet freed; the callee may
4701/// take or keep ownership exactly as the C API specifies.
4702///
4703/// - `filename` must point to valid NUL-terminated
4704/// strings (or NULL where the C contract allows) for the lifetime
4705/// of the call.
4706///
4707/// The caller must not race this call with concurrent mutation of the
4708/// same objects from other threads (per-object state is not internally
4709/// synchronized). Violating any of the above is undefined behavior.
4710///
4711/// Exercised by the C-API differential courts
4712/// (courts/suites/data-abi/*-family-probe.c) and the CLI differential
4713/// courts; those pass byte-for-byte against the upstream oracle.
4714#[no_mangle]
4715pub unsafe extern "C" fn xmlSAXParseEntity(
4716 sax: *mut _xmlSAXHandler,
4717 filename: *const c_char,
4718) -> *mut _xmlDoc {
4719 if filename.is_null() {
4720 return ptr::null_mut();
4721 }
4722 unsafe {
4723 let ctxt = xmlNewSAXParserCtxt(sax, ptr::null_mut());
4724 if ctxt.is_null() {
4725 return ptr::null_mut();
4726 }
4727 let input = match helpers::input_from_file(filename) {
4728 Ok(i) => i,
4729 Err(_) => {
4730 helpers::free_parser_ctxt(ctxt);
4731 return ptr::null_mut();
4732 }
4733 };
4734 helpers::setup_parser_input(ctxt, input);
4735 let rc = helpers::parse_document(ctxt);
4736 let doc = (*ctxt).myDoc;
4737 (*ctxt).myDoc = ptr::null_mut();
4738 if rc != 0 || (*ctxt).wellFormed == 0 {
4739 if !doc.is_null() {
4740 tree::free_doc(doc);
4741 }
4742 helpers::free_parser_ctxt(ctxt);
4743 return ptr::null_mut();
4744 }
4745 helpers::free_parser_ctxt(ctxt);
4746 doc
4747 }
4748}
4749
4750// ═══════════════════════════════════════════════════════════════════════════════
4751// C14N: xmlC14NDocSave
4752// ═══════════════════════════════════════════════════════════════════════════════
4753
4754/// Canonicalise a document (or node set) and save it to a file.
4755///
4756/// # UPSTREAM-PARITY
4757///
4758/// ```c
4759/// int xmlC14NDocSave(xmlDocPtr doc, xmlNodeSetPtr nodes, int mode,
4760/// xmlChar **inclusive_ns_prefixes, int with_comments,
4761/// const char *filename, int compression);
4762/// ```
4763///
4764/// # SAFETY
4765///
4766/// - `doc`, `nodes`, `inclusive_ns_prefixes` must be valid pointers (or NULL
4767/// where the upstream C contract allows), obtained from the
4768/// matching constructor/owner and not yet freed; the callee may
4769/// take or keep ownership exactly as the C API specifies.
4770///
4771/// - `filename` must point to valid NUL-terminated
4772/// strings (or NULL where the C contract allows) for the lifetime
4773/// of the call.
4774///
4775/// The caller must not race this call with concurrent mutation of the
4776/// same objects from other threads (per-object state is not internally
4777/// synchronized). Violating any of the above is undefined behavior.
4778///
4779/// Exercised by the C-API differential courts
4780/// (courts/suites/data-abi/*-family-probe.c) and the CLI differential
4781/// courts; those pass byte-for-byte against the upstream oracle.
4782#[no_mangle]
4783pub unsafe extern "C" fn xmlC14NDocSave(
4784 doc: *mut _xmlDoc,
4785 nodes: *mut _xmlNodeSet,
4786 mode: c_int,
4787 inclusive_ns_prefixes: *mut *mut xmlChar,
4788 with_comments: c_int,
4789 filename: *const c_char,
4790 compression: c_int,
4791) -> c_int {
4792 if filename.is_null() {
4793 return -1;
4794 }
4795 unsafe {
4796 let output = io::output_buffer_create_filename(filename, ptr::null_mut(), compression);
4797 if output.is_null() {
4798 return -1;
4799 }
4800 let ret = crate::xml::c14n::xmlC14NDocSaveTo(
4801 doc,
4802 nodes,
4803 mode,
4804 inclusive_ns_prefixes,
4805 with_comments,
4806 output,
4807 );
4808 if ret < 0 {
4809 io::output_buffer_close(output);
4810 return -1;
4811 }
4812 let close_ret = io::output_buffer_close(output);
4813 if close_ret < 0 {
4814 -1
4815 } else {
4816 ret
4817 }
4818 }
4819}