LLVM 19.0.0git
Signals.inc
Go to the documentation of this file.
1//===- Win32/Signals.cpp - Win32 Signals Implementation ---------*- C++ -*-===//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//
7//===----------------------------------------------------------------------===//
8//
9// This file provides the Win32 specific implementation of the Signals class.
10//
11//===----------------------------------------------------------------------===//
15#include "llvm/Support/Path.h"
18#include <algorithm>
19#include <io.h>
20#include <signal.h>
21#include <stdio.h>
22
23#include "llvm/Support/Format.h"
25
26// The Windows.h header must be after LLVM and standard headers.
28
29#ifdef __MINGW32__
30#include <imagehlp.h>
31#else
32#include <crtdbg.h>
33#include <dbghelp.h>
34#endif
35#include <psapi.h>
36
37#ifdef _MSC_VER
38#pragma comment(lib, "psapi.lib")
39#elif __MINGW32__
40// The version of g++ that comes with MinGW does *not* properly understand
41// the ll format specifier for printf. However, MinGW passes the format
42// specifiers on to the MSVCRT entirely, and the CRT understands the ll
43// specifier. So these warnings are spurious in this case. Since we compile
44// with -Wall, this will generate these warnings which should be ignored. So
45// we will turn off the warnings for this just file. However, MinGW also does
46// not support push and pop for diagnostics, so we have to manually turn it
47// back on at the end of the file.
48#pragma GCC diagnostic ignored "-Wformat"
49#pragma GCC diagnostic ignored "-Wformat-extra-args"
50
51#if !defined(__MINGW64_VERSION_MAJOR)
52// MinGW.org does not have updated support for the 64-bit versions of the
53// DebugHlp APIs. So we will have to load them manually. The structures and
54// method signatures were pulled from DbgHelp.h in the Windows Platform SDK,
55// and adjusted for brevity.
56typedef struct _IMAGEHLP_LINE64 {
57 DWORD SizeOfStruct;
58 PVOID Key;
59 DWORD LineNumber;
60 PCHAR FileName;
61 DWORD64 Address;
62} IMAGEHLP_LINE64, *PIMAGEHLP_LINE64;
63
64typedef struct _IMAGEHLP_SYMBOL64 {
65 DWORD SizeOfStruct;
66 DWORD64 Address;
67 DWORD Size;
69 DWORD MaxNameLength;
70 CHAR Name[1];
71} IMAGEHLP_SYMBOL64, *PIMAGEHLP_SYMBOL64;
72
73typedef struct _tagADDRESS64 {
74 DWORD64 Offset;
75 WORD Segment;
76 ADDRESS_MODE Mode;
77} ADDRESS64, *LPADDRESS64;
78
79typedef struct _KDHELP64 {
80 DWORD64 Thread;
81 DWORD ThCallbackStack;
82 DWORD ThCallbackBStore;
83 DWORD NextCallback;
84 DWORD FramePointer;
85 DWORD64 KiCallUserMode;
86 DWORD64 KeUserCallbackDispatcher;
87 DWORD64 SystemRangeStart;
88 DWORD64 KiUserExceptionDispatcher;
89 DWORD64 StackBase;
90 DWORD64 StackLimit;
91 DWORD64 Reserved[5];
92} KDHELP64, *PKDHELP64;
93
94typedef struct _tagSTACKFRAME64 {
95 ADDRESS64 AddrPC;
96 ADDRESS64 AddrReturn;
97 ADDRESS64 AddrFrame;
98 ADDRESS64 AddrStack;
99 ADDRESS64 AddrBStore;
100 PVOID FuncTableEntry;
101 DWORD64 Params[4];
102 BOOL Far;
103 BOOL Virtual;
104 DWORD64 Reserved[3];
105 KDHELP64 KdHelp;
106} STACKFRAME64, *LPSTACKFRAME64;
107#endif // !defined(__MINGW64_VERSION_MAJOR)
108#endif // __MINGW32__
109
110typedef BOOL(__stdcall *PREAD_PROCESS_MEMORY_ROUTINE64)(
111 HANDLE hProcess, DWORD64 qwBaseAddress, PVOID lpBuffer, DWORD nSize,
112 LPDWORD lpNumberOfBytesRead);
113
114typedef PVOID(__stdcall *PFUNCTION_TABLE_ACCESS_ROUTINE64)(HANDLE ahProcess,
115 DWORD64 AddrBase);
116
117typedef DWORD64(__stdcall *PGET_MODULE_BASE_ROUTINE64)(HANDLE hProcess,
118 DWORD64 Address);
119
120typedef DWORD64(__stdcall *PTRANSLATE_ADDRESS_ROUTINE64)(HANDLE hProcess,
121 HANDLE hThread,
122 LPADDRESS64 lpaddr);
123
124typedef BOOL(WINAPI *fpMiniDumpWriteDump)(HANDLE, DWORD, HANDLE, MINIDUMP_TYPE,
125 PMINIDUMP_EXCEPTION_INFORMATION,
126 PMINIDUMP_USER_STREAM_INFORMATION,
127 PMINIDUMP_CALLBACK_INFORMATION);
128static fpMiniDumpWriteDump fMiniDumpWriteDump;
129
130typedef BOOL(WINAPI *fpStackWalk64)(DWORD, HANDLE, HANDLE, LPSTACKFRAME64,
131 PVOID, PREAD_PROCESS_MEMORY_ROUTINE64,
132 PFUNCTION_TABLE_ACCESS_ROUTINE64,
133 PGET_MODULE_BASE_ROUTINE64,
134 PTRANSLATE_ADDRESS_ROUTINE64);
135static fpStackWalk64 fStackWalk64;
136
137typedef DWORD64(WINAPI *fpSymGetModuleBase64)(HANDLE, DWORD64);
138static fpSymGetModuleBase64 fSymGetModuleBase64;
139
140typedef BOOL(WINAPI *fpSymGetSymFromAddr64)(HANDLE, DWORD64, PDWORD64,
141 PIMAGEHLP_SYMBOL64);
142static fpSymGetSymFromAddr64 fSymGetSymFromAddr64;
143
144typedef BOOL(WINAPI *fpSymGetLineFromAddr64)(HANDLE, DWORD64, PDWORD,
145 PIMAGEHLP_LINE64);
146static fpSymGetLineFromAddr64 fSymGetLineFromAddr64;
147
148typedef BOOL(WINAPI *fpSymGetModuleInfo64)(HANDLE hProcess, DWORD64 dwAddr,
149 PIMAGEHLP_MODULE64 ModuleInfo);
150static fpSymGetModuleInfo64 fSymGetModuleInfo64;
151
152typedef PVOID(WINAPI *fpSymFunctionTableAccess64)(HANDLE, DWORD64);
153static fpSymFunctionTableAccess64 fSymFunctionTableAccess64;
154
155typedef DWORD(WINAPI *fpSymSetOptions)(DWORD);
156static fpSymSetOptions fSymSetOptions;
157
158typedef BOOL(WINAPI *fpSymInitialize)(HANDLE, PCSTR, BOOL);
159static fpSymInitialize fSymInitialize;
160
161typedef BOOL(WINAPI *fpEnumerateLoadedModules)(HANDLE,
162 PENUMLOADED_MODULES_CALLBACK64,
163 PVOID);
164static fpEnumerateLoadedModules fEnumerateLoadedModules;
165
166static bool isDebugHelpInitialized() {
167 return fStackWalk64 && fSymInitialize && fSymSetOptions && fMiniDumpWriteDump;
168}
169
170static bool load64BitDebugHelp(void) {
171 HMODULE hLib =
172 ::LoadLibraryExA("Dbghelp.dll", NULL, LOAD_LIBRARY_SEARCH_SYSTEM32);
173 if (hLib) {
174 fMiniDumpWriteDump =
175 (fpMiniDumpWriteDump)::GetProcAddress(hLib, "MiniDumpWriteDump");
176 fStackWalk64 = (fpStackWalk64)::GetProcAddress(hLib, "StackWalk64");
177 fSymGetModuleBase64 =
178 (fpSymGetModuleBase64)::GetProcAddress(hLib, "SymGetModuleBase64");
179 fSymGetSymFromAddr64 =
180 (fpSymGetSymFromAddr64)::GetProcAddress(hLib, "SymGetSymFromAddr64");
181 fSymGetLineFromAddr64 =
182 (fpSymGetLineFromAddr64)::GetProcAddress(hLib, "SymGetLineFromAddr64");
183 fSymGetModuleInfo64 =
184 (fpSymGetModuleInfo64)::GetProcAddress(hLib, "SymGetModuleInfo64");
185 fSymFunctionTableAccess64 = (fpSymFunctionTableAccess64)::GetProcAddress(
186 hLib, "SymFunctionTableAccess64");
187 fSymSetOptions = (fpSymSetOptions)::GetProcAddress(hLib, "SymSetOptions");
188 fSymInitialize = (fpSymInitialize)::GetProcAddress(hLib, "SymInitialize");
189 fEnumerateLoadedModules = (fpEnumerateLoadedModules)::GetProcAddress(
190 hLib, "EnumerateLoadedModules64");
191 }
192 return isDebugHelpInitialized();
193}
194
195using namespace llvm;
196
197// Forward declare.
198static LONG WINAPI LLVMUnhandledExceptionFilter(LPEXCEPTION_POINTERS ep);
199static BOOL WINAPI LLVMConsoleCtrlHandler(DWORD dwCtrlType);
200
201// The function to call if ctrl-c is pressed.
202static void (*InterruptFunction)() = 0;
203
204static std::vector<std::string> *FilesToRemove = NULL;
205static bool RegisteredUnhandledExceptionFilter = false;
206static bool CleanupExecuted = false;
207static PTOP_LEVEL_EXCEPTION_FILTER OldFilter = NULL;
208
209/// The function to call on "SIGPIPE" (one-time use only).
210static std::atomic<void (*)()> OneShotPipeSignalFunction(nullptr);
211
212// Windows creates a new thread to execute the console handler when an event
213// (such as CTRL/C) occurs. This causes concurrency issues with the above
214// globals which this critical section addresses.
215static CRITICAL_SECTION CriticalSection;
216static bool CriticalSectionInitialized = false;
217
218static StringRef Argv0;
219
220enum {
221#if defined(_M_X64)
222 NativeMachineType = IMAGE_FILE_MACHINE_AMD64
223#elif defined(_M_ARM64)
224 NativeMachineType = IMAGE_FILE_MACHINE_ARM64
225#elif defined(_M_IX86)
226 NativeMachineType = IMAGE_FILE_MACHINE_I386
227#elif defined(_M_ARM)
228 NativeMachineType = IMAGE_FILE_MACHINE_ARMNT
229#else
230 NativeMachineType = IMAGE_FILE_MACHINE_UNKNOWN
231#endif
232};
233
234static bool printStackTraceWithLLVMSymbolizer(llvm::raw_ostream &OS,
235 HANDLE hProcess, HANDLE hThread,
236 STACKFRAME64 &StackFrameOrig,
237 CONTEXT *ContextOrig) {
238 // StackWalk64 modifies the incoming stack frame and context, so copy them.
239 STACKFRAME64 StackFrame = StackFrameOrig;
240
241 // Copy the register context so that we don't modify it while we unwind. We
242 // could use InitializeContext + CopyContext, but that's only required to get
243 // at AVX registers, which typically aren't needed by StackWalk64. Reduce the
244 // flag set to indicate that there's less data.
245 CONTEXT Context = *ContextOrig;
246 Context.ContextFlags = CONTEXT_CONTROL | CONTEXT_INTEGER;
247
248 static void *StackTrace[256];
249 size_t Depth = 0;
250 while (fStackWalk64(NativeMachineType, hProcess, hThread, &StackFrame,
251 &Context, 0, fSymFunctionTableAccess64,
252 fSymGetModuleBase64, 0)) {
253 if (StackFrame.AddrFrame.Offset == 0)
254 break;
255 StackTrace[Depth++] = (void *)(uintptr_t)StackFrame.AddrPC.Offset;
256 if (Depth >= std::size(StackTrace))
257 break;
258 }
259
260 return printSymbolizedStackTrace(Argv0, &StackTrace[0], Depth, OS);
261}
262
263namespace {
264struct FindModuleData {
265 void **StackTrace;
266 int Depth;
267 const char **Modules;
268 intptr_t *Offsets;
269 StringSaver *StrPool;
270};
271} // namespace
272
273static BOOL CALLBACK findModuleCallback(PCSTR ModuleName, DWORD64 ModuleBase,
274 ULONG ModuleSize, void *VoidData) {
275 FindModuleData *Data = (FindModuleData *)VoidData;
276 intptr_t Beg = ModuleBase;
277 intptr_t End = Beg + ModuleSize;
278 for (int I = 0; I < Data->Depth; I++) {
279 if (Data->Modules[I])
280 continue;
281 intptr_t Addr = (intptr_t)Data->StackTrace[I];
282 if (Beg <= Addr && Addr < End) {
283 Data->Modules[I] = Data->StrPool->save(ModuleName).data();
284 Data->Offsets[I] = Addr - Beg;
285 }
286 }
287 return TRUE;
288}
289
290static bool findModulesAndOffsets(void **StackTrace, int Depth,
291 const char **Modules, intptr_t *Offsets,
292 const char *MainExecutableName,
293 StringSaver &StrPool) {
294 if (!fEnumerateLoadedModules)
295 return false;
296 FindModuleData Data;
297 Data.StackTrace = StackTrace;
298 Data.Depth = Depth;
299 Data.Modules = Modules;
300 Data.Offsets = Offsets;
301 Data.StrPool = &StrPool;
302 fEnumerateLoadedModules(GetCurrentProcess(), findModuleCallback, &Data);
303 return true;
304}
305
307 const char *MainExecutableName) {
308 return false;
309}
310
311static void PrintStackTraceForThread(llvm::raw_ostream &OS, HANDLE hProcess,
312 HANDLE hThread, STACKFRAME64 &StackFrame,
313 CONTEXT *Context) {
314 // It's possible that DbgHelp.dll hasn't been loaded yet (e.g. if this
315 // function is called before the main program called `llvm::InitLLVM`).
316 // In this case just return, not stacktrace will be printed.
317 if (!isDebugHelpInitialized())
318 return;
319
320 // Initialize the symbol handler.
321 fSymSetOptions(SYMOPT_DEFERRED_LOADS | SYMOPT_LOAD_LINES);
322 fSymInitialize(hProcess, NULL, TRUE);
323
324 // Try llvm-symbolizer first. llvm-symbolizer knows how to deal with both PDBs
325 // and DWARF, so it should do a good job regardless of what debug info or
326 // linker is in use.
327 if (printStackTraceWithLLVMSymbolizer(OS, hProcess, hThread, StackFrame,
328 Context)) {
329 return;
330 }
331
332 while (true) {
333 if (!fStackWalk64(NativeMachineType, hProcess, hThread, &StackFrame,
334 Context, 0, fSymFunctionTableAccess64,
335 fSymGetModuleBase64, 0)) {
336 break;
337 }
338
339 if (StackFrame.AddrFrame.Offset == 0)
340 break;
341
342 using namespace llvm;
343 // Print the PC in hexadecimal.
344 DWORD64 PC = StackFrame.AddrPC.Offset;
345#if defined(_M_X64) || defined(_M_ARM64)
346 OS << format("0x%016llX", PC);
347#elif defined(_M_IX86) || defined(_M_ARM)
348 OS << format("0x%08lX", static_cast<DWORD>(PC));
349#endif
350
351 // Verify the PC belongs to a module in this process.
352 if (!fSymGetModuleBase64(hProcess, PC)) {
353 OS << " <unknown module>\n";
354 continue;
355 }
356
357 IMAGEHLP_MODULE64 M;
358 memset(&M, 0, sizeof(IMAGEHLP_MODULE64));
359 M.SizeOfStruct = sizeof(IMAGEHLP_MODULE64);
360 if (fSymGetModuleInfo64(hProcess, fSymGetModuleBase64(hProcess, PC), &M)) {
361 DWORD64 const disp = PC - M.BaseOfImage;
362 OS << format(", %s(0x%016llX) + 0x%llX byte(s)",
363 static_cast<char *>(M.ImageName), M.BaseOfImage,
364 static_cast<long long>(disp));
365 } else {
366 OS << ", <unknown module>";
367 }
368
369 // Print the symbol name.
370 char buffer[512];
371 IMAGEHLP_SYMBOL64 *symbol = reinterpret_cast<IMAGEHLP_SYMBOL64 *>(buffer);
372 memset(symbol, 0, sizeof(IMAGEHLP_SYMBOL64));
373 symbol->SizeOfStruct = sizeof(IMAGEHLP_SYMBOL64);
374 symbol->MaxNameLength = 512 - sizeof(IMAGEHLP_SYMBOL64);
375
376 DWORD64 dwDisp;
377 if (!fSymGetSymFromAddr64(hProcess, PC, &dwDisp, symbol)) {
378 OS << '\n';
379 continue;
380 }
381
382 buffer[511] = 0;
383 OS << format(", %s() + 0x%llX byte(s)", static_cast<char *>(symbol->Name),
384 static_cast<long long>(dwDisp));
385
386 // Print the source file and line number information.
387 IMAGEHLP_LINE64 line = {};
388 DWORD dwLineDisp;
389 line.SizeOfStruct = sizeof(line);
390 if (fSymGetLineFromAddr64(hProcess, PC, &dwLineDisp, &line)) {
391 OS << format(", %s, line %lu + 0x%lX byte(s)", line.FileName,
392 line.LineNumber, dwLineDisp);
393 }
394
395 OS << '\n';
396 }
397}
398
399namespace llvm {
400
401//===----------------------------------------------------------------------===//
402//=== WARNING: Implementation here must contain only Win32 specific code
403//=== and must not be UNIX code
404//===----------------------------------------------------------------------===//
405
406#ifdef _MSC_VER
407/// Emulates hitting "retry" from an "abort, retry, ignore" CRT debug report
408/// dialog. "retry" raises an exception which ultimately triggers our stack
409/// dumper.
410static LLVM_ATTRIBUTE_UNUSED int
411AvoidMessageBoxHook(int ReportType, char *Message, int *Return) {
412 // Set *Return to the retry code for the return value of _CrtDbgReport:
413 // http://msdn.microsoft.com/en-us/library/8hyw4sy7(v=vs.71).aspx
414 // This may also trigger just-in-time debugging via DebugBreak().
415 if (Return)
416 *Return = 1;
417 // Don't call _CrtDbgReport.
418 return TRUE;
419}
420
421#endif
422
423extern "C" void HandleAbort(int Sig) {
424 if (Sig == SIGABRT) {
426 }
427}
428
429static void InitializeThreading() {
430 if (CriticalSectionInitialized)
431 return;
432
433 // Now's the time to create the critical section. This is the first time
434 // through here, and there's only one thread.
435 InitializeCriticalSection(&CriticalSection);
436 CriticalSectionInitialized = true;
437}
438
439static void RegisterHandler() {
440 // If we cannot load up the APIs (which would be unexpected as they should
441 // exist on every version of Windows we support), we will bail out since
442 // there would be nothing to report.
443 if (!load64BitDebugHelp()) {
444 assert(false && "These APIs should always be available");
445 return;
446 }
447
448 if (RegisteredUnhandledExceptionFilter) {
449 EnterCriticalSection(&CriticalSection);
450 return;
451 }
452
453 InitializeThreading();
454
455 // Enter it immediately. Now if someone hits CTRL/C, the console handler
456 // can't proceed until the globals are updated.
457 EnterCriticalSection(&CriticalSection);
458
459 RegisteredUnhandledExceptionFilter = true;
460 OldFilter = SetUnhandledExceptionFilter(LLVMUnhandledExceptionFilter);
461 SetConsoleCtrlHandler(LLVMConsoleCtrlHandler, TRUE);
462
463 // IMPORTANT NOTE: Caller must call LeaveCriticalSection(&CriticalSection) or
464 // else multi-threading problems will ensue.
465}
466
467// The public API
468bool sys::RemoveFileOnSignal(StringRef Filename, std::string *ErrMsg) {
469 RegisterHandler();
470
471 if (CleanupExecuted) {
472 if (ErrMsg)
473 *ErrMsg = "Process terminating -- cannot register for removal";
474 return true;
475 }
476
477 if (FilesToRemove == NULL)
478 FilesToRemove = new std::vector<std::string>;
479
480 FilesToRemove->push_back(std::string(Filename));
481
482 LeaveCriticalSection(&CriticalSection);
483 return false;
484}
485
486// The public API
488 if (FilesToRemove == NULL)
489 return;
490
491 RegisterHandler();
492
493 std::vector<std::string>::reverse_iterator I =
494 find(reverse(*FilesToRemove), Filename);
495 if (I != FilesToRemove->rend())
496 FilesToRemove->erase(I.base() - 1);
497
498 LeaveCriticalSection(&CriticalSection);
499}
500
502 // Crash to stack trace handler on abort.
503 signal(SIGABRT, HandleAbort);
504
505 // The following functions are not reliably accessible on MinGW.
506#ifdef _MSC_VER
507 // We're already handling writing a "something went wrong" message.
508 _set_abort_behavior(0, _WRITE_ABORT_MSG);
509 // Disable Dr. Watson.
510 _set_abort_behavior(0, _CALL_REPORTFAULT);
511 _CrtSetReportHook(AvoidMessageBoxHook);
512#endif
513
514 // Disable standard error dialog box.
515 SetErrorMode(SEM_FAILCRITICALERRORS | SEM_NOGPFAULTERRORBOX |
516 SEM_NOOPENFILEERRORBOX);
517 _set_error_mode(_OUT_TO_STDERR);
518}
519
520/// When an error signal (such as SIGABRT or SIGSEGV) is delivered to the
521/// process, print a stack trace and then exit.
523 bool DisableCrashReporting) {
524 ::Argv0 = Argv0;
525
526 if (DisableCrashReporting || getenv("LLVM_DISABLE_CRASH_REPORT"))
528
530 RegisterHandler();
531 LeaveCriticalSection(&CriticalSection);
532}
533} // namespace llvm
534
535#if defined(__MINGW32__) && !defined(__MINGW64_VERSION_MAJOR)
536// Provide a prototype for RtlCaptureContext, mingw32 from mingw.org is
537// missing it but mingw-w64 has it.
538extern "C" VOID WINAPI RtlCaptureContext(PCONTEXT ContextRecord);
539#endif
540
541static void LocalPrintStackTrace(raw_ostream &OS, PCONTEXT C) {
542 STACKFRAME64 StackFrame{};
543 CONTEXT Context{};
544 if (!C) {
545 ::RtlCaptureContext(&Context);
546 C = &Context;
547 }
548#if defined(_M_X64)
549 StackFrame.AddrPC.Offset = Context.Rip;
550 StackFrame.AddrStack.Offset = Context.Rsp;
551 StackFrame.AddrFrame.Offset = Context.Rbp;
552#elif defined(_M_IX86)
553 StackFrame.AddrPC.Offset = Context.Eip;
554 StackFrame.AddrStack.Offset = Context.Esp;
555 StackFrame.AddrFrame.Offset = Context.Ebp;
556#elif defined(_M_ARM64)
557 StackFrame.AddrPC.Offset = Context.Pc;
558 StackFrame.AddrStack.Offset = Context.Sp;
559 StackFrame.AddrFrame.Offset = Context.Fp;
560#elif defined(_M_ARM)
561 StackFrame.AddrPC.Offset = Context.Pc;
562 StackFrame.AddrStack.Offset = Context.Sp;
563 StackFrame.AddrFrame.Offset = Context.R11;
564#endif
565 StackFrame.AddrPC.Mode = AddrModeFlat;
566 StackFrame.AddrStack.Mode = AddrModeFlat;
567 StackFrame.AddrFrame.Mode = AddrModeFlat;
568 PrintStackTraceForThread(OS, GetCurrentProcess(), GetCurrentThread(),
569 StackFrame, C);
570}
571
572void llvm::sys::PrintStackTrace(raw_ostream &OS, int Depth) {
573 // FIXME: Handle "Depth" parameter to print stack trace upto specified Depth
574 LocalPrintStackTrace(OS, nullptr);
575}
576
577void llvm::sys::SetInterruptFunction(void (*IF)()) {
578 RegisterHandler();
579 InterruptFunction = IF;
580 LeaveCriticalSection(&CriticalSection);
581}
582
583void llvm::sys::SetInfoSignalFunction(void (*Handler)()) {
584 // Unimplemented.
585}
586
587void llvm::sys::SetOneShotPipeSignalFunction(void (*Handler)()) {
588 OneShotPipeSignalFunction.exchange(Handler);
589}
590
592 llvm::sys::Process::Exit(EX_IOERR, /*NoCleanup=*/true);
593}
594
595void llvm::sys::CallOneShotPipeSignalHandler() {
596 if (auto OldOneShotPipeFunction = OneShotPipeSignalFunction.exchange(nullptr))
597 OldOneShotPipeFunction();
598}
599
600/// Add a function to be called when a signal is delivered to the process. The
601/// handler can have a cookie passed to it to identify what instance of the
602/// handler it is.
604 void *Cookie) {
605 insertSignalHandler(FnPtr, Cookie);
606 RegisterHandler();
607 LeaveCriticalSection(&CriticalSection);
608}
609
610static void Cleanup(bool ExecuteSignalHandlers) {
611 if (CleanupExecuted)
612 return;
613
614 EnterCriticalSection(&CriticalSection);
615
616 // Prevent other thread from registering new files and directories for
617 // removal, should we be executing because of the console handler callback.
618 CleanupExecuted = true;
619
620 // FIXME: open files cannot be deleted.
621 if (FilesToRemove != NULL)
622 while (!FilesToRemove->empty()) {
623 llvm::sys::fs::remove(FilesToRemove->back());
624 FilesToRemove->pop_back();
625 }
626
627 if (ExecuteSignalHandlers)
629
630 LeaveCriticalSection(&CriticalSection);
631}
632
634 // The interrupt handler may be called from an interrupt, but it may also be
635 // called manually (such as the case of report_fatal_error with no registered
636 // error handler). We must ensure that the critical section is properly
637 // initialized.
638 InitializeThreading();
639 Cleanup(true);
640}
641
642/// Find the Windows Registry Key for a given location.
643///
644/// \returns a valid HKEY if the location exists, else NULL.
645static HKEY FindWERKey(const llvm::Twine &RegistryLocation) {
646 HKEY Key;
647 if (ERROR_SUCCESS != ::RegOpenKeyExA(HKEY_LOCAL_MACHINE,
648 RegistryLocation.str().c_str(), 0,
649 KEY_QUERY_VALUE | KEY_READ, &Key))
650 return NULL;
651
652 return Key;
653}
654
655/// Populate ResultDirectory with the value for "DumpFolder" for a given
656/// Windows Registry key.
657///
658/// \returns true if a valid value for DumpFolder exists, false otherwise.
659static bool GetDumpFolder(HKEY Key,
660 llvm::SmallVectorImpl<char> &ResultDirectory) {
661 using llvm::sys::windows::UTF16ToUTF8;
662
663 if (!Key)
664 return false;
665
666 DWORD BufferLengthBytes = 0;
667
668 if (ERROR_SUCCESS != ::RegGetValueW(Key, 0, L"DumpFolder", REG_EXPAND_SZ,
669 NULL, NULL, &BufferLengthBytes))
670 return false;
671
672 SmallVector<wchar_t, MAX_PATH> Buffer(BufferLengthBytes);
673
674 if (ERROR_SUCCESS != ::RegGetValueW(Key, 0, L"DumpFolder", REG_EXPAND_SZ,
675 NULL, Buffer.data(), &BufferLengthBytes))
676 return false;
677
678 DWORD ExpandBufferSize = ::ExpandEnvironmentStringsW(Buffer.data(), NULL, 0);
679
680 if (!ExpandBufferSize)
681 return false;
682
683 SmallVector<wchar_t, MAX_PATH> ExpandBuffer(ExpandBufferSize);
684
685 if (ExpandBufferSize != ::ExpandEnvironmentStringsW(Buffer.data(),
686 ExpandBuffer.data(),
687 ExpandBufferSize))
688 return false;
689
690 if (UTF16ToUTF8(ExpandBuffer.data(), ExpandBufferSize - 1, ResultDirectory))
691 return false;
692
693 return true;
694}
695
696/// Populate ResultType with a valid MINIDUMP_TYPE based on the value of
697/// "DumpType" for a given Windows Registry key.
698///
699/// According to
700/// https://msdn.microsoft.com/en-us/library/windows/desktop/bb787181(v=vs.85).aspx
701/// valid values for DumpType are:
702/// * 0: Custom dump
703/// * 1: Mini dump
704/// * 2: Full dump
705/// If "Custom dump" is specified then the "CustomDumpFlags" field is read
706/// containing a bitwise combination of MINIDUMP_TYPE values.
707///
708/// \returns true if a valid value for ResultType can be set, false otherwise.
709static bool GetDumpType(HKEY Key, MINIDUMP_TYPE &ResultType) {
710 if (!Key)
711 return false;
712
713 DWORD DumpType;
714 DWORD TypeSize = sizeof(DumpType);
715 if (ERROR_SUCCESS != ::RegGetValueW(Key, NULL, L"DumpType", RRF_RT_REG_DWORD,
716 NULL, &DumpType, &TypeSize))
717 return false;
718
719 switch (DumpType) {
720 case 0: {
721 DWORD Flags = 0;
722 if (ERROR_SUCCESS != ::RegGetValueW(Key, NULL, L"CustomDumpFlags",
723 RRF_RT_REG_DWORD, NULL, &Flags,
724 &TypeSize))
725 return false;
726
727 ResultType = static_cast<MINIDUMP_TYPE>(Flags);
728 break;
729 }
730 case 1:
731 ResultType = MiniDumpNormal;
732 break;
733 case 2:
734 ResultType = MiniDumpWithFullMemory;
735 break;
736 default:
737 return false;
738 }
739 return true;
740}
741
742/// Write a Windows dump file containing process information that can be
743/// used for post-mortem debugging.
744///
745/// \returns zero error code if a mini dump created, actual error code
746/// otherwise.
747static std::error_code WINAPI
748WriteWindowsDumpFile(PMINIDUMP_EXCEPTION_INFORMATION ExceptionInfo) {
749 struct ScopedCriticalSection {
750 ScopedCriticalSection() { EnterCriticalSection(&CriticalSection); }
751 ~ScopedCriticalSection() { LeaveCriticalSection(&CriticalSection); }
752 } SCS;
753
754 using namespace llvm;
755 using namespace llvm::sys;
756
757 std::string MainExecutableName = fs::getMainExecutable(nullptr, nullptr);
758 StringRef ProgramName;
759
760 if (MainExecutableName.empty()) {
761 // If we can't get the executable filename,
762 // things are in worse shape than we realize
763 // and we should just bail out.
764 return mapWindowsError(::GetLastError());
765 }
766
767 ProgramName = path::filename(MainExecutableName.c_str());
768
769 // The Windows Registry location as specified at
770 // https://msdn.microsoft.com/en-us/library/windows/desktop/bb787181%28v=vs.85%29.aspx
771 // "Collecting User-Mode Dumps" that may optionally be set to collect crash
772 // dumps in a specified location.
773 StringRef LocalDumpsRegistryLocation =
774 "SOFTWARE\\Microsoft\\Windows\\Windows Error Reporting\\LocalDumps";
775
776 // The key pointing to the Registry location that may contain global crash
777 // dump settings. This will be NULL if the location can not be found.
778 ScopedRegHandle DefaultLocalDumpsKey(FindWERKey(LocalDumpsRegistryLocation));
779
780 // The key pointing to the Registry location that may contain
781 // application-specific crash dump settings. This will be NULL if the
782 // location can not be found.
783 ScopedRegHandle AppSpecificKey(
784 FindWERKey(Twine(LocalDumpsRegistryLocation) + "\\" + ProgramName));
785
786 // Look to see if a dump type is specified in the registry; first with the
787 // app-specific key and failing that with the global key. If none are found
788 // default to a normal dump (GetDumpType will return false either if the key
789 // is NULL or if there is no valid DumpType value at its location).
790 MINIDUMP_TYPE DumpType;
791 if (!GetDumpType(AppSpecificKey, DumpType))
792 if (!GetDumpType(DefaultLocalDumpsKey, DumpType))
793 DumpType = MiniDumpNormal;
794
795 // Look to see if a dump location is specified on the command line. If not,
796 // look to see if a dump location is specified in the registry; first with the
797 // app-specific key and failing that with the global key. If none are found
798 // we'll just create the dump file in the default temporary file location
799 // (GetDumpFolder will return false either if the key is NULL or if there is
800 // no valid DumpFolder value at its location).
801 bool ExplicitDumpDirectorySet = true;
803 if (DumpDirectory.empty())
804 if (!GetDumpFolder(AppSpecificKey, DumpDirectory))
805 if (!GetDumpFolder(DefaultLocalDumpsKey, DumpDirectory))
806 ExplicitDumpDirectorySet = false;
807
808 int FD;
809 SmallString<MAX_PATH> DumpPath;
810
811 if (ExplicitDumpDirectorySet) {
812 if (std::error_code EC = fs::create_directories(DumpDirectory))
813 return EC;
814 if (std::error_code EC = fs::createUniqueFile(
815 Twine(DumpDirectory) + "\\" + ProgramName + ".%%%%%%.dmp", FD,
816 DumpPath))
817 return EC;
818 } else if (std::error_code EC =
819 fs::createTemporaryFile(ProgramName, "dmp", FD, DumpPath))
820 return EC;
821
822 // Our support functions return a file descriptor but Windows wants a handle.
823 ScopedCommonHandle FileHandle(reinterpret_cast<HANDLE>(_get_osfhandle(FD)));
824
825 if (!fMiniDumpWriteDump(::GetCurrentProcess(), ::GetCurrentProcessId(),
826 FileHandle, DumpType, ExceptionInfo, NULL, NULL))
827 return mapWindowsError(::GetLastError());
828
829 llvm::errs() << "Wrote crash dump file \"" << DumpPath << "\"\n";
830 return std::error_code();
831}
832
833void sys::CleanupOnSignal(uintptr_t Context) {
834 LPEXCEPTION_POINTERS EP = (LPEXCEPTION_POINTERS)Context;
835 // Broken pipe is not a crash.
836 //
837 // 0xE0000000 is combined with the return code in the exception raised in
838 // CrashRecoveryContext::HandleExit().
839 unsigned RetCode = EP->ExceptionRecord->ExceptionCode;
840 if (RetCode == (0xE0000000 | EX_IOERR))
841 return;
842 LLVMUnhandledExceptionFilter(EP);
843}
844
845static LONG WINAPI LLVMUnhandledExceptionFilter(LPEXCEPTION_POINTERS ep) {
846 Cleanup(true);
847
848 // Write out the exception code.
849 if (ep && ep->ExceptionRecord)
850 llvm::errs() << format("Exception Code: 0x%08X",
851 ep->ExceptionRecord->ExceptionCode)
852 << "\n";
853
854 // We'll automatically write a Minidump file here to help diagnose
855 // the nasty sorts of crashes that aren't 100% reproducible from a set of
856 // inputs (or in the event that the user is unable or unwilling to provide a
857 // reproducible case).
859 MINIDUMP_EXCEPTION_INFORMATION ExceptionInfo;
860 ExceptionInfo.ThreadId = ::GetCurrentThreadId();
861 ExceptionInfo.ExceptionPointers = ep;
862 ExceptionInfo.ClientPointers = FALSE;
863
864 if (std::error_code EC = WriteWindowsDumpFile(&ExceptionInfo))
865 llvm::errs() << "Could not write crash dump file: " << EC.message()
866 << "\n";
867 }
868
869 // Stack unwinding appears to modify the context. Copy it to preserve the
870 // caller's context.
871 CONTEXT ContextCopy;
872 if (ep)
873 memcpy(&ContextCopy, ep->ContextRecord, sizeof(ContextCopy));
874
875 LocalPrintStackTrace(llvm::errs(), ep ? &ContextCopy : nullptr);
876
877 return EXCEPTION_EXECUTE_HANDLER;
878}
879
880static BOOL WINAPI LLVMConsoleCtrlHandler(DWORD dwCtrlType) {
881 // We are running in our very own thread, courtesy of Windows.
882 EnterCriticalSection(&CriticalSection);
883 // This function is only ever called when a CTRL-C or similar control signal
884 // is fired. Killing a process in this way is normal, so don't trigger the
885 // signal handlers.
886 Cleanup(false);
887
888 // If an interrupt function has been set, go and run one it; otherwise,
889 // the process dies.
890 void (*IF)() = InterruptFunction;
891 InterruptFunction = 0; // Don't run it on another CTRL-C.
892
893 if (IF) {
894 // Note: if the interrupt function throws an exception, there is nothing
895 // to catch it in this thread so it will kill the process.
896 IF(); // Run it now.
897 LeaveCriticalSection(&CriticalSection);
898 return TRUE; // Don't kill the process.
899 }
900
901 // Allow normal processing to take place; i.e., the process dies.
902 LeaveCriticalSection(&CriticalSection);
903 return FALSE;
904}
905
906#if __MINGW32__
907// We turned these warnings off for this file so that MinGW-g++ doesn't
908// complain about the ll format specifiers used. Now we are turning the
909// warnings back on. If MinGW starts to support diagnostic stacks, we can
910// replace this with a pop.
911#pragma GCC diagnostic warning "-Wformat"
912#pragma GCC diagnostic warning "-Wformat-extra-args"
913#endif
914
915void sys::unregisterHandlers() {}
static GCRegistry::Add< ShadowStackGC > C("shadow-stack", "Very portable GC for uncooperative code generators")
#define LLVM_BUILTIN_TRAP
LLVM_BUILTIN_UNREACHABLE - On compilers which support it, expands to an expression which states that ...
Definition: Compiler.h:375
#define LLVM_ATTRIBUTE_UNUSED
Definition: Compiler.h:203
uint64_t Addr
std::string Name
uint64_t Size
bool End
Definition: ELF_riscv.cpp:480
uint64_t Offset
Definition: ELF_riscv.cpp:478
This file contains definitions of exit codes for exit() function.
static const HTTPClientCleanup Cleanup
Definition: HTTPClient.cpp:42
#define I(x, y, z)
Definition: MD5.cpp:58
LLVMContext & Context
if(VerifyEach)
Provides a library for accessing information about this process and other processes on the operating ...
uint64_t Thread
Definition: Profile.cpp:48
static cl::opt< RegAllocEvictionAdvisorAnalysis::AdvisorMode > Mode("regalloc-enable-advisor", cl::Hidden, cl::init(RegAllocEvictionAdvisorAnalysis::AdvisorMode::Default), cl::desc("Enable regalloc advisor mode"), cl::values(clEnumValN(RegAllocEvictionAdvisorAnalysis::AdvisorMode::Default, "default", "Default"), clEnumValN(RegAllocEvictionAdvisorAnalysis::AdvisorMode::Release, "release", "precompiled"), clEnumValN(RegAllocEvictionAdvisorAnalysis::AdvisorMode::Development, "development", "for training")))
assert(ImpDefSCC.getReg()==AMDGPU::SCC &&ImpDefSCC.isDef())
raw_pwrite_stream & OS
static LLVM_ATTRIBUTE_USED bool printSymbolizedStackTrace(StringRef Argv0, void **StackTrace, int Depth, llvm::raw_ostream &OS)
Helper that launches llvm-symbolizer and symbolizes a backtrace.
Definition: Signals.cpp:142
static bool findModulesAndOffsets(void **StackTrace, int Depth, const char **Modules, intptr_t *Offsets, const char *MainExecutableName, StringSaver &StrPool)
static ManagedStatic< std::string > CrashDiagnosticsDirectory
Definition: Signals.cpp:45
static bool printMarkupContext(raw_ostream &OS, const char *MainExecutableName)
static void insertSignalHandler(sys::SignalHandlerCallback FnPtr, void *Cookie)
Definition: Signals.cpp:112
SmallString - A SmallString is just a SmallVector with methods and accessors that make it work better...
Definition: SmallString.h:26
This class consists of common code factored out of the SmallVector class to reduce code duplication b...
Definition: SmallVector.h:586
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small.
Definition: SmallVector.h:1209
StringRef - Represent a constant reference to a string, i.e.
Definition: StringRef.h:50
Saves strings in the provided stable storage and returns a StringRef with a stable character pointer.
Definition: StringSaver.h:21
Twine - A lightweight data structure for efficiently representing the concatenation of temporary valu...
Definition: Twine.h:81
std::string str() const
Return the twine contents as a std::string.
Definition: Twine.cpp:17
This class implements an extremely fast bulk output stream that can only output to a stream.
Definition: raw_ostream.h:52
static void PreventCoreFiles()
This function makes the necessary calls to the operating system to prevent core files or any other ki...
static void Exit(int RetCode, bool NoCleanup=false)
Equivalent to ::exit(), except when running inside a CrashRecoveryContext.
Definition: Process.cpp:111
static bool AreCoreFilesPrevented()
true if PreventCoreFiles has been called, false otherwise.
Definition: Process.cpp:109
Key
PAL metadata keys.
@ IMAGE_FILE_MACHINE_ARM64
Definition: COFF.h:100
@ IMAGE_FILE_MACHINE_UNKNOWN
Definition: COFF.h:95
@ IMAGE_FILE_MACHINE_AMD64
Definition: COFF.h:97
@ IMAGE_FILE_MACHINE_I386
Definition: COFF.h:104
@ IMAGE_FILE_MACHINE_ARMNT
Definition: COFF.h:99
Offsets
Offsets in bytes from the start of the input buffer.
Definition: SIInstrInfo.h:1542
std::error_code remove(const Twine &path, bool IgnoreNonExisting=true)
Remove path.
void SetInterruptFunction(void(*IF)())
This function registers a function to be called when the user "interrupts" the program (typically by ...
void PrintStackTrace(raw_ostream &OS, int Depth=0)
Print the stack trace using the given raw_ostream object.
void DisableSystemDialogsOnCrash()
Disable all system dialog boxes that appear when the process crashes.
void SetOneShotPipeSignalFunction(void(*Handler)())
Registers a function to be called in a "one-shot" manner when a pipe signal is delivered to the proce...
void DontRemoveFileOnSignal(StringRef Filename)
This function removes a file from the list of files to be removed on signal delivery.
void DefaultOneShotPipeSignalHandler()
On Unix systems and Windows, this function exits with an "IO error" exit code.
void(*)(void *) SignalHandlerCallback
Definition: Signals.h:61
void AddSignalHandler(SignalHandlerCallback FnPtr, void *Cookie)
Add a function to be called when an abort/kill signal is delivered to the process.
void RunSignalHandlers()
Definition: Signals.cpp:98
void SetInfoSignalFunction(void(*Handler)())
Registers a function to be called when an "info" signal is delivered to the process.
void PrintStackTraceOnErrorSignal(StringRef Argv0, bool DisableCrashReporting=false)
When an error signal (such as SIGABRT or SIGSEGV) is delivered to the process, print a stack trace an...
void RunInterruptHandlers()
This function runs all the registered interrupt handlers, including the removal of files registered b...
bool RemoveFileOnSignal(StringRef Filename, std::string *ErrMsg=nullptr)
This function registers signal handlers to ensure that if a signal gets delivered that the named file...
This is an optimization pass for GlobalISel generic memory operations.
Definition: AddressRanges.h:18
auto find(R &&Range, const T &Val)
Provide wrappers to std::find which take ranges instead of having to pass begin/end explicitly.
Definition: STLExtras.h:1742
auto reverse(ContainerTy &&C)
Definition: STLExtras.h:419
format_object< Ts... > format(const char *Fmt, const Ts &... Vals)
These are helper functions used to produce formatted output.
Definition: Format.h:125
raw_fd_ostream & errs()
This returns a reference to a raw_ostream for standard error.
std::error_code mapWindowsError(unsigned EV)