Path: blob/master/tools/include/nolibc/stackprotector.h
49156 views
/* SPDX-License-Identifier: LGPL-2.1 OR MIT */1/*2* Stack protector support for NOLIBC3* Copyright (C) 2023 Thomas Weißschuh <[email protected]>4*/56#ifndef _NOLIBC_STACKPROTECTOR_H7#define _NOLIBC_STACKPROTECTOR_H89#include "compiler.h"1011#ifndef NOLIBC_NO_RUNTIME12#if defined(_NOLIBC_STACKPROTECTOR)1314#include "sys.h"15#include "stdlib.h"1617/* The functions in this header are using raw syscall macros to avoid18* triggering stack protector errors themselves19*/2021void __stack_chk_fail(void);22__attribute__((weak,used,noreturn,section(".text.nolibc_stack_chk")))23void __stack_chk_fail(void)24{25pid_t pid;26my_syscall3(__NR_write, STDERR_FILENO, "!!Stack smashing detected!!\n", 28);27pid = my_syscall0(__NR_getpid);28my_syscall2(__NR_kill, pid, SIGABRT);29for (;;);30}3132void __stack_chk_fail_local(void);33__attribute__((weak,noreturn,section(".text.nolibc_stack_chk")))34void __stack_chk_fail_local(void)35{36__stack_chk_fail();37}3839__attribute__((weak,used,section(".data.nolibc_stack_chk")))40uintptr_t __stack_chk_guard;4142static __no_stack_protector void __stack_chk_init(void)43{44my_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 */46if (__stack_chk_guard != (uintptr_t) &__stack_chk_guard)47__stack_chk_guard ^= (uintptr_t) &__stack_chk_guard;48}49#else /* !defined(_NOLIBC_STACKPROTECTOR) */50static void __stack_chk_init(void) {}51#endif /* defined(_NOLIBC_STACKPROTECTOR) */52#endif /* NOLIBC_NO_RUNTIME */5354#endif /* _NOLIBC_STACKPROTECTOR_H */555657