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 ***************************************************************/
20 DBG_DEFAULT_CHANNEL(PELOADER
);
23 WinLdrpCompareDllName(IN PCH DllName
,
24 IN PUNICODE_STRING UnicodeName
);
27 WinLdrpBindImportName(IN OUT PLIST_ENTRY ModuleListHead
,
30 IN PIMAGE_THUNK_DATA ThunkData
,
31 IN PIMAGE_EXPORT_DIRECTORY ExportDirectory
,
33 IN BOOLEAN ProcessForwards
,
34 IN PCSTR DirectoryPath
);
37 WinLdrpLoadAndScanReferencedDll(PLIST_ENTRY ModuleListHead
,
40 PLDR_DATA_TABLE_ENTRY
*DataTableEntry
);
43 WinLdrpScanImportAddressTable(IN OUT PLIST_ENTRY ModuleListHead
,
46 IN PIMAGE_THUNK_DATA ThunkData
,
47 IN PCSTR DirectoryPath
);
51 /* FUNCTIONS **************************************************************/
53 /* Returns TRUE if DLL has already been loaded - looks in LoadOrderList in LPB */
55 WinLdrCheckForLoadedDll(IN OUT PLIST_ENTRY ModuleListHead
,
57 OUT PLDR_DATA_TABLE_ENTRY
*LoadedEntry
)
59 PLDR_DATA_TABLE_ENTRY DataTableEntry
;
60 LIST_ENTRY
*ModuleEntry
;
62 TRACE("WinLdrCheckForLoadedDll: DllName %s\n", DllName
);
64 /* Just go through each entry in the LoadOrderList and compare loaded module's
65 name with a given name */
66 ModuleEntry
= ModuleListHead
->Flink
;
67 while (ModuleEntry
!= ModuleListHead
)
69 /* Get pointer to the current DTE */
70 DataTableEntry
= CONTAINING_RECORD(ModuleEntry
,
74 TRACE("WinLdrCheckForLoadedDll: DTE %p, EP %p, base %p name '%.*ws'\n",
75 DataTableEntry
, DataTableEntry
->EntryPoint
, DataTableEntry
->DllBase
,
76 DataTableEntry
->BaseDllName
.Length
/ 2, VaToPa(DataTableEntry
->BaseDllName
.Buffer
));
79 if (WinLdrpCompareDllName(DllName
, &DataTableEntry
->BaseDllName
))
81 /* Yes, found it, report pointer to the loaded module's DTE
82 to the caller and increase load count for it */
83 *LoadedEntry
= DataTableEntry
;
84 DataTableEntry
->LoadCount
++;
85 TRACE("WinLdrCheckForLoadedDll: LoadedEntry %X\n", DataTableEntry
);
89 /* Go to the next entry */
90 ModuleEntry
= ModuleEntry
->Flink
;
98 WinLdrScanImportDescriptorTable(IN OUT PLIST_ENTRY ModuleListHead
,
99 IN PCCH DirectoryPath
,
100 IN PLDR_DATA_TABLE_ENTRY ScanDTE
)
102 PLDR_DATA_TABLE_ENTRY DataTableEntry
;
103 PIMAGE_IMPORT_DESCRIPTOR ImportTable
;
104 ULONG ImportTableSize
;
108 /* Get a pointer to the import table of this image */
109 ImportTable
= (PIMAGE_IMPORT_DESCRIPTOR
)RtlImageDirectoryEntryToData(VaToPa(ScanDTE
->DllBase
),
110 TRUE
, IMAGE_DIRECTORY_ENTRY_IMPORT
, &ImportTableSize
);
113 UNICODE_STRING BaseName
;
114 BaseName
.Buffer
= VaToPa(ScanDTE
->BaseDllName
.Buffer
);
115 BaseName
.MaximumLength
= ScanDTE
->BaseDllName
.MaximumLength
;
116 BaseName
.Length
= ScanDTE
->BaseDllName
.Length
;
117 TRACE("WinLdrScanImportDescriptorTable(): %wZ ImportTable = 0x%X\n",
118 &BaseName
, ImportTable
);
121 /* If image doesn't have any import directory - just return success */
122 if (ImportTable
== NULL
)
125 /* Loop through all entries */
126 for (;(ImportTable
->Name
!= 0) && (ImportTable
->FirstThunk
!= 0);ImportTable
++)
128 /* Get pointer to the name */
129 ImportName
= (PCH
)VaToPa(RVA(ScanDTE
->DllBase
, ImportTable
->Name
));
130 TRACE("WinLdrScanImportDescriptorTable(): Looking at %s\n", ImportName
);
132 /* In case we get a reference to ourselves - just skip it */
133 if (WinLdrpCompareDllName(ImportName
, &ScanDTE
->BaseDllName
))
136 /* Load the DLL if it is not already loaded */
137 if (!WinLdrCheckForLoadedDll(ModuleListHead
, ImportName
, &DataTableEntry
))
139 Status
= WinLdrpLoadAndScanReferencedDll(ModuleListHead
,
146 ERR("WinLdrpLoadAndScanReferencedDll() failed\n");
151 /* Scan its import address table */
152 Status
= WinLdrpScanImportAddressTable(
154 DataTableEntry
->DllBase
,
156 (PIMAGE_THUNK_DATA
)RVA(ScanDTE
->DllBase
, ImportTable
->FirstThunk
),
161 ERR("WinLdrpScanImportAddressTable() failed: ImportName = '%s', DirectoryPath = '%s'\n",
162 ImportName
, DirectoryPath
);
171 WinLdrAllocateDataTableEntry(IN OUT PLIST_ENTRY ModuleListHead
,
175 OUT PLDR_DATA_TABLE_ENTRY
*NewEntry
)
177 PVOID BaseVA
= PaToVa(BasePA
);
179 PLDR_DATA_TABLE_ENTRY DataTableEntry
;
180 PIMAGE_NT_HEADERS NtHeaders
;
182 TRACE("WinLdrAllocateDataTableEntry(, '%s', '%s', %p)\n",
183 BaseDllName
, FullDllName
, BasePA
);
185 /* Allocate memory for a data table entry, zero-initialize it */
186 DataTableEntry
= (PLDR_DATA_TABLE_ENTRY
)MmHeapAlloc(sizeof(LDR_DATA_TABLE_ENTRY
));
187 if (DataTableEntry
== NULL
)
189 RtlZeroMemory(DataTableEntry
, sizeof(LDR_DATA_TABLE_ENTRY
));
191 /* Get NT headers from the image */
192 NtHeaders
= RtlImageNtHeader(BasePA
);
194 /* Initialize corresponding fields of DTE based on NT headers value */
195 DataTableEntry
->DllBase
= BaseVA
;
196 DataTableEntry
->SizeOfImage
= NtHeaders
->OptionalHeader
.SizeOfImage
;
197 DataTableEntry
->EntryPoint
= RVA(BaseVA
, NtHeaders
->OptionalHeader
.AddressOfEntryPoint
);
198 DataTableEntry
->SectionPointer
= 0;
199 DataTableEntry
->CheckSum
= NtHeaders
->OptionalHeader
.CheckSum
;
201 /* Initialize BaseDllName field (UNICODE_STRING) from the Ansi BaseDllName
202 by simple conversion - copying each character */
203 Length
= (USHORT
)(strlen(BaseDllName
) * sizeof(WCHAR
));
204 Buffer
= (PWSTR
)MmHeapAlloc(Length
);
207 MmHeapFree(DataTableEntry
);
210 RtlZeroMemory(Buffer
, Length
);
212 DataTableEntry
->BaseDllName
.Length
= Length
;
213 DataTableEntry
->BaseDllName
.MaximumLength
= Length
;
214 DataTableEntry
->BaseDllName
.Buffer
= PaToVa(Buffer
);
215 while (*BaseDllName
!= 0)
217 *Buffer
++ = *BaseDllName
++;
220 /* Initialize FullDllName field (UNICODE_STRING) from the Ansi FullDllName
221 using the same method */
222 Length
= (USHORT
)(strlen(FullDllName
) * sizeof(WCHAR
));
223 Buffer
= (PWSTR
)MmHeapAlloc(Length
);
226 MmHeapFree(DataTableEntry
);
229 RtlZeroMemory(Buffer
, Length
);
231 DataTableEntry
->FullDllName
.Length
= Length
;
232 DataTableEntry
->FullDllName
.MaximumLength
= Length
;
233 DataTableEntry
->FullDllName
.Buffer
= PaToVa(Buffer
);
234 while (*FullDllName
!= 0)
236 *Buffer
++ = *FullDllName
++;
239 /* Initialize what's left - LoadCount which is 1, and set Flags so that
240 we know this entry is processed */
241 DataTableEntry
->Flags
= LDRP_ENTRY_PROCESSED
;
242 DataTableEntry
->LoadCount
= 1;
244 /* Insert this DTE to a list in the LPB */
245 InsertTailList(ModuleListHead
, &DataTableEntry
->InLoadOrderLinks
);
246 TRACE("Inserting DTE %p, name='%.*S' DllBase=%p \n", DataTableEntry
,
247 DataTableEntry
->BaseDllName
.Length
/ 2,
248 VaToPa(DataTableEntry
->BaseDllName
.Buffer
),
249 DataTableEntry
->DllBase
);
251 /* Save pointer to a newly allocated and initialized entry */
252 *NewEntry
= DataTableEntry
;
258 /* WinLdrLoadImage loads the specified image from the file (it doesn't
259 perform any additional operations on the filename, just directly
260 calls the file I/O routines), and relocates it so that it's ready
261 to be used when paging is enabled.
262 Addressing mode: physical
265 WinLdrLoadImage(IN PCHAR FileName
,
266 TYPE_OF_MEMORY MemoryType
,
267 OUT PVOID
*ImageBasePA
)
271 PVOID VirtualBase
= NULL
;
272 UCHAR HeadersBuffer
[SECTOR_SIZE
* 2];
273 PIMAGE_NT_HEADERS NtHeaders
;
274 PIMAGE_SECTION_HEADER SectionHeader
;
275 ULONG VirtualSize
, SizeOfRawData
, NumberOfSections
;
277 LARGE_INTEGER Position
;
279 TRACE("WinLdrLoadImage(%s, %ld, *)\n", FileName
, MemoryType
);
281 /* Open the image file */
282 Status
= ArcOpen(FileName
, OpenReadOnly
, &FileId
);
283 if (Status
!= ESUCCESS
)
285 //UiMessageBox("Can not open the file");
289 /* Load the first 2 sectors of the image so we can read the PE header */
290 Status
= ArcRead(FileId
, HeadersBuffer
, SECTOR_SIZE
* 2, &BytesRead
);
291 if (Status
!= ESUCCESS
)
293 UiMessageBox("Error reading from file");
298 /* Now read the MZ header to get the offset to the PE Header */
299 NtHeaders
= RtlImageNtHeader(HeadersBuffer
);
302 //Print(L"Error - no NT header found in %s\n", FileName);
303 UiMessageBox("Error - no NT header found");
308 /* Ensure this is executable image */
309 if (((NtHeaders
->FileHeader
.Characteristics
& IMAGE_FILE_EXECUTABLE_IMAGE
) == 0))
311 //Print(L"Not an executable image %s\n", FileName);
312 UiMessageBox("Not an executable image");
317 /* Store number of sections to read and a pointer to the first section */
318 NumberOfSections
= NtHeaders
->FileHeader
.NumberOfSections
;
319 SectionHeader
= IMAGE_FIRST_SECTION(NtHeaders
);
321 /* Try to allocate this memory, if fails - allocate somewhere else */
322 PhysicalBase
= MmAllocateMemoryAtAddress(NtHeaders
->OptionalHeader
.SizeOfImage
,
323 (PVOID
)((ULONG
)NtHeaders
->OptionalHeader
.ImageBase
& (KSEG0_BASE
- 1)),
326 if (PhysicalBase
== NULL
)
328 /* It's ok, we don't panic - let's allocate again at any other "low" place */
329 PhysicalBase
= MmAllocateMemoryWithType(NtHeaders
->OptionalHeader
.SizeOfImage
, MemoryType
);
331 if (PhysicalBase
== NULL
)
333 //Print(L"Failed to alloc pages for image %s\n", FileName);
334 UiMessageBox("Failed to alloc pages for image");
340 /* This is the real image base - in form of a virtual address */
341 VirtualBase
= PaToVa(PhysicalBase
);
343 TRACE("Base PA: 0x%X, VA: 0x%X\n", PhysicalBase
, VirtualBase
);
345 /* Set to 0 position and fully load the file image */
346 Position
.HighPart
= Position
.LowPart
= 0;
347 Status
= ArcSeek(FileId
, &Position
, SeekAbsolute
);
348 if (Status
!= ESUCCESS
)
350 UiMessageBox("Error seeking to start of file");
355 Status
= ArcRead(FileId
, PhysicalBase
, NtHeaders
->OptionalHeader
.SizeOfHeaders
, &BytesRead
);
357 if (Status
!= ESUCCESS
)
359 //Print(L"Error reading headers %s\n", FileName);
360 UiMessageBox("Error reading headers");
365 /* Reload the NT Header */
366 NtHeaders
= RtlImageNtHeader(PhysicalBase
);
368 /* Load the first section */
369 SectionHeader
= IMAGE_FIRST_SECTION(NtHeaders
);
371 /* Fill output parameters */
372 *ImageBasePA
= PhysicalBase
;
374 /* Walk through each section and read it (check/fix any possible
375 bad situations, if they arise) */
376 for (i
= 0; i
< NumberOfSections
; i
++)
378 VirtualSize
= SectionHeader
->Misc
.VirtualSize
;
379 SizeOfRawData
= SectionHeader
->SizeOfRawData
;
381 /* Handle a case when VirtualSize equals 0 */
382 if (VirtualSize
== 0)
383 VirtualSize
= SizeOfRawData
;
385 /* If PointerToRawData is 0, then force its size to be also 0 */
386 if (SectionHeader
->PointerToRawData
== 0)
392 /* Cut the loaded size to the VirtualSize extents */
393 if (SizeOfRawData
> VirtualSize
)
394 SizeOfRawData
= VirtualSize
;
397 /* Actually read the section (if its size is not 0) */
398 if (SizeOfRawData
!= 0)
400 /* Seek to the correct position */
401 Position
.LowPart
= SectionHeader
->PointerToRawData
;
402 Status
= ArcSeek(FileId
, &Position
, SeekAbsolute
);
404 TRACE("SH->VA: 0x%X\n", SectionHeader
->VirtualAddress
);
406 /* Read this section from the file, size = SizeOfRawData */
407 Status
= ArcRead(FileId
, (PUCHAR
)PhysicalBase
+ SectionHeader
->VirtualAddress
, SizeOfRawData
, &BytesRead
);
409 if (Status
!= ESUCCESS
)
411 ERR("WinLdrLoadImage(): Error reading section from file!\n");
416 /* Size of data is less than the virtual size - fill up the remainder with zeroes */
417 if (SizeOfRawData
< VirtualSize
)
419 TRACE("WinLdrLoadImage(): SORD %d < VS %d\n", SizeOfRawData
, VirtualSize
);
420 RtlZeroMemory((PVOID
)(SectionHeader
->VirtualAddress
+ (ULONG_PTR
)PhysicalBase
+ SizeOfRawData
), VirtualSize
- SizeOfRawData
);
426 /* We are done with the file - close it */
429 /* If loading failed - return right now */
430 if (Status
!= ESUCCESS
)
434 /* Relocate the image, if it needs it */
435 if (NtHeaders
->OptionalHeader
.ImageBase
!= (ULONG_PTR
)VirtualBase
)
437 WARN("Relocating %p -> %p\n", NtHeaders
->OptionalHeader
.ImageBase
,
439 return (BOOLEAN
)LdrRelocateImageWithBias(PhysicalBase
,
440 (ULONG_PTR
)VirtualBase
- (ULONG_PTR
)PhysicalBase
,
443 TRUE
, /* in case of conflict still return success */
447 TRACE("WinLdrLoadImage() done, PA = %p\n", *ImageBasePA
);
451 /* PRIVATE FUNCTIONS *******************************************************/
453 /* DllName - physical, UnicodeString->Buffer - virtual */
455 WinLdrpCompareDllName(IN PCH DllName
,
456 IN PUNICODE_STRING UnicodeName
)
459 UNICODE_STRING UnicodeNamePA
;
462 /* First obvious check: for length of two names */
463 Length
= strlen(DllName
);
465 UnicodeNamePA
.Length
= UnicodeName
->Length
;
466 UnicodeNamePA
.MaximumLength
= UnicodeName
->MaximumLength
;
467 UnicodeNamePA
.Buffer
= VaToPa(UnicodeName
->Buffer
);
468 TRACE("WinLdrpCompareDllName: %s and %wZ, Length = %d "
469 "UN->Length %d\n", DllName
, &UnicodeNamePA
, Length
, UnicodeName
->Length
);
471 if ((Length
* sizeof(WCHAR
)) > UnicodeName
->Length
)
474 /* Store pointer to unicode string's buffer */
475 Buffer
= VaToPa(UnicodeName
->Buffer
);
477 /* Loop character by character */
478 for (i
= 0; i
< Length
; i
++)
480 /* Compare two characters, uppercasing them */
481 if (toupper(*DllName
) != toupper((CHAR
)*Buffer
))
484 /* Move to the next character */
489 /* Check, if strings either fully match, or match till the "." (w/o extension) */
490 if ((UnicodeName
->Length
== Length
* sizeof(WCHAR
)) || (*Buffer
== L
'.'))
496 /* Strings don't match, return FALSE */
501 WinLdrpBindImportName(IN OUT PLIST_ENTRY ModuleListHead
,
504 IN PIMAGE_THUNK_DATA ThunkData
,
505 IN PIMAGE_EXPORT_DIRECTORY ExportDirectory
,
507 IN BOOLEAN ProcessForwards
,
508 IN PCSTR DirectoryPath
)
511 PULONG NameTable
, FunctionTable
;
512 PUSHORT OrdinalTable
;
513 LONG High
, Low
, Middle
, Result
;
515 PIMAGE_IMPORT_BY_NAME ImportData
;
516 PCHAR ExportName
, ForwarderName
;
519 //TRACE("WinLdrpBindImportName(): DllBase 0x%X, ImageBase 0x%X, ThunkData 0x%X, ExportDirectory 0x%X, ExportSize %d, ProcessForwards 0x%X\n",
520 // DllBase, ImageBase, ThunkData, ExportDirectory, ExportSize, ProcessForwards);
522 /* Check passed DllBase param */
525 WARN("DllBase == NULL!\n");
529 /* Convert all non-critical pointers to PA from VA */
530 ThunkData
= VaToPa(ThunkData
);
532 /* Is the reference by ordinal? */
533 if (IMAGE_SNAP_BY_ORDINAL(ThunkData
->u1
.Ordinal
) && !ProcessForwards
)
535 /* Yes, calculate the ordinal */
536 Ordinal
= (ULONG
)(IMAGE_ORDINAL(ThunkData
->u1
.Ordinal
) - (UINT32
)ExportDirectory
->Base
);
537 //TRACE("WinLdrpBindImportName(): Ordinal %d\n", Ordinal);
541 /* It's reference by name, we have to look it up in the export directory */
542 if (!ProcessForwards
)
544 /* AddressOfData in thunk entry will become a virtual address (from relative) */
545 //TRACE("WinLdrpBindImportName(): ThunkData->u1.AOD was %p\n", ThunkData->u1.AddressOfData);
546 ThunkData
->u1
.AddressOfData
=
547 (ULONG_PTR
)RVA(ImageBase
, ThunkData
->u1
.AddressOfData
);
548 //TRACE("WinLdrpBindImportName(): ThunkData->u1.AOD became %p\n", ThunkData->u1.AddressOfData);
551 /* Get the import name */
552 ImportData
= VaToPa((PVOID
)ThunkData
->u1
.AddressOfData
);
554 /* Get pointers to Name and Ordinal tables (RVA -> VA) */
555 NameTable
= VaToPa(RVA(DllBase
, ExportDirectory
->AddressOfNames
));
556 OrdinalTable
= VaToPa(RVA(DllBase
, ExportDirectory
->AddressOfNameOrdinals
));
558 //TRACE("NameTable 0x%X, OrdinalTable 0x%X, ED->AddressOfNames 0x%X, ED->AOFO 0x%X\n",
559 // NameTable, OrdinalTable, ExportDirectory->AddressOfNames, ExportDirectory->AddressOfNameOrdinals);
561 /* Get the hint, convert it to a physical pointer */
562 Hint
= ((PIMAGE_IMPORT_BY_NAME
)VaToPa((PVOID
)ThunkData
->u1
.AddressOfData
))->Hint
;
563 //TRACE("HintIndex %d\n", Hint);
565 /* Get the export name from the hint */
566 ExportName
= VaToPa(RVA(DllBase
, NameTable
[Hint
]));
568 /* If Hint is less than total number of entries in the export directory,
569 and import name == export name, then we can just get it from the OrdinalTable */
570 if ((Hint
< ExportDirectory
->NumberOfNames
) &&
571 (strcmp(ExportName
, (PCHAR
)ImportData
->Name
) == 0))
573 Ordinal
= OrdinalTable
[Hint
];
574 //TRACE("WinLdrpBindImportName(): Ordinal %d\n", Ordinal);
578 /* It's not the easy way, we have to lookup import name in the name table.
579 Let's use a binary search for this task. */
581 //TRACE("WinLdrpBindImportName() looking up the import name using binary search...\n");
583 /* Low boundary is set to 0, and high boundary to the maximum index */
585 High
= ExportDirectory
->NumberOfNames
- 1;
587 /* Perform a binary-search loop */
590 /* Divide by 2 by shifting to the right once */
591 Middle
= (Low
+ High
) / 2;
593 /* Get the name from the name table */
594 ExportName
= VaToPa(RVA(DllBase
, NameTable
[Middle
]));
596 /* Compare the names */
597 Result
= strcmp(ExportName
, (PCHAR
)ImportData
->Name
);
599 /*TRACE("Binary search: comparing Import '__', Export '%s'\n",*/
600 /*VaToPa(&((PIMAGE_IMPORT_BY_NAME)VaToPa(ThunkData->u1.AddressOfData))->Name[0]),*/
601 /*(PCHAR)VaToPa(RVA(DllBase, NameTable[Middle])));*/
603 /*TRACE("TE->u1.AOD %p, fulladdr %p\n",
604 ThunkData->u1.AddressOfData,
605 ((PIMAGE_IMPORT_BY_NAME)VaToPa(ThunkData->u1.AddressOfData))->Name );*/
608 /* Depending on result of strcmp, perform different actions */
611 /* Adjust top boundary */
616 /* Adjust bottom boundary */
626 /* If high boundary is less than low boundary, then no result found */
629 //Print(L"Error in binary search\n");
630 ERR("Did not find export '%s'!\n", (PCHAR
)ImportData
->Name
);
634 /* Everything allright, get the ordinal */
635 Ordinal
= OrdinalTable
[Middle
];
637 //TRACE("WinLdrpBindImportName() found Ordinal %d\n", Ordinal);
641 /* Check ordinal number for validity! */
642 if (Ordinal
>= ExportDirectory
->NumberOfFunctions
)
644 ERR("Ordinal number is invalid!\n");
648 /* Get a pointer to the function table */
649 FunctionTable
= (PULONG
)VaToPa(RVA(DllBase
, ExportDirectory
->AddressOfFunctions
));
651 /* Save a pointer to the function */
652 ThunkData
->u1
.Function
= (ULONG_PTR
)RVA(DllBase
, FunctionTable
[Ordinal
]);
654 /* Is it a forwarder? (function pointer is within the export directory) */
655 ForwarderName
= (PCHAR
)VaToPa((PVOID
)ThunkData
->u1
.Function
);
656 if (((ULONG_PTR
)ForwarderName
> (ULONG_PTR
)ExportDirectory
) &&
657 ((ULONG_PTR
)ForwarderName
< ((ULONG_PTR
)ExportDirectory
+ ExportSize
)))
659 PLDR_DATA_TABLE_ENTRY DataTableEntry
;
660 CHAR ForwardDllName
[255];
661 PIMAGE_EXPORT_DIRECTORY RefExportDirectory
;
663 TRACE("WinLdrpBindImportName(): ForwarderName %s\n", ForwarderName
);
665 /* Save the name of the forward dll */
666 RtlCopyMemory(ForwardDllName
, ForwarderName
, sizeof(ForwardDllName
));
668 /* Strip out the symbol name */
669 *strrchr(ForwardDllName
,'.') = '\0';
671 /* Check if the target image is already loaded */
672 if (!WinLdrCheckForLoadedDll(ModuleListHead
, ForwardDllName
, &DataTableEntry
))
674 /* Check if the forward dll name has an extension */
675 if (strchr(ForwardDllName
, '.') == NULL
)
677 /* Name does not have an extension, append '.dll' */
678 strcat(ForwardDllName
, ".dll");
681 /* Now let's try to load it! */
682 Status
= WinLdrpLoadAndScanReferencedDll(ModuleListHead
,
688 ERR("WinLdrpLoadAndScanReferencedDll() failed to load forwarder dll.\n");
693 /* Get pointer to the export directory of loaded DLL */
694 RefExportDirectory
= (PIMAGE_EXPORT_DIRECTORY
)
695 RtlImageDirectoryEntryToData(VaToPa(DataTableEntry
->DllBase
),
697 IMAGE_DIRECTORY_ENTRY_EXPORT
,
700 /* Fail if it's NULL */
701 if (RefExportDirectory
)
704 IMAGE_THUNK_DATA RefThunkData
;
705 PIMAGE_IMPORT_BY_NAME ImportByName
;
708 /* Get pointer to the import name */
709 ImportName
= strrchr(ForwarderName
, '.') + 1;
711 /* Create a IMAGE_IMPORT_BY_NAME structure, pointing to the local Buffer */
712 ImportByName
= (PIMAGE_IMPORT_BY_NAME
)Buffer
;
714 /* Fill the name with the import name */
715 RtlCopyMemory(ImportByName
->Name
, ImportName
, strlen(ImportName
)+1);
718 ImportByName
->Hint
= 0;
720 /* And finally point ThunkData's AddressOfData to that structure */
721 RefThunkData
.u1
.AddressOfData
= (ULONG_PTR
)ImportByName
;
723 /* And recursively call ourselves */
724 Status
= WinLdrpBindImportName(
726 DataTableEntry
->DllBase
,
734 /* Fill out the ThunkData with data from RefThunkData */
735 ThunkData
->u1
= RefThunkData
.u1
;
737 /* Return what we got from the recursive call */
742 /* Fail if ExportDirectory is NULL */
752 WinLdrpLoadAndScanReferencedDll(PLIST_ENTRY ModuleListHead
,
755 PLDR_DATA_TABLE_ENTRY
*DataTableEntry
)
757 CHAR FullDllName
[256];
761 /* Prepare the full path to the file to be loaded */
762 strcpy(FullDllName
, DirectoryPath
);
763 strcat(FullDllName
, ImportName
);
765 TRACE("Loading referenced DLL: %s\n", FullDllName
);
766 //Print(L"Loading referenced DLL: %s\n", FullDllName);
769 Status
= WinLdrLoadImage(FullDllName
, LoaderBootDriver
, &BasePA
);
772 ERR("WinLdrLoadImage() failed\n");
776 /* Allocate DTE for newly loaded DLL */
777 Status
= WinLdrAllocateDataTableEntry(ModuleListHead
,
784 ERR("WinLdrAllocateDataTableEntry() failed with Status=0x%X\n", Status
);
788 /* Scan its dependencies too */
789 TRACE("WinLdrScanImportDescriptorTable() calling ourselves for %S\n",
790 VaToPa((*DataTableEntry
)->BaseDllName
.Buffer
));
791 Status
= WinLdrScanImportDescriptorTable(ModuleListHead
, DirectoryPath
, *DataTableEntry
);
794 ERR("WinLdrScanImportDescriptorTable() failed with Status=0x%X\n", Status
);
802 WinLdrpScanImportAddressTable(IN OUT PLIST_ENTRY ModuleListHead
,
805 IN PIMAGE_THUNK_DATA ThunkData
,
806 IN PCSTR DirectoryPath
)
808 PIMAGE_EXPORT_DIRECTORY ExportDirectory
= NULL
;
812 TRACE("WinLdrpScanImportAddressTable(): DllBase 0x%X, "
813 "ImageBase 0x%X, ThunkData 0x%X\n", DllBase
, ImageBase
, ThunkData
);
815 /* Obtain the export table from the DLL's base */
818 ERR("Error, DllBase == NULL!\n");
824 (PIMAGE_EXPORT_DIRECTORY
)RtlImageDirectoryEntryToData(VaToPa(DllBase
),
826 IMAGE_DIRECTORY_ENTRY_EXPORT
,
830 TRACE("WinLdrpScanImportAddressTable(): ExportDirectory 0x%X\n", ExportDirectory
);
832 /* If pointer to Export Directory is */
833 if (ExportDirectory
== NULL
)
835 ERR("DllBase=%p(%p)\n", DllBase
, VaToPa(DllBase
));
839 /* Go through each entry in the thunk table and bind it */
840 while (((PIMAGE_THUNK_DATA
)VaToPa(ThunkData
))->u1
.AddressOfData
!= 0)
843 Status
= WinLdrpBindImportName(
853 /* Move to the next entry */
856 /* Return error if binding was unsuccessful */