void MyMapDll(byte
*
DllData,
PVOID
*
BaseAddress,
PSIZE_T ViewSize
) {
/
/
获取基地址
__int64 DllMemoryBase
=
(__int64)&DllData[
0
];
PIMAGE_DOS_HEADER DOSHeader
=
(PIMAGE_DOS_HEADER)DllMemoryBase;
/
/
读出文件DOS头
if
(DOSHeader
-
>e_magic
=
=
IMAGE_DOS_SIGNATURE) {
/
/
检测MZ头
PIMAGE_NT_HEADERS NTHeader
=
(PIMAGE_NT_HEADERS)(DllMemoryBase
+
DOSHeader
-
>e_lfanew);
if
(NTHeader
-
>Signature
=
=
IMAGE_NT_SIGNATURE) {
/
/
检测PE头
PVOID l_location, l_lpBaseAddress;
PIMAGE_SECTION_HEADER Sectionheaders;
__int64 SectionOffset;
SectionOffset
=
DOSHeader
-
>e_lfanew
+
sizeof(IMAGE_NT_HEADERS);
/
/
IMAGE_SECTION_HEADER在内存中的偏移
*
BaseAddress
=
VirtualAlloc(NULL,
NTHeader
-
>OptionalHeader.SizeOfImage,
MEM_COMMIT,
PAGE_EXECUTE_READWRITE);
/
/
分配一块内存供给Dll使用
*
ViewSize
=
NTHeader
-
>OptionalHeader.SizeOfImage;
/
/
下面开始根据SECTION信息将Dll数据逐步映射到内存
int
l_count
=
NTHeader
-
>FileHeader.NumberOfSections;
/
/
拷贝DOS头
RtlMoveMemory(
*
BaseAddress, &DllData[
0
], SectionOffset
+
sizeof(IMAGE_SECTION_HEADER)
*
l_count);
/
/
设置头部的保护
VirtualProtect(&DllData[
0
],
0x1000
, PAGE_READONLY,
0
);
for
(
int
i
=
0
; i < l_count; i
+
+
) {
Sectionheaders
=
(PIMAGE_SECTION_HEADER)(DllMemoryBase
+
SectionOffset);
if
(Sectionheaders
-
>PointerToRawData !
=
0
) {
/
/
如果Sectionheaders
-
>PointerToRawData不为
0
,表示该段是有数据的,需要拷贝。
l_location
=
(PVOID)(DllMemoryBase
+
Sectionheaders
-
>PointerToRawData);
l_lpBaseAddress
=
(PVOID)((__int64)
*
BaseAddress
+
Sectionheaders
-
>VirtualAddress);
/
/
将段数据拷贝到分配的内存中
RtlMoveMemory(l_lpBaseAddress, l_location, Sectionheaders
-
>SizeOfRawData);
/
/
设置保护
VirtualProtect(l_lpBaseAddress,
Sectionheaders
-
>Misc.VirtualSize,
GetProtect(Sectionheaders
-
>Characteristics),
0
);
}
SectionOffset
+
=
sizeof(IMAGE_SECTION_HEADER);
/
/
读取下一个SECTION
}
}
}
}