Don't bother checking canRead() before calling getMagicNumber();
[oota-llvm.git] / lib / System / Win32 / Signals.inc
index 130d3d63a18af130eacfe8da79e6c091426dddbd..a3a393c76e456c0021888e2cbc0d6d1dd07b3051 100644 (file)
@@ -2,8 +2,8 @@
 // 
 //                     The LLVM Compiler Infrastructure
 //
-// This file was developed by Jeff Cohen and is distributed under the 
-// University of Illinois Open Source License. See LICENSE.TXT for details.
+// This file is distributed under the University of Illinois Open Source
+// License. See LICENSE.TXT for details.
 // 
 //===----------------------------------------------------------------------===//
 //
 //===----------------------------------------------------------------------===//
 
 #include "Win32.h"
-#include <llvm/System/Signals.h>
+#include <stdio.h>
 #include <vector>
-
-#include "dbghelp.h"
-#include "psapi.h"
-
-#pragma comment(lib, "psapi.lib")
-#pragma comment(lib, "dbghelp.lib")
+#include <algorithm>
+
+#ifdef __MINGW32__
+ #include <imagehlp.h>
+#else
+ #include <dbghelp.h>
+#endif
+#include <psapi.h>
+
+#ifdef __MINGW32__
+ #if ((HAVE_LIBIMAGEHLP != 1) || (HAVE_LIBPSAPI != 1))
+  #error "libimagehlp.a & libpsapi.a should be present"
+ #endif
+#else
+ #pragma comment(lib, "psapi.lib")
+ #pragma comment(lib, "dbghelp.lib")
+#endif
 
 // Forward declare.
 static LONG WINAPI LLVMUnhandledExceptionFilter(LPEXCEPTION_POINTERS ep);
 static BOOL WINAPI LLVMConsoleCtrlHandler(DWORD dwCtrlType);
 
-static std::vector<std::string> *FilesToRemove = NULL;
-static std::vector<llvm::sys::Path> *DirectoriesToRemove = NULL;
+// InterruptFunction - The function to call if ctrl-c is pressed.
+static void (*InterruptFunction)() = 0;
+
+static std::vector<llvm::sys::Path> *FilesToRemove = NULL;
+static std::vector<std::pair<void(*)(void*), void*> > *CallBacksToRun = 0;
 static bool RegisteredUnhandledExceptionFilter = false;
+static bool CleanupExecuted = false;
+#ifdef _MSC_VER
+static bool ExitOnUnhandledExceptions = false;
+#endif
+static PTOP_LEVEL_EXCEPTION_FILTER OldFilter = NULL;
 
 // Windows creates a new thread to execute the console handler when an event
 // (such as CTRL/C) occurs.  This causes concurrency issues with the above
