3 * COPYRIGHT: See COPYING in the top level directory
4 * PROJECT: ReactOS kernel
5 * FILE: lib/ntdll/ldr/startup.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 /* PROTOTYPES ****************************************************************/
36 static NTSTATUS LdrFindEntryForName(PUNICODE_STRING Name, PLDR_MODULE *Module);
37 static PVOID LdrFixupForward(PCHAR ForwardName);
38 static PVOID LdrGetExportByName(PVOID BaseAddress, PUCHAR SymbolName, USHORT Hint);
41 /* FUNCTIONS *****************************************************************/
47 LdrpLoadUserModuleSymbols(PLDR_MODULE LdrModule)
61 /***************************************************************************
66 * Adjusts the name of a dll to a fully qualified name.
69 * FullDllName: Pointer to caller supplied storage for the fully
71 * DllName: Pointer to the dll name.
72 * BaseName: TRUE: Only the file name is passed to FullDllName
73 * FALSE: The full path is preserved in FullDllName
81 * A given path is not affected by the adjustment, but the file
85 * ntdll.xyz --> ntdll.xyz
89 LdrAdjustDllName (PUNICODE_STRING FullDllName,
90 PUNICODE_STRING DllName,
93 WCHAR Buffer[MAX_PATH];
98 Length = DllName->Length / sizeof(WCHAR);
100 if (BaseName == TRUE)
102 /* get the base dll name */
103 Pointer = DllName->Buffer + Length;
110 while (Pointer >= DllName->Buffer && *Pointer != L'\\' && *Pointer != L'/');
113 Length = Extension - Pointer;
114 memmove (Buffer, Pointer, Length * sizeof(WCHAR));
115 Buffer[Length] = L'\0';
119 /* get the full dll name */
120 memmove (Buffer, DllName->Buffer, DllName->Length);
121 Buffer[DllName->Length / sizeof(WCHAR)] = L'\0';
124 /* Build the DLL's absolute name */
125 Extension = wcsrchr (Buffer, L'.');
126 if ((Extension != NULL) && (*Extension == L'.'))
128 /* with extension - remove dot if it's the last character */
129 if (Buffer[Length - 1] == L'.')
135 /* name without extension - assume that it is .dll */
136 memmove (Buffer + Length, L".dll", 10);
139 RtlCreateUnicodeString (FullDllName,
144 LdrAddModuleEntry(PVOID ImageBase, PIMAGE_NT_HEADERS NTHeaders,
148 Module = RtlAllocateHeap(RtlGetProcessHeap(),
150 sizeof (LDR_MODULE));
152 Module->BaseAddress = (PVOID)ImageBase;
153 Module->EntryPoint = NTHeaders->OptionalHeader.AddressOfEntryPoint;
154 if (Module->EntryPoint != 0)
155 Module->EntryPoint += (ULONG)Module->BaseAddress;
156 Module->SizeOfImage = NTHeaders->OptionalHeader.SizeOfImage;
157 if (NtCurrentPeb()->Ldr->Initialized == TRUE)
159 /* loading while app is running */
160 Module->LoadCount = 1;
165 * loading while app is initializing
166 * dll must not be unloaded
168 Module->LoadCount = -1;
171 Module->TlsIndex = 0;
172 Module->CheckSum = NTHeaders->OptionalHeader.CheckSum;
173 Module->TimeDateStamp = NTHeaders->FileHeader.TimeDateStamp;
175 RtlCreateUnicodeString (&Module->FullDllName,
177 RtlCreateUnicodeString (&Module->BaseDllName,
178 wcsrchr(FullDosName, L'\\') + 1);
179 DPRINT ("BaseDllName %wZ\n", &Module->BaseDllName);
181 /* FIXME: aquire loader lock */
182 InsertTailList(&NtCurrentPeb()->Ldr->InLoadOrderModuleList,
183 &Module->InLoadOrderModuleList);
184 InsertTailList(&NtCurrentPeb()->Ldr->InInitializationOrderModuleList,
185 &Module->InInitializationOrderModuleList);
186 /* FIXME: release loader lock */
191 /***************************************************************************
208 LdrLoadDll (IN PWSTR SearchPath OPTIONAL,
210 IN PUNICODE_STRING Name,
211 OUT PVOID *BaseAddress OPTIONAL)
213 WCHAR SearchPathBuffer[MAX_PATH];
214 WCHAR FullDosName[MAX_PATH];
215 UNICODE_STRING AdjustedName;
216 UNICODE_STRING FullNtFileName;
217 OBJECT_ATTRIBUTES FileObjectAttributes;
218 char BlockBuffer [1024];
219 PIMAGE_DOS_HEADER DosHeader;
221 PIMAGE_NT_HEADERS NTHeaders;
223 ULONG InitialViewSize;
226 HANDLE SectionHandle;
227 PDLLMAIN_FUNC Entrypoint = NULL;
232 *BaseAddress = NtCurrentPeb()->ImageBaseAddress;
233 return STATUS_SUCCESS;
238 DPRINT("LdrLoadDll(Name \"%wZ\" BaseAddress %x)\n",
241 /* adjust the full dll name */
242 LdrAdjustDllName (&AdjustedName,
245 DPRINT("AdjustedName: %wZ\n", &AdjustedName);
248 * Test if dll is already loaded.
250 if (LdrFindEntryForName(&AdjustedName, &Module) == STATUS_SUCCESS)
252 DPRINT("DLL %wZ already loaded.\n", &AdjustedName);
253 if (Module->LoadCount != -1)
255 *BaseAddress = Module->BaseAddress;
256 return STATUS_SUCCESS;
258 DPRINT("Loading \"%wZ\"\n", Name);
260 if (SearchPath == NULL)
262 SearchPath = SearchPathBuffer;
263 wcscpy (SearchPathBuffer, SharedUserData->NtSystemRoot);
264 wcscat (SearchPathBuffer, L"\\system32;");
265 wcscat (SearchPathBuffer, SharedUserData->NtSystemRoot);
266 wcscat (SearchPathBuffer, L";.");
269 DPRINT("SearchPath %S\n", SearchPath);
271 if (RtlDosSearchPath_U (SearchPath,
277 return STATUS_DLL_NOT_FOUND;
279 DPRINT("FullDosName %S\n", FullDosName);
281 RtlFreeUnicodeString (&AdjustedName);
283 if (!RtlDosPathNameToNtPathName_U (FullDosName,
287 return STATUS_DLL_NOT_FOUND;
289 DPRINT("FullNtFileName %wZ\n", &FullNtFileName);
291 InitializeObjectAttributes(&FileObjectAttributes,
297 DPRINT("Opening dll \"%wZ\"\n", &FullNtFileName);
299 Status = ZwOpenFile(&FileHandle,
301 &FileObjectAttributes,
305 if (!NT_SUCCESS(Status))
307 DbgPrint("Dll open of %wZ failed: Status = 0x%08x\n",
308 &FullNtFileName, Status);
309 RtlFreeUnicodeString (&FullNtFileName);
312 RtlFreeUnicodeString (&FullNtFileName);
314 Status = ZwReadFile(FileHandle,
323 if (!NT_SUCCESS(Status))
325 DPRINT("Dll header read failed: Status = 0x%08x\n", Status);
330 * Overlay DOS and NT headers structures to the
331 * buffer with DLL's header raw data.
333 DosHeader = (PIMAGE_DOS_HEADER) BlockBuffer;
334 NTHeaders = (PIMAGE_NT_HEADERS) (BlockBuffer + DosHeader->e_lfanew);
336 * Check it is a PE image file.
338 if ((DosHeader->e_magic != IMAGE_DOS_MAGIC)
339 || (DosHeader->e_lfanew == 0L)
340 || (*(PULONG)(NTHeaders) != IMAGE_PE_MAGIC))
342 DPRINT("NTDLL format invalid\n");
345 return STATUS_UNSUCCESSFUL;
348 ImageBase = (PVOID) NTHeaders->OptionalHeader.ImageBase;
349 ImageSize = NTHeaders->OptionalHeader.SizeOfImage;
351 DPRINT("ImageBase 0x%08x\n", ImageBase);
354 * Create a section for dll.
356 Status = ZwCreateSection(&SectionHandle,
361 SEC_COMMIT | SEC_IMAGE,
363 if (!NT_SUCCESS(Status))
365 DPRINT("NTDLL create section failed: Status = 0x%08x\n", Status);
371 * Map the dll into the process.
375 Status = ZwMapViewOfSection(SectionHandle,
385 if (!NT_SUCCESS(Status))
387 DbgPrint("NTDLL.LDR: map view of section failed (Status %x)\n",
394 /* relocate dll and fixup import table */
395 if ((NTHeaders->FileHeader.Characteristics & IMAGE_FILE_DLL) ==
399 (PDLLMAIN_FUNC) LdrPEStartup(ImageBase, SectionHandle, &Module,
401 if (Entrypoint == NULL)
403 return(STATUS_UNSUCCESSFUL);
409 LdrpLoadUserModuleSymbols(Module);
414 if ((NTHeaders->FileHeader.Characteristics & IMAGE_FILE_DLL) ==
417 if (Module->EntryPoint != 0)
419 Entrypoint = (PDLLMAIN_FUNC)Module->EntryPoint;
421 DPRINT("Calling entry point at 0x%08x\n", Entrypoint);
422 if (FALSE == Entrypoint(Module->BaseAddress,
426 DPRINT("NTDLL.LDR: DLL \"%wZ\" failed to initialize\n",
427 &Module->BaseDllName);
428 /* FIXME: should clean up and fail */
432 DPRINT("NTDLL.LDR: DLL \"%wZ\" initialized successfully\n",
433 &Module->BaseDllName);
438 DPRINT("NTDLL.LDR: Entrypoint is NULL for \"%wZ\"\n",
439 &Module->BaseDllName);
443 *BaseAddress = Module->BaseAddress;
444 return STATUS_SUCCESS;
448 /***************************************************************************
450 * LdrFindEntryForAddress
464 LdrFindEntryForAddress(PVOID Address,
467 PLIST_ENTRY ModuleListHead;
469 PLDR_MODULE ModulePtr;
471 DPRINT("NTDLL.LdrFindEntryForAddress(Address %p)\n", Address);
473 if (NtCurrentPeb()->Ldr == NULL)
474 return(STATUS_NO_MORE_ENTRIES);
476 ModuleListHead = &NtCurrentPeb()->Ldr->InLoadOrderModuleList;
477 Entry = ModuleListHead->Flink;
478 if (Entry == ModuleListHead)
479 return(STATUS_NO_MORE_ENTRIES);
481 while (Entry != ModuleListHead)
483 ModulePtr = CONTAINING_RECORD(Entry, LDR_MODULE, InLoadOrderModuleList);
485 DPRINT("Scanning %wZ at %p\n", &ModulePtr->BaseDllName, ModulePtr->BaseAddress);
487 if ((Address >= ModulePtr->BaseAddress) &&
488 (Address <= (ModulePtr->BaseAddress + ModulePtr->SizeOfImage)))
491 return(STATUS_SUCCESS);
494 Entry = Entry->Flink;
497 DPRINT("Failed to find module entry.\n");
499 return(STATUS_NO_MORE_ENTRIES);
503 /***************************************************************************
505 * LdrFindEntryForName
519 LdrFindEntryForName(PUNICODE_STRING Name,
522 PLIST_ENTRY ModuleListHead;
524 PLDR_MODULE ModulePtr;
526 DPRINT("NTDLL.LdrFindEntryForName(Name %wZ)\n", Name);
528 if (NtCurrentPeb()->Ldr == NULL)
529 return(STATUS_NO_MORE_ENTRIES);
531 ModuleListHead = &NtCurrentPeb()->Ldr->InLoadOrderModuleList;
532 Entry = ModuleListHead->Flink;
533 if (Entry == ModuleListHead)
534 return(STATUS_NO_MORE_ENTRIES);
536 // NULL is the current process
539 *Module = CONTAINING_RECORD(Entry, LDR_MODULE, InLoadOrderModuleList);
540 return(STATUS_SUCCESS);
543 while (Entry != ModuleListHead)
545 ModulePtr = CONTAINING_RECORD(Entry, LDR_MODULE, InLoadOrderModuleList);
547 DPRINT("Scanning %wZ %wZ\n", &ModulePtr->BaseDllName, Name);
549 if (RtlCompareUnicodeString(&ModulePtr->BaseDllName, Name, TRUE) == 0)
552 return(STATUS_SUCCESS);
555 Entry = Entry->Flink;
558 DPRINT("Failed to find dll %wZ\n", Name);
560 return(STATUS_NO_MORE_ENTRIES);
563 /**********************************************************************
579 LdrFixupForward(PCHAR ForwardName)
581 CHAR NameBuffer[128];
582 UNICODE_STRING DllName;
583 UNICODE_STRING FunctionName;
588 strcpy(NameBuffer, ForwardName);
589 p = strchr(NameBuffer, '.');
594 DPRINT("Dll: %s Function: %s\n", NameBuffer, p+1);
595 RtlCreateUnicodeStringFromAsciiz (&DllName,
598 Status = LdrGetDllHandle (0, 0, &DllName, &BaseAddress);
599 if (!NT_SUCCESS(Status))
601 Status = LdrLoadDll(NULL,
605 if (!NT_SUCCESS(Status))
607 DbgPrint("LdrFixupForward: failed to load %wZ\n", &DllName);
608 RtlFreeUnicodeString (&DllName);
613 RtlFreeUnicodeString (&DllName);
614 DPRINT("BaseAddress: %p\n", BaseAddress);
616 return LdrGetExportByName(BaseAddress, p+1, -1);
623 /**********************************************************************
625 * LdrGetExportByOrdinal
639 LdrGetExportByOrdinal (
644 PIMAGE_EXPORT_DIRECTORY ExportDir;
645 PDWORD * ExFunctions;
648 ExportDir = (PIMAGE_EXPORT_DIRECTORY)
649 RtlImageDirectoryEntryToData (BaseAddress,
651 IMAGE_DIRECTORY_ENTRY_EXPORT,
655 ExOrdinals = (USHORT *)
658 ExportDir->AddressOfNameOrdinals
660 ExFunctions = (PDWORD *)
663 ExportDir->AddressOfFunctions
666 "LdrGetExportByOrdinal(Ordinal %d) = %x\n",
668 ExFunctions[ExOrdinals[Ordinal - ExportDir->Base]]
670 return(ExFunctions[ExOrdinals[Ordinal - ExportDir->Base]]);
674 /**********************************************************************
690 LdrGetExportByName(PVOID BaseAddress,
694 PIMAGE_EXPORT_DIRECTORY ExportDir;
695 PDWORD * ExFunctions;
705 DPRINT("LdrGetExportByName %x %s %hu\n", BaseAddress, SymbolName, Hint);
707 ExportDir = (PIMAGE_EXPORT_DIRECTORY)
708 RtlImageDirectoryEntryToData(BaseAddress,
710 IMAGE_DIRECTORY_ENTRY_EXPORT,
712 if (ExportDir == NULL)
714 DbgPrint("LdrGetExportByName(): no export directory!\n");
719 * Get header pointers
721 ExNames = (PDWORD *)RVA(BaseAddress,
722 ExportDir->AddressOfNames);
723 ExOrdinals = (USHORT *)RVA(BaseAddress,
724 ExportDir->AddressOfNameOrdinals);
725 ExFunctions = (PDWORD *)RVA(BaseAddress,
726 ExportDir->AddressOfFunctions);
729 * Check the hint first
731 if (Hint < ExportDir->NumberOfFunctions)
733 ExName = RVA(BaseAddress, ExNames[Hint]);
734 if (strcmp(ExName, SymbolName) == 0)
736 Ordinal = ExOrdinals[Hint];
737 Function = RVA(BaseAddress, ExFunctions[Ordinal]);
738 if (((ULONG)Function >= (ULONG)ExportDir) &&
739 ((ULONG)Function < (ULONG)ExportDir + (ULONG)ExportDirSize))
741 DPRINT("Forward: %s\n", (PCHAR)Function);
742 Function = LdrFixupForward((PCHAR)Function);
744 if (Function != NULL)
750 * Try a binary search first
753 maxn = ExportDir->NumberOfFunctions;
759 mid = (minn + maxn) / 2;
761 ExName = RVA(BaseAddress, ExNames[mid]);
762 res = strcmp(ExName, SymbolName);
765 Ordinal = ExOrdinals[mid];
766 Function = RVA(BaseAddress, ExFunctions[Ordinal]);
767 if (((ULONG)Function >= (ULONG)ExportDir) &&
768 ((ULONG)Function < (ULONG)ExportDir + (ULONG)ExportDirSize))
770 DPRINT("Forward: %s\n", (PCHAR)Function);
771 Function = LdrFixupForward((PCHAR)Function);
773 if (Function != NULL)
776 else if (minn == maxn)
778 DPRINT("LdrGetExportByName(): binary search failed\n");
792 * Fall back on a linear search
794 DPRINT("LdrGetExportByName(): Falling back on a linear search of export table\n");
795 for (i = 0; i < ExportDir->NumberOfFunctions; i++)
797 ExName = RVA(BaseAddress, ExNames[i]);
798 if (strcmp(ExName,SymbolName) == 0)
800 Ordinal = ExOrdinals[i];
801 Function = RVA(BaseAddress, ExFunctions[Ordinal]);
802 DPRINT("%x %x %x\n", Function, ExportDir, ExportDir + ExportDirSize);
803 if (((ULONG)Function >= (ULONG)ExportDir) &&
804 ((ULONG)Function < (ULONG)ExportDir + (ULONG)ExportDirSize))
806 DPRINT("Forward: %s\n", (PCHAR)Function);
807 Function = LdrFixupForward((PCHAR)Function);
812 DbgPrint("LdrGetExportByName(): failed to find %s\n",SymbolName);
817 /**********************************************************************
819 * LdrPerformRelocations
822 * Relocate a DLL's memory image.
833 static NTSTATUS LdrPerformRelocations (PIMAGE_NT_HEADERS NTHeaders,
836 USHORT NumberOfEntries;
842 PRELOCATION_DIRECTORY RelocationDir;
843 PRELOCATION_ENTRY RelocationBlock;
845 PIMAGE_DATA_DIRECTORY RelocationDDir;
848 PIMAGE_SECTION_HEADER Sections;
853 (PIMAGE_SECTION_HEADER)((PVOID)NTHeaders + sizeof(IMAGE_NT_HEADERS));
855 for (i = 0; i < NTHeaders->FileHeader.NumberOfSections; i++)
857 if (!(Sections[i].Characteristics & IMAGE_SECTION_NOLOAD))
861 (ULONG)(Sections[i].VirtualAddress + Sections[i].Misc.VirtualSize);
862 MaxExtend = max(MaxExtend, Extend);
867 &NTHeaders->OptionalHeader.DataDirectory[IMAGE_DIRECTORY_ENTRY_BASERELOC];
868 RelocationRVA = RelocationDDir->VirtualAddress;
873 (PRELOCATION_DIRECTORY)((PCHAR)ImageBase + RelocationRVA);
875 while (RelocationDir->SizeOfBlock)
877 if (RelocationDir->VirtualAddress > MaxExtend)
879 RelocationRVA += RelocationDir->SizeOfBlock;
881 (PRELOCATION_DIRECTORY) (ImageBase + RelocationRVA);
885 Delta32 = (ULONG)(ImageBase - NTHeaders->OptionalHeader.ImageBase);
887 (PRELOCATION_ENTRY) (RelocationRVA + ImageBase +
888 sizeof (RELOCATION_DIRECTORY));
890 RelocationDir->SizeOfBlock - sizeof (RELOCATION_DIRECTORY);
891 NumberOfEntries = NumberOfEntries / sizeof (RELOCATION_ENTRY);
893 Status = NtProtectVirtualMemory(NtCurrentProcess(),
895 RelocationDir->VirtualAddress,
899 if (!NT_SUCCESS(Status))
901 DPRINT1("Failed to unprotect relocation target.\n");
905 for (i = 0; i < NumberOfEntries; i++)
907 Offset = (RelocationBlock[i].TypeOffset & 0xfff);
908 Offset += (ULONG)(RelocationDir->VirtualAddress + ImageBase);
911 * What kind of relocations should we perform
912 * for the current entry?
914 switch (RelocationBlock[i].TypeOffset >> 12)
916 case TYPE_RELOC_ABSOLUTE:
919 case TYPE_RELOC_HIGH:
920 pValue16 = (PUSHORT)Offset;
921 *pValue16 += Delta32 >> 16;
925 pValue16 = (PUSHORT)Offset;
926 *pValue16 += Delta32 & 0xffff;
929 case TYPE_RELOC_HIGHLOW:
930 pValue32 = (PULONG)Offset;
931 *pValue32 += Delta32;
934 case TYPE_RELOC_HIGHADJ:
935 /* FIXME: do the highadjust fixup */
936 DPRINT("TYPE_RELOC_HIGHADJ fixup not implemented, sorry\n");
937 return(STATUS_UNSUCCESSFUL);
940 DPRINT("unexpected fixup type\n");
941 return STATUS_UNSUCCESSFUL;
945 Status = NtProtectVirtualMemory(NtCurrentProcess(),
947 RelocationDir->VirtualAddress,
951 if (!NT_SUCCESS(Status))
953 DPRINT1("Failed to protect relocation target.\n");
957 RelocationRVA += RelocationDir->SizeOfBlock;
959 (PRELOCATION_DIRECTORY) (ImageBase + RelocationRVA);
962 return STATUS_SUCCESS;
966 /**********************************************************************
971 * Compute the entry point for every symbol the DLL imports
972 * from other modules.
983 static NTSTATUS LdrFixupImports(PIMAGE_NT_HEADERS NTHeaders,
986 PIMAGE_IMPORT_MODULE_DIRECTORY ImportModuleDirectory;
992 DPRINT("LdrFixupImports(NTHeaders %x, ImageBase %x)\n", NTHeaders,
996 * Process each import module.
998 ImportModuleDirectory = (PIMAGE_IMPORT_MODULE_DIRECTORY)(
999 ImageBase + NTHeaders->OptionalHeader
1000 .DataDirectory[IMAGE_DIRECTORY_ENTRY_IMPORT]
1002 DPRINT("ImportModuleDirectory %x\n", ImportModuleDirectory);
1004 while (ImportModuleDirectory->dwRVAModuleName)
1006 PVOID * ImportAddressList;
1007 PULONG FunctionNameList;
1008 UNICODE_STRING DllName;
1014 DPRINT("ImportModule->Directory->dwRVAModuleName %s\n",
1015 (PCHAR)(ImageBase + ImportModuleDirectory->dwRVAModuleName));
1017 RtlCreateUnicodeStringFromAsciiz (&DllName,
1018 (PCHAR)(ImageBase + ImportModuleDirectory->dwRVAModuleName));
1020 Status = LdrGetDllHandle (0, 0, &DllName, &BaseAddress);
1021 if (!NT_SUCCESS(Status))
1023 Status = LdrLoadDll(NULL,
1027 RtlFreeUnicodeString (&DllName);
1028 if (!NT_SUCCESS(Status))
1030 DbgPrint("LdrFixupImports:failed to load %s\n"
1032 + ImportModuleDirectory->dwRVAModuleName));
1039 * Get the import address list.
1041 ImportAddressList = (PVOID *)(NTHeaders->OptionalHeader.ImageBase
1042 + ImportModuleDirectory->dwRVAFunctionAddressList);
1045 * Get the list of functions to import.
1047 if (ImportModuleDirectory->dwRVAFunctionNameList != 0)
1049 FunctionNameList = (PULONG) (
1051 + ImportModuleDirectory->dwRVAFunctionNameList
1058 + ImportModuleDirectory->dwRVAFunctionAddressList);
1062 * Get the size of IAT.
1065 while (FunctionNameList[IATSize] != 0L)
1071 * Unprotect the region we are about to write into.
1073 IATBase = (PVOID)ImportAddressList;
1074 Status = NtProtectVirtualMemory(NtCurrentProcess(),
1076 IATSize * sizeof(PVOID*),
1079 if (!NT_SUCCESS(Status))
1081 DbgPrint("LDR: Failed to unprotect IAT.\n");
1086 * Walk through function list and fixup addresses.
1088 while (*FunctionNameList != 0L)
1090 if ((*FunctionNameList) & 0x80000000)
1092 Ordinal = (*FunctionNameList) & 0x7fffffff;
1093 *ImportAddressList =
1094 LdrGetExportByOrdinal(BaseAddress,
1099 pName = (DWORD) (ImageBase + *FunctionNameList + 2);
1100 pHint = *(PWORD)(ImageBase + *FunctionNameList);
1102 *ImportAddressList =
1103 LdrGetExportByName(BaseAddress, (PUCHAR)pName, pHint);
1104 if ((*ImportAddressList) == NULL)
1106 DbgPrint("Failed to import %s\n", pName);
1107 return STATUS_UNSUCCESSFUL;
1110 ImportAddressList++;
1115 * Protect the region we are about to write into.
1117 Status = NtProtectVirtualMemory(NtCurrentProcess(),
1119 IATSize * sizeof(PVOID*),
1122 if (!NT_SUCCESS(Status))
1124 DbgPrint("LDR: Failed to protect IAT.\n");
1128 ImportModuleDirectory++;
1130 return STATUS_SUCCESS;
1134 /**********************************************************************
1139 * 1. Map the DLL's sections into memory.
1140 * 2. Relocate, if needed the DLL.
1141 * 3. Fixup any imported symbol.
1142 * 4. Compute the DLL's entry point.
1146 * Address at which the DLL's image
1150 * Handle of the section that contains
1154 * NULL on error; otherwise the entry point
1155 * to call for initializing the DLL.
1162 PEPFUNC LdrPEStartup (PVOID ImageBase,
1163 HANDLE SectionHandle,
1164 PLDR_MODULE* Module,
1168 PEPFUNC EntryPoint = NULL;
1169 PIMAGE_DOS_HEADER DosHeader;
1170 PIMAGE_NT_HEADERS NTHeaders;
1172 DPRINT("LdrPEStartup(ImageBase %x SectionHandle %x)\n",
1173 ImageBase, (ULONG)SectionHandle);
1176 * Overlay DOS and WNT headers structures
1177 * to the DLL's image.
1179 DosHeader = (PIMAGE_DOS_HEADER) ImageBase;
1180 NTHeaders = (PIMAGE_NT_HEADERS) (ImageBase + DosHeader->e_lfanew);
1183 * If the base address is different from the
1184 * one the DLL is actually loaded, perform any
1187 if (ImageBase != (PVOID) NTHeaders->OptionalHeader.ImageBase)
1189 DbgPrint("LDR: Performing relocations\n");
1190 Status = LdrPerformRelocations(NTHeaders, ImageBase);
1191 if (!NT_SUCCESS(Status))
1193 DbgPrint("LdrPerformRelocations() failed\n");
1200 *Module = LdrAddModuleEntry(ImageBase, NTHeaders, FullDosName);
1204 * If the DLL's imports symbols from other
1205 * modules, fixup the imported calls entry points.
1207 if (NTHeaders->OptionalHeader.DataDirectory[IMAGE_DIRECTORY_ENTRY_IMPORT]
1208 .VirtualAddress != 0)
1210 DPRINT("About to fixup imports\n");
1211 Status = LdrFixupImports(NTHeaders, ImageBase);
1212 if (!NT_SUCCESS(Status))
1214 DbgPrint("LdrFixupImports() failed\n");
1217 DPRINT("Fixup done\n");
1221 * Compute the DLL's entry point's address.
1223 DPRINT("ImageBase = %x\n",(ULONG)ImageBase);
1224 DPRINT("AddressOfEntryPoint = %x\n",(ULONG)NTHeaders->OptionalHeader.AddressOfEntryPoint);
1225 if (NTHeaders->OptionalHeader.AddressOfEntryPoint != 0)
1227 EntryPoint = (PEPFUNC) (ImageBase
1228 + NTHeaders->OptionalHeader.AddressOfEntryPoint);
1230 DPRINT("LdrPEStartup() = %x\n",EntryPoint);
1236 LdrUnloadDll (IN PVOID BaseAddress)
1238 PIMAGE_NT_HEADERS NtHeaders;
1239 PDLLMAIN_FUNC Entrypoint;
1240 PLIST_ENTRY ModuleListHead;
1245 if (BaseAddress == NULL)
1246 return STATUS_SUCCESS;
1248 ModuleListHead = &NtCurrentPeb()->Ldr->InLoadOrderModuleList;
1249 Entry = ModuleListHead->Flink;
1251 while (Entry != ModuleListHead)
1253 Module = CONTAINING_RECORD(Entry, LDR_MODULE, InLoadOrderModuleList);
1254 if (Module->BaseAddress == BaseAddress)
1256 if (Module->LoadCount == -1)
1258 /* never unload this dll */
1259 return STATUS_SUCCESS;
1261 else if (Module->LoadCount > 1)
1263 Module->LoadCount--;
1264 return STATUS_SUCCESS;
1267 NtHeaders = RtlImageNtHeader (Module->BaseAddress);
1268 if ((NtHeaders->FileHeader.Characteristics & IMAGE_FILE_DLL) == IMAGE_FILE_DLL)
1270 if (Module->EntryPoint != 0)
1272 Entrypoint = (PDLLMAIN_FUNC)Module->EntryPoint;
1273 DPRINT("Calling entry point at 0x%08x\n", Entrypoint);
1274 Entrypoint(Module->BaseAddress,
1280 DPRINT("NTDLL.LDR: Entrypoint is NULL for \n");
1283 Status = ZwUnmapViewOfSection (NtCurrentProcess (),
1284 Module->BaseAddress);
1285 ZwClose (Module->SectionHandle);
1287 /* remove the module entry from the list */
1288 RtlFreeUnicodeString (&Module->FullDllName);
1289 RtlFreeUnicodeString (&Module->BaseDllName);
1290 RemoveEntryList (Entry);
1291 RtlFreeHeap (RtlGetProcessHeap (), 0, Module);
1296 Entry = Entry->Flink;
1299 DPRINT("NTDLL.LDR: Dll not found\n")
1301 return STATUS_UNSUCCESSFUL;
1306 LdrFindResource_U(PVOID BaseAddress,
1307 PLDR_RESOURCE_INFO ResourceInfo,
1309 PIMAGE_RESOURCE_DATA_ENTRY *ResourceDataEntry)
1311 PIMAGE_RESOURCE_DIRECTORY ResDir;
1312 PIMAGE_RESOURCE_DIRECTORY ResBase;
1313 PIMAGE_RESOURCE_DIRECTORY_ENTRY ResEntry;
1314 NTSTATUS Status = STATUS_SUCCESS;
1320 DPRINT ("LdrFindResource_U()\n");
1322 /* Get the pointer to the resource directory */
1323 ResDir = (PIMAGE_RESOURCE_DIRECTORY)
1324 RtlImageDirectoryEntryToData (BaseAddress,
1326 IMAGE_DIRECTORY_ENTRY_RESOURCE,
1330 return STATUS_RESOURCE_DATA_NOT_FOUND;
1333 DPRINT("ResourceDirectory: %x\n", (ULONG)ResDir);
1337 /* Let's go into resource tree */
1338 for (i = 0; i < Level; i++)
1340 DPRINT("ResDir: %x\n", (ULONG)ResDir);
1341 Id = ((PULONG)ResourceInfo)[i];
1342 EntryCount = ResDir->NumberOfNamedEntries;
1343 ResEntry = (PIMAGE_RESOURCE_DIRECTORY_ENTRY)(ResDir + 1);
1344 DPRINT("ResEntry %x\n", (ULONG)ResEntry);
1345 if (Id & 0xFFFF0000)
1347 /* Resource name is a unicode string */
1348 for (; EntryCount--; ResEntry++)
1350 /* Scan entries for equal name */
1351 if (ResEntry->Name & 0x80000000)
1353 ws = (PWCHAR)((ULONG)ResDir + (ResEntry->Name & 0x7FFFFFFF));
1354 if (!wcsncmp((PWCHAR)Id, ws + 1, *ws ) &&
1355 wcslen((PWCHAR)Id) == (int)*ws )
1364 /* We use ID number instead of string */
1365 ResEntry += EntryCount;
1366 EntryCount = ResDir->NumberOfIdEntries;
1367 for (; EntryCount--; ResEntry++)
1369 /* Scan entries for equal name */
1370 if (ResEntry->Name == Id)
1372 DPRINT("ID entry found %x\n", Id);
1377 DPRINT("Error %lu\n", i);
1382 return STATUS_RESOURCE_TYPE_NOT_FOUND;
1385 return STATUS_RESOURCE_NAME_NOT_FOUND;
1388 if (ResDir->NumberOfNamedEntries || ResDir->NumberOfIdEntries)
1390 /* Use the first available language */
1391 ResEntry = (IMAGE_RESOURCE_DIRECTORY_ENTRY*)(ResDir + 1);
1394 return STATUS_RESOURCE_LANG_NOT_FOUND;
1397 return STATUS_RESOURCE_DATA_NOT_FOUND;
1400 return STATUS_INVALID_PARAMETER;
1403 ResDir = (PIMAGE_RESOURCE_DIRECTORY)((ULONG)ResBase +
1404 (ResEntry->OffsetToData & 0x7FFFFFFF));
1406 DPRINT("ResourceDataEntry: %x\n", (ULONG)ResDir);
1408 if (ResourceDataEntry)
1410 *ResourceDataEntry = (PVOID)ResDir;
1418 LdrAccessResource(IN PVOID BaseAddress,
1419 IN PIMAGE_RESOURCE_DATA_ENTRY ResourceDataEntry,
1420 OUT PVOID *Resource OPTIONAL,
1421 OUT PULONG Size OPTIONAL)
1423 PIMAGE_SECTION_HEADER Section;
1424 PIMAGE_NT_HEADERS NtHeader;
1431 Data = (ULONG)RtlImageDirectoryEntryToData (BaseAddress,
1433 IMAGE_DIRECTORY_ENTRY_RESOURCE,
1436 return STATUS_RESOURCE_DATA_NOT_FOUND;
1438 if ((ULONG)BaseAddress & 1)
1440 /* loaded as ordinary file */
1441 NtHeader = RtlImageNtHeader((PVOID)((ULONG)BaseAddress & ~1UL));
1442 Offset = (ULONG)BaseAddress - Data + NtHeader->OptionalHeader.DataDirectory[IMAGE_DIRECTORY_ENTRY_RESOURCE].VirtualAddress;
1443 Section = RtlImageRvaToSection (NtHeader, BaseAddress, NtHeader->OptionalHeader.DataDirectory[IMAGE_DIRECTORY_ENTRY_RESOURCE].VirtualAddress);
1444 if (Section == NULL)
1446 return STATUS_RESOURCE_DATA_NOT_FOUND;
1449 if (Section->Misc.VirtualSize < ResourceDataEntry->OffsetToData)
1451 SectionRva = RtlImageRvaToSection (NtHeader, BaseAddress, ResourceDataEntry->OffsetToData)->VirtualAddress;
1452 SectionVa = RtlImageRvaToVa(NtHeader, BaseAddress, SectionRva, NULL);
1453 Offset = SectionRva - SectionVa + Data - Section->VirtualAddress;
1459 *Resource = (PVOID)(ResourceDataEntry->OffsetToData - Offset + (ULONG)BaseAddress);
1464 *Size = ResourceDataEntry->Size;
1467 return STATUS_SUCCESS;
1472 LdrDisableThreadCalloutsForDll (IN PVOID BaseAddress)
1474 PLIST_ENTRY ModuleListHead;
1479 DPRINT("LdrDisableThreadCalloutsForDll (BaseAddress %x)\n",
1482 Status = STATUS_DLL_NOT_FOUND;
1484 ModuleListHead = &NtCurrentPeb()->Ldr->InLoadOrderModuleList;
1485 Entry = ModuleListHead->Flink;
1487 while (Entry != ModuleListHead)
1489 Module = CONTAINING_RECORD(Entry, LDR_MODULE, InLoadOrderModuleList);
1491 DPRINT("BaseDllName %wZ BaseAddress %x\n",
1492 &Module->BaseDllName,
1493 Module->BaseAddress);
1495 if (Module->BaseAddress == BaseAddress)
1497 if (Module->TlsIndex == 0)
1499 Module->Flags |= 0x00040000;
1500 Status = STATUS_SUCCESS;
1505 Entry = Entry->Flink;
1513 LdrFindResourceDirectory_U (IN PVOID BaseAddress,
1518 PIMAGE_RESOURCE_DIRECTORY ResDir;
1519 PIMAGE_RESOURCE_DIRECTORY_ENTRY ResEntry;
1522 NTSTATUS Status = STATUS_SUCCESS;
1525 /* Get the pointer to the resource directory */
1526 ResDir = (PIMAGE_RESOURCE_DIRECTORY)
1527 RtlImageDirectoryEntryToData (BaseAddress,
1529 IMAGE_DIRECTORY_ENTRY_RESOURCE,
1533 return STATUS_RESOURCE_DATA_NOT_FOUND;
1536 /* Let's go into resource tree */
1537 for (i = 0; i < level; i++, name++)
1539 EntryCount = ResDir->NumberOfNamedEntries;
1540 ResEntry = (PIMAGE_RESOURCE_DIRECTORY_ENTRY)(ResDir + 1);
1541 if ((ULONG)(*name) & 0xFFFF0000)
1543 /* Resource name is a unicode string */
1544 for (; EntryCount--; ResEntry++)
1546 /* Scan entries for equal name */
1547 if (ResEntry->Name & 0x80000000)
1549 ws = (WCHAR*)((ULONG)ResDir + (ResEntry->Name & 0x7FFFFFFF));
1550 if (!wcsncmp( *name, ws + 1, *ws ) && wcslen( *name ) == (int)*ws )
1559 /* We use ID number instead of string */
1560 ResEntry += EntryCount;
1561 EntryCount = ResDir->NumberOfIdEntries;
1562 for (; EntryCount--; ResEntry++)
1564 /* Scan entries for equal name */
1565 if (ResEntry->Name == (ULONG)(*name))
1573 return STATUS_RESOURCE_TYPE_NOT_FOUND;
1576 return STATUS_RESOURCE_NAME_NOT_FOUND;
1579 Status = STATUS_RESOURCE_LANG_NOT_FOUND;
1580 /* Just use first language entry */
1581 if (ResDir->NumberOfNamedEntries || ResDir->NumberOfIdEntries)
1583 ResEntry = (IMAGE_RESOURCE_DIRECTORY_ENTRY*)(ResDir + 1);
1589 return STATUS_RESOURCE_DATA_NOT_FOUND;
1592 return STATUS_INVALID_PARAMETER;
1595 ResDir = (PIMAGE_RESOURCE_DIRECTORY)((ULONG)ResDir + ResEntry->OffsetToData);
1600 *addr = (PVOID)ResDir;
1608 LdrGetDllHandle (IN ULONG Unknown1,
1610 IN PUNICODE_STRING DllName,
1611 OUT PVOID *BaseAddress)
1613 UNICODE_STRING FullDllName;
1614 PLIST_ENTRY ModuleListHead;
1618 DPRINT("LdrGetDllHandle (Unknown1 %x Unknown2 %x DllName %wZ BaseAddress %p)\n",
1619 Unknown1, Unknown2, DllName, BaseAddress);
1621 /* NULL is the current executable */
1622 if ( DllName == NULL )
1624 *BaseAddress = NtCurrentPeb()->ImageBaseAddress;
1625 DPRINT("BaseAddress %x\n", *BaseAddress);
1626 return STATUS_SUCCESS;
1629 LdrAdjustDllName (&FullDllName,
1633 DPRINT("FullDllName %wZ\n",
1636 ModuleListHead = &NtCurrentPeb()->Ldr->InLoadOrderModuleList;
1637 Entry = ModuleListHead->Flink;
1639 while (Entry != ModuleListHead)
1641 Module = CONTAINING_RECORD(Entry, LDR_MODULE, InLoadOrderModuleList);
1643 DPRINT("EntryPoint %x\n", Module->EntryPoint);
1644 DPRINT("Comparing %wZ and %wZ\n",
1645 &Module->BaseDllName,
1648 if (!RtlCompareUnicodeString(&Module->BaseDllName, &FullDllName, TRUE))
1650 RtlFreeUnicodeString (&FullDllName);
1651 *BaseAddress = Module->BaseAddress;
1652 DPRINT("BaseAddress %x\n", *BaseAddress);
1653 return STATUS_SUCCESS;
1656 Entry = Entry->Flink;
1659 DPRINT("Failed to find dll %wZ\n", &FullDllName);
1660 RtlFreeUnicodeString (&FullDllName);
1661 *BaseAddress = NULL;
1662 return STATUS_DLL_NOT_FOUND;
1667 LdrGetProcedureAddress (IN PVOID BaseAddress,
1668 IN PANSI_STRING Name,
1670 OUT PVOID *ProcedureAddress)
1672 PIMAGE_EXPORT_DIRECTORY ExportDir;
1678 DPRINT("LdrGetProcedureAddress (BaseAddress %x Name %Z Ordinal %lu ProcedureAddress %x)\n",
1679 BaseAddress, Name, Ordinal, ProcedureAddress);
1681 /* Get the pointer to the export directory */
1682 ExportDir = (PIMAGE_EXPORT_DIRECTORY)
1683 RtlImageDirectoryEntryToData (BaseAddress,
1685 IMAGE_DIRECTORY_ENTRY_EXPORT,
1688 DPRINT("ExportDir %x i %lu\n", ExportDir, i);
1690 if (!ExportDir || !i || !ProcedureAddress)
1692 return STATUS_INVALID_PARAMETER;
1695 AddressPtr = (PULONG)((ULONG)BaseAddress + (ULONG)ExportDir->AddressOfFunctions);
1696 if (Name && Name->Length)
1699 OrdinalPtr = (PUSHORT)((ULONG)BaseAddress + (ULONG)ExportDir->AddressOfNameOrdinals);
1700 NamePtr = (PULONG)((ULONG)BaseAddress + (ULONG)ExportDir->AddressOfNames);
1701 for( i = 0; i < ExportDir->NumberOfNames; i++, NamePtr++, OrdinalPtr++)
1703 if (!_strnicmp(Name->Buffer, (char*)(BaseAddress + *NamePtr), Name->Length))
1705 *ProcedureAddress = (PVOID)((ULONG)BaseAddress + (ULONG)AddressPtr[*OrdinalPtr]);
1706 return STATUS_SUCCESS;
1709 DbgPrint("LdrGetProcedureAddress: Can't resolve symbol '%Z'\n", Name);
1714 Ordinal &= 0x0000FFFF;
1715 if (Ordinal - ExportDir->Base < ExportDir->NumberOfFunctions)
1717 *ProcedureAddress = (PVOID)((ULONG)BaseAddress + (ULONG)AddressPtr[Ordinal - ExportDir->Base]);
1718 return STATUS_SUCCESS;
1720 DbgPrint("LdrGetProcedureAddress: Can't resolve symbol @%d\n", Ordinal);
1723 return STATUS_PROCEDURE_NOT_FOUND;
1728 LdrShutdownProcess (VOID)
1730 PLIST_ENTRY ModuleListHead;
1734 DPRINT("LdrShutdownProcess() called\n");
1736 RtlEnterCriticalSection (NtCurrentPeb()->LoaderLock);
1738 ModuleListHead = &NtCurrentPeb()->Ldr->InInitializationOrderModuleList;
1739 Entry = ModuleListHead->Blink;
1741 while (Entry != ModuleListHead)
1743 Module = CONTAINING_RECORD(Entry, LDR_MODULE, InInitializationOrderModuleList);
1745 DPRINT(" Unloading %S\n",
1746 &Module->BaseDllName);
1747 // PJS: only detach from static dlls, they should FreeLibrary() any dlls that
1748 // they loaded dynamically, and when the last reference is gone, that lib will
1750 if (Module->EntryPoint != 0 && Module->LoadCount == -1)
1752 PDLLMAIN_FUNC Entrypoint = (PDLLMAIN_FUNC)Module->EntryPoint;
1754 DPRINT("Calling entry point at 0x%08x\n", Entrypoint);
1755 Entrypoint (Module->BaseAddress,
1760 Entry = Entry->Blink;
1763 RtlLeaveCriticalSection (NtCurrentPeb()->LoaderLock);
1765 DPRINT("LdrShutdownProcess() done\n");
1767 return STATUS_SUCCESS;
1772 LdrShutdownThread (VOID)
1774 PLIST_ENTRY ModuleListHead;
1778 DPRINT("LdrShutdownThread() called\n");
1780 RtlEnterCriticalSection (NtCurrentPeb()->LoaderLock);
1782 ModuleListHead = &NtCurrentPeb()->Ldr->InInitializationOrderModuleList;
1783 Entry = ModuleListHead->Blink;
1785 while (Entry != ModuleListHead)
1787 Module = CONTAINING_RECORD(Entry, LDR_MODULE, InInitializationOrderModuleList);
1789 DPRINT(" Unloading %wZ\n",
1790 &Module->BaseDllName);
1792 if (Module->EntryPoint != 0)
1794 PDLLMAIN_FUNC Entrypoint = (PDLLMAIN_FUNC)Module->EntryPoint;
1796 DPRINT("Calling entry point at 0x%08x\n", Entrypoint);
1797 Entrypoint (Module->BaseAddress,
1802 Entry = Entry->Blink;
1805 RtlLeaveCriticalSection (NtCurrentPeb()->LoaderLock);
1807 DPRINT("LdrShutdownThread() done\n");
1809 return STATUS_SUCCESS;
1813 /***************************************************************************
1815 * LdrQueryProcessModuleInformation
1828 LdrQueryProcessModuleInformation(IN PMODULE_INFORMATION ModuleInformation OPTIONAL,
1829 IN ULONG Size OPTIONAL,
1830 OUT PULONG ReturnedSize)
1833 PLIST_ENTRY ModuleListHead;
1836 PMODULE_ENTRY ModulePtr = NULL;
1837 NTSTATUS Status = STATUS_SUCCESS;
1838 ULONG UsedSize = sizeof(ULONG);
1839 ANSI_STRING AnsiString;
1842 DPRINT("LdrQueryProcessModuleInformation() called\n");
1844 RtlEnterCriticalSection (NtCurrentPeb()->LoaderLock);
1846 if (ModuleInformation == NULL || Size == 0)
1848 Status = STATUS_INFO_LENGTH_MISMATCH;
1852 ModuleInformation->ModuleCount = 0;
1853 ModulePtr = &ModuleInformation->ModuleEntry[0];
1854 Status = STATUS_SUCCESS;
1857 ModuleListHead = &NtCurrentPeb()->Ldr->InLoadOrderModuleList;
1858 Entry = ModuleListHead->Flink;
1860 while (Entry != ModuleListHead)
1862 Module = CONTAINING_RECORD(Entry, LDR_MODULE, InLoadOrderModuleList);
1864 DPRINT(" Module %wZ\n",
1865 &Module->FullDllName);
1867 if (UsedSize > Size)
1869 Status = STATUS_INFO_LENGTH_MISMATCH;
1871 else if (ModuleInformation != NULL)
1873 ModulePtr->Unknown0 = 0; // FIXME: ??
1874 ModulePtr->Unknown1 = 0; // FIXME: ??
1875 ModulePtr->BaseAddress = Module->BaseAddress;
1876 ModulePtr->SizeOfImage = Module->SizeOfImage;
1877 ModulePtr->Flags = Module->Flags;
1878 ModulePtr->Unknown2 = 0; // FIXME: load order index ??
1879 ModulePtr->Unknown3 = 0; // FIXME: ??
1880 ModulePtr->LoadCount = Module->LoadCount;
1882 AnsiString.Length = 0;
1883 AnsiString.MaximumLength = 256;
1884 AnsiString.Buffer = ModulePtr->ModuleName;
1885 RtlUnicodeStringToAnsiString(&AnsiString,
1886 &Module->FullDllName,
1888 p = strrchr(ModulePtr->ModuleName, '\\');
1890 ModulePtr->PathLength = p - ModulePtr->ModuleName + 1;
1892 ModulePtr->PathLength = 0;
1895 ModuleInformation->ModuleCount++;
1897 UsedSize += sizeof(MODULE_ENTRY);
1899 Entry = Entry->Flink;
1902 RtlLeaveCriticalSection (NtCurrentPeb()->LoaderLock);
1904 if (ReturnedSize != 0)
1905 *ReturnedSize = UsedSize;
1907 DPRINT("LdrQueryProcessModuleInformation() done\n");