1 /* SPDX-License-Identifier: LGPL-2.1 OR MIT */
2 /*
3 * Stack protector support for NOLIBC
4 * Copyright (C) 2023 Thomas Weißschuh <linux@weissschuh.net>
5 */
6
7 #ifndef _NOLIBC_STACKPROTECTOR_H
8 #define _NOLIBC_STACKPROTECTOR_H
9
10 #include "compiler.h"
11
12 #if defined(_NOLIBC_STACKPROTECTOR)
13
14 #include "sys.h"
15 #include "stdlib.h"
16
17 /* The functions in this header are using raw syscall macros to avoid
18 * triggering stack protector errors themselves
19 */
20
21 void __stack_chk_fail(void);
22 __attribute__((weak,used,noreturn,section(".text.nolibc_stack_chk")))
__stack_chk_fail(void)23 void __stack_chk_fail(void)
24 {
25 pid_t pid;
26 my_syscall3(__NR_write, STDERR_FILENO, "!!Stack smashing detected!!\n", 28);
27 pid = my_syscall0(__NR_getpid);
28 my_syscall2(__NR_kill, pid, SIGABRT);
29 for (;;);
30 }
31
32 void __stack_chk_fail_local(void);
33 __attribute__((weak,noreturn,section(".text.nolibc_stack_chk")))
__stack_chk_fail_local(void)34 void __stack_chk_fail_local(void)
35 {
36 __stack_chk_fail();
37 }
38
39 __attribute__((weak,used,section(".data.nolibc_stack_chk")))
40 uintptr_t __stack_chk_guard;
41
__stack_chk_init(void)42 static __no_stack_protector void __stack_chk_init(void)
43 {
44 my_syscall3(__NR_getrandom, &__stack_chk_guard, sizeof(__stack_chk_guard), 0);
45 /* a bit more randomness in case getrandom() fails, ensure the guard is never 0 */
46 if (__stack_chk_guard != (uintptr_t) &__stack_chk_guard)
47 __stack_chk_guard ^= (uintptr_t) &__stack_chk_guard;
48 }
49 #else /* !defined(_NOLIBC_STACKPROTECTOR) */
__stack_chk_init(void)50 static void __stack_chk_init(void) {}
51 #endif /* defined(_NOLIBC_STACKPROTECTOR) */
52
53 #endif /* _NOLIBC_STACKPROTECTOR_H */
54