1
+ #include " Reloc.h"
2
+
3
+ int MakePeHandle (IMAGE_DOS_HEADER* peData, PEHANDLE* pe)
4
+ {
5
+ pe->lpImage = peData;
6
+
7
+ if (peData->e_magic != IMAGE_DOS_SIGNATURE)
8
+ {
9
+ return RELOC_NON_EXECUTABLE;
10
+ }
11
+
12
+ auto header = (IMAGE_NT_HEADERS*)((char *)peData + peData->e_lfanew );
13
+ pe->lpHeader = header;
14
+ pe->firstReloc = 1 ;
15
+
16
+ // Check for the PE signature or the relocated signature
17
+ if (header->Signature != IMAGE_NT_SIGNATURE)
18
+ {
19
+ if (header->Signature != 0x4551 )
20
+ {
21
+ return RELOC_NON_EXECUTABLE;
22
+ }
23
+
24
+ pe->firstReloc = 0 ;
25
+ }
26
+
27
+ if (header->FileHeader .Machine != IMAGE_FILE_MACHINE_I386)
28
+ {
29
+ return RELOC_NON_EXECUTABLE;
30
+ }
31
+
32
+ auto flags = header->FileHeader .Characteristics ;
33
+
34
+ if ((flags & IMAGE_FILE_EXECUTABLE_IMAGE) == 0 || (flags & IMAGE_FILE_DLL) == 0 )
35
+ {
36
+ return RELOC_NON_EXECUTABLE;
37
+ }
38
+
39
+ // Read the sections
40
+ pe->lpSectionTable = IMAGE_FIRST_SECTION (header);
41
+
42
+ if (header->FileHeader .NumberOfSections <= 0 )
43
+ {
44
+ return RELOC_SUCCESS;
45
+ }
46
+
47
+ for (int i = 0 ; i < header->FileHeader .NumberOfSections ; i++)
48
+ {
49
+ auto section = pe->lpSectionTable [i];
50
+
51
+ if (section.Misc .VirtualSize > section.SizeOfRawData )
52
+ {
53
+ // Since there is no virtual memory allocated for the sections the raw data size
54
+ // cannot be smaller than the virtual size
55
+ return RELOC_INVALID_SECTION;
56
+ }
57
+
58
+ // Check if the section is executable
59
+ if (pe->firstReloc && (section.Characteristics & IMAGE_SCN_CNT_CODE) != 0 )
60
+ {
61
+ // Change the protection of the memory region to executable to allow code to execute
62
+ // even with the Data Execution Prevention (DEP) enabled in Windows.
63
+ DWORD oldProtect;
64
+ VirtualProtect ((void *)((char *)peData + section.PointerToRawData ), section.SizeOfRawData , PAGE_EXECUTE_READWRITE, &oldProtect);
65
+ }
66
+
67
+ // Set the virtual size to the raw size since there's no virtual memory allocated
68
+ pe->lpSectionTable [i].Misc .VirtualSize = section.SizeOfRawData ;
69
+ }
70
+
71
+ return RELOC_SUCCESS;
72
+ }
0 commit comments