74 lines
2.0 KiB
C++
74 lines
2.0 KiB
C++
#include "handoff.hpp"
|
|
|
|
#ifdef _WIN32
|
|
#define WIN32_LEAN_AND_MEAN
|
|
#include <windows.h>
|
|
#include <cstdio>
|
|
#include <cstring>
|
|
#else
|
|
// Stub for non-Windows builds (so the file compiles everywhere).
|
|
#include <cstdio>
|
|
#endif
|
|
|
|
namespace voidlibc::loader::windows_handoff {
|
|
|
|
LoadResult load_pe_buffer(const std::vector<std::uint8_t>& bytes) {
|
|
#ifdef _WIN32
|
|
// Write bytes to a temp file, load it, then delete the file.
|
|
char tmp_path[MAX_PATH];
|
|
char tmp_dir[MAX_PATH];
|
|
GetTempPathA(MAX_PATH, tmp_dir);
|
|
GetTempFileNameA(tmp_dir, "vlc", 0, tmp_path);
|
|
|
|
// Write PE bytes.
|
|
HANDLE fh = CreateFileA(tmp_path, GENERIC_WRITE, 0, nullptr,
|
|
CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, nullptr);
|
|
if (fh == INVALID_HANDLE_VALUE) {
|
|
return {nullptr, "CreateFile failed for temp PE", false};
|
|
}
|
|
DWORD written = 0;
|
|
BOOL ok = WriteFile(fh, bytes.data(),
|
|
static_cast<DWORD>(bytes.size()), &written, nullptr);
|
|
CloseHandle(fh);
|
|
if (!ok || written != bytes.size()) {
|
|
DeleteFileA(tmp_path);
|
|
return {nullptr, "WriteFile failed for temp PE", false};
|
|
}
|
|
|
|
// Load the DLL.
|
|
HMODULE mod = LoadLibraryExA(tmp_path, nullptr, LOAD_WITH_ALTERED_SEARCH_PATH);
|
|
DeleteFileA(tmp_path); // safe to delete once mapped
|
|
|
|
if (!mod) {
|
|
char msg[256];
|
|
std::snprintf(msg, sizeof(msg),
|
|
"LoadLibraryEx failed (error %lu)", GetLastError());
|
|
return {nullptr, msg, false};
|
|
}
|
|
return {static_cast<void*>(mod), {}, true};
|
|
#else
|
|
(void)bytes;
|
|
return {nullptr, "load_pe_buffer: not implemented on non-Windows", false};
|
|
#endif
|
|
}
|
|
|
|
void* get_proc(void* handle, const char* name) {
|
|
#ifdef _WIN32
|
|
return reinterpret_cast<void*>(
|
|
GetProcAddress(static_cast<HMODULE>(handle), name));
|
|
#else
|
|
(void)handle; (void)name;
|
|
return nullptr;
|
|
#endif
|
|
}
|
|
|
|
void unload(void* handle) {
|
|
#ifdef _WIN32
|
|
FreeLibrary(static_cast<HMODULE>(handle));
|
|
#else
|
|
(void)handle;
|
|
#endif
|
|
}
|
|
|
|
} // namespace voidlibc::loader::windows_handoff
|