Repository navigation
perf: a default image may be the PREFIX of an object, not a copy of it - #196
Merged
Merged
Conversation
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.
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>
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Part of sofa-buffers/generator#741. The generator PR that emits prefix images needs this merged first (its
lang-cjob pins this corelib'smain): sofa-buffers/generator —perf/c-prefix-default-image-741.What the image costs today
SOFAB_OBJECT_DESCR_WITH_DEFAULTSdocuments its argument as "a fully-populated object", and every read addresses the image through the field's own offset:object.cinitmemcpy(obj + field->offset, image + field->offset, field->size)object.cinit, sized buffer_load_uint(image + field->offset - width, width)_field_is_default, stringstrncmp(src + off, image + off, size)_field_is_default, sizedimage + off - width, thenmemcmp(image + off, …)_field_is_default, plainmemcmp(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
.rodatato carry 16 bytes of actual defaults — 14.6 % of that target's entire flash image, measured on cortex-m0.What changes
SOFAB_OBJECT_SEQ_HOLDER): all 16 bits stay the element slot count, so anarray<string, count: 300>keeps its 300 slots. A holder never carries an image, so it has no extent to store.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()returningNULLpast 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:
SOFAB_OBJECT_DESCR_WITH_DEFAULTSsizeof(*image), or 0SOFAB_OBJECT_DESCR_WITH_PREFIX_DEFAULTS(new)sizeof(*prefix)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'stests/bench --rows c(vehicle_telemetry,-Os), with the generator emitting prefix images:.textARMv6-m.textARMv7-m+fp.dp.textRV32IMCsizeof(sofab_object_descr_t)The field count is hoisted out of the three loops that had it in their condition: at
-Osthe 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
.textfollowing 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 holds0xDEADBEEFexactly 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 throughWITH_DEFAULTSreads as extent 0 and seeds the member at offset 300: the shape every generated file before this PR has (vehicle_telemetryis 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_UNIONguard.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_PROFILEalready makes for an offset, and it costs no.textor.rodataon any of the four architectures.SOFAB_OBJECT_DESCR_FIELD_COUNT_MAXan_object_may_not_declare_more_than_255_fieldsSOFAB_OBJECT_DESCR_EXTENT_MAXa_prefix_default_image_may_not_exceed_255_bytesSOFAB_OBJECT_DESCR_SLOT_COUNT_MAXa_wrapper_array_may_not_declare_more_than_65535_slotsThe 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 insideobject.h.The image limit is the one with a way out: a whole-object image goes through
SOFAB_OBJECT_DESCR_WITH_DEFAULTSat 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 (astring<maxlen: 300>with a default is enough; ASan reports aglobal-buffer-overflowinsofab_object_initunder 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 inSOFAB_OBJECT_DESCR_SEQ/_SEQ_SIZED. The cast silenced-Woverflow, which was all that stood between a 70 000-slot holder under_BIGand 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_initasked_field_defaulttwice per field -- once for the value, once for a sized buffer's companion length -- and-Osfolded neither call. Asking once, measured on the library alone (tools/footprint.sh's metric):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
sofabgenfrom generatormain(what every existing generated file looks like) and from #743, generated the shippedexamples/messages/realworldschemas plus one probe schema per limit, and compiled them against this branch under_SMALL,_MEDIUMand_BIG:main(whole images)initseeds every default, an all-default message encodes to 0 B, encode → decode → encode round-trips — wire byte-identical to the prefix buildWITH_PREFIX_DEFAULTSa_prefix_default_image_may_not_exceed_255_bytesThe 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 namessofab_object_descr_t::field_counthas to saycount_extent— through the macros nothing changes.SOFAB_OBJECT_COUNT_EXTENTis renamedSOFAB_OBJECT_DESCR_COUNT_WORDon purpose. #743 emits its prefix images throughWITH_DEFAULTSand guards ondefined(SOFAB_OBJECT_COUNT_EXTENT); against this corelib that output would read a prefix over 255 B as the whole object — reproduced, ASanglobal-buffer-overflowinsofab_object_init. #743's lang-c job pins this corelib'smainand 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:SOFAB_OBJECT_DESCR_WITH_PREFIX_DEFAULTSinstead ofWITH_DEFAULTSfor a prefix image;defined(SOFAB_OBJECT_DESCR_WITH_PREFIX_DEFAULTS);WITH_DEFAULTSwhen the defaulted prefix would exceed 255 B — otherwise such a schema generates code that does not compile, where generatormaincompiled 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 (
-Woverflowon a >65 535-slot holder under_BIG, againstmain) is nowa_wrapper_array_may_not_declare_more_than_65535_slots.