| 1 |
|
| 2 | |
| 3 | * Stack protector support for NOLIBC
|
| 4 | * Copyright (C) 2023 Thomas Weißschuh <[email protected]>
|
| 5 |
|
| 6 |
|
| 7 | #ifndef _NOLIBC_STACKPROTECTOR_H
|
| 8 | #define _NOLIBC_STACKPROTECTOR_H
|
| 9 |
|
| 10 | #include "compiler.h"
|
| 11 |
|
| 12 | #ifndef NOLIBC_NO_RUNTIME
|
| 13 | #if defined(_NOLIBC_STACKPROTECTOR)
|
| 14 |
|
| 15 | #include "sys.h"
|
| 16 | #include "stdlib.h"
|
| 17 |
|
| 18 | |
| 19 | * triggering stack protector errors themselves
|
| 20 |
|
| 21 |
|
| 22 | void __stack_chk_fail(void);
|
| 23 | __attribute__((weak,used,noreturn,section(".text.nolibc_stack_chk")))
|
| 24 | void __stack_chk_fail(void)
|
| 25 | {
|
| 26 | pid_t pid;
|
| 27 | __nolibc_syscall3(__NR_write, STDERR_FILENO, "!!Stack smashing detected!!\n", 28);
|
| 28 | pid = __nolibc_syscall0(__NR_getpid);
|
| 29 | __nolibc_syscall2(__NR_kill, pid, SIGABRT);
|
| 30 | for (;;);
|
| 31 | }
|
| 32 |
|
| 33 | void __stack_chk_fail_local(void);
|
| 34 | __attribute__((weak,noreturn,section(".text.nolibc_stack_chk")))
|
| 35 | void __stack_chk_fail_local(void)
|
| 36 | {
|
| 37 | __stack_chk_fail();
|
| 38 | }
|
| 39 |
|
| 40 | __attribute__((weak,used,section(".data.nolibc_stack_chk")))
|
| 41 | uintptr_t __stack_chk_guard;
|
| 42 |
|
| 43 | static __nolibc_no_stack_protector void __stack_chk_init(void)
|
| 44 | {
|
| 45 | __nolibc_syscall3(__NR_getrandom, &__stack_chk_guard, sizeof(__stack_chk_guard),
|
| 46 | GRND_INSECURE | GRND_NONBLOCK);
|
| 47 |
|
| 48 | if (__stack_chk_guard != (uintptr_t) &__stack_chk_guard)
|
| 49 | __stack_chk_guard ^= (uintptr_t) &__stack_chk_guard;
|
| 50 | }
|
| 51 | #else
|
| 52 | static void __stack_chk_init(void) {}
|
| 53 | #endif
|
| 54 | #endif
|
| 55 |
|
| 56 | #endif
|