eBPF-based security platform
testing: prove the pin names, archive paths, hex and JSON strings in Lean 4
Daniel Borkmann83679ca8b332
diff --git a/Documentation/contribute/testing/proof-coverage.rst b/Documentation/contribute/testing/proof-coverage.rstindex fd3eaf22..5d4b1966 100644--- a/Documentation/contribute/testing/proof-coverage.rst+++ b/Documentation/contribute/testing/proof-coverage.rst@@ -69,6 +69,11 @@ or shorter, and "lengths 0 to 6" every input of each of those lengths.exactly ``2 * n`` hex digits of either case and yields theirvalue, and ``hex_decode_max()`` any even count up to ``2 * cap``,reading no further than the digit after them+ * - ``hex-model``+ - ``hex_encode()``, ``hex_decode()``, ``hex_decode_max()``+ - Up to 8 bytes, strings up to 17 characters, counts and capacities+ up to 8 and past ``SIZE_MAX / 2``+ - The result and the bytes of the Lean model ``Shirudo.Hex``* - ``io-lines``- ``lines_len()``- Up to 8 bytes@@ -96,6 +101,10 @@ or shorter, and "lengths 0 to 6" every input of each of those lengths.- Every field of 8 and 12 bytes- Accepted exactly as octal digits with blanks or NULs around them,at their value; nothing written on refusal+ * - ``paths-bpffs-name-model``+ - ``upatch_bpffs_name()``, ``upatch_name_from_bpffs()``+ - Up to 8 bytes, buffers up to 18+ - The result and the string of the Lean model ``Shirudo.PinName``* - ``bpm-tar-header``- ``bpm_tar_header_ok()``- Every header without an octal checksum; the checksum against@@ -111,6 +120,10 @@ or shorter, and "lengths 0 to 6" every input of each of those lengths.- ``bpm_name_ok()``, ``bpm_version_ok()``, ``bpm_package_name_ok()``- Up to 129 bytes, past the 128-byte limit- Exactly the character, length and first-character rules+ * - ``bpm-archive-path-model``+ - ``bpm_archive_rel_ok()``, ``package_member_name_ok()``+ - Names of lengths 0 to 10, members up to 3 bytes+ - The decision of the Lean model ``Shirudo.ArchivePath``* - ``bpm-semver-valid``- ``bpm_semver_valid()``- Up to 11 bytes@@ -293,6 +306,17 @@ or shorter, and "lengths 0 to 6" every input of each of those lengths.- An integer field takes exactly an ECMA-404 integer at its value; astring fits its room; a boolean takes ``true`` or ``false``;``null`` gives no value+ * - ``json-string-model``+ - ``parse_string()``+ - Lengths 0 to 6, every buffer up to 7 bytes or none, a+ ``JSON_MAX_STRING_BYTES`` of 3+ - The result, end and bytes of the Lean model ``Shirudo.JsonString``+ * - ``json-escape-model``+ - ``parse_string()``+ - Every pair of ``\u`` escapes in either case, every buffer up to 8+ bytes or none+ - The result, end and bytes of the Lean model ``Shirudo.JsonString``,+ surrogate pairs, ``\u0000`` and lone surrogates included* - ``json-walk``- ``json_walk()``- Every document of up to 2 bytes, depth 2@@ -314,6 +338,11 @@ or shorter, and "lengths 0 to 6" every input of each of those lengths.- The writer and ``parse_string()``- Strings of 0 to 4 bytes- Every string the strict writer takes reads back whole+ * - ``json-emit-string-model``+ - ``put_string_n()``, strict+ - Lengths 0 to 4+ - Refuses exactly where the Lean model ``Shirudo.JsonString`` does,+ and otherwise writes the same bytes* - ``json-emit-buffer``- ``put()``, ``grow()``- Texts of 0 to 4 bytes, every room and limit, allocations allowed@@ -512,6 +541,58 @@ the model follows the C.- None; numeric identifiers compare by value only without a leadingzero, which ``semverParse_wellFormed`` shows the parser ensures- CBMC, ``bpm-semver-model``, up to 9 bytes+ * - ``Shirudo.PinName``, ``upatch_bpffs_name()`` and+ ``upatch_name_from_bpffs()`` of :src:`util/paths.h`+ - ``decode_encode``: a name without ``~`` decodes back from its+ encoding; ``dot_not_mem_encode``: an encoding holds no dot;+ ``encode_injective``: no two names without ``~`` share a pin;+ ``encode_decode``, ``tilde_not_mem_decode``: a pin name without a+ dot that decodes is the encoding of a name without ``~``;+ ``bpffsName_ok``, ``nameFromBpffs_ok``, ``pin_round_trip``: the+ same through the buffers, ``-ENAMETOOLONG`` exactly where the C+ refuses+ - A C string is shorter than 2^63 bytes+ - CBMC, ``paths-bpffs-name-model``, up to 8 bytes+ * - ``Shirudo.ArchivePath``, ``bpm_archive_rel_ok()``,+ ``package_member_name_ok()`` and the member checks of+ ``bpm_pkg_extract()`` of :src:`util/bpm_package.c`+ - ``relOk_iff``, ``relOk_plain``: the check takes exactly the relative+ paths of plain components, with or without a final ``/``;+ ``relOk_contained``: every name it takes, resolved below any+ directory, leads strictly below it, as does each directory on the+ way; ``memberNameOk_iff``: a member matches only as one plain+ component, ``/`` and the member; ``extract_contained``: every+ member extracted is a regular file or a directory strictly below+ ``dest``, or ``dest`` itself+ - Resolution as the kernel walks a path, ``.`` staying, ``..`` going+ up and an empty component refused; the extraction's limits on+ count, size and path length are left out+ - CBMC, ``bpm-archive-path-model``, names of lengths 0 to 10; review+ for ``bpm_pkg_extract()``+ * - ``Shirudo.Hex``, :src:`util/hex.c`+ - ``decode_encode``, ``length_encode``, ``encode_lower``: an encoding+ is lowercase hex twice its length that decodes back;+ ``decode_spec``: ``hex_decode()`` takes exactly ``2 * n`` hex+ digits of either case, and its bytes encode back to them in+ lowercase; ``decodeMax_spec``: ``hex_decode_max()`` takes exactly+ the even runs of at most ``2 * cap``; ``encode_injective``+ - A string is shorter than ``SIZE_MAX``+ - CBMC, ``hex-model``, up to 8 bytes and 17 digits+ * - ``Shirudo.JsonString``, the strict ``put_string_n()`` that+ ``json_str()`` calls and ``parse_string()`` of :src:`util/json.c`+ - ``read_write``: the reader returns exactly every string the writer+ takes and stops at its closing quote; ``write_isSome``: the writer+ takes exactly well-formed UTF-8 without NUL; ``write_string``: it+ writes one ECMA-404 string in well-formed UTF-8, with no control+ byte and no ``"`` or ``\`` outside an escape; ``readString_wf``:+ whatever the reader returns, from any input, is well-formed UTF-8+ without NUL+ - The emitter has room; for ``read_write``, the string fits+ ``JSON_MAX_STRING_BYTES`` and the buffer; well-formed UTF-8 is+ Table 3-7, which ``string-utf8`` proves ``utf8_width()`` computes+ - CBMC, ``json-emit-string-model`` up to 4 bytes,+ ``json-string-model`` lengths 0 to 6, ``json-escape-model`` every+ pair of ``\u`` escapesNot covered yet---------------diff --git a/Documentation/reference/formats/bpm-formats.rst b/Documentation/reference/formats/bpm-formats.rstindex 29015228..2b5969bc 100644--- a/Documentation/reference/formats/bpm-formats.rst+++ b/Documentation/reference/formats/bpm-formats.rst@@ -22,7 +22,8 @@ member names, the registry's challenges, tokens, headers anddescriptors, the package names and versions, the tree publication'sselectors and operations, and the checks that keep a publication fromtaking a node back. Lean 4 proves the version order total for versions-of every length.+of every length, and that every member name the archive check takes,+of any length, extracts strictly below the package's directory.What is signed--------------diff --git a/Documentation/security/threat-model.rst b/Documentation/security/threat-model.rstindex 0f04ed62..51951cf3 100644--- a/Documentation/security/threat-model.rst+++ b/Documentation/security/threat-model.rst@@ -1039,8 +1039,9 @@ revocation does not reach tree publications (U13).:Proofs: ``bpm-tar-header``, ``bpm-tar-octal``, ``bpm-archive-path``,``bpm-oci-challenge``, ``bpm-oci-token``, ``bpm-oci-header``,``bpm-oci-descriptor``, ``bpm-semver-model``, ``Shirudo.SemVer``,- ``bpm-tree-follows``, ``bpm-tree-reader``, ``json-string``,- ``json-limits``+ ``Shirudo.ArchivePath``, ``bpm-archive-path-model``,+ ``Shirudo.JsonString``, ``bpm-tree-follows``, ``bpm-tree-reader``,+ ``json-string``, ``json-limits``:Residual: R8, R9, U3, U4, U13, U15T8 Quantum-capable adversaries against the trust anchordiff --git a/testing/proofs/cbmc/bpm-archive-path-model.c b/testing/proofs/cbmc/bpm-archive-path-model.cnew file mode 100644index 00000000..256f7806--- /dev/null+++ b/testing/proofs/cbmc/bpm-archive-path-model.c@@ -0,0 +1,92 @@+// SPDX-License-Identifier: BSD-2-Clause+/*+ * Copyright (c) 2026 Authors of shirudo+ *+ * bpm_archive_rel_ok() and package_member_name_ok() of util/bpm_package.c+ * against the model testing/proofs/lean4/Shirudo/ArchivePath.lean proves+ * keeps every name inside the directory it is resolved below, for names+ * of every length: on every name of LEN bytes and member of up to+ * MEMBER_MAX they decide as relOk and memberNameOk do.+ */++#include <stdbool.h>+#include <zlib.h>+#include <openssl/bio.h>+#include <openssl/evp.h>+#include <openssl/pem.h>+#include <openssl/x509.h>++#include "proof.h"+#include "../../../util/string.c"+#include "../../../util/bpm_package.c"++#define MEMBER_MAX 3++/* bad: empty, "." or "..". */+static bool model_bad(const char *c, size_t n)+{+ return !n || (n == 1 && c[0] == '.') ||+ (n == 2 && c[0] == '.' && c[1] == '.');+}++/* relLoop from p: takeWhile to the next '/', then dropWhile. */+static bool model_rel_loop(const char *s, size_t len, size_t p)+{+ size_t q;++ while (p < len) {+ for (q = p; q < len && s[q] != '/'; q++)+ ;+ if (model_bad(s + p, q - p))+ return false;+ if (q == len)+ return true;+ p = q + 1;+ }+ return true;+}++/* relOk. */+static bool model_rel_ok(const char *s, size_t len)+{+ return len && s[0] != '/' && model_rel_loop(s, len, 0);+}++/* memberNameOk. */+static bool model_member_name_ok(const char *name, size_t len,+ const char *member, size_t member_len)+{+ size_t t;++ for (t = 0; t < len && name[t] != '/'; t++)+ ;+ return model_rel_ok(name, len) && t < len && t &&+ !(len >= 2 && name[0] == '.' && name[1] == '/') &&+ model_rel_ok(member, member_len) &&+ len - t - 1 == member_len &&+ !memcmp(name + t + 1, member, member_len);+}++static char *string(size_t len, size_t room)+{+ char *s = any_bytes(room + 1);++ __CPROVER_assume(!s[len] && strnlen(s, len) == len);+ return s;+}++void harness(void)+{+ char *name, *member;+ size_t member_len;++ name = string(LEN, LEN);+ __CPROVER_assert(bpm_archive_rel_ok(name) == model_rel_ok(name, LEN),+ "relOk");++ __CPROVER_assume(member_len <= MEMBER_MAX);+ member = string(member_len, MEMBER_MAX);+ __CPROVER_assert(package_member_name_ok(name, member) ==+ model_member_name_ok(name, LEN, member, member_len),+ "memberNameOk");+}diff --git a/testing/proofs/cbmc/hex-model.c b/testing/proofs/cbmc/hex-model.cnew file mode 100644index 00000000..0fac53f2--- /dev/null+++ b/testing/proofs/cbmc/hex-model.c@@ -0,0 +1,143 @@+// SPDX-License-Identifier: BSD-2-Clause+/*+ * Copyright (c) 2026 Authors of shirudo+ *+ * util/hex.c against the model testing/proofs/lean4/Shirudo/Hex.lean+ * proves for every length: on every input of up to LEN_MAX bytes, and for+ * counts and capacities small and past SIZE_MAX / 2, hex_encode(),+ * hex_decode() and hex_decode_max() compute encode, decode and decodeMax.+ */++#include <errno.h>+#include <stdbool.h>++#include "proof.h"+#include "../../../util/hex.c"++#define LEN_MAX 8++static const char model_table[] = "0123456789abcdef";++static size_t model_size_mul(size_t a, size_t b)+{+ size_t r;++ return check_mul_overflow(a, b, &r) ? SIZE_MAX : r;+}++static size_t model_size_add(size_t a, size_t b)+{+ size_t r;++ return check_add_overflow(a, b, &r) ? SIZE_MAX : r;+}++/* nibble, with -1 for none. */+static int model_nibble(__u8 c)+{+ if (c >= 0x30 && c <= 0x39)+ return c - 0x30;+ if (c >= 0x61 && c <= 0x66)+ return c - 0x61 + 10;+ if (c >= 0x41 && c <= 0x46)+ return c - 0x41 + 10;+ return -1;+}++/* decodePairs: none for a single byte left or a pair not of digits. */+static bool model_pairs(const char *s, size_t len, __u8 *out)+{+ size_t i;++ for (i = 0; i < len; i += 2) {+ int hi, lo;++ if (i + 1 == len)+ return false;+ hi = model_nibble(s[i]);+ lo = model_nibble(s[i + 1]);+ if (hi < 0 || lo < 0)+ return false;+ out[i / 2] = (__u8)(hi * 16 + lo);+ }+ return true;+}++/* decode: the length check with size_mul(), then decodePairs. */+static bool model_decode(const char *s, size_t len, size_t n, __u8 *out)+{+ return len == model_size_mul(n, 2) && model_pairs(s, len, out);+}++static char *any_string(size_t len)+{+ char *s = any_bytes(len + 1);++ __CPROVER_assume(!s[len] && strnlen(s, len) == len);+ return s;+}++static void encode_is_model(void)+{+ char out[2 * LEN_MAX + 1];+ size_t n, i;+ __u8 *in;++ __CPROVER_assume(n <= LEN_MAX);+ in = any_bytes(n);+ hex_encode(in, n, out);+ for (i = 0; i < n; i++)+ __CPROVER_assert(out[2 * i] == model_table[in[i] >> 4] &&+ out[2 * i + 1] == model_table[in[i] & 0xf],+ "encodeByte of each byte");+ __CPROVER_assert(!out[2 * n], "and the NUL");+}++static void decode_is_model(bool huge)+{+ __u8 out[LEN_MAX], want[LEN_MAX];+ size_t len, n, twice;+ bool model;+ char *s;+ int ret;++ __CPROVER_assume(len <= 2 * LEN_MAX + 1);+ __CPROVER_assume(huge ? check_mul_overflow(n, (size_t)2, &twice) :+ n <= LEN_MAX);+ s = any_string(len);+ ret = hex_decode(s, out, n);+ model = model_decode(s, len, n, want);+ __CPROVER_assert(ret == (model ? 0 : -EINVAL), "decode's result");+ if (!ret)+ __CPROVER_assert(!memcmp(out, want, n), "and its bytes");+}++static void decode_max_is_model(bool huge)+{+ __u8 out[LEN_MAX + 1], want[LEN_MAX + 1];+ size_t len, cap, n, k, twice;+ bool model;+ char *s;+ int ret;++ __CPROVER_assume(len <= 2 * LEN_MAX + 1);+ __CPROVER_assume(huge ? check_mul_overflow(cap, (size_t)2, &twice) :+ cap <= LEN_MAX);+ s = any_string(len);+ ret = hex_decode_max(s, out, cap, &n);+ k = min(len, model_size_add(model_size_mul(cap, 2), 1));+ model = !(k % 2) && k / 2 <= cap && model_decode(s, len, k / 2, want);+ __CPROVER_assert(ret == (model ? 0 : -EINVAL), "decodeMax's result");+ if (!ret)+ __CPROVER_assert(n == k / 2 && !memcmp(out, want, n),+ "and its bytes");+}++void harness(void)+{+ encode_is_model();+ decode_is_model(false);+ decode_is_model(true);+ decode_max_is_model(false);+ decode_max_is_model(true);+}diff --git a/testing/proofs/cbmc/json-emit-string-model.c b/testing/proofs/cbmc/json-emit-string-model.cnew file mode 100644index 00000000..14acdefe--- /dev/null+++ b/testing/proofs/cbmc/json-emit-string-model.c@@ -0,0 +1,38 @@+// SPDX-License-Identifier: BSD-2-Clause+/*+ * Copyright (c) 2026 Authors of shirudo+ *+ * The strict string writer of util/json.c against the model+ * testing/proofs/lean4/Shirudo/JsonString.lean proves the reader inverts+ * for every length: on every string of LEN bytes put_string_n() refuses+ * exactly where write does, and otherwise writes the same bytes.+ */++#include "proof.h"+#include "../../../util/malloc.c"+#include "../../../util/string.c"+#include "../../../util/hex.c"+#include "../../../util/json.c"+#include "json-model.h"++#define OUT_MAX (6 * LEN + 3)++void harness(void)+{+ struct json_emit e = {};+ __u8 want[OUT_MAX];+ size_t want_len;+ const __u8 *s;+ int model;++ s = any_bytes(LEN);+ e.buf = any_bytes(OUT_MAX);+ e.cap = OUT_MAX;+ put_string_n(&e, (const char *)s, LEN, false);+ model = model_write(s, LEN, want, &want_len);+ __CPROVER_assert(e.err == model, "write's result");+ if (model)+ return;+ __CPROVER_assert(e.len == want_len && !memcmp(e.buf, want, want_len),+ "and its bytes");+}diff --git a/testing/proofs/cbmc/json-escape-model.c b/testing/proofs/cbmc/json-escape-model.cnew file mode 100644index 00000000..53ab61a3--- /dev/null+++ b/testing/proofs/cbmc/json-escape-model.c@@ -0,0 +1,66 @@+// SPDX-License-Identifier: BSD-2-Clause+/*+ * Copyright (c) 2026 Authors of shirudo+ *+ * The \u escapes of util/json.c against the reader of+ * testing/proofs/lean4/Shirudo/JsonString.lean, for every pair of code+ * units spelled in either case and every buffer of up to 8 bytes or none:+ * parse_string() returns what readString returns, ends where it does and+ * decodes the same bytes, a surrogate pair, \u0000 and a lone surrogate+ * included.+ */++#include "proof.h"+#include "../../../util/malloc.c"+#include "../../../util/string.c"+#include "../../../util/hex.c"+#include "../../../util/json.c"+#include "json-model.h"++static void spell(char *out, __u16 cu)+{+ int i;++ out[0] = '\\';+ out[1] = 'u';+ for (i = 0; i < 4; i++) {+ __u8 d = cu >> (12 - 4 * i) & 15;+ bool upper;++ out[2 + i] = d < 10 ? '0' + d : (upper ? 'A' : 'a') + d - 10;+ }+}++void harness(void)+{+ size_t cap, k = 0, end = 0;+ struct pctx c = {};+ __u8 want[8];+ struct room r;+ char text[14];+ char buf[8];+ __u16 hi, lo;+ bool discard;+ int ret, model;++ text[0] = '"';+ spell(text + 1, hi);+ spell(text + 7, lo);+ text[13] = '"';+ c.p = text;+ c.end = text + sizeof(text);+ __CPROVER_assume(cap <= sizeof(buf));+ r.dst = !discard;+ r.cap = cap;+ r.max = JSON_MAX_STRING_BYTES;+ ret = parse_string(&c, discard ? NULL : buf, cap);+ model = model_read((const __u8 *)text, sizeof(text), &r, want, &k,+ &end);+ __CPROVER_assert(ret == model, "readString's result");+ if (ret)+ return;+ __CPROVER_assert(c.p == text + end, "ending where it does");+ if (!discard)+ __CPROVER_assert(!memcmp(buf, want, k) && !buf[k],+ "with the same bytes");+}diff --git a/testing/proofs/cbmc/json-model.h b/testing/proofs/cbmc/json-model.hnew file mode 100644index 00000000..67612923--- /dev/null+++ b/testing/proofs/cbmc/json-model.h@@ -0,0 +1,270 @@+/* SPDX-License-Identifier: BSD-2-Clause */+/*+ * Copyright (c) 2026 Authors of shirudo+ *+ * The models of testing/proofs/lean4/Shirudo/JsonString.lean in C, a+ * branch of the model a turn, for the harnesses that check util/json.c+ * against them: the strict writer, write, and the reader, readString.+ */++#ifndef SHIRUDO_PROOF_JSON_MODEL_H+#define SHIRUDO_PROOF_JSON_MODEL_H++static const char model_table[] = "0123456789abcdef";++static bool in(__u32 c, __u32 lo, __u32 hi)+{+ return c >= lo && c <= hi;+}++/* rowWidth, Row1 to Row4 of Table 3-7, on the n bytes at s. */+static size_t model_width(const __u8 *s, size_t n)+{+ if (n >= 1 && s[0] <= 0x7f)+ return 1;+ if (n >= 2 && in(s[0], 0xc2, 0xdf) && in(s[1], 0x80, 0xbf))+ return 2;+ if (n >= 3 && in(s[2], 0x80, 0xbf) &&+ ((s[0] == 0xe0 && in(s[1], 0xa0, 0xbf)) ||+ (in(s[0], 0xe1, 0xec) && in(s[1], 0x80, 0xbf)) ||+ (s[0] == 0xed && in(s[1], 0x80, 0x9f)) ||+ (in(s[0], 0xee, 0xef) && in(s[1], 0x80, 0xbf))))+ return 3;+ if (n >= 4 && in(s[2], 0x80, 0xbf) && in(s[3], 0x80, 0xbf) &&+ ((s[0] == 0xf0 && in(s[1], 0x90, 0xbf)) ||+ (in(s[0], 0xf1, 0xf3) && in(s[1], 0x80, 0xbf)) ||+ (s[0] == 0xf4 && in(s[1], 0x80, 0x8f))))+ return 4;+ return 0;+}++/* writeBody between write's quotes, one branch of the model a byte. */+static int model_write(const __u8 *s, size_t len, __u8 *out, size_t *n)+{+ size_t i = 0, k = 0, w;++ out[k++] = '"';+ while (i < len) {+ __u8 c = s[i];++ if (c == '"' || c == '\\') {+ out[k++] = '\\';+ out[k++] = c;+ i++;+ } else if (c == 0x0a || c == 0x0d || c == 0x09) {+ out[k++] = '\\';+ out[k++] = c == 0x0a ? 'n' : c == 0x0d ? 'r' : 't';+ i++;+ } else if (c && c < 0x20) {+ out[k++] = '\\';+ out[k++] = 'u';+ out[k++] = model_table[c / 4096 % 16];+ out[k++] = model_table[c / 256 % 16];+ out[k++] = model_table[c / 16 % 16];+ out[k++] = model_table[c % 16];+ i++;+ } else if (c && c < 0x80) {+ out[k++] = c;+ i++;+ } else {+ w = c ? model_width(s + i, min(len - i, 4U)) : 0;+ if (!w)+ return -EILSEQ;+ while (w--)+ out[k++] = s[i++];+ }+ }+ out[k++] = '"';+ *n = k;+ return 0;+}++/* Room: dst given, its cap, and JSON_MAX_STRING_BYTES. */+struct room {+ bool dst;+ size_t cap;+ size_t max;+};++/* emit. */+static int model_emit(const struct room *r, __u8 *out, size_t *k, __u32 b)+{+ if (*k >= r->max)+ return -E2BIG;+ if (r->dst && *k + 1 >= r->cap)+ return -ENOSPC;+ out[(*k)++] = (__u8)b;+ return 0;+}++/* emitAll. */+static int model_emit_all(const struct room *r, __u8 *out, size_t *k,+ const __u32 *b, size_t n)+{+ size_t i;+ int ret;++ for (i = 0; i < n; i++) {+ ret = model_emit(r, out, k, b[i]);+ if (ret)+ return ret;+ }+ return 0;+}++/* emitCp, with utf8Emit below U+10000 and utf8Four from it. */+static int model_emit_cp(const struct room *r, __u8 *out, size_t *k,+ __u32 cp)+{+ __u32 b[4];++ if (cp < 0x80)+ return model_emit(r, out, k, cp);+ if (cp < 0x800) {+ b[0] = 0xc0 | (cp >> 6);+ b[1] = 0x80 | (cp & 0x3f);+ return model_emit_all(r, out, k, b, 2);+ }+ if (cp < 0x10000) {+ b[0] = 0xe0 | (cp >> 12);+ b[1] = 0x80 | ((cp >> 6) & 0x3f);+ b[2] = 0x80 | (cp & 0x3f);+ return model_emit_all(r, out, k, b, 3);+ }+ b[0] = 0xf0 | (cp >> 18);+ b[1] = 0x80 | ((cp >> 12) & 0x3f);+ b[2] = 0x80 | ((cp >> 6) & 0x3f);+ b[3] = 0x80 | (cp & 0x3f);+ return model_emit_all(r, out, k, b, 4);+}++/* Hex.nibble, -1 for none. */+static int model_nibble(__u8 c)+{+ if (c >= 0x30 && c <= 0x39)+ return c - 0x30;+ if (c >= 0x61 && c <= 0x66)+ return c - 0x61 + 10;+ if (c >= 0x41 && c <= 0x46)+ return c - 0x41 + 10;+ return -1;+}++/* hex4, -1 for none. */+static int model_hex4(const __u8 *d)+{+ int v = 0, n, i;++ for (i = 0; i < 4; i++) {+ n = model_nibble(d[i]);+ if (n < 0)+ return -1;+ v = v * 16 + n;+ }+ return v;+}++/* simpleEscape, -1 for none. */+static int model_simple_escape(__u8 e)+{+ if (e == 0x22 || e == 0x5c || e == 0x2f)+ return e;+ if (e == 0x62)+ return 0x08;+ if (e == 0x66)+ return 0x0c;+ if (e == 0x6e)+ return 0x0a;+ if (e == 0x72)+ return 0x0d;+ if (e == 0x74)+ return 0x09;+ return -1;+}++/* uCodePoint on the bytes from t[*i] to t[n], moving *i past them. */+static int model_code_point(const __u8 *t, size_t n, size_t *i, __u32 *cp)+{+ int hi, lo;++ if (n - *i < 4)+ return -EINVAL;+ hi = model_hex4(t + *i);+ if (hi < 0 || !hi)+ return -EINVAL;+ *i += 4;+ if (in(hi, 0xd800, 0xdbff)) {+ if (n - *i < 6 || t[*i] != '\\' || t[*i + 1] != 'u')+ return -EINVAL;+ lo = model_hex4(t + *i + 2);+ if (lo < 0 || !in(lo, 0xdc00, 0xdfff))+ return -EINVAL;+ *i += 6;+ *cp = 0x10000 + (hi - 0xd800) * 1024 + (lo - 0xdc00);+ return 0;+ }+ if (in(hi, 0xdc00, 0xdfff))+ return -EINVAL;+ *cp = hi;+ return 0;+}++/* readString and readLoop, one branch of the model a turn. */+static int model_read(const __u8 *t, size_t n, const struct room *r,+ __u8 *out, size_t *k, size_t *end)+{+ __u32 b[4], cp;+ size_t i = 0, w, j;+ int ret, v;+ __u8 ch;++ if (i == n || t[i] != '"')+ return -EINVAL;+ i++;+ for (;;) {+ if (i == n)+ return -EINVAL;+ ch = t[i];+ if (ch == '"') {+ i++;+ break;+ }+ if (ch == '\\') {+ if (i + 1 == n)+ return -EINVAL;+ v = model_simple_escape(t[i + 1]);+ i += 2;+ if (v >= 0) {+ ret = model_emit(r, out, k, v);+ if (ret)+ return ret;+ continue;+ }+ if (t[i - 1] != 'u')+ return -EINVAL;+ ret = model_code_point(t, n, &i, &cp);+ if (!ret)+ ret = model_emit_cp(r, out, k, cp);+ if (ret)+ return ret;+ continue;+ }+ if (ch < 0x20)+ return -EINVAL;+ w = model_width(t + i, n - i);+ if (!w)+ return -EINVAL;+ for (j = 0; j < w; j++)+ b[j] = t[i + j];+ ret = model_emit_all(r, out, k, b, w);+ if (ret)+ return ret;+ i += w;+ }+ if (r->dst && !r->cap)+ return -ENOSPC;+ *end = i;+ return 0;+}++#endif /* SHIRUDO_PROOF_JSON_MODEL_H */diff --git a/testing/proofs/cbmc/json-string-model.c b/testing/proofs/cbmc/json-string-model.cnew file mode 100644index 00000000..55c7f282--- /dev/null+++ b/testing/proofs/cbmc/json-string-model.c@@ -0,0 +1,49 @@+// SPDX-License-Identifier: BSD-2-Clause+/*+ * Copyright (c) 2026 Authors of shirudo+ *+ * The string reader of util/json.c against the model+ * testing/proofs/lean4/Shirudo/JsonString.lean proves inverts the writer+ * for every length: on every input of LEN bytes, every buffer of up to+ * LEN + 1 bytes or none, and a JSON_MAX_STRING_BYTES the input can pass,+ * parse_string() returns what readString returns, ends where it does and+ * decodes the same bytes.+ */++#define JSON_MAX_STRING_BYTES 3++#include "proof.h"+#include "../../../util/malloc.c"+#include "../../../util/string.c"+#include "../../../util/hex.c"+#include "../../../util/json.c"+#include "json-model.h"++void harness(void)+{+ size_t cap, k = 0, end = 0;+ char buf[LEN + 1];+ __u8 want[LEN + 1];+ struct pctx c = {};+ struct room r;+ const char *s;+ bool discard;+ int ret, model;++ s = any_bytes(LEN);+ c.p = s;+ c.end = s + LEN;+ __CPROVER_assume(cap <= sizeof(buf));+ r.dst = !discard;+ r.cap = cap;+ r.max = JSON_MAX_STRING_BYTES;+ ret = parse_string(&c, discard ? NULL : buf, cap);+ model = model_read((const __u8 *)s, LEN, &r, want, &k, &end);+ __CPROVER_assert(ret == model, "readString's result");+ if (ret)+ return;+ __CPROVER_assert(c.p == s + end, "ending where it does");+ if (!discard)+ __CPROVER_assert(!memcmp(buf, want, k) && !buf[k],+ "with the same bytes");+}diff --git a/testing/proofs/cbmc/paths-bpffs-name-model.c b/testing/proofs/cbmc/paths-bpffs-name-model.cnew file mode 100644index 00000000..643d48bf--- /dev/null+++ b/testing/proofs/cbmc/paths-bpffs-name-model.c@@ -0,0 +1,120 @@+// SPDX-License-Identifier: BSD-2-Clause+/*+ * Copyright (c) 2026 Authors of shirudo+ *+ * upatch_bpffs_name() and upatch_name_from_bpffs() of util/paths.h against+ * the model testing/proofs/lean4/Shirudo/PinName.lean proves a bijection+ * for names of every length: on every string of up to LEN_MAX bytes and+ * every buffer of up to SZ_MAX bytes they return what bpffsName and+ * nameFromBpffs return, and write the same string.+ */++#include <errno.h>+#include <stdbool.h>++#include "proof.h"+#include "../../../util/paths.h"++#define LEN_MAX 8+#define SZ_MAX (2 * LEN_MAX + 2)++static char *any_string(size_t len)+{+ char *s = any_bytes(len + 1);++ __CPROVER_assume(!s[len] && strnlen(s, len) == len);+ return s;+}++/* bpffsName: the length check, then encode, each dot as ~d. */+static int model_bpffs_name(const char *name, size_t len, size_t out_sz,+ char *out, size_t *n)+{+ size_t i, j = 0;++ if (!out_sz)+ return -EINVAL;+ if (len * 2 + 1 > out_sz)+ return -ENAMETOOLONG;+ for (i = 0; i < len; i++) {+ if (name[i] == '.') {+ out[j++] = '~';+ out[j++] = 'd';+ } else {+ out[j++] = name[i];+ }+ }+ *n = j;+ return 0;+}++/* nameFromBpffs: fromLoop from j = 0, one pattern of the model a turn. */+static int model_name_from_bpffs(const char *p, size_t len, size_t out_sz,+ char *out, size_t *n)+{+ size_t i = 0, j = 0;++ if (!out_sz)+ return -EINVAL;+ while (i < len) {+ char c = p[i];++ if (c == '~') {+ if (i + 1 == len || p[i + 1] != 'd')+ return -EINVAL;+ if (j + 1 >= out_sz)+ return -ENAMETOOLONG;+ out[j++] = '.';+ i += 2;+ continue;+ }+ if (j + 1 >= out_sz)+ return -ENAMETOOLONG;+ out[j++] = c;+ i++;+ }+ *n = j;+ return 0;+}++static void encode_is_model(void)+{+ char out[SZ_MAX], want[SZ_MAX];+ size_t len, sz, n;+ int ret, model;+ char *name;++ __CPROVER_assume(len <= LEN_MAX && sz <= SZ_MAX);+ name = any_string(len);+ ret = upatch_bpffs_name(out, sz, name);+ model = model_bpffs_name(name, len, sz, want, &n);+ __CPROVER_assert(ret == model, "bpffsName's result");+ if (ret)+ return;+ __CPROVER_assert(n < sz && !out[n] && !memcmp(out, want, n),+ "and its encoding");+}++static void decode_is_model(void)+{+ char out[SZ_MAX], want[SZ_MAX];+ size_t len, sz, n;+ int ret, model;+ char *pin;++ __CPROVER_assume(len <= LEN_MAX && sz <= SZ_MAX);+ pin = any_string(len);+ ret = upatch_name_from_bpffs(out, sz, pin);+ model = model_name_from_bpffs(pin, len, sz, want, &n);+ __CPROVER_assert(ret == model, "nameFromBpffs's result");+ if (ret)+ return;+ __CPROVER_assert(n < sz && !out[n] && !memcmp(out, want, n),+ "and its decoding");+}++void harness(void)+{+ encode_is_model();+ decode_is_model();+}diff --git a/testing/proofs/cbmc/proofs.list b/testing/proofs/cbmc/proofs.listindex 8baef00b..d21484be 100644--- a/testing/proofs/cbmc/proofs.list+++ b/testing/proofs/cbmc/proofs.list@@ -73,3 +73,9 @@ bpm-source-config --unwind 14bpm-oci-strings --unwind 9bpm-semver-model --slice-formula --unwind 1 --unwindset strlen.0:10,strcmp.0:10,strcspn.0:2,strcspn.1:4,digits.0:10,parse_base.0:10,parse_base.1:10,semver_parse.0:4,semver_identifiers.0:4,semver_identifiers.1:3,prerelease_compare.0:3,memchr.0:4,memcmp.0:4,bpm_semver_compare.0:4,strnlen.0:10,any_string.0:10,break_at.0:10,split_on.0:10,next_ident.0:4,numeral.0:8,numeric.0:8,ident_ok.0:4,identifiers.0:3,lex_bytes.0:10,memcmp_model.0:4,lex_idents.0:3,semver_model_compare.0:4 LEN=9chain-events --unwind 258 LEN=0-8,255-257+hex-model --unwind 20+paths-bpffs-name-model --unwind 20+json-emit-string-model --unwind 5 --unwindset put_string_n.0:5,put_string_n.1:5,put_raw.0:7,model_write.0:5,model_write.1:5,memcmp.0:27 LEN=0-4+json-string-model --unwind 5 --unwindset parse_string.0:7,parse_string.1:7,model_read.0:7,memcmp.0:7 LEN=0-6+json-escape-model --unwind 5 --unwindset parse_string.0:4,parse_string.1:4,model_read.0:4,memcmp.0:9+bpm-archive-path-model --unwind 12 LEN=0-10diff --git a/testing/proofs/lean4/Shirudo.lean b/testing/proofs/lean4/Shirudo.leanindex ccc4c332..a80731bb 100644--- a/testing/proofs/lean4/Shirudo.lean+++ b/testing/proofs/lean4/Shirudo.lean@@ -6,3 +6,7 @@ import Shirudo.Chainimport Shirudo.SemVerimport Shirudo.Eventsimport Shirudo.Measured+import Shirudo.PinName+import Shirudo.ArchivePath+import Shirudo.Hex+import Shirudo.JsonStringdiff --git a/testing/proofs/lean4/Shirudo/ArchivePath.lean b/testing/proofs/lean4/Shirudo/ArchivePath.leannew file mode 100644index 00000000..ad6bb73e--- /dev/null+++ b/testing/proofs/lean4/Shirudo/ArchivePath.lean@@ -0,0 +1,639 @@+-- SPDX-License-Identifier: BSD-2-Clause+-- Copyright (c) 2026 Authors of shirudo++/-!+The member paths of util/bpm_package.c. `bpm_archive_rel_ok()` takes a+name from a .bee archive when it is not empty, does not start with `/`,+and none of the components `strchr()` finds between its slashes is empty,+`.` or `..`; a final `/`, as tar ends a directory member with, leaves no+component after it. `package_member_name_ok()` matches a member only as+the whole path below the archive's top directory. `bpm_pkg_extract()`+takes the top directory from the first member, refuses a member whose+name fails the check, lies outside that directory, or, below it, is empty+for anything but a directory or fails the check, and refuses every+member but a regular file (`0`) and a directory (`5`) before it writes.+It then creates `<dest>/<rel>`.++Path resolution is modelled as the kernel walks a path: a path splits+into the components between its slashes, one that starts with `/` starts+at the filesystem root, a final `/` names the directory before it, `.`+stays, `..` goes up, except at the filesystem root, and any other+component goes down. An empty component is refused, where the kernel and+the `strtok_r()` walk of util/seal.c skip it; no name the check takes+holds one. A directory is the list of its components from the+filesystem root. util/seal.c walks every component with `O_NOFOLLOW`, so+no symbolic link is followed, and the archive can create none.++For names of every length: every name the check takes, resolved below any+directory, leads strictly below it, and so does every directory the walk+passes through; the check takes exactly the relative paths of plain+components, with or without a final `/`; a member name matches exactly+when it is one plain component, a `/` and the member; and every member+`bpm_pkg_extract()` writes is a regular file or a directory strictly+below `dest`, or `dest` itself for the top directory. A string is its+bytes before the NUL, each byte its value.+testing/proofs/cbmc/bpm-archive-path-model.c checks the two checks of+the C against the model on every name of up to 10 bytes and member of up+to 3; the model of `bpm_pkg_extract()` follows the C by review.+-/++namespace Shirudo.ArchivePath++/-- `/`. -/+def slash : Nat := 0x2f++/-- `.`. -/+def dot : Nat := 0x2e++/-- The type flag of a regular file, `0`. -/+def regType : Nat := 0x30++/-- The type flag of a directory, `5`. -/+def dirType : Nat := 0x35++/-- Not a `/`, what `strchr(p, '/')` skips. -/+def notSlash (c : Nat) : Bool := c != slash++/-- A component `bpm_archive_rel_ok()` refuses: `q == p`, or `.` or `..`. -/+def bad (comp : List Nat) : Bool := comp == [] || comp == [dot] || comp == [dot, dot]++theorem length_dropWhile_lt (p : List Nat) (r : List Nat) (c : Nat)+ (h : p.dropWhile notSlash = c :: r) : r.length < p.length := by+ have e := List.takeWhile_append_dropWhile (p := notSlash) (l := p)+ rw [h] at e+ have := congrArg List.length e+ simp only [List.length_append, List.length_cons] at this+ omega++/-- The loop of `bpm_archive_rel_ok()` from `p`: the component up to the+next `/` or the end is refused when bad, and the loop goes on past the+`/`, or stops at the end. -/+def relLoop (p : List Nat) : Bool :=+ if p = [] then true+ else if bad (p.takeWhile notSlash) then false+ else+ match _hq : p.dropWhile notSlash with+ | [] => true+ | _ :: r => relLoop r+termination_by p.length+decreasing_by exact length_dropWhile_lt _ _ _ _hq++/-- `bpm_archive_rel_ok(name)`. -/+def relOk (name : List Nat) : Bool :=+ match name with+ | [] => false+ | c :: _ => if c = slash then false else relLoop name++/-- A component a relative path may hold: not empty, no `/`, not `.` and+not `..`. -/+def Plain (c : List Nat) : Prop :=+ c ≠ [] ∧ slash ∉ c ∧ c ≠ [dot] ∧ c ≠ [dot, dot]++/-- Components joined by `/`. -/+def join : List (List Nat) → List Nat+ | [] => []+ | [c] => c+ | c :: cs => c ++ slash :: join cs++/-! ### Resolution -/++/-- A directory: the names of its components from the filesystem root. -/+abbrev Dir := List (List Nat)++/-- The parts of a string between its slashes, empty ones included. -/+def splitSlash : List Nat → List (List Nat)+ | [] => [[]]+ | c :: s =>+ if c = slash then [] :: splitSlash s+ else+ match splitSlash s with+ | p :: ps => (c :: p) :: ps+ | [] => [[c]]++/-- The components of a path: its parts, less the empty one a final `/`+leaves, since a final `/` names the directory before it. -/+def parts (s : List Nat) : List (List Nat) :=+ let ps := splitSlash s+ if 2 ≤ ps.length ∧ ps.getLast? = some [] then ps.dropLast else ps++/-- One component of a walk from directory `d`: an empty one is refused,+`.` stays, `..` goes up, except at the filesystem root, and a name goes+down. -/+def step (d : Dir) (c : List Nat) : Option Dir :=+ if c = [] then none+ else if c = [dot] then some d+ else if c = [dot, dot] then some d.dropLast+ else some (d ++ [c])++/-- The directories a walk from `d` passes through, the last one where it+leads. -/+def walk (d : Dir) : List (List Nat) → Option (List Dir)+ | [] => some []+ | c :: cs =>+ match step d c with+ | none => none+ | some d' => (walk d' cs).map (d' :: ·)++/-- Where path `s` leads from directory `root`, with each directory it+passes through: from the filesystem root when it starts with `/`. -/+def resolve (root : Dir) (s : List Nat) : Option (List Dir) :=+ match parts s with+ | [] :: c :: cs => walk [] (c :: cs)+ | cs => walk root cs++/-- Strictly below `root`. -/+def Below (root d : Dir) : Prop := ∃ e, e ≠ [] ∧ d = root ++ e++/-! ### The loop of the check -/++theorem notSlash_iff (c : Nat) : notSlash c = true ↔ c ≠ slash := by+ simp [notSlash]++theorem all_notSlash (c : List Nat) (h : slash ∉ c) :+ ∀ a ∈ c, notSlash a = true := by+ intro a ha+ rw [notSlash_iff]+ intro e; subst e; exact h ha++theorem takeWhile_comp (c rest : List Nat) (h : slash ∉ c) :+ (c ++ slash :: rest).takeWhile notSlash = c := by+ rw [List.takeWhile_append_of_pos (all_notSlash c h)]+ simp [notSlash]++theorem dropWhile_comp (c rest : List Nat) (h : slash ∉ c) :+ (c ++ slash :: rest).dropWhile notSlash = slash :: rest := by+ rw [List.dropWhile_append_of_pos (all_notSlash c h)]+ simp [notSlash]++theorem takeWhile_last (c : List Nat) (h : slash ∉ c) :+ c.takeWhile notSlash = c := by+ have := List.takeWhile_append_of_pos (l₂ := []) (all_notSlash c h)+ simpa using this++theorem dropWhile_last (c : List Nat) (h : slash ∉ c) :+ c.dropWhile notSlash = [] := by+ have := List.dropWhile_append_of_pos (l₂ := []) (all_notSlash c h)+ simpa using this++theorem bad_iff (c : List Nat) : bad c = true ↔ c = [] ∨ c = [dot] ∨ c = [dot, dot] := by+ simp [bad, or_assoc]++theorem plain_not_bad (c : List Nat) (h : Plain c) : bad c = false := by+ have ⟨h1, _, h3, h4⟩ := h+ cases hb : bad c+ · rfl+ · rw [bad_iff] at hb+ rcases hb with e | e | e <;> contradiction++theorem relLoop_comp (c rest : List Nat) (hs : slash ∉ c) :+ relLoop (c ++ slash :: rest) = if bad c then false else relLoop rest := by+ rw [relLoop.eq_def]+ rw [ite_eq_right (by simp), takeWhile_comp c rest hs]+ split+ · rfl+ · split+ · next hq => rw [dropWhile_comp c rest hs] at hq; simp at hq+ · next r hq =>+ rw [dropWhile_comp c rest hs] at hq+ simp only [List.cons.injEq] at hq+ rw [hq.2]++theorem relLoop_cons_comp (c rest : List Nat) (h : Plain c) :+ relLoop (c ++ slash :: rest) = relLoop rest := by+ rw [relLoop_comp c rest h.2.1, plain_not_bad c h]+ rfl++theorem relLoop_last (c : List Nat) (h : Plain c) : relLoop c = true := by+ have ⟨hne, hs, _, _⟩ := h+ obtain ⟨x, xs, hx⟩ : ∃ x xs, c = x :: xs := by+ cases c with+ | nil => contradiction+ | cons x xs => exact ⟨x, xs, rfl⟩+ rw [relLoop.eq_def]+ rw [ite_eq_right (by rw [hx]; simp), takeWhile_last c hs, plain_not_bad c h]+ simp only [Bool.false_eq_true, ite_false]+ split+ · rfl+ · next r hq => rw [dropWhile_last c hs] at hq; simp at hq++theorem relLoop_join (cs : List (List Nat)) (hne : cs ≠ [])+ (h : ∀ c ∈ cs, Plain c) :+ relLoop (join cs) = true ∧ relLoop (join cs ++ [slash]) = true := by+ induction cs with+ | nil => contradiction+ | cons c cs ih =>+ have hc := h c List.mem_cons_self+ cases cs with+ | nil =>+ refine ⟨relLoop_last c hc, ?_⟩+ simp only [join]+ rw [relLoop_cons_comp c [] hc]+ simp [relLoop]+ | cons d ds =>+ have ih' := ih (by simp) (fun x m => h x (List.mem_cons_of_mem c m))+ simp only [join]+ refine ⟨?_, ?_⟩+ · rw [relLoop_cons_comp c _ hc]+ exact ih'.1+ · rw [List.append_assoc, List.cons_append, relLoop_cons_comp c _ hc]+ exact ih'.2++theorem plain_of_takeWhile (p : List Nat) (hb : bad (p.takeWhile notSlash) = false) :+ Plain (p.takeWhile notSlash) := by+ refine ⟨?_, ?_, ?_, ?_⟩+ · intro e; rw [e] at hb; simp [bad] at hb+ · intro m+ have := List.all_eq_true.1 (List.all_takeWhile (p := notSlash) (l := p)) _ m+ simp [notSlash] at this+ · intro e; rw [e] at hb; simp [bad] at hb+ · intro e; rw [e] at hb; simp [bad] at hb++theorem join_cons (c : List Nat) (cs : List (List Nat)) (hne : cs ≠ []) :+ join (c :: cs) = c ++ slash :: join cs := by+ cases cs with+ | nil => contradiction+ | cons d ds => rfl++/-- What the loop takes is empty, or plain components joined by `/`, with+or without a final `/`. -/+theorem relLoop_sound : ∀ (p : List Nat), relLoop p = true → p = [] ∨+ ∃ cs, cs ≠ [] ∧ (∀ c ∈ cs, Plain c) ∧ (p = join cs ∨ p = join cs ++ [slash])+ | [], _ => Or.inl rfl+ | x :: xs, h => by+ right+ rw [relLoop.eq_def] at h+ rw [ite_eq_right (by simp)] at h+ split at h+ · contradiction+ · next hb =>+ have hb' : bad ((x :: xs).takeWhile notSlash) = false := by+ simpa using hb+ have hp := plain_of_takeWhile (x :: xs) hb'+ have hsplit := List.takeWhile_append_dropWhile (p := notSlash) (l := x :: xs)+ generalize (x :: xs).takeWhile notSlash = c at hp hsplit+ split at h+ · next hq =>+ rw [hq, List.append_nil] at hsplit+ exact ⟨[c], by simp, by simpa using hp, Or.inl (by rw [← hsplit]; rfl)⟩+ · next s r hq =>+ have hs : s = slash := by+ have := List.head_dropWhile_not notSlash (l := x :: xs) (by simp [hq])+ simp only [hq, List.head_cons, notSlash] at this+ simpa using this+ subst hs+ have hlt := length_dropWhile_lt (x :: xs) r slash hq+ rw [hq] at hsplit+ rcases relLoop_sound r h with hr | ⟨cs, hne, hcs, hr⟩+ · subst hr+ exact ⟨[c], by simp, by simpa using hp, Or.inr (by rw [← hsplit]; rfl)⟩+ · refine ⟨c :: cs, by simp, ?_, ?_⟩+ · intro c' hc+ simp only [List.mem_cons] at hc+ rcases hc with hc | hc+ · rw [hc]; exact hp+ · exact hcs c' hc+ · rw [join_cons _ _ hne]+ rcases hr with hr | hr+ · left; rw [← hsplit, hr]+ · right; rw [← hsplit, hr, List.append_assoc, List.cons_append]+termination_by p => p.length+decreasing_by exact hlt++theorem relOk_cons (x : Nat) (xs : List Nat) :+ relOk (x :: xs) = if x = slash then false else relLoop (x :: xs) := rfl++/-- The check takes exactly the relative paths of plain components, with+or without a final `/`. -/+theorem relOk_iff (s : List Nat) :+ relOk s = true ↔ ∃ cs, cs ≠ [] ∧ (∀ c ∈ cs, Plain c) ∧+ (s = join cs ∨ s = join cs ++ [slash]) := by+ constructor+ · intro h+ cases s with+ | nil => simp [relOk] at h+ | cons x xs =>+ simp only [relOk] at h+ split at h+ · contradiction+ · rcases relLoop_sound (x :: xs) h with e | e+ · simp at e+ · exact e+ · intro ⟨cs, hne, hcs, hs⟩+ have hl := relLoop_join cs hne hcs+ obtain ⟨c, cs', rfl⟩ : ∃ c cs', cs = c :: cs' := by+ cases cs with+ | nil => contradiction+ | cons c cs' => exact ⟨c, cs', rfl⟩+ have ⟨hcne, hcs1, _, _⟩ := hcs c List.mem_cons_self+ obtain ⟨x, xs, hx⟩ : ∃ x xs, c = x :: xs := by+ cases c with+ | nil => contradiction+ | cons x xs => exact ⟨x, xs, rfl⟩+ have hxs : x ≠ slash := by+ intro e; subst e; exact hcs1 (by rw [hx]; exact List.mem_cons_self)+ have hhead : ∀ t, join (c :: cs') ++ t = x :: (xs ++ (join (c :: cs') ++ t).drop c.length) := by+ intro t+ cases cs' with+ | nil => simp [join, hx]+ | cons d ds => simp [join, hx]+ rcases hs with hs | hs+ · subst hs+ have := hhead []+ rw [List.append_nil] at this+ rw [this, relOk_cons, ite_eq_right hxs, ← this]+ exact hl.1+ · subst hs+ rw [hhead [slash], relOk_cons, ite_eq_right hxs, ← hhead [slash]]+ exact hl.2++/-! ### Resolution of what the check takes -/++theorem splitSlash_comp (c rest : List Nat) (h : slash ∉ c) :+ splitSlash (c ++ slash :: rest) = c :: splitSlash rest := by+ induction c with+ | nil => simp [splitSlash]+ | cons x c ih =>+ have hx : x ≠ slash := fun e => h (e ▸ List.mem_cons_self)+ have hc : slash ∉ c := fun m => h (List.mem_cons_of_mem x m)+ simp only [List.cons_append, splitSlash, hx, ite_false, ih hc]++theorem splitSlash_last (c : List Nat) (h : slash ∉ c) : splitSlash c = [c] := by+ induction c with+ | nil => rfl+ | cons x c ih =>+ have hx : x ≠ slash := fun e => h (e ▸ List.mem_cons_self)+ have hc : slash ∉ c := fun m => h (List.mem_cons_of_mem x m)+ simp only [splitSlash, hx, ite_false, ih hc]++theorem splitSlash_join (cs : List (List Nat)) (hne : cs ≠ [])+ (h : ∀ c ∈ cs, slash ∉ c) :+ splitSlash (join cs) = cs ∧ splitSlash (join cs ++ [slash]) = cs ++ [[]] := by+ induction cs with+ | nil => contradiction+ | cons c cs ih =>+ have hc := h c List.mem_cons_self+ cases cs with+ | nil =>+ simp only [join]+ exact ⟨splitSlash_last c hc, by rw [splitSlash_comp c [] hc]; rfl⟩+ | cons d ds =>+ have ih' := ih (by simp) (fun x m => h x (List.mem_cons_of_mem c m))+ simp only [join] at ih' ⊢+ refine ⟨by rw [splitSlash_comp c _ hc, ih'.1], ?_⟩+ rw [List.append_assoc, List.cons_append, splitSlash_comp c _ hc, ih'.2]+ rfl++theorem parts_join (cs : List (List Nat)) (hne : cs ≠ [])+ (h : ∀ c ∈ cs, Plain c) :+ parts (join cs) = cs ∧ parts (join cs ++ [slash]) = cs := by+ have hs := splitSlash_join cs hne (fun c m => (h c m).2.1)+ have hlast : cs.getLast? ≠ some [] := by+ intro e+ have := List.mem_of_getLast? e+ exact (h [] this).1 rfl+ unfold parts+ constructor+ · rw [hs.1]+ simp only [hlast, and_false, ite_false]+ · rw [hs.2]+ have hl : 2 ≤ (cs ++ [[]]).length := by+ cases cs with+ | nil => contradiction+ | cons _ _ => simp+ simp only [hl, List.getLast?_append, List.getLast?_singleton, Option.some_or,+ and_self, ite_true, List.dropLast_concat]++theorem walk_plain (cs : List (List Nat)) (h : ∀ c ∈ cs, Plain c) :+ ∀ d : Dir, ∃ ds, walk d cs = some ds ∧ ds.length = cs.length ∧+ ∀ x ∈ ds, Below d x := by+ induction cs with+ | nil => intro d; exact ⟨[], rfl, rfl, by simp⟩+ | cons c cs ih =>+ intro d+ have ⟨h1, _, h3, h4⟩ := h c List.mem_cons_self+ have hstep : step d c = some (d ++ [c]) := by+ simp [step, h1, h3, h4]+ have ⟨ds, hw, hl, hb⟩ := ih (fun x m => h x (List.mem_cons_of_mem c m)) (d ++ [c])+ refine ⟨(d ++ [c]) :: ds, by simp [walk, hstep, hw], by simp [hl], ?_⟩+ intro x hx+ simp only [List.mem_cons] at hx+ rcases hx with hx | hx+ · exact ⟨[c], by simp, hx⟩+ · have ⟨e, he, hxe⟩ := hb x hx+ exact ⟨c :: e, by simp, by rw [hxe]; simp⟩++theorem resolve_relative (root : Dir) (s : List Nat) (cs : List (List Nat))+ (hp : parts s = cs) (hc : ∀ c ∈ cs, c ≠ []) :+ resolve root s = walk root cs := by+ unfold resolve+ rw [hp]+ match cs, hc with+ | [], _ => rfl+ | [] :: _, hc => exact absurd rfl (hc [] List.mem_cons_self)+ | (_ :: _) :: _, _ => rfl++/-- Every name the check takes, resolved below any directory `root`, leads+strictly below it, and so does every directory the walk passes through. -/+theorem relOk_contained (root : Dir) (s : List Nat) (h : relOk s = true) :+ ∃ ds, resolve root s = some ds ∧ ds ≠ [] ∧ ∀ d ∈ ds, Below root d := by+ have ⟨cs, hne, hcs, hs⟩ := (relOk_iff s).1 h+ have hp := parts_join cs hne hcs+ have hps : parts s = cs := by+ rcases hs with hs | hs <;> rw [hs]+ · exact hp.1+ · exact hp.2+ rw [resolve_relative root s cs hps (fun c m => (hcs c m).1)]+ have ⟨ds, hw, hl, hb⟩ := walk_plain cs hcs root+ refine ⟨ds, hw, ?_, hb⟩+ intro e; subst e+ cases cs with+ | nil => contradiction+ | cons _ _ => simp at hl++/-- The check takes every relative path of plain components, with or+without a final `/`. -/+theorem relOk_plain (cs : List (List Nat)) (hne : cs ≠ [])+ (h : ∀ c ∈ cs, Plain c) :+ relOk (join cs) = true ∧ relOk (join cs ++ [slash]) = true :=+ ⟨(relOk_iff _).2 ⟨cs, hne, h, Or.inl rfl⟩,+ (relOk_iff _).2 ⟨cs, hne, h, Or.inr rfl⟩⟩++/-! ### Members -/++/-- `package_member_name_ok(name, member)`: `strchr(name, '/')` found, not+first, `name` not starting `./`, `member` taken by the check and the+same as what follows that `/`. -/+def memberNameOk (name member : List Nat) : Bool :=+ let t := name.takeWhile notSlash+ relOk name && decide (t.length < name.length) && decide (t ≠ []) &&+ decide (name.take 2 ≠ [dot, slash]) && relOk member &&+ decide (name.drop (t.length + 1) = member)++theorem split_at_slash (name : List Nat)+ (h : (name.takeWhile notSlash).length < name.length) :+ name = name.takeWhile notSlash +++ slash :: name.drop ((name.takeWhile notSlash).length + 1) := by+ have hsplit := List.takeWhile_append_dropWhile (p := notSlash) (l := name)+ have hne : name.dropWhile notSlash ≠ [] := by+ intro e+ rw [e, List.append_nil] at hsplit+ rw [hsplit] at h+ omega+ obtain ⟨y, r, hyr⟩ : ∃ y r, name.dropWhile notSlash = y :: r := by+ cases hq : name.dropWhile notSlash with+ | nil => exact absurd hq hne+ | cons y r => exact ⟨y, r, rfl⟩+ have hy : y = slash := by+ have := List.head_dropWhile_not notSlash (l := name) hne+ simp only [hyr, List.head_cons, notSlash] at this+ simpa using this+ subst hy+ rw [hyr] at hsplit+ generalize name.takeWhile notSlash = tw at hsplit ⊢+ subst hsplit+ simp [List.drop_append]++theorem takeWhile_slash_free (name : List Nat) : slash ∉ name.takeWhile notSlash := by+ intro m+ have := List.all_eq_true.1 (List.all_takeWhile (p := notSlash) (l := name)) _ m+ simp [notSlash] at this++/-- A member name matches exactly when it is one plain component, a `/` and+the member, which the check takes: a member is found only in the+archive's top directory. -/+theorem memberNameOk_iff (name member : List Nat) :+ memberNameOk name member = true ↔+ ∃ t, Plain t ∧ relOk member = true ∧ name = t ++ slash :: member := by+ unfold memberNameOk+ simp only [Bool.and_eq_true, decide_eq_true_eq]+ constructor+ · intro ⟨⟨⟨⟨⟨hname, hlt⟩, hne⟩, h2⟩, hmem⟩, hdrop⟩+ have hsp := split_at_slash name hlt+ rw [hdrop] at hsp+ have hsf := takeWhile_slash_free name+ refine ⟨name.takeWhile notSlash, ?_, hmem, hsp⟩+ have hloop : relLoop name = true := by+ cases name with+ | nil => simp [relOk] at hname+ | cons x xs =>+ rw [relOk_cons] at hname+ split at hname+ · contradiction+ · exact hname+ rw [hsp, relLoop_comp _ _ hsf] at hloop+ have hb : bad (name.takeWhile notSlash) = false := by+ cases hb : bad (name.takeWhile notSlash)+ · rfl+ · rw [hb] at hloop; simp at hloop+ exact plain_of_takeWhile name hb+ · intro ⟨t, ht, hmem, hname⟩+ have ⟨cs, hne, hcs, hm⟩ := (relOk_iff member).1 hmem+ have htw : name.takeWhile notSlash = t := by+ rw [hname, takeWhile_comp t member ht.2.1]+ rw [htw]+ refine ⟨⟨⟨⟨⟨?_, ?_⟩, ht.1⟩, ?_⟩, hmem⟩, ?_⟩+ · apply (relOk_iff name).2+ refine ⟨t :: cs, by simp, ?_, ?_⟩+ · intro c hc+ simp only [List.mem_cons] at hc+ rcases hc with hc | hc+ · rw [hc]; exact ht+ · exact hcs c hc+ · rw [join_cons t cs hne, hname]+ rcases hm with hm | hm+ · left; rw [hm]+ · right; rw [hm]; simp+ · rw [hname]; simp+ · intro e+ rw [hname] at e+ have ⟨h1, h2, h3, _⟩ := ht+ match t, h1, h2, h3, e with+ | [x], _, _, h3, e =>+ simp only [List.cons_append, List.nil_append, List.take_succ_cons,+ List.take_zero, List.cons.injEq, and_true] at e+ exact h3 (by rw [e])+ | x :: y :: t', _, h2, _, e =>+ simp only [List.cons_append, List.take_succ_cons, List.take_zero,+ List.cons.injEq, and_true] at e+ exact h2 (by rw [← e.2]; simp)+ · rw [hname]; simp++/-! ### Extraction -/++/-- The top directory `bpm_pkg_extract()` takes from the first member: the+name up to its first `/`, which it must have, not first, and shorter+than the 256 bytes of `root`. -/+def topOf (name : List Nat) : Option (List Nat) :=+ let t := name.takeWhile notSlash+ if t.length < name.length ∧ t ≠ [] ∧ t.length < 256 then some t else none++/-- The top directory of the members before, or this member's for the+first. -/+def topFor (top : Option (List Nat)) (name : List Nat) : Option (List Nat) :=+ match top with+ | some t => some t+ | none => topOf name++/-- The checks `bpm_pkg_extract()` makes of a member's name and type+before it writes: the name passes the check, lies below the top+directory, and what follows it is empty only for a directory and passes+the check otherwise, and the member is a regular file or a directory.+Yields the top directory and the path it then creates below `dest`. The+limits on count, size and path length refuse more and are left out. -/+def extractMember (top : Option (List Nat)) (name : List Nat) (type : Nat) :+ Option (List Nat × List Nat) :=+ if relOk name = false then none+ else+ match topFor top name with+ | none => none+ | some t =>+ if name.take (t.length + 1) ≠ t ++ [slash] then none+ else if (name.drop (t.length + 1) = [] ∧ type ≠ dirType) ∨+ (name.drop (t.length + 1) ≠ [] ∧+ relOk (name.drop (t.length + 1)) = false) then none+ else if type ≠ regType ∧ type ≠ dirType then none+ else some (t, name.drop (t.length + 1))++/-- Every member `bpm_pkg_extract()` writes is a regular file or a+directory, no symbolic or hard link, and is created strictly below+`dest`, as is every directory on its way, or is `dest` itself for the+top directory. -/+theorem extract_contained (dest : Dir) (top : Option (List Nat))+ (name : List Nat) (type : Nat) (t rel : List Nat)+ (h : extractMember top name type = some (t, rel)) :+ (type = regType ∨ type = dirType) ∧+ ((rel = [] ∧ type = dirType) ∨+ ∃ ds, resolve dest rel = some ds ∧ ds ≠ [] ∧ ∀ d ∈ ds, Below dest d) := by+ unfold extractMember at h+ by_cases h1 : relOk name = false+ · rw [ite_eq_left h1] at h; contradiction+ rw [ite_eq_right h1] at h+ cases htop : topFor top name with+ | none => simp [htop] at h+ | some t' =>+ simp only [htop] at h+ by_cases h2 : name.take (t'.length + 1) ≠ t' ++ [slash]+ · rw [ite_eq_left h2] at h; contradiction+ rw [ite_eq_right h2] at h+ generalize hd : name.drop (t'.length + 1) = d at h+ by_cases h3 : (d = [] ∧ type ≠ dirType) ∨ (d ≠ [] ∧ relOk d = false)+ · rw [ite_eq_left h3] at h; contradiction+ rw [ite_eq_right h3] at h+ by_cases h4 : type ≠ regType ∧ type ≠ dirType+ · rw [ite_eq_left h4] at h; contradiction+ rw [ite_eq_right h4] at h+ simp only [Option.some.injEq, Prod.mk.injEq] at h+ obtain ⟨_, hr⟩ := h+ subst hr+ refine ⟨Classical.byContradiction fun hn =>+ h4 ⟨fun e => hn (Or.inl e), fun e => hn (Or.inr e)⟩, ?_⟩+ by_cases he : d = []+ · left; exact ⟨he, Classical.byContradiction fun hn => h3 (Or.inl ⟨he, hn⟩)⟩+ · right+ have hok : relOk d = true := by+ cases hr : relOk d+ · exact absurd (Or.inr ⟨he, hr⟩) h3+ · rfl+ exact relOk_contained dest d hok++end Shirudo.ArchivePathdiff --git a/testing/proofs/lean4/Shirudo/Hex.lean b/testing/proofs/lean4/Shirudo/Hex.leannew file mode 100644index 00000000..7190ac65--- /dev/null+++ b/testing/proofs/lean4/Shirudo/Hex.lean@@ -0,0 +1,355 @@+-- SPDX-License-Identifier: BSD-2-Clause+-- Copyright (c) 2026 Authors of shirudo++/-!+The hex codec of util/hex.c. `hex_encode()` writes each byte as two+lowercase digits from the table `0123456789abcdef`, the high nibble+first. `hex_nibble()` gives the value of one digit of either case, or -1.+`hex_decode()` takes a string of exactly `2 * n` digits into `n` bytes,+after comparing its `strlen()` with `size_mul(n, 2)`, and+`hex_decode_max()` takes any even count of digits up to `2 * cap`, after+counting them with `strnlen()` up to `size_add(size_mul(cap, 2), 1)`.+`size_mul()` and `size_add()` saturate at `SIZE_MAX`.++For strings of every length: an encoding is lowercase hex twice the length+of its input and decodes back to it, a decoding encodes back to its input+in lowercase, so each determines the other, `hex_decode()` takes exactly+the strings of `2 * n` hex digits and `hex_decode_max()` exactly the even+runs of hex digits of at most `2 * cap`, and what either yields is bytes.+A string is its bytes before the NUL, each byte its value; a string with+its NUL fits in memory, so it is shorter than `SIZE_MAX`. The CBMC proof+testing/proofs/cbmc/hex-model.c checks the C against the model on every+input of up to 8 bytes, strings of up to 17 digits, and counts and+capacities both small and past `SIZE_MAX / 2`.+-/++namespace Shirudo.Hex++/-- `SIZE_MAX`. -/+def sizeMax : Nat := 18446744073709551615++/-- `size_mul()` of include/shirudo/overflow.h. -/+def sizeMul (a b : Nat) : Nat := if a * b ≤ sizeMax then a * b else sizeMax++/-- `size_add()` of include/shirudo/overflow.h. -/+def sizeAdd (a b : Nat) : Nat := if a + b ≤ sizeMax then a + b else sizeMax++/-- The digit table `d` of `hex_encode()`. -/+def table : List Nat :=+ [0x30, 0x31, 0x32, 0x33, 0x34, 0x35, 0x36, 0x37, 0x38, 0x39,+ 0x61, 0x62, 0x63, 0x64, 0x65, 0x66]++/-- What the loop of `hex_encode()` writes for one byte:+`d[in[i] >> 4]` and `d[in[i] & 0xf]`. -/+def encodeByte (b : Nat) : List Nat :=+ [table.getD (b >>> 4) 0, table.getD (b &&& 0xf) 0]++/-- `hex_encode()`, without its NUL. -/+def encode (bs : List Nat) : List Nat := bs.flatMap encodeByte++/-- `hex_nibble()`; `none` is -1. -/+def nibble (c : Nat) : Option Nat :=+ if 0x30 ≤ c ∧ c ≤ 0x39 then some (c - 0x30)+ else if 0x61 ≤ c ∧ c ≤ 0x66 then some (c - 0x61 + 10)+ else if 0x41 ≤ c ∧ c ≤ 0x46 then some (c - 0x41 + 10)+ else none++/-- The loop of `hex_decode()`: `(hi << 4) | lo` from each pair of digits,+refusing the first pair that holds anything else. The length check before+it leaves no single byte over. -/+def decodePairs : List Nat → Option (List Nat)+ | [] => some []+ | [_] => none+ | h :: l :: rest =>+ match nibble h, nibble l with+ | some hi, some lo => (decodePairs rest).map (((hi <<< 4) ||| lo) :: ·)+ | _, _ => none++/-- `hex_decode(hex, out, n)`; `none` is `-EINVAL`. -/+def decode (s : List Nat) (n : Nat) : Option (List Nat) :=+ if s.length ≠ sizeMul n 2 then none else decodePairs s++/-- `hex_decode_max(hex, out, cap, len)`; `none` is `-EINVAL`, and the+length of what it yields is `*len`. -/+def decodeMax (s : List Nat) (cap : Nat) : Option (List Nat) :=+ let n := min s.length (sizeAdd (sizeMul cap 2) 1)+ if n % 2 ≠ 0 ∨ n / 2 > cap then none else decode s (n / 2)++/-- A hex digit of either case. -/+def isHex (c : Nat) : Bool := (nibble c).isSome++/-- A lowercase hex digit. -/+def isLowerHex (c : Nat) : Prop := (0x30 ≤ c ∧ c ≤ 0x39) ∨ (0x61 ≤ c ∧ c ≤ 0x66)++/-- A digit in lowercase, any other byte as it is. -/+def lower (c : Nat) : Nat := if 0x41 ≤ c ∧ c ≤ 0x46 then c + 0x20 else c++/-! ### One byte and one pair -/++theorem shr4 (b : Nat) : b >>> 4 = b / 16 := by+ rw [Nat.shiftRight_eq_div_pow]++theorem and15 (b : Nat) : b &&& 0xf = b % 16 := by+ have := Nat.and_two_pow_sub_one_eq_mod b 4+ simpa using this++theorem table_lower : ∀ v, v < 16 → isLowerHex (table.getD v 0) := by+ unfold isLowerHex+ decide++theorem nibble_table : ∀ v, v < 16 → nibble (table.getD v 0) = some v := by+ decide++theorem pair_value : ∀ hi, hi < 16 → ∀ lo, lo < 16 →+ (hi <<< 4) ||| lo = hi * 16 + lo := by+ decide++theorem encodeByte_lower (b : Nat) (hb : b < 256) :+ ∀ c ∈ encodeByte b, isLowerHex c := by+ intro c hc+ simp only [encodeByte, List.mem_cons, List.not_mem_nil, or_false] at hc+ rcases hc with hc | hc <;> subst hc+ · exact table_lower _ (by rw [shr4]; omega)+ · exact table_lower _ (by rw [and15]; omega)++theorem decode_encodeByte (b : Nat) (hb : b < 256) :+ nibble (table.getD (b >>> 4) 0) = some (b >>> 4) ∧+ nibble (table.getD (b &&& 0xf) 0) = some (b &&& 0xf) ∧+ ((b >>> 4) <<< 4) ||| (b &&& 0xf) = b := by+ have h1 : b >>> 4 < 16 := by rw [shr4]; omega+ have h2 : b &&& 0xf < 16 := by rw [and15]; omega+ refine ⟨nibble_table _ h1, nibble_table _ h2, ?_⟩+ rw [pair_value _ h1 _ h2, shr4, and15]+ omega++theorem pair_byte (hi lo : Nat) (hhi : hi < 16) (hlo : lo < 16) :+ (hi <<< 4) ||| lo < 256 ∧+ encodeByte ((hi <<< 4) ||| lo) = [table.getD hi 0, table.getD lo 0] := by+ rw [pair_value hi hhi lo hlo]+ refine ⟨by omega, ?_⟩+ simp only [encodeByte, shr4, and15]+ have e1 : (hi * 16 + lo) / 16 = hi := by omega+ have e2 : (hi * 16 + lo) % 16 = lo := by omega+ rw [e1, e2]++theorem nibble_lt (c v : Nat) (h : nibble c = some v) : v < 16 := by+ unfold nibble at h+ split at h+ · simp only [Option.some.injEq] at h; omega+ · split at h+ · simp only [Option.some.injEq] at h; omega+ · split at h+ · simp only [Option.some.injEq] at h; omega+ · simp at h++theorem table_nibble (c v : Nat) (h : nibble c = some v) :+ table.getD v 0 = lower c := by+ unfold nibble at h+ unfold lower+ split at h+ · simp only [Option.some.injEq] at h+ subst h+ have hc : c - 0x30 < 10 := by omega+ rw [ite_eq_right (by omega)]+ have := (by decide : ∀ k, k < 10 → table.getD k 0 = k + 0x30) _ hc+ omega+ · split at h+ · simp only [Option.some.injEq] at h+ subst h+ rw [ite_eq_right (by omega)]+ have := (by decide : ∀ k, k < 6 → table.getD (k + 10) 0 = k + 0x61)+ (c - 0x61) (by omega)+ omega+ · split at h+ · simp only [Option.some.injEq] at h+ subst h+ rw [ite_eq_left (by omega)]+ have := (by decide : ∀ k, k < 6 → table.getD (k + 10) 0 = k + 0x61)+ (c - 0x41) (by omega)+ omega+ · simp at h++/-! ### Encoding -/++theorem encode_cons (b : Nat) (bs : List Nat) :+ encode (b :: bs) = encodeByte b ++ encode bs := by+ simp [encode]++/-- An encoding is twice as long as its input. -/+theorem length_encode (bs : List Nat) : (encode bs).length = 2 * bs.length := by+ induction bs with+ | nil => rfl+ | cons b bs ih =>+ rw [encode_cons, List.length_append, ih]+ simp [encodeByte]+ omega++/-- An encoding of bytes is lowercase hex. -/+theorem encode_lower (bs : List Nat) (h : ∀ b ∈ bs, b < 256) :+ ∀ c ∈ encode bs, isLowerHex c := by+ induction bs with+ | nil => simp [encode]+ | cons b bs ih =>+ intro c hc+ rw [encode_cons, List.mem_append] at hc+ rcases hc with hc | hc+ · exact encodeByte_lower b (h b List.mem_cons_self) c hc+ · exact ih (fun b' m => h b' (List.mem_cons_of_mem b m)) c hc++theorem decodePairs_encode (bs : List Nat) (h : ∀ b ∈ bs, b < 256) :+ decodePairs (encode bs) = some bs := by+ induction bs with+ | nil => rfl+ | cons b bs ih =>+ have ⟨hh, hl, hv⟩ := decode_encodeByte b (h b List.mem_cons_self)+ rw [encode_cons]+ simp only [encodeByte, List.cons_append, List.nil_append, decodePairs, hh, hl,+ ih (fun b' m => h b' (List.mem_cons_of_mem b m)), Option.map_some, hv]++theorem sizeMul_two (n : Nat) (h : 2 * n ≤ sizeMax) : sizeMul n 2 = 2 * n := by+ unfold sizeMul+ split <;> omega++/-- `hex_decode()` takes back what `hex_encode()` writes, for bytes of+every count whose encoding fits in memory. -/+theorem decode_encode (bs : List Nat) (h : ∀ b ∈ bs, b < 256)+ (hfit : 2 * bs.length ≤ sizeMax) :+ decode (encode bs) bs.length = some bs := by+ unfold decode+ rw [length_encode, sizeMul_two _ hfit]+ simp only [ne_eq, not_true_eq_false, ite_false]+ exact decodePairs_encode bs h++/-! ### Decoding -/++/-- The loop of `hex_decode()` takes exactly the even runs of hex digits,+and yields bytes that encode back to the digits in lowercase. -/+theorem decodePairs_some : ∀ s : List Nat,+ (decodePairs s ≠ none ↔ s.length % 2 = 0 ∧ ∀ c ∈ s, isHex c) ∧+ ∀ bs, decodePairs s = some bs →+ bs.length * 2 = s.length ∧ (∀ b ∈ bs, b < 256) ∧ encode bs = s.map lower+ | [] => by simp [decodePairs, encode]+ | [c] => by simp [decodePairs]+ | h :: l :: rest => by+ have ih := decodePairs_some rest+ cases hh : nibble h with+ | none =>+ have : isHex h = false := by simp [isHex, hh]+ simp [decodePairs, hh]+ intro _ hm+ simp_all+ | some hi =>+ cases hl : nibble l with+ | none =>+ have : isHex l = false := by simp [isHex, hl]+ simp [decodePairs, hh, hl]+ intro _ _ hm+ simp_all+ | some lo =>+ have hhi := nibble_lt h hi hh+ have hlo := nibble_lt l lo hl+ have ⟨hlt, he⟩ := pair_byte hi lo hhi hlo+ have ihx : isHex h = true ∧ isHex l = true := by simp [isHex, hh, hl]+ simp only [decodePairs, hh, hl]+ constructor+ · rw [ne_eq, Option.map_eq_none_iff, ← ne_eq, ih.1]+ simp only [List.length_cons, List.mem_cons, forall_eq_or_imp, ihx,+ true_and]+ constructor+ · intro ⟨h1, h2⟩; exact ⟨by omega, h2⟩+ · intro ⟨h1, h2⟩; exact ⟨by omega, h2⟩+ · intro bs hbs+ cases hr : decodePairs rest with+ | none => simp [hr] at hbs+ | some bs' =>+ simp only [hr, Option.map_some, Option.some.injEq] at hbs+ subst hbs+ have ⟨h1, h2, h3⟩ := ih.2 bs' hr+ refine ⟨by simp; omega, ?_, ?_⟩+ · intro b hb+ simp only [List.mem_cons] at hb+ rcases hb with hb | hb+ · rw [hb]; exact hlt+ · exact h2 b hb+ · rw [encode_cons, he, h3, table_nibble h hi hh, table_nibble l lo hl]+ rfl++/-- `hex_decode(hex, out, n)` takes exactly the strings of `2 * n` hex+digits of either case, and yields `n` bytes that `hex_encode()` writes+back as the digits in lowercase. -/+theorem decode_spec (s : List Nat) (n : Nat) (hs : s.length < sizeMax) :+ (decode s n ≠ none ↔ s.length = 2 * n ∧ ∀ c ∈ s, isHex c) ∧+ ∀ bs, decode s n = some bs →+ bs.length = n ∧ (∀ b ∈ bs, b < 256) ∧ encode bs = s.map lower := by+ have hm : s.length = sizeMul n 2 ↔ s.length = 2 * n := by+ unfold sizeMul+ split <;> omega+ have hp := decodePairs_some s+ unfold decode+ constructor+ · by_cases hl : s.length = sizeMul n 2+ · rw [ite_eq_right (fun e => e hl), hp.1, hm.1 hl]+ simp only [true_and]+ constructor+ · intro ⟨_, h⟩; exact h+ · intro h; exact ⟨by omega, h⟩+ · rw [ite_eq_left hl]+ simp only [ne_eq, not_true_eq_false, false_iff, not_and]+ intro e; exact absurd (hm.2 e) hl+ · intro bs h+ by_cases hl : s.length = sizeMul n 2+ · rw [ite_eq_right (fun e => e hl)] at h+ have ⟨h1, h2, h3⟩ := hp.2 bs h+ exact ⟨by have := hm.1 hl; omega, h2, h3⟩+ · rw [ite_eq_left hl] at h; simp at h++/-- Bytes are determined by their encoding: the decoding of any string is+the only input whose encoding is that string in lowercase. -/+theorem encode_injective (a b : List Nat) (ha : ∀ x ∈ a, x < 256)+ (hb : ∀ x ∈ b, x < 256) (h : encode a = encode b) : a = b := by+ have e := decodePairs_encode a ha+ rw [h, decodePairs_encode b hb] at e+ exact (Option.some.inj e).symm++/-- `hex_decode_max(hex, out, cap, len)` takes exactly the even runs of hex+digits of either case, none at all included, of at most `2 * cap` digits,+and yields half as many bytes as there are digits, which encode back to+the digits in lowercase. -/+theorem decodeMax_spec (s : List Nat) (cap : Nat) (hs : s.length < sizeMax) :+ (decodeMax s cap ≠ none ↔+ s.length % 2 = 0 ∧ s.length / 2 ≤ cap ∧ ∀ c ∈ s, isHex c) ∧+ ∀ bs, decodeMax s cap = some bs →+ bs.length * 2 = s.length ∧ (∀ b ∈ bs, b < 256) ∧+ encode bs = s.map lower := by+ have hn : min s.length (sizeAdd (sizeMul cap 2) 1) =+ if s.length ≤ 2 * cap then s.length else 2 * cap + 1 := by+ unfold sizeAdd sizeMul+ split <;> split <;> split <;> omega+ have hd := decode_spec s (s.length / 2) hs+ by_cases hok : s.length % 2 = 0 ∧ s.length ≤ 2 * cap+ · have e : decodeMax s cap = decode s (s.length / 2) := by+ unfold decodeMax+ simp only [hn, hok.2, ite_true]+ rw [ite_eq_right (by omega)]+ rw [e]+ constructor+ · rw [hd.1]+ constructor+ · intro ⟨_, h⟩; exact ⟨hok.1, by omega, h⟩+ · intro ⟨_, _, h⟩; exact ⟨by omega, h⟩+ · intro bs h+ have ⟨h1, h2, h3⟩ := hd.2 bs h+ exact ⟨by omega, h2, h3⟩+ · have e : decodeMax s cap = none := by+ unfold decodeMax+ simp only [hn]+ split+ · rw [ite_eq_left (by omega)]+ · rw [ite_eq_left (by omega)]+ rw [e]+ constructor+ · simp only [ne_eq, not_true_eq_false, false_iff, not_and]+ intro h1 h2; exact absurd ⟨h1, by omega⟩ hok+ · intro bs h; simp at h++end Shirudo.Hexdiff --git a/testing/proofs/lean4/Shirudo/JsonString.lean b/testing/proofs/lean4/Shirudo/JsonString.leannew file mode 100644index 00000000..33313b34--- /dev/null+++ b/testing/proofs/lean4/Shirudo/JsonString.lean@@ -0,0 +1,1297 @@+-- SPDX-License-Identifier: BSD-2-Clause+-- Copyright (c) 2026 Authors of shirudo++import Shirudo.Hex++/-!+The JSON strings of util/json.c. The strict writer, `put_string_n()` with+`lossy` false as `json_str()` calls it on the bytes of a C string, writes+a quote, then `"` and `\` escaped, `\n`, `\r` and `\t` by name, every+other control byte as `\u00XX`, the other ASCII bytes as they are and+each sequence of Table 3-7 of the Unicode Standard as it is, and a quote;+it refuses a NUL or a byte that starts no such sequence with `-EILSEQ`.+The reader, `parse_string()`, takes the escapes of one letter and+`\uXXXX`, joining a high and a low surrogate into one code point and+refusing `\u0000` and a lone surrogate, refuses an unescaped control+byte, and copies each sequence of Table 3-7; `emit_byte()` refuses with+`-E2BIG` past `JSON_MAX_STRING_BYTES` and with `-ENOSPC` when `dst` has no+room for a byte and the NUL.++The models follow the C step by step on byte lists, each byte its value.+Well-formed UTF-8 is Table 3-7, as `table_width()` of+testing/proofs/cbmc/string-utf8.c states it, which proves that+`utf8_width()` computes it for every input; `%04x` writes four lowercase+hex digits. The writer's emitter is assumed to have room: a `put()` that+fails sets the sticky error that fails the whole document.++For byte strings of every length: the strict writer takes exactly the+well-formed UTF-8 without NUL; what it writes is a quote, the characters+of a string of ECMA-404 with no control byte at all and no `"` or `\`+outside an escape, in well-formed UTF-8, and a quote; and the reader,+with room for it, returns exactly the bytes it was written from and stops+at the closing quote, whatever follows. Whatever the reader returns, from+any input, is well-formed UTF-8 without NUL.+testing/proofs/cbmc/json-emit-string-model.c checks the writer against+the model on every string of up to 4 bytes,+testing/proofs/cbmc/json-string-model.c the reader on every input of up+to 6 bytes, every buffer and a `JSON_MAX_STRING_BYTES` of 3, and+testing/proofs/cbmc/json-escape-model.c the reader on every pair of+`\u` escapes in either case.+-/++namespace Shirudo.JsonString+open Shirudo.Hex (nibble table)++/-- `"`. -/+def quote : Nat := 0x22++/-- `\`. -/+def backslash : Nat := 0x5c++/-! ### Well-formed UTF-8 -/++/-- The first row of Table 3-7 of the Unicode Standard, on the first+bytes of `n`: U+0000..U+007F. -/+def Row1 (n b0 : Nat) : Prop := 1 ≤ n ∧ b0 ≤ 0x7f++/-- The second row: U+0080..U+07FF. -/+def Row2 (n b0 b1 : Nat) : Prop :=+ 2 ≤ n ∧ 0xc2 ≤ b0 ∧ b0 ≤ 0xdf ∧ 0x80 ≤ b1 ∧ b1 ≤ 0xbf++/-- The next four rows: U+0800..U+FFFF without the surrogates. -/+def Row3 (n b0 b1 b2 : Nat) : Prop :=+ 3 ≤ n ∧ 0x80 ≤ b2 ∧ b2 ≤ 0xbf ∧+ ((b0 = 0xe0 ∧ 0xa0 ≤ b1 ∧ b1 ≤ 0xbf) ∨+ (0xe1 ≤ b0 ∧ b0 ≤ 0xec ∧ 0x80 ≤ b1 ∧ b1 ≤ 0xbf) ∨+ (b0 = 0xed ∧ 0x80 ≤ b1 ∧ b1 ≤ 0x9f) ∨+ (0xee ≤ b0 ∧ b0 ≤ 0xef ∧ 0x80 ≤ b1 ∧ b1 ≤ 0xbf))++/-- The last three rows: U+10000..U+10FFFF. -/+def Row4 (n b0 b1 b2 b3 : Nat) : Prop :=+ 4 ≤ n ∧ 0x80 ≤ b2 ∧ b2 ≤ 0xbf ∧ 0x80 ≤ b3 ∧ b3 ≤ 0xbf ∧+ ((b0 = 0xf0 ∧ 0x90 ≤ b1 ∧ b1 ≤ 0xbf) ∨+ (0xf1 ≤ b0 ∧ b0 ≤ 0xf3 ∧ 0x80 ≤ b1 ∧ b1 ≤ 0xbf) ∨+ (b0 = 0xf4 ∧ 0x80 ≤ b1 ∧ b1 ≤ 0x8f))++instance (n b0 : Nat) : Decidable (Row1 n b0) := by unfold Row1; infer_instance+instance (n b0 b1 : Nat) : Decidable (Row2 n b0 b1) := by unfold Row2; infer_instance+instance (n b0 b1 b2 : Nat) : Decidable (Row3 n b0 b1 b2) := by+ unfold Row3; infer_instance+instance (n b0 b1 b2 b3 : Nat) : Decidable (Row4 n b0 b1 b2 b3) := by+ unfold Row4; infer_instance++/-- Table 3-7 row by row on the first bytes `b0` to `b3` of `n`: the+length of the well-formed sequence they start, or 0. This is+`table_width()` of testing/proofs/cbmc/string-utf8.c, which proves that+`utf8_width()` of util/string.c computes it for every input. -/+def rowWidth (n b0 b1 b2 b3 : Nat) : Nat :=+ if Row1 n b0 then 1+ else if Row2 n b0 b1 then 2+ else if Row3 n b0 b1 b2 then 3+ else if Row4 n b0 b1 b2 b3 then 4+ else 0++/-- `utf8_width(s, n)` on the `n` bytes `s`. -/+def width (s : List Nat) : Nat :=+ rowWidth s.length (s.getD 0 0) (s.getD 1 0) (s.getD 2 0) (s.getD 3 0)++/-- Well-formed UTF-8: the bytes are a sequence of rows of Table 3-7, as+`well_formed()` of testing/proofs/cbmc/json-emit-string.c reads them. -/+def wellFormed (s : List Nat) : Bool :=+ match s with+ | [] => true+ | c :: rest =>+ match width (c :: rest) with+ | 0 => false+ | n + 1 => wellFormed (rest.drop n)+termination_by s.length+decreasing_by simp only [List.length_cons, List.length_drop]; omega++theorem rowWidth_cases (n b0 b1 b2 b3 : Nat) :+ (rowWidth n b0 b1 b2 b3 = 1 ∧ Row1 n b0) ∨+ (rowWidth n b0 b1 b2 b3 = 2 ∧ Row2 n b0 b1) ∨+ (rowWidth n b0 b1 b2 b3 = 3 ∧ Row3 n b0 b1 b2) ∨+ (rowWidth n b0 b1 b2 b3 = 4 ∧ Row4 n b0 b1 b2 b3) ∨+ rowWidth n b0 b1 b2 b3 = 0 := by+ unfold rowWidth+ by_cases h1 : Row1 n b0+ · simp [h1]+ by_cases h2 : Row2 n b0 b1+ · simp [h1, h2]+ by_cases h3 : Row3 n b0 b1 b2+ · simp [h1, h2, h3]+ by_cases h4 : Row4 n b0 b1 b2 b3+ · simp [h1, h2, h3, h4]+ · simp [h1, h2, h3, h4]++theorem rowWidth_of_row1 (n b0 b1 b2 b3 : Nat) (h : Row1 n b0) :+ rowWidth n b0 b1 b2 b3 = 1 := by+ unfold rowWidth+ rw [ite_eq_left h]++theorem rowWidth_of_row2 (n b0 b1 b2 b3 : Nat) (h : Row2 n b0 b1) :+ rowWidth n b0 b1 b2 b3 = 2 := by+ have h1 : ¬ Row1 n b0 := by unfold Row1 Row2 at *; omega+ simp [rowWidth, h1, h]++theorem rowWidth_of_row3 (n b0 b1 b2 b3 : Nat) (h : Row3 n b0 b1 b2) :+ rowWidth n b0 b1 b2 b3 = 3 := by+ have h1 : ¬ Row1 n b0 := by unfold Row1 Row3 at *; omega+ have h2 : ¬ Row2 n b0 b1 := by unfold Row2 Row3 at *; omega+ simp [rowWidth, h1, h2, h]++theorem rowWidth_of_row4 (n b0 b1 b2 b3 : Nat) (h : Row4 n b0 b1 b2 b3) :+ rowWidth n b0 b1 b2 b3 = 4 := by+ have h1 : ¬ Row1 n b0 := by unfold Row1 Row4 at *; omega+ have h2 : ¬ Row2 n b0 b1 := by unfold Row2 Row4 at *; omega+ have h3 : ¬ Row3 n b0 b1 b2 := by unfold Row3 Row4 at *; omega+ simp [rowWidth, h1, h2, h3, h]++theorem rowWidth_le (n b0 b1 b2 b3 : Nat) :+ rowWidth n b0 b1 b2 b3 ≤ n ∧ rowWidth n b0 b1 b2 b3 ≤ 4 := by+ rcases rowWidth_cases n b0 b1 b2 b3 with ⟨h, r⟩ | ⟨h, r⟩ | ⟨h, r⟩ | ⟨h, r⟩ | h+ · unfold Row1 at r; omega+ · unfold Row2 at r; omega+ · unfold Row3 at r; omega+ · unfold Row4 at r; omega+ · omega++theorem width_le (s : List Nat) : width s ≤ s.length ∧ width s ≤ 4 :=+ rowWidth_le _ _ _ _ _++theorem getD_take_append (s t : List Nat) (n i : Nat) (hi : i < n)+ (hn : n ≤ s.length) : (s.take n ++ t).getD i 0 = s.getD i 0 := by+ simp only [List.getD_eq_getElem?_getD]+ rw [List.getElem?_append_left (by simp; omega), List.getElem?_take_of_lt hi]++/-- A sequence that starts a row keeps it whatever follows. -/+theorem width_prefix (s t : List Nat) (h : 0 < width s) :+ width (s.take (width s) ++ t) = width s := by+ have hle := width_le s+ have hl : width s ≤ (s.take (width s) ++ t).length := by simp; omega+ have g : ∀ i, i < width s →+ (s.take (width s) ++ t).getD i 0 = s.getD i 0 := fun i hi =>+ getD_take_append s t _ i hi hle.1+ generalize hw : width s = w at h hle hl g+ unfold width at hw ⊢+ generalize (s.take w ++ t).length = L' at hl+ rcases rowWidth_cases s.length (s.getD 0 0) (s.getD 1 0) (s.getD 2 0)+ (s.getD 3 0) with ⟨e, r⟩ | ⟨e, r⟩ | ⟨e, r⟩ | ⟨e, r⟩ | e <;> rw [e] at hw <;>+ subst hw+ · apply rowWidth_of_row1+ rw [g 0 (by omega)]; unfold Row1 at r ⊢; omega+ · apply rowWidth_of_row2+ rw [g 0 (by omega), g 1 (by omega)]; unfold Row2 at r ⊢; omega+ · apply rowWidth_of_row3+ rw [g 0 (by omega), g 1 (by omega), g 2 (by omega)]; unfold Row3 at r ⊢; omega+ · apply rowWidth_of_row4+ rw [g 0 (by omega), g 1 (by omega), g 2 (by omega), g 3 (by omega)]+ unfold Row4 at r ⊢; omega+ · omega++/-- `utf8_width(p, min(left, 4))` is `utf8_width(p, left)`. -/+theorem width_take4 (s : List Nat) : width (s.take 4) = width s := by+ unfold width+ have g : ∀ i, i < 4 → (s.take 4).getD i 0 = s.getD i 0 := by+ intro i hi+ simp only [List.getD_eq_getElem?_getD, List.getElem?_take_of_lt hi]+ rw [g 0 (by omega), g 1 (by omega), g 2 (by omega), g 3 (by omega),+ List.length_take]+ have e1 : (1 ≤ min 4 s.length) = (1 ≤ s.length) := by+ apply propext; omega+ have e2 : (2 ≤ min 4 s.length) = (2 ≤ s.length) := by+ apply propext; omega+ have e3 : (3 ≤ min 4 s.length) = (3 ≤ s.length) := by+ apply propext; omega+ have e4 : (4 ≤ min 4 s.length) = (4 ≤ s.length) := by+ apply propext; omega+ simp only [rowWidth, Row1, Row2, Row3, Row4, e1, e2, e3, e4]++/-- An ASCII byte is a row of its own. -/+theorem width_ascii (c : Nat) (rest : List Nat) (h : c ≤ 0x7f) :+ width (c :: rest) = 1 := by+ apply rowWidth_of_row1+ unfold Row1; simp; omega++/-- A byte from 0x80 starts no row of one byte. -/+theorem width_high (c : Nat) (rest : List Nat) (h : 0x80 ≤ c) :+ width (c :: rest) ≠ 1 := by+ unfold width+ rcases rowWidth_cases (c :: rest).length ((c :: rest).getD 0 0)+ ((c :: rest).getD 1 0) ((c :: rest).getD 2 0) ((c :: rest).getD 3 0)+ with ⟨e, r⟩ | ⟨e, _⟩ | ⟨e, _⟩ | ⟨e, _⟩ | e <;> rw [e]+ · unfold Row1 at r; simp at r; omega+ all_goals omega++/-- Every byte of a row of more than one byte is from 0x80. -/+theorem width_high_bytes (s : List Nat) (h : 2 ≤ width s) :+ ∀ i, i < width s → 0x80 ≤ s.getD i 0 := by+ intro i hi+ unfold width at h hi+ rcases rowWidth_cases s.length (s.getD 0 0) (s.getD 1 0) (s.getD 2 0)+ (s.getD 3 0) with ⟨e, r⟩ | ⟨e, r⟩ | ⟨e, r⟩ | ⟨e, r⟩ | e <;> rw [e] at h hi+ · omega+ · unfold Row2 at r+ rcases (by omega : i = 0 ∨ i = 1) with e | e <;> subst e <;> omega+ · unfold Row3 at r+ rcases (by omega : i = 0 ∨ i = 1 ∨ i = 2) with e | e | e <;> subst e <;> omega+ · unfold Row4 at r+ rcases (by omega : i = 0 ∨ i = 1 ∨ i = 2 ∨ i = 3) with e | e | e | e <;>+ subst e <;> omega+ · omega++/-! ### The writer -/++/-- `\u%04x` of `c`: `\u` and its four lowercase hex digits. -/+def uEscape (c : Nat) : List Nat :=+ [backslash, 0x75, table.getD (c / 4096 % 16) 0, table.getD (c / 256 % 16) 0,+ table.getD (c / 16 % 16) 0, table.getD (c % 16) 0]++/-- The loop of `put_string_n(e, s, len, false)` over the bytes from `p`:+`"` and `\` escaped, `\n`, `\r` and `\t` by name, every other control+byte as `\u00XX`, the other ASCII bytes as they are, and a sequence of+Table 3-7 as it is; `none` is `-EILSEQ`, for a NUL or a byte that starts+no sequence of the `utf8_width(p, min(left, 4))` bytes. -/+def writeBody (s : List Nat) : Option (List Nat) :=+ match s with+ | [] => some []+ | c :: rest =>+ if c = quote ∨ c = backslash then (writeBody rest).map ([backslash, c] ++ ·)+ else if c = 0x0a then (writeBody rest).map ([backslash, 0x6e] ++ ·)+ else if c = 0x0d then (writeBody rest).map ([backslash, 0x72] ++ ·)+ else if c = 0x09 then (writeBody rest).map ([backslash, 0x74] ++ ·)+ else if c ≠ 0 ∧ c < 0x20 then (writeBody rest).map (uEscape c ++ ·)+ else if c ≠ 0 ∧ c < 0x80 then (writeBody rest).map (c :: ·)+ else+ match (if c ≠ 0 then width ((c :: rest).take 4) else 0) with+ | 0 => none+ | n + 1 => (writeBody (rest.drop n)).map ((c :: rest).take (n + 1) ++ ·)+termination_by s.length+decreasing_by all_goals simp only [List.length_cons, List.length_drop]; omega++/-- `put_string_n(e, s, len, false)`, as `json_str()` calls it with the+bytes of a C string: the body between two quotes. The emitter is assumed+to have room, as a failed `put()` fails the whole document. -/+def write (s : List Nat) : Option (List Nat) :=+ (writeBody s).map (fun b => quote :: b ++ [quote])++/-! ### The reader -/++/-- `-EINVAL`, `-E2BIG` and `-ENOSPC`. -/+inductive Err where+ | inval+ | tooBig+ | noSpace+ deriving DecidableEq, Repr++/-- Where `parse_string()` decodes to: `dst` given or `NULL`, its `cap`,+and `JSON_MAX_STRING_BYTES`. -/+structure Room where+ dst : Bool+ cap : Nat+ max : Nat++/-- `emit_byte()`: `-E2BIG` past `JSON_MAX_STRING_BYTES`, `-ENOSPC` when+`dst` leaves no room for the byte and the NUL. -/+def emit (r : Room) (out : List Nat) (b : Nat) : Except Err (List Nat) :=+ if out.length ≥ r.max then .error .tooBig+ else if r.dst = true ∧ out.length + 1 ≥ r.cap then .error .noSpace+ else .ok (out ++ [b])++/-- `emit_byte()` on each byte in turn, stopping at the first error. -/+def emitAll (r : Room) (out : List Nat) : List Nat → Except Err (List Nat)+ | [] => .ok out+ | b :: bs =>+ match emit r out b with+ | .error e => .error e+ | .ok out' => emitAll r out' bs++/-- `utf8_emit()`: a code point below U+10000 as one, two or three bytes. -/+def utf8Emit (r : Room) (out : List Nat) (cp : Nat) : Except Err (List Nat) :=+ if cp < 0x80 then emit r out cp+ else if cp < 0x800 then+ emitAll r out [0xc0 ||| (cp >>> 6), 0x80 ||| (cp &&& 0x3f)]+ else+ emitAll r out [0xe0 ||| (cp >>> 12), 0x80 ||| ((cp >>> 6) &&& 0x3f),+ 0x80 ||| (cp &&& 0x3f)]++/-- The four bytes `parse_string()` writes for a code point from U+10000. -/+def utf8Four (cp : Nat) : List Nat :=+ [0xf0 ||| (cp >>> 18), 0x80 ||| ((cp >>> 12) &&& 0x3f),+ 0x80 ||| ((cp >>> 6) &&& 0x3f), 0x80 ||| (cp &&& 0x3f)]++/-- What `parse_string()` writes for the code point of an escape. -/+def emitCp (r : Room) (out : List Nat) (cp : Nat) : Except Err (List Nat) :=+ if cp < 0x10000 then utf8Emit r out cp else emitAll r out (utf8Four cp)++/-- `hex4()`: `v = (v << 4) | n` over four hex digits; `none` is -1. -/+def hex4 (ds : List Nat) : Option Nat :=+ ds.foldl (fun v ch =>+ match v, nibble ch with+ | some v, some n => some ((v <<< 4) ||| n)+ | _, _ => none) (some 0)++/-- The byte each escape of one letter stands for. -/+def simpleEscape (e : Nat) : Option Nat :=+ if e = 0x22 then some 0x22+ else if e = 0x5c then some 0x5c+ else if e = 0x2f then some 0x2f+ else if e = 0x62 then some 0x08+ else if e = 0x66 then some 0x0c+ else if e = 0x6e then some 0x0a+ else if e = 0x72 then some 0x0d+ else if e = 0x74 then some 0x09+ else none++/-- The code point of the `\u` escape whose digits start `s`, joined+with the low surrogate escape that must follow a high one, and the bytes+after it: `hex4()` and its checks in `parse_string()`. `\u0000`, a+digit missing and a lone surrogate are `-EINVAL`. -/+def uCodePoint (s : List Nat) : Except Err (Nat × List Nat) :=+ match s with+ | a :: b :: c :: d :: rest =>+ match hex4 [a, b, c, d] with+ | none => .error .inval+ | some cp =>+ if cp = 0 then .error .inval+ else if 0xd800 ≤ cp ∧ cp ≤ 0xdbff then+ match rest with+ | p0 :: p1 :: a' :: b' :: c' :: d' :: rest' =>+ if p0 ≠ backslash ∨ p1 ≠ 0x75 then .error .inval+ else+ match hex4 [a', b', c', d'] with+ | none => .error .inval+ | some lo =>+ if 0xdc00 ≤ lo ∧ lo ≤ 0xdfff then+ .ok (0x10000 + ((cp - 0xd800) <<< 10) + (lo - 0xdc00), rest')+ else .error .inval+ | _ => .error .inval+ else if 0xdc00 ≤ cp ∧ cp ≤ 0xdfff then .error .inval+ else .ok (cp, rest)+ | _ => .error .inval++theorem uCodePoint_shorter (s rest : List Nat) (cp : Nat)+ (h : uCodePoint s = .ok (cp, rest)) : rest.length < s.length := by+ unfold uCodePoint at h+ split at h+ · split at h+ · contradiction+ · split at h+ · contradiction+ · split at h+ · split at h+ · split at h+ · contradiction+ · split at h+ · contradiction+ · split at h+ · simp only [Except.ok.injEq, Prod.mk.injEq] at h+ rw [← h.2]; simp; omega+ · contradiction+ · contradiction+ · split at h+ · contradiction+ · simp only [Except.ok.injEq, Prod.mk.injEq] at h+ rw [← h.2]; simp; omega+ · contradiction++/-- The loop of `parse_string()` on the bytes from `c->p` to `c->end`,+with `out` decoded so far: the decoded bytes and the bytes after the+closing quote. An escape of one letter stands for its byte, a `\u`+escape for the UTF-8 of its code point; an unescaped control byte is+refused, and any other byte must start a sequence of Table 3-7, which is+copied. -/+def readLoop (r : Room) (out : List Nat) (s : List Nat) :+ Except Err (List Nat × List Nat) :=+ match s with+ | [] => .error .inval+ | ch :: rest =>+ if ch = quote then .ok (out, rest)+ else if ch = backslash then+ match rest with+ | [] => .error .inval+ | e :: rest' =>+ match simpleEscape e with+ | some v =>+ match emit r out v with+ | .error x => .error x+ | .ok out' => readLoop r out' rest'+ | none =>+ if e ≠ 0x75 then .error .inval+ else+ match _hu : uCodePoint rest' with+ | .error x => .error x+ | .ok (cp, rest'') =>+ match emitCp r out cp with+ | .error x => .error x+ | .ok out' => readLoop r out' rest''+ else if ch < 0x20 then .error .inval+ else+ match width (ch :: rest) with+ | 0 => .error .inval+ | n + 1 =>+ match emitAll r out ((ch :: rest).take (n + 1)) with+ | .error x => .error x+ | .ok out' => readLoop r out' (rest.drop n)+termination_by s.length+decreasing_by+ all_goals simp only [List.length_cons, List.length_drop]+ all_goals first+ | omega+ | (have := uCodePoint_shorter _ _ _ _hu; omega)++/-- `parse_string(c, dst, cap)` on the bytes from `c->p` to `c->end`: the+decoded bytes and the bytes after the string. -/+def readString (r : Room) (s : List Nat) : Except Err (List Nat × List Nat) :=+ match s with+ | [] => .error .inval+ | q :: rest =>+ if q ≠ quote then .error .inval+ else+ match readLoop r [] rest with+ | .error x => .error x+ | .ok (out, rest') =>+ if r.dst = true ∧ r.cap = 0 then .error .noSpace else .ok (out, rest')++/-! ### Steps of the reader -/++theorem option_map_some {α β : Type} (f : α → β) (x : Option α) (b : β) :+ x.map f = some b ↔ ∃ a, x = some a ∧ f a = b := by+ cases x <;> simp++theorem shl4_or (v n : Nat) (hn : n < 16) : (v <<< 4) ||| n = v * 16 + n := by+ rw [← Nat.shiftLeft_add_eq_or_of_lt (by simpa using hn), Nat.shiftLeft_eq]++/-- `hex4()` reads back the four digits `%04x` writes. -/+theorem hex4_digits (c : Nat) (hc : c < 0x10000) :+ hex4 [table.getD (c / 4096 % 16) 0, table.getD (c / 256 % 16) 0,+ table.getD (c / 16 % 16) 0, table.getD (c % 16) 0] = some c := by+ simp only [hex4, List.foldl_cons, List.foldl_nil,+ Hex.nibble_table _ (Nat.mod_lt _ (by omega : 16 > 0))]+ rw [shl4_or _ _ (Nat.mod_lt _ (by omega)), shl4_or _ _ (Nat.mod_lt _ (by omega)),+ shl4_or _ _ (Nat.mod_lt _ (by omega)), shl4_or _ _ (Nat.mod_lt _ (by omega))]+ congr 1+ omega++theorem emit_ok (r : Room) (out : List Nat) (b : Nat) (hm : out.length < r.max)+ (hc : r.dst = true → out.length + 1 < r.cap) :+ emit r out b = .ok (out ++ [b]) := by+ unfold emit+ rw [ite_eq_right (by omega), ite_eq_right (fun h => by have := hc h.1; omega)]++theorem emitAll_ok (r : Room) (out u : List Nat) (hm : out.length + u.length ≤ r.max)+ (hc : r.dst = true → out.length + u.length < r.cap) :+ emitAll r out u = .ok (out ++ u) := by+ induction u generalizing out with+ | nil => simp [emitAll]+ | cons b u ih =>+ simp only [List.length_cons] at hm hc+ simp only [emitAll]+ rw [emit_ok r out b (by omega) (fun h => by have := hc h; omega)]+ simp only+ rw [ih (out ++ [b]) (by simp; omega) (fun h => by have := hc h; simp; omega)]+ simp++theorem readLoop_quote (r : Room) (out more : List Nat) :+ readLoop r out (quote :: more) = .ok (out, more) := by+ rw [readLoop.eq_def]+ simp++theorem readLoop_escape (r : Room) (out more : List Nat) (e v : Nat)+ (h : simpleEscape e = some v) :+ readLoop r out (backslash :: e :: more) =+ match emit r out v with+ | .error x => .error x+ | .ok out' => readLoop r out' more := by+ rw [readLoop.eq_def]+ simp only [backslash, quote, h]+ rfl++theorem readLoop_u (r : Room) (out more rest : List Nat) (cp : Nat)+ (h : uCodePoint more = .ok (cp, rest)) :+ readLoop r out (backslash :: 0x75 :: more) =+ match emitCp r out cp with+ | .error x => .error x+ | .ok out' => readLoop r out' rest := by+ rw [readLoop.eq_def]+ simp only [backslash, quote]+ simp only [simpleEscape, Nat.reduceEqDiff, ite_false, ite_true, ne_eq,+ not_true_eq_false]+ split+ · next x hx => rw [h] at hx; contradiction+ · next cp' rest' hx =>+ rw [h] at hx+ simp only [Except.ok.injEq, Prod.mk.injEq] at hx+ rw [hx.1, hx.2]++theorem uCodePoint_bmp (a b c d : Nat) (rest : List Nat) (cp : Nat)+ (h : hex4 [a, b, c, d] = some cp) (h0 : cp ≠ 0)+ (hs : ¬ (0xd800 ≤ cp ∧ cp ≤ 0xdfff)) :+ uCodePoint (a :: b :: c :: d :: rest) = .ok (cp, rest) := by+ rw [uCodePoint, h]+ simp only+ rw [ite_eq_right h0, ite_eq_right (by omega), ite_eq_right (by omega)]++/-- A byte from U+0020 but `"` and `\` that starts a sequence of Table+3-7 is copied with the rest of the sequence. -/+theorem readLoop_raw (r : Room) (out u more : List Nat) (hu : u ≠ [])+ (h0 : 0x20 ≤ u.getD 0 0) (hq : u.getD 0 0 ≠ quote)+ (hb : u.getD 0 0 ≠ backslash) (hw : width (u ++ more) = u.length) :+ readLoop r out (u ++ more) =+ match emitAll r out u with+ | .error x => .error x+ | .ok out' => readLoop r out' more := by+ obtain ⟨ch, u', rfl⟩ : ∃ ch u', u = ch :: u' := by+ cases u with+ | nil => contradiction+ | cons ch u' => exact ⟨ch, u', rfl⟩+ simp only [List.getD_cons_zero] at h0 hq hb+ simp only [List.cons_append] at hw ⊢+ rw [readLoop.eq_def]+ simp only [hq, hb, ite_false]+ rw [ite_eq_right (by omega), hw]+ simp only [List.length_cons, List.take_succ_cons, List.take_left',+ List.drop_left']++/-! ### The round trip -/++theorem write_nil : writeBody [] = some [] := by+ rw [writeBody.eq_def]++theorem writeBody_cons (c : Nat) (rest : List Nat) :+ writeBody (c :: rest) =+ if c = quote ∨ c = backslash then (writeBody rest).map ([backslash, c] ++ ·)+ else if c = 0x0a then (writeBody rest).map ([backslash, 0x6e] ++ ·)+ else if c = 0x0d then (writeBody rest).map ([backslash, 0x72] ++ ·)+ else if c = 0x09 then (writeBody rest).map ([backslash, 0x74] ++ ·)+ else if c ≠ 0 ∧ c < 0x20 then (writeBody rest).map (uEscape c ++ ·)+ else if c ≠ 0 ∧ c < 0x80 then (writeBody rest).map (c :: ·)+ else+ match (if c ≠ 0 then width ((c :: rest).take 4) else 0) with+ | 0 => none+ | n + 1 => (writeBody (rest.drop n)).map ((c :: rest).take (n + 1) ++ ·) := by+ rw [writeBody.eq_def]++/-- An escape of one letter reads back as its byte. -/+theorem step_escape (r : Room) (out s b' more : List Nat) (e c : Nat)+ (hv : simpleEscape e = some c) (hm : out.length < r.max)+ (hc : r.dst = true → out.length + 1 < r.cap)+ (ih : readLoop r (out ++ [c]) (b' ++ more) = .ok (out ++ [c] ++ s, more.drop 1))+ : readLoop r out (([backslash, e] ++ b') ++ more) =+ .ok (out ++ c :: s, more.drop 1) := by+ simp only [List.cons_append, List.nil_append]+ rw [readLoop_escape r out _ e c hv, emit_ok r out c hm hc]+ simp only+ rw [ih]+ simp++/-- What `put_string_n()` writes, `parse_string()` reads back: the bytes+it was written from, and the bytes after the closing quote. -/+theorem loop_write (r : Room) (rest : List Nat) :+ ∀ (s b out : List Nat), writeBody s = some b →+ out.length + s.length ≤ r.max →+ (r.dst = true → out.length + s.length < r.cap) →+ readLoop r out (b ++ quote :: rest) = .ok (out ++ s, rest)+ | [], b, out, h, _, _ => by+ rw [write_nil, Option.some.injEq] at h+ subst h+ simp [readLoop_quote]+ | c :: s, b, out, h, hm, hc => by+ simp only [List.length_cons] at hm hc+ have room : out.length < r.max ∧ (r.dst = true → out.length + 1 < r.cap) :=+ ⟨by omega, fun h => by have := hc h; omega⟩+ have next : ∀ (v : Nat) (b' : List Nat), writeBody s = some b' →+ readLoop r (out ++ [v]) (b' ++ quote :: rest) =+ .ok (out ++ [v] ++ s, rest) := fun v b' hb' =>+ loop_write r rest s b' (out ++ [v]) hb' (by simp; omega)+ (fun h => by have := hc h; simp; omega)+ rw [writeBody_cons] at h+ by_cases h1 : c = quote ∨ c = backslash+ · rw [ite_eq_left h1] at h+ obtain ⟨b', hb', rfl⟩ := (option_map_some _ _ _).1 h+ have hv : simpleEscape c = some c := by+ rcases h1 with e | e <;> subst e <;> rfl+ have := step_escape r out s b' (quote :: rest) c c hv room.1 room.2+ (by rw [next c b' hb']; rfl)+ simpa using this+ rw [ite_eq_right h1] at h+ by_cases h2 : c = 0x0a+ · rw [ite_eq_left h2] at h+ obtain ⟨b', hb', rfl⟩ := (option_map_some _ _ _).1 h+ subst h2+ have := step_escape r out s b' (quote :: rest) 0x6e 0x0a rfl room.1 room.2+ (by rw [next 0x0a b' hb']; rfl)+ simpa using this+ rw [ite_eq_right h2] at h+ by_cases h3 : c = 0x0d+ · rw [ite_eq_left h3] at h+ obtain ⟨b', hb', rfl⟩ := (option_map_some _ _ _).1 h+ subst h3+ have := step_escape r out s b' (quote :: rest) 0x72 0x0d rfl room.1 room.2+ (by rw [next 0x0d b' hb']; rfl)+ simpa using this+ rw [ite_eq_right h3] at h+ by_cases h4 : c = 0x09+ · rw [ite_eq_left h4] at h+ obtain ⟨b', hb', rfl⟩ := (option_map_some _ _ _).1 h+ subst h4+ have := step_escape r out s b' (quote :: rest) 0x74 0x09 rfl room.1 room.2+ (by rw [next 0x09 b' hb']; rfl)+ simpa using this+ rw [ite_eq_right h4] at h+ by_cases h5 : c ≠ 0 ∧ c < 0x20+ · rw [ite_eq_left h5] at h+ obtain ⟨b', hb', rfl⟩ := (option_map_some _ _ _).1 h+ have hcp := uCodePoint_bmp _ _ _ _ (b' ++ quote :: rest) c+ (hex4_digits c (by omega)) h5.1 (by omega)+ have he : emitCp r out c = .ok (out ++ [c]) := by+ unfold emitCp utf8Emit+ rw [ite_eq_left (by omega), ite_eq_left (by omega)]+ exact emit_ok r out c room.1 room.2+ simp only [uEscape, List.cons_append, List.nil_append]+ rw [readLoop_u r out _ _ c hcp, he]+ simp only+ rw [next c b' hb']+ simp+ rw [ite_eq_right h5] at h+ by_cases h6 : c ≠ 0 ∧ c < 0x80+ · rw [ite_eq_left h6] at h+ obtain ⟨b', hb', rfl⟩ := (option_map_some _ _ _).1 h+ have hw : width ([c] ++ (b' ++ quote :: rest)) = [c].length :=+ width_ascii c _ (by omega)+ have := readLoop_raw r out [c] (b' ++ quote :: rest) (by simp)+ (by simp; omega) (by simp only [List.getD_cons_zero]; exact fun e => h1 (Or.inl e))+ (by simp only [List.getD_cons_zero]; exact fun e => h1 (Or.inr e)) hw+ rw [List.singleton_append] at this+ rw [List.cons_append, this, emitAll_ok r out [c] (by simp; omega)+ (fun h => by have := hc h; simp; omega)]+ simp only+ rw [next c b' hb']+ simp+ rw [ite_eq_right h6] at h+ have hc0 : c ≠ 0 := by+ intro e; subst e; simp at h+ simp only [ne_eq, hc0, not_false_eq_true, ite_true, width_take4] at h+ have hhigh : 0x80 ≤ c := by omega+ split at h+ · contradiction+ · next n hn =>+ obtain ⟨b', hb', rfl⟩ := (option_map_some _ _ _).1 h+ have hle := width_le (c :: s)+ have hn1 : n ≠ 0 := fun e => width_high c s hhigh (by rw [hn, e])+ have hlen : n ≤ s.length := by simp at hle; omega+ have hu := width_prefix (c :: s) (b' ++ quote :: rest) (by omega)+ rw [hn] at hu+ have := readLoop_raw r out ((c :: s).take (n + 1)) (b' ++ quote :: rest)+ (by simp) (by simp; omega) (by simp [quote]; omega)+ (by simp [backslash]; omega) (by rw [hu]; simp; omega)+ rw [List.append_assoc, this, emitAll_ok r out _ (by simp; omega)+ (fun h => by have := hc h; simp; omega)]+ simp only+ have hr : out ++ (c :: s).take (n + 1) ++ s.drop n = out ++ c :: s := by+ rw [List.append_assoc, List.take_succ_cons, List.cons_append,+ List.take_append_drop]+ rw [loop_write r rest (s.drop n) b' (out ++ (c :: s).take (n + 1)) hb'+ (by simp; omega) (fun h => by have := hc h; simp; omega), hr]+termination_by s => s.length+decreasing_by all_goals simp only [List.length_cons, List.length_drop]; omega++/-- For every byte string the strict writer takes, of every length, the+reader returns exactly it, and the bytes after the string, when it fits+`JSON_MAX_STRING_BYTES` and the buffer. -/+theorem read_write (r : Room) (s w rest : List Nat) (h : write s = some w)+ (hm : s.length ≤ r.max) (hc : r.dst = true → s.length < r.cap) :+ readString r (w ++ rest) = .ok (s, rest) := by+ obtain ⟨b, hb, rfl⟩ := (option_map_some _ _ _).1 h+ have hl := loop_write r rest s b [] hb (by simpa using hm) (by simpa using hc)+ simp only [List.cons_append, List.append_assoc]+ unfold readString+ simp only [ne_eq, not_true_eq_false, ite_false, List.nil_append] at hl ⊢+ rw [hl]+ simp only+ rw [ite_eq_right (fun h => by have := hc h.1; omega)]++/-! ### What the writer takes -/++theorem wellFormed_nil : wellFormed [] = true := by+ rw [wellFormed.eq_def]++theorem wellFormed_cons (c : Nat) (rest : List Nat) :+ wellFormed (c :: rest) =+ match width (c :: rest) with+ | 0 => false+ | n + 1 => wellFormed (rest.drop n) := by+ rw [wellFormed.eq_def]++theorem wellFormed_ascii (c : Nat) (rest : List Nat) (h : c ≤ 0x7f) :+ wellFormed (c :: rest) = wellFormed rest := by+ rw [wellFormed_cons, width_ascii c rest h]+ rfl++theorem mem_take_getD (l : List Nat) (k x : Nat) (h : x ∈ l.take k) :+ ∃ i, i < k ∧ i < l.length ∧ l.getD i 0 = x := by+ obtain ⟨i, hi, e⟩ := List.mem_iff_getElem.1 h+ simp only [List.length_take] at hi+ refine ⟨i, by omega, by omega, ?_⟩+ rw [List.getElem_take] at e+ simp [List.getD_eq_getElem?_getD, List.getElem?_eq_getElem (by omega : i < l.length), e]++/-- The bytes of a row of more than one byte hold no NUL. -/+theorem nul_not_mem_row (l : List Nat) (h : 2 ≤ width l) : 0 ∉ l.take (width l) := by+ intro m+ obtain ⟨i, hi, _, e⟩ := mem_take_getD l _ 0 m+ have := width_high_bytes l h i hi+ omega++theorem writeBody_small (c : Nat) (s : List Nat) (h0 : c ≠ 0) (h : c < 0x80) :+ (writeBody (c :: s)).isSome = (writeBody s).isSome := by+ rw [writeBody_cons]+ by_cases h1 : c = quote ∨ c = backslash+ · rw [ite_eq_left h1, Option.isSome_map]+ rw [ite_eq_right h1]+ by_cases h2 : c = 0x0a+ · rw [ite_eq_left h2, Option.isSome_map]+ rw [ite_eq_right h2]+ by_cases h3 : c = 0x0d+ · rw [ite_eq_left h3, Option.isSome_map]+ rw [ite_eq_right h3]+ by_cases h4 : c = 0x09+ · rw [ite_eq_left h4, Option.isSome_map]+ rw [ite_eq_right h4]+ by_cases h5 : c ≠ 0 ∧ c < 0x20+ · rw [ite_eq_left h5, Option.isSome_map]+ rw [ite_eq_right h5, ite_eq_left ⟨h0, h⟩, Option.isSome_map]++/-- Past the escapes and ASCII, the writer copies a row of Table 3-7, or+refuses a NUL or a byte that starts none. -/+theorem writeBody_high (c : Nat) (s : List Nat) (h : ¬ (c ≠ 0 ∧ c < 0x80)) :+ writeBody (c :: s) =+ match (if c ≠ 0 then width (c :: s) else 0) with+ | 0 => none+ | n + 1 => (writeBody (s.drop n)).map ((c :: s).take (n + 1) ++ ·) := by+ have hq : ¬ (c = quote ∨ c = backslash) := by unfold quote backslash; omega+ rw [writeBody_cons, ite_eq_right hq, ite_eq_right (by omega), ite_eq_right (by omega),+ ite_eq_right (by omega), ite_eq_right (by omega), ite_eq_right h, width_take4]++/-- The strict writer takes exactly the well-formed UTF-8 without NUL, and+refuses everything else with `-EILSEQ`. -/+theorem writeBody_isSome : ∀ s : List Nat,+ (writeBody s).isSome = true ↔ wellFormed s = true ∧ 0 ∉ s+ | [] => by simp [write_nil, wellFormed]+ | c :: s => by+ by_cases h0 : c = 0+ · subst h0+ rw [writeBody_high 0 s (by omega)]+ simp+ by_cases h : c < 0x80+ · rw [writeBody_small c s h0 h, writeBody_isSome s, wellFormed_ascii c s (by omega)]+ simp only [List.mem_cons, not_or]+ constructor+ · intro ⟨a, b⟩; exact ⟨a, fun e => h0 e.symm, b⟩+ · intro ⟨a, _, b⟩; exact ⟨a, b⟩+ · rw [writeBody_high c s (by omega), ite_eq_left h0, wellFormed_cons]+ split+ · simp+ · next n hn =>+ have hn1 : n ≠ 0 := fun e => width_high c s (by omega) (by rw [hn, e])+ rw [Option.isSome_map, writeBody_isSome (s.drop n)]+ have hsplit : c :: s = (c :: s).take (n + 1) ++ s.drop n := by+ rw [List.take_succ_cons, List.cons_append, List.take_append_drop]+ have hnul := nul_not_mem_row (c :: s) (by omega)+ rw [hn] at hnul+ constructor+ · intro ⟨a, b⟩+ refine ⟨a, ?_⟩+ rw [hsplit, List.mem_append]+ intro m; rcases m with m | m+ · exact hnul m+ · exact b m+ · intro ⟨a, b⟩+ refine ⟨a, fun m => b ?_⟩+ rw [hsplit, List.mem_append]; exact Or.inr m+termination_by s => s.length+decreasing_by all_goals simp only [List.length_cons, List.length_drop]; omega++/-- `put_string_n()` writes a string exactly when it is well-formed UTF-8+without NUL, and through `json_str()` a C string holds none. -/+theorem write_isSome (s : List Nat) :+ (write s).isSome = true ↔ wellFormed s = true ∧ 0 ∉ s := by+ rw [write, Option.isSome_map]+ exact writeBody_isSome s++/-! ### What the writer writes -/++/-- The characters of a string of ECMA-404, section 9, in UTF-8: a+sequence of Table 3-7 from U+0020 but `"` and `\`, an escape of one+letter, or `\u` and four hex digits. -/+inductive Chars : List Nat → Prop+ | nil : Chars []+ | char (u rest : List Nat) : u ≠ [] → width u = u.length →+ 0x20 ≤ u.getD 0 0 → u.getD 0 0 ≠ quote → u.getD 0 0 ≠ backslash →+ Chars rest → Chars (u ++ rest)+ | escape (e : Nat) (rest : List Nat) :+ e ∈ [0x22, 0x5c, 0x2f, 0x62, 0x66, 0x6e, 0x72, 0x74] →+ Chars rest → Chars (backslash :: e :: rest)+ | unicode (a b c d : Nat) (rest : List Nat) :+ Hex.isHex a = true → Hex.isHex b = true → Hex.isHex c = true →+ Hex.isHex d = true → Chars rest →+ Chars (backslash :: 0x75 :: a :: b :: c :: d :: rest)++theorem isHex_table (v : Nat) (h : v < 16) : Hex.isHex (table.getD v 0) = true := by+ unfold Hex.isHex+ rw [Hex.nibble_table v h]+ rfl++theorem writeBody_chars : ∀ (s b : List Nat), writeBody s = some b → Chars b+ | [], b, h => by+ rw [write_nil, Option.some.injEq] at h+ subst h; exact Chars.nil+ | c :: s, b, h => by+ rw [writeBody_cons] at h+ by_cases h1 : c = quote ∨ c = backslash+ · rw [ite_eq_left h1] at h+ obtain ⟨b', hb', rfl⟩ := (option_map_some _ _ _).1 h+ apply Chars.escape c b'+ · rcases h1 with e | e <;> subst e <;> simp [quote, backslash]+ · exact writeBody_chars s b' hb'+ rw [ite_eq_right h1] at h+ by_cases h2 : c = 0x0a+ · rw [ite_eq_left h2] at h+ obtain ⟨b', hb', rfl⟩ := (option_map_some _ _ _).1 h+ exact Chars.escape 0x6e b' (by simp) (writeBody_chars s b' hb')+ rw [ite_eq_right h2] at h+ by_cases h3 : c = 0x0d+ · rw [ite_eq_left h3] at h+ obtain ⟨b', hb', rfl⟩ := (option_map_some _ _ _).1 h+ exact Chars.escape 0x72 b' (by simp) (writeBody_chars s b' hb')+ rw [ite_eq_right h3] at h+ by_cases h4 : c = 0x09+ · rw [ite_eq_left h4] at h+ obtain ⟨b', hb', rfl⟩ := (option_map_some _ _ _).1 h+ exact Chars.escape 0x74 b' (by simp) (writeBody_chars s b' hb')+ rw [ite_eq_right h4] at h+ by_cases h5 : c ≠ 0 ∧ c < 0x20+ · rw [ite_eq_left h5] at h+ obtain ⟨b', hb', rfl⟩ := (option_map_some _ _ _).1 h+ exact Chars.unicode _ _ _ _ b' (isHex_table _ (Nat.mod_lt _ (by omega)))+ (isHex_table _ (Nat.mod_lt _ (by omega))) (isHex_table _ (Nat.mod_lt _ (by omega)))+ (isHex_table _ (Nat.mod_lt _ (by omega))) (writeBody_chars s b' hb')+ rw [ite_eq_right h5] at h+ by_cases h6 : c ≠ 0 ∧ c < 0x80+ · rw [ite_eq_left h6] at h+ obtain ⟨b', hb', rfl⟩ := (option_map_some _ _ _).1 h+ have := Chars.char [c] b' (by simp) (width_ascii c [] (by omega))+ (by simp; omega) (by simp only [List.getD_cons_zero]; exact fun e => h1 (Or.inl e))+ (by simp only [List.getD_cons_zero]; exact fun e => h1 (Or.inr e))+ (writeBody_chars s b' hb')+ simpa using this+ rw [ite_eq_right h6] at h+ have hc0 : c ≠ 0 := by+ intro e; subst e; simp at h+ rw [ite_eq_left hc0] at h+ split at h+ · contradiction+ · next n hn =>+ rw [width_take4] at hn+ obtain ⟨b', hb', rfl⟩ := (option_map_some _ _ _).1 h+ have hle := width_le (c :: s)+ rw [hn, List.length_cons] at hle+ have hu := width_prefix (c :: s) [] (by omega)+ rw [List.append_nil, hn] at hu+ have hl : ((c :: s).take (n + 1)).length = n + 1 := by+ rw [List.length_take, List.length_cons]; omega+ apply Chars.char _ b' (by simp) (by rw [hl]; exact hu) (by simp; omega)+ (by simp; unfold quote; omega) (by simp; unfold backslash; omega)+ exact writeBody_chars (s.drop n) b' hb'+termination_by s => s.length+decreasing_by all_goals simp only [List.length_cons, List.length_drop]; omega++/-- Every byte of the characters of a string is from 0x20: no control+byte, escaped or not. -/+theorem chars_no_control (b : List Nat) (h : Chars b) : ∀ x ∈ b, 0x20 ≤ x := by+ induction h with+ | nil => simp+ | char u rest hne hw h0 _ _ _ ih =>+ intro x hx+ rw [List.mem_append] at hx+ rcases hx with hx | hx+ · rw [← List.take_length (l := u)] at hx+ obtain ⟨i, hi, _, e⟩ := mem_take_getD u _ x hx+ subst e+ by_cases i0 : i = 0+ · subst i0; exact h0+ · have := width_high_bytes u (by omega) i (by omega)+ omega+ · exact ih x hx+ | escape e rest he _ ih =>+ intro x hx+ simp only [List.mem_cons] at hx+ rcases hx with hx | hx | hx+ · subst hx; simp [backslash]+ · subst hx; simp at he; omega+ · exact ih x hx+ | unicode a b c d rest ha hb hc hd _ ih =>+ have hex : ∀ y, Hex.isHex y = true → 0x20 ≤ y := by+ intro y hy+ unfold Hex.isHex Hex.nibble at hy+ split at hy+ · omega+ · split at hy+ · omega+ · split at hy+ · omega+ · simp at hy+ intro x hx+ simp only [List.mem_cons] at hx+ rcases hx with hx | hx | hx | hx | hx | hx | hx+ · subst hx; simp [backslash]+ · subst hx; omega+ · subst hx; exact hex _ ha+ · subst hx; exact hex _ hb+ · subst hx; exact hex _ hc+ · subst hx; exact hex _ hd+ · exact ih x hx++theorem isHex_ascii (y : Nat) (h : Hex.isHex y = true) : y ≤ 0x7f := by+ unfold Hex.isHex Hex.nibble at h+ split at h+ · omega+ · split at h+ · omega+ · split at h+ · omega+ · simp at h++/-- The characters of a string are well-formed UTF-8. -/+theorem chars_wellFormed (b : List Nat) (h : Chars b) : wellFormed b = true := by+ induction h with+ | nil => simp [wellFormed]+ | char u rest hne hw _ _ _ _ ih =>+ obtain ⟨ch, u', rfl⟩ : ∃ ch u', u = ch :: u' := by+ cases u with+ | nil => contradiction+ | cons ch u' => exact ⟨ch, u', rfl⟩+ have hp := width_prefix (ch :: u') rest (by rw [hw]; simp)+ rw [hw, List.take_length] at hp+ simp only [List.cons_append] at hp ⊢+ rw [wellFormed_cons, hp]+ simp only [List.length_cons]+ rw [List.drop_left]+ exact ih+ | escape e rest he _ ih =>+ rw [wellFormed_ascii _ _ (by simp [backslash]),+ wellFormed_ascii _ _ (by simp at he; omega)]+ exact ih+ | unicode a b c d rest ha hb hc hd _ ih =>+ rw [wellFormed_ascii _ _ (by simp [backslash]), wellFormed_ascii _ _ (by omega),+ wellFormed_ascii _ _ (isHex_ascii a ha), wellFormed_ascii _ _ (isHex_ascii b hb),+ wellFormed_ascii _ _ (isHex_ascii c hc), wellFormed_ascii _ _ (isHex_ascii d hd)]+ exact ih++/-- What `json_str()` writes is one string of ECMA-404 in well-formed+UTF-8: a quote, characters with no unescaped `"`, `\` or control byte,+and a quote. `read_write` adds that the reader ends it at the last quote. -/+theorem write_string (s w : List Nat) (h : write s = some w) :+ ∃ body, w = quote :: body ++ [quote] ∧ Chars body ∧+ (∀ x ∈ body, 0x20 ≤ x) ∧ wellFormed body = true := by+ obtain ⟨b, hb, rfl⟩ := (option_map_some _ _ _).1 h+ have hc := writeBody_chars s b hb+ exact ⟨b, rfl, hc, chars_no_control b hc, chars_wellFormed b hc⟩++/-! ### What the reader returns -/++theorem emit_eq (r : Room) (out out' : List Nat) (b : Nat)+ (h : emit r out b = .ok out') : out' = out ++ [b] := by+ unfold emit at h+ split at h+ · contradiction+ · split at h+ · contradiction+ · simp only [Except.ok.injEq] at h; exact h.symm++theorem emitAll_eq (r : Room) (u : List Nat) :+ ∀ out out', emitAll r out u = .ok out' → out' = out ++ u := by+ induction u with+ | nil => intro out out' h; simp only [emitAll, Except.ok.injEq] at h; simp [h]+ | cons b u ih =>+ intro out out' h+ simp only [emitAll] at h+ split at h+ · contradiction+ · next o he =>+ rw [ih o out' h, emit_eq r out o b he]+ simp++/-- A row of Table 3-7 is read as itself. -/+theorem wellFormed_row (u rest : List Nat) (hne : u ≠ []) (hw : width u = u.length) :+ wellFormed (u ++ rest) = wellFormed rest := by+ obtain ⟨ch, u', rfl⟩ : ∃ ch u', u = ch :: u' := by+ cases u with+ | nil => contradiction+ | cons ch u' => exact ⟨ch, u', rfl⟩+ have hp := width_prefix (ch :: u') rest (by rw [hw]; simp)+ rw [hw, List.take_length] at hp+ simp only [List.cons_append] at hp ⊢+ rw [wellFormed_cons, hp]+ simp only [List.length_cons]+ rw [List.drop_left]++/-- Well-formed UTF-8 followed by well-formed UTF-8 is well-formed. -/+theorem wellFormed_append : ∀ (a b : List Nat), wellFormed a = true →+ wellFormed b = true → wellFormed (a ++ b) = true+ | [], b, _, hb => hb+ | c :: rest, b, ha, hb => by+ rw [wellFormed_cons] at ha+ split at ha+ · contradiction+ · next n hn =>+ have hle := width_le (c :: rest)+ rw [hn] at hle+ have hrow : width ((c :: rest).take (n + 1)) = ((c :: rest).take (n + 1)).length := by+ have := width_prefix (c :: rest) [] (by omega)+ rw [List.append_nil, hn] at this+ rw [this, List.length_take]; simp at hle ⊢; omega+ have hsplit : (c :: rest) ++ b = (c :: rest).take (n + 1) ++ (rest.drop n ++ b) := by+ rw [List.take_succ_cons, List.cons_append, List.cons_append, ← List.append_assoc,+ List.take_append_drop]+ rw [hsplit, wellFormed_row _ _ (by simp) hrow]+ exact wellFormed_append (rest.drop n) b ha hb+termination_by a => a.length+decreasing_by simp only [List.length_cons, List.length_drop]; omega++theorem or_low (k x : Nat) (hk : k = 0x80 ∨ k = 0xc0 ∨ k = 0xe0 ∨ k = 0xf0)+ (hx : x < 0x100 - k) (h64 : x < 64) : k ||| x = k + x := by+ have h80 : ∀ y, y < 64 → 0x80 ||| y = 0x80 + y := by decide+ have hc0 : ∀ y, y < 64 → 0xc0 ||| y = 0xc0 + y := by decide+ have he0 : ∀ y, y < 32 → 0xe0 ||| y = 0xe0 + y := by decide+ have hf0 : ∀ y, y < 16 → 0xf0 ||| y = 0xf0 + y := by decide+ rcases hk with e | e | e | e <;> subst e+ · exact h80 x h64+ · exact hc0 x (by omega)+ · exact he0 x (by omega)+ · exact hf0 x (by omega)++theorem shr (x k : Nat) : x >>> k = x / 2 ^ k := Nat.shiftRight_eq_div_pow x k++theorem and3f (x : Nat) : x &&& 0x3f = x % 64 := by+ have := Nat.and_two_pow_sub_one_eq_mod x 6+ simpa using this++/-- The bytes `parse_string()` writes for a code point. -/+def cpBytes (cp : Nat) : List Nat :=+ if cp < 0x80 then [cp]+ else if cp < 0x800 then [0xc0 ||| (cp >>> 6), 0x80 ||| (cp &&& 0x3f)]+ else if cp < 0x10000 then+ [0xe0 ||| (cp >>> 12), 0x80 ||| ((cp >>> 6) &&& 0x3f), 0x80 ||| (cp &&& 0x3f)]+ else utf8Four cp++theorem emitCp_eq (r : Room) (out : List Nat) (cp : Nat) :+ emitCp r out cp = emitAll r out (cpBytes cp) := by+ unfold emitCp utf8Emit cpBytes+ by_cases h1 : cp < 0x80+ · simp only [h1, ite_true, (by omega : cp < 0x10000)]+ simp only [emitAll]+ cases emit r out cp <;> rfl+ · by_cases h2 : cp < 0x800+ · simp [h1, h2, (by omega : cp < 0x10000)]+ · by_cases h3 : cp < 0x10000+ · simp [h1, h2, h3]+ · simp [h1, h2, h3]++/-- A scalar value, not NUL, is written as a row of Table 3-7 without NUL. -/+theorem cpBytes_row (cp : Nat) (h0 : 0 < cp) (hmax : cp ≤ 0x10ffff)+ (hs : ¬ (0xd800 ≤ cp ∧ cp ≤ 0xdfff)) :+ cpBytes cp ≠ [] ∧ width (cpBytes cp) = (cpBytes cp).length ∧+ 0 ∉ cpBytes cp := by+ unfold cpBytes+ by_cases h1 : cp < 0x80+ · simp only [h1, ite_true]+ refine ⟨by simp, width_ascii cp [] (by omega), by simp; omega⟩+ by_cases h2 : cp < 0x800+ · simp only [h1, h2, ite_true, ite_false]+ rw [shr, and3f, or_low 0xc0 _ (by omega) (by simp; omega) (by simp; omega),+ or_low 0x80 _ (by omega) (by omega) (by omega)]+ refine ⟨by simp, ?_, by simp; omega⟩+ apply rowWidth_of_row2+ unfold Row2; simp; omega+ by_cases h3 : cp < 0x10000+ · simp only [h1, h2, h3, ite_true, ite_false]+ rw [shr, shr, and3f, and3f,+ or_low 0xe0 _ (by omega) (by simp; omega) (by simp; omega),+ or_low 0x80 (cp / 2 ^ 6 % 64) (by omega) (by omega) (by omega),+ or_low 0x80 (cp % 64) (by omega) (by omega) (by omega)]+ refine ⟨by simp, ?_, by simp; omega⟩+ apply rowWidth_of_row3+ unfold Row3; simp; omega+ · simp only [h1, h2, h3, ite_false, utf8Four]+ rw [shr, shr, shr, and3f, and3f, and3f,+ or_low 0xf0 _ (by omega) (by simp; omega) (by simp; omega),+ or_low 0x80 (cp / 2 ^ 12 % 64) (by omega) (by omega) (by omega),+ or_low 0x80 (cp / 2 ^ 6 % 64) (by omega) (by omega) (by omega),+ or_low 0x80 (cp % 64) (by omega) (by omega) (by omega)]+ refine ⟨by simp, ?_, by simp; omega⟩+ apply rowWidth_of_row4+ unfold Row4; simp; omega++theorem hex4_lt (a b c d v : Nat) (h : hex4 [a, b, c, d] = some v) : v < 0x10000 := by+ simp only [hex4, List.foldl_cons, List.foldl_nil] at h+ cases ha : nibble a <;> cases hb : nibble b <;> cases hc : nibble c <;>+ cases hd : nibble d <;> simp only [ha, hb, hc, hd] at h <;> try contradiction+ next x y z w =>+ simp only [Option.some.injEq] at h+ have := Hex.nibble_lt a x ha+ have := Hex.nibble_lt b y hb+ have := Hex.nibble_lt c z hc+ have := Hex.nibble_lt d w hd+ rw [shl4_or _ _ (by omega), shl4_or _ _ (by omega), shl4_or _ _ (by omega),+ shl4_or _ _ (by omega)] at h+ omega++/-- A `\u` escape stands for a scalar value other than NUL. -/+theorem uCodePoint_scalar (s rest : List Nat) (cp : Nat)+ (h : uCodePoint s = .ok (cp, rest)) :+ 0 < cp ∧ cp ≤ 0x10ffff ∧ ¬ (0xd800 ≤ cp ∧ cp ≤ 0xdfff) := by+ unfold uCodePoint at h+ split at h+ · split at h+ · contradiction+ · next a b c d _ _ hi hhex =>+ have hlt := hex4_lt a b c d hi hhex+ split at h+ · contradiction+ · next hne =>+ split at h+ · next hhi =>+ split at h+ · split at h+ · contradiction+ · split at h+ · contradiction+ · next a' b' c' d' _ _ lo hlo =>+ split at h+ · next hlor =>+ simp only [Except.ok.injEq, Prod.mk.injEq] at h+ rw [← h.1, Nat.shiftLeft_eq]+ have : hi - 0xd800 < 1024 := by omega+ refine ⟨by omega, ?_, by omega⟩+ have : (hi - 0xd800) * 2 ^ 10 ≤ 1023 * 1024 := by+ have := Nat.mul_le_mul_right (2 ^ 10) (by omega : hi - 0xd800 ≤ 1023)+ simpa using this+ omega+ · contradiction+ · contradiction+ · split at h+ · contradiction+ · simp only [Except.ok.injEq, Prod.mk.injEq] at h+ rw [← h.1]+ omega+ · contradiction++theorem simpleEscape_ascii (e v : Nat) (h : simpleEscape e = some v) :+ 0 < v ∧ v ≤ 0x7f := by+ unfold simpleEscape at h+ repeat (split at h; · simp only [Option.some.injEq] at h; omega)+ contradiction++/-- What the loop of `parse_string()` adds to well-formed UTF-8 without NUL+keeps it so. -/+theorem readLoop_wf (r : Room) : ∀ (s out out' rest : List Nat),+ readLoop r out s = .ok (out', rest) → wellFormed out = true → 0 ∉ out →+ wellFormed out' = true ∧ 0 ∉ out'+ | [], _, _, _, h, _, _ => by rw [readLoop.eq_def] at h; contradiction+ | ch :: s, out, out', rest, h, hw, hn => by+ rw [readLoop.eq_def] at h+ simp only at h+ split at h+ · simp only [Except.ok.injEq, Prod.mk.injEq] at h+ rw [← h.1]; exact ⟨hw, hn⟩+ · split at h+ · cases hs : s with+ | nil => rw [hs] at h; simp only at h; contradiction+ | cons e rest' =>+ have hlt : rest'.length < s.length := by rw [hs]; simp+ rw [hs] at h+ simp only at h+ split at h+ · next v hv =>+ split at h+ · contradiction+ · next o ho =>+ have ⟨hv0, hv7⟩ := simpleEscape_ascii e v hv+ rw [emit_eq r out o v ho] at h+ refine readLoop_wf r rest' _ out' rest h ?_ ?_+ · exact wellFormed_append _ _ hw+ (by rw [wellFormed_ascii v [] hv7, wellFormed_nil])+ · simp only [List.mem_append, List.mem_singleton, not_or]+ exact ⟨hn, by omega⟩+ · split at h+ · contradiction+ · split at h+ · contradiction+ · next cp rest'' hu =>+ split at h+ · contradiction+ · next o ho =>+ have ⟨h0, hmax, hs⟩ := uCodePoint_scalar rest' rest'' cp hu+ have ⟨hne, hrow, hnul⟩ := cpBytes_row cp h0 hmax hs+ rw [emitCp_eq] at ho+ rw [emitAll_eq r _ out o ho] at h+ have := uCodePoint_shorter rest' rest'' cp hu+ refine readLoop_wf r rest'' _ out' rest h ?_ ?_+ · exact wellFormed_append _ _ hw+ (by have := wellFormed_row _ [] hne hrow+ rw [List.append_nil] at this; rw [this, wellFormed_nil])+ · simp only [List.mem_append, not_or]; exact ⟨hn, hnul⟩+ · split at h+ · contradiction+ · next hb hc =>+ split at h+ · contradiction+ · next n hwn =>+ split at h+ · contradiction+ · next o ho =>+ rw [emitAll_eq r _ out o ho] at h+ have hle := width_le (ch :: s)+ rw [hwn] at hle+ have hrow : width ((ch :: s).take (n + 1)) =+ ((ch :: s).take (n + 1)).length := by+ have := width_prefix (ch :: s) [] (by omega)+ rw [List.append_nil, hwn] at this+ rw [this, List.length_take]; simp at hle ⊢; omega+ have hnul : 0 ∉ (ch :: s).take (n + 1) := by+ by_cases hn0 : n = 0+ · subst hn0; simp; omega+ · have := nul_not_mem_row (ch :: s) (by omega)+ rwa [hwn] at this+ refine readLoop_wf r (s.drop n) _ out' rest h ?_ ?_+ · exact wellFormed_append _ _ hw+ (by have := wellFormed_row _ [] (by simp) hrow+ rw [List.append_nil] at this; rw [this, wellFormed_nil])+ · simp only [List.mem_append, not_or]; exact ⟨hn, hnul⟩+termination_by s => s.length+decreasing_by+ all_goals simp only [List.length_cons, List.length_drop]+ all_goals omega++/-- Whatever `parse_string()` returns, from any input, is well-formed+UTF-8 without NUL: no escape can smuggle in a NUL that would cut the C+string short, or a lone surrogate or other ill-formed byte. -/+theorem readString_wf (r : Room) (s out rest : List Nat)+ (h : readString r s = .ok (out, rest)) :+ wellFormed out = true ∧ 0 ∉ out := by+ unfold readString at h+ split at h+ · contradiction+ · split at h+ · contradiction+ · split at h+ · contradiction+ · next o rest' hl =>+ split at h+ · contradiction+ · simp only [Except.ok.injEq, Prod.mk.injEq] at h+ rw [← h.1]+ exact readLoop_wf r _ [] o rest' hl wellFormed_nil (by simp)++end Shirudo.JsonStringdiff --git a/testing/proofs/lean4/Shirudo/PinName.lean b/testing/proofs/lean4/Shirudo/PinName.leannew file mode 100644index 00000000..44736c3f--- /dev/null+++ b/testing/proofs/lean4/Shirudo/PinName.lean@@ -0,0 +1,342 @@+-- SPDX-License-Identifier: BSD-2-Clause+-- Copyright (c) 2026 Authors of shirudo++/-!+The pin name codec of util/paths.h. bpffs refuses a dot in a path+component and an upatch name may carry one, so `upatch_bpffs_name()`+writes each `.` of a name as `~d` and every other byte as itself, and+`upatch_name_from_bpffs()` turns each `~d` back into a dot and refuses a+`~` before any other byte or the end. No valid upatch name holds a `~`.++For names of every length: the decoding of the encoding of a name without+`~` is that name, an encoding holds no dot, two names without `~` never+share an encoding, so no two upatches share a pin, and a pin name without+a dot that decodes is the encoding of the name it decodes to, which holds+no `~`. The codec is thus a bijection between the names without `~` and+the pin names without a dot that decode.++`encode` and `decode` are the loops of the two functions, and `bpffsName`+and `nameFromBpffs` the functions with their buffer: the first refuses an+`out_sz` below twice the length and one before it writes, as the C does,+and the second each byte that would leave no room for the NUL. A string is+its bytes before the NUL, each byte its value. A C string is shorter than+2^63 bytes, so the C's `len * 2 + 1` does not wrap and is the model's.+testing/proofs/cbmc/paths-bpffs-name-model.c checks the C against the+model on every string of up to 8 bytes and every buffer size up to 18.+-/++namespace Shirudo.PinName++/-- `.`, which bpffs refuses in a path component. -/+def dot : Nat := 0x2e++/-- `~`, which no upatch name holds. -/+def tilde : Nat := 0x7e++/-- `d`, which follows the `~` that stands for a dot. -/+def letterD : Nat := 0x64++/-- What the loop of `upatch_bpffs_name()` writes for one byte. -/+def encodeByte (c : Nat) : List Nat :=+ if c = dot then [tilde, letterD] else [c]++/-- The loop of `upatch_bpffs_name()`: each dot becomes `~d`. -/+def encode (name : List Nat) : List Nat :=+ name.flatMap encodeByte++/-- The loop of `upatch_name_from_bpffs()` with room enough: `~d` becomes a+dot, and `~` before any other byte or the end is refused, as `none`. -/+def decode : List Nat → Option (List Nat)+ | [] => some []+ | c :: rest =>+ if c = tilde then+ match rest with+ | d :: rest' => if d = letterD then (decode rest').map (dot :: ·) else none+ | [] => none+ else (decode rest).map (c :: ·)++/-- `-EINVAL` and `-ENAMETOOLONG`. -/+inductive Err where+ | inval+ | nameTooLong+ deriving DecidableEq, Repr++/-- `upatch_bpffs_name(out, out_sz, name)`: `-EINVAL` for no buffer,+`-ENAMETOOLONG` when `out_sz` is below twice the length and one, and the+encoding otherwise. -/+def bpffsName (outSz : Nat) (name : List Nat) : Except Err (List Nat) :=+ if outSz = 0 then .error .inval+ else if name.length * 2 + 1 > outSz then .error .nameTooLong+ else .ok (encode name)++/-- The loop of `upatch_name_from_bpffs()` with `j` bytes written: a `~`+before anything but `d` is `-EINVAL`, and a byte that leaves no room for+the NUL `-ENAMETOOLONG`, whichever comes first. -/+def fromLoop (outSz j : Nat) : List Nat → Except Err (List Nat)+ | [] => .ok []+ | c :: rest =>+ if c = tilde then+ match rest with+ | d :: rest' =>+ if d = letterD then+ if j + 1 ≥ outSz then .error .nameTooLong+ else (fromLoop outSz (j + 1) rest').map (dot :: ·)+ else .error .inval+ | [] => .error .inval+ else if j + 1 ≥ outSz then .error .nameTooLong+ else (fromLoop outSz (j + 1) rest).map (c :: ·)++/-- `upatch_name_from_bpffs(out, out_sz, name)`. -/+def nameFromBpffs (outSz : Nat) (name : List Nat) : Except Err (List Nat) :=+ if outSz = 0 then .error .inval else fromLoop outSz 0 name++/-! ### The codec -/++theorem encode_cons (c : Nat) (cs : List Nat) :+ encode (c :: cs) = encodeByte c ++ encode cs := by+ simp [encode]++theorem decode_tilde_d (rest : List Nat) :+ decode (tilde :: letterD :: rest) = (decode rest).map (dot :: ·) := by+ simp [decode]++theorem decode_other (c : Nat) (rest : List Nat) (h : c ≠ tilde) :+ decode (c :: rest) = (decode rest).map (c :: ·) := by+ rw [decode.eq_def]+ simp only [h, ite_false]++/-- Decoding the encoding of a name without `~` gives the name back. -/+theorem decode_encode (name : List Nat) (h : tilde ∉ name) :+ decode (encode name) = some name := by+ induction name with+ | nil => rfl+ | cons c cs ih =>+ have hc : c ≠ tilde := fun e => h (e ▸ List.mem_cons_self)+ have hcs : tilde ∉ cs := fun m => h (List.mem_cons_of_mem c m)+ rw [encode_cons]+ by_cases hd : c = dot+ · simp only [encodeByte, hd, ite_true, List.cons_append, List.nil_append]+ rw [decode_tilde_d, ih hcs]+ rfl+ · simp only [encodeByte, hd, ite_false, List.cons_append, List.nil_append]+ rw [decode_other c _ hc, ih hcs]+ rfl++/-- An encoding holds no dot, which bpffs would refuse. -/+theorem dot_not_mem_encode (name : List Nat) : dot ∉ encode name := by+ induction name with+ | nil => simp [encode]+ | cons c cs ih =>+ rw [encode_cons, List.mem_append]+ intro hm+ rcases hm with hm | hm+ · by_cases hd : c = dot+ · simp [encodeByte, hd, dot, tilde, letterD] at hm+ · simp only [encodeByte, hd, ite_false, List.mem_singleton] at hm+ exact hd hm.symm+ · exact ih hm++/-- An encoding holds a NUL only where the name does: the C writes a+string that ends where the name's encoding does. -/+theorem nul_not_mem_encode (name : List Nat) (h : 0 ∉ name) :+ 0 ∉ encode name := by+ induction name with+ | nil => simp [encode]+ | cons c cs ih =>+ have hc : c ≠ 0 := fun e => h (e ▸ List.mem_cons_self)+ rw [encode_cons, List.mem_append]+ intro hm+ rcases hm with hm | hm+ · by_cases hd : c = dot+ · simp [encodeByte, hd, tilde, letterD] at hm+ · simp only [encodeByte, hd, ite_false, List.mem_singleton] at hm+ exact hc hm.symm+ · exact ih (fun m => h (List.mem_cons_of_mem c m)) hm++/-- Two names without `~` have the same encoding only when they are the+same name: no two upatches share a pin. -/+theorem encode_injective (a b : List Nat) (ha : tilde ∉ a) (hb : tilde ∉ b)+ (h : encode a = encode b) : a = b := by+ have e := decode_encode a ha+ rw [h, decode_encode b hb] at e+ exact (Option.some.inj e).symm++/-- What a pin name decodes to holds no `~`, so it is an upatch name the+codec covers. -/+theorem tilde_not_mem_decode : ∀ (p n : List Nat), decode p = some n → tilde ∉ n+ | [], n, h => by+ simp only [decode, Option.some.injEq] at h+ subst h; simp+ | c :: rest, n, h => by+ by_cases hc : c = tilde+ · cases rest with+ | nil => simp [decode, hc] at h+ | cons d rest' =>+ by_cases hd : d = letterD+ · subst hc hd+ rw [decode_tilde_d] at h+ cases hr : decode rest' with+ | none => simp [hr] at h+ | some m =>+ simp only [hr, Option.map_some, Option.some.injEq] at h+ subst h+ have := tilde_not_mem_decode rest' m hr+ simp only [List.mem_cons, not_or]+ exact ⟨by decide, this⟩+ · simp [decode, hc, hd] at h+ · rw [decode_other c rest hc] at h+ cases hr : decode rest with+ | none => simp [hr] at h+ | some m =>+ simp only [hr, Option.map_some, Option.some.injEq] at h+ subst h+ have := tilde_not_mem_decode rest m hr+ simp only [List.mem_cons, not_or]+ exact ⟨fun e => hc e.symm, this⟩++/-- A pin name without a dot that decodes is the encoding of the name it+decodes to. -/+theorem encode_decode : ∀ (p n : List Nat), dot ∉ p → decode p = some n →+ encode n = p+ | [], n, _, h => by+ simp only [decode, Option.some.injEq] at h+ subst h; rfl+ | c :: rest, n, hp, h => by+ have hc : c ≠ dot := fun e => hp (e ▸ List.mem_cons_self)+ by_cases ht : c = tilde+ · cases rest with+ | nil => simp [decode, ht] at h+ | cons d rest' =>+ by_cases hd : d = letterD+ · subst ht hd+ rw [decode_tilde_d] at h+ cases hr : decode rest' with+ | none => simp [hr] at h+ | some m =>+ simp only [hr, Option.map_some, Option.some.injEq] at h+ subst h+ have hp' : dot ∉ rest' := fun m' =>+ hp (List.mem_cons_of_mem _ (List.mem_cons_of_mem _ m'))+ rw [encode_cons, encode_decode rest' m hp' hr]+ rfl+ · simp [decode, ht, hd] at h+ · rw [decode_other c rest ht] at h+ cases hr : decode rest with+ | none => simp [hr] at h+ | some m =>+ simp only [hr, Option.map_some, Option.some.injEq] at h+ subst h+ have hp' : dot ∉ rest := fun m' => hp (List.mem_cons_of_mem _ m')+ rw [encode_cons, encode_decode rest m hp' hr]+ simp [encodeByte, hc]++/-! ### The functions with their buffer -/++theorem length_encode_le (name : List Nat) :+ (encode name).length ≤ 2 * name.length := by+ induction name with+ | nil => simp [encode]+ | cons c cs ih =>+ rw [encode_cons, List.length_append]+ by_cases hd : c = dot <;> simp [encodeByte, hd] <;> omega++/-- `upatch_bpffs_name()` writes the encoding exactly when `out_sz` holds+twice the length and its NUL, and the encoding with its NUL fits `out_sz`. -/+theorem bpffsName_ok (outSz : Nat) (name p : List Nat) :+ bpffsName outSz name = .ok p ↔+ 0 < outSz ∧ 2 * name.length + 1 ≤ outSz ∧ p = encode name := by+ unfold bpffsName+ by_cases h0 : outSz = 0+ · simp [h0]+ · by_cases h1 : name.length * 2 + 1 > outSz+ · simp only [h0, h1, ite_false, ite_true, reduceCtorEq, false_iff]+ omega+ · simp only [h0, h1, ite_false, Except.ok.injEq]+ constructor+ · intro e; exact ⟨by omega, by omega, e.symm⟩+ · intro ⟨_, _, e⟩; exact e.symm++theorem except_map_ok {α β ε : Type} (f : α → β) (x : Except ε α) (b : β) :+ x.map f = .ok b ↔ ∃ a, x = .ok a ∧ f a = b := by+ cases x <;> simp [Except.map]++theorem option_map_some {α β : Type} (f : α → β) (x : Option α) (b : β) :+ x.map f = some b ↔ ∃ a, x = some a ∧ f a = b := by+ cases x <;> simp++/-- With `j` bytes written and room for the NUL, the loop of+`upatch_name_from_bpffs()` yields the decoding exactly when it fits+`out_sz` with its NUL. -/+theorem fromLoop_ok : ∀ (outSz j : Nat) (p n : List Nat), j < outSz →+ (fromLoop outSz j p = .ok n ↔ decode p = some n ∧ j + n.length < outSz)+ | outSz, j, [], n, hj => by+ simp only [fromLoop, Except.ok.injEq, decode, Option.some.injEq]+ constructor+ · intro e; subst e; simpa using hj+ · intro ⟨e, _⟩; exact e+ | outSz, j, c :: rest, n, hj => by+ by_cases ht : c = tilde+ · cases rest with+ | nil => simp [fromLoop, decode, ht]+ | cons d rest' =>+ by_cases hd : d = letterD+ · subst ht hd+ rw [decode_tilde_d, option_map_some]+ by_cases hroom : j + 1 ≥ outSz+ · simp only [fromLoop, ite_true, hroom, reduceCtorEq, false_iff]+ intro ⟨⟨m, _, e⟩, hl⟩+ subst e+ simp at hl+ omega+ · simp only [fromLoop, ite_true, hroom, ite_false, except_map_ok]+ constructor+ · intro ⟨m, hm, e⟩+ have := (fromLoop_ok outSz (j + 1) rest' m (by omega)).1 hm+ subst e+ exact ⟨⟨m, this.1, rfl⟩, by simp; omega⟩+ · intro ⟨⟨m, hm, e⟩, hl⟩+ subst e+ simp at hl+ exact ⟨m, (fromLoop_ok outSz (j + 1) rest' m (by omega)).2+ ⟨hm, by omega⟩, rfl⟩+ · simp [fromLoop, decode, ht, hd]+ · rw [decode_other c rest ht, option_map_some, fromLoop.eq_def]+ by_cases hroom : j + 1 ≥ outSz+ · simp only [ht, ite_false, hroom, ite_true, reduceCtorEq, false_iff]+ intro ⟨⟨m, _, e⟩, hl⟩+ subst e+ simp at hl+ omega+ · simp only [ht, hroom, ite_false, except_map_ok]+ constructor+ · intro ⟨m, hm, e⟩+ have := (fromLoop_ok outSz (j + 1) rest m (by omega)).1 hm+ subst e+ exact ⟨⟨m, this.1, rfl⟩, by simp; omega⟩+ · intro ⟨⟨m, hm, e⟩, hl⟩+ subst e+ simp at hl+ exact ⟨m, (fromLoop_ok outSz (j + 1) rest m (by omega)).2+ ⟨hm, by omega⟩, rfl⟩++/-- `upatch_name_from_bpffs()` yields a name exactly when the pin name+decodes to it and it fits `out_sz` with its NUL. -/+theorem nameFromBpffs_ok (outSz : Nat) (p n : List Nat) :+ nameFromBpffs outSz p = .ok n ↔ decode p = some n ∧ n.length < outSz := by+ unfold nameFromBpffs+ by_cases h0 : outSz = 0+ · simp [h0]+ · simp only [h0, ite_false]+ rw [fromLoop_ok outSz 0 p n (by omega), Nat.zero_add]++/-- Through the C with its buffers: a name without `~` that+`upatch_bpffs_name()` encodes, `upatch_name_from_bpffs()` turns back into+the name, given room for it and its NUL. -/+theorem pin_round_trip (outSz backSz : Nat) (name p : List Nat)+ (h : tilde ∉ name) (he : bpffsName outSz name = .ok p)+ (hb : name.length < backSz) : nameFromBpffs backSz p = .ok name := by+ have ⟨_, _, e⟩ := (bpffsName_ok outSz name p).1 he+ subst e+ exact (nameFromBpffs_ok backSz _ name).2 ⟨decode_encode name h, hb⟩++end Shirudo.PinName