Skip to content

v0.70.0

Latest

Choose a tag to compare

@alexveden alexveden released this 04 Oct 10:59
· 19 commits to master since this release

CEX 0.70 — Release Keynotes

0.70 reaches production-beta. The CEX core — error handling, allocators and
mem$scope, arr$/hm$ data structures, str/sbuf, the unit-test runner, and
the cexy$ build system — is now stable and well covered: the test suite exercises
it end-to-end and coverage tooling tracks it.

v0.22.0 → 0.70. This release is mostly about what happens when things go
wrong
: errors now carry a buffered traceback, and allocation failure is a
panic by default instead of a NULL you were probably not checking. The data
structures and the test runner were rebuilt around that contract. There is also
new tooling — coverage and an agent-friendly ./cex help.

The full itemized list lives in CHANGELOG.md. These are the changes that can
break your build or change runtime behavior.

1. Error handling goes buffered

e$raise / e$assert / e$except* / e$ret / e$goto no longer print as they
run. They record a frame into a ring and keep going. The ring is compiled in by
CEX_TRACEBACK_VERBOSITY (0..3, default 2): 0 disables it, 1 and 2 buffer
frames, 3 prints immediately. Buffered frames are not printed automatically —
you flush them once at the top-level sink. Read them back with e$traceback_arr
/ e$traceback_len / e$traceback_reset, or print with e$traceback_print.
Ring capacity is CEX_TRACEBACK_CAP (default 32).

Why: every helper used to spew to stderr, so one handled error produced a wall
of noise and no context about where it originated. Now error context is opt-in
and cheap until you actually need it.

Add a sink in main():

int
main(int argc, char** argv)
{
    e$except (err, app_main(argc, argv)) {
        e$traceback_print(stderr);
        return 1;
    }
    return 0;
}

Removed in the process: e$except_silent, e$traceback_fmt, and the uassertf*
family. If you relied on errors printing themselves, you need the sink.

2. Panics are the new contract

Heap allocation failure is now fatal. mem$malloc / calloc / realloc /
new panic through cex$platform_mem_panic (default cex$platform_panic,
which prints [MEMORY] file:line reason). Arena argument and limit violations —
bad page size, zero or oversized allocation, misalignment — panic the same way.
OOM is rarely recoverable, so failing fast beats threading a NULL check
through every call site.

Opt back into NULL returns by defining the hook as an empty function-like
macro before including CEX:

#define cex$platform_mem_panic(...)   // restore NULL on OOM

Assertions got a matching split: uassert() is stripped by NDEBUG, while the
new uassert_always() always traps. Both are tuned by CEX_PANIC_VERBOSITY
(0..2, default 1). unreachable() is gone:

// before
if (!ok) { unreachable(); }

// after
if (!ok) { uassert_always(false && "unreachable"); }

Synthetic test$alloc OOM and
custom-backing allocator failures still return NULL, so the recoverable path
remains testable.

3. Size arithmetic is overflow-checked

mem$ gains a domain bound and overflow-free size checks. mem$MAX is the maximum
valid size/index (PTRDIFF_MAX); anything above it is invalid, and mem$MAX + 1 is
the reserved overflow sentinel.

  • mem$has_overflow(cap, off, n) — true when [off, off + n) does not fit in cap,
    or any argument is out of range (negative cast, SIZE_MAX). Never wraps.
  • mem$calc_overflow(cap, off, n) — 0 when it fits, the shortfall to grow by
    (1..mem$MAX), or mem$MAX + 1 when an argument is out of range.
  • mem$add_overflow / mem$sub_overflow / mem$mul_overflow remain for checked
    arithmetic when you need the result value.

Allocators now reject any requested size >= mem$MAX, so a signed-negative size cast
to usize fails as a memory error instead of becoming a huge allocation. calloc
detects nmemb * size overflow (previously wrapped to a small/zero allocation) and
panics. Internally arr$, hm$, sbuf, str.fmt and both allocators migrated their
ad-hoc off + n > cap / len + add checks to these primitives.

Why: off + n > cap is not a bounds check once off + n can wrap, and cap - off
underflows to a huge "remaining room" — both are direct paths to out-of-bounds writes.
The half-usize domain (mem$MAX = PTRDIFF_MAX) keeps every valid size addable
without wrap and rejects negative lengths on sight. Even a missed calc_overflow
guard fails safe: cap += (mem$MAX + 1) cannot wrap and lands above mem$MAX, which
the allocator rejects downstream.

