Something went wrong. Try again.
XPath 1.0 for Zig 0.16, over a ztree document.
Something went wrong. Try again.
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385// SPDX-FileCopyrightText: © 2026 Jeffrey C. Ollie <jeff@ocjtech.us>// SPDX-License-Identifier: MIT
//! What the compiler and the evaluator must do with input nobody wrote.//!//! An expression is the part of a stylesheet, a query or a config file that//! most often comes from somewhere else, so the property is the usual weak//! one: **return, do not crash**. An error is a fine answer and so is a value;//! a panic, a leak or a stack overflow is a failure in whatever embedded this//! rather than in the expression that caused it.//!//! Compiling and evaluating are separate targets because they fail in separate//! ways. A compiler is a parser and breaks on shapes; an evaluator breaks on//! what the shapes mean once there is a document under them.//!//! Both also run each input a second time with one allocation refused, since//! the paths an allocation failure takes are the ones nothing else reaches.
const std = @import("std");const builtin = @import("builtin");const Allocator = std.mem.Allocator;const zxpath = @import("zxpath");const ztree = @import("ztree");
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, seeds: []const []const u8,};
pub const targets = [_]Target{ .{ .name = "compile", .run = fuzzCompile, .seeds = &expression_seeds }, .{ .name = "evaluate", .run = fuzzEvaluate, .seeds = &expression_seeds },};
fn fuzzCompile(input: []const u8) anyerror!void { try withOneFailure(input, compileOnce, {});}
fn compileOnce(gpa: Allocator, input: []const u8, _: void) anyerror!void { var compiled = zxpath.Compiled.init(gpa, input, ns.resolver()) catch return; defer compiled.deinit();}
/// Compiles and then runs the expression against a small document, which is/// the only way to reach the axes, the predicates and the core library at all.fn fuzzEvaluate(input: []const u8) anyerror!void { try withOneFailure(input, evaluateEverywhere, try sampleScene());}
const Scene = struct { doc: *ztree.Document, contexts: ztree.NodeId };
var scene_cache: ?Scene = null;
/// The sample document, parsed once per process and never freed.////// Parsing it for every input was most of what an input cost. It is not/// parsed with `backing`, whose leak check would then report it, and its/// allocations are not the failing allocator's to refuse: the document is/// ztree's to get right.////// Every element's namespace nodes are made here, because asking for the/// namespace axis otherwise adds them to the document on first use, and a/// document that changed as inputs ran over it would make what an input did/// depend on the inputs before it. Made up front, they are context nodes like/// any other.fn sampleScene() !Scene { if (scene_cache) |scene| return scene; const doc = try ztree.parse(std.heap.smp_allocator, sample, .{ .dtd = true }); const elements = doc.nodes.items.len; for (0..elements) |i| { const id: ztree.NodeId = @intCast(i); if (doc.node(id).kind == .element) _ = try doc.namespaceNodes(id); } scene_cache = .{ .doc = doc, .contexts = @intCast(doc.nodes.items.len) }; return scene_cache.?;}
/// Every node in the document is the context node once, each with its own/// position and size. A path from the root reaches nothing on the sibling,/// following and preceding axes, and `position()` from a lone context is/// always 1, so evaluating only from the root left most of the axes and/// half the comparisons unvisited.fn evaluateEverywhere(gpa: Allocator, input: []const u8, scene: Scene) anyerror!void { var compiled = zxpath.Compiled.init(gpa, input, ns.resolver()) catch return; defer compiled.deinit();
var host: Host = .{ .doc = scene.doc }; var ev: Ev = .init(gpa); ev.variables = .{ .ctx = &host, .lookupFn = Host.variable }; ev.extensions = .{ .ctx = &host, .callFn = Host.call };
for (0..scene.contexts) |i| { const id: ztree.NodeId = @intCast(i); const focus: zxpath.Focus = .{ .node = scene.doc.ref(id), .position = i + 1, .size = scene.contexts, }; const v = ev.eval(compiled.expr, focus) catch continue; defer v.deinit(gpa);
// Every value must convert to every other type without complaint: that // is what XPath promises, and a conversion is where an evaluator that // built something malformed finally trips. const str = try v.toString(gpa); defer gpa.free(str); _ = try v.toNumber(gpa); _ = v.toBoolean(); }
// And once more as a caller with no variables and no extensions of its own // would run it, which is a different instance of the generic evaluator and // the one most callers use. var plain: zxpath.Evaluator(error{}) = .init(gpa); const v = plain.eval(compiled.expr, .{ .node = scene.doc.ref(scene.doc.root) }) catch return; defer v.deinit(gpa); const str = try v.toString(gpa); defer gpa.free(str);}
/// Runs a target twice: once as it is, counting its allocations, and once/// with one of them refused. Every `errdefer` in the library is on a path only/// an allocation failure takes, and without this none of them ever runs; the/// testing allocator's leak check is what catches one that frees too little,/// and a double free is caught as it happens.////// Which allocation is refused comes from a hash of the input, so a failure/// reproduces from the input alone and the fuzzer's mutations spread the/// refusals over all of them. With `refuse_every` set, allocations are refused/// in turn instead, which is what the seed replay does.fn withOneFailure( input: []const u8, comptime run: anytype, context: anytype,) anyerror!void { var counting: std.testing.FailingAllocator = .init(backing, .{}); try run(counting.allocator(), input, context); if (counting.allocations == 0) return;
if (refuse_every) { const stride = @max(1, counting.allocations / max_refusals); var index: usize = 0; while (index < counting.allocations) : (index += stride) { try refuse(index, input, run, context); } } else { try refuse(std.hash.Wyhash.hash(0, input) % counting.allocations, input, run, context); }}
/// Refuse allocations in turn rather than the one the input's hash picks: all/// of them for an input that makes few, and `max_refusals` spread evenly over/// the rest. Refusing every one of them is quadratic in the allocations an/// input makes, and evaluating from every node of the sample makes hundreds,/// which took the seed replay to a minute.pub var refuse_every = false;const max_refusals = 16;
fn refuse(index: usize, input: []const u8, comptime run: anytype, context: anytype) anyerror!void { var failing: std.testing.FailingAllocator = .init(backing, .{ .fail_index = index }); run(failing.allocator(), input, context) catch |err| switch (err) { error.OutOfMemory => {}, else => return err, };}
/// What a host can fail with that XPath cannot, so that a host error has to/// travel back out through the evaluator's own cleanup.const HostError = error{HostFailure};const Ev = zxpath.Evaluator(HostError);
/// `p` is bound and `q` is not, though the sample document declares both: a/// prefix in an expression means what the expression's context says, never/// what the document happens to say.const ns_map: zxpath.MapResolver = .{ .entries = &.{.{ "p", "urn:p" }} };const ns = &ns_map;
/// The variables and extension functions an embedding supplies. There is one/// variable of each type, an empty node-set, and in `urn:p` a variable and a/// function that fail with a host error.const Host = struct { doc: *ztree.Document,
fn variable(ctx: ?*anyopaque, ev: *Ev, name: ztree.Name) Ev.Error!?zxpath.Value { const host: *Host = @ptrCast(@alignCast(ctx.?)); const gpa = ev.gpa; if (std.mem.eql(u8, name.uri, "urn:p")) { if (std.mem.eql(u8, name.local, "fail")) return error.HostFailure; return null; } if (name.uri.len != 0) return null; const table = std.StaticStringMap(enum { n, s, b, ns, empty }).initComptime(.{ .{ "n", .n }, .{ "s", .s }, .{ "b", .b }, .{ "ns", .ns }, .{ "empty", .empty }, }); return switch (table.get(name.local) orelse return null) { .n => .{ .number = 25 }, .s => try zxpath.Value.ownedString(gpa, "b1 b2"), .b => .{ .boolean = true }, .ns => try host.books(gpa), .empty => zxpath.Value.empty_node_set, }; }
/// `p:echo(x)` hands back a copy of its argument, which makes a value of /// any type available anywhere an expression is, `p:books()` is `$ns` as a /// call, and `p:fail()` fails. fn call( ctx: ?*anyopaque, ev: *Ev, _: zxpath.Focus, name: ztree.Name, args: []const zxpath.Value, ) Ev.Error!?zxpath.Value { const host: *Host = @ptrCast(@alignCast(ctx.?)); const gpa = ev.gpa; if (!std.mem.eql(u8, name.uri, "urn:p")) return null; if (std.mem.eql(u8, name.local, "fail")) return error.HostFailure; if (std.mem.eql(u8, name.local, "books")) return try host.books(gpa); if (std.mem.eql(u8, name.local, "echo")) { if (args.len == 0) return zxpath.Value.empty_node_set; return switch (args[0]) { .node_set => |set| .{ .node_set = try gpa.dupe(ztree.NodeRef, set) }, .string => |str| try zxpath.Value.ownedString(gpa, str), .number, .boolean => args[0], }; } return null; }
fn books(host: *Host, gpa: Allocator) Allocator.Error!zxpath.Value { var b: zxpath.NodeSetBuilder = .init(gpa); defer b.deinit(); for (host.doc.nodes.items, 0..) |n, i| { if (n.kind == .element and std.mem.eql(u8, n.name.local, "book")) try b.add(host.doc.ref(@intCast(i))); } return b.toOwnedValue(); }};
/// Small, but with something for every part of the library to find: an ID/// declared in the internal subset, both unprefixed and prefixed, and an/// `xml:id` that needs no declaration, so that `id()` has something to look/// up; `xml:lang` inherited and overridden, for `lang()`; siblings on every/// level, for the sibling, following and preceding axes; an entity, a/// comment, a processing instruction, and a namespace declared below the/// document element.const sample = \\<!DOCTYPE catalog [ \\ <!ATTLIST book id ID #IMPLIED> \\ <!ATTLIST item p:key ID #IMPLIED> \\ <!ENTITY e "entity text"> \\]> \\<catalog xmlns:p="urn:p" xml:lang="en"> \\ <book id="b1" ref="b2 p1"><title>Alpha</title><price>10</price></book> \\ <book id="b2" xml:lang="fr-CA"><title xml:lang="de">Beta &e;</title><price>25</price><price>7</price></book> \\ <p:extra a="1" xmlns:q="urn:q"><q:deep>text<!--inner--></q:deep><item p:key="p1"/></p:extra> \\ <book xml:id="x1"><title>Gamma</title></book> \\ <!--c--><?pi data?> \\ <empty/> \\</catalog>;
const expression_seeds = [_][]const u8{ "", ".", "/", "//", "*", "@*", "@id", "node()", "text()", "comment()", "processing-instruction()", "processing-instruction('pi')", "//book", "//book[1]", "//book[@lang='en']", "//book[price>20]", "//book[last()]", "//book/../book", "//title|//price", "(//title)[1]", "count(//book)", "sum(//price)", "string(//title)", "concat('a','b','c')", "substring('12345',2,3)", "substring('12345',1.5,2.6)", "normalize-space(' a b ')", "translate('abc','ab','AB')", "starts-with('abc','a')", "contains('abc','b')", "substring-before('a/b','/')", "substring-after('a/b','/')", "string-length('héllo')", "boolean(//book)", "not(//none)", "true()", "false()", "lang('en')", "number('42')", "floor(-2.5)", "ceiling(-2.5)", "round(-1.5)", "1 div 0", "0 div 0", "1 + 2 * 3 - 4 div 5 mod 6", "- - -1", "//price = 10", "//price != 10", "//price < 20", "a and b or c", "$undefined", "unknown-function()", "ancestor::node()", "descendant::*", "following::*", "preceding::*", "following-sibling::*", "preceding-sibling::*", "namespace::*", "self::node()", "parent::node()", "ancestor-or-self::*", "descendant-or-self::*", "div div div", "mod mod mod", "a[a[a[a]]]", "((((1))))", "'unterminated", "concat(", "bogus-axis::a", ":", "::", "id('b1')", "local-name()", "namespace-uri()", "name(//*[1])", // A filter over something that is not a node-set. These are a type error, // and the point is that raising it frees the operand exactly once: an // `errdefer` beside the explicit free made `'x'[1]` a double free. "'x'[1]", "1[1]", "true()[1]", "concat('a','b')[1]", "(1)[1]", "'x'[1][2]", // A string literal that is not valid UTF-8. Nothing forbids one, and the // character-counting functions used to step past the end of it. "substring('abcd\xf0', 1, 9)", "string-length('abcd\xf0')", "translate('abcd\xf0', '\xf0', 'x')", // The context-dependent forms of the core functions, which take the // context node when they are given no argument. "position()", "last() - position()", "string()", "string-length()", "normalize-space()", "number()", "name()", "local-name(..)", "lang('fr')", "lang('EN')", "lang('en-US')", // `id()` over the IDs the internal subset declares, by string and by // node-set, and one that is declared on a prefixed attribute. "id(//@ref)", "id('b1 b2 p1')", "id(//book/@id)", "count(id('p1'))", "id($ns)", // Paths that start with something other than a step. "/catalog", "/catalog/book", "a//b", "(//book)//title", "(//book)/title", "$ns/title", "$ns//price", "p:books()/title", "p:echo(//book)[2]", "..", ".//text()", "@*/..", // The axes from wherever the context happens to be. "following-sibling::*[1]", "preceding-sibling::node()[last()]", "following::node()", "preceding::node()", "ancestor::*[1]", "namespace::*[name()='p']", "//namespace::*", "//*[position() mod 2 = 0]", // A prefix the expression's context binds, and one only the document does. "p:*", "p:extra", "@p:*", "//p:*", "//item[@p:key]", "q:*", "p:1", // The host's variables and functions, and its failures. "$n", "$s", "$b", "$ns", "$empty", "$p:fail", "$p:none", "p:fail()", "p:none()", "p:echo(1)", "p:echo('x')", "p:echo(true())", "p:echo()", "concat(p:fail(), 'x')", "//book[p:fail()]", "(//book)[p:fail()]", "count($ns | p:books())", // Every pairing of types on either side of a comparison. "$ns = $ns", "$ns != $empty", "//price = //title", "//price = //price", "//book = true()", "$empty = false()", "//price > '5'", "'5' < //price", "$b != //book", "//price = 25", "'Alpha' = //title", "true() = 1", "1 = '1'", "'a' != 'b'", "'1' < '2'", "true() > false()", "1 <= 2", "2 >= 1", "1 > 2 = 1 < 2", "true() and 1", "false() or 'x'", "-//price", "sum(//price) div count(//price)", "'x'/title", "$n//a", "()", "translate('abc', 'abc', 'x')", "id('x1')", "number('+1')", "number(' -1.5 ')", "number('1e3')", "#", "1 + )",};
const testing = std.testing;
// Replays every seed of every target, which 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" { refuse_every = true; defer refuse_every = false; 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; }; } }}
/// `Smith` reads a four-byte little-endian length before the bytes, so a/// corpus entry has to carry one. Without it every seed decodes to the empty/// string and the run tests 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;}
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 compile" { try std.testing.fuzz({}, fuzzOne(0), .{ .corpus = comptime smithCorpus(&expression_seeds) });}
test "fuzz evaluate" { try std.testing.fuzz({}, fuzzOne(1), .{ .corpus = comptime smithCorpus(&expression_seeds) });}