Debian Codegraph @

tests/rust_owned_tests.rs

raw symbols SCIP
1 //! Tests for `Node::set_rust_owned` and the `Linkage` state machine —
2 //! ownership transfer for detached subtrees, drop-order invariants, and
3 //! misuse-mode guards.
4
5 use libxml::parser::Parser;
6 use libxml::tree::{Document, Node};
7
8 // ---- set_rust_owned: ownership transfer for detached subtrees ---------
9
10 #[test]
11 /// `Node::is_rust_owned` defaults to false for newly-wrapped nodes.
12 fn rust_owned_default_is_false() {
13 let parser = Parser::default();
14 let doc = parser
15 .parse_string("<r><a/></r>".as_bytes())
16 .expect("parse");
17 let root = doc.get_root_element().expect("root");
18 assert!(!root.is_rust_owned());
19 let a = root.get_first_element_child().expect("a");
20 assert!(!a.is_rust_owned());
21 }
22
23 #[test]
24 /// `set_rust_owned` is idempotent — calling it twice does not cause
25 /// a double free; the C node is freed exactly once when the last
26 /// `Node` clone drops.
27 fn rust_owned_idempotent() {
28 let parser = Parser::default();
29 let doc = parser
30 .parse_string("<r><a/></r>".as_bytes())
31 .expect("parse");
32 let root = doc.get_root_element().expect("root");
33 let mut a = root.get_first_element_child().expect("a");
34 a.unlink_node();
35 // After unlink, source doc no longer reaches the subtree via tree
36 // walks, but `node->doc` still points at the source. Mark it ours.
37 a.set_rust_owned();
38 a.set_rust_owned(); // idempotent — second call is a no-op
39 assert!(a.is_rust_owned());
40 drop(a);
41 drop(doc);
42 // No crash, no double-free.
43 }
44
45 #[test]
46 /// The `rust_owned` flag is sticky across clones: setting it on one
47 /// clone makes every clone observe it, and the C node is freed exactly
48 /// once when the last clone drops.
49 fn rust_owned_flag_visible_through_clones() {
50 let parser = Parser::default();
51 let doc = parser
52 .parse_string("<r><a/></r>".as_bytes())
53 .expect("parse");
54 let root = doc.get_root_element().expect("root");
55 let mut a = root.get_first_element_child().expect("a");
56 a.unlink_node();
57
58 let a_clone1 = a.clone();
59 let a_clone2 = a.clone();
60
61 // Set the flag through one clone; observe it through the others.
62 a_clone1.set_rust_owned();
63 assert!(a.is_rust_owned());
64 assert!(a_clone1.is_rust_owned());
65 assert!(a_clone2.is_rust_owned());
66
67 // Drop in some order; only the last drop should free.
68 drop(a);
69 drop(a_clone1);
70 drop(a_clone2);
71 drop(doc);
72 }
73
74 #[test]
75 /// Drop ordering matters: a rust-owned orphan MUST drop while its
76 /// source document is still alive. The orphan's strings are typically
77 /// interned in `source_doc->dict`; libxml2's `xmlFreeNode` consults
78 /// `node->doc->dict` via `xmlDictOwns` to decide whether to free each
79 /// string. If the source doc has already been freed, that read is a
80 /// UAF — in libxml2, not in this wrapper. So the supported pattern is:
81 /// 1. parse / build source doc
82 /// 2. extract subtrees (`unlink_node` + `dup_node_into_new_doc`)
83 /// 3. mark source-side detached nodes `set_rust_owned`
84 /// 4. drop them (frees their C subtree)
85 /// 5. drop source doc
86 ///
87 /// This test exercises that order.
88 fn rust_owned_drops_before_source_doc() {
89 let parser = Parser::default();
90 let doc = parser
91 .parse_string("<r><a><b/></a></r>".as_bytes())
92 .expect("parse");
93 let root = doc.get_root_element().expect("root");
94 let mut a = root.get_first_element_child().expect("a");
95 a.unlink_node();
96 a.set_rust_owned();
97 drop(a);
98 drop(doc);
99 }
100
101 #[test]
102 /// After `dup_node_into_new_doc`, the original detached subtree is no
103 /// longer referenced by the source document's tree topology and can be
104 /// safely marked rust-owned. The duplicated copy in the new sub-doc
105 /// must remain valid after the original is dropped.
106 fn rust_owned_after_dup_node_into_new_doc() {
107 let parser = Parser::default();
108 let doc = parser
109 .parse_string("<r><a id=\"a1\"><b>hello</b></a><c/></r>".as_bytes())
110 .expect("parse");
111 let root = doc.get_root_element().expect("root");
112 let mut a = root.get_first_element_child().expect("a");
113 a.unlink_node();
114
115 let sub = Document::dup_node_into_new_doc(&a).expect("dup");
116 // The source-side `a` is no longer needed; transfer ownership to Rust
117 // so that dropping its wrapper actually reclaims the C alloc rather
118 // than leaking it (source doc's xmlFreeDoc won't reach it).
119 a.set_rust_owned();
120 drop(a);
121
122 // The duplicated copy in `sub` is independent and must still be
123 // intact.
124 let sub_root = sub.get_root_element().expect("sub root");
125 assert_eq!(sub_root.get_name(), "a");
126 let sub_b = sub_root.get_first_element_child().expect("sub b");
127 assert_eq!(sub_b.get_name(), "b");
128 assert_eq!(sub_b.get_content(), "hello");
129
130 // `c` (sibling that was *not* unlinked) is still in the source doc.
131 let c = root.get_last_element_child().expect("c");
132 assert_eq!(c.get_name(), "c");
133
134 drop(sub);
135 drop(doc);
136 }
137
138 #[test]
139 /// Stress: split-extract every section out of a multi-section source
140 /// doc, dup each one into its own sub-doc, and mark the source-side
141 /// extracted node rust-owned. Source doc and all sub-docs must drop
142 /// cleanly with no UAF and no double-free.
143 fn rust_owned_split_extract_stress() {
144 let parser = Parser::default();
145 let mut xml = String::from("<book>");
146 for i in 0..16 {
147 xml.push_str(&format!(
148 "<section id=\"s{}\"><h>title {}</h><p>body {}</p></section>",
149 i, i, i
150 ));
151 }
152 xml.push_str("</book>");
153 let doc = parser.parse_string(xml.as_bytes()).expect("parse");
154 let root = doc.get_root_element().expect("root");
155
156 let mut sections: Vec<Node> = root.get_child_elements();
157 let mut subdocs: Vec<Document> = Vec::new();
158
159 for n in sections.iter_mut() {
160 n.unlink_node();
161 let sub = Document::dup_node_into_new_doc(n).expect("dup");
162 n.set_rust_owned();
163 subdocs.push(sub);
164 }
165
166 // Drop the source-side extracted nodes first.
167 drop(sections);
168 // Source doc still has its root (now childless of element kids).
169 let root2 = doc.get_root_element().expect("root still there");
170 assert_eq!(root2.get_name(), "book");
171
172 // Sub-docs remain independently valid.
173 for (i, sub) in subdocs.iter().enumerate() {
174 let sub_root = sub.get_root_element().expect("sub root");
175 assert_eq!(sub_root.get_name(), "section");
176 assert_eq!(
177 sub_root.get_attribute("id"),
178 Some(format!("s{}", i))
179 );
180 }
181
182 drop(subdocs);
183 drop(doc);
184 }
185
186 #[test]
187 /// When a rust-owned subtree is dropped, libxml2's `xmlFreeNode`
188 /// recursively frees every descendant in C. Any wrapper that points
189 /// at a descendant of that subtree must therefore drop *before* the
190 /// rust-owned ancestor — otherwise it would dereference a freed
191 /// pointer. This test exercises the supported order: descendant
192 /// wrappers drop first, then the rust-owned ancestor.
193 fn rust_owned_descendant_wrappers_drop_before_parent() {
194 let parser = Parser::default();
195 let doc = parser
196 .parse_string("<r><a><b><c/><d/></b><e/></a></r>".as_bytes())
197 .expect("parse");
198 let root = doc.get_root_element().expect("root");
199 let mut a = root.get_first_element_child().expect("a");
200 a.unlink_node();
201 a.set_rust_owned();
202
203 // Hold wrappers to descendants. They must drop before `a` does.
204 let b = a.get_first_element_child().expect("b");
205 let c = b.get_first_element_child().expect("c");
206 let d = c.get_next_element_sibling().expect("d");
207 let e = a.get_last_element_child().expect("e");
208
209 // Verify the wrappers see the expected names.
210 assert_eq!(b.get_name(), "b");
211 assert_eq!(c.get_name(), "c");
212 assert_eq!(d.get_name(), "d");
213 assert_eq!(e.get_name(), "e");
214
215 // Drop descendant wrappers first (no-op: they are Linked under `a`).
216 drop(c);
217 drop(d);
218 drop(b);
219 drop(e);
220
221 // Now drop `a` — fires xmlFreeNode and recursively reclaims the
222 // whole subtree. No prior wrapper is alive to dereference the freed
223 // descendants.
224 drop(a);
225 drop(doc);
226 }
227
228 #[test]
229 /// `Document::import_node` must reject `RustOwned` source nodes in
230 /// release builds (where the `set_linked` debug-assert is compiled
231 /// out). The early return preserves wrapper invariants — without it,
232 /// a release-build caller could re-link a rust-owned source via
233 /// `set_linked` and set up a later double-free.
234 fn import_node_rejects_rust_owned_source() {
235 let parser = Parser::default();
236 let src = parser
237 .parse_string("<r><a/></r>".as_bytes())
238 .expect("parse src");
239 let mut dest = parser
240 .parse_string("<root/>".as_bytes())
241 .expect("parse dest");
242
243 let src_root = src.get_root_element().expect("src root");
244 let mut a = src_root.get_first_element_child().expect("a");
245 a.unlink_node();
246 a.set_rust_owned();
247
248 // Must not import a rust-owned node — would set up a double-free.
249 let result = dest.import_node(&mut a);
250 assert!(result.is_err(), "import_node must reject RustOwned source");
251 // Wrapper state unchanged.
252 assert!(a.is_rust_owned());
253
254 drop(a);
255 drop(dest);
256 drop(src);
257 }
258
259 #[test]
260 /// `set_rust_owned` must not be called on a `Linked` node. In debug
261 /// builds we panic via `debug_assert!`; this test exercises the guard.
262 /// In release builds the call would be a silent UB, leaving the
263 /// wrapper poised to free a still-tree-attached node.
264 #[should_panic(expected = "set_rust_owned called on a Linked node")]
265 #[cfg(debug_assertions)]
266 fn rust_owned_panics_on_linked_node() {
267 let parser = Parser::default();
268 let doc = parser
269 .parse_string("<r><a/></r>".as_bytes())
270 .expect("parse");
271 let root = doc.get_root_element().expect("root");
272 let a = root.get_first_element_child().expect("a");
273 // `a` is still in the tree — must NOT mark it rust-owned.
274 a.set_rust_owned();
275 drop(doc);
276 }
277
278 #[test]
279 /// Re-attaching a `RustOwned` node via `add_child` (or any other
280 /// linker) is a misuse pattern. In debug builds, the crate-private
281 /// `set_linked` transition fires a `debug_assert!` to catch this. We
282 /// exercise the guard via the public `add_child` path.
283 #[should_panic(expected = "set_linked called on a RustOwned node")]
284 #[cfg(debug_assertions)]
285 fn rust_owned_relink_via_add_child_panics_in_debug() {
286 let parser = Parser::default();
287 let doc = parser
288 .parse_string("<r><a/></r>".as_bytes())
289 .expect("parse");
290 let mut root = doc.get_root_element().expect("root");
291 let mut a = root.get_first_element_child().expect("a");
292 a.unlink_node();
293 a.set_rust_owned();
294 // Intentional misuse: re-attach a rust-owned node. The crate-private
295 // `set_linked` called by `add_child` must trip the debug assertion.
296 let _ = root.add_child(&mut a);
297 drop(doc);
298 }
299
300 #[test]
301 /// Mixed lifetime: some unlinked subtrees are re-attached to the
302 /// source doc, others are marked rust-owned and dropped. The wrapper
303 /// must NOT free re-attached nodes (the source doc still owns them),
304 /// and MUST free the rust-owned ones.
305 fn rust_owned_mixed_with_reattach() {
306 let parser = Parser::default();
307 let doc = parser
308 .parse_string("<r><a/><b/><c/><d/></r>".as_bytes())
309 .expect("parse");
310 let mut root = doc.get_root_element().expect("root");
311
312 let kids: Vec<Node> = root.get_child_elements();
313 // Names: a, b, c, d
314 let mut a = kids[0].clone();
315 let mut b = kids[1].clone();
316 let mut c = kids[2].clone();
317 let mut d = kids[3].clone();
318 drop(kids);
319
320 // Detach all four.
321 a.unlink_node();
322 b.unlink_node();
323 c.unlink_node();
324 d.unlink_node();
325
326 // Re-attach a and c; mark b and d rust-owned.
327 root.add_child(&mut a).expect("re-attach a");
328 root.add_child(&mut c).expect("re-attach c");
329 b.set_rust_owned();
330 d.set_rust_owned();
331
332 drop(b);
333 drop(d);
334
335 // a and c should still be there and walkable.
336 let names: Vec<String> = root
337 .get_child_elements()
338 .iter()
339 .map(|n| n.get_name())
340 .collect();
341 assert_eq!(names, vec!["a", "c"]);
342
343 drop(a);
344 drop(c);
345 drop(root);
346 drop(doc);
347 }