Skip to content

Commit ef844ce

Browse files
rbbrnsjhedberg
authored andcommitted
kernel: make k_is_pre_kernel safe to call from user mode
Make k_is_pre_kernel safe to call from user mode. Since z_sys_post_kernel memory is not accessible to user threads, calling k_is_pre_kernel would result in a memory access fault. This change adds k_is_user_context guard. It can be assumed the system is post-kernel if k_is_user_context is true. Signed-off-by: Rob Barnes <[email protected]>
1 parent 2487fe9 commit ef844ce

File tree

2 files changed

+21
-0
lines changed

2 files changed

+21
-0
lines changed

include/zephyr/kernel.h

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1289,6 +1289,15 @@ static inline bool k_is_pre_kernel(void)
12891289
{
12901290
extern bool z_sys_post_kernel; /* in init.c */
12911291

1292+
/*
1293+
* If called from user mode, it must already be post kernel.
1294+
* This guard is necessary because z_sys_post_kernel memory
1295+
* is not accessible to user threads.
1296+
*/
1297+
if (k_is_user_context()) {
1298+
return false;
1299+
}
1300+
12921301
return !z_sys_post_kernel;
12931302
}
12941303

tests/kernel/mem_protect/userspace/src/main.c

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -110,6 +110,18 @@ ZTEST_USER(userspace, test_is_usermode)
110110
zassert_true(k_is_user_context(), "thread left in kernel mode");
111111
}
112112

113+
/**
114+
* @brief Test to check if k_is_pre_kernel works from user mode
115+
*
116+
* @ingroup kernel_memprotect_tests
117+
*/
118+
ZTEST_USER(userspace, test_is_post_kernel)
119+
{
120+
clear_fault();
121+
122+
zassert_false(k_is_pre_kernel(), "still pre-kernel in user mode");
123+
}
124+
113125
/**
114126
* @brief Test to write to a control register
115127
*

0 commit comments

Comments
 (0)