StackInfo.cpp 1.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364
  1. /*
  2. * Copyright (c) 2020, the SerenityOS developers.
  3. *
  4. * SPDX-License-Identifier: BSD-2-Clause
  5. */
  6. #include <AK/Assertions.h>
  7. #include <AK/Platform.h>
  8. #include <AK/StackInfo.h>
  9. #include <stdio.h>
  10. #include <string.h>
  11. #ifdef __serenity__
  12. # include <serenity.h>
  13. #elif defined(__linux__) or defined(AK_OS_MACOS)
  14. # include <pthread.h>
  15. #endif
  16. namespace AK {
  17. StackInfo::StackInfo()
  18. {
  19. #ifdef __serenity__
  20. if (get_stack_bounds(&m_base, &m_size) < 0) {
  21. perror("get_stack_bounds");
  22. VERIFY_NOT_REACHED();
  23. }
  24. #elif defined(__linux__)
  25. int rc;
  26. pthread_attr_t attr = {};
  27. if ((rc = pthread_getattr_np(pthread_self(), &attr)) != 0) {
  28. fprintf(stderr, "pthread_getattr_np: %s\n", strerror(-rc));
  29. VERIFY_NOT_REACHED();
  30. }
  31. if ((rc = pthread_attr_getstack(&attr, (void**)&m_base, &m_size)) != 0) {
  32. fprintf(stderr, "pthread_attr_getstack: %s\n", strerror(-rc));
  33. VERIFY_NOT_REACHED();
  34. }
  35. pthread_attr_destroy(&attr);
  36. #elif defined(AK_OS_MACOS)
  37. // NOTE: !! On MacOS, pthread_get_stackaddr_np gives the TOP of the stack, not the bottom!
  38. FlatPtr top_of_stack = (FlatPtr)pthread_get_stackaddr_np(pthread_self());
  39. m_size = (size_t)pthread_get_stacksize_np(pthread_self());
  40. // https://github.com/rust-lang/rust/issues/43347#issuecomment-316783599
  41. // https://developer.apple.com/library/archive/qa/qa1419/_index.html
  42. //
  43. // MacOS seems inconsistent on what stack size is given for the main thread.
  44. // According to the Apple docs, default for main thread is 8MB, and default for
  45. // other threads is 512KB
  46. constexpr size_t eight_megabytes = 0x800000;
  47. if (pthread_main_np() == 1 && m_size < eight_megabytes) {
  48. // Assume no one messed with stack size linker options for the main thread,
  49. // and just set it to 8MB.
  50. m_size = eight_megabytes;
  51. }
  52. m_base = top_of_stack - m_size;
  53. #else
  54. VERIFY_NOT_REACHED();
  55. #endif
  56. m_top = m_base + m_size;
  57. }
  58. }