Skip to content

Commit 27b395d

Browse files
author
Roger Sanders
committed
[libc++] Switched to assume API set is already loaded as per MS STL
1 parent 930b0c4 commit 27b395d

File tree

1 file changed

+15
-9
lines changed

1 file changed

+15
-9
lines changed

libcxx/src/atomic.cpp

Lines changed: 15 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -43,8 +43,8 @@
4343

4444
#elif defined(_WIN32)
4545

46-
# include <windows.h>
4746
# include <memory>
47+
# include <windows.h>
4848

4949
#else // <- Add other operating systems here
5050

@@ -109,14 +109,20 @@ static void __libcpp_platform_wake_by_address(__cxx_atomic_contention_t const vo
109109
#elif defined(_WIN32)
110110

111111
static void* win32_get_synch_api_function(const char* function_name) {
112-
// Attempt to load the API set. Note that HMODULE is documented as being a pointer type, which means we can safely use
113-
// std::unique_ptr here as a wrapper for the handle, with a destructor freeing the handle when this module is
114-
// unloaded.
115-
// https://learn.microsoft.com/en-us/windows/win32/winprog/windows-data-types
116-
// https://devblogs.microsoft.com/oldnewthing/20180307-00/?p=98175
117-
static auto module_handle = std::unique_ptr<std::remove_pointer<HMODULE>::type, decltype(&FreeLibrary)>(
118-
LoadLibraryW(L"api-ms-win-core-synch-l1-2-0.dll"), &FreeLibrary);
119-
if (!module_handle) {
112+
// Attempt to load the API set. Note that as per the Microsoft STL implementation, we assume this API is already
113+
// loaded and accessible. While this isn't explicitly guaranteed by publicly available Win32 API documentation, it is
114+
// true in practice, and may be guaranteed by internal documentation not released publicly. In any case the fact that
115+
// the Microsoft STL made this assumption is reasonable basis to say that we can too. The alternative to this would be
116+
// to use LoadLibrary, but then leak the module handle. We can't call FreeLibrary, as this would have to be triggered
117+
// by a global static destructor, which would hang off DllMain, and calling FreeLibrary from DllMain is explicitly
118+
// mentioned as not being allowed:
119+
// https://learn.microsoft.com/en-us/windows/win32/dlls/dllmain
120+
// Given the range of bad options here, we have chosen to mirror what Microsoft did, as it seems fair to assume that
121+
// Microsoft will guarantee compatibility for us, as we are exposed to the same conditions as all existing Windows
122+
// apps using the Microsoft STL VS2015/2017/2019/2022 runtimes, where Windows 7 support has not been excluded at
123+
// compile time.
124+
static auto module_handle = GetModuleHandleW(L"api-ms-win-core-synch-l1-2-0.dll");
125+
if (module_handle == nullptr) {
120126
return nullptr;
121127
}
122128

0 commit comments

Comments
 (0)