[PATCH master 1/4] KASan: fix possible breakage with CONFIG_INIT_STACK_ALL

Ahmad Fatoum a.fatoum at pengutronix.de
Tue Apr 22 00:55:16 PDT 2025


From: Ahmad Fatoum <a.fatoum at barebox.org>

With CONFIG_INIT_STACK_ALL_PATTERN or CONFIG_INIT_STACK_ALL_ZERO,
the compiler emits calls to memset to initialize variables on the stack.

With kasan enabled, this would end up calling KASAN memset, which can
lead to access of global variables prior to relocation.

Brace ourselves for this situation by sidestepping KASAN prior to
relocation.

Signed-off-by: Ahmad Fatoum <a.fatoum at barebox.org>
---
 lib/kasan/generic.c | 11 +++++++++++
 1 file changed, 11 insertions(+)

diff --git a/lib/kasan/generic.c b/lib/kasan/generic.c
index 66eebac15600..dda80f790151 100644
--- a/lib/kasan/generic.c
+++ b/lib/kasan/generic.c
@@ -17,6 +17,7 @@
 #define pr_fmt(fmt) "kasan: generic: " fmt
 
 #include <common.h>
+#include <asm/reloc.h>
 
 #include "kasan.h"
 
@@ -160,6 +161,16 @@ static __always_inline bool check_memory_region_inline(unsigned long addr,
 						size_t size, bool write,
 						unsigned long ret_ip)
 {
+	/*
+	 * Hardening options like -ftrivial-auto-var-init=zero can end up
+	 * emitting memset calls to initialize stack variables.
+	 * This can lead to this function reached before relocation.
+	 *
+	 * Play it safe by ensuring we are relocated before proceeding.
+	 */
+	if (global_variable_offset() != 0)
+		return true;
+
 	if (!kasan_initialized)
 		return true;
 
-- 
2.39.5




More information about the barebox mailing list