// SPDX-FileCopyrightText: © 2026 Jeffrey C. Ollie // SPDX-License-Identifier: MIT //! Fuzz targets for everything here that reads input it did not write. //! //! Each target is a property written once and driven twice. `zig build //! test` runs it over a list of seeds, which is what keeps a case that //! once failed from coming back. `zig build test --fuzz` hands the //! same property to the fuzzer, which goes looking for new ones. //! //! The properties are deliberately weak about what a parser should //! *accept*, because that is what the moment.js oracles are for and a //! fuzzer has no opinion about it. What they check is that nothing //! crashes on input nobody chose, and that whatever does come back holds //! together: a date that says it parsed is a real date, a zone that says //! it loaded can be asked about any instant, and anything with an inverse //! survives the round trip. //! //! Any input reaching a parser here is untrusted by construction. A //! panic, an unreachable, or an index out of bounds is a bug even when //! the input is nonsense, which is the whole point of pointing a fuzzer //! at it. const std = @import("std"); const build_options = @import("build_options"); const Date = @import("Date.zig"); const Duration = @import("Duration.zig"); const DateTime = @import("DateTime.zig"); const DayOfWeek = @import("dayofweek.zig").DayOfWeek; const Instant = @import("Instant.zig"); const Interval = @import("interval.zig").Interval; const Month = @import("month.zig").Month; const TimeZone = @import("TimeZone.zig"); const Year = @import("year.zig").Year; const cldr = @import("cldr.zig"); const dotnet = @import("dotnet.zig"); const golayout = @import("golayout.zig"); const hinnant = @import("hinnant"); const iso8601 = @import("iso8601.zig"); const locale = @import("locale.zig"); const posixtz = @import("posixtz.zig"); const powershell = @import("powershell.zig"); const rfc822 = @import("rfc822.zig"); const rfc5322 = @import("rfc5322.zig"); const strftime = @import("strftime.zig"); const tzif = @import("tzif.zig"); const tzdb = @import("tzdb.zig"); /// The longest input any target reads. Long enough for a real date, a /// POSIX rule, or a small TZif file, and short enough that the fuzzer /// spends its time on shapes rather than on length. const max_input = 256; /// Runs `property` over each of `seeds`, which is what a normal test run /// does with a fuzz target. fn overSeeds(comptime property: fn ([]const u8) anyerror!void, seeds: []const []const u8) !void { for (seeds) |seed| try property(seed); } /// Hands `property` to the fuzzer, which is what `zig build test --fuzz` /// does. /// /// Under an ordinary test run `std.testing.fuzz` calls the target once /// with an empty input, so `overMutations` is what explores then. Under /// `--fuzz` the fuzzer feeds it, steered by coverage, which needs the test /// binary compiled by LLVM; build.zig sets `use_llvm` for that reason. fn overFuzzer(comptime property: fn ([]const u8) anyerror!void) !void { const driver = struct { fn one(_: void, smith: *std.testing.Smith) anyerror!void { var buffer: [max_input]u8 = undefined; const len = smith.slice(&buffer); try property(buffer[0..len]); } }; try std.testing.fuzz({}, driver.one, .{}); } /// Runs `property` over inputs built by mutating `seeds`, which is the /// part that actually goes looking for something. /// /// Random bytes on their own rarely reach far into a date parser, because /// almost nothing is a date. Starting from inputs that are nearly right /// and breaking them a little at a time gets past the first check and /// into the arithmetic behind it, which is where the interesting failures /// were: every bug this file found was an overflow reached through a /// value that had already parsed. /// /// The seed comes from the test runner, so `zig build test --seed=N` /// replays a failure exactly. fn overMutations(comptime property: fn ([]const u8) anyerror!void, seeds: []const []const u8) !void { var prng: std.Random.DefaultPrng = .init(std.testing.random_seed); const random = prng.random(); var buffer: [max_input]u8 = undefined; for (0..build_options.fuzz_iterations) |_| { const input = mutate(random, seeds, &buffer); property(input) catch |err| { std.debug.print( "fuzz: seed {d} produced {any}\n on input: {s}\n as bytes: {x}\n", .{ std.testing.random_seed, err, input, input }, ); return err; }; } } /// Builds one input by taking a seed and damaging it. fn mutate(random: std.Random, seeds: []const []const u8, buffer: []u8) []const u8 { const base = seeds[random.uintLessThan(usize, seeds.len)]; var len = @min(base.len, buffer.len); @memcpy(buffer[0..len], base[0..len]); // Between one and four changes, so an input stays recognizable often // enough to get deep and is wrecked often enough to test the shallow // paths too. const rounds = random.uintLessThan(usize, 4) + 1; for (0..rounds) |_| { switch (random.uintLessThan(u8, 6)) { // Flip a byte to anything at all. 0 => if (len > 0) { buffer[random.uintLessThan(usize, len)] = random.int(u8); }, // Flip a byte to something a date might hold, which reaches // further in than a random byte does. 1 => if (len > 0) { const alphabet = "0123456789:-+TZW.,/ abcdefMTWSJ<>"; buffer[random.uintLessThan(usize, len)] = alphabet[random.uintLessThan(usize, alphabet.len)]; }, // Cut it short. 2 => if (len > 0) { len = random.uintLessThan(usize, len); }, // Grow it with a byte. 3 => if (len < buffer.len) { buffer[len] = random.int(u8); len += 1; }, // Splice another seed onto the end. 4 => { const other = seeds[random.uintLessThan(usize, seeds.len)]; const take = @min(other.len, buffer.len - len); @memcpy(buffer[len..][0..take], other[0..take]); len += take; }, // Repeat a stretch of it, which is how a length field or a // count gets somewhere unreasonable. else => if (len > 0 and len < buffer.len) { const take = @min(random.uintLessThan(usize, len) + 1, buffer.len - len); @memcpy(buffer[len..][0..take], buffer[0..take]); len += take; }, } } return buffer[0..len]; } /// Runs `property` over values drawn from a generator seeded by the test /// runner, for the targets whose input is a value rather than text. /// /// These are the properties `std.testing.fuzz` drives through a `Smith` /// under `zig build test --fuzz`. Outside that mode `std.testing.fuzz` /// hands a target a single empty input, and a `Smith` reading from nothing /// answers every range with its minimum, so a target driven only that way /// checks one value and looks like it checked millions. This draws the /// values itself. `zig build test --seed=N` replays a failure exactly, and /// the property prints the value it failed on. fn overRandom(comptime property: fn (std.Random) anyerror!void) !void { var prng: std.Random.DefaultPrng = .init(std.testing.random_seed); const random = prng.random(); for (0..build_options.fuzz_iterations) |i| { property(random) catch |err| { std.debug.print("fuzz: seed {d} produced {any} on draw {d}\n", .{ std.testing.random_seed, err, i }); return err; }; } } /// A year anywhere a `Year` reaches, most often near the present, sometimes /// far from it, and sometimes at one of its two ends, which is where the /// arithmetic has overflowed before. fn randomYear(random: std.Random) Year { return switch (random.uintLessThan(u8, 8)) { 0 => std.math.minInt(Year) + random.intRangeAtMost(Year, 0, 400), 1 => std.math.maxInt(Year) - random.intRangeAtMost(Year, 0, 400), 2, 3 => random.int(Year), else => random.intRangeAtMost(Year, -10000, 10000), }; } /// Any date a `Date` can hold, drawn as `randomYear` draws its year. fn randomDate(random: std.Random) Date { const year = randomYear(random); const month: Month = @fromBackingInt(@intCast(random.intRangeAtMost(u4, 1, 12))); return .{ .year = year, .month = month, .day = random.intRangeAtMost(u6, 1, month.lastDay(year)) }; } /// Any well formed `DateTime`, at any offset the parsers can produce. fn randomDateTime(random: std.Random) DateTime { const date = randomDate(random); var value: DateTime = .{ .year = date.year, .month = date.month, .day = date.day, .hour = random.intRangeAtMost(u5, 0, 23), .minute = random.intRangeAtMost(u6, 0, 59), .second = random.intRangeAtMost(u6, 0, 59), .nanosecond = random.intRangeAtMost(u30, 0, std.time.ns_per_s - 1), .offset = random.intRangeAtMost(i32, -(24 * std.time.s_per_hour - 1), 24 * std.time.s_per_hour - 1), }; value.updateDayOfWeek(); return value; } /// An integer of type `T` that is zero, small, middling or anywhere at all, /// either sign, since each size reaches a different part of the arithmetic. fn randomAmount(comptime T: type, random: std.Random, small: T, middling: T) T { return switch (random.uintLessThan(u8, 5)) { 0 => 0, 1 => random.intRangeAtMost(T, -small, small), 2, 3 => random.intRangeAtMost(T, -middling, middling), else => random.int(T), }; } fn randomDuration(random: std.Random) Duration { return .{ .months = randomAmount(i64, random, 24, 12 * 100_000), .days = randomAmount(i64, random, 60, 366 * 100_000), .nanoseconds = randomAmount(i128, random, 2 * Duration.nanoseconds_per_day, 366 * 100_000 * Duration.nanoseconds_per_day), }; } /// Asserts that `datetime` is a date that could exist, which every parser /// here promises about anything it returns. fn isWellFormed(datetime: DateTime) !void { try std.testing.expect(datetime.asDate().isRegular()); try std.testing.expectEqual(datetime.asDate().dayOfWeek(), datetime.weekday); try std.testing.expect(datetime.hour < 24); try std.testing.expect(datetime.minute < 60); // Up to 61, not 60: `Second` holds the C89 "double leap second", and // `strftime.parse` reads `%S` up to 61 because glibc's `strptime` does // (checked against glibc 2.42, which refuses 62). try std.testing.expect(datetime.second <= 61); try std.testing.expect(datetime.nanosecond < std.time.ns_per_s); // An offset has to be one the syntaxes admit, which is wider than any // zone has ever used: RFC 3339 writes the hour as `00-23` and both // parsers here follow it, so `+20:24` is a well formed offset even // though no such zone exists. Asserting the real range instead -- // -12:00 to +14:00 -- says the parsers are wrong when they are not. try std.testing.expect(datetime.offset > -24 * std.time.s_per_hour); try std.testing.expect(datetime.offset < 24 * std.time.s_per_hour); } // ISO 8601 ------------------------------------------------------------- /// Whatever `iso8601.parse` accepts has to be a real date, and what it /// says it consumed has to be a prefix of what it was given. fn iso8601Property(text: []const u8) !void { const result = iso8601.parse(text) catch return; try isWellFormed(result.value); try std.testing.expect(result.str.len <= text.len); try std.testing.expectEqualStrings(result.str, text[0..result.str.len]); // A reduced representation cannot claim more precision than it wrote. if (result.precision == .year) { try std.testing.expectEqual(Month.Jan, result.value.month); try std.testing.expectEqual(@as(u6, 1), result.value.day); } if (!result.has_offset) try std.testing.expectEqual(@as(i32, 0), result.value.offset); } const iso8601_seeds = [_][]const u8{ "", "2024-03-15", "20240315", "2024-03", "2024", "2024-075", "2024075", "2024-W11-5", "2024W115", "2024-W11", "2024-03-15T14:30:00Z", "2024-03-15T14:30:00.5+05:30", "2024-03-15T24:00", "2024-02-30", "2024-13-01", "2024-00-01", "2024-W54-1", "2024-W00-1", "2024-000", "2024-367", "0000-01-01", "9999-12-31", "2024-03-15T14:30:60", "-------", "TTTTTT", "2024-03-15T", "2024-W", "..", ",,", "2024-03-15T.5", }; test "iso8601.parse over the seeds" { try overSeeds(iso8601Property, &iso8601_seeds); } test "fuzz iso8601.parse" { try overFuzzer(iso8601Property); } test "mutate iso8601.parse" { try overMutations(iso8601Property, &iso8601_seeds); } // ISO 8601 durations --------------------------------------------------- /// Whatever `iso8601.parseDuration` accepts, `Duration.format` writes in a /// form that reads back as the same value: canonical, so not always the /// same text, but always the same duration, whatever its fields' signs. fn iso8601DurationProperty(text: []const u8) !void { const result = iso8601.parseDuration(text) catch return; try std.testing.expect(result.str.len <= text.len); try std.testing.expectEqualStrings(result.str, text[0..result.str.len]); var buffer: [max_input]u8 = undefined; var writer = std.Io.Writer.fixed(&buffer); try result.value.format(&writer); const again = iso8601.parseDuration(writer.buffered()) catch |err| { std.debug.print("wrote \"{s}\", which does not read back\n", .{writer.buffered()}); return err; }; try std.testing.expectEqualStrings(writer.buffered(), again.str); try std.testing.expect(again.value.eql(result.value)); } const iso8601_duration_seeds = [_][]const u8{ "", "P3Y6M4DT12H30M5S", "PT0.5S", "-P1D", "P2W", "P1.5D", "P1M-1D", "P3Y15M3DT-10M", "P-1Y-2M3D", "P1DT-1H-30M-0.5S", "-P1Y-2M", "P9223372036854775807D", "PT-9999999999999999999H", "P--1D", }; test "iso8601.parseDuration over the seeds" { try overSeeds(iso8601DurationProperty, &iso8601_duration_seeds); } test "fuzz iso8601.parseDuration" { try overFuzzer(iso8601DurationProperty); } test "mutate iso8601.parseDuration" { try overMutations(iso8601DurationProperty, &iso8601_duration_seeds); } // ISO 8601 intervals --------------------------------------------------- /// Whatever `iso8601.parseInterval` accepts has well formed endpoints that /// run forward, can be resolved without a panic, and survives being /// written out and read back. fn iso8601IntervalProperty(text: []const u8) !void { const result = iso8601.parseInterval(text) catch return; try std.testing.expect(result.str.len <= text.len); try std.testing.expectEqualStrings(result.str, text[0..result.str.len]); // The parser promises that both of these are safe to call, which is // the point of its range check. const interval = result.value; const start = interval.start(); const end = interval.end(); try isWellFormed(start); try isWellFormed(end); try std.testing.expect(interval.length() >= 0); // Written out, it reads back as the same interval, in the same form. // Only while the years stay within the four digits ISO 8601 allows, // which a duration or an end of 24:00 can carry them past. if (start.year < 0 or start.year > 9999 or end.year < 0 or end.year > 9999) return; var buffer: [max_input * 2]u8 = undefined; var writer = std.Io.Writer.fixed(&buffer); try interval.format(&writer); const again = iso8601.parseInterval(writer.buffered()) catch |err| { std.debug.print("wrote \"{s}\", which does not read back\n", .{writer.buffered()}); return err; }; try std.testing.expectEqualStrings(writer.buffered(), again.str); try std.testing.expectEqual(std.meta.activeTag(interval), std.meta.activeTag(again.value)); try std.testing.expectEqual(start.toInstant(), again.value.start().toInstant()); try std.testing.expectEqual(end.toInstant(), again.value.end().toInstant()); if (interval.duration()) |d| try std.testing.expect(d.eql(again.value.duration().?)); } const iso8601_interval_seeds = [_][]const u8{ "", "2007-03-01T13:00:00Z/2008-05-11T15:30:00Z", "2007-03-01T13:00:00Z/P1Y2M10DT2H30M", "P1Y2M10DT2H30M/2008-05-11T15:30:00Z", "2024-03--2024-04", "2007-12-14T13:30-06:00/15:30", "2008-02-15/03-14", "2008-02-15T09:00/16T17:00", "20071214T1330/1530", "2024-03-15T09:00/24:00", "9999-12-31T23:00/24:00", "9999-12-31/P1D", "P1M/0000-01-31", "2024-03-15/PT1.5S", "2024-W11-5/W12-1", "2024-075/080", "2024-03-15/P9999999999Y", "//", "----", }; test "iso8601.parseInterval over the seeds" { try overSeeds(iso8601IntervalProperty, &iso8601_interval_seeds); } test "fuzz iso8601.parseInterval" { try overFuzzer(iso8601IntervalProperty); } test "mutate iso8601.parseInterval" { try overMutations(iso8601IntervalProperty, &iso8601_interval_seeds); } // ISO 8601 recurring intervals ----------------------------------------- /// Whatever `iso8601.parseRecurringInterval` accepts walks as a series /// without a panic: each occurrence is well formed, meets the one before it /// end to end, and the walk stops at its count or at an `OutOfRange` at the /// edge of the calendar. And it reads back as itself once written out. fn iso8601RecurringProperty(text: []const u8) !void { const result = iso8601.parseRecurringInterval(text) catch return; try std.testing.expect(result.str.len <= text.len); try std.testing.expectEqualStrings(result.str, text[0..result.str.len]); const series = result.value; try std.testing.expect(series.count != 0); var it = series.iterator(); var previous: ?Interval = null; var seen: u64 = 0; while (seen < 64) : (seen += 1) { const occurrence = (it.next() catch |err| switch (err) { error.OutOfRange => break, }) orelse break; try isWellFormed(occurrence.start()); try isWellFormed(occurrence.end()); try std.testing.expect(occurrence.length() >= 0); if (previous) |p| { // Consecutive: the series has no gaps and no overlaps. if (series.isForward()) { try std.testing.expectEqual(p.end().toInstant(), occurrence.start().toInstant()); } else { try std.testing.expectEqual(p.start().toInstant(), occurrence.end().toInstant()); } } previous = occurrence; } if (series.count) |count| { if (count <= 64) try std.testing.expect(seen <= count); } const first = series.interval; const start = first.start(); const end = first.end(); if (start.year < 0 or start.year > 9999 or end.year < 0 or end.year > 9999) return; var buffer: [max_input * 2]u8 = undefined; var writer = std.Io.Writer.fixed(&buffer); try series.format(&writer); const again = iso8601.parseRecurringInterval(writer.buffered()) catch |err| { std.debug.print("wrote \"{s}\", which does not read back\n", .{writer.buffered()}); return err; }; try std.testing.expectEqualStrings(writer.buffered(), again.str); try std.testing.expectEqual(series.count, again.value.count); try std.testing.expectEqual(start.toInstant(), again.value.interval.start().toInstant()); try std.testing.expectEqual(end.toInstant(), again.value.interval.end().toInstant()); } const iso8601_recurring_seeds = [_][]const u8{ "", "R12/1985-04-12T23:20:50Z/1985-06-25T10:30:00Z", "R12/1985-04-12T23:20:50Z/P1Y2M15DT12H30M", "R/P1Y2M15DT12H/1985-04-12T23:20:50Z", "R5/2024-01-31/P1M", "R/2024-03-15T09:00Z/17:00", "R2/2024-03--2024-04", "R/9999-12-30/P1D", "R/P1D/0000-01-02", "R3/2024-03-15/PT0S", "R0/2024-03-15/P1D", "R-1/2024-03-15/P1D", "R18446744073709551615/2024-03-15/P1D", "R12/20150929T140000Z/P1H30M0S/F2W", "RRRR", }; test "iso8601.parseRecurringInterval over the seeds" { try overSeeds(iso8601RecurringProperty, &iso8601_recurring_seeds); } test "fuzz iso8601.parseRecurringInterval" { try overFuzzer(iso8601RecurringProperty); } test "mutate iso8601.parseRecurringInterval" { try overMutations(iso8601RecurringProperty, &iso8601_recurring_seeds); } // RFC 822 -------------------------------------------------------------- fn rfc822Property(text: []const u8) !void { const result = rfc822.parse(text) catch return; try isWellFormed(result.value); try std.testing.expect(result.str.len <= text.len); try std.testing.expectEqualStrings(result.str, text[0..result.str.len]); } const rfc822_seeds = [_][]const u8{ "", "Sun, 06 Nov 1994 08:49:37 GMT", "20 Jun 82 12:34 -0500", "Fri, 21 Nov 1997 09:55:06 -0600", "Mon, 06 Nov 1994 08:49:37 GMT", "06 Nov 1994 08:49:37 Z", "32 Nov 1994 08:49:37 GMT", "06 Xxx 1994 08:49:37 GMT", "06 Nov 1994 25:49:37 GMT", "06 Nov 1994 08:49:37 +9999", "Sun,,,06 Nov 1994 08:49:37 GMT", "\t\t\t", "Sun", "06 Nov", "06 Nov 1994", "06 Nov 1994 08:49", }; test "rfc822.parse over the seeds" { try overSeeds(rfc822Property, &rfc822_seeds); } test "fuzz rfc822.parse" { try overFuzzer(rfc822Property); } test "mutate rfc822.parse" { try overMutations(rfc822Property, &rfc822_seeds); } // RFC 5322 ------------------------------------------------------------- fn rfc5322Property(text: []const u8) !void { const result = rfc5322.parse(text) catch return; try isWellFormed(result.value); try std.testing.expect(result.str.len <= text.len); try std.testing.expectEqualStrings(result.str, text[0..result.str.len]); // Only "-0000" claims an unknown offset, and it is UTC either way. if (result.unknown_offset) try std.testing.expectEqual(@as(i32, 0), result.value.offset); } const rfc5322_seeds = [_][]const u8{ "", "Fri, 21 Nov 1997 09:55:06 -0600", "21 Nov 1997 09:55 +0000", "Thu, 13 (the thirteenth) Feb 1969 23:32:54 -0330 (Newfoundland)", "Fri,\r\n 21 Nov\r\n\t1997 09:55:06 -0600", "Fri, 21 Nov 1997 09:55:06 -0000", "Mon, 21 Nov 1997 09:55:06 -0600", "20 Jun 82 12:34 EST", "21 Nov 1997 09:55:06 +9999", "21 Nov 1997 12345678901 09:55:06 +0000", "Fri, 21 Nov 1997 09:55:06 -0600 (never closed", "((((((((((", "21 Nov 1997 09:55:06 -0600 (a (nested \\) one)", "\r\n\r\n\r\n", "Fri,", "21 Nov", }; test "rfc5322.parse over the seeds" { try overSeeds(rfc5322Property, &rfc5322_seeds); } test "fuzz rfc5322.parse" { try overFuzzer(rfc5322Property); } test "mutate rfc5322.parse" { try overMutations(rfc5322Property, &rfc5322_seeds); } // Format strings ------------------------------------------------------- /// Both parsing modes have to survive anything, and both have to keep /// their promises about what they consumed. fn formatStringProperty(text: []const u8) !void { inline for (.{ DateTime.Mode.lenient, DateTime.Mode.strict }) |mode| { // A format string with most of the shapes in it, so one input // exercises names, numbers, an offset and a literal at once. if (DateTime.parseWith("ddd, DD MMM YYYY HH:mm:ss ZZ", text, .{ .mode = mode })) |result| { try isWellFormed(result.value); try std.testing.expect(result.skipped <= result.str.len); try std.testing.expect(result.str.len <= text.len); // Strict takes all of it or none of it. if (mode == .strict) { try std.testing.expectEqual(text.len, result.str.len); try std.testing.expectEqual(@as(usize, 0), result.skipped); } } else |_| {} } } const format_string_seeds = [_][]const u8{ "", "Fri, 15 Mar 2024 14:30:05 +0000", "Fri, 15 Mar 2024 14:30:05 -0500", "Mon, 15 Mar 2024 14:30:05 +0000", "Xxx, 15 Mar 2024 14:30:05 +0000", "Fri, 32 Mar 2024 14:30:05 +0000", "Fri, 15 Xxx 2024 14:30:05 +0000", "Fri, 15 Mar 2024 24:00:00 +0000", "Fri, 15 Mar 2024 14:30:05", "Friday, 15 March 2024 14:30:05 +0000", ",,,,,,,,", "0000000000000000", }; test "DateTime.parseWith over the seeds" { try overSeeds(formatStringProperty, &format_string_seeds); } test "fuzz DateTime.parseWith" { try overFuzzer(formatStringProperty); } test "mutate DateTime.parseWith" { try overMutations(formatStringProperty, &format_string_seeds); } // strftime ------------------------------------------------------------- /// A strftime format string is comptime, so the untrusted surface is the /// text handed to the parser. Everything it can reach is in one format /// string here: names, numbers at several widths, a day of the year, an /// ISO week date, a meridiem, an offset and a zone abbreviation, which is /// also the assembly in `State.finish` -- the arithmetic that turns a /// week number or a day of the year into a date, and the place a value /// that had already parsed can still overflow. fn strftimeProperty(text: []const u8) !void { inline for (.{ "%Y-%m-%dT%H:%M:%S%z", "%a, %d %b %Y %H:%M:%S %Z", "%G-W%V-%u", "%C%y-%j %I:%M %p", "%s", }) |format_string| { if (strftime.parse(format_string, text)) |result| { try isWellFormed(result.value); try std.testing.expect(result.str.len <= text.len); try std.testing.expectEqualStrings(result.str, text[0..result.str.len]); } else |_| {} } } const strftime_seeds = [_][]const u8{ "", "2024-03-15T14:30:05-0500", "Fri, 15 Mar 2024 14:30:05 CDT", "2024-W11-5", "2024-075 02:30 PM", "1710513005", "-2208988800", "9999-99-99T99:99:99+9999", "0000-W53-7", "0000-366 12:00 AM", "99999999999999999999", "2024-03-15T14:30:05Z", " ", }; test "strftime.parse over the seeds" { try overSeeds(strftimeProperty, &strftime_seeds); } test "fuzz strftime.parse" { try overFuzzer(strftimeProperty); } test "mutate strftime.parse" { try overMutations(strftimeProperty, &strftime_seeds); } // .NET and PowerShell -------------------------------------------------- /// A .NET format string is comptime, so the untrusted surface is the text. /// The formats here reach every reader the parser has between them: both /// of .NET's own fast paths, names long and short, one and two digit /// numbers, a two digit year, a meridiem both whole and by its first /// letter, the era, all three offsets, `Z` and `GMT`, and an optional /// fraction behind an optional dot -- and `State.finish`, where a value /// that had already parsed can still be refused. fn dotnetProperty(text: []const u8) !void { inline for (.{ "o", "r", "u", "dddd, MMMM d, yyyy h:mm:ss.FFFFFFF tt K", "ddd dd MMM yy H:m:s.fff t zz gg", "yyyyyy-M-dTHH:mm:ss.FFz Z", "yyyyMMddTHHmmssffff GMT", }) |format_string| { if (dotnet.parse(format_string, text)) |result| { try isWellFormed(result.value); } else |_| {} } } const dotnet_seeds = [_][]const u8{ "", "2024-03-15T14:30:05.1234567-05:00", "2024-03-15T14:30:05.1234567+5:45", "Fri, 15 Mar 2024 19:30:05 GMT", "2024-03-15 19:30:05Z", "Friday, March 15, 2024 2:30:05.12 PM -05:00", "Fri 15 Mar 24 14:30:5.123 P -05 A.D.", "002024-3-15T14:30:05.1-5 Z", "20240315T1430051234 GMT", "9999-12-31T23:59:59.9999999+14:00", "0000-00-00T99:99:99.9999999+99:99", "Sunday, February 30, 2024 13:61:61 PM Z", "999999-99-99T99:99:99.99+99 gmt", }; test "dotnet.parse over the seeds" { try overSeeds(dotnetProperty, &dotnet_seeds); } test "fuzz dotnet.parse" { try overFuzzer(dotnetProperty); } test "mutate dotnet.parse" { try overMutations(dotnetProperty, &dotnet_seeds); } /// The same for a `-UFormat` string, where the parser's own work is in /// `UState.finish`: a date settled from `%s`, from a year and a month, /// from `%j`, or from an ISO week, and every other field checked against /// it. fn uformatProperty(text: []const u8) !void { inline for (.{ "%c %Z", "%F %T %Z (%j, %U, %u, %w, %V, %G, %g, %C)", "%G-W%V-%u %r", "%Y %j %l:%M:%S %p", "%s %Z", "%D %e %k", }) |format_string| { if (powershell.parseUFormat(format_string, text)) |result| { try isWellFormed(result.value); } else |_| {} } } const uformat_seeds = [_][]const u8{ "", "Fri 15 Mar 2024 14:30:05 -05", "2024-03-15 14:30:05 -05 (075, 10, 5, 5, 11, 2024, 24, 20)", "2020-W53-5 09:00:00 PM", "2024 075 2:30:05 PM", "1710513005 -05", "-62135596800 +14", "999999999999999 +00", "03/15/24 15 14", "0000-W99-9 13:99:99 XM", "9999 366 12:59:59 AM", }; test "powershell.parseUFormat over the seeds" { try overSeeds(uformatProperty, &uformat_seeds); } test "fuzz powershell.parseUFormat" { try overFuzzer(uformatProperty); } test "mutate powershell.parseUFormat" { try overMutations(uformatProperty, &uformat_seeds); } /// Writing has no untrusted text, but it has the whole range of `Year`, /// which .NET never had to think about: an ISO week year past either end, /// a count of seconds since the epoch in the tens of quadrillions for /// `%s`, and `g` before year 1. None of it may crash. Where a value is one /// .NET could hold, what is written has to read back as it was. fn dotnetFormatProperty(random: std.Random) !void { var value = randomDateTime(random); var buffer: [512]u8 = undefined; inline for (.{ "o", "r", "U", "F", "dddd, MMMM d, yyyy h:mm:ss.FFFFFFF tt K", "yyyyy yy gg z" }) |format_string| { var writer = std.Io.Writer.fixed(&buffer); dotnet.format(value, format_string, &writer) catch |err| switch (err) { error.YearOutsideEra => try std.testing.expect(value.year < 1), else => return err, }; } inline for (.{ "%c %Z %s", "%G %g %V %u %C %j %U %e %k %l" }) |format_string| { var writer = std.Io.Writer.fixed(&buffer); try powershell.uformat(value, format_string, &writer); } // Brought within what .NET holds -- years 1 to 9999, a tick of a // hundred nanoseconds, whole minutes of offset within fourteen hours -- // and then written and read back. if (value.year < 1 or value.year > 9999) return; value.nanosecond -= value.nanosecond % 100; value.offset = @divTrunc(std.math.clamp(value.offset, -14 * std.time.s_per_hour, 14 * std.time.s_per_hour), 60) * 60; const round_trip = "yyyy-MM-ddTHH:mm:ss.fffffffzzz"; var writer = std.Io.Writer.fixed(&buffer); try dotnet.format(value, round_trip, &writer); const back = try dotnet.parse(round_trip, writer.buffered()); try std.testing.expect(back.has_offset); try std.testing.expectEqual(value, back.value); // `%Z` says only the hour, so the offset is brought to a whole one. value.offset = @divTrunc(value.offset, std.time.s_per_hour) * std.time.s_per_hour; value.nanosecond = 0; const uformat = "%F %T %Z"; var uwriter = std.Io.Writer.fixed(&buffer); try powershell.uformat(value, uformat, &uwriter); const uback = try powershell.parseUFormat(uformat, uwriter.buffered()); try std.testing.expectEqual(value, uback.value); } test "random values through dotnet.format and powershell.uformat" { try overRandom(dotnetFormatProperty); } // Locales -------------------------------------------------------------- /// Cuts fuzzer bytes into the runs a locale is made of. /// /// Where a run starts and how long it is both come out of the input, so /// that the fuzzer decides the shape of a locale as well as its contents: /// empty names, names that are prefixes of one another, and names that /// are not valid UTF-8 all arrive without being asked for. const Carver = struct { text: []const u8, at: usize = 0, /// Returns the next run, of at most `max` bytes. fn next(self: *Carver, max: usize) []const u8 { if (self.text.len == 0) return ""; // One byte says how long the run is, and the run follows it. const header = self.at % self.text.len; const wanted = self.text[header] % (max + 1); const from = (header + 1) % self.text.len; const len = @min(wanted, self.text.len - from); self.at = from + len; return self.text[from..][0..len]; } }; test Carver { // One byte of length, then that many bytes, then the next length. var carver: Carver = .{ .text = "\x03abc\x02ef" }; try std.testing.expectEqualStrings("abc", carver.next(8)); try std.testing.expectEqualStrings("ef", carver.next(8)); // A run is never longer than asked for, and an empty input yields // nothing however often it is asked. var short: Carver = .{ .text = "\xffabcdef" }; try std.testing.expect(short.next(2).len <= 2); var empty: Carver = .{ .text = "" }; try std.testing.expectEqualStrings("", empty.next(8)); try std.testing.expectEqualStrings("", empty.next(8)); } /// A `Locale` carved out of fuzzer bytes. /// /// Everything a locale holds is a string this library did not write, and /// ten of them are format strings: the `L` family stands for another /// format string rather than for a value, and the locale supplies it. So /// those reach the tokenizer at run time, where before a locale every /// format string was comptime and a bad one was a compile error. That is /// the new untrusted surface, and this is what points the fuzzer at it. /// /// The arrays live here so that the `Locale` can borrow them; a `Locale` /// built by `asLocale` must not outlive the `FuzzLocale` it came from. const FuzzLocale = struct { months: [12][]const u8 = undefined, months_short: [12][]const u8 = undefined, weekdays: [7][]const u8 = undefined, weekdays_short: [7][]const u8 = undefined, weekdays_min: [7][]const u8 = undefined, long: locale.LongDateFormat = undefined, fn init(text: []const u8) FuzzLocale { var carver: Carver = .{ .text = text }; var built: FuzzLocale = .{}; for (&built.months) |*name| name.* = carver.next(16); for (&built.months_short) |*name| name.* = carver.next(8); for (&built.weekdays) |*name| name.* = carver.next(16); for (&built.weekdays_short) |*name| name.* = carver.next(8); for (&built.weekdays_min) |*name| name.* = carver.next(4); built.long = .{ .LT = carver.next(24), .LTS = carver.next(24), .L = carver.next(24), .LL = carver.next(24), .LLL = carver.next(32), .LLLL = carver.next(32), // Left to be derived half the time, so that both ways through // `LongDateFormat.get` are reached. .l = if (text.len > 0 and text[0] & 1 == 0) carver.next(24) else null, .llll = if (text.len > 1 and text[1] & 1 == 0) carver.next(32) else null, }; return built; } fn asLocale(self: *const FuzzLocale, text: []const u8) locale.Locale { return .{ .tag = "fuzz", .months = &self.months, .months_short = &self.months_short, .weekdays = &self.weekdays, .weekdays_short = &self.weekdays_short, .weekdays_min = &self.weekdays_min, .long_date_format = self.long, .week = .{ // Any rule at all, including the ones whose first week // opens in the December before. .starts_on = @fromBackingInt(@intCast(if (text.len > 2) text[2] % 7 else 0)), .january_day_in_first_week = if (text.len > 3) @as(i8, @bitCast(text[3])) else 1, }, .months_decline = .{ .day_then_month = text.len > 4 and text[4] & 1 == 1, .month_then_ordinal = text.len > 4 and text[4] & 2 == 2, }, }; } }; /// The sequences a locale can reach, including every localized one, since /// those are the ones whose expansion the locale controls. const locale_formats = [_][]const u8{ "L", "LL", "LLL", "LLLL", "l", "ll", "lll", "llll", "LT", "LTS", "A a", "Do Mo wo DDDo do Wo", "dddd D MMMM YYYY", "ddd MMM dd", "e d E w ww gg gggg", "[x] LLLL [y] L", }; /// Writing a date in a locale nobody sanitized has to be safe, whatever /// the locale says a sequence stands for. fn localeFormatProperty(text: []const u8) !void { var built: FuzzLocale = .init(text); const in = built.asLocale(text); const dates = [_]DateTime{ .{ .year = 2024, .month = .Mar, .day = 5, .hour = 13, .minute = 7, .weekday = .Tue }, .{ .year = 1900, .month = .Jan, .day = 1, .hour = 0, .minute = 0, .weekday = .Mon }, .{ .year = 2024, .month = .Dec, .day = 31, .hour = 23, .minute = 59, .weekday = .Tue }, }; var buffer: [4096]u8 = undefined; for (dates) |value| { inline for (locale_formats) |fmt| { var writer = std.Io.Writer.fixed(&buffer); // A locale can name an expansion longer than any buffer, so // running out of room is an answer rather than a failure. value.formatWith(fmt, in, &writer) catch {}; } } } /// And reading one back. Whatever a locale lets through still has to be a /// real date, which is the promise `parseWith` makes to every caller and /// which a locale is in no position to change. fn localeParseProperty(text: []const u8) !void { var built: FuzzLocale = .init(text); const in = built.asLocale(text); inline for (.{ DateTime.Mode.lenient, DateTime.Mode.strict }) |mode| { inline for (.{ "LLLL", "L", "llll", "dddd D MMMM YYYY", "Do MMM A" }) |fmt| { if (DateTime.parseWith(fmt, text, .{ .locale = in, .mode = mode })) |result| { try isWellFormed(result.value); try std.testing.expect(result.skipped <= result.str.len); try std.testing.expect(result.str.len <= text.len); } else |_| {} } } } /// The same against the locales that ship, which have real names rather /// than carved ones: what this looks for is an input that gets a real /// table to misbehave. fn localeTableProperty(text: []const u8) !void { const shipped: []const locale.Locale = if (locale.embedded) locale.all else &.{locale.en}; // One of them per input rather than all of them, chosen by the input. // Walking a hundred and thirty-seven tables for every input spends // the run on the same answers over and over; letting the fuzzer pick // gets through far more inputs, and it reaches every locale soon // enough over a run of any length. const in = shipped[(if (text.len > 0) text[text.len - 1] else 0) % shipped.len]; inline for (.{ DateTime.Mode.lenient, DateTime.Mode.strict }) |mode| { if (DateTime.parseWith("dddd D MMMM YYYY", text, .{ .locale = in, .mode = mode })) |result| { try isWellFormed(result.value); } else |_| {} } // And the name lookups on their own, which is where a name that is a // prefix of another one has to lose to the longer one. if (in.matchMonth(text, .MMMM)) |found| { try std.testing.expect(found.len <= text.len); try std.testing.expect(found.len > 0); } if (in.matchWeekday(text, .dddd)) |found| { try std.testing.expect(found.len <= text.len); try std.testing.expect(found.len > 0); } if (in.matchMeridiem(text)) |found| { try std.testing.expect(found.len <= text.len); } _ = locale.byName(text); } const locale_seeds = [_][]const u8{ "", // A locale's worth of plausible runs: names, then the `L` family. "\x03Jan\x03Feb\x03Mar\x03Apr\x03May\x03Jun\x03Jul\x03Aug\x03Sep\x03Oct\x03Nov\x03Dec", // Format strings where a locale expects them, including ones that // name a localized sequence and so would expand for ever if nothing // stopped them. "\x0aMM/DD/YYYY\x0aD MMMM YYYY\x04LLLL\x01L", "\x04LLLL\x04LLLL\x04LLLL\x04LLLL\x04LLLL\x04LLLL", // Empty names throughout, which match everywhere and consume nothing. "\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00", // Bracketed and escaped text in an expansion, which the tokenizer // treats specially and which a locale can now leave unbalanced. "\x06[abc]\x02\\\\\x05[a[b]\x03[ab", // Real dates, for the parsing half. "Tuesday 5 March 2024", "mardi 5 mars 2024", "\u{432}\u{442}\u{43e}\u{440}\u{43d}\u{438}\u{43a} 5 \u{43c}\u{430}\u{440}\u{442}\u{430} 2024", "5th Mar PM", "\xff\xff\xff\xff\xff\xff\xff\xff", }; test "DateTime.formatWith over the locale seeds" { try overSeeds(localeFormatProperty, &locale_seeds); } test "fuzz DateTime.formatWith with a locale" { try overFuzzer(localeFormatProperty); } test "mutate DateTime.formatWith with a locale" { try overMutations(localeFormatProperty, &locale_seeds); } test "DateTime.parseWith over the locale seeds" { try overSeeds(localeParseProperty, &locale_seeds); } test "fuzz DateTime.parseWith with a locale" { try overFuzzer(localeParseProperty); } test "mutate DateTime.parseWith with a locale" { try overMutations(localeParseProperty, &locale_seeds); } test "the shipped locales over the locale seeds" { try overSeeds(localeTableProperty, &locale_seeds); } test "fuzz the shipped locales" { try overFuzzer(localeTableProperty); } test "mutate the shipped locales" { try overMutations(localeTableProperty, &locale_seeds); } /// A locale that ships has to be able to read back what it wrote, for any /// date and in any language. /// /// The properties above are weak on purpose: they ask that nothing falls /// over, because a locale carved out of fuzzer bytes has no business /// round tripping. This is the strong one, and it is only possible /// because the shipped tables are real: a name written in a language has /// to be a name readable in that language, whatever the date and whatever /// the alphabet. An asymmetry between the two sides -- a name that is a /// prefix of another and wins when it should lose, a form written that is /// not among the forms matched -- shows up here and nowhere else. /// /// The date comes out of the input rather than out of a list, so this /// explores the calendar as well as the languages. fn localeRoundTripProperty(text: []const u8) !void { if (text.len < 6) return; const shipped: []const locale.Locale = if (locale.embedded) locale.all else &.{locale.en}; const in = shipped[text[0] % shipped.len]; // moment's pseudo-locale wraps its names in tildes, which are not // letters in any alphabet and which moment's own name pattern does // not accept either. It is for making untranslated text obvious on // screen, not for reading back. if (std.mem.eql(u8, in.tag, "x-pseudo")) return; // Any day of a wide span, kept inside what a four digit year can // write since the format string below cannot express anything wider. const span = 3_000_000; const days: Date.DayNumber = @mod(std.mem.readInt(i32, text[1..5], .little), span) - span / 3; const date = Date.fromDayNumber(days); if (!date.isRegular() or date.year < 1 or date.year > 9999) return; const value: DateTime = .{ .year = date.year, .month = date.month, .day = date.day, .weekday = date.dayOfWeek(), }; // Separated by a character no language uses in a name, so that what // is being tested is the names rather than where one ends. var buffer: [256]u8 = undefined; var writer = std.Io.Writer.fixed(&buffer); try value.formatWith("dddd|D|MMMM|YYYY", in, &writer); const written = writer.buffered(); const parsed = DateTime.parseWith("dddd|D|MMMM|YYYY", written, .{ .locale = in, .mode = .strict, }) catch |err| { std.debug.print("fuzz: {s} wrote {s} and could not read it: {}\n", .{ in.tag, written, err }); return err; }; try std.testing.expectEqual(value.year, parsed.value.year); try std.testing.expectEqual(value.month, parsed.value.month); try std.testing.expectEqual(value.day, parsed.value.day); try std.testing.expectEqual(value.weekday, parsed.value.weekday); } const locale_round_trip_seeds = [_][]const u8{ // A locale index and four bytes of day number, which is what the // property reads; the rest are what mutating these produces. "\x00\x00\x00\x00\x00\x00", "\x01\x40\x4c\x00\x00\x00", "\x2a\xff\xff\xff\x7f\x00", "\x55\x00\x00\x00\x80\x00", "\x7f\x9c\x1f\x00\x00\x00", }; test "the shipped locales round trip over the seeds" { try overSeeds(localeRoundTripProperty, &locale_round_trip_seeds); } test "fuzz the shipped locales round trip" { try overFuzzer(localeRoundTripProperty); } test "mutate the shipped locales round trip" { try overMutations(localeRoundTripProperty, &locale_round_trip_seeds); } // CLDR patterns -------------------------------------------------------- /// A CLDR pattern is text this library did not write, and unlike a /// moment.js format string it does not have to be comptime: `cldr`'s /// runtime entry point exists because the locale's own patterns arrive as /// data, and a caller may just as well hand it a pattern out of a /// configuration file. So the tokenizer, the quoting, and every field /// writer are reachable from arbitrary bytes, which is what this points /// the fuzzer at. /// /// The property is only that nothing crashes and that a refusal is one of /// the three documented errors. What a pattern *should* write is what /// `zig build oracle-cldr` is for, and a fuzzer has no opinion about it. fn cldrPatternProperty(text: []const u8) !void { const dates = [_]DateTime{ .{ .year = 2024, .month = .Mar, .day = 5, .hour = 13, .minute = 7, .weekday = .Tue, .offset = -21036 }, .{ .year = 1, .month = .Jan, .day = 1, .weekday = .Mon }, .{ .year = -4000, .month = .Dec, .day = 31, .hour = 23, .minute = 59, .second = 59, .weekday = .Tue }, }; // One shipped locale per input, chosen by the input, for the same // reason the moment locale target does it: walking every table for // every input spends the run on the same answers over and over. const shipped: []const cldr.Locale = if (cldr.embedded) cldr.all else &.{cldr.en}; const in = shipped[(if (text.len > 0) text[text.len - 1] else 0) % shipped.len]; var buffer: [4096]u8 = undefined; for (dates) |value| { var writer = std.Io.Writer.fixed(&buffer); // A pattern can ask for more than any buffer holds -- `yyyy` // repeated is a legal pattern -- so running out of room is an // answer rather than a failure. cldr.formatRuntime(value, text, in, &writer) catch |err| switch (err) { error.WriteFailed => {}, error.UnterminatedQuote, error.UnknownField, error.InvalidFieldWidth => {}, }; // And the locale's own patterns, which are the ones a caller // reaches without writing a pattern at all. for ([_]cldr.Length{ .full, .long, .medium, .short }) |length| { var styled = std.Io.Writer.fixed(&buffer); cldr.formatDateTime(value, length, length, in, &styled) catch {}; } } } const cldr_pattern_seeds = [_][]const u8{ "", "yyyy-MM-dd'T'HH:mm:ssXXX", "EEEE, MMMM d, y 'at' h:mm:ss a zzzz", "GGGGG QQQQQ LLLLL cccccc bbbbb BBBBB", // Quoting, which is the part of the tokenizer with state in it. "'", "''", "'unterminated", "'don''t' HH", "''", // Counts at and past the edge of what each field means. "MMMMMM", "OO", "VVV", "jjj", "yyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyy", "SSSSSSSSSSSSSSSSSSSS", "AAAAAAAAAAAAAAAAAAAA", // Letters that name nothing, which are reserved rather than text. "PPPP", "hello world", "\xff\xff\xff\xff", }; test "cldr.formatRuntime over the seeds" { try overSeeds(cldrPatternProperty, &cldr_pattern_seeds); } test "fuzz cldr.formatRuntime" { try overFuzzer(cldrPatternProperty); } test "mutate cldr.formatRuntime" { try overMutations(cldrPatternProperty, &cldr_pattern_seeds); } // Week rules ----------------------------------------------------------- /// A week rule is two numbers a locale hands over, and both of them reach /// the calendar arithmetic. /// /// The day the week starts on is one of seven, but the day that anchors /// week one is signed and can name a day of the December before -- eight /// of moment's locales use one that does. So the arithmetic has to hold /// for an anchor nobody would write as well as for the four ISO 8601 /// uses. fn weekRuleProperty(text: []const u8) !void { if (text.len < 6) return; const year: Year = @bitCast(std.mem.readInt(u32, text[0..4], .little)); const starts_on: DayOfWeek = @fromBackingInt(@intCast(text[4] % 7)); const anchor: i8 = @bitCast(text[5]); const weeks = Date.weeksInYear(year, starts_on, anchor); try std.testing.expect(weeks >= 1); // Every week the rule admits names a real date, and that date is back // in the week it came from. var week: u16 = 1; while (week <= @as(u16, @intCast(@min(weeks, 60)))) : (week += 1) { const date = Date.fromWeek(year, week, starts_on, starts_on, anchor); if (!date.isRegular()) continue; const found = date.weekOfYear(starts_on, anchor); try std.testing.expect(found.week >= 1); } } const week_rule_seeds = [_][]const u8{ // 2024, Monday, the fourth: ISO 8601. "\xe8\x07\x00\x00\x01\x04", // 2024, Sunday, the first: what moment's `en` uses. "\xe8\x07\x00\x00\x00\x01", // 2024, Sunday, five days before it: what a `doy` of 12 comes to. "\xe8\x07\x00\x00\x00\xfb", // The ends of the calendar, where the arithmetic saturates. "\x00\x00\x00\x80\x01\x04", "\xff\xff\xff\x7f\x01\x04", "\x00\x00\x00\x00\x00\x00", }; test "the week rules over the seeds" { try overSeeds(weekRuleProperty, &week_rule_seeds); } test "fuzz the week rules" { try overFuzzer(weekRuleProperty); } test "mutate the week rules" { try overMutations(weekRuleProperty, &week_rule_seeds); } // POSIX TZ rules ------------------------------------------------------- /// A rule that parses has to answer for any instant without falling over, /// including the ends of the range. fn posixtzProperty(text: []const u8) !void { const rule = posixtz.parse(text) catch return; // Inside the calendar the answers have to hold together. for ([_]i64{ 0, 1710513005, -2208988800, std.math.minInt(i32), std.math.maxInt(i32), // A margin off each end, because placing a span needs the years // either side and the outermost year has none. See `Posix.spanAt`. Date.min_seconds + 2 * 366 * std.time.s_per_day, Date.max_seconds - 2 * 366 * std.time.s_per_day, }) |at| { const local_type = rule.typeAt(at); try std.testing.expect(local_type.designation.len > 0); // A span has to contain the instant it was asked about, which is // the whole reason a caller can trust its bounds. const span = rule.spanAt(at); try std.testing.expect(span.start <= at); try std.testing.expect(span.end > at); try std.testing.expectEqual(local_type.offset, span.local_type.offset); // The bounds have to be switches rather than arbitrary instants: // the span holds all the way to its end, and something else // begins there. This is what the agreement above stopped being // able to check once `typeAt` started deferring to `spanAt`. if (span.start > std.math.minInt(i64) and span.start < Date.max_seconds) { try std.testing.expectEqual(span.local_type.offset, rule.typeAt(span.start).offset); } if (span.end < Date.max_seconds and span.end > Date.min_seconds) { const next = rule.spanAt(span.end); try std.testing.expect(next.start >= span.end); } } // Outside it there is no year to evaluate the rule against, so the // only promise is that asking is safe. See `Posix.spanAt`. for ([_]i64{ std.math.minInt(i64), std.math.maxInt(i64), Date.min_seconds, Date.max_seconds, Date.min_seconds - 1, Date.max_seconds + 1, std.math.minInt(i64) / 4, std.math.maxInt(i64) / 4, }) |at| { _ = rule.typeAt(at); _ = rule.spanAt(at); } } const posixtz_seeds = [_][]const u8{ "", "CST6CDT,M3.2.0,M11.1.0", "IST-5:30", "<-03>3", "EST5EDT", "EST5EDT,M3.2.0/2,M11.1.0/2", "CST6CDT,J60,J300", "CST6CDT,59,300", "CST6CDT,M3.5.0,M11.1.0", "AAA0BBB,M1.1.0/167,M1.1.0/-167", "AAA24BBB25,M1.1.0,M2.1.0", "<>0", " at); try std.testing.expectEqual(span.local_type, rule.typeAt(at)); // The next span starts where this one ends, exactly, which is // what lets `TimeZone.resolve` walk from one to the next. if (span.end < Date.max_seconds and span.end > Date.min_seconds) { try std.testing.expectEqual(span.end, rule.spanAt(span.end).start); } } for ([_]i64{ std.math.minInt(i64), std.math.maxInt(i64), Date.min_seconds, Date.max_seconds, }) |at| { _ = rule.spanAt(at); } } const posixtz_lenient_seeds = posixtz_seeds ++ [_][]const u8{ "ABC-25", "XYZ3:75", "XYZ3,junk", "EST5:-1", "ABC5DEF,M4.1.9,M10.1.0", "ABC5DEF,M4.1.0/500", "ABC5DEF,M4.1.0/-x,M10.1.0", "ABC5DEF,M 4.1.0/3M1.1.0", "EST99999999999DEF,J1/-65535", "ABC5DEF,M4.1.65535/2147483647,M12.5.65535/-2147483648", }; test "posixtz.parseLenient over the seeds" { try overSeeds(posixtzLenientProperty, &posixtz_lenient_seeds); } test "fuzz posixtz.parseLenient" { try overFuzzer(posixtzLenientProperty); } test "mutate posixtz.parseLenient" { try overMutations(posixtzLenientProperty, &posixtz_lenient_seeds); } // TZif files ----------------------------------------------------------- /// The one that reads a binary format rather than text, and the one most /// worth pointing a fuzzer at: everything it returns is a slice into /// bytes it was handed, sized by counts the same bytes claimed. fn tzifProperty(bytes: []const u8) !void { const file = tzif.parse(bytes) catch return; // Every index the counts admit has to be readable. var index: usize = 0; while (index < file.transitionCount()) : (index += 1) _ = file.transitionAt(index); index = 0; while (index < file.typeCount()) : (index += 1) { const local_type = file.typeAt(index); // A designation is a slice into the file's own bytes and has to // stay inside them. try std.testing.expect(@intFromPtr(local_type.designation.ptr) >= @intFromPtr(bytes.ptr)); try std.testing.expect( @intFromPtr(local_type.designation.ptr) + local_type.designation.len <= @intFromPtr(bytes.ptr) + bytes.len, ); } _ = file.defaultType(); _ = file.lastType(); for ([_]i64{ 0, 1710513005, -2208988800, std.math.minInt(i64), std.math.maxInt(i64) }) |at| { if (file.spanAtTimestamp(at)) |span| { try std.testing.expect(span.start <= at); try std.testing.expect(span.end > at); } _ = file.typeAtTimestamp(at); } // Transitions are supposed to be sorted, which is what makes the // binary search in `spanAtTimestamp` mean anything. if (file.transitionCount() > 1) { index = 1; while (index < file.transitionCount()) : (index += 1) { if (file.transitionAt(index - 1) > file.transitionAt(index)) break; } } } const tzif_seeds = [_][]const u8{ "", "TZif", "TZif2", "TZif" ++ @as([40]u8, @splat(0x00)), "TZif" ++ @as([40]u8, @splat(0xff)), "TZif2" ++ @as([39]u8, @splat(0x00)), "XZif" ++ @as([40]u8, @splat(0x00)), "TZif" ++ @as([15]u8, @splat(0x00)) ++ @as([25]u8, @splat(0xff)), }; test "tzif.parse over the seeds" { try overSeeds(tzifProperty, &tzif_seeds); } test "fuzz tzif.parse" { try overFuzzer(tzifProperty); } test "mutate tzif.parse" { try overMutations(tzifProperty, &tzif_seeds); } // Zone names ----------------------------------------------------------- /// A name that validates is about to be joined onto a directory, so it /// must not be able to reach outside one. fn zoneNameProperty(text: []const u8) !void { tzdb.validateName(text) catch return; try std.testing.expect(text.len > 0); try std.testing.expect(text[0] != '/'); try std.testing.expect(text[0] != '.'); try std.testing.expect(std.mem.find(u8, text, "..") == null); for (text) |char| try std.testing.expect(std.ascii.isPrint(char)); } const zone_name_seeds = [_][]const u8{ "", "UTC", "America/Chicago", "Etc/GMT+5", "US/Central", "../../etc/passwd", "/etc/passwd", ".hidden", "a/../b", "a//b", "America/Chicago\x00", "\x00", "..", ".", &@as([257]u8, @splat('a')), }; test "tzdb.validateName over the seeds" { try overSeeds(zoneNameProperty, &zone_name_seeds); } test "fuzz tzdb.validateName" { try overFuzzer(zoneNameProperty); } test "mutate tzdb.validateName" { try overMutations(zoneNameProperty, &zone_name_seeds); } // Go layouts ----------------------------------------------------------- /// A Go layout is comptime, so the untrusted surface is the text. The /// layouts here between them reach every kind of chunk the parser has: /// names long and short, padded and unpadded numbers, a two digit year, a /// meridiem, the three spellings of an offset, a zone name, and fractions /// both fixed and trimmed. fn golayoutProperty(text: []const u8) !void { inline for (.{ golayout.layout.rfc3339_nano, golayout.layout.rfc1123z, golayout.layout.rfc850, golayout.layout.unix_date, golayout.layout.default, golayout.layout.stamp_micro, golayout.layout.kitchen, "2006-002 15:04:05.000 Z0700", }) |layout_string| { if (golayout.parse(layout_string, text)) |value| { // Go reads an offset of up to `+24:60:60`, past the day that // `isWellFormed` holds the other parsers to, so the offset is // held to Go's limit here and everything else to the usual one. var clock = value; clock.offset = 0; try isWellFormed(clock); const go_limit = 24 * std.time.s_per_hour + 60 * std.time.s_per_min + 60; try std.testing.expect(@abs(value.offset) <= go_limit); } else |_| {} } } const golayout_seeds = [_][]const u8{ "", "2024-03-15T14:30:05.123456789-05:00", "2024-03-15T14:30:05Z", "Fri, 15 Mar 2024 14:30:05 -0500", "Friday, 15-Mar-24 14:30:05 CDT", "Fri Mar 15 14:30:05 CDT 2024", "03/15 02:30:05PM '24 -0500", "Mar 15 14:30:05.123456", "2:30PM", "2024-075 14:30:05.123 Z", "2024-366 14:30:05.123 +0530", "9999-12-31T23:59:59.999999999+23:59", "Mar 32 25:61:61.000000", "13/32 13:60:60AM '99 +9999", }; test "golayout.parse over the seeds" { try overSeeds(golayoutProperty, &golayout_seeds); } test "fuzz golayout.parse" { try overFuzzer(golayoutProperty); } test "mutate golayout.parse" { try overMutations(golayoutProperty, &golayout_seeds); } // Calendar arithmetic -------------------------------------------------- /// `DateTime.addChecked` either answers with the date and time the /// calendar says, or refuses with `OutOfRange` exactly when that answer is /// outside the years a `Year` can hold -- never panics, never refuses /// something that fits, and never answers something that does not. /// /// The expected answer is worked out here in `i256`, where no duration a /// `Duration` can hold overflows anything, following XML Schema's order as /// `add` does: the sub-day part and its carry, the months with the day /// clamped, then the days. Two further checks do not share that working: /// a purely sub-day duration moves the instant by exactly that much, and /// a purely whole-day one moves the day number by exactly that many. fn arithmeticProperty(random: std.Random) !void { const start = randomDateTime(random); const duration = randomDuration(random); const arithmetic: Duration.Arithmetic = if (random.boolean()) .xml_schema else .composite; checkArithmetic(start, duration, arithmetic) catch |err| { std.debug.print("addChecked ({s}): {any}\n plus {any}\n", .{ @tagName(arithmetic), start, duration }); return err; }; } fn checkArithmetic(start: DateTime, duration: Duration, arithmetic: Duration.Arithmetic) !void { const got = start.addCheckedWith(duration, arithmetic); const ns_per_day: i256 = Duration.nanoseconds_per_day; const time_of_day: i256 = @as(i256, start.hour) * Duration.nanoseconds_per_hour + @as(i256, start.minute) * Duration.nanoseconds_per_minute + @as(i256, start.second) * Duration.nanoseconds_per_second + start.nanosecond; const total = time_of_day + duration.nanoseconds; const carry = @divFloor(total, ns_per_day); const rest = total - carry * ns_per_day; const month_index = @as(i256, start.year) * 12 + (@backingInt(start.month) - 1) + duration.months; const year_wide = @divFloor(month_index, 12); const year_fits = year_wide >= std.math.minInt(Year) and year_wide <= std.math.maxInt(Year); const expected: ?Date = blk: { if (!year_fits) break :blk null; const year: Year = @intCast(year_wide); const month: Month = @fromBackingInt(@intCast(@as(u4, @intCast(@mod(month_index, 12) + 1)))); const moved = @as(i256, duration.days) + carry; // XML Schema clamps the day to its month and then counts; ISO // 8601-2's composite method does the same unless the day itself was // moved, in which case its full value counts from the first of the // month and the excess runs into the next. const days = if (arithmetic == .composite and moved != 0) @as(i256, (Date{ .year = year, .month = month, .day = 1 }).toDayNumber()) + (start.day - 1) + moved else @as(i256, (Date{ .year = year, .month = month, .day = @min(start.day, month.lastDay(year)) }).toDayNumber()) + moved; if (days < Date.min_day_number or days > Date.max_day_number) break :blk null; break :blk Date.fromDayNumber(@intCast(days)); }; const value = got catch |err| { try std.testing.expectEqual(error.OutOfRange, err); // Refused, so the calendar's answer must really be out of range. try std.testing.expectEqual(@as(?Date, null), expected); return; }; // Answered, so it must be the calendar's answer. try std.testing.expect(expected != null); try isWellFormed(value); try std.testing.expectEqual(expected.?, value.asDate()); try std.testing.expectEqual(@as(i256, value.hour), @divFloor(rest, Duration.nanoseconds_per_hour)); try std.testing.expectEqual(@as(i256, value.minute), @mod(@divFloor(rest, Duration.nanoseconds_per_minute), 60)); try std.testing.expectEqual(@as(i256, value.second), @mod(@divFloor(rest, Duration.nanoseconds_per_second), 60)); try std.testing.expectEqual(@as(i256, value.nanosecond), @mod(rest, Duration.nanoseconds_per_second)); try std.testing.expectEqual(start.offset, value.offset); if (duration.months == 0 and duration.days == 0) { // Only the clock moved, at a fixed offset: the instant moved by // exactly the duration. try std.testing.expectEqual( @as(i256, start.toInstant().timestamp) + duration.nanoseconds, @as(i256, value.toInstant().timestamp), ); } if (duration.months == 0 and duration.nanoseconds == 0) { // Only whole days: the day number moved by exactly that many, and // the time of day did not move at all. try std.testing.expectEqual( @as(i256, start.asDate().toDayNumber()) + duration.days, @as(i256, value.asDate().toDayNumber()), ); try std.testing.expectEqual(start.hour, value.hour); try std.testing.expectEqual(start.nanosecond, value.nanosecond); } } test "random DateTime.addChecked" { try overRandom(arithmeticProperty); } // The two edges, by name, since a random draw reaches them only by luck: // a day before the last one fits and a day after it does not, and the same // at the other end. test "DateTime.addChecked at the ends of the calendar" { const last: DateTime = .{ .year = std.math.maxInt(Year), .month = .Dec, .day = 31, .hour = 23, .weekday = (Date{ .year = std.math.maxInt(Year), .month = .Dec, .day = 31 }).dayOfWeek() }; inline for (.{ Duration.Arithmetic.xml_schema, Duration.Arithmetic.composite }) |a| try checkArithmetic(last, .{ .nanoseconds = Duration.nanoseconds_per_hour - 1 }, a); inline for (.{ Duration.Arithmetic.xml_schema, Duration.Arithmetic.composite }) |a| try checkArithmetic(last, .{ .nanoseconds = Duration.nanoseconds_per_hour }, a); inline for (.{ Duration.Arithmetic.xml_schema, Duration.Arithmetic.composite }) |a| try checkArithmetic(last, .{ .days = -1 }, a); inline for (.{ Duration.Arithmetic.xml_schema, Duration.Arithmetic.composite }) |a| try checkArithmetic(last, .{ .months = 1 }, a); const first: DateTime = .{ .year = std.math.minInt(Year), .month = .Jan, .day = 1, .weekday = (Date{ .year = std.math.minInt(Year), .month = .Jan, .day = 1 }).dayOfWeek() }; inline for (.{ Duration.Arithmetic.xml_schema, Duration.Arithmetic.composite }) |a| try checkArithmetic(first, .{ .nanoseconds = -1 }, a); inline for (.{ Duration.Arithmetic.xml_schema, Duration.Arithmetic.composite }) |a| try checkArithmetic(first, .{ .days = 1 }, a); inline for (.{ Duration.Arithmetic.xml_schema, Duration.Arithmetic.composite }) |a| try checkArithmetic(first, .{ .months = -1 }, a); inline for (.{ Duration.Arithmetic.xml_schema, Duration.Arithmetic.composite }) |a| try checkArithmetic(first, .{ .months = std.math.minInt(i64), .days = std.math.minInt(i64), .nanoseconds = std.math.minInt(i128) }, a); inline for (.{ Duration.Arithmetic.xml_schema, Duration.Arithmetic.composite }) |a| try checkArithmetic(first, .{ .months = std.math.maxInt(i64), .days = std.math.maxInt(i64), .nanoseconds = std.math.maxInt(i128) }, a); } // Round trips ---------------------------------------------------------- // Anything with an inverse has to survive it, for any date at all rather // than the handful a test would think to write down. test "fuzz the calendar round trips" { const driver = struct { fn one(_: void, smith: *std.testing.Smith) anyerror!void { const year = smith.valueRangeAtMost(Year, -10000, 10000); const month: Month = @fromBackingInt(@intCast(smith.valueRangeAtMost(u4, 1, 12))); const date: Date = .{ .year = year, .month = month, .day = smith.valueRangeAtMost(u6, 1, month.lastDay(year)), }; // A date is its day number and back again. try std.testing.expectEqual(date, Date.fromDayNumber(date.toDayNumber())); // And its day of the year and back again. try std.testing.expectEqual(date, Date.fromDayOfYear(date.year, date.dayOfYear())); // And its week and weekday and back again, under either rule. const iso = date.isoWeek(); try std.testing.expectEqual(date, Date.fromWeek(iso.year, iso.week, date.dayOfWeek(), .Mon, 4)); try std.testing.expect(iso.week >= 1 and iso.week <= 53); const english = date.localeWeek(); try std.testing.expectEqual(date, Date.fromWeek(english.year, english.week, date.dayOfWeek(), .Sun, 1)); try std.testing.expect(english.week >= 1 and english.week <= 54); } }; try std.testing.fuzz({}, driver.one, .{}); } /// The calendar round trips again, over every year a `Year` holds, drawn /// by `overRandom` so that they run on more than the one date a `Smith` /// with nothing to read produces. fn calendarProperty(random: std.Random) !void { const date = randomDate(random); checkCalendar(date) catch |err| { std.debug.print("calendar: {any}\n", .{date}); return err; }; } fn checkCalendar(date: Date) !void { try std.testing.expectEqual(date, Date.fromDayNumber(date.toDayNumber())); try std.testing.expectEqual(date, Date.fromDayOfYear(date.year, date.dayOfYear())); const iso = date.isoWeek(); try std.testing.expect(iso.week >= 1 and iso.week <= 53); try std.testing.expectEqual(date, Date.fromWeek(iso.year, iso.week, date.dayOfWeek(), .Mon, 4)); const english = date.localeWeek(); try std.testing.expect(english.week >= 1 and english.week <= 54); try std.testing.expectEqual(date, Date.fromWeek(english.year, english.week, date.dayOfWeek(), .Sun, 1)); } test "random calendar round trips" { try overRandom(calendarProperty); } // `Date.fromDayNumber` and `Date.toDayNumber` are // Joffe's algorithms, and `hinnant.civilFromDays` and // `hinnant.daysFromCivil` the plain ones they replaced. They have to agree // on every day number a `Date` holds; `zig build verify-days` checks all of // them, and these look for a disagreement on every ordinary test run. test "fuzz Date day numbers against Hinnant" { const driver = struct { fn one(_: void, smith: *std.testing.Smith) anyerror!void { try checkAgainstHinnant(smith.valueRangeAtMost(Date.DayNumber, Date.min_day_number, Date.max_day_number)); } }; try std.testing.fuzz({}, driver.one, .{}); } /// A day number anywhere a `Date` reaches, drawn the way `randomYear` /// draws a year: often near the present, sometimes anywhere, and sometimes /// at one of the two ends. fn hinnantProperty(random: std.Random) !void { const days: Date.DayNumber = switch (random.uintLessThan(u8, 8)) { 0 => Date.min_day_number + random.intRangeAtMost(Date.DayNumber, 0, 146097), 1 => Date.max_day_number - random.intRangeAtMost(Date.DayNumber, 0, 146097), 2, 3 => random.intRangeAtMost(Date.DayNumber, Date.min_day_number, Date.max_day_number), else => random.intRangeAtMost(Date.DayNumber, -4_000_000, 4_000_000), }; try checkAgainstHinnant(days); } fn checkAgainstHinnant(days: Date.DayNumber) !void { const expected = hinnant.civilFromDays(days); const got = Date.fromDayNumber(days); errdefer std.debug.print("day {d}: Hinnant {any}, got {any}\n", .{ days, expected, got }); try std.testing.expectEqual(expected.year, got.year); try std.testing.expectEqual(expected.month, got.month.monthNumber()); try std.testing.expectEqual(expected.day, got.day); try std.testing.expectEqual(@as(i64, days), hinnant.daysFromCivil(expected)); try std.testing.expectEqual(days, got.toDayNumber()); } test "random Date day numbers against Hinnant" { try overRandom(hinnantProperty); } // Formatting and parsing are inverses for any instant, which is the // property the moment oracles cannot check because they compare text // rather than values. test "fuzz format and parse round trip" { const driver = struct { fn one(_: void, smith: *std.testing.Smith) anyerror!void { // Kept inside the range a four digit year can write, since // the format string cannot express anything wider. const at = smith.valueRangeAtMost(i64, -62135596800, 253402300799); const offset_minutes = smith.valueRangeAtMost(i32, -12 * 60, 14 * 60); const seconds = offset_minutes * 60; const shifted: Instant = .{ .timestamp = @as(i128, at + seconds) * std.time.ns_per_s, }; var value = shifted.asDateTime(); value.offset = seconds; var buffer: [64]u8 = undefined; var writer = std.Io.Writer.fixed(&buffer); try value.format("YYYY-MM-DDTHH:mm:ssZ", &writer); const parsed = try DateTime.parseStrict("YYYY-MM-DDTHH:mm:ssZ", writer.buffered()); try std.testing.expectEqual(value.year, parsed.value.year); try std.testing.expectEqual(value.month, parsed.value.month); try std.testing.expectEqual(value.day, parsed.value.day); try std.testing.expectEqual(value.hour, parsed.value.hour); try std.testing.expectEqual(value.minute, parsed.value.minute); try std.testing.expectEqual(value.second, parsed.value.second); try std.testing.expectEqual(value.offset, parsed.value.offset); try std.testing.expectEqual(value.weekday, parsed.value.weekday); } }; try std.testing.fuzz({}, driver.one, .{}); }