1
    2
    3
    4
    5
    6
    7
    8
    9
   10
   11
   12
   13
   14
   15
   16
   17
   18
   19
   20
   21
   22
   23
   24
   25
   26
   27
   28
   29
   30
   31
   32
   33
   34
   35
   36
   37
   38
   39
   40
   41
   42
   43
   44
   45
   46
   47
   48
   49
   50
   51
   52
   53
   54
   55
   56
   57
   58
   59
   60
   61
   62
   63
   64
   65
   66
   67
   68
   69
   70
   71
   72
   73
   74
   75
   76
   77
   78
   79
   80
   81
   82
   83
   84
   85
   86
   87
   88
   89
   90
   91
   92
   93
   94
   95
   96
   97
   98
   99
  100
  101
  102
  103
  104
  105
  106
  107
  108
  109
  110
  111
  112
  113
  114
  115
  116
  117
  118
  119
  120
  121
  122
  123
  124
  125
  126
  127
  128
  129
  130
  131
  132
  133
  134
  135
  136
  137
  138
  139
  140
  141
  142
  143
  144
  145
  146
  147
  148
  149
  150
  151
  152
  153
  154
  155
  156
  157
  158
  159
  160
  161
  162
  163
  164
  165
  166
  167
  168
  169
  170
  171
  172
  173
  174
  175
  176
  177
  178
  179
  180
  181
  182
  183
  184
  185
  186
  187
  188
  189
  190
  191
  192
  193
  194
  195
  196
  197
  198
  199
  200
  201
  202
  203
  204
  205
  206
  207
  208
  209
  210
  211
  212
  213
  214
  215
  216
  217
  218
  219
  220
  221
  222
  223
  224
  225
  226
  227
  228
  229
  230
  231
  232
  233
  234
  235
  236
  237
  238
  239
  240
  241
  242
  243
  244
  245
  246
  247
  248
  249
  250
  251
  252
  253
  254
  255
  256
  257
  258
  259
  260
  261
  262
  263
  264
  265
  266
  267
  268
  269
  270
  271
  272
  273
  274
  275
  276
  277
  278
  279
  280
  281
  282
  283
  284
  285
  286
  287
  288
  289
  290
  291
  292
  293
  294
  295
  296
  297
  298
  299
  300
  301
  302
  303
  304
  305
  306
  307
  308
  309
  310
  311
  312
  313
  314
  315
  316
  317
  318
  319
  320
  321
  322
  323
  324
  325
  326
  327
  328
  329
  330
  331
  332
  333
  334
  335
  336
  337
  338
  339
  340
  341
  342
  343
  344
  345
  346
  347
  348
  349
  350
  351
  352
  353
  354
  355
  356
  357
  358
  359
  360
  361
  362
  363
  364
  365
  366
  367
  368
  369
  370
  371
  372
  373
  374
  375
  376
  377
  378
  379
  380
  381
  382
  383
  384
  385
  386
  387
  388
  389
  390
  391
  392
  393
  394
  395
  396
  397
  398
  399
  400
  401
  402
  403
  404
  405
  406
  407
  408
  409
  410
  411
  412
  413
  414
  415
  416
  417
  418
  419
  420
  421
  422
  423
  424
  425
  426
  427
  428
  429
  430
  431
  432
  433
  434
  435
  436
  437
  438
  439
  440
  441
  442
  443
  444
  445
  446
  447
  448
  449
  450
  451
  452
  453
  454
  455
  456
  457
  458
  459
  460
  461
  462
  463
  464
  465
  466
  467
  468
  469
  470
  471
  472
  473
  474
  475
  476
  477
  478
  479
  480
  481
  482
  483
  484
  485
  486
  487
  488
  489
  490
  491
  492
  493
  494
  495
  496
  497
  498
  499
  500
  501
  502
  503
  504
  505
  506
  507
  508
  509
  510
  511
  512
  513
  514
  515
  516
  517
  518
  519
  520
  521
  522
  523
  524
  525
  526
  527
  528
  529
  530
  531
  532
  533
  534
  535
  536
  537
  538
  539
  540
  541
  542
  543
  544
  545
  546
  547
  548
  549
  550
  551
  552
  553
  554
  555
  556
  557
  558
  559
  560
  561
  562
  563
  564
  565
  566
  567
  568
  569
  570
  571
  572
  573
  574
  575
  576
  577
  578
  579
  580
  581
  582
  583
  584
  585
  586
  587
  588
  589
  590
  591
  592
  593
  594
  595
  596
  597
  598
  599
  600
  601
  602
  603
  604
  605
  606
  607
  608
  609
  610
  611
  612
  613
  614
  615
  616
  617
  618
  619
  620
  621
  622
  623
  624
  625
  626
  627
  628
  629
  630
  631
  632
  633
  634
  635
  636
  637
  638
  639
  640
  641
  642
  643
  644
  645
  646
  647
  648
  649
  650
  651
  652
  653
  654
  655
  656
  657
  658
  659
  660
  661
  662
  663
  664
  665
  666
  667
  668
  669
  670
  671
  672
  673
  674
  675
  676
  677
  678
  679
  680
  681
  682
  683
  684
  685
  686
  687
  688
  689
  690
  691
  692
  693
  694
  695
  696
  697
  698
  699
  700
  701
  702
  703
  704
  705
  706
  707
  708
  709
  710
  711
  712
  713
  714
  715
  716
  717
  718
  719
  720
  721
  722
  723
  724
  725
  726
  727
  728
  729
  730
  731
  732
  733
  734
  735
  736
  737
  738
  739
  740
  741
  742
  743
  744
  745
  746
  747
  748
  749
  750
  751
  752
  753
  754
  755
  756
  757
  758
  759
  760
  761
  762
  763
  764
  765
  766
  767
  768
  769
  770
  771
  772
  773
  774
  775
  776
  777
  778
  779
  780
  781
  782
  783
  784
  785
  786
  787
  788
  789
  790
  791
  792
  793
  794
  795
  796
  797
  798
  799
  800
  801
  802
  803
  804
  805
  806
  807
  808
  809
  810
  811
  812
  813
  814
  815
  816
  817
  818
  819
  820
  821
  822
  823
  824
  825
  826
  827
  828
  829
  830
  831
  832
  833
  834
  835
  836
  837
  838
  839
  840
  841
  842
  843
  844
  845
  846
  847
  848
  849
  850
  851
  852
  853
  854
  855
  856
  857
  858
  859
  860
  861
  862
  863
  864
  865
  866
  867
  868
  869
  870
  871
  872
  873
  874
  875
  876
  877
  878
  879
  880
  881
  882
  883
  884
  885
  886
  887
  888
  889
  890
  891
  892
  893
  894
  895
  896
  897
  898
  899
  900
  901
  902
  903
  904
  905
  906
  907
  908
  909
  910
  911
  912
  913
  914
  915
  916
  917
  918
  919
  920
  921
  922
  923
  924
  925
  926
  927
  928
  929
  930
  931
  932
  933
  934
  935
  936
  937
  938
  939
  940
  941
  942
  943
  944
  945
  946
  947
  948
  949
  950
  951
  952
  953
  954
  955
  956
  957
  958
  959
  960
  961
  962
  963
  964
  965
  966
  967
  968
  969
  970
  971
  972
  973
  974
  975
  976
  977
  978
  979
  980
  981
  982
  983
  984
  985
  986
  987
  988
  989
  990
  991
  992
  993
  994
  995
  996
  997
  998
  999
 1000
 1001
 1002
 1003
 1004
 1005
 1006
 1007
 1008
 1009
 1010
 1011
 1012
 1013
 1014
 1015
 1016
 1017
 1018
 1019
 1020
 1021
 1022
 1023
 1024
 1025
 1026
 1027
 1028
 1029
 1030
 1031
 1032
 1033
 1034
 1035
 1036
 1037
 1038
 1039
 1040
 1041
 1042
 1043
 1044
 1045
 1046
 1047
 1048
 1049
 1050
 1051
 1052
 1053
 1054
 1055
 1056
 1057
 1058
 1059
 1060
 1061
 1062
 1063
 1064
 1065
 1066
 1067
 1068
 1069
 1070
 1071
 1072
 1073
 1074
 1075
 1076
 1077
 1078
 1079
 1080
 1081
 1082
 1083
 1084
 1085
 1086
 1087
 1088
 1089
 1090
 1091
 1092
 1093
 1094
 1095
 1096
 1097
 1098
 1099
 1100
 1101
 1102
 1103
 1104
 1105
 1106
 1107
 1108
 1109
 1110
 1111
 1112
 1113
 1114
 1115
 1116
 1117
 1118
 1119
 1120
 1121
 1122
 1123
 1124
 1125
 1126
 1127
 1128
 1129
 1130
 1131
 1132
 1133
 1134
 1135
 1136
 1137
 1138
 1139
 1140
 1141
 1142
 1143
 1144
 1145
 1146

