Path: blob/master/tools/include/nolibc/stackprotector.h
26288 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#if defined(_NOLIBC_STACKPROTECTOR)1213#include "sys.h"14#include "stdlib.h"1516/* The functions in this header are using raw syscall macros to avoid17* triggering stack protector errors themselves18*/1920void __stack_chk_fail(void);21__attribute__((weak,used,noreturn,section(".text.nolibc_stack_chk")))22void __stack_chk_fail(void)23{24pid_t pid;25my_syscall3(__NR_write, STDERR_FILENO, "!!Stack smashing detected!!\n", 28);26pid = my_syscall0(__NR_getpid);27my_syscall2(__NR_kill, pid, SIGABRT);28for (;;);29}3031void __stack_chk_fail_local(void);32__attribute__((weak,noreturn,section(".text.nolibc_stack_chk")))33void __stack_chk_fail_local(void)34{35__stack_chk_fail();36}3738__attribute__((weak,used,section(".data.nolibc_stack_chk")))39uintptr_t __stack_chk_guard;4041static __no_stack_protector void __stack_chk_init(void)42{43my_syscall3(__NR_getrandom, &__stack_chk_guard, sizeof(__stack_chk_guard), 0);44/* a bit more randomness in case getrandom() fails, ensure the guard is never 0 */45if (__stack_chk_guard != (uintptr_t) &__stack_chk_guard)46__stack_chk_guard ^= (uintptr_t) &__stack_chk_guard;47}48#else /* !defined(_NOLIBC_STACKPROTECTOR) */49static void __stack_chk_init(void) {}50#endif /* defined(_NOLIBC_STACKPROTECTOR) */5152#endif /* _NOLIBC_STACKPROTECTOR_H */535455