tst-longjmp_chk3.c 2.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889
  1. /* Make sure longjmp fortification catches bad signal stacks.
  2. Copyright (C) 2013-2026 Free Software Foundation, Inc.
  3. This file is part of the GNU C Library.
  4. The GNU C Library is free software; you can redistribute it and/or
  5. modify it under the terms of the GNU Lesser General Public
  6. License as published by the Free Software Foundation; either
  7. version 2.1 of the License, or (at your option) any later version.
  8. The GNU C Library is distributed in the hope that it will be useful,
  9. but WITHOUT ANY WARRANTY; without even the implied warranty of
  10. MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
  11. Lesser General Public License for more details.
  12. You should have received a copy of the GNU Lesser General Public
  13. License along with the GNU C Library; if not, see
  14. <https://www.gnu.org/licenses/>. */
  15. #include <setjmp.h>
  16. #include <signal.h>
  17. #include <stdio.h>
  18. #include <string.h>
  19. #include <unistd.h>
  20. #include <support/support.h>
  21. static char *buf;
  22. static jmp_buf jb;
  23. static void
  24. handler (int sig)
  25. {
  26. if (sig == SIGUSR1)
  27. {
  28. if (setjmp (jb) != 0)
  29. {
  30. puts ("setjmp should not have been called");
  31. kill (getpid (), SIGTERM);
  32. }
  33. }
  34. else if (sig == SIGABRT)
  35. {
  36. /* Yeah it worked. */
  37. _exit (0);
  38. }
  39. }
  40. static int
  41. do_test (void)
  42. {
  43. stack_t ss;
  44. set_fortify_handler (handler);
  45. /* Create a valid signal stack and enable it. */
  46. size_t bufsize = SIGSTKSZ * 4;
  47. buf = xmalloc (bufsize);
  48. ss.ss_sp = buf;
  49. ss.ss_size = bufsize;
  50. ss.ss_flags = 0;
  51. if (sigaltstack (&ss, NULL) < 0)
  52. {
  53. printf ("first sigaltstack failed: %m\n");
  54. return 1;
  55. }
  56. /* Trigger the signal handler which will create a jmpbuf that points to the
  57. end of the signal stack. */
  58. signal (SIGUSR1, handler);
  59. kill (getpid (), SIGUSR1);
  60. /* Shrink the signal stack so the jmpbuf is now invalid.
  61. We adjust the start & end to handle stacks that grow up & down. */
  62. ss.ss_sp = buf + bufsize / 2;
  63. ss.ss_size = bufsize / 4;
  64. if (sigaltstack (&ss, NULL) < 0)
  65. {
  66. printf ("second sigaltstack failed: %m\n");
  67. return 1;
  68. }
  69. /* This should fail. */
  70. longjmp (jb, 1);
  71. puts ("longjmp returned and shouldn't");
  72. return 1;
  73. }
  74. #include <support/test-driver.c>