Skip to content

Commit

Permalink
Fix Clang and GCC [-Wcast-function-type] warning on casting result
Browse files Browse the repository at this point in the history
of `GetProcAddress()` function.
  • Loading branch information
zufuliu committed Dec 11, 2024
1 parent b78335e commit e11ca00
Show file tree
Hide file tree
Showing 3 changed files with 13 additions and 3 deletions.
2 changes: 1 addition & 1 deletion src/disk_interface.cc
Original file line number Diff line number Diff line change
Expand Up @@ -165,7 +165,7 @@ RealDiskInterface::RealDiskInterface()
HINSTANCE ntdll_lib = ::GetModuleHandleW(L"ntdll");
if (ntdll_lib) {
typedef BOOLEAN(WINAPI FunctionType)();
auto* func_ptr = reinterpret_cast<FunctionType*>(
auto* func_ptr = FunctionCast<FunctionType*>(
::GetProcAddress(ntdll_lib, "RtlAreLongPathsEnabled"));
if (func_ptr) {
long_paths_enabled_ = (*func_ptr)();
Expand Down
4 changes: 2 additions & 2 deletions src/minidump-win32.cc
Original file line number Diff line number Diff line change
Expand Up @@ -51,8 +51,8 @@ void CreateWin32MiniDump(_EXCEPTION_POINTERS* pep) {
return;
}

MiniDumpWriteDumpFunc mini_dump_write_dump =
(MiniDumpWriteDumpFunc)GetProcAddress(dbghelp, "MiniDumpWriteDump");
MiniDumpWriteDumpFunc mini_dump_write_dump = FunctionCast
<MiniDumpWriteDumpFunc>(GetProcAddress(dbghelp, "MiniDumpWriteDump"));
if (mini_dump_write_dump == NULL) {
Error("failed to create minidump: GetProcAddress('MiniDumpWriteDump'): %s",
GetLastErrorString().c_str());
Expand Down
10 changes: 10 additions & 0 deletions src/util.h
Original file line number Diff line number Diff line change
Expand Up @@ -124,6 +124,16 @@ std::string GetLastErrorString();

/// Calls Fatal() with a function name and GetLastErrorString.
NORETURN void Win32Fatal(const char* function, const char* hint = NULL);

/// Naive implemention of C++ 20 std::bit_cast(), used to fix Clang and GCC
/// [-Wcast-function-type] warning on casting result of GetProcAddress().
template <class To, class From>
inline To FunctionCast(From from) {
static_assert(sizeof(To) == sizeof(From), "");
To result;
memcpy(&result, &from, sizeof(To));
return result;
}
#endif

#endif // NINJA_UTIL_H_

0 comments on commit e11ca00

Please sign in to comment.