1 /*
2 * Copyright (c) 2018 Intel Corporation
3 *
4 * SPDX-License-Identifier: Apache-2.0
5 */
6
7 /**
8 * @file
9 * @brief Thread entry
10 *
11 * This file provides the common thread entry function
12 */
13
14 #include <zephyr/kernel.h>
15 #include <zephyr/arch/cfi.h>
16 #ifdef CONFIG_CURRENT_THREAD_USE_TLS
17 #include <zephyr/random/random.h>
18
19 Z_THREAD_LOCAL k_tid_t z_tls_current;
20 #endif
21
22 #ifdef CONFIG_STACK_CANARIES_TLS
23 extern Z_THREAD_LOCAL volatile uintptr_t __stack_chk_guard;
24 #endif /* CONFIG_STACK_CANARIES_TLS */
25
26 /*
27 * Common thread entry point function (used by all threads)
28 *
29 * This routine invokes the actual thread entry point function and passes
30 * it three arguments. It also handles graceful termination of the thread
31 * if the entry point function ever returns.
32 *
33 * This routine does not return, and is marked as such so the compiler won't
34 * generate preamble code that is only used by functions that actually return.
35 */
z_thread_entry(k_thread_entry_t entry,void * p1,void * p2,void * p3)36 FUNC_NORETURN void z_thread_entry(k_thread_entry_t entry,
37 void *p1, void *p2, void *p3)
38 {
39 /*
40 * Inform the unwinder that the current return address is undefined.
41 *
42 * This is typically used at points in the code where execution does not
43 * return like a normal function (for example, thread entry routines).
44 * Marking the return address as undefined prevents stack unwinding or
45 * backtrace tools from following a bogus return address, which could
46 * otherwise lead to reading invalid memory and cause faults during
47 * unwinding or debugging.
48 */
49 ARCH_CFI_UNDEFINED_RETURN_ADDRESS();
50 #ifdef CONFIG_CURRENT_THREAD_USE_TLS
51 z_tls_current = k_sched_current_thread_query();
52 #endif
53 #ifdef CONFIG_STACK_CANARIES_TLS
54 uintptr_t stack_guard;
55
56 sys_rand_get((uint8_t *)&stack_guard, sizeof(stack_guard));
57 __stack_chk_guard = stack_guard;
58 __stack_chk_guard <<= 8;
59 #endif /* CONFIG_STACK_CANARIES */
60 entry(p1, p2, p3);
61
62 k_thread_abort(k_current_get());
63
64 /*
65 * Compiler can't tell that k_thread_abort() won't return and issues a
66 * warning unless we tell it that control never gets this far.
67 */
68
69 CODE_UNREACHABLE; /* LCOV_EXCL_LINE */
70 }
71