1 // Copyright 2012 The Chromium Authors
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
4
5 #include "base/debug/stack_trace.h"
6
7 #include <errno.h>
8 #include <fcntl.h>
9 #include <signal.h>
10 #include <stddef.h>
11 #include <stdint.h>
12 #include <stdio.h>
13 #include <stdlib.h>
14 #include <string.h>
15 #include <sys/param.h>
16 #include <sys/stat.h>
17 #include <sys/syscall.h>
18 #include <sys/types.h>
19 #include <unistd.h>
20
21 #include <algorithm>
22 #include <map>
23 #include <memory>
24 #include <ostream>
25 #include <string>
26 #include <tuple>
27 #include <vector>
28
29 #include "base/memory/raw_ptr.h"
30 #include "build/build_config.h"
31
32 // Controls whether `dladdr(...)` is used to print the callstack. This is
33 // only used on iOS Official build where `backtrace_symbols(...)` prints
34 // misleading symbols (as the binary is stripped).
35 #if BUILDFLAG(IS_IOS) && defined(OFFICIAL_BUILD)
36 #define HAVE_DLADDR
37 #include <dlfcn.h>
38 #endif
39
40 // Surprisingly, uClibc defines __GLIBC__ in some build configs, but
41 // execinfo.h and backtrace(3) are really only present in glibc and in macOS
42 // libc.
43 #if BUILDFLAG(IS_APPLE) || \
44 (defined(__GLIBC__) && !defined(__UCLIBC__) && !defined(__AIX))
45 #define HAVE_BACKTRACE
46 #include <execinfo.h>
47 #endif
48
49 // Controls whether to include code to demangle C++ symbols.
50 #if !defined(USE_SYMBOLIZE) && defined(HAVE_BACKTRACE) && !defined(HAVE_DLADDR)
51 #define DEMANGLE_SYMBOLS
52 #endif
53
54 #if defined(DEMANGLE_SYMBOLS)
55 #include <cxxabi.h>
56 #endif
57
58 #if BUILDFLAG(IS_APPLE)
59 #include <AvailabilityMacros.h>
60 #endif
61
62 #if BUILDFLAG(IS_LINUX) || BUILDFLAG(IS_CHROMEOS)
63 #include <sys/prctl.h>
64
65 #include "base/debug/proc_maps_linux.h"
66 #endif
67
68 #include "base/cfi_buildflags.h"
69 #include "base/debug/debugger.h"
70 #include "base/debug/stack_trace.h"
71 #include "base/files/scoped_file.h"
72 #include "base/logging.h"
73 #include "base/memory/free_deleter.h"
74 #include "base/memory/singleton.h"
75 #include "base/numerics/safe_conversions.h"
76 #include "base/posix/eintr_wrapper.h"
77 #include "base/strings/string_number_conversions.h"
78 #include "base/strings/string_util.h"
79 #include "build/build_config.h"
80
81 #if defined(USE_SYMBOLIZE)
82 #include "base/third_party/symbolize/symbolize.h" // nogncheck
83
84 #if BUILDFLAG(ENABLE_STACK_TRACE_LINE_NUMBERS)
85 #include "base/debug/dwarf_line_no.h" // nogncheck
86 #endif
87
88 #endif
89
90 namespace base {
91 namespace debug {
92
93 namespace {
94
95 volatile sig_atomic_t in_signal_handler = 0;
96
97 #if !BUILDFLAG(IS_NACL)
98 bool (*try_handle_signal)(int, siginfo_t*, void*) = nullptr;
99 #endif
100
101 #if defined(DEMANGLE_SYMBOLS)
102 // The prefix used for mangled symbols, per the Itanium C++ ABI:
103 // http://www.codesourcery.com/cxx-abi/abi.html#mangling
104 const char kMangledSymbolPrefix[] = "_Z";
105
106 // Characters that can be used for symbols, generated by Ruby:
107 // (('a'..'z').to_a+('A'..'Z').to_a+('0'..'9').to_a + ['_']).join
108 const char kSymbolCharacters[] =
109 "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789_";
110
111 // Demangles C++ symbols in the given text. Example:
112 //
113 // "out/Debug/base_unittests(_ZN10StackTraceC1Ev+0x20) [0x817778c]"
114 // =>
115 // "out/Debug/base_unittests(StackTrace::StackTrace()+0x20) [0x817778c]"
DemangleSymbols(std::string * text)116 void DemangleSymbols(std::string* text) {
117 // Note: code in this function is NOT async-signal safe (std::string uses
118 // malloc internally).
119
120 std::string::size_type search_from = 0;
121 while (search_from < text->size()) {
122 // Look for the start of a mangled symbol, from search_from.
123 std::string::size_type mangled_start =
124 text->find(kMangledSymbolPrefix, search_from);
125 if (mangled_start == std::string::npos) {
126 break; // Mangled symbol not found.
127 }
128
129 // Look for the end of the mangled symbol.
130 std::string::size_type mangled_end =
131 text->find_first_not_of(kSymbolCharacters, mangled_start);
132 if (mangled_end == std::string::npos) {
133 mangled_end = text->size();
134 }
135 std::string mangled_symbol =
136 text->substr(mangled_start, mangled_end - mangled_start);
137
138 // Try to demangle the mangled symbol candidate.
139 int status = 0;
140 std::unique_ptr<char, base::FreeDeleter> demangled_symbol(
141 abi::__cxa_demangle(mangled_symbol.c_str(), nullptr, 0, &status));
142 if (status == 0) { // Demangling is successful.
143 // Remove the mangled symbol.
144 text->erase(mangled_start, mangled_end - mangled_start);
145 // Insert the demangled symbol.
146 text->insert(mangled_start, demangled_symbol.get());
147 // Next time, we'll start right after the demangled symbol we inserted.
148 search_from = mangled_start + strlen(demangled_symbol.get());
149 } else {
150 // Failed to demangle. Retry after the "_Z" we just found.
151 search_from = mangled_start + 2;
152 }
153 }
154 }
155 #endif // defined(DEMANGLE_SYMBOLS)
156
157 class BacktraceOutputHandler {
158 public:
159 virtual void HandleOutput(const char* output) = 0;
160
161 protected:
162 virtual ~BacktraceOutputHandler() = default;
163 };
164
165 #if defined(HAVE_BACKTRACE)
OutputPointer(const void * pointer,BacktraceOutputHandler * handler)166 void OutputPointer(const void* pointer, BacktraceOutputHandler* handler) {
167 // This should be more than enough to store a 64-bit number in hex:
168 // 16 hex digits + 1 for null-terminator.
169 char buf[17] = { '\0' };
170 handler->HandleOutput("0x");
171 internal::itoa_r(reinterpret_cast<intptr_t>(pointer),
172 buf, sizeof(buf), 16, 12);
173 handler->HandleOutput(buf);
174 }
175
176 #if defined(HAVE_DLADDR) || defined(USE_SYMBOLIZE)
OutputValue(size_t value,BacktraceOutputHandler * handler)177 void OutputValue(size_t value, BacktraceOutputHandler* handler) {
178 // Max unsigned 64-bit number in decimal has 20 digits (18446744073709551615).
179 // Hence, 30 digits should be more than enough to represent it in decimal
180 // (including the null-terminator).
181 char buf[30] = { '\0' };
182 internal::itoa_r(static_cast<intptr_t>(value), buf, sizeof(buf), 10, 1);
183 handler->HandleOutput(buf);
184 }
185 #endif // defined(HAVE_DLADDR) || defined(USE_SYMBOLIZE)
186
187 #if defined(USE_SYMBOLIZE)
OutputFrameId(size_t frame_id,BacktraceOutputHandler * handler)188 void OutputFrameId(size_t frame_id, BacktraceOutputHandler* handler) {
189 handler->HandleOutput("#");
190 OutputValue(frame_id, handler);
191 }
192 #endif // defined(USE_SYMBOLIZE)
193
ProcessBacktrace(const void * const * trace,size_t size,cstring_view prefix_string,BacktraceOutputHandler * handler)194 void ProcessBacktrace(const void* const* trace,
195 size_t size,
196 cstring_view prefix_string,
197 BacktraceOutputHandler* handler) {
198 // NOTE: This code MUST be async-signal safe (it's used by in-process
199 // stack dumping signal handler). NO malloc or stdio is allowed here.
200
201 #if defined(USE_SYMBOLIZE)
202 #if BUILDFLAG(ENABLE_STACK_TRACE_LINE_NUMBERS)
203 uint64_t cu_offsets[StackTrace::kMaxTraces] = {};
204 GetDwarfCompileUnitOffsets(trace, cu_offsets, size);
205 #endif
206
207 for (size_t i = 0; i < size; ++i) {
208 if (!prefix_string.empty())
209 handler->HandleOutput(prefix_string.c_str());
210
211 OutputFrameId(i, handler);
212 handler->HandleOutput(" ");
213 OutputPointer(trace[i], handler);
214 handler->HandleOutput(" ");
215
216 char buf[1024] = {'\0'};
217
218 // Subtract by one as return address of function may be in the next
219 // function when a function is annotated as noreturn.
220 const void* address = static_cast<const char*>(trace[i]) - 1;
221 if (google::Symbolize(const_cast<void*>(address), buf, sizeof(buf))) {
222 handler->HandleOutput(buf);
223 #if BUILDFLAG(ENABLE_STACK_TRACE_LINE_NUMBERS)
224 // Only output the source line number if the offset was found. Otherwise,
225 // it takes far too long in debug mode when there are lots of symbols.
226 if (GetDwarfSourceLineNumber(address, cu_offsets[i], &buf[0],
227 sizeof(buf))) {
228 handler->HandleOutput(" [");
229 handler->HandleOutput(buf);
230 handler->HandleOutput("]");
231 }
232 #endif
233 } else {
234 handler->HandleOutput("<unknown>");
235 }
236
237 handler->HandleOutput("\n");
238 }
239 #else
240 bool printed = false;
241
242 // Below part is async-signal unsafe (uses malloc), so execute it only
243 // when we are not executing the signal handler.
244 if (in_signal_handler == 0 && IsValueInRangeForNumericType<int>(size)) {
245 #if defined(HAVE_DLADDR)
246 Dl_info dl_info;
247 for (size_t i = 0; i < size; ++i) {
248 if (!prefix_string.empty()) {
249 handler->HandleOutput(prefix_string.c_str());
250 }
251
252 OutputValue(i, handler);
253 handler->HandleOutput(" ");
254
255 const bool dl_info_found = dladdr(trace[i], &dl_info) != 0;
256 if (dl_info_found) {
257 const char* last_sep = strrchr(dl_info.dli_fname, '/');
258 const char* basename = last_sep ? last_sep + 1 : dl_info.dli_fname;
259 handler->HandleOutput(basename);
260 } else {
261 handler->HandleOutput("???");
262 }
263 handler->HandleOutput(" ");
264 OutputPointer(trace[i], handler);
265
266 handler->HandleOutput("\n");
267 }
268 printed = true;
269 #else // defined(HAVE_DLADDR)
270 std::unique_ptr<char*, FreeDeleter> trace_symbols(backtrace_symbols(
271 const_cast<void* const*>(trace), static_cast<int>(size)));
272 if (trace_symbols.get()) {
273 for (size_t i = 0; i < size; ++i) {
274 std::string trace_symbol = trace_symbols.get()[i];
275 DemangleSymbols(&trace_symbol);
276 if (!prefix_string.empty())
277 handler->HandleOutput(prefix_string.c_str());
278 handler->HandleOutput(trace_symbol.c_str());
279 handler->HandleOutput("\n");
280 }
281
282 printed = true;
283 }
284 #endif // defined(HAVE_DLADDR)
285 }
286
287 if (!printed) {
288 for (size_t i = 0; i < size; ++i) {
289 handler->HandleOutput(" [");
290 OutputPointer(trace[i], handler);
291 handler->HandleOutput("]\n");
292 }
293 }
294 #endif // defined(USE_SYMBOLIZE)
295 }
296 #endif // defined(HAVE_BACKTRACE)
297
PrintToStderr(const char * output)298 void PrintToStderr(const char* output) {
299 // NOTE: This code MUST be async-signal safe (it's used by in-process
300 // stack dumping signal handler). NO malloc or stdio is allowed here.
301 std::ignore = HANDLE_EINTR(write(STDERR_FILENO, output, strlen(output)));
302 }
303
304 #if BUILDFLAG(IS_LINUX) || BUILDFLAG(IS_ANDROID) || BUILDFLAG(IS_CHROMEOS)
AlarmSignalHandler(int signal,siginfo_t * info,void * void_context)305 void AlarmSignalHandler(int signal, siginfo_t* info, void* void_context) {
306 // We have seen rare cases on AMD linux where the default signal handler
307 // either does not run or a thread (Probably an AMD driver thread) prevents
308 // the termination of the gpu process. We catch this case when the alarm fires
309 // and then call exit_group() to kill all threads of the process. This has
310 // resolved the zombie gpu process issues we have seen on our context lost
311 // test.
312 // Note that many different calls were tried to kill the process when it is in
313 // this state. Only 'exit_group' was found to cause termination and it is
314 // speculated that only this works because only this exit kills all threads in
315 // the process (not simply the current thread).
316 // See: http://crbug.com/1396451.
317 PrintToStderr(
318 "Warning: Default signal handler failed to terminate process.\n");
319 PrintToStderr("Calling exit_group() directly to prevent timeout.\n");
320 // See: https://man7.org/linux/man-pages/man2/exit_group.2.html
321 syscall(SYS_exit_group, EXIT_FAILURE);
322 }
323 #endif // BUILDFLAG(IS_LINUX) || BUILDFLAG(IS_ANDROID) ||
324 // BUILDFLAG(IS_CHROMEOS)
325
StackDumpSignalHandler(int signal,siginfo_t * info,void * void_context)326 void StackDumpSignalHandler(int signal, siginfo_t* info, void* void_context) {
327 // NOTE: This code MUST be async-signal safe.
328 // NO malloc or stdio is allowed here.
329
330 #if !BUILDFLAG(IS_NACL)
331 // Give a registered callback a chance to recover from this signal
332 //
333 // V8 uses guard regions to guarantee memory safety in WebAssembly. This means
334 // some signals might be expected if they originate from Wasm code while
335 // accessing the guard region. We give V8 the chance to handle and recover
336 // from these signals first.
337 if (try_handle_signal != nullptr &&
338 try_handle_signal(signal, info, void_context)) {
339 // The first chance handler took care of this. The SA_RESETHAND flag
340 // replaced this signal handler upon entry, but we want to stay
341 // installed. Thus, we reinstall ourselves before returning.
342 struct sigaction action;
343 memset(&action, 0, sizeof(action));
344 action.sa_flags = static_cast<int>(SA_RESETHAND | SA_SIGINFO);
345 action.sa_sigaction = &StackDumpSignalHandler;
346 sigemptyset(&action.sa_mask);
347
348 sigaction(signal, &action, nullptr);
349 return;
350 }
351 #endif
352
353 // Do not take the "in signal handler" code path on Mac in a DCHECK-enabled
354 // build, as this prevents seeing a useful (symbolized) stack trace on a crash
355 // or DCHECK() failure. While it may not be fully safe to run the stack symbol
356 // printing code, in practice it's better to provide meaningful stack traces -
357 // and the risk is low given we're likely crashing already.
358 #if !BUILDFLAG(IS_APPLE) || !DCHECK_IS_ON()
359 // Record the fact that we are in the signal handler now, so that the rest
360 // of StackTrace can behave in an async-signal-safe manner.
361 in_signal_handler = 1;
362 #endif
363
364 if (BeingDebugged())
365 BreakDebugger();
366
367 PrintToStderr("Received signal ");
368 char buf[1024] = { 0 };
369 internal::itoa_r(signal, buf, sizeof(buf), 10, 0);
370 PrintToStderr(buf);
371 if (signal == SIGBUS) {
372 if (info->si_code == BUS_ADRALN)
373 PrintToStderr(" BUS_ADRALN ");
374 else if (info->si_code == BUS_ADRERR)
375 PrintToStderr(" BUS_ADRERR ");
376 else if (info->si_code == BUS_OBJERR)
377 PrintToStderr(" BUS_OBJERR ");
378 else
379 PrintToStderr(" <unknown> ");
380 } else if (signal == SIGFPE) {
381 if (info->si_code == FPE_FLTDIV)
382 PrintToStderr(" FPE_FLTDIV ");
383 else if (info->si_code == FPE_FLTINV)
384 PrintToStderr(" FPE_FLTINV ");
385 else if (info->si_code == FPE_FLTOVF)
386 PrintToStderr(" FPE_FLTOVF ");
387 else if (info->si_code == FPE_FLTRES)
388 PrintToStderr(" FPE_FLTRES ");
389 else if (info->si_code == FPE_FLTSUB)
390 PrintToStderr(" FPE_FLTSUB ");
391 else if (info->si_code == FPE_FLTUND)
392 PrintToStderr(" FPE_FLTUND ");
393 else if (info->si_code == FPE_INTDIV)
394 PrintToStderr(" FPE_INTDIV ");
395 else if (info->si_code == FPE_INTOVF)
396 PrintToStderr(" FPE_INTOVF ");
397 else
398 PrintToStderr(" <unknown> ");
399 } else if (signal == SIGILL) {
400 if (info->si_code == ILL_BADSTK)
401 PrintToStderr(" ILL_BADSTK ");
402 else if (info->si_code == ILL_COPROC)
403 PrintToStderr(" ILL_COPROC ");
404 else if (info->si_code == ILL_ILLOPN)
405 PrintToStderr(" ILL_ILLOPN ");
406 else if (info->si_code == ILL_ILLADR)
407 PrintToStderr(" ILL_ILLADR ");
408 else if (info->si_code == ILL_ILLTRP)
409 PrintToStderr(" ILL_ILLTRP ");
410 else if (info->si_code == ILL_PRVOPC)
411 PrintToStderr(" ILL_PRVOPC ");
412 else if (info->si_code == ILL_PRVREG)
413 PrintToStderr(" ILL_PRVREG ");
414 else
415 PrintToStderr(" <unknown> ");
416 } else if (signal == SIGSEGV) {
417 if (info->si_code == SEGV_MAPERR)
418 PrintToStderr(" SEGV_MAPERR ");
419 else if (info->si_code == SEGV_ACCERR)
420 PrintToStderr(" SEGV_ACCERR ");
421 #if defined(ARCH_CPU_X86_64) && \
422 (BUILDFLAG(IS_LINUX) || BUILDFLAG(IS_ANDROID) || BUILDFLAG(IS_CHROMEOS))
423 else if (info->si_code == SI_KERNEL)
424 PrintToStderr(" SI_KERNEL");
425 #endif
426 else
427 PrintToStderr(" <unknown> ");
428 }
429 if (signal == SIGBUS || signal == SIGFPE ||
430 signal == SIGILL || signal == SIGSEGV) {
431 internal::itoa_r(reinterpret_cast<intptr_t>(info->si_addr),
432 buf, sizeof(buf), 16, 12);
433 PrintToStderr(buf);
434 }
435 PrintToStderr("\n");
436
437 #if BUILDFLAG(CFI_ENFORCEMENT_TRAP)
438 if (signal == SIGILL && info->si_code == ILL_ILLOPN) {
439 PrintToStderr(
440 "CFI: Most likely a control flow integrity violation; for more "
441 "information see:\n");
442 PrintToStderr(
443 "https://www.chromium.org/developers/testing/control-flow-integrity\n");
444 }
445 #endif // BUILDFLAG(CFI_ENFORCEMENT_TRAP)
446
447 #if defined(ARCH_CPU_X86_64) && \
448 (BUILDFLAG(IS_LINUX) || BUILDFLAG(IS_ANDROID) || BUILDFLAG(IS_CHROMEOS))
449 if (signal == SIGSEGV && info->si_code == SI_KERNEL) {
450 PrintToStderr(
451 " Possibly a General Protection Fault, can be due to a non-canonical "
452 "address dereference. See \"Intel 64 and IA-32 Architectures Software "
453 "Developer’s Manual\", Volume 1, Section 3.3.7.1.\n");
454 }
455 #endif
456
457 debug::StackTrace().Print();
458
459 #if BUILDFLAG(IS_LINUX) || BUILDFLAG(IS_CHROMEOS)
460 #if ARCH_CPU_X86_FAMILY
461 ucontext_t* context = reinterpret_cast<ucontext_t*>(void_context);
462 const struct {
463 const char* label;
464 greg_t value;
465 } registers[] = {
466 #if ARCH_CPU_32_BITS
467 { " gs: ", context->uc_mcontext.gregs[REG_GS] },
468 { " fs: ", context->uc_mcontext.gregs[REG_FS] },
469 { " es: ", context->uc_mcontext.gregs[REG_ES] },
470 { " ds: ", context->uc_mcontext.gregs[REG_DS] },
471 { " edi: ", context->uc_mcontext.gregs[REG_EDI] },
472 { " esi: ", context->uc_mcontext.gregs[REG_ESI] },
473 { " ebp: ", context->uc_mcontext.gregs[REG_EBP] },
474 { " esp: ", context->uc_mcontext.gregs[REG_ESP] },
475 { " ebx: ", context->uc_mcontext.gregs[REG_EBX] },
476 { " edx: ", context->uc_mcontext.gregs[REG_EDX] },
477 { " ecx: ", context->uc_mcontext.gregs[REG_ECX] },
478 { " eax: ", context->uc_mcontext.gregs[REG_EAX] },
479 { " trp: ", context->uc_mcontext.gregs[REG_TRAPNO] },
480 { " err: ", context->uc_mcontext.gregs[REG_ERR] },
481 { " ip: ", context->uc_mcontext.gregs[REG_EIP] },
482 { " cs: ", context->uc_mcontext.gregs[REG_CS] },
483 { " efl: ", context->uc_mcontext.gregs[REG_EFL] },
484 { " usp: ", context->uc_mcontext.gregs[REG_UESP] },
485 { " ss: ", context->uc_mcontext.gregs[REG_SS] },
486 #elif ARCH_CPU_64_BITS
487 { " r8: ", context->uc_mcontext.gregs[REG_R8] },
488 { " r9: ", context->uc_mcontext.gregs[REG_R9] },
489 { " r10: ", context->uc_mcontext.gregs[REG_R10] },
490 { " r11: ", context->uc_mcontext.gregs[REG_R11] },
491 { " r12: ", context->uc_mcontext.gregs[REG_R12] },
492 { " r13: ", context->uc_mcontext.gregs[REG_R13] },
493 { " r14: ", context->uc_mcontext.gregs[REG_R14] },
494 { " r15: ", context->uc_mcontext.gregs[REG_R15] },
495 { " di: ", context->uc_mcontext.gregs[REG_RDI] },
496 { " si: ", context->uc_mcontext.gregs[REG_RSI] },
497 { " bp: ", context->uc_mcontext.gregs[REG_RBP] },
498 { " bx: ", context->uc_mcontext.gregs[REG_RBX] },
499 { " dx: ", context->uc_mcontext.gregs[REG_RDX] },
500 { " ax: ", context->uc_mcontext.gregs[REG_RAX] },
501 { " cx: ", context->uc_mcontext.gregs[REG_RCX] },
502 { " sp: ", context->uc_mcontext.gregs[REG_RSP] },
503 { " ip: ", context->uc_mcontext.gregs[REG_RIP] },
504 { " efl: ", context->uc_mcontext.gregs[REG_EFL] },
505 { " cgf: ", context->uc_mcontext.gregs[REG_CSGSFS] },
506 { " erf: ", context->uc_mcontext.gregs[REG_ERR] },
507 { " trp: ", context->uc_mcontext.gregs[REG_TRAPNO] },
508 { " msk: ", context->uc_mcontext.gregs[REG_OLDMASK] },
509 { " cr2: ", context->uc_mcontext.gregs[REG_CR2] },
510 #endif // ARCH_CPU_32_BITS
511 };
512
513 #if ARCH_CPU_32_BITS
514 const int kRegisterPadding = 8;
515 #elif ARCH_CPU_64_BITS
516 const int kRegisterPadding = 16;
517 #endif
518
519 for (size_t i = 0; i < std::size(registers); i++) {
520 PrintToStderr(registers[i].label);
521 internal::itoa_r(registers[i].value, buf, sizeof(buf),
522 16, kRegisterPadding);
523 PrintToStderr(buf);
524
525 if ((i + 1) % 4 == 0)
526 PrintToStderr("\n");
527 }
528 PrintToStderr("\n");
529 #endif // ARCH_CPU_X86_FAMILY
530 #endif // BUILDFLAG(IS_LINUX) || BUILDFLAG(IS_CHROMEOS)
531
532 PrintToStderr("[end of stack trace]\n");
533
534 if (::signal(signal, SIG_DFL) == SIG_ERR) {
535 _exit(EXIT_FAILURE);
536 }
537
538 #if BUILDFLAG(IS_LINUX) || BUILDFLAG(IS_ANDROID) || BUILDFLAG(IS_CHROMEOS)
539 // Set an alarm to trigger in case the default handler does not terminate
540 // the process. See 'AlarmSignalHandler' for more details.
541 struct sigaction action;
542 memset(&action, 0, sizeof(action));
543 action.sa_flags = static_cast<int>(SA_RESETHAND);
544 action.sa_sigaction = &AlarmSignalHandler;
545 sigemptyset(&action.sa_mask);
546 sigaction(SIGALRM, &action, nullptr);
547 // 'alarm' function is signal handler safe.
548 // https://man7.org/linux/man-pages/man7/signal-safety.7.html
549 // This delay is set to be long enough for the real signal handler to fire but
550 // shorter than chrome's process watchdog timer.
551 constexpr unsigned int kAlarmSignalDelaySeconds = 5;
552 alarm(kAlarmSignalDelaySeconds);
553
554 // The following is mostly from
555 // third_party/crashpad/crashpad/util/posix/signals.cc as re-raising signals
556 // is complicated.
557
558 // If we can raise a signal with siginfo on this platform, do so. This ensures
559 // that we preserve the siginfo information for asynchronous signals (i.e.
560 // signals that do not re-raise autonomously), such as signals delivered via
561 // kill() and asynchronous hardware faults such as SEGV_MTEAERR, which would
562 // otherwise be lost when re-raising the signal via raise().
563 long retval = syscall(SYS_rt_tgsigqueueinfo, getpid(), syscall(SYS_gettid),
564 info->si_signo, info);
565 if (retval == 0) {
566 return;
567 }
568
569 // Kernels without commit 66dd34ad31e5 ("signal: allow to send any siginfo to
570 // itself"), which was first released in kernel version 3.9, did not permit a
571 // process to send arbitrary signals to itself, and will reject the
572 // rt_tgsigqueueinfo syscall with EPERM. If that happens, follow the non-Linux
573 // code path. Any other errno is unexpected and will cause us to exit.
574 if (errno != EPERM) {
575 _exit(EXIT_FAILURE);
576 }
577 #endif // BUILDFLAG(IS_LINUX) || BUILDFLAG(IS_ANDROID) ||
578 // BUILDFLAG(IS_CHROMEOS)
579
580 // Explicitly re-raise the signal even if it might have re-raised itself on
581 // return. Because signal handlers normally execute with their signal blocked,
582 // this raise() cannot immediately deliver the signal. Delivery is deferred
583 // until the signal handler returns and the signal becomes unblocked. The
584 // re-raised signal will appear with the same context as where it was
585 // initially triggered.
586 if (raise(signal) != 0) {
587 _exit(EXIT_FAILURE);
588 }
589 }
590
591 class PrintBacktraceOutputHandler : public BacktraceOutputHandler {
592 public:
593 PrintBacktraceOutputHandler() = default;
594
595 PrintBacktraceOutputHandler(const PrintBacktraceOutputHandler&) = delete;
596 PrintBacktraceOutputHandler& operator=(const PrintBacktraceOutputHandler&) =
597 delete;
598
HandleOutput(const char * output)599 void HandleOutput(const char* output) override {
600 // NOTE: This code MUST be async-signal safe (it's used by in-process
601 // stack dumping signal handler). NO malloc or stdio is allowed here.
602 PrintToStderr(output);
603 }
604 };
605
606 class StreamBacktraceOutputHandler : public BacktraceOutputHandler {
607 public:
StreamBacktraceOutputHandler(std::ostream * os)608 explicit StreamBacktraceOutputHandler(std::ostream* os) : os_(os) {
609 }
610
611 StreamBacktraceOutputHandler(const StreamBacktraceOutputHandler&) = delete;
612 StreamBacktraceOutputHandler& operator=(const StreamBacktraceOutputHandler&) =
613 delete;
614
HandleOutput(const char * output)615 void HandleOutput(const char* output) override { (*os_) << output; }
616
617 private:
618 raw_ptr<std::ostream> os_;
619 };
620
WarmUpBacktrace()621 void WarmUpBacktrace() {
622 // Warm up stack trace infrastructure. It turns out that on the first
623 // call glibc initializes some internal data structures using pthread_once,
624 // and even backtrace() can call malloc(), leading to hangs.
625 //
626 // Example stack trace snippet (with tcmalloc):
627 //
628 // #8 0x0000000000a173b5 in tc_malloc
629 // at ./third_party/tcmalloc/chromium/src/debugallocation.cc:1161
630 // #9 0x00007ffff7de7900 in _dl_map_object_deps at dl-deps.c:517
631 // #10 0x00007ffff7ded8a9 in dl_open_worker at dl-open.c:262
632 // #11 0x00007ffff7de9176 in _dl_catch_error at dl-error.c:178
633 // #12 0x00007ffff7ded31a in _dl_open (file=0x7ffff625e298 "libgcc_s.so.1")
634 // at dl-open.c:639
635 // #13 0x00007ffff6215602 in do_dlopen at dl-libc.c:89
636 // #14 0x00007ffff7de9176 in _dl_catch_error at dl-error.c:178
637 // #15 0x00007ffff62156c4 in dlerror_run at dl-libc.c:48
638 // #16 __GI___libc_dlopen_mode at dl-libc.c:165
639 // #17 0x00007ffff61ef8f5 in init
640 // at ../sysdeps/x86_64/../ia64/backtrace.c:53
641 // #18 0x00007ffff6aad400 in pthread_once
642 // at ../nptl/sysdeps/unix/sysv/linux/x86_64/pthread_once.S:104
643 // #19 0x00007ffff61efa14 in __GI___backtrace
644 // at ../sysdeps/x86_64/../ia64/backtrace.c:104
645 // #20 0x0000000000752a54 in base::debug::StackTrace::StackTrace
646 // at base/debug/stack_trace_posix.cc:175
647 // #21 0x00000000007a4ae5 in
648 // base::(anonymous namespace)::StackDumpSignalHandler
649 // at base/process_util_posix.cc:172
650 // #22 <signal handler called>
651 StackTrace stack_trace;
652 }
653
654 #if defined(USE_SYMBOLIZE)
655
656 // class SandboxSymbolizeHelper.
657 //
658 // The purpose of this class is to prepare and install a "file open" callback
659 // needed by the stack trace symbolization code
660 // (base/third_party/symbolize/symbolize.h) so that it can function properly
661 // in a sandboxed process. The caveat is that this class must be instantiated
662 // before the sandboxing is enabled so that it can get the chance to open all
663 // the object files that are loaded in the virtual address space of the current
664 // process.
665 class SandboxSymbolizeHelper {
666 public:
667 // Returns the singleton instance.
GetInstance()668 static SandboxSymbolizeHelper* GetInstance() {
669 return Singleton<SandboxSymbolizeHelper,
670 LeakySingletonTraits<SandboxSymbolizeHelper>>::get();
671 }
672
673 SandboxSymbolizeHelper(const SandboxSymbolizeHelper&) = delete;
674 SandboxSymbolizeHelper& operator=(const SandboxSymbolizeHelper&) = delete;
675
676 private:
677 friend struct DefaultSingletonTraits<SandboxSymbolizeHelper>;
678
SandboxSymbolizeHelper()679 SandboxSymbolizeHelper()
680 : is_initialized_(false) {
681 Init();
682 }
683
~SandboxSymbolizeHelper()684 ~SandboxSymbolizeHelper() {
685 UnregisterCallback();
686 CloseObjectFiles();
687 }
688
689 // Returns a O_RDONLY file descriptor for |file_path| if it was opened
690 // successfully during the initialization. The file is repositioned at
691 // offset 0.
692 // IMPORTANT: This function must be async-signal-safe because it can be
693 // called from a signal handler (symbolizing stack frames for a crash).
GetFileDescriptor(const char * file_path)694 int GetFileDescriptor(const char* file_path) {
695 int fd = -1;
696
697 #if !defined(OFFICIAL_BUILD) || !defined(NO_UNWIND_TABLES)
698 if (file_path) {
699 // The assumption here is that iterating over std::map<std::string,
700 // base::ScopedFD> does not allocate dynamic memory, hence it is
701 // async-signal-safe.
702 for (const auto& filepath_fd : modules_) {
703 if (strcmp(filepath_fd.first.c_str(), file_path) == 0) {
704 // POSIX.1-2004 requires an implementation to guarantee that dup()
705 // is async-signal-safe.
706 fd = HANDLE_EINTR(dup(filepath_fd.second.get()));
707 break;
708 }
709 }
710 // POSIX.1-2004 requires an implementation to guarantee that lseek()
711 // is async-signal-safe.
712 if (fd >= 0 && lseek(fd, 0, SEEK_SET) < 0) {
713 // Failed to seek.
714 fd = -1;
715 }
716 }
717 #endif // !defined(OFFICIAL_BUILD) || !defined(NO_UNWIND_TABLES)
718
719 return fd;
720 }
721
722 // Searches for the object file (from /proc/self/maps) that contains
723 // the specified pc. If found, sets |start_address| to the start address
724 // of where this object file is mapped in memory, sets the module base
725 // address into |base_address|, copies the object file name into
726 // |out_file_name|, and attempts to open the object file. If the object
727 // file is opened successfully, returns the file descriptor. Otherwise,
728 // returns -1. |out_file_name_size| is the size of the file name buffer
729 // (including the null terminator).
730 // IMPORTANT: This function must be async-signal-safe because it can be
731 // called from a signal handler (symbolizing stack frames for a crash).
OpenObjectFileContainingPc(uint64_t pc,uint64_t & start_address,uint64_t & base_address,char * file_path,size_t file_path_size)732 static int OpenObjectFileContainingPc(uint64_t pc,
733 uint64_t& start_address,
734 uint64_t& base_address,
735 char* file_path,
736 size_t file_path_size) {
737 // This method can only be called after the singleton is instantiated.
738 // This is ensured by the following facts:
739 // * This is the only static method in this class, it is private, and
740 // the class has no friends (except for the DefaultSingletonTraits).
741 // The compiler guarantees that it can only be called after the
742 // singleton is instantiated.
743 // * This method is used as a callback for the stack tracing code and
744 // the callback registration is done in the constructor, so logically
745 // it cannot be called before the singleton is created.
746 SandboxSymbolizeHelper* instance = GetInstance();
747
748 // Cannot use STL iterators here, since debug iterators use locks.
749 // NOLINTNEXTLINE(modernize-loop-convert)
750 for (size_t i = 0; i < instance->regions_.size(); ++i) {
751 const MappedMemoryRegion& region = instance->regions_[i];
752 if (region.start <= pc && pc < region.end) {
753 start_address = region.start;
754 base_address = region.base;
755 if (file_path && file_path_size > 0) {
756 strncpy(file_path, region.path.c_str(), file_path_size);
757 // Ensure null termination.
758 file_path[file_path_size - 1] = '\0';
759 }
760 return instance->GetFileDescriptor(region.path.c_str());
761 }
762 }
763 return -1;
764 }
765
766 // This class is copied from
767 // third_party/crashpad/crashpad/util/linux/scoped_pr_set_dumpable.h.
768 // It aims at ensuring the process is dumpable before opening /proc/self/mem.
769 // If the process is already dumpable, this class doesn't do anything.
770 class ScopedPrSetDumpable {
771 public:
772 // Uses `PR_SET_DUMPABLE` to make the current process dumpable.
773 //
774 // Restores the dumpable flag to its original value on destruction. If the
775 // original value couldn't be determined, the destructor attempts to
776 // restore the flag to 0 (non-dumpable).
ScopedPrSetDumpable()777 explicit ScopedPrSetDumpable() {
778 int result = prctl(PR_GET_DUMPABLE, 0, 0, 0, 0);
779 was_dumpable_ = result > 0;
780
781 if (!was_dumpable_) {
782 std::ignore = prctl(PR_SET_DUMPABLE, 1, 0, 0, 0);
783 }
784 }
785
786 ScopedPrSetDumpable(const ScopedPrSetDumpable&) = delete;
787 ScopedPrSetDumpable& operator=(const ScopedPrSetDumpable&) = delete;
788
~ScopedPrSetDumpable()789 ~ScopedPrSetDumpable() {
790 if (!was_dumpable_) {
791 std::ignore = prctl(PR_SET_DUMPABLE, 0, 0, 0, 0);
792 }
793 }
794
795 private:
796 bool was_dumpable_;
797 };
798
799 // Set the base address for each memory region by reading ELF headers in
800 // process memory.
SetBaseAddressesForMemoryRegions()801 void SetBaseAddressesForMemoryRegions() {
802 base::ScopedFD mem_fd;
803 {
804 ScopedPrSetDumpable s;
805 mem_fd = base::ScopedFD(
806 HANDLE_EINTR(open("/proc/self/mem", O_RDONLY | O_CLOEXEC)));
807 if (!mem_fd.is_valid()) {
808 return;
809 }
810 }
811
812 auto safe_memcpy = [&mem_fd](void* dst, uintptr_t src, size_t size) {
813 return HANDLE_EINTR(pread(mem_fd.get(), dst, size,
814 static_cast<off_t>(src))) == ssize_t(size);
815 };
816
817 uintptr_t cur_base = 0;
818 for (auto& r : regions_) {
819 ElfW(Ehdr) ehdr;
820 static_assert(SELFMAG <= sizeof(ElfW(Ehdr)), "SELFMAG too large");
821 if ((r.permissions & MappedMemoryRegion::READ) &&
822 safe_memcpy(&ehdr, r.start, sizeof(ElfW(Ehdr))) &&
823 memcmp(ehdr.e_ident, ELFMAG, SELFMAG) == 0) {
824 switch (ehdr.e_type) {
825 case ET_EXEC:
826 cur_base = 0;
827 break;
828 case ET_DYN:
829 // Find the segment containing file offset 0. This will correspond
830 // to the ELF header that we just read. Normally this will have
831 // virtual address 0, but this is not guaranteed. We must subtract
832 // the virtual address from the address where the ELF header was
833 // mapped to get the base address.
834 //
835 // If we fail to find a segment for file offset 0, use the address
836 // of the ELF header as the base address.
837 cur_base = r.start;
838 for (unsigned i = 0; i != ehdr.e_phnum; ++i) {
839 ElfW(Phdr) phdr;
840 if (safe_memcpy(&phdr, r.start + ehdr.e_phoff + i * sizeof(phdr),
841 sizeof(phdr)) &&
842 phdr.p_type == PT_LOAD && phdr.p_offset == 0) {
843 cur_base = r.start - phdr.p_vaddr;
844 break;
845 }
846 }
847 break;
848 default:
849 // ET_REL or ET_CORE. These aren't directly executable, so they
850 // don't affect the base address.
851 break;
852 }
853 }
854
855 r.base = cur_base;
856 }
857 }
858
859 // Parses /proc/self/maps in order to compile a list of all object file names
860 // for the modules that are loaded in the current process.
861 // Returns true on success.
CacheMemoryRegions()862 bool CacheMemoryRegions() {
863 // Reads /proc/self/maps.
864 std::string contents;
865 if (!ReadProcMaps(&contents)) {
866 LOG(ERROR) << "Failed to read /proc/self/maps";
867 return false;
868 }
869
870 // Parses /proc/self/maps.
871 if (!ParseProcMaps(contents, ®ions_)) {
872 LOG(ERROR) << "Failed to parse the contents of /proc/self/maps";
873 return false;
874 }
875
876 SetBaseAddressesForMemoryRegions();
877
878 is_initialized_ = true;
879 return true;
880 }
881
882 // Opens all object files and caches their file descriptors.
OpenSymbolFiles()883 void OpenSymbolFiles() {
884 // Pre-opening and caching the file descriptors of all loaded modules is
885 // not safe for production builds. Hence it is only done in non-official
886 // builds. For more details, take a look at: http://crbug.com/341966.
887 #if !defined(OFFICIAL_BUILD) || !defined(NO_UNWIND_TABLES)
888 // Open the object files for all read-only executable regions and cache
889 // their file descriptors.
890 std::vector<MappedMemoryRegion>::const_iterator it;
891 for (it = regions_.begin(); it != regions_.end(); ++it) {
892 const MappedMemoryRegion& region = *it;
893 // Only interesed in read-only executable regions.
894 if ((region.permissions & MappedMemoryRegion::READ) ==
895 MappedMemoryRegion::READ &&
896 (region.permissions & MappedMemoryRegion::WRITE) == 0 &&
897 (region.permissions & MappedMemoryRegion::EXECUTE) ==
898 MappedMemoryRegion::EXECUTE) {
899 if (region.path.empty()) {
900 // Skip regions with empty file names.
901 continue;
902 }
903 if (region.path[0] == '[') {
904 // Skip pseudo-paths, like [stack], [vdso], [heap], etc ...
905 continue;
906 }
907 if (base::EndsWith(region.path, " (deleted)",
908 base::CompareCase::SENSITIVE)) {
909 // Skip deleted files.
910 continue;
911 }
912 // Avoid duplicates.
913 if (modules_.find(region.path) == modules_.end()) {
914 int fd = open(region.path.c_str(), O_RDONLY | O_CLOEXEC);
915 if (fd >= 0) {
916 modules_.emplace(region.path, base::ScopedFD(fd));
917 } else {
918 LOG(WARNING) << "Failed to open file: " << region.path
919 << "\n Error: " << strerror(errno);
920 }
921 }
922 }
923 }
924 #endif // !defined(OFFICIAL_BUILD) || !defined(NO_UNWIND_TABLES)
925 }
926
927 // Initializes and installs the symbolization callback.
Init()928 void Init() {
929 if (CacheMemoryRegions()) {
930 OpenSymbolFiles();
931 google::InstallSymbolizeOpenObjectFileCallback(
932 &OpenObjectFileContainingPc);
933 }
934 }
935
936 // Unregister symbolization callback.
UnregisterCallback()937 void UnregisterCallback() {
938 if (is_initialized_) {
939 google::InstallSymbolizeOpenObjectFileCallback(nullptr);
940 is_initialized_ = false;
941 }
942 }
943
944 // Closes all file descriptors owned by this instance.
CloseObjectFiles()945 void CloseObjectFiles() {
946 #if !defined(OFFICIAL_BUILD) || !defined(NO_UNWIND_TABLES)
947 modules_.clear();
948 #endif // !defined(OFFICIAL_BUILD) || !defined(NO_UNWIND_TABLES)
949 }
950
951 // Set to true upon successful initialization.
952 bool is_initialized_;
953
954 #if !defined(OFFICIAL_BUILD) || !defined(NO_UNWIND_TABLES)
955 // Mapping from file name to file descriptor. Includes file descriptors
956 // for all successfully opened object files and the file descriptor for
957 // /proc/self/maps. This code is not safe for production builds.
958 std::map<std::string, base::ScopedFD> modules_;
959 #endif // !defined(OFFICIAL_BUILD) || !defined(NO_UNWIND_TABLES)
960
961 // Cache for the process memory regions. Produced by parsing the contents
962 // of /proc/self/maps cache.
963 std::vector<MappedMemoryRegion> regions_;
964 };
965 #endif // USE_SYMBOLIZE
966
967 } // namespace
968
EnableInProcessStackDumping()969 bool EnableInProcessStackDumping() {
970 #if defined(USE_SYMBOLIZE)
971 SandboxSymbolizeHelper::GetInstance();
972 #endif // USE_SYMBOLIZE
973
974 // When running in an application, our code typically expects SIGPIPE
975 // to be ignored. Therefore, when testing that same code, it should run
976 // with SIGPIPE ignored as well.
977 struct sigaction sigpipe_action;
978 memset(&sigpipe_action, 0, sizeof(sigpipe_action));
979 sigpipe_action.sa_handler = SIG_IGN;
980 sigemptyset(&sigpipe_action.sa_mask);
981 bool success = (sigaction(SIGPIPE, &sigpipe_action, nullptr) == 0);
982
983 // Avoid hangs during backtrace initialization, see above.
984 WarmUpBacktrace();
985
986 struct sigaction action;
987 memset(&action, 0, sizeof(action));
988 action.sa_flags = static_cast<int>(SA_RESETHAND | SA_SIGINFO);
989 action.sa_sigaction = &StackDumpSignalHandler;
990 sigemptyset(&action.sa_mask);
991
992 success &= (sigaction(SIGILL, &action, nullptr) == 0);
993 success &= (sigaction(SIGABRT, &action, nullptr) == 0);
994 success &= (sigaction(SIGFPE, &action, nullptr) == 0);
995 success &= (sigaction(SIGBUS, &action, nullptr) == 0);
996 success &= (sigaction(SIGSEGV, &action, nullptr) == 0);
997 // On Linux, SIGSYS is reserved by the kernel for seccomp-bpf sandboxing.
998 #if !BUILDFLAG(IS_LINUX) && !BUILDFLAG(IS_CHROMEOS)
999 success &= (sigaction(SIGSYS, &action, nullptr) == 0);
1000 #endif // !BUILDFLAG(IS_LINUX) && !BUILDFLAG(IS_CHROMEOS)
1001
1002 return success;
1003 }
1004
1005 #if !BUILDFLAG(IS_NACL)
SetStackDumpFirstChanceCallback(bool (* handler)(int,siginfo_t *,void *))1006 bool SetStackDumpFirstChanceCallback(bool (*handler)(int, siginfo_t*, void*)) {
1007 DCHECK(try_handle_signal == nullptr || handler == nullptr);
1008 try_handle_signal = handler;
1009
1010 #if defined(ADDRESS_SANITIZER) || defined(MEMORY_SANITIZER) || \
1011 defined(THREAD_SANITIZER) || defined(LEAK_SANITIZER) || \
1012 defined(UNDEFINED_SANITIZER)
1013 struct sigaction installed_handler;
1014 CHECK_EQ(sigaction(SIGSEGV, NULL, &installed_handler), 0);
1015 // If the installed handler does not point to StackDumpSignalHandler, then
1016 // allow_user_segv_handler is 0.
1017 if (installed_handler.sa_sigaction != StackDumpSignalHandler) {
1018 LOG(WARNING)
1019 << "WARNING: sanitizers are preventing signal handler installation. "
1020 << "WebAssembly trap handlers are disabled.\n";
1021 return false;
1022 }
1023 #endif
1024 return true;
1025 }
1026 #endif
1027
CollectStackTrace(const void ** trace,size_t count)1028 size_t CollectStackTrace(const void** trace, size_t count) {
1029 // NOTE: This code MUST be async-signal safe (it's used by in-process
1030 // stack dumping signal handler). NO malloc or stdio is allowed here.
1031
1032 #if defined(NO_UNWIND_TABLES) && BUILDFLAG(CAN_UNWIND_WITH_FRAME_POINTERS)
1033 // If we do not have unwind tables, then try tracing using frame pointers.
1034 return base::debug::TraceStackFramePointers(trace, count, 0);
1035 #elif defined(HAVE_BACKTRACE)
1036 // Though the backtrace API man page does not list any possible negative
1037 // return values, we take no chance.
1038 return base::saturated_cast<size_t>(
1039 backtrace(const_cast<void**>(trace), base::saturated_cast<int>(count)));
1040 #else
1041 return 0;
1042 #endif
1043 }
1044
1045 // static
PrintMessageWithPrefix(cstring_view prefix_string,cstring_view message)1046 void StackTrace::PrintMessageWithPrefix(cstring_view prefix_string,
1047 cstring_view message) {
1048 // NOTE: This code MUST be async-signal safe (it's used by in-process
1049 // stack dumping signal handler). NO malloc or stdio is allowed here.
1050 if (!prefix_string.empty()) {
1051 PrintToStderr(prefix_string.c_str());
1052 }
1053 PrintToStderr(message.c_str());
1054 }
1055
PrintWithPrefixImpl(cstring_view prefix_string) const1056 void StackTrace::PrintWithPrefixImpl(cstring_view prefix_string) const {
1057 // NOTE: This code MUST be async-signal safe (it's used by in-process
1058 // stack dumping signal handler). NO malloc or stdio is allowed here.
1059 #if defined(HAVE_BACKTRACE)
1060 PrintBacktraceOutputHandler handler;
1061 ProcessBacktrace(trace_, count_, prefix_string, &handler);
1062 #endif
1063 }
1064
1065 #if defined(HAVE_BACKTRACE)
OutputToStreamWithPrefixImpl(std::ostream * os,cstring_view prefix_string) const1066 void StackTrace::OutputToStreamWithPrefixImpl(
1067 std::ostream* os,
1068 cstring_view prefix_string) const {
1069 StreamBacktraceOutputHandler handler(os);
1070 ProcessBacktrace(trace_, count_, prefix_string, &handler);
1071 }
1072 #endif
1073
1074 namespace internal {
1075
1076 // NOTE: code from sandbox/linux/seccomp-bpf/demo.cc.
itoa_r(intptr_t i,char * buf,size_t sz,int base,size_t padding)1077 char* itoa_r(intptr_t i, char* buf, size_t sz, int base, size_t padding) {
1078 // Make sure we can write at least one NUL byte.
1079 size_t n = 1;
1080 if (n > sz)
1081 return nullptr;
1082
1083 if (base < 2 || base > 16) {
1084 buf[0] = '\000';
1085 return nullptr;
1086 }
1087
1088 char* start = buf;
1089
1090 uintptr_t j = static_cast<uintptr_t>(i);
1091
1092 // Handle negative numbers (only for base 10).
1093 if (i < 0 && base == 10) {
1094 // This does "j = -i" while avoiding integer overflow.
1095 j = static_cast<uintptr_t>(-(i + 1)) + 1;
1096
1097 // Make sure we can write the '-' character.
1098 if (++n > sz) {
1099 buf[0] = '\000';
1100 return nullptr;
1101 }
1102 *start++ = '-';
1103 }
1104
1105 // Loop until we have converted the entire number. Output at least one
1106 // character (i.e. '0').
1107 char* ptr = start;
1108 do {
1109 // Make sure there is still enough space left in our output buffer.
1110 if (++n > sz) {
1111 buf[0] = '\000';
1112 return nullptr;
1113 }
1114
1115 // Output the next digit.
1116 *ptr++ = "0123456789abcdef"[j % static_cast<uintptr_t>(base)];
1117 j /= static_cast<uintptr_t>(base);
1118
1119 if (padding > 0)
1120 padding--;
1121 } while (j > 0 || padding > 0);
1122
1123 // Terminate the output with a NUL character.
1124 *ptr = '\000';
1125
1126 // Conversion to ASCII actually resulted in the digits being in reverse
1127 // order. We can't easily generate them in forward order, as we can't tell
1128 // the number of characters needed until we are done converting.
1129 // So, now, we reverse the string (except for the possible "-" sign).
1130 while (--ptr > start) {
1131 char ch = *ptr;
1132 *ptr = *start;
1133 *start++ = ch;
1134 }
1135 return buf;
1136 }
1137
1138 } // namespace internal
1139
1140 } // namespace debug
1141 } // namespace base
1142