|
| 1 | +#define WIN32_LEAN_AND_MEAN |
| 2 | + |
| 3 | +#include <windows.h> |
| 4 | +#include <tchar.h> |
| 5 | +#include <stdio.h> |
| 6 | +#include <malloc.h> |
| 7 | + |
| 8 | +#include "../MemoryModule.h" |
| 9 | + |
| 10 | +typedef int (*addNumberProc)(int, int); |
| 11 | + |
| 12 | +BOOL LoadFromMemory(char *filename) |
| 13 | +{ |
| 14 | + FILE *fp; |
| 15 | + unsigned char *data=NULL; |
| 16 | + size_t size; |
| 17 | + HMEMORYMODULE handle; |
| 18 | + addNumberProc addNumber; |
| 19 | + HMEMORYRSRC resourceInfo; |
| 20 | + DWORD resourceSize; |
| 21 | + LPVOID resourceData; |
| 22 | + TCHAR buffer[100]; |
| 23 | + BOOL result = TRUE; |
| 24 | + |
| 25 | + fp = fopen(filename, "rb"); |
| 26 | + if (fp == NULL) |
| 27 | + { |
| 28 | + printf("Can't open DLL file \"%s\".", filename); |
| 29 | + result = FALSE; |
| 30 | + goto exit; |
| 31 | + } |
| 32 | + |
| 33 | + fseek(fp, 0, SEEK_END); |
| 34 | + size = ftell(fp); |
| 35 | + data = (unsigned char *)malloc(size); |
| 36 | + fseek(fp, 0, SEEK_SET); |
| 37 | + fread(data, 1, size, fp); |
| 38 | + fclose(fp); |
| 39 | + |
| 40 | + handle = MemoryLoadLibrary(data); |
| 41 | + if (handle == NULL) |
| 42 | + { |
| 43 | + _tprintf(_T("Can't load library from memory.\n")); |
| 44 | + result = FALSE; |
| 45 | + goto exit; |
| 46 | + } |
| 47 | + |
| 48 | + addNumber = (addNumberProc)MemoryGetProcAddress(handle, "addNumbers"); |
| 49 | + _tprintf(_T("From memory: %d\n"), addNumber(1, 2)); |
| 50 | + |
| 51 | + resourceInfo = MemoryFindResource(handle, MAKEINTRESOURCE(VS_VERSION_INFO), RT_VERSION); |
| 52 | + _tprintf(_T("MemoryFindResource returned 0x%p\n"), resourceInfo); |
| 53 | + |
| 54 | + if (resourceInfo != NULL) { |
| 55 | + resourceSize = MemorySizeofResource(handle, resourceInfo); |
| 56 | + resourceData = MemoryLoadResource(handle, resourceInfo); |
| 57 | + _tprintf(_T("Memory resource data: %ld bytes at 0x%p\n"), resourceSize, resourceData); |
| 58 | + |
| 59 | + MemoryLoadString(handle, 1, buffer, sizeof(buffer)); |
| 60 | + _tprintf(_T("String1: %s\n"), buffer); |
| 61 | + |
| 62 | + MemoryLoadString(handle, 20, buffer, sizeof(buffer)); |
| 63 | + _tprintf(_T("String2: %s\n"), buffer); |
| 64 | + } else { |
| 65 | + result = FALSE; |
| 66 | + } |
| 67 | + |
| 68 | + MemoryFreeLibrary(handle); |
| 69 | + |
| 70 | +exit: |
| 71 | + if (data) |
| 72 | + free(data); |
| 73 | + return result; |
| 74 | +} |
| 75 | + |
| 76 | +int main(int argc, char* argv[]) |
| 77 | +{ |
| 78 | + if (argc < 2) { |
| 79 | + fprintf(stderr, "USAGE: %s <filename.dll>\n", argv[0]); |
| 80 | + return 1; |
| 81 | + } |
| 82 | + |
| 83 | + if (!LoadFromMemory(argv[1])) { |
| 84 | + return 2; |
| 85 | + } |
| 86 | + |
| 87 | + return 0; |
| 88 | +} |
0 commit comments