libxml-rs 0.1.0-alpha.37

Native-Rust forensic reimplementation of libxml2+libxslt with C ABI drop-in replacement. Cross-version oracle matrix (libxml2 2.7.8-2.15.3, libxslt 1.1.26-1.1.45) with semantic epochs correlated to upstream commits; full xmllint/xmlcatalog/xsltproc CLIs; differential-court-verified C API closure; three-DSO ELF packaging (libxml2.so.16 core + libxslt.so.1/libexslt.so.0 facades, upstream NEEDED chain); fail-closed oracle-isolated function-signature ABI plane (SOURCE_PROTOTYPE + MACHINE_ABI fingerprints, zero silent omissions) and the libc default allocator (ALLOCATOR-DEFAULT-001) verified byte-identical; proof-scoped safety commentary (0 unaccounted unsafe sites); residual ledger 79 FIXED / 3 OPEN; 1183 tests passing.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
//! String utility functions for libxml-rs.
//!
//! Provides operations on `xmlChar*` (i.e. `*mut u8`) strings compatible
//! with upstream libxml2 string handling.
//!
//! # Upstream contract
//!
//! Mirrors upstream xmlstring.c (SRC-LIBXML2-2.15.0-XMLSTRING-C): xmlStrlen,
//! xmlStrdup, xmlStrndup, xmlStrchr, xmlStrstr, xmlStrcmp, xmlStrEqual,
//! xmlStrsub, the UTF-8 helpers and the xmlChar* memory functions. Parity
//! target: the system libxml2 2.15.3 oracle.
//!
//! # Conceptual behavior
//!
//! Provides operations on xmlChar* (u8) NUL-terminated strings compatible
//! with upstream semantics: length scan, duplication, comparison, UTF-8
//! iteration and substring extraction. String values are owned per the
//! upstream contract — the caller frees xmlStrdup results with xmlFree.
//!
//! # Ownership & safety invariants
//!
//! SAFETY: functions require NUL-terminated inputs (or NULL); callers own
//! returned copies (freed with xmlFree). The R-000169 lesson applies here:
//! xml_strndup must be used when the source is a Rust String with an exact
//! length — xml_strdup on a non-NUL-terminated as_ptr() scans past the
//! allocation (heap-buffer-overflow, caught by ASan).
//!
//! # Historical quirks & epochs
//!
//! The 11.1-X fix (R-000169) switched the parser filename duplication from
//! xml_strdup to xml_strndup(fname.as_ptr(), fname.len()) after ASan pinned
//! the overflow. Historical quirk: the upstream limit macro XML_MAX_TEXT_
//! LENGHT was misspelled for years (QUIRK-0004, commit 1fb2e0df) — the
//! spelling is part of the observable header surface.
//!
//! # Deliberate oddities
//!
//! Deliberate oddity: xml_strdup returns NULL on NULL input and on OOM
//! (matching upstream xmlStrdup); the module deliberately never assumes
//! Rust-length semantics — every operation is NUL-terminated-centric.
//!
//! # Proving courts
//!
//! Exercised indirectly by TREE-001 (URL/base fingerprints), ERROR-001
//! (str1/str2/str3 copies), the data-ABI family probes, and `cargo test
//! --lib` under ASan (which caught the R-000169 overflow).
//!
//! # Tempting simplifications that would break parity
//!
//! The tempting simplification is using Rust String/slices everywhere and
//! dropping the NUL-terminated xmlChar* model — it would break the C ABI
//! (xmlChar* parameters) and the ownership contract. Do not fix xml_strdup
//! callers to assume NUL-termination of Rust Strings: that was the exact
//! heap-buffer-overflow R-000169 fixed.

use crate::abi::allocator::{xmlFreeImpl, xmlMallocImpl};
use crate::abi::types::xmlChar;
use core::ffi::c_void;
use core::ptr;
use std::os::raw::{c_char, c_int};
use std::slice;

/// Compute the length of a null-terminated `xmlChar` string.
///
/// # UPSTREAM-PARITY
///
/// Equivalent to `strlen((const char *)str)` in C.
///
/// # Safety
///
/// `str` must point to a null-terminated sequence of bytes.
#[inline]
pub(crate) const unsafe fn xml_strlen(str: *const xmlChar) -> usize {
    if str.is_null() {
        return 0;
    }
    let mut len: usize = 0;
    while *str.add(len) != 0 {
        len += 1;
    }
    len
}