base / debug / stack_trace_posix.cc [blame]

// Copyright 2012 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "base/debug/stack_trace.h"

#include <errno.h>
#include <fcntl.h>
#include <signal.h>
#include <stddef.h>
#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/param.h>
#include <sys/stat.h>
#include <sys/syscall.h>
#include <sys/types.h>
#include <unistd.h>

#include <algorithm>
#include <array>
#include <map>
#include <memory>
#include <ostream>
#include <string>
#include <tuple>
#include <vector>

#include "base/containers/heap_array.h"
#include "base/containers/span.h"
#include "base/containers/span_writer.h"
#include "base/memory/raw_ptr.h"
#include "base/strings/cstring_view.h"
#include "build/build_config.h"

// Controls whether `dladdr(...)` is used to print the callstack. This is
// only used on iOS Official build where `backtrace_symbols(...)` prints
// misleading symbols (as the binary is stripped).
#if BUILDFLAG(IS_IOS) && defined(OFFICIAL_BUILD)
#define HAVE_DLADDR
#include <dlfcn.h>
#endif

// Surprisingly, uClibc defines __GLIBC__ in some build configs, but
// execinfo.h and backtrace(3) are really only present in glibc and in macOS
// libc.
#if BUILDFLAG(IS_APPLE) || \
    (defined(__GLIBC__) && !defined(__UCLIBC__) && !defined(__AIX))
#define HAVE_BACKTRACE
#include <execinfo.h>
#endif

// Controls whether to include code to demangle C++ symbols.
#if !defined(USE_SYMBOLIZE) && defined(HAVE_BACKTRACE) && !defined(HAVE_DLADDR)
#define DEMANGLE_SYMBOLS
#endif

#if defined(DEMANGLE_SYMBOLS)
#include <cxxabi.h>
#endif

#if BUILDFLAG(IS_APPLE)
#include <AvailabilityMacros.h>
#endif

#if BUILDFLAG(IS_LINUX) || BUILDFLAG(IS_CHROMEOS)
#include <sys/prctl.h>

#include "base/debug/proc_maps_linux.h"
#endif

#include "base/cfi_buildflags.h"
#include "base/debug/debugger.h"
#include "base/debug/debugging_buildflags.h"
#include "base/debug/stack_trace.h"
#include "base/files/scoped_file.h"
#include "base/logging.h"
#include "base/memory/free_deleter.h"
#include "base/memory/singleton.h"
#include "base/numerics/safe_conversions.h"
#include "base/posix/eintr_wrapper.h"
#include "base/strings/string_number_conversions.h"
#include "base/strings/string_util.h"
#include "build/build_config.h"

#if defined(USE_SYMBOLIZE)
#include "base/third_party/symbolize/symbolize.h"  // nogncheck

#if BUILDFLAG(ENABLE_STACK_TRACE_LINE_NUMBERS)
#include "base/debug/dwarf_line_no.h"  // nogncheck
#endif

#endif

namespace base::debug {

namespace {

volatile sig_atomic_t in_signal_handler = 0;

#if !BUILDFLAG(IS_NACL)
bool (*try_handle_signal)(int, siginfo_t*, void*) = nullptr;
#endif

#if defined(DEMANGLE_SYMBOLS)
// The prefix used for mangled symbols, per the Itanium C++ ABI:
// http://www.codesourcery.com/cxx-abi/abi.html#mangling
const char kMangledSymbolPrefix[] = "_Z";

// Characters that can be used for symbols, generated by Ruby:
// (('a'..'z').to_a+('A'..'Z').to_a+('0'..'9').to_a + ['_']).join
const char kSymbolCharacters[] =
    "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789_";

// Demangles C++ symbols in the given text. Example:
//
// "out/Debug/base_unittests(_ZN10StackTraceC1Ev+0x20) [0x817778c]"
// =>
// "out/Debug/base_unittests(StackTrace::StackTrace()+0x20) [0x817778c]"
void DemangleSymbols(std::string* text) {
  // Note: code in this function is NOT async-signal safe (std::string uses
  // malloc internally).

  std::string::size_type search_from = 0;
  while (search_from < text->size()) {
    // Look for the start of a mangled symbol, from search_from.
    std::string::size_type mangled_start =
        text->find(kMangledSymbolPrefix, search_from);
    if (mangled_start == std::string::npos) {
      break;  // Mangled symbol not found.
    }

    // Look for the end of the mangled symbol.
    std::string::size_type mangled_end =
        text->find_first_not_of(kSymbolCharacters, mangled_start);
    if (mangled_end == std::string::npos) {
      mangled_end = text->size();
    }
    std::string mangled_symbol =
        text->substr(mangled_start, mangled_end - mangled_start);

    // Try to demangle the mangled symbol candidate.
    int status = 0;
    std::unique_ptr<char, base::FreeDeleter> demangled_symbol(
        abi::__cxa_demangle(mangled_symbol.c_str(), nullptr, 0, &status));
    if (status == 0) {  // Demangling is successful.
      // Remove the mangled symbol.
      text->erase(mangled_start, mangled_end - mangled_start);
      // Insert the demangled symbol.
      text->insert(mangled_start, demangled_symbol.get());
      // Next time, we'll start right after the demangled symbol we inserted.
      search_from = mangled_start + strlen(demangled_symbol.get());
    } else {
      // Failed to demangle.  Retry after the "_Z" we just found.
      search_from = mangled_start + 2;
    }
  }
}
#endif  // defined(DEMANGLE_SYMBOLS)

class BacktraceOutputHandler {
 public:
  virtual void HandleOutput(const char* output) = 0;

