Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 8 additions & 0 deletions CMakeLists.txt
Original file line number Diff line number Diff line change
Expand Up @@ -40,6 +40,14 @@ function(add_node_api_cts_addon ADDON_NAME)
endif()
target_include_directories(${ADDON_NAME} PRIVATE ${NODE_API_HEADERS_DIR})
target_link_libraries(${ADDON_NAME} PRIVATE ${NODE_API_LIB})
if(MSVC)
# Delay-load the node.exe imports and resolve them against the host
# process at runtime, so the addons can be loaded by any Node-API host
# executable regardless of its file name (the node-gyp approach).
target_sources(${ADDON_NAME} PRIVATE ${PROJECT_SOURCE_DIR}/src/win_delay_load_hook.cc)
target_link_libraries(${ADDON_NAME} PRIVATE delayimp)
target_link_options(${ADDON_NAME} PRIVATE "/DELAYLOAD:NODE.EXE")
endif()
target_compile_features(${ADDON_NAME} PRIVATE cxx_std_17)
target_compile_definitions(${ADDON_NAME} PRIVATE ADDON_NAME=${ADDON_NAME})
endfunction()
Expand Down
39 changes: 39 additions & 0 deletions src/win_delay_load_hook.cc
Original file line number Diff line number Diff line change
@@ -0,0 +1,39 @@
/*
* When this file is linked to a DLL, it sets up a delay-load hook that
* intervenes when the DLL is trying to load 'node.exe' dynamically. Instead
* of trying to locate the .exe file it'll just return a handle to the
* process image.
*
* This allows the test addons to load into any Node-API host executable,
* regardless of its file name. Same approach as node-gyp's
* win_delay_load_hook.cc.
*/

#ifdef _MSC_VER

#ifndef WIN32_LEAN_AND_MEAN
#define WIN32_LEAN_AND_MEAN
#endif

#include <windows.h>

#include <delayimp.h>
#include <string.h>

static FARPROC WINAPI load_exe_hook(unsigned int event, DelayLoadInfo* info) {
HMODULE m;
if (event != dliNotePreLoadLibrary)
return NULL;

if (_stricmp(info->szDll, "node.exe") != 0)
return NULL;

// Prefer libnode.dll to support a Node.js built as a shared library.
m = GetModuleHandle(TEXT("libnode.dll"));
if (m == NULL) m = GetModuleHandle(NULL);
return (FARPROC) m;
}

decltype(__pfnDliNotifyHook2) __pfnDliNotifyHook2 = load_exe_hook;

#endif
Loading