/// Duplicate a null-terminated `xmlChar` string using `xmlMalloc`.
///
/// # UPSTREAM-PARITY
///
/// Equivalent to `xmlStrdup` in upstream libxml2.
/// Returns a newly allocated copy. Caller must free with `xmlFree`.
///
/// # Safety
///
/// `str` must point to a null-terminated sequence of bytes, or be NULL.
#[inline]
pub(crate) unsafe fn xml_strdup(str: *const xmlChar) -> *mut xmlChar {
    if str.is_null() {
        return ptr::null_mut();
    }
    let len = xml_strlen(str);
    let copy = xmlMallocImpl(len + 1) as *mut xmlChar;
    if copy.is_null() {
        return ptr::null_mut();
    }
    ptr::copy_nonoverlapping(str, copy, len + 1);
    copy
}

/// Duplicate a C `char*` string using `xmlMalloc`.
///
/// # Safety
///
/// `str` must point to a null-terminated C string, or be NULL.
#[inline]
pub(crate) unsafe fn c_strdup(str: *const c_char) -> *mut c_char {
    if str.is_null() {
        return ptr::null_mut();
    }
    let len = libc::strlen(str);
    let copy = xmlMallocImpl(len + 1) as *mut c_char;
    if copy.is_null() {
        return ptr::null_mut();
    }
    ptr::copy_nonoverlapping(str as *const u8, copy as *mut u8, len + 1);
    copy
}

/// Convert a Rust byte slice to a null-terminated `xmlChar*` allocated via `xmlMalloc`.
///
/// # Safety
///
/// The caller must free the returned pointer with `xmlFree`.
pub(crate) unsafe fn bytes_to_xmlstr(bytes: &[u8]) -> *mut xmlChar {
    let len = bytes.len();
    let ptr = xmlMallocImpl(len + 1) as *mut xmlChar;
    if ptr.is_null() {
        return ptr::null_mut();
    }
    ptr::copy_nonoverlapping(bytes.as_ptr(), ptr, len);
    *ptr.add(len) = 0; // null-terminate
    ptr
}

/// Convert a `*const xmlChar` to a byte slice.
///
/// # Safety
///
/// `str` must be NULL or point to a null-terminated sequence of bytes.
/// The returned slice borrows from the original memory.
#[inline]
pub(crate) const unsafe fn xmlstr_to_bytes(str: *const xmlChar) -> &'static [u8] {
    if str.is_null() {
        return &[];
    }
    let len = xml_strlen(str);
    slice::from_raw_parts(str, len)
}

/// Compare two null-terminated `xmlChar` strings.
///
/// Returns 0 if equal, <0 if str1 < str2, >0 if str1 > str2.
///
/// # Safety
///
/// Both strings must be null-terminated or NULL.
#[inline]
pub(crate) unsafe fn xml_strcmp(str1: *const xmlChar, str2: *const xmlChar) -> i32 {
    if str1 == str2 {
        return 0;
    }
    if str1.is_null() {
        return -1;
    }
    if str2.is_null() {
        return 1;
    }
    let mut i: usize = 0;
    loop {
        let a = *str1.add(i);
        let b = *str2.add(i);
        if a != b {
            return a as i32 - b as i32;
        }
        if a == 0 {
            return 0;
        }
        i += 1;
    }
}

/// Concatenate two null-terminated `xmlChar` strings.
///
/// Returns a newly allocated string. Caller must free with `xmlFree`.
///
/// # Safety
///
/// Both strings must be null-terminated or NULL.
#[inline]
#[allow(dead_code)]
pub(crate) unsafe fn xml_strcat(str1: *const xmlChar, str2: *const xmlChar) -> *mut xmlChar {
    let len1 = xml_strlen(str1);
    let len2 = xml_strlen(str2);
    let result = xmlMallocImpl(len1 + len2 + 1) as *mut xmlChar;
    if result.is_null() {
        return ptr::null_mut();
    }
    if !str1.is_null() {
        ptr::copy_nonoverlapping(str1, result, len1);
    }
    if !str2.is_null() {
        ptr::copy_nonoverlapping(str2, result.add(len1), len2);
    }
    *result.add(len1 + len2) = 0;
    result
}

