crt: Implement at_quick_exit()

The declaration of at_quick_exit() was added in
7dda261ef062073eed4ed5b46effa3edd4a658fc. However it is not exported
from any DLL, so we have to implement it ourselves.

This uses _crt_at_quick_exit to register functions to call if called
from an EXE, but does nothing if called from a DLL. In a DLL, we can't
unregister the callbacks if the DLL gets unloaded. This also matches
actual observed behaviour when using at_quick_exit from a DLL
when built with MSVC with the -MD option.

Signed-off-by: Martin Storsjö <martin@martin.st>
diff --git a/mingw-w64-crt/crt/ucrtbase_compat.c b/mingw-w64-crt/crt/ucrtbase_compat.c
index 4af098c..d01293a 100644
--- a/mingw-w64-crt/crt/ucrtbase_compat.c
+++ b/mingw-w64-crt/crt/ucrtbase_compat.c
@@ -55,6 +55,8 @@
 // Declared in new.h, but only visible to C++
 _CRTIMP int __cdecl _set_new_mode(int _NewMode);
 
+extern char __mingw_module_is_dll;
+
 
 // Wrappers with legacy msvcrt.dll style API, based on the new ucrtbase.dll functions.
 int __cdecl __getmainargs(int * _Argc, char *** _Argv, char ***_Env, int _DoWildCard, _startupinfo *_StartInfo)
@@ -88,6 +90,18 @@
 
 _onexit_t __cdecl (*__MINGW_IMP_SYMBOL(_onexit))(_onexit_t func) = _onexit;
 
+int __cdecl at_quick_exit(void (__cdecl *func)(void))
+{
+  // In a DLL, we can't register a function with _crt_at_quick_exit, because
+  // we can't unregister it when the DLL is unloaded. This matches how
+  // at_quick_exit/quick_exit work with MSVC with a dynamically linked CRT.
+  if (__mingw_module_is_dll)
+    return 0;
+  return _crt_at_quick_exit(func);
+}
+
+int __cdecl (*__MINGW_IMP_SYMBOL(at_quick_exit))(void (__cdecl *)(void)) = at_quick_exit;
+
 void __cdecl _amsg_exit(int ret) {
   fprintf(stderr, "runtime error %d\n", ret);
 }