Skip to content

Add support for native records (OTP29 & OTP30) - #2470

Open
pguyot wants to merge 3 commits into
atomvm:release-0.7from
pguyot:w20/native-records
Open

pguyot wants to merge 3 commits into
atomvm:release-0.7from
pguyot:w20/native-records

Conversation

@pguyot

@pguyot pguyot commented Nov 8, 2026

Copy link
Copy Markdown
Collaborator

These changes are made under both the "Apache 2.0" and the "GNU Lesser General
Public License 2.1 or later" license terms (dual license).

SPDX-License-Identifier: Apache-2.0 OR LGPL-2.1-or-later

Comment thread src/libAtomVM/bif.c Fixed
@pguyot
pguyot force-pushed the w20/native-records branch from 1c6a1c6 to 64002e5 Compare November 8, 2026 21:52

@bettio bettio left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Let's start with a round of automated review.

Comment thread libs/jit/src/jit.erl
%% per-field name lookup. Discard Id and FailLabel (the
%% record-type guard is statically satisfied; no field can be
%% missing because the JIT verified the layout at compile time).
Rest3 = skip_compact_term(Rest2),

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

When Src has a tracked record type, the Id operand is skipped and the field is loaded by position from the tracked layout. With f(X) when is_record(X, other) -> X#pair.a the OTP 29 compiler emits is_native_record(other) followed by get_record_field ... pair a in the same block, so the JIT returns X's a where the interpreter (and BEAM) raise {badrecord, X}. Take the fast path only when Id is the tracked record's name atom (or {ThisModule, Name}); store the name in the info recorded by track_if_local, otherwise fall back to get_record_field_generic.

Comment thread src/libAtomVM/jit.c Outdated
return dst;
}

static term jit_put_record(Context *ctx, JITState *jit_state, term id, term src, uint32_t num_pairs, term *kv)

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

jit_put_record (lines 573, 579, 596, 614) and jit_put_record_resolved (529, 532, 549) call raise_badrecord/raise_badfield, which run memory_ensure_free* with no x-register roots (memory_gc never scans ctx->x, and a GC is forced whenever heap fragments exist, which literal values/defaults create). On the JIT side handle_error_or_jump_if at jit.erl:4902 and :5154 then jumps to Fail when it is non-zero, so execution continues with stale x registers and a dangling exception set. OTP 30 emits non-zero fail labels here (the PR's own test_fail_label relies on it), and the interpreter version correctly checks fail_label before raising. Pass fail_label into both primitives and return term_invalid_term() without raising when it is non-zero, as jit_get_record_field already does.

Comment thread src/libAtomVM/opcodesswitch.h Outdated
const struct RecordDef *def = term_get_record_def(src);
bool id_matches = false;
if (term_is_atom(id)) {
id_matches = (id == def->name);

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The compiler encodes X#.a as get_record_field with Id '' (valid OTP 29 syntax, returns the field on BEAM). The atom branch requires id == def->name, so AtomVM raises {badrecord, X} on both interpreter and JIT. Same check in bif.c:429 and jit.c:485. ERTS skips the name check when the id is '_' (erl_get_local_record_field); a default atom for _ is needed since none exists.

Comment thread src/libAtomVM/module.c
return 2;
case COMPACT_NBITS_VALUE: {
int sz = (first_byte >> 5) + 2;
if (sz > 8) {

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

record_compact_term_byte_len returns 0 for the 9+ byte integer encoding (0xF9, length byte, N bytes) that beam_asm emits for |N| >= 2^63, so the loader aborts with "Recs chunk truncated or malformed" and the whole module fails to load. Verified with -record(#r{big = 16#FFFFFFFFFFFFFFFFFF}); all other default kinds (negative, float, binary, nil, map, 8-byte ints) load fine. module_decode_record_default at line 1219 has the same cutoff. Both should accept the extended-length form like the interpreter's decode_nbits_integer does.

Comment thread src/libAtomVM/opcodesswitch.h Outdated
bool id_matches = false;
if (term_is_atom(id)) {
id_matches = (id == def->name);
} else if (term_is_tuple(id) && term_get_tuple_arity(id) == 2) {

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

(also bif.c:430, jit.c:486): with a {Module, Name} id, ERTS raises {badrecord, R} when the record is not exported; AtomVM returns the value, so R#mod:rec.field bypasses record encapsulation. A missing field raises badarg (line 6715, bif.c:448, jit.c:505) where ERTS raises {badfield, {{Module, Name}, Field}}. Both verified against OTP 29 with a two-module test.

Comment thread src/libAtomVM/opcodesswitch.h Outdated
pc = mod->labels[fail_label];
break;
}
RAISE_ERROR(BADARG_ATOM);

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

OTP 29 raises {badfield, {{rec_exp_ext, vector}, w}} for V#rec_exp_ext:vector.w; this path raises plain badarg (same in bif.c:448 and jit.c:505, and erlang.erl documents the badarg). raise_badfield already builds the right term, so use it in the three places and fix the doc.

Comment thread src/libAtomVM/opcodesswitch.h Outdated
DECODE_ATOM(hint, pc);
UNUSED(hint);
}
// The compiler emits id as either an atom literal or a

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

module_load_literal copies the literal into a heap fragment appended to the context heap, so after the GC at line 6563 a {Module, Name} id is stale. It is only read afterwards at lines 6587 and 6597 (OOM or undecodable default), so no practical impact, but either re-decode id from its pc after the GC or raise with def->name and drop the comment.

%% [EEP-0079](https://www.erlang.org/eeps/eep-0079) that AtomVM supports
%% today. The functions in this module are intended for debugging,
%% inspecting record values at runtime, and implementing tools such as
%% printers. Production code should prefer the `Expr#Name.Field' syntax

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This doc says the module is meant for implementing printers, but io_lib:format("~p", [Rec]) currently fails with function_clause because format_spw in io_lib.erl has no record clause (records are not tuples, so they match nothing). OTP 29 prints #fmt:pair{a = 1,b = [x,y]} for both ~w and ~p. A clause before the tuple one at io_lib.erl:339 using records:get_module/1, records:get_name/1, records:get_field_names/1 and records:get/2 would cover it.

Comment thread src/libAtomVM/bifs.gperf
erlang:is_port/1, {.bif.base.type = BIFFunctionType, .bif.bif1_ptr = bif_erlang_is_port_1}
erlang:is_reference/1, {.bif.base.type = BIFFunctionType, .bif.bif1_ptr = bif_erlang_is_reference_1}
erlang:is_tuple/1, {.bif.base.type = BIFFunctionType, .bif.bif1_ptr = bif_erlang_is_tuple_1}
erlang:is_record/1, {.bif.base.type = BIFFunctionType, .bif.bif1_ptr = bif_erlang_is_record_1}

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The OTP 29 compiler turns the body call into is_any_native_record followed by {bif, is_record/3, ...}. There is no erlang:is_record/3 in the BIF table, so OP_BIF3 (opcodesswitch.h:6367) reads bif3_ptr out of an unresolved import entry and jumps to a wild address. A three-line module (chk(X) -> erlang:is_record(X, mymod, pair).) segfaults on both the interpreter and the JIT, where BEAM returns true/false. Add a bif3 for erlang:is_record/3 that handles (Term, Module, Name) for native records and (Term, Tag, Arity) for tuples, next to bif_erlang_is_record_2 at bif.c:370. The guard form already works because it compiles to is_native_record.

Comment thread src/libAtomVM/term.h
/**
* @brief Returns \c true if a term is a native record.
*/
static inline bool term_is_record(term t)

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

hash_term_incr in ets_multimap.c walks the term_is_* predicates and has no term_is_record branch, so every insert/lookup with a record key logs this line to stderr (line 750) and all records land in the same bucket. Hashing module, name and the field values the way the tuple branch does is enough, since term_compare already decides equality.

@bettio

bettio commented Nov 9, 2026

Copy link
Copy Markdown
Collaborator

Let's also remember to merge this PR after atomvm_packbeam

@bettio bettio left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Another round of automated review before manual one.

Comment thread libs/jit/src/jit_precompile.erl Outdated
<<_, _, Rest/binary>> = Bin,
Rest;
?COMPACT_NBITS_VALUE ->
Total = 1 + ((First bsr 5) + 2),

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

recs_skip_large_imm/1 skips 1 + ((First bsr 5) + 2) bytes, but when (First bsr 5) + 2 > 8 the encoding is the extended form (first byte, a compact literal N, then 9 + N bytes), exactly what commit efe35f0 handles in record_compact_term_byte_len in module.c. The parser then reads garbage atom indices and crashes (function_clause in lists:nth).

The PR's own test_native_records.beam has such a default (with_bigint_default), so cmake -DAVM_DISABLE_JIT=OFF with OTP 29 fails to build. Mirror the C code:

?COMPACT_NBITS_VALUE ->
    case (First bsr 5) + 2 of
        Sz when Sz > 8 ->
            <<_, Rest0/binary>> = Bin,
            {N, Rest1} = recs_decode_value(Rest0),
            <<_Skip:(9 + N)/binary, Rest/binary>> = Rest1,
            Rest;
        Sz ->
            <<_Skip:(1 + Sz)/binary, Rest/binary>> = Bin,
            Rest
    end

With this change the JIT build completes and test-erlang passes 484/484 on x86_64, including test_native_records.

Comment thread libs/jit/src/jit.erl Outdated
undefined -> not_local;
Info -> {ok, Info, Rest}
end;
{Mod, Name} when is_atom(Mod), is_atom(Name) ->

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

OTP 29 compiles #?MODULE:nodef{zz = 1} and #?MODULE:nodef{b = 3} (missing required field) with only warnings and raises badfield / novalue at run time. Because this clause resolves the literal tuple as local, put_record_resolved hits error({jit, unknown_record_field, zz}) at line 4894, so the whole module fails to JIT-compile (and to precompile). It also skips the exported check that ERTS applies to every {Module, Name} creation. Return not_local for tuple ids (the generic path raises badfield at run time); the compiler only guarantees field validity for plain atom ids.

def = module_find_record_def(mod, id);
} else if (term_is_tuple(id) && term_get_tuple_arity(id) == 2) {
// Cross-module record: literal {Module, Name}.
def = module_find_record_def_global(ctx->global,

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

ERTS (erl_create_native_record) raises {badrecord, {Module, Name}} unless is_exported is true. On the branch #test_native_records_ext:unexported{a = 1, b = 2} from another module succeeds, which bypasses record encapsulation on the creation side (the read side was fixed in 6416ed5). Add if (!def->is_exported) def = NULL; after this lookup (only in the src nil branch; updates are already guarded by is_record_accessible).

Comment thread src/libAtomVM/jit.c Outdated
return module_find_record_def(jit_state->module, id);
}
if (term_is_tuple(id) && term_get_tuple_arity(id) == 2) {
return module_find_record_def_global(ctx->global,

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Same bug as the interpreter for the generic JIT path: a {Module, Name} creation must fail with {badrecord, Id} when the record is not exported.

Comment thread src/libAtomVM/bif.c Outdated
return term_invalid_term();
}

term record_get_field(Context *ctx, uint32_t fail_label, term current_module, term src, term id, term field)

@bettio bettio Nov 11, 2026 •

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The exported check a few lines below (def->is_exported || def->module == current_module) is laxer than ERTS: erl_get_record_field raises badrecord whenever the record is not exported, even inside the defining module. On OTP 29 P#avm_exp:pair.a with an unexported pair raises {badrecord, P}, AtomVM returns the value. Keep only def->is_exported; the current_module parameter then becomes unnecessary.

HANDLE_ERROR();
}
for (size_t i = 0; i < num_fields; i++) {
if (def->fields[i].default_encoded == NULL) {

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

When a record is created and a field without a default is not in the update list, OTP 29 raises {novalue, {{Module, Name}, Field}} (a badfield takes priority). On the branch #rec_ext2:nodef{b = 3} yields #rec_ext2:nodef{a = [], b = 3}. This is reachable for any exported record created from another module. After applying the updates, raise novalue for the first field that has default_encoded == NULL and was not provided (a novalue atom needs adding).

Comment thread src/libAtomVM/jit.c
term_put_record_value(dst, i, term_nil());
}
for (size_t i = 0; i < num_fields; i++) {
if (def->fields[i].default_encoded == NULL) {

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Same silent [] as the interpreter (verified on the x86_64 JIT); jit_put_record_resolved at line 525 needs it too if tuple ids keep using that path.

@pguyot
pguyot force-pushed the w20/native-records branch 2 times, most recently from 4ee69cf to 40e01dc Compare November 15, 2026 09:43

@bettio bettio left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Another round of automated reviews. Found a problem here.

Comment thread libs/jit/src/jit_wasm32.erl Outdated
%% @doc Record a type assertion for a VM x/y register. The assertion is
%% invalidated automatically by the same hooks that invalidate `regs` tracking
%% (writes to the VM register, C calls clobbering x regs, labels).
set_vm_record_type(#state{regs = Regs} = State, VmLoc, Type) ->

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The native backends drop a register's tracked type when the register is written; jit_wasm32 never does, because it has no write tracking (jit_regs:invalidate_vm_loc is never called). So a type recorded here outlives the value until the next C call or label.

OTP 29 compiles case R of #outer{i = #_{i = V}} -> V; _ -> none end to is_native_record x0 outer, get_record_elements x0 [i -> x0], is_any_native_record x0, is_record_accessible x0 auto_local, get_record_elements x0 [i -> x0]. On wasm32 the last two still treat x0 as #outer{}. The accessibility check is folded away and the inner record's i is read at outer's fixed offset. That gives the wrong field, a read past the end of a smaller record, or access to a non-exported record from another module.

Please make this a no-op on wasm32 (set_vm_record_type(State, _VmLoc, Type) -> State.) and add this nested # pattern to the tests.

Native records (EEP-79) are a new term type introduced in OTP 29.

- Load the Recs chunk and keep per-module record definitions, with defaults
  encoded as compact terms (including integers that don't fit in 64 bits).
- New term type with GC, comparison, hashing (ETS bags), copy and external
  term (RECORD_EXT) support.
- Interpreter and JIT support for the OTP 29 instructions (is_any_native_record,
  is_native_record, get_record_elements, put_record, is_record_accessible,
  get_record_field, update_record) and the OTP 30 ones
  (get_record_elements_id, update_record_id, the records allocator tag,
  non-zero fail labels), with ERTS-compatible badrecord, badfield and novalue
  errors and export checks.
- JIT: track record layouts after type tests, invalidated on stack trim.
- erlang:is_record/3 BIF, 3-arity BIF calls through call_ext, the records
  module and code_server:record_resolver/2 for the JIT precompiler.

Signed-off-by: Paul Guyot <pguyot@kallisys.net>
Signed-off-by: Paul Guyot <pguyot@kallisys.net>
wasm32 has no register write tracking, so a recorded record type outlived
the value written to the register. With nested patterns such as
#outer{i = #_{i = V}}, the inner record was then read using the outer
record's layout. Make set_vm_record_type a no-op and cover the nested
pattern in test_native_records.

Signed-off-by: Paul Guyot <pguyot@kallisys.net>
@pguyot
pguyot force-pushed the w20/native-records branch from e2c631c to 3fe7508 Compare December 5, 2026 05:51
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.

3 participants