From 178ea7363cbbfe69bc622cb813ab7c090522b1a0 Mon Sep 17 00:00:00 2001 From: Joachim Bauch Date: Sun, 24 Oct 2010 22:17:57 +0200 Subject: [PATCH] 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); }