[libFuzzer] Use TerminateProcess for immediate exits on Windows (#247877)

On Windows, `_Exit()` calls `ExitProcess()`, which kills all other threads
and then runs `DllMain(DLL_PROCESS_DETACH)` for every loaded DLL while
holding the loader lock. libFuzzer often exits from a non-main thread
(timeout, RSS limit, or crash handler). If a DLL's detach handler waits on a
lock or a thread that was already killed, the process hangs instead of
exiting. We saw this on ClusterFuzz after `SUMMARY: libFuzzer: timeout`.

Add `ExitImmediately()`, which uses `TerminateProcess()` on Windows to skip
DLL detach, the same way as `internal__exit()` in sanitizer_common. Other
platforms still use `_Exit()`. Use it for all existing `_Exit()` calls in
libFuzzer.

Assisted-by: Gemini
GitOrigin-RevId: bb6c5944ad071d9646916ac0d7fc40bb35443d58
diff --git a/FuzzerLoop.cpp b/FuzzerLoop.cpp
index 55f6f7b..bfb6f13 100644
--- a/FuzzerLoop.cpp
+++ b/FuzzerLoop.cpp
@@ -15,6 +15,7 @@
 #include "FuzzerPlatform.h"
 #include "FuzzerRandom.h"
 #include "FuzzerTracePC.h"
+#include "FuzzerUtil.h"
 #include <algorithm>
 #include <cstring>
 #include <memory>
@@ -132,7 +133,7 @@
   DumpCurrentUnit("oom-");
   Printf("SUMMARY: libFuzzer: out-of-memory\n");
   PrintFinalStats();
-  _Exit(Options.OOMExitCode); // Stop right now.
+  ExitImmediately(Options.OOMExitCode); // Stop right now.
 }
 
 Fuzzer::Fuzzer(UserCallback CB, InputCorpus &Corpus, MutationDispatcher &MD,
@@ -235,7 +236,7 @@
   Printf("SUMMARY: libFuzzer: deadly signal\n");
   DumpCurrentUnit("crash-");
   PrintFinalStats();
-  _Exit(Options.ErrorExitCode); // Stop right now.
+  ExitImmediately(Options.ErrorExitCode); // Stop right now.
 }
 
 void Fuzzer::ExitCallback() {
@@ -249,7 +250,7 @@
   Printf("SUMMARY: libFuzzer: fuzz target exited\n");
   DumpCurrentUnit("crash-");
   PrintFinalStats();
-  _Exit(Options.ErrorExitCode);
+  ExitImmediately(Options.ErrorExitCode);
 }
 
 void Fuzzer::MaybeExitGracefully() {
@@ -257,7 +258,7 @@
   Printf("==%lu== INFO: libFuzzer: exiting as requested\n", GetPid());
   RmDirRecursive(TempPath("FuzzWithFork", ".dir"));
   F->PrintFinalStats();
-  _Exit(0);
+  ExitImmediately(0);
 }
 
 int Fuzzer::InterruptExitCode() {
@@ -271,7 +272,7 @@
   ScopedDisableMsanInterceptorChecks S; // RmDirRecursive may call opendir().
   RmDirRecursive(TempPath("FuzzWithFork", ".dir"));
   // Stop right now, don't perform any at-exit actions.
-  _Exit(Options.InterruptExitCode);
+  ExitImmediately(Options.InterruptExitCode);
 }
 
 NO_SANITIZE_MEMORY
@@ -304,7 +305,7 @@
     PrintStackTrace();
     Printf("SUMMARY: libFuzzer: timeout\n");
     PrintFinalStats();
-    _Exit(Options.TimeoutExitCode); // Stop right now.
+    ExitImmediately(Options.TimeoutExitCode); // Stop right now.
   }
 }
 
@@ -319,7 +320,7 @@
   DumpCurrentUnit("oom-");
   Printf("SUMMARY: libFuzzer: out-of-memory\n");
   PrintFinalStats();
-  _Exit(Options.OOMExitCode); // Stop right now.
+  ExitImmediately(Options.OOMExitCode); // Stop right now.
 }
 
 void Fuzzer::PrintStats(const char *Where, const char *End, size_t Units,
@@ -400,7 +401,7 @@
       if (Descr.find(Options.ExitOnSrcPos) != std::string::npos) {
         Printf("INFO: found line matching '%s', exiting.\n",
                Options.ExitOnSrcPos.c_str());
-        _Exit(0);
+        ExitImmediately(0);
       }
     };
     TPC.ForEachObservedPC(HandlePC);
@@ -409,7 +410,7 @@
     if (Corpus.HasUnit(Options.ExitOnItem)) {
       Printf("INFO: found item with checksum '%s', exiting.\n",
              Options.ExitOnItem.c_str());
-      _Exit(0);
+      ExitImmediately(0);
     }
   }
 }
