Skip to content

Reject XML node insertions that would create cycles - #1111

Open
mzfr wants to merge 1 commit into
leethomason:masterfrom
mzfr:fix/reject-cyclic-node-insertion
Open

mzfr wants to merge 1 commit into
leethomason:masterfrom
mzfr:fix/reject-cyclic-node-insertion

Conversation

@mzfr

@mzfr mzfr commented Nov 18, 2026

Copy link
Copy Markdown
  • Reject inserting a node beneath itself or one of its descendants.
  • Perform the hierarchy check before unlinking, so rejected insertions leave the tree unchanged.
  • Apply the same validation to InsertEndChild, InsertFirstChild, and InsertAfterChild while preserving valid existing-node moves.
  • Document the new null-return case and add regression coverage for traversal, cloning, printing, and destruction of the resulting valid trees.

Bug

The shared insertion preamble previously verified document ownership and then immediately unlinked an existing node. It did not verify that the proposed child was the destination node itself or an ancestor of it. Relinking such a node creates a cycle in the DOM. Recursive operations such as Accept, DeepClone, XML printing, and document destruction can then exhaust the stack.

This includes the self-insertion case reported in #915 and the broader strict-ancestor case. It is separate from the adjacent-child InsertAfterChild issue handled by #1103; this change does not alter that case.

Fix

Before any unlinking or allocation tracking, walk from the proposed parent through its _parent chain. If the node being inserted is encountered, return null without modifying either tree. The check lives in the shared insertion preamble used by all three insertion APIs.

Tests

Regression tests cover, for each insertion API:

  • rejected self insertion;
  • rejected strict-ancestor insertion;
  • unchanged serialization through Accept;
  • successful DeepClone and printing after rejection;
  • a valid move of an already-linked node;
  • normal scope-exit destruction.

Validation with GCC 16.2.1:

  • release xmltest: Pass 549, Fail 0;
  • debug xmltest (TINYXML2_DEBUG): Pass 549, Fail 0;
  • ASan xmltest: Pass 549, Fail 0, no diagnostics;
  • UBSan xmltest: Pass 549, Fail 0, no diagnostics;
  • focused reproducer matrix: all 27 combinations of 3 insertion APIs, 3 traversal/clone/print sinks, and normal/ASan/UBSan exited 0 with no sanitizer diagnostics.

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant