From c661765f1d4d479a24b240f9fae2752eb1fc0aa6 Mon Sep 17 00:00:00 2001 From: Daniel Leung Date: Fri, 5 Feb 2021 09:16:00 -0800 Subject: [PATCH] arm: cortex-m: setup TLS pointer before switching to main The TLS global pointer is only set during context switch. So for the first switch to main thread, the TLS pointer is NULL which would cause access violation when trying to access any thread local variables in main thread. Fix it by setting it before going into main thread. Signed-off-by: Daniel Leung --- arch/arm/core/aarch32/thread.c | 13 +++++++++++++ 1 file changed, 13 insertions(+) diff --git a/arch/arm/core/aarch32/thread.c b/arch/arm/core/aarch32/thread.c index 7847171996f..746ec23c691 100644 --- a/arch/arm/core/aarch32/thread.c +++ b/arch/arm/core/aarch32/thread.c @@ -509,6 +509,19 @@ void arch_switch_to_main_thread(struct k_thread *main_thread, char *stack_ptr, z_arm_prepare_switch_to_main(); _current = main_thread; + +#if defined(CONFIG_THREAD_LOCAL_STORAGE) && defined(CONFIG_CPU_CORTEX_M) + /* On Cortex-M, TLS uses a global variable as pointer to + * the thread local storage area. So this needs to point + * to the main thread's TLS area before switching to any + * thread for the first time, as the pointer is only set + * during context switching. + */ + extern uintptr_t z_arm_tls_ptr; + + z_arm_tls_ptr = main_thread->tls; +#endif + #ifdef CONFIG_INSTRUMENT_THREAD_SWITCHING z_thread_mark_switched_in(); #endif