Something went wrong. Try again.
An XSLT 1.0 processor for Zig 0.16, built on zxml.
Something went wrong. Try again.
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479// SPDX-FileCopyrightText: © 2026 Jeffrey C. Ollie <jeff@ocjtech.us>// SPDX-License-Identifier: MIT
//! What the parsers must do with input nobody wrote.//!//! Everything here takes bytes from outside: an XPath expression out of a//! stylesheet, a stylesheet off disk, a document off the network. The property//! each target checks is the same and is deliberately weak -- **return, do not//! crash**. An error is a fine answer and so is a result; a panic, an//! out-of-bounds index, a leak or a stack overflow is not, because each of//! those is a failure in whatever program embedded this library rather than in//! the document that caused it.//!//! The targets are ordinary tests as well as fuzz targets, so `zig build test`//! runs every one of them over the seeds below without a fuzzer being//! involved. The seeds are the shapes that have broken something at least once//! -- deep nesting, unterminated constructs, a prefix nothing declares -- and//! replaying them is the cheapest regression suite in the project.//!//! `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 zxsl = @import("zxsl");
/// 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 = "xpath", .run = fuzzXPath, .seeds = &xpath_seeds }, .{ .name = "pattern", .run = fuzzPattern, .seeds = &xpath_seeds }, .{ .name = "document", .run = fuzzDocument, .seeds = &document_seeds }, .{ .name = "stylesheet", .run = fuzzStylesheet, .seeds = &stylesheet_seeds }, .{ .name = "transform", .run = fuzzTransform, .seeds = &transform_seeds }, .{ .name = "date", .run = fuzzDate, .seeds = &date_seeds }, .{ .name = "duration", .run = fuzzDuration, .seeds = &duration_seeds }, .{ .name = "picture", .run = fuzzPicture, .seeds = &picture_seeds },};
/// Compiling an expression must never do anything but return or fail.fn fuzzXPath(input: []const u8) anyerror!void { var compiled = zxsl.xpath.Compiled.init(backing, input, .none) catch return; defer compiled.deinit();}
fn fuzzPattern(input: []const u8) anyerror!void { var arena: std.heap.ArenaAllocator = .init(backing); defer arena.deinit(); _ = zxsl.pattern.compile(arena.allocator(), input, .none) catch return;}
/// Parsing a document, and then serializing what came back.////// The serializer is included because it is the half that is easy to forget:/// a tree that parsed is not necessarily a tree that can be written, and a/// name or a namespace that came out of a hostile document reaches the writer/// without anything in between having looked at it.fn fuzzDocument(input: []const u8) anyerror!void { const doc = zxsl.tree.parse(backing, input, .{}) catch return; defer doc.destroy();
const out = try zxsl.serialize.toOwnedSlice(backing, doc, .{}); defer backing.free(out);
// What a parser produced must parse again. This is the one property here // that is more than "did not crash": a serializer that escapes too little // makes a document that is no longer well-formed, and nothing else would // notice. const again = zxsl.tree.parse(backing, out, .{}) catch |err| { std.debug.print("serialized output did not parse again: {t}\n{s}\n", .{ err, out }); return error.RoundTripFailed; }; defer again.destroy();}
fn fuzzStylesheet(input: []const u8) anyerror!void { const sheet = zxsl.stylesheet.parse(backing, input, .{}) catch return; defer sheet.destroy();}
/// A stylesheet and a document together, which is the only way to reach the/// engine at all.////// The two are carved out of one buffer because that is what a fuzzer hands/// over: the first two bytes are a little-endian length for the stylesheet and/// the rest is the document. A length past the end takes everything, so a/// mutation that grows the buffer still produces a usable pair rather than/// nothing.fn fuzzTransform(input: []const u8) anyerror!void { if (input.len < 2) return; const split = @min(2 + @as(usize, std.mem.readInt(u16, input[0..2], .little)), input.len);
const sheet = zxsl.stylesheet.parse(backing, input[2..split], .{}) catch return; defer sheet.destroy();
const source = zxsl.tree.parse(backing, input[split..], .{}) catch return; defer source.destroy();
const out = zxsl.transform.transformToString(backing, sheet, source, .{}) catch return; defer backing.free(out);}
/// One of XML Schema's date types, and the writing of it.////// The property is a round trip: whatever parsed must be writable, and what/// was written must parse back to the same value. A date is a structure with/// eight fields and eight spellings, and the way to get it wrong is for the/// reader and the writer to disagree about which spelling carries which/// field.////// `has_offset` is exempt for a dateTime, and only for a dateTime, because/// libxslt writes an offset there whether or not one was read -- see/// `date.write`.fn fuzzDate(input: []const u8) anyerror!void { const first = zxsl.date.parse(input) orelse return;
const written = try zxsl.date.toOwnedString(backing, first); defer backing.free(written);
const again = zxsl.date.parse(written) orelse { std.debug.print("written date did not parse again: {s} -> {s}\n", .{ input, written }); return error.RoundTripFailed; };
if (first.kind != again.kind or first.dt.year != again.dt.year or first.dt.month != again.dt.month or first.dt.day != again.dt.day or first.dt.hour != again.dt.hour or first.dt.minute != again.dt.minute or first.dt.second != again.dt.second or first.dt.nanosecond != again.dt.nanosecond or first.dt.offset != again.dt.offset or (first.kind != .date_time and first.has_offset != again.has_offset)) { std.debug.print("date changed on a round trip: {s} -> {s}\n", .{ input, written }); return error.RoundTripFailed; }}
/// An ISO 8601 duration, and the writing of it.////// The same round trip, and it holds exactly: the parser never produces a/// duration whose fields disagree in sign, which is the one shape the writer/// cannot spell.fn fuzzDuration(input: []const u8) anyerror!void { const parsed = zxsl.datetime.iso8601.parseDuration(input) catch return;
var buf: [256]u8 = undefined; var w = std.Io.Writer.fixed(&buf); parsed.value.format(&w) catch return; const written = w.buffered();
const again = zxsl.datetime.iso8601.parseDuration(written) catch |err| { std.debug.print("written duration did not parse again: {t}\n{s} -> {s}\n", .{ err, input, written }); return error.RoundTripFailed; }; if (!parsed.value.eql(again.value)) { std.debug.print("duration changed on a round trip: {s} -> {s}\n", .{ input, written }); return error.RoundTripFailed; }}
/// A `format-number` picture, which is a small language of its own and is/// handed straight from the stylesheet to a routine that indexes into it.////// Return or fail is the whole property: an unusable picture is an error the/// engine turns into the plain number, and there is nothing to compare/// against.fn fuzzPicture(input: []const u8) anyerror!void { for ([_]f64{ 0, 1, -1, 0.5, -1234.5678, 1e300 }) |n| { const out = zxsl.number.formatNumber(backing, n, input, .{}) catch continue; backing.free(out); }}
/// Builds an input for the `transform` target out of a stylesheet and a/// document, so that the seeds below read as what they are.fn transformInput(comptime stylesheet: []const u8, comptime document: []const u8) []const u8 { var buf: [2]u8 = undefined; std.mem.writeInt(u16, &buf, stylesheet.len, .little); return buf ++ stylesheet ++ document;}
const xpath_seeds = [_][]const u8{ "", ".", "/", "//", "*", "@", "@*", "a/b/c", "a[1][2][3]", "//a//b//c", "$x", "$", "'unterminated", "\"", "concat(", "concat()", "count(//a|//b)", "1 + 2 * 3 div 4 mod 5", "- - - -1", "a and b or c and d", "div div div", "mod mod mod", "processing-instruction('x')", "processing-instruction(", "node()", "text()[1]", "ancestor-or-self::node()", "bogus::a", "p:*", "p:a", "e:f($x)/a", "((((((((((1))))))))))", "a[a[a[a[a[a[a[a]]]]]]]", ":", "::", "a::", "@::", "1e5", ".5", "5.", "..", "...", "a//", "|", "a|", "(a|b)/c[1]", "key('k','v')/x", "id('x')", "substring-before(., '}')",};
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>&<>"'</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>", "</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>", // A name that is a bare colon. zxml accepts it, and a tree that kept it // would serialize to `<>`; found by the fuzzer's round-trip property. "<a xmlns=\"urn:x\"><:/></a>", "<a:/>", "<:a/>", "", "not xml at all",};
const stylesheet_seeds = [_][]const u8{ "<xsl:stylesheet version=\"1.0\" xmlns:xsl=\"http://www.w3.org/1999/XSL/Transform\"/>", \\<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform"> \\<xsl:template match="/"><out/></xsl:template> \\</xsl:stylesheet> , \\<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform"> \\<xsl:template match="a|b|c" priority="not-a-number"/> \\</xsl:stylesheet> , \\<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform"> \\<xsl:key name="k" match="a" use="@b"/> \\<xsl:output method="html" indent="yes"/> \\<xsl:strip-space elements="* p:*"/> \\</xsl:stylesheet> , "<html xsl:version=\"1.0\" xmlns:xsl=\"http://www.w3.org/1999/XSL/Transform\"/>", "<not-a-stylesheet/>", "",};
const transform_seeds = [_][]const u8{ transformInput( \\<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform"> \\<xsl:template match="/"><xsl:apply-templates/></xsl:template> \\</xsl:stylesheet> , "<r><a>one</a><b>two</b></r>"), transformInput( \\<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform"> \\<xsl:template match="@*|node()"><xsl:copy><xsl:apply-templates select="@*|node()"/></xsl:copy></xsl:template> \\</xsl:stylesheet> , "<r a=\"1\"><b><c/></b></r>"), transformInput( \\<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform"> \\<xsl:output method="text"/> \\<xsl:template match="/"><xsl:for-each select="//n"><xsl:sort select="." data-type="number"/><xsl:value-of select="."/></xsl:for-each></xsl:template> \\</xsl:stylesheet> , "<r><n>3</n><n>1</n><n>2</n></r>"), // A template that calls itself, which must hit the recursion limit rather // than the bottom of the stack. transformInput( \\<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform"> \\<xsl:template match="/"><xsl:call-template name="loop"/></xsl:template> \\<xsl:template name="loop"><xsl:call-template name="loop"/></xsl:template> \\</xsl:stylesheet> , "<r/>"),};
// -- 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 Zig's fuzzer 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 xpath" { try std.testing.fuzz({}, fuzzOne(0), .{ .corpus = comptime smithCorpus(&xpath_seeds) });}
test "fuzz pattern" { try std.testing.fuzz({}, fuzzOne(1), .{ .corpus = comptime smithCorpus(&xpath_seeds) });}
test "fuzz document" { try std.testing.fuzz({}, fuzzOne(2), .{ .corpus = comptime smithCorpus(&document_seeds) });}
test "fuzz stylesheet" { try std.testing.fuzz({}, fuzzOne(3), .{ .corpus = comptime smithCorpus(&stylesheet_seeds) });}
test "fuzz transform" { try std.testing.fuzz({}, fuzzOne(4), .{ .corpus = comptime smithCorpus(&transform_seeds) });}
const date_seeds = [_][]const u8{ "2001-02-28T10:31:07", "2001-02-28T10:31:07Z", "2001-02-28T10:31:07.5-05:00", "2001-02-28T10:31:07.99999999999+14:00", "2001-02-28", "2001-02-28Z", "2001-02", "2001", "10000-12-31T23:59:59Z", // The year before year one, which XML Schema numbers `-0001` and the // calendar underneath numbers zero. "-0001", "-0001-12-31T23:59:59-05:00", "-10000-12-31T23:59:59Z", "--02-28", // A day its default month does not have, which is still a gMonthDay // because the type names no year to decide it against. "--02-30", "--02--", "---28", "10:31:07", "10:31:07.5Z", "24:00:00", "0000", "2001-02-30", "2001-13-01", "",};
const duration_seeds = [_][]const u8{ "P1Y", "P1Y6M", "P3Y6M4DT12H30M5S", "PT30M", "P2W", "PT0S", "-P1D", "+P1D", "PT1.5S", "PT1,5S", "P1.5D", "P0D", "PT36H", "PT86400S", "P99999999999999Y", "P0.5Y", "PT1.S", "P1DT", "P", "",};
const picture_seeds = [_][]const u8{ "#", "0", "#.##", "0.00", "#,##0.00", "#,#,###.##", "_#,#,000.000##_", ".", "#.", ".#", ".##", "%##0.00", "\u{2030}##0.00", "#;(#)", "-0;-0", "prefix#suffix", "abc0.00123", "", ";", "##,##,00.##",};