Debian Codegraph @

tests/xml_copy_invariant_tests.rs

raw symbols SCIP
1 //! Low-level libxml2 invariant tests: `xmlCopyDoc` / `xmlCopyNode`
2 //! behavior across our wrapper's lifetime model. Each test imports the
3 //! raw FFI symbols inline.
4
5 use libxml::parser::Parser;
6 use libxml::tree::{Document, Node};
7
8
9 #[test]
10 /// Source-doc corruption test: after a single xmlCopyDoc + xmlFreeDoc
11 /// of the copy, can we still read xml:id attributes off the source?
12 /// If this test fails, there's per-doc dict sharing between
13 /// xmlCopyDoc's source and result that violates libxml2's documented
14 /// independence guarantee.
15 fn xml_copy_doc_does_not_corrupt_source() {
16 use libxml::bindings::{xmlCopyDoc, xmlFreeDoc};
17 let parser = Parser::default();
18 let path = "tests/resources/large_doc.xml";
19 if std::fs::metadata(path).is_err() {
20 return;
21 }
22 let src = parser.parse_file(path).expect("parse");
23 let root = src.get_root_element().expect("root");
24 // Find every section, snapshot its xml:id BEFORE the copy.
25 let sections: Vec<Node> = root
26 .findnodes("descendant::*[local-name()='section']")
27 .unwrap_or_default()
28 .into_iter()
29 .filter(|n| {
30 n.get_parent()
31 .map(|p| p.get_name() == "chapter")
32 .unwrap_or(false)
33 })
34 .collect();
35 let pre: Vec<Option<String>> = sections.iter().map(|s| s.get_attribute("xml:id")).collect();
36
37 // Copy the source doc, then immediately free the copy.
38 unsafe {
39 let copy = xmlCopyDoc(src.doc_ptr(), 1);
40 assert!(!copy.is_null());
41 xmlFreeDoc(copy);
42 }
43
44 // After the copy round-trip, source xml:ids must still be readable.
45 let post: Vec<Option<String>> = sections.iter().map(|s| s.get_attribute("xml:id")).collect();
46 for (i, (p, q)) in pre.iter().zip(post.iter()).enumerate() {
47 assert_eq!(p, q, "section {i} xml:id changed across xmlCopyDoc round-trip: {p:?} -> {q:?}");
48 }
49 }
50
51 #[test]
52 /// Same source-corruption check, but mirroring the host-app's path:
53 /// parse from a STRING (not file), run an `//*[@xml:id]` and a
54 /// `processing-instruction` XPath against the doc (the LaTeXML
55 /// PostDocument init walk), THEN xmlCopyDoc + xmlFreeDoc.
56 fn xml_copy_doc_does_not_corrupt_source_after_init_walks() {
57 use libxml::bindings::{xmlCopyDoc, xmlFreeDoc};
58 let path = "tests/resources/large_doc.xml";
59 if std::fs::metadata(path).is_err() {
60 return;
61 }
62 let xml = std::fs::read_to_string(path).expect("read");
63 let parser = Parser::default();
64 let src = parser.parse_string(&xml).expect("parse");
65 let root = src.get_root_element().unwrap();
66 // Mirror PostDocument::set_document_internal init walks.
67 let mut ctx = libxml::xpath::Context::new(&src).unwrap();
68 let _id_walk = ctx.findnodes("//*[@xml:id]", None).unwrap_or_default();
69 let _pi_walk = ctx
70 .findnodes(".//processing-instruction('latexml')", None)
71 .unwrap_or_default();
72
73 let sections: Vec<Node> = root
74 .findnodes("descendant::*[local-name()='section']")
75 .unwrap_or_default()
76 .into_iter()
77 .filter(|n| {
78 n.get_parent()
79 .map(|p| p.get_name() == "chapter")
80 .unwrap_or(false)
81 })
82 .collect();
83 let pre: Vec<Option<String>> = sections.iter().map(|s| s.get_attribute("xml:id")).collect();
84
85 unsafe {
86 let copy = xmlCopyDoc(src.doc_ptr(), 1);
87 assert!(!copy.is_null());
88 xmlFreeDoc(copy);
89 }
90
91 let post: Vec<Option<String>> = sections.iter().map(|s| s.get_attribute("xml:id")).collect();
92 for (i, (p, q)) in pre.iter().zip(post.iter()).enumerate() {
93 assert_eq!(p, q, "section {i} xml:id changed across copy/free: {p:?} -> {q:?}");
94 }
95 }
96
97 #[test]
98 /// Mirror oxide more precisely: parse_string + init XPath walks +
99 /// detach sections + xmlCopyDoc + xmlFreeDoc + check source xml:id
100 /// readable.
101 fn xml_copy_doc_no_corrupt_after_unlink() {
102 use libxml::bindings::{xmlCopyDoc, xmlFreeDoc};
103 let path = "tests/resources/large_doc.xml";
104 if std::fs::metadata(path).is_err() {
105 return;
106 }
107 let xml = std::fs::read_to_string(path).expect("read");
108 let parser = Parser::default();
109 let src = parser.parse_string(&xml).expect("parse");
110 let root = src.get_root_element().unwrap();
111 let mut ctx = libxml::xpath::Context::new(&src).unwrap();
112 let _ = ctx.findnodes("//*[@xml:id]", None).unwrap_or_default();
113
114 let mut sections: Vec<Node> = root
115 .findnodes("descendant::*[local-name()='section']")
116 .unwrap_or_default()
117 .into_iter()
118 .filter(|n| {
119 n.get_parent()
120 .map(|p| p.get_name() == "chapter")
121 .unwrap_or(false)
122 })
123 .collect();
124
125 // Read xml:id BEFORE unlinking.
126 let pre: Vec<Option<String>> = sections.iter().map(|s| s.get_attribute("xml:id")).collect();
127
128 // Detach each section from its parent.
129 for s in sections.iter_mut() {
130 s.unlink_node();
131 }
132
133 // After unlink, xml:id reads MUST still match pre.
134 let mid: Vec<Option<String>> = sections.iter().map(|s| s.get_attribute("xml:id")).collect();
135 for (i, (p, q)) in pre.iter().zip(mid.iter()).enumerate() {
136 assert_eq!(p, q, "section {i} xml:id changed BY unlink: {p:?} -> {q:?}");
137 }
138
139 // Now xmlCopyDoc + xmlFreeDoc.
140 unsafe {
141 let copy = xmlCopyDoc(src.doc_ptr(), 1);
142 assert!(!copy.is_null());
143 xmlFreeDoc(copy);
144 }
145
146 let post: Vec<Option<String>> = sections.iter().map(|s| s.get_attribute("xml:id")).collect();
147 for (i, (p, q)) in pre.iter().zip(post.iter()).enumerate() {
148 assert_eq!(p, q, "section {i} xml:id changed AFTER copy/free: {p:?} -> {q:?}");
149 }
150 }
151
152 #[test]
153 /// Two xmlCopyNode calls on the SAME source node, with realistic
154 /// LaTeXML doc as the source and the node detached after the first
155 /// call. Checks whether the failure is per-source-doc state or
156 /// per-source-node.
157 fn xml_copy_node_twice_same_source() {
158 use libxml::bindings::{xmlCopyNode, xmlFreeNode};
159 let path = "tests/resources/large_doc.xml";
160 if std::fs::metadata(path).is_err() {
161 return;
162 }
163 let xml = std::fs::read_to_string(path).expect("read");
164 let parser = Parser::default();
165 let src = parser.parse_string(&xml).expect("parse");
166 let root = src.get_root_element().unwrap();
167 // PostDocument-like init.
168 let mut ctx = libxml::xpath::Context::new(&src).unwrap();
169 let _ = ctx.findnodes("//*[@xml:id]", None).unwrap_or_default();
170 let _ = ctx
171 .findnodes(".//processing-instruction('latexml')", None)
172 .unwrap_or_default();
173
174 let sections: Vec<Node> = root
175 .findnodes("descendant::*[local-name()='section']")
176 .unwrap_or_default()
177 .into_iter()
178 .filter(|n| {
179 n.get_parent()
180 .map(|p| p.get_name() == "chapter")
181 .unwrap_or(false)
182 })
183 .collect();
184 assert!(sections.len() >= 2);
185
186 // Detach first section.
187 let mut s1 = sections[0].clone();
188 s1.unlink_node();
189
190 // First copy.
191 unsafe {
192 let c1 = xmlCopyNode(s1.node_ptr(), 1);
193 assert!(!c1.is_null(), "first xmlCopyNode of S1 returned NULL");
194 xmlFreeNode(c1);
195 }
196
197 // Second copy of the SAME node.
198 unsafe {
199 let c2 = xmlCopyNode(s1.node_ptr(), 1);
200 assert!(!c2.is_null(), "second xmlCopyNode of S1 returned NULL");
201 xmlFreeNode(c2);
202 }
203 }
204
205 #[test]
206 /// Two xmlCopyNode calls on DIFFERENT sibling sections, both detached
207 /// before the first copy. Mirrors the exact sequence in
208 /// `Split::process_pages`.
209 fn xml_copy_node_twice_different_sources_after_unlink_all() {
210 use libxml::bindings::{xmlCopyNode, xmlFreeNode};
211 let path = "tests/resources/large_doc.xml";
212 if std::fs::metadata(path).is_err() {
213 return;
214 }
215 let xml = std::fs::read_to_string(path).expect("read");
216 let parser = Parser::default();
217 let src = parser.parse_string(&xml).expect("parse");
218 let root = src.get_root_element().unwrap();
219 let mut ctx = libxml::xpath::Context::new(&src).unwrap();
220 let _ = ctx.findnodes("//*[@xml:id]", None).unwrap_or_default();
221 let _ = ctx
222 .findnodes(".//processing-instruction('latexml')", None)
223 .unwrap_or_default();
224
225 let mut sections: Vec<Node> = root
226 .findnodes("descendant::*[local-name()='section']")
227 .unwrap_or_default()
228 .into_iter()
229 .filter(|n| {
230 n.get_parent()
231 .map(|p| p.get_name() == "chapter")
232 .unwrap_or(false)
233 })
234 .collect();
235 assert!(sections.len() >= 2);
236
237 // Detach ALL sections from the chapter (pop-all).
238 for s in sections.iter_mut() {
239 s.unlink_node();
240 }
241
242 unsafe {
243 let c1 = xmlCopyNode(sections[0].node_ptr(), 1);
244 assert!(!c1.is_null(), "first copy returned NULL");
245 let c2 = xmlCopyNode(sections[1].node_ptr(), 1);
246 assert!(
247 !c2.is_null(),
248 "SECOND copy returned NULL — this is the oxide failure mode"
249 );
250 xmlFreeNode(c1);
251 xmlFreeNode(c2);
252 }
253 }
254
255 #[test]
256 /// Reproduce oxide's exact pre-dup operations: parse_string + init
257 /// XPath walks + Split.process's own `set_attribute("xml:id",
258 /// "TEMPORARY_DOCUMENT_ID")` on the root + getPages XPath descent.
259 /// Then detach + dup pair.
260 fn xml_copy_node_pair_with_split_preamble() {
261 use libxml::bindings::{xmlCopyNode, xmlFreeNode};
262 let path = "tests/resources/large_doc.xml";
263 if std::fs::metadata(path).is_err() {
264 return;
265 }
266 let xml = std::fs::read_to_string(path).expect("read");
267 let parser = Parser::default();
268 let src = parser.parse_string(&xml).expect("parse");
269 let mut root = src.get_root_element().unwrap();
270 // PostDocument init walks.
271 let mut ctx = libxml::xpath::Context::new(&src).unwrap();
272 let _ = ctx.findnodes("//*[@xml:id]", None).unwrap_or_default();
273 let _ = ctx
274 .findnodes(".//processing-instruction('latexml')", None)
275 .unwrap_or_default();
276 // Split.process: assign TEMPORARY_DOCUMENT_ID if root has no xml:id.
277 if root.get_attribute("xml:id").is_none() {
278 root.set_attribute("xml:id", "TEMPORARY_DOCUMENT_ID").ok();
279 }
280 // Split.getPages XPath (a richer path than just descendant::section).
281 let _pages = root
282 .findnodes(
283 "//ltx:section | //ltx:chapter | //ltx:part | //ltx:bibliography \
284 | //ltx:appendix | //ltx:index",
285 )
286 .unwrap_or_default();
287
288 let mut sections: Vec<Node> = root
289 .findnodes("descendant::*[local-name()='section']")
290 .unwrap_or_default()
291 .into_iter()
292 .filter(|n| {
293 n.get_parent()
294 .map(|p| p.get_name() == "chapter")
295 .unwrap_or(false)
296 })
297 .collect();
298 for s in sections.iter_mut() {
299 s.unlink_node();
300 }
301
302 unsafe {
303 let c1 = xmlCopyNode(sections[0].node_ptr(), 1);
304 assert!(!c1.is_null(), "first copy returned NULL");
305 let c2 = xmlCopyNode(sections[1].node_ptr(), 1);
306 assert!(!c2.is_null(), "SECOND copy returned NULL — repro of oxide bug");
307 xmlFreeNode(c1);
308 xmlFreeNode(c2);
309 }
310 }
311
312 #[test]
313 /// dup S1 → XPath on source for resources/PIs → dup S2. Mirrors the
314 /// `findnodes('descendant::ltx:resource')` and PI-scan that oxide's
315 /// PostDocument::new_document runs BETWEEN successive dups.
316 fn xml_copy_node_pair_with_intermediate_xpath_on_source() {
317 use libxml::bindings::{xmlCopyNode, xmlFreeNode};
318 let path = "tests/resources/large_doc.xml";
319 if std::fs::metadata(path).is_err() {
320 return;
321 }
322 let xml = std::fs::read_to_string(path).expect("read");
323 let parser = Parser::default();
324 let src = parser.parse_string(&xml).expect("parse");
325 let mut root = src.get_root_element().unwrap();
326 let mut ctx = libxml::xpath::Context::new(&src).unwrap();
327 let _ = ctx.findnodes("//*[@xml:id]", None).unwrap_or_default();
328 if root.get_attribute("xml:id").is_none() {
329 root.set_attribute("xml:id", "TEMPORARY_DOCUMENT_ID").ok();
330 }
331
332 let mut sections: Vec<Node> = root
333 .findnodes("descendant::*[local-name()='section']")
334 .unwrap_or_default()
335 .into_iter()
336 .filter(|n| {
337 n.get_parent()
338 .map(|p| p.get_name() == "chapter")
339 .unwrap_or(false)
340 })
341 .collect();
342 for s in sections.iter_mut() {
343 s.unlink_node();
344 }
345
346 unsafe {
347 let c1 = xmlCopyNode(sections[0].node_ptr(), 1);
348 assert!(!c1.is_null(), "first copy returned NULL");
349 xmlFreeNode(c1);
350 }
351
352 // Mid-pair: XPath descents on source, mimicking oxide.
353 let _r = root
354 .findnodes("descendant::*[local-name()='resource']")
355 .unwrap_or_default();
356 let _p = root
357 .findnodes(".//processing-instruction('latexml')")
358 .unwrap_or_default();
359 let _i = root
360 .findnodes("//*[@xml:id]")
361 .unwrap_or_default();
362
363 unsafe {
364 let c2 = xmlCopyNode(sections[1].node_ptr(), 1);
365 assert!(
366 !c2.is_null(),
367 "SECOND copy returned NULL after intermediate XPath — repro of oxide bug"
368 );
369 xmlFreeNode(c2);
370 }
371 }
372
373 #[test]
374 /// Closest possible repro: parse, set TEMPORARY_DOCUMENT_ID, get
375 /// pages, detach all, then for each page do dup + create a wrapping
376 /// Document via Document::new_ptr (mirroring what libxml-rs's higher-
377 /// level callers do) + run XPath on the subdoc + run XPath on source.
378 fn xml_copy_node_pair_full_oxide_style() {
379 use libxml::bindings::{xmlCopyNode, xmlNewDoc, xmlDocSetRootElement, xmlSetTreeDoc, xmlReconciliateNs};
380 let path = "tests/resources/large_doc.xml";
381 if std::fs::metadata(path).is_err() {
382 return;
383 }
384 let xml = std::fs::read_to_string(path).expect("read");
385 let parser = Parser::default();
386 let src = parser.parse_string(&xml).expect("parse");
387 let mut root = src.get_root_element().unwrap();
388 let mut ctx = libxml::xpath::Context::new(&src).unwrap();
389 let _ = ctx.findnodes("//*[@xml:id]", None).unwrap_or_default();
390 if root.get_attribute("xml:id").is_none() {
391 root.set_attribute("xml:id", "TEMPORARY_DOCUMENT_ID").ok();
392 }
393
394 let mut sections: Vec<Node> = root
395 .findnodes("descendant::*[local-name()='section']")
396 .unwrap_or_default()
397 .into_iter()
398 .filter(|n| {
399 n.get_parent()
400 .map(|p| p.get_name() == "chapter")
401 .unwrap_or(false)
402 })
403 .collect();
404 for s in sections.iter_mut() {
405 s.unlink_node();
406 }
407
408 let mut subdocs: Vec<Document> = Vec::new();
409 for (i, s) in sections.iter().enumerate() {
410 let sub: Document = unsafe {
411 let copy = xmlCopyNode(s.node_ptr(), 1);
412 assert!(!copy.is_null(), "dup #{i} xmlCopyNode returned NULL");
413 let doc_ptr = xmlNewDoc(c"1.0".as_ptr() as *const u8);
414 xmlDocSetRootElement(doc_ptr, copy);
415 xmlSetTreeDoc(copy, doc_ptr);
416 let _ = xmlReconciliateNs(doc_ptr, copy);
417 Document::new_ptr(doc_ptr)
418 };
419 // Mirror PostDocument::new_document post-dup work:
420 let _id_walk = sub.get_root_element().unwrap()
421 .findnodes("//*[@xml:id]")
422 .unwrap_or_default();
423 let _src_pis = root
424 .findnodes(".//processing-instruction('latexml')")
425 .unwrap_or_default();
426 let _src_res = root
427 .findnodes("descendant::*[local-name()='resource']")
428 .unwrap_or_default();
429 subdocs.push(sub);
430 }
431 drop(sections);
432 drop(src);
433 for s in &subdocs {
434 let _ = s.to_string();
435 }
436 }
437
438 #[test]
439 /// Parse the source with XML_PARSE_NODICT to disable string interning,
440 /// then run the dup pair. If this works while the default parse fails,
441 /// the bug is dict-related in libxml2's xmlStaticCopyNode for this
442 /// document shape.
443 fn xml_copy_node_pair_nodict_parse() {
444 use libxml::bindings::{
445 xmlCopyNode, xmlFreeDoc, xmlFreeNode, xmlReadMemory,
446 xmlParserOption_XML_PARSE_NODICT,
447 };
448 let path = "tests/resources/large_doc.xml";
449 if std::fs::metadata(path).is_err() {
450 return;
451 }
452 let xml = std::fs::read_to_string(path).expect("read");
453 let xml_bytes = xml.as_bytes();
454 unsafe {
455 let doc_ptr = xmlReadMemory(
456 xml_bytes.as_ptr() as *const ::std::os::raw::c_char,
457 xml_bytes.len() as ::std::os::raw::c_int,
458 c"file.xml".as_ptr(),
459 std::ptr::null(),
460 xmlParserOption_XML_PARSE_NODICT as ::std::os::raw::c_int,
461 );
462 assert!(!doc_ptr.is_null(), "xmlReadMemory returned NULL");
463 let doc = Document::new_ptr(doc_ptr);
464 let root = doc.get_root_element().unwrap();
465 // Find sections.
466 let sections: Vec<Node> = root
467 .findnodes("descendant::*[local-name()='section']")
468 .unwrap_or_default()
469 .into_iter()
470 .filter(|n| {
471 n.get_parent()
472 .map(|p| p.get_name() == "chapter")
473 .unwrap_or(false)
474 })
475 .collect();
476 let mut detached: Vec<Node> = sections.to_vec();
477 for s in detached.iter_mut() {
478 s.unlink_node();
479 }
480 let mut copies = Vec::new();
481 for (i, s) in detached.iter().enumerate() {
482 let c = xmlCopyNode(s.node_ptr(), 1);
483 eprintln!("[NODICT] dup #{} ret={:p}", i, c);
484 assert!(!c.is_null(), "dup #{} returned NULL even with NODICT", i);
485 copies.push(c);
486 }
487 for c in copies {
488 xmlFreeNode(c);
489 }
490 drop(detached);
491 drop(doc);
492 let _ = doc_ptr; // just for symmetry
493 // (xmlFreeDoc already called by Document::drop via doc-ptr ownership)
494 let _ = xmlFreeDoc;
495 }
496 }
497
498 #[test]
499 /// Repro using same allocator path as the host application: this test
500 /// is only meaningful when run via a binary that has mimalloc as the
501 /// global allocator (e.g. a fresh integration test compiled with
502 /// mimalloc). For now, kept as documentation; libxml-rs's test runner
503 /// uses the default allocator and will pass.
504 fn _doc_allocator_repro_marker() {
505 // Intentionally empty.
506 }