lib: sbi: add UBSan support

UBSan (Undefined Behavior Sanitizer) is a tool implemented using
compiler instrumentation at runtime that allows checking for
statements whose output is not deterministic or defined by the C
standard. Compiling and running OpenSBI with UBSan instrumentation
will print a message in the console if any sentence performs such
an action.

Support involves two main components:
1. The UBSan implementation hooks (derived from NetBSD),
   used by the compiler to handle the check output.
2. A test suite integrated with the SBI unit test framework to
   verify correct operation at runtime.

Usage:

  make UBSAN=y PLATFORM=generic ...

The test suite is built when both UBSAN=y and CONFIG_SBIUNIT=y are
enabled.

When UBSan is enabled, FW_PAYLOAD_OFFSET may need to be increased
due to the size increase added by the instrumentation. A
value of 0x400000 has been tested.

UBSan adds runtime overhead and is intended for development builds
only, not for production.

Note: This patch marks __stack_chk_guard in sbi_init.c as a weak
symbol to prevent multiple definition errors at compile time with
UBSan instrumentation enabled. This resolves the conflict
between the .globl definitions in sbi_init.c and test_head.S.

Signed-off-by: Marcos Oduardo <marcos.oduardo@gmail.com>
Reviewed-by: Anup Patel <anup@brainfault.org>
Link: https://lore.kernel.org/r/20260515163321.2038366-1-marcos.oduardo@gmail.com
Signed-off-by: Anup Patel <anup@brainfault.org>
This commit is contained in:
Marcos Oduardo
2026-05-15 18:33:21 +02:00
committed by Anup Patel
parent c175c97a27
commit 7bdcf55705
7 changed files with 1078 additions and 1 deletions
+17
View File
@@ -455,6 +455,23 @@ else
CFLAGS += -O2
endif
ifeq ($(UBSAN),y)
UBSAN_CC_FLAGS := -fsanitize=undefined
UBSAN_CC_FLAGS += -DUBSAN_ENABLED
UBSAN_CC_FLAGS += -fno-sanitize=vptr
UBSAN_CC_FLAGS += -fno-sanitize=float-cast-overflow
UBSAN_CC_FLAGS += -fno-sanitize=float-divide-by-zero
UBSAN_CC_FLAGS += -fsanitize-recover=undefined
UBSAN_CC_FLAGS += -fsanitize=pointer-overflow
UBSAN_CC_FLAGS += -fsanitize=alignment
UBSAN_CC_FLAGS += -fno-sanitize-recover=alignment
UBSAN_CC_FLAGS += -fno-stack-protector
ifeq ($(LLVM), y)
UBSAN_CC_FLAGS += -fno-sanitize-link-runtime
endif
CFLAGS += $(UBSAN_CC_FLAGS)
endif
ifeq ($(V), 1)
ELFFLAGS += -Wl,--print-gc-sections
endif