Something went wrong. Try again.
An XML document tree and serializer for Zig 0.16, built on zxml.
Something went wrong. Try again.
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267// SPDX-FileCopyrightText: © 2026 Jeffrey C. Ollie <jeff@ocjtech.us>// SPDX-License-Identifier: MIT
//! What the tree builder and the serializer must do with input nobody wrote.//!//! The weak property is the usual one -- **return, do not crash**. An error is//! a fine answer and so is a tree; a panic, an out-of-bounds index, a leak or//! a stack overflow is a failure in whatever embedded this library rather than//! in the document that caused it.//!//! The strong one is the interesting one: **whatever parsed must serialize to//! something that parses again**. A tree is not much use if writing it out//! produces a document nobody can read, and the two halves are easy to drift//! apart because nothing else compares them. That property is what found the//! bug behind zxml's name validation -- `<:/>` parsed as an element whose name//! was a single colon, and serialized to `<>`.//!//! `backing` is how a target gets an allocator in both worlds://! `std.testing.allocator` does not exist outside a test build, so the//! standalone driver in `tools/fuzz.zig` points this at a `DebugAllocator` it//! checks for leaks after every input.
const std = @import("std");const builtin = @import("builtin");const Allocator = std.mem.Allocator;const ztree = @import("ztree");
/// The allocator every target uses. A test build gets the testing allocator,/// which fails the test on a leak; the standalone driver sets this to one it/// owns.pub var backing: Allocator = if (builtin.is_test) std.testing.allocator else undefined;
pub const Target = struct { name: []const u8, run: *const fn (input: []const u8) anyerror!void, /// Inputs that have broken something, or that reach a part of the target /// random bytes never would. seeds: []const []const u8,};
pub const targets = [_]Target{ .{ .name = "document", .run = fuzzDocument, .seeds = &document_seeds }, .{ .name = "indent", .run = fuzzIndent, .seeds = &document_seeds }, .{ .name = "html", .run = fuzzHtml, .seeds = &html_seeds }, .{ .name = "strip", .run = fuzzStrip, .seeds = &document_seeds }, .{ .name = "validate", .run = fuzzValidate, .seeds = &dtd_seeds },};
/// Parse, serialize, and parse what came out.fn fuzzDocument(input: []const u8) anyerror!void { return roundTrip(input, .{}, .{});}
/// The same, indented. Indenting inserts text into the document, so it is the/// one output setting that can change what a reparse sees.fn fuzzIndent(input: []const u8) anyerror!void { return roundTrip(input, .{}, .{ .indent = true });}
/// Whitespace stripping on the way in, which removes nodes from a tree that/// has already been built.fn fuzzStrip(input: []const u8) anyerror!void { return roundTrip(input, .{ .whitespace = .strip }, .{});}
/// The HTML output method, which is not XML and so is checked only for not/// crashing: `<br>` is deliberately not well-formed XML.fn fuzzHtml(input: []const u8) anyerror!void { const doc = ztree.parse(backing, input, .{}) catch return; defer doc.destroy(); const out = try ztree.serialize.toOwnedSlice(backing, doc, .{ .method = .html }); defer backing.free(out);}
/// Read the document type, throw the source away, then reach a verdict.////// Freeing the source before validating is the property worth having here./// The declarations are copied into the document's arena precisely so that a/// tree outlives the text it came from, and a validator that reached back into/// that text would read freed memory -- which is the kind of bug that surfaces/// in six months rather than in the test that introduced it.fn fuzzValidate(input: []const u8) anyerror!void { const source = try backing.dupe(u8, input); const doc = ztree.parse(backing, source, .{ .dtd = true }) catch { backing.free(source); return; }; defer doc.destroy(); backing.free(source);
const report = ztree.validate.run(backing, doc) catch return; defer report.deinit(backing); for (report.problems) |problem| { // A problem nobody can act on is not a problem that was found. if (problem.detail.len == 0) return error.EmptyDetail; if (problem.node >= doc.nodes.items.len) return error.ProblemOutOfRange; }}
fn roundTrip( input: []const u8, parse_options: ztree.ParseOptions, output: ztree.serialize.Output,) anyerror!void { const doc = ztree.parse(backing, input, parse_options) catch return; defer doc.destroy();
const out = try ztree.serialize.toOwnedSlice(backing, doc, output); defer backing.free(out);
const again = ztree.parse(backing, out, parse_options) catch |err| { std.debug.print("serialized output did not parse again: {t}\n{s}\n", .{ err, out }); return error.RoundTripFailed; }; defer again.destroy();}
const document_seeds = [_][]const u8{ "<a/>", "<a></a>", "<a>text</a>", "<a><b><c/></b></a>", "<a xmlns=\"urn:x\"><b/></a>", "<a xmlns:p=\"urn:p\"><p:b p:c=\"1\"/></a>", "<a xmlns:p=\"urn:p\"><p:b xmlns:p=\"urn:q\"/></a>", "<a>&<>"'</a>", "<a>AA</a>", "<a><![CDATA[<not markup>]]></a>", "<a><!-- comment --></a>", "<a><?target data?></a>", "<?xml version=\"1.0\" encoding=\"UTF-8\"?><a/>", "<!DOCTYPE a><a/>", "<a b=\"one\ttwo\nthree\"/>", "<a b=\"<&"\"/>", "<a/><b/>", "<a>", "</a>", "<a></b>", "<p:a/>", "<a xmlns:p=\"\"/>", "<a b='1' b='2'/>", "<a>]]></a>", "<a>\r\n</a>", "<a xml:space=\"preserve\"> </a>", "<a>&undefined;</a>", // Names a namespace cannot read. zxml rejects these now; the seeds stay // because they are what the round-trip property was added to catch. "<:/>", "<a:/>", "<a xmlns=\"urn:x\"><:/></a>", // Mixed content, which indenting must not reflow. "<a>one<b>two</b>three</a>", "", "not xml at all",};
/// Documents with a document type, since random bytes never form one and the/// declarations are otherwise never reached.const dtd_seeds = [_][]const u8{ "<!DOCTYPE a [<!ELEMENT a EMPTY>]><a/>", "<!DOCTYPE a [<!ELEMENT a (b+)><!ELEMENT b EMPTY>]><a><b/><b/></a>", "<!DOCTYPE a [<!ELEMENT a (#PCDATA|b)*><!ELEMENT b EMPTY>]><a>x<b/>y</a>", "<!DOCTYPE a [<!ELEMENT a ((b|c)*,d?)><!ELEMENT b EMPTY><!ELEMENT c EMPTY><!ELEMENT d EMPTY>]><a><b/><c/><d/></a>", "<!DOCTYPE a [<!ELEMENT a EMPTY><!ATTLIST a id ID #REQUIRED>]><a id=\"x\"/>", "<!DOCTYPE a [<!ELEMENT a EMPTY><!ATTLIST a k (p|q) \"p\" v CDATA #FIXED \"1\">]><a/>", "<!DOCTYPE a [<!ELEMENT a (b*)><!ELEMENT b EMPTY><!ATTLIST b id ID #IMPLIED ref IDREF #IMPLIED>]><a><b id=\"x\" ref=\"y\"/><b id=\"y\"/></a>", "<!DOCTYPE a [<!ENTITY e \"text\"><!ELEMENT a (#PCDATA)>]><a>&e;</a>", "<!DOCTYPE a [<!ENTITY e SYSTEM \"x\" NDATA n><!NOTATION n SYSTEM \"y\"><!ELEMENT a EMPTY><!ATTLIST a p ENTITY #IMPLIED>]><a p=\"e\"/>", "<!DOCTYPE a [<!ENTITY % p \"<!ELEMENT a EMPTY>\">%p;]><a/>", // An external subset, which is named and never read, so no verdict is // reached at all. "<!DOCTYPE a SYSTEM \"a.dtd\"><a/>", // Every kind of invalid: wrong root, undeclared element, unsatisfied // model, duplicate ID, dangling reference. "<!DOCTYPE a [<!ELEMENT a EMPTY>]><b/>", "<!DOCTYPE a [<!ELEMENT a (b)><!ELEMENT b EMPTY>]><a><c/></a>", "<!DOCTYPE a [<!ELEMENT a (b,b)><!ELEMENT b EMPTY>]><a><b/></a>", "<!DOCTYPE a [<!ELEMENT a (b*)><!ELEMENT b EMPTY><!ATTLIST b id ID #IMPLIED>]><a><b id=\"x\"/><b id=\"x\"/></a>", // Declarations that do not parse, and a document type with nothing in it. "<!DOCTYPE a [bogus]><a/>", "<!DOCTYPE a []><a/>", "<!DOCTYPE a><a/>", "<a/>", "",};
const html_seeds = [_][]const u8{ "<html><body><p>hi</p></body></html>", "<html><head><title>T</title></head><body><br/><hr/></body></html>", "<html><head><meta charset=\"x\"/></head><body/></html>", "<html><script>if (a < b && c) f();</script></html>", "<html><input checked=\"checked\"/></html>", "<html><pre><x/><y/></pre><picture><x/><y/></picture></html>", "<html><unknownelem><a1/><a2/></unknownelem></html>", "<html/>",};
// -- tests -------------------------------------------------------------------
const testing = std.testing;
// Replays every seed of every target. This is what makes the corpus a// regression suite rather than a pile of inputs only the fuzzer ever reads.test "the seed corpus still passes every target" { for (targets) |target| { for (target.seeds) |seed| { target.run(seed) catch |err| { std.debug.print("target {s} failed on seed: {s}\n", .{ target.name, seed }); return err; }; } }}
/// Each target also gets a `std.testing.fuzz` test of its own, which is what/// `zig build fuzz --fuzz` drives one at a time.////// `Smith` is how 0.16 hands bytes to a target, and it does not hand over the/// input directly: `slice` reads a four-byte little-endian length and then/// that many bytes. A corpus entry therefore has to carry that length, which/// is what `smithCorpus` puts in front of each seed. Without it every seed/// decodes to the empty string and the run reports millions of iterations/// having tested nothing at all.fn fuzzOne(comptime index: usize) fn (void, *std.testing.Smith) anyerror!void { return struct { fn run(_: void, smith: *std.testing.Smith) anyerror!void { var buf: [16 * 1024]u8 = undefined; const len = smith.slice(&buf); return targets[index].run(buf[0..len]); } }.run;}
/// Puts a `Smith`-readable length in front of each seed.inline fn smithCorpus(comptime seeds: []const []const u8) []const []const u8 { comptime { var out: [seeds.len][]const u8 = undefined; for (seeds, &out) |seed, *slot| { var length: [4]u8 = undefined; std.mem.writeInt(u32, &length, @intCast(seed.len), .little); slot.* = length ++ seed; } const frozen = out; return &frozen; }}
test "fuzz document" { try std.testing.fuzz({}, fuzzOne(0), .{ .corpus = comptime smithCorpus(&document_seeds) });}
test "fuzz indent" { try std.testing.fuzz({}, fuzzOne(1), .{ .corpus = comptime smithCorpus(&document_seeds) });}
test "fuzz html" { try std.testing.fuzz({}, fuzzOne(2), .{ .corpus = comptime smithCorpus(&html_seeds) });}
test "fuzz strip" { try std.testing.fuzz({}, fuzzOne(3), .{ .corpus = comptime smithCorpus(&document_seeds) });}
test "fuzz validate" { try std.testing.fuzz({}, fuzzOne(4), .{ .corpus = comptime smithCorpus(&dtd_seeds) });}