3 * COPYRIGHT: See COPYING in the top level directory
4 * PROJECT: ReactOS kernel
5 * FILE: ntoskrnl/ldr/loader.c
6 * PURPOSE: Loaders for PE executables
8 * PROGRAMMERS: Jean Michault
9 * Rex Jolliff (rex@lvcablemodem.com)
10 * Jason Filby (jasonfilby@yahoo.com)
11 * Casper S. Hornstrup (chorns@users.sourceforge.net)
15 /* INCLUDES *****************************************************************/
20 #include <internal/ntosdbg.h>
30 #include <internal/debug.h>
32 /* GLOBALS *******************************************************************/
34 LIST_ENTRY ModuleListHead
;
35 KSPIN_LOCK ModuleListLock
;
36 MODULE_OBJECT NtoskrnlModuleObject
;
37 MODULE_OBJECT HalModuleObject
;
39 LIST_ENTRY ModuleTextListHead
;
40 STATIC MODULE_TEXT_SECTION NtoskrnlTextSection
;
41 STATIC MODULE_TEXT_SECTION LdrHalTextSection
;
45 #define HIWORD(X) ((WORD) (((DWORD) (X) >> 16) & 0xFFFF))
48 #define LOWORD(X) ((WORD) (X))
51 /* FORWARD DECLARATIONS ******************************************************/
56 PUNICODE_STRING ModuleName
,
57 PMODULE_OBJECT
*ModuleObject
);
60 LdrpBuildModuleBaseName (
61 PUNICODE_STRING BaseName
,
62 PUNICODE_STRING FullName
);
65 LdrpCompareModuleNames (
66 IN PUNICODE_STRING String1
,
67 IN PUNICODE_STRING String2
);
70 /* PE Driver load support */
74 PUNICODE_STRING FileName
,
75 PMODULE_OBJECT
*ModuleObject
);
78 LdrPEGetExportByName (
84 LdrPEFixupForward ( PCHAR ForwardName
);
87 LdrPEPerformRelocations (
92 LdrPEFixupImports ( PMODULE_OBJECT Module
);
94 /* FUNCTIONS *****************************************************************/
97 LdrInitDebug ( PLOADER_MODULE Module
, PWCH Name
)
99 PLIST_ENTRY current_entry
;
100 MODULE_TEXT_SECTION
* current
;
102 current_entry
= ModuleTextListHead
.Flink
;
103 while (current_entry
!= &ModuleTextListHead
)
106 CONTAINING_RECORD(current_entry
, MODULE_TEXT_SECTION
, ListEntry
);
107 if (wcscmp(current
->Name
, Name
) == 0)
111 current_entry
= current_entry
->Flink
;
114 if (current_entry
== &ModuleTextListHead
)
123 PIMAGE_NT_HEADERS NtHeader
;
124 PIMAGE_SECTION_HEADER SectionList
;
126 InitializeListHead(&ModuleTextListHead
);
128 /* Setup ntoskrnl.exe text section */
130 * This isn't the base of the text segment, but the start of the
131 * full image (in memory)
132 * Also, the Length field isn't set to the length of the segment,
133 * but is more like the offset, from the image base, to the end
136 NtHeader
= RtlImageNtHeader((PVOID
)KERNEL_BASE
);
137 SectionList
= IMAGE_FIRST_SECTION(NtHeader
);
138 NtoskrnlTextSection
.Base
= KERNEL_BASE
;
139 NtoskrnlTextSection
.Length
= SectionList
[0].Misc
.VirtualSize
140 + SectionList
[0].VirtualAddress
;
141 NtoskrnlTextSection
.Name
= KERNEL_MODULE_NAME
;
142 NtoskrnlTextSection
.OptionalHeader
= OPTHDROFFSET(KERNEL_BASE
);
143 InsertTailList(&ModuleTextListHead
, &NtoskrnlTextSection
.ListEntry
);
145 /* Setup hal.dll text section */
146 /* Same comment as above applies */
147 NtHeader
= RtlImageNtHeader((PVOID
)LdrHalBase
);
148 SectionList
= IMAGE_FIRST_SECTION(NtHeader
);
149 LdrHalTextSection
.Base
= LdrHalBase
;
150 LdrHalTextSection
.Length
= SectionList
[0].Misc
.VirtualSize
151 + SectionList
[0].VirtualAddress
;
152 LdrHalTextSection
.Name
= HAL_MODULE_NAME
;
153 LdrHalTextSection
.OptionalHeader
= OPTHDROFFSET(LdrHalBase
);
154 InsertTailList(&ModuleTextListHead
, &LdrHalTextSection
.ListEntry
);
156 /* Hook for KDB on initialization of the loader. */
157 KDB_LOADERINIT_HOOK(&NtoskrnlTextSection
, &LdrHalTextSection
);
161 LdrInitModuleManagement ( VOID
)
163 PIMAGE_NT_HEADERS NtHeader
;
165 /* Initialize the module list and spinlock */
166 InitializeListHead(&ModuleListHead
);
167 KeInitializeSpinLock(&ModuleListLock
);
169 /* Initialize ModuleObject for NTOSKRNL */
170 RtlZeroMemory(&NtoskrnlModuleObject
, sizeof(MODULE_OBJECT
));
171 NtoskrnlModuleObject
.Base
= (PVOID
) KERNEL_BASE
;
172 NtoskrnlModuleObject
.Flags
= MODULE_FLAG_PE
;
173 RtlInitUnicodeString(&NtoskrnlModuleObject
.FullName
, KERNEL_MODULE_NAME
);
174 LdrpBuildModuleBaseName(&NtoskrnlModuleObject
.BaseName
, &NtoskrnlModuleObject
.FullName
);
176 NtHeader
= RtlImageNtHeader((PVOID
)KERNEL_BASE
);
177 NtoskrnlModuleObject
.Image
.PE
.FileHeader
= &NtHeader
->FileHeader
;
178 NtoskrnlModuleObject
.Image
.PE
.OptionalHeader
= &NtHeader
->OptionalHeader
;
179 NtoskrnlModuleObject
.Image
.PE
.SectionList
= IMAGE_FIRST_SECTION(NtHeader
);
180 NtoskrnlModuleObject
.EntryPoint
= (PVOID
) ((ULONG_PTR
) NtoskrnlModuleObject
.Base
+ NtHeader
->OptionalHeader
.AddressOfEntryPoint
);
181 DPRINT("ModuleObject:%08x entrypoint at %x\n", &NtoskrnlModuleObject
, NtoskrnlModuleObject
.EntryPoint
);
182 NtoskrnlModuleObject
.Length
= NtoskrnlModuleObject
.Image
.PE
.OptionalHeader
->SizeOfImage
;
183 NtoskrnlModuleObject
.TextSection
= &NtoskrnlTextSection
;
185 InsertTailList(&ModuleListHead
,
186 &NtoskrnlModuleObject
.ListEntry
);
188 /* Initialize ModuleObject for HAL */
189 RtlZeroMemory(&HalModuleObject
, sizeof(MODULE_OBJECT
));
190 HalModuleObject
.Base
= (PVOID
) LdrHalBase
;
191 HalModuleObject
.Flags
= MODULE_FLAG_PE
;
193 RtlInitUnicodeString(&HalModuleObject
.FullName
, HAL_MODULE_NAME
);
194 LdrpBuildModuleBaseName(&HalModuleObject
.BaseName
, &HalModuleObject
.FullName
);
196 NtHeader
= RtlImageNtHeader((PVOID
)LdrHalBase
);
197 HalModuleObject
.Image
.PE
.FileHeader
= &NtHeader
->FileHeader
;
198 HalModuleObject
.Image
.PE
.OptionalHeader
= &NtHeader
->OptionalHeader
;
199 HalModuleObject
.Image
.PE
.SectionList
= IMAGE_FIRST_SECTION(NtHeader
);
200 HalModuleObject
.EntryPoint
= (PVOID
) ((ULONG_PTR
) HalModuleObject
.Base
+ NtHeader
->OptionalHeader
.AddressOfEntryPoint
);
201 DPRINT("ModuleObject:%08x entrypoint at %x\n", &HalModuleObject
, HalModuleObject
.EntryPoint
);
202 HalModuleObject
.Length
= HalModuleObject
.Image
.PE
.OptionalHeader
->SizeOfImage
;
203 HalModuleObject
.TextSection
= &LdrHalTextSection
;
205 InsertTailList(&ModuleListHead
,
206 &HalModuleObject
.ListEntry
);
211 PUNICODE_STRING DriverName
,
213 PVOID
*SectionPointer
,
215 PVOID
*ExportSectionPointer
)
217 PMODULE_OBJECT ModuleObject
;
220 ModuleObject
= LdrGetModuleObject(DriverName
);
221 if (ModuleObject
== NULL
)
223 Status
= LdrLoadModule(DriverName
, &ModuleObject
);
224 if (!NT_SUCCESS(Status
))
231 *ModuleBase
= ModuleObject
->Base
;
233 //if (SectionPointer)
234 // *SectionPointer = ModuleObject->
237 *EntryPoint
= ModuleObject
->EntryPoint
;
239 //if (ExportSectionPointer)
240 // *ExportSectionPointer = ModuleObject->
242 return(STATUS_SUCCESS
);
247 LdrpUnloadImage ( PVOID ModuleBase
)
249 return(STATUS_NOT_IMPLEMENTED
);
254 LdrpLoadAndCallImage ( PUNICODE_STRING ModuleName
)
256 PDRIVER_INITIALIZE DriverEntry
;
257 PMODULE_OBJECT ModuleObject
;
260 ModuleObject
= LdrGetModuleObject(ModuleName
);
261 if (ModuleObject
!= NULL
)
263 return(STATUS_IMAGE_ALREADY_LOADED
);
266 Status
= LdrLoadModule(ModuleName
, &ModuleObject
);
267 if (!NT_SUCCESS(Status
))
272 DriverEntry
= (PDRIVER_INITIALIZE
)ModuleObject
->EntryPoint
;
274 Status
= DriverEntry(NULL
, NULL
);
275 if (!NT_SUCCESS(Status
))
277 LdrUnloadModule(ModuleObject
);
286 PUNICODE_STRING Filename
,
287 PMODULE_OBJECT
*ModuleObject
)
289 PVOID ModuleLoadBase
;
292 OBJECT_ATTRIBUTES ObjectAttributes
;
293 PMODULE_OBJECT Module
;
294 FILE_STANDARD_INFORMATION FileStdInfo
;
295 IO_STATUS_BLOCK IoStatusBlock
;
297 *ModuleObject
= NULL
;
299 DPRINT("Loading Module %wZ...\n", Filename
);
301 /* Open the Module */
302 InitializeObjectAttributes(&ObjectAttributes
,
304 OBJ_CASE_INSENSITIVE
,
308 Status
= ZwOpenFile(&FileHandle
,
313 FILE_SYNCHRONOUS_IO_NONALERT
);
315 if (!NT_SUCCESS(Status
))
317 CPRINT("Could not open module file: %wZ\n", Filename
);
322 /* Get the size of the file */
323 Status
= ZwQueryInformationFile(FileHandle
,
327 FileStandardInformation
);
328 if (!NT_SUCCESS(Status
))
330 CPRINT("Could not get file size\n");
336 /* Allocate nonpageable memory for driver */
337 ModuleLoadBase
= ExAllocatePoolWithTag(NonPagedPool
,
338 FileStdInfo
.EndOfFile
.u
.LowPart
,
340 if (ModuleLoadBase
== NULL
)
342 CPRINT("Could not allocate memory for module");
344 return(STATUS_INSUFFICIENT_RESOURCES
);
348 /* Load driver into memory chunk */
349 Status
= ZwReadFile(FileHandle
,
353 FileStdInfo
.EndOfFile
.u
.LowPart
,
355 if (!NT_SUCCESS(Status
))
357 CPRINT("Could not read module file into memory");
358 ExFreePool(ModuleLoadBase
);
366 Status
= LdrProcessModule(ModuleLoadBase
,
369 if (!NT_SUCCESS(Status
))
371 CPRINT("Could not process module\n");
372 ExFreePool(ModuleLoadBase
);
377 ExFreePool(ModuleLoadBase
);
379 *ModuleObject
= Module
;
381 /* Hook for KDB on loading a driver. */
382 KDB_LOADDRIVER_HOOK(Filename
, Module
);
384 return(STATUS_SUCCESS
);
389 LdrUnloadModule ( PMODULE_OBJECT ModuleObject
)
393 /* Remove the module from the module list */
394 KeAcquireSpinLock(&ModuleListLock
,&Irql
);
395 RemoveEntryList(&ModuleObject
->ListEntry
);
396 KeReleaseSpinLock(&ModuleListLock
, Irql
);
398 /* Hook for KDB on unloading a driver. */
399 KDB_UNLOADDRIVER_HOOK(ModuleObject
);
401 /* Free text section */
402 if (ModuleObject
->TextSection
!= NULL
)
404 ExFreePool(ModuleObject
->TextSection
->Name
);
405 RemoveEntryList(&ModuleObject
->TextSection
->ListEntry
);
406 ExFreePool(ModuleObject
->TextSection
);
407 ModuleObject
->TextSection
= NULL
;
410 /* Free module section */
411 // MmFreeSection(ModuleObject->Base);
413 ExFreePool(ModuleObject
->FullName
.Buffer
);
414 ExFreePool(ModuleObject
);
416 return(STATUS_SUCCESS
);
422 PVOID ModuleLoadBase
,
423 PUNICODE_STRING ModuleName
,
424 PMODULE_OBJECT
*ModuleObject
)
426 PIMAGE_DOS_HEADER PEDosHeader
;
428 /* If MZ header exists */
429 PEDosHeader
= (PIMAGE_DOS_HEADER
) ModuleLoadBase
;
430 if (PEDosHeader
->e_magic
== IMAGE_DOS_SIGNATURE
&& PEDosHeader
->e_lfanew
!= 0L)
432 return LdrPEProcessModule(ModuleLoadBase
,
437 CPRINT("Module wasn't PE\n");
438 return STATUS_UNSUCCESSFUL
;
442 LdrpQueryModuleInformation (
447 PLIST_ENTRY current_entry
;
448 PMODULE_OBJECT current
;
449 ULONG ModuleCount
= 0;
450 PSYSTEM_MODULE_INFORMATION Smi
;
451 ANSI_STRING AnsiName
;
455 KeAcquireSpinLock(&ModuleListLock
,&Irql
);
457 /* calculate required size */
458 current_entry
= ModuleListHead
.Flink
;
459 while (current_entry
!= (&ModuleListHead
))
462 current_entry
= current_entry
->Flink
;
465 *ReqSize
= sizeof(SYSTEM_MODULE_INFORMATION
)+
466 (ModuleCount
- 1) * sizeof(SYSTEM_MODULE_INFORMATION_ENTRY
);
470 KeReleaseSpinLock(&ModuleListLock
, Irql
);
471 return(STATUS_INFO_LENGTH_MISMATCH
);
474 /* fill the buffer */
475 memset(Buffer
, '=', Size
);
477 Smi
= (PSYSTEM_MODULE_INFORMATION
)Buffer
;
478 Smi
->Count
= ModuleCount
;
481 current_entry
= ModuleListHead
.Flink
;
482 while (current_entry
!= (&ModuleListHead
))
484 current
= CONTAINING_RECORD(current_entry
,MODULE_OBJECT
,ListEntry
);
486 Smi
->Module
[ModuleCount
].Unknown1
= 0; /* Always 0 */
487 Smi
->Module
[ModuleCount
].Unknown2
= 0; /* Always 0 */
488 Smi
->Module
[ModuleCount
].Base
= current
->Base
;
489 Smi
->Module
[ModuleCount
].Size
= current
->Length
;
490 Smi
->Module
[ModuleCount
].Flags
= 0; /* Flags ??? (GN) */
491 Smi
->Module
[ModuleCount
].Index
= (USHORT
)ModuleCount
;
492 Smi
->Module
[ModuleCount
].NameLength
= 0;
493 Smi
->Module
[ModuleCount
].LoadCount
= 0; /* FIXME */
496 AnsiName
.MaximumLength
= 256;
497 AnsiName
.Buffer
= Smi
->Module
[ModuleCount
].ImageName
;
498 RtlUnicodeStringToAnsiString(&AnsiName
,
502 p
= strrchr(AnsiName
.Buffer
, '\\');
505 Smi
->Module
[ModuleCount
].PathLength
= 0;
510 Smi
->Module
[ModuleCount
].PathLength
= p
- AnsiName
.Buffer
;
514 current_entry
= current_entry
->Flink
;
517 KeReleaseSpinLock(&ModuleListLock
, Irql
);
519 return(STATUS_SUCCESS
);
524 LdrpBuildModuleBaseName (
525 PUNICODE_STRING BaseName
,
526 PUNICODE_STRING FullName
)
530 DPRINT("LdrpBuildModuleBaseName()\n");
531 DPRINT("FullName %wZ\n", FullName
);
533 p
= wcsrchr(FullName
->Buffer
, L
'\\');
536 p
= FullName
->Buffer
;
545 RtlInitUnicodeString(BaseName
, p
);
550 LdrpCompareModuleNames (
551 IN PUNICODE_STRING String1
,
552 IN PUNICODE_STRING String2
)
558 if (String1
&& String2
)
560 /* Search String1 for last path component */
561 len1
= String1
->Length
/ sizeof(WCHAR
);
562 s1
= String1
->Buffer
;
563 for (i
= 0, p
= String1
->Buffer
; i
< String1
->Length
; i
= i
+ sizeof(WCHAR
), p
++)
567 if (i
== String1
->Length
- sizeof(WCHAR
))
575 len1
= (String1
->Length
- i
) / sizeof(WCHAR
);
580 /* Search String2 for last path component */
581 len2
= String2
->Length
/ sizeof(WCHAR
);
582 s2
= String2
->Buffer
;
583 for (i
= 0, p
= String2
->Buffer
; i
< String2
->Length
; i
= i
+ sizeof(WCHAR
), p
++)
587 if (i
== String2
->Length
- sizeof(WCHAR
))
595 len2
= (String2
->Length
- i
) / sizeof(WCHAR
);
600 /* Compare last path components */
605 c1
= len1
-- ? RtlUpcaseUnicodeChar (*s1
++) : 0;
606 c2
= len2
-- ? RtlUpcaseUnicodeChar (*s2
++) : 0;
607 if ((c1
== 0 && c2
== L
'.') || (c1
== L
'.' && c2
== 0))
609 if (!c1
|| !c2
|| c1
!= c2
)
619 LdrGetModuleObject ( PUNICODE_STRING ModuleName
)
621 PMODULE_OBJECT Module
;
625 DPRINT("LdrGetModuleObject(%wZ) called\n", ModuleName
);
627 KeAcquireSpinLock(&ModuleListLock
,&Irql
);
629 Entry
= ModuleListHead
.Flink
;
630 while (Entry
!= &ModuleListHead
)
632 Module
= CONTAINING_RECORD(Entry
, MODULE_OBJECT
, ListEntry
);
634 DPRINT("Comparing %wZ and %wZ\n",
638 if (!LdrpCompareModuleNames(&Module
->BaseName
, ModuleName
))
640 DPRINT("Module %wZ\n", &Module
->BaseName
);
641 KeReleaseSpinLock(&ModuleListLock
, Irql
);
645 Entry
= Entry
->Flink
;
648 KeReleaseSpinLock(&ModuleListLock
, Irql
);
650 DPRINT("Could not find module '%wZ'\n", ModuleName
);
656 /* ---------------------------------------------- PE Module support */
659 LdrLookupPageProtection (
662 PIMAGE_FILE_HEADER PEFileHeader
,
663 PIMAGE_SECTION_HEADER PESectionHeaders
)
665 BOOLEAN Write
= FALSE
;
666 BOOLEAN Execute
= FALSE
;
667 ULONG Characteristics
;
672 for (Idx
= 0; Idx
< PEFileHeader
->NumberOfSections
&& (!Write
|| !Execute
); Idx
++)
674 Characteristics
= PESectionHeaders
[Idx
].Characteristics
;
675 if (!(Characteristics
& IMAGE_SCN_TYPE_NOLOAD
))
677 Length
= max(PESectionHeaders
[Idx
].Misc
.VirtualSize
, PESectionHeaders
[Idx
].SizeOfRawData
);
678 BaseAddress
= PESectionHeaders
[Idx
].VirtualAddress
+ (char*)DriverBase
;
679 if (BaseAddress
< (PVOID
)((ULONG_PTR
)PageStart
+ PAGE_SIZE
) &&
680 PageStart
< (PVOID
)((ULONG_PTR
)BaseAddress
+ Length
))
682 if (Characteristics
& IMAGE_SCN_CNT_CODE
)
686 if (Characteristics
& (IMAGE_SCN_MEM_WRITE
|IMAGE_SCN_CNT_UNINITIALIZED_DATA
))
693 if (Write
&& Execute
)
695 return PAGE_EXECUTE_READWRITE
;
699 return PAGE_EXECUTE_READ
;
703 return PAGE_READWRITE
;
707 return PAGE_READONLY
;
713 PVOID ModuleLoadBase
,
714 PUNICODE_STRING FileName
,
715 PMODULE_OBJECT
*ModuleObject
)
717 unsigned int DriverSize
, Idx
;
720 PIMAGE_DOS_HEADER PEDosHeader
;
721 PIMAGE_NT_HEADERS PENtHeaders
;
722 PIMAGE_SECTION_HEADER PESectionHeaders
;
723 PMODULE_OBJECT CreatedModuleObject
;
724 MODULE_TEXT_SECTION
* ModuleTextSection
;
728 DPRINT("Processing PE Module at module base:%08lx\n", ModuleLoadBase
);
730 /* Get header pointers */
731 PEDosHeader
= (PIMAGE_DOS_HEADER
) ModuleLoadBase
;
732 PENtHeaders
= RtlImageNtHeader(ModuleLoadBase
);
733 PESectionHeaders
= IMAGE_FIRST_SECTION(PENtHeaders
);
736 /* Check file magic numbers */
737 if (PEDosHeader
->e_magic
!= IMAGE_DOS_SIGNATURE
)
739 CPRINT("Incorrect MZ magic: %04x\n", PEDosHeader
->e_magic
);
740 return STATUS_UNSUCCESSFUL
;
742 if (PEDosHeader
->e_lfanew
== 0)
744 CPRINT("Invalid lfanew offset: %08x\n", PEDosHeader
->e_lfanew
);
745 return STATUS_UNSUCCESSFUL
;
747 if (PENtHeaders
->Signature
!= IMAGE_NT_SIGNATURE
)
749 CPRINT("Incorrect PE magic: %08x\n", PENtHeaders
->Signature
);
750 return STATUS_UNSUCCESSFUL
;
752 if (PENtHeaders
->FileHeader
.Machine
!= IMAGE_FILE_MACHINE_I386
)
754 CPRINT("Incorrect Architechture: %04x\n", PENtHeaders
->FileHeader
.Machine
);
755 return STATUS_UNSUCCESSFUL
;
759 /* FIXME: if image is fixed-address load, then fail */
761 /* FIXME: check/verify OS version number */
763 DPRINT("OptionalHdrMagic:%04x LinkVersion:%d.%d\n",
764 PENtHeaders
->OptionalHeader
.Magic
,
765 PENtHeaders
->OptionalHeader
.MajorLinkerVersion
,
766 PENtHeaders
->OptionalHeader
.MinorLinkerVersion
);
767 DPRINT("Entry Point:%08lx\n", PENtHeaders
->OptionalHeader
.AddressOfEntryPoint
);
769 /* Determine the size of the module */
771 for (Idx
= 0; Idx
< PENtHeaders
->FileHeader
.NumberOfSections
; Idx
++)
773 if (!(PESectionHeaders
[Idx
].Characteristics
& IMAGE_SCN_TYPE_NOLOAD
))
775 CurrentSize
= PESectionHeaders
[Idx
].VirtualAddress
+ PESectionHeaders
[Idx
].Misc
.VirtualSize
;
776 DriverSize
= max(DriverSize
, CurrentSize
);
779 DriverSize
= ROUND_UP(DriverSize
, PENtHeaders
->OptionalHeader
.SectionAlignment
);
780 DPRINT("DriverSize %x, SizeOfImage %x\n",DriverSize
, PENtHeaders
->OptionalHeader
.SizeOfImage
);
782 /* Allocate a virtual section for the module */
784 DriverBase
= MmAllocateSection(DriverSize
, DriverBase
);
787 CPRINT("Failed to allocate a virtual section for driver\n");
788 return STATUS_UNSUCCESSFUL
;
790 DPRINT("DriverBase for %wZ: %x\n", FileName
, DriverBase
);
792 /* Copy headers over */
793 memcpy(DriverBase
, ModuleLoadBase
, PENtHeaders
->OptionalHeader
.SizeOfHeaders
);
795 /* Copy image sections into virtual section */
796 for (Idx
= 0; Idx
< PENtHeaders
->FileHeader
.NumberOfSections
; Idx
++)
798 CurrentSize
= PESectionHeaders
[Idx
].VirtualAddress
+ PESectionHeaders
[Idx
].Misc
.VirtualSize
;
799 /* Copy current section into current offset of virtual section */
800 if (CurrentSize
<= DriverSize
&&
801 PESectionHeaders
[Idx
].SizeOfRawData
)
803 DPRINT("PESectionHeaders[Idx].VirtualAddress + DriverBase %x\n",
804 PESectionHeaders
[Idx
].VirtualAddress
+ (ULONG_PTR
)DriverBase
);
805 memcpy((PVOID
)((ULONG_PTR
)DriverBase
+ PESectionHeaders
[Idx
].VirtualAddress
),
806 (PVOID
)((ULONG_PTR
)ModuleLoadBase
+ PESectionHeaders
[Idx
].PointerToRawData
),
807 PESectionHeaders
[Idx
].Misc
.VirtualSize
> PESectionHeaders
[Idx
].SizeOfRawData
808 ? PESectionHeaders
[Idx
].SizeOfRawData
: PESectionHeaders
[Idx
].Misc
.VirtualSize
);
812 /* Perform relocation fixups */
813 Status
= LdrPEPerformRelocations(DriverBase
, DriverSize
);
814 if (!NT_SUCCESS(Status
))
816 // MmFreeSection(DriverBase);
820 /* Create the module */
821 CreatedModuleObject
= ExAllocatePoolWithTag (
822 NonPagedPool
, sizeof(MODULE_OBJECT
), TAG_MODULE_OBJECT
);
823 if (CreatedModuleObject
== NULL
)
825 // MmFreeSection(DriverBase);
826 return STATUS_INSUFFICIENT_RESOURCES
;
829 RtlZeroMemory(CreatedModuleObject
, sizeof(MODULE_OBJECT
));
831 /* Initialize ModuleObject data */
832 CreatedModuleObject
->Base
= DriverBase
;
833 CreatedModuleObject
->Flags
= MODULE_FLAG_PE
;
835 CreatedModuleObject
->FullName
.Length
= 0;
836 CreatedModuleObject
->FullName
.MaximumLength
= FileName
->Length
+ sizeof(UNICODE_NULL
);
837 CreatedModuleObject
->FullName
.Buffer
=
838 ExAllocatePoolWithTag(PagedPool
, CreatedModuleObject
->FullName
.MaximumLength
, TAG_LDR_WSTR
);
839 if (CreatedModuleObject
->FullName
.Buffer
== NULL
)
841 ExFreePool(CreatedModuleObject
);
842 // MmFreeSection(DriverBase);
843 return STATUS_INSUFFICIENT_RESOURCES
;
846 RtlCopyUnicodeString(&CreatedModuleObject
->FullName
, FileName
);
847 LdrpBuildModuleBaseName(&CreatedModuleObject
->BaseName
,
848 &CreatedModuleObject
->FullName
);
850 CreatedModuleObject
->EntryPoint
=
851 (PVOID
)((ULONG_PTR
)DriverBase
+
852 PENtHeaders
->OptionalHeader
.AddressOfEntryPoint
);
853 CreatedModuleObject
->Length
= DriverSize
;
854 DPRINT("EntryPoint at %x\n", CreatedModuleObject
->EntryPoint
);
856 CreatedModuleObject
->Image
.PE
.FileHeader
=
857 (PIMAGE_FILE_HEADER
) ((unsigned int) DriverBase
+ PEDosHeader
->e_lfanew
+ sizeof(ULONG
));
859 DPRINT("FileHeader at %x\n", CreatedModuleObject
->Image
.PE
.FileHeader
);
860 CreatedModuleObject
->Image
.PE
.OptionalHeader
=
861 (PIMAGE_OPTIONAL_HEADER
) ((unsigned int) DriverBase
+ PEDosHeader
->e_lfanew
+ sizeof(ULONG
) +
862 sizeof(IMAGE_FILE_HEADER
));
863 DPRINT("OptionalHeader at %x\n", CreatedModuleObject
->Image
.PE
.OptionalHeader
);
864 CreatedModuleObject
->Image
.PE
.SectionList
=
865 (PIMAGE_SECTION_HEADER
) ((unsigned int) DriverBase
+ PEDosHeader
->e_lfanew
+ sizeof(ULONG
) +
866 sizeof(IMAGE_FILE_HEADER
) + CreatedModuleObject
->Image
.PE
.FileHeader
->SizeOfOptionalHeader
);
867 DPRINT("SectionList at %x\n", CreatedModuleObject
->Image
.PE
.SectionList
);
869 /* Perform import fixups */
870 Status
= LdrPEFixupImports(CreatedModuleObject
);
871 if (!NT_SUCCESS(Status
))
873 // MmFreeSection(DriverBase);
874 ExFreePool(CreatedModuleObject
->FullName
.Buffer
);
875 ExFreePool(CreatedModuleObject
);
879 MmSetPageProtect(NULL
, DriverBase
, PAGE_READONLY
);
880 /* Set the protections for the various parts of the driver */
881 for (Idx
= 0; Idx
< PENtHeaders
->FileHeader
.NumberOfSections
; Idx
++)
883 ULONG Characteristics
= PESectionHeaders
[Idx
].Characteristics
;
888 Length
= PESectionHeaders
[Idx
].Misc
.VirtualSize
;
889 BaseAddress
= PESectionHeaders
[Idx
].VirtualAddress
+ (char*)DriverBase
;
890 PageAddress
= (PVOID
)PAGE_ROUND_DOWN(BaseAddress
);
892 Protect
= LdrLookupPageProtection(PageAddress
, DriverBase
, &PENtHeaders
->FileHeader
, PESectionHeaders
);
896 * This driver modifies a string in the first page of the text section while initialising.
898 if (0 == _wcsicmp(L
"fireport.sys", FileName
->Buffer
))
900 Protect
= PAGE_EXECUTE_READWRITE
;
903 if (PageAddress
< DriverBase
+ DriverSize
)
905 MmSetPageProtect(NULL
, PageAddress
, Protect
);
908 if (Characteristics
& IMAGE_SCN_CNT_CODE
)
910 if (Characteristics
& IMAGE_SCN_MEM_WRITE
)
912 Protect
= PAGE_EXECUTE_READWRITE
;
916 Protect
= PAGE_EXECUTE_READ
;
919 else if (Characteristics
& (IMAGE_SCN_MEM_WRITE
|IMAGE_SCN_CNT_UNINITIALIZED_DATA
))
921 Protect
= PAGE_READWRITE
;
925 Protect
= PAGE_READONLY
;
927 PageAddress
= (PVOID
)((ULONG_PTR
)PageAddress
+ PAGE_SIZE
);
928 while ((ULONG_PTR
)PageAddress
+ PAGE_SIZE
< (ULONG_PTR
)BaseAddress
+ Length
)
930 if (PageAddress
< DriverBase
+ DriverSize
)
932 MmSetPageProtect(NULL
, PageAddress
, Protect
);
934 PageAddress
= (PVOID
)((ULONG_PTR
)PageAddress
+ PAGE_SIZE
);
936 if (PageAddress
< (PVOID
)((ULONG_PTR
)BaseAddress
+ Length
) &&
937 PageAddress
< DriverBase
+ DriverSize
)
939 Protect
= LdrLookupPageProtection(PageAddress
, DriverBase
, &PENtHeaders
->FileHeader
, PESectionHeaders
);
940 MmSetPageProtect(NULL
, PageAddress
, Protect
);
945 KeAcquireSpinLock(&ModuleListLock
, &Irql
);
946 InsertTailList(&ModuleListHead
,
947 &CreatedModuleObject
->ListEntry
);
948 KeReleaseSpinLock(&ModuleListLock
, Irql
);
951 ModuleTextSection
= ExAllocatePoolWithTag (
953 sizeof(MODULE_TEXT_SECTION
),
954 TAG_MODULE_TEXT_SECTION
);
955 ASSERT(ModuleTextSection
);
956 RtlZeroMemory(ModuleTextSection
, sizeof(MODULE_TEXT_SECTION
));
957 ModuleTextSection
->Base
= (ULONG
)DriverBase
;
958 ModuleTextSection
->Length
= DriverSize
;
959 ModuleTextSection
->Name
= ExAllocatePoolWithTag (
961 (CreatedModuleObject
->BaseName
.Length
+ 1) * sizeof(WCHAR
),
963 RtlCopyMemory(ModuleTextSection
->Name
,
964 CreatedModuleObject
->BaseName
.Buffer
,
965 CreatedModuleObject
->BaseName
.Length
);
966 ModuleTextSection
->Name
[CreatedModuleObject
->BaseName
.Length
/ sizeof(WCHAR
)] = 0;
967 ModuleTextSection
->OptionalHeader
=
968 CreatedModuleObject
->Image
.PE
.OptionalHeader
;
969 InsertTailList(&ModuleTextListHead
, &ModuleTextSection
->ListEntry
);
971 CreatedModuleObject
->TextSection
= ModuleTextSection
;
973 *ModuleObject
= CreatedModuleObject
;
975 DPRINT("Loading Module %wZ...\n", FileName
);
977 DPRINT("Module %wZ loaded at 0x%.08x.\n",
978 FileName
, CreatedModuleObject
->Base
);
980 return STATUS_SUCCESS
;
985 LdrSafePEProcessModule (
986 PVOID ModuleLoadBase
,
988 PVOID ImportModuleBase
,
993 PIMAGE_DOS_HEADER PEDosHeader
;
994 PIMAGE_NT_HEADERS PENtHeaders
;
995 PIMAGE_SECTION_HEADER PESectionHeaders
;
998 ps("Processing PE Module at module base:%08lx\n", ModuleLoadBase
);
1000 /* Get header pointers */
1001 PEDosHeader
= (PIMAGE_DOS_HEADER
) ModuleLoadBase
;
1002 PENtHeaders
= RtlImageNtHeader(ModuleLoadBase
);
1003 PESectionHeaders
= IMAGE_FIRST_SECTION(PENtHeaders
);
1006 /* Check file magic numbers */
1007 if (PEDosHeader
->e_magic
!= IMAGE_DOS_SIGNATURE
)
1011 if (PEDosHeader
->e_lfanew
== 0)
1015 if (PENtHeaders
->Signature
!= IMAGE_NT_SIGNATURE
)
1019 if (PENtHeaders
->FileHeader
.Machine
!= IMAGE_FILE_MACHINE_I386
)
1024 ps("OptionalHdrMagic:%04x LinkVersion:%d.%d\n",
1025 PENtHeaders
->OptionalHeader
.Magic
,
1026 PENtHeaders
->OptionalHeader
.MajorLinkerVersion
,
1027 PENtHeaders
->OptionalHeader
.MinorLinkerVersion
);
1028 ps("Entry Point:%08lx\n", PENtHeaders
->OptionalHeader
.AddressOfEntryPoint
);
1030 /* Determine the size of the module */
1031 *DriverSize
= PENtHeaders
->OptionalHeader
.SizeOfImage
;
1032 ps("DriverSize %x\n",*DriverSize
);
1034 /* Copy headers over */
1035 if (DriverBase
!= ModuleLoadBase
)
1037 memcpy(DriverBase
, ModuleLoadBase
, PENtHeaders
->OptionalHeader
.SizeOfHeaders
);
1040 ps("Hdr: 0x%X\n", PENtHeaders
);
1041 ps("Hdr->SizeOfHeaders: 0x%X\n", PENtHeaders
->OptionalHeader
.SizeOfHeaders
);
1042 ps("FileHdr->NumberOfSections: 0x%X\n", PENtHeaders
->FileHeader
.NumberOfSections
);
1044 /* Ntoskrnl.exe need no relocation fixups since it is linked to run at the same
1045 address as it is mapped */
1046 if (DriverBase
!= ModuleLoadBase
)
1050 /* Copy image sections into virtual section */
1051 for (Idx
= 0; Idx
< PENtHeaders
->FileHeader
.NumberOfSections
; Idx
++)
1053 PIMAGE_SECTION_HEADER Section
= &PESectionHeaders
[Idx
];
1054 // Copy current section into current offset of virtual section
1055 if (Section
->SizeOfRawData
)
1057 // ps("PESectionHeaders[Idx].VirtualAddress (%X) + DriverBase %x\n",
1058 // PESectionHeaders[Idx].VirtualAddress, PESectionHeaders[Idx].VirtualAddress + DriverBase);
1059 memcpy(Section
->VirtualAddress
+ (char*)DriverBase
,
1060 Section
->PointerToRawData
+ (char*)ModuleLoadBase
,
1061 Section
->Misc
.VirtualSize
> Section
->SizeOfRawData
? Section
->SizeOfRawData
: Section
->Misc
.VirtualSize
);
1063 if (Section
->SizeOfRawData
< Section
->Misc
.VirtualSize
)
1065 memset(Section
->VirtualAddress
+ Section
->SizeOfRawData
+ (char*)DriverBase
,
1067 Section
->Misc
.VirtualSize
- Section
->SizeOfRawData
);
1069 CurrentSize
+= ROUND_UP(Section
->Misc
.VirtualSize
,
1070 PENtHeaders
->OptionalHeader
.SectionAlignment
);
1073 /* Perform relocation fixups */
1074 Status
= LdrPEPerformRelocations(DriverBase
, *DriverSize
);
1075 if (!NT_SUCCESS(Status
))
1081 /* Perform import fixups */
1082 Status
= LdrPEFixupImports(DriverBase
== ModuleLoadBase
? &NtoskrnlModuleObject
: &HalModuleObject
);
1083 if (!NT_SUCCESS(Status
))
1088 /* Set the page protection for the virtual sections */
1089 MmSetPageProtect(NULL
, DriverBase
, PAGE_READONLY
);
1090 for (Idx
= 0; Idx
< PENtHeaders
->FileHeader
.NumberOfSections
; Idx
++)
1092 ULONG Characteristics
= PESectionHeaders
[Idx
].Characteristics
;
1097 Length
= PESectionHeaders
[Idx
].Misc
.VirtualSize
;
1098 BaseAddress
= PESectionHeaders
[Idx
].VirtualAddress
+ (char*)DriverBase
;
1099 PageAddress
= (PVOID
)PAGE_ROUND_DOWN(BaseAddress
);
1101 if (Characteristics
& IMAGE_SCN_MEM_EXECUTE
)
1103 if (Characteristics
& IMAGE_SCN_MEM_WRITE
)
1105 Protect
= PAGE_EXECUTE_READWRITE
;
1109 Protect
= PAGE_EXECUTE_READ
;
1112 else if (Characteristics
& IMAGE_SCN_MEM_WRITE
)
1114 Protect
= PAGE_READWRITE
;
1118 Protect
= PAGE_READONLY
;
1120 while ((ULONG_PTR
)PageAddress
< (ULONG_PTR
)BaseAddress
+ Length
)
1122 MmSetPageProtect(NULL
, PageAddress
, Protect
);
1123 PageAddress
= (PVOID
)((ULONG_PTR
)PageAddress
+ PAGE_SIZE
);
1125 if (DriverBase
== ModuleLoadBase
&&
1126 Characteristics
& IMAGE_SCN_CNT_UNINITIALIZED_DATA
)
1128 /* For ntoskrnl, we must stop after the bss section */
1138 LdrPEFixupForward ( PCHAR ForwardName
)
1140 CHAR NameBuffer
[128];
1141 UNICODE_STRING ModuleName
;
1143 PMODULE_OBJECT ModuleObject
;
1145 DPRINT("LdrPEFixupForward (%s)\n", ForwardName
);
1147 strcpy(NameBuffer
, ForwardName
);
1148 p
= strchr(NameBuffer
, '.');
1156 DPRINT("Driver: %s Function: %s\n", NameBuffer
, p
+1);
1158 RtlCreateUnicodeStringFromAsciiz(&ModuleName
,
1160 ModuleObject
= LdrGetModuleObject(&ModuleName
);
1161 RtlFreeUnicodeString(&ModuleName
);
1163 DPRINT("ModuleObject: %p\n", ModuleObject
);
1165 if (ModuleObject
== NULL
)
1167 CPRINT("LdrPEFixupForward: failed to find module %s\n", NameBuffer
);
1170 return LdrPEGetExportByName(ModuleObject
->Base
, (PUCHAR
)(p
+1), 0xffff);
1174 LdrPEPerformRelocations (
1178 PIMAGE_NT_HEADERS NtHeaders
;
1179 PIMAGE_DATA_DIRECTORY RelocationDDir
;
1180 PIMAGE_BASE_RELOCATION RelocationDir
, RelocationEnd
;
1182 PVOID Address
, MaxAddress
;
1190 NtHeaders
= RtlImageNtHeader(DriverBase
);
1192 if (NtHeaders
->FileHeader
.Characteristics
& IMAGE_FILE_RELOCS_STRIPPED
)
1194 return STATUS_UNSUCCESSFUL
;
1197 RelocationDDir
= &NtHeaders
->OptionalHeader
.DataDirectory
[IMAGE_DIRECTORY_ENTRY_BASERELOC
];
1199 if (RelocationDDir
->VirtualAddress
== 0 || RelocationDDir
->Size
== 0)
1201 return STATUS_SUCCESS
;
1204 Delta
= (ULONG_PTR
)DriverBase
- NtHeaders
->OptionalHeader
.ImageBase
;
1205 RelocationDir
= (PIMAGE_BASE_RELOCATION
)((ULONG_PTR
)DriverBase
+ RelocationDDir
->VirtualAddress
);
1206 RelocationEnd
= (PIMAGE_BASE_RELOCATION
)((ULONG_PTR
)RelocationDir
+ RelocationDDir
->Size
);
1207 MaxAddress
= DriverBase
+ DriverSize
;
1209 while (RelocationDir
< RelocationEnd
&&
1210 RelocationDir
->SizeOfBlock
> 0)
1212 Count
= (RelocationDir
->SizeOfBlock
- sizeof(IMAGE_BASE_RELOCATION
)) / sizeof(USHORT
);
1213 Address
= DriverBase
+ RelocationDir
->VirtualAddress
;
1214 TypeOffset
= (PUSHORT
)(RelocationDir
+ 1);
1216 for (i
= 0; i
< Count
; i
++)
1218 Offset
= *TypeOffset
& 0xFFF;
1219 Type
= *TypeOffset
>> 12;
1220 ShortPtr
= (PUSHORT
)(Address
+ Offset
);
1222 /* Don't relocate after the end of the loaded driver */
1223 if ((PVOID
)ShortPtr
>= MaxAddress
)
1229 * Don't relocate within the relocation section itself.
1230 * GCC/LD generates sometimes relocation records for the relecotion section.
1231 * This is a bug in GCC/LD.
1233 if ((ULONG_PTR
)ShortPtr
< (ULONG_PTR
)RelocationDir
||
1234 (ULONG_PTR
)ShortPtr
>= (ULONG_PTR
)RelocationEnd
)
1238 case IMAGE_REL_BASED_ABSOLUTE
:
1241 case IMAGE_REL_BASED_HIGH
:
1242 *ShortPtr
+= HIWORD(Delta
);
1245 case IMAGE_REL_BASED_LOW
:
1246 *ShortPtr
+= LOWORD(Delta
);
1249 case IMAGE_REL_BASED_HIGHLOW
:
1250 LongPtr
= (PULONG
)ShortPtr
;
1254 case IMAGE_REL_BASED_HIGHADJ
:
1255 case IMAGE_REL_BASED_MIPS_JMPADDR
:
1257 DPRINT1("Unknown/unsupported fixup type %hu.\n", Type
);
1258 DPRINT1("Address %x, Current %d, Count %d, *TypeOffset %x\n", Address
, i
, Count
, *TypeOffset
);
1259 return STATUS_UNSUCCESSFUL
;
1264 RelocationDir
= (PIMAGE_BASE_RELOCATION
)((ULONG_PTR
)RelocationDir
+ RelocationDir
->SizeOfBlock
);
1267 return STATUS_SUCCESS
;
1271 LdrPEGetOrLoadModule (
1272 PMODULE_OBJECT Module
,
1274 PMODULE_OBJECT
* ImportedModule
)
1276 UNICODE_STRING DriverName
;
1277 UNICODE_STRING NameString
;
1278 WCHAR NameBuffer
[PATH_MAX
];
1279 NTSTATUS Status
= STATUS_SUCCESS
;
1281 if (0 == _stricmp(ImportedName
, "ntoskrnl") ||
1282 0 == _stricmp(ImportedName
, "ntoskrnl.exe"))
1284 *ImportedModule
= &NtoskrnlModuleObject
;
1285 return STATUS_SUCCESS
;
1288 if (0 == _stricmp(ImportedName
, "hal") ||
1289 0 == _stricmp(ImportedName
, "hal.dll"))
1291 *ImportedModule
= &HalModuleObject
;
1292 return STATUS_SUCCESS
;
1295 RtlCreateUnicodeStringFromAsciiz (&DriverName
, ImportedName
);
1296 DPRINT("Import module: %wZ\n", &DriverName
);
1298 *ImportedModule
= LdrGetModuleObject(&DriverName
);
1299 if (*ImportedModule
== NULL
)
1304 PathEnd
= wcsrchr(Module
->FullName
.Buffer
, L
'\\');
1305 if (NULL
!= PathEnd
)
1307 PathLength
= (PathEnd
- Module
->FullName
.Buffer
+ 1) * sizeof(WCHAR
);
1308 RtlCopyMemory(NameBuffer
, Module
->FullName
.Buffer
, PathLength
);
1309 RtlCopyMemory(NameBuffer
+ (PathLength
/ sizeof(WCHAR
)), DriverName
.Buffer
, DriverName
.Length
);
1310 NameString
.Buffer
= NameBuffer
;
1311 NameString
.MaximumLength
= NameString
.Length
= PathLength
+ DriverName
.Length
;
1313 /* NULL-terminate */
1314 NameString
.MaximumLength
++;
1315 NameBuffer
[NameString
.Length
/ sizeof(WCHAR
)] = 0;
1317 Status
= LdrLoadModule(&NameString
, ImportedModule
);
1321 DPRINT("Module '%wZ' not loaded yet\n", &DriverName
);
1322 wcscpy(NameBuffer
, L
"\\SystemRoot\\system32\\drivers\\");
1323 wcsncat(NameBuffer
, DriverName
.Buffer
, DriverName
.Length
/ sizeof(WCHAR
));
1324 RtlInitUnicodeString(&NameString
, NameBuffer
);
1325 Status
= LdrLoadModule(&NameString
, ImportedModule
);
1327 if (!NT_SUCCESS(Status
))
1329 wcscpy(NameBuffer
, L
"\\SystemRoot\\system32\\");
1330 wcsncat(NameBuffer
, DriverName
.Buffer
, DriverName
.Length
/ sizeof(WCHAR
));
1331 RtlInitUnicodeString(&NameString
, NameBuffer
);
1332 Status
= LdrLoadModule(&NameString
, ImportedModule
);
1333 if (!NT_SUCCESS(Status
))
1335 DPRINT1("Unknown import module: %wZ (Status %lx)\n", &DriverName
, Status
);
1339 RtlFreeUnicodeString(&DriverName
);
1344 LdrPEGetExportByName (
1349 PIMAGE_EXPORT_DIRECTORY ExportDir
;
1350 PDWORD
* ExFunctions
;
1352 USHORT
* ExOrdinals
;
1358 ULONG ExportDirSize
;
1360 DPRINT("LdrPEGetExportByName %x %s %hu\n", BaseAddress
, SymbolName
, Hint
);
1362 ExportDir
= (PIMAGE_EXPORT_DIRECTORY
)RtlImageDirectoryEntryToData(BaseAddress
,
1364 IMAGE_DIRECTORY_ENTRY_EXPORT
,
1366 if (ExportDir
== NULL
)
1368 DPRINT1("LdrPEGetExportByName(): no export directory!\n");
1373 /* The symbol names may be missing entirely */
1374 if (ExportDir
->AddressOfNames
== 0)
1376 DPRINT("LdrPEGetExportByName(): symbol names missing entirely\n");
1381 * Get header pointers
1383 ExNames
= (PDWORD
*)RVA(BaseAddress
, ExportDir
->AddressOfNames
);
1384 ExOrdinals
= (USHORT
*)RVA(BaseAddress
, ExportDir
->AddressOfNameOrdinals
);
1385 ExFunctions
= (PDWORD
*)RVA(BaseAddress
, ExportDir
->AddressOfFunctions
);
1388 * Check the hint first
1390 if (Hint
< ExportDir
->NumberOfNames
)
1392 ExName
= RVA(BaseAddress
, ExNames
[Hint
]);
1393 if (strcmp(ExName
, (PCHAR
)SymbolName
) == 0)
1395 Ordinal
= ExOrdinals
[Hint
];
1396 Function
= RVA(BaseAddress
, ExFunctions
[Ordinal
]);
1397 if ((ULONG_PTR
)Function
>= (ULONG_PTR
)ExportDir
&&
1398 (ULONG_PTR
)Function
< (ULONG_PTR
)ExportDir
+ ExportDirSize
)
1400 DPRINT("Forward: %s\n", (PCHAR
)Function
);
1401 Function
= LdrPEFixupForward((PCHAR
)Function
);
1402 if (Function
== NULL
)
1404 DPRINT1("LdrPEGetExportByName(): failed to find %s\n",SymbolName
);
1408 if (Function
!= NULL
)
1416 * Try a binary search first
1419 maxn
= ExportDir
->NumberOfNames
- 1;
1420 while (minn
<= maxn
)
1425 mid
= (minn
+ maxn
) / 2;
1427 ExName
= RVA(BaseAddress
, ExNames
[mid
]);
1428 res
= strcmp(ExName
, (PCHAR
)SymbolName
);
1431 Ordinal
= ExOrdinals
[mid
];
1432 Function
= RVA(BaseAddress
, ExFunctions
[Ordinal
]);
1433 if ((ULONG_PTR
)Function
>= (ULONG_PTR
)ExportDir
&&
1434 (ULONG_PTR
)Function
< (ULONG_PTR
)ExportDir
+ ExportDirSize
)
1436 DPRINT("Forward: %s\n", (PCHAR
)Function
);
1437 Function
= LdrPEFixupForward((PCHAR
)Function
);
1438 if (Function
== NULL
)
1440 DPRINT1("LdrPEGetExportByName(): failed to find %s\n",SymbolName
);
1444 if (Function
!= NULL
)
1449 else if (minn
== maxn
)
1451 DPRINT("LdrPEGetExportByName(): binary search failed\n");
1465 * Fall back on a linear search
1467 DPRINT("LdrPEGetExportByName(): Falling back on a linear search of export table\n");
1468 for (i
= 0; i
< ExportDir
->NumberOfNames
; i
++)
1470 ExName
= RVA(BaseAddress
, ExNames
[i
]);
1471 if (strcmp(ExName
, (PCHAR
)SymbolName
) == 0)
1473 Ordinal
= ExOrdinals
[i
];
1474 Function
= RVA(BaseAddress
, ExFunctions
[Ordinal
]);
1475 DPRINT("%x %x %x\n", Function
, ExportDir
, ExportDir
+ ExportDirSize
);
1476 if ((ULONG_PTR
)Function
>= (ULONG_PTR
)ExportDir
&&
1477 (ULONG_PTR
)Function
< (ULONG_PTR
)ExportDir
+ ExportDirSize
)
1479 DPRINT("Forward: %s\n", (PCHAR
)Function
);
1480 Function
= LdrPEFixupForward((PCHAR
)Function
);
1482 if (Function
== NULL
)
1489 DPRINT1("LdrPEGetExportByName(): failed to find %s\n",SymbolName
);
1494 LdrPEGetExportByOrdinal (
1498 PIMAGE_EXPORT_DIRECTORY ExportDir
;
1499 ULONG ExportDirSize
;
1500 PDWORD
* ExFunctions
;
1503 ExportDir
= (PIMAGE_EXPORT_DIRECTORY
)RtlImageDirectoryEntryToData (
1506 IMAGE_DIRECTORY_ENTRY_EXPORT
,
1509 ExFunctions
= (PDWORD
*)RVA(BaseAddress
,
1510 ExportDir
->AddressOfFunctions
);
1511 DPRINT("LdrPEGetExportByOrdinal(Ordinal %d) = %x\n",
1513 RVA(BaseAddress
, ExFunctions
[Ordinal
- ExportDir
->Base
]));
1515 Function
= 0 != ExFunctions
[Ordinal
- ExportDir
->Base
]
1516 ? RVA(BaseAddress
, ExFunctions
[Ordinal
- ExportDir
->Base
] )
1519 if (((ULONG
)Function
>= (ULONG
)ExportDir
) &&
1520 ((ULONG
)Function
< (ULONG
)ExportDir
+ (ULONG
)ExportDirSize
))
1522 DPRINT("Forward: %s\n", (PCHAR
)Function
);
1523 Function
= LdrPEFixupForward((PCHAR
)Function
);
1530 LdrPEProcessImportDirectoryEntry(
1532 PMODULE_OBJECT ImportedModule
,
1533 PIMAGE_IMPORT_DESCRIPTOR ImportModuleDirectory
)
1535 PVOID
* ImportAddressList
;
1536 PULONG FunctionNameList
;
1539 if (ImportModuleDirectory
== NULL
|| ImportModuleDirectory
->Name
== 0)
1541 return STATUS_UNSUCCESSFUL
;
1544 /* Get the import address list. */
1545 ImportAddressList
= (PVOID
*)(DriverBase
+ (ULONG_PTR
)ImportModuleDirectory
->FirstThunk
);
1547 /* Get the list of functions to import. */
1548 if (ImportModuleDirectory
->OriginalFirstThunk
!= 0)
1550 FunctionNameList
= (PULONG
) (DriverBase
+ (ULONG_PTR
)ImportModuleDirectory
->OriginalFirstThunk
);
1554 FunctionNameList
= (PULONG
)(DriverBase
+ (ULONG_PTR
)ImportModuleDirectory
->FirstThunk
);
1557 /* Walk through function list and fixup addresses. */
1558 while (*FunctionNameList
!= 0L)
1560 if ((*FunctionNameList
) & 0x80000000)
1562 Ordinal
= (*FunctionNameList
) & 0x7fffffff;
1563 *ImportAddressList
= LdrPEGetExportByOrdinal(ImportedModule
->Base
, Ordinal
);
1564 if ((*ImportAddressList
) == NULL
)
1566 DPRINT1("Failed to import #%ld from %wZ\n", Ordinal
, &ImportedModule
->FullName
);
1567 return STATUS_UNSUCCESSFUL
;
1572 IMAGE_IMPORT_BY_NAME
*pe_name
;
1573 pe_name
= RVA(DriverBase
, *FunctionNameList
);
1574 *ImportAddressList
= LdrPEGetExportByName(ImportedModule
->Base
, pe_name
->Name
, pe_name
->Hint
);
1575 if ((*ImportAddressList
) == NULL
)
1577 DPRINT1("Failed to import %s from %wZ\n", pe_name
->Name
, &ImportedModule
->FullName
);
1578 return STATUS_UNSUCCESSFUL
;
1581 ImportAddressList
++;
1584 return STATUS_SUCCESS
;
1588 LdrPEFixupImports ( PMODULE_OBJECT Module
)
1590 PIMAGE_IMPORT_DESCRIPTOR ImportModuleDirectory
;
1592 PMODULE_OBJECT ImportedModule
;
1595 /* Process each import module */
1596 ImportModuleDirectory
= (PIMAGE_IMPORT_DESCRIPTOR
)
1597 RtlImageDirectoryEntryToData(Module
->Base
,
1599 IMAGE_DIRECTORY_ENTRY_IMPORT
,
1601 DPRINT("Processeing import directory at %p\n", ImportModuleDirectory
);
1602 while (ImportModuleDirectory
->Name
)
1604 if (Module
->Length
<= ImportModuleDirectory
->Name
)
1606 DPRINT1("Invalid import directory in %wZ\n", &Module
->FullName
);
1607 return STATUS_SECTION_NOT_IMAGE
;
1610 /* Check to make sure that import lib is kernel */
1611 ImportedName
= (PCHAR
) Module
->Base
+ ImportModuleDirectory
->Name
;
1613 Status
= LdrPEGetOrLoadModule(Module
, ImportedName
, &ImportedModule
);
1614 if (!NT_SUCCESS(Status
))
1619 Status
= LdrPEProcessImportDirectoryEntry(Module
->Base
, ImportedModule
, ImportModuleDirectory
);
1620 if (!NT_SUCCESS(Status
))
1625 ImportModuleDirectory
++;
1627 return STATUS_SUCCESS
;