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