setjmp.h 2.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485
  1. /*
  2. * Copyright (c) 2018-2020, Andreas Kling <kling@serenityos.org>
  3. *
  4. * SPDX-License-Identifier: BSD-2-Clause
  5. */
  6. #pragma once
  7. #include <bits/stdint.h>
  8. #include <signal.h>
  9. #include <stdbool.h>
  10. #include <sys/cdefs.h>
  11. #include <sys/types.h>
  12. __BEGIN_DECLS
  13. //
  14. // /!\ This structure is accessed inside setjmp.S, keep both files in sync!
  15. //
  16. struct __jmp_buf {
  17. #if defined(__x86_64__)
  18. uint64_t rbx;
  19. uint64_t r12;
  20. uint64_t r13;
  21. uint64_t r14;
  22. uint64_t r15;
  23. uint64_t rbp;
  24. uint64_t rsp;
  25. uint64_t rip;
  26. #elif defined(__aarch64__)
  27. // FIXME: This is likely incorrect.
  28. uint64_t regs[22];
  29. #else
  30. # error
  31. #endif
  32. int did_save_signal_mask;
  33. sigset_t saved_signal_mask;
  34. };
  35. typedef struct __jmp_buf jmp_buf[1];
  36. typedef struct __jmp_buf sigjmp_buf[1];
  37. /**
  38. * Since setjmp.h may be included by ports written in C, we need to guard this.
  39. */
  40. #ifdef __cplusplus
  41. # if defined(__x86_64__)
  42. static_assert(sizeof(struct __jmp_buf) == 72, "struct __jmp_buf unsynchronized with x86_64/setjmp.S");
  43. # elif defined(__aarch64__)
  44. static_assert(sizeof(struct __jmp_buf) == 184, "struct __jmp_buf unsynchronized with aarch64/setjmp.S");
  45. # else
  46. # error
  47. # endif
  48. #endif
  49. /**
  50. * Calling conventions mandates that sigsetjmp() cannot call setjmp(),
  51. * otherwise the restored calling environment will not be the original caller's
  52. * but sigsetjmp()'s and we'll return to the wrong call site on siglongjmp().
  53. *
  54. * The setjmp(), sigsetjmp() and longjmp() functions have to be implemented in
  55. * assembly because they touch the call stack and registers in non-portable
  56. * ways. However, we *can* implement siglongjmp() as a standard C function.
  57. */
  58. int setjmp(jmp_buf);
  59. __attribute__((noreturn)) void longjmp(jmp_buf, int val);
  60. int sigsetjmp(sigjmp_buf, int savesigs);
  61. __attribute__((noreturn)) void siglongjmp(sigjmp_buf, int val);
  62. /**
  63. * _setjmp() and _longjmp() are specified as behaving the exactly the same as
  64. * setjmp() and longjmp(), except they are not supposed to modify the signal mask.
  65. *
  66. * Our implementations already follow this restriction, so we just map them directly
  67. * to the same functions.
  68. *
  69. * https://pubs.opengroup.org/onlinepubs/9699969599/functions/_setjmp.html
  70. */
  71. int _setjmp(jmp_buf);
  72. __attribute__((noreturn)) void _longjmp(jmp_buf, int val);
  73. __END_DECLS