@@ -576,7 +577,7 @@
   Printf("SUMMARY: libFuzzer: overwrites-const-input\n");
   DumpCurrentUnit("crash-");
   PrintFinalStats();
-  _Exit(Options.ErrorExitCode); // Stop right now.
+  ExitImmediately(Options.ErrorExitCode); // Stop right now.
 }
 
 // Compare two arrays, but not all bytes if the arrays are large.
@@ -720,7 +721,8 @@
     CurrentUnitSize = Size;
     DumpCurrentUnit("leak-");
     PrintFinalStats();
-    _Exit(Options.ErrorExitCode); // not exit() to disable lsan further on.
+    // Use ExitImmediately() rather than exit() to disable lsan further on.
+    ExitImmediately(Options.ErrorExitCode);
   }
 }
 
diff --git a/FuzzerTracePC.cpp b/FuzzerTracePC.cpp
index a5976db..9696aeb 100644
--- a/FuzzerTracePC.cpp
+++ b/FuzzerTracePC.cpp
@@ -104,7 +104,7 @@
              "please contact the libFuzzer developers.\n"
              "Also check https://bugs.llvm.org/show_bug.cgi?id=34636\n"
              "for possible workarounds (tl;dr: don't use the old GNU ld)\n");
-      _Exit(1);
+      ExitImmediately(1);
     }
   }
   if (size_t NumExtraCounters = ExtraCountersEnd() - ExtraCountersBegin())
diff --git a/FuzzerUtil.h b/FuzzerUtil.h
index ba711d4..2840f66 100644
--- a/FuzzerUtil.h
+++ b/FuzzerUtil.h
@@ -53,6 +53,10 @@
 // Platform-specific one-time initialization, called early in FuzzerDriver.
 void PlatformInit();
 
+// Terminates the process immediately with ExitCode without running atexit
+// handlers or DLL_PROCESS_DETACH callbacks.
+[[noreturn]] void ExitImmediately(int ExitCode);
+
 void SleepSeconds(int Seconds);
 
 unsigned long GetPid();
diff --git a/FuzzerUtilFuchsia.cpp b/FuzzerUtilFuchsia.cpp
index 4f7da64..2f02baa 100644
--- a/FuzzerUtilFuchsia.cpp
+++ b/FuzzerUtilFuchsia.cpp
@@ -17,6 +17,7 @@
 #include <cerrno>
 #include <cinttypes>
 #include <cstdint>
+#include <cstdlib>
 #include <fcntl.h>
 #include <lib/fdio/fdio.h>
 #include <lib/fdio/spawn.h>
@@ -670,6 +671,8 @@
 
 void PlatformInit() {}
 
+[[noreturn]] void ExitImmediately(int ExitCode) { std::_Exit(ExitCode); }
+
 } // namespace fuzzer
 
 #endif // LIBFUZZER_FUCHSIA
diff --git a/FuzzerUtilPosix.cpp b/FuzzerUtilPosix.cpp
index 607f3b8..86aa260 100644
--- a/FuzzerUtilPosix.cpp
+++ b/FuzzerUtilPosix.cpp
@@ -12,8 +12,10 @@
 #include "FuzzerIO.h"
 #include "FuzzerInternal.h"
 #include "FuzzerTracePC.h"
+#include "FuzzerUtil.h"
 #include <cassert>
 #include <chrono>
+#include <cstdlib>
 #include <cstring>
 #include <errno.h>
 #include <iomanip>
@@ -195,6 +197,8 @@
 void PlatformInit() {}
 #endif
 
+[[noreturn]] void ExitImmediately(int ExitCode) { std::_Exit(ExitCode); }
+
 }  // namespace fuzzer
 
 #endif // LIBFUZZER_POSIX
diff --git a/FuzzerUtilWindows.cpp b/FuzzerUtilWindows.cpp
index 7ee72ea..857a10f 100644
--- a/FuzzerUtilWindows.cpp
+++ b/FuzzerUtilWindows.cpp
@@ -12,8 +12,10 @@
 #include "FuzzerCommand.h"
 #include "FuzzerIO.h"
 #include "FuzzerInternal.h"
+#include "FuzzerUtil.h"
 #include <cassert>
 #include <chrono>
+#include <cstdlib>
 #include <cstring>
 #include <errno.h>
 #include <io.h>
@@ -152,6 +154,14 @@
 
 void SleepSeconds(int Seconds) { Sleep(Seconds * 1000); }
 
+[[noreturn]] void ExitImmediately(int ExitCode) {
+  // _Exit() on Windows calls ExitProcess(), which runs
+  // DllMain(DLL_PROCESS_DETACH) after terminating other threads and can
+  // deadlock when invoked from a timer, RSS, or signal/exception thread.
+  TerminateProcess(GetCurrentProcess(), static_cast<UINT>(ExitCode));
+  std::_Exit(ExitCode);
+}
+
 unsigned long GetPid() { return GetCurrentProcessId(); }
 
 size_t GetPeakRSSMb() {