stacktrace_powerpc-inl.inc 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258
  1. // Copyright 2017 The Abseil Authors.
  2. //
  3. // Licensed under the Apache License, Version 2.0 (the "License");
  4. // you may not use this file except in compliance with the License.
  5. // You may obtain a copy of the License at
  6. //
  7. // https://www.apache.org/licenses/LICENSE-2.0
  8. //
  9. // Unless required by applicable law or agreed to in writing, software
  10. // distributed under the License is distributed on an "AS IS" BASIS,
  11. // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. // See the License for the specific language governing permissions and
  13. // limitations under the License.
  14. //
  15. // Produce stack trace. I'm guessing (hoping!) the code is much like
  16. // for x86. For apple machines, at least, it seems to be; see
  17. // https://developer.apple.com/documentation/mac/runtimehtml/RTArch-59.html
  18. // https://www.linux-foundation.org/spec/ELF/ppc64/PPC-elf64abi-1.9.html#STACK
  19. // Linux has similar code: http://patchwork.ozlabs.org/linuxppc/patch?id=8882
  20. #ifndef ABSL_DEBUGGING_INTERNAL_STACKTRACE_POWERPC_INL_H_
  21. #define ABSL_DEBUGGING_INTERNAL_STACKTRACE_POWERPC_INL_H_
  22. #if defined(__linux__)
  23. #include <asm/ptrace.h> // for PT_NIP.
  24. #include <ucontext.h> // for ucontext_t
  25. #endif
  26. #include <unistd.h>
  27. #include <cassert>
  28. #include <cstdint>
  29. #include <cstdio>
  30. #include "absl/base/attributes.h"
  31. #include "absl/base/optimization.h"
  32. #include "absl/base/port.h"
  33. #include "absl/debugging/stacktrace.h"
  34. #include "absl/debugging/internal/address_is_readable.h"
  35. #include "absl/debugging/internal/vdso_support.h" // a no-op on non-elf or non-glibc systems
  36. // Given a stack pointer, return the saved link register value.
  37. // Note that this is the link register for a callee.
  38. static inline void *StacktracePowerPCGetLR(void **sp) {
  39. // PowerPC has 3 main ABIs, which say where in the stack the
  40. // Link Register is. For DARWIN and AIX (used by apple and
  41. // linux ppc64), it's in sp[2]. For SYSV (used by linux ppc),
  42. // it's in sp[1].
  43. #if defined(_CALL_AIX) || defined(_CALL_DARWIN)
  44. return *(sp+2);
  45. #elif defined(_CALL_SYSV)
  46. return *(sp+1);
  47. #elif defined(__APPLE__) || defined(__FreeBSD__) || \
  48. (defined(__linux__) && defined(__PPC64__))
  49. // This check is in case the compiler doesn't define _CALL_AIX/etc.
  50. return *(sp+2);
  51. #elif defined(__linux)
  52. // This check is in case the compiler doesn't define _CALL_SYSV.
  53. return *(sp+1);
  54. #else
  55. #error Need to specify the PPC ABI for your architecture.
  56. #endif
  57. }
  58. // Given a pointer to a stack frame, locate and return the calling
  59. // stackframe, or return null if no stackframe can be found. Perform sanity
  60. // checks (the strictness of which is controlled by the boolean parameter
  61. // "STRICT_UNWINDING") to reduce the chance that a bad pointer is returned.
  62. template<bool STRICT_UNWINDING, bool IS_WITH_CONTEXT>
  63. ABSL_ATTRIBUTE_NO_SANITIZE_ADDRESS // May read random elements from stack.
  64. ABSL_ATTRIBUTE_NO_SANITIZE_MEMORY // May read random elements from stack.
  65. static void **NextStackFrame(void **old_sp, const void *uc) {
  66. void **new_sp = (void **) *old_sp;
  67. enum { kStackAlignment = 16 };
  68. // Check that the transition from frame pointer old_sp to frame
  69. // pointer new_sp isn't clearly bogus
  70. if (STRICT_UNWINDING) {
  71. // With the stack growing downwards, older stack frame must be
  72. // at a greater address that the current one.
  73. if (new_sp <= old_sp) return nullptr;
  74. // Assume stack frames larger than 100,000 bytes are bogus.
  75. if ((uintptr_t)new_sp - (uintptr_t)old_sp > 100000) return nullptr;
  76. } else {
  77. // In the non-strict mode, allow discontiguous stack frames.
  78. // (alternate-signal-stacks for example).
  79. if (new_sp == old_sp) return nullptr;
  80. // And allow frames upto about 1MB.
  81. if ((new_sp > old_sp)
  82. && ((uintptr_t)new_sp - (uintptr_t)old_sp > 1000000)) return nullptr;
  83. }
  84. if ((uintptr_t)new_sp % kStackAlignment != 0) return nullptr;
  85. #if defined(__linux__)
  86. enum StackTraceKernelSymbolStatus {
  87. kNotInitialized = 0, kAddressValid, kAddressInvalid };
  88. if (IS_WITH_CONTEXT && uc != nullptr) {
  89. static StackTraceKernelSymbolStatus kernel_symbol_status =
  90. kNotInitialized; // Sentinel: not computed yet.
  91. // Initialize with sentinel value: __kernel_rt_sigtramp_rt64 can not
  92. // possibly be there.
  93. static const unsigned char *kernel_sigtramp_rt64_address = nullptr;
  94. if (kernel_symbol_status == kNotInitialized) {
  95. absl::debugging_internal::VDSOSupport vdso;
  96. if (vdso.IsPresent()) {
  97. absl::debugging_internal::VDSOSupport::SymbolInfo
  98. sigtramp_rt64_symbol_info;
  99. if (!vdso.LookupSymbol(
  100. "__kernel_sigtramp_rt64", "LINUX_2.6.15",
  101. absl::debugging_internal::VDSOSupport::kVDSOSymbolType,
  102. &sigtramp_rt64_symbol_info) ||
  103. sigtramp_rt64_symbol_info.address == nullptr) {
  104. // Unexpected: VDSO is present, yet the expected symbol is missing
  105. // or null.
  106. assert(false && "VDSO is present, but doesn't have expected symbol");
  107. kernel_symbol_status = kAddressInvalid;
  108. } else {
  109. kernel_sigtramp_rt64_address =
  110. reinterpret_cast<const unsigned char *>(
  111. sigtramp_rt64_symbol_info.address);
  112. kernel_symbol_status = kAddressValid;
  113. }
  114. } else {
  115. kernel_symbol_status = kAddressInvalid;
  116. }
  117. }
  118. if (new_sp != nullptr &&
  119. kernel_symbol_status == kAddressValid &&
  120. StacktracePowerPCGetLR(new_sp) == kernel_sigtramp_rt64_address) {
  121. const ucontext_t* signal_context =
  122. reinterpret_cast<const ucontext_t*>(uc);
  123. void **const sp_before_signal =
  124. #if defined(__PPC64__)
  125. reinterpret_cast<void **>(signal_context->uc_mcontext.gp_regs[PT_R1]);
  126. #else
  127. reinterpret_cast<void **>(
  128. signal_context->uc_mcontext.uc_regs->gregs[PT_R1]);
  129. #endif
  130. // Check that alleged sp before signal is nonnull and is reasonably
  131. // aligned.
  132. if (sp_before_signal != nullptr &&
  133. ((uintptr_t)sp_before_signal % kStackAlignment) == 0) {
  134. // Check that alleged stack pointer is actually readable. This is to
  135. // prevent a "double fault" in case we hit the first fault due to e.g.
  136. // a stack corruption.
  137. if (absl::debugging_internal::AddressIsReadable(sp_before_signal)) {
  138. // Alleged stack pointer is readable, use it for further unwinding.
  139. new_sp = sp_before_signal;
  140. }
  141. }
  142. }
  143. }
  144. #endif
  145. return new_sp;
  146. }
  147. // This ensures that absl::GetStackTrace sets up the Link Register properly.
  148. ABSL_ATTRIBUTE_NOINLINE static void AbslStacktracePowerPCDummyFunction() {
  149. ABSL_BLOCK_TAIL_CALL_OPTIMIZATION();
  150. }
  151. template <bool IS_STACK_FRAMES, bool IS_WITH_CONTEXT>
  152. ABSL_ATTRIBUTE_NO_SANITIZE_ADDRESS // May read random elements from stack.
  153. ABSL_ATTRIBUTE_NO_SANITIZE_MEMORY // May read random elements from stack.
  154. static int UnwindImpl(void** result, int* sizes, int max_depth, int skip_count,
  155. const void *ucp, int *min_dropped_frames) {
  156. void **sp;
  157. // Apple macOS uses an old version of gnu as -- both Darwin 7.9.0 (Panther)
  158. // and Darwin 8.8.1 (Tiger) use as 1.38. This means we have to use a
  159. // different asm syntax. I don't know quite the best way to discriminate
  160. // systems using the old as from the new one; I've gone with __APPLE__.
  161. #ifdef __APPLE__
  162. __asm__ volatile ("mr %0,r1" : "=r" (sp));
  163. #else
  164. __asm__ volatile ("mr %0,1" : "=r" (sp));
  165. #endif
  166. // On PowerPC, the "Link Register" or "Link Record" (LR), is a stack
  167. // entry that holds the return address of the subroutine call (what
  168. // instruction we run after our function finishes). This is the
  169. // same as the stack-pointer of our parent routine, which is what we
  170. // want here. While the compiler will always(?) set up LR for
  171. // subroutine calls, it may not for leaf functions (such as this one).
  172. // This routine forces the compiler (at least gcc) to push it anyway.
  173. AbslStacktracePowerPCDummyFunction();
  174. // The LR save area is used by the callee, so the top entry is bogus.
  175. skip_count++;
  176. int n = 0;
  177. // Unlike ABIs of X86 and ARM, PowerPC ABIs say that return address (in
  178. // the link register) of a function call is stored in the caller's stack
  179. // frame instead of the callee's. When we look for the return address
  180. // associated with a stack frame, we need to make sure that there is a
  181. // caller frame before it. So we call NextStackFrame before entering the
  182. // loop below and check next_sp instead of sp for loop termination.
  183. // The outermost frame is set up by runtimes and it does not have a
  184. // caller frame, so it is skipped.
  185. // The absl::GetStackFrames routine is called when we are in some
  186. // informational context (the failure signal handler for example).
  187. // Use the non-strict unwinding rules to produce a stack trace
  188. // that is as complete as possible (even if it contains a few
  189. // bogus entries in some rare cases).
  190. void **next_sp = NextStackFrame<!IS_STACK_FRAMES, IS_WITH_CONTEXT>(sp, ucp);
  191. while (next_sp && n < max_depth) {
  192. if (skip_count > 0) {
  193. skip_count--;
  194. } else {
  195. result[n] = StacktracePowerPCGetLR(sp);
  196. if (IS_STACK_FRAMES) {
  197. if (next_sp > sp) {
  198. sizes[n] = (uintptr_t)next_sp - (uintptr_t)sp;
  199. } else {
  200. // A frame-size of 0 is used to indicate unknown frame size.
  201. sizes[n] = 0;
  202. }
  203. }
  204. n++;
  205. }
  206. sp = next_sp;
  207. next_sp = NextStackFrame<!IS_STACK_FRAMES, IS_WITH_CONTEXT>(sp, ucp);
  208. }
  209. if (min_dropped_frames != nullptr) {
  210. // Implementation detail: we clamp the max of frames we are willing to
  211. // count, so as not to spend too much time in the loop below.
  212. const int kMaxUnwind = 1000;
  213. int num_dropped_frames = 0;
  214. for (int j = 0; next_sp != nullptr && j < kMaxUnwind; j++) {
  215. if (skip_count > 0) {
  216. skip_count--;
  217. } else {
  218. num_dropped_frames++;
  219. }
  220. next_sp = NextStackFrame<!IS_STACK_FRAMES, IS_WITH_CONTEXT>(next_sp, ucp);
  221. }
  222. *min_dropped_frames = num_dropped_frames;
  223. }
  224. return n;
  225. }
  226. namespace absl {
  227. ABSL_NAMESPACE_BEGIN
  228. namespace debugging_internal {
  229. bool StackTraceWorksForTest() {
  230. return true;
  231. }
  232. } // namespace debugging_internal
  233. ABSL_NAMESPACE_END
  234. } // namespace absl
  235. #endif // ABSL_DEBUGGING_INTERNAL_STACKTRACE_POWERPC_INL_H_