 protected:
  virtual ~BacktraceOutputHandler() = default;
};

#if defined(HAVE_BACKTRACE)
void OutputPointer(const void* pointer, BacktraceOutputHandler* handler) {
  // This should be more than enough to store a 64-bit number in hex:
  // 16 hex digits + 1 for null-terminator.
  char buf[17] = { '\0' };
  handler->HandleOutput("0x");
  internal::itoa_r(reinterpret_cast<intptr_t>(pointer), 16, 12, buf);
  handler->HandleOutput(buf);
}

#if defined(HAVE_DLADDR) || defined(USE_SYMBOLIZE)
void OutputValue(size_t value, BacktraceOutputHandler* handler) {
  // Max unsigned 64-bit number in decimal has 20 digits (18446744073709551615).
  // Hence, 30 digits should be more than enough to represent it in decimal
  // (including the null-terminator).
  char buf[30] = { '\0' };
  internal::itoa_r(static_cast<intptr_t>(value), 10, 1, buf);
  handler->HandleOutput(buf);
}
#endif  // defined(HAVE_DLADDR) || defined(USE_SYMBOLIZE)

#if defined(USE_SYMBOLIZE)
void OutputFrameId(size_t frame_id, BacktraceOutputHandler* handler) {
  handler->HandleOutput("#");
  OutputValue(frame_id, handler);
}
#endif  // defined(USE_SYMBOLIZE)

void ProcessBacktrace(span<const void* const> traces,
                      cstring_view prefix_string,
                      BacktraceOutputHandler* handler) {
  // NOTE: This code MUST be async-signal safe (it's used by in-process
  // stack dumping signal handler). NO malloc or stdio is allowed here.

  // Don't exceed kMaxTraces or GetDwarfCompileUnitOffsets can go OOB.
  traces = traces.first(std::min(traces.size(), StackTrace::kMaxTraces));

#if defined(USE_SYMBOLIZE)
#if BUILDFLAG(ENABLE_STACK_TRACE_LINE_NUMBERS)
  std::array<uint64_t, StackTrace::kMaxTraces> cu_offsets = {};
  GetDwarfCompileUnitOffsets(traces.data(), cu_offsets.data(), traces.size());
#endif

  for (size_t i = 0; i < traces.size(); ++i) {
    if (!prefix_string.empty())
      handler->HandleOutput(prefix_string.c_str());

    OutputFrameId(i, handler);
    handler->HandleOutput(" ");
    OutputPointer(traces[i], handler);
    handler->HandleOutput(" ");

    std::array<char, 1024> buf = {};

    // Subtract by one as return address of function may be in the next function
    // when a function is annotated as noreturn.
    //
    // SAFETY: The pointer here is not dereferenced, it is a program counter and
    // it is used to look up an object file/function. It is treated as a
    // `uintptr_t` inside Symbolize().
    const void* address =
        UNSAFE_BUFFERS(static_cast<const char*>(traces[i]) - 1);
    if (google::Symbolize(const_cast<void*>(address), buf.data(), buf.size())) {
      handler->HandleOutput(buf.data());
#if BUILDFLAG(ENABLE_STACK_TRACE_LINE_NUMBERS)
      // Only output the source line number if the offset was found. Otherwise,
      // it takes far too long in debug mode when there are lots of symbols.
      if (GetDwarfSourceLineNumber(address, cu_offsets[i], buf.data(),
                                   buf.size())) {
        handler->HandleOutput(" [");
        handler->HandleOutput(buf.data());
        handler->HandleOutput("]");
      }
#endif
    } else {
      handler->HandleOutput("<unknown>");
    }

    handler->HandleOutput("\n");
  }
#else
  bool printed = false;

  // Below part is async-signal unsafe (uses malloc), so execute it only
  // when we are not executing the signal handler.
  if (in_signal_handler == 0 &&
      IsValueInRangeForNumericType<int>(traces.size())) {
#if defined(HAVE_DLADDR)
    Dl_info dl_info;
    for (size_t i = 0; i < traces.size(); ++i) {
      if (!prefix_string.empty()) {
        handler->HandleOutput(prefix_string.c_str());
      }

      OutputValue(i, handler);
      handler->HandleOutput(" ");

      const bool dl_info_found = dladdr(traces[i], &dl_info) != 0;
      if (dl_info_found) {
        // SAFETY: dl_info::dli_fname is a NUL-terminated cstring.
        auto dli_fname = UNSAFE_BUFFERS(base::cstring_view(dl_info.dli_fname));
        if (size_t last_sep = dli_fname.rfind('/');
            last_sep != base::cstring_view::npos) {
          dli_fname.remove_prefix(last_sep + 1u);
        }
        handler->HandleOutput(dli_fname.c_str());
      } else {
        handler->HandleOutput("???");
      }
      handler->HandleOutput(" ");
      OutputPointer(traces[i], handler);

      handler->HandleOutput("\n");
    }
    printed = true;
#else   // defined(HAVE_DLADDR)
    auto trace_symbols =
        // SAFETY: backtrace_symbols returns an allocated array of the same size
        // as the input array, which is traces.size().
        UNSAFE_BUFFERS(base::HeapArray<char*, FreeDeleter>::FromOwningPointer(
            backtrace_symbols(const_cast<void* const*>(traces.data()),
                              static_cast<int>(traces.size())),
            traces.size()));
    if (!trace_symbols.empty()) {
      for (char* s : trace_symbols) {
        auto trace_symbol = std::string(s);
        DemangleSymbols(&trace_symbol);
        if (!prefix_string.empty())
          handler->HandleOutput(prefix_string.c_str());
        handler->HandleOutput(trace_symbol.c_str());
        handler->HandleOutput("\n");
      }

      printed = true;
    }
#endif  // defined(HAVE_DLADDR)
  }

  if (!printed) {
    for (const void* const trace : traces) {
      handler->HandleOutput(" [");
      OutputPointer(trace, handler);
      handler->HandleOutput("]\n");
    }
  }
#endif  // defined(USE_SYMBOLIZE)
}
#endif  // defined(HAVE_BACKTRACE)

void PrintToStderr(const char* output) {
  // NOTE: This code MUST be async-signal safe (it's used by in-process
  // stack dumping signal handler). NO malloc or stdio is allowed here.
  std::ignore = HANDLE_EINTR(write(STDERR_FILENO, output, strlen(output)));
}

#if BUILDFLAG(IS_LINUX) || BUILDFLAG(IS_ANDROID) || BUILDFLAG(IS_CHROMEOS)
void AlarmSignalHandler(int signal, siginfo_t* info, void* void_context) {
  // We have seen rare cases on AMD linux where the default signal handler
  // either does not run or a thread (Probably an AMD driver thread) prevents
  // the termination of the gpu process. We catch this case when the alarm fires
  // and then call exit_group() to kill all threads of the process. This has
  // resolved the zombie gpu process issues we have seen on our context lost
  // test.
  // Note that many different calls were tried to kill the process when it is in
  // this state. Only 'exit_group' was found to cause termination and it is
  // speculated that only this works because only this exit kills all threads in
  // the process (not simply the current thread).
  // See: http://crbug.com/1396451.
  PrintToStderr(
      "Warning: Default signal handler failed to terminate process.\n");
  PrintToStderr("Calling exit_group() directly to prevent timeout.\n");
  // See: https://man7.org/linux/man-pages/man2/exit_group.2.html
  syscall(SYS_exit_group, EXIT_FAILURE);
}
#endif  // BUILDFLAG(IS_LINUX) || BUILDFLAG(IS_ANDROID) ||
        // BUILDFLAG(IS_CHROMEOS)

void StackDumpSignalHandler(int signal, siginfo_t* info, void* void_context) {
  // NOTE: This code MUST be async-signal safe.
  // NO malloc or stdio is allowed here.

#if !BUILDFLAG(IS_NACL)
  // Give a registered callback a chance to recover from this signal
  //
  // V8 uses guard regions to guarantee memory safety in WebAssembly. This means
  // some signals might be expected if they originate from Wasm code while
  // accessing the guard region. We give V8 the chance to handle and recover
  // from these signals first.
  if (try_handle_signal != nullptr &&
      try_handle_signal(signal, info, void_context)) {
    // The first chance handler took care of this. The SA_RESETHAND flag
    // replaced this signal handler upon entry, but we want to stay
    // installed. Thus, we reinstall ourselves before returning.
    struct sigaction action;
    memset(&action, 0, sizeof(action));
    action.sa_flags = static_cast<int>(SA_RESETHAND | SA_SIGINFO);
    action.sa_sigaction = &StackDumpSignalHandler;
    sigemptyset(&action.sa_mask);

    sigaction(signal, &action, nullptr);
    return;
  }
#endif

// Do not take the "in signal handler" code path on Mac in a DCHECK-enabled
// build, as this prevents seeing a useful (symbolized) stack trace on a crash
// or DCHECK() failure. While it may not be fully safe to run the stack symbol
// printing code, in practice it's better to provide meaningful stack traces -
// and the risk is low given we're likely crashing already.
#if !BUILDFLAG(IS_APPLE) || !DCHECK_IS_ON()
  // Record the fact that we are in the signal handler now, so that the rest
  // of StackTrace can behave in an async-signal-safe manner.
  in_signal_handler = 1;
#endif

  if (BeingDebugged())
    BreakDebugger();

  PrintToStderr("Received signal ");
  char buf[1024] = { 0 };
  internal::itoa_r(signal, 10, 0, buf);
  PrintToStderr(buf);
  if (signal == SIGBUS) {
    if (info->si_code == BUS_ADRALN)
      PrintToStderr(" BUS_ADRALN ");
    else if (info->si_code == BUS_ADRERR)
      PrintToStderr(" BUS_ADRERR ");
    else if (info->si_code == BUS_OBJERR)
      PrintToStderr(" BUS_OBJERR ");
    else
      PrintToStderr(" <unknown> ");
  } else if (signal == SIGFPE) {
    if (info->si_code == FPE_FLTDIV)
      PrintToStderr(" FPE_FLTDIV ");
    else if (info->si_code == FPE_FLTINV)
      PrintToStderr(" FPE_FLTINV ");
    else if (info->si_code == FPE_FLTOVF)
      PrintToStderr(" FPE_FLTOVF ");
    else if (info->si_code == FPE_FLTRES)
      PrintToStderr(" FPE_FLTRES ");
    else if (info->si_code == FPE_FLTSUB)
      PrintToStderr(" FPE_FLTSUB ");
    else if (info->si_code == FPE_FLTUND)
      PrintToStderr(" FPE_FLTUND ");
    else if (info->si_code == FPE_INTDIV)
      PrintToStderr(" FPE_INTDIV ");
    else if (info->si_code == FPE_INTOVF)
      PrintToStderr(" FPE_INTOVF ");
    else
      PrintToStderr(" <unknown> ");
  } else if (signal == SIGILL) {
    if (info->si_code == ILL_BADSTK)
      PrintToStderr(" ILL_BADSTK ");
    else if (info->si_code == ILL_COPROC)
      PrintToStderr(" ILL_COPROC ");
    else if (info->si_code == ILL_ILLOPN)
      PrintToStderr(" ILL_ILLOPN ");
    else if (info->si_code == ILL_ILLADR)
      PrintToStderr(" ILL_ILLADR ");
    else if (info->si_code == ILL_ILLTRP)
      PrintToStderr(" ILL_ILLTRP ");
    else if (info->si_code == ILL_PRVOPC)
      PrintToStderr(" ILL_PRVOPC ");
    else if (info->si_code == ILL_PRVREG)
      PrintToStderr(" ILL_PRVREG ");
    else
      PrintToStderr(" <unknown> ");
  } else if (signal == SIGSEGV) {
    if (info->si_code == SEGV_MAPERR)
      PrintToStderr(" SEGV_MAPERR ");
    else if (info->si_code == SEGV_ACCERR)
      PrintToStderr(" SEGV_ACCERR ");
#if defined(ARCH_CPU_X86_64) && \
    (BUILDFLAG(IS_LINUX) || BUILDFLAG(IS_ANDROID) || BUILDFLAG(IS_CHROMEOS))
    else if (info->si_code == SI_KERNEL)
      PrintToStderr(" SI_KERNEL");
#endif
    else
      PrintToStderr(" <unknown> ");
  }
  if (signal == SIGBUS || signal == SIGFPE ||
      signal == SIGILL || signal == SIGSEGV) {
    internal::itoa_r(reinterpret_cast<intptr_t>(info->si_addr), 16, 12, buf);
    PrintToStderr(buf);
  }
  PrintToStderr("\n");

#if BUILDFLAG(CFI_ENFORCEMENT_TRAP)
  if (signal == SIGILL && info->si_code == ILL_ILLOPN) {
    PrintToStderr(
        "CFI: Most likely a control flow integrity violation; for more "
        "information see:\n");
    PrintToStderr(
        "https://www.chromium.org/developers/testing/control-flow-integrity\n");
  }
#endif  // BUILDFLAG(CFI_ENFORCEMENT_TRAP)

#if defined(ARCH_CPU_X86_64) && \
    (BUILDFLAG(IS_LINUX) || BUILDFLAG(IS_ANDROID) || BUILDFLAG(IS_CHROMEOS))
  if (signal == SIGSEGV && info->si_code == SI_KERNEL) {
    PrintToStderr(
        " Possibly a General Protection Fault, can be due to a non-canonical "
        "address dereference. See \"Intel 64 and IA-32 Architectures Software "
        "Developer’s Manual\", Volume 1, Section 3.3.7.1.\n");
  }
#endif

  debug::StackTrace().Print();

#if BUILDFLAG(IS_LINUX) || BUILDFLAG(IS_CHROMEOS)
#if ARCH_CPU_X86_FAMILY
  ucontext_t* context = reinterpret_cast<ucontext_t*>(void_context);
  auto gregs = base::span(context->uc_mcontext.gregs);

  struct Register {
    const char* label;
    greg_t value;
  };
  const auto registers = std::to_array<Register>({
#if ARCH_CPU_32_BITS
      {"  gs: ", gregs[REG_GS]},     {"  fs: ", gregs[REG_FS]},
      {"  es: ", gregs[REG_ES]},     {"  ds: ", gregs[REG_DS]},
      {" edi: ", gregs[REG_EDI]},    {" esi: ", gregs[REG_ESI]},
      {" ebp: ", gregs[REG_EBP]},    {" esp: ", gregs[REG_ESP]},
      {" ebx: ", gregs[REG_EBX]},    {" edx: ", gregs[REG_EDX]},
      {" ecx: ", gregs[REG_ECX]},    {" eax: ", gregs[REG_EAX]},
      {" trp: ", gregs[REG_TRAPNO]}, {" err: ", gregs[REG_ERR]},
      {"  ip: ", gregs[REG_EIP]},    {"  cs: ", gregs[REG_CS]},
      {" efl: ", gregs[REG_EFL]},    {" usp: ", gregs[REG_UESP]},
      {"  ss: ", gregs[REG_SS]},
#elif ARCH_CPU_64_BITS
      {"  r8: ", gregs[REG_R8]},     {"  r9: ", gregs[REG_R9]},
      {" r10: ", gregs[REG_R10]},    {" r11: ", gregs[REG_R11]},
      {" r12: ", gregs[REG_R12]},    {" r13: ", gregs[REG_R13]},
      {" r14: ", gregs[REG_R14]},    {" r15: ", gregs[REG_R15]},
      {"  di: ", gregs[REG_RDI]},    {"  si: ", gregs[REG_RSI]},
      {"  bp: ", gregs[REG_RBP]},    {"  bx: ", gregs[REG_RBX]},
      {"  dx: ", gregs[REG_RDX]},    {"  ax: ", gregs[REG_RAX]},
      {"  cx: ", gregs[REG_RCX]},    {"  sp: ", gregs[REG_RSP]},
      {"  ip: ", gregs[REG_RIP]},    {" efl: ", gregs[REG_EFL]},
      {" cgf: ", gregs[REG_CSGSFS]}, {" erf: ", gregs[REG_ERR]},
      {" trp: ", gregs[REG_TRAPNO]}, {" msk: ", gregs[REG_OLDMASK]},
      {" cr2: ", gregs[REG_CR2]},
#endif  // ARCH_CPU_32_BITS
  });

#if ARCH_CPU_32_BITS
  const int kRegisterPadding = 8;
#elif ARCH_CPU_64_BITS
  const int kRegisterPadding = 16;
#endif

  for (size_t i = 0; i < std::size(registers); i++) {
    PrintToStderr(registers[i].label);
    internal::itoa_r(registers[i].value, 16, kRegisterPadding, buf);
    PrintToStderr(buf);

    if ((i + 1) % 4 == 0)
      PrintToStderr("\n");
  }
  PrintToStderr("\n");
#endif  // ARCH_CPU_X86_FAMILY
#endif  // BUILDFLAG(IS_LINUX) || BUILDFLAG(IS_CHROMEOS)

  PrintToStderr("[end of stack trace]\n");

  if (::signal(signal, SIG_DFL) == SIG_ERR) {
    _exit(EXIT_FAILURE);
  }

#if BUILDFLAG(IS_LINUX) || BUILDFLAG(IS_ANDROID) || BUILDFLAG(IS_CHROMEOS)
  // Set an alarm to trigger in case the default handler does not terminate
  // the process. See 'AlarmSignalHandler' for more details.
  struct sigaction action;
  memset(&action, 0, sizeof(action));
  action.sa_flags = static_cast<int>(SA_RESETHAND);
  action.sa_sigaction = &AlarmSignalHandler;
  sigemptyset(&action.sa_mask);
  sigaction(SIGALRM, &action, nullptr);
  // 'alarm' function is signal handler safe.
  // https://man7.org/linux/man-pages/man7/signal-safety.7.html
  // This delay is set to be long enough for the real signal handler to fire but
  // shorter than chrome's process watchdog timer.
  constexpr unsigned int kAlarmSignalDelaySeconds = 5;
  alarm(kAlarmSignalDelaySeconds);

  // The following is mostly from
  // third_party/crashpad/crashpad/util/posix/signals.cc as re-raising signals
  // is complicated.

  // If we can raise a signal with siginfo on this platform, do so. This ensures
  // that we preserve the siginfo information for asynchronous signals (i.e.
  // signals that do not re-raise autonomously), such as signals delivered via
  // kill() and asynchronous hardware faults such as SEGV_MTEAERR, which would
  // otherwise be lost when re-raising the signal via raise().
  long retval = syscall(SYS_rt_tgsigqueueinfo, getpid(), syscall(SYS_gettid),
                        info->si_signo, info);
  if (retval == 0) {
    return;
  }

  // Kernels without commit 66dd34ad31e5 ("signal: allow to send any siginfo to
  // itself"), which was first released in kernel version 3.9, did not permit a
  // process to send arbitrary signals to itself, and will reject the
  // rt_tgsigqueueinfo syscall with EPERM. If that happens, follow the non-Linux
  // code path. Any other errno is unexpected and will cause us to exit.
  if (errno != EPERM) {
    _exit(EXIT_FAILURE);
  }
#endif  // BUILDFLAG(IS_LINUX) || BUILDFLAG(IS_ANDROID) ||
        // BUILDFLAG(IS_CHROMEOS)

  // Explicitly re-raise the signal even if it might have re-raised itself on
  // return. Because signal handlers normally execute with their signal blocked,
  // this raise() cannot immediately deliver the signal. Delivery is deferred
  // until the signal handler returns and the signal becomes unblocked. The
  // re-raised signal will appear with the same context as where it was
  // initially triggered.
  if (raise(signal) != 0) {
    _exit(EXIT_FAILURE);
  }
}

class PrintBacktraceOutputHandler : public BacktraceOutputHandler {
 public:
  PrintBacktraceOutputHandler() = default;