// untrusted buf/len slice
if (mem$has_overflow(cap, off, n)) return Error.overflow;
memcpy(dst, buf + off, n);

// allocation size: a wrapped product is a heap overflow
usize total;
if (mem$mul_overflow(nmemb, size, &total)) return Error.overflow;

// grow by the exact shortfall (no-op when it already fits)
usize need = mem$calc_overflow(cap, len, add);
if (need >= mem$MAX) return Error.overflow;
cap += need;

4. Data structures survive OOM

arr$ and hm$ were reworked to be OOM-safe. Mutating macros now return a
pointer to the item slot or NULL; a grow that runs out of memory frees the
container and sets your variable to NULL, leaving no leak and no corrupt
state. Most macros tolerate a NULL container as their first argument —
hm$get returns the default, appends/inserts return NULL, deletes return
false.

Two behaviors broke deliberately:

  • arr$at / arr$last / arr$pop now assert on a NULL array instead of
    returning a zero value. Accessing an empty/NULL array was always a bug.
  • arr$validate(a) / hm$validate(t) were added: Error.memory on NULL,
    Error.integrity on a bad magic, EOK otherwise. The strict integrity check
    now runs only in unit tests.
e$ret(arr$validate(array));          // Error.memory on NULL, Error.integrity on bad handle
arr$(int) grown = arr$new(grown, mem$);
arr$push(grown, 1);                  // NULL container is tolerated
if (grown == NULL) { return Error.memory; } // synthetic OOM grow nulled it

5. OOM is now testable and fuzzable

AllocatorArena_kw.test_oom_probability and AllocatorArena_c.test_oom_probability
are renamed to test_oom_threshold. The single field now encodes three modes:
0 disabled, (0,1) probability, 1 always fail, >1 fail after N-1 calls.
test$alloc_set_oom_probability(prob) still works; the new
test$alloc_set_oom_on_call(n) is the deterministic version. In CEX_TEST
builds mem$ is assignable, so a test can route every allocation through the
per-case arena. mem$realloc also unconditionally nullifies the old pointer.

test$case(my_test_case)
{
    test$alloc_set_oom_on_call(3);   // first two allocations succeed, third fails
    tassert(mem$malloc(test$alloc, 64) != NULL);
    tassert(mem$malloc(test$alloc, 64) != NULL);
    tassert(mem$malloc(test$alloc, 64) == NULL);
    return EOK;
}

Two OOM fuzz harnesses ship under fuzz/ds/ (fuzz_ds_hashmap_oom.c,
fuzz_ds_array_oom.c) that inject test_oom_threshold failures at every
operation under ASAN/UBSan.

6. sbuf header layout changed

The sbuf metadata header is now explicit fields instead of bitfields:
nullterm is the first byte (always 0), then elsize, then the u32 magic at
offset 4. Static buffers are aligned up before the header and capacity accounts
for the slack, so a raw static buffer always reads as an empty string.
sbuf.destroy() tolerates NULL. This only breaks code that peeks at raw
header bytes; normal sbuf.* callers just recompile.

7. Coverage tooling (new)

First-class coverage, built on the test runner:

./cex coverage run all                       # build+run all tests instrumented
./cex coverage report all                    # text report
./cex coverage report --format=json all      # machine-readable JSON
./cex coverage report --format=html all      # HTML -> cexy$build_dir/coverage
./cex coverage report --file 'src/foo*.c' all
./cex coverage export -o coverage.info all   # lcov tracefile
./cex coverage clean all

Engines are auto (llvm for clang, lcov for gcc) or --engine=llvm|lcov. The
precompiled cex.h stays uninstrumented, and raw data resets per target, so you
can re-run a single test without losing the rest.

8. Agentic ./cex help (new)

./cex help now emits compact, machine-usable API maps:

./cex help --list                            # all namespaces in the project
./cex help --brief str$ [os$ e$ ...]         # one line per member
./cex help --idioms str$                     # namespace docs block
./cex help --brief --idioms str$             # idioms + compact API
./cex help --agents [--out AGENTS.md]        # dump idioms for agent instruction files
./cex help --source 'str$s'                  # print a function/macro source
./cex help --example str.find                # real usages (deterministic)

Also in 0.70

  • AllocatorArena_kw.backing_alloc — arena pages can be backed by a custom
    allocator (default mem$); the backing allocator must outlive the arena.