Coverage Report

Created: 2026-02-14 07:09

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