1 //
2 // Copyright 2018 The Abseil Authors.
3 //
4 // Licensed under the Apache License, Version 2.0 (the "License");
5 // you may not use this file except in compliance with the License.
6 // You may obtain a copy of the License at
7 //
8 // https://www.apache.org/licenses/LICENSE-2.0
9 //
10 // Unless required by applicable law or agreed to in writing, software
11 // distributed under the License is distributed on an "AS IS" BASIS,
12 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 // See the License for the specific language governing permissions and
14 // limitations under the License.
15 //
16
17 #include "absl/debugging/internal/examine_stack.h"
18
19 #ifndef _WIN32
20 #include <unistd.h>
21 #endif
22
23 #include "absl/base/config.h"
24
25 #ifdef ABSL_HAVE_MMAP
26 #include <sys/mman.h>
27 #endif
28
29 #if defined(__linux__) || defined(__APPLE__)
30 #include <sys/ucontext.h>
31 #endif
32
33 #include <csignal>
34 #include <cstdio>
35
36 #include "absl/base/attributes.h"
37 #include "absl/base/internal/raw_logging.h"
38 #include "absl/base/macros.h"
39 #include "absl/debugging/stacktrace.h"
40 #include "absl/debugging/symbolize.h"
41
42 namespace absl {
43 ABSL_NAMESPACE_BEGIN
44 namespace debugging_internal {
45
46 namespace {
47 constexpr int kDefaultDumpStackFramesLimit = 64;
48 // The %p field width for printf() functions is two characters per byte,
49 // and two extra for the leading "0x".
50 constexpr int kPrintfPointerFieldWidth = 2 + 2 * sizeof(void*);
51
52 ABSL_CONST_INIT SymbolizeUrlEmitter debug_stack_trace_hook = nullptr;
53
54 // Async-signal safe mmap allocator.
Allocate(size_t num_bytes)55 void* Allocate(size_t num_bytes) {
56 #ifdef ABSL_HAVE_MMAP
57 void* p = ::mmap(nullptr, num_bytes, PROT_READ | PROT_WRITE,
58 MAP_PRIVATE | MAP_ANONYMOUS, -1, 0);
59 return p == MAP_FAILED ? nullptr : p;
60 #else
61 (void)num_bytes;
62 return nullptr;
63 #endif // ABSL_HAVE_MMAP
64 }
65
Deallocate(void * p,size_t size)66 void Deallocate(void* p, size_t size) {
67 #ifdef ABSL_HAVE_MMAP
68 ::munmap(p, size);
69 #else
70 (void)p;
71 (void)size;
72 #endif // ABSL_HAVE_MMAP
73 }
74
75 // Print a program counter only.
DumpPC(OutputWriter * writer,void * writer_arg,void * const pc,const char * const prefix)76 void DumpPC(OutputWriter* writer, void* writer_arg, void* const pc,
77 const char* const prefix) {
78 char buf[100];
79 snprintf(buf, sizeof(buf), "%s@ %*p\n", prefix, kPrintfPointerFieldWidth, pc);
80 writer(buf, writer_arg);
81 }
82
83 // Print a program counter and the corresponding stack frame size.
DumpPCAndFrameSize(OutputWriter * writer,void * writer_arg,void * const pc,int framesize,const char * const prefix)84 void DumpPCAndFrameSize(OutputWriter* writer, void* writer_arg, void* const pc,
85 int framesize, const char* const prefix) {
86 char buf[100];
87 if (framesize <= 0) {
88 snprintf(buf, sizeof(buf), "%s@ %*p (unknown)\n", prefix,
89 kPrintfPointerFieldWidth, pc);
90 } else {
91 snprintf(buf, sizeof(buf), "%s@ %*p %9d\n", prefix,
92 kPrintfPointerFieldWidth, pc, framesize);
93 }
94 writer(buf, writer_arg);
95 }
96
97 // Print a program counter and the corresponding symbol.
DumpPCAndSymbol(OutputWriter * writer,void * writer_arg,void * const pc,const char * const prefix)98 void DumpPCAndSymbol(OutputWriter* writer, void* writer_arg, void* const pc,
99 const char* const prefix) {
100 char tmp[1024];
101 const char* symbol = "(unknown)";
102 // Symbolizes the previous address of pc because pc may be in the
103 // next function. The overrun happens when the function ends with
104 // a call to a function annotated noreturn (e.g. CHECK).
105 // If symbolization of pc-1 fails, also try pc on the off-chance
106 // that we crashed on the first instruction of a function (that
107 // actually happens very often for e.g. __restore_rt).
108 const uintptr_t prev_pc = reinterpret_cast<uintptr_t>(pc) - 1;
109 if (absl::Symbolize(reinterpret_cast<const char*>(prev_pc), tmp,
110 sizeof(tmp)) ||
111 absl::Symbolize(pc, tmp, sizeof(tmp))) {
112 symbol = tmp;
113 }
114 char buf[1024];
115 snprintf(buf, sizeof(buf), "%s@ %*p %s\n", prefix, kPrintfPointerFieldWidth,
116 pc, symbol);
117 writer(buf, writer_arg);
118 }
119
120 // Print a program counter, its stack frame size, and its symbol name.
121 // Note that there is a separate symbolize_pc argument. Return addresses may be
122 // at the end of the function, and this allows the caller to back up from pc if
123 // appropriate.
DumpPCAndFrameSizeAndSymbol(OutputWriter * writer,void * writer_arg,void * const pc,void * const symbolize_pc,int framesize,const char * const prefix)124 void DumpPCAndFrameSizeAndSymbol(OutputWriter* writer, void* writer_arg,
125 void* const pc, void* const symbolize_pc,
126 int framesize, const char* const prefix) {
127 char tmp[1024];
128 const char* symbol = "(unknown)";
129 if (absl::Symbolize(symbolize_pc, tmp, sizeof(tmp))) {
130 symbol = tmp;
131 }
132 char buf[1024];
133 if (framesize <= 0) {
134 snprintf(buf, sizeof(buf), "%s@ %*p (unknown) %s\n", prefix,
135 kPrintfPointerFieldWidth, pc, symbol);
136 } else {
137 snprintf(buf, sizeof(buf), "%s@ %*p %9d %s\n", prefix,
138 kPrintfPointerFieldWidth, pc, framesize, symbol);
139 }
140 writer(buf, writer_arg);
141 }
142
143 } // namespace
144
RegisterDebugStackTraceHook(SymbolizeUrlEmitter hook)145 void RegisterDebugStackTraceHook(SymbolizeUrlEmitter hook) {
146 debug_stack_trace_hook = hook;
147 }
148
GetDebugStackTraceHook()149 SymbolizeUrlEmitter GetDebugStackTraceHook() { return debug_stack_trace_hook; }
150
151 // Returns the program counter from signal context, nullptr if
152 // unknown. vuc is a ucontext_t*. We use void* to avoid the use of
153 // ucontext_t on non-POSIX systems.
GetProgramCounter(void * const vuc)154 void* GetProgramCounter(void* const vuc) {
155 #ifdef __linux__
156 if (vuc != nullptr) {
157 ucontext_t* context = reinterpret_cast<ucontext_t*>(vuc);
158 #if defined(__aarch64__)
159 return reinterpret_cast<void*>(context->uc_mcontext.pc);
160 #elif defined(__alpha__)
161 return reinterpret_cast<void*>(context->uc_mcontext.sc_pc);
162 #elif defined(__arm__)
163 return reinterpret_cast<void*>(context->uc_mcontext.arm_pc);
164 #elif defined(__hppa__)
165 return reinterpret_cast<void*>(context->uc_mcontext.sc_iaoq[0]);
166 #elif defined(__i386__)
167 if (14 < ABSL_ARRAYSIZE(context->uc_mcontext.gregs))
168 return reinterpret_cast<void*>(context->uc_mcontext.gregs[14]);
169 #elif defined(__ia64__)
170 return reinterpret_cast<void*>(context->uc_mcontext.sc_ip);
171 #elif defined(__m68k__)
172 return reinterpret_cast<void*>(context->uc_mcontext.gregs[16]);
173 #elif defined(__mips__)
174 return reinterpret_cast<void*>(context->uc_mcontext.pc);
175 #elif defined(__powerpc64__)
176 return reinterpret_cast<void*>(context->uc_mcontext.gp_regs[32]);
177 #elif defined(__powerpc__)
178 return reinterpret_cast<void*>(context->uc_mcontext.uc_regs->gregs[32]);
179 #elif defined(__riscv)
180 return reinterpret_cast<void*>(context->uc_mcontext.__gregs[REG_PC]);
181 #elif defined(__s390__) && !defined(__s390x__)
182 return reinterpret_cast<void*>(context->uc_mcontext.psw.addr & 0x7fffffff);
183 #elif defined(__s390__) && defined(__s390x__)
184 return reinterpret_cast<void*>(context->uc_mcontext.psw.addr);
185 #elif defined(__sh__)
186 return reinterpret_cast<void*>(context->uc_mcontext.pc);
187 #elif defined(__sparc__) && !defined(__arch64__)
188 return reinterpret_cast<void*>(context->uc_mcontext.gregs[19]);
189 #elif defined(__sparc__) && defined(__arch64__)
190 return reinterpret_cast<void*>(context->uc_mcontext.mc_gregs[19]);
191 #elif defined(__x86_64__)
192 if (16 < ABSL_ARRAYSIZE(context->uc_mcontext.gregs))
193 return reinterpret_cast<void*>(context->uc_mcontext.gregs[16]);
194 #elif defined(__e2k__)
195 return reinterpret_cast<void*>(context->uc_mcontext.cr0_hi);
196 #elif defined(__loongarch__)
197 return reinterpret_cast<void*>(context->uc_mcontext.__pc);
198 #else
199 #error "Undefined Architecture."
200 #endif
201 }
202 #elif defined(__APPLE__)
203 if (vuc != nullptr) {
204 ucontext_t* signal_ucontext = reinterpret_cast<ucontext_t*>(vuc);
205 #if defined(__aarch64__)
206 return reinterpret_cast<void*>(
207 __darwin_arm_thread_state64_get_pc(signal_ucontext->uc_mcontext->__ss));
208 #elif defined(__arm__)
209 #if __DARWIN_UNIX03
210 return reinterpret_cast<void*>(signal_ucontext->uc_mcontext->__ss.__pc);
211 #else
212 return reinterpret_cast<void*>(signal_ucontext->uc_mcontext->ss.pc);
213 #endif
214 #elif defined(__i386__)
215 #if __DARWIN_UNIX03
216 return reinterpret_cast<void*>(signal_ucontext->uc_mcontext->__ss.__eip);
217 #else
218 return reinterpret_cast<void*>(signal_ucontext->uc_mcontext->ss.eip);
219 #endif
220 #elif defined(__x86_64__)
221 #if __DARWIN_UNIX03
222 return reinterpret_cast<void*>(signal_ucontext->uc_mcontext->__ss.__rip);
223 #else
224 return reinterpret_cast<void*>(signal_ucontext->uc_mcontext->ss.rip);
225 #endif
226 #endif
227 }
228 #elif defined(__akaros__)
229 auto* ctx = reinterpret_cast<struct user_context*>(vuc);
230 return reinterpret_cast<void*>(get_user_ctx_pc(ctx));
231 #endif
232 static_cast<void>(vuc);
233 return nullptr;
234 }
235
DumpPCAndFrameSizesAndStackTrace(void * const pc,void * const stack[],int frame_sizes[],int depth,int min_dropped_frames,bool symbolize_stacktrace,OutputWriter * writer,void * writer_arg)236 void DumpPCAndFrameSizesAndStackTrace(void* const pc, void* const stack[],
237 int frame_sizes[], int depth,
238 int min_dropped_frames,
239 bool symbolize_stacktrace,
240 OutputWriter* writer, void* writer_arg) {
241 if (pc != nullptr) {
242 // We don't know the stack frame size for PC, use 0.
243 if (symbolize_stacktrace) {
244 DumpPCAndFrameSizeAndSymbol(writer, writer_arg, pc, pc, 0, "PC: ");
245 } else {
246 DumpPCAndFrameSize(writer, writer_arg, pc, 0, "PC: ");
247 }
248 }
249 for (int i = 0; i < depth; i++) {
250 if (symbolize_stacktrace) {
251 // Pass the previous address of pc as the symbol address because pc is a
252 // return address, and an overrun may occur when the function ends with a
253 // call to a function annotated noreturn (e.g. CHECK). Note that we don't
254 // do this for pc above, as the adjustment is only correct for return
255 // addresses.
256 DumpPCAndFrameSizeAndSymbol(writer, writer_arg, stack[i],
257 reinterpret_cast<char*>(stack[i]) - 1,
258 frame_sizes[i], " ");
259 } else {
260 DumpPCAndFrameSize(writer, writer_arg, stack[i], frame_sizes[i], " ");
261 }
262 }
263 if (min_dropped_frames > 0) {
264 char buf[100];
265 snprintf(buf, sizeof(buf), " @ ... and at least %d more frames\n",
266 min_dropped_frames);
267 writer(buf, writer_arg);
268 }
269 }
270
271 // Dump current stack trace as directed by writer.
272 // Make sure this function is not inlined to avoid skipping too many top frames.
273 ABSL_ATTRIBUTE_NOINLINE
DumpStackTrace(int min_dropped_frames,int max_num_frames,bool symbolize_stacktrace,OutputWriter * writer,void * writer_arg)274 void DumpStackTrace(int min_dropped_frames, int max_num_frames,
275 bool symbolize_stacktrace, OutputWriter* writer,
276 void* writer_arg) {
277 // Print stack trace
278 void* stack_buf[kDefaultDumpStackFramesLimit];
279 void** stack = stack_buf;
280 int num_stack = kDefaultDumpStackFramesLimit;
281 size_t allocated_bytes = 0;
282
283 if (num_stack >= max_num_frames) {
284 // User requested fewer frames than we already have space for.
285 num_stack = max_num_frames;
286 } else {
287 const size_t needed_bytes =
288 static_cast<size_t>(max_num_frames) * sizeof(stack[0]);
289 void* p = Allocate(needed_bytes);
290 if (p != nullptr) { // We got the space.
291 num_stack = max_num_frames;
292 stack = reinterpret_cast<void**>(p);
293 allocated_bytes = needed_bytes;
294 }
295 }
296
297 int depth = absl::GetStackTrace(stack, num_stack, min_dropped_frames + 1);
298 for (int i = 0; i < depth; i++) {
299 if (symbolize_stacktrace) {
300 DumpPCAndSymbol(writer, writer_arg, stack[static_cast<size_t>(i)],
301 " ");
302 } else {
303 DumpPC(writer, writer_arg, stack[static_cast<size_t>(i)], " ");
304 }
305 }
306
307 auto hook = GetDebugStackTraceHook();
308 if (hook != nullptr) {
309 (*hook)(stack, depth, writer, writer_arg);
310 }
311
312 if (allocated_bytes != 0) Deallocate(stack, allocated_bytes);
313 }
314
315 } // namespace debugging_internal
316 ABSL_NAMESPACE_END
317 } // namespace absl
318