  PrintBacktraceOutputHandler(const PrintBacktraceOutputHandler&) = delete;
  PrintBacktraceOutputHandler& operator=(const PrintBacktraceOutputHandler&) =
      delete;

  void HandleOutput(const char* output) override {
    // NOTE: This code MUST be async-signal safe (it's used by in-process
    // stack dumping signal handler). NO malloc or stdio is allowed here.
    PrintToStderr(output);
  }
};

class StreamBacktraceOutputHandler : public BacktraceOutputHandler {
 public:
  explicit StreamBacktraceOutputHandler(std::ostream* os) : os_(os) {
  }

  StreamBacktraceOutputHandler(const StreamBacktraceOutputHandler&) = delete;
  StreamBacktraceOutputHandler& operator=(const StreamBacktraceOutputHandler&) =
      delete;

  void HandleOutput(const char* output) override { (*os_) << output; }

 private:
  raw_ptr<std::ostream> os_;
};

void WarmUpBacktrace() {
  // Warm up stack trace infrastructure. It turns out that on the first
  // call glibc initializes some internal data structures using pthread_once,
  // and even backtrace() can call malloc(), leading to hangs.
  //
  // Example stack trace snippet (with tcmalloc):
  //
  // #8  0x0000000000a173b5 in tc_malloc
  //             at ./third_party/tcmalloc/chromium/src/debugallocation.cc:1161
  // #9  0x00007ffff7de7900 in _dl_map_object_deps at dl-deps.c:517
  // #10 0x00007ffff7ded8a9 in dl_open_worker at dl-open.c:262
  // #11 0x00007ffff7de9176 in _dl_catch_error at dl-error.c:178
  // #12 0x00007ffff7ded31a in _dl_open (file=0x7ffff625e298 "libgcc_s.so.1")
  //             at dl-open.c:639
  // #13 0x00007ffff6215602 in do_dlopen at dl-libc.c:89
  // #14 0x00007ffff7de9176 in _dl_catch_error at dl-error.c:178
  // #15 0x00007ffff62156c4 in dlerror_run at dl-libc.c:48
  // #16 __GI___libc_dlopen_mode at dl-libc.c:165
  // #17 0x00007ffff61ef8f5 in init
  //             at ../sysdeps/x86_64/../ia64/backtrace.c:53
  // #18 0x00007ffff6aad400 in pthread_once
  //             at ../nptl/sysdeps/unix/sysv/linux/x86_64/pthread_once.S:104
  // #19 0x00007ffff61efa14 in __GI___backtrace
  //             at ../sysdeps/x86_64/../ia64/backtrace.c:104
  // #20 0x0000000000752a54 in base::debug::StackTrace::StackTrace
  //             at base/debug/stack_trace_posix.cc:175
  // #21 0x00000000007a4ae5 in
  //             base::(anonymous namespace)::StackDumpSignalHandler
  //             at base/process_util_posix.cc:172
  // #22 <signal handler called>
  StackTrace stack_trace;
}

#if defined(USE_SYMBOLIZE)

// class SandboxSymbolizeHelper.
//
// The purpose of this class is to prepare and install a "file open" callback
// needed by the stack trace symbolization code
// (base/third_party/symbolize/symbolize.h) so that it can function properly
// in a sandboxed process.  The caveat is that this class must be instantiated
// before the sandboxing is enabled so that it can get the chance to open all
// the object files that are loaded in the virtual address space of the current
// process.
class SandboxSymbolizeHelper {
 public:
  // Returns the singleton instance.
  static SandboxSymbolizeHelper* GetInstance() {
    return Singleton<SandboxSymbolizeHelper,
                     LeakySingletonTraits<SandboxSymbolizeHelper>>::get();
  }

  SandboxSymbolizeHelper(const SandboxSymbolizeHelper&) = delete;
  SandboxSymbolizeHelper& operator=(const SandboxSymbolizeHelper&) = delete;

 private:
  friend struct DefaultSingletonTraits<SandboxSymbolizeHelper>;

  SandboxSymbolizeHelper()
      : is_initialized_(false) {
    Init();
  }

  ~SandboxSymbolizeHelper() {
    UnregisterCallback();
    CloseObjectFiles();
  }

  // Returns a O_RDONLY file descriptor for |file_path| if it was opened
  // successfully during the initialization.  The file is repositioned at
  // offset 0.
  // IMPORTANT: This function must be async-signal-safe because it can be
  // called from a signal handler (symbolizing stack frames for a crash).
  int GetFileDescriptor(const char* file_path) {
    int fd = -1;

#if !defined(OFFICIAL_BUILD) || !defined(NO_UNWIND_TABLES)
    if (file_path) {
      // The assumption here is that iterating over std::map<std::string,
      // base::ScopedFD> does not allocate dynamic memory, hence it is
      // async-signal-safe.
      for (const auto& filepath_fd : modules_) {
        if (strcmp(filepath_fd.first.c_str(), file_path) == 0) {
          // POSIX.1-2004 requires an implementation to guarantee that dup()
          // is async-signal-safe.
          fd = HANDLE_EINTR(dup(filepath_fd.second.get()));
          break;
        }
      }
      // POSIX.1-2004 requires an implementation to guarantee that lseek()
      // is async-signal-safe.
      if (fd >= 0 && lseek(fd, 0, SEEK_SET) < 0) {
        // Failed to seek.
        fd = -1;
      }
    }
#endif  // !defined(OFFICIAL_BUILD) || !defined(NO_UNWIND_TABLES)

    return fd;
  }

  // Searches for the object file (from /proc/self/maps) that contains
  // the specified pc.  If found, sets |start_address| to the start address
  // of where this object file is mapped in memory, sets the module base
  // address into |base_address|, copies the object file name into
  // |out_file_name|, and attempts to open the object file.  If the object
  // file is opened successfully, returns the file descriptor.  Otherwise,
  // returns -1.
  // IMPORTANT: This function must be async-signal-safe because it can be
  // called from a signal handler (symbolizing stack frames for a crash).
  static int OpenObjectFileContainingPc(uint64_t pc,
                                        uint64_t& start_address,
                                        uint64_t& base_address,
                                        char* file_path_ptr,
                                        size_t file_path_size) {
    auto file_path =
        // SAFETY: This function is given as a function pointer to
        // google::InstallSymbolizeOpenObjectFileCallback. It provides
        // `file_path_size` as the size of the string in `file_path_ptr`,
        // including a NUL terminator. Via code inspection we can see that
        // `file_path_ptr` can be null, in which case `file_path_size` is zero.
        UNSAFE_BUFFERS(base::span(file_path_ptr, file_path_size));

    // This method can only be called after the singleton is instantiated.
    // This is ensured by the following facts:
    // * This is the only static method in this class, it is private, and
    //   the class has no friends (except for the DefaultSingletonTraits).
    //   The compiler guarantees that it can only be called after the
    //   singleton is instantiated.
    // * This method is used as a callback for the stack tracing code and
    //   the callback registration is done in the constructor, so logically
    //   it cannot be called before the singleton is created.
    SandboxSymbolizeHelper* instance = GetInstance();

    // Cannot use STL iterators here, since debug iterators use locks.
    // NOLINTNEXTLINE(modernize-loop-convert)
    for (size_t i = 0; i < instance->regions_.size(); ++i) {
      const MappedMemoryRegion& region = instance->regions_[i];
      // We overwrite the file_path with the if `pc` is within a
      // MemoryMappedRegion.
      if (region.start <= pc && pc < region.end) {
        start_address = region.start;
        base_address = region.base;
        if (!file_path.empty()) {
          strlcpy(file_path, region.path);
        }
        return instance->GetFileDescriptor(region.path.c_str());
      }
    }
    return -1;
  }

  // This class is copied from
  // third_party/crashpad/crashpad/util/linux/scoped_pr_set_dumpable.h.
  // It aims at ensuring the process is dumpable before opening /proc/self/mem.
  // If the process is already dumpable, this class doesn't do anything.
  class ScopedPrSetDumpable {
   public:
    // Uses `PR_SET_DUMPABLE` to make the current process dumpable.
    //
    // Restores the dumpable flag to its original value on destruction. If the
    // original value couldn't be determined, the destructor attempts to
    // restore the flag to 0 (non-dumpable).
    explicit ScopedPrSetDumpable() {
      int result = prctl(PR_GET_DUMPABLE, 0, 0, 0, 0);
      was_dumpable_ = result > 0;

      if (!was_dumpable_) {
        std::ignore = prctl(PR_SET_DUMPABLE, 1, 0, 0, 0);
      }
    }

    ScopedPrSetDumpable(const ScopedPrSetDumpable&) = delete;
    ScopedPrSetDumpable& operator=(const ScopedPrSetDumpable&) = delete;

    ~ScopedPrSetDumpable() {
      if (!was_dumpable_) {
        std::ignore = prctl(PR_SET_DUMPABLE, 0, 0, 0, 0);
      }
    }

   private:
    bool was_dumpable_;
  };

  // Set the base address for each memory region by reading ELF headers in
  // process memory.
  void SetBaseAddressesForMemoryRegions() {
    base::ScopedFD mem_fd;
    {
      ScopedPrSetDumpable s;
      mem_fd = base::ScopedFD(
          HANDLE_EINTR(open("/proc/self/mem", O_RDONLY | O_CLOEXEC)));
      if (!mem_fd.is_valid()) {
        return;
      }
    }

    auto safe_memcpy = [&mem_fd](void* dst, uintptr_t src, size_t size) {
      return HANDLE_EINTR(pread(mem_fd.get(), dst, size,
                                static_cast<off_t>(src))) == ssize_t(size);
    };

    uintptr_t cur_base = 0;
    for (auto& r : regions_) {
      ElfW(Ehdr) ehdr;
      static_assert(SELFMAG <= sizeof(ElfW(Ehdr)), "SELFMAG too large");
      if ((r.permissions & MappedMemoryRegion::READ) &&
          safe_memcpy(&ehdr, r.start, sizeof(ElfW(Ehdr))) &&
          memcmp(ehdr.e_ident, ELFMAG, SELFMAG) == 0) {
        switch (ehdr.e_type) {
          case ET_EXEC:
            cur_base = 0;
            break;
          case ET_DYN:
            // Find the segment containing file offset 0. This will correspond
            // to the ELF header that we just read. Normally this will have
            // virtual address 0, but this is not guaranteed. We must subtract
            // the virtual address from the address where the ELF header was
            // mapped to get the base address.
            //
            // If we fail to find a segment for file offset 0, use the address
            // of the ELF header as the base address.
            cur_base = r.start;
            for (unsigned i = 0; i != ehdr.e_phnum; ++i) {
              ElfW(Phdr) phdr;
              if (safe_memcpy(&phdr, r.start + ehdr.e_phoff + i * sizeof(phdr),
                              sizeof(phdr)) &&
                  phdr.p_type == PT_LOAD && phdr.p_offset == 0) {
                cur_base = r.start - phdr.p_vaddr;
                break;
              }
            }
            break;
          default:
            // ET_REL or ET_CORE. These aren't directly executable, so they
            // don't affect the base address.
            break;
        }
      }

      r.base = cur_base;
    }
  }

  // Parses /proc/self/maps in order to compile a list of all object file names
  // for the modules that are loaded in the current process.
  // Returns true on success.
  bool CacheMemoryRegions() {
    // Reads /proc/self/maps.
    std::string contents;
    if (!ReadProcMaps(&contents)) {
      LOG(ERROR) << "Failed to read /proc/self/maps";
      return false;
    }

    // Parses /proc/self/maps.
    if (!ParseProcMaps(contents, ®ions_)) {
      LOG(ERROR) << "Failed to parse the contents of /proc/self/maps";
      return false;
    }

    SetBaseAddressesForMemoryRegions();

    is_initialized_ = true;
    return true;
  }

  // Opens all object files and caches their file descriptors.
  void OpenSymbolFiles() {
    // Pre-opening and caching the file descriptors of all loaded modules is
    // not safe for production builds.  Hence it is only done in non-official
    // builds.  For more details, take a look at: http://crbug.com/341966.
#if !defined(OFFICIAL_BUILD) || !defined(NO_UNWIND_TABLES)
    // Open the object files for all read-only executable regions and cache
    // their file descriptors.
    std::vector<MappedMemoryRegion>::const_iterator it;
    for (it = regions_.begin(); it != regions_.end(); ++it) {
      const MappedMemoryRegion& region = *it;
      // Only interesed in read-only executable regions.
      if ((region.permissions & MappedMemoryRegion::READ) ==
              MappedMemoryRegion::READ &&
          (region.permissions & MappedMemoryRegion::WRITE) == 0 &&
          (region.permissions & MappedMemoryRegion::EXECUTE) ==
              MappedMemoryRegion::EXECUTE) {
        if (region.path.empty()) {
          // Skip regions with empty file names.
          continue;
        }
        if (region.path[0] == '[') {
          // Skip pseudo-paths, like [stack], [vdso], [heap], etc ...
          continue;
        }
        if (base::EndsWith(region.path, " (deleted)",
                           base::CompareCase::SENSITIVE)) {
          // Skip deleted files.
          continue;
        }
        // Avoid duplicates.
        if (modules_.find(region.path) == modules_.end()) {
          int fd = open(region.path.c_str(), O_RDONLY | O_CLOEXEC);
          if (fd >= 0) {
            modules_.emplace(region.path, base::ScopedFD(fd));
          } else {
            PLOG(WARNING) << "Failed to open file: " << region.path;
          }
        }
      }
    }
#endif  // !defined(OFFICIAL_BUILD) || !defined(NO_UNWIND_TABLES)
  }

  // Initializes and installs the symbolization callback.
  void Init() {
    if (CacheMemoryRegions()) {
      OpenSymbolFiles();
      google::InstallSymbolizeOpenObjectFileCallback(
          &OpenObjectFileContainingPc);
    }
  }

  // Unregister symbolization callback.
  void UnregisterCallback() {
    if (is_initialized_) {
      google::InstallSymbolizeOpenObjectFileCallback(nullptr);
      is_initialized_ = false;
    }
  }

  // Closes all file descriptors owned by this instance.
  void CloseObjectFiles() {
#if !defined(OFFICIAL_BUILD) || !defined(NO_UNWIND_TABLES)
    modules_.clear();
#endif  // !defined(OFFICIAL_BUILD) || !defined(NO_UNWIND_TABLES)
  }

  // Set to true upon successful initialization.
  bool is_initialized_;

#if !defined(OFFICIAL_BUILD) || !defined(NO_UNWIND_TABLES)
  // Mapping from file name to file descriptor.  Includes file descriptors
  // for all successfully opened object files and the file descriptor for
  // /proc/self/maps.  This code is not safe for production builds.
  std::map<std::string, base::ScopedFD> modules_;
#endif  // !defined(OFFICIAL_BUILD) || !defined(NO_UNWIND_TABLES)

  // Cache for the process memory regions.  Produced by parsing the contents
  // of /proc/self/maps cache.
  std::vector<MappedMemoryRegion> regions_;
};
#endif  // USE_SYMBOLIZE

}  // namespace

bool EnableInProcessStackDumping() {
#if defined(USE_SYMBOLIZE)
  SandboxSymbolizeHelper::GetInstance();
#endif  // USE_SYMBOLIZE

  // When running in an application, our code typically expects SIGPIPE
  // to be ignored.  Therefore, when testing that same code, it should run
  // with SIGPIPE ignored as well.
  struct sigaction sigpipe_action;
  memset(&sigpipe_action, 0, sizeof(sigpipe_action));
  sigpipe_action.sa_handler = SIG_IGN;
  sigemptyset(&sigpipe_action.sa_mask);
  bool success = (sigaction(SIGPIPE, &sigpipe_action, nullptr) == 0);

  // Avoid hangs during backtrace initialization, see above.
  WarmUpBacktrace();

  struct sigaction action;
  memset(&action, 0, sizeof(action));
  action.sa_flags = static_cast<int>(SA_RESETHAND | SA_SIGINFO);
  action.sa_sigaction = &StackDumpSignalHandler;
  sigemptyset(&action.sa_mask);

  success &= (sigaction(SIGILL, &action, nullptr) == 0);
  success &= (sigaction(SIGABRT, &action, nullptr) == 0);
  success &= (sigaction(SIGFPE, &action, nullptr) == 0);
  success &= (sigaction(SIGBUS, &action, nullptr) == 0);
  success &= (sigaction(SIGSEGV, &action, nullptr) == 0);
// On Linux, SIGSYS is reserved by the kernel for seccomp-bpf sandboxing.
#if !BUILDFLAG(IS_LINUX) && !BUILDFLAG(IS_CHROMEOS)
  success &= (sigaction(SIGSYS, &action, nullptr) == 0);
#endif  // !BUILDFLAG(IS_LINUX) && !BUILDFLAG(IS_CHROMEOS)

  return success;
}

#if !BUILDFLAG(IS_NACL)
bool SetStackDumpFirstChanceCallback(bool (*handler)(int, siginfo_t*, void*)) {
  DCHECK(try_handle_signal == nullptr || handler == nullptr);
  try_handle_signal = handler;

#if defined(ADDRESS_SANITIZER) || defined(MEMORY_SANITIZER) || \
    defined(THREAD_SANITIZER) || defined(LEAK_SANITIZER) ||    \
    defined(UNDEFINED_SANITIZER)
  struct sigaction installed_handler;
  CHECK_EQ(sigaction(SIGSEGV, NULL, &installed_handler), 0);
  // If the installed handler does not point to StackDumpSignalHandler, then
  // allow_user_segv_handler is 0.
  if (installed_handler.sa_sigaction != StackDumpSignalHandler) {
    LOG(WARNING)
        << "WARNING: sanitizers are preventing signal handler installation. "
        << "WebAssembly trap handlers are disabled.\n";
    return false;
  }
#endif
  return true;
}
#endif

size_t CollectStackTrace(span<const void*> trace) {
  // NOTE: This code MUST be async-signal safe (it's used by in-process
  // stack dumping signal handler). NO malloc or stdio is allowed here.

#if defined(NO_UNWIND_TABLES) && BUILDFLAG(CAN_UNWIND_WITH_FRAME_POINTERS)
  // If we do not have unwind tables, then try tracing using frame pointers.
  return base::debug::TraceStackFramePointers(trace, 0);
#elif defined(HAVE_BACKTRACE)
  // Though the backtrace API man page does not list any possible negative
  // return values, we take no chance.
  return base::saturated_cast<size_t>(
      backtrace(const_cast<void**>(trace.data()),
                base::saturated_cast<int>(trace.size())));
#else
  return 0;
#endif
}

// static
void StackTrace::PrintMessageWithPrefix(cstring_view prefix_string,
                                        cstring_view message) {
  // NOTE: This code MUST be async-signal safe (it's used by in-process
  // stack dumping signal handler). NO malloc or stdio is allowed here.
  if (!prefix_string.empty()) {
    PrintToStderr(prefix_string.c_str());
  }
  PrintToStderr(message.c_str());
}

void StackTrace::PrintWithPrefixImpl(cstring_view prefix_string) const {
// NOTE: This code MUST be async-signal safe (it's used by in-process
// stack dumping signal handler). NO malloc or stdio is allowed here.
#if defined(HAVE_BACKTRACE)
  PrintBacktraceOutputHandler handler;
  ProcessBacktrace(addresses(), prefix_string, &handler);
#endif
}

#if defined(HAVE_BACKTRACE)
void StackTrace::OutputToStreamWithPrefixImpl(
    std::ostream* os,
    cstring_view prefix_string) const {
  StreamBacktraceOutputHandler handler(os);
  ProcessBacktrace(addresses(), prefix_string, &handler);
}
#endif

namespace internal {

// NOTE: code from sandbox/linux/seccomp-bpf/demo.cc.
// Modified to use bounds-checked containers.
void itoa_r(intptr_t i, int base, size_t padding, base::span<char> buf) {
  // Make sure we can write at least one NUL byte.
  if (buf.empty()) {
    return;
  }

  if (base < 2 || base > 16) {
    buf[0u] = '\000';
    return;
  }

  auto writer = base::SpanWriter(buf);
  size_t start = 0u;

  uintptr_t j = static_cast<uintptr_t>(i);

  // Handle negative numbers (only for base 10).
  if (i < 0 && base == 10) {
    // This does "j = -i" while avoiding integer overflow.
    j = static_cast<uintptr_t>(-(i + 1)) + 1;

    // Make sure we can write the '-' character.
    if (!writer.Write('-')) {
      buf[0u] = '\000';
      return;
    }
    start += 1u;  // The number starts after the sign.
  }

  // Loop until we have converted the entire number. Output at least one
  // character (i.e. '0').
  constexpr std::string_view digits = "0123456789abcdef";
  do {
    // Output the next digit.
    if (!writer.Write(digits[j % static_cast<uintptr_t>(base)])) {
      buf[0] = '\000';
      return;
    }
    j /= static_cast<uintptr_t>(base);

    if (padding > 0)
      padding--;
  } while (j > 0 || padding > 0);

  // Terminate the output with a NUL character.
  if (!writer.Write('\000')) {
    buf[0] = '\000';
    return;
  }

  // Conversion to ASCII actually resulted in the digits being in reverse order.
  // We can't easily generate them in forward order, as we can't tell the number
  // of characters needed until we are done converting. So, now, we reverse the
  // string (except for the possible "-" sign and the NUL terminator).
  std::ranges::reverse(buf.first(writer.num_written() - 1u).subspan(start));
}

}  // namespace internal

}  // namespace base::debug