From 97a299633caf9a70f0e5e47bfbc074a1c68d4f8d Mon Sep 17 00:00:00 2001 From: minelogy <72928567+minelogy-dev@users.noreply.github.com> Date: Mon, 2 Nov 2026 12:17:01 -0800 Subject: [PATCH 1/2] fix: reject overflowing write ranges before reserve and copy Validate idx + input length before pointer arithmetic, including the view path's pre-reserve. Preserve owned-input consumption and valid binary/aliased writes. Add sanitizer regressions and a focused same-host cross-library cost check with baseline failure reproduction. Co-authored-by: Codex --- .github/scripts/check-write-safety.py | 202 ++++++++++++++++++++++++++ .github/workflows/write-safety.yml | 80 ++++++++++ docs/WRITE_SAFETY.md | 42 ++++++ include/sx_core.h | 5 +- src/sx_core.c | 12 +- tests/write_overflow.c | 13 ++ tests/write_overflow_cases.h | 94 ++++++++++++ tests/write_overflow_exact.c | 14 ++ 8 files changed, 458 insertions(+), 4 deletions(-) create mode 100644 .github/scripts/check-write-safety.py create mode 100644 .github/workflows/write-safety.yml create mode 100644 docs/WRITE_SAFETY.md create mode 100644 tests/write_overflow.c create mode 100644 tests/write_overflow_cases.h create mode 100644 tests/write_overflow_exact.c diff --git a/.github/scripts/check-write-safety.py b/.github/scripts/check-write-safety.py new file mode 100644 index 0000000..6f601f2 --- /dev/null +++ b/.github/scripts/check-write-safety.py @@ -0,0 +1,202 @@ +#!/usr/bin/env python3 +"""Reproduce the write overflow, then compare guarded writes on one runner.""" +import argparse +import csv +import hashlib +import importlib.util +import json +import os +from pathlib import Path +import re +import statistics +import subprocess + +ROOT = Path(__file__).resolve().parents[2] +BASELINE = "452314a7ca51f90a7a8fa66930947164af8fc4f6" +HARNESS = "7f8a624af4809c9dc606c41533991acd1b51917d" +PINS = {"sds": "5347739b1581fcba74fd5cab1fc21d2aef317d71", + "bstrlib": "f0ff1e808102a42cdc7204a4bb6fe231a24c4546"} + +def main(): + parser = argparse.ArgumentParser() + parser.add_argument("--before", type=Path, required=True) + parser.add_argument("--harness", type=Path, required=True) + parser.add_argument("--deps", type=Path, required=True) + parser.add_argument("--out", type=Path, required=True) + args = parser.parse_args() + before, harness, deps, out = [p.resolve() for p in + (args.before, args.harness, args.deps, args.out)] + out.mkdir(parents=True, exist_ok=True) + spec = importlib.util.spec_from_file_location("audited_bench", harness / "benchmarks/recheck.py") + bench = importlib.util.module_from_spec(spec) + spec.loader.exec_module(bench) + assert bench.capture(["git", "rev-parse", "HEAD"], before) == BASELINE + assert bench.capture(["git", "rev-parse", "HEAD"], harness) == HARNESS + for lib, sha in PINS.items(): + assert bench.capture(["git", "rev-parse", "HEAD"], deps / lib) == sha + + generated = out / "harness" / "benchmarks" + generated.mkdir(parents=True, exist_ok=True) + header = (harness / "benchmarks/recheck.h").read_text() + (generated / "recheck.h").write_text(header) + code = (harness / "benchmarks/recheck.c").read_text() + start = code.index("/* Independent byte-window oracle") + end = code.index("static uint64_t prepare", start) + code = code[:start] + code[end:] + anchor = "uint64_t expected = reference(h, c->n, f->pattern, c->m);" + assert code.count(anchor) == 1 + code = code.replace(anchor, "uint64_t expected = 1; /* success; bytes checked separately */") + code = code.replace('"SDS+glibc"', '"SDS"').replace('"raw_glibc_same_buffer"', '"raw_memcpy_same_buffer"') + code = code.replace("expected_pos", "expected_result").replace("(long long)expected-1", "(long long)expected") + anchor = " (void)cold_once(workers[lib], &f, lib, expected);" + assert code.count(anchor) == 1 + code = code.replace(anchor, anchor + "\n CHECK(memcmp(f.text_bytes[lib], f.pattern_bytes[lib], f.n) == 0);") + anchor = " sample,it,elapsed,(double)elapsed/(double)it);" + assert code.count(anchor) == 1 + code = code.replace(anchor, anchor + "\n CHECK(memcmp(f.text_bytes[lib], f.pattern_bytes[lib], f.n) == 0);") + (generated / "recheck.c").write_text(code) + adapters = r'''// SPDX-License-Identifier: MIT +#define _GNU_SOURCE +#include "recheck.h" +#include +#ifdef RECHECK_VERIFY_CALLS +#define RECORD() (++recheck_call_counts[LIB_INDEX]) +#else +#define RECORD() ((void)0) +#endif +#if LIB_INDEX == 0 +__attribute__((noinline)) uint64_t recheck_sx(recheck_input *f) { + RECORD(); + return sx_write_view(f->sx, 0, sx_view(f->sx_pattern)) == f->sx; +} +#elif LIB_INDEX == 1 +__attribute__((noinline)) uint64_t recheck_sds(recheck_input *f) { + RECORD(); + sds result = sdscpylen(f->sd, f->pattern, f->m); + if (!result) return 0; + f->sd = result; + return 1; +} +#elif LIB_INDEX == 2 +__attribute__((noinline)) uint64_t recheck_bstr(recheck_input *f) { + RECORD(); + return bassignblk(f->bs, f->bs_pattern->data, (int)f->m) == BSTR_OK; +} +#elif LIB_INDEX == 3 +__attribute__((noinline)) uint64_t recheck_raw(recheck_input *f) { + RECORD(); + memcpy(f->sd, f->pattern, f->m); + return 1; +} +#endif +''' + (generated / "recheck_adapter.c").write_text(adapters) + sizes = (8, 64, 4096, 65536) + (out / "recheck_cases.h").write_text( + "static const Case cases[] = {\n" + "".join( + f' {{"write{n}", 5, {n}, {n}, 0, 0, UINT32_C(40581213), 0}},\n' + for n in sizes) + "};\n") + bench.ROOT = generated.parent + cpu = min(os.sched_getaffinity(0)) + after_sha = bench.capture(["git", "rev-parse", "HEAD"], ROOT) + env = os.environ.copy() + env.update(ASAN_OPTIONS="detect_leaks=1:halt_on_error=1", + UBSAN_OPTIONS="halt_on_error=1:print_stacktrace=1") + metadata = dict(before=BASELINE, after=after_sha, harness=HARNESS, dependencies=PINS, + cpu=cpu, lscpu=json.loads(bench.capture(["lscpu", "-J"])), + libc=bench.capture(["ldd", "--version"]).splitlines()[0], + flags=bench.COMMON + ["-O3", "-DNDEBUG"], sizes=sizes, + processes=3, samples_per_process=7, + contract="Overwrite an existing equal-sized binary string in place; setup excluded. Exact bytes checked outside timing. Flushed mode flushes source and target, excludes flush cost.", + source_hashes={name: hashlib.sha256((generated / name).read_bytes()).hexdigest() + for name in ("recheck.c", "recheck.h", "recheck_adapter.c")}) + for variant, source in (("before", before), ("after", ROOT)): + metadata[variant + "_core_sha256"] = hashlib.sha256((source / "src/sx_core.c").read_bytes()).hexdigest() + (out / "environment.json").write_text(json.dumps(metadata, indent=2) + "\n") + print("WRITE_ENV_JSON=" + json.dumps(metadata), flush=True) + report = ["# Write overflow safety and cost", "", + "Same job/CPU; binary overwrites, no allocation in timed writes; three fresh processes.", + "Flushed samples average eight individually flushed calls; flush cost excluded.", + "Source/target bytes are checked outside timing. Small differences on a shared runner are inconclusive.", ""] + for cc in ("clang-19", "gcc-14"): + folder = out / cc + folder.mkdir(parents=True, exist_ok=True) + log = folder / "commands.log" + version = bench.capture([cc, "--version"]) + (folder / "compiler.txt").write_text(version + "\n") + flags = ["-std=c23", "-O1", "-g", "-fsanitize=address,undefined", + "-fno-sanitize-recover=all", "-fno-omit-frame-pointer", + "-DSX_WRITE_OVERFLOW_STANDALONE"] + def regression(source, target, exact=False): + bench.run([cc, *flags, *(["-DSX_FORCE_EXACT_RESERVE"] if exact else []), + "-isystem", source / "include", ROOT / "tests/write_overflow.c", + source / "src/sx_core.c", source / "src/sx_raw.c", "-o", target], log) + old = folder / "old-overflow" + regression(before, old) + failed = subprocess.run([str(old)], cwd=ROOT, env=env, text=True, capture_output=True) + (folder / "baseline-overflow.log").write_text(failed.stdout + failed.stderr) + assert failed.returncode != 0 + assert re.search(r"AddressSanitizer|UndefinedBehaviorSanitizer|runtime error:", failed.stderr) + for exact in (False, True): + target = folder / ("fixed-exact" if exact else "fixed-default") + regression(ROOT, target, exact) + bench.run([target], log, cpu=cpu, env=env) + print("WRITE_REPRO_JSON=" + json.dumps(dict(compiler=cc, + baseline_exit=failed.returncode, baseline_sanitizer_failure=True, + fixed_default_pass=True, fixed_exact_pass=True)), flush=True) + results = {} + for variant in (("before", "after") if cc == "clang-19" else ("after", "before")): + source = before if variant == "before" else ROOT + dest = folder / variant + dest.mkdir(parents=True, exist_ok=True) + verify = bench.build(cc, dest / "verify", "verify", source, deps, out, log) + bench.run([verify, "--verify"], log, cpu=cpu, env=env) + binary = bench.build(cc, dest / "release", "release", source, deps, out, log) + assembly = bench.capture(["objdump", "-drwC", binary]) + (dest / "release.asm").write_text(assembly + "\n") + hot = bench.capture(["objdump", "-d", "--disassemble=recheck_hot", binary]) + assert re.search(r"\bcallq?\s+\*", hot) + for symbol, callee in (("recheck_sx", "sx_write_view"), ("recheck_sds", "sdscpylen"), + ("recheck_bstr", "bassignblk"), ("recheck_raw", "memcpy")): + text = bench.capture(["objdump", "-d", "--disassemble=" + symbol, binary]) + assert callee in text and "recheck_call_counts" not in text, text + rows = [] + for process in range(3): + raw = dest / f"samples-{process}.csv" + bench.run([binary, "--measure", str(process)], log, cpu=cpu, stdout=raw) + with raw.open() as f: + rows.extend(csv.DictReader(f)) + groups = {} + for row in rows: + assert int(row["expected_result"]) == 1 + groups.setdefault((row["case"], row["library"], row["mode"]), []).append(float(row["ns_per_op"])) + assert len(groups) == len(sizes) * 4 * 2 + stats = [dict(case=k[0], library=k[1], mode=k[2], median_ns=statistics.median(v), + p10_ns=bench.quantile(v, .1), p90_ns=bench.quantile(v, .9), + samples=len(v)) for k, v in sorted(groups.items())] + assert all(r["samples"] == 21 for r in stats) + (dest / "summary.json").write_text(json.dumps(stats, indent=2) + "\n") + results[variant] = stats + print("WRITE_RESULT_JSON=" + json.dumps(dict(compiler=cc, variant=variant, + binary_sha256=hashlib.sha256(binary.read_bytes()).hexdigest(), + results=stats)), flush=True) + for mode in ("hot", "flushed"): + report += [f"## {cc}: {mode}", "", + "| Bytes | StringX before ns | StringX after ns | SDS ns | bstrlib ns |", + "| --- | ---: | ---: | ---: | ---: |"] + def value(variant, n, lib): + return next(r["median_ns"] for r in results[variant] + if r["case"] == f"write{n}" and r["library"] == lib and r["mode"] == mode) + for n in sizes: + report.append(f"| {n} | {value('before',n,'StringX'):.2f} | " + f"{value('after',n,'StringX'):.2f} | {value('after',n,'SDS'):.2f} | " + f"{value('after',n,'bstrlib'):.2f} |") + report.append("") + text = "\n".join(report) + "\n" + (out / "summary.md").write_text(text) + if os.environ.get("GITHUB_STEP_SUMMARY"): + with open(os.environ["GITHUB_STEP_SUMMARY"], "a") as f: + f.write(text) + +if __name__ == "__main__": + main() diff --git a/.github/workflows/write-safety.yml b/.github/workflows/write-safety.yml new file mode 100644 index 0000000..9bfbe9a --- /dev/null +++ b/.github/workflows/write-safety.yml @@ -0,0 +1,80 @@ +name: Write safety and cost + +on: + pull_request: + paths: + - 'src/sx_core.c' + - 'tests/write_overflow*' + - '.github/scripts/check-write-safety.py' + - '.github/workflows/write-safety.yml' + workflow_dispatch: + +permissions: + contents: read + +concurrency: + group: write-safety-${{ github.event.pull_request.number || github.ref }} + cancel-in-progress: true + +defaults: + run: + shell: bash + +jobs: + verify: + name: Reproduce overflow and compare safe writes + runs-on: ubuntu-24.04 + timeout-minutes: 15 + steps: + - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + with: + ref: ${{ github.event.pull_request.head.sha || github.sha }} + persist-credentials: false + - name: Install compilers and audit tools + timeout-minutes: 5 + run: | + if test -f /etc/apt/apt-mirrors.txt; then + printf '%s\n' 'https://archive.ubuntu.com/ubuntu' | sudo tee /etc/apt/apt-mirrors.txt > /dev/null + fi + sudo apt-get -o Acquire::Retries=3 -o Acquire::http::Timeout=30 -o Acquire::https::Timeout=30 update + sudo env DEBIAN_FRONTEND=noninteractive apt-get \ + -o DPkg::Lock::Timeout=120 -o Acquire::Retries=3 \ + -o Acquire::http::Timeout=30 -o Acquire::https::Timeout=30 \ + install --no-install-recommends -y gcc-14 clang-19 libclang-rt-19-dev binutils + - name: Check out the unchanged baseline + uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + with: + ref: 452314a7ca51f90a7a8fa66930947164af8fc4f6 + path: build/write/before + persist-credentials: false + - name: Check out the audited measurement harness + uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + with: + ref: 7f8a624af4809c9dc606c41533991acd1b51917d + path: build/write/harness + persist-credentials: false + - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + with: + repository: antirez/sds + ref: 5347739b1581fcba74fd5cab1fc21d2aef317d71 + path: build/write/deps/sds + persist-credentials: false + - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + with: + repository: websnarf/bstrlib + ref: f0ff1e808102a42cdc7204a4bb6fe231a24c4546 + path: build/write/deps/bstrlib + persist-credentials: false + - name: Verify overflow rejection and measure write overhead + run: | + python3 .github/scripts/check-write-safety.py \ + --before build/write/before --harness build/write/harness \ + --deps build/write/deps --out build/write/results + - name: Keep evidence and raw samples + if: always() + uses: actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9 # v7.0.2 + with: + name: write-safety-${{ github.run_id }} + path: build/write/results + retention-days: 14 + if-no-files-found: ignore diff --git a/docs/WRITE_SAFETY.md b/docs/WRITE_SAFETY.md new file mode 100644 index 0000000..99ed351 --- /dev/null +++ b/docs/WRITE_SAFETY.md @@ -0,0 +1,42 @@ +# Write offset arithmetic + +The write APIs accept a size_t offset. The sum of that offset and the +input length must fit in size_t and leave room for the terminating NUL. +For example, sx_write_cstr(s, SIZE_MAX, "X") previously wrapped the +reserve request to zero, then formed an out-of-bounds destination pointer. + +The shared write helper rejects arithmetic overflow before computing a +destination. sx_write_view also checks before its alias-preserving +pre-reserve, so an invalid range cannot mutate the target capacity first. +The existing reserve helper rejects a total content length of SIZE_MAX, +which cannot include a terminator. Owned write inputs are still consumed +on failure. Valid writes, binary data and view aliases retain their semantics. + +Tests exercise all three write APIs near SIZE_MAX with real small input +buffers, unchanged target contents/capacity, borrowed views, owned failures, +binary writes and valid aliased growth. Both normal and exact-reserve +configurations run under the existing sanitizer suite. + +The Write safety and cost workflow compiles the same regression against +the immutable old implementation, requires a sanitizer failure there, and +requires both fixed configurations to pass with GCC 14 and Clang 19. + +The focused performance check reuses the pinned audited harness from +7f8a624af4809c9dc606c41533991acd1b51917d. It generates an overwrite-only +harness and saves that exact source in the artifact. Source/target lengths +are equal (8/64/4096/65536 bytes), buffers are preallocated, and binary +contents are compared in full outside timing. The APIs are sx_write_view, +sdscpylen and bassignblk, with raw memcpy using the same SDS buffer as a +control. This contract is an equal-length overwrite; it does not compare +their different truncation/extension semantics. + +Before/after StringX and peers run on the same pinned CPU, with three +fresh processes and seven samples per group. Separate translation units, +no LTO, verification-only call counters and release disassembly preserve +the audited call structure. Hot and CLFLUSH-based data conditions are +reported separately; flushing cost is excluded. No counting is enabled in +timed release adapters. This is a targeted write-cost check; it makes no +new claim about search or growth performance. + +Other mutator arithmetic (such as insert/erase/view ranges) remains a +separate audit target. This change is limited to write-range validation. diff --git a/include/sx_core.h b/include/sx_core.h index f77480f..6b6a781 100644 --- a/include/sx_core.h +++ b/include/sx_core.h @@ -42,6 +42,9 @@ sx_view_t sx_view(const sx_t *h); sx_t *sx_append(sx_t *self, sx_t *owned); sx_t *sx_append_cstr(sx_t *self, const char *s); sx_t *sx_append_view(sx_t *self, sx_view_t v); +/* Writes return NULL if the resulting length cannot be reserved, including + unsigned overflow. Overflow leaves self unchanged; sx_write still consumes + its owned input on failure. */ sx_t *sx_write(sx_t *self, size_t idx, sx_t *owned); sx_t *sx_write_cstr(sx_t *self, size_t idx, const char *s); sx_t *sx_write_view(sx_t *self, size_t idx, sx_view_t v); @@ -100,4 +103,4 @@ int sx_starts_with_cstr(const sx_t *h, const char *prefix); int sx_ends_with(const sx_t *h, const sx_t *suffix); int sx_ends_with_view(const sx_t *h, sx_view_t suffix); int sx_ends_with_cstr(const sx_t *h, const char *suffix); -#endif \ No newline at end of file +#endif diff --git a/src/sx_core.c b/src/sx_core.c index a09638d..d6295b1 100644 --- a/src/sx_core.c +++ b/src/sx_core.c @@ -91,11 +91,14 @@ SYMBOL_PUBLIC sx_t *sx_append_view(sx_t *self, sx_view_t v) { } static inline sx_t *write(sx_t *self, size_t idx, const char *str, size_t len, void *(*copy)(void *, const void *, size_t)) { - if (sx__reserve(self->ref, idx + len)) + if (len > SIZE_MAX - idx) + return NULL; + const size_t end = idx + len; + if (sx__reserve(self->ref, end)) return NULL; copy(self->ref->ptr + idx, str, len * sizeof(char)); - if (idx + len > self->ref->len) - self->ref->len = idx + len; + if (end > self->ref->len) + self->ref->len = end; self->ref->ptr[self->ref->len] = '\0'; /* keep the invariant */ return self; } @@ -112,6 +115,9 @@ SYMBOL_PUBLIC sx_t *sx_write_cstr(sx_t *self, size_t idx, const char *s) { return write(self, idx, s, strlen(s), memcpy); } SYMBOL_PUBLIC sx_t *sx_write_view(sx_t *self, size_t idx, sx_view_t v) { + /* Reject overflow before the alias-preserving pre-reserve can mutate self. */ + if (v.len > SIZE_MAX - idx) + return NULL; if (sx__reserve(self->ref, idx + v.len)) return NULL; if (self->ref == v.ref) diff --git a/tests/write_overflow.c b/tests/write_overflow.c new file mode 100644 index 0000000..6bd7d18 --- /dev/null +++ b/tests/write_overflow.c @@ -0,0 +1,13 @@ +// Include include +// Include src +// Include /usr/lib/forge/include +// Source src/sx_raw.c +// Source src/sx_core.c +// Source src/sx_adv.c +// Option -std=c23 +// Option -O1 +// Option -g +// Option -fsanitize=address,undefined +// Option -fno-omit-frame-pointer +// Library /usr/local/lib +#include "write_overflow_cases.h" diff --git a/tests/write_overflow_cases.h b/tests/write_overflow_cases.h new file mode 100644 index 0000000..b786458 --- /dev/null +++ b/tests/write_overflow_cases.h @@ -0,0 +1,94 @@ +#ifndef SX_WRITE_OVERFLOW_CASES +#define SX_WRITE_OVERFLOW_CASES +#include "sx_core.h" +#include +#include +#ifdef SX_WRITE_OVERFLOW_STANDALONE +#include +#include +#define TEST(x) do { if (!(x)) { \ + fprintf(stderr, "failed %s:%d: %s\n", __FILE__, __LINE__, #x); abort(); \ +} } while (0) +#define PASS() puts("PASSED: write overflow") +#else +#include +#endif + +static void unchanged(sx_t *s, char *buffer, int cap) { + TEST(sx_buf_mut(s) == buffer); + TEST(sx_cap(s) == cap && sx_len(s) == 3); + TEST(memcmp(sx_buf_mut(s), "abc", 4) == 0); +} + +int main(void) { + sx_t *s = sx_new_from_cstr("abc"); + sx_t *source = sx_new_with_cap(41); + TEST(s && source && sx_truncate(source, 40) == source); + for (size_t i = 0; i < 40; ++i) + sx_buf_mut(source)[i] = i % 7 == 0 ? 0 : (char)(0x80 + i); + sx_view_t view = sx_view(source); + view.offset = 4; + view.len = 32; + char text[33]; + memset(text, 'x', 32); + text[32] = 0; + char *buffer = sx_buf_mut(s); + int cap = sx_cap(s); + + /* Baseline repro: SIZE_MAX + 1 wraps to zero, bypasses reserve, + then copies one byte just before the target allocation. */ + TEST(sx_write_cstr(s, SIZE_MAX, "X") == NULL); + unchanged(s, buffer, cap); + + /* Cover sums wrapping to 0..31, including wrapped values large + enough to trigger the view pre-reserve on the old implementation. + back==32 yields SIZE_MAX, which cannot include a terminator. */ + for (size_t back = 0; back <= 32; ++back) { + size_t idx = SIZE_MAX - back; + TEST(sx_write_cstr(s, idx, text) == NULL); + unchanged(s, buffer, cap); + TEST(sx_write_view(s, idx, view) == NULL); + unchanged(s, buffer, cap); + sx_t *owned = sx_new_from_cstr(text); + TEST(owned); + TEST(sx_write(s, idx, owned) == NULL); /* consumed even on failure */ + unchanged(s, buffer, cap); + TEST(sx_len(source) == 40 && sx_buf_mut(source)[4] == (char)0x84); + } + + sx_view_t alias = sx_view(s); + for (size_t back = 0; back <= 3; ++back) { + TEST(sx_write_view(s, SIZE_MAX - back, alias) == NULL); + unchanged(s, buffer, cap); + TEST(memcmp(sx_buf_view_mut(alias), "abc", 3) == 0); + } + view.len = 0; + TEST(sx_write_view(s, SIZE_MAX, view) == NULL); + unchanged(s, buffer, cap); + TEST(sx_write_view(s, 3, view) == s); + unchanged(s, buffer, cap); + + sx_t *binary = sx_new_from_cstr("XqY"); + TEST(binary); + sx_buf_mut(binary)[1] = 0; + TEST(sx_write_view(s, 1, sx_view(binary)) == s); + const char expected[] = {'a', 'X', 0, 'Y'}; + TEST(sx_len(s) == 4 && memcmp(sx_buf_mut(s), expected, 4) == 0); + TEST(sx_buf_mut(s)[4] == 0); + + /* Valid aliased writes must still reacquire the source after growth. */ + alias = sx_view(s); + TEST(sx_write_view(s, 4, alias) == s); + TEST(sx_len(s) == 8); + TEST(memcmp(sx_buf_mut(s), expected, 4) == 0); + TEST(memcmp(sx_buf_mut(s) + 4, expected, 4) == 0); + TEST(sx_buf_mut(s)[8] == 0); + TEST(sx_write(s, 0, sx_new_from_cstr("ok")) == s); + TEST(memcmp(sx_buf_mut(s), "ok", 2) == 0 && sx_len(s) == 8); + sx_free(binary); + sx_free(source); + sx_free(s); + PASS(); + return 0; +} +#endif diff --git a/tests/write_overflow_exact.c b/tests/write_overflow_exact.c new file mode 100644 index 0000000..2ecc6fb --- /dev/null +++ b/tests/write_overflow_exact.c @@ -0,0 +1,14 @@ +// Include include +// Include src +// Include /usr/lib/forge/include +// Source src/sx_raw.c +// Source src/sx_core.c +// Source src/sx_adv.c +// Option -std=c23 +// Option -O1 +// Option -g +// Option -fsanitize=address,undefined +// Option -fno-omit-frame-pointer +// Option -DSX_FORCE_EXACT_RESERVE +// Library /usr/local/lib +#include "write_overflow_cases.h" From 71e80ae81e0f5a881dd96c9cf7cac6ac654b874d Mon Sep 17 00:00:00 2001 From: minelogy <72928567+minelogy-dev@users.noreply.github.com> Date: Mon, 2 Nov 2026 12:20:22 -0800 Subject: [PATCH 2/2] bench: use the SDS API's explicit byte-pointer type Co-authored-by: Codex --- .github/scripts/check-write-safety.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.github/scripts/check-write-safety.py b/.github/scripts/check-write-safety.py index 6f601f2..7971e90 100644 --- a/.github/scripts/check-write-safety.py +++ b/.github/scripts/check-write-safety.py @@ -72,7 +72,7 @@ def main(): #elif LIB_INDEX == 1 __attribute__((noinline)) uint64_t recheck_sds(recheck_input *f) { RECORD(); - sds result = sdscpylen(f->sd, f->pattern, f->m); + sds result = sdscpylen(f->sd, (const char *)f->pattern, f->m); if (!result) return 0; f->sd = result; return 1;