From 983c988ef5add870f2d05043c41d9ed69df7ecb7 Mon Sep 17 00:00:00 2001 From: Luc Blaeser <112870813+luc-blaeser@users.noreply.github.com> Date: Wed, 11 Sep 2024 13:12:59 +0200 Subject: [PATCH] Fix: Start Wasm table for the RTS at offset >= 1 (#4685) Rust requires a table offset of at least 1 as the element index 0 is considered invalid and causes a debug null check to panic when called. On the other hand, `elem[0]` can be used by the Motoko backend code, as correct Rust-generated Wasm code does not call `elem[0]`. This bug is independent of `wasm32` and `wasm64`. This issue has been observed in https://github.com/dfinity/motoko/actions/runs/10703077671/job/29672766216?pr=4683 and happened only on Linux and only under `nix-build` (not `nix-shell`). --- src/linking/linkModule.ml | 8 +++++++- test/ld/ok/representative.linked.wat.ok | 2 +- 2 files changed, 8 insertions(+), 2 deletions(-) diff --git a/src/linking/linkModule.ml b/src/linking/linkModule.ml index 6adf1535312..55c657285a1 100644 --- a/src/linking/linkModule.ml +++ b/src/linking/linkModule.ml @@ -846,7 +846,13 @@ let link (em1 : extended_module) libname (em2 : extended_module) = ) end else (); - let old_table_size = read_table_size em1.module_ in + let max x y = if x >= y then x else y in (* use `Int.max` when bumping to 4.13 *) + + (* Rust requires a table offset of at least 1 as elem[0] is considered invalid. + There are debug checks panicking if the element index is zero. + On the other hand, elem[0] can be used by the Motoko backend code (em1), + as correct Rust-generated Wasm code does not call elem[0]. *) + let old_table_size = max (read_table_size em1.module_) 1l in let lib_table_start = align_i32 dylink.table_alignment old_table_size in let uses_memory64 = uses_memory64 em1.module_ in diff --git a/test/ld/ok/representative.linked.wat.ok b/test/ld/ok/representative.linked.wat.ok index bcf3c073ec9..076c64ab1df 100644 --- a/test/ld/ok/representative.linked.wat.ok +++ b/test/ld/ok/representative.linked.wat.ok @@ -22,7 +22,7 @@ i32.mul) (func $link_start (type 0) call $__wasm_call_ctors) - (table (;0;) 0 0 funcref) + (table (;0;) 1 1 funcref) (memory (;0;) i64 2) (global (;0;) i64 (i64.const 65536)) (start $link_start))