/*
* Memory DLL loading code
* Version 0.0.4
*
* Copyright (c) 2004-2015 by Joachim Bauch / mail@joachim-bauch.de
* http://www.joachim-bauch.de
*
* The contents of this file are subject to the Mozilla Public License Version
* 2.0 (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
* http://www.mozilla.org/MPL/
*
* Software distributed under the License is distributed on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
* for the specific language governing rights and limitations under the
* License.
*
* The Original Code is MemoryModule.c
*
* The Initial Developer of the Original Code is Joachim Bauch.
*
* Portions created by Joachim Bauch are Copyright (C) 2004-2015
* Joachim Bauch. All Rights Reserved.
*
*
* THeller: Added binary search in MemoryGetProcAddress function
* (#define USE_BINARY_SEARCH to enable it). This gives a very large
* speedup for libraries that exports lots of functions.
*
* These portions are Copyright (C) 2013 Thomas Heller.
*/
#include <windows.h>
#include <winnt.h>
#include <stddef.h>
#include <tchar.h>
#ifdef DEBUG_OUTPUT
#include <stdio.h>
#endif
#if _MSC_VER
// Disable warning about data -> function pointer conversion
#pragma warning(disable:4055)
// C4244: conversion from 'uintptr_t' to 'DWORD', possible loss of data.
#pragma warning(error: 4244)
// C4267: conversion from 'size_t' to 'int', possible loss of data.
#pragma warning(error: 4267)
#define inline __inline
#endif
#ifndef IMAGE_SIZEOF_BASE_RELOCATION
// Vista SDKs no longer define IMAGE_SIZEOF_BASE_RELOCATION!?
#define IMAGE_SIZEOF_BASE_RELOCATION (sizeof(IMAGE_BASE_RELOCATION))
#endif
#ifdef _WIN64
#define HOST_MACHINE IMAGE_FILE_MACHINE_AMD64
#else
#define HOST_MACHINE IMAGE_FILE_MACHINE_I386
#endif
#include "MemoryModule.h"
struct ExportNameEntry {
LPCSTR name;
WORD idx;
};
typedef BOOL (WINAPI *DllEntryProc)(HINSTANCE hinstDLL, DWORD fdwReason, LPVOID lpReserved);
typedef int (WINAPI *ExeEntryProc)(void);
#ifdef _WIN64
typedef struct POINTER_LIST {
struct POINTER_LIST *next;
void *address;
} POINTER_LIST;
#endif
typedef struct {
PIMAGE_NT_HEADERS headers;
unsigned char *codeBase;
HCUSTOMMODULE *modules;
int numModules;
BOOL initialized;
BOOL isDLL;
BOOL isRelocated;
CustomAllocFunc alloc;
CustomFreeFunc free;
CustomLoadLibraryFunc loadLibrary;
CustomGetProcAddressFunc getProcAddress;
CustomFreeLibraryFunc freeLibrary;
struct ExportNameEntry *nameExportsTable;
void *userdata;
ExeEntryProc exeEntry;
DWORD pageSize;
#ifdef _WIN64
POINTER_LIST *blockedMemory;
#endif
} MEMORYMODULE, *PMEMORYMODULE;
typedef struct {
LPVOID address;
LPVOID alignedAddress;
SIZE_T size;
DWORD characteristics;
BOOL last;
} SECTIONFINALIZEDATA, *PSECTIONFINALIZEDATA;
#define GET_HEADER_DICTIONARY(module, idx) &(module)->headers->OptionalHeader.DataDirectory[idx]
static inline uintptr_t
AlignValueDown(uintptr_t value, uintptr_t alignment) {
return value & ~(alignment - 1);
}
static inline LPVOID
AlignAddressDown(LPVOID address, uintptr_t alignment) {
return (LPVOID) AlignValueDown((uintptr_t) address, alignment);
}
static inline size_t
AlignValueUp(size_t value, size_t alignment) {
return (value + alignment - 1) & ~(alignment - 1);
}
static inline void*
OffsetPointer(void* data, ptrdiff_t offset) {
return (void*) ((uintptr_t) data + offset);
}
static inline void
OutputLastError(const char *msg)
{
#ifndef DEBUG_OUTPUT
UNREFERENCED_PARAMETER(msg);
#else
LPVOID tmp;
char *tmpmsg;
FormatMessage(FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS,
NULL, GetLastError(), MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), (LPTSTR)&tmp, 0, NULL);
tmpmsg = (char *)LocalAlloc(LPTR, strlen(msg) + strlen(tmp) + 3);
sprintf(tmpmsg, "%s: %s", msg, tmp);
OutputDebugString(tmpmsg);
LocalFree(tmpmsg);
LocalFree(tmp);
#endif
}
#ifdef _WIN64
static void
FreePointerList(POINTER_LIST *head, CustomFreeFunc freeMemory, void *userdata)
{
POINTER_LIST *node = head;
while (node) {
POINTER_LIST *next;
freeMemory(node->address, 0, MEM_RELEASE, userdata);
next = node->next;
free(node);
node = next;
}
}
#endif
static BOOL
CheckSize(size_t size, size_t expected) {
if (size < expected) {
SetLastError(ERROR_INVALID_DATA);
return FALSE;
}
return TRUE;
}
static BOOL
CopySections(const unsigned char *data, size_t size, PIMAGE_NT_HEADERS old_headers, PMEMORYMODULE module)
{
int i, section_size;
unsigned char *codeBase = module->codeBase;
unsigned char *dest;
PIMAGE_SECTION_HEADER section = IMAGE_FIRST_SECTION(module->headers);
for (i=0; i<module->headers->FileHeader.NumberOfSections; i++, section++) {
if (section->SizeOfRawData == 0) {
// section doesn't contain data in the dll itself, but may define
// uninitialized data
section_size = old_headers->OptionalHeader.SectionAlignment;
if (section_size > 0) {
dest = (unsigned char *)module->alloc(codeBase + section->VirtualAddress,
section_size,
MEM_COMMIT,
PAGE_READWRITE,
module->userdata);
if (dest == NULL) {
return FALSE;
}
// Always use position from file to support alignments smaller
// than page size (allocation above will align to page size).
dest = codeBase + section->VirtualAddress;
// NOTE: On 64bit systems we truncate to 32bit here but expand
// again later when "PhysicalAddress" is used.
section->Misc.PhysicalAddress = (DWORD) ((uintptr_t) dest & 0xffffffff);
memset(dest, 0, section_size);
}
// section is empty
continue;
}
if (!CheckSize(size, section->PointerToRawData + section->SizeOfRawData)) {
return FALSE;
}
// commit memory block and copy data from dll
dest = (unsigned char *)module->alloc(codeBase + section->VirtualAddress,
section->SizeOfRawData,
MEM_COMMIT,
PAGE_READWRITE,
module->userdata);
if (dest == NULL) {
return FALSE;
}
// Always use position from file to support alignments smaller
// than page size (allocation above will align to page size).
dest = codeBase + section->VirtualAddress;
memcpy(dest, data + section->PointerToRawData, section->SizeOfRawData);
// NOTE: On 64bit systems we truncate to 32bit here but expand
// again later when "PhysicalAddress" is used.
section->Misc.PhysicalAddress = (DWORD) ((uintptr_t) dest & 0xffffffff);
}
return TRUE;
}
// Protection flags for memory pages (Executable, Readable, Writeable)
static int ProtectionFlags[2][2][2] = {
{
// not executable
{PAGE_NOACCESS, PAGE_WRITECOPY},
{PAGE_READONLY, PAGE_READWRITE},
}, {
// executable
{PAGE_EXECUTE, PAGE_EXECUTE_WRITECOPY},
{PAGE_EXECUTE_READ, PAGE_EXECUTE_READWRITE},
},
};
static SIZE_T
GetRealSectionSize(PMEMORYMODULE module, PIMAGE_SECTION_HEADER section) {
DWORD size = section->SizeOfRawData;
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) {
size = module->headers->OptionalHeader.SizeOfUninitializedData;
}
}
return (SI
评论0