:pserver:cvsanon@mok.lvcm.com:/CVS/ReactOS reactos
[reactos.git] / ntoskrnl / ldr / loader.c
1 /* $Id$
2  * 
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
7  * PROGRAMMERS:     Jean Michault
8  *                  Rex Jolliff (rex@lvcablemodem.com)
9  *                  Jason Filby (jasonfilby@yahoo.com)
10  *                  Casper S. Hornstrup (chorns@users.sourceforge.net)
11  * UPDATE HISTORY:
12  *   DW   22/05/98   Created
13  *   RJJ  10/12/98   Completed image loader function and added hooks for MZ/PE
14  *   RJJ  10/12/98   Built driver loader function and added hooks for PE/COFF
15  *   RJJ  10/12/98   Rolled in David's code to load COFF drivers
16  *   JM   14/12/98   Built initial PE user module loader
17  *   RJJ  06/03/99   Moved user PE loader into NTDLL
18  *   JF   26/01/2000 Recoded some parts to retrieve export details correctly
19  *   DW   27/06/2000 Removed redundant header files
20  *   CSH  11/04/2001 Added automatic loading of module symbols if they exist
21  */
22
23
24 /* INCLUDES *****************************************************************/
25
26 #include <limits.h>
27 #include <ddk/ntddk.h>
28 #include <roscfg.h>
29 #include <internal/module.h>
30 #include <internal/ntoskrnl.h>
31 #include <internal/kd.h>
32 #include <internal/io.h>
33 #include <internal/mm.h>
34 #include <internal/ps.h>
35 #include <internal/ldr.h>
36 #include <internal/pool.h>
37 #include <internal/kd.h>
38 #include <ntos/minmax.h>
39
40 #ifdef HALDBG
41 #include <internal/ntosdbg.h>
42 #else
43 #define ps(args...)
44 #endif
45
46 #define NDEBUG
47 #include <internal/debug.h>
48
49 /* GLOBALS *******************************************************************/
50
51 LIST_ENTRY ModuleListHead;
52 KSPIN_LOCK ModuleListLock;
53
54 LIST_ENTRY ModuleTextListHead;
55 STATIC MODULE_TEXT_SECTION NtoskrnlTextSection;
56 STATIC MODULE_TEXT_SECTION LdrHalTextSection;
57 ULONG_PTR LdrHalBase;
58
59 #define TAG_DRIVER_MEM  TAG('D', 'R', 'V', 'M')
60
61 /* FORWARD DECLARATIONS ******************************************************/
62
63 NTSTATUS
64 LdrProcessModule(PVOID ModuleLoadBase,
65                  PUNICODE_STRING ModuleName,
66                  PMODULE_OBJECT *ModuleObject);
67
68 PVOID
69 LdrGetExportAddress(PMODULE_OBJECT ModuleObject,
70                     char *Name,
71                     unsigned short Hint);
72
73 static VOID
74 LdrpBuildModuleBaseName(PUNICODE_STRING BaseName,
75                         PUNICODE_STRING FullName);
76
77 static LONG
78 LdrpCompareModuleNames(IN PUNICODE_STRING String1,
79                        IN PUNICODE_STRING String2);
80
81
82 /*  PE Driver load support  */
83 static NTSTATUS LdrPEProcessModule(PVOID ModuleLoadBase,
84                                    PUNICODE_STRING FileName,
85                                    PMODULE_OBJECT *ModuleObject);
86 static PVOID
87 LdrPEGetExportAddress(PMODULE_OBJECT ModuleObject,
88                       PCHAR Name,
89                       USHORT Hint);
90
91 static PVOID
92 LdrSafePEGetExportAddress(PVOID ImportModuleBase,
93                           PCHAR Name,
94                           USHORT Hint);
95
96 static PVOID
97 LdrPEFixupForward(PCHAR ForwardName);
98
99
100 /* FUNCTIONS *****************************************************************/
101
102 VOID
103 LdrInitDebug(PLOADER_MODULE Module, PWCH Name)
104 {
105   PLIST_ENTRY current_entry;
106   MODULE_TEXT_SECTION* current;
107
108   current_entry = ModuleTextListHead.Flink;
109   while (current_entry != &ModuleTextListHead)
110     {
111       current = 
112         CONTAINING_RECORD(current_entry, MODULE_TEXT_SECTION, ListEntry);
113       if (wcscmp(current->Name, Name) == 0)
114         {
115           break;
116         }
117       current_entry = current_entry->Flink;
118     }
119
120   if (current_entry == &ModuleTextListHead)
121     {
122       return;
123     }
124 }
125
126 VOID
127 LdrInit1(VOID)
128 {
129   PIMAGE_DOS_HEADER DosHeader;
130   PIMAGE_FILE_HEADER FileHeader;
131   PIMAGE_OPTIONAL_HEADER OptionalHeader;
132   PIMAGE_SECTION_HEADER SectionList;
133
134   InitializeListHead(&ModuleTextListHead);
135
136   /* Setup ntoskrnl.exe text section */
137   DosHeader = (PIMAGE_DOS_HEADER) KERNEL_BASE;
138   FileHeader =
139     (PIMAGE_FILE_HEADER) ((DWORD)KERNEL_BASE + 
140                           DosHeader->e_lfanew + sizeof(ULONG));
141   OptionalHeader = (PIMAGE_OPTIONAL_HEADER)
142     ((DWORD)FileHeader + sizeof(IMAGE_FILE_HEADER));
143   SectionList = (PIMAGE_SECTION_HEADER)
144     ((DWORD)OptionalHeader + sizeof(IMAGE_OPTIONAL_HEADER));
145   NtoskrnlTextSection.Base = KERNEL_BASE;
146   NtoskrnlTextSection.Length = SectionList[0].Misc.VirtualSize +
147     SectionList[0].VirtualAddress;
148   NtoskrnlTextSection.Name = KERNEL_MODULE_NAME;
149   NtoskrnlTextSection.OptionalHeader = OptionalHeader;
150   InsertTailList(&ModuleTextListHead, &NtoskrnlTextSection.ListEntry);
151
152   /* Setup hal.dll text section */
153   DosHeader = (PIMAGE_DOS_HEADER)LdrHalBase;
154   FileHeader =
155     (PIMAGE_FILE_HEADER) ((DWORD)LdrHalBase + 
156                           DosHeader->e_lfanew + sizeof(ULONG));
157   OptionalHeader = (PIMAGE_OPTIONAL_HEADER)
158     ((DWORD)FileHeader + sizeof(IMAGE_FILE_HEADER));
159   SectionList = (PIMAGE_SECTION_HEADER)
160     ((DWORD)OptionalHeader + sizeof(IMAGE_OPTIONAL_HEADER));
161   LdrHalTextSection.Base = LdrHalBase;
162   LdrHalTextSection.Length = SectionList[0].Misc.VirtualSize +
163     SectionList[0].VirtualAddress;
164   LdrHalTextSection.Name = HAL_MODULE_NAME;
165   LdrHalTextSection.OptionalHeader = OptionalHeader;
166   InsertTailList(&ModuleTextListHead, &LdrHalTextSection.ListEntry);
167
168   /* Hook for KDB on initialization of the loader. */
169   KDB_LOADERINIT_HOOK(&NtoskrnlTextSection, &LdrHalTextSection);
170 }
171
172
173 VOID
174 LdrInitModuleManagement(VOID)
175 {
176   PIMAGE_DOS_HEADER DosHeader;
177   PMODULE_OBJECT ModuleObject;
178
179   /* Initialize the module list and spinlock */
180   InitializeListHead(&ModuleListHead);
181   KeInitializeSpinLock(&ModuleListLock);
182
183   /* Create module object for NTOSKRNL */
184   ModuleObject = ExAllocatePool(NonPagedPool, sizeof(MODULE_OBJECT));
185   assert(ModuleObject != NULL);
186   RtlZeroMemory(ModuleObject, sizeof(MODULE_OBJECT));
187
188   /* Initialize ModuleObject data */
189   ModuleObject->Base = (PVOID) KERNEL_BASE;
190   ModuleObject->Flags = MODULE_FLAG_PE;
191   RtlCreateUnicodeString(&ModuleObject->FullName,
192                          KERNEL_MODULE_NAME);
193   LdrpBuildModuleBaseName(&ModuleObject->BaseName,
194                           &ModuleObject->FullName);
195
196   DosHeader = (PIMAGE_DOS_HEADER) KERNEL_BASE;
197   ModuleObject->Image.PE.FileHeader =
198     (PIMAGE_FILE_HEADER) ((DWORD) ModuleObject->Base +
199     DosHeader->e_lfanew + sizeof(ULONG));
200   ModuleObject->Image.PE.OptionalHeader = (PIMAGE_OPTIONAL_HEADER)
201     ((DWORD)ModuleObject->Image.PE.FileHeader + sizeof(IMAGE_FILE_HEADER));
202   ModuleObject->Image.PE.SectionList = (PIMAGE_SECTION_HEADER)
203     ((DWORD)ModuleObject->Image.PE.OptionalHeader + sizeof(IMAGE_OPTIONAL_HEADER));
204   ModuleObject->EntryPoint = (PVOID) ((DWORD) ModuleObject->Base +
205     ModuleObject->Image.PE.OptionalHeader->AddressOfEntryPoint);
206   DPRINT("ModuleObject:%08x  entrypoint at %x\n", ModuleObject, ModuleObject->EntryPoint);
207   ModuleObject->Length = ModuleObject->Image.PE.OptionalHeader->SizeOfImage;
208   ModuleObject->TextSection = &NtoskrnlTextSection;
209
210   InsertTailList(&ModuleListHead,
211                  &ModuleObject->ListEntry);
212
213   /* Create module object for HAL */
214   ModuleObject = ExAllocatePool(NonPagedPool, sizeof(MODULE_OBJECT));
215   assert(ModuleObject != NULL);
216   RtlZeroMemory(ModuleObject, sizeof(MODULE_OBJECT));
217
218   /* Initialize ModuleObject data */
219   ModuleObject->Base = (PVOID) LdrHalBase;
220   ModuleObject->Flags = MODULE_FLAG_PE;
221
222   RtlCreateUnicodeString(&ModuleObject->FullName,
223                          HAL_MODULE_NAME);
224   LdrpBuildModuleBaseName(&ModuleObject->BaseName,
225                           &ModuleObject->FullName);
226
227   DosHeader = (PIMAGE_DOS_HEADER) LdrHalBase;
228   ModuleObject->Image.PE.FileHeader =
229     (PIMAGE_FILE_HEADER) ((DWORD) ModuleObject->Base +
230     DosHeader->e_lfanew + sizeof(ULONG));
231   ModuleObject->Image.PE.OptionalHeader = (PIMAGE_OPTIONAL_HEADER)
232     ((DWORD)ModuleObject->Image.PE.FileHeader + sizeof(IMAGE_FILE_HEADER));
233   ModuleObject->Image.PE.SectionList = (PIMAGE_SECTION_HEADER)
234     ((DWORD)ModuleObject->Image.PE.OptionalHeader + sizeof(IMAGE_OPTIONAL_HEADER));
235   ModuleObject->EntryPoint = (PVOID) ((DWORD) ModuleObject->Base +
236     ModuleObject->Image.PE.OptionalHeader->AddressOfEntryPoint);
237   DPRINT("ModuleObject:%08x  entrypoint at %x\n", ModuleObject, ModuleObject->EntryPoint);
238   ModuleObject->Length = ModuleObject->Image.PE.OptionalHeader->SizeOfImage;
239   ModuleObject->TextSection = &LdrHalTextSection;
240
241   InsertTailList(&ModuleListHead,
242                  &ModuleObject->ListEntry);
243 }
244
245 NTSTATUS
246 LdrpLoadImage(PUNICODE_STRING DriverName,
247               PVOID *ModuleBase,
248               PVOID *SectionPointer,
249               PVOID *EntryPoint,
250               PVOID *ExportSectionPointer)
251 {
252   PMODULE_OBJECT ModuleObject;
253   NTSTATUS Status;
254
255   ModuleObject = LdrGetModuleObject(DriverName);
256   if (ModuleObject == NULL)
257     {
258       Status = LdrLoadModule(DriverName, &ModuleObject);
259       if (!NT_SUCCESS(Status))
260         {
261           return(Status);
262         }
263     }
264
265   if (ModuleBase)
266     *ModuleBase = ModuleObject->Base;
267
268 //  if (SectionPointer)
269 //    *SectionPointer = ModuleObject->
270
271   if (EntryPoint)
272     *EntryPoint = ModuleObject->EntryPoint;
273
274 //  if (ExportSectionPointer)
275 //    *ExportSectionPointer = ModuleObject->
276
277   return(STATUS_SUCCESS);
278 }
279
280
281 NTSTATUS
282 LdrpUnloadImage(PVOID ModuleBase)
283 {
284   return(STATUS_NOT_IMPLEMENTED);
285 }
286
287
288 NTSTATUS
289 LdrpLoadAndCallImage(PUNICODE_STRING ModuleName)
290 {
291   PDRIVER_INITIALIZE DriverEntry;
292   PMODULE_OBJECT ModuleObject;
293   NTSTATUS Status;
294
295   ModuleObject = LdrGetModuleObject(ModuleName);
296   if (ModuleObject != NULL)
297     {
298       return(STATUS_IMAGE_ALREADY_LOADED);
299     }
300
301   Status = LdrLoadModule(ModuleName, &ModuleObject);
302   if (!NT_SUCCESS(Status))
303     {
304       return(Status);
305     }
306
307   DriverEntry = (PDRIVER_INITIALIZE)ModuleObject->EntryPoint;
308
309   Status = DriverEntry(NULL, NULL);
310   if (!NT_SUCCESS(Status))
311     {
312       LdrUnloadModule(ModuleObject);
313     }
314
315   return(Status);
316 }
317
318
319 NTSTATUS
320 LdrLoadModule(PUNICODE_STRING Filename,
321               PMODULE_OBJECT *ModuleObject)
322 {
323   PVOID ModuleLoadBase;
324   NTSTATUS Status;
325   HANDLE FileHandle;
326   OBJECT_ATTRIBUTES ObjectAttributes;
327   PMODULE_OBJECT Module;
328   FILE_STANDARD_INFORMATION FileStdInfo;
329   IO_STATUS_BLOCK IoStatusBlock;
330
331   *ModuleObject = NULL;
332
333   DPRINT("Loading Module %wZ...\n", Filename);
334
335   /*  Open the Module  */
336   InitializeObjectAttributes(&ObjectAttributes,
337                              Filename,
338                              0,
339                              NULL,
340                              NULL);
341   CHECKPOINT;
342   Status = NtOpenFile(&FileHandle,
343                       FILE_ALL_ACCESS,
344                       &ObjectAttributes,
345                       &IoStatusBlock,
346                       0,
347                       FILE_SYNCHRONOUS_IO_NONALERT);
348   CHECKPOINT;
349   if (!NT_SUCCESS(Status))
350     {
351       CPRINT("Could not open module file: %wZ\n", Filename);
352       return(Status);
353     }
354   CHECKPOINT;
355
356   /*  Get the size of the file  */
357   Status = NtQueryInformationFile(FileHandle,
358                                   &IoStatusBlock,
359                                   &FileStdInfo,
360                                   sizeof(FileStdInfo),
361                                   FileStandardInformation);
362   if (!NT_SUCCESS(Status))
363     {
364       CPRINT("Could not get file size\n");
365       NtClose(FileHandle);
366       return(Status);
367     }
368   CHECKPOINT;
369
370   /*  Allocate nonpageable memory for driver  */
371   ModuleLoadBase = ExAllocatePoolWithTag(NonPagedPool,
372                                          FileStdInfo.EndOfFile.u.LowPart,
373                                          TAG_DRIVER_MEM);
374   if (ModuleLoadBase == NULL)
375     {
376       CPRINT("Could not allocate memory for module");
377       NtClose(FileHandle);
378       return(STATUS_INSUFFICIENT_RESOURCES);
379     }
380   CHECKPOINT;
381
382   /*  Load driver into memory chunk  */
383   Status = NtReadFile(FileHandle,
384                       0, 0, 0,
385                       &IoStatusBlock,
386                       ModuleLoadBase,
387                       FileStdInfo.EndOfFile.u.LowPart,
388                       0, 0);
389   if (!NT_SUCCESS(Status))
390     {
391       CPRINT("Could not read module file into memory");
392       ExFreePool(ModuleLoadBase);
393       NtClose(FileHandle);
394       return(Status);
395     }
396   CHECKPOINT;
397
398   NtClose(FileHandle);
399
400   Status = LdrProcessModule(ModuleLoadBase,
401                             Filename,
402                             &Module);
403   if (!NT_SUCCESS(Status))
404     {
405       CPRINT("Could not process module");
406       ExFreePool(ModuleLoadBase);
407       return(Status);
408     }
409
410   /*  Cleanup  */
411   ExFreePool(ModuleLoadBase);
412
413   *ModuleObject = Module;
414
415   /* Hook for KDB on loading a driver. */
416   KDB_LOADDRIVER_HOOK(Filename, Module);
417
418   return(STATUS_SUCCESS);
419 }
420
421
422 NTSTATUS
423 LdrUnloadModule(PMODULE_OBJECT ModuleObject)
424 {
425   KIRQL Irql;
426
427   /* Remove the module from the module list */
428   KeAcquireSpinLock(&ModuleListLock,&Irql);
429   RemoveEntryList(&ModuleObject->ListEntry);
430   KeReleaseSpinLock(&ModuleListLock, Irql);
431
432   /* Hook for KDB on unloading a driver. */
433   KDB_UNLOADDRIVER_HOOK(ModuleObject);
434
435   /* Free text section */
436   if (ModuleObject->TextSection != NULL)
437     {
438       ExFreePool(ModuleObject->TextSection->Name);
439       RemoveEntryList(&ModuleObject->TextSection->ListEntry);
440       ExFreePool(ModuleObject->TextSection);
441       ModuleObject->TextSection = NULL;
442     }
443
444   /* Free module section */
445 //  MmFreeSection(ModuleObject->Base);
446
447   ExFreePool(ModuleObject);
448
449   return(STATUS_SUCCESS);
450 }
451
452
453 NTSTATUS
454 LdrInitializeBootStartDriver(PVOID ModuleLoadBase,
455                              PCHAR FileName,
456                              ULONG ModuleLength)
457 {
458   PMODULE_OBJECT ModuleObject;
459   UNICODE_STRING ModuleName;
460   PDEVICE_NODE DeviceNode;
461   NTSTATUS Status;
462
463   WCHAR Buffer[MAX_PATH];
464   ULONG Length;
465   LPWSTR Start;
466   LPWSTR Ext;
467   PCHAR FileExt;
468   CHAR TextBuffer [256];
469   ULONG x, y, cx, cy;
470
471   HalQueryDisplayParameters(&x, &y, &cx, &cy);
472   RtlFillMemory(TextBuffer, x, ' ');
473   TextBuffer[x] = '\0';
474   HalSetDisplayParameters(0, y-1);
475   HalDisplayString(TextBuffer);
476
477   sprintf(TextBuffer, "Initializing %s...\n", FileName);
478   HalSetDisplayParameters(0, y-1);
479   HalDisplayString(TextBuffer);
480   HalSetDisplayParameters(cx, cy);
481
482   /*  Split the filename into base name and extension  */
483   FileExt = strrchr(FileName, '.');
484   if (FileExt != NULL)
485     Length = FileExt - FileName;
486   else
487     Length = strlen(FileName);
488
489   if ((FileExt != NULL) && (strcmp(FileExt, ".sym") == 0))
490     {
491       KDB_SYMBOLFILE_HOOK(ModuleLoadBase, FileName, Length);
492       return(STATUS_SUCCESS);
493     }
494   else if ((FileExt != NULL) && !(strcmp(FileExt, ".sys") == 0))
495     {
496       CPRINT("Ignoring non-driver file %s\n", FileName);
497       return STATUS_SUCCESS;
498     }
499
500   /* Use IopRootDeviceNode for now */
501   Status = IopCreateDeviceNode(IopRootDeviceNode, NULL, &DeviceNode);
502   if (!NT_SUCCESS(Status))
503     {
504       CPRINT("Driver load failed, status (%x)\n", Status);
505       return(Status);
506     }
507
508   RtlCreateUnicodeStringFromAsciiz(&ModuleName,
509                                    FileName);
510   Status = LdrProcessModule(ModuleLoadBase,
511                             &ModuleName,
512                             &ModuleObject);
513   RtlFreeUnicodeString(&ModuleName);
514   if (ModuleObject == NULL)
515     {
516       IopFreeDeviceNode(DeviceNode);
517       CPRINT("Driver load failed, status (%x)\n", Status);
518       return(STATUS_UNSUCCESSFUL);
519     }
520
521
522   /* Get the service name from the module name */
523   Start = wcsrchr(ModuleObject->BaseName.Buffer, L'\\');
524   if (Start == NULL)
525     Start = ModuleObject->BaseName.Buffer;
526   else
527     Start++;
528
529   Ext = wcsrchr(ModuleObject->BaseName.Buffer, L'.');
530   if (Ext != NULL)
531     Length = Ext - Start;
532   else
533     Length = wcslen(Start);
534
535   wcsncpy(Buffer, Start, Length);
536   RtlCreateUnicodeString(&DeviceNode->ServiceName, Buffer);
537
538   Status = IopInitializeDriver(ModuleObject->EntryPoint,
539                                DeviceNode, FALSE);
540   if (!NT_SUCCESS(Status))
541     {
542       IopFreeDeviceNode(DeviceNode);
543       CPRINT("Driver load failed, status (%x)\n", Status);
544     }
545
546   return(Status);
547 }
548
549
550 NTSTATUS
551 LdrProcessModule(PVOID ModuleLoadBase,
552                  PUNICODE_STRING ModuleName,
553                  PMODULE_OBJECT *ModuleObject)
554 {
555   PIMAGE_DOS_HEADER PEDosHeader;
556
557   /*  If MZ header exists  */
558   PEDosHeader = (PIMAGE_DOS_HEADER) ModuleLoadBase;
559   if (PEDosHeader->e_magic == IMAGE_DOS_MAGIC && PEDosHeader->e_lfanew != 0L)
560     {
561       return LdrPEProcessModule(ModuleLoadBase,
562                                 ModuleName,
563                                 ModuleObject);
564     }
565
566   CPRINT("Module wasn't PE\n");
567   return STATUS_UNSUCCESSFUL;
568 }
569
570
571 PVOID
572 LdrGetExportAddress(PMODULE_OBJECT ModuleObject,
573                     char *Name,
574                     unsigned short Hint)
575 {
576   if (ModuleObject->Flags & MODULE_FLAG_PE)
577     {
578       return LdrPEGetExportAddress(ModuleObject, Name, Hint);
579     }
580   else
581     {
582       return 0;
583     }
584 }
585
586
587 NTSTATUS
588 LdrpQueryModuleInformation(PVOID Buffer,
589                            ULONG Size,
590                            PULONG ReqSize)
591 {
592   PLIST_ENTRY current_entry;
593   PMODULE_OBJECT current;
594   ULONG ModuleCount = 0;
595   PSYSTEM_MODULE_INFORMATION Smi;
596   ANSI_STRING AnsiName;
597   PCHAR p;
598   KIRQL Irql;
599
600   KeAcquireSpinLock(&ModuleListLock,&Irql);
601
602   /* calculate required size */
603   current_entry = ModuleListHead.Flink;
604   while (current_entry != (&ModuleListHead))
605     {
606       ModuleCount++;
607       current_entry = current_entry->Flink;
608     }
609
610   *ReqSize = sizeof(SYSTEM_MODULE_INFORMATION)+
611     (ModuleCount - 1) * sizeof(SYSTEM_MODULE_ENTRY);
612
613   if (Size < *ReqSize)
614     {
615       KeReleaseSpinLock(&ModuleListLock, Irql);
616       return(STATUS_INFO_LENGTH_MISMATCH);
617     }
618
619   /* fill the buffer */
620   memset(Buffer, '=', Size);
621
622   Smi = (PSYSTEM_MODULE_INFORMATION)Buffer;
623   Smi->Count = ModuleCount;
624
625   ModuleCount = 0;
626   current_entry = ModuleListHead.Flink;
627   while (current_entry != (&ModuleListHead))
628     {
629       current = CONTAINING_RECORD(current_entry,MODULE_OBJECT,ListEntry);
630
631       Smi->Module[ModuleCount].Unknown2 = 0;            /* Always 0 */
632       Smi->Module[ModuleCount].BaseAddress = current->Base;
633       Smi->Module[ModuleCount].Size = current->Length;
634       Smi->Module[ModuleCount].Flags = 0;               /* Flags ??? (GN) */
635       Smi->Module[ModuleCount].EntryIndex = ModuleCount;
636
637       AnsiName.Length = 0;
638       AnsiName.MaximumLength = 256;
639       AnsiName.Buffer = Smi->Module[ModuleCount].Name;
640       RtlUnicodeStringToAnsiString(&AnsiName,
641                                    &current->FullName,
642                                    FALSE);
643
644       p = strrchr(AnsiName.Buffer, '\\');
645       if (p == NULL)
646         {
647           Smi->Module[ModuleCount].PathLength = 0;
648           Smi->Module[ModuleCount].NameLength = strlen(AnsiName.Buffer);
649         }
650       else
651         {
652           p++;
653           Smi->Module[ModuleCount].PathLength = p - AnsiName.Buffer;
654           Smi->Module[ModuleCount].NameLength = strlen(p);
655         }
656
657       ModuleCount++;
658       current_entry = current_entry->Flink;
659     }
660
661   KeReleaseSpinLock(&ModuleListLock, Irql);
662
663   return(STATUS_SUCCESS);
664 }
665
666
667 static VOID
668 LdrpBuildModuleBaseName(PUNICODE_STRING BaseName,
669                         PUNICODE_STRING FullName)
670 {
671    UNICODE_STRING Name;
672    PWCHAR p;
673    PWCHAR q;
674
675    DPRINT("LdrpBuildModuleBaseName()\n");
676    DPRINT("FullName %wZ\n", FullName);
677
678    p = wcsrchr(FullName->Buffer, L'\\');
679    if (p == NULL)
680      {
681         p = FullName->Buffer;
682      }
683    else
684      {
685         p++;
686      }
687
688    DPRINT("p %S\n", p);
689
690    RtlCreateUnicodeString(&Name, p);
691
692    q = wcschr(Name.Buffer, L'.');
693    if (q != NULL)
694      {
695         *q = (WCHAR)0;
696      }
697
698    DPRINT("p %S\n", p);
699
700    RtlCreateUnicodeString(BaseName, Name.Buffer);
701    RtlFreeUnicodeString(&Name);
702 }
703
704
705 static LONG
706 LdrpCompareModuleNames(IN PUNICODE_STRING String1,
707                        IN PUNICODE_STRING String2)
708 {
709   ULONG len1, len2, i;
710   PWCHAR s1, s2, p;
711   WCHAR  c1, c2;
712
713   if (String1 && String2)
714     {
715       /* Search String1 for last path component */
716       len1 = String1->Length / sizeof(WCHAR);
717       s1 = String1->Buffer;
718       for (i = 0, p = String1->Buffer; i < String1->Length; i = i + sizeof(WCHAR), p++)
719         {
720           if (*p == L'\\')
721             {
722               if (i == String1->Length - sizeof(WCHAR))
723                 {
724                   s1 = NULL;
725                   len1 = 0;
726                 }
727               else
728                 {
729                   s1 = p + 1;
730                   len1 = (String1->Length - i) / sizeof(WCHAR);
731                 }
732             }
733         }
734
735       /* Search String2 for last path component */
736       len2 = String2->Length / sizeof(WCHAR);
737       s2 = String2->Buffer;
738       for (i = 0, p = String2->Buffer; i < String2->Length; i = i + sizeof(WCHAR), p++)
739         {
740           if (*p == L'\\')
741             {
742               if (i == String2->Length - sizeof(WCHAR))
743                 {
744                   s2 = NULL;
745                   len2 = 0;
746                 }
747               else
748                 {
749                   s2 = p + 1;
750                   len2 = (String2->Length - i) / sizeof(WCHAR);
751                 }
752             }
753         }
754
755       /* Compare last path components */
756       if (s1 && s2)
757         {
758           while (1)
759             {
760               c1 = len1-- ? RtlUpcaseUnicodeChar (*s1++) : 0;
761               c2 = len2-- ? RtlUpcaseUnicodeChar (*s2++) : 0;
762               if ((c1 == 0 && c2 == L'.') || (c1 == L'.' && c2 == 0))
763                 return(0);
764               if (!c1 || !c2 || c1 != c2)
765                 return(c1 - c2);
766             }
767         }
768     }
769
770   return(0);
771 }
772
773
774 PMODULE_OBJECT
775 LdrGetModuleObject(PUNICODE_STRING ModuleName)
776 {
777   PMODULE_OBJECT Module;
778   PLIST_ENTRY Entry;
779   KIRQL Irql;
780
781   DPRINT("LdrpGetModuleObject(%wZ) called\n", ModuleName);
782
783   KeAcquireSpinLock(&ModuleListLock,&Irql);
784
785   Entry = ModuleListHead.Flink;
786   while (Entry != &ModuleListHead)
787     {
788       Module = CONTAINING_RECORD(Entry, MODULE_OBJECT, ListEntry);
789
790       DPRINT("Comparing %wZ and %wZ\n",
791              &Module->BaseName,
792              ModuleName);
793
794       if (!LdrpCompareModuleNames(&Module->BaseName, ModuleName))
795         {
796           DPRINT("Module %wZ\n", &Module->BaseName);
797           KeReleaseSpinLock(&ModuleListLock, Irql);
798           return(Module);
799         }
800
801       Entry = Entry->Flink;
802     }
803
804   KeReleaseSpinLock(&ModuleListLock, Irql);
805
806   DPRINT("Could not find module '%wZ'\n", ModuleName);
807
808   return(NULL);
809 }
810
811
812 /*  ----------------------------------------------  PE Module support */
813
814 static NTSTATUS
815 LdrPEProcessModule(PVOID ModuleLoadBase,
816                    PUNICODE_STRING FileName,
817                    PMODULE_OBJECT *ModuleObject)
818 {
819   unsigned int DriverSize, Idx;
820   ULONG RelocDelta, NumRelocs;
821   DWORD CurrentSize, TotalRelocs;
822   PVOID DriverBase;
823   PULONG PEMagic;
824   PIMAGE_DOS_HEADER PEDosHeader;
825   PIMAGE_FILE_HEADER PEFileHeader;
826   PIMAGE_OPTIONAL_HEADER PEOptionalHeader;
827   PIMAGE_SECTION_HEADER PESectionHeaders;
828   PRELOCATION_DIRECTORY RelocDir;
829   PRELOCATION_ENTRY RelocEntry;
830   PMODULE_OBJECT  LibraryModuleObject;
831   PMODULE_OBJECT CreatedModuleObject;
832   PVOID *ImportAddressList;
833   PULONG FunctionNameList;
834   PCHAR pName;
835   WORD Hint;
836   UNICODE_STRING ModuleName;
837   UNICODE_STRING NameString;
838   WCHAR  NameBuffer[60];
839   MODULE_TEXT_SECTION* ModuleTextSection;
840   NTSTATUS Status;
841   KIRQL Irql;
842
843   DPRINT("Processing PE Module at module base:%08lx\n", ModuleLoadBase);
844
845   /*  Get header pointers  */
846   PEDosHeader = (PIMAGE_DOS_HEADER) ModuleLoadBase;
847   PEMagic = (PULONG) ((unsigned int) ModuleLoadBase + 
848     PEDosHeader->e_lfanew);
849   PEFileHeader = (PIMAGE_FILE_HEADER) ((unsigned int) ModuleLoadBase + 
850     PEDosHeader->e_lfanew + sizeof(ULONG));
851   PEOptionalHeader = (PIMAGE_OPTIONAL_HEADER) ((unsigned int) ModuleLoadBase + 
852     PEDosHeader->e_lfanew + sizeof(ULONG) + sizeof(IMAGE_FILE_HEADER));
853   PESectionHeaders = (PIMAGE_SECTION_HEADER) ((unsigned int) ModuleLoadBase + 
854     PEDosHeader->e_lfanew + sizeof(ULONG) + sizeof(IMAGE_FILE_HEADER) +
855     sizeof(IMAGE_OPTIONAL_HEADER));
856   CHECKPOINT;
857
858   /*  Check file magic numbers  */
859   if (PEDosHeader->e_magic != IMAGE_DOS_MAGIC)
860     {
861       CPRINT("Incorrect MZ magic: %04x\n", PEDosHeader->e_magic);
862       return STATUS_UNSUCCESSFUL;
863     }
864   if (PEDosHeader->e_lfanew == 0)
865     {
866       CPRINT("Invalid lfanew offset: %08x\n", PEDosHeader->e_lfanew);
867       return STATUS_UNSUCCESSFUL;
868     }
869   if (*PEMagic != IMAGE_PE_MAGIC)
870     {
871       CPRINT("Incorrect PE magic: %08x\n", *PEMagic);
872       return STATUS_UNSUCCESSFUL;
873     }
874   if (PEFileHeader->Machine != IMAGE_FILE_MACHINE_I386)
875     {
876       CPRINT("Incorrect Architechture: %04x\n", PEFileHeader->Machine);
877       return STATUS_UNSUCCESSFUL;
878     }
879   CHECKPOINT;
880
881   /* FIXME: if image is fixed-address load, then fail  */
882
883   /* FIXME: check/verify OS version number  */
884
885   DPRINT("OptionalHdrMagic:%04x LinkVersion:%d.%d\n", 
886          PEOptionalHeader->Magic,
887          PEOptionalHeader->MajorLinkerVersion,
888          PEOptionalHeader->MinorLinkerVersion);
889   DPRINT("Entry Point:%08lx\n", PEOptionalHeader->AddressOfEntryPoint);
890   CHECKPOINT;
891
892   /*  Determine the size of the module  */
893   DriverSize = PEOptionalHeader->SizeOfImage;
894   DPRINT("DriverSize %x\n",DriverSize);
895
896   /*  Allocate a virtual section for the module  */
897   DriverBase = MmAllocateSection(DriverSize);
898   if (DriverBase == 0)
899     {
900       CPRINT("Failed to allocate a virtual section for driver\n");
901       return STATUS_UNSUCCESSFUL;
902     }
903   DbgPrint("DriverBase for %wZ: %x\n", FileName, DriverBase);
904   CHECKPOINT;
905   /*  Copy headers over */
906   memcpy(DriverBase, ModuleLoadBase, PEOptionalHeader->SizeOfHeaders);
907    CurrentSize = 0;
908   /*  Copy image sections into virtual section  */
909   for (Idx = 0; Idx < PEFileHeader->NumberOfSections; Idx++)
910     {
911       //  Copy current section into current offset of virtual section
912       if (PESectionHeaders[Idx].Characteristics & 
913           (IMAGE_SECTION_CHAR_CODE | IMAGE_SECTION_CHAR_DATA))
914         {
915            DPRINT("PESectionHeaders[Idx].VirtualAddress + DriverBase %x\n",
916                   PESectionHeaders[Idx].VirtualAddress + DriverBase);
917            memcpy(PESectionHeaders[Idx].VirtualAddress + DriverBase,
918                   (PVOID)(ModuleLoadBase + PESectionHeaders[Idx].PointerToRawData),
919                   PESectionHeaders[Idx].Misc.VirtualSize > PESectionHeaders[Idx].SizeOfRawData
920                   ? PESectionHeaders[Idx].SizeOfRawData : PESectionHeaders[Idx].Misc.VirtualSize );
921         }
922       else
923         {
924            DPRINT("PESectionHeaders[Idx].VirtualAddress + DriverBase %x\n",
925                   PESectionHeaders[Idx].VirtualAddress + DriverBase);
926            memset(PESectionHeaders[Idx].VirtualAddress + DriverBase, 
927                   '\0', PESectionHeaders[Idx].Misc.VirtualSize);
928
929         }
930       CurrentSize += ROUND_UP(PESectionHeaders[Idx].Misc.VirtualSize,
931                               PEOptionalHeader->SectionAlignment);
932
933
934 //      CurrentBase = (PVOID)((DWORD)CurrentBase + 
935   //      ROUND_UP(PESectionHeaders[Idx].SizeOfRawData.Misc.VirtualSize,
936     //             PEOptionalHeader->SectionAlignment));
937     }
938
939   /*  Perform relocation fixups  */
940   RelocDelta = (DWORD) DriverBase - PEOptionalHeader->ImageBase;
941   RelocDir = (PRELOCATION_DIRECTORY)(PEOptionalHeader->DataDirectory[
942     IMAGE_DIRECTORY_ENTRY_BASERELOC].VirtualAddress);
943   DPRINT("DrvrBase:%08lx ImgBase:%08lx RelocDelta:%08lx\n", 
944          DriverBase,
945          PEOptionalHeader->ImageBase,
946          RelocDelta);   
947   DPRINT("RelocDir %x\n",RelocDir);
948 #if 1
949   for (Idx = 0; Idx < PEFileHeader->NumberOfSections; Idx++)
950     {
951        if (PESectionHeaders[Idx].VirtualAddress == (DWORD)RelocDir)
952          {
953             DPRINT("Name %.8s PESectionHeader[Idx].PointerToRawData %x\n",
954                    PESectionHeaders[Idx].Name,
955                    PESectionHeaders[Idx].PointerToRawData);
956             RelocDir = PESectionHeaders[Idx].PointerToRawData +
957               ModuleLoadBase;
958             CurrentSize = PESectionHeaders[Idx].Misc.VirtualSize;
959             break;
960          }
961     }
962 #else
963    RelocDir = RelocDir + (ULONG)DriverBase;
964    CurrentSize = PEOptionalHeader->DataDirectory
965                   [IMAGE_DIRECTORY_ENTRY_BASERELOC].Size;
966 #endif
967   DPRINT("RelocDir %08lx CurrentSize %08lx\n", RelocDir, CurrentSize);
968   TotalRelocs = 0;
969   while (TotalRelocs < CurrentSize && RelocDir->SizeOfBlock != 0)
970     {
971       NumRelocs = (RelocDir->SizeOfBlock - sizeof(RELOCATION_DIRECTORY)) / 
972         sizeof(WORD);
973 /*      DPRINT("RelocDir at %08lx for VA %08lx with %08lx relocs\n",
974              RelocDir, 
975              RelocDir->VirtualAddress,
976              NumRelocs);*/
977       RelocEntry = (PRELOCATION_ENTRY) ((DWORD)RelocDir + 
978         sizeof(RELOCATION_DIRECTORY));
979       for (Idx = 0; Idx < NumRelocs; Idx++)
980         {
981            ULONG Offset;
982            ULONG Type;
983            PDWORD RelocItem;
984            
985            Offset = RelocEntry[Idx].TypeOffset & 0xfff;
986            Type = (RelocEntry[Idx].TypeOffset >> 12) & 0xf;
987            RelocItem = (PDWORD)(DriverBase + RelocDir->VirtualAddress + 
988                                 Offset);
989 /*         DPRINT("  reloc at %08lx %x %s old:%08lx new:%08lx\n", 
990                   RelocItem,
991                   Type,
992                   Type ? "HIGHLOW" : "ABS",
993                   *RelocItem,
994                   (*RelocItem) + RelocDelta); */
995           if (Type == 3)
996             {
997               (*RelocItem) += RelocDelta;
998             }
999           else if (Type != 0)
1000             {
1001               CPRINT("Unknown relocation type %x at %x\n",Type, &Type);
1002               return STATUS_UNSUCCESSFUL;
1003             }
1004         }
1005       TotalRelocs += RelocDir->SizeOfBlock;
1006       RelocDir = (PRELOCATION_DIRECTORY)((DWORD)RelocDir + 
1007         RelocDir->SizeOfBlock);
1008 //      DPRINT("TotalRelocs: %08lx  CurrentSize: %08lx\n", TotalRelocs, CurrentSize);
1009     }
1010    
1011   DPRINT("PEOptionalHeader->DataDirectory[IMAGE_DIRECTORY_ENTRY_IMPORT] %x\n",
1012          PEOptionalHeader->DataDirectory[IMAGE_DIRECTORY_ENTRY_IMPORT]
1013          .VirtualAddress);
1014   /*  Perform import fixups  */
1015   if (PEOptionalHeader->DataDirectory[IMAGE_DIRECTORY_ENTRY_IMPORT].VirtualAddress)
1016     {
1017       PIMAGE_IMPORT_MODULE_DIRECTORY ImportModuleDirectory;
1018
1019       /*  Process each import module  */
1020       ImportModuleDirectory = (PIMAGE_IMPORT_MODULE_DIRECTORY)
1021         ((DWORD)DriverBase + PEOptionalHeader->
1022           DataDirectory[IMAGE_DIRECTORY_ENTRY_IMPORT].VirtualAddress);
1023       DPRINT("Processeing import directory at %p\n", ImportModuleDirectory);
1024       while (ImportModuleDirectory->dwRVAModuleName)
1025         {
1026           /*  Check to make sure that import lib is kernel  */
1027           pName = (PCHAR) DriverBase + 
1028             ImportModuleDirectory->dwRVAModuleName;
1029
1030           RtlCreateUnicodeStringFromAsciiz(&ModuleName, pName);
1031           DPRINT("Import module: %wZ\n", &ModuleName);
1032
1033           LibraryModuleObject = LdrGetModuleObject(&ModuleName);
1034           if (LibraryModuleObject == NULL)
1035             {
1036               CPRINT("Module '%wZ' not loaded yet\n", &ModuleName);
1037               wcscpy(NameBuffer, L"\\SystemRoot\\system32\\drivers\\");
1038               wcscat(NameBuffer, ModuleName.Buffer);
1039               RtlInitUnicodeString(&NameString, NameBuffer);
1040               Status = LdrLoadModule(&NameString, &LibraryModuleObject);
1041               if (!NT_SUCCESS(Status))
1042                 {
1043                   CPRINT("Unknown import module: %wZ (Status %lx)\n", &ModuleName, Status);
1044                   return(Status);
1045                 }
1046             }
1047           /*  Get the import address list  */
1048           ImportAddressList = (PVOID *) ((DWORD)DriverBase + 
1049             ImportModuleDirectory->dwRVAFunctionAddressList);
1050
1051           /*  Get the list of functions to import  */
1052           if (ImportModuleDirectory->dwRVAFunctionNameList != 0)
1053             {
1054               FunctionNameList = (PULONG) ((DWORD)DriverBase + 
1055                 ImportModuleDirectory->dwRVAFunctionNameList);
1056             }
1057           else
1058             {
1059               FunctionNameList = (PULONG) ((DWORD)DriverBase + 
1060                 ImportModuleDirectory->dwRVAFunctionAddressList);
1061             }
1062           /*  Walk through function list and fixup addresses  */
1063           while (*FunctionNameList != 0L)
1064             {
1065               if ((*FunctionNameList) & 0x80000000) // hint
1066                 {
1067                   pName = NULL;
1068
1069
1070                   Hint = (*FunctionNameList) & 0xffff;
1071                 }
1072               else // hint-name
1073                 {
1074                   pName = (PCHAR)((DWORD)DriverBase + 
1075                                   *FunctionNameList + 2);
1076                   Hint = *(PWORD)((DWORD)DriverBase + *FunctionNameList);
1077                 }
1078               DPRINT("  Hint:%04x  Name:%s\n", Hint, pName);
1079
1080               /*  Fixup the current import symbol  */
1081               if (LibraryModuleObject != NULL)
1082                 {
1083                   *ImportAddressList = LdrGetExportAddress(LibraryModuleObject, 
1084                                                            pName, 
1085                                                            Hint);
1086                 }
1087               else
1088                 {
1089                   CPRINT("Unresolved kernel symbol: %s\n", pName);
1090                   return STATUS_UNSUCCESSFUL;
1091                 }
1092               ImportAddressList++;
1093               FunctionNameList++;
1094             }
1095
1096           RtlFreeUnicodeString(&ModuleName);
1097
1098           ImportModuleDirectory++;
1099         }
1100     }
1101
1102   /* Set the protections for the various parts of the driver */
1103   for (Idx = 0; Idx < PEFileHeader->NumberOfSections; Idx++)
1104     {
1105       ULONG Characteristics = PESectionHeaders[Idx].Characteristics;
1106       ULONG Length;
1107       PVOID BaseAddress;
1108       ULONG i;
1109       Length = 
1110         max(PESectionHeaders[Idx].Misc.VirtualSize,
1111             PESectionHeaders[Idx].SizeOfRawData);
1112       BaseAddress = PESectionHeaders[Idx].VirtualAddress + DriverBase;
1113       if (Characteristics & IMAGE_SECTION_CHAR_CODE &&
1114           !(Characteristics & IMAGE_SECTION_CHAR_WRITABLE ||
1115             Characteristics & IMAGE_SECTION_CHAR_DATA ||
1116             Characteristics & IMAGE_SECTION_CHAR_BSS))
1117         {
1118           for (i = 0; i < PAGE_ROUND_DOWN(Length) / PAGE_SIZE; i++)
1119             {
1120               MmSetPageProtect(NULL, BaseAddress + (i * PAGE_SIZE), 
1121                                PAGE_READONLY);
1122             }
1123         }
1124     }
1125
1126   /* Create the module */
1127   CreatedModuleObject = ExAllocatePool(NonPagedPool, sizeof(MODULE_OBJECT));
1128   if (CreatedModuleObject == NULL)
1129     {
1130       return(STATUS_INSUFFICIENT_RESOURCES);
1131     }
1132
1133   RtlZeroMemory(CreatedModuleObject, sizeof(MODULE_OBJECT));
1134
1135    /*  Initialize ModuleObject data  */
1136   CreatedModuleObject->Base = DriverBase;
1137   CreatedModuleObject->Flags = MODULE_FLAG_PE;
1138   
1139   RtlCreateUnicodeString(&CreatedModuleObject->FullName,
1140                          FileName->Buffer);
1141   LdrpBuildModuleBaseName(&CreatedModuleObject->BaseName,
1142                           &CreatedModuleObject->FullName);
1143   
1144   CreatedModuleObject->EntryPoint = 
1145     (PVOID)((DWORD)DriverBase + 
1146             PEOptionalHeader->AddressOfEntryPoint);
1147   CreatedModuleObject->Length = DriverSize;
1148   DPRINT("EntryPoint at %x\n", CreatedModuleObject->EntryPoint);
1149   
1150   CreatedModuleObject->Image.PE.FileHeader =
1151     (PIMAGE_FILE_HEADER) ((unsigned int) DriverBase + PEDosHeader->e_lfanew + sizeof(ULONG));
1152
1153   DPRINT("FileHeader at %x\n", CreatedModuleObject->Image.PE.FileHeader);
1154   CreatedModuleObject->Image.PE.OptionalHeader = 
1155     (PIMAGE_OPTIONAL_HEADER) ((unsigned int) DriverBase + PEDosHeader->e_lfanew + sizeof(ULONG) +
1156     sizeof(IMAGE_FILE_HEADER));
1157   DPRINT("OptionalHeader at %x\n", CreatedModuleObject->Image.PE.OptionalHeader);
1158   CreatedModuleObject->Image.PE.SectionList = 
1159     (PIMAGE_SECTION_HEADER) ((unsigned int) DriverBase + PEDosHeader->e_lfanew + sizeof(ULONG) +
1160     sizeof(IMAGE_FILE_HEADER) + sizeof(IMAGE_OPTIONAL_HEADER));
1161   DPRINT("SectionList at %x\n", CreatedModuleObject->Image.PE.SectionList);
1162
1163   /* Insert module */
1164   KeAcquireSpinLock(&ModuleListLock, &Irql);
1165   InsertTailList(&ModuleListHead,
1166                  &CreatedModuleObject->ListEntry);
1167   KeReleaseSpinLock(&ModuleListLock, Irql);
1168
1169
1170   ModuleTextSection = ExAllocatePool(NonPagedPool, 
1171                                      sizeof(MODULE_TEXT_SECTION));
1172   assert(ModuleTextSection);
1173   RtlZeroMemory(ModuleTextSection, sizeof(MODULE_TEXT_SECTION));
1174   ModuleTextSection->Base = (ULONG)DriverBase;
1175   ModuleTextSection->Length = DriverSize;
1176   ModuleTextSection->Name = ExAllocatePool(NonPagedPool, 
1177         (wcslen(CreatedModuleObject->BaseName.Buffer) + 1) * sizeof(WCHAR));
1178   wcscpy(ModuleTextSection->Name, CreatedModuleObject->BaseName.Buffer);
1179   ModuleTextSection->OptionalHeader = 
1180     CreatedModuleObject->Image.PE.OptionalHeader;
1181   InsertTailList(&ModuleTextListHead, &ModuleTextSection->ListEntry);
1182
1183   CreatedModuleObject->TextSection = ModuleTextSection;
1184
1185   *ModuleObject = CreatedModuleObject;
1186
1187   DPRINT("Loading Module %wZ...\n", FileName);
1188
1189   if ((KdDebuggerEnabled == TRUE) && (KdDebugState & KD_DEBUG_GDB))
1190     {
1191       DPRINT("Module %wZ loaded at 0x%.08x.\n",
1192               FileName, CreatedModuleObject->Base);
1193     }
1194
1195   return STATUS_SUCCESS;
1196 }
1197
1198
1199 PVOID
1200 LdrSafePEProcessModule(PVOID ModuleLoadBase,
1201                        PVOID DriverBase,
1202                        PVOID ImportModuleBase,
1203                        PULONG DriverSize)
1204 {
1205   unsigned int Idx;
1206   ULONG RelocDelta, NumRelocs;
1207   ULONG CurrentSize, TotalRelocs;
1208   PULONG PEMagic;
1209   PIMAGE_DOS_HEADER PEDosHeader;
1210   PIMAGE_FILE_HEADER PEFileHeader;
1211   PIMAGE_OPTIONAL_HEADER PEOptionalHeader;
1212   PIMAGE_SECTION_HEADER PESectionHeaders;
1213   PRELOCATION_DIRECTORY RelocDir;
1214   PRELOCATION_ENTRY RelocEntry;
1215   PVOID *ImportAddressList;
1216   PULONG FunctionNameList;
1217   PCHAR pName;
1218   USHORT Hint;
1219
1220   ps("Processing PE Module at module base:%08lx\n", ModuleLoadBase);
1221
1222   /*  Get header pointers  */
1223   PEDosHeader = (PIMAGE_DOS_HEADER) ModuleLoadBase;
1224   PEMagic = (PULONG) ((unsigned int) ModuleLoadBase + 
1225     PEDosHeader->e_lfanew);
1226   PEFileHeader = (PIMAGE_FILE_HEADER) ((unsigned int) ModuleLoadBase + 
1227     PEDosHeader->e_lfanew + sizeof(ULONG));
1228   PEOptionalHeader = (PIMAGE_OPTIONAL_HEADER) ((unsigned int) ModuleLoadBase + 
1229     PEDosHeader->e_lfanew + sizeof(ULONG) + sizeof(IMAGE_FILE_HEADER));
1230   PESectionHeaders = (PIMAGE_SECTION_HEADER) ((unsigned int) ModuleLoadBase + 
1231     PEDosHeader->e_lfanew + sizeof(ULONG) + sizeof(IMAGE_FILE_HEADER) +
1232     sizeof(IMAGE_OPTIONAL_HEADER));
1233   CHECKPOINT;
1234
1235   /*  Check file magic numbers  */
1236   if (PEDosHeader->e_magic != IMAGE_DOS_MAGIC)
1237     {
1238       return 0;
1239     }
1240   if (PEDosHeader->e_lfanew == 0)
1241     {
1242       return 0;
1243     }
1244   if (*PEMagic != IMAGE_PE_MAGIC)
1245     {
1246       return 0;
1247     }
1248   if (PEFileHeader->Machine != IMAGE_FILE_MACHINE_I386)
1249     {
1250       return 0;
1251     }
1252
1253   ps("OptionalHdrMagic:%04x LinkVersion:%d.%d\n", 
1254          PEOptionalHeader->Magic,
1255          PEOptionalHeader->MajorLinkerVersion,
1256          PEOptionalHeader->MinorLinkerVersion);
1257   ps("Entry Point:%08lx\n", PEOptionalHeader->AddressOfEntryPoint);
1258
1259   /*  Determine the size of the module  */
1260   *DriverSize = PEOptionalHeader->SizeOfImage;
1261   ps("DriverSize %x\n",*DriverSize);
1262
1263   /*  Copy headers over */
1264   if (DriverBase != ModuleLoadBase)
1265     {
1266       memcpy(DriverBase, ModuleLoadBase, PEOptionalHeader->SizeOfHeaders);
1267     }
1268
1269   ps("Hdr: 0x%X\n", (ULONG)PEOptionalHeader);
1270   ps("Hdr->SizeOfHeaders: 0x%X\n", (ULONG)PEOptionalHeader->SizeOfHeaders);
1271   ps("FileHdr->NumberOfSections: 0x%X\n", (ULONG)PEFileHeader->NumberOfSections);
1272
1273   /* Ntoskrnl.exe need no relocation fixups since it is linked to run at the same
1274      address as it is mapped */
1275   if (DriverBase != ModuleLoadBase)
1276     {
1277       CurrentSize = 0;
1278
1279   /*  Copy image sections into virtual section  */
1280   for (Idx = 0; Idx < PEFileHeader->NumberOfSections; Idx++)
1281     {
1282       //  Copy current section into current offset of virtual section
1283       if (PESectionHeaders[Idx].Characteristics & 
1284           (IMAGE_SECTION_CHAR_CODE | IMAGE_SECTION_CHAR_DATA))
1285         {
1286           //ps("PESectionHeaders[Idx].VirtualAddress (%X) + DriverBase %x\n",
1287           //PESectionHeaders[Idx].VirtualAddress, PESectionHeaders[Idx].VirtualAddress + DriverBase);
1288           memcpy(PESectionHeaders[Idx].VirtualAddress + DriverBase,
1289                  (PVOID)(ModuleLoadBase + PESectionHeaders[Idx].PointerToRawData),
1290                  PESectionHeaders[Idx].Misc.VirtualSize > PESectionHeaders[Idx].SizeOfRawData ?
1291                    PESectionHeaders[Idx].SizeOfRawData : PESectionHeaders[Idx].Misc.VirtualSize );
1292         }
1293       else
1294         {
1295           ps("PESectionHeaders[Idx].VirtualAddress (%X) + DriverBase %x\n",
1296              PESectionHeaders[Idx].VirtualAddress, PESectionHeaders[Idx].VirtualAddress + DriverBase);
1297           memset(PESectionHeaders[Idx].VirtualAddress + DriverBase, 
1298                  '\0',
1299                  PESectionHeaders[Idx].Misc.VirtualSize);
1300         }
1301       CurrentSize += ROUND_UP(PESectionHeaders[Idx].Misc.VirtualSize,
1302                               PEOptionalHeader->SectionAlignment);
1303     }
1304
1305   /*  Perform relocation fixups  */
1306   RelocDelta = (ULONG) DriverBase - PEOptionalHeader->ImageBase;
1307   RelocDir = (PRELOCATION_DIRECTORY)(PEOptionalHeader->DataDirectory[
1308     IMAGE_DIRECTORY_ENTRY_BASERELOC].VirtualAddress);
1309   ps("DrvrBase:%08lx ImgBase:%08lx RelocDelta:%08lx\n", 
1310          DriverBase,
1311          PEOptionalHeader->ImageBase,
1312          RelocDelta);   
1313   ps("RelocDir %x\n",RelocDir);
1314
1315   for (Idx = 0; Idx < PEFileHeader->NumberOfSections; Idx++)
1316     {
1317       if (PESectionHeaders[Idx].VirtualAddress == (ULONG)RelocDir)
1318         {
1319           DPRINT("Name %.8s PESectionHeader[Idx].PointerToRawData %x\n",
1320                  PESectionHeaders[Idx].Name,
1321                  PESectionHeaders[Idx].PointerToRawData);
1322           RelocDir = PESectionHeaders[Idx].PointerToRawData + ModuleLoadBase;
1323           CurrentSize = PESectionHeaders[Idx].Misc.VirtualSize;
1324           break;
1325         }
1326     }
1327
1328   ps("RelocDir %08lx CurrentSize %08lx\n", RelocDir, CurrentSize);
1329
1330   TotalRelocs = 0;
1331   while (TotalRelocs < CurrentSize && RelocDir->SizeOfBlock != 0)
1332     {
1333       NumRelocs = (RelocDir->SizeOfBlock - sizeof(RELOCATION_DIRECTORY)) / 
1334         sizeof(USHORT);
1335       RelocEntry = (PRELOCATION_ENTRY)((ULONG)RelocDir + 
1336         sizeof(RELOCATION_DIRECTORY));
1337       for (Idx = 0; Idx < NumRelocs; Idx++)
1338         {
1339           ULONG Offset;
1340           ULONG Type;
1341           PDWORD RelocItem;
1342
1343           Offset = RelocEntry[Idx].TypeOffset & 0xfff;
1344           Type = (RelocEntry[Idx].TypeOffset >> 12) & 0xf;
1345           RelocItem = (PULONG)(DriverBase + RelocDir->VirtualAddress + Offset);
1346           if (Type == 3)
1347             {
1348               (*RelocItem) += RelocDelta;
1349             }
1350           else if (Type != 0)
1351             {
1352               CPRINT("Unknown relocation type %x at %x\n",Type, &Type);
1353               return(0);
1354             }
1355         }
1356       TotalRelocs += RelocDir->SizeOfBlock;
1357       RelocDir = (PRELOCATION_DIRECTORY)((ULONG)RelocDir + 
1358         RelocDir->SizeOfBlock);
1359     }
1360
1361     ps("PEOptionalHeader->DataDirectory[IMAGE_DIRECTORY_ENTRY_IMPORT] %x\n",
1362          PEOptionalHeader->DataDirectory[IMAGE_DIRECTORY_ENTRY_IMPORT]
1363          .VirtualAddress);
1364   }
1365
1366   /*  Perform import fixups  */
1367   if (PEOptionalHeader->DataDirectory[IMAGE_DIRECTORY_ENTRY_IMPORT].VirtualAddress)
1368     {
1369       PIMAGE_IMPORT_MODULE_DIRECTORY ImportModuleDirectory;
1370
1371       /*  Process each import module  */
1372       ImportModuleDirectory = (PIMAGE_IMPORT_MODULE_DIRECTORY)
1373         ((ULONG)DriverBase + PEOptionalHeader->
1374           DataDirectory[IMAGE_DIRECTORY_ENTRY_IMPORT].VirtualAddress);
1375
1376       ps("Processeing import directory at %p\n", ImportModuleDirectory);
1377
1378       /*  Check to make sure that import lib is kernel  */
1379       pName = (PCHAR)DriverBase + ImportModuleDirectory->dwRVAModuleName;
1380
1381       ps("Import module: %s\n", pName);
1382
1383       /*  Get the import address list  */
1384       ImportAddressList = (PVOID *)((ULONG)DriverBase + 
1385         ImportModuleDirectory->dwRVAFunctionAddressList);
1386
1387       ps("  ImportModuleDirectory->dwRVAFunctionAddressList: 0x%X\n",
1388          ImportModuleDirectory->dwRVAFunctionAddressList);
1389       ps("  ImportAddressList: 0x%X\n", ImportAddressList);
1390
1391       /*  Get the list of functions to import  */
1392       if (ImportModuleDirectory->dwRVAFunctionNameList != 0)
1393         {
1394           ps("Using function name list.\n");
1395
1396           FunctionNameList = (PULONG)((ULONG)DriverBase + 
1397             ImportModuleDirectory->dwRVAFunctionNameList);
1398         }
1399       else
1400         {
1401           ps("Using function address list.\n");
1402
1403           FunctionNameList = (PULONG)((ULONG)DriverBase + 
1404             ImportModuleDirectory->dwRVAFunctionAddressList);
1405         }
1406
1407       /* Walk through function list and fixup addresses */
1408       while (*FunctionNameList != 0L)
1409         {
1410           if ((*FunctionNameList) & 0x80000000)
1411             {
1412                /* Hint */
1413               pName = NULL;
1414               Hint = (*FunctionNameList) & 0xffff;
1415             }
1416           else
1417             {
1418               /* Hint name */
1419               pName = (PCHAR)((ULONG)DriverBase + *FunctionNameList + 2);
1420               Hint = *(PWORD)((ULONG)DriverBase + *FunctionNameList);
1421             }
1422           //ps("  Hint:%04x  Name:%s(0x%X)(%x)\n", Hint, pName, pName, ImportAddressList);
1423
1424           *ImportAddressList = LdrSafePEGetExportAddress(ImportModuleBase,
1425                                                          pName,
1426                                                          Hint);
1427
1428           ImportAddressList++;
1429           FunctionNameList++;
1430         }
1431     }
1432
1433   ps("Finished importing.\n");
1434
1435   return(0);
1436 }
1437
1438
1439 static PVOID
1440 LdrPEGetExportAddress(PMODULE_OBJECT ModuleObject,
1441                       PCHAR Name,
1442                       USHORT Hint)
1443 {
1444   PIMAGE_EXPORT_DIRECTORY ExportDir;
1445   ULONG ExportDirSize;
1446   USHORT Idx;
1447   PVOID  ExportAddress;
1448   PWORD  OrdinalList;
1449   PDWORD FunctionList, NameList;
1450
1451    ExportDir = (PIMAGE_EXPORT_DIRECTORY)
1452      RtlImageDirectoryEntryToData(ModuleObject->Base,
1453                                   TRUE,
1454                                   IMAGE_DIRECTORY_ENTRY_EXPORT,
1455                                   &ExportDirSize);
1456    DPRINT("ExportDir %p ExportDirSize %lx\n", ExportDir, ExportDirSize);
1457    if (ExportDir == NULL)
1458      {
1459         return NULL;
1460      }
1461
1462    FunctionList = (PDWORD)((DWORD)ExportDir->AddressOfFunctions + ModuleObject->Base);
1463    NameList = (PDWORD)((DWORD)ExportDir->AddressOfNames + ModuleObject->Base);
1464    OrdinalList = (PWORD)((DWORD)ExportDir->AddressOfNameOrdinals + ModuleObject->Base);
1465
1466   ExportAddress = 0;
1467
1468   if (Name != NULL)
1469     {
1470       for (Idx = 0; Idx < ExportDir->NumberOfNames; Idx++)
1471         {
1472 #if 0
1473           DPRINT("  Name:%s  NameList[%d]:%s\n", 
1474                  Name, 
1475                  Idx, 
1476                  (DWORD) ModuleObject->Base + NameList[Idx]);
1477
1478 #endif
1479           if (!strcmp(Name, (PCHAR) ((DWORD)ModuleObject->Base + NameList[Idx])))
1480             {
1481               ExportAddress = (PVOID) ((DWORD)ModuleObject->Base +
1482                 FunctionList[OrdinalList[Idx]]);
1483                   if (((ULONG)ExportAddress >= (ULONG)ExportDir) &&
1484                       ((ULONG)ExportAddress < (ULONG)ExportDir + ExportDirSize))
1485                     {
1486                        DPRINT("Forward: %s\n", (PCHAR)ExportAddress);
1487                        ExportAddress = LdrPEFixupForward((PCHAR)ExportAddress);
1488                        DPRINT("ExportAddress: %p\n", ExportAddress);
1489                     }
1490
1491               break;
1492             }
1493         }
1494     }
1495   else  /*  use hint  */
1496     {
1497       ExportAddress = (PVOID) ((DWORD)ModuleObject->Base +
1498         FunctionList[Hint - ExportDir->Base]);
1499     }
1500
1501   if (ExportAddress == NULL)
1502     {
1503       CPRINT("Export not found for %d:%s\n",
1504              Hint,
1505              Name != NULL ? Name : "(Ordinal)");
1506       KeBugCheck(0);
1507     }
1508
1509   return(ExportAddress);
1510 }
1511
1512
1513 static PVOID
1514 LdrSafePEGetExportAddress(PVOID ImportModuleBase,
1515                           PCHAR Name,
1516                           USHORT Hint)
1517 {
1518   USHORT Idx;
1519   PVOID  ExportAddress;
1520   PWORD  OrdinalList;
1521   PDWORD FunctionList, NameList;
1522   PIMAGE_EXPORT_DIRECTORY  ExportDir;
1523   ULONG ExportDirSize;
1524
1525   static BOOLEAN EP = FALSE;
1526
1527   ExportDir = (PIMAGE_EXPORT_DIRECTORY)
1528     RtlImageDirectoryEntryToData(ImportModuleBase,
1529           TRUE,
1530                 IMAGE_DIRECTORY_ENTRY_EXPORT,
1531                 &ExportDirSize);
1532
1533   if (!EP) {
1534     EP = TRUE;
1535     ps("ExportDir %x\n", ExportDir);
1536   }
1537
1538   FunctionList = (PDWORD)((DWORD)ExportDir->AddressOfFunctions + ImportModuleBase);
1539   NameList = (PDWORD)((DWORD)ExportDir->AddressOfNames + ImportModuleBase);
1540   OrdinalList = (PWORD)((DWORD)ExportDir->AddressOfNameOrdinals + ImportModuleBase);
1541
1542   ExportAddress = 0;
1543
1544   if (Name != NULL)
1545     {
1546       for (Idx = 0; Idx < ExportDir->NumberOfNames; Idx++)
1547         {
1548           if (!strcmp(Name, (PCHAR) ((DWORD)ImportModuleBase + NameList[Idx])))
1549                         {
1550               ExportAddress = (PVOID) ((DWORD)ImportModuleBase +
1551                 FunctionList[OrdinalList[Idx]]);
1552               break;
1553             }
1554         }
1555     }
1556   else  /*  use hint  */
1557     {
1558       ExportAddress = (PVOID) ((DWORD)ImportModuleBase +
1559
1560         FunctionList[Hint - ExportDir->Base]);
1561     }
1562
1563   if (ExportAddress == 0)
1564     {
1565       ps("Export not found for %d:%s\n",
1566          Hint,
1567          Name != NULL ? Name : "(Ordinal)");
1568       KeBugCheck(0);
1569     }
1570   return ExportAddress;
1571 }
1572
1573
1574 static PVOID
1575 LdrPEFixupForward(PCHAR ForwardName)
1576 {
1577    CHAR NameBuffer[128];
1578    UNICODE_STRING ModuleName;
1579    PCHAR p;
1580    PMODULE_OBJECT ModuleObject;
1581
1582    DPRINT("LdrPEFixupForward (%s)\n", ForwardName);
1583
1584    strcpy(NameBuffer, ForwardName);
1585    p = strchr(NameBuffer, '.');
1586    if (p == NULL)
1587      {
1588         return NULL;
1589      }
1590
1591    *p = 0;
1592
1593    DPRINT("Driver: %s  Function: %s\n", NameBuffer, p+1);
1594
1595    RtlCreateUnicodeStringFromAsciiz(&ModuleName,
1596                                     NameBuffer);
1597    ModuleObject = LdrGetModuleObject(&ModuleName);
1598    RtlFreeUnicodeString(&ModuleName);
1599
1600    DPRINT("ModuleObject: %p\n", ModuleObject);
1601
1602    if (ModuleObject == NULL)
1603      {
1604         CPRINT("LdrPEFixupForward: failed to find module %s\n", NameBuffer);
1605         return NULL;
1606      }
1607
1608   return(LdrPEGetExportAddress(ModuleObject, p+1, 0));
1609 }
1610
1611 /* EOF */