### Custom Allocator with Logging for MemoryLoadLibraryEx Source: https://context7.com/fancycode/memorymodule/llms.txt This example demonstrates a custom memory allocation callback that logs allocation requests. It uses MemoryDefaultAlloc for the actual allocation and wraps it with logging. Use this when you need to track memory operations performed by MemoryModule. ```c #include "MemoryModule.h" /* Example: custom allocator with logging; everything else uses defaults */ static LPVOID WINAPI LoggingAlloc(LPVOID addr, SIZE_T size, DWORD type, DWORD protect, void *ud) { LPVOID result = MemoryDefaultAlloc(addr, size, type, protect, ud); printf("[alloc] requested %zu bytes -> %p\n", (size_t)size, result); return result; } HMEMORYMODULE load_with_logging(const void *data, size_t size) { return MemoryLoadLibraryEx( data, size, LoggingAlloc, /* custom */ MemoryDefaultFree, /* default */ MemoryDefaultLoadLibrary, /* default */ MemoryDefaultGetProcAddress, /* default */ MemoryDefaultFreeLibrary, /* default */ NULL ); } ``` -------------------------------- ### Access Resource Data in Memory Source: https://context7.com/fancycode/memorymodule/llms.txt Use `MemorySizeofResource` to get the size of a resource and `MemoryLoadResource` to obtain a pointer to its data within the loaded module's memory. The pointer remains valid for the lifetime of the `HMEMORYMODULE`. This example demonstrates copying resource bytes into a caller-owned buffer. ```c #include "MemoryModule.h" #include BOOL extract_resource(HMEMORYMODULE module, LPCTSTR name, LPCTSTR type, void **outBuf, DWORD *outSize) { HMEMORYRSRC rsrc = MemoryFindResource(module, name, type); if (rsrc == NULL) return FALSE; *outSize = MemorySizeofResource(module, rsrc); LPVOID src = MemoryLoadResource(module, rsrc); if (src == NULL || *outSize == 0) return FALSE; /* Copy resource bytes into caller-owned buffer */ *outBuf = malloc(*outSize); if (!*outBuf) return FALSE; memcpy(*outBuf, src, *outSize); return TRUE; } ``` -------------------------------- ### MemoryModule API Functions Source: https://github.com/fancycode/memorymodule/blob/master/doc/readme.rst Defines the core API functions for the MemoryModule library: loading, getting procedure addresses, and freeing libraries. ```c typedef void *HMEMORYMODULE; HMEMORYMODULE MemoryLoadLibrary(const void *, size_t); FARPROC MemoryGetProcAddress(HMEMORYMODULE, const char *); void MemoryFreeLibrary(HMEMORYMODULE); ``` -------------------------------- ### Load DLL from Memory with MemoryModule Source: https://context7.com/fancycode/memorymodule/llms.txt Demonstrates loading a DLL from a memory buffer using MemoryLoadLibrary, resolving an exported function with MemoryGetProcAddress, and freeing the module with MemoryFreeLibrary. Ensure the DLL file is accessible and the exported function exists. ```c #include #include #include "MemoryModule.h" /* Function prototype matching an export in the target DLL */ typedef int (*AddNumbersProc)(int a, int b); int main(void) { /* Step 1: Read the DLL file into a heap buffer */ FILE *fp = fopen("SampleDLL.dll", "rb"); if (!fp) { fprintf(stderr, "Cannot open DLL\n"); return 1; } fseek(fp, 0, SEEK_END); size_t size = (size_t)ftell(fp); fseek(fp, 0, SEEK_SET); void *data = malloc(size); fread(data, 1, size, fp); fclose(fp); /* Step 2: Load the DLL from the memory buffer */ HMEMORYMODULE module = MemoryLoadLibrary(data, size); if (module == NULL) { fprintf(stderr, "MemoryLoadLibrary failed: %lu\n", GetLastError()); free(data); return 1; } /* Step 3: Resolve and call an exported function */ AddNumbersProc addNumbers = (AddNumbersProc)MemoryGetProcAddress(module, "addNumbers"); if (addNumbers) { printf("addNumbers(3, 4) = %d\n", addNumbers(3, 4)); /* Output: addNumbers(3, 4) = 7 */ } /* Step 4: Clean up */ MemoryFreeLibrary(module); free(data); return 0; } ``` -------------------------------- ### Configure SampleDLL Build Source: https://github.com/fancycode/memorymodule/blob/master/example/SampleDLL/CMakeLists.txt Defines the source files, adds a preprocessor definition, and creates a MODULE library target. It also sets specific properties for non-MSVC compilers to ensure correct naming conventions for the DLL. ```cmake set (sources SampleDLL.cpp SampleDLL.h SampleDLL.rc ) add_definitions (-DSAMPLEDLL_EXPORTS) add_library (SampleDLL MODULE ${sources}) if (NOT MSVC) set_target_properties ("SampleDLL" PROPERTIES PREFIX "") set_target_properties ("SampleDLL" PROPERTIES SUFFIX ".dll") endif () ``` -------------------------------- ### Call DLL Entry Point Source: https://github.com/fancycode/memorymodule/blob/master/doc/readme.rst Call the DLL entry point to notify the library about being attached to a process. This is typically done during library loading. ```c typedef BOOL (WINAPI *DllEntryProc)(HINSTANCE hinstDLL, DWORD fdwReason, LPVOID lpReserved); DllEntryProc entry = (DllEntryProc)(baseAddress + PEHeader->OptionalHeader.AddressOfEntryPoint); (*entry)((HINSTANCE)baseAddress, DLL_PROCESS_ATTACH, 0); ``` -------------------------------- ### MemoryCallEntryPoint — Execute the entry point of an in-memory EXE Source: https://context7.com/fancycode/memorymodule/llms.txt Invokes the entry point of an EXE (not DLL) image that was loaded via MemoryLoadLibrary. The executable must have been loaded at its preferred base address, or relocation information must be present; otherwise this function returns -1. This call does not return if the EXE runs to completion — the process terminates when the loaded EXE's entry point returns. ```APIDOC ## MemoryCallEntryPoint ### Description Invokes the entry point of an EXE (not DLL) image that was loaded via `MemoryLoadLibrary`. The executable must have been loaded at its preferred base address, or relocation information must be present; otherwise this function returns -1. This call does not return if the EXE runs to completion — the process terminates when the loaded EXE's entry point returns. ### Parameters * **module** (HMEMORYMODULE) - Handle to the loaded memory module. ### Return Value * Returns an integer representing the exit code of the EXE, or -1 if the entry point could not be called. ``` -------------------------------- ### Allocate Memory for Library Source: https://github.com/fancycode/memorymodule/blob/master/doc/readme.rst Reserves memory for a library using VirtualAlloc, based on the SizeOfImage and ImageBase specified in the PE Optional Header. This is a crucial step in emulating the PE loader. ```c memory = VirtualAlloc((LPVOID)(PEHeader->OptionalHeader.ImageBase), PEHeader->OptionalHeader.SizeOfImage, ``` -------------------------------- ### MemoryLoadLibraryEx Source: https://context7.com/fancycode/memorymodule/llms.txt Loads a DLL with custom allocator and resolver callbacks. This extended version allows for fine-grained control over memory allocation and dependency loading, making it suitable for environments with restricted or custom API implementations. ```APIDOC ## MemoryLoadLibraryEx ### Description Extended version of `MemoryLoadLibrary` that accepts five callback functions replacing the default VirtualAlloc/VirtualFree/LoadLibraryA/GetProcAddress/FreeLibrary implementations. Use this when you need to control where the image is placed in memory, intercept dependency loading, or operate in an environment where the default Win32 APIs are unavailable or restricted. ### Parameters - **data** (const void *) - Pointer to the DLL's binary data. - **size** (size_t) - Size of the DLL's binary data. - **CustomAllocFunc** (MemoryAllocFunc) - Callback function for memory allocation. - **CustomFreeFunc** (MemoryFreeFunc) - Callback function for memory deallocation. - **CustomLoadLibraryFunc** (MemoryLoadLibraryFunc) - Callback function for loading dependent libraries. - **CustomGetProcAddressFunc** (MemoryGetProcAddressFunc) - Callback function for resolving function addresses. - **CustomFreeLibraryFunc** (MemoryFreeLibraryFunc) - Callback function for freeing dependent libraries. - **userdata** (void *) - User-defined data passed to callback functions. ### Return Value - Returns a handle to the loaded in-memory module (HMEMORYMODULE) on success. - Returns NULL on failure. Call `GetLastError()` for more information. ### Request Example ```c #include #include #include "MemoryModule.h" typedef int (*AddNumbersProc)(int, int); /* Custom allocator: forces the image above 4 GB on 64-bit builds */ static LPVOID WINAPI HighMemAlloc(LPVOID addr, SIZE_T size, DWORD type, DWORD protect, void *userdata) { (void)userdata; #ifdef _WIN64 /* Bias the preferred address upward so relocation is exercised */ if (addr) addr = (LPVOID)((uintptr_t)addr + 0x10000000000ULL); #endif /* Fall back to the default allocator */ return VirtualAlloc(addr, size, type, protect); } static BOOL WINAPI HighMemFree(LPVOID addr, SIZE_T size, DWORD type, void *userdata) { (void)userdata; return VirtualFree(addr, size, type); } int main(void) { FILE *fp = fopen("SampleDLL.dll", "rb"); fseek(fp, 0, SEEK_END); size_t size = (size_t)ftell(fp); fseek(fp, 0, SEEK_SET); void *data = malloc(size); fread(data, 1, size, fp); fclose(fp); /* Load with custom alloc/free; use defaults for library/proc resolution */ HMEMORYMODULE module = MemoryLoadLibraryEx( data, size, HighMemAlloc, /* CustomAllocFunc */ HighMemFree, /* CustomFreeFunc */ MemoryDefaultLoadLibrary, /* CustomLoadLibraryFunc */ MemoryDefaultGetProcAddress, /* CustomGetProcAddressFunc */ MemoryDefaultFreeLibrary, /* CustomFreeLibraryFunc */ NULL /* userdata */ ); if (module == NULL) { fprintf(stderr, "Load failed: %lu\n", GetLastError()); free(data); return 1; } AddNumbersProc fn = (AddNumbersProc)MemoryGetProcAddress(module, "addNumbers"); printf("Result: %d\n", fn(10, 20)); /* Output: Result: 30 */ MemoryFreeLibrary(module); free(data); return 0; } ``` ``` -------------------------------- ### Load DLL with Custom Allocator and Resolver Callbacks Source: https://context7.com/fancycode/memorymodule/llms.txt Use MemoryLoadLibraryEx to load a DLL with custom memory allocation and dependency loading callbacks. This is useful for controlling memory placement or operating in restricted environments. ```c #include #include #include "MemoryModule.h" typedef int (*AddNumbersProc)(int, int); /* Custom allocator: forces the image above 4 GB on 64-bit builds */ static LPVOID WINAPI HighMemAlloc(LPVOID addr, SIZE_T size, DWORD type, DWORD protect, void *userdata) { (void)userdata; #ifdef _WIN64 /* Bias the preferred address upward so relocation is exercised */ if (addr) addr = (LPVOID)((uintptr_t)addr + 0x10000000000ULL); #endif /* Fall back to the default allocator */ return VirtualAlloc(addr, size, type, protect); } static BOOL WINAPI HighMemFree(LPVOID addr, SIZE_T size, DWORD type, void *userdata) { (void)userdata; return VirtualFree(addr, size, type); } int main(void) { FILE *fp = fopen("SampleDLL.dll", "rb"); fseek(fp, 0, SEEK_END); size_t size = (size_t)ftell(fp); fseek(fp, 0, SEEK_SET); void *data = malloc(size); fread(data, 1, size, fp); fclose(fp); /* Load with custom alloc/free; use defaults for library/proc resolution */ HMEMORYMODULE module = MemoryLoadLibraryEx( data, size, HighMemAlloc, /* CustomAllocFunc */ HighMemFree, /* CustomFreeFunc */ MemoryDefaultLoadLibrary, /* CustomLoadLibraryFunc */ MemoryDefaultGetProcAddress, /* CustomGetProcAddressFunc */ MemoryDefaultFreeLibrary, /* CustomFreeLibraryFunc */ NULL /* userdata */ ); if (module == NULL) { fprintf(stderr, "Load failed: %lu\n", GetLastError()); free(data); return 1; } AddNumbersProc fn = (AddNumbersProc)MemoryGetProcAddress(module, "addNumbers"); printf("Result: %d\n", fn(10, 20)); /* Output: Result: 30 */ MemoryFreeLibrary(module); free(data); return 0; } ``` -------------------------------- ### Execute In-Memory EXE Entry Point Source: https://context7.com/fancycode/memorymodule/llms.txt Use `MemoryCallEntryPoint` to invoke the entry point of an EXE loaded via `MemoryLoadLibrary`. The process will terminate if the EXE runs to completion. Ensure the EXE was loaded at its preferred base address or that relocation information is present. ```c #include "MemoryModule.h" #include void run_exe_from_memory(const void *exeData, size_t exeSize) { HMEMORYMODULE module = MemoryLoadLibrary(exeData, exeSize); if (module == NULL) { fprintf(stderr, "Failed to load EXE from memory: %lu\n", GetLastError()); return; } /* Blocks until the loaded EXE terminates; process exits with its return code */ int result = MemoryCallEntryPoint(module); if (result < 0) { /* Returned negative value means entry point could not be called */ fprintf(stderr, "Entry point execution failed (code %d)\n", result); MemoryFreeLibrary(module); } /* If result >= 0 the process has already exited — unreachable */ } ``` -------------------------------- ### Configure Test Suite Build Source: https://github.com/fancycode/memorymodule/blob/master/tests/CMakeLists.txt Defines the source files for the test suite and links the executable against the MemoryModule library. It also sets specific linker flags for shared libraries in non-MSVC environments and the executable suffix. ```cmake set (sources_testsuite TestSuite.c ) if (NOT MSVC) set (CMAKE_SHARED_LIBRARY_LINK_C_FLAGS "-static") set (CMAKE_SHARED_LIBRARY_LINK_CXX_FLAGS "-static") endif () add_executable (TestSuite ${sources_testsuite}) target_link_libraries ("TestSuite" "MemoryModule") if (NOT MSVC) set_target_properties ("TestSuite" PROPERTIES SUFFIX ".exe") endif () ``` -------------------------------- ### Load String Resource from Memory Module Source: https://context7.com/fancycode/memorymodule/llms.txt Employ `MemoryLoadString` and `MemoryLoadStringEx` to load string resources from a memory-mapped module into a buffer, mirroring the Win32 `LoadString` API. `MemoryLoadStringEx` allows specifying a language identifier. The functions return the number of characters copied, excluding the null terminator, or `0` on failure. ```c #include "MemoryModule.h" #include #include void print_string_resources(HMEMORYMODULE module) { TCHAR buf[256]; int len; /* Load string ID 1 using default thread locale */ len = MemoryLoadString(module, 1, buf, (int)(sizeof(buf) / sizeof(TCHAR))); if (len > 0) _tprintf(_T("String[1]: %s\n"), buf); /* Load string ID 20 for a specific language */ len = MemoryLoadStringEx(module, 20, buf, (int)(sizeof(buf) / sizeof(TCHAR)), MAKELANGID(LANG_ENGLISH, SUBLANG_ENGLISH_US)); if (len > 0) _tprintf(_T("String[20] (en-US): %s\n"), buf); else _tprintf(_T("String[20] not found: %lu\n"), GetLastError()); } ``` -------------------------------- ### MemoryLoadLibrary Source: https://context7.com/fancycode/memorymodule/llms.txt Loads a Portable Executable (PE) image from a memory buffer. It handles parsing, mapping, import resolution, relocation, TLS callbacks, and entry point invocation. Returns a handle to the loaded module or NULL on failure. ```APIDOC ## MemoryLoadLibrary ### Description Parses and maps a PE image held in a raw memory buffer, resolves all imports using the default Windows `LoadLibraryA`/`GetProcAddress`, applies base relocations if necessary, runs TLS callbacks, and calls the DLL entry point with `DLL_PROCESS_ATTACH`. Returns an opaque `HMEMORYMODULE` handle on success, or `NULL` on failure (call `GetLastError()` for the error code). ### Function Signature ```c HMEMORYMODULE MemoryLoadLibrary(const void *data, size_t size) ``` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body - **data** (const void *) - Required - Pointer to the memory buffer containing the PE image. - **size** (size_t) - Required - The size of the memory buffer in bytes. ### Request Example ```c // Example usage within a C program #include #include #include "MemoryModule.h" typedef int (*AddNumbersProc)(int a, int b); int main(void) { /* Step 1: Read the DLL file into a heap buffer */ FILE *fp = fopen("SampleDLL.dll", "rb"); if (!fp) { fprintf(stderr, "Cannot open DLL\n"); return 1; } fseek(fp, 0, SEEK_END); size_t size = (size_t)ftell(fp); fseek(fp, 0, SEEK_SET); void *data = malloc(size); fread(data, 1, size, fp); fclose(fp); /* Step 2: Load the DLL from the memory buffer */ HMEMORYMODULE module = MemoryLoadLibrary(data, size); if (module == NULL) { fprintf(stderr, "MemoryLoadLibrary failed: %lu\n", GetLastError()); free(data); return 1; } /* Step 3: Resolve and call an exported function */ AddNumbersProc addNumbers = (AddNumbersProc)MemoryGetProcAddress(module, "addNumbers"); if (addNumbers) { printf("addNumbers(3, 4) = %d\n", addNumbers(3, 4)); /* Output: addNumbers(3, 4) = 7 */ } /* Step 4: Clean up */ MemoryFreeLibrary(module); free(data); return 0; } ``` ### Response #### Success Response (HMEMORYMODULE) - **HMEMORYMODULE** - An opaque handle to the loaded module. This handle is used for subsequent calls to `MemoryGetProcAddress` and `MemoryFreeLibrary`. #### Failure Response (NULL) - **NULL** - Indicates that the module failed to load. Call `GetLastError()` for specific error information. #### Response Example ```c // Success: Returns a valid HMEMORYMODULE handle HMEMORYMODULE module = MemoryLoadLibrary(dllData, dllSize); // Failure: Returns NULL if (module == NULL) { // Handle error } ``` ``` -------------------------------- ### Define DllLoader Executable Sources Source: https://github.com/fancycode/memorymodule/blob/master/example/DllLoader/CMakeLists.txt Defines the source files for the DllLoader executable. ```cmake set (sources_dllloader DllLoader.cpp ) ``` -------------------------------- ### Define DllLoaderLoader Executable Sources Source: https://github.com/fancycode/memorymodule/blob/master/example/DllLoader/CMakeLists.txt Defines the source files for the DllLoaderLoader executable. ```cmake set (sources_dllloaderloader DllLoaderLoader.cpp ) ``` -------------------------------- ### MemoryFindResource / MemoryFindResourceEx — Locate a resource in an in-memory module Source: https://context7.com/fancycode/memorymodule/llms.txt Searches the PE resource tree of a memory-loaded module for a resource identified by type and name, mirroring the Win32 FindResource/FindResourceEx API. MemoryFindResourceEx additionally accepts a language identifier. Returns an HMEMORYRSRC handle usable with MemorySizeofResource and MemoryLoadResource, or NULL on failure. ```APIDOC ## MemoryFindResource / MemoryFindResourceEx ### Description Searches the PE resource tree of a memory-loaded module for a resource identified by type and name, mirroring the Win32 `FindResource`/`FindResourceEx` API. `MemoryFindResourceEx` additionally accepts a language identifier. Returns an `HMEMORYRSRC` handle usable with `MemorySizeofResource` and `MemoryLoadResource`, or `NULL` on failure. ### Parameters * **module** (HMEMORYMODULE) - Handle to the loaded memory module. * **name** (LPCTSTR) - The name or ID of the resource. * **type** (LPCTSTR) - The type of the resource. * **language** (LANGID, optional for `MemoryFindResourceEx`) - The language identifier for the resource. ### Return Value * Returns an `HMEMORYRSRC` handle to the located resource, or `NULL` on failure. ``` -------------------------------- ### IMAGE_OPTIONAL_HEADER32 Structure Source: https://github.com/fancycode/memorymodule/blob/master/doc/readme.rst Defines the optional header for a 32-bit PE file, containing information about the image's size, base address, and subsystem. ```c typedef struct _IMAGE_OPTIONAL_HEADER32 { WORD MajorSubsystemVersion; WORD MinorSubsystemVersion; DWORD Win32VersionValue; DWORD SizeOfImage; DWORD SizeOfHeaders; DWORD CheckSum; WORD Subsystem; WORD DllCharacteristics; DWORD SizeOfStackReserve; DWORD SizeOfStackCommit; DWORD SizeOfHeapReserve; DWORD SizeOfHeapCommit; DWORD LoaderFlags; DWORD NumberOfRvaAndSizes; IMAGE_DATA_DIRECTORY DataDirectory[IMAGE_NUMBEROF_DIRECTORY_ENTRIES]; } IMAGE_OPTIONAL_HEADER32, *PIMAGE_OPTIONAL_HEADER32; ``` -------------------------------- ### MemoryLoadString / MemoryLoadStringEx — Load a string resource Source: https://context7.com/fancycode/memorymodule/llms.txt Loads a string from the RT_STRING resource table of a memory-mapped module into a caller-supplied buffer, mirroring LoadString/LoadStringEx. MemoryLoadStringEx accepts an explicit language identifier. Returns the number of characters copied (excluding the null terminator), or 0 on failure. ```APIDOC ## MemoryLoadString / MemoryLoadStringEx ### Description Loads a string from the `RT_STRING` resource table of a memory-mapped module into a caller-supplied buffer, mirroring `LoadString`/`LoadStringEx`. `MemoryLoadStringEx` accepts an explicit language identifier. Returns the number of characters copied (excluding the null terminator), or `0` on failure. ### Parameters * **module** (HMEMORYMODULE) - Handle to the loaded memory module. * **id** (UINT) - The string identifier. * **buf** (LPTSTR) - Buffer that receives the string. * **len** (int) - The maximum number of characters to copy to the buffer, including the null terminator. * **language** (LANGID, optional for `MemoryLoadStringEx`) - The language identifier for the string resource. ### Return Value * Returns the number of characters copied to the buffer, excluding the null terminator. Returns `0` on failure. ``` -------------------------------- ### Image Export Directory Structure Source: https://github.com/fancycode/memorymodule/blob/master/doc/readme.rst Defines the structure for the IMAGE_EXPORT_DIRECTORY, which contains information about exported functions in a DLL. ```c typedef struct _IMAGE_EXPORT_DIRECTORY { DWORD Characteristics; DWORD TimeDateStamp; WORD MajorVersion; WORD MinorVersion; DWORD Name; DWORD Base; DWORD NumberOfFunctions; DWORD NumberOfNames; DWORD AddressOfFunctions; // RVA from base of image DWORD AddressOfNames; // RVA from base of image DWORD AddressOfNameOrdinals; // RVA from base of image } IMAGE_EXPORT_DIRECTORY, *PIMAGE_EXPORT_DIRECTORY; ``` -------------------------------- ### Build and Link DllLoader Executable Source: https://github.com/fancycode/memorymodule/blob/master/example/DllLoader/CMakeLists.txt Adds the DllLoader executable target and links it against the 'MemoryModule' library. This is the primary executable for loading DLLs. ```cmake add_executable (DllLoader ${sources_dllloader}) target_link_libraries ("DllLoader" "MemoryModule") ``` -------------------------------- ### C Struct for IMAGE_OPTIONAL_HEADER Source: https://github.com/fancycode/memorymodule/blob/master/doc/readme.rst Defines the optional header within the PE header, containing logical format information such as base address, entry point, and memory requirements. ```c typedef struct _IMAGE_OPTIONAL_HEADER { WORD Magic; BYTE MajorLinkerVersion; BYTE MinorLinkerVersion; DWORD SizeOfCode; DWORD SizeOfInitializedData; DWORD SizeOfUninitializedData; DWORD AddressOfEntryPoint; DWORD BaseOfCode; DWORD BaseOfData; DWORD ImageBase; DWORD SectionAlignment; DWORD FileAlignment; WORD MajorOperatingSystemVersion; WORD MinorOperatingSystemVersion; WORD MajorImageVersion; WORD MinorImageVersion; ``` -------------------------------- ### Build and Link DllLoaderLoader Executable Source: https://github.com/fancycode/memorymodule/blob/master/example/DllLoader/CMakeLists.txt Adds the DllLoaderLoader executable target and links it against the 'MemoryModule' library. This is a secondary executable, potentially for testing or a different loading scenario. ```cmake add_executable (DllLoaderLoader ${sources_dllloaderloader}) target_link_libraries ("DllLoaderLoader" "MemoryModule") ``` -------------------------------- ### Find Resource in Memory Module Source: https://context7.com/fancycode/memorymodule/llms.txt Utilize `MemoryFindResource` and `MemoryFindResourceEx` to locate resources within a memory-loaded module, similar to Win32's `FindResource` API. `MemoryFindResourceEx` allows specifying a language identifier. These functions return an `HMEMORYRSRC` handle for use with `MemorySizeofResource` and `MemoryLoadResource`. ```c #include "MemoryModule.h" #include void read_version_resource(HMEMORYMODULE module) { /* Find the VS_VERSION_INFO resource using default thread locale */ HMEMORYRSRC rsrc = MemoryFindResource( module, MAKEINTRESOURCE(VS_VERSION_INFO), /* resource name */ RT_VERSION /* resource type */ ); if (rsrc == NULL) { fprintf(stderr, "Version resource not found: %lu\n", GetLastError()); return; } DWORD size = MemorySizeofResource(module, rsrc); LPVOID data = MemoryLoadResource(module, rsrc); printf("VS_VERSION_INFO: %lu bytes at %p\n", size, data); /* Find same resource for a specific language (US English) */ HMEMORYRSRC rsrcEn = MemoryFindResourceEx( module, MAKEINTRESOURCE(VS_VERSION_INFO), RT_VERSION, MAKELANGID(LANG_ENGLISH, SUBLANG_ENGLISH_US) ); if (rsrcEn) { printf("EN-US version resource found (%lu bytes)\n", MemorySizeofResource(module, rsrcEn)); } } ``` -------------------------------- ### Configure Static Linking for Shared Libraries (Non-MSVC) Source: https://github.com/fancycode/memorymodule/blob/master/example/DllLoader/CMakeLists.txt Sets flags to ensure shared libraries are linked statically when not using MSVC. This is typically used for compatibility or specific build environments. ```cmake if (NOT MSVC) set (CMAKE_SHARED_LIBRARY_LINK_C_FLAGS "-static") set (CMAKE_SHARED_LIBRARY_LINK_CXX_FLAGS "-static") endif () ``` -------------------------------- ### IMAGE_SECTION_HEADER Structure Source: https://github.com/fancycode/memorymodule/blob/master/doc/readme.rst Defines a section header within a PE file, providing details about each section's name, size, and location. ```c typedef struct _IMAGE_SECTION_HEADER { BYTE Name[IMAGE_SIZEOF_SHORT_NAME]; union { DWORD PhysicalAddress; DWORD VirtualSize; } Misc; DWORD VirtualAddress; DWORD SizeOfRawData; DWORD PointerToRawData; DWORD PointerToRelocations; DWORD PointerToLinenumbers; WORD NumberOfRelocations; WORD NumberOfLinenumbers; DWORD Characteristics; } IMAGE_SECTION_HEADER, *PIMAGE_SECTION_HEADER; ``` -------------------------------- ### C Struct for IMAGE_DOS_HEADER Source: https://github.com/fancycode/memorymodule/blob/master/doc/readme.rst Defines the structure of the DOS header in Windows executables. This is used for backwards compatibility. ```c typedef struct _IMAGE_DOS_HEADER { WORD e_magic; WORD e_cblp; WORD e_cp; WORD e_crlc; WORD e_cparhdr; WORD e_minalloc; WORD e_maxalloc; WORD e_ss; WORD e_sp; WORD e_csum; WORD e_ip; WORD e_cs; WORD e_lfarlc; WORD e_ovno; WORD e_res[4]; WORD e_oemid; WORD e_oeminfo; WORD e_res2[10]; LONG e_lfanew; } IMAGE_DOS_HEADER, *PIMAGE_DOS_HEADER; ``` -------------------------------- ### C Struct for IMAGE_NT_HEADERS Source: https://github.com/fancycode/memorymodule/blob/master/doc/readme.rst Defines the structure of the PE (Portable Executable) header, which contains information about the executable's sections, imports, and exports. ```c typedef struct _IMAGE_NT_HEADERS { DWORD Signature; IMAGE_FILE_HEADER FileHeader; IMAGE_OPTIONAL_HEADER32 OptionalHeader; } IMAGE_NT_HEADERS32, *PIMAGE_NT_HEADERS32; ``` -------------------------------- ### Resolve Imports Source: https://github.com/fancycode/memorymodule/blob/master/doc/readme.rst Resolves imported functions from external libraries. This involves walking the import descriptor, finding function names, and obtaining their addresses using GetProcAddress. ```c nameRef = (DWORD *)(baseAddress + importDesc->OriginalFirstThunk); symbolRef = (DWORD *)(baseAddress + importDesc->FirstThunk); for (; *nameRef; nameRef++, symbolRef++) { PIMAGE_IMPORT_BY_NAME thunkData = (PIMAGE_IMPORT_BY_NAME)(codeBase + *nameRef); *symbolRef = (DWORD)GetProcAddress(handle, (LPCSTR)&thunkData->Name); if (*funcRef == 0) { handleImportError(); return; } } ``` -------------------------------- ### Set DllLoader Target Properties (Non-MSVC) Source: https://github.com/fancycode/memorymodule/blob/master/example/DllLoader/CMakeLists.txt Configures specific properties for the DllLoader executable when not using MSVC. This includes setting the suffix to '.exe' and specifying linker flags for a fixed image base address. ```cmake if (NOT MSVC) set_target_properties ("DllLoader" PROPERTIES SUFFIX ".exe") set_target_properties ("DllLoader" PROPERTIES LINK_FLAGS "-Wl,--image-base -Wl,0x20000000") endif () ``` -------------------------------- ### MemoryGetProcAddress Source: https://context7.com/fancycode/memorymodule/llms.txt Resolves an exported symbol by name or ordinal from a module loaded by MemoryLoadLibrary or MemoryLoadLibraryEx. It efficiently handles lookups using a binary-searched name table. ```APIDOC ## MemoryGetProcAddress ### Description Looks up an exported function in a module loaded by `MemoryLoadLibrary`/`MemoryLoadLibraryEx`. Supports lookup by name (string) and by ordinal (pass the ordinal value cast via `MAKEINTRESOURCE`). Uses a lazily-built, binary-searched name table for efficient repeated lookups. Returns `NULL` and sets `ERROR_PROC_NOT_FOUND` when the symbol is absent. ### Parameters - **module** (HMEMORYMODULE) - Handle to the loaded in-memory module. - **nameOrOrdinal** (LPCSTR or MAKEINTRESOURCE) - The name of the exported symbol or its ordinal number. ### Return Value - Returns a pointer to the exported function on success. - Returns `NULL` if the symbol is not found. Call `GetLastError()` for more information (expected to be `ERROR_PROC_NOT_FOUND`). ### Request Example ```c #include "MemoryModule.h" #include typedef void (*PrintMsgProc)(const char *); void resolve_exports(HMEMORYMODULE module) { /* Lookup by exported name */ PrintMsgProc printMsg = (PrintMsgProc)MemoryGetProcAddress(module, "PrintMessage"); if (printMsg == NULL) { fprintf(stderr, "Export 'PrintMessage' not found: %lu\n", GetLastError()); return; } printMsg("Hello from in-memory DLL!"); /* Lookup by ordinal (ordinal #1) */ PrintMsgProc byOrdinal = (PrintMsgProc)MemoryGetProcAddress(module, MAKEINTRESOURCE(1)); if (byOrdinal) { byOrdinal("Called via ordinal 1"); } } ``` ``` -------------------------------- ### C Struct for IMAGE_FILE_HEADER Source: https://github.com/fancycode/memorymodule/blob/master/doc/readme.rst Defines the file header within the PE header, detailing the physical format of the file, including section count and characteristics. ```c typedef struct _IMAGE_FILE_HEADER { WORD Machine; WORD NumberOfSections; DWORD TimeDateStamp; DWORD PointerToSymbolTable; DWORD NumberOfSymbols; WORD SizeOfOptionalHeader; WORD Characteristics; } IMAGE_FILE_HEADER, *PIMAGE_FILE_HEADER; ``` -------------------------------- ### Set DllLoaderLoader Target Properties (Non-MSVC) Source: https://github.com/fancycode/memorymodule/blob/master/example/DllLoader/CMakeLists.txt Configures specific properties for the DllLoaderLoader executable when not using MSVC. This includes setting the suffix to '.exe' and specifying linker flags for a different fixed image base address. ```cmake if (NOT MSVC) set_target_properties ("DllLoaderLoader" PROPERTIES SUFFIX ".exe") set_target_properties ("DllLoaderLoader" PROPERTIES LINK_FLAGS "-Wl,--image-base -Wl,0x10000000") endif () ``` -------------------------------- ### MemoryFreeLibrary Source: https://context7.com/fancycode/memorymodule/llms.txt Unloads an in-memory module. This function calls the DLL entry point with DLL_PROCESS_DETACH, releases dependent libraries, frees the export name table, and deallocates the virtual memory used by the image. It is safe to call with a NULL handle. ```APIDOC ## MemoryFreeLibrary ### Description Unload an in-memory module. Calls the DLL entry point with `DLL_PROCESS_DETACH`, releases all dependency libraries loaded during import resolution, frees the export name table, and releases the allocated virtual memory for the image. Safe to call with `NULL`. ### Parameters - **module** (HMEMORYMODULE) - Handle to the in-memory module to be unloaded. Can be `NULL`. ### Return Value This function does not return a value. ### Request Example ```c #include "MemoryModule.h" void load_use_unload(const void *dllData, size_t dllSize) { HMEMORYMODULE module = MemoryLoadLibrary(dllData, dllSize); if (module == NULL) return; /* ... use the module ... */ MemoryFreeLibrary(module); /* DLL_PROCESS_DETACH is called automatically */ /* module handle is now invalid — do not use it after this point */ } ``` ``` -------------------------------- ### Resolve Exported Symbol by Name or Ordinal Source: https://context7.com/fancycode/memorymodule/llms.txt Use MemoryGetProcAddress to find exported functions in a loaded module. Supports lookup by string name or ordinal value. Returns NULL and sets ERROR_PROC_NOT_FOUND if the symbol is absent. ```c #include "MemoryModule.h" #include typedef void (*PrintMsgProc)(const char *); void resolve_exports(HMEMORYMODULE module) { /* Lookup by exported name */ PrintMsgProc printMsg = (PrintMsgProc)MemoryGetProcAddress(module, "PrintMessage"); if (printMsg == NULL) { fprintf(stderr, "Export 'PrintMessage' not found: %lu\n", GetLastError()); return; } printMsg("Hello from in-memory DLL!"); /* Lookup by ordinal (ordinal #1) */ PrintMsgProc byOrdinal = (PrintMsgProc)MemoryGetProcAddress(module, MAKEINTRESOURCE(1)); if (byOrdinal) { byOrdinal("Called via ordinal 1"); } } ``` -------------------------------- ### Commit Memory for Sections Source: https://github.com/fancycode/memorymodule/blob/master/doc/readme.rst Commits memory for a section of the module. Use this after reserving memory and before copying section data. Sections without file data have a SizeOfRawData of 0. ```c dest = VirtualAlloc(baseAddress + section->VirtualAddress, section->SizeOfRawData, MEM_COMMIT, PAGE_READWRITE); ``` -------------------------------- ### MemoryLoadResource / MemorySizeofResource — Access resource data Source: https://context7.com/fancycode/memorymodule/llms.txt MemorySizeofResource returns the byte size of a located resource. MemoryLoadResource returns a pointer directly into the loaded module's memory at the resource data location. The pointer is valid for the lifetime of the HMEMORYMODULE. ```APIDOC ## MemoryLoadResource / MemorySizeofResource ### Description `MemorySizeofResource` returns the byte size of a located resource. `MemoryLoadResource` returns a pointer directly into the loaded module's memory at the resource data location. The pointer is valid for the lifetime of the `HMEMORYMODULE`. ### Parameters * **module** (HMEMORYMODULE) - Handle to the loaded memory module. * **rsrc** (HMEMORYRSRC) - Handle to the located resource obtained from `MemoryFindResource` or `MemoryFindResourceEx`. ### Return Value * `MemorySizeofResource`: Returns the size of the resource in bytes. * `MemoryLoadResource`: Returns a pointer to the resource data, or `NULL` on failure. ``` -------------------------------- ### Unload an In-Memory Module Source: https://context7.com/fancycode/memorymodule/llms.txt Use MemoryFreeLibrary to unload a module loaded by MemoryLoadLibrary or MemoryLoadLibraryEx. This function calls the DLL entry point with DLL_PROCESS_DETACH, releases dependencies, frees the export table, and deallocates memory. It is safe to call with NULL. ```c #include "MemoryModule.h" void load_use_unload(const void *dllData, size_t dllSize) { HMEMORYMODULE module = MemoryLoadLibrary(dllData, dllSize); if (module == NULL) return; /* ... use the module ... */ MemoryFreeLibrary(module); /* DLL_PROCESS_DETACH is called automatically */ /* module handle is now invalid — do not use it after this point */ } ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.