Skip to content

perf: a default image may be the PREFIX of an object, not a copy of it - #196

Merged
Andste82 merged 5 commits into
mainfrom
perf/prefix-default-image
Oct 13, 2026
Merged

Andste82 merged 5 commits into
mainfrom
perf/prefix-default-image

Conversation

@Andste82

@Andste82 Andste82 commented Oct 13, 2026 •

Copy link
Copy Markdown
Member

Part of sofa-buffers/generator#741. The generator PR that emits prefix images needs this merged first (its lang-c job pins this corelib's main): sofa-buffers/generator — perf/c-prefix-default-image-741.

What the image costs today

SOFAB_OBJECT_DESCR_WITH_DEFAULTS documents its argument as "a fully-populated object", and every read addresses the image through the field's own offset:

site read
object.c init memcpy(obj + field->offset, image + field->offset, field->size)
object.c init, sized buffer _load_uint(image + field->offset - width, width)
_field_is_default, string strncmp(src + off, image + off, size)
_field_is_default, sized length from image + off - width, then memcmp(image + off, …)
_field_is_default, plain memcmp(image + off, val, size)

So the only buffer a generator can hand over is a copy of the whole struct. On sofa-buffers/generator's own realworld schema that is 824 bytes of .rodata to carry 16 bytes of actual defaults — 14.6 % of that target's entire flash image, measured on cortex-m0.

What changes

const uint16_t count_extent;   /* was: const uint16_t field_count */
  • Holder (SOFAB_OBJECT_SEQ_HOLDER): all 16 bits stay the element slot count, so an array<string, count: 300> keeps its 300 slots. A holder never carries an image, so it has no extent to store.
  • Object (message, struct, union): low byte = field count (255 max, asserted by the macros), high byte = how many bytes of the object the image describes.

The descriptor therefore does not grow — still 16 bytes on a 32-bit target, where a separate extent field would have made it 20 (measured; that variant cost +4 B per descriptor and turned into a net loss for small structs with many descriptors).

A field at or past the extent has no declared default, so it is compared against and seeded with zero — which is what "no declared default" has always meant. _field_default() returning NULL past the extent therefore lands on the existing zero-compare path instead of adding one.

Extent 0 means "the whole object". That is what every descriptor written before this field carries (an omitted initialiser is 0), and what a union image uses.

The two kinds of image get two spellings, because a macro cannot tell a prefix from a whole object by its size:

macro image extent recorded longer than 255 B
SOFAB_OBJECT_DESCR_WITH_DEFAULTS the whole object (contract unchanged) sizeof(*image), or 0 0 = "all of it" — right for a whole image, so it takes one of any size
SOFAB_OBJECT_DESCR_WITH_PREFIX_DEFAULTS (new) a prefix, defaulted members first sizeof(*prefix) compile error — no extent value says how far it reaches

Old descriptors and old generated code keep working unchanged — see Compatibility for how that was verified, and for the one exception.

Measured

sofa-buffers/generator's tests/bench --rows c (vehicle_telemetry, -Os), with the generator emitting prefix images:

before after
.text ARMv6-m 5 628 5 016 (−612)
.text ARMv7-m+fp.dp 5 616 4 982 (−634)
.text RV32IMC 6 170 5 560 (−610)
Ir/op encode 26 491 26 567 (+0.3 %)
Ir/op decode 54 510 54 568 (+0.1 %)
sizeof(sofab_object_descr_t) 16 16

The field count is hoisted out of the three loops that had it in their condition: at -Os the load+mask was re-evaluated per iteration, which cost 2 035 Ir/op on decode (+3.8 %) before the hoist. That is the only reason the Ir numbers are flat rather than up.

A one-default-at-a-time sweep over a 25-field schema (one variant per field kind, 23 accepted, generated and run against both corelibs) shows the image dropping from 232 B to exactly the defaulted member's size — 1, 2, 4, 8, 9, 10, 13, 16 B — with identical wire output in every variant, and .text following the saving byte for byte.

Tests

  • test_object_default_image_may_be_a_prefix — the fields the image covers are seeded, a field past the extent stays zero, and the omission test follows the same line. The image buffer holds 0xDEADBEEF exactly where that field would be read from, so the boundary shows as a wrong value, not only under a sanitizer. (Its first version passed with the logic broken, on zeroed .rodata; that is why the poison is there.)
  • test_object_extent_zero_means_the_whole_object — the legacy reading, hand-built as an old descriptor looks like.
  • test_object_holder_keeps_a_16_bit_slot_count — a 300-slot holder reaches its last element; a byte-wide slot count would have stopped at 255.
  • test_object_whole_image_longer_than_the_extent_byte — a whole image of 304 B through WITH_DEFAULTS reads as extent 0 and seeds the member at offset 300: the shape every generated file before this PR has (vehicle_telemetry is 824 B).

Mutation-checked: ignoring the extent fails the first, reading the slot count byte-wide fails the third. Whole C suite green under -Wall -Wextra -Werror -fsanitize=address,undefined, and the minimal feature subset (-DSOFAB_DISABLE_SEQUENCE/ARRAY/FIXLEN/FP64/INT64_SUPPORT) compiles — that leg caught a real defect during development, a helper left inside the _SOFAB_WITH_UNION guard.

The limits this introduces

Every one of them is a build error that names itself, not a value that wraps -- the same bargain SOFAB_OBJECT_ASSERT_FITS_PROFILE already makes for an offset, and it costs no .text or .rodata on any of the four architectures.

limit macro over it
255 fields per object (message, struct, union) SOFAB_OBJECT_DESCR_FIELD_COUNT_MAX an_object_may_not_declare_more_than_255_fields
255 bytes of prefix default image SOFAB_OBJECT_DESCR_EXTENT_MAX a_prefix_default_image_may_not_exceed_255_bytes
65 535 element slots per wrapper-array holder SOFAB_OBJECT_DESCR_SLOT_COUNT_MAX a_wrapper_array_may_not_declare_more_than_65535_slots

The three maxima are exported so generated code can hold a schema against them at compile time the way it already does with SOFAB_ID_MAX, instead of discovering a ceiling as an assertion failure inside object.h.

The image limit is the one with a way out: a whole-object image goes through SOFAB_OBJECT_DESCR_WITH_DEFAULTS at any size. A prefix longer than 255 bytes has no extent that describes it, and must not be read as the whole object: the walk would seed and compare every field behind it through the image and read past its end (a string<maxlen: 300> with a default is enough; ASan reports a global-buffer-overflow in sofab_object_init under MEDIUM and BIG, while SMALL is immune only because the field behind such a prefix is already past its own offset ceiling).

The slot-count assert replaces an explicit (uint16_t) cast that had grown around the holder count in SOFAB_OBJECT_DESCR_SEQ / _SEQ_SIZED. The cast silenced -Woverflow, which was all that stood between a 70 000-slot holder under _BIG and a descriptor that walks 4 464 slots and rejects the rest as over-index elements (§7.1).

And 38 B less than the table above

sofab_object_init asked _field_default twice per field -- once for the value, once for a sized buffer's companion length -- and -Os folded neither call. Asking once, measured on the library alone (tools/footprint.sh's metric):

target before after
ARMv6-m 4 104 4 066
ARMv7-m+fp.dp 4 064 4 046
RV32IMC 5 264 5 236
atmega8 7 664 7 702

atmega8 pays 38 B: the pointer now lives across the memcpy, whose clobbers spill it, where two short live ranges needed no stack. It is its own commit, so an AVR budget can drop it. Two other shapes measured worse everywhere and are documented in that commit.

Compatibility — verified against generated code

Built sofabgen from generator main (what every existing generated file looks like) and from #743, generated the shipped examples/messages/realworld schemas plus one probe schema per limit, and compiled them against this branch under _SMALL, _MEDIUM and _BIG:

generated by against this branch
generator main (whole images) builds; under ASan+UBSan init seeds every default, an all-default message encodes to 0 B, encode → decode → encode round-trips — wire byte-identical to the prefix build
#743 as it stands refused by its own guard — see below
#743 emitting WITH_PREFIX_DEFAULTS builds and round-trips; a 256 B prefix is a_prefix_default_image_may_not_exceed_255_bytes

The one break for existing generated code: an object with more than 255 fields compiled against main (the field count was 16 bits) and is a compile error here. Hand-written code that names sofab_object_descr_t::field_count has to say count_extent — through the macros nothing changes.

SOFAB_OBJECT_COUNT_EXTENT is renamed SOFAB_OBJECT_DESCR_COUNT_WORD on purpose. #743 emits its prefix images through WITH_DEFAULTS and guards on defined(SOFAB_OBJECT_COUNT_EXTENT); against this corelib that output would read a prefix over 255 B as the whole object — reproduced, ASan global-buffer-overflow in sofab_object_init. #743's lang-c job pins this corelib's main and its test images are small, so it would have gone green. With the name gone, its own guard stops the build instead. #743 needs, before it merges:

  1. emit SOFAB_OBJECT_DESCR_WITH_PREFIX_DEFAULTS instead of WITH_DEFAULTS for a prefix image;
  2. guard on defined(SOFAB_OBJECT_DESCR_WITH_PREFIX_DEFAULTS);
  3. fall back to the whole-object image through WITH_DEFAULTS when the defaulted prefix would exceed 255 B — otherwise such a schema generates code that does not compile, where generator main compiled it.

1 and 2 were tried locally (three lines in generators/c/backend.go) and are what the third row above was built with; 3 is not done.

Verified limits

The README has a new Descriptor limits section: what each profile can describe, per schema type, and the error each limit raises. Every number there without a footnote was bisected the same way — a schema at the limit and one past it, generated and compiled against each profile, N builds and N+1 fails with the named error. No limit wraps silently or only warns any more; the one that used to (-Woverflow on a >65 535-slot holder under _BIG, against main) is now a_wrapper_array_may_not_declare_more_than_65535_slots.

SOFAB_OBJECT_DESCR_WITH_DEFAULTS documented its argument as "a fully-populated
object", and every read addresses the image through the FIELD's own offset
(object.c: init's memcpy and its sized-length seed, and the three compares in
_field_is_default). So the only buffer a generator could hand over was a copy of
the whole struct -- for sofa-buffers/generator's own realworld schema, 824 bytes
of .rodata to carry 16 bytes of actual defaults, 14.6 % of that target's entire
flash image.

The descriptor now records how many bytes of the object the image describes, so
it may stop after the members that have defaults:

    const uint16_t count_extent;   /* was: const uint16_t field_count */

A wrapper-array HOLDER keeps all 16 bits for its element slot count, so an
`array<string, count: 300>` still has its 300 slots. Every other object spends
the low byte on the field count -- 255 max, asserted by the macros -- and the
high byte on the image's extent. The descriptor therefore does NOT grow: still
16 bytes on a 32-bit target, where a separate extent field would have made it 20.
Read through _field_count() and _default_extent(), never directly.

A field at or past the extent has no declared default and is compared against
(and seeded with) zero, which is what "no declared default" has always meant --
so _field_default() returning NULL past the extent lands on the existing
zero-compare path rather than a new one. An extent of 0 reads as "the whole
object": what every descriptor written before this field carries (an omitted
initialiser is 0), what a union image uses, and what an image longer than 255
bytes falls back to. Old descriptors and old generated code therefore keep
working unchanged -- verified by building generator-emitted code from before this
change against this corelib with -Wall -Wextra -Werror.

Measured with sofa-buffers/generator's `tests/bench --rows c` (vehicle_telemetry,
cortex-m0/m7/rv32imc, -Os), generator emitting prefix images:

    .text  ARMv6-m   5628 -> 5016   (-612)
           ARMv7-m   5616 -> 4982   (-634)
           RV32IMC   6170 -> 5560   (-610)
    Ir/op  encode   26491 -> 26567  (+0.3 %)
           decode   54510 -> 54568  (+0.1 %)

The field count is hoisted out of the three loops that had it in their condition:
at -Os the load+mask was re-evaluated per iteration, which cost 2035 Ir/op on
decode (+3.8 %) before.

Tests: a prefix image seeds the fields it covers and leaves a field past the
extent at zero -- with 0xDEADBEEF sitting in the image buffer exactly where that
field would be read from, so the boundary shows up as a wrong VALUE and not only
under a sanitizer; extent 0 still means the whole object; and a 300-slot holder
reaches its last element, which a byte-wide slot count would have cut at 255.
Each is mutation-checked: ignoring the extent fails the first, reading the slot
count byte-wide fails the third.
Andste82 and others added 4 commits October 13, 2026 09:09
SOFAB_OBJECT_COUNT_EXTENT clamped an image longer than 255 bytes to extent
0 -- and 0 reads as "the image covers the whole object". That is the
conservative reading for a whole-object image and the wrong one for a
PREFIX: every field past the prefix is then seeded and compared through
the image, reading past its end. A generator-emitted message defaulting a
`string<maxlen: 300>` or an `array<u32, count: 64>` lands there, and
nothing says so -- under MEDIUM and BIG the walk reads .rodata it does not
own (AddressSanitizer: global-buffer-overflow in sofab_object_init);
SMALL is immune only because the field behind such a prefix has an offset
past its own ceiling and is already a build error.

So the clamp is gone and the macros name every ceiling they cannot
describe, the way SOFAB_OBJECT_ASSERT_FITS_PROFILE already does for an
offset:

  - SOFAB_OBJECT_ASSERT_EXTENT refuses an image over
    SOFAB_OBJECT_DESCR_EXTENT_MAX. An image that really is a copy of the
    whole object says so with the new
    SOFAB_OBJECT_DESCR_WITH_WHOLE_DEFAULTS, which records extent 0 on
    purpose -- the form every descriptor written before the extent
    existed already has, and the only form left for an image the extent
    cannot reach.
  - SOFAB_OBJECT_ASSERT_SLOT_COUNT replaces the (uint16_t) cast that
    SOFAB_OBJECT_DESCR_SEQ / _SEQ_SIZED had grown around their slot
    count. The cast silenced -Woverflow, which was the only thing
    standing between a 70000-slot holder under BIG and a descriptor that
    silently walks 4464 of them and rejects the rest as over-index
    elements (MESSAGE_SPEC §7.1).
  - SOFAB_OBJECT_DESCR_FIELD_COUNT_MAX / _EXTENT_MAX / _SLOT_COUNT_MAX
    are exported so generated code can hold a schema against them at
    compile time the way it already does with SOFAB_ID_MAX, instead of
    discovering the ceiling as an assertion failure inside this header.
    object.c reads its mask and shift from the same two macros.

All of it is compile-time: .text and .rodata are byte-identical on
ARMv6-m, ARMv7-m+fp.dp, RV32IMC and atmega8.

The extent-0 test now also builds its descriptor through
WITH_WHOLE_DEFAULTS and pins its count word against the hand-rolled
legacy one, so the macro cannot drift from the shape it stands for.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
The init walk asked _field_default twice for every field -- once for the
value, once for a sized buffer's companion length -- and at -Os neither
compiler folded the second call away, although the function is pure and
both calls are in the same block. Asking once:

| target        | .text before | after |
|---------------|-------------:|------:|
| ARMv6-m       |        4 104 | 4 066 |
| ARMv7-m+fp.dp |        4 064 | 4 046 |
| RV32IMC       |        5 264 | 5 236 |
| atmega8       |        7 664 | 7 702 |

atmega8 is the one that pays: the pointer now lives across the memcpy,
whose clobbers spill it, where two short live ranges needed no stack at
all. 38 B on an 8-bit target against 38/18/28 B on the three 32-bit ones
is the trade this commit makes, and it is its own commit so it can be
dropped if an AVR budget disagrees.

Two other shapes measured worse everywhere and are not here: taking the
companion length first (ARMv6-m 4 070, atmega8 7 718), which would also
have matched the order _field_is_default reads the two in; and hoisting
the image pointer and its extent out of the field loop as the
object-invariants they are, with a three-argument core (ARMv6-m 4 086,
atmega8 7 712) -- the per-field compare that remains is not what the loop
was spending.

Whole C suite green, and green again under
-fsanitize=address,undefined.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
…x says so

bfd624d made SOFAB_OBJECT_DESCR_WITH_DEFAULTS refuse an image over 255
bytes, to stop a PREFIX that long from being clamped to extent 0 and read
past its end. The macro cannot tell a prefix from a whole object, though,
and every file the generator emits today hands over the WHOLE object: its
own realworld example (vehicle_telemetry, 824 B) stopped compiling against
this branch, while it builds against main -- the opposite of the "old
generated code keeps working" this PR promises, and a broken lang-c job in
sofa-buffers/generator the moment this merges.

So the two images get two spellings:

  - SOFAB_OBJECT_DESCR_WITH_DEFAULTS keeps its contract: a fully-populated
    object, of any size. It records sizeof(*image), or 0 when that is past
    the extent byte -- for a whole image the two mean the same.
  - SOFAB_OBJECT_DESCR_WITH_PREFIX_DEFAULTS is the prefix form. It records
    sizeof(*prefix) and refuses one over SOFAB_OBJECT_DESCR_EXTENT_MAX
    (a_prefix_default_image_may_not_exceed_255_bytes), because no extent
    value says how far such a prefix reaches.

WITH_WHOLE_DEFAULTS goes again: WITH_DEFAULTS already is that macro.

SOFAB_OBJECT_COUNT_EXTENT becomes SOFAB_OBJECT_DESCR_COUNT_WORD on
purpose. Generator PR #743 still emits its prefix images through
WITH_DEFAULTS and guards on `defined(SOFAB_OBJECT_COUNT_EXTENT)`; paired
with this corelib that output would read a prefix over 255 B as the whole
object (ASan: global-buffer-overflow in sofab_object_init, reproduced).
With the old name gone, its own guard stops the build instead, until it
emits WITH_PREFIX_DEFAULTS and guards on that.

Verified against generated code, not hand-written descriptors -- current
generator main, #743 as it stands, and #743 switched to the prefix macro,
against this branch under SMALL/MEDIUM/BIG:

  - generator main, realworld: builds, seeds, round-trips; wire identical
    to the prefix build (10 B probe), clean under ASan+UBSan
  - #743 as it stands: refused by its own guard, never silently paired
  - #743 + WITH_PREFIX_DEFAULTS: builds; a 256 B prefix is the named error

test_object_whole_image_longer_than_the_extent_byte pins the case that
broke: a whole image of 304 B whose last member sits at offset 300.

.text is byte-identical to the previous commit on all four targets.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
A new "Descriptor limits" section, linked from the SOFAB_OBJECT_DESCR_PROFILE
row: what the descriptor can hold per profile, what that leaves for each
schema type, the name of the compile error at every limit, and why a
wrapper array runs out long before its element count does (it is one member
of its parent, so its whole byte size meets the profile's `size` ceiling --
10 elements of `string<maxlen: 24>` under SMALL, 2 621 under MEDIUM).

Every number without a footnote was found the same way: a schema at the
limit and one past it, generated with sofabgen (#743 emitting
WITH_PREFIX_DEFAULTS) and compiled against SMALL, MEDIUM and BIG -- N
builds, N+1 fails with the named error, in every row and every profile.
The footnoted ones are the schema's and the wire's own bounds, or follow
from the 32-bit width where the struct at the boundary would be
gigabytes.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
@Andste82
Andste82 merged commit 08ff097 into main Oct 13, 2026
26 checks passed
@Andste82
Andste82 deleted the perf/prefix-default-image branch October 13, 2026 17:37
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant