Debian Codegraph @

src/kj/exception.c++

raw
1 // Copyright (c) 2013-2014 Sandstorm Development Group, Inc. and contributors
2 // Licensed under the MIT License:
3 //
4 // Permission is hereby granted, free of charge, to any person obtaining a copy
5 // of this software and associated documentation files (the "Software"), to deal
6 // in the Software without restriction, including without limitation the rights
7 // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
8 // copies of the Software, and to permit persons to whom the Software is
9 // furnished to do so, subject to the following conditions:
10 //
11 // The above copyright notice and this permission notice shall be included in
12 // all copies or substantial portions of the Software.
13 //
14 // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
15 // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
16 // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
17 // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
18 // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
19 // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
20 // THE SOFTWARE.
21
22 #ifndef _GNU_SOURCE
23 #define _GNU_SOURCE
24 #endif
25
26 #if _WIN32 || __CYGWIN__
27 #include "win32-api-version.h"
28 #endif
29
30 #if (_WIN32 && _M_X64) || (__CYGWIN__ && __x86_64__)
31 // Currently the Win32 stack-trace code only supports x86_64. We could easily extend it to support
32 // i386 as well but it requires some code changes around how we read the context to start the
33 // trace.
34 #define KJ_USE_WIN32_DBGHELP 1
35 #endif
36
37 #include "exception.h"
38 #include "string.h"
39 #include "debug.h"
40 #include "threadlocal.h"
41 #include "miniposix.h"
42 #include "function.h"
43 #include "main.h"
44 #include <stdlib.h>
45 #include <exception>
46 #include <new>
47 #include <signal.h>
48 #include <stdint.h>
49 #ifndef _WIN32
50 #include <sys/mman.h>
51 #endif
52 #include "io.h"
53
54 #if !KJ_NO_RTTI
55 #include <typeinfo>
56 #endif
57 #if __GNUC__
58 #include <cxxabi.h>
59 #endif
60
61 #ifndef KJ_USE_BACKTRACE
62 #if (__linux__ && __GLIBC__ && !__UCLIBC__) || __APPLE__
63 #define KJ_USE_BACKTRACE 1
64 #endif
65 #endif
66
67 #if KJ_USE_BACKTRACE
68 #include <execinfo.h>
69 #endif
70
71 #if _WIN32 || __CYGWIN__
72 #include <windows.h>
73 #include "windows-sanity.h"
74 #include <dbghelp.h>
75 #endif
76
77 #if (__linux__ || __APPLE__ || __CYGWIN__)
78 #include <stdio.h>
79 #include <pthread.h>
80 #endif
81
82 #if __CYGWIN__
83 #include <sys/cygwin.h>
84 #include <ucontext.h>
85 #endif
86
87 #if KJ_HAS_LIBDL
88 #include "dlfcn.h"
89 #endif
90
91 #if _MSC_VER
92 #include <intrin.h>
93 #endif
94
95 #if KJ_HAS_COMPILER_FEATURE(address_sanitizer) || defined(__SANITIZE_ADDRESS__)
96 #include <sanitizer/lsan_interface.h>
97 #else
98 static void __lsan_ignore_object(const void* p) {}
99 #endif
100 // TODO(cleanup): Remove the LSAN stuff per https://github.com/capnproto/capnproto/pull/1255
101 // feedback.
102
103 namespace {
104 template <typename T>
105 inline T* lsanIgnoreObjectAndReturn(T* ptr) {
106 // Defensively lsan_ignore_object since the documentation doesn't explicitly specify what happens
107 // if you call this multiple times on the same object.
108 // TODO(cleanup): Remove this per https://github.com/capnproto/capnproto/pull/1255.
109 __lsan_ignore_object(ptr);
110 return ptr;
111 }
112 }
113
114 namespace kj {
115
116 StringPtr KJ_STRINGIFY(LogSeverity severity) {
117 static const char* SEVERITY_STRINGS[] = {
118 "info",
119 "warning",
120 "error",
121 "fatal",
122 "debug"
123 };
124
125 return SEVERITY_STRINGS[static_cast<uint>(severity)];
126 }
127
128 #if KJ_USE_WIN32_DBGHELP
129
130 namespace {
131
132 struct Dbghelp {
133 // Load dbghelp.dll dynamically since we don't really need it, it's just for debugging.
134
135 HINSTANCE lib;
136
137 BOOL (WINAPI *symInitialize)(HANDLE hProcess,PCSTR UserSearchPath,BOOL fInvadeProcess);
138 BOOL (WINAPI *stackWalk64)(
139 DWORD MachineType,HANDLE hProcess,HANDLE hThread,
140 LPSTACKFRAME64 StackFrame,PVOID ContextRecord,
141 PREAD_PROCESS_MEMORY_ROUTINE64 ReadMemoryRoutine,
142 PFUNCTION_TABLE_ACCESS_ROUTINE64 FunctionTableAccessRoutine,
143 PGET_MODULE_BASE_ROUTINE64 GetModuleBaseRoutine,
144 PTRANSLATE_ADDRESS_ROUTINE64 TranslateAddress);
145 PVOID (WINAPI *symFunctionTableAccess64)(HANDLE hProcess,DWORD64 AddrBase);
146 DWORD64 (WINAPI *symGetModuleBase64)(HANDLE hProcess,DWORD64 qwAddr);
147 BOOL (WINAPI *symGetLineFromAddr64)(
148 HANDLE hProcess,DWORD64 qwAddr,PDWORD pdwDisplacement,PIMAGEHLP_LINE64 Line64);
149
150 #if __GNUC__ && !__clang__ && __GNUC__ >= 8
151 // GCC 8 warns that our reinterpret_casts of function pointers below are casting between
152 // incompatible types. Yes, GCC, we know that. This is the nature of GetProcAddress(); it returns
153 // everything as `long long int (*)()` and we have to cast to the actual type.
154 #pragma GCC diagnostic push
155 #pragma GCC diagnostic ignored "-Wcast-function-type"
156 #endif
157 Dbghelp()
158 : lib(LoadLibraryA("dbghelp.dll")),
159 symInitialize(lib == nullptr ? nullptr :
160 reinterpret_cast<decltype(symInitialize)>(
161 GetProcAddress(lib, "SymInitialize"))),
162 stackWalk64(symInitialize == nullptr ? nullptr :
163 reinterpret_cast<decltype(stackWalk64)>(
164 GetProcAddress(lib, "StackWalk64"))),
165 symFunctionTableAccess64(symInitialize == nullptr ? nullptr :
166 reinterpret_cast<decltype(symFunctionTableAccess64)>(
167 GetProcAddress(lib, "SymFunctionTableAccess64"))),
168 symGetModuleBase64(symInitialize == nullptr ? nullptr :
169 reinterpret_cast<decltype(symGetModuleBase64)>(
170 GetProcAddress(lib, "SymGetModuleBase64"))),
171 symGetLineFromAddr64(symInitialize == nullptr ? nullptr :
172 reinterpret_cast<decltype(symGetLineFromAddr64)>(
173 GetProcAddress(lib, "SymGetLineFromAddr64"))) {
174 if (symInitialize != nullptr) {
175 symInitialize(GetCurrentProcess(), NULL, TRUE);
176 }
177 }
178 #if __GNUC__ && !__clang__ && __GNUC__ >= 9
179 #pragma GCC diagnostic pop
180 #endif
181 };
182
183 const Dbghelp& getDbghelp() {
184 static Dbghelp dbghelp;
185 return dbghelp;
186 }
187
188 ArrayPtr<void* const> getStackTrace(ArrayPtr<void*> space, uint ignoreCount,
189 HANDLE thread, CONTEXT& context) {
190 // NOTE: Apparently there is a function CaptureStackBackTrace() that is equivalent to glibc's
191 // backtrace(). Somehow I missed that when I originally wrote this. However,
192 // CaptureStackBackTrace() does not accept a CONTEXT parameter; it can only trace the caller.
193 // That's more problematic on Windows where breakHandler(), sehHandler(), and Cygwin signal
194 // handlers all depend on the ability to pass a CONTEXT. So we'll keep this code, which works
195 // after all.
196
197 const Dbghelp& dbghelp = getDbghelp();
198 if (dbghelp.stackWalk64 == nullptr ||
199 dbghelp.symFunctionTableAccess64 == nullptr ||
200 dbghelp.symGetModuleBase64 == nullptr) {
201 return nullptr;
202 }
203
204 STACKFRAME64 frame;
205 memset(&frame, 0, sizeof(frame));
206
207 frame.AddrPC.Offset = context.Rip;
208 frame.AddrPC.Mode = AddrModeFlat;
209 frame.AddrStack.Offset = context.Rsp;
210 frame.AddrStack.Mode = AddrModeFlat;
211 frame.AddrFrame.Offset = context.Rbp;
212 frame.AddrFrame.Mode = AddrModeFlat;
213
214 HANDLE process = GetCurrentProcess();
215
216 uint count = 0;
217 for (; count < space.size(); count++) {
218 if (!dbghelp.stackWalk64(IMAGE_FILE_MACHINE_AMD64, process, thread,
219 &frame, &context, NULL, dbghelp.symFunctionTableAccess64,
220 dbghelp.symGetModuleBase64, NULL)){
221 break;
222 }
223
224 // Subtract 1 from each address so that we identify the calling instructions, rather than the
225 // return addresses (which are typically the instruction after the call).
226 space[count] = reinterpret_cast<void*>(frame.AddrPC.Offset - 1);
227 }
228
229 return space.slice(kj::min(ignoreCount, count), count);
230 }
231
232 } // namespace
233 #endif
234
235 ArrayPtr<void* const> getStackTrace(ArrayPtr<void*> space, uint ignoreCount) {
236 if (getExceptionCallback().stackTraceMode() == ExceptionCallback::StackTraceMode::NONE) {
237 return nullptr;
238 }
239
240 #if KJ_USE_WIN32_DBGHELP
241 CONTEXT context;
242 RtlCaptureContext(&context);
243 return getStackTrace(space, ignoreCount, GetCurrentThread(), context);
244 #elif KJ_USE_BACKTRACE
245 size_t size = backtrace(space.begin(), space.size());
246 for (auto& addr: space.slice(0, size)) {
247 // The addresses produced by backtrace() are return addresses, which means they point to the
248 // instruction immediately after the call. Invoking addr2line on these can be confusing because
249 // it often points to the next line. If the next instruction is inlined from another function,
250 // the trace can be extra-confusing, since now it claims to be in a function that was not
251 // actually on the call stack. If we subtract 1 from each address, though, we get a much more
252 // reasonable trace. This may cause the addresses to be invalid instruction pointers if the
253 // instructions were multi-byte, but it appears addr2line is able to cope with this.
254 addr = reinterpret_cast<void*>(reinterpret_cast<uintptr_t>(addr) - 1);
255 }
256 return space.slice(kj::min(ignoreCount + 1, size), size);
257 #else
258 return nullptr;
259 #endif
260 }
261
262 #if (__GNUC__ && !_WIN32) || __clang__
263 // Allow dependents to override the implementation of stack symbolication by making it a weak
264 // symbol. We prefer weak symbols over some sort of callback registration mechanism becasue this
265 // allows an alternate symbolication library to be easily linked into tests without changing the
266 // code of the test.
267 __attribute__((weak))
268 #endif
269 String stringifyStackTrace(ArrayPtr<void* const> trace) {
270 if (trace.size() == 0) return nullptr;
271 if (getExceptionCallback().stackTraceMode() != ExceptionCallback::StackTraceMode::FULL) {
272 return nullptr;
273 }
274
275 #if KJ_USE_WIN32_DBGHELP && _MSC_VER
276
277 // Try to get file/line using SymGetLineFromAddr64(). We don't bother if we aren't on MSVC since
278 // this requires MSVC debug info.
279 //
280 // TODO(someday): We could perhaps shell out to addr2line on MinGW.
281
282 const Dbghelp& dbghelp = getDbghelp();
283 if (dbghelp.symGetLineFromAddr64 == nullptr) return nullptr;
284
285 HANDLE process = GetCurrentProcess();
286
287 KJ_STACK_ARRAY(String, lines, trace.size(), 32, 32);
288
289 for (auto i: kj::indices(trace)) {
290 IMAGEHLP_LINE64 lineInfo;
291 memset(&lineInfo, 0, sizeof(lineInfo));
292 lineInfo.SizeOfStruct = sizeof(lineInfo);
293 DWORD displacement;
294 if (dbghelp.symGetLineFromAddr64(process, reinterpret_cast<DWORD64>(trace[i]), &displacement, &lineInfo)) {
295 lines[i] = kj::str('\n', lineInfo.FileName, ':', lineInfo.LineNumber);
296 }
297 }
298
299 return strArray(lines, "");
300
301 #elif (__linux__ || __APPLE__ || __CYGWIN__) && !__ANDROID__
302 // We want to generate a human-readable stack trace.
303
304 // TODO(someday): It would be really great if we could avoid farming out to another process
305 // and do this all in-process, but that may involve onerous requirements like large library
306 // dependencies or using -rdynamic.
307
308 // The environment manipulation is not thread-safe, so lock a mutex. This could still be
309 // problematic if another thread is manipulating the environment in unrelated code, but there's
310 // not much we can do about that. This is debug-only anyway and only an issue when LD_PRELOAD
311 // is in use.
312 static pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
313 pthread_mutex_lock(&mutex);
314 KJ_DEFER(pthread_mutex_unlock(&mutex));
315
316 // Don't heapcheck / intercept syscalls.
317 const char* preload = getenv("LD_PRELOAD");
318 String oldPreload;
319 if (preload != nullptr) {
320 oldPreload = heapString(preload);
321 unsetenv("LD_PRELOAD");
322 }
323 KJ_DEFER(if (oldPreload != nullptr) { setenv("LD_PRELOAD", oldPreload.cStr(), true); });
324
325 String lines[32];
326 FILE* p = nullptr;
327 auto strTrace = strArray(trace, " ");
328
329 #if __linux__
330 if (access("/proc/self/exe", R_OK) < 0) {
331 // Apparently /proc is not available?
332 return nullptr;
333 }
334
335 // Obtain symbolic stack trace using addr2line.
336 // TODO(cleanup): Use fork() and exec() or maybe our own Subprocess API (once it exists), to
337 // avoid depending on a shell.
338 p = popen(str("addr2line -e /proc/", getpid(), "/exe ", strTrace).cStr(), "r");
339 #elif __APPLE__
340 // The Mac OS X equivalent of addr2line is atos.
341 // (Internally, it uses the private CoreSymbolication.framework library.)
342 p = popen(str("xcrun atos -p ", getpid(), ' ', strTrace).cStr(), "r");
343 #elif __CYGWIN__
344 wchar_t exeWinPath[MAX_PATH];
345 if (GetModuleFileNameW(nullptr, exeWinPath, sizeof(exeWinPath)) == 0) {
346 return nullptr;
347 }
348 char exePosixPath[MAX_PATH * 2];
349 if (cygwin_conv_path(CCP_WIN_W_TO_POSIX, exeWinPath, exePosixPath, sizeof(exePosixPath)) < 0) {
350 return nullptr;
351 }
352 p = popen(str("addr2line -e '", exePosixPath, "' ", strTrace).cStr(), "r");
353 #endif
354
355 if (p == nullptr) {
356 return nullptr;
357 }
358
359 char line[512];
360 size_t i = 0;
361 while (i < kj::size(lines) && fgets(line, sizeof(line), p) != nullptr) {
362 // Don't include exception-handling infrastructure or promise infrastructure in stack trace.
363 // addr2line output matches file names; atos output matches symbol names.
364 if (strstr(line, "kj/common.c++") != nullptr ||
365 strstr(line, "kj/exception.") != nullptr ||
366 strstr(line, "kj/debug.") != nullptr ||
367 strstr(line, "kj/async.") != nullptr ||
368 strstr(line, "kj/async-prelude.h") != nullptr ||
369 strstr(line, "kj/async-inl.h") != nullptr ||
370 strstr(line, "kj::Exception") != nullptr ||
371 strstr(line, "kj::_::Debug") != nullptr) {
372 continue;
373 }
374
375 size_t len = strlen(line);
376 if (len > 0 && line[len-1] == '\n') line[len-1] = '\0';
377 lines[i++] = str("\n ", trimSourceFilename(line), ": returning here");
378 }
379
380 // Skip remaining input.
381 while (fgets(line, sizeof(line), p) != nullptr) {}
382
383 pclose(p);
384
385 return strArray(arrayPtr(lines, i), "");
386
387 #else
388 return nullptr;
389 #endif
390 }
391
392 String stringifyStackTraceAddresses(ArrayPtr<void* const> trace) {
393 #if KJ_HAS_LIBDL
394 return strArray(KJ_MAP(addr, trace) {
395 Dl_info info;
396 // Shared libraries are mapped near the end of the address space while the executable is mapped
397 // near the beginning. We want to print addresses in the executable as raw addresses, not
398 // offsets, since that's what addr2line expects for executables. For shared libraries it
399 // expects offsets. In any case, most frames are likely to be in the main executable so it
400 // makes the output cleaner if we don't repeatedly write its name.
401 if (reinterpret_cast<uintptr_t>(addr) >= 0x400000000000ull && dladdr(addr, &info)) {
402 uintptr_t offset = reinterpret_cast<uintptr_t>(addr) -
403 reinterpret_cast<uintptr_t>(info.dli_fbase);
404 return kj::str(info.dli_fname, '@', reinterpret_cast<void*>(offset));
405 } else {
406 return kj::str(addr);
407 }
408 }, " ");
409 #else
410 // TODO(someday): Support other platforms.
411 return kj::strArray(trace, " ");
412 #endif
413 }
414
415 StringPtr stringifyStackTraceAddresses(ArrayPtr<void* const> trace, ArrayPtr<char> scratch) {
416 // Version which writes into a pre-allocated buffer. This is safe for signal handlers to the
417 // extent that dladdr() is safe.
418 //
419 // TODO(cleanup): We should improve the KJ stringification framework so that there's a way to
420 // write this string directly into a larger message buffer with strPreallocated().
421
422 #if KJ_HAS_LIBDL
423 char* ptr = scratch.begin();
424 char* limit = scratch.end() - 1;
425
426 for (auto addr: trace) {
427 Dl_info info;
428 // Shared libraries are mapped near the end of the address space while the executable is mapped
429 // near the beginning. We want to print addresses in the executable as raw addresses, not
430 // offsets, since that's what addr2line expects for executables. For shared libraries it
431 // expects offsets. In any case, most frames are likely to be in the main executable so it
432 // makes the output cleaner if we don't repeatedly write its name.
433 if (reinterpret_cast<uintptr_t>(addr) >= 0x400000000000ull && dladdr(addr, &info)) {
434 uintptr_t offset = reinterpret_cast<uintptr_t>(addr) -
435 reinterpret_cast<uintptr_t>(info.dli_fbase);
436 ptr = _::fillLimited(ptr, limit, kj::StringPtr(info.dli_fname), "@0x"_kj, hex(offset));
437 } else {
438 ptr = _::fillLimited(ptr, limit, toCharSequence(addr));
439 }
440
441 ptr = _::fillLimited(ptr, limit, " "_kj);
442 }
443 *ptr = '\0';
444 return StringPtr(scratch.begin(), ptr);
445 #else
446 // TODO(someday): Support other platforms.
447 return kj::strPreallocated(scratch, kj::delimited(trace, " "));
448 #endif
449 }
450
451 String getStackTrace() {
452 void* space[32];
453 auto trace = getStackTrace(space, 2);
454 return kj::str(stringifyStackTraceAddresses(trace), stringifyStackTrace(trace));
455 }
456
457 namespace {
458
459 #if !KJ_NO_EXCEPTIONS
460
461 [[noreturn]] void terminateHandler() {
462 void* traceSpace[32];
463
464 // ignoreCount = 3 to ignore std::terminate entry.
465 auto trace = kj::getStackTrace(traceSpace, 3);
466
467 kj::String message;
468
469 auto eptr = std::current_exception();
470 if (eptr != nullptr) {
471 try {
472 std::rethrow_exception(eptr);
473 } catch (const kj::Exception& exception) {
474 message = kj::str("*** Fatal uncaught kj::Exception: ", exception, '\n');
475 } catch (const std::exception& exception) {
476 message = kj::str("*** Fatal uncaught std::exception: ", exception.what(),
477 "\nstack: ", stringifyStackTraceAddresses(trace),
478 stringifyStackTrace(trace), '\n');
479 } catch (...) {
480 message = kj::str("*** Fatal uncaught exception of type: ", kj::getCaughtExceptionType(),
481 "\nstack: ", stringifyStackTraceAddresses(trace),
482 stringifyStackTrace(trace), '\n');
483 }
484 } else {
485 message = kj::str("*** std::terminate() called with no exception"
486 "\nstack: ", stringifyStackTraceAddresses(trace),
487 stringifyStackTrace(trace), '\n');
488 }
489
490 kj::FdOutputStream(STDERR_FILENO).write(message.begin(), message.size());
491 _exit(1);
492 }
493
494 #endif
495
496 } // namespace
497
498 #if KJ_USE_WIN32_DBGHELP && !__CYGWIN__
499 namespace {
500
501 DWORD mainThreadId = 0;
502
503 BOOL WINAPI breakHandler(DWORD type) {
504 switch (type) {
505 case CTRL_C_EVENT:
506 case CTRL_BREAK_EVENT: {
507 HANDLE thread = OpenThread(THREAD_ALL_ACCESS, FALSE, mainThreadId);
508 if (thread != NULL) {
509 if (SuspendThread(thread) != (DWORD)-1) {
510 CONTEXT context;
511 memset(&context, 0, sizeof(context));
512 context.ContextFlags = CONTEXT_FULL;
513 if (GetThreadContext(thread, &context)) {
514 void* traceSpace[32];
515 auto trace = getStackTrace(traceSpace, 0, thread, context);
516 ResumeThread(thread);
517 auto message = kj::str("*** Received CTRL+C. stack: ",
518 stringifyStackTraceAddresses(trace),
519 stringifyStackTrace(trace), '\n');
520 FdOutputStream(STDERR_FILENO).write(message.begin(), message.size());
521 } else {
522 ResumeThread(thread);
523 }
524 }
525 CloseHandle(thread);
526 }
527 break;
528 }
529 default:
530 break;
531 }
532
533 return FALSE; // still crash
534 }
535
536 kj::StringPtr exceptionDescription(DWORD code) {
537 switch (code) {
538 case EXCEPTION_ACCESS_VIOLATION: return "access violation";
539 case EXCEPTION_ARRAY_BOUNDS_EXCEEDED: return "array bounds exceeded";
540 case EXCEPTION_BREAKPOINT: return "breakpoint";
541 case EXCEPTION_DATATYPE_MISALIGNMENT: return "datatype misalignment";
542 case EXCEPTION_FLT_DENORMAL_OPERAND: return "denormal floating point operand";
543 case EXCEPTION_FLT_DIVIDE_BY_ZERO: return "floating point division by zero";
544 case EXCEPTION_FLT_INEXACT_RESULT: return "inexact floating point result";
545 case EXCEPTION_FLT_INVALID_OPERATION: return "invalid floating point operation";
546 case EXCEPTION_FLT_OVERFLOW: return "floating point overflow";
547 case EXCEPTION_FLT_STACK_CHECK: return "floating point stack overflow";
548 case EXCEPTION_FLT_UNDERFLOW: return "floating point underflow";
549 case EXCEPTION_ILLEGAL_INSTRUCTION: return "illegal instruction";
550 case EXCEPTION_IN_PAGE_ERROR: return "page error";
551 case EXCEPTION_INT_DIVIDE_BY_ZERO: return "integer divided by zero";
552 case EXCEPTION_INT_OVERFLOW: return "integer overflow";
553 case EXCEPTION_INVALID_DISPOSITION: return "invalid disposition";
554 case EXCEPTION_NONCONTINUABLE_EXCEPTION: return "noncontinuable exception";
555 case EXCEPTION_PRIV_INSTRUCTION: return "privileged instruction";
556 case EXCEPTION_SINGLE_STEP: return "single step";
557 case EXCEPTION_STACK_OVERFLOW: return "stack overflow";
558 default: return "(unknown exception code)";
559 }
560 }
561
562 LONG WINAPI sehHandler(EXCEPTION_POINTERS* info) {
563 void* traceSpace[32];
564 auto trace = getStackTrace(traceSpace, 0, GetCurrentThread(), *info->ContextRecord);
565 auto message = kj::str("*** Received structured exception #0x",
566 hex(info->ExceptionRecord->ExceptionCode), ": ",
567 exceptionDescription(info->ExceptionRecord->ExceptionCode),
568 "; stack: ",
569 stringifyStackTraceAddresses(trace),
570 stringifyStackTrace(trace), '\n');
571 FdOutputStream(STDERR_FILENO).write(message.begin(), message.size());
572 return EXCEPTION_EXECUTE_HANDLER; // still crash
573 }
574
575 } // namespace
576
577 void printStackTraceOnCrash() {
578 mainThreadId = GetCurrentThreadId();
579 KJ_WIN32(SetConsoleCtrlHandler(breakHandler, TRUE));
580 SetUnhandledExceptionFilter(&sehHandler);
581
582 #if !KJ_NO_EXCEPTIONS
583 // Also override std::terminate() handler with something nicer for KJ.
584 std::set_terminate(&terminateHandler);
585 #endif
586 }
587
588 #elif _WIN32
589 // Windows, but KJ_USE_WIN32_DBGHELP is not enabled. We can't print useful stack traces, so don't
590 // try to catch SEH nor ctrl+C.
591
592 void printStackTraceOnCrash() {
593 #if !KJ_NO_EXCEPTIONS
594 std::set_terminate(&terminateHandler);
595 #endif
596 }
597
598 #else
599 namespace {
600
601 [[noreturn]] void crashHandler(int signo, siginfo_t* info, void* context) {
602 void* traceSpace[32];
603
604 #if KJ_USE_WIN32_DBGHELP
605 // Win32 backtracing can't trace its way out of a Cygwin signal handler. However, Cygwin gives
606 // us direct access to the CONTEXT, which we can pass to the Win32 tracing functions.
607 ucontext_t* ucontext = reinterpret_cast<ucontext_t*>(context);
608 // Cygwin's mcontext_t has the same layout as CONTEXT.
609 // TODO(someday): Figure out why this produces garbage for SIGINT from ctrl+C. It seems to work
610 // correctly for SIGSEGV.
611 CONTEXT win32Context;
612 static_assert(sizeof(ucontext->uc_mcontext) >= sizeof(win32Context),
613 "mcontext_t should be an extension of CONTEXT");
614 memcpy(&win32Context, &ucontext->uc_mcontext, sizeof(win32Context));
615 auto trace = getStackTrace(traceSpace, 0, GetCurrentThread(), win32Context);
616 #else
617 // ignoreCount = 2 to ignore crashHandler() and signal trampoline.
618 auto trace = getStackTrace(traceSpace, 2);
619 #endif
620
621 auto message = kj::str("*** Received signal #", signo, ": ", strsignal(signo),
622 "\nstack: ", stringifyStackTraceAddresses(trace),
623 stringifyStackTrace(trace), '\n');
624
625 FdOutputStream(STDERR_FILENO).write(message.begin(), message.size());
626 _exit(1);
627 }
628
629 } // namespace
630
631 void printStackTraceOnCrash() {
632 // Set up alternate signal stack so that stack overflows can be handled.
633 stack_t stack;
634 memset(&stack, 0, sizeof(stack));
635
636 #ifndef MAP_ANONYMOUS
637 #define MAP_ANONYMOUS MAP_ANON
638 #endif
639 #ifndef MAP_GROWSDOWN
640 #define MAP_GROWSDOWN 0
641 #endif
642
643 stack.ss_size = 65536;
644 // Note: ss_sp is char* on FreeBSD, void* on Linux and OSX.
645 stack.ss_sp = reinterpret_cast<char*>(mmap(
646 nullptr, stack.ss_size, PROT_READ | PROT_WRITE,
647 MAP_ANONYMOUS | MAP_PRIVATE | MAP_GROWSDOWN, -1, 0));
648 KJ_SYSCALL(sigaltstack(&stack, nullptr));
649
650 // Catch all relevant signals.
651 struct sigaction action;
652 memset(&action, 0, sizeof(action));
653
654 action.sa_flags = SA_SIGINFO | SA_ONSTACK | SA_NODEFER | SA_RESETHAND;
655 action.sa_sigaction = &crashHandler;
656
657 // Dump stack on common "crash" signals.
658 KJ_SYSCALL(sigaction(SIGSEGV, &action, nullptr));
659 KJ_SYSCALL(sigaction(SIGBUS, &action, nullptr));
660 KJ_SYSCALL(sigaction(SIGFPE, &action, nullptr));
661 KJ_SYSCALL(sigaction(SIGABRT, &action, nullptr));
662 KJ_SYSCALL(sigaction(SIGILL, &action, nullptr));
663
664 // Dump stack on unimplemented syscalls -- useful in seccomp sandboxes.
665 KJ_SYSCALL(sigaction(SIGSYS, &action, nullptr));
666
667 #ifdef KJ_DEBUG
668 // Dump stack on keyboard interrupt -- useful for infinite loops. Only in debug mode, though,
669 // because stack traces on ctrl+c can be obnoxious for, say, command-line tools.
670 KJ_SYSCALL(sigaction(SIGINT, &action, nullptr));
671 #endif
672
673 #if !KJ_NO_EXCEPTIONS
674 // Also override std::terminate() handler with something nicer for KJ.
675 std::set_terminate(&terminateHandler);
676 #endif
677 }
678 #endif
679
680 kj::StringPtr trimSourceFilename(kj::StringPtr filename) {
681 // Removes noisy prefixes from source code file name.
682 //
683 // The goal here is to produce the "canonical" filename given the filename returned by e.g.
684 // addr2line. addr2line gives us the full path of the file as passed on the compiler
685 // command-line, which in turn is affected by build system and by whether and where we're
686 // performing an out-of-tree build.
687 //
688 // To deal with all this, we look for directory names in the path which we recognize to be
689 // locations that represent roots of the source tree. We strip said root and everything before
690 // it.
691 //
692 // On Windows, we often get filenames containing backslashes. Since we aren't allowed to allocate
693 // a new string here, we can't do much about this, so our returned "canonical" name will
694 // unfortunately end up with backslashes.
695
696 static constexpr const char* ROOTS[] = {
697 "ekam-provider/canonical/", // Ekam source file.
698 "ekam-provider/c++header/", // Ekam include file.
699 "src/", // Non-Ekam source root.
700 "tmp/", // Non-Ekam generated code.
701 #if _WIN32
702 "src\\", // Win32 source root.
703 "tmp\\", // Win32 generated code.
704 #endif
705 };
706
707 retry:
708 for (size_t i: kj::indices(filename)) {
709 if (i == 0 || filename[i-1] == '/'
710 #if _WIN32
711 || filename[i-1] == '\\'
712 #endif
713 ) {
714 // We're at the start of a directory name. Check for valid prefixes.
715 for (kj::StringPtr root: ROOTS) {
716 if (filename.slice(i).startsWith(root)) {
717 filename = filename.slice(i + root.size());
718
719 // We should keep searching to find the last instance of a root name. `i` is no longer
720 // a valid index for `filename` so start the loop over.
721 goto retry;
722 }
723 }
724 }
725 }
726
727 return filename;
728 }
729
730 void resetCrashHandlers() {
731 #ifndef _WIN32
732 struct sigaction action;
733 memset(&action, 0, sizeof(action));
734
735 action.sa_handler = SIG_DFL;
736 KJ_SYSCALL(sigaction(SIGSEGV, &action, nullptr));
737 KJ_SYSCALL(sigaction(SIGBUS, &action, nullptr));
738 KJ_SYSCALL(sigaction(SIGFPE, &action, nullptr));
739 KJ_SYSCALL(sigaction(SIGABRT, &action, nullptr));
740 KJ_SYSCALL(sigaction(SIGILL, &action, nullptr));
741 KJ_SYSCALL(sigaction(SIGSYS, &action, nullptr));
742
743 #ifdef KJ_DEBUG
744 KJ_SYSCALL(sigaction(SIGINT, &action, nullptr));
745 #endif
746 #endif
747
748 #if !KJ_NO_EXCEPTIONS
749 std::set_terminate(nullptr);
750 #endif
751 }
752
753 StringPtr KJ_STRINGIFY(Exception::Type type) {
754 static const char* TYPE_STRINGS[] = {
755 "failed",
756 "overloaded",
757 "disconnected",
758 "unimplemented"
759 };
760
761 return TYPE_STRINGS[static_cast<uint>(type)];
762 }
763
764 String KJ_STRINGIFY(const Exception& e) {
765 uint contextDepth = 0;
766
767 Maybe<const Exception::Context&> contextPtr = e.getContext();
768 for (;;) {
769 KJ_IF_MAYBE(c, contextPtr) {
770 ++contextDepth;
771 contextPtr = c->next;
772 } else {
773 break;
774 }
775 }
776
777 Array<String> contextText = heapArray<String>(contextDepth);
778
779 contextDepth = 0;
780 contextPtr = e.getContext();
781 for (;;) {
782 KJ_IF_MAYBE(c, contextPtr) {
783 contextText[contextDepth++] =
784 str(trimSourceFilename(c->file), ":", c->line, ": context: ", c->description, "\n");
785 contextPtr = c->next;
786 } else {
787 break;
788 }
789 }
790
791 // Note that we put "remote" before "stack" because trace frames are ordered callee before
792 // caller, so this is the most natural presentation ordering.
793 return str(strArray(contextText, ""),
794 e.getFile(), ":", e.getLine(), ": ", e.getType(),
795 e.getDescription() == nullptr ? "" : ": ", e.getDescription(),
796 e.getRemoteTrace().size() > 0 ? "\nremote: " : "",
797 e.getRemoteTrace(),
798 e.getStackTrace().size() > 0 ? "\nstack: " : "",
799 stringifyStackTraceAddresses(e.getStackTrace()),
800 stringifyStackTrace(e.getStackTrace()));
801 }
802
803 Exception::Exception(Type type, const char* file, int line, String description) noexcept
804 : file(trimSourceFilename(file).cStr()), line(line), type(type), description(mv(description)),
805 traceCount(0) {}
806
807 Exception::Exception(Type type, String file, int line, String description) noexcept
808 : ownFile(kj::mv(file)), file(trimSourceFilename(ownFile).cStr()), line(line), type(type),
809 description(mv(description)), traceCount(0) {}
810
811 Exception::Exception(const Exception& other) noexcept
812 : file(other.file), line(other.line), type(other.type),
813 description(heapString(other.description)), traceCount(other.traceCount) {
814 if (file == other.ownFile.cStr()) {
815 ownFile = heapString(other.ownFile);
816 file = ownFile.cStr();
817 }
818
819 if (other.remoteTrace != nullptr) {
820 remoteTrace = kj::str(other.remoteTrace);
821 }
822
823 memcpy(trace, other.trace, sizeof(trace[0]) * traceCount);
824
825 KJ_IF_MAYBE(c, other.context) {
826 context = heap(**c);
827 }
828 }
829
830 Exception::~Exception() noexcept {}
831
832 Exception::Context::Context(const Context& other) noexcept
833 : file(other.file), line(other.line), description(str(other.description)) {
834 KJ_IF_MAYBE(n, other.next) {
835 next = heap(**n);
836 }
837 }
838
839 void Exception::wrapContext(const char* file, int line, String&& description) {
840 context = heap<Context>(file, line, mv(description), mv(context));
841 }
842
843 void Exception::extendTrace(uint ignoreCount, uint limit) {
844 if (isFullTrace) {
845 // Awkward: extendTrace() was called twice without truncating in between. This should probably
846 // be an error, but historically we didn't check for this so I'm hesitant to make it an error
847 // now. We shouldn't actually extend the trace, though, as our current trace is presumably
848 // rooted in main() and it'd be weird to append frames "above" that.
849 // TODO(cleanup): Abort here and see what breaks?
850 return;
851 }
852
853 KJ_STACK_ARRAY(void*, newTraceSpace, kj::min(kj::size(trace), limit) + ignoreCount + 1,
854 sizeof(trace)/sizeof(trace[0]) + 8, 128);
855
856 auto newTrace = kj::getStackTrace(newTraceSpace, ignoreCount + 1);
857 if (newTrace.size() > ignoreCount + 2) {
858 // Remove suffix that won't fit into our static-sized trace.
859 newTrace = newTrace.slice(0, kj::min(kj::size(trace) - traceCount, newTrace.size()));
860
861 // Copy the rest into our trace.
862 memcpy(trace + traceCount, newTrace.begin(), newTrace.asBytes().size());
863 traceCount += newTrace.size();
864 isFullTrace = true;
865 }
866 }
867
868 void Exception::truncateCommonTrace() {
869 if (isFullTrace) {
870 // We're truncating the common portion of the full trace, turning it back into a limited
871 // trace.
872 isFullTrace = false;
873 } else {
874 // If the trace was never extended in the first place, trying to truncate it is at best a waste
875 // of time and at worst might remove information for no reason. So, don't.
876 //
877 // This comes up in particular in coroutines, when the exception originated from a co_awaited
878 // promise. In that case we manually add the one relevant frame to the trace, rather than
879 // call extendTrace() just to have to truncate most of it again a moment later in the
880 // unhandled_exception() callback.
881 return;
882 }
883
884 if (traceCount > 0) {
885 // Create a "reference" stack trace that is a little bit deeper than the one in the exception.
886 void* refTraceSpace[sizeof(this->trace) / sizeof(this->trace[0]) + 4];
887 auto refTrace = kj::getStackTrace(refTraceSpace, 0);
888
889 // We expect that the deepest frame in the exception's stack trace should be somewhere in our
890 // own trace, since our own trace has a deeper limit. Search for it.
891 for (uint i = refTrace.size(); i > 0; i--) {
892 if (refTrace[i-1] == trace[traceCount-1]) {
893 // See how many frames match.
894 for (uint j = 0; j < i; j++) {
895 if (j >= traceCount) {
896 // We matched the whole trace, apparently?
897 traceCount = 0;
898 return;
899 } else if (refTrace[i-j-1] != trace[traceCount-j-1]) {
900 // Found mismatching entry.
901
902 // If we matched more than half of the reference trace, guess that this is in fact
903 // the prefix we're looking for.
904 if (j > refTrace.size() / 2) {
905 // Delete the matching suffix. Also delete one non-matched entry on the assumption
906 // that both traces contain that stack frame but are simply at different points in
907 // the function.
908 traceCount -= j + 1;
909 return;
910 }
911 }
912 }
913 }
914 }
915
916 // No match. Ignore.
917 }
918 }
919
920 void Exception::addTrace(void* ptr) {
921 // TODO(cleanup): Abort here if isFullTrace is true, and see what breaks. This method only makes
922 // sense to call on partial traces.
923
924 if (traceCount < kj::size(trace)) {
925 trace[traceCount++] = ptr;
926 }
927 }
928
929 void Exception::addTraceHere() {
930 #if __GNUC__
931 addTrace(__builtin_return_address(0));
932 #elif _MSC_VER
933 addTrace(_ReturnAddress());
934 #else
935 #error "please implement for your compiler"
936 #endif
937 }
938
939 #if !KJ_NO_EXCEPTIONS
940
941 namespace {
942
943 KJ_THREADLOCAL_PTR(ExceptionImpl) currentException = nullptr;
944
945 } // namespace
946
947 class ExceptionImpl: public Exception, public std::exception {
948 public:
949 inline ExceptionImpl(Exception&& other): Exception(mv(other)) {
950 insertIntoCurrentExceptions();
951 }
952 ExceptionImpl(const ExceptionImpl& other): Exception(other) {
953 // No need to copy whatBuffer since it's just to hold the return value of what().
954 insertIntoCurrentExceptions();
955 }
956 ~ExceptionImpl() {
957 // Look for ourselves in the list.
958 for (auto* ptr = &currentException; *ptr != nullptr; ptr = &(*ptr)->nextCurrentException) {
959 if (*ptr == this) {
960 *ptr = nextCurrentException;
961 return;
962 }
963 }
964
965 // Possibly the ExceptionImpl was destroyed on a different thread than created it? That's
966 // pretty bad, we'd better abort.
967 abort();
968 }
969
970 const char* what() const noexcept override;
971
972 private:
973 mutable String whatBuffer;
974 ExceptionImpl* nextCurrentException = nullptr;
975
976 void insertIntoCurrentExceptions() {
977 nextCurrentException = currentException;
978 currentException = this;
979 }
980
981 friend class InFlightExceptionIterator;
982 };
983
984 const char* ExceptionImpl::what() const noexcept {
985 whatBuffer = str(*this);
986 return whatBuffer.begin();
987 }
988
989 InFlightExceptionIterator::InFlightExceptionIterator()
990 : ptr(currentException) {}
991
992 Maybe<const Exception&> InFlightExceptionIterator::next() {
993 if (ptr == nullptr) return nullptr;
994
995 const ExceptionImpl& result = *static_cast<const ExceptionImpl*>(ptr);
996 ptr = result.nextCurrentException;
997 return result;
998 }
999
1000 #endif // !KJ_NO_EXCEPTIONS
1001
1002 kj::Exception getDestructionReason(void* traceSeparator, kj::Exception::Type defaultType,
1003 const char* defaultFile, int defaultLine, kj::StringPtr defaultDescription) {
1004 #if !KJ_NO_EXCEPTIONS
1005 InFlightExceptionIterator iter;
1006 KJ_IF_MAYBE(e, iter.next()) {
1007 auto copy = kj::cp(*e);
1008 copy.truncateCommonTrace();
1009 return copy;
1010 } else {
1011 #endif
1012 // Darn, use a generic exception.
1013 kj::Exception exception(defaultType, defaultFile, defaultLine,
1014 kj::heapString(defaultDescription));
1015
1016 // Let's give some context on where the PromiseFulfiller was destroyed.
1017 exception.extendTrace(2, 16);
1018
1019 // Add a separator that hopefully makes this understandable...
1020 exception.addTrace(traceSeparator);
1021
1022 return exception;
1023 #if !KJ_NO_EXCEPTIONS
1024 }
1025 #endif
1026 }
1027
1028 // =======================================================================================
1029
1030 namespace {
1031
1032 KJ_THREADLOCAL_PTR(ExceptionCallback) threadLocalCallback = nullptr;
1033
1034 } // namespace
1035
1036 void requireOnStack(void* ptr, kj::StringPtr description) {
1037 #if defined(FUZZING_BUILD_MODE_UNSAFE_FOR_PRODUCTION) || \
1038 KJ_HAS_COMPILER_FEATURE(address_sanitizer) || \
1039 KJ_HAS_COMPILER_FEATURE(hwaddress_sanitizer) || \
1040 defined(__SANITIZE_ADDRESS__)
1041 // When using libfuzzer or ASAN, this sanity check may spurriously fail, so skip it.
1042 #else
1043 char stackVar;
1044 ptrdiff_t offset = reinterpret_cast<char*>(ptr) - &stackVar;
1045 KJ_REQUIRE(offset < 65536 && offset > -65536,
1046 kj::str(description));
1047 #endif
1048 }
1049
1050 ExceptionCallback::ExceptionCallback(): next(getExceptionCallback()) {
1051 requireOnStack(this, "ExceptionCallback must be allocated on the stack.");
1052 threadLocalCallback = this;
1053 }
1054
1055 ExceptionCallback::ExceptionCallback(ExceptionCallback& next): next(next) {}
1056
1057 ExceptionCallback::~ExceptionCallback() noexcept(false) {
1058 if (&next != this) {
1059 threadLocalCallback = &next;
1060 }
1061 }
1062
1063 void ExceptionCallback::onRecoverableException(Exception&& exception) {
1064 next.onRecoverableException(mv(exception));
1065 }
1066
1067 void ExceptionCallback::onFatalException(Exception&& exception) {
1068 next.onFatalException(mv(exception));
1069 }
1070
1071 void ExceptionCallback::logMessage(
1072 LogSeverity severity, const char* file, int line, int contextDepth, String&& text) {
1073 next.logMessage(severity, file, line, contextDepth, mv(text));
1074 }
1075
1076 ExceptionCallback::StackTraceMode ExceptionCallback::stackTraceMode() {
1077 return next.stackTraceMode();
1078 }
1079
1080 Function<void(Function<void()>)> ExceptionCallback::getThreadInitializer() {
1081 return next.getThreadInitializer();
1082 }
1083
1084 namespace _ { // private
1085 uint uncaughtExceptionCount(); // defined later in this file
1086 }
1087
1088 class ExceptionCallback::RootExceptionCallback: public ExceptionCallback {
1089 public:
1090 RootExceptionCallback(): ExceptionCallback(*this) {}
1091
1092 void onRecoverableException(Exception&& exception) override {
1093 #if KJ_NO_EXCEPTIONS
1094 logException(LogSeverity::ERROR, mv(exception));
1095 #else
1096 if (_::uncaughtExceptionCount() > 0) {
1097 // Bad time to throw an exception. Just log instead.
1098 //
1099 // TODO(someday): We should really compare uncaughtExceptionCount() against the count at
1100 // the innermost runCatchingExceptions() frame in this thread to tell if exceptions are
1101 // being caught correctly.
1102 logException(LogSeverity::ERROR, mv(exception));
1103 } else {
1104 throw ExceptionImpl(mv(exception));
1105 }
1106 #endif
1107 }
1108
1109 void onFatalException(Exception&& exception) override {
1110 #if KJ_NO_EXCEPTIONS
1111 logException(LogSeverity::FATAL, mv(exception));
1112 #else
1113 throw ExceptionImpl(mv(exception));
1114 #endif
1115 }
1116
1117 void logMessage(LogSeverity severity, const char* file, int line, int contextDepth,
1118 String&& text) override {
1119 text = str(kj::repeat('_', contextDepth), file, ":", line, ": ", severity, ": ",
1120 mv(text), '\n');
1121
1122 StringPtr textPtr = text;
1123
1124 while (textPtr != nullptr) {
1125 miniposix::ssize_t n = miniposix::write(STDERR_FILENO, textPtr.begin(), textPtr.size());
1126 if (n <= 0) {
1127 // stderr is broken. Give up.
1128 return;
1129 }
1130 textPtr = textPtr.slice(n);
1131 }
1132 }
1133
1134 StackTraceMode stackTraceMode() override {
1135 #ifdef KJ_DEBUG
1136 return StackTraceMode::FULL;
1137 #else
1138 return StackTraceMode::ADDRESS_ONLY;
1139 #endif
1140 }
1141
1142 Function<void(Function<void()>)> getThreadInitializer() override {
1143 return [](Function<void()> func) {
1144 // No initialization needed since RootExceptionCallback is automatically the root callback
1145 // for new threads.
1146 func();
1147 };
1148 }
1149
1150 private:
1151 void logException(LogSeverity severity, Exception&& e) {
1152 // We intentionally go back to the top exception callback on the stack because we don't want to
1153 // bypass whatever log processing is in effect.
1154 //
1155 // We intentionally don't log the context since it should get re-added by the exception callback
1156 // anyway.
1157 getExceptionCallback().logMessage(severity, e.getFile(), e.getLine(), 0, str(
1158 e.getType(), e.getDescription() == nullptr ? "" : ": ", e.getDescription(),
1159 e.getRemoteTrace().size() > 0 ? "\nremote: " : "",
1160 e.getRemoteTrace(),
1161 e.getStackTrace().size() > 0 ? "\nstack: " : "",
1162 stringifyStackTraceAddresses(e.getStackTrace()),
1163 stringifyStackTrace(e.getStackTrace()), "\n"));
1164 }
1165 };
1166
1167 ExceptionCallback& getExceptionCallback() {
1168 static auto defaultCallback = lsanIgnoreObjectAndReturn(
1169 new ExceptionCallback::RootExceptionCallback());
1170 // We allocate on the heap because some objects may throw in their destructors. If those objects
1171 // had static storage, they might get fully constructed before the root callback. If they however
1172 // then throw an exception during destruction, there would be a lifetime issue because their
1173 // destructor would end up getting registered after the root callback's destructor. One solution
1174 // is to just leak this pointer & allocate on first-use. The cost is that the initialization is
1175 // mildly more expensive (+ we need to annotate sanitizers to ignore the problem). A great
1176 // compiler annotation that would simply things would be one that allowed static variables to have
1177 // their destruction omitted wholesale. That would allow us to avoid the heap but still have the
1178 // same robust safety semantics leaking would give us. A practical alternative that could be
1179 // implemented without new compilers would be to define another static root callback in
1180 // RootExceptionCallback's destructor (+ a separate pointer to share its value with this
1181 // function). Since this would end up getting constructed during exit unwind, it would have the
1182 // nice property of effectively being guaranteed to be evicted last.
1183 //
1184 // All this being said, I came back to leaking the object is the easiest tweak here:
1185 // * Can't go wrong
1186 // * Easy to maintain
1187 // * Throwing exceptions is bound to do be expensive and malloc-happy anyway, so the incremental
1188 // cost of 1 heap allocation is minimal.
1189 //
1190 // TODO(cleanup): Harris has an excellent suggestion in
1191 // https://github.com/capnproto/capnproto/pull/1255 that should ensure we initialize the root
1192 // callback once on first use as a global & never destroy it.
1193
1194 ExceptionCallback* scoped = threadLocalCallback;
1195 return scoped != nullptr ? *scoped : *defaultCallback;
1196 }
1197
1198 void throwFatalException(kj::Exception&& exception, uint ignoreCount) {
1199 if (ignoreCount != (uint)kj::maxValue) exception.extendTrace(ignoreCount + 1);
1200 getExceptionCallback().onFatalException(kj::mv(exception));
1201 abort();
1202 }
1203
1204 void throwRecoverableException(kj::Exception&& exception, uint ignoreCount) {
1205 if (ignoreCount != (uint)kj::maxValue) exception.extendTrace(ignoreCount + 1);
1206 getExceptionCallback().onRecoverableException(kj::mv(exception));
1207 }
1208
1209 // =======================================================================================
1210
1211 namespace _ { // private
1212
1213 #if KJ_CPP_STD >= 201703L
1214
1215 uint uncaughtExceptionCount() {
1216 return std::uncaught_exceptions();
1217 }
1218
1219 #elif __GNUC__
1220
1221 // Horrible -- but working -- hack: We can dig into __cxa_get_globals() in order to extract the
1222 // count of uncaught exceptions. This function is part of the C++ ABI implementation used on Linux,
1223 // OSX, and probably other platforms that use GCC. Unfortunately, __cxa_get_globals() is only
1224 // actually defined in cxxabi.h on some platforms (e.g. Linux, but not OSX), and even where it is
1225 // defined, it returns an incomplete type. Here we use the same hack used by Evgeny Panasyuk:
1226 // https://github.com/panaseleus/stack_unwinding/blob/master/boost/exception/uncaught_exception_count.hpp
1227 //
1228 // Notice that a similar hack is possible on MSVC -- if its C++11 support ever gets to the point of
1229 // supporting KJ in the first place.
1230 //
1231 // It appears likely that a future version of the C++ standard may include an
1232 // uncaught_exception_count() function in the standard library, or an equivalent language feature.
1233 // Some discussion:
1234 // https://groups.google.com/a/isocpp.org/d/msg/std-proposals/HglEslyZFYs/kKdu5jJw5AgJ
1235
1236 struct FakeEhGlobals {
1237 // Fake
1238
1239 void* caughtExceptions;
1240 uint uncaughtExceptions;
1241 };
1242
1243 // LLVM's libstdc++ doesn't declare __cxa_get_globals in its cxxabi.h. GNU does. Because it is
1244 // extern "C", the compiler wills get upset if we re-declare it even in a different namespace.
1245 #if _LIBCPPABI_VERSION
1246 extern "C" void* __cxa_get_globals();
1247 #else
1248 using abi::__cxa_get_globals;
1249 #endif
1250
1251 uint uncaughtExceptionCount() {
1252 return reinterpret_cast<FakeEhGlobals*>(__cxa_get_globals())->uncaughtExceptions;
1253 }
1254
1255 #elif _MSC_VER
1256
1257 #if _MSC_VER >= 1900
1258 // MSVC14 has a refactored CRT which now provides a direct accessor for this value.
1259 // See https://svn.boost.org/trac/boost/ticket/10158 for a brief discussion.
1260 extern "C" int *__cdecl __processing_throw();
1261
1262 uint uncaughtExceptionCount() {
1263 return static_cast<uint>(*__processing_throw());
1264 }
1265
1266 #elif _MSC_VER >= 1400
1267 // The below was copied from:
1268 // https://github.com/panaseleus/stack_unwinding/blob/master/boost/exception/uncaught_exception_count.hpp
1269
1270 extern "C" char *__cdecl _getptd();
1271
1272 uint uncaughtExceptionCount() {
1273 return *reinterpret_cast<uint*>(_getptd() + (sizeof(void*) == 8 ? 0x100 : 0x90));
1274 }
1275 #else
1276 uint uncaughtExceptionCount() {
1277 // Since the above doesn't work, fall back to uncaught_exception(). This will produce incorrect
1278 // results in very obscure cases that Cap'n Proto doesn't really rely on anyway.
1279 return std::uncaught_exception();
1280 }
1281 #endif
1282
1283 #else
1284 #error "This needs to be ported to your compiler / C++ ABI."
1285 #endif
1286
1287 } // namespace _ (private)
1288
1289 UnwindDetector::UnwindDetector(): uncaughtCount(_::uncaughtExceptionCount()) {}
1290
1291 bool UnwindDetector::isUnwinding() const {
1292 return _::uncaughtExceptionCount() > uncaughtCount;
1293 }
1294
1295 #if !KJ_NO_EXCEPTIONS
1296 void UnwindDetector::catchThrownExceptionAsSecondaryFault() const {
1297 // TODO(someday): Attach the secondary exception to whatever primary exception is causing
1298 // the unwind. For now we just drop it on the floor as this is probably fine most of the
1299 // time.
1300 getCaughtExceptionAsKj();
1301 }
1302 #endif
1303
1304 #if __GNUC__ && !KJ_NO_RTTI
1305 static kj::String demangleTypeName(const char* name) {
1306 if (name == nullptr) return kj::heapString("(nil)");
1307
1308 int status;
1309 char* buf = abi::__cxa_demangle(name, nullptr, nullptr, &status);
1310 kj::String result = kj::heapString(buf == nullptr ? name : buf);
1311 free(buf);
1312 return kj::mv(result);
1313 }
1314
1315 kj::String getCaughtExceptionType() {
1316 return demangleTypeName(abi::__cxa_current_exception_type()->name());
1317 }
1318 #else
1319 kj::String getCaughtExceptionType() {
1320 return kj::heapString("(unknown)");
1321 }
1322 #endif
1323
1324 namespace {
1325
1326 size_t sharedSuffixLength(kj::ArrayPtr<void* const> a, kj::ArrayPtr<void* const> b) {
1327 size_t result = 0;
1328 while (a.size() > 0 && b.size() > 0 && a.back() == b.back()) {
1329 ++result;
1330 a = a.slice(0, a.size() - 1);
1331 b = b.slice(0, b.size() - 1);
1332 }
1333 return result;
1334 }
1335
1336 } // namespace
1337
1338 kj::ArrayPtr<void* const> computeRelativeTrace(
1339 kj::ArrayPtr<void* const> trace, kj::ArrayPtr<void* const> relativeTo) {
1340 using miniposix::ssize_t;
1341
1342 static constexpr size_t MIN_MATCH_LEN = 4;
1343 if (trace.size() < MIN_MATCH_LEN || relativeTo.size() < MIN_MATCH_LEN) {
1344 return trace;
1345 }
1346
1347 kj::ArrayPtr<void* const> bestMatch = trace;
1348 uint bestMatchLen = MIN_MATCH_LEN - 1; // must beat this to choose something else
1349
1350 // `trace` and `relativeTrace` may have been truncated at different points. We iterate through
1351 // truncating various suffixes from one of the two and then seeing if the remaining suffixes
1352 // match.
1353 for (ssize_t i = -(ssize_t)(trace.size() - MIN_MATCH_LEN);
1354 i <= (ssize_t)(relativeTo.size() - MIN_MATCH_LEN);
1355 i++) {
1356 // Negative values truncate `trace`, positive values truncate `relativeTo`.
1357 kj::ArrayPtr<void* const> subtrace = trace.slice(0, trace.size() - kj::max<ssize_t>(0, -i));
1358 kj::ArrayPtr<void* const> subrt = relativeTo
1359 .slice(0, relativeTo.size() - kj::max<ssize_t>(0, i));
1360
1361 uint matchLen = sharedSuffixLength(subtrace, subrt);
1362 if (matchLen > bestMatchLen) {
1363 bestMatchLen = matchLen;
1364 bestMatch = subtrace.slice(0, subtrace.size() - matchLen + 1);
1365 }
1366 }
1367
1368 return bestMatch;
1369 }
1370
1371 #if KJ_NO_EXCEPTIONS
1372
1373 namespace _ { // private
1374
1375 class RecoverableExceptionCatcher: public ExceptionCallback {
1376 // Catches a recoverable exception without using try/catch. Used when compiled with
1377 // -fno-exceptions.
1378
1379 public:
1380 virtual ~RecoverableExceptionCatcher() noexcept(false) {}
1381
1382 void onRecoverableException(Exception&& exception) override {
1383 if (caught == nullptr) {
1384 caught = mv(exception);
1385 } else {
1386 // TODO(someday): Consider it a secondary fault?
1387 }
1388 }
1389
1390 Maybe<Exception> caught;
1391 };
1392
1393 Maybe<Exception> runCatchingExceptions(Runnable& runnable) {
1394 RecoverableExceptionCatcher catcher;
1395 runnable.run();
1396 KJ_IF_MAYBE(e, catcher.caught) {
1397 e->truncateCommonTrace();
1398 }
1399 return mv(catcher.caught);
1400 }
1401
1402 } // namespace _ (private)
1403
1404 #else // KJ_NO_EXCEPTIONS
1405
1406 kj::Exception getCaughtExceptionAsKj() {
1407 try {
1408 throw;
1409 } catch (Exception& e) {
1410 e.truncateCommonTrace();
1411 return kj::mv(e);
1412 } catch (CanceledException) {
1413 throw;
1414 } catch (std::bad_alloc& e) {
1415 return Exception(Exception::Type::OVERLOADED,
1416 "(unknown)", -1, str("std::bad_alloc: ", e.what()));
1417 } catch (std::exception& e) {
1418 return Exception(Exception::Type::FAILED,
1419 "(unknown)", -1, str("std::exception: ", e.what()));
1420 } catch (TopLevelProcessContext::CleanShutdownException) {
1421 throw;
1422 } catch (...) {
1423 #if __GNUC__ && !KJ_NO_RTTI
1424 return Exception(Exception::Type::FAILED, "(unknown)", -1, str(
1425 "unknown non-KJ exception of type: ", getCaughtExceptionType()));
1426 #else
1427 return Exception(Exception::Type::FAILED, "(unknown)", -1, str("unknown non-KJ exception"));
1428 #endif
1429 }
1430 }
1431 #endif // !KJ_NO_EXCEPTIONS
1432
1433 } // namespace kj