enable-execute-stack-mprotect.c 2.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879
  1. /* Implement __enable_execute_stack using mprotect(2).
  2. Copyright (C) 2011-2022 Free Software Foundation, Inc.
  3. This file is part of GCC.
  4. GCC is free software; you can redistribute it and/or modify it under
  5. the terms of the GNU General Public License as published by the Free
  6. Software Foundation; either version 3, or (at your option) any later
  7. version.
  8. GCC is distributed in the hope that it will be useful, but WITHOUT ANY
  9. WARRANTY; without even the implied warranty of MERCHANTABILITY or
  10. FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
  11. for more details.
  12. Under Section 7 of GPL version 3, you are granted additional
  13. permissions described in the GCC Runtime Library Exception, version
  14. 3.1, as published by the Free Software Foundation.
  15. You should have received a copy of the GNU General Public License and
  16. a copy of the GCC Runtime Library Exception along with this program;
  17. see the files COPYING3 and COPYING.RUNTIME respectively. If not, see
  18. <http://www.gnu.org/licenses/>. */
  19. #include <sys/mman.h>
  20. #include <unistd.h>
  21. #include <stdlib.h>
  22. #define STACK_PROT_RWX (PROT_READ | PROT_WRITE | PROT_EXEC)
  23. static int need_enable_exec_stack;
  24. static void check_enabling (void) __attribute__ ((unused));
  25. extern void __enable_execute_stack (void *);
  26. #if defined __sun__ && defined __svr4__
  27. static void __attribute__ ((constructor))
  28. check_enabling (void)
  29. {
  30. int prot = (int) sysconf (_SC_STACK_PROT);
  31. if (prot != STACK_PROT_RWX)
  32. need_enable_exec_stack = 1;
  33. }
  34. #else
  35. /* There is no way to query the execute permission of the stack, so
  36. we always issue the mprotect() call. */
  37. static int need_enable_exec_stack = 1;
  38. #endif
  39. /* Attempt to turn on access permissions for the stack. Unfortunately it
  40. is not possible to make this namespace-clean.*/
  41. void
  42. __enable_execute_stack (void *addr)
  43. {
  44. if (!need_enable_exec_stack)
  45. return;
  46. else
  47. {
  48. static long size, mask;
  49. if (size == 0) {
  50. size = getpagesize ();
  51. mask = ~(size - 1);
  52. }
  53. char *page = (char *) (((long) addr) & mask);
  54. char *end = (char *)
  55. ((((long) (addr + __LIBGCC_TRAMPOLINE_SIZE__)) & mask) + size);
  56. if (mprotect (page, end - page, STACK_PROT_RWX) < 0)
  57. /* Note that no errors should be emitted by this code; it is
  58. considered dangerous for library calls to send messages to
  59. stdout/stderr. */
  60. abort ();
  61. }
  62. }