/// Convert a `*const xmlChar` to a Rust `String`.
///
/// Returns an empty string for NULL pointers.
///
/// # Safety
///
/// `str` must be NULL or point to a null-terminated sequence of bytes.
#[inline]
pub(crate) unsafe fn xml_strndup(str: *const xmlChar, len: usize) -> *mut xmlChar {
    if str.is_null() {
        return ptr::null_mut();
    }
    let p = unsafe { xmlMallocImpl(len + 1) as *mut xmlChar };
    if p.is_null() {
        return ptr::null_mut();
    }
    unsafe {
        ptr::copy_nonoverlapping(str, p, len);
        *p.add(len) = 0;
    }
    p
}

/// Convert a null-terminated `xmlChar` string into a Rust `String`
/// (lossy UTF-8 conversion; empty string for NULL).
///
/// # Safety
///
/// `str` must be NULL or point to a null-terminated byte sequence.
pub(crate) unsafe fn xmlstr_to_string(str: *const xmlChar) -> String {
    if str.is_null() {
        return String::new();
    }
    let bytes = unsafe { xmlstr_to_bytes(str) };
    String::from_utf8_lossy(bytes).to_string()
}

/// Build a QName `prefix:local` (upstream tree.c `xmlBuildQName`):
/// writes into `memory` when it is large enough, otherwise allocates.
/// Returns the resulting string (allocator-owned when not `memory`), or
/// NULL on error. A NULL prefix returns `ncname` unchanged.
///
/// # Safety
///
/// - `ncname`, `prefix` must be valid null-terminated strings or NULL.
/// - `memory` must be a valid buffer of `len` bytes or NULL.
pub unsafe fn build_qname(
    ncname: *const xmlChar,
    prefix: *const xmlChar,
    memory: *mut xmlChar,
    len: c_int,
) -> *mut xmlChar {
    if ncname.is_null() {
        return ptr::null_mut();
    }
    if prefix.is_null() {
        return ncname as *mut xmlChar;
    }
    unsafe {
        let lenn = xml_strlen(ncname);
        let lenp = xml_strlen(prefix);
        let ret = if memory.is_null() || (len as usize) < lenn + lenp + 2 {
            let p = xmlMallocImpl(lenn + lenp + 2) as *mut xmlChar;
            if p.is_null() {
                return ptr::null_mut();
            }
            p
        } else {
            memory
        };
        ptr::copy_nonoverlapping(prefix, ret, lenp);
        *ret.add(lenp) = b':' as xmlChar;
        ptr::copy_nonoverlapping(ncname, ret.add(lenp + 1), lenn);
        *ret.add(lenn + lenp + 1) = 0;
        ret
    }
}

/// Split a QName into prefix and local part (upstream tree.c
/// `xmlSplitQName2`): returns NULL when the name has no prefix (or starts
/// with ':'), otherwise allocates `*prefix` with the prefix and returns the
/// local part.
///
/// # Safety
///
/// - `name` must be a valid null-terminated string or NULL.
/// - `prefix` must be a valid `xmlChar**`.
pub unsafe fn split_qname2(name: *const xmlChar, prefix: *mut *mut xmlChar) -> *mut xmlChar {
    if prefix.is_null() {
        return ptr::null_mut();
    }
    unsafe {
        *prefix = ptr::null_mut();
    }
    if name.is_null() {
        return ptr::null_mut();
    }
    unsafe {
        // "nasty but valid" (upstream): leading ':' has no prefix
        if *name == b':' as xmlChar {
            return ptr::null_mut();
        }
        let mut len: usize = 0;
        while *name.add(len) != 0 && *name.add(len) != b':' as xmlChar {
            len += 1;
        }
        if *name.add(len) == 0 || *name.add(len + 1) == 0 {
            return ptr::null_mut();
        }
        let p = xml_strndup(name, len);
        if p.is_null() {
            return ptr::null_mut();
        }
        *prefix = p;
        let ret = xml_strdup(name.add(len + 1));
        if ret.is_null() {
            xmlFreeImpl(*prefix as *mut c_void);
            *prefix = ptr::null_mut();
            return ptr::null_mut();
        }
        ret
    }
}

