Skip to content

Instantly share code, notes, and snippets.

@mgeeky
Forked from rossy/loadlibrary_system.c
Created March 2, 2023 17:57
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mgeeky/b6ab693c62f788e5ee55604c3e02ab0f to your computer and use it in GitHub Desktop.
Save mgeeky/b6ab693c62f788e5ee55604c3e02ab0f to your computer and use it in GitHub Desktop.
Safe LoadLibrary for DLLs that are expected to be in system32
#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