Created
June 25, 2013 07:08
-
-
Save rossy/5856556 to your computer and use it in GitHub Desktop.
Safe LoadLibrary for DLLs that are expected to be in system32
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <windows.h> | |
#include <wchar.h> | |
#define LOAD_LIBRARY_SEARCH_SYSTEM32 (0x00000800) | |
HMODULE loadlibrary_system(const wchar_t* name) | |
{ | |
/* If running on Windows 8 or a system with KB2533623, LoadLibraryEx with | |
LOAD_LIBRARY_SEARCH_SYSTEM32 does the right thing */ | |
if (GetProcAddress(GetModuleHandleW(L"kernel32.dll"), "AddDllDirectory")) | |
return LoadLibraryExW(name, NULL, LOAD_LIBRARY_SEARCH_SYSTEM32); | |
wchar_t* path = malloc(MAX_PATH * sizeof(wchar_t)); | |
size_t pathlen = GetSystemDirectoryW(path, MAX_PATH); | |
if (pathlen == 0 || pathlen + wcslen(name) + 2 > MAX_PATH) | |
return NULL; | |
path[pathlen] = '\\'; | |
wcscpy(path + pathlen + 1, name); | |
HMODULE module = LoadLibraryExW(path, NULL, LOAD_WITH_ALTERED_SEARCH_PATH); | |
free(path); | |
return module; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment