// SPDX-FileCopyrightText: © 2026 Jeffrey C. Ollie // 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: `
` 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{ "", "", "text", "", "", "", "", "&<>"'", "AA", "]]>", "", "", "", "", "", "", "", "", "", "", "", "", "", "]]>", "\r\n", " ", "&undefined;", // Names a namespace cannot read. zxml rejects these now; the seeds stay // because they are what the round-trip property was added to catch. "<:/>", "", "<:/>", // Mixed content, which indenting must not reflow. "onetwothree", "", "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{ "]>", "]>", "]>xy", "]>", "]>", "]>", "]>", "]>&e;", "]>", "\">%p;]>", // An external subset, which is named and never read, so no verdict is // reached at all. "", // Every kind of invalid: wrong root, undeclared element, unsatisfied // model, duplicate ID, dangling reference. "]>", "]>", "]>", "]>", // Declarations that do not parse, and a document type with nothing in it. "", "", "", "", "", }; const html_seeds = [_][]const u8{ "

hi

", "T

", "", "", "", "
", "", "", }; // -- 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) }); }