90faea1f3b826f57c7ade0360f013203ed54e740
[reactos.git] / boot / freeldr / freeldr / windows / peloader.c
1 /*
2 * PROJECT: FreeLoader
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)
14 */
15
16 /* INCLUDES ***************************************************************/
17 #include <freeldr.h>
18 #include <debug.h>
19
20 DBG_DEFAULT_CHANNEL(PELOADER);
21
22 static BOOLEAN
23 WinLdrpCompareDllName(IN PCH DllName,
24 IN PUNICODE_STRING UnicodeName);
25
26 static BOOLEAN
27 WinLdrpBindImportName(IN OUT PLIST_ENTRY ModuleListHead,
28 IN PVOID DllBase,
29 IN PVOID ImageBase,
30 IN PIMAGE_THUNK_DATA ThunkData,
31 IN PIMAGE_EXPORT_DIRECTORY ExportDirectory,
32 IN ULONG ExportSize,
33 IN BOOLEAN ProcessForwards,
34 IN PCSTR DirectoryPath);
35
36 static BOOLEAN
37 WinLdrpLoadAndScanReferencedDll(PLIST_ENTRY ModuleListHead,
38 PCCH DirectoryPath,
39 PCH ImportName,
40 PLDR_DATA_TABLE_ENTRY *DataTableEntry);
41
42 static BOOLEAN
43 WinLdrpScanImportAddressTable(IN OUT PLIST_ENTRY ModuleListHead,
44 IN PVOID DllBase,
45 IN PVOID ImageBase,
46 IN PIMAGE_THUNK_DATA ThunkData,
47 IN PCSTR DirectoryPath);
48
49
50
51 /* FUNCTIONS **************************************************************/
52
53 /* Returns TRUE if DLL has already been loaded - looks in LoadOrderList in LPB */
54 BOOLEAN
55 WinLdrCheckForLoadedDll(IN OUT PLIST_ENTRY ModuleListHead,
56 IN PCH DllName,
57 OUT PLDR_DATA_TABLE_ENTRY *LoadedEntry)
58 {
59 PLDR_DATA_TABLE_ENTRY DataTableEntry;
60 LIST_ENTRY *ModuleEntry;
61
62 TRACE("WinLdrCheckForLoadedDll: DllName %s\n", DllName);
63
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)
68 {
69 /* Get pointer to the current DTE */
70 DataTableEntry = CONTAINING_RECORD(ModuleEntry,
71 LDR_DATA_TABLE_ENTRY,
72 InLoadOrderLinks);
73
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));
77
78 /* Compare names */
79 if (WinLdrpCompareDllName(DllName, &DataTableEntry->BaseDllName))
80 {
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);
86 return TRUE;
87 }
88
89 /* Go to the next entry */
90 ModuleEntry = ModuleEntry->Flink;
91 }
92
93 /* Nothing found */
94 return FALSE;
95 }
96
97 BOOLEAN
98 WinLdrScanImportDescriptorTable(IN OUT PLIST_ENTRY ModuleListHead,
99 IN PCCH DirectoryPath,
100 IN PLDR_DATA_TABLE_ENTRY ScanDTE)
101 {
102 PLDR_DATA_TABLE_ENTRY DataTableEntry;
103 PIMAGE_IMPORT_DESCRIPTOR ImportTable;
104 ULONG ImportTableSize;
105 PCH ImportName;
106 BOOLEAN Status;
107
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);
111
112 {
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);
119 }
120
121 /* If image doesn't have any import directory - just return success */
122 if (ImportTable == NULL)
123 return TRUE;
124
125 /* Loop through all entries */
126 for (;(ImportTable->Name != 0) && (ImportTable->FirstThunk != 0);ImportTable++)
127 {
128 /* Get pointer to the name */
129 ImportName = (PCH)VaToPa(RVA(ScanDTE->DllBase, ImportTable->Name));
130 TRACE("WinLdrScanImportDescriptorTable(): Looking at %s\n", ImportName);
131
132 /* In case we get a reference to ourselves - just skip it */
133 if (WinLdrpCompareDllName(ImportName, &ScanDTE->BaseDllName))
134 continue;
135
136 /* Load the DLL if it is not already loaded */
137 if (!WinLdrCheckForLoadedDll(ModuleListHead, ImportName, &DataTableEntry))
138 {
139 Status = WinLdrpLoadAndScanReferencedDll(ModuleListHead,
140 DirectoryPath,
141 ImportName,
142 &DataTableEntry);
143
144 if (!Status)
145 {
146 ERR("WinLdrpLoadAndScanReferencedDll() failed\n");
147 return Status;
148 }
149 }
150
151 /* Scan its import address table */
152 Status = WinLdrpScanImportAddressTable(
153 ModuleListHead,
154 DataTableEntry->DllBase,
155 ScanDTE->DllBase,
156 (PIMAGE_THUNK_DATA)RVA(ScanDTE->DllBase, ImportTable->FirstThunk),
157 DirectoryPath);
158
159 if (!Status)
160 {
161 ERR("WinLdrpScanImportAddressTable() failed: ImportName = '%s', DirectoryPath = '%s'\n",
162 ImportName, DirectoryPath);
163 return Status;
164 }
165 }
166
167 return TRUE;
168 }
169
170 BOOLEAN
171 WinLdrAllocateDataTableEntry(IN OUT PLIST_ENTRY ModuleListHead,
172 IN PCCH BaseDllName,
173 IN PCCH FullDllName,
174 IN PVOID BasePA,
175 OUT PLDR_DATA_TABLE_ENTRY *NewEntry)
176 {
177 PVOID BaseVA = PaToVa(BasePA);
178 PWSTR Buffer;
179 PLDR_DATA_TABLE_ENTRY DataTableEntry;
180 PIMAGE_NT_HEADERS NtHeaders;
181 USHORT Length;
182 TRACE("WinLdrAllocateDataTableEntry(, '%s', '%s', %p)\n",
183 BaseDllName, FullDllName, BasePA);
184
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)
188 return FALSE;
189 RtlZeroMemory(DataTableEntry, sizeof(LDR_DATA_TABLE_ENTRY));
190
191 /* Get NT headers from the image */
192 NtHeaders = RtlImageNtHeader(BasePA);
193
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;
200
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);
205 if (Buffer == NULL)
206 {
207 MmHeapFree(DataTableEntry);
208 return FALSE;
209 }
210 RtlZeroMemory(Buffer, Length);
211
212 DataTableEntry->BaseDllName.Length = Length;
213 DataTableEntry->BaseDllName.MaximumLength = Length;
214 DataTableEntry->BaseDllName.Buffer = PaToVa(Buffer);
215 while (*BaseDllName != 0)
216 {
217 *Buffer++ = *BaseDllName++;
218 }
219
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);
224 if (Buffer == NULL)
225 {
226 MmHeapFree(DataTableEntry);
227 return FALSE;
228 }
229 RtlZeroMemory(Buffer, Length);
230
231 DataTableEntry->FullDllName.Length = Length;
232 DataTableEntry->FullDllName.MaximumLength = Length;
233 DataTableEntry->FullDllName.Buffer = PaToVa(Buffer);
234 while (*FullDllName != 0)
235 {
236 *Buffer++ = *FullDllName++;
237 }
238
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;
243
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);
250
251 /* Save pointer to a newly allocated and initialized entry */
252 *NewEntry = DataTableEntry;
253
254 /* Return success */
255 return TRUE;
256 }
257
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
263 */
264 BOOLEAN
265 WinLdrLoadImage(IN PCHAR FileName,
266 TYPE_OF_MEMORY MemoryType,
267 OUT PVOID *ImageBasePA)
268 {
269 ULONG FileId;
270 PVOID PhysicalBase;
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;
276 LONG Status;
277 LARGE_INTEGER Position;
278 ULONG i, BytesRead;
279 TRACE("WinLdrLoadImage(%s, %ld, *)\n", FileName, MemoryType);
280
281 /* Open the image file */
282 Status = ArcOpen(FileName, OpenReadOnly, &FileId);
283 if (Status != ESUCCESS)
284 {
285 //UiMessageBox("Can not open the file");
286 return FALSE;
287 }
288
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)
292 {
293 UiMessageBox("Error reading from file");
294 ArcClose(FileId);
295 return FALSE;
296 }
297
298 /* Now read the MZ header to get the offset to the PE Header */
299 NtHeaders = RtlImageNtHeader(HeadersBuffer);
300 if (!NtHeaders)
301 {
302 //Print(L"Error - no NT header found in %s\n", FileName);
303 UiMessageBox("Error - no NT header found");
304 ArcClose(FileId);
305 return FALSE;
306 }
307
308 /* Ensure this is executable image */
309 if (((NtHeaders->FileHeader.Characteristics & IMAGE_FILE_EXECUTABLE_IMAGE) == 0))
310 {
311 //Print(L"Not an executable image %s\n", FileName);
312 UiMessageBox("Not an executable image");
313 ArcClose(FileId);
314 return FALSE;
315 }
316
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);
320
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)),
324 MemoryType);
325
326 if (PhysicalBase == NULL)
327 {
328 /* It's ok, we don't panic - let's allocate again at any other "low" place */
329 PhysicalBase = MmAllocateMemoryWithType(NtHeaders->OptionalHeader.SizeOfImage, MemoryType);
330
331 if (PhysicalBase == NULL)
332 {
333 //Print(L"Failed to alloc pages for image %s\n", FileName);
334 UiMessageBox("Failed to alloc pages for image");
335 ArcClose(FileId);
336 return FALSE;
337 }
338 }
339
340 /* This is the real image base - in form of a virtual address */
341 VirtualBase = PaToVa(PhysicalBase);
342
343 TRACE("Base PA: 0x%X, VA: 0x%X\n", PhysicalBase, VirtualBase);
344
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)
349 {
350 UiMessageBox("Error seeking to start of file");
351 ArcClose(FileId);
352 return FALSE;
353 }
354
355 Status = ArcRead(FileId, PhysicalBase, NtHeaders->OptionalHeader.SizeOfHeaders, &BytesRead);
356
357 if (Status != ESUCCESS)
358 {
359 //Print(L"Error reading headers %s\n", FileName);
360 UiMessageBox("Error reading headers");
361 ArcClose(FileId);
362 return FALSE;
363 }
364
365 /* Reload the NT Header */
366 NtHeaders = RtlImageNtHeader(PhysicalBase);
367
368 /* Load the first section */
369 SectionHeader = IMAGE_FIRST_SECTION(NtHeaders);
370
371 /* Fill output parameters */
372 *ImageBasePA = PhysicalBase;
373
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++)
377 {
378 VirtualSize = SectionHeader->Misc.VirtualSize;
379 SizeOfRawData = SectionHeader->SizeOfRawData;
380
381 /* Handle a case when VirtualSize equals 0 */
382 if (VirtualSize == 0)
383 VirtualSize = SizeOfRawData;
384
385 /* If PointerToRawData is 0, then force its size to be also 0 */
386 if (SectionHeader->PointerToRawData == 0)
387 {
388 SizeOfRawData = 0;
389 }
390 else
391 {
392 /* Cut the loaded size to the VirtualSize extents */
393 if (SizeOfRawData > VirtualSize)
394 SizeOfRawData = VirtualSize;
395 }
396
397 /* Actually read the section (if its size is not 0) */
398 if (SizeOfRawData != 0)
399 {
400 /* Seek to the correct position */
401 Position.LowPart = SectionHeader->PointerToRawData;
402 Status = ArcSeek(FileId, &Position, SeekAbsolute);
403
404 TRACE("SH->VA: 0x%X\n", SectionHeader->VirtualAddress);
405
406 /* Read this section from the file, size = SizeOfRawData */
407 Status = ArcRead(FileId, (PUCHAR)PhysicalBase + SectionHeader->VirtualAddress, SizeOfRawData, &BytesRead);
408
409 if (Status != ESUCCESS)
410 {
411 ERR("WinLdrLoadImage(): Error reading section from file!\n");
412 break;
413 }
414 }
415
416 /* Size of data is less than the virtual size - fill up the remainder with zeroes */
417 if (SizeOfRawData < VirtualSize)
418 {
419 TRACE("WinLdrLoadImage(): SORD %d < VS %d\n", SizeOfRawData, VirtualSize);
420 RtlZeroMemory((PVOID)(SectionHeader->VirtualAddress + (ULONG_PTR)PhysicalBase + SizeOfRawData), VirtualSize - SizeOfRawData);
421 }
422
423 SectionHeader++;
424 }
425
426 /* We are done with the file - close it */
427 ArcClose(FileId);
428
429 /* If loading failed - return right now */
430 if (Status != ESUCCESS)
431 return FALSE;
432
433
434 /* Relocate the image, if it needs it */
435 if (NtHeaders->OptionalHeader.ImageBase != (ULONG_PTR)VirtualBase)
436 {
437 WARN("Relocating %p -> %p\n", NtHeaders->OptionalHeader.ImageBase,
438 VirtualBase);
439 return (BOOLEAN)LdrRelocateImageWithBias(PhysicalBase,
440 (ULONG_PTR)VirtualBase - (ULONG_PTR)PhysicalBase,
441 "FreeLdr",
442 TRUE,
443 TRUE, /* in case of conflict still return success */
444 FALSE);
445 }
446
447 TRACE("WinLdrLoadImage() done, PA = %p\n", *ImageBasePA);
448 return TRUE;
449 }
450
451 /* PRIVATE FUNCTIONS *******************************************************/
452
453 /* DllName - physical, UnicodeString->Buffer - virtual */
454 static BOOLEAN
455 WinLdrpCompareDllName(IN PCH DllName,
456 IN PUNICODE_STRING UnicodeName)
457 {
458 PWSTR Buffer;
459 UNICODE_STRING UnicodeNamePA;
460 SIZE_T i, Length;
461
462 /* First obvious check: for length of two names */
463 Length = strlen(DllName);
464
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);
470
471 if ((Length * sizeof(WCHAR)) > UnicodeName->Length)
472 return FALSE;
473
474 /* Store pointer to unicode string's buffer */
475 Buffer = VaToPa(UnicodeName->Buffer);
476
477 /* Loop character by character */
478 for (i = 0; i < Length; i++)
479 {
480 /* Compare two characters, uppercasing them */
481 if (toupper(*DllName) != toupper((CHAR)*Buffer))
482 return FALSE;
483
484 /* Move to the next character */
485 DllName++;
486 Buffer++;
487 }
488
489 /* Check, if strings either fully match, or match till the "." (w/o extension) */
490 if ((UnicodeName->Length == Length * sizeof(WCHAR)) || (*Buffer == L'.'))
491 {
492 /* Yes they do */
493 return TRUE;
494 }
495
496 /* Strings don't match, return FALSE */
497 return FALSE;
498 }
499
500 static BOOLEAN
501 WinLdrpBindImportName(IN OUT PLIST_ENTRY ModuleListHead,
502 IN PVOID DllBase,
503 IN PVOID ImageBase,
504 IN PIMAGE_THUNK_DATA ThunkData,
505 IN PIMAGE_EXPORT_DIRECTORY ExportDirectory,
506 IN ULONG ExportSize,
507 IN BOOLEAN ProcessForwards,
508 IN PCSTR DirectoryPath)
509 {
510 ULONG Ordinal;
511 PULONG NameTable, FunctionTable;
512 PUSHORT OrdinalTable;
513 LONG High, Low, Middle, Result;
514 ULONG Hint;
515 PIMAGE_IMPORT_BY_NAME ImportData;
516 PCHAR ExportName, ForwarderName;
517 BOOLEAN Status;
518
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);
521
522 /* Check passed DllBase param */
523 if(DllBase == NULL)
524 {
525 WARN("DllBase == NULL!\n");
526 return FALSE;
527 }
528
529 /* Convert all non-critical pointers to PA from VA */
530 ThunkData = VaToPa(ThunkData);
531
532 /* Is the reference by ordinal? */
533 if (IMAGE_SNAP_BY_ORDINAL(ThunkData->u1.Ordinal) && !ProcessForwards)
534 {
535 /* Yes, calculate the ordinal */
536 Ordinal = (ULONG)(IMAGE_ORDINAL(ThunkData->u1.Ordinal) - (UINT32)ExportDirectory->Base);
537 //TRACE("WinLdrpBindImportName(): Ordinal %d\n", Ordinal);
538 }
539 else
540 {
541 /* It's reference by name, we have to look it up in the export directory */
542 if (!ProcessForwards)
543 {
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);
549 }
550
551 /* Get the import name */
552 ImportData = VaToPa((PVOID)ThunkData->u1.AddressOfData);
553
554 /* Get pointers to Name and Ordinal tables (RVA -> VA) */
555 NameTable = VaToPa(RVA(DllBase, ExportDirectory->AddressOfNames));
556 OrdinalTable = VaToPa(RVA(DllBase, ExportDirectory->AddressOfNameOrdinals));
557
558 //TRACE("NameTable 0x%X, OrdinalTable 0x%X, ED->AddressOfNames 0x%X, ED->AOFO 0x%X\n",
559 // NameTable, OrdinalTable, ExportDirectory->AddressOfNames, ExportDirectory->AddressOfNameOrdinals);
560
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);
564
565 /* Get the export name from the hint */
566 ExportName = VaToPa(RVA(DllBase, NameTable[Hint]));
567
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))
572 {
573 Ordinal = OrdinalTable[Hint];
574 //TRACE("WinLdrpBindImportName(): Ordinal %d\n", Ordinal);
575 }
576 else
577 {
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. */
580
581 //TRACE("WinLdrpBindImportName() looking up the import name using binary search...\n");
582
583 /* Low boundary is set to 0, and high boundary to the maximum index */
584 Low = 0;
585 High = ExportDirectory->NumberOfNames - 1;
586
587 /* Perform a binary-search loop */
588 while (High >= Low)
589 {
590 /* Divide by 2 by shifting to the right once */
591 Middle = (Low + High) / 2;
592
593 /* Get the name from the name table */
594 ExportName = VaToPa(RVA(DllBase, NameTable[Middle]));
595
596 /* Compare the names */
597 Result = strcmp(ExportName, (PCHAR)ImportData->Name);
598
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])));*/
602
603 /*TRACE("TE->u1.AOD %p, fulladdr %p\n",
604 ThunkData->u1.AddressOfData,
605 ((PIMAGE_IMPORT_BY_NAME)VaToPa(ThunkData->u1.AddressOfData))->Name );*/
606
607
608 /* Depending on result of strcmp, perform different actions */
609 if (Result > 0)
610 {
611 /* Adjust top boundary */
612 High = Middle - 1;
613 }
614 else if (Result < 0)
615 {
616 /* Adjust bottom boundary */
617 Low = Middle + 1;
618 }
619 else
620 {
621 /* Yay, found it! */
622 break;
623 }
624 }
625
626 /* If high boundary is less than low boundary, then no result found */
627 if (High < Low)
628 {
629 //Print(L"Error in binary search\n");
630 ERR("Did not find export '%s'!\n", (PCHAR)ImportData->Name);
631 return FALSE;
632 }
633
634 /* Everything allright, get the ordinal */
635 Ordinal = OrdinalTable[Middle];
636
637 //TRACE("WinLdrpBindImportName() found Ordinal %d\n", Ordinal);
638 }
639 }
640
641 /* Check ordinal number for validity! */
642 if (Ordinal >= ExportDirectory->NumberOfFunctions)
643 {
644 ERR("Ordinal number is invalid!\n");
645 return FALSE;
646 }
647
648 /* Get a pointer to the function table */
649 FunctionTable = (PULONG)VaToPa(RVA(DllBase, ExportDirectory->AddressOfFunctions));
650
651 /* Save a pointer to the function */
652 ThunkData->u1.Function = (ULONG_PTR)RVA(DllBase, FunctionTable[Ordinal]);
653
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)))
658 {
659 PLDR_DATA_TABLE_ENTRY DataTableEntry;
660 CHAR ForwardDllName[255];
661 PIMAGE_EXPORT_DIRECTORY RefExportDirectory;
662 ULONG RefExportSize;
663 TRACE("WinLdrpBindImportName(): ForwarderName %s\n", ForwarderName);
664
665 /* Save the name of the forward dll */
666 RtlCopyMemory(ForwardDllName, ForwarderName, sizeof(ForwardDllName));
667
668 /* Strip out the symbol name */
669 *strrchr(ForwardDllName,'.') = '\0';
670
671 /* Check if the target image is already loaded */
672 if (!WinLdrCheckForLoadedDll(ModuleListHead, ForwardDllName, &DataTableEntry))
673 {
674 /* Check if the forward dll name has an extension */
675 if (strchr(ForwardDllName, '.') == NULL)
676 {
677 /* Name does not have an extension, append '.dll' */
678 strcat(ForwardDllName, ".dll");
679 }
680
681 /* Now let's try to load it! */
682 Status = WinLdrpLoadAndScanReferencedDll(ModuleListHead,
683 DirectoryPath,
684 ForwardDllName,
685 &DataTableEntry);
686 if (!Status)
687 {
688 ERR("WinLdrpLoadAndScanReferencedDll() failed to load forwarder dll.\n");
689 return Status;
690 }
691 }
692
693 /* Get pointer to the export directory of loaded DLL */
694 RefExportDirectory = (PIMAGE_EXPORT_DIRECTORY)
695 RtlImageDirectoryEntryToData(VaToPa(DataTableEntry->DllBase),
696 TRUE,
697 IMAGE_DIRECTORY_ENTRY_EXPORT,
698 &RefExportSize);
699
700 /* Fail if it's NULL */
701 if (RefExportDirectory)
702 {
703 UCHAR Buffer[128];
704 IMAGE_THUNK_DATA RefThunkData;
705 PIMAGE_IMPORT_BY_NAME ImportByName;
706 PCHAR ImportName;
707
708 /* Get pointer to the import name */
709 ImportName = strrchr(ForwarderName, '.') + 1;
710
711 /* Create a IMAGE_IMPORT_BY_NAME structure, pointing to the local Buffer */
712 ImportByName = (PIMAGE_IMPORT_BY_NAME)Buffer;
713
714 /* Fill the name with the import name */
715 RtlCopyMemory(ImportByName->Name, ImportName, strlen(ImportName)+1);
716
717 /* Set Hint to 0 */
718 ImportByName->Hint = 0;
719
720 /* And finally point ThunkData's AddressOfData to that structure */
721 RefThunkData.u1.AddressOfData = (ULONG_PTR)ImportByName;
722
723 /* And recursively call ourselves */
724 Status = WinLdrpBindImportName(
725 ModuleListHead,
726 DataTableEntry->DllBase,
727 ImageBase,
728 &RefThunkData,
729 RefExportDirectory,
730 RefExportSize,
731 TRUE,
732 DirectoryPath);
733
734 /* Fill out the ThunkData with data from RefThunkData */
735 ThunkData->u1 = RefThunkData.u1;
736
737 /* Return what we got from the recursive call */
738 return Status;
739 }
740 else
741 {
742 /* Fail if ExportDirectory is NULL */
743 return FALSE;
744 }
745 }
746
747 /* Success! */
748 return TRUE;
749 }
750
751 static BOOLEAN
752 WinLdrpLoadAndScanReferencedDll(PLIST_ENTRY ModuleListHead,
753 PCCH DirectoryPath,
754 PCH ImportName,
755 PLDR_DATA_TABLE_ENTRY *DataTableEntry)
756 {
757 CHAR FullDllName[256];
758 BOOLEAN Status;
759 PVOID BasePA;
760
761 /* Prepare the full path to the file to be loaded */
762 strcpy(FullDllName, DirectoryPath);
763 strcat(FullDllName, ImportName);
764
765 TRACE("Loading referenced DLL: %s\n", FullDllName);
766 //Print(L"Loading referenced DLL: %s\n", FullDllName);
767
768 /* Load the image */
769 Status = WinLdrLoadImage(FullDllName, LoaderBootDriver, &BasePA);
770 if (!Status)
771 {
772 ERR("WinLdrLoadImage() failed\n");
773 return Status;
774 }
775
776 /* Allocate DTE for newly loaded DLL */
777 Status = WinLdrAllocateDataTableEntry(ModuleListHead,
778 ImportName,
779 FullDllName,
780 BasePA,
781 DataTableEntry);
782 if (!Status)
783 {
784 ERR("WinLdrAllocateDataTableEntry() failed with Status=0x%X\n", Status);
785 return Status;
786 }
787
788 /* Scan its dependencies too */
789 TRACE("WinLdrScanImportDescriptorTable() calling ourselves for %S\n",
790 VaToPa((*DataTableEntry)->BaseDllName.Buffer));
791 Status = WinLdrScanImportDescriptorTable(ModuleListHead, DirectoryPath, *DataTableEntry);
792 if (!Status)
793 {
794 ERR("WinLdrScanImportDescriptorTable() failed with Status=0x%X\n", Status);
795 return Status;
796 }
797
798 return TRUE;
799 }
800
801 static BOOLEAN
802 WinLdrpScanImportAddressTable(IN OUT PLIST_ENTRY ModuleListHead,
803 IN PVOID DllBase,
804 IN PVOID ImageBase,
805 IN PIMAGE_THUNK_DATA ThunkData,
806 IN PCSTR DirectoryPath)
807 {
808 PIMAGE_EXPORT_DIRECTORY ExportDirectory = NULL;
809 BOOLEAN Status;
810 ULONG ExportSize;
811
812 TRACE("WinLdrpScanImportAddressTable(): DllBase 0x%X, "
813 "ImageBase 0x%X, ThunkData 0x%X\n", DllBase, ImageBase, ThunkData);
814
815 /* Obtain the export table from the DLL's base */
816 if (DllBase == NULL)
817 {
818 ERR("Error, DllBase == NULL!\n");
819 return FALSE;
820 }
821 else
822 {
823 ExportDirectory =
824 (PIMAGE_EXPORT_DIRECTORY)RtlImageDirectoryEntryToData(VaToPa(DllBase),
825 TRUE,
826 IMAGE_DIRECTORY_ENTRY_EXPORT,
827 &ExportSize);
828 }
829
830 TRACE("WinLdrpScanImportAddressTable(): ExportDirectory 0x%X\n", ExportDirectory);
831
832 /* If pointer to Export Directory is */
833 if (ExportDirectory == NULL)
834 {
835 ERR("DllBase=%p(%p)\n", DllBase, VaToPa(DllBase));
836 return FALSE;
837 }
838
839 /* Go through each entry in the thunk table and bind it */
840 while (((PIMAGE_THUNK_DATA)VaToPa(ThunkData))->u1.AddressOfData != 0)
841 {
842 /* Bind it */
843 Status = WinLdrpBindImportName(
844 ModuleListHead,
845 DllBase,
846 ImageBase,
847 ThunkData,
848 ExportDirectory,
849 ExportSize,
850 FALSE,
851 DirectoryPath);
852
853 /* Move to the next entry */
854 ThunkData++;
855
856 /* Return error if binding was unsuccessful */
857 if (!Status)
858 return Status;
859 }
860
861 /* Return success */
862 return TRUE;
863 }