#include "base/debug/stack_trace.h"
#include <string.h>
#include <algorithm>
#include <optional>
#include <sstream>
#include <utility>
#include "base/byte_count.h"
#include "base/check_op.h"
#include "base/debug/debugging_buildflags.h"
#include "base/features.h"
#include "base/numerics/clamped_math.h"
#include "build/build_config.h"
#include "build/config/compiler/compiler_buildflags.h"
#if BUILDFLAG(CAN_UNWIND_WITH_FRAME_POINTERS)
#include <optional>
#if BUILDFLAG(IS_LINUX) || BUILDFLAG(IS_CHROMEOS) || BUILDFLAG(IS_ANDROID) || BUILDFLAG(IS_OHOS)
#include <pthread.h>
#include "base/process/process_handle.h"
#include "base/threading/platform_thread.h"
#endif
#if BUILDFLAG(IS_APPLE)
#include <pthread.h>
#endif
#if (BUILDFLAG(IS_LINUX) || BUILDFLAG(IS_CHROMEOS)) && defined(__GLIBC__)
extern "C" void* __libc_stack_end;
#endif
#endif
namespace base::debug {
namespace {
#if BUILDFLAG(CAN_UNWIND_WITH_FRAME_POINTERS)
#if defined(__arm__) && defined(__GNUC__) && !defined(__clang__)
constexpr size_t kStackFrameAdjustment = sizeof(uintptr_t);
#else
constexpr size_t kStackFrameAdjustment = 0;
#endif
constinit std::optional<size_t> g_stack_scan_max_fp_to_stack_end_gap_bytes{
std::nullopt};
static uintptr_t StripPointerAuthenticationBits(uintptr_t ptr) {
#if defined(ARCH_CPU_ARM64)
register uintptr_t x30 __asm("x30") = ptr;
asm("xpaclri" : "+r"(x30));
return x30;
#else
return ptr;
#endif
}
uintptr_t GetNextStackFrame(uintptr_t fp) {
const uintptr_t* fp_addr = reinterpret_cast<const uintptr_t*>(fp);
UNSAFE_BUFFERS({
MSAN_UNPOISON(&fp_addr[0], sizeof(uintptr_t));
return fp_addr[0] - kStackFrameAdjustment;
})
}
uintptr_t GetStackFramePC(uintptr_t fp) {
const uintptr_t* fp_addr = reinterpret_cast<const uintptr_t*>(fp);
UNSAFE_BUFFERS({
MSAN_UNPOISON(&fp_addr[1], sizeof(uintptr_t));
return StripPointerAuthenticationBits(fp_addr[1]);
})
}
bool IsStackFrameValid(uintptr_t fp, uintptr_t prev_fp, uintptr_t stack_end) {
if (fp <= prev_fp) {
return false;
}
if (fp - prev_fp > 100000) {
return false;
}
if (fp & (sizeof(uintptr_t) - 1)) {
return false;
}
if (stack_end) {
if (fp > stack_end - 2 * sizeof(uintptr_t)) {
return false;
}
if (GetStackFramePC(fp) < 32768) {
return false;
}
}
return true;
}
uintptr_t ScanStackForNextFrame(uintptr_t fp, uintptr_t stack_end) {
constexpr size_t kMaxStackScanArea = 8192;
if (!stack_end) {
return 0;
}
if (g_stack_scan_max_fp_to_stack_end_gap_bytes.has_value()) {
if (stack_end < fp ||
(stack_end - fp) > *g_stack_scan_max_fp_to_stack_end_gap_bytes) {
return 0;
}
}
fp += sizeof(uintptr_t);
uintptr_t last_fp_to_scan =
(base::ClampedNumeric<uintptr_t>(fp) + kMaxStackScanArea).Min(stack_end) -
sizeof(uintptr_t);
for (; fp <= last_fp_to_scan; fp += sizeof(uintptr_t)) {
uintptr_t next_fp = GetNextStackFrame(fp);
if (IsStackFrameValid(next_fp, fp, stack_end)) {
uintptr_t next2_fp = GetNextStackFrame(next_fp);
if (IsStackFrameValid(next2_fp, next_fp, stack_end)) {
return fp;
}
}
}
return 0;
}
void* LinkStackFrames(void* fpp, void* parent_fp) {
uintptr_t fp = reinterpret_cast<uintptr_t>(fpp) - kStackFrameAdjustment;
void* prev_parent_fp = reinterpret_cast<void**>(fp)[0];
reinterpret_cast<void**>(fp)[0] = parent_fp;
return prev_parent_fp;
}
#endif
std::string* g_stack_trace_message = nullptr;
OverrideStackTraceOutputForTesting::Mode g_override_suppression =
OverrideStackTraceOutputForTesting::Mode::kUnset;
}
#if BUILDFLAG(CAN_UNWIND_WITH_FRAME_POINTERS)
uintptr_t GetStackEnd() {
#if BUILDFLAG(IS_ANDROID)
static uintptr_t main_stack_end = 0;
bool is_main_thread = GetCurrentProcId() == PlatformThread::CurrentId().raw();
if (is_main_thread && main_stack_end) {
return main_stack_end;
}
uintptr_t stack_begin = 0;
size_t stack_size = 0;
pthread_attr_t attributes;
int error = pthread_getattr_np(pthread_self(), &attributes);
if (!error) {
error = pthread_attr_getstack(
&attributes, reinterpret_cast<void**>(&stack_begin), &stack_size);
pthread_attr_destroy(&attributes);
}
DCHECK(!error);
uintptr_t stack_end = stack_begin + stack_size;
if (is_main_thread) {
main_stack_end = stack_end;
}
return stack_end;
#elif BUILDFLAG(IS_APPLE)
return reinterpret_cast<uintptr_t>(pthread_get_stackaddr_np(pthread_self()));
#else
#if (BUILDFLAG(IS_LINUX) || BUILDFLAG(IS_CHROMEOS)) && defined(__GLIBC__)
static_assert(std::is_same_v<ProcessId, PlatformThreadId::UnderlyingType>);
if (GetCurrentProcId() == PlatformThread::CurrentId().raw()) {
return reinterpret_cast<uintptr_t>(__libc_stack_end);
}
#endif
return 0;
#endif
}
#endif
StackTrace::StackTrace() : StackTrace(std::size(trace_)) {}
StackTrace::StackTrace(size_t count)
: count_(ShouldSuppressOutput()
? 0
: CollectStackTrace(base::span(trace_).first(
std::min(count, std::size(trace_))))) {}
StackTrace::StackTrace(span<const void* const> trace)
: count_(std::min(trace.size(), std::size(trace_))) {
if (count_) {
base::span(trace_).copy_prefix_from(trace.first(count_));
}
}
bool StackTrace::WillSymbolizeToStreamForTesting() {
#if BUILDFLAG(HAS_SYMBOLS) == 0
return false;
#elif defined(__UCLIBC__) || defined(_AIX)
return false;
#elif defined(OFFICIAL_BUILD) && \
((BUILDFLAG(IS_POSIX) && !BUILDFLAG(IS_APPLE)) || BUILDFLAG(IS_FUCHSIA))
return false;
#elif defined(OFFICIAL_BUILD) && BUILDFLAG(IS_APPLE)
return false;
#elif BUILDFLAG(IS_FUCHSIA) || BUILDFLAG(IS_ANDROID)
return false;
#elif BUILDFLAG(PRINT_UNSYMBOLIZED_STACK_TRACES)
return false;
#else
return true;
#endif
}
void StackTrace::InitializeFeatures() {
#if BUILDFLAG(CAN_UNWIND_WITH_FRAME_POINTERS)
if (FeatureList::IsEnabled(
features::kStackScanMaxFramePointerToStackEndGap)) {
g_stack_scan_max_fp_to_stack_end_gap_bytes =
MiB(features::kStackScanMaxFramePointerToStackEndGapThresholdMB.Get())
.InBytesUnsigned();
}
#endif
}
void StackTrace::Print() const {
PrintWithPrefix({});
}
void StackTrace::PrintWithPrefix(cstring_view prefix_string) const {
if (!count_ || ShouldSuppressOutput()) {
if (g_stack_trace_message) {
PrintMessageWithPrefix(prefix_string, *g_stack_trace_message);
}
return;
}
PrintWithPrefixImpl(prefix_string);
}
void StackTrace::OutputToStream(std::ostream* os) const {
OutputToStreamWithPrefix(os, {});
}
void StackTrace::OutputToStreamWithPrefix(std::ostream* os,
cstring_view prefix_string) const {
if (!count_ || ShouldSuppressOutput()) {
if (g_stack_trace_message) {
(*os) << prefix_string << *g_stack_trace_message;
}
return;
}
OutputToStreamWithPrefixImpl(os, prefix_string);
}
std::string StackTrace::ToString() const {
return ToStringWithPrefix({});
}
std::string StackTrace::ToStringWithPrefix(cstring_view prefix_string) const {
std::stringstream stream;
#if !defined(__UCLIBC__) && !defined(_AIX)
OutputToStreamWithPrefix(&stream, prefix_string);
#endif
return stream.str();
}
void StackTrace::SuppressStackTracesWithMessageForTesting(std::string message) {
delete std::exchange(
g_stack_trace_message,
(message.empty() ? nullptr : new std::string(std::move(message))));
}
bool StackTrace::ShouldSuppressOutput() {
using Mode = OverrideStackTraceOutputForTesting::Mode;
return g_override_suppression != Mode::kUnset
? (g_override_suppression == Mode::kSuppressOutput)
: (g_stack_trace_message != nullptr);
}
std::ostream& operator<<(std::ostream& os, const StackTrace& s) {
#if !defined(__UCLIBC__) && !defined(_AIX)
s.OutputToStream(&os);
#else
os << "StackTrace::OutputToStream not implemented.";
#endif
return os;
}
OverrideStackTraceOutputForTesting::OverrideStackTraceOutputForTesting(
Mode mode) {
CHECK_NE(mode, Mode::kUnset);
CHECK_EQ(g_override_suppression, Mode::kUnset);
g_override_suppression = mode;
}
OverrideStackTraceOutputForTesting::~OverrideStackTraceOutputForTesting() {
CHECK_NE(g_override_suppression, Mode::kUnset);
g_override_suppression = Mode::kUnset;
}
#if BUILDFLAG(CAN_UNWIND_WITH_FRAME_POINTERS)
struct AddressRange {
uintptr_t start;
uintptr_t end;
};
bool IsWithinRange(uintptr_t address, const AddressRange& range) {
return address >= range.start && address <= range.end;
}
NOINLINE size_t TraceStackFramePointers(span<const void*> out_trace,
size_t skip_initial,
bool enable_scanning) {
#if defined(ARCH_CPU_ARM64)
static constexpr uintptr_t kCallInstructionSize = 4;
#else
static constexpr uintptr_t kCallInstructionSize = 0;
#endif
uintptr_t fp = reinterpret_cast<uintptr_t>(__builtin_frame_address(0)) -
kStackFrameAdjustment;
uintptr_t stack_end = GetStackEnd();
size_t depth = 0;
while (depth < out_trace.size()) {
uintptr_t pc = GetStackFramePC(fp);
if (skip_initial != 0) {
skip_initial--;
} else {
out_trace[depth++] =
reinterpret_cast<const void*>(pc - kCallInstructionSize);
}
uintptr_t next_fp = GetNextStackFrame(fp);
if (IsStackFrameValid(next_fp, fp, stack_end)) {
fp = next_fp;
continue;
}
if (!enable_scanning) {
break;
}
next_fp = ScanStackForNextFrame(fp, stack_end);
if (next_fp) {
fp = next_fp;
} else {
break;
}
}
return depth;
}
ScopedStackFrameLinker::ScopedStackFrameLinker(void* fp, void* parent_fp)
: fp_(fp),
parent_fp_(parent_fp),
original_parent_fp_(LinkStackFrames(fp, parent_fp)) {}
ScopedStackFrameLinker::~ScopedStackFrameLinker() {
void* previous_parent_fp = LinkStackFrames(fp_, original_parent_fp_);
CHECK_EQ(parent_fp_, previous_parent_fp)
<< "Stack frame's parent pointer has changed!";
}
#endif
}