void
CopySections(const unsigned char *data, PIMAGE_NT_HEADERS old_headers, PMEMORYMODULE module)
{
int i, 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
size = old_headers->OptionalHeader.SectionAlignment;
if (size > 0) {
dest = (unsigned char *)VirtualAlloc(codeBase + section->VirtualAddress,
size,
MEM_COMMIT,
PAGE_READWRITE);
section->Misc.PhysicalAddress = (DWORD) (POINTER_TYPE) dest;
memset(dest, 0, size);
}
// section is empty
continue;
}
// commit memory block and copy data from dll
dest = (unsigned char *)VirtualAlloc(codeBase + section->VirtualAddress,
section->SizeOfRawData,
MEM_COMMIT,
PAGE_READWRITE);
memcpy(dest, data + section->PointerToRawData, section->SizeOfRawData);
section->Misc.PhysicalAddress = (DWORD) (POINTER_TYPE) dest;
}
}
我想从内存中加载一个 dll 文件。上面的代码在http://www.joachim-bauch.de/tutorials/loading-a-dll-from-memory中找到。
我还发现作者说:“文件中没有数据的部分(如已使用变量的数据部分)的 SizeOfRawData 为 0,因此您可以使用 OptionalHeader 的 SizeOfInitializedData 或 SizeOfUninitializedData。必须根据位选择哪个标志 IMAGE_SCN_CNT_INITIALIZED_DATA 和 IMAGE_SCN_CNT_UNINITIALIZED_DATA 可以在部分的特征中设置。”
但是我不明白什么时候 SizeOfRawData 为零,为什么提交的内存大小是 SectionAlignment,既不是 SizeOfInitializedData 也不是 SizeOfUninitializedData。