From 2f0bb27c681ada201a4c614da3786d2c1b8c88a6 Mon Sep 17 00:00:00 2001 From: Joachim Bauch Date: Sun, 24 Oct 2010 02:48:03 +0200 Subject: [PATCH 1/5] added support for 64bit DLLs --- MemoryModule.c | 51 ++++++++++++++++++++++++++++++++++---------------- 1 file changed, 35 insertions(+), 16 deletions(-) diff --git a/MemoryModule.c b/MemoryModule.c index 201b651..6525b1e 100644 --- a/MemoryModule.c +++ b/MemoryModule.c @@ -24,8 +24,16 @@ * */ +#ifndef __GNUC__ // disable warnings about pointer <-> DWORD conversions #pragma warning( disable : 4311 4312 ) +#endif + +#ifdef _WIN64 +#define POINTER_TYPE ULONGLONG +#else +#define POINTER_TYPE DWORD +#endif #include #include @@ -46,7 +54,7 @@ typedef struct { typedef BOOL (WINAPI *DllEntryProc)(HINSTANCE hinstDLL, DWORD fdwReason, LPVOID lpReserved); #define GET_HEADER_DICTIONARY(module, idx) &(module)->headers->OptionalHeader.DataDirectory[idx] -#define CALCULATE_ADDRESS(base, offset) (((DWORD)(base)) + (offset)) +#define CALCULATE_ADDRESS(base, offset) (((unsigned char *)(base)) + (offset)) #ifdef DEBUG_OUTPUT static void @@ -85,7 +93,7 @@ CopySections(const unsigned char *data, PIMAGE_NT_HEADERS old_headers, PMEMORYMO MEM_COMMIT, PAGE_READWRITE); - section->Misc.PhysicalAddress = (DWORD)dest; + section->Misc.PhysicalAddress = (POINTER_TYPE)dest; memset(dest, 0, size); } @@ -99,7 +107,7 @@ CopySections(const unsigned char *data, PIMAGE_NT_HEADERS old_headers, PMEMORYMO MEM_COMMIT, PAGE_READWRITE); memcpy(dest, (unsigned char *)CALCULATE_ADDRESS(data, section->PointerToRawData), section->SizeOfRawData); - section->Misc.PhysicalAddress = (DWORD)dest; + section->Misc.PhysicalAddress = (POINTER_TYPE)dest; } } @@ -133,7 +141,7 @@ FinalizeSections(PMEMORYMODULE module) if (section->Characteristics & IMAGE_SCN_MEM_DISCARDABLE) { // section is not needed any more and can safely be freed - VirtualFree((LPVOID)section->Misc.PhysicalAddress, section->SizeOfRawData, MEM_DECOMMIT); + VirtualFree((LPVOID)(POINTER_TYPE)section->Misc.PhysicalAddress, section->SizeOfRawData, MEM_DECOMMIT); continue; } @@ -155,7 +163,7 @@ FinalizeSections(PMEMORYMODULE module) if (size > 0) { // change memory access flags - if (VirtualProtect((LPVOID)section->Misc.PhysicalAddress, section->SizeOfRawData, protect, &oldProtect) == 0) + if (VirtualProtect((LPVOID)(POINTER_TYPE)section->Misc.PhysicalAddress, section->SizeOfRawData, protect, &oldProtect) == 0) #ifdef DEBUG_OUTPUT OutputLastError("Error protecting memory page") #endif @@ -165,7 +173,7 @@ FinalizeSections(PMEMORYMODULE module) } static void -PerformBaseRelocation(PMEMORYMODULE module, DWORD delta) +PerformBaseRelocation(PMEMORYMODULE module, SIZE_T delta) { DWORD i; unsigned char *codeBase = module->codeBase; @@ -181,6 +189,9 @@ PerformBaseRelocation(PMEMORYMODULE module, DWORD delta) for (i=0; i<((relocation->SizeOfBlock-IMAGE_SIZEOF_BASE_RELOCATION) / 2); i++, relInfo++) { DWORD *patchAddrHL; +#ifdef _WIN64 + ULONGLONG *patchAddr64; +#endif int type, offset; // the upper 4 bits define the type of relocation @@ -199,6 +210,13 @@ PerformBaseRelocation(PMEMORYMODULE module, DWORD delta) patchAddrHL = (DWORD *)CALCULATE_ADDRESS(dest, offset); *patchAddrHL += delta; break; + +#ifdef _WIN64 + case IMAGE_REL_BASED_DIR64: + patchAddr64 = (ULONGLONG *)CALCULATE_ADDRESS(dest, offset); + *patchAddr64 += delta; + break; +#endif default: //printf("Unknown relocation: %d\n", type); @@ -224,7 +242,8 @@ BuildImportTable(PMEMORYMODULE module) PIMAGE_IMPORT_DESCRIPTOR importDesc = (PIMAGE_IMPORT_DESCRIPTOR)CALCULATE_ADDRESS(codeBase, directory->VirtualAddress); for (; !IsBadReadPtr(importDesc, sizeof(IMAGE_IMPORT_DESCRIPTOR)) && importDesc->Name; importDesc++) { - DWORD *thunkRef, *funcRef; + POINTER_TYPE *thunkRef; + FARPROC *funcRef; HMODULE handle = LoadLibrary((LPCSTR)CALCULATE_ADDRESS(codeBase, importDesc->Name)); if (handle == INVALID_HANDLE_VALUE) { @@ -245,20 +264,20 @@ BuildImportTable(PMEMORYMODULE module) module->modules[module->numModules++] = handle; if (importDesc->OriginalFirstThunk) { - thunkRef = (DWORD *)CALCULATE_ADDRESS(codeBase, importDesc->OriginalFirstThunk); - funcRef = (DWORD *)CALCULATE_ADDRESS(codeBase, importDesc->FirstThunk); + thunkRef = (POINTER_TYPE *)CALCULATE_ADDRESS(codeBase, importDesc->OriginalFirstThunk); + funcRef = (FARPROC *)CALCULATE_ADDRESS(codeBase, importDesc->FirstThunk); } else { // no hint table - thunkRef = (DWORD *)CALCULATE_ADDRESS(codeBase, importDesc->FirstThunk); - funcRef = (DWORD *)CALCULATE_ADDRESS(codeBase, importDesc->FirstThunk); + thunkRef = (POINTER_TYPE *)CALCULATE_ADDRESS(codeBase, importDesc->FirstThunk); + funcRef = (FARPROC *)CALCULATE_ADDRESS(codeBase, importDesc->FirstThunk); } for (; *thunkRef; thunkRef++, funcRef++) { if IMAGE_SNAP_BY_ORDINAL(*thunkRef) - *funcRef = (DWORD)GetProcAddress(handle, (LPCSTR)IMAGE_ORDINAL(*thunkRef)); + *funcRef = (FARPROC)GetProcAddress(handle, (LPCSTR)IMAGE_ORDINAL(*thunkRef)); else { PIMAGE_IMPORT_BY_NAME thunkData = (PIMAGE_IMPORT_BY_NAME)CALCULATE_ADDRESS(codeBase, *thunkRef); - *funcRef = (DWORD)GetProcAddress(handle, (LPCSTR)&thunkData->Name); + *funcRef = (FARPROC)GetProcAddress(handle, (LPCSTR)&thunkData->Name); } if (*funcRef == 0) { @@ -281,7 +300,7 @@ HMEMORYMODULE MemoryLoadLibrary(const void *data) PIMAGE_DOS_HEADER dos_header; PIMAGE_NT_HEADERS old_header; unsigned char *code, *headers; - DWORD locationDelta; + SIZE_T locationDelta; DllEntryProc DllEntry; BOOL successfull; @@ -348,13 +367,13 @@ HMEMORYMODULE MemoryLoadLibrary(const void *data) result->headers = (PIMAGE_NT_HEADERS)&((const unsigned char *)(headers))[dos_header->e_lfanew]; // update position - result->headers->OptionalHeader.ImageBase = (DWORD)code; + result->headers->OptionalHeader.ImageBase = (POINTER_TYPE)code; // copy sections from DLL file block to new memory location CopySections(data, old_header, result); // adjust base address of imported data - locationDelta = (DWORD)(code - old_header->OptionalHeader.ImageBase); + locationDelta = (SIZE_T)(code - old_header->OptionalHeader.ImageBase); if (locationDelta != 0) PerformBaseRelocation(result, locationDelta); From 75021eff5f37a58278fc93941826914bc1044436 Mon Sep 17 00:00:00 2001 From: Joachim Bauch Date: Sun, 24 Oct 2010 03:03:35 +0200 Subject: [PATCH 2/5] adjust addresses to protect by upper 32bit for 64bit modules --- MemoryModule.c | 12 ++++++++++-- 1 file changed, 10 insertions(+), 2 deletions(-) diff --git a/MemoryModule.c b/MemoryModule.c index 6525b1e..c69de46 100644 --- a/MemoryModule.c +++ b/MemoryModule.c @@ -129,6 +129,11 @@ FinalizeSections(PMEMORYMODULE module) { int i; PIMAGE_SECTION_HEADER section = IMAGE_FIRST_SECTION(module->headers); +#ifdef _WIN64 + POINTER_TYPE imageOffset = (module->headers->OptionalHeader.ImageBase & 0xffffffff00000000); +#else + #define imageOffset 0 +#endif // loop through all sections and change access flags for (i=0; iheaders->FileHeader.NumberOfSections; i++, section++) @@ -141,7 +146,7 @@ FinalizeSections(PMEMORYMODULE module) if (section->Characteristics & IMAGE_SCN_MEM_DISCARDABLE) { // section is not needed any more and can safely be freed - VirtualFree((LPVOID)(POINTER_TYPE)section->Misc.PhysicalAddress, section->SizeOfRawData, MEM_DECOMMIT); + VirtualFree((LPVOID)((POINTER_TYPE)section->Misc.PhysicalAddress | imageOffset), section->SizeOfRawData, MEM_DECOMMIT); continue; } @@ -163,13 +168,16 @@ FinalizeSections(PMEMORYMODULE module) if (size > 0) { // change memory access flags - if (VirtualProtect((LPVOID)(POINTER_TYPE)section->Misc.PhysicalAddress, section->SizeOfRawData, protect, &oldProtect) == 0) + if (VirtualProtect((LPVOID)((POINTER_TYPE)section->Misc.PhysicalAddress | imageOffset), section->SizeOfRawData, protect, &oldProtect) == 0) #ifdef DEBUG_OUTPUT OutputLastError("Error protecting memory page") #endif ; } } +#ifndef _WIN64 +#undef imageOffset +#endif } static void From b0e63038e248be52c485432f8b9961533bf26f17 Mon Sep 17 00:00:00 2001 From: Joachim Bauch Date: Sun, 24 Oct 2010 22:10:25 +0200 Subject: [PATCH 3/5] removed macro to calculate addresses, not really needed --- MemoryModule.c | 45 ++++++++++++++++++++++----------------------- 1 file changed, 22 insertions(+), 23 deletions(-) diff --git a/MemoryModule.c b/MemoryModule.c index c69de46..d229252 100644 --- a/MemoryModule.c +++ b/MemoryModule.c @@ -54,7 +54,6 @@ typedef struct { typedef BOOL (WINAPI *DllEntryProc)(HINSTANCE hinstDLL, DWORD fdwReason, LPVOID lpReserved); #define GET_HEADER_DICTIONARY(module, idx) &(module)->headers->OptionalHeader.DataDirectory[idx] -#define CALCULATE_ADDRESS(base, offset) (((unsigned char *)(base)) + (offset)) #ifdef DEBUG_OUTPUT static void @@ -88,7 +87,7 @@ CopySections(const unsigned char *data, PIMAGE_NT_HEADERS old_headers, PMEMORYMO size = old_headers->OptionalHeader.SectionAlignment; if (size > 0) { - dest = (unsigned char *)VirtualAlloc((unsigned char *)CALCULATE_ADDRESS(codeBase, section->VirtualAddress), + dest = (unsigned char *)VirtualAlloc(codeBase + section->VirtualAddress, size, MEM_COMMIT, PAGE_READWRITE); @@ -102,11 +101,11 @@ CopySections(const unsigned char *data, PIMAGE_NT_HEADERS old_headers, PMEMORYMO } // commit memory block and copy data from dll - dest = (unsigned char *)VirtualAlloc((unsigned char *)CALCULATE_ADDRESS(codeBase, section->VirtualAddress), + dest = (unsigned char *)VirtualAlloc(codeBase + section->VirtualAddress, section->SizeOfRawData, MEM_COMMIT, PAGE_READWRITE); - memcpy(dest, (unsigned char *)CALCULATE_ADDRESS(data, section->PointerToRawData), section->SizeOfRawData); + memcpy(dest, data + section->PointerToRawData, section->SizeOfRawData); section->Misc.PhysicalAddress = (POINTER_TYPE)dest; } } @@ -189,10 +188,10 @@ PerformBaseRelocation(PMEMORYMODULE module, SIZE_T delta) PIMAGE_DATA_DIRECTORY directory = GET_HEADER_DICTIONARY(module, IMAGE_DIRECTORY_ENTRY_BASERELOC); if (directory->Size > 0) { - PIMAGE_BASE_RELOCATION relocation = (PIMAGE_BASE_RELOCATION)CALCULATE_ADDRESS(codeBase, directory->VirtualAddress); + PIMAGE_BASE_RELOCATION relocation = (PIMAGE_BASE_RELOCATION) (codeBase + directory->VirtualAddress); for (; relocation->VirtualAddress > 0; ) { - unsigned char *dest = (unsigned char *)CALCULATE_ADDRESS(codeBase, relocation->VirtualAddress); + unsigned char *dest = codeBase + relocation->VirtualAddress; unsigned short *relInfo = (unsigned short *)((unsigned char *)relocation + IMAGE_SIZEOF_BASE_RELOCATION); for (i=0; i<((relocation->SizeOfBlock-IMAGE_SIZEOF_BASE_RELOCATION) / 2); i++, relInfo++) { @@ -215,13 +214,13 @@ PerformBaseRelocation(PMEMORYMODULE module, SIZE_T delta) case IMAGE_REL_BASED_HIGHLOW: // change complete 32 bit address - patchAddrHL = (DWORD *)CALCULATE_ADDRESS(dest, offset); + patchAddrHL = (DWORD *) (dest + offset); *patchAddrHL += delta; break; #ifdef _WIN64 case IMAGE_REL_BASED_DIR64: - patchAddr64 = (ULONGLONG *)CALCULATE_ADDRESS(dest, offset); + patchAddr64 = (ULONGLONG *) (dest + offset); *patchAddr64 += delta; break; #endif @@ -233,7 +232,7 @@ PerformBaseRelocation(PMEMORYMODULE module, SIZE_T delta) } // advance to next relocation block - relocation = (PIMAGE_BASE_RELOCATION)CALCULATE_ADDRESS(relocation, relocation->SizeOfBlock); + relocation = (PIMAGE_BASE_RELOCATION) (((char *) relocation) + relocation->SizeOfBlock); } } } @@ -247,12 +246,12 @@ BuildImportTable(PMEMORYMODULE module) PIMAGE_DATA_DIRECTORY directory = GET_HEADER_DICTIONARY(module, IMAGE_DIRECTORY_ENTRY_IMPORT); if (directory->Size > 0) { - PIMAGE_IMPORT_DESCRIPTOR importDesc = (PIMAGE_IMPORT_DESCRIPTOR)CALCULATE_ADDRESS(codeBase, directory->VirtualAddress); + PIMAGE_IMPORT_DESCRIPTOR importDesc = (PIMAGE_IMPORT_DESCRIPTOR) (codeBase + directory->VirtualAddress); for (; !IsBadReadPtr(importDesc, sizeof(IMAGE_IMPORT_DESCRIPTOR)) && importDesc->Name; importDesc++) { POINTER_TYPE *thunkRef; FARPROC *funcRef; - HMODULE handle = LoadLibrary((LPCSTR)CALCULATE_ADDRESS(codeBase, importDesc->Name)); + HMODULE handle = LoadLibrary((LPCSTR) (codeBase + importDesc->Name)); if (handle == INVALID_HANDLE_VALUE) { #if DEBUG_OUTPUT @@ -272,19 +271,19 @@ BuildImportTable(PMEMORYMODULE module) module->modules[module->numModules++] = handle; if (importDesc->OriginalFirstThunk) { - thunkRef = (POINTER_TYPE *)CALCULATE_ADDRESS(codeBase, importDesc->OriginalFirstThunk); - funcRef = (FARPROC *)CALCULATE_ADDRESS(codeBase, importDesc->FirstThunk); + thunkRef = (POINTER_TYPE *) (codeBase + importDesc->OriginalFirstThunk); + funcRef = (FARPROC *) (codeBase + importDesc->FirstThunk); } else { // no hint table - thunkRef = (POINTER_TYPE *)CALCULATE_ADDRESS(codeBase, importDesc->FirstThunk); - funcRef = (FARPROC *)CALCULATE_ADDRESS(codeBase, importDesc->FirstThunk); + thunkRef = (POINTER_TYPE *) (codeBase + importDesc->FirstThunk); + funcRef = (FARPROC *) (codeBase + importDesc->FirstThunk); } for (; *thunkRef; thunkRef++, funcRef++) { if IMAGE_SNAP_BY_ORDINAL(*thunkRef) *funcRef = (FARPROC)GetProcAddress(handle, (LPCSTR)IMAGE_ORDINAL(*thunkRef)); else { - PIMAGE_IMPORT_BY_NAME thunkData = (PIMAGE_IMPORT_BY_NAME)CALCULATE_ADDRESS(codeBase, *thunkRef); + PIMAGE_IMPORT_BY_NAME thunkData = (PIMAGE_IMPORT_BY_NAME) (codeBase + (*thunkRef)); *funcRef = (FARPROC)GetProcAddress(handle, (LPCSTR)&thunkData->Name); } if (*funcRef == 0) @@ -396,7 +395,7 @@ HMEMORYMODULE MemoryLoadLibrary(const void *data) // get entry point of loaded library if (result->headers->OptionalHeader.AddressOfEntryPoint != 0) { - DllEntry = (DllEntryProc)CALCULATE_ADDRESS(code, result->headers->OptionalHeader.AddressOfEntryPoint); + DllEntry = (DllEntryProc) (code + result->headers->OptionalHeader.AddressOfEntryPoint); if (DllEntry == 0) { #if DEBUG_OUTPUT @@ -437,16 +436,16 @@ FARPROC MemoryGetProcAddress(HMEMORYMODULE module, const char *name) // no export table found return NULL; - exports = (PIMAGE_EXPORT_DIRECTORY)CALCULATE_ADDRESS(codeBase, directory->VirtualAddress); + exports = (PIMAGE_EXPORT_DIRECTORY) (codeBase + directory->VirtualAddress); if (exports->NumberOfNames == 0 || exports->NumberOfFunctions == 0) // DLL doesn't export anything return NULL; // search function name in list of exported names - nameRef = (DWORD *)CALCULATE_ADDRESS(codeBase, exports->AddressOfNames); - ordinal = (WORD *)CALCULATE_ADDRESS(codeBase, exports->AddressOfNameOrdinals); + nameRef = (DWORD *) (codeBase + exports->AddressOfNames); + ordinal = (WORD *) (codeBase + exports->AddressOfNameOrdinals); for (i=0; iNumberOfNames; i++, nameRef++, ordinal++) - if (stricmp(name, (const char *)CALCULATE_ADDRESS(codeBase, *nameRef)) == 0) + if (stricmp(name, (const char *) (codeBase + (*nameRef))) == 0) { idx = *ordinal; break; @@ -461,7 +460,7 @@ FARPROC MemoryGetProcAddress(HMEMORYMODULE module, const char *name) return NULL; // AddressOfFunctions contains the RVAs to the "real" functions - return (FARPROC)CALCULATE_ADDRESS(codeBase, *(DWORD *)CALCULATE_ADDRESS(codeBase, exports->AddressOfFunctions + (idx*4))); + return (FARPROC) (codeBase + (*(DWORD *) (codeBase + exports->AddressOfFunctions + (idx*4)))); } void MemoryFreeLibrary(HMEMORYMODULE mod) @@ -474,7 +473,7 @@ void MemoryFreeLibrary(HMEMORYMODULE mod) if (module->initialized != 0) { // notify library about detaching from process - DllEntryProc DllEntry = (DllEntryProc)CALCULATE_ADDRESS(module->codeBase, module->headers->OptionalHeader.AddressOfEntryPoint); + DllEntryProc DllEntry = (DllEntryProc) (module->codeBase + module->headers->OptionalHeader.AddressOfEntryPoint); (*DllEntry)((HINSTANCE)module->codeBase, DLL_PROCESS_DETACH, 0); module->initialized = 0; } From 178ea7363cbbfe69bc622cb813ab7c090522b1a0 Mon Sep 17 00:00:00 2001 From: Joachim Bauch Date: Sun, 24 Oct 2010 22:17:57 +0200 Subject: [PATCH 4/5] updated code layout --- MemoryModule.c | 136 ++++++++++++++++++++++--------------------------- 1 file changed, 61 insertions(+), 75 deletions(-) diff --git a/MemoryModule.c b/MemoryModule.c index d229252..d9b2d0d 100644 --- a/MemoryModule.c +++ b/MemoryModule.c @@ -78,15 +78,12 @@ CopySections(const unsigned char *data, PIMAGE_NT_HEADERS old_headers, PMEMORYMO unsigned char *codeBase = module->codeBase; unsigned char *dest; PIMAGE_SECTION_HEADER section = IMAGE_FIRST_SECTION(module->headers); - for (i=0; iheaders->FileHeader.NumberOfSections; i++, section++) - { - if (section->SizeOfRawData == 0) - { + for (i=0; iheaders->FileHeader.NumberOfSections; i++, section++) { + if (section->SizeOfRawData == 0) { // section doesn't contain data in the dll itself, but may define // uninitialized data size = old_headers->OptionalHeader.SectionAlignment; - if (size > 0) - { + if (size > 0) { dest = (unsigned char *)VirtualAlloc(codeBase + section->VirtualAddress, size, MEM_COMMIT, @@ -135,15 +132,13 @@ FinalizeSections(PMEMORYMODULE module) #endif // loop through all sections and change access flags - for (i=0; iheaders->FileHeader.NumberOfSections; i++, section++) - { + for (i=0; iheaders->FileHeader.NumberOfSections; i++, section++) { DWORD protect, oldProtect, size; int executable = (section->Characteristics & IMAGE_SCN_MEM_EXECUTE) != 0; int readable = (section->Characteristics & IMAGE_SCN_MEM_READ) != 0; int writeable = (section->Characteristics & IMAGE_SCN_MEM_WRITE) != 0; - if (section->Characteristics & IMAGE_SCN_MEM_DISCARDABLE) - { + if (section->Characteristics & IMAGE_SCN_MEM_DISCARDABLE) { // section is not needed any more and can safely be freed VirtualFree((LPVOID)((POINTER_TYPE)section->Misc.PhysicalAddress | imageOffset), section->SizeOfRawData, MEM_DECOMMIT); continue; @@ -151,21 +146,21 @@ FinalizeSections(PMEMORYMODULE module) // determine protection flags based on characteristics protect = ProtectionFlags[executable][readable][writeable]; - if (section->Characteristics & IMAGE_SCN_MEM_NOT_CACHED) + if (section->Characteristics & IMAGE_SCN_MEM_NOT_CACHED) { protect |= PAGE_NOCACHE; + } // determine size of region size = section->SizeOfRawData; - if (size == 0) - { - if (section->Characteristics & IMAGE_SCN_CNT_INITIALIZED_DATA) + if (size == 0) { + if (section->Characteristics & IMAGE_SCN_CNT_INITIALIZED_DATA) { size = module->headers->OptionalHeader.SizeOfInitializedData; - else if (section->Characteristics & IMAGE_SCN_CNT_UNINITIALIZED_DATA) + } else if (section->Characteristics & IMAGE_SCN_CNT_UNINITIALIZED_DATA) { size = module->headers->OptionalHeader.SizeOfUninitializedData; + } } - if (size > 0) - { + if (size > 0) { // change memory access flags if (VirtualProtect((LPVOID)((POINTER_TYPE)section->Misc.PhysicalAddress | imageOffset), section->SizeOfRawData, protect, &oldProtect) == 0) #ifdef DEBUG_OUTPUT @@ -186,15 +181,12 @@ PerformBaseRelocation(PMEMORYMODULE module, SIZE_T delta) unsigned char *codeBase = module->codeBase; PIMAGE_DATA_DIRECTORY directory = GET_HEADER_DICTIONARY(module, IMAGE_DIRECTORY_ENTRY_BASERELOC); - if (directory->Size > 0) - { + if (directory->Size > 0) { PIMAGE_BASE_RELOCATION relocation = (PIMAGE_BASE_RELOCATION) (codeBase + directory->VirtualAddress); - for (; relocation->VirtualAddress > 0; ) - { + for (; relocation->VirtualAddress > 0; ) { unsigned char *dest = codeBase + relocation->VirtualAddress; unsigned short *relInfo = (unsigned short *)((unsigned char *)relocation + IMAGE_SIZEOF_BASE_RELOCATION); - for (i=0; i<((relocation->SizeOfBlock-IMAGE_SIZEOF_BASE_RELOCATION) / 2); i++, relInfo++) - { + for (i=0; i<((relocation->SizeOfBlock-IMAGE_SIZEOF_BASE_RELOCATION) / 2); i++, relInfo++) { DWORD *patchAddrHL; #ifdef _WIN64 ULONGLONG *patchAddr64; @@ -244,16 +236,13 @@ BuildImportTable(PMEMORYMODULE module) unsigned char *codeBase = module->codeBase; PIMAGE_DATA_DIRECTORY directory = GET_HEADER_DICTIONARY(module, IMAGE_DIRECTORY_ENTRY_IMPORT); - if (directory->Size > 0) - { + if (directory->Size > 0) { PIMAGE_IMPORT_DESCRIPTOR importDesc = (PIMAGE_IMPORT_DESCRIPTOR) (codeBase + directory->VirtualAddress); - for (; !IsBadReadPtr(importDesc, sizeof(IMAGE_IMPORT_DESCRIPTOR)) && importDesc->Name; importDesc++) - { + for (; !IsBadReadPtr(importDesc, sizeof(IMAGE_IMPORT_DESCRIPTOR)) && importDesc->Name; importDesc++) { POINTER_TYPE *thunkRef; FARPROC *funcRef; HMODULE handle = LoadLibrary((LPCSTR) (codeBase + importDesc->Name)); - if (handle == INVALID_HANDLE_VALUE) - { + if (handle == INVALID_HANDLE_VALUE) { #if DEBUG_OUTPUT OutputLastError("Can't load library"); #endif @@ -262,15 +251,13 @@ BuildImportTable(PMEMORYMODULE module) } module->modules = (HMODULE *)realloc(module->modules, (module->numModules+1)*(sizeof(HMODULE))); - if (module->modules == NULL) - { + if (module->modules == NULL) { result = 0; break; } module->modules[module->numModules++] = handle; - if (importDesc->OriginalFirstThunk) - { + if (importDesc->OriginalFirstThunk) { thunkRef = (POINTER_TYPE *) (codeBase + importDesc->OriginalFirstThunk); funcRef = (FARPROC *) (codeBase + importDesc->FirstThunk); } else { @@ -278,23 +265,22 @@ BuildImportTable(PMEMORYMODULE module) thunkRef = (POINTER_TYPE *) (codeBase + importDesc->FirstThunk); funcRef = (FARPROC *) (codeBase + importDesc->FirstThunk); } - for (; *thunkRef; thunkRef++, funcRef++) - { - if IMAGE_SNAP_BY_ORDINAL(*thunkRef) + for (; *thunkRef; thunkRef++, funcRef++) { + if (IMAGE_SNAP_BY_ORDINAL(*thunkRef)) { *funcRef = (FARPROC)GetProcAddress(handle, (LPCSTR)IMAGE_ORDINAL(*thunkRef)); - else { + } else { PIMAGE_IMPORT_BY_NAME thunkData = (PIMAGE_IMPORT_BY_NAME) (codeBase + (*thunkRef)); *funcRef = (FARPROC)GetProcAddress(handle, (LPCSTR)&thunkData->Name); } - if (*funcRef == 0) - { + if (*funcRef == 0) { result = 0; break; } } - if (!result) + if (!result) { break; + } } } @@ -312,8 +298,7 @@ HMEMORYMODULE MemoryLoadLibrary(const void *data) BOOL successfull; dos_header = (PIMAGE_DOS_HEADER)data; - if (dos_header->e_magic != IMAGE_DOS_SIGNATURE) - { + if (dos_header->e_magic != IMAGE_DOS_SIGNATURE) { #if DEBUG_OUTPUT OutputDebugString("Not a valid executable file.\n"); #endif @@ -321,8 +306,7 @@ HMEMORYMODULE MemoryLoadLibrary(const void *data) } old_header = (PIMAGE_NT_HEADERS)&((const unsigned char *)(data))[dos_header->e_lfanew]; - if (old_header->Signature != IMAGE_NT_SIGNATURE) - { + if (old_header->Signature != IMAGE_NT_SIGNATURE) { #if DEBUG_OUTPUT OutputDebugString("No PE header found.\n"); #endif @@ -335,21 +319,20 @@ HMEMORYMODULE MemoryLoadLibrary(const void *data) MEM_RESERVE, PAGE_READWRITE); - if (code == NULL) + if (code == NULL) { // try to allocate memory at arbitrary position code = (unsigned char *)VirtualAlloc(NULL, old_header->OptionalHeader.SizeOfImage, MEM_RESERVE, PAGE_READWRITE); - - if (code == NULL) - { + if (code == NULL) { #if DEBUG_OUTPUT - OutputLastError("Can't reserve memory"); + OutputLastError("Can't reserve memory"); #endif - return NULL; + return NULL; + } } - + result = (PMEMORYMODULE)HeapAlloc(GetProcessHeap(), 0, sizeof(MEMORYMODULE)); result->codeBase = code; result->numModules = 0; @@ -381,23 +364,23 @@ HMEMORYMODULE MemoryLoadLibrary(const void *data) // adjust base address of imported data locationDelta = (SIZE_T)(code - old_header->OptionalHeader.ImageBase); - if (locationDelta != 0) + if (locationDelta != 0) { PerformBaseRelocation(result, locationDelta); + } // load required dlls and adjust function table of imports - if (!BuildImportTable(result)) + if (!BuildImportTable(result)) { goto error; + } // mark memory pages depending on section headers and release // sections that are marked as "discardable" FinalizeSections(result); // get entry point of loaded library - if (result->headers->OptionalHeader.AddressOfEntryPoint != 0) - { + if (result->headers->OptionalHeader.AddressOfEntryPoint != 0) { DllEntry = (DllEntryProc) (code + result->headers->OptionalHeader.AddressOfEntryPoint); - if (DllEntry == 0) - { + if (DllEntry == 0) { #if DEBUG_OUTPUT OutputDebugString("Library has no entry point.\n"); #endif @@ -406,8 +389,7 @@ HMEMORYMODULE MemoryLoadLibrary(const void *data) // notify library about attaching to process successfull = (*DllEntry)((HINSTANCE)code, DLL_PROCESS_ATTACH, 0); - if (!successfull) - { + if (!successfull) { #if DEBUG_OUTPUT OutputDebugString("Can't attach library.\n"); #endif @@ -432,32 +414,36 @@ FARPROC MemoryGetProcAddress(HMEMORYMODULE module, const char *name) WORD *ordinal; PIMAGE_EXPORT_DIRECTORY exports; PIMAGE_DATA_DIRECTORY directory = GET_HEADER_DICTIONARY((PMEMORYMODULE)module, IMAGE_DIRECTORY_ENTRY_EXPORT); - if (directory->Size == 0) + if (directory->Size == 0) { // no export table found return NULL; + } exports = (PIMAGE_EXPORT_DIRECTORY) (codeBase + directory->VirtualAddress); - if (exports->NumberOfNames == 0 || exports->NumberOfFunctions == 0) + if (exports->NumberOfNames == 0 || exports->NumberOfFunctions == 0) { // DLL doesn't export anything return NULL; + } // search function name in list of exported names nameRef = (DWORD *) (codeBase + exports->AddressOfNames); ordinal = (WORD *) (codeBase + exports->AddressOfNameOrdinals); - for (i=0; iNumberOfNames; i++, nameRef++, ordinal++) - if (stricmp(name, (const char *) (codeBase + (*nameRef))) == 0) - { + for (i=0; iNumberOfNames; i++, nameRef++, ordinal++) { + if (stricmp(name, (const char *) (codeBase + (*nameRef))) == 0) { idx = *ordinal; break; } + } - if (idx == -1) + if (idx == -1) { // exported symbol not found return NULL; + } - if ((DWORD)idx > exports->NumberOfFunctions) + if ((DWORD)idx > exports->NumberOfFunctions) { // name <-> ordinal number don't match return NULL; + } // AddressOfFunctions contains the RVAs to the "real" functions return (FARPROC) (codeBase + (*(DWORD *) (codeBase + exports->AddressOfFunctions + (idx*4)))); @@ -468,29 +454,29 @@ void MemoryFreeLibrary(HMEMORYMODULE mod) int i; PMEMORYMODULE module = (PMEMORYMODULE)mod; - if (module != NULL) - { - if (module->initialized != 0) - { + if (module != NULL) { + if (module->initialized != 0) { // notify library about detaching from process DllEntryProc DllEntry = (DllEntryProc) (module->codeBase + module->headers->OptionalHeader.AddressOfEntryPoint); (*DllEntry)((HINSTANCE)module->codeBase, DLL_PROCESS_DETACH, 0); module->initialized = 0; } - if (module->modules != NULL) - { + if (module->modules != NULL) { // free previously opened libraries - for (i=0; inumModules; i++) - if (module->modules[i] != INVALID_HANDLE_VALUE) + for (i=0; inumModules; i++) { + if (module->modules[i] != INVALID_HANDLE_VALUE) { FreeLibrary(module->modules[i]); + } + } free(module->modules); } - if (module->codeBase != NULL) + if (module->codeBase != NULL) { // release memory of library VirtualFree(module->codeBase, 0, MEM_RELEASE); + } HeapFree(GetProcessHeap(), 0, module); } From 9e480a552eaabd4cb70b1eb27f4c1d75800ac7e3 Mon Sep 17 00:00:00 2001 From: Joachim Bauch Date: Sun, 24 Oct 2010 22:19:26 +0200 Subject: [PATCH 5/5] use correct size for sections that have no raw size defined but define their data size --- MemoryModule.c | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/MemoryModule.c b/MemoryModule.c index d9b2d0d..c883317 100644 --- a/MemoryModule.c +++ b/MemoryModule.c @@ -162,7 +162,7 @@ FinalizeSections(PMEMORYMODULE module) if (size > 0) { // change memory access flags - if (VirtualProtect((LPVOID)((POINTER_TYPE)section->Misc.PhysicalAddress | imageOffset), section->SizeOfRawData, protect, &oldProtect) == 0) + if (VirtualProtect((LPVOID)((POINTER_TYPE)section->Misc.PhysicalAddress | imageOffset), size, protect, &oldProtect) == 0) #ifdef DEBUG_OUTPUT OutputLastError("Error protecting memory page") #endif