1 /* $Id: utils.c,v 1.69 2003/07/27 11:39:18 ekohl Exp $
3 * COPYRIGHT: See COPYING in the top level directory
4 * PROJECT: ReactOS kernel
5 * FILE: lib/ntdll/ldr/utils.c
6 * PURPOSE: Process startup for PE executables
7 * PROGRAMMERS: Jean Michault
8 * Rex Jolliff (rex@lvcablemodem.com)
13 * - Fix calling of entry points
14 * - Handle loading flags correctly
18 /* INCLUDES *****************************************************************/
20 #include <reactos/config.h>
21 #include <ddk/ntddk.h>
25 #include <ntdll/ldr.h>
26 #include <ntos/minmax.h>
29 #ifdef DBG_NTDLL_LDR_UTILS
32 #include <ntdll/ntdll.h>
34 /* GLOBALS *******************************************************************/
36 static HANDLE LdrpKnownDllsDirHandle
= NULL
;
37 static UNICODE_STRING LdrpKnownDllPath
= {0, 0, NULL
};
40 /* PROTOTYPES ****************************************************************/
42 static NTSTATUS
LdrFindEntryForName(PUNICODE_STRING Name
, PLDR_MODULE
*Module
);
43 static PVOID
LdrFixupForward(PCHAR ForwardName
);
44 static PVOID
LdrGetExportByName(PVOID BaseAddress
, PUCHAR SymbolName
, USHORT Hint
);
47 /* FUNCTIONS *****************************************************************/
53 LdrpLoadUserModuleSymbols(PLDR_MODULE LdrModule
)
70 OBJECT_ATTRIBUTES ObjectAttributes
;
71 UNICODE_STRING LinkTarget
;
77 DPRINT("LdrpInitLoader() called\n");
79 /* Get handle to the 'KnownDlls' directory */
80 RtlInitUnicodeString(&Name
,
82 InitializeObjectAttributes(&ObjectAttributes
,
87 Status
= NtOpenDirectoryObject(&LdrpKnownDllsDirHandle
,
88 DIRECTORY_QUERY
| DIRECTORY_TRAVERSE
,
90 if (!NT_SUCCESS(Status
))
92 DPRINT("NtOpenDirectoryObject() failed (Status %lx)\n", Status
);
93 LdrpKnownDllsDirHandle
= NULL
;
97 /* Allocate target name string */
98 LinkTarget
.Length
= 0;
99 LinkTarget
.MaximumLength
= MAX_PATH
* sizeof(WCHAR
);
100 LinkTarget
.Buffer
= RtlAllocateHeap(RtlGetProcessHeap(),
102 MAX_PATH
* sizeof(WCHAR
));
103 if (LinkTarget
.Buffer
== NULL
)
105 NtClose(LdrpKnownDllsDirHandle
);
106 LdrpKnownDllsDirHandle
= NULL
;
110 RtlInitUnicodeString(&Name
,
112 InitializeObjectAttributes(&ObjectAttributes
,
114 OBJ_CASE_INSENSITIVE
| OBJ_OPENLINK
,
115 LdrpKnownDllsDirHandle
,
117 Status
= NtOpenSymbolicLinkObject(&LinkHandle
,
118 SYMBOLIC_LINK_ALL_ACCESS
,
120 if (!NT_SUCCESS(Status
))
122 RtlFreeUnicodeString(&LinkTarget
);
123 NtClose(LdrpKnownDllsDirHandle
);
124 LdrpKnownDllsDirHandle
= NULL
;
128 Status
= NtQuerySymbolicLinkObject(LinkHandle
,
132 if (!NT_SUCCESS(Status
))
134 RtlFreeUnicodeString(&LinkTarget
);
135 NtClose(LdrpKnownDllsDirHandle
);
136 LdrpKnownDllsDirHandle
= NULL
;
139 RtlCreateUnicodeString(&LdrpKnownDllPath
,
142 RtlFreeUnicodeString(&LinkTarget
);
144 DPRINT("LdrpInitLoader() done\n");
148 /***************************************************************************
153 * Adjusts the name of a dll to a fully qualified name.
156 * FullDllName: Pointer to caller supplied storage for the fully
157 * qualified dll name.
158 * DllName: Pointer to the dll name.
159 * BaseName: TRUE: Only the file name is passed to FullDllName
160 * FALSE: The full path is preserved in FullDllName
168 * A given path is not affected by the adjustment, but the file
170 * ntdll --> ntdll.dll
172 * ntdll.xyz --> ntdll.xyz
176 LdrAdjustDllName (PUNICODE_STRING FullDllName
,
177 PUNICODE_STRING DllName
,
180 WCHAR Buffer
[MAX_PATH
];
185 Length
= DllName
->Length
/ sizeof(WCHAR
);
187 if (BaseName
== TRUE
)
189 /* get the base dll name */
190 Pointer
= DllName
->Buffer
+ Length
;
197 while (Pointer
>= DllName
->Buffer
&& *Pointer
!= L
'\\' && *Pointer
!= L
'/');
200 Length
= Extension
- Pointer
;
201 memmove (Buffer
, Pointer
, Length
* sizeof(WCHAR
));
202 Buffer
[Length
] = L
'\0';
206 /* get the full dll name */
207 memmove (Buffer
, DllName
->Buffer
, DllName
->Length
);
208 Buffer
[DllName
->Length
/ sizeof(WCHAR
)] = L
'\0';
211 /* Build the DLL's absolute name */
212 Extension
= wcsrchr (Buffer
, L
'.');
213 if ((Extension
!= NULL
) && (*Extension
== L
'.'))
215 /* with extension - remove dot if it's the last character */
216 if (Buffer
[Length
- 1] == L
'.')
222 /* name without extension - assume that it is .dll */
223 memmove (Buffer
+ Length
, L
".dll", 10);
226 RtlCreateUnicodeString(FullDllName
, Buffer
);
230 LdrAddModuleEntry(PVOID ImageBase
,
231 PIMAGE_NT_HEADERS NTHeaders
,
235 Module
= RtlAllocateHeap(RtlGetProcessHeap(), 0, sizeof (LDR_MODULE
));
237 Module
->BaseAddress
= (PVOID
)ImageBase
;
238 Module
->EntryPoint
= NTHeaders
->OptionalHeader
.AddressOfEntryPoint
;
239 if (Module
->EntryPoint
!= 0)
240 Module
->EntryPoint
+= (ULONG
)Module
->BaseAddress
;
241 Module
->SizeOfImage
= NTHeaders
->OptionalHeader
.SizeOfImage
;
242 if (NtCurrentPeb()->Ldr
->Initialized
== TRUE
)
244 /* loading while app is running */
245 Module
->LoadCount
= 1;
248 * loading while app is initializing
249 * dll must not be unloaded
251 Module
->LoadCount
= -1;
254 Module
->TlsIndex
= 0;
255 Module
->CheckSum
= NTHeaders
->OptionalHeader
.CheckSum
;
256 Module
->TimeDateStamp
= NTHeaders
->FileHeader
.TimeDateStamp
;
258 RtlCreateUnicodeString (&Module
->FullDllName
,
260 RtlCreateUnicodeString (&Module
->BaseDllName
,
261 wcsrchr(FullDosName
, L
'\\') + 1);
262 DPRINT ("BaseDllName %wZ\n", &Module
->BaseDllName
);
264 /* FIXME: aquire loader lock */
265 InsertTailList(&NtCurrentPeb()->Ldr
->InLoadOrderModuleList
,
266 &Module
->InLoadOrderModuleList
);
267 InsertTailList(&NtCurrentPeb()->Ldr
->InInitializationOrderModuleList
,
268 &Module
->InInitializationOrderModuleList
);
269 /* FIXME: release loader lock */
276 LdrpMapKnownDll(IN PUNICODE_STRING DllName
,
277 OUT PUNICODE_STRING FullDosName
,
278 OUT PHANDLE SectionHandle
)
280 OBJECT_ATTRIBUTES ObjectAttributes
;
281 UNICODE_STRING ObjectDirName
;
284 DPRINT("LdrpMapKnownDll() called\n");
286 if (LdrpKnownDllsDirHandle
== NULL
)
288 DPRINT("Invalid 'KnownDlls' directory\n");
289 return STATUS_UNSUCCESSFUL
;
292 DPRINT("LdrpKnownDllPath '%wZ'\n", &LdrpKnownDllPath
);
294 InitializeObjectAttributes(&ObjectAttributes
,
296 OBJ_CASE_INSENSITIVE
,
297 LdrpKnownDllsDirHandle
,
299 Status
= NtOpenSection(SectionHandle
,
300 SECTION_MAP_READ
| SECTION_MAP_WRITE
| SECTION_MAP_EXECUTE
,
302 if (!NT_SUCCESS(Status
))
304 DPRINT("NtOpenSection() failed for '%wZ' (Status %lx)\n", DllName
, Status
);
308 FullDosName
->Length
= LdrpKnownDllPath
.Length
+ DllName
->Length
+ sizeof(WCHAR
);
309 FullDosName
->MaximumLength
= FullDosName
->Length
+ sizeof(WCHAR
);
310 FullDosName
->Buffer
= RtlAllocateHeap(RtlGetProcessHeap(),
312 FullDosName
->MaximumLength
);
313 if (FullDosName
->Buffer
== NULL
)
315 FullDosName
->Length
= 0;
316 FullDosName
->MaximumLength
= 0;
317 return STATUS_SUCCESS
;
320 wcscpy(FullDosName
->Buffer
, LdrpKnownDllPath
.Buffer
);
321 wcscat(FullDosName
->Buffer
, L
"\\");
322 wcscat(FullDosName
->Buffer
, DllName
->Buffer
);
324 DPRINT("FullDosName '%wZ'\n", FullDosName
);
326 DPRINT("LdrpMapKnownDll() done\n");
328 return STATUS_SUCCESS
;
333 LdrpMapDllImageFile(IN PWSTR SearchPath OPTIONAL
,
334 IN PUNICODE_STRING DllName
,
335 OUT PUNICODE_STRING FullDosName
,
336 OUT PHANDLE SectionHandle
)
338 WCHAR SearchPathBuffer
[MAX_PATH
];
339 WCHAR DosName
[MAX_PATH
];
340 UNICODE_STRING FullNtFileName
;
341 OBJECT_ATTRIBUTES FileObjectAttributes
;
343 char BlockBuffer
[1024];
344 PIMAGE_DOS_HEADER DosHeader
;
345 PIMAGE_NT_HEADERS NTHeaders
;
350 DPRINT("LdrpMapDllImageFile() called\n");
352 if (SearchPath
== NULL
)
354 SearchPath
= SearchPathBuffer
;
355 wcscpy (SearchPathBuffer
, SharedUserData
->NtSystemRoot
);
356 wcscat (SearchPathBuffer
, L
"\\system32;");
357 wcscat (SearchPathBuffer
, SharedUserData
->NtSystemRoot
);
358 wcscat (SearchPathBuffer
, L
";.");
361 DPRINT("SearchPath %S\n", SearchPath
);
363 if (RtlDosSearchPath_U (SearchPath
,
369 return STATUS_DLL_NOT_FOUND
;
371 DPRINT("DosName %S\n", DosName
);
373 if (!RtlDosPathNameToNtPathName_U (DosName
,
377 return STATUS_DLL_NOT_FOUND
;
379 DPRINT("FullNtFileName %wZ\n", &FullNtFileName
);
381 InitializeObjectAttributes(&FileObjectAttributes
,
387 DPRINT("Opening dll \"%wZ\"\n", &FullNtFileName
);
389 Status
= ZwOpenFile(&FileHandle
,
391 &FileObjectAttributes
,
395 if (!NT_SUCCESS(Status
))
397 DbgPrint("Dll open of %wZ failed: Status = 0x%08x\n",
398 &FullNtFileName
, Status
);
399 RtlFreeUnicodeString (&FullNtFileName
);
402 RtlFreeUnicodeString (&FullNtFileName
);
404 Status
= ZwReadFile(FileHandle
,
413 if (!NT_SUCCESS(Status
))
415 DPRINT("Dll header read failed: Status = 0x%08x\n", Status
);
420 * Overlay DOS and NT headers structures to the
421 * buffer with DLL's header raw data.
423 DosHeader
= (PIMAGE_DOS_HEADER
) BlockBuffer
;
424 NTHeaders
= (PIMAGE_NT_HEADERS
) (BlockBuffer
+ DosHeader
->e_lfanew
);
426 * Check it is a PE image file.
428 if ((DosHeader
->e_magic
!= IMAGE_DOS_MAGIC
)
429 || (DosHeader
->e_lfanew
== 0L)
430 || (*(PULONG
)(NTHeaders
) != IMAGE_PE_MAGIC
))
432 DPRINT("NTDLL format invalid\n");
435 return STATUS_UNSUCCESSFUL
;
438 ImageBase
= (PVOID
) NTHeaders
->OptionalHeader
.ImageBase
;
439 ImageSize
= NTHeaders
->OptionalHeader
.SizeOfImage
;
441 DPRINT("ImageBase 0x%08x\n", ImageBase
);
444 * Create a section for dll.
446 Status
= ZwCreateSection(SectionHandle
,
451 SEC_COMMIT
| SEC_IMAGE
,
455 if (!NT_SUCCESS(Status
))
457 DPRINT("NTDLL create section failed: Status = 0x%08x\n", Status
);
461 RtlCreateUnicodeString(FullDosName
,
469 /***************************************************************************
487 LdrLoadDll (IN PWSTR SearchPath OPTIONAL
,
489 IN PUNICODE_STRING Name
,
490 OUT PVOID
*BaseAddress OPTIONAL
)
492 UNICODE_STRING FullDosName
;
493 UNICODE_STRING AdjustedName
;
495 PIMAGE_NT_HEADERS NTHeaders
;
498 HANDLE SectionHandle
;
499 PDLLMAIN_FUNC Entrypoint
= NULL
;
505 *BaseAddress
= NtCurrentPeb()->ImageBaseAddress
;
506 return STATUS_SUCCESS
;
511 DPRINT("LdrLoadDll(Name \"%wZ\" BaseAddress %x)\n",
514 /* adjust the full dll name */
515 LdrAdjustDllName (&AdjustedName
,
518 DPRINT("AdjustedName: %wZ\n", &AdjustedName
);
521 * Test if dll is already loaded.
523 if (LdrFindEntryForName(&AdjustedName
, &Module
) == STATUS_SUCCESS
)
525 DPRINT("DLL %wZ already loaded.\n", &AdjustedName
);
526 if (Module
->LoadCount
!= -1)
528 *BaseAddress
= Module
->BaseAddress
;
529 return STATUS_SUCCESS
;
531 DPRINT("Loading \"%wZ\"\n", Name
);
533 /* Open or create dll image section */
534 Status
= LdrpMapKnownDll(&AdjustedName
,
537 if (!NT_SUCCESS(Status
))
539 Status
= LdrpMapDllImageFile(SearchPath
,
545 RtlFreeUnicodeString(&AdjustedName
);
547 if (!NT_SUCCESS(Status
))
549 DPRINT1("Failed to create or open dll section (Status %lx)\n", Status
);
554 * Map the dll into the process.
558 Status
= NtMapViewOfSection(SectionHandle
,
568 if (!NT_SUCCESS(Status
))
570 DbgPrint("NTDLL.LDR: map view of section failed (Status %x)\n", Status
);
571 RtlFreeUnicodeString(&FullDosName
);
572 NtClose(SectionHandle
);
576 /* Get and check the NT headers */
577 NTHeaders
= RtlImageNtHeader(ImageBase
);
578 if (NTHeaders
== NULL
)
580 DPRINT1("RtlImageNtHeaders() failed\n");
581 RtlFreeUnicodeString(&FullDosName
);
582 return STATUS_UNSUCCESSFUL
;
585 /* relocate dll and fixup import table */
586 if ((NTHeaders
->FileHeader
.Characteristics
& IMAGE_FILE_DLL
) ==
590 (PDLLMAIN_FUNC
) LdrPEStartup(ImageBase
, SectionHandle
, &Module
,
592 if (Entrypoint
== NULL
)
594 RtlFreeUnicodeString(&FullDosName
);
595 return(STATUS_UNSUCCESSFUL
);
599 RtlFreeUnicodeString(&FullDosName
);
603 LdrpLoadUserModuleSymbols(Module
);
608 if ((NTHeaders
->FileHeader
.Characteristics
& IMAGE_FILE_DLL
) ==
611 if (Module
->EntryPoint
!= 0)
613 Entrypoint
= (PDLLMAIN_FUNC
)Module
->EntryPoint
;
615 DPRINT("Calling entry point at 0x%08x\n", Entrypoint
);
616 if (FALSE
== Entrypoint(Module
->BaseAddress
,
620 /* Do this as a DPRINT1 for now, until clean up and fail implemented */
621 DPRINT1("NTDLL.LDR: DLL \"%wZ\" failed to initialize\n",
622 &Module
->BaseDllName
);
623 /* FIXME: should clean up and fail */
627 DPRINT("NTDLL.LDR: DLL \"%wZ\" initialized successfully\n",
628 &Module
->BaseDllName
);
633 DPRINT("NTDLL.LDR: Entrypoint is NULL for \"%wZ\"\n",
634 &Module
->BaseDllName
);
638 *BaseAddress
= Module
->BaseAddress
;
639 return STATUS_SUCCESS
;
643 /***************************************************************************
645 * LdrFindEntryForAddress
660 LdrFindEntryForAddress(PVOID Address
,
663 PLIST_ENTRY ModuleListHead
;
665 PLDR_MODULE ModulePtr
;
667 DPRINT("NTDLL.LdrFindEntryForAddress(Address %p)\n", Address
);
669 if (NtCurrentPeb()->Ldr
== NULL
)
670 return(STATUS_NO_MORE_ENTRIES
);
672 ModuleListHead
= &NtCurrentPeb()->Ldr
->InLoadOrderModuleList
;
673 Entry
= ModuleListHead
->Flink
;
674 if (Entry
== ModuleListHead
)
675 return(STATUS_NO_MORE_ENTRIES
);
677 while (Entry
!= ModuleListHead
)
679 ModulePtr
= CONTAINING_RECORD(Entry
, LDR_MODULE
, InLoadOrderModuleList
);
681 DPRINT("Scanning %wZ at %p\n", &ModulePtr
->BaseDllName
, ModulePtr
->BaseAddress
);
683 if ((Address
>= ModulePtr
->BaseAddress
) &&
684 (Address
<= (ModulePtr
->BaseAddress
+ ModulePtr
->SizeOfImage
)))
687 return(STATUS_SUCCESS
);
690 Entry
= Entry
->Flink
;
693 DPRINT("Failed to find module entry.\n");
695 return(STATUS_NO_MORE_ENTRIES
);
699 /***************************************************************************
701 * LdrFindEntryForName
715 LdrFindEntryForName(PUNICODE_STRING Name
,
718 PLIST_ENTRY ModuleListHead
;
720 PLDR_MODULE ModulePtr
;
721 BOOLEAN ContainsPath
;
724 DPRINT("NTDLL.LdrFindEntryForName(Name %wZ)\n", Name
);
726 if (NtCurrentPeb()->Ldr
== NULL
)
727 return(STATUS_NO_MORE_ENTRIES
);
729 ModuleListHead
= &NtCurrentPeb()->Ldr
->InLoadOrderModuleList
;
730 Entry
= ModuleListHead
->Flink
;
731 if (Entry
== ModuleListHead
)
732 return(STATUS_NO_MORE_ENTRIES
);
734 // NULL is the current process
737 *Module
= CONTAINING_RECORD(Entry
, LDR_MODULE
, InLoadOrderModuleList
);
738 return(STATUS_SUCCESS
);
741 ContainsPath
= (Name
->Length
>= 2 * sizeof(WCHAR
) && L
':' == Name
->Buffer
[1]);
742 for (i
= 0; ! ContainsPath
&& i
< Name
->Length
/ sizeof(WCHAR
); i
++)
744 ContainsPath
= L
'\\' == Name
->Buffer
[i
] ||
745 L
'/' == Name
->Buffer
[i
];
747 while (Entry
!= ModuleListHead
)
749 ModulePtr
= CONTAINING_RECORD(Entry
, LDR_MODULE
, InLoadOrderModuleList
);
751 DPRINT("Scanning %wZ %wZ\n", &ModulePtr
->BaseDllName
, Name
);
753 if ((! ContainsPath
&&
754 0 == RtlCompareUnicodeString(&ModulePtr
->BaseDllName
, Name
, TRUE
)) ||
756 0 == RtlCompareUnicodeString(&ModulePtr
->FullDllName
, Name
, TRUE
)))
759 return(STATUS_SUCCESS
);
762 Entry
= Entry
->Flink
;
765 DPRINT("Failed to find dll %wZ\n", Name
);
767 return(STATUS_NO_MORE_ENTRIES
);
770 /**********************************************************************
786 LdrFixupForward(PCHAR ForwardName
)
788 CHAR NameBuffer
[128];
789 UNICODE_STRING DllName
;
790 UNICODE_STRING FunctionName
;
795 strcpy(NameBuffer
, ForwardName
);
796 p
= strchr(NameBuffer
, '.');
801 DPRINT("Dll: %s Function: %s\n", NameBuffer
, p
+1);
802 RtlCreateUnicodeStringFromAsciiz (&DllName
,
805 Status
= LdrGetDllHandle (0, 0, &DllName
, &BaseAddress
);
806 if (!NT_SUCCESS(Status
))
808 Status
= LdrLoadDll(NULL
,
812 if (!NT_SUCCESS(Status
))
814 DbgPrint("LdrFixupForward: failed to load %wZ\n", &DllName
);
815 RtlFreeUnicodeString (&DllName
);
820 RtlFreeUnicodeString (&DllName
);
821 DPRINT("BaseAddress: %p\n", BaseAddress
);
823 return LdrGetExportByName(BaseAddress
, p
+1, -1);
830 /**********************************************************************
832 * LdrGetExportByOrdinal
846 LdrGetExportByOrdinal (
851 PIMAGE_EXPORT_DIRECTORY ExportDir
;
852 PDWORD
* ExFunctions
;
855 ExportDir
= (PIMAGE_EXPORT_DIRECTORY
)
856 RtlImageDirectoryEntryToData (BaseAddress
,
858 IMAGE_DIRECTORY_ENTRY_EXPORT
,
862 ExOrdinals
= (USHORT
*)
865 ExportDir
->AddressOfNameOrdinals
867 ExFunctions
= (PDWORD
*)
870 ExportDir
->AddressOfFunctions
873 "LdrGetExportByOrdinal(Ordinal %d) = %x\n",
875 RVA(BaseAddress
, ExFunctions
[Ordinal
- ExportDir
->Base
] )
877 return(RVA(BaseAddress
, ExFunctions
[Ordinal
- ExportDir
->Base
] ));
881 /**********************************************************************
894 * AddressOfNames and AddressOfNameOrdinals are paralell tables,
895 * both with NumberOfNames entries.
899 LdrGetExportByName(PVOID BaseAddress
,
903 PIMAGE_EXPORT_DIRECTORY ExportDir
;
904 PDWORD
* ExFunctions
;
914 DPRINT("LdrGetExportByName %x %s %hu\n", BaseAddress
, SymbolName
, Hint
);
916 ExportDir
= (PIMAGE_EXPORT_DIRECTORY
)
917 RtlImageDirectoryEntryToData(BaseAddress
,
919 IMAGE_DIRECTORY_ENTRY_EXPORT
,
921 if (ExportDir
== NULL
)
923 DbgPrint("LdrGetExportByName(): no export directory!\n");
928 //The symbol names may be missing entirely
929 if (ExportDir
->AddressOfNames
== 0)
931 DPRINT("LdrGetExportByName(): symbol names missing entirely\n");
936 * Get header pointers
938 ExNames
= (PDWORD
*)RVA(BaseAddress
,
939 ExportDir
->AddressOfNames
);
940 ExOrdinals
= (USHORT
*)RVA(BaseAddress
,
941 ExportDir
->AddressOfNameOrdinals
);
942 ExFunctions
= (PDWORD
*)RVA(BaseAddress
,
943 ExportDir
->AddressOfFunctions
);
946 * Check the hint first
948 if (Hint
< ExportDir
->NumberOfNames
)
950 ExName
= RVA(BaseAddress
, ExNames
[Hint
]);
951 if (strcmp(ExName
, SymbolName
) == 0)
953 Ordinal
= ExOrdinals
[Hint
];
954 Function
= RVA(BaseAddress
, ExFunctions
[Ordinal
]);
955 if (((ULONG
)Function
>= (ULONG
)ExportDir
) &&
956 ((ULONG
)Function
< (ULONG
)ExportDir
+ (ULONG
)ExportDirSize
))
958 DPRINT("Forward: %s\n", (PCHAR
)Function
);
959 Function
= LdrFixupForward((PCHAR
)Function
);
961 if (Function
!= NULL
)
967 * Try a binary search first
970 maxn
= ExportDir
->NumberOfNames
;
976 mid
= (minn
+ maxn
) / 2;
978 ExName
= RVA(BaseAddress
, ExNames
[mid
]);
979 res
= strcmp(ExName
, SymbolName
);
982 Ordinal
= ExOrdinals
[mid
];
983 Function
= RVA(BaseAddress
, ExFunctions
[Ordinal
]);
984 if (((ULONG
)Function
>= (ULONG
)ExportDir
) &&
985 ((ULONG
)Function
< (ULONG
)ExportDir
+ (ULONG
)ExportDirSize
))
987 DPRINT("Forward: %s\n", (PCHAR
)Function
);
988 Function
= LdrFixupForward((PCHAR
)Function
);
990 if (Function
!= NULL
)
993 else if (minn
== maxn
)
995 DPRINT("LdrGetExportByName(): binary search failed\n");
1009 * Fall back on a linear search
1011 DPRINT("LdrGetExportByName(): Falling back on a linear search of export table\n");
1012 for (i
= 0; i
< ExportDir
->NumberOfNames
; i
++)
1014 ExName
= RVA(BaseAddress
, ExNames
[i
]);
1015 if (strcmp(ExName
,SymbolName
) == 0)
1017 Ordinal
= ExOrdinals
[i
];
1018 Function
= RVA(BaseAddress
, ExFunctions
[Ordinal
]);
1019 DPRINT("%x %x %x\n", Function
, ExportDir
, ExportDir
+ ExportDirSize
);
1020 if (((ULONG
)Function
>= (ULONG
)ExportDir
) &&
1021 ((ULONG
)Function
< (ULONG
)ExportDir
+ (ULONG
)ExportDirSize
))
1023 DPRINT("Forward: %s\n", (PCHAR
)Function
);
1024 Function
= LdrFixupForward((PCHAR
)Function
);
1029 DbgPrint("LdrGetExportByName(): failed to find %s\n",SymbolName
);
1034 /**********************************************************************
1036 * LdrPerformRelocations
1039 * Relocate a DLL's memory image.
1050 static NTSTATUS
LdrPerformRelocations (PIMAGE_NT_HEADERS NTHeaders
,
1053 USHORT NumberOfEntries
;
1055 ULONG RelocationRVA
;
1059 PRELOCATION_DIRECTORY RelocationDir
;
1060 PRELOCATION_ENTRY RelocationBlock
;
1062 PIMAGE_DATA_DIRECTORY RelocationDDir
;
1066 PIMAGE_SECTION_HEADER Sections
;
1071 (PIMAGE_SECTION_HEADER
)((PVOID
)NTHeaders
+ sizeof(IMAGE_NT_HEADERS
));
1073 for (i
= 0; i
< NTHeaders
->FileHeader
.NumberOfSections
; i
++)
1075 if (!(Sections
[i
].Characteristics
& IMAGE_SECTION_NOLOAD
))
1079 (ULONG
)(Sections
[i
].VirtualAddress
+ Sections
[i
].Misc
.VirtualSize
);
1080 MaxExtend
= max(MaxExtend
, Extend
);
1085 &NTHeaders
->OptionalHeader
.DataDirectory
[IMAGE_DIRECTORY_ENTRY_BASERELOC
];
1086 RelocationRVA
= RelocationDDir
->VirtualAddress
;
1091 (PRELOCATION_DIRECTORY
)((PCHAR
)ImageBase
+ RelocationRVA
);
1093 while (RelocationDir
->SizeOfBlock
)
1095 if (RelocationDir
->VirtualAddress
> MaxExtend
)
1097 RelocationRVA
+= RelocationDir
->SizeOfBlock
;
1099 (PRELOCATION_DIRECTORY
) (ImageBase
+ RelocationRVA
);
1103 Delta32
= (ULONG
)(ImageBase
- NTHeaders
->OptionalHeader
.ImageBase
);
1105 (PRELOCATION_ENTRY
) (RelocationRVA
+ ImageBase
+
1106 sizeof (RELOCATION_DIRECTORY
));
1108 RelocationDir
->SizeOfBlock
- sizeof (RELOCATION_DIRECTORY
);
1109 NumberOfEntries
= NumberOfEntries
/ sizeof (RELOCATION_ENTRY
);
1111 Status
= NtProtectVirtualMemory(NtCurrentProcess(),
1113 RelocationDir
->VirtualAddress
,
1117 if (!NT_SUCCESS(Status
))
1119 DPRINT1("Failed to unprotect relocation target.\n");
1123 if (RelocationDir
->VirtualAddress
+ PAGE_SIZE
< MaxExtend
)
1125 Status
= NtProtectVirtualMemory(NtCurrentProcess(),
1127 RelocationDir
->VirtualAddress
+ PAGE_SIZE
,
1131 if (!NT_SUCCESS(Status
))
1133 DPRINT1("Failed to unprotect relocation target (2).\n");
1134 NtProtectVirtualMemory(NtCurrentProcess(),
1136 RelocationDir
->VirtualAddress
,
1144 for (i
= 0; i
< NumberOfEntries
; i
++)
1146 Offset
= (RelocationBlock
[i
].TypeOffset
& 0xfff);
1147 Offset
+= (ULONG
)(RelocationDir
->VirtualAddress
+ ImageBase
);
1150 * What kind of relocations should we perform
1151 * for the current entry?
1153 switch (RelocationBlock
[i
].TypeOffset
>> 12)
1155 case TYPE_RELOC_ABSOLUTE
:
1158 case TYPE_RELOC_HIGH
:
1159 pValue16
= (PUSHORT
)Offset
;
1160 *pValue16
+= Delta32
>> 16;
1163 case TYPE_RELOC_LOW
:
1164 pValue16
= (PUSHORT
)Offset
;
1165 *pValue16
+= Delta32
& 0xffff;
1168 case TYPE_RELOC_HIGHLOW
:
1169 pValue32
= (PULONG
)Offset
;
1170 *pValue32
+= Delta32
;
1173 case TYPE_RELOC_HIGHADJ
:
1174 /* FIXME: do the highadjust fixup */
1175 DPRINT("TYPE_RELOC_HIGHADJ fixup not implemented, sorry\n");
1176 return(STATUS_UNSUCCESSFUL
);
1179 DPRINT("unexpected fixup type\n");
1180 return STATUS_UNSUCCESSFUL
;
1184 Status
= NtProtectVirtualMemory(NtCurrentProcess(),
1186 RelocationDir
->VirtualAddress
,
1190 if (!NT_SUCCESS(Status
))
1192 DPRINT1("Failed to protect relocation target.\n");
1196 if (RelocationDir
->VirtualAddress
+ PAGE_SIZE
< MaxExtend
)
1198 Status
= NtProtectVirtualMemory(NtCurrentProcess(),
1200 RelocationDir
->VirtualAddress
+ PAGE_SIZE
,
1204 if (!NT_SUCCESS(Status
))
1206 DPRINT1("Failed to protect relocation target2.\n");
1211 RelocationRVA
+= RelocationDir
->SizeOfBlock
;
1213 (PRELOCATION_DIRECTORY
) (ImageBase
+ RelocationRVA
);
1216 return STATUS_SUCCESS
;
1220 /**********************************************************************
1225 * Compute the entry point for every symbol the DLL imports
1226 * from other modules.
1237 static NTSTATUS
LdrFixupImports(PIMAGE_NT_HEADERS NTHeaders
,
1240 PIMAGE_IMPORT_MODULE_DIRECTORY ImportModuleDirectory
;
1246 DPRINT("LdrFixupImports(NTHeaders %x, ImageBase %x)\n", NTHeaders
,
1250 * Process each import module.
1252 ImportModuleDirectory
= (PIMAGE_IMPORT_MODULE_DIRECTORY
)(
1253 ImageBase
+ NTHeaders
->OptionalHeader
1254 .DataDirectory
[IMAGE_DIRECTORY_ENTRY_IMPORT
]
1256 DPRINT("ImportModuleDirectory %x\n", ImportModuleDirectory
);
1258 while (ImportModuleDirectory
->dwRVAModuleName
)
1260 PVOID
* ImportAddressList
;
1261 PULONG FunctionNameList
;
1262 UNICODE_STRING DllName
;
1268 DPRINT("ImportModule->Directory->dwRVAModuleName %s\n",
1269 (PCHAR
)(ImageBase
+ ImportModuleDirectory
->dwRVAModuleName
));
1271 RtlCreateUnicodeStringFromAsciiz (&DllName
,
1272 (PCHAR
)(ImageBase
+ ImportModuleDirectory
->dwRVAModuleName
));
1274 Status
= LdrGetDllHandle (0, 0, &DllName
, &BaseAddress
);
1275 if (!NT_SUCCESS(Status
))
1277 Status
= LdrLoadDll(NULL
,
1281 RtlFreeUnicodeString (&DllName
);
1282 if (!NT_SUCCESS(Status
))
1284 DbgPrint("LdrFixupImports:failed to load %s\n"
1286 + ImportModuleDirectory
->dwRVAModuleName
));
1293 * Get the import address list.
1295 ImportAddressList
= (PVOID
*)(ImageBase
1296 + ImportModuleDirectory
->dwRVAFunctionAddressList
);
1299 * Get the list of functions to import.
1301 if (ImportModuleDirectory
->dwRVAFunctionNameList
!= 0)
1303 FunctionNameList
= (PULONG
) (
1305 + ImportModuleDirectory
->dwRVAFunctionNameList
1312 + ImportModuleDirectory
->dwRVAFunctionAddressList
);
1316 * Get the size of IAT.
1319 while (FunctionNameList
[IATSize
] != 0L)
1325 * Unprotect the region we are about to write into.
1327 IATBase
= (PVOID
)ImportAddressList
;
1328 Status
= NtProtectVirtualMemory(NtCurrentProcess(),
1330 IATSize
* sizeof(PVOID
*),
1333 if (!NT_SUCCESS(Status
))
1335 DbgPrint("LDR: Failed to unprotect IAT.\n");
1340 * Walk through function list and fixup addresses.
1342 while (*FunctionNameList
!= 0L)
1344 if ((*FunctionNameList
) & 0x80000000)
1346 Ordinal
= (*FunctionNameList
) & 0x7fffffff;
1347 *ImportAddressList
=
1348 LdrGetExportByOrdinal(BaseAddress
,
1353 pName
= (DWORD
) (ImageBase
+ *FunctionNameList
+ 2);
1354 pHint
= *(PWORD
)(ImageBase
+ *FunctionNameList
);
1356 *ImportAddressList
=
1357 LdrGetExportByName(BaseAddress
, (PUCHAR
)pName
, pHint
);
1358 if ((*ImportAddressList
) == NULL
)
1360 DbgPrint("Failed to import %s\n", pName
);
1361 return STATUS_UNSUCCESSFUL
;
1364 ImportAddressList
++;
1369 * Protect the region we are about to write into.
1371 Status
= NtProtectVirtualMemory(NtCurrentProcess(),
1373 IATSize
* sizeof(PVOID
*),
1376 if (!NT_SUCCESS(Status
))
1378 DbgPrint("LDR: Failed to protect IAT.\n");
1382 ImportModuleDirectory
++;
1384 return STATUS_SUCCESS
;
1388 /**********************************************************************
1393 * 1. Map the DLL's sections into memory.
1394 * 2. Relocate, if needed the DLL.
1395 * 3. Fixup any imported symbol.
1396 * 4. Compute the DLL's entry point.
1400 * Address at which the DLL's image
1404 * Handle of the section that contains
1408 * NULL on error; otherwise the entry point
1409 * to call for initializing the DLL.
1416 PEPFUNC
LdrPEStartup (PVOID ImageBase
,
1417 HANDLE SectionHandle
,
1418 PLDR_MODULE
* Module
,
1422 PEPFUNC EntryPoint
= NULL
;
1423 PIMAGE_DOS_HEADER DosHeader
;
1424 PIMAGE_NT_HEADERS NTHeaders
;
1426 DPRINT("LdrPEStartup(ImageBase %x SectionHandle %x)\n",
1427 ImageBase
, (ULONG
)SectionHandle
);
1430 * Overlay DOS and WNT headers structures
1431 * to the DLL's image.
1433 DosHeader
= (PIMAGE_DOS_HEADER
) ImageBase
;
1434 NTHeaders
= (PIMAGE_NT_HEADERS
) (ImageBase
+ DosHeader
->e_lfanew
);
1437 * If the base address is different from the
1438 * one the DLL is actually loaded, perform any
1441 if (ImageBase
!= (PVOID
) NTHeaders
->OptionalHeader
.ImageBase
)
1443 DbgPrint("LDR: Performing relocations\n");
1444 Status
= LdrPerformRelocations(NTHeaders
, ImageBase
);
1445 if (!NT_SUCCESS(Status
))
1447 DbgPrint("LdrPerformRelocations() failed\n");
1454 *Module
= LdrAddModuleEntry(ImageBase
, NTHeaders
, FullDosName
);
1455 (*Module
)->SectionHandle
= SectionHandle
;
1459 * If the DLL's imports symbols from other
1460 * modules, fixup the imported calls entry points.
1462 if (NTHeaders
->OptionalHeader
.DataDirectory
[IMAGE_DIRECTORY_ENTRY_IMPORT
]
1463 .VirtualAddress
!= 0)
1465 DPRINT("About to fixup imports\n");
1466 Status
= LdrFixupImports(NTHeaders
, ImageBase
);
1467 if (!NT_SUCCESS(Status
))
1469 DbgPrint("LdrFixupImports() failed\n");
1472 DPRINT("Fixup done\n");
1476 * Compute the DLL's entry point's address.
1478 DPRINT("ImageBase = %x\n",(ULONG
)ImageBase
);
1479 DPRINT("AddressOfEntryPoint = %x\n",(ULONG
)NTHeaders
->OptionalHeader
.AddressOfEntryPoint
);
1480 if (NTHeaders
->OptionalHeader
.AddressOfEntryPoint
!= 0)
1482 EntryPoint
= (PEPFUNC
) (ImageBase
1483 + NTHeaders
->OptionalHeader
.AddressOfEntryPoint
);
1485 DPRINT("LdrPEStartup() = %x\n",EntryPoint
);
1494 LdrUnloadDll (IN PVOID BaseAddress
)
1496 PIMAGE_NT_HEADERS NtHeaders
;
1497 PDLLMAIN_FUNC Entrypoint
;
1498 PLIST_ENTRY ModuleListHead
;
1503 if (BaseAddress
== NULL
)
1504 return STATUS_SUCCESS
;
1506 ModuleListHead
= &NtCurrentPeb()->Ldr
->InLoadOrderModuleList
;
1507 Entry
= ModuleListHead
->Flink
;
1509 while (Entry
!= ModuleListHead
)
1511 Module
= CONTAINING_RECORD(Entry
, LDR_MODULE
, InLoadOrderModuleList
);
1512 if (Module
->BaseAddress
== BaseAddress
)
1514 if (Module
->LoadCount
== -1)
1516 /* never unload this dll */
1517 return STATUS_SUCCESS
;
1519 else if (Module
->LoadCount
> 1)
1521 Module
->LoadCount
--;
1522 return STATUS_SUCCESS
;
1525 NtHeaders
= RtlImageNtHeader (Module
->BaseAddress
);
1526 if ((NtHeaders
->FileHeader
.Characteristics
& IMAGE_FILE_DLL
) == IMAGE_FILE_DLL
)
1528 if (Module
->EntryPoint
!= 0)
1530 Entrypoint
= (PDLLMAIN_FUNC
)Module
->EntryPoint
;
1531 DPRINT("Calling entry point at 0x%08x\n", Entrypoint
);
1532 Entrypoint(Module
->BaseAddress
,
1538 DPRINT("NTDLL.LDR: Entrypoint is NULL for \n");
1541 Status
= ZwUnmapViewOfSection (NtCurrentProcess (),
1542 Module
->BaseAddress
);
1543 ZwClose (Module
->SectionHandle
);
1545 /* remove the module entry from the list */
1546 RtlFreeUnicodeString (&Module
->FullDllName
);
1547 RtlFreeUnicodeString (&Module
->BaseDllName
);
1548 RemoveEntryList (Entry
);
1549 RtlFreeHeap (RtlGetProcessHeap (), 0, Module
);
1554 Entry
= Entry
->Flink
;
1557 DPRINT("NTDLL.LDR: Dll not found\n")
1559 return STATUS_UNSUCCESSFUL
;
1567 LdrDisableThreadCalloutsForDll(IN PVOID BaseAddress
)
1569 PLIST_ENTRY ModuleListHead
;
1574 DPRINT("LdrDisableThreadCalloutsForDll (BaseAddress %x)\n", BaseAddress
);
1576 Status
= STATUS_DLL_NOT_FOUND
;
1577 ModuleListHead
= &NtCurrentPeb()->Ldr
->InLoadOrderModuleList
;
1578 Entry
= ModuleListHead
->Flink
;
1579 while (Entry
!= ModuleListHead
) {
1580 Module
= CONTAINING_RECORD(Entry
, LDR_MODULE
, InLoadOrderModuleList
);
1582 DPRINT("BaseDllName %wZ BaseAddress %x\n", &Module
->BaseDllName
, Module
->BaseAddress
);
1584 if (Module
->BaseAddress
== BaseAddress
) {
1585 if (Module
->TlsIndex
== 0) {
1586 Module
->Flags
|= 0x00040000;
1587 Status
= STATUS_SUCCESS
;
1591 Entry
= Entry
->Flink
;
1601 LdrGetDllHandle(IN ULONG Unknown1
,
1603 IN PUNICODE_STRING DllName
,
1604 OUT PVOID
* BaseAddress
)
1606 UNICODE_STRING FullDllName
;
1607 PLIST_ENTRY ModuleListHead
;
1611 DPRINT("LdrGetDllHandle (Unknown1 %x Unknown2 %x DllName %wZ BaseAddress %p)\n",
1612 Unknown1
, Unknown2
, DllName
, BaseAddress
);
1614 /* NULL is the current executable */
1615 if (DllName
== NULL
) {
1616 *BaseAddress
= NtCurrentPeb()->ImageBaseAddress
;
1617 DPRINT("BaseAddress %x\n", *BaseAddress
);
1618 return STATUS_SUCCESS
;
1620 LdrAdjustDllName(&FullDllName
, DllName
, TRUE
);
1622 DPRINT("FullDllName %wZ\n", &FullDllName
);
1624 ModuleListHead
= &NtCurrentPeb()->Ldr
->InLoadOrderModuleList
;
1625 Entry
= ModuleListHead
->Flink
;
1626 while (Entry
!= ModuleListHead
) {
1627 Module
= CONTAINING_RECORD(Entry
, LDR_MODULE
, InLoadOrderModuleList
);
1629 DPRINT("EntryPoint %x\n", Module
->EntryPoint
);
1630 DPRINT("Comparing %wZ and %wZ\n", &Module
->BaseDllName
, &FullDllName
);
1632 if (!RtlCompareUnicodeString(&Module
->BaseDllName
, &FullDllName
, TRUE
)) {
1633 RtlFreeUnicodeString(&FullDllName
);
1634 *BaseAddress
= Module
->BaseAddress
;
1635 DPRINT("BaseAddress %x\n", *BaseAddress
);
1636 return STATUS_SUCCESS
;
1638 Entry
= Entry
->Flink
;
1641 DPRINT("Failed to find dll %wZ\n", &FullDllName
);
1643 RtlFreeUnicodeString(&FullDllName
);
1644 *BaseAddress
= NULL
;
1645 return STATUS_DLL_NOT_FOUND
;
1653 LdrGetProcedureAddress (IN PVOID BaseAddress
,
1654 IN PANSI_STRING Name
,
1656 OUT PVOID
*ProcedureAddress
)
1658 PIMAGE_EXPORT_DIRECTORY ExportDir
;
1664 DPRINT("LdrGetProcedureAddress (BaseAddress %x Name %Z Ordinal %lu ProcedureAddress %x)\n",
1665 BaseAddress
, Name
, Ordinal
, ProcedureAddress
);
1667 /* Get the pointer to the export directory */
1668 ExportDir
= (PIMAGE_EXPORT_DIRECTORY
)
1669 RtlImageDirectoryEntryToData (BaseAddress
,
1671 IMAGE_DIRECTORY_ENTRY_EXPORT
,
1674 DPRINT("ExportDir %x i %lu\n", ExportDir
, i
);
1676 if (!ExportDir
|| !i
|| !ProcedureAddress
)
1678 return STATUS_INVALID_PARAMETER
;
1681 AddressPtr
= (PULONG
)((ULONG
)BaseAddress
+ (ULONG
)ExportDir
->AddressOfFunctions
);
1682 if (Name
&& Name
->Length
)
1685 OrdinalPtr
= (PUSHORT
)((ULONG
)BaseAddress
+ (ULONG
)ExportDir
->AddressOfNameOrdinals
);
1686 NamePtr
= (PULONG
)((ULONG
)BaseAddress
+ (ULONG
)ExportDir
->AddressOfNames
);
1687 for( i
= 0; i
< ExportDir
->NumberOfNames
; i
++, NamePtr
++, OrdinalPtr
++)
1689 if (!_strnicmp(Name
->Buffer
, (char*)(BaseAddress
+ *NamePtr
), Name
->Length
))
1691 *ProcedureAddress
= (PVOID
)((ULONG
)BaseAddress
+ (ULONG
)AddressPtr
[*OrdinalPtr
]);
1692 return STATUS_SUCCESS
;
1695 DPRINT("LdrGetProcedureAddress: Can't resolve symbol '%Z'\n", Name
);
1700 Ordinal
&= 0x0000FFFF;
1701 if (Ordinal
- ExportDir
->Base
< ExportDir
->NumberOfFunctions
)
1703 *ProcedureAddress
= (PVOID
)((ULONG
)BaseAddress
+ (ULONG
)AddressPtr
[Ordinal
- ExportDir
->Base
]);
1704 return STATUS_SUCCESS
;
1706 DPRINT("LdrGetProcedureAddress: Can't resolve symbol @%d\n", Ordinal
);
1709 return STATUS_PROCEDURE_NOT_FOUND
;
1717 LdrShutdownProcess (VOID
)
1719 PLIST_ENTRY ModuleListHead
;
1723 DPRINT("LdrShutdownProcess() called\n");
1725 RtlEnterCriticalSection (NtCurrentPeb()->LoaderLock
);
1727 ModuleListHead
= &NtCurrentPeb()->Ldr
->InInitializationOrderModuleList
;
1728 Entry
= ModuleListHead
->Blink
;
1730 while (Entry
!= ModuleListHead
)
1732 Module
= CONTAINING_RECORD(Entry
, LDR_MODULE
, InInitializationOrderModuleList
);
1734 DPRINT(" Unloading %wZ\n",
1735 &Module
->BaseDllName
);
1736 // PJS: only detach from static dlls, they should FreeLibrary() any dlls that
1737 // they loaded dynamically, and when the last reference is gone, that lib will
1739 if (Module
->EntryPoint
!= 0 && Module
->LoadCount
== -1)
1741 PDLLMAIN_FUNC Entrypoint
= (PDLLMAIN_FUNC
)Module
->EntryPoint
;
1743 DPRINT("Calling entry point at 0x%08x\n", Entrypoint
);
1744 Entrypoint (Module
->BaseAddress
,
1749 Entry
= Entry
->Blink
;
1752 RtlLeaveCriticalSection (NtCurrentPeb()->LoaderLock
);
1754 DPRINT("LdrShutdownProcess() done\n");
1756 return STATUS_SUCCESS
;
1764 LdrShutdownThread (VOID
)
1766 PLIST_ENTRY ModuleListHead
;
1770 DPRINT("LdrShutdownThread() called\n");
1772 RtlEnterCriticalSection (NtCurrentPeb()->LoaderLock
);
1774 ModuleListHead
= &NtCurrentPeb()->Ldr
->InInitializationOrderModuleList
;
1775 Entry
= ModuleListHead
->Blink
;
1777 while (Entry
!= ModuleListHead
)
1779 Module
= CONTAINING_RECORD(Entry
, LDR_MODULE
, InInitializationOrderModuleList
);
1781 DPRINT(" Unloading %wZ\n",
1782 &Module
->BaseDllName
);
1784 if (Module
->EntryPoint
!= 0)
1786 PDLLMAIN_FUNC Entrypoint
= (PDLLMAIN_FUNC
)Module
->EntryPoint
;
1788 DPRINT("Calling entry point at 0x%08x\n", Entrypoint
);
1789 Entrypoint (Module
->BaseAddress
,
1794 Entry
= Entry
->Blink
;
1797 RtlLeaveCriticalSection (NtCurrentPeb()->LoaderLock
);
1799 DPRINT("LdrShutdownThread() done\n");
1801 return STATUS_SUCCESS
;
1805 /***************************************************************************
1807 * LdrQueryProcessModuleInformation
1822 LdrQueryProcessModuleInformation(IN PMODULE_INFORMATION ModuleInformation OPTIONAL
,
1823 IN ULONG Size OPTIONAL
,
1824 OUT PULONG ReturnedSize
)
1826 PLIST_ENTRY ModuleListHead
;
1829 PMODULE_ENTRY ModulePtr
= NULL
;
1830 NTSTATUS Status
= STATUS_SUCCESS
;
1831 ULONG UsedSize
= sizeof(ULONG
);
1832 ANSI_STRING AnsiString
;
1835 DPRINT("LdrQueryProcessModuleInformation() called\n");
1837 RtlEnterCriticalSection (NtCurrentPeb()->LoaderLock
);
1839 if (ModuleInformation
== NULL
|| Size
== 0)
1841 Status
= STATUS_INFO_LENGTH_MISMATCH
;
1845 ModuleInformation
->ModuleCount
= 0;
1846 ModulePtr
= &ModuleInformation
->ModuleEntry
[0];
1847 Status
= STATUS_SUCCESS
;
1850 ModuleListHead
= &NtCurrentPeb()->Ldr
->InLoadOrderModuleList
;
1851 Entry
= ModuleListHead
->Flink
;
1853 while (Entry
!= ModuleListHead
)
1855 Module
= CONTAINING_RECORD(Entry
, LDR_MODULE
, InLoadOrderModuleList
);
1857 DPRINT(" Module %wZ\n",
1858 &Module
->FullDllName
);
1860 if (UsedSize
> Size
)
1862 Status
= STATUS_INFO_LENGTH_MISMATCH
;
1864 else if (ModuleInformation
!= NULL
)
1866 ModulePtr
->Unknown0
= 0; // FIXME: ??
1867 ModulePtr
->Unknown1
= 0; // FIXME: ??
1868 ModulePtr
->BaseAddress
= Module
->BaseAddress
;
1869 ModulePtr
->SizeOfImage
= Module
->SizeOfImage
;
1870 ModulePtr
->Flags
= Module
->Flags
;
1871 ModulePtr
->Unknown2
= 0; // FIXME: load order index ??
1872 ModulePtr
->Unknown3
= 0; // FIXME: ??
1873 ModulePtr
->LoadCount
= Module
->LoadCount
;
1875 AnsiString
.Length
= 0;
1876 AnsiString
.MaximumLength
= 256;
1877 AnsiString
.Buffer
= ModulePtr
->ModuleName
;
1878 RtlUnicodeStringToAnsiString(&AnsiString
,
1879 &Module
->FullDllName
,
1881 p
= strrchr(ModulePtr
->ModuleName
, '\\');
1883 ModulePtr
->PathLength
= p
- ModulePtr
->ModuleName
+ 1;
1885 ModulePtr
->PathLength
= 0;
1888 ModuleInformation
->ModuleCount
++;
1890 UsedSize
+= sizeof(MODULE_ENTRY
);
1892 Entry
= Entry
->Flink
;
1895 RtlLeaveCriticalSection (NtCurrentPeb()->LoaderLock
);
1897 if (ReturnedSize
!= 0)
1898 *ReturnedSize
= UsedSize
;
1900 DPRINT("LdrQueryProcessModuleInformation() done\n");
1907 LdrpCheckImageChecksum (IN PVOID BaseAddress
,
1910 PIMAGE_NT_HEADERS Header
;
1917 Header
= RtlImageNtHeader (BaseAddress
);
1921 HeaderSum
= Header
->OptionalHeader
.CheckSum
;
1926 Ptr
= (PUSHORT
) BaseAddress
;
1927 for (i
= 0; i
< ImageSize
/ sizeof (USHORT
); i
++)
1930 if (HIWORD(Sum
) != 0)
1932 Sum
= LOWORD(Sum
) + HIWORD(Sum
);
1939 Sum
+= (ULONG
)*((PUCHAR
)Ptr
);
1940 if (HIWORD(Sum
) != 0)
1942 Sum
= LOWORD(Sum
) + HIWORD(Sum
);
1946 CalcSum
= (USHORT
)(LOWORD(Sum
) + HIWORD(Sum
));
1948 /* Subtract image checksum from calculated checksum. */
1949 /* fix low word of checksum */
1950 if (LOWORD(CalcSum
) >= LOWORD(HeaderSum
))
1952 CalcSum
-= LOWORD(HeaderSum
);
1956 CalcSum
= ((LOWORD(CalcSum
) - LOWORD(HeaderSum
)) & 0xFFFF) - 1;
1959 /* fix high word of checksum */
1960 if (LOWORD(CalcSum
) >= HIWORD(HeaderSum
))
1962 CalcSum
-= HIWORD(HeaderSum
);
1966 CalcSum
= ((LOWORD(CalcSum
) - HIWORD(HeaderSum
)) & 0xFFFF) - 1;
1969 /* add file length */
1970 CalcSum
+= ImageSize
;
1972 return (BOOLEAN
)(CalcSum
== HeaderSum
);
1976 /***************************************************************************
1978 * LdrVerifyImageMatchesChecksum
1993 LdrVerifyImageMatchesChecksum (IN HANDLE FileHandle
,
1998 FILE_STANDARD_INFORMATION FileInfo
;
1999 IO_STATUS_BLOCK IoStatusBlock
;
2000 HANDLE SectionHandle
;
2006 DPRINT ("LdrVerifyImageMatchesChecksum() called\n");
2008 Status
= NtCreateSection (&SectionHandle
,
2009 SECTION_MAP_EXECUTE
,
2015 if (!NT_SUCCESS(Status
))
2017 DPRINT1 ("NtCreateSection() failed (Status %lx)\n", Status
);
2023 Status
= NtMapViewOfSection (SectionHandle
,
2024 NtCurrentProcess (),
2033 if (!NT_SUCCESS(Status
))
2035 DPRINT1 ("NtMapViewOfSection() failed (Status %lx)\n", Status
);
2036 NtClose (SectionHandle
);
2040 Status
= NtQueryInformationFile (FileHandle
,
2043 sizeof (FILE_STANDARD_INFORMATION
),
2044 FileStandardInformation
);
2045 if (!NT_SUCCESS(Status
))
2047 DPRINT1 ("NtMapViewOfSection() failed (Status %lx)\n", Status
);
2048 NtUnmapViewOfSection (NtCurrentProcess (),
2050 NtClose (SectionHandle
);
2054 Result
= LdrpCheckImageChecksum (BaseAddress
,
2055 FileInfo
.EndOfFile
.u
.LowPart
);
2056 if (Result
== FALSE
)
2058 Status
= STATUS_IMAGE_CHECKSUM_MISMATCH
;
2061 NtUnmapViewOfSection (NtCurrentProcess (),
2064 NtClose (SectionHandle
);
2070 /***************************************************************************
2072 * LdrQueryImageFileExecutionOptions
2087 LdrQueryImageFileExecutionOptions (IN PUNICODE_STRING SubKey
,
2088 IN PCWSTR ValueName
,
2091 IN ULONG BufferSize
,
2092 OUT PULONG ReturnedLength OPTIONAL
)
2094 PKEY_VALUE_PARTIAL_INFORMATION KeyInfo
;
2095 OBJECT_ATTRIBUTES ObjectAttributes
;
2096 UNICODE_STRING ValueNameString
;
2097 UNICODE_STRING ValueString
;
2098 UNICODE_STRING KeyName
;
2099 WCHAR NameBuffer
[256];
2107 L
"\\Registry\\Machine\\Software\\Microsoft\\Windows NT\\CurrentVersion\\Image File Execution Options\\");
2108 Ptr
= wcsrchr (SubKey
->Buffer
, L
'\\');
2111 Ptr
= SubKey
->Buffer
;
2117 wcscat (NameBuffer
, Ptr
);
2118 RtlInitUnicodeString (&KeyName
,
2121 InitializeObjectAttributes (&ObjectAttributes
,
2123 OBJ_CASE_INSENSITIVE
,
2127 Status
= NtOpenKey (&KeyHandle
,
2130 if (!NT_SUCCESS(Status
))
2132 DPRINT1 ("NtOpenKey() failed (Status %lx)\n", Status
);
2136 KeyInfoSize
= sizeof(KEY_VALUE_PARTIAL_INFORMATION
) + 32;
2137 KeyInfo
= RtlAllocateHeap (RtlGetProcessHeap(),
2141 RtlInitUnicodeString (&ValueNameString
,
2143 Status
= NtQueryValueKey (KeyHandle
,
2145 KeyValuePartialInformation
,
2149 if (Status
== STATUS_BUFFER_OVERFLOW
)
2151 KeyInfoSize
= sizeof(KEY_VALUE_PARTIAL_INFORMATION
) + KeyInfo
->DataLength
;
2152 RtlFreeHeap (RtlGetProcessHeap(),
2155 KeyInfo
= RtlAllocateHeap (RtlGetProcessHeap(),
2158 if (KeyInfo
== NULL
)
2160 NtClose (KeyHandle
);
2164 Status
= NtQueryValueKey (KeyHandle
,
2166 KeyValuePartialInformation
,
2171 NtClose (KeyHandle
);
2173 if (!NT_SUCCESS(Status
))
2175 if (KeyInfo
!= NULL
)
2177 RtlFreeHeap (RtlGetProcessHeap(),
2184 if (KeyInfo
->Type
!= REG_SZ
)
2186 RtlFreeHeap (RtlGetProcessHeap(),
2189 return STATUS_OBJECT_TYPE_MISMATCH
;
2192 if (ValueSize
== sizeof(ULONG
))
2194 if (BufferSize
!= sizeof(ULONG
))
2197 Status
= STATUS_INFO_LENGTH_MISMATCH
;
2201 ResultSize
= sizeof(ULONG
);
2202 ValueString
.Length
= (USHORT
)KeyInfo
->DataLength
- sizeof(WCHAR
);
2203 ValueString
.MaximumLength
= (USHORT
)KeyInfo
->DataLength
;
2204 ValueString
.Buffer
= (PWSTR
)&KeyInfo
->Data
;
2205 Status
= RtlUnicodeStringToInteger (&ValueString
,
2212 ResultSize
= BufferSize
;
2213 if (ResultSize
< KeyInfo
->DataLength
)
2215 Status
= STATUS_BUFFER_OVERFLOW
;
2219 ResultSize
= KeyInfo
->DataLength
;
2221 RtlCopyMemory (Buffer
,
2226 RtlFreeHeap (RtlGetProcessHeap(),
2230 if (ReturnedLength
!= NULL
)
2232 *ReturnedLength
= ResultSize
;