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