projects/linux·blob uaccess-cleanups · refs

56 lines · 1.6 KiB

1/* SPDX-License-Identifier: LGPL-2.1 OR MIT */
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/* The functions in this header are using raw syscall macros to avoid
19 * triggering stack protector errors themselves
20 */
21
22void __stack_chk_fail(void);
23__attribute__((weak,used,noreturn,section(".text.nolibc_stack_chk")))
24void __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
33void __stack_chk_fail_local(void);
34__attribute__((weak,noreturn,section(".text.nolibc_stack_chk")))
35void __stack_chk_fail_local(void)
36{
37 __stack_chk_fail();
38}
39
40__attribute__((weak,used,section(".data.nolibc_stack_chk")))
41uintptr_t __stack_chk_guard;
42
43static __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 /* a bit more randomness in case getrandom() fails, ensure the guard is never 0 */
48 if (__stack_chk_guard != (uintptr_t) &__stack_chk_guard)
49 __stack_chk_guard ^= (uintptr_t) &__stack_chk_guard;
50}
51#else /* !defined(_NOLIBC_STACKPROTECTOR) */
52static void __stack_chk_init(void) {}
53#endif /* defined(_NOLIBC_STACKPROTECTOR) */
54#endif /* NOLIBC_NO_RUNTIME */
55
56#endif /* _NOLIBC_STACKPROTECTOR_H */