/// Split a QName returning the local-name pointer (upstream tree.c
/// `xmlSplitQName3`): returns a pointer to the local part after the ':' and
/// fills `*len` with the prefix length, or NULL when the name has no prefix
/// (or NULL arguments). R-000176: the candidate previously returned the
/// prefix length as an int.
///
/// # Safety
///
/// - `name` must be a valid null-terminated string or NULL.
pub unsafe fn split_qname3(name: *const xmlChar, len: *mut c_int) -> *mut xmlChar {
    if name.is_null() || len.is_null() {
        return ptr::null_mut();
    }
    unsafe {
        if *name == b':' as xmlChar {
            return ptr::null_mut();
        }
        let mut l: usize = 0;
        while *name.add(l) != 0 && *name.add(l) != b':' as xmlChar {
            l += 1;
        }
        if *name.add(l) == 0 {
            return ptr::null_mut();
        }
        *len = l as c_int;
        name.add(l + 1) as *mut xmlChar
    }
}

/// Return the number of UTF-8 characters in a string (upstream
/// `xmlUTF8Strlen`).
///
/// # Safety
///
/// - `utf` must be a valid null-terminated UTF-8 string.
pub const unsafe fn utf8_strlen(utf: *const xmlChar) -> c_int {
    if utf.is_null() {
        return 0;
    }
    unsafe {
        let mut n: c_int = 0;
        let mut cur = utf;
        while *cur != 0 {
            let c = *cur;
            if c & 0x80 == 0 {
                cur = cur.add(1);
            } else if c & 0xe0 == 0xc0 {
                cur = cur.add(2);
            } else if c & 0xf0 == 0xe0 {
                cur = cur.add(3);
            } else if c & 0xf8 == 0xf0 {
                cur = cur.add(4);
            } else {
                // invalid sequence: stop counting
                return n;
            }
            n += 1;
        }
        n
    }
}

/// Size in bytes of the UTF-8 sequence starting at `utf` (upstream
/// `xmlUTF8Size`): returns the sequence length, or -1 on invalid leading
/// byte, 0 on NUL.
///
/// # Safety
///
/// - `utf` must be a valid pointer into a UTF-8 string.
pub const unsafe fn utf8_size(utf: *const xmlChar) -> c_int {
    if utf.is_null() {
        return -1;
    }
    unsafe {
        let c = *utf;
        if c == 0 {
            return 0;
        }
        if c & 0x80 == 0 {
            1
        } else if c & 0xe0 == 0xc0 {
            2
        } else if c & 0xf0 == 0xe0 {
            3
        } else if c & 0xf8 == 0xf0 {
            4
        } else {
            -1
        }
    }
}

/// Check that a byte string is valid UTF-8 (upstream `xmlCheckUTF8`):
/// returns 1 when valid, 0 otherwise.
///
/// # Safety
///
/// - `utf` must be a valid null-terminated byte string.
pub const unsafe fn check_utf8(utf: *const xmlChar) -> c_int {
    if utf.is_null() {
        return 0;
    }
    unsafe {
        let mut cur = utf;
        while *cur != 0 {
            let c = *cur;
            if c & 0x80 == 0 {
                cur = cur.add(1);
            } else if c & 0xe0 == 0xc0 {
                // 2-byte: 110xxxxx 10xxxxxx
                let c1 = *cur.add(1);
                if c1 & 0xc0 != 0x80 {
                    return 0;
                }
                cur = cur.add(2);
            } else if c & 0xf0 == 0xe0 {
                let c1 = *cur.add(1);
                let c2 = *cur.add(2);
                if c1 & 0xc0 != 0x80 || c2 & 0xc0 != 0x80 {
                    return 0;
                }
                cur = cur.add(3);
            } else if c & 0xf8 == 0xf0 {
                let c1 = *cur.add(1);
                let c2 = *cur.add(2);
                let c3 = *cur.add(3);
                if c1 & 0xc0 != 0x80 || c2 & 0xc0 != 0x80 || c3 & 0xc0 != 0x80 {
                    return 0;
                }
                cur = cur.add(4);
            } else {
                return 0;
            }
        }
        1
    }
}
#[inline]
pub(crate) const unsafe fn xml_str_starts_with(
    str: *const xmlChar,
    prefix: *const xmlChar,
) -> bool {
    if str.is_null() || prefix.is_null() {
        return false;
    }
    let mut i: usize = 0;
    loop {
        let p = *prefix.add(i);
        if p == 0 {
            return true; // reached end of prefix without mismatch
        }
        if *str.add(i) != p {
            return false;
        }
        i += 1;
    }
}

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

    /// Measure C-string lengths, including the NULL and empty cases.
    ///
    /// # Safety
    ///
    /// - The tested pointers are NULL or static NUL-terminated strings
    ///   valid for the duration of `xml_strlen`'s scan.
    #[test]
    fn test_xml_strlen() {
        unsafe {
            assert_eq!(xml_strlen(ptr::null()), 0);
            let s = b"hello\0" as *const u8 as *const xmlChar;
            assert_eq!(xml_strlen(s), 5);
            let empty = b"\0" as *const u8 as *const xmlChar;
            assert_eq!(xml_strlen(empty), 0);
        }
    }

    /// Duplicate a C string and verify the copy's contents and terminator.
    ///
    /// # Safety
    ///
    /// - `s` is NULL or a static NUL-terminated string; `dup` is
    ///   allocator-owned, valid for `len + 1` bytes, and freed with
    ///   `xmlFreeImpl` exactly once; `dup` must not be read afterwards.
    #[test]
    fn test_xml_strdup() {
        unsafe {
            assert!(xml_strdup(ptr::null()).is_null());
            let s = b"hello\0" as *const u8 as *const xmlChar;
            let dup = xml_strdup(s);
            assert!(!dup.is_null());
            assert_eq!(xml_strlen(dup), 5);
            assert_eq!(*dup.add(0), b'h');
            assert_eq!(*dup.add(4), b'o');
            assert_eq!(*dup.add(5), 0);
            xmlFreeImpl(dup as *mut c_void);
        }
    }

    /// Compare C strings, including NULL arguments.
    ///
    /// # Safety
    ///
    /// - Every tested pointer is NULL or a static NUL-terminated string
    ///   valid for the duration of `xml_strcmp`'s scan.
    #[test]
    fn test_xml_strcmp() {
        unsafe {
            assert_eq!(xml_strcmp(ptr::null(), ptr::null()), 0);
            assert!(xml_strcmp(b"a\0" as *const u8 as *const xmlChar, ptr::null()) > 0);
            let a = b"abc\0" as *const u8 as *const xmlChar;
            let b = b"abc\0" as *const u8 as *const xmlChar;
            assert_eq!(xml_strcmp(a, b), 0);
            let c = b"abd\0" as *const u8 as *const xmlChar;
            assert!(xml_strcmp(a, c) < 0);
            assert!(xml_strcmp(c, a) > 0);
        }
    }

    /// Concatenate two C strings and verify the result.
    ///
    /// # Safety
    ///
    /// - `a` and `b` are static NUL-terminated strings valid for the call;
    ///   `result` is allocator-owned, valid while read, and freed with
    ///   `xmlFreeImpl` exactly once.
    #[test]
    fn test_xml_strcat() {
        unsafe {
            let a = b"hello \0" as *const u8 as *const xmlChar;
            let b = b"world\0" as *const u8 as *const xmlChar;
            let result = xml_strcat(a, b);
            assert!(!result.is_null());
            assert_eq!(xml_strlen(result), 11);
            let expected = b"hello world\0";
            let mut i = 0;
            while expected[i] != 0 {
                assert_eq!(*result.add(i), expected[i]);
                i += 1;
            }
            xmlFreeImpl(result as *mut c_void);
        }
    }

    /// Convert a byte slice to a NUL-terminated xmlChar buffer.
    ///
    /// # Safety
    ///
    /// - `bytes` is a static slice; `ptr` is allocator-owned, valid for
    ///   `len + 1` bytes, and freed with `xmlFreeImpl` exactly once.
    #[test]
    fn test_bytes_to_xmlstr() {
        unsafe {
            let bytes = b"hello";
            let ptr = bytes_to_xmlstr(bytes);
            assert!(!ptr.is_null());
            assert_eq!(xml_strlen(ptr), 5);
            assert_eq!(*ptr.add(5), 0);
            xmlFreeImpl(ptr as *mut c_void);
        }
    }

    /// Check prefix matching, including NULL arguments.
    ///
    /// # Safety
    ///
    /// - The tested pointers are NULL or static NUL-terminated strings
    ///   valid for the duration of `xml_str_starts_with`'s scan.
    #[test]
    fn test_xml_str_starts_with() {
        unsafe {
            let s = b"hello world\0" as *const u8 as *const xmlChar;
            let prefix = b"hello\0" as *const u8 as *const xmlChar;
            let not_prefix = b"world\0" as *const u8 as *const xmlChar;
            assert!(xml_str_starts_with(s, prefix));
            assert!(!xml_str_starts_with(s, not_prefix));
            assert!(!xml_str_starts_with(ptr::null(), prefix));
            assert!(!xml_str_starts_with(s, ptr::null()));
        }
    }
}