3 * LICENSE: GPL - See COPYING in the top level directory
4 * FILE: freeldr/winldr/peloader.c
5 * PURPOSE: Provides routines for loading PE files. To be merged with
6 * arch/i386/loader.c in future
7 * This article was very handy during development:
8 * http://msdn.microsoft.com/msdnmag/issues/02/03/PE2/
9 * PROGRAMMERS: Aleksey Bragin (aleksey@reactos.org)
10 * The source code in this file is based on the work of respective
11 * authors of PE loading code in ReactOS and Brian Palmer and
12 * Alex Ionescu's arch/i386/loader.c, and my research project
13 * (creating a native EFI loader for Windows)
16 /* INCLUDES ***************************************************************/
22 WinLdrpCompareDllName(IN PCH DllName
,
23 IN PUNICODE_STRING UnicodeName
);
26 WinLdrpBindImportName(IN OUT PLOADER_PARAMETER_BLOCK WinLdrBlock
,
29 IN PIMAGE_THUNK_DATA ThunkData
,
30 IN PIMAGE_EXPORT_DIRECTORY ExportDirectory
,
32 IN BOOLEAN ProcessForwards
);
35 WinLdrpLoadAndScanReferencedDll(PLOADER_PARAMETER_BLOCK WinLdrBlock
,
38 PLDR_DATA_TABLE_ENTRY
*DataTableEntry
);
41 WinLdrpScanImportAddressTable(IN OUT PLOADER_PARAMETER_BLOCK WinLdrBlock
,
44 IN PIMAGE_THUNK_DATA ThunkData
);
48 /* FUNCTIONS **************************************************************/
50 /* Returns TRUE if DLL has already been loaded - looks in LoadOrderList in LPB */
52 WinLdrCheckForLoadedDll(IN OUT PLOADER_PARAMETER_BLOCK WinLdrBlock
,
54 OUT PLDR_DATA_TABLE_ENTRY
*LoadedEntry
)
56 PLDR_DATA_TABLE_ENTRY DataTableEntry
;
57 LIST_ENTRY
*ModuleEntry
;
59 DPRINTM(DPRINT_WINDOWS
, "WinLdrCheckForLoadedDll: DllName %X, LoadedEntry: %X\n",
60 DllName
, LoadedEntry
);
62 /* Just go through each entry in the LoadOrderList and compare loaded module's
63 name with a given name */
64 ModuleEntry
= WinLdrBlock
->LoadOrderListHead
.Flink
;
65 while (ModuleEntry
!= &WinLdrBlock
->LoadOrderListHead
)
67 /* Get pointer to the current DTE */
68 DataTableEntry
= CONTAINING_RECORD(ModuleEntry
,
72 DPRINTM(DPRINT_WINDOWS
, "WinLdrCheckForLoadedDll: DTE %p, EP %p\n",
73 DataTableEntry
, DataTableEntry
->EntryPoint
);
76 if (WinLdrpCompareDllName(DllName
, &DataTableEntry
->BaseDllName
))
78 /* Yes, found it, report pointer to the loaded module's DTE
79 to the caller and increase load count for it */
80 *LoadedEntry
= DataTableEntry
;
81 DataTableEntry
->LoadCount
++;
82 DPRINTM(DPRINT_WINDOWS
, "WinLdrCheckForLoadedDll: LoadedEntry %X\n", DataTableEntry
);
86 /* Go to the next entry */
87 ModuleEntry
= ModuleEntry
->Flink
;
95 WinLdrScanImportDescriptorTable(IN OUT PLOADER_PARAMETER_BLOCK WinLdrBlock
,
96 IN PCCH DirectoryPath
,
97 IN PLDR_DATA_TABLE_ENTRY ScanDTE
)
99 PLDR_DATA_TABLE_ENTRY DataTableEntry
;
100 PIMAGE_IMPORT_DESCRIPTOR ImportTable
;
101 ULONG ImportTableSize
;
105 /* Get a pointer to the import table of this image */
106 ImportTable
= (PIMAGE_IMPORT_DESCRIPTOR
)RtlImageDirectoryEntryToData(VaToPa(ScanDTE
->DllBase
),
107 TRUE
, IMAGE_DIRECTORY_ENTRY_IMPORT
, &ImportTableSize
);
110 UNICODE_STRING BaseName
;
111 BaseName
.Buffer
= VaToPa(ScanDTE
->BaseDllName
.Buffer
);
112 BaseName
.MaximumLength
= ScanDTE
->BaseDllName
.MaximumLength
;
113 BaseName
.Length
= ScanDTE
->BaseDllName
.Length
;
114 DPRINTM(DPRINT_WINDOWS
, "WinLdrScanImportDescriptorTable(): %wZ ImportTable = 0x%X\n",
115 &BaseName
, ImportTable
);
118 /* If image doesn't have any import directory - just return success */
119 if (ImportTable
== NULL
)
122 /* Loop through all entries */
123 for (;(ImportTable
->Name
!= 0) && (ImportTable
->FirstThunk
!= 0);ImportTable
++)
125 /* Get pointer to the name */
126 ImportName
= (PCH
)VaToPa(RVA(ScanDTE
->DllBase
, ImportTable
->Name
));
127 DPRINTM(DPRINT_WINDOWS
, "WinLdrScanImportDescriptorTable(): Looking at %s\n", ImportName
);
129 /* In case we get a reference to ourselves - just skip it */
130 if (WinLdrpCompareDllName(ImportName
, &ScanDTE
->BaseDllName
))
133 /* Load the DLL if it is not already loaded */
134 if (!WinLdrCheckForLoadedDll(WinLdrBlock
, ImportName
, &DataTableEntry
))
136 Status
= WinLdrpLoadAndScanReferencedDll(WinLdrBlock
,
143 DPRINTM(DPRINT_WINDOWS
, "WinLdrpLoadAndScanReferencedDll() failed\n");
148 /* Scan its import address table */
149 Status
= WinLdrpScanImportAddressTable(
151 DataTableEntry
->DllBase
,
153 (PIMAGE_THUNK_DATA
)RVA(ScanDTE
->DllBase
, ImportTable
->FirstThunk
));
157 DPRINTM(DPRINT_WINDOWS
, "WinLdrpScanImportAddressTable() failed\n");
166 WinLdrAllocateDataTableEntry(IN OUT PLOADER_PARAMETER_BLOCK WinLdrBlock
,
170 OUT PLDR_DATA_TABLE_ENTRY
*NewEntry
)
172 PVOID BaseVA
= PaToVa(BasePA
);
174 PLDR_DATA_TABLE_ENTRY DataTableEntry
;
175 PIMAGE_NT_HEADERS NtHeaders
;
178 /* Allocate memory for a data table entry, zero-initialize it */
179 DataTableEntry
= (PLDR_DATA_TABLE_ENTRY
)MmHeapAlloc(sizeof(LDR_DATA_TABLE_ENTRY
));
180 if (DataTableEntry
== NULL
)
182 RtlZeroMemory(DataTableEntry
, sizeof(LDR_DATA_TABLE_ENTRY
));
184 /* Get NT headers from the image */
185 NtHeaders
= RtlImageNtHeader(BasePA
);
187 /* Initialize corresponding fields of DTE based on NT headers value */
188 DataTableEntry
->DllBase
= BaseVA
;
189 DataTableEntry
->SizeOfImage
= NtHeaders
->OptionalHeader
.SizeOfImage
;
190 DataTableEntry
->EntryPoint
= RVA(BaseVA
, NtHeaders
->OptionalHeader
.AddressOfEntryPoint
);
191 DataTableEntry
->SectionPointer
= 0;
192 DataTableEntry
->CheckSum
= NtHeaders
->OptionalHeader
.CheckSum
;
194 /* Initialize BaseDllName field (UNICODE_STRING) from the Ansi BaseDllName
195 by simple conversion - copying each character */
196 Length
= (USHORT
)(strlen(BaseDllName
) * sizeof(WCHAR
));
197 Buffer
= (PWSTR
)MmHeapAlloc(Length
);
200 MmHeapFree(DataTableEntry
);
203 RtlZeroMemory(Buffer
, Length
);
205 DataTableEntry
->BaseDllName
.Length
= Length
;
206 DataTableEntry
->BaseDllName
.MaximumLength
= Length
;
207 DataTableEntry
->BaseDllName
.Buffer
= PaToVa(Buffer
);
208 while (*BaseDllName
!= 0)
210 *Buffer
++ = *BaseDllName
++;
213 /* Initialize FullDllName field (UNICODE_STRING) from the Ansi FullDllName
214 using the same method */
215 Length
= (USHORT
)(strlen(FullDllName
) * sizeof(WCHAR
));
216 Buffer
= (PWSTR
)MmHeapAlloc(Length
);
219 MmHeapFree(DataTableEntry
);
222 RtlZeroMemory(Buffer
, Length
);
224 DataTableEntry
->FullDllName
.Length
= Length
;
225 DataTableEntry
->FullDllName
.MaximumLength
= Length
;
226 DataTableEntry
->FullDllName
.Buffer
= PaToVa(Buffer
);
227 while (*FullDllName
!= 0)
229 *Buffer
++ = *FullDllName
++;
232 /* Initialize what's left - LoadCount which is 1, and set Flags so that
233 we know this entry is processed */
234 DataTableEntry
->Flags
= LDRP_ENTRY_PROCESSED
;
235 DataTableEntry
->LoadCount
= 1;
237 /* Insert this DTE to a list in the LPB */
238 InsertTailList(&WinLdrBlock
->LoadOrderListHead
, &DataTableEntry
->InLoadOrderLinks
);
240 /* Save pointer to a newly allocated and initialized entry */
241 *NewEntry
= DataTableEntry
;
247 /* WinLdrLoadImage loads the specified image from the file (it doesn't
248 perform any additional operations on the filename, just directly
249 calls the file I/O routines), and relocates it so that it's ready
250 to be used when paging is enabled.
251 Addressing mode: physical
254 WinLdrLoadImage(IN PCHAR FileName
,
255 TYPE_OF_MEMORY MemoryType
,
256 OUT PVOID
*ImageBasePA
)
260 PVOID VirtualBase
= NULL
;
261 UCHAR HeadersBuffer
[SECTOR_SIZE
* 2];
262 PIMAGE_NT_HEADERS NtHeaders
;
263 PIMAGE_SECTION_HEADER SectionHeader
;
264 ULONG VirtualSize
, SizeOfRawData
, NumberOfSections
;
268 CHAR ProgressString
[256];
270 /* Inform user we are loading files */
271 sprintf(ProgressString
, "Loading %s...", FileName
);
272 UiDrawProgressBarCenter(1, 100, ProgressString
);
274 /* Open the image file */
275 FileHandle
= FsOpenFile(FileName
);
277 if (FileHandle
== NULL
)
279 //Print(L"Can not open the file %s\n",FileName);
280 UiMessageBox("Can not open the file");
284 /* Load the first 2 sectors of the image so we can read the PE header */
285 Status
= FsReadFile(FileHandle
, SECTOR_SIZE
* 2, NULL
, HeadersBuffer
);
288 //Print(L"Error reading from file %s\n", FileName);
289 UiMessageBox("Error reading from file");
290 FsCloseFile(FileHandle
);
294 /* Now read the MZ header to get the offset to the PE Header */
295 NtHeaders
= RtlImageNtHeader(HeadersBuffer
);
299 //Print(L"Error - no NT header found in %s\n", FileName);
300 UiMessageBox("Error - no NT header found");
301 FsCloseFile(FileHandle
);
305 /* Ensure this is executable image */
306 if (((NtHeaders
->FileHeader
.Characteristics
& IMAGE_FILE_EXECUTABLE_IMAGE
) == 0))
308 //Print(L"Not an executable image %s\n", FileName);
309 UiMessageBox("Not an executable image");
310 FsCloseFile(FileHandle
);
314 /* Store number of sections to read and a pointer to the first section */
315 NumberOfSections
= NtHeaders
->FileHeader
.NumberOfSections
;
316 SectionHeader
= IMAGE_FIRST_SECTION(NtHeaders
);
318 /* Try to allocate this memory, if fails - allocate somewhere else */
319 PhysicalBase
= MmAllocateMemoryAtAddress(NtHeaders
->OptionalHeader
.SizeOfImage
,
320 (PVOID
)((ULONG
)NtHeaders
->OptionalHeader
.ImageBase
& (KSEG0_BASE
- 1)),
323 if (PhysicalBase
== NULL
)
325 /* It's ok, we don't panic - let's allocate again at any other "low" place */
326 PhysicalBase
= MmAllocateMemoryWithType(NtHeaders
->OptionalHeader
.SizeOfImage
, MemoryType
);
328 if (PhysicalBase
== NULL
)
330 //Print(L"Failed to alloc pages for image %s\n", FileName);
331 UiMessageBox("Failed to alloc pages for image");
332 FsCloseFile(FileHandle
);
337 /* This is the real image base - in form of a virtual address */
338 VirtualBase
= PaToVa(PhysicalBase
);
340 DPRINTM(DPRINT_WINDOWS
, "Base PA: 0x%X, VA: 0x%X\n", PhysicalBase
, VirtualBase
);
342 /* Set to 0 position and fully load the file image */
343 FsSetFilePointer(FileHandle
, 0);
345 Status
= FsReadFile(FileHandle
, NtHeaders
->OptionalHeader
.SizeOfHeaders
, NULL
, PhysicalBase
);
349 //Print(L"Error reading headers %s\n", FileName);
350 UiMessageBox("Error reading headers");
351 FsCloseFile(FileHandle
);
355 /* Reload the NT Header */
356 NtHeaders
= RtlImageNtHeader(PhysicalBase
);
358 /* Load the first section */
359 SectionHeader
= IMAGE_FIRST_SECTION(NtHeaders
);
361 /* Fill output parameters */
362 *ImageBasePA
= PhysicalBase
;
364 /* Walk through each section and read it (check/fix any possible
365 bad situations, if they arise) */
366 for (i
= 0; i
< NumberOfSections
; i
++)
368 VirtualSize
= SectionHeader
->Misc
.VirtualSize
;
369 SizeOfRawData
= SectionHeader
->SizeOfRawData
;
371 /* Handle a case when VirtualSize equals 0 */
372 if (VirtualSize
== 0)
373 VirtualSize
= SizeOfRawData
;
375 /* If PointerToRawData is 0, then force its size to be also 0 */
376 if (SectionHeader
->PointerToRawData
== 0)
382 /* Cut the loaded size to the VirtualSize extents */
383 if (SizeOfRawData
> VirtualSize
)
384 SizeOfRawData
= VirtualSize
;
387 /* Actually read the section (if its size is not 0) */
388 if (SizeOfRawData
!= 0)
390 /* Seek to the correct position */
391 FsSetFilePointer(FileHandle
, SectionHeader
->PointerToRawData
);
393 DPRINTM(DPRINT_WINDOWS
, "SH->VA: 0x%X\n", SectionHeader
->VirtualAddress
);
395 /* Read this section from the file, size = SizeOfRawData */
396 Status
= FsReadFile(FileHandle
, SizeOfRawData
, &BytesRead
, (PUCHAR
)PhysicalBase
+ SectionHeader
->VirtualAddress
);
398 if (!Status
&& (BytesRead
== 0))
400 DPRINTM(DPRINT_WINDOWS
, "WinLdrLoadImage(): Error reading section from file!\n");
405 /* Size of data is less than the virtual size - fill up the remainder with zeroes */
406 if (SizeOfRawData
< VirtualSize
)
408 DPRINTM(DPRINT_WINDOWS
, "WinLdrLoadImage(): SORD %d < VS %d\n", SizeOfRawData
, VirtualSize
);
409 RtlZeroMemory((PVOID
)(SectionHeader
->VirtualAddress
+ (ULONG
)PhysicalBase
+ SizeOfRawData
), VirtualSize
- SizeOfRawData
);
415 /* We are done with the file - close it */
416 FsCloseFile(FileHandle
);
418 /* If loading failed - return right now */
423 /* Relocate the image, if it needs it */
424 if (NtHeaders
->OptionalHeader
.ImageBase
!= (ULONG
)VirtualBase
)
426 DPRINTM(DPRINT_WINDOWS
, "Relocating %p -> %p\n",
427 NtHeaders
->OptionalHeader
.ImageBase
, VirtualBase
);
428 Status
= (BOOLEAN
)LdrRelocateImageWithBias(PhysicalBase
,
429 (ULONG_PTR
)VirtualBase
- (ULONG_PTR
)PhysicalBase
,
432 TRUE
, /* in case of conflict still return success */
439 /* PRIVATE FUNCTIONS *******************************************************/
441 /* DllName - physical, UnicodeString->Buffer - virtual */
443 WinLdrpCompareDllName(IN PCH DllName
,
444 IN PUNICODE_STRING UnicodeName
)
447 UNICODE_STRING UnicodeNamePA
;
450 /* First obvious check: for length of two names */
451 Length
= strlen(DllName
);
453 UnicodeNamePA
.Length
= UnicodeName
->Length
;
454 UnicodeNamePA
.MaximumLength
= UnicodeName
->MaximumLength
;
455 UnicodeNamePA
.Buffer
= VaToPa(UnicodeName
->Buffer
);
456 DPRINTM(DPRINT_WINDOWS
, "WinLdrpCompareDllName: %s and %wZ, Length = %d "
457 "UN->Length %d\n", DllName
, &UnicodeNamePA
, Length
, UnicodeName
->Length
);
459 if ((Length
* sizeof(WCHAR
)) > UnicodeName
->Length
)
462 /* Store pointer to unicode string's buffer */
463 Buffer
= VaToPa(UnicodeName
->Buffer
);
465 /* Loop character by character */
466 for (i
= 0; i
< Length
; i
++)
468 /* Compare two characters, uppercasing them */
469 if (toupper(*DllName
) != toupper((CHAR
)*Buffer
))
472 /* Move to the next character */
477 /* Check, if strings either fully match, or match till the "." (w/o extension) */
478 if ((UnicodeName
->Length
== Length
* sizeof(WCHAR
)) || (*Buffer
== L
'.'))
484 /* Strings don't match, return FALSE */
489 WinLdrpBindImportName(IN OUT PLOADER_PARAMETER_BLOCK WinLdrBlock
,
492 IN PIMAGE_THUNK_DATA ThunkData
,
493 IN PIMAGE_EXPORT_DIRECTORY ExportDirectory
,
495 IN BOOLEAN ProcessForwards
)
498 PULONG NameTable
, FunctionTable
;
499 PUSHORT OrdinalTable
;
500 LONG High
, Low
, Middle
, Result
;
503 //DPRINTM(DPRINT_WINDOWS, "WinLdrpBindImportName(): DllBase 0x%X, ImageBase 0x%X, ThunkData 0x%X, ExportDirectory 0x%X, ExportSize %d, ProcessForwards 0x%X\n",
504 // DllBase, ImageBase, ThunkData, ExportDirectory, ExportSize, ProcessForwards);
506 /* Check passed DllBase param */
509 DPRINTM(DPRINT_WINDOWS
, "WARNING: DllBase == NULL!\n");
513 /* Convert all non-critical pointers to PA from VA */
514 ThunkData
= VaToPa(ThunkData
);
516 /* Is the reference by ordinal? */
517 if (IMAGE_SNAP_BY_ORDINAL(ThunkData
->u1
.Ordinal
) && !ProcessForwards
)
519 /* Yes, calculate the ordinal */
520 Ordinal
= (ULONG
)(IMAGE_ORDINAL(ThunkData
->u1
.Ordinal
) - (UINT32
)ExportDirectory
->Base
);
521 //DPRINTM(DPRINT_WINDOWS, "WinLdrpBindImportName(): Ordinal %d\n", Ordinal);
525 /* It's reference by name, we have to look it up in the export directory */
526 if (!ProcessForwards
)
528 /* AddressOfData in thunk entry will become a virtual address (from relative) */
529 //DPRINTM(DPRINT_WINDOWS, "WinLdrpBindImportName(): ThunkData->u1.AOD was %p\n", ThunkData->u1.AddressOfData);
530 ThunkData
->u1
.AddressOfData
=
531 (ULONG
)RVA(ImageBase
, ThunkData
->u1
.AddressOfData
);
532 //DPRINTM(DPRINT_WINDOWS, "WinLdrpBindImportName(): ThunkData->u1.AOD became %p\n", ThunkData->u1.AddressOfData);
535 /* Get pointers to Name and Ordinal tables (RVA -> VA) */
536 NameTable
= (PULONG
)VaToPa(RVA(DllBase
, ExportDirectory
->AddressOfNames
));
537 OrdinalTable
= (PUSHORT
)VaToPa(RVA(DllBase
, ExportDirectory
->AddressOfNameOrdinals
));
539 //DPRINTM(DPRINT_WINDOWS, "NameTable 0x%X, OrdinalTable 0x%X, ED->AddressOfNames 0x%X, ED->AOFO 0x%X\n",
540 // NameTable, OrdinalTable, ExportDirectory->AddressOfNames, ExportDirectory->AddressOfNameOrdinals);
542 /* Get the hint, convert it to a physical pointer */
543 Hint
= ((PIMAGE_IMPORT_BY_NAME
)VaToPa((PVOID
)ThunkData
->u1
.AddressOfData
))->Hint
;
544 //DPRINTM(DPRINT_WINDOWS, "HintIndex %d\n", Hint);
546 /* If Hint is less than total number of entries in the export directory,
547 and import name == export name, then we can just get it from the OrdinalTable */
549 (Hint
< ExportDirectory
->NumberOfNames
) &&
551 strcmp(VaToPa(&((PIMAGE_IMPORT_BY_NAME
)VaToPa((PVOID
)ThunkData
->u1
.AddressOfData
))->Name
[0]),
552 (PCHAR
)VaToPa( RVA(DllBase
, NameTable
[Hint
])) ) == 0
556 Ordinal
= OrdinalTable
[Hint
];
557 //DPRINTM(DPRINT_WINDOWS, "WinLdrpBindImportName(): Ordinal %d\n", Ordinal);
561 /* It's not the easy way, we have to lookup import name in the name table.
562 Let's use a binary search for this task. */
564 //DPRINTM(DPRINT_WINDOWS, "WinLdrpBindImportName() looking up the import name using binary search...\n");
566 /* Low boundary is set to 0, and high boundary to the maximum index */
568 High
= ExportDirectory
->NumberOfNames
- 1;
570 /* Perform a binary-search loop */
573 /* Divide by 2 by shifting to the right once */
574 Middle
= (Low
+ High
) >> 1;
576 /* Compare the names */
577 Result
= strcmp(VaToPa(&((PIMAGE_IMPORT_BY_NAME
)VaToPa((PVOID
)ThunkData
->u1
.AddressOfData
))->Name
[0]),
578 (PCHAR
)VaToPa(RVA(DllBase
, NameTable
[Middle
])));
580 /*DPRINTM(DPRINT_WINDOWS, "Binary search: comparing Import '__', Export '%s'\n",*/
581 /*VaToPa(&((PIMAGE_IMPORT_BY_NAME)VaToPa(ThunkData->u1.AddressOfData))->Name[0]),*/
582 /*(PCHAR)VaToPa(RVA(DllBase, NameTable[Middle])));*/
584 /*DPRINTM(DPRINT_WINDOWS, "TE->u1.AOD %p, fulladdr %p\n",
585 ThunkData->u1.AddressOfData,
586 ((PIMAGE_IMPORT_BY_NAME)VaToPa(ThunkData->u1.AddressOfData))->Name );*/
589 /* Depending on result of strcmp, perform different actions */
592 /* Adjust top boundary */
597 /* Adjust bottom boundary */
607 /* If high boundary is less than low boundary, then no result found */
610 //Print(L"Error in binary search\n");
611 DPRINTM(DPRINT_WINDOWS
, "Error in binary search!\n");
615 /* Everything allright, get the ordinal */
616 Ordinal
= OrdinalTable
[Middle
];
618 //DPRINTM(DPRINT_WINDOWS, "WinLdrpBindImportName() found Ordinal %d\n", Ordinal);
622 /* Check ordinal number for validity! */
623 if (Ordinal
>= ExportDirectory
->NumberOfFunctions
)
625 DPRINTM(DPRINT_WINDOWS
, "Ordinal number is invalid!\n");
629 /* Get a pointer to the function table */
630 FunctionTable
= (PULONG
)VaToPa(RVA(DllBase
, ExportDirectory
->AddressOfFunctions
));
632 /* Save a pointer to the function */
633 ThunkData
->u1
.Function
= (ULONG
)RVA(DllBase
, FunctionTable
[Ordinal
]);
635 /* Is it a forwarder? (function pointer isn't within the export directory) */
636 if (((ULONG
)VaToPa((PVOID
)ThunkData
->u1
.Function
) > (ULONG
)ExportDirectory
) &&
637 ((ULONG
)VaToPa((PVOID
)ThunkData
->u1
.Function
) < ((ULONG
)ExportDirectory
+ ExportSize
)))
639 PLDR_DATA_TABLE_ENTRY DataTableEntry
;
640 CHAR ForwardDllName
[255];
641 PIMAGE_EXPORT_DIRECTORY RefExportDirectory
;
644 /* Save the name of the forward dll */
645 RtlCopyMemory(ForwardDllName
, (PCHAR
)VaToPa((PVOID
)ThunkData
->u1
.Function
), sizeof(ForwardDllName
));
647 /* Strip out its extension */
648 *strchr(ForwardDllName
,'.') = '\0';
650 DPRINTM(DPRINT_WINDOWS
, "WinLdrpBindImportName(): ForwardDllName %s\n", ForwardDllName
);
651 if (!WinLdrCheckForLoadedDll(WinLdrBlock
, ForwardDllName
, &DataTableEntry
))
653 /* We can't continue if DLL couldn't be loaded, so bomb out with an error */
654 //Print(L"Error loading DLL!\n");
655 DPRINTM(DPRINT_WINDOWS
, "Error loading DLL!\n");
659 /* Get pointer to the export directory of loaded DLL */
660 RefExportDirectory
= (PIMAGE_EXPORT_DIRECTORY
)
661 RtlImageDirectoryEntryToData(VaToPa(DataTableEntry
->DllBase
),
663 IMAGE_DIRECTORY_ENTRY_EXPORT
,
666 /* Fail if it's NULL */
667 if (RefExportDirectory
)
670 IMAGE_THUNK_DATA RefThunkData
;
671 PIMAGE_IMPORT_BY_NAME ImportByName
;
675 /* Get pointer to the import name */
676 ImportName
= strchr((PCHAR
)VaToPa((PVOID
)ThunkData
->u1
.Function
), '.') + 1;
678 /* Create a IMAGE_IMPORT_BY_NAME structure, pointing to the local Buffer */
679 ImportByName
= (PIMAGE_IMPORT_BY_NAME
)Buffer
;
681 /* Fill the name with the import name */
682 RtlCopyMemory(ImportByName
->Name
, ImportName
, strlen(ImportName
)+1);
685 ImportByName
->Hint
= 0;
687 /* And finally point ThunkData's AddressOfData to that structure */
688 RefThunkData
.u1
.AddressOfData
= (ULONG
)ImportByName
;
690 /* And recursively call ourselves */
691 Status
= WinLdrpBindImportName(
693 DataTableEntry
->DllBase
,
700 /* Fill out the ThunkData with data from RefThunkData */
701 ThunkData
->u1
= RefThunkData
.u1
;
703 /* Return what we got from the recursive call */
708 /* Fail if ExportDirectory is NULL */
718 WinLdrpLoadAndScanReferencedDll(PLOADER_PARAMETER_BLOCK WinLdrBlock
,
721 PLDR_DATA_TABLE_ENTRY
*DataTableEntry
)
723 CHAR FullDllName
[256];
727 /* Prepare the full path to the file to be loaded */
728 strcpy(FullDllName
, DirectoryPath
);
729 strcat(FullDllName
, ImportName
);
731 DPRINTM(DPRINT_WINDOWS
, "Loading referenced DLL: %s\n", FullDllName
);
732 //Print(L"Loading referenced DLL: %s\n", FullDllName);
735 Status
= WinLdrLoadImage(FullDllName
, LoaderHalCode
, &BasePA
);
739 DPRINTM(DPRINT_WINDOWS
, "WinLdrLoadImage() failed\n");
743 /* Allocate DTE for newly loaded DLL */
744 Status
= WinLdrAllocateDataTableEntry(WinLdrBlock
,
752 DPRINTM(DPRINT_WINDOWS
,
753 "WinLdrAllocateDataTableEntry() failed with Status=0x%X\n", Status
);
757 /* Scan its dependencies too */
758 DPRINTM(DPRINT_WINDOWS
,
759 "WinLdrScanImportDescriptorTable() calling ourselves for %S\n",
760 VaToPa((*DataTableEntry
)->BaseDllName
.Buffer
));
761 Status
= WinLdrScanImportDescriptorTable(WinLdrBlock
, DirectoryPath
, *DataTableEntry
);
765 DPRINTM(DPRINT_WINDOWS
,
766 "WinLdrScanImportDescriptorTable() failed with Status=0x%X\n", Status
);
774 WinLdrpScanImportAddressTable(IN OUT PLOADER_PARAMETER_BLOCK WinLdrBlock
,
777 IN PIMAGE_THUNK_DATA ThunkData
)
779 PIMAGE_EXPORT_DIRECTORY ExportDirectory
= NULL
;
783 DPRINTM(DPRINT_WINDOWS
, "WinLdrpScanImportAddressTable(): DllBase 0x%X, "
784 "ImageBase 0x%X, ThunkData 0x%X\n", DllBase
, ImageBase
, ThunkData
);
786 /* Obtain the export table from the DLL's base */
789 //Print(L"Error, DllBase == NULL!\n");
795 (PIMAGE_EXPORT_DIRECTORY
)RtlImageDirectoryEntryToData(VaToPa(DllBase
),
797 IMAGE_DIRECTORY_ENTRY_EXPORT
,
801 DPRINTM(DPRINT_WINDOWS
, "WinLdrpScanImportAddressTable(): ExportDirectory 0x%X\n", ExportDirectory
);
803 /* If pointer to Export Directory is */
804 if (ExportDirectory
== NULL
)
807 /* Go through each entry in the thunk table and bind it */
808 while (((PIMAGE_THUNK_DATA
)VaToPa(ThunkData
))->u1
.AddressOfData
!= 0)
811 Status
= WinLdrpBindImportName(
820 /* Move to the next entry */
823 /* Return error if binding was unsuccessful */