stackprotector.h 1.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455
  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. #ifndef _NOLIBC_STACKPROTECTOR_H
  7. #define _NOLIBC_STACKPROTECTOR_H
  8. #include "compiler.h"
  9. #ifndef NOLIBC_NO_RUNTIME
  10. #if defined(_NOLIBC_STACKPROTECTOR)
  11. #include "sys.h"
  12. #include "stdlib.h"
  13. /* The functions in this header are using raw syscall macros to avoid
  14. * triggering stack protector errors themselves
  15. */
  16. void __stack_chk_fail(void);
  17. __attribute__((weak,used,noreturn,section(".text.nolibc_stack_chk")))
  18. void __stack_chk_fail(void)
  19. {
  20. pid_t pid;
  21. my_syscall3(__NR_write, STDERR_FILENO, "!!Stack smashing detected!!\n", 28);
  22. pid = my_syscall0(__NR_getpid);
  23. my_syscall2(__NR_kill, pid, SIGABRT);
  24. for (;;);
  25. }
  26. void __stack_chk_fail_local(void);
  27. __attribute__((weak,noreturn,section(".text.nolibc_stack_chk")))
  28. void __stack_chk_fail_local(void)
  29. {
  30. __stack_chk_fail();
  31. }
  32. __attribute__((weak,used,section(".data.nolibc_stack_chk")))
  33. uintptr_t __stack_chk_guard;
  34. static __no_stack_protector void __stack_chk_init(void)
  35. {
  36. my_syscall3(__NR_getrandom, &__stack_chk_guard, sizeof(__stack_chk_guard), 0);
  37. /* a bit more randomness in case getrandom() fails, ensure the guard is never 0 */
  38. if (__stack_chk_guard != (uintptr_t) &__stack_chk_guard)
  39. __stack_chk_guard ^= (uintptr_t) &__stack_chk_guard;
  40. }
  41. #else /* !defined(_NOLIBC_STACKPROTECTOR) */
  42. static void __stack_chk_init(void) {}
  43. #endif /* defined(_NOLIBC_STACKPROTECTOR) */
  44. #endif /* NOLIBC_NO_RUNTIME */
  45. #endif /* _NOLIBC_STACKPROTECTOR_H */