@@ -41,10 +60,39 @@ namespace llvm {
 //===          and must not be UNIX code
 //===----------------------------------------------------------------------===//
 
+#ifdef _MSC_VER
+/// CRTReportHook - Function called on a CRT debugging event.
+static int CRTReportHook(int ReportType, char *Message, int *Return) {
+  // Don't cause a DebugBreak() on return.
+  if (Return)
+    *Return = 0;
+
+  switch (ReportType) {
+  default:
+  case _CRT_ASSERT:
+    fprintf(stderr, "CRT assert: %s\n", Message);
+    // FIXME: Is there a way to just crash? Perhaps throw to the unhandled
+    // exception code? Perhaps SetErrorMode() handles this.
+    _exit(3);
+    break;
+  case _CRT_ERROR:
+    fprintf(stderr, "CRT error: %s\n", Message);
+    // FIXME: Is there a way to just crash? Perhaps throw to the unhandled
+    // exception code? Perhaps SetErrorMode() handles this.
+    _exit(3);
+    break;
+  case _CRT_WARN:
+    fprintf(stderr, "CRT warn: %s\n", Message);
+    break;
+  }
+
+  // Don't call _CrtDbgReport.
+  return TRUE;
+}
+#endif
 
-static void RegisterHandler() { 
-  if (RegisteredUnhandledExceptionFilter)
-  {
+static void RegisterHandler() {
+  if (RegisteredUnhandledExceptionFilter) {
     EnterCriticalSection(&CriticalSection);
     return;
   }
@@ -58,76 +106,101 @@ static void RegisterHandler() {
   EnterCriticalSection(&CriticalSection);
 
   RegisteredUnhandledExceptionFilter = true;
-  SetUnhandledExceptionFilter(LLVMUnhandledExceptionFilter);
+  OldFilter = SetUnhandledExceptionFilter(LLVMUnhandledExceptionFilter);
   SetConsoleCtrlHandler(LLVMConsoleCtrlHandler, TRUE);
 
+  // Environment variable to disable any kind of crash dialog.
+#ifdef _MSC_VER
+  if (getenv("LLVM_DISABLE_CRT_DEBUG")) {
+    _CrtSetReportHook(CRTReportHook);
+    ExitOnUnhandledExceptions = true;
+  }
+#endif
+
   // IMPORTANT NOTE: Caller must call LeaveCriticalSection(&CriticalSection) or
   // else multi-threading problems will ensue.
 }
 
 // RemoveFileOnSignal - The public API
-void sys::RemoveFileOnSignal(const std::string &Filename) {
+bool sys::RemoveFileOnSignal(const sys::Path &Filename, std::string* ErrMsg) {
   RegisterHandler();
 
+  if (CleanupExecuted) {
+    if (ErrMsg)
+      *ErrMsg = "Process terminating -- cannot register for removal";
+    return true;
+  }
+
   if (FilesToRemove == NULL)
-    FilesToRemove = new std::vector<std::string>;
+    FilesToRemove = new std::vector<sys::Path>;
 
   FilesToRemove->push_back(Filename);
 
   LeaveCriticalSection(&CriticalSection);
+  return false;
 }
 
-// RemoveDirectoryOnSignal - The public API
-void sys::RemoveDirectoryOnSignal(const sys::Path& path) {
+/// PrintStackTraceOnErrorSignal - When an error signal (such as SIBABRT or
+/// SIGSEGV) is delivered to the process, print a stack trace and then exit.
+void sys::PrintStackTraceOnErrorSignal() {
   RegisterHandler();
+  LeaveCriticalSection(&CriticalSection);
+}
 
-  if (path.is_directory()) {
-    if (DirectoriesToRemove == NULL)
-      DirectoriesToRemove = new std::vector<sys::Path>;
-
-    DirectoriesToRemove->push_back(path);
-  }
 
+void sys::SetInterruptFunction(void (*IF)()) {
+  RegisterHandler();
+  InterruptFunction = IF;
   LeaveCriticalSection(&CriticalSection);
 }
 
-/// PrintStackTraceOnErrorSignal - When an error signal (such as SIBABRT or
-/// SIGSEGV) is delivered to the process, print a stack trace and then exit.
-void sys::PrintStackTraceOnErrorSignal() {
+
+/// AddSignalHandler - Add a function to be called when a signal is delivered
+/// to the process.  The handler can have a cookie passed to it to identify
+/// what instance of the handler it is.
+void sys::AddSignalHandler(void (*FnPtr)(void *), void *Cookie) {
+  if (CallBacksToRun == 0)
+    CallBacksToRun = new std::vector<std::pair<void(*)(void*), void*> >();
+  CallBacksToRun->push_back(std::make_pair(FnPtr, Cookie));
   RegisterHandler();
   LeaveCriticalSection(&CriticalSection);
 }
-
 }
 
 static void Cleanup() {
   EnterCriticalSection(&CriticalSection);
 
+  // Prevent other thread from registering new files and directories for
+  // removal, should we be executing because of the console handler callback.
+  CleanupExecuted = true;
+
+  // FIXME: open files cannot be deleted.
+
   if (FilesToRemove != NULL)
     while (!FilesToRemove->empty()) {
-      try {
-        std::remove(FilesToRemove->back().c_str());
-      } catch (...) {
-      }
+      FilesToRemove->back().eraseFromDisk();
       FilesToRemove->pop_back();
     }
 
-  if (DirectoriesToRemove != NULL)
-    while (!DirectoriesToRemove->empty()) {
-      try {
-        DirectoriesToRemove->back().destroy_directory(true);
-      } catch (...) {
-      }
-      DirectoriesToRemove->pop_back();
-    }
+  if (CallBacksToRun)
+    for (unsigned i = 0, e = CallBacksToRun->size(); i != e; ++i)
+      (*CallBacksToRun)[i].first((*CallBacksToRun)[i].second);
 
   LeaveCriticalSection(&CriticalSection);
 }
 
+void llvm::sys::RunInterruptHandlers() {
+  Cleanup();
+}
+
 static LONG WINAPI LLVMUnhandledExceptionFilter(LPEXCEPTION_POINTERS ep) {
   try {
     Cleanup();
-
+    
+#ifdef _WIN64
+  // TODO: provide a x64 friendly version of the following
+#else
+    
     // Initialize the STACKFRAME structure.
     STACKFRAME StackFrame;
     memset(&StackFrame, 0, sizeof(StackFrame));
@@ -144,7 +217,7 @@ static LONG WINAPI LLVMUnhandledExceptionFilter(LPEXCEPTION_POINTERS ep) {
 
     // Initialize the symbol handler.
     SymSetOptions(SYMOPT_DEFERRED_LOADS|SYMOPT_LOAD_LINES);
-    SymInitialize(GetCurrentProcess(), NULL, TRUE);
+    SymInitialize(hProcess, NULL, TRUE);
 
     while (true) {
       if (!StackWalk(IMAGE_FILE_MACHINE_I386, hProcess, hThread, &StackFrame,
@@ -158,15 +231,15 @@ static LONG WINAPI LLVMUnhandledExceptionFilter(LPEXCEPTION_POINTERS ep) {
 
       // Print the PC in hexadecimal.
       DWORD PC = StackFrame.AddrPC.Offset;
-      fprintf(stderr, "%04X:%08X", ep->ContextRecord->SegCs, PC);
+      fprintf(stderr, "%08lX", PC);
 
       // Print the parameters.  Assume there are four.
-      fprintf(stderr, " (0x%08X 0x%08X 0x%08X 0x%08X)", StackFrame.Params[0],
+      fprintf(stderr, " (0x%08lX 0x%08lX 0x%08lX 0x%08lX)", StackFrame.Params[0],
               StackFrame.Params[1], StackFrame.Params[2], StackFrame.Params[3]);
 
       // Verify the PC belongs to a module in this process.
       if (!SymGetModuleBase(hProcess, PC)) {
-        fputc('\n', stderr);
+        fputs(" <unknown module>\n", stderr);
         continue;
       }
 
@@ -185,7 +258,7 @@ static LONG WINAPI LLVMUnhandledExceptionFilter(LPEXCEPTION_POINTERS ep) {
 
       buffer[511] = 0;
       if (dwDisp > 0)
-        fprintf(stderr, ", %s()+%04d bytes(s)", symbol->Name, dwDisp);
+        fprintf(stderr, ", %s()+%04lu bytes(s)", symbol->Name, dwDisp);
       else
         fprintf(stderr, ", %s", symbol->Name);
 
@@ -194,32 +267,52 @@ static LONG WINAPI LLVMUnhandledExceptionFilter(LPEXCEPTION_POINTERS ep) {
       memset(&line, 0, sizeof(line));
       line.SizeOfStruct = sizeof(line);
       if (SymGetLineFromAddr(hProcess, PC, &dwDisp, &line)) {
-        fprintf(stderr, ", %s, line %d", line.FileName, line.LineNumber);
+        fprintf(stderr, ", %s, line %lu", line.FileName, line.LineNumber);
         if (dwDisp > 0)
-          fprintf(stderr, "+%04d byte(s)", dwDisp);
+          fprintf(stderr, "+%04lu byte(s)", dwDisp);
       }
 
       fputc('\n', stderr);
     }
-  }
-  catch (...)
-  {
-      assert(!"Crashed in LLVMUnhandledExceptionFilter");
+
+#endif
+
+  } catch (...) {
+      assert(0 && "Crashed in LLVMUnhandledExceptionFilter");
   }
 
+#ifdef _MSC_VER
+  if (ExitOnUnhandledExceptions)
+       _exit(-3);
+#endif
+
   // Allow dialog box to pop up allowing choice to start debugger.
-  return EXCEPTION_CONTINUE_SEARCH;
+  if (OldFilter)
+    return (*OldFilter)(ep);
+  else
+    return EXCEPTION_CONTINUE_SEARCH;
 }
 
 static BOOL WINAPI LLVMConsoleCtrlHandler(DWORD dwCtrlType) {
-  // FIXME: This handler executes on a different thread.  The main thread
-  // is still running, potentially creating new files to be cleaned up
-  // in the tiny window between the call to Cleanup() and process termination.
-  // Also, any files currently open cannot be deleted.
+  // We are running in our very own thread, courtesy of Windows.
+  EnterCriticalSection(&CriticalSection);
   Cleanup();
 
+  // If an interrupt function has been set, go and run one it; otherwise,
+  // the process dies.
+  void (*IF)() = InterruptFunction;
+  InterruptFunction = 0;      // Don't run it on another CTRL-C.
+
+  if (IF) {
+    // Note: if the interrupt function throws an exception, there is nothing
+    // to catch it in this thread so it will kill the process.
+    IF();                     // Run it now.
+    LeaveCriticalSection(&CriticalSection);
+    return TRUE;              // Don't kill the process.
+  }
+
   // Allow normal processing to take place; i.e., the process dies.
+  LeaveCriticalSection(&CriticalSection);
   return FALSE;
 }
 
-// vim: sw=2 smartindent smarttab tw=80 autoindent expandtab