| 1 |
/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ |
| 2 |
/* vim: set ts=8 sts=2 et sw=2 tw=80: */ |
| 3 |
/* This Source Code Form is subject to the terms of the Mozilla Public |
| 4 |
* License, v. 2.0. If a copy of the MPL was not distributed with this |
| 5 |
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */ |
| 6 |
|
| 7 |
/* API for getting a stack trace of the C/C++ stack on the current thread */ |
| 8 |
|
| 9 |
#include "mozilla/Array.h" |
| 10 |
#include "mozilla/ArrayUtils.h" |
| 11 |
#include "mozilla/Atomics.h" |
| 12 |
#include "mozilla/Attributes.h" |
| 13 |
#include "mozilla/StackWalk.h" |
| 14 |
#ifdef XP_WIN |
| 15 |
# include "mozilla/StackWalkThread.h" |
| 16 |
# include <io.h> |
| 17 |
#else |
| 18 |
# include <unistd.h> |
| 19 |
#endif |
| 20 |
#include "mozilla/Sprintf.h" |
| 21 |
|
| 22 |
#include <string.h> |
| 23 |
|
| 24 |
#if defined(ANDROID) && defined(MOZ_LINKER) |
| 25 |
# include "Linker.h" |
| 26 |
# include <android/log.h> |
| 27 |
#endif |
| 28 |
|
| 29 |
using namespace mozilla; |
| 30 |
|
| 31 |
// for _Unwind_Backtrace from libcxxrt or libunwind |
| 32 |
// cxxabi.h from libcxxrt implicitly includes unwind.h first |
| 33 |
#if defined(HAVE__UNWIND_BACKTRACE) && !defined(_GNU_SOURCE) |
| 34 |
# define _GNU_SOURCE |
| 35 |
#endif |
| 36 |
|
| 37 |
#if defined(HAVE_DLFCN_H) || defined(XP_DARWIN) |
| 38 |
# include <dlfcn.h> |
| 39 |
#endif |
| 40 |
|
| 41 |
#if (defined(XP_DARWIN) && \ |
| 42 |
(defined(__i386) || defined(__ppc__) || defined(HAVE__UNWIND_BACKTRACE))) |
| 43 |
# define MOZ_STACKWALK_SUPPORTS_MACOSX 1 |
| 44 |
#else |
| 45 |
# define MOZ_STACKWALK_SUPPORTS_MACOSX 0 |
| 46 |
#endif |
| 47 |
|
| 48 |
#if __GLIBC__ > 2 || (__GLIBC__ == 2 && __GLIBC_MINOR__ >= 1) |
| 49 |
# define HAVE___LIBC_STACK_END 1 |
| 50 |
#else |
| 51 |
# define HAVE___LIBC_STACK_END 0 |
| 52 |
#endif |
| 53 |
|
| 54 |
#if (defined(linux) && \ |
| 55 |
((defined(__GNUC__) && (defined(__i386) || defined(PPC))) || \ |
| 56 |
defined(HAVE__UNWIND_BACKTRACE)) && \ |
| 57 |
(HAVE___LIBC_STACK_END || ANDROID)) |
| 58 |
# define MOZ_STACKWALK_SUPPORTS_LINUX 1 |
| 59 |
#else |
| 60 |
# define MOZ_STACKWALK_SUPPORTS_LINUX 0 |
| 61 |
#endif |
| 62 |
|
| 63 |
#if HAVE___LIBC_STACK_END |
| 64 |
extern MOZ_EXPORT void* __libc_stack_end; // from ld-linux.so |
| 65 |
# ifdef __aarch64__ |
| 66 |
static Atomic<uintptr_t> ldso_base; |
| 67 |
# endif |
| 68 |
#endif |
| 69 |
|
| 70 |
#ifdef ANDROID |
| 71 |
# include <algorithm> |
| 72 |
# include <unistd.h> |
| 73 |
# include <pthread.h> |
| 74 |
#endif |
| 75 |
|
| 76 |
class FrameSkipper { |
| 77 |
public: |
| 78 |
constexpr FrameSkipper() : mSkipUntilAddr(0) {} |
| 79 |
static uintptr_t AddressFromPC(const void* aPC) { |
| 80 |
#ifdef __arm__ |
| 81 |
// On 32-bit ARM, mask off the thumb bit to get the instruction address. |
| 82 |
return uintptr_t(aPC) & ~1; |
| 83 |
#else |
| 84 |
return uintptr_t(aPC); |
| 85 |
#endif |
| 86 |
} |
| 87 |
bool ShouldSkipPC(void* aPC) { |
| 88 |
// Skip frames until we encounter the one we were initialized with, |
| 89 |
// and then never skip again. |
| 90 |
uintptr_t instructionAddress = AddressFromPC(aPC); |
| 91 |
if (mSkipUntilAddr != 0) { |
| 92 |
if (mSkipUntilAddr != instructionAddress) { |
| 93 |
return true; |
| 94 |
} |
| 95 |
mSkipUntilAddr = 0; |
| 96 |
} |
| 97 |
return false; |
| 98 |
} |
| 99 |
explicit FrameSkipper(const void* aPC) : mSkipUntilAddr(AddressFromPC(aPC)) {} |
| 100 |
|
| 101 |
private: |
| 102 |
uintptr_t mSkipUntilAddr; |
| 103 |
}; |
| 104 |
|
| 105 |
#ifdef XP_WIN |
| 106 |
|
| 107 |
# include <windows.h> |
| 108 |
# include <process.h> |
| 109 |
# include <stdio.h> |
| 110 |
# include <malloc.h> |
| 111 |
# include "mozilla/ArrayUtils.h" |
| 112 |
# include "mozilla/Atomics.h" |
| 113 |
# include "mozilla/StackWalk_windows.h" |
| 114 |
# include "mozilla/WindowsVersion.h" |
| 115 |
|
| 116 |
# include <imagehlp.h> |
| 117 |
// We need a way to know if we are building for WXP (or later), as if we are, we |
| 118 |
// need to use the newer 64-bit APIs. API_VERSION_NUMBER seems to fit the bill. |
| 119 |
// A value of 9 indicates we want to use the new APIs. |
| 120 |
# if API_VERSION_NUMBER < 9 |
| 121 |
# error Too old imagehlp.h |
| 122 |
# endif |
| 123 |
|
| 124 |
# if defined(_M_AMD64) || defined(_M_ARM64) |
| 125 |
// We must use RtlLookupFunctionEntry to do stack walking on x86-64 and arm64, |
| 126 |
// but internally this function does a blocking shared acquire of SRW locks |
| 127 |
// that live in ntdll and are not exported. This is problematic when we want to |
| 128 |
// suspend a thread and walk its stack, like we do in the profiler and the |
| 129 |
// background hang reporter. If the suspended thread happens to hold one of the |
| 130 |
// locks exclusively while suspended, then the stack walking thread will |
| 131 |
// deadlock if it calls RtlLookupFunctionEntry. |
| 132 |
// |
| 133 |
// Note that we only care about deadlocks between the stack walking thread and |
| 134 |
// the suspended thread. Any other deadlock scenario is considered out of |
| 135 |
// scope, because they are unlikely to be our fault -- these other scenarios |
| 136 |
// imply that some thread that we did not suspend is stuck holding one of the |
| 137 |
// locks exclusively, and exclusive acquisition of these locks only happens for |
| 138 |
// a brief time during Microsoft API calls (e.g. LdrLoadDll, LdrUnloadDll). |
| 139 |
// |
| 140 |
// We use one of two alternative strategies to gracefully fail to capture a |
| 141 |
// stack instead of running into a deadlock: |
| 142 |
// (1) collect pointers to the ntdll internal locks at stack walk |
| 143 |
// initialization, then try to acquire them non-blockingly before |
| 144 |
// initiating any stack walk; |
| 145 |
// or (2) mark all code paths that can potentially end up doing an exclusive |
| 146 |
// acquisition of the locks as stack walk suppression paths, then check |
| 147 |
// if any thread is currently on a stack walk suppression path before |
| 148 |
// initiating any stack walk; |
| 149 |
// |
| 150 |
// Strategy (2) can only avoid all deadlocks under the easily wronged |
| 151 |
// assumption that we have correctly identified all existing paths that should |
| 152 |
// be stack suppression paths. With strategy (2) we cannot collect stacks e.g. |
| 153 |
// during the whole duration of a DLL load happening on any thread so the |
| 154 |
// profiling results are worse. |
| 155 |
// |
| 156 |
// Strategy (1) guarantees no deadlock. It also gives better profiling results |
| 157 |
// because it is more fine-grained. Therefore we always prefer strategy (1), |
| 158 |
// and we only use strategy (2) as a fallback. |
| 159 |
|
| 160 |
// Strategy (1): Ntdll Internal Locks |
| 161 |
// |
| 162 |
// The external stack walk initialization code will feed us pointers to the |
| 163 |
// ntdll internal locks. Once we have them, we no longer need to rely on |
| 164 |
// strategy (2). |
| 165 |
static Atomic<bool> sStackWalkLocksInitialized; |
| 166 |
static Array<SRWLOCK*, 2> sStackWalkLocks; |
| 167 |
|
| 168 |
MFBT_API |
| 169 |
void InitializeStackWalkLocks(const Array<void*, 2>& aStackWalkLocks) { |
| 170 |
sStackWalkLocks[0] = reinterpret_cast<SRWLOCK*>(aStackWalkLocks[0]); |
| 171 |
sStackWalkLocks[1] = reinterpret_cast<SRWLOCK*>(aStackWalkLocks[1]); |
| 172 |
sStackWalkLocksInitialized = true; |
| 173 |
} |
| 174 |
|
| 175 |
// Strategy (2): Stack Walk Suppressions |
| 176 |
// |
| 177 |
// We're using an atomic counter rather than a critical section because we |
| 178 |
// don't require mutual exclusion with the stack walker. If the stack walker |
| 179 |
// determines that it's safe to start unwinding the suspended thread (i.e. |
| 180 |
// there are no suppressions when the unwind begins), then it's safe to |
| 181 |
// continue unwinding that thread even if other threads request suppressions |
| 182 |
// in the meantime, because we can't deadlock with those other threads. |
| 183 |
// |
| 184 |
// XXX: This global variable is a larger-than-necessary hammer. A more scoped |
| 185 |
// solution would be to maintain a counter per thread, but then it would be |
| 186 |
// more difficult for WalkStackMain64 to read the suspended thread's counter. |
| 187 |
static Atomic<size_t> sStackWalkSuppressions; |
| 188 |
|
| 189 |
void SuppressStackWalking() { ++sStackWalkSuppressions; } |
| 190 |
|
| 191 |
void DesuppressStackWalking() { |
| 192 |
auto previousValue = sStackWalkSuppressions--; |
| 193 |
// We should never desuppress from 0. See bug 1687510 comment 10 for an |
| 194 |
// example in which this occured. |
| 195 |
MOZ_RELEASE_ASSERT(previousValue); |
| 196 |
} |
| 197 |
|
| 198 |
MFBT_API |
| 199 |
AutoSuppressStackWalking::AutoSuppressStackWalking() { SuppressStackWalking(); } |
| 200 |
|
| 201 |
MFBT_API |
| 202 |
AutoSuppressStackWalking::~AutoSuppressStackWalking() { |
| 203 |
DesuppressStackWalking(); |
| 204 |
} |
| 205 |
|
| 206 |
bool IsStackWalkingSafe() { |
| 207 |
// Use strategy (1), if initialized. |
| 208 |
if (sStackWalkLocksInitialized) { |
| 209 |
bool isSafe = false; |
| 210 |
if (::TryAcquireSRWLockShared(sStackWalkLocks[0])) { |
| 211 |
if (::TryAcquireSRWLockShared(sStackWalkLocks[1])) { |
| 212 |
isSafe = true; |
| 213 |
::ReleaseSRWLockShared(sStackWalkLocks[1]); |
| 214 |
} |
| 215 |
::ReleaseSRWLockShared(sStackWalkLocks[0]); |
| 216 |
} |
| 217 |
return isSafe; |
| 218 |
} |
| 219 |
|
| 220 |
// Otherwise, fall back to strategy (2). |
| 221 |
return sStackWalkSuppressions == 0; |
| 222 |
} |
| 223 |
|
| 224 |
static uint8_t* sJitCodeRegionStart; |
| 225 |
static size_t sJitCodeRegionSize; |
| 226 |
uint8_t* sMsMpegJitCodeRegionStart; |
| 227 |
size_t sMsMpegJitCodeRegionSize; |
| 228 |
|
| 229 |
MFBT_API void RegisterJitCodeRegion(uint8_t* aStart, size_t aSize) { |
| 230 |
// Currently we can only handle one JIT code region at a time |
| 231 |
MOZ_RELEASE_ASSERT(!sJitCodeRegionStart); |
| 232 |
|
| 233 |
sJitCodeRegionStart = aStart; |
| 234 |
sJitCodeRegionSize = aSize; |
| 235 |
} |
| 236 |
|
| 237 |
MFBT_API void UnregisterJitCodeRegion(uint8_t* aStart, size_t aSize) { |
| 238 |
// Currently we can only handle one JIT code region at a time |
| 239 |
MOZ_RELEASE_ASSERT(sJitCodeRegionStart && sJitCodeRegionStart == aStart && |
| 240 |
sJitCodeRegionSize == aSize); |
| 241 |
|
| 242 |
sJitCodeRegionStart = nullptr; |
| 243 |
sJitCodeRegionSize = 0; |
| 244 |
} |
| 245 |
|
| 246 |
# endif // _M_AMD64 || _M_ARM64 |
| 247 |
|
| 248 |
// Routine to print an error message to standard error. |
| 249 |
static void PrintError(const char* aPrefix) { |
| 250 |
LPSTR lpMsgBuf; |
| 251 |
DWORD lastErr = GetLastError(); |
| 252 |
FormatMessageA(FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM | |
| 253 |
FORMAT_MESSAGE_IGNORE_INSERTS, |
| 254 |
nullptr, lastErr, |
| 255 |
MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), // Default language |
| 256 |
(LPSTR)&lpMsgBuf, 0, nullptr); |
| 257 |
fprintf(stderr, "### ERROR: %s: %s", aPrefix, |
| 258 |
lpMsgBuf ? lpMsgBuf : "(null)\n"); |
| 259 |
fflush(stderr); |
| 260 |
LocalFree(lpMsgBuf); |
| 261 |
} |
| 262 |
|
| 263 |
class MOZ_RAII AutoCriticalSection { |
| 264 |
public: |
| 265 |
explicit inline AutoCriticalSection(LPCRITICAL_SECTION aCriticalSection) |
| 266 |
: mCriticalSection{aCriticalSection} { |
| 267 |
::EnterCriticalSection(mCriticalSection); |
| 268 |
} |
| 269 |
inline ~AutoCriticalSection() { ::LeaveCriticalSection(mCriticalSection); } |
| 270 |
|
| 271 |
AutoCriticalSection(AutoCriticalSection&& other) = delete; |
| 272 |
AutoCriticalSection operator=(AutoCriticalSection&& other) = delete; |
| 273 |
AutoCriticalSection(const AutoCriticalSection&) = delete; |
| 274 |
AutoCriticalSection operator=(const AutoCriticalSection&) = delete; |
| 275 |
|
| 276 |
private: |
| 277 |
LPCRITICAL_SECTION mCriticalSection; |
| 278 |
}; |
| 279 |
|
| 280 |
// A thread-safe safe object interface for Microsoft's DbgHelp.dll. DbgHelp |
| 281 |
// APIs are not thread-safe and they require the use of a unique HANDLE value |
| 282 |
// as an identifier for the current session. All this is handled internally by |
| 283 |
// DbgHelpWrapper. |
| 284 |
class DbgHelpWrapper { |
| 285 |
public: |
| 286 |
explicit inline DbgHelpWrapper() : DbgHelpWrapper(InitFlag::BasicInit) {} |
| 287 |
DbgHelpWrapper(DbgHelpWrapper&& other) = delete; |
| 288 |
DbgHelpWrapper operator=(DbgHelpWrapper&& other) = delete; |
| 289 |
DbgHelpWrapper(const DbgHelpWrapper&) = delete; |
| 290 |
DbgHelpWrapper operator=(const DbgHelpWrapper&) = delete; |
| 291 |
|
| 292 |
inline bool ReadyToUse() { return mInitSuccess; } |
| 293 |
|
| 294 |
inline BOOL StackWalk64( |
| 295 |
DWORD aMachineType, HANDLE aThread, LPSTACKFRAME64 aStackFrame, |
| 296 |
PVOID aContextRecord, PREAD_PROCESS_MEMORY_ROUTINE64 aReadMemoryRoutine, |
| 297 |
PFUNCTION_TABLE_ACCESS_ROUTINE64 aFunctionTableAccessRoutine, |
| 298 |
PGET_MODULE_BASE_ROUTINE64 aGetModuleBaseRoutine, |
| 299 |
PTRANSLATE_ADDRESS_ROUTINE64 aTranslateAddress) { |
| 300 |
if (!ReadyToUse()) { |
| 301 |
return FALSE; |
| 302 |
} |
| 303 |
|
| 304 |
AutoCriticalSection guard(&sCriticalSection); |
| 305 |
return ::StackWalk64(aMachineType, sSessionId, aThread, aStackFrame, |
| 306 |
aContextRecord, aReadMemoryRoutine, |
| 307 |
aFunctionTableAccessRoutine, aGetModuleBaseRoutine, |
| 308 |
aTranslateAddress); |
| 309 |
} |
| 310 |
|
| 311 |
protected: |
| 312 |
enum class InitFlag : bool { |
| 313 |
BasicInit, |
| 314 |
WithSymbolSupport, |
| 315 |
}; |
| 316 |
|
| 317 |
explicit inline DbgHelpWrapper(InitFlag initFlag) { |
| 318 |
mInitSuccess = Initialize(initFlag); |
| 319 |
} |
| 320 |
|
| 321 |
// DbgHelp functions are not thread-safe and should therefore be protected |
| 322 |
// by using this critical section through a AutoCriticalSection. |
| 323 |
static CRITICAL_SECTION sCriticalSection; |
| 324 |
|
| 325 |
// DbgHelp functions require a unique HANDLE hProcess that should be the same |
| 326 |
// throughout the current session. We refer to this handle as a session id. |
| 327 |
// Ideally the session id should be a valid HANDLE to the target process, |
| 328 |
// which in our case is the current process. |
| 329 |
// |
| 330 |
// However, in order to avoid conflicts with other sessions, the session id |
| 331 |
// should be unique and therefore not just GetCurrentProcess(), which other |
| 332 |
// pieces of code tend to already use (see bug 1699328). |
| 333 |
// |
| 334 |
// We therefore define sSessionId as a duplicate of the current process |
| 335 |
// handle, a solution that meets all the requirements listed above. |
| 336 |
static HANDLE sSessionId; |
| 337 |
|
| 338 |
private: |
| 339 |
bool mInitSuccess; |
| 340 |
|
| 341 |
// This function initializes sCriticalSection, sSessionId and loads DbgHelp. |
| 342 |
// It also calls SymInitialize if called with aInitFlag::WithSymbolSupport. |
| 343 |
// It is thread-safe and reentrancy-safe. |
| 344 |
[[nodiscard]] static bool Initialize(InitFlag aInitFlag); |
| 345 |
|
| 346 |
// In debug and fuzzing builds, MOZ_ASSERT and MOZ_CRASH walk the stack to |
| 347 |
// print it before actually crashing. This code path uses a DbgHelpWrapper |
| 348 |
// object, hence *any* MOZ_ASSERT or MOZ_CRASH failure reached from |
| 349 |
// Initialize() leads to rentrancy (see bug 1869997 for an example). Such |
| 350 |
// failures can occur indirectly when we load dbghelp.dll, because we |
| 351 |
// override various Microsoft-internal functions that are called upon DLL |
| 352 |
// loading. We protect against reentrancy by keeping track of the ID of the |
| 353 |
// thread that runs the initialization code. |
| 354 |
static Atomic<DWORD> sInitializationThreadId; |
| 355 |
}; |
| 356 |
|
| 357 |
CRITICAL_SECTION DbgHelpWrapper::sCriticalSection{}; |
| 358 |
Atomic<DWORD> DbgHelpWrapper::sInitializationThreadId{0}; |
| 359 |
HANDLE DbgHelpWrapper::sSessionId{nullptr}; |
| 360 |
|
| 361 |
// Thread-safety here is ensured by the C++ standard: scoped static |
| 362 |
// initialization is thread-safe. sInitializationThreadId is used to protect |
| 363 |
// against reentrancy -- and only for that purpose. |
| 364 |
[[nodiscard]] /* static */ bool DbgHelpWrapper::Initialize( |
| 365 |
DbgHelpWrapper::InitFlag aInitFlag) { |
| 366 |
// In the code below, it is only safe to reach MOZ_ASSERT or MOZ_CRASH while |
| 367 |
// sInitializationThreadId is set to the current thread id. |
| 368 |
static Atomic<DWORD> sInitializationThreadId{0}; |
| 369 |
DWORD currentThreadId = ::GetCurrentThreadId(); |
| 370 |
|
| 371 |
// This code relies on Windows never giving us a current thread ID of zero. |
| 372 |
// We make this assumption explicit, by failing if that should ever occur. |
| 373 |
if (!currentThreadId) { |
| 374 |
return false; |
| 375 |
} |
| 376 |
|
| 377 |
if (sInitializationThreadId == currentThreadId) { |
| 378 |
// This is a reentrant call and we must abort here. |
| 379 |
return false; |
| 380 |
} |
| 381 |
|
| 382 |
static const bool sHasInitializedDbgHelp = [currentThreadId]() { |
| 383 |
// Per the C++ standard, only one thread evers reaches this path. |
| 384 |
sInitializationThreadId = currentThreadId; |
| 385 |
|
| 386 |
::InitializeCriticalSection(&sCriticalSection); |
| 387 |
|
| 388 |
if (!::DuplicateHandle(GetCurrentProcess(), GetCurrentProcess(), |
| 389 |
GetCurrentProcess(), &sSessionId, 0, FALSE, |
| 390 |
DUPLICATE_SAME_ACCESS)) { |
| 391 |
return false; |
| 392 |
} |
| 393 |
|
| 394 |
bool dbgHelpLoaded = static_cast<bool>(::LoadLibraryW(L"dbghelp.dll")); |
| 395 |
|
| 396 |
MOZ_ASSERT(dbgHelpLoaded); |
| 397 |
sInitializationThreadId = 0; |
| 398 |
return dbgHelpLoaded; |
| 399 |
}(); |
| 400 |
|
| 401 |
// If we don't need symbol initialization, we are done. If we need it, we |
| 402 |
// can only proceed if DbgHelp initialization was successful. |
| 403 |
if (aInitFlag == InitFlag::BasicInit || !sHasInitializedDbgHelp) { |
| 404 |
return sHasInitializedDbgHelp; |
| 405 |
} |
| 406 |
|
| 407 |
static const bool sHasInitializedSymbols = [currentThreadId]() { |
| 408 |
// Per the C++ standard, only one thread evers reaches this path. |
| 409 |
sInitializationThreadId = currentThreadId; |
| 410 |
|
| 411 |
bool symbolsInitialized = false; |
| 412 |
|
| 413 |
{ |
| 414 |
AutoCriticalSection guard(&sCriticalSection); |
| 415 |
::SymSetOptions(SYMOPT_LOAD_LINES | SYMOPT_UNDNAME); |
| 416 |
symbolsInitialized = |
| 417 |
static_cast<bool>(::SymInitializeW(sSessionId, nullptr, TRUE)); |
| 418 |
/* XXX At some point we need to arrange to call SymCleanup */ |
| 419 |
} |
| 420 |
|
| 421 |
if (!symbolsInitialized) { |
| 422 |
PrintError("SymInitialize"); |
| 423 |
} |
| 424 |
|
| 425 |
MOZ_ASSERT(symbolsInitialized); |
| 426 |
sInitializationThreadId = 0; |
| 427 |
return symbolsInitialized; |
| 428 |
}(); |
| 429 |
|
| 430 |
return sHasInitializedSymbols; |
| 431 |
} |
| 432 |
|
| 433 |
// Some APIs such as SymFromAddr also require that the session id has gone |
| 434 |
// through SymInitialize. This is handled by child class DbgHelpWrapperSym. |
| 435 |
class DbgHelpWrapperSym : public DbgHelpWrapper { |
| 436 |
public: |
| 437 |
explicit DbgHelpWrapperSym() : DbgHelpWrapper(InitFlag::WithSymbolSupport) {} |
| 438 |
|
| 439 |
inline BOOL SymFromAddr(DWORD64 aAddress, PDWORD64 aDisplacement, |
| 440 |
PSYMBOL_INFO aSymbol) { |
| 441 |
if (!ReadyToUse()) { |
| 442 |
return FALSE; |
| 443 |
} |
| 444 |
|
| 445 |
AutoCriticalSection guard(&sCriticalSection); |
| 446 |
return ::SymFromAddr(sSessionId, aAddress, aDisplacement, aSymbol); |
| 447 |
} |
| 448 |
|
| 449 |
BOOL SymGetModuleInfoEspecial64(DWORD64 aAddr, PIMAGEHLP_MODULE64 aModuleInfo, |
| 450 |
PIMAGEHLP_LINE64 aLineInfo); |
| 451 |
|
| 452 |
private: |
| 453 |
// Helpers for SymGetModuleInfoEspecial64 |
| 454 |
struct CallbackEspecial64UserContext { |
| 455 |
HANDLE mSessionId; |
| 456 |
DWORD64 mAddr; |
| 457 |
}; |
| 458 |
|
| 459 |
static BOOL CALLBACK CallbackEspecial64(PCSTR aModuleName, |
| 460 |
DWORD64 aModuleBase, |
| 461 |
ULONG aModuleSize, |
| 462 |
PVOID aUserContext); |
| 463 |
}; |
| 464 |
|
| 465 |
// Wrapper around a reference to a CONTEXT, to simplify access to main |
| 466 |
// platform-specific execution registers. |
| 467 |
// It also avoids using CONTEXT* nullable pointers. |
| 468 |
class CONTEXTGenericAccessors { |
| 469 |
public: |
| 470 |
explicit CONTEXTGenericAccessors(CONTEXT& aCONTEXT) : mCONTEXT(aCONTEXT) {} |
| 471 |
|
| 472 |
CONTEXT* CONTEXTPtr() { return &mCONTEXT; } |
| 473 |
|
| 474 |
inline auto& PC() { |
| 475 |
# if defined(_M_AMD64) |
| 476 |
return mCONTEXT.Rip; |
| 477 |
# elif defined(_M_ARM64) |
| 478 |
return mCONTEXT.Pc; |
| 479 |
# elif defined(_M_IX86) |
| 480 |
return mCONTEXT.Eip; |
| 481 |
# else |
| 482 |
# error "unknown platform" |
| 483 |
# endif |
| 484 |
} |
| 485 |
|
| 486 |
inline auto& SP() { |
| 487 |
# if defined(_M_AMD64) |
| 488 |
return mCONTEXT.Rsp; |
| 489 |
# elif defined(_M_ARM64) |
| 490 |
return mCONTEXT.Sp; |
| 491 |
# elif defined(_M_IX86) |
| 492 |
return mCONTEXT.Esp; |
| 493 |
# else |
| 494 |
# error "unknown platform" |
| 495 |
# endif |
| 496 |
} |
| 497 |
|
| 498 |
inline auto& BP() { |
| 499 |
# if defined(_M_AMD64) |
| 500 |
return mCONTEXT.Rbp; |
| 501 |
# elif defined(_M_ARM64) |
| 502 |
return mCONTEXT.Fp; |
| 503 |
# elif defined(_M_IX86) |
| 504 |
return mCONTEXT.Ebp; |
| 505 |
# else |
| 506 |
# error "unknown platform" |
| 507 |
# endif |
| 508 |
} |
| 509 |
|
| 510 |
private: |
| 511 |
CONTEXT& mCONTEXT; |
| 512 |
}; |
| 513 |
|
| 514 |
/** |
| 515 |
* Walk the stack, translating PC's found into strings and recording the |
| 516 |
* chain in aBuffer. For this to work properly, the DLLs must be rebased |
| 517 |
* so that the address in the file agrees with the address in memory. |
| 518 |
* Otherwise StackWalk will return FALSE when it hits a frame in a DLL |
| 519 |
* whose in memory address doesn't match its in-file address. |
| 520 |
*/ |
| 521 |
|
| 522 |
static void DoMozStackWalkThread(MozWalkStackCallback aCallback, |
| 523 |
const void* aFirstFramePC, uint32_t aMaxFrames, |
| 524 |
void* aClosure, HANDLE aThread, |
| 525 |
CONTEXT* aContext) { |
| 526 |
# if defined(_M_IX86) |
| 527 |
DbgHelpWrapper dbgHelp; |
| 528 |
if (!dbgHelp.ReadyToUse()) { |
| 529 |
return; |
| 530 |
} |
| 531 |
# endif |
| 532 |
|
| 533 |
HANDLE targetThread = aThread; |
| 534 |
bool walkCallingThread; |
| 535 |
if (!targetThread) { |
| 536 |
targetThread = ::GetCurrentThread(); |
| 537 |
walkCallingThread = true; |
| 538 |
} else { |
| 539 |
DWORD targetThreadId = ::GetThreadId(targetThread); |
| 540 |
DWORD currentThreadId = ::GetCurrentThreadId(); |
| 541 |
walkCallingThread = (targetThreadId == currentThreadId); |
| 542 |
} |
| 543 |
|
| 544 |
// If not already provided, get a context for the specified thread. |
| 545 |
CONTEXT context_buf; |
| 546 |
if (!aContext) { |
| 547 |
memset(&context_buf, 0, sizeof(CONTEXT)); |
| 548 |
context_buf.ContextFlags = CONTEXT_FULL; |
| 549 |
if (walkCallingThread) { |
| 550 |
::RtlCaptureContext(&context_buf); |
| 551 |
} else if (!GetThreadContext(targetThread, &context_buf)) { |
| 552 |
return; |
| 553 |
} |
| 554 |
} |
| 555 |
CONTEXTGenericAccessors context{aContext ? *aContext : context_buf}; |
| 556 |
|
| 557 |
# if defined(_M_IX86) |
| 558 |
// Setup initial stack frame to walk from. |
| 559 |
STACKFRAME64 frame64; |
| 560 |
memset(&frame64, 0, sizeof(frame64)); |
| 561 |
frame64.AddrPC.Offset = context.PC(); |
| 562 |
frame64.AddrStack.Offset = context.SP(); |
| 563 |
frame64.AddrFrame.Offset = context.BP(); |
| 564 |
frame64.AddrPC.Mode = AddrModeFlat; |
| 565 |
frame64.AddrStack.Mode = AddrModeFlat; |
| 566 |
frame64.AddrFrame.Mode = AddrModeFlat; |
| 567 |
frame64.AddrReturn.Mode = AddrModeFlat; |
| 568 |
# endif |
| 569 |
|
| 570 |
# if defined(_M_AMD64) || defined(_M_ARM64) |
| 571 |
// If at least one thread (we don't know which) may be holding a lock that |
| 572 |
// can deadlock RtlLookupFunctionEntry, we can't proceed because that thread |
| 573 |
// may be the one that we're trying to walk the stack of. |
| 574 |
// |
| 575 |
// But if there is no such thread by this point, then our target thread can't |
| 576 |
// be holding a lock, so it's safe to proceed. By virtue of being suspended, |
| 577 |
// the target thread can't acquire any new locks during our stack walking, so |
| 578 |
// we only need to do this check once. Other threads may temporarily acquire |
| 579 |
// the locks while we're walking the stack, but that's mostly fine -- calling |
| 580 |
// RtlLookupFunctionEntry will make us wait for them to release the locks, |
| 581 |
// but at least we won't deadlock. |
| 582 |
if (!IsStackWalkingSafe()) { |
| 583 |
return; |
| 584 |
} |
| 585 |
|
| 586 |
bool firstFrame = true; |
| 587 |
# endif |
| 588 |
|
| 589 |
FrameSkipper skipper(aFirstFramePC); |
| 590 |
|
| 591 |
uint32_t frames = 0; |
| 592 |
|
| 593 |
// Now walk the stack. |
| 594 |
while (true) { |
| 595 |
DWORD64 addr; |
| 596 |
DWORD64 spaddr; |
| 597 |
|
| 598 |
# if defined(_M_IX86) |
| 599 |
// 32-bit frame unwinding. |
| 600 |
BOOL ok = dbgHelp.StackWalk64( |
| 601 |
IMAGE_FILE_MACHINE_I386, targetThread, &frame64, context.CONTEXTPtr(), |
| 602 |
nullptr, |
| 603 |
::SymFunctionTableAccess64, // function table access routine |
| 604 |
::SymGetModuleBase64, // module base routine |
| 605 |
0); |
| 606 |
|
| 607 |
if (ok) { |
| 608 |
addr = frame64.AddrPC.Offset; |
| 609 |
spaddr = frame64.AddrStack.Offset; |
| 610 |
} else { |
| 611 |
addr = 0; |
| 612 |
spaddr = 0; |
| 613 |
if (walkCallingThread) { |
| 614 |
PrintError("WalkStack64"); |
| 615 |
} |
| 616 |
} |
| 617 |
|
| 618 |
if (!ok) { |
| 619 |
break; |
| 620 |
} |
| 621 |
|
| 622 |
# elif defined(_M_AMD64) || defined(_M_ARM64) |
| 623 |
|
| 624 |
auto currentInstr = context.PC(); |
| 625 |
|
| 626 |
// If we reach a frame in JIT code, we don't have enough information to |
| 627 |
// unwind, so we have to give up. |
| 628 |
if (sJitCodeRegionStart && (uint8_t*)currentInstr >= sJitCodeRegionStart && |
| 629 |
(uint8_t*)currentInstr < sJitCodeRegionStart + sJitCodeRegionSize) { |
| 630 |
break; |
| 631 |
} |
| 632 |
|
| 633 |
// We must also avoid msmpeg2vdec.dll's JIT region: they don't generate |
| 634 |
// unwind data, so their JIT unwind callback just throws up its hands and |
| 635 |
// terminates the process. |
| 636 |
if (sMsMpegJitCodeRegionStart && |
| 637 |
(uint8_t*)currentInstr >= sMsMpegJitCodeRegionStart && |
| 638 |
(uint8_t*)currentInstr < |
| 639 |
sMsMpegJitCodeRegionStart + sMsMpegJitCodeRegionSize) { |
| 640 |
break; |
| 641 |
} |
| 642 |
|
| 643 |
// 64-bit frame unwinding. |
| 644 |
// Try to look up unwind metadata for the current function. |
| 645 |
ULONG64 imageBase; |
| 646 |
PRUNTIME_FUNCTION runtimeFunction = |
| 647 |
RtlLookupFunctionEntry(currentInstr, &imageBase, NULL); |
| 648 |
|
| 649 |
if (runtimeFunction) { |
| 650 |
PVOID dummyHandlerData; |
| 651 |
ULONG64 dummyEstablisherFrame; |
| 652 |
RtlVirtualUnwind(UNW_FLAG_NHANDLER, imageBase, currentInstr, |
| 653 |
runtimeFunction, context.CONTEXTPtr(), &dummyHandlerData, |
| 654 |
&dummyEstablisherFrame, nullptr); |
| 655 |
} else if (firstFrame) { |
| 656 |
// Leaf functions can be unwound by hand. |
| 657 |
context.PC() = *reinterpret_cast<DWORD64*>(context.SP()); |
| 658 |
context.SP() += sizeof(void*); |
| 659 |
} else { |
| 660 |
// Something went wrong. |
| 661 |
break; |
| 662 |
} |
| 663 |
|
| 664 |
addr = context.PC(); |
| 665 |
spaddr = context.SP(); |
| 666 |
firstFrame = false; |
| 667 |
# else |
| 668 |
# error "unknown platform" |
| 669 |
# endif |
| 670 |
|
| 671 |
if (addr == 0) { |
| 672 |
break; |
| 673 |
} |
| 674 |
|
| 675 |
if (skipper.ShouldSkipPC((void*)addr)) { |
| 676 |
continue; |
| 677 |
} |
| 678 |
|
| 679 |
aCallback(++frames, (void*)addr, (void*)spaddr, aClosure); |
| 680 |
|
| 681 |
if (aMaxFrames != 0 && frames == aMaxFrames) { |
| 682 |
break; |
| 683 |
} |
| 684 |
|
| 685 |
# if defined(_M_IX86) |
| 686 |
if (frame64.AddrReturn.Offset == 0) { |
| 687 |
break; |
| 688 |
} |
| 689 |
# endif |
| 690 |
} |
| 691 |
} |
| 692 |
|
| 693 |
MFBT_API void MozStackWalkThread(MozWalkStackCallback aCallback, |
| 694 |
uint32_t aMaxFrames, void* aClosure, |
| 695 |
HANDLE aThread, CONTEXT* aContext) { |
| 696 |
// We don't pass a aFirstFramePC because we walk the stack for another |
| 697 |
// thread. |
| 698 |
DoMozStackWalkThread(aCallback, nullptr, aMaxFrames, aClosure, aThread, |
| 699 |
aContext); |
| 700 |
} |
| 701 |
|
| 702 |
MFBT_API void MozStackWalk(MozWalkStackCallback aCallback, |
| 703 |
const void* aFirstFramePC, uint32_t aMaxFrames, |
| 704 |
void* aClosure) { |
| 705 |
DoMozStackWalkThread(aCallback, aFirstFramePC ? aFirstFramePC : CallerPC(), |
| 706 |
aMaxFrames, aClosure, nullptr, nullptr); |
| 707 |
} |
| 708 |
|
| 709 |
/* static */ BOOL CALLBACK |
| 710 |
DbgHelpWrapperSym::CallbackEspecial64(PCSTR aModuleName, DWORD64 aModuleBase, |
| 711 |
ULONG aModuleSize, PVOID aUserContext) { |
| 712 |
BOOL retval = TRUE; |
| 713 |
auto context = reinterpret_cast<CallbackEspecial64UserContext*>(aUserContext); |
| 714 |
DWORD64 addr = context->mAddr; |
| 715 |
|
| 716 |
/* |
| 717 |
* You'll want to control this if we are running on an |
| 718 |
* architecture where the addresses go the other direction. |
| 719 |
* Not sure this is even a realistic consideration. |
| 720 |
*/ |
| 721 |
const BOOL addressIncreases = TRUE; |
| 722 |
|
| 723 |
/* |
| 724 |
* If it falls in side the known range, load the symbols. |
| 725 |
*/ |
| 726 |
if (addressIncreases |
| 727 |
? (addr >= aModuleBase && addr <= (aModuleBase + aModuleSize)) |
| 728 |
: (addr <= aModuleBase && addr >= (aModuleBase - aModuleSize))) { |
| 729 |
retval = !!::SymLoadModule64(context->mSessionId, nullptr, aModuleName, |
| 730 |
nullptr, aModuleBase, aModuleSize); |
| 731 |
if (!retval) { |
| 732 |
PrintError("SymLoadModule64"); |
| 733 |
} |
| 734 |
} |
| 735 |
|
| 736 |
return retval; |
| 737 |
} |
| 738 |
|
| 739 |
/* |
| 740 |
* SymGetModuleInfoEspecial |
| 741 |
* |
| 742 |
* Attempt to determine the module information. |
| 743 |
* Bug 112196 says this DLL may not have been loaded at the time |
| 744 |
* SymInitialize was called, and thus the module information |
| 745 |
* and symbol information is not available. |
| 746 |
* This code rectifies that problem. |
| 747 |
*/ |
| 748 |
|
| 749 |
// New members were added to IMAGEHLP_MODULE64 (that show up in the |
| 750 |
// Platform SDK that ships with VC8, but not the Platform SDK that ships |
| 751 |
// with VC7.1, i.e., between DbgHelp 6.0 and 6.1), but we don't need to |
| 752 |
// use them, and it's useful to be able to function correctly with the |
| 753 |
// older library. (Stock Windows XP SP2 seems to ship with dbghelp.dll |
| 754 |
// version 5.1.) Since Platform SDK version need not correspond to |
| 755 |
// compiler version, and the version number in debughlp.h was NOT bumped |
| 756 |
// when these changes were made, ifdef based on a constant that was |
| 757 |
// added between these versions. |
| 758 |
# ifdef SSRVOPT_SETCONTEXT |
| 759 |
# define NS_IMAGEHLP_MODULE64_SIZE \ |
| 760 |
(((offsetof(IMAGEHLP_MODULE64, LoadedPdbName) + sizeof(DWORD64) - 1) / \ |
| 761 |
sizeof(DWORD64)) * \ |
| 762 |
sizeof(DWORD64)) |
| 763 |
# else |
| 764 |
# define NS_IMAGEHLP_MODULE64_SIZE sizeof(IMAGEHLP_MODULE64) |
| 765 |
# endif |
| 766 |
|
| 767 |
BOOL DbgHelpWrapperSym::SymGetModuleInfoEspecial64( |
| 768 |
DWORD64 aAddr, PIMAGEHLP_MODULE64 aModuleInfo, PIMAGEHLP_LINE64 aLineInfo) { |
| 769 |
if (!ReadyToUse()) { |
| 770 |
return FALSE; |
| 771 |
} |
| 772 |
|
| 773 |
AutoCriticalSection guard(&sCriticalSection); |
| 774 |
BOOL retval = FALSE; |
| 775 |
|
| 776 |
/* |
| 777 |
* Init the vars if we have em. |
| 778 |
*/ |
| 779 |
aModuleInfo->SizeOfStruct = NS_IMAGEHLP_MODULE64_SIZE; |
| 780 |
if (aLineInfo) { |
| 781 |
aLineInfo->SizeOfStruct = sizeof(IMAGEHLP_LINE64); |
| 782 |
} |
| 783 |
|
| 784 |
/* |
| 785 |
* Give it a go. |
| 786 |
* It may already be loaded. |
| 787 |
*/ |
| 788 |
retval = ::SymGetModuleInfo64(sSessionId, aAddr, aModuleInfo); |
| 789 |
if (retval == FALSE) { |
| 790 |
/* |
| 791 |
* Not loaded, here's the magic. |
| 792 |
* Go through all the modules. |
| 793 |
*/ |
| 794 |
CallbackEspecial64UserContext context{ |
| 795 |
.mSessionId = sSessionId, |
| 796 |
.mAddr = aAddr, |
| 797 |
}; |
| 798 |
BOOL enumRes = ::EnumerateLoadedModules64( |
| 799 |
sSessionId, CallbackEspecial64, reinterpret_cast<PVOID>(&context)); |
| 800 |
if (enumRes != FALSE) { |
| 801 |
/* |
| 802 |
* One final go. |
| 803 |
* If it fails, then well, we have other problems. |
| 804 |
*/ |
| 805 |
retval = ::SymGetModuleInfo64(sSessionId, aAddr, aModuleInfo); |
| 806 |
} |
| 807 |
} |
| 808 |
|
| 809 |
/* |
| 810 |
* If we got module info, we may attempt line info as well. |
| 811 |
* We will not report failure if this does not work. |
| 812 |
*/ |
| 813 |
if (retval != FALSE && aLineInfo) { |
| 814 |
DWORD displacement = 0; |
| 815 |
BOOL lineRes = FALSE; |
| 816 |
lineRes = |
| 817 |
::SymGetLineFromAddr64(sSessionId, aAddr, &displacement, aLineInfo); |
| 818 |
if (!lineRes) { |
| 819 |
// Clear out aLineInfo to indicate that it's not valid |
| 820 |
memset(aLineInfo, 0, sizeof(*aLineInfo)); |
| 821 |
} |
| 822 |
} |
| 823 |
|
| 824 |
return retval; |
| 825 |
} |
| 826 |
|
| 827 |
MFBT_API bool MozDescribeCodeAddress(void* aPC, |
| 828 |
MozCodeAddressDetails* aDetails) { |
| 829 |
aDetails->library[0] = '\0'; |
| 830 |
aDetails->loffset = 0; |
| 831 |
aDetails->filename[0] = '\0'; |
| 832 |
aDetails->lineno = 0; |
| 833 |
aDetails->function[0] = '\0'; |
| 834 |
aDetails->foffset = 0; |
| 835 |
|
| 836 |
DbgHelpWrapperSym dbgHelp; |
| 837 |
if (!dbgHelp.ReadyToUse()) { |
| 838 |
return false; |
| 839 |
} |
| 840 |
|
| 841 |
// Attempt to load module info before we attempt to resolve the symbol. |
| 842 |
// This just makes sure we get good info if available. |
| 843 |
DWORD64 addr = (DWORD64)aPC; |
| 844 |
IMAGEHLP_MODULE64 modInfo; |
| 845 |
IMAGEHLP_LINE64 lineInfo; |
| 846 |
BOOL modInfoRes; |
| 847 |
modInfoRes = dbgHelp.SymGetModuleInfoEspecial64(addr, &modInfo, &lineInfo); |
| 848 |
|
| 849 |
if (modInfoRes) { |
| 850 |
strncpy(aDetails->library, modInfo.LoadedImageName, |
| 851 |
sizeof(aDetails->library)); |
| 852 |
aDetails->library[std::size(aDetails->library) - 1] = '\0'; |
| 853 |
aDetails->loffset = (char*)aPC - (char*)modInfo.BaseOfImage; |
| 854 |
|
| 855 |
if (lineInfo.FileName) { |
| 856 |
strncpy(aDetails->filename, lineInfo.FileName, |
| 857 |
sizeof(aDetails->filename)); |
| 858 |
aDetails->filename[std::size(aDetails->filename) - 1] = '\0'; |
| 859 |
aDetails->lineno = lineInfo.LineNumber; |
| 860 |
} |
| 861 |
} |
| 862 |
|
| 863 |
ULONG64 buffer[(sizeof(SYMBOL_INFO) + MAX_SYM_NAME * sizeof(TCHAR) + |
| 864 |
sizeof(ULONG64) - 1) / |
| 865 |
sizeof(ULONG64)]; |
| 866 |
PSYMBOL_INFO pSymbol = (PSYMBOL_INFO)buffer; |
| 867 |
pSymbol->SizeOfStruct = sizeof(SYMBOL_INFO); |
| 868 |
pSymbol->MaxNameLen = MAX_SYM_NAME; |
| 869 |
|
| 870 |
DWORD64 displacement; |
| 871 |
BOOL ok = dbgHelp.SymFromAddr(addr, &displacement, pSymbol); |
| 872 |
|
| 873 |
if (ok) { |
| 874 |
strncpy(aDetails->function, pSymbol->Name, sizeof(aDetails->function)); |
| 875 |
aDetails->function[std::size(aDetails->function) - 1] = '\0'; |
| 876 |
aDetails->foffset = static_cast<ptrdiff_t>(displacement); |
| 877 |
} |
| 878 |
|
| 879 |
return true; |
| 880 |
} |
| 881 |
|
| 882 |
// i386 or PPC Linux stackwalking code |
| 883 |
// |
| 884 |
// Changes to to OS/Architecture support here should be reflected in |
| 885 |
// build/moz.configure/memory.configure |
| 886 |
#elif HAVE_DLADDR && \ |
| 887 |
(HAVE__UNWIND_BACKTRACE || MOZ_STACKWALK_SUPPORTS_LINUX || \ |
| 888 |
MOZ_STACKWALK_SUPPORTS_MACOSX) |
| 889 |
|
| 890 |
# include <stdlib.h> |
| 891 |
# include <stdio.h> |
| 892 |
|
| 893 |
// On glibc 2.1, the Dl_info api defined in <dlfcn.h> is only exposed |
| 894 |
// if __USE_GNU is defined. I suppose its some kind of standards |
| 895 |
// adherence thing. |
| 896 |
// |
| 897 |
# if (__GLIBC_MINOR__ >= 1) && !defined(__USE_GNU) |
| 898 |
# define __USE_GNU |
| 899 |
# endif |
| 900 |
|
| 901 |
// This thing is exported by libstdc++ |
| 902 |
// Yes, this is a gcc only hack |
| 903 |
# if defined(MOZ_DEMANGLE_SYMBOLS) |
| 904 |
# include <cxxabi.h> |
| 905 |
# endif // MOZ_DEMANGLE_SYMBOLS |
| 906 |
|
| 907 |
namespace mozilla { |
| 908 |
|
| 909 |
void DemangleSymbol(const char* aSymbol, char* aBuffer, int aBufLen) { |
| 910 |
aBuffer[0] = '\0'; |
| 911 |
|
| 912 |
# if defined(MOZ_DEMANGLE_SYMBOLS) |
| 913 |
/* See demangle.h in the gcc source for the voodoo */ |
| 914 |
char* demangled = abi::__cxa_demangle(aSymbol, 0, 0, 0); |
| 915 |
|
| 916 |
if (demangled) { |
| 917 |
strncpy(aBuffer, demangled, aBufLen); |
| 918 |
aBuffer[aBufLen - 1] = '\0'; |
| 919 |
free(demangled); |
| 920 |
} |
| 921 |
# endif // MOZ_DEMANGLE_SYMBOLS |
| 922 |
} |
| 923 |
|
| 924 |
} // namespace mozilla |
| 925 |
|
| 926 |
// {x86, ppc} x {Linux, Mac} stackwalking code. |
| 927 |
// |
| 928 |
// Changes to to OS/Architecture support here should be reflected in |
| 929 |
// build/moz.configure/memory.configure |
| 930 |
# if ((defined(__i386) || defined(PPC) || defined(__ppc__)) && \ |
| 931 |
(MOZ_STACKWALK_SUPPORTS_MACOSX || MOZ_STACKWALK_SUPPORTS_LINUX)) |
| 932 |
|
| 933 |
static void DoFramePointerStackWalk(MozWalkStackCallback aCallback, |
| 934 |
const void* aFirstFramePC, |
| 935 |
uint32_t aMaxFrames, void* aClosure, |
| 936 |
void** aBp, void* aStackEnd); |
| 937 |
|
| 938 |
MFBT_API void MozStackWalk(MozWalkStackCallback aCallback, |
| 939 |
const void* aFirstFramePC, uint32_t aMaxFrames, |
| 940 |
void* aClosure) { |
| 941 |
// Get the frame pointer |
| 942 |
void** bp = (void**)__builtin_frame_address(0); |
| 943 |
|
| 944 |
void* stackEnd; |
| 945 |
# if HAVE___LIBC_STACK_END |
| 946 |
stackEnd = __libc_stack_end; |
| 947 |
# elif defined(XP_DARWIN) |
| 948 |
stackEnd = pthread_get_stackaddr_np(pthread_self()); |
| 949 |
# elif defined(ANDROID) |
| 950 |
pthread_attr_t sattr; |
| 951 |
pthread_attr_init(&sattr); |
| 952 |
int rc = pthread_getattr_np(pthread_self(), &sattr); |
| 953 |
MOZ_RELEASE_ASSERT(rc == 0, "pthread_getattr_np failed"); |
| 954 |
void* stackBase = stackEnd = nullptr; |
| 955 |
size_t stackSize = 0; |
| 956 |
if (gettid() != getpid()) { |
| 957 |
// bionic's pthread_attr_getstack doesn't tell the truth for the main |
| 958 |
// thread (see bug 846670). So don't use it for the main thread. |
| 959 |
if (!pthread_attr_getstack(&sattr, &stackBase, &stackSize)) { |
| 960 |
stackEnd = static_cast<char*>(stackBase) + stackSize; |
| 961 |
} else { |
| 962 |
stackEnd = nullptr; |
| 963 |
} |
| 964 |
} |
| 965 |
if (!stackEnd) { |
| 966 |
// So consider the current frame pointer + an arbitrary size of 8MB |
| 967 |
// (modulo overflow ; not really arbitrary as it's the default stack |
| 968 |
// size for the main thread) if pthread_attr_getstack failed for |
| 969 |
// some reason (or was skipped). |
| 970 |
static const uintptr_t kMaxStackSize = 8 * 1024 * 1024; |
| 971 |
uintptr_t maxStackStart = uintptr_t(-1) - kMaxStackSize; |
| 972 |
uintptr_t stackStart = std::max(maxStackStart, uintptr_t(bp)); |
| 973 |
stackEnd = reinterpret_cast<void*>(stackStart + kMaxStackSize); |
| 974 |
} |
| 975 |
# else |
| 976 |
# error Unsupported configuration |
| 977 |
# endif |
| 978 |
DoFramePointerStackWalk(aCallback, aFirstFramePC, aMaxFrames, aClosure, bp, |
| 979 |
stackEnd); |
| 980 |
} |
| 981 |
|
| 982 |
# elif defined(HAVE__UNWIND_BACKTRACE) |
| 983 |
|
| 984 |
// libgcc_s.so symbols _Unwind_Backtrace@@GCC_3.3 and _Unwind_GetIP@@GCC_3.0 |
| 985 |
# include <unwind.h> |
| 986 |
|
| 987 |
struct unwind_info { |
| 988 |
MozWalkStackCallback callback; |
| 989 |
FrameSkipper skipper; |
| 990 |
int maxFrames; |
| 991 |
int numFrames; |
| 992 |
void* closure; |
| 993 |
}; |
| 994 |
|
| 995 |
static _Unwind_Reason_Code unwind_callback(struct _Unwind_Context* context, |
| 996 |
void* closure) { |
| 997 |
_Unwind_Reason_Code ret = _URC_NO_REASON; |
| 998 |
unwind_info* info = static_cast<unwind_info*>(closure); |
| 999 |
void* pc = reinterpret_cast<void*>(_Unwind_GetIP(context)); |
| 1000 |
# if HAVE___LIBC_STACK_END && defined(__aarch64__) |
| 1001 |
// Work around https://sourceware.org/bugzilla/show_bug.cgi?id=32612 |
| 1002 |
// The _dl_tlsdesc_dynamic function can't be unwound through with |
| 1003 |
// _Unwind_Backtrace when glibc is built with aarch64 PAC (that leads |
| 1004 |
// to a crash). |
| 1005 |
// Unfortunately, we can't get the address of that specific function, so |
| 1006 |
// we just disallow all of ld-linux-aarch64.so.1: when we hit an address |
| 1007 |
// in there, we make _Unwind_Backtrace stop. |
| 1008 |
// In the case of _dl_tlsdesc_dynamic, this would stop the stackwalk at |
| 1009 |
// tls_get_addr_tail, which is enough information to know the stack comes |
| 1010 |
// from ld.so, and we even get inlining info giving us malloc, |
| 1011 |
// allocate_dtv_entry and allocate_and_init, which is plenty enough and |
| 1012 |
// better than nothing^Hcrashing. |
| 1013 |
// To figure out whether the frame falls into ld-linux-aarch64.so.1, we |
| 1014 |
// use __libc_stack_end (which lives there and is .data) as upper bound |
| 1015 |
// (assuming .data comes after .text), and get the base address of the |
| 1016 |
// library via dladdr. |
| 1017 |
if (!ldso_base) { |
| 1018 |
Dl_info info; |
| 1019 |
dladdr(&__libc_stack_end, &info); |
| 1020 |
ldso_base = (uintptr_t)info.dli_fbase; |
| 1021 |
} |
| 1022 |
if (ldso_base && ((uintptr_t)pc > ldso_base) && |
| 1023 |
(uintptr_t)pc < (uintptr_t)&__libc_stack_end) { |
| 1024 |
// Any error code will do, we just want to stop the walk even when |
| 1025 |
// we haven't reached the limit. |
| 1026 |
ret = _URC_FOREIGN_EXCEPTION_CAUGHT; |
| 1027 |
} |
| 1028 |
# endif |
| 1029 |
// TODO Use something like '_Unwind_GetGR()' to get the stack pointer. |
| 1030 |
if (!info->skipper.ShouldSkipPC(pc)) { |
| 1031 |
info->numFrames++; |
| 1032 |
(*info->callback)(info->numFrames, pc, nullptr, info->closure); |
| 1033 |
if (info->maxFrames != 0 && info->numFrames == info->maxFrames) { |
| 1034 |
// Again, any error code that stops the walk will do. |
| 1035 |
return _URC_FOREIGN_EXCEPTION_CAUGHT; |
| 1036 |
} |
| 1037 |
} |
| 1038 |
return ret; |
| 1039 |
} |
| 1040 |
|
| 1041 |
MFBT_API void MozStackWalk(MozWalkStackCallback aCallback, |
| 1042 |
const void* aFirstFramePC, uint32_t aMaxFrames, |
| 1043 |
void* aClosure) { |
| 1044 |
unwind_info info; |
| 1045 |
info.callback = aCallback; |
| 1046 |
info.skipper = FrameSkipper(aFirstFramePC ? aFirstFramePC : CallerPC()); |
| 1047 |
info.maxFrames = aMaxFrames; |
| 1048 |
info.numFrames = 0; |
| 1049 |
info.closure = aClosure; |
| 1050 |
|
| 1051 |
// We ignore the return value from _Unwind_Backtrace. There are three main |
| 1052 |
// reasons for this. |
| 1053 |
// - On ARM/Android bionic's _Unwind_Backtrace usually (always?) returns |
| 1054 |
// _URC_FAILURE. See |
| 1055 |
// https://bugzilla.mozilla.org/show_bug.cgi?id=717853#c110. |
| 1056 |
// - If aMaxFrames != 0, we want to stop early, and the only way to do that |
| 1057 |
// is to make unwind_callback return something other than _URC_NO_REASON, |
| 1058 |
// which causes _Unwind_Backtrace to return a non-success code. |
| 1059 |
// - MozStackWalk doesn't have a return value anyway. |
| 1060 |
(void)_Unwind_Backtrace(unwind_callback, &info); |
| 1061 |
} |
| 1062 |
|
| 1063 |
# endif |
| 1064 |
|
| 1065 |
bool MFBT_API MozDescribeCodeAddress(void* aPC, |
| 1066 |
MozCodeAddressDetails* aDetails) { |
| 1067 |
aDetails->library[0] = '\0'; |
| 1068 |
aDetails->loffset = 0; |
| 1069 |
aDetails->filename[0] = '\0'; |
| 1070 |
aDetails->lineno = 0; |
| 1071 |
aDetails->function[0] = '\0'; |
| 1072 |
aDetails->foffset = 0; |
| 1073 |
|
| 1074 |
Dl_info info; |
| 1075 |
|
| 1076 |
# if defined(ANDROID) && defined(MOZ_LINKER) |
| 1077 |
int ok = __wrap_dladdr(aPC, &info); |
| 1078 |
# else |
| 1079 |
int ok = dladdr(aPC, &info); |
| 1080 |
# endif |
| 1081 |
|
| 1082 |
if (!ok) { |
| 1083 |
return true; |
| 1084 |
} |
| 1085 |
|
| 1086 |
strncpy(aDetails->library, info.dli_fname, sizeof(aDetails->library)); |
| 1087 |
aDetails->library[std::size(aDetails->library) - 1] = '\0'; |
| 1088 |
aDetails->loffset = (char*)aPC - (char*)info.dli_fbase; |
| 1089 |
|
| 1090 |
# if !defined(XP_FREEBSD) |
| 1091 |
// On FreeBSD, dli_sname is unusably bad, it often returns things like |
| 1092 |
// 'gtk_xtbin_new' or 'XRE_GetBootstrap' instead of long C++ symbols. Just let |
| 1093 |
// GetFunction do the lookup directly in the ELF image. |
| 1094 |
|
| 1095 |
const char* symbol = info.dli_sname; |
| 1096 |
if (!symbol || symbol[0] == '\0') { |
| 1097 |
return true; |
| 1098 |
} |
| 1099 |
|
| 1100 |
DemangleSymbol(symbol, aDetails->function, sizeof(aDetails->function)); |
| 1101 |
|
| 1102 |
if (aDetails->function[0] == '\0') { |
| 1103 |
// Just use the mangled symbol if demangling failed. |
| 1104 |
strncpy(aDetails->function, symbol, sizeof(aDetails->function)); |
| 1105 |
aDetails->function[std::size(aDetails->function) - 1] = '\0'; |
| 1106 |
} |
| 1107 |
|
| 1108 |
aDetails->foffset = (char*)aPC - (char*)info.dli_saddr; |
| 1109 |
# endif |
| 1110 |
|
| 1111 |
return true; |
| 1112 |
} |
| 1113 |
|
| 1114 |
#else // unsupported platform. |
| 1115 |
|
| 1116 |
MFBT_API void MozStackWalk(MozWalkStackCallback aCallback, |
| 1117 |
const void* aFirstFramePC, uint32_t aMaxFrames, |
| 1118 |
void* aClosure) {} |
| 1119 |
|
| 1120 |
MFBT_API bool MozDescribeCodeAddress(void* aPC, |
| 1121 |
MozCodeAddressDetails* aDetails) { |
| 1122 |
aDetails->library[0] = '\0'; |
| 1123 |
aDetails->loffset = 0; |
| 1124 |
aDetails->filename[0] = '\0'; |
| 1125 |
aDetails->lineno = 0; |
| 1126 |
aDetails->function[0] = '\0'; |
| 1127 |
aDetails->foffset = 0; |
| 1128 |
return false; |
| 1129 |
} |
| 1130 |
|
| 1131 |
#endif |
| 1132 |
|
| 1133 |
#if defined(XP_WIN) || defined(XP_MACOSX) || defined(XP_LINUX) |
| 1134 |
|
| 1135 |
# if defined(XP_MACOSX) && defined(__aarch64__) |
| 1136 |
// On macOS arm64, system libraries are arm64e binaries, and arm64e can do |
| 1137 |
// pointer authentication: The low bits of the pointer are the actual pointer |
| 1138 |
// value, and the high bits are an encrypted hash. During stackwalking, we need |
| 1139 |
// to strip off this hash. In theory, ptrauth_strip would be the right function |
| 1140 |
// to call for this. However, that function is a no-op unless it's called from |
| 1141 |
// code which also builds as arm64e - which we do not. So we cannot use it. So |
| 1142 |
// for now, we hardcode a mask that seems to work today: 40 bits for the pointer |
| 1143 |
// and 24 bits for the hash seems to do the trick. We can worry about |
| 1144 |
// dynamically computing the correct mask if this ever stops working. |
| 1145 |
const uintptr_t kPointerMask = |
| 1146 |
(uintptr_t(1) << 40) - 1; // 40 bits pointer, 24 bit PAC |
| 1147 |
# else |
| 1148 |
const uintptr_t kPointerMask = ~uintptr_t(0); |
| 1149 |
# endif |
| 1150 |
|
| 1151 |
MOZ_ASAN_IGNORE |
| 1152 |
static void DoFramePointerStackWalk(MozWalkStackCallback aCallback, |
| 1153 |
const void* aFirstFramePC, |
| 1154 |
uint32_t aMaxFrames, void* aClosure, |
| 1155 |
void** aBp, void* aStackEnd) { |
| 1156 |
// Stack walking code courtesy Kipp's "leaky". |
| 1157 |
|
| 1158 |
FrameSkipper skipper(aFirstFramePC); |
| 1159 |
uint32_t numFrames = 0; |
| 1160 |
|
| 1161 |
// Sanitize the given aBp. Assume that something reasonably close to |
| 1162 |
// but before the stack end is going be a valid frame pointer. Also |
| 1163 |
// check that it is an aligned address. This increases the chances |
| 1164 |
// that if the pointer is not valid (which might happen if the caller |
| 1165 |
// called __builtin_frame_address(1) and its frame is busted for some |
| 1166 |
// reason), we won't read it, leading to a crash. Because the calling |
| 1167 |
// code is not using frame pointers when returning, it might actually |
| 1168 |
// recover just fine. |
| 1169 |
static const uintptr_t kMaxStackSize = 8 * 1024 * 1024; |
| 1170 |
if (uintptr_t(aBp) < uintptr_t(aStackEnd) - |
| 1171 |
std::min(kMaxStackSize, uintptr_t(aStackEnd)) || |
| 1172 |
aBp >= aStackEnd || (uintptr_t(aBp) & 3)) { |
| 1173 |
return; |
| 1174 |
} |
| 1175 |
|
| 1176 |
while (aBp) { |
| 1177 |
void** next = (void**)*aBp; |
| 1178 |
// aBp may not be a frame pointer on i386 if code was compiled with |
| 1179 |
// -fomit-frame-pointer, so do some sanity checks. |
| 1180 |
// (aBp should be a frame pointer on ppc(64) but checking anyway may help |
| 1181 |
// a little if the stack has been corrupted.) |
| 1182 |
// We don't need to check against the begining of the stack because |
| 1183 |
// we can assume that aBp > sp |
| 1184 |
if (next <= aBp || next >= aStackEnd || (uintptr_t(next) & 3)) { |
| 1185 |
break; |
| 1186 |
} |
| 1187 |
# if (defined(__ppc__) && defined(XP_MACOSX)) || defined(__powerpc64__) |
| 1188 |
// ppc mac or powerpc64 linux |
| 1189 |
void* pc = *(aBp + 2); |
| 1190 |
aBp += 3; |
| 1191 |
# else // i386 or powerpc32 linux |
| 1192 |
void* pc = *(aBp + 1); |
| 1193 |
aBp += 2; |
| 1194 |
# endif |
| 1195 |
|
| 1196 |
// Strip off pointer authentication hash, if present. For now, it looks |
| 1197 |
// like only return addresses require stripping, and stack pointers do |
| 1198 |
// not. This might change in the future. |
| 1199 |
pc = (void*)((uintptr_t)pc & kPointerMask); |
| 1200 |
|
| 1201 |
if (!skipper.ShouldSkipPC(pc)) { |
| 1202 |
// Assume that the SP points to the BP of the function |
| 1203 |
// it called. We can't know the exact location of the SP |
| 1204 |
// but this should be sufficient for our use the SP |
| 1205 |
// to order elements on the stack. |
| 1206 |
numFrames++; |
| 1207 |
(*aCallback)(numFrames, pc, aBp, aClosure); |
| 1208 |
if (aMaxFrames != 0 && numFrames == aMaxFrames) { |
| 1209 |
break; |
| 1210 |
} |
| 1211 |
} |
| 1212 |
aBp = next; |
| 1213 |
} |
| 1214 |
} |
| 1215 |
|
| 1216 |
namespace mozilla { |
| 1217 |
|
| 1218 |
MFBT_API void FramePointerStackWalk(MozWalkStackCallback aCallback, |
| 1219 |
uint32_t aMaxFrames, void* aClosure, |
| 1220 |
void** aBp, void* aStackEnd) { |
| 1221 |
// We don't pass a aFirstFramePC because we start walking the stack from the |
| 1222 |
// frame at aBp. |
| 1223 |
DoFramePointerStackWalk(aCallback, nullptr, aMaxFrames, aClosure, aBp, |
| 1224 |
aStackEnd); |
| 1225 |
} |
| 1226 |
|
| 1227 |
} // namespace mozilla |
| 1228 |
|
| 1229 |
#else |
| 1230 |
|
| 1231 |
namespace mozilla { |
| 1232 |
MFBT_API void FramePointerStackWalk(MozWalkStackCallback aCallback, |
| 1233 |
uint32_t aMaxFrames, void* aClosure, |
| 1234 |
void** aBp, void* aStackEnd) {} |
| 1235 |
} // namespace mozilla |
| 1236 |
|
| 1237 |
#endif |
| 1238 |
|
| 1239 |
MFBT_API int MozFormatCodeAddressDetails( |
| 1240 |
char* aBuffer, uint32_t aBufferSize, uint32_t aFrameNumber, void* aPC, |
| 1241 |
const MozCodeAddressDetails* aDetails) { |
| 1242 |
return MozFormatCodeAddress(aBuffer, aBufferSize, aFrameNumber, aPC, |
| 1243 |
aDetails->function, aDetails->library, |
| 1244 |
aDetails->loffset, aDetails->filename, |
| 1245 |
aDetails->lineno); |
| 1246 |
} |
| 1247 |
|
| 1248 |
MFBT_API int MozFormatCodeAddress(char* aBuffer, uint32_t aBufferSize, |
| 1249 |
uint32_t aFrameNumber, const void* aPC, |
| 1250 |
const char* aFunction, const char* aLibrary, |
| 1251 |
ptrdiff_t aLOffset, const char* aFileName, |
| 1252 |
uint32_t aLineNo) { |
| 1253 |
const char* function = aFunction && aFunction[0] ? aFunction : "???"; |
| 1254 |
if (aFileName && aFileName[0]) { |
| 1255 |
// We have a filename and (presumably) a line number. Use them. |
| 1256 |
return SprintfBuf(aBuffer, aBufferSize, "#%02u: %s (%s:%u)", aFrameNumber, |
| 1257 |
function, aFileName, aLineNo); |
| 1258 |
} else if (aLibrary && aLibrary[0]) { |
| 1259 |
// We have no filename, but we do have a library name. Use it and the |
| 1260 |
// library offset, and print them in a way that `fix_stacks.py` can |
| 1261 |
// post-process. |
| 1262 |
return SprintfBuf(aBuffer, aBufferSize, "#%02u: %s[%s +0x%" PRIxPTR "]", |
| 1263 |
aFrameNumber, function, aLibrary, |
| 1264 |
static_cast<uintptr_t>(aLOffset)); |
| 1265 |
} else { |
| 1266 |
// We have nothing useful to go on. (The format string is split because |
| 1267 |
// '??)' is a trigraph and causes a warning, sigh.) |
| 1268 |
return SprintfBuf(aBuffer, aBufferSize, |
| 1269 |
"#%02u: ??? (???:???" |
| 1270 |
")", |
| 1271 |
aFrameNumber); |
| 1272 |
} |
| 1273 |
} |
| 1274 |
|
| 1275 |
static void EnsureWrite(FILE* aStream, const char* aBuf, size_t aLen) { |
| 1276 |
#ifdef XP_WIN |
| 1277 |
int fd = _fileno(aStream); |
| 1278 |
#else |
| 1279 |
int fd = fileno(aStream); |
| 1280 |
#endif |
| 1281 |
while (aLen > 0) { |
| 1282 |
#ifdef XP_WIN |
| 1283 |
auto written = _write(fd, aBuf, aLen); |
| 1284 |
#else |
| 1285 |
auto written = write(fd, aBuf, aLen); |
| 1286 |
#endif |
| 1287 |
if (written <= 0 || size_t(written) > aLen) { |
| 1288 |
break; |
| 1289 |
} |
| 1290 |
aBuf += written; |
| 1291 |
aLen -= written; |
| 1292 |
} |
| 1293 |
} |
| 1294 |
|
| 1295 |
template <int N> |
| 1296 |
static int PrintStackFrameBuf(char (&aBuf)[N], uint32_t aFrameNumber, void* aPC, |
| 1297 |
void* aSP) { |
| 1298 |
MozCodeAddressDetails details; |
| 1299 |
MozDescribeCodeAddress(aPC, &details); |
| 1300 |
int len = |
| 1301 |
MozFormatCodeAddressDetails(aBuf, N - 1, aFrameNumber, aPC, &details); |
| 1302 |
len = std::min(len, N - 2); |
| 1303 |
aBuf[len++] = '\n'; |
| 1304 |
aBuf[len] = '\0'; |
| 1305 |
return len; |
| 1306 |
} |
| 1307 |
|
| 1308 |
static void PrintStackFrame(uint32_t aFrameNumber, void* aPC, void* aSP, |
| 1309 |
void* aClosure) { |
| 1310 |
FILE* stream = (FILE*)aClosure; |
| 1311 |
char buf[1025]; // 1024 + 1 for trailing '\n' |
| 1312 |
int len = PrintStackFrameBuf(buf, aFrameNumber, aPC, aSP); |
| 1313 |
fflush(stream); |
| 1314 |
EnsureWrite(stream, buf, len); |
| 1315 |
} |
| 1316 |
|
| 1317 |
static bool WalkTheStackEnabled() { |
| 1318 |
static bool result = [] { |
| 1319 |
char* value = getenv("MOZ_DISABLE_WALKTHESTACK"); |
| 1320 |
return !(value && value[0]); |
| 1321 |
}(); |
| 1322 |
return result; |
| 1323 |
} |
| 1324 |
|
| 1325 |
MFBT_API void MozWalkTheStack(FILE* aStream, const void* aFirstFramePC, |
| 1326 |
uint32_t aMaxFrames) { |
| 1327 |
if (WalkTheStackEnabled()) { |
| 1328 |
MozStackWalk(PrintStackFrame, aFirstFramePC ? aFirstFramePC : CallerPC(), |
| 1329 |
aMaxFrames, aStream); |
| 1330 |
} |
| 1331 |
} |
| 1332 |
|
| 1333 |
static void WriteStackFrame(uint32_t aFrameNumber, void* aPC, void* aSP, |
| 1334 |
void* aClosure) { |
| 1335 |
auto writer = (void (*)(const char*))aClosure; |
| 1336 |
char buf[1024]; |
| 1337 |
PrintStackFrameBuf(buf, aFrameNumber, aPC, aSP); |
| 1338 |
writer(buf); |
| 1339 |
} |
| 1340 |
|
| 1341 |
MFBT_API void MozWalkTheStackWithWriter(void (*aWriter)(const char*), |
| 1342 |
const void* aFirstFramePC, |
| 1343 |
uint32_t aMaxFrames) { |
| 1344 |
if (WalkTheStackEnabled()) { |
| 1345 |
MozStackWalk(WriteStackFrame, aFirstFramePC ? aFirstFramePC : CallerPC(), |
| 1346 |
aMaxFrames, (void*)aWriter); |
| 1347 |
} |
| 1348 |
} |