From 2171b2cd744541ca9afdb5736033cbc00fae2a90 Mon Sep 17 00:00:00 2001 From: Miriam Polzer Date: Wed, 25 Nov 2026 11:50:06 +0100 Subject: [PATCH] ToCString: word-align stackalloc buffers Printed code accesses memory bytewise or through memcpy, but stackalloc'd buffers are often passed to external C that takes word pointers (e.g. fiat-crypto field arithmetic in BoringSSL), where an underaligned uint8_t array is undefined behavior (observed with UBSan on 32-bit) and can fault on strict-alignment targets. The semantics lets stackalloc return any address, so choosing a word-aligned one is a refinement; the RISC-V compiler already does so. The prelude defines BR_STACKALLOC_ALIGN unless it is already defined; code printed with c_func but without the prelude must define it (possibly empty). --- bedrock2/src/bedrock2/ToCString.v | 9 ++++++++- 1 file changed, 8 insertions(+), 1 deletion(-) diff --git a/bedrock2/src/bedrock2/ToCString.v b/bedrock2/src/bedrock2/ToCString.v index 5eb7d7600..30afaa341 100644 --- a/bedrock2/src/bedrock2/ToCString.v +++ b/bedrock2/src/bedrock2/ToCString.v @@ -7,6 +7,7 @@ Definition prelude := "// Generated from Bedrock code. Avoid editing directly. #include #include #include +#include #define BR_WORD_MAX UINTPTR_MAX typedef uintptr_t br_word_t; @@ -28,6 +29,12 @@ static_assert(~(br_signed_t)0 == -(br_signed_t)1, ""two's complement""); #error ""failed to confirm that target is little-endian"" #endif +// Word-align stackalloc buffers so they can be passed to external code that +// takes word pointers. Define BR_STACKALLOC_ALIGN empty for byte alignment. +#ifndef BR_STACKALLOC_ALIGN +#define BR_STACKALLOC_ALIGN alignas(br_word_t) +#endif + // ""An object shall have its stored value accessed only ... a character type."" static inline br_word_t _br_load1(br_word_t a) { return *((uint8_t *)a); @@ -224,7 +231,7 @@ Fixpoint c_cmd (indent : string) (c : cmd) : string := * favoring readability over timely deallocation (which clang et al don't * do anyway. However, name collisions can cause compilation errors. *) let tmp := "_br_stackalloc_"++x in - indent ++ "uint8_t "++tmp++"["++c_lit n++"] = {0}; "++x++" = (br_word_t)&"++tmp++";"++LF++ + indent ++ "BR_STACKALLOC_ALIGN uint8_t "++tmp++"["++c_lit n++"] = {0}; "++x++" = (br_word_t)&"++tmp++";"++LF++ c_cmd indent body | cmd.set x (expr.inlinetable s t ei) => indent ++ "{ " ++ c_inlinetable t ++ " " ++ x ++ " = " ++ c_loadtable s (c_expr ei) ++ "; }" ++ LF