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)
14 * - Handle loading flags correctly
15 * - Handle errors correctly (unload dll's)
16 * - Implement a faster way to find modules (hash table)
20 /* INCLUDES *****************************************************************/
26 #define LDRP_PROCESS_CREATION_TIME 0x8000000
28 /* GLOBALS *******************************************************************/
32 #define TRACE_LDR(args...) if (RtlGetNtGlobalFlags() & FLG_SHOW_LDR_SNAPS) { DbgPrint("(LDR:%s:%d) ",__FILE__,__LINE__); DbgPrint(args); }
36 #define TRACE_LDR(args...) do { DbgPrint("(LDR:%s:%d) ",__FILE__,__LINE__); DbgPrint(args); } while(0)
39 typedef struct _TLS_DATA
41 PVOID StartAddressOfRawData
;
44 PIMAGE_TLS_CALLBACK TlsAddressOfCallBacks
;
45 PLDR_DATA_TABLE_ENTRY Module
;
46 } TLS_DATA
, *PTLS_DATA
;
48 static PTLS_DATA LdrpTlsArray
= NULL
;
49 static ULONG LdrpTlsCount
= 0;
50 static ULONG LdrpTlsSize
= 0;
51 static HANDLE LdrpKnownDllsDirHandle
= NULL
;
52 static UNICODE_STRING LdrpKnownDllPath
= {0, 0, NULL
};
53 static PLDR_DATA_TABLE_ENTRY LdrpLastModule
= NULL
;
54 extern PLDR_DATA_TABLE_ENTRY ExeModule
;
56 /* PROTOTYPES ****************************************************************/
58 static NTSTATUS
LdrFindEntryForName(PUNICODE_STRING Name
, PLDR_DATA_TABLE_ENTRY
*Module
, BOOLEAN Ref
);
59 static PVOID
LdrFixupForward(PCHAR ForwardName
);
60 static PVOID
LdrGetExportByName(PVOID BaseAddress
, PUCHAR SymbolName
, USHORT Hint
);
61 static NTSTATUS
LdrpLoadModule(IN PWSTR SearchPath OPTIONAL
,
63 IN PUNICODE_STRING Name
,
64 OUT PLDR_DATA_TABLE_ENTRY
*Module
,
65 OUT PVOID
*BaseAddress OPTIONAL
);
66 static NTSTATUS
LdrpAttachProcess(VOID
);
67 static VOID
LdrpDetachProcess(BOOLEAN UnloadAll
);
69 /* FUNCTIONS *****************************************************************/
71 #if defined(DBG) || defined(KDBG)
74 LdrpLoadUserModuleSymbols(PLDR_DATA_TABLE_ENTRY LdrModule
)
85 #endif /* DBG || KDBG */
88 LdrMappedAsDataFile(PVOID
*BaseAddress
)
90 if (0 != ((DWORD_PTR
) *BaseAddress
& (PAGE_SIZE
- 1)))
92 *BaseAddress
= (PVOID
) ((DWORD_PTR
) *BaseAddress
& ~ ((DWORD_PTR
) PAGE_SIZE
- 1));
99 static __inline LONG
LdrpDecrementLoadCount(PLDR_DATA_TABLE_ENTRY Module
, BOOLEAN Locked
)
104 RtlEnterCriticalSection (NtCurrentPeb()->LoaderLock
);
106 LoadCount
= Module
->LoadCount
;
107 if (Module
->LoadCount
> 0 && Module
->LoadCount
!= 0xFFFF)
113 RtlLeaveCriticalSection(NtCurrentPeb()->LoaderLock
);
118 static __inline LONG
LdrpIncrementLoadCount(PLDR_DATA_TABLE_ENTRY Module
, BOOLEAN Locked
)
123 RtlEnterCriticalSection (NtCurrentPeb()->LoaderLock
);
125 LoadCount
= Module
->LoadCount
;
126 if (Module
->LoadCount
!= 0xFFFF)
132 RtlLeaveCriticalSection(NtCurrentPeb()->LoaderLock
);
137 static __inline VOID
LdrpAcquireTlsSlot(PLDR_DATA_TABLE_ENTRY Module
, ULONG Size
, BOOLEAN Locked
)
141 RtlEnterCriticalSection (NtCurrentPeb()->LoaderLock
);
143 Module
->TlsIndex
= (SHORT
)LdrpTlsCount
;
148 RtlLeaveCriticalSection(NtCurrentPeb()->LoaderLock
);
152 static __inline VOID
LdrpTlsCallback(PLDR_DATA_TABLE_ENTRY Module
, ULONG dwReason
)
154 PIMAGE_TLS_CALLBACK TlsCallback
;
155 if (Module
->TlsIndex
!= 0xFFFF && Module
->LoadCount
== 0xFFFF)
157 TlsCallback
= LdrpTlsArray
[Module
->TlsIndex
].TlsAddressOfCallBacks
;
162 TRACE_LDR("%wZ - Calling tls callback at %x\n",
163 &Module
->BaseDllName
, TlsCallback
);
164 TlsCallback(Module
->DllBase
, dwReason
, NULL
);
165 TlsCallback
= (PIMAGE_TLS_CALLBACK
)((ULONG_PTR
)TlsCallback
+ sizeof(PVOID
));
171 static BOOLEAN
LdrpCallDllEntry(PLDR_DATA_TABLE_ENTRY Module
, DWORD dwReason
, PVOID lpReserved
)
173 if (!(Module
->Flags
& LDRP_IMAGE_DLL
) ||
174 Module
->EntryPoint
== 0)
178 LdrpTlsCallback(Module
, dwReason
);
179 return ((PDLLMAIN_FUNC
)Module
->EntryPoint
)(Module
->DllBase
, dwReason
, lpReserved
);
183 LdrpInitializeTlsForThread(VOID
)
189 PTEB Teb
= NtCurrentTeb();
191 DPRINT("LdrpInitializeTlsForThread() called for %wZ\n", &ExeModule
->BaseDllName
);
193 Teb
->StaticUnicodeString
.Length
= 0;
194 Teb
->StaticUnicodeString
.MaximumLength
= sizeof(Teb
->StaticUnicodeBuffer
);
195 Teb
->StaticUnicodeString
.Buffer
= Teb
->StaticUnicodeBuffer
;
197 if (LdrpTlsCount
> 0)
199 TlsPointers
= RtlAllocateHeap(RtlGetProcessHeap(),
201 LdrpTlsCount
* sizeof(PVOID
) + LdrpTlsSize
);
202 if (TlsPointers
== NULL
)
204 DPRINT1("failed to allocate thread tls data\n");
205 return STATUS_NO_MEMORY
;
208 TlsData
= (PVOID
)((ULONG_PTR
)TlsPointers
+ LdrpTlsCount
* sizeof(PVOID
));
209 Teb
->ThreadLocalStoragePointer
= TlsPointers
;
211 TlsInfo
= LdrpTlsArray
;
212 for (i
= 0; i
< LdrpTlsCount
; i
++, TlsInfo
++)
214 TRACE_LDR("Initialize tls data for %wZ\n", &TlsInfo
->Module
->BaseDllName
);
215 TlsPointers
[i
] = TlsData
;
216 if (TlsInfo
->TlsDataSize
)
218 memcpy(TlsData
, TlsInfo
->StartAddressOfRawData
, TlsInfo
->TlsDataSize
);
219 TlsData
= (PVOID
)((ULONG_PTR
)TlsData
+ TlsInfo
->TlsDataSize
);
221 if (TlsInfo
->TlsZeroSize
)
223 memset(TlsData
, 0, TlsInfo
->TlsZeroSize
);
224 TlsData
= (PVOID
)((ULONG_PTR
)TlsData
+ TlsInfo
->TlsZeroSize
);
228 DPRINT("LdrpInitializeTlsForThread() done\n");
229 return STATUS_SUCCESS
;
233 LdrpInitializeTlsForProccess(VOID
)
235 PLIST_ENTRY ModuleListHead
;
237 PLDR_DATA_TABLE_ENTRY Module
;
238 PIMAGE_TLS_DIRECTORY TlsDirectory
;
242 DPRINT("LdrpInitializeTlsForProccess() called for %wZ\n", &ExeModule
->BaseDllName
);
244 if (LdrpTlsCount
> 0)
246 LdrpTlsArray
= RtlAllocateHeap(RtlGetProcessHeap(),
248 LdrpTlsCount
* sizeof(TLS_DATA
));
249 if (LdrpTlsArray
== NULL
)
251 DPRINT1("Failed to allocate global tls data\n");
252 return STATUS_NO_MEMORY
;
255 ModuleListHead
= &NtCurrentPeb()->Ldr
->InLoadOrderModuleList
;
256 Entry
= ModuleListHead
->Flink
;
257 while (Entry
!= ModuleListHead
)
259 Module
= CONTAINING_RECORD(Entry
, LDR_DATA_TABLE_ENTRY
, InLoadOrderModuleList
);
260 if (Module
->LoadCount
== 0xFFFF &&
261 Module
->TlsIndex
!= 0xFFFF)
263 TlsDirectory
= (PIMAGE_TLS_DIRECTORY
)
264 RtlImageDirectoryEntryToData(Module
->DllBase
,
266 IMAGE_DIRECTORY_ENTRY_TLS
,
268 ASSERT(Module
->TlsIndex
< LdrpTlsCount
);
269 TlsData
= &LdrpTlsArray
[Module
->TlsIndex
];
270 TlsData
->StartAddressOfRawData
= (PVOID
)TlsDirectory
->StartAddressOfRawData
;
271 TlsData
->TlsDataSize
= TlsDirectory
->EndAddressOfRawData
- TlsDirectory
->StartAddressOfRawData
;
272 TlsData
->TlsZeroSize
= TlsDirectory
->SizeOfZeroFill
;
273 if (TlsDirectory
->AddressOfCallBacks
)
274 TlsData
->TlsAddressOfCallBacks
= *(PIMAGE_TLS_CALLBACK
*)TlsDirectory
->AddressOfCallBacks
;
276 TlsData
->TlsAddressOfCallBacks
= NULL
;
277 TlsData
->Module
= Module
;
279 DbgPrint("TLS directory for %wZ\n", &Module
->BaseDllName
);
280 DbgPrint("StartAddressOfRawData: %x\n", TlsDirectory
->StartAddressOfRawData
);
281 DbgPrint("EndAddressOfRawData: %x\n", TlsDirectory
->EndAddressOfRawData
);
282 DbgPrint("SizeOfRawData: %d\n", TlsDirectory
->EndAddressOfRawData
- TlsDirectory
->StartAddressOfRawData
);
283 DbgPrint("AddressOfIndex: %x\n", TlsDirectory
->AddressOfIndex
);
284 DbgPrint("AddressOfCallBacks: %x (%x)\n", TlsDirectory
->AddressOfCallBacks
, *TlsDirectory
->AddressOfCallBacks
);
285 DbgPrint("SizeOfZeroFill: %d\n", TlsDirectory
->SizeOfZeroFill
);
286 DbgPrint("Characteristics: %x\n", TlsDirectory
->Characteristics
);
290 * Is this region allways writable ?
292 *(PULONG
)TlsDirectory
->AddressOfIndex
= Module
->TlsIndex
;
294 Entry
= Entry
->Flink
;
297 DPRINT("LdrpInitializeTlsForProccess() done\n");
298 return STATUS_SUCCESS
;
304 OBJECT_ATTRIBUTES ObjectAttributes
;
305 UNICODE_STRING LinkTarget
;
311 DPRINT("LdrpInitLoader() called for %wZ\n", &ExeModule
->BaseDllName
);
313 /* Get handle to the 'KnownDlls' directory */
314 RtlInitUnicodeString(&Name
,
316 InitializeObjectAttributes(&ObjectAttributes
,
318 OBJ_CASE_INSENSITIVE
,
321 Status
= NtOpenDirectoryObject(&LdrpKnownDllsDirHandle
,
322 DIRECTORY_QUERY
| DIRECTORY_TRAVERSE
,
324 if (!NT_SUCCESS(Status
))
326 DPRINT("NtOpenDirectoryObject() failed (Status %lx)\n", Status
);
327 LdrpKnownDllsDirHandle
= NULL
;
331 /* Allocate target name string */
332 LinkTarget
.Length
= 0;
333 LinkTarget
.MaximumLength
= MAX_PATH
* sizeof(WCHAR
);
334 LinkTarget
.Buffer
= RtlAllocateHeap(RtlGetProcessHeap(),
336 MAX_PATH
* sizeof(WCHAR
));
337 if (LinkTarget
.Buffer
== NULL
)
339 NtClose(LdrpKnownDllsDirHandle
);
340 LdrpKnownDllsDirHandle
= NULL
;
344 RtlInitUnicodeString(&Name
,
346 InitializeObjectAttributes(&ObjectAttributes
,
348 OBJ_CASE_INSENSITIVE
| OBJ_OPENLINK
,
349 LdrpKnownDllsDirHandle
,
351 Status
= NtOpenSymbolicLinkObject(&LinkHandle
,
352 SYMBOLIC_LINK_ALL_ACCESS
,
354 if (!NT_SUCCESS(Status
))
356 RtlFreeUnicodeString(&LinkTarget
);
357 NtClose(LdrpKnownDllsDirHandle
);
358 LdrpKnownDllsDirHandle
= NULL
;
362 Status
= NtQuerySymbolicLinkObject(LinkHandle
,
366 if (!NT_SUCCESS(Status
))
368 RtlFreeUnicodeString(&LinkTarget
);
369 NtClose(LdrpKnownDllsDirHandle
);
370 LdrpKnownDllsDirHandle
= NULL
;
373 RtlCreateUnicodeString(&LdrpKnownDllPath
,
376 RtlFreeUnicodeString(&LinkTarget
);
378 DPRINT("LdrpInitLoader() done\n");
382 /***************************************************************************
387 * Adjusts the name of a dll to a fully qualified name.
390 * FullDllName: Pointer to caller supplied storage for the fully
391 * qualified dll name.
392 * DllName: Pointer to the dll name.
393 * BaseName: TRUE: Only the file name is passed to FullDllName
394 * FALSE: The full path is preserved in FullDllName
402 * A given path is not affected by the adjustment, but the file
404 * ntdll --> ntdll.dll
406 * ntdll.xyz --> ntdll.xyz
409 LdrAdjustDllName (PUNICODE_STRING FullDllName
,
410 PUNICODE_STRING DllName
,
413 WCHAR Buffer
[MAX_PATH
];
418 Length
= DllName
->Length
/ sizeof(WCHAR
);
422 /* get the base dll name */
423 Pointer
= DllName
->Buffer
+ Length
;
430 while (Pointer
>= DllName
->Buffer
&& *Pointer
!= L
'\\' && *Pointer
!= L
'/');
433 Length
= Extension
- Pointer
;
434 memmove (Buffer
, Pointer
, Length
* sizeof(WCHAR
));
435 Buffer
[Length
] = L
'\0';
439 /* get the full dll name */
440 memmove (Buffer
, DllName
->Buffer
, DllName
->Length
);
441 Buffer
[DllName
->Length
/ sizeof(WCHAR
)] = L
'\0';
444 /* Build the DLL's absolute name */
445 Extension
= wcsrchr (Buffer
, L
'.');
446 if ((Extension
!= NULL
) && (*Extension
== L
'.'))
448 /* with extension - remove dot if it's the last character */
449 if (Buffer
[Length
- 1] == L
'.')
455 /* name without extension - assume that it is .dll */
456 memmove (Buffer
+ Length
, L
".dll", 10);
459 RtlCreateUnicodeString(FullDllName
, Buffer
);
462 PLDR_DATA_TABLE_ENTRY
463 LdrAddModuleEntry(PVOID ImageBase
,
464 PIMAGE_NT_HEADERS NTHeaders
,
467 PLDR_DATA_TABLE_ENTRY Module
;
469 Module
= RtlAllocateHeap(RtlGetProcessHeap(), 0, sizeof (LDR_DATA_TABLE_ENTRY
));
471 memset(Module
, 0, sizeof(LDR_DATA_TABLE_ENTRY
));
472 Module
->DllBase
= (PVOID
)ImageBase
;
473 Module
->EntryPoint
= (PVOID
)NTHeaders
->OptionalHeader
.AddressOfEntryPoint
;
474 if (Module
->EntryPoint
!= 0)
475 Module
->EntryPoint
= (PVOID
)((ULONG_PTR
)Module
->EntryPoint
+ (ULONG_PTR
)Module
->DllBase
);
476 Module
->SizeOfImage
= LdrpGetResidentSize(NTHeaders
);
477 if (NtCurrentPeb()->Ldr
->Initialized
== TRUE
)
479 /* loading while app is running */
480 Module
->LoadCount
= 1;
483 * loading while app is initializing
484 * dll must not be unloaded
486 Module
->LoadCount
= 0xFFFF;
490 Module
->TlsIndex
= -1;
491 Module
->CheckSum
= NTHeaders
->OptionalHeader
.CheckSum
;
492 Module
->TimeDateStamp
= NTHeaders
->FileHeader
.TimeDateStamp
;
494 RtlCreateUnicodeString (&Module
->FullDllName
,
496 RtlCreateUnicodeString (&Module
->BaseDllName
,
497 wcsrchr(FullDosName
, L
'\\') + 1);
498 DPRINT ("BaseDllName %wZ\n", &Module
->BaseDllName
);
500 RtlEnterCriticalSection (NtCurrentPeb()->LoaderLock
);
501 InsertTailList(&NtCurrentPeb()->Ldr
->InLoadOrderModuleList
,
502 &Module
->InLoadOrderModuleList
);
503 RtlLeaveCriticalSection(NtCurrentPeb()->LoaderLock
);
510 LdrpMapKnownDll(IN PUNICODE_STRING DllName
,
511 OUT PUNICODE_STRING FullDosName
,
512 OUT PHANDLE SectionHandle
)
514 OBJECT_ATTRIBUTES ObjectAttributes
;
517 DPRINT("LdrpMapKnownDll() called\n");
519 if (LdrpKnownDllsDirHandle
== NULL
)
521 DPRINT("Invalid 'KnownDlls' directory\n");
522 return STATUS_UNSUCCESSFUL
;
525 DPRINT("LdrpKnownDllPath '%wZ'\n", &LdrpKnownDllPath
);
527 InitializeObjectAttributes(&ObjectAttributes
,
529 OBJ_CASE_INSENSITIVE
,
530 LdrpKnownDllsDirHandle
,
532 Status
= NtOpenSection(SectionHandle
,
533 SECTION_MAP_READ
| SECTION_MAP_WRITE
| SECTION_MAP_EXECUTE
,
535 if (!NT_SUCCESS(Status
))
537 DPRINT("NtOpenSection() failed for '%wZ' (Status 0x%08lx)\n", DllName
, Status
);
541 FullDosName
->Length
= LdrpKnownDllPath
.Length
+ DllName
->Length
+ sizeof(WCHAR
);
542 FullDosName
->MaximumLength
= FullDosName
->Length
+ sizeof(WCHAR
);
543 FullDosName
->Buffer
= RtlAllocateHeap(RtlGetProcessHeap(),
545 FullDosName
->MaximumLength
);
546 if (FullDosName
->Buffer
== NULL
)
548 FullDosName
->Length
= 0;
549 FullDosName
->MaximumLength
= 0;
550 return STATUS_SUCCESS
;
553 wcscpy(FullDosName
->Buffer
, LdrpKnownDllPath
.Buffer
);
554 wcscat(FullDosName
->Buffer
, L
"\\");
555 wcscat(FullDosName
->Buffer
, DllName
->Buffer
);
557 DPRINT("FullDosName '%wZ'\n", FullDosName
);
559 DPRINT("LdrpMapKnownDll() done\n");
561 return STATUS_SUCCESS
;
566 LdrpMapDllImageFile(IN PWSTR SearchPath OPTIONAL
,
567 IN PUNICODE_STRING DllName
,
568 OUT PUNICODE_STRING FullDosName
,
569 IN BOOLEAN MapAsDataFile
,
570 OUT PHANDLE SectionHandle
)
572 WCHAR SearchPathBuffer
[MAX_PATH
];
573 WCHAR DosName
[MAX_PATH
];
574 UNICODE_STRING FullNtFileName
;
575 OBJECT_ATTRIBUTES FileObjectAttributes
;
577 char BlockBuffer
[1024];
578 PIMAGE_DOS_HEADER DosHeader
;
579 PIMAGE_NT_HEADERS NTHeaders
;
580 IO_STATUS_BLOCK IoStatusBlock
;
584 DPRINT("LdrpMapDllImageFile() called\n");
586 if (SearchPath
== NULL
)
588 /* get application running path */
590 wcscpy (SearchPathBuffer
, NtCurrentPeb()->ProcessParameters
->ImagePathName
.Buffer
);
592 len
= wcslen (SearchPathBuffer
);
594 while (len
&& SearchPathBuffer
[len
- 1] != L
'\\')
597 if (len
) SearchPathBuffer
[len
-1] = L
'\0';
599 wcscat (SearchPathBuffer
, L
";");
601 wcscat (SearchPathBuffer
, SharedUserData
->NtSystemRoot
);
602 wcscat (SearchPathBuffer
, L
"\\system32;");
603 wcscat (SearchPathBuffer
, SharedUserData
->NtSystemRoot
);
604 wcscat (SearchPathBuffer
, L
";.");
606 SearchPath
= SearchPathBuffer
;
609 if (RtlDosSearchPath_U (SearchPath
,
615 return STATUS_DLL_NOT_FOUND
;
618 if (!RtlDosPathNameToNtPathName_U (DosName
,
622 return STATUS_DLL_NOT_FOUND
;
624 DPRINT("FullNtFileName %wZ\n", &FullNtFileName
);
626 InitializeObjectAttributes(&FileObjectAttributes
,
632 DPRINT("Opening dll \"%wZ\"\n", &FullNtFileName
);
634 Status
= NtOpenFile(&FileHandle
,
635 GENERIC_READ
|SYNCHRONIZE
,
636 &FileObjectAttributes
,
639 FILE_SYNCHRONOUS_IO_NONALERT
);
640 if (!NT_SUCCESS(Status
))
642 DPRINT1("Dll open of %wZ failed: Status = 0x%08lx\n",
643 &FullNtFileName
, Status
);
644 RtlFreeUnicodeString (&FullNtFileName
);
647 RtlFreeUnicodeString (&FullNtFileName
);
649 Status
= NtReadFile(FileHandle
,
658 if (!NT_SUCCESS(Status
))
660 DPRINT("Dll header read failed: Status = 0x%08lx\n", Status
);
665 * Overlay DOS and NT headers structures to the
666 * buffer with DLL's header raw data.
668 DosHeader
= (PIMAGE_DOS_HEADER
) BlockBuffer
;
669 NTHeaders
= (PIMAGE_NT_HEADERS
) (BlockBuffer
+ DosHeader
->e_lfanew
);
671 * Check it is a PE image file.
673 if ((DosHeader
->e_magic
!= IMAGE_DOS_SIGNATURE
)
674 || (DosHeader
->e_lfanew
== 0L)
675 || (*(PULONG
)(NTHeaders
) != IMAGE_NT_SIGNATURE
))
677 DPRINT("NTDLL format invalid\n");
680 return STATUS_UNSUCCESSFUL
;
684 * Create a section for dll.
686 Status
= NtCreateSection(SectionHandle
,
691 SEC_COMMIT
| (MapAsDataFile
? 0 : SEC_IMAGE
),
695 if (!NT_SUCCESS(Status
))
697 DPRINT("NTDLL create section failed: Status = 0x%08lx\n", Status
);
701 RtlCreateUnicodeString(FullDosName
,
709 /***************************************************************************
726 LdrLoadDll (IN PWSTR SearchPath OPTIONAL
,
728 IN PUNICODE_STRING Name
,
729 OUT PVOID
*BaseAddress OPTIONAL
)
732 PLDR_DATA_TABLE_ENTRY Module
;
734 TRACE_LDR("LdrLoadDll, loading %wZ%s%S\n",
736 SearchPath
? " from " : "",
737 SearchPath
? SearchPath
: L
"");
741 *BaseAddress
= NtCurrentPeb()->ImageBaseAddress
;
742 return STATUS_SUCCESS
;
747 Status
= LdrpLoadModule(SearchPath
, LoadFlags
, Name
, &Module
, BaseAddress
);
748 if (NT_SUCCESS(Status
) && 0 == (LoadFlags
& LOAD_LIBRARY_AS_DATAFILE
))
750 RtlEnterCriticalSection(NtCurrentPeb()->LoaderLock
);
751 Status
= LdrpAttachProcess();
752 RtlLeaveCriticalSection(NtCurrentPeb()->LoaderLock
);
753 if (NT_SUCCESS(Status
))
755 *BaseAddress
= Module
->DllBase
;
762 /***************************************************************************
764 * LdrFindEntryForAddress
779 LdrFindEntryForAddress(PVOID Address
,
780 PLDR_DATA_TABLE_ENTRY
*Module
)
782 PLIST_ENTRY ModuleListHead
;
784 PLDR_DATA_TABLE_ENTRY ModulePtr
;
786 DPRINT("LdrFindEntryForAddress(Address %p)\n", Address
);
788 if (NtCurrentPeb()->Ldr
== NULL
)
789 return(STATUS_NO_MORE_ENTRIES
);
791 RtlEnterCriticalSection(NtCurrentPeb()->LoaderLock
);
792 ModuleListHead
= &NtCurrentPeb()->Ldr
->InLoadOrderModuleList
;
793 Entry
= ModuleListHead
->Flink
;
794 if (Entry
== ModuleListHead
)
796 RtlLeaveCriticalSection(NtCurrentPeb()->LoaderLock
);
797 return(STATUS_NO_MORE_ENTRIES
);
800 while (Entry
!= ModuleListHead
)
802 ModulePtr
= CONTAINING_RECORD(Entry
, LDR_DATA_TABLE_ENTRY
, InLoadOrderModuleList
);
804 DPRINT("Scanning %wZ at %p\n", &ModulePtr
->BaseDllName
, ModulePtr
->DllBase
);
806 if ((Address
>= ModulePtr
->DllBase
) &&
807 ((ULONG_PTR
)Address
<= ((ULONG_PTR
)ModulePtr
->DllBase
+ ModulePtr
->SizeOfImage
)))
810 RtlLeaveCriticalSection(NtCurrentPeb()->LoaderLock
);
811 return(STATUS_SUCCESS
);
814 Entry
= Entry
->Flink
;
817 DPRINT("Failed to find module entry.\n");
819 RtlLeaveCriticalSection(NtCurrentPeb()->LoaderLock
);
820 return(STATUS_NO_MORE_ENTRIES
);
824 /***************************************************************************
826 * LdrFindEntryForName
840 LdrFindEntryForName(PUNICODE_STRING Name
,
841 PLDR_DATA_TABLE_ENTRY
*Module
,
844 PLIST_ENTRY ModuleListHead
;
846 PLDR_DATA_TABLE_ENTRY ModulePtr
;
847 BOOLEAN ContainsPath
;
848 UNICODE_STRING AdjustedName
;
851 DPRINT("LdrFindEntryForName(Name %wZ)\n", Name
);
853 if (NtCurrentPeb()->Ldr
== NULL
)
854 return(STATUS_NO_MORE_ENTRIES
);
856 RtlEnterCriticalSection(NtCurrentPeb()->LoaderLock
);
857 ModuleListHead
= &NtCurrentPeb()->Ldr
->InLoadOrderModuleList
;
858 Entry
= ModuleListHead
->Flink
;
859 if (Entry
== ModuleListHead
)
861 RtlLeaveCriticalSection(NtCurrentPeb()->LoaderLock
);
862 return(STATUS_NO_MORE_ENTRIES
);
865 // NULL is the current process
869 RtlLeaveCriticalSection(NtCurrentPeb()->LoaderLock
);
870 return(STATUS_SUCCESS
);
873 LdrAdjustDllName (&AdjustedName
, Name
, FALSE
);
875 ContainsPath
= (AdjustedName
.Length
>= 2 * sizeof(WCHAR
) && L
':' == AdjustedName
.Buffer
[1]);
876 for (i
= 0; ! ContainsPath
&& i
< AdjustedName
.Length
/ sizeof(WCHAR
); i
++)
878 ContainsPath
= L
'\\' == AdjustedName
.Buffer
[i
] ||
879 L
'/' == AdjustedName
.Buffer
[i
];
884 if ((! ContainsPath
&&
885 0 == RtlCompareUnicodeString(&LdrpLastModule
->BaseDllName
, &AdjustedName
, TRUE
)) ||
887 0 == RtlCompareUnicodeString(&LdrpLastModule
->FullDllName
, &AdjustedName
, TRUE
)))
889 *Module
= LdrpLastModule
;
890 if (Ref
&& (*Module
)->LoadCount
!= 0xFFFF)
892 (*Module
)->LoadCount
++;
894 RtlLeaveCriticalSection(NtCurrentPeb()->LoaderLock
);
895 RtlFreeUnicodeString(&AdjustedName
);
896 return(STATUS_SUCCESS
);
899 while (Entry
!= ModuleListHead
)
901 ModulePtr
= CONTAINING_RECORD(Entry
, LDR_DATA_TABLE_ENTRY
, InLoadOrderModuleList
);
903 DPRINT("Scanning %wZ %wZ\n", &ModulePtr
->BaseDllName
, &AdjustedName
);
905 if ((! ContainsPath
&&
906 0 == RtlCompareUnicodeString(&ModulePtr
->BaseDllName
, &AdjustedName
, TRUE
)) ||
908 0 == RtlCompareUnicodeString(&ModulePtr
->FullDllName
, &AdjustedName
, TRUE
)))
910 *Module
= LdrpLastModule
= ModulePtr
;
911 if (Ref
&& ModulePtr
->LoadCount
!= 0xFFFF)
913 ModulePtr
->LoadCount
++;
915 RtlLeaveCriticalSection(NtCurrentPeb()->LoaderLock
);
916 RtlFreeUnicodeString(&AdjustedName
);
917 return(STATUS_SUCCESS
);
920 Entry
= Entry
->Flink
;
923 DPRINT("Failed to find dll %wZ\n", Name
);
924 RtlLeaveCriticalSection(NtCurrentPeb()->LoaderLock
);
925 RtlFreeUnicodeString(&AdjustedName
);
926 return(STATUS_NO_MORE_ENTRIES
);
929 /**********************************************************************
945 LdrFixupForward(PCHAR ForwardName
)
947 CHAR NameBuffer
[128];
948 UNICODE_STRING DllName
;
951 PLDR_DATA_TABLE_ENTRY Module
;
954 strcpy(NameBuffer
, ForwardName
);
955 p
= strchr(NameBuffer
, '.');
960 DPRINT("Dll: %s Function: %s\n", NameBuffer
, p
+1);
961 RtlCreateUnicodeStringFromAsciiz (&DllName
,
964 Status
= LdrFindEntryForName (&DllName
, &Module
, FALSE
);
966 * The caller (or the image) is responsible for loading of the dll, where the function is forwarded.
968 if (!NT_SUCCESS(Status
))
970 Status
= LdrLoadDll(NULL
,
971 LDRP_PROCESS_CREATION_TIME
,
974 if (NT_SUCCESS(Status
))
976 Status
= LdrFindEntryForName (&DllName
, &Module
, FALSE
);
979 RtlFreeUnicodeString (&DllName
);
980 if (!NT_SUCCESS(Status
))
982 DPRINT1("LdrFixupForward: failed to load %s\n", NameBuffer
);
986 DPRINT("BaseAddress: %p\n", Module
->DllBase
);
988 return LdrGetExportByName(Module
->DllBase
, (PUCHAR
)(p
+1), -1);
995 /**********************************************************************
997 * LdrGetExportByOrdinal
1011 LdrGetExportByOrdinal (
1016 PIMAGE_EXPORT_DIRECTORY ExportDir
;
1017 ULONG ExportDirSize
;
1018 PDWORD
* ExFunctions
;
1021 ExportDir
= (PIMAGE_EXPORT_DIRECTORY
)
1022 RtlImageDirectoryEntryToData (BaseAddress
,
1024 IMAGE_DIRECTORY_ENTRY_EXPORT
,
1028 ExFunctions
= (PDWORD
*)
1031 ExportDir
->AddressOfFunctions
1034 "LdrGetExportByOrdinal(Ordinal %lu) = %p\n",
1036 RVA(BaseAddress
, ExFunctions
[Ordinal
- ExportDir
->Base
] )
1039 Function
= (0 != ExFunctions
[Ordinal
- ExportDir
->Base
]
1040 ? RVA(BaseAddress
, ExFunctions
[Ordinal
- ExportDir
->Base
] )
1043 if (((ULONG
)Function
>= (ULONG
)ExportDir
) &&
1044 ((ULONG
)Function
< (ULONG
)ExportDir
+ (ULONG
)ExportDirSize
))
1046 DPRINT("Forward: %s\n", (PCHAR
)Function
);
1047 Function
= LdrFixupForward((PCHAR
)Function
);
1054 /**********************************************************************
1056 * LdrGetExportByName
1067 * AddressOfNames and AddressOfNameOrdinals are paralell tables,
1068 * both with NumberOfNames entries.
1072 LdrGetExportByName(PVOID BaseAddress
,
1076 PIMAGE_EXPORT_DIRECTORY ExportDir
;
1077 PDWORD
* ExFunctions
;
1079 USHORT
* ExOrdinals
;
1084 ULONG ExportDirSize
;
1086 DPRINT("LdrGetExportByName %p %s %hu\n", BaseAddress
, SymbolName
, Hint
);
1088 ExportDir
= (PIMAGE_EXPORT_DIRECTORY
)
1089 RtlImageDirectoryEntryToData(BaseAddress
,
1091 IMAGE_DIRECTORY_ENTRY_EXPORT
,
1093 if (ExportDir
== NULL
)
1095 DPRINT1("LdrGetExportByName(): no export directory!\n");
1100 //The symbol names may be missing entirely
1101 if (ExportDir
->AddressOfNames
== 0)
1103 DPRINT("LdrGetExportByName(): symbol names missing entirely\n");
1108 * Get header pointers
1110 ExNames
= (PDWORD
*)RVA(BaseAddress
,
1111 ExportDir
->AddressOfNames
);
1112 ExOrdinals
= (USHORT
*)RVA(BaseAddress
,
1113 ExportDir
->AddressOfNameOrdinals
);
1114 ExFunctions
= (PDWORD
*)RVA(BaseAddress
,
1115 ExportDir
->AddressOfFunctions
);
1118 * Check the hint first
1120 if (Hint
< ExportDir
->NumberOfNames
)
1122 ExName
= RVA(BaseAddress
, ExNames
[Hint
]);
1123 if (strcmp(ExName
, (PCHAR
)SymbolName
) == 0)
1125 Ordinal
= ExOrdinals
[Hint
];
1126 Function
= RVA(BaseAddress
, ExFunctions
[Ordinal
]);
1127 if (((ULONG
)Function
>= (ULONG
)ExportDir
) &&
1128 ((ULONG
)Function
< (ULONG
)ExportDir
+ (ULONG
)ExportDirSize
))
1130 DPRINT("Forward: %s\n", (PCHAR
)Function
);
1131 Function
= LdrFixupForward((PCHAR
)Function
);
1132 if (Function
== NULL
)
1134 DPRINT1("LdrGetExportByName(): failed to find %s\n",SymbolName
);
1138 if (Function
!= NULL
)
1147 maxn
= ExportDir
->NumberOfNames
- 1;
1148 while (minn
<= maxn
)
1153 mid
= (minn
+ maxn
) / 2;
1155 ExName
= RVA(BaseAddress
, ExNames
[mid
]);
1156 res
= strcmp(ExName
, (PCHAR
)SymbolName
);
1159 Ordinal
= ExOrdinals
[mid
];
1160 Function
= RVA(BaseAddress
, ExFunctions
[Ordinal
]);
1161 if (((ULONG
)Function
>= (ULONG
)ExportDir
) &&
1162 ((ULONG
)Function
< (ULONG
)ExportDir
+ (ULONG
)ExportDirSize
))
1164 DPRINT("Forward: %s\n", (PCHAR
)Function
);
1165 Function
= LdrFixupForward((PCHAR
)Function
);
1166 if (Function
== NULL
)
1168 DPRINT1("LdrGetExportByName(): failed to find %s\n",SymbolName
);
1172 if (Function
!= NULL
)
1175 else if (minn
== maxn
)
1177 DPRINT("LdrGetExportByName(): binary search failed\n");
1190 DPRINT1("LdrGetExportByName(): failed to find %s\n",SymbolName
);
1195 /**********************************************************************
1197 * LdrPerformRelocations
1200 * Relocate a DLL's memory image.
1212 LdrPerformRelocations(PIMAGE_NT_HEADERS NTHeaders
,
1215 PIMAGE_DATA_DIRECTORY RelocationDDir
;
1216 PIMAGE_BASE_RELOCATION RelocationDir
, RelocationEnd
;
1217 ULONG Count
, ProtectSize
, OldProtect
, OldProtect2
;
1218 PVOID Page
, ProtectPage
, ProtectPage2
;
1223 if (NTHeaders
->FileHeader
.Characteristics
& IMAGE_FILE_RELOCS_STRIPPED
)
1225 return STATUS_UNSUCCESSFUL
;
1229 &NTHeaders
->OptionalHeader
.DataDirectory
[IMAGE_DIRECTORY_ENTRY_BASERELOC
];
1231 if (RelocationDDir
->VirtualAddress
== 0 || RelocationDDir
->Size
== 0)
1233 return STATUS_SUCCESS
;
1236 ProtectSize
= PAGE_SIZE
;
1237 Delta
= (ULONG_PTR
)ImageBase
- NTHeaders
->OptionalHeader
.ImageBase
;
1238 RelocationDir
= (PIMAGE_BASE_RELOCATION
)((ULONG_PTR
)ImageBase
+
1239 RelocationDDir
->VirtualAddress
);
1240 RelocationEnd
= (PIMAGE_BASE_RELOCATION
)((ULONG_PTR
)ImageBase
+
1241 RelocationDDir
->VirtualAddress
+ RelocationDDir
->Size
);
1243 while (RelocationDir
< RelocationEnd
&&
1244 RelocationDir
->SizeOfBlock
> 0)
1246 Count
= (RelocationDir
->SizeOfBlock
- sizeof(IMAGE_BASE_RELOCATION
)) /
1248 Page
= (PVOID
)((ULONG_PTR
)ImageBase
+ (ULONG_PTR
)RelocationDir
->VirtualAddress
);
1249 TypeOffset
= (PUSHORT
)(RelocationDir
+ 1);
1251 /* Unprotect the page(s) we're about to relocate. */
1253 Status
= NtProtectVirtualMemory(NtCurrentProcess(),
1258 if (!NT_SUCCESS(Status
))
1260 DPRINT1("Failed to unprotect relocation target.\n");
1264 if (RelocationDir
->VirtualAddress
+ PAGE_SIZE
<
1265 NTHeaders
->OptionalHeader
.SizeOfImage
)
1267 ProtectPage2
= (PVOID
)((ULONG_PTR
)ProtectPage
+ PAGE_SIZE
);
1268 Status
= NtProtectVirtualMemory(NtCurrentProcess(),
1273 if (!NT_SUCCESS(Status
))
1275 DPRINT1("Failed to unprotect relocation target (2).\n");
1276 NtProtectVirtualMemory(NtCurrentProcess(),
1286 ProtectPage2
= NULL
;
1289 RelocationDir
= LdrProcessRelocationBlock(Page
,
1293 if (RelocationDir
== NULL
)
1294 return STATUS_UNSUCCESSFUL
;
1296 /* Restore old page protection. */
1297 NtProtectVirtualMemory(NtCurrentProcess(),
1303 if (ProtectPage2
!= NULL
)
1305 NtProtectVirtualMemory(NtCurrentProcess(),
1313 return STATUS_SUCCESS
;
1317 LdrpGetOrLoadModule(PWCHAR SerachPath
,
1319 PLDR_DATA_TABLE_ENTRY
* Module
,
1322 UNICODE_STRING DllName
;
1325 DPRINT("LdrpGetOrLoadModule() called for %s\n", Name
);
1327 RtlCreateUnicodeStringFromAsciiz (&DllName
, Name
);
1329 Status
= LdrFindEntryForName (&DllName
, Module
, Load
);
1330 if (Load
&& !NT_SUCCESS(Status
))
1332 Status
= LdrpLoadModule(SerachPath
,
1333 NtCurrentPeb()->Ldr
->Initialized
? 0 : LDRP_PROCESS_CREATION_TIME
,
1337 if (NT_SUCCESS(Status
))
1339 Status
= LdrFindEntryForName (&DllName
, Module
, FALSE
);
1341 if (!NT_SUCCESS(Status
))
1343 DPRINT1("failed to load %wZ\n", &DllName
);
1346 RtlFreeUnicodeString (&DllName
);
1351 LdrpProcessImportDirectoryEntry(PLDR_DATA_TABLE_ENTRY Module
,
1352 PLDR_DATA_TABLE_ENTRY ImportedModule
,
1353 PIMAGE_IMPORT_DESCRIPTOR ImportModuleDirectory
)
1356 PVOID
* ImportAddressList
;
1357 PULONG FunctionNameList
;
1363 if (ImportModuleDirectory
== NULL
|| ImportModuleDirectory
->Name
== 0)
1365 return STATUS_UNSUCCESSFUL
;
1368 /* Get the import address list. */
1369 ImportAddressList
= (PVOID
*)((ULONG_PTR
)Module
->DllBase
+ (ULONG_PTR
)ImportModuleDirectory
->FirstThunk
);
1371 /* Get the list of functions to import. */
1372 if (ImportModuleDirectory
->OriginalFirstThunk
!= 0)
1374 FunctionNameList
= (PULONG
) ((ULONG_PTR
)Module
->DllBase
+ (ULONG_PTR
)ImportModuleDirectory
->OriginalFirstThunk
);
1378 FunctionNameList
= (PULONG
)((ULONG_PTR
)Module
->DllBase
+ (ULONG_PTR
)ImportModuleDirectory
->FirstThunk
);
1381 /* Get the size of IAT. */
1383 while (FunctionNameList
[IATSize
] != 0L)
1388 /* Unprotect the region we are about to write into. */
1389 IATBase
= (PVOID
)ImportAddressList
;
1390 IATSize
*= sizeof(PVOID
*);
1391 Status
= NtProtectVirtualMemory(NtCurrentProcess(),
1396 if (!NT_SUCCESS(Status
))
1398 DPRINT1("Failed to unprotect IAT.\n");
1402 /* Walk through function list and fixup addresses. */
1403 while (*FunctionNameList
!= 0L)
1405 if ((*FunctionNameList
) & 0x80000000)
1407 Ordinal
= (*FunctionNameList
) & 0x7fffffff;
1408 *ImportAddressList
= LdrGetExportByOrdinal(ImportedModule
->DllBase
, Ordinal
);
1409 if ((*ImportAddressList
) == NULL
)
1411 DPRINT1("Failed to import #%ld from %wZ\n", Ordinal
, &ImportedModule
->FullDllName
);
1412 return STATUS_UNSUCCESSFUL
;
1417 IMAGE_IMPORT_BY_NAME
*pe_name
;
1418 pe_name
= RVA(Module
->DllBase
, *FunctionNameList
);
1419 *ImportAddressList
= LdrGetExportByName(ImportedModule
->DllBase
, pe_name
->Name
, pe_name
->Hint
);
1420 if ((*ImportAddressList
) == NULL
)
1422 DPRINT1("Failed to import %s from %wZ\n", pe_name
->Name
, &ImportedModule
->FullDllName
);
1423 return STATUS_UNSUCCESSFUL
;
1426 ImportAddressList
++;
1430 /* Protect the region we are about to write into. */
1431 Status
= NtProtectVirtualMemory(NtCurrentProcess(),
1436 if (!NT_SUCCESS(Status
))
1438 DPRINT1("Failed to protect IAT.\n");
1442 return STATUS_SUCCESS
;
1446 LdrpProcessImportDirectory(
1447 PLDR_DATA_TABLE_ENTRY Module
,
1448 PLDR_DATA_TABLE_ENTRY ImportedModule
,
1452 PIMAGE_IMPORT_DESCRIPTOR ImportModuleDirectory
;
1456 DPRINT("LdrpProcessImportDirectory(%p '%wZ', '%s')\n",
1457 Module
, &Module
->BaseDllName
, ImportedName
);
1460 ImportModuleDirectory
= (PIMAGE_IMPORT_DESCRIPTOR
)
1461 RtlImageDirectoryEntryToData(Module
->DllBase
,
1463 IMAGE_DIRECTORY_ENTRY_IMPORT
,
1465 if (ImportModuleDirectory
== NULL
)
1467 return STATUS_UNSUCCESSFUL
;
1470 while (ImportModuleDirectory
->Name
)
1472 Name
= (PCHAR
)Module
->DllBase
+ ImportModuleDirectory
->Name
;
1473 if (0 == _stricmp(Name
, ImportedName
))
1475 Status
= LdrpProcessImportDirectoryEntry(Module
,
1477 ImportModuleDirectory
);
1478 if (!NT_SUCCESS(Status
))
1483 ImportModuleDirectory
++;
1487 return STATUS_SUCCESS
;
1492 LdrpAdjustImportDirectory(PLDR_DATA_TABLE_ENTRY Module
,
1493 PLDR_DATA_TABLE_ENTRY ImportedModule
,
1496 PIMAGE_IMPORT_DESCRIPTOR ImportModuleDirectory
;
1498 PVOID
* ImportAddressList
;
1501 PULONG FunctionNameList
;
1506 PIMAGE_NT_HEADERS NTHeaders
;
1510 DPRINT("LdrpAdjustImportDirectory(Module %p '%wZ', %p '%wZ', '%s')\n",
1511 Module
, &Module
->BaseDllName
, ImportedModule
, &ImportedModule
->BaseDllName
, ImportedName
);
1513 ImportModuleDirectory
= (PIMAGE_IMPORT_DESCRIPTOR
)
1514 RtlImageDirectoryEntryToData(Module
->DllBase
,
1516 IMAGE_DIRECTORY_ENTRY_IMPORT
,
1518 if (ImportModuleDirectory
== NULL
)
1520 return STATUS_UNSUCCESSFUL
;
1523 while (ImportModuleDirectory
->Name
)
1525 Name
= (PCHAR
)Module
->DllBase
+ ImportModuleDirectory
->Name
;
1526 if (0 == _stricmp(Name
, (PCHAR
)ImportedName
))
1529 /* Get the import address list. */
1530 ImportAddressList
= (PVOID
*)((ULONG_PTR
)Module
->DllBase
+ (ULONG_PTR
)ImportModuleDirectory
->FirstThunk
);
1532 /* Get the list of functions to import. */
1533 if (ImportModuleDirectory
->OriginalFirstThunk
!= 0)
1535 FunctionNameList
= (PULONG
) ((ULONG_PTR
)Module
->DllBase
+ (ULONG_PTR
)ImportModuleDirectory
->OriginalFirstThunk
);
1539 FunctionNameList
= (PULONG
)((ULONG_PTR
)Module
->DllBase
+ (ULONG_PTR
)ImportModuleDirectory
->FirstThunk
);
1542 /* Get the size of IAT. */
1544 while (FunctionNameList
[IATSize
] != 0L)
1549 /* Unprotect the region we are about to write into. */
1550 IATBase
= (PVOID
)ImportAddressList
;
1551 IATSize
*= sizeof(PVOID
*);
1552 Status
= NtProtectVirtualMemory(NtCurrentProcess(),
1557 if (!NT_SUCCESS(Status
))
1559 DPRINT1("Failed to unprotect IAT.\n");
1563 NTHeaders
= RtlImageNtHeader (ImportedModule
->DllBase
);
1564 Start
= (PVOID
)NTHeaders
->OptionalHeader
.ImageBase
;
1565 End
= (PVOID
)((ULONG_PTR
)Start
+ ImportedModule
->SizeOfImage
);
1566 Offset
= (ULONG
)((ULONG_PTR
)ImportedModule
->DllBase
- (ULONG_PTR
)Start
);
1568 /* Walk through function list and fixup addresses. */
1569 while (*FunctionNameList
!= 0L)
1571 if (*ImportAddressList
>= Start
&& *ImportAddressList
< End
)
1573 (*ImportAddressList
) = (PVOID
)((ULONG_PTR
)(*ImportAddressList
) + Offset
);
1575 ImportAddressList
++;
1579 /* Protect the region we are about to write into. */
1580 Status
= NtProtectVirtualMemory(NtCurrentProcess(),
1585 if (!NT_SUCCESS(Status
))
1587 DPRINT1("Failed to protect IAT.\n");
1591 ImportModuleDirectory
++;
1593 return STATUS_SUCCESS
;
1597 /**********************************************************************
1602 * Compute the entry point for every symbol the DLL imports
1603 * from other modules.
1615 LdrFixupImports(IN PWSTR SearchPath OPTIONAL
,
1616 IN PLDR_DATA_TABLE_ENTRY Module
)
1618 PIMAGE_IMPORT_DESCRIPTOR ImportModuleDirectory
;
1619 PIMAGE_IMPORT_DESCRIPTOR ImportModuleDirectoryCurrent
;
1620 PIMAGE_BOUND_IMPORT_DESCRIPTOR BoundImportDescriptor
;
1621 PIMAGE_BOUND_IMPORT_DESCRIPTOR BoundImportDescriptorCurrent
;
1622 PIMAGE_TLS_DIRECTORY TlsDirectory
;
1625 PLDR_DATA_TABLE_ENTRY ImportedModule
;
1629 DPRINT("LdrFixupImports(SearchPath %S, Module %p)\n", SearchPath
, Module
);
1631 /* Check for tls data */
1632 TlsDirectory
= (PIMAGE_TLS_DIRECTORY
)
1633 RtlImageDirectoryEntryToData(Module
->DllBase
,
1635 IMAGE_DIRECTORY_ENTRY_TLS
,
1639 TlsSize
= TlsDirectory
->EndAddressOfRawData
1640 - TlsDirectory
->StartAddressOfRawData
1641 + TlsDirectory
->SizeOfZeroFill
;
1643 NtCurrentPeb()->Ldr
->Initialized
)
1645 TRACE_LDR("Trying to load dynamicly %wZ which contains a tls directory\n",
1646 &Module
->BaseDllName
);
1647 return STATUS_UNSUCCESSFUL
;
1651 * Process each import module.
1653 ImportModuleDirectory
= (PIMAGE_IMPORT_DESCRIPTOR
)
1654 RtlImageDirectoryEntryToData(Module
->DllBase
,
1656 IMAGE_DIRECTORY_ENTRY_IMPORT
,
1659 BoundImportDescriptor
= (PIMAGE_BOUND_IMPORT_DESCRIPTOR
)
1660 RtlImageDirectoryEntryToData(Module
->DllBase
,
1662 IMAGE_DIRECTORY_ENTRY_BOUND_IMPORT
,
1665 if (BoundImportDescriptor
!= NULL
&& ImportModuleDirectory
== NULL
)
1667 DPRINT1("%wZ has only a bound import directory\n", &Module
->BaseDllName
);
1668 return STATUS_UNSUCCESSFUL
;
1670 if (BoundImportDescriptor
)
1672 DPRINT("BoundImportDescriptor %p\n", BoundImportDescriptor
);
1674 BoundImportDescriptorCurrent
= BoundImportDescriptor
;
1675 while (BoundImportDescriptorCurrent
->OffsetModuleName
)
1677 ImportedName
= (PCHAR
)BoundImportDescriptor
+ BoundImportDescriptorCurrent
->OffsetModuleName
;
1678 TRACE_LDR("%wZ bound to %s\n", &Module
->BaseDllName
, ImportedName
);
1679 Status
= LdrpGetOrLoadModule(SearchPath
, ImportedName
, &ImportedModule
, TRUE
);
1680 if (!NT_SUCCESS(Status
))
1682 DPRINT1("failed to load %s\n", ImportedName
);
1685 if (Module
== ImportedModule
)
1687 LdrpDecrementLoadCount(Module
, FALSE
);
1689 if (ImportedModule
->TimeDateStamp
!= BoundImportDescriptorCurrent
->TimeDateStamp
)
1691 TRACE_LDR("%wZ has stale binding to %wZ\n",
1692 &Module
->BaseDllName
, &ImportedModule
->BaseDllName
);
1693 Status
= LdrpProcessImportDirectory(Module
, ImportedModule
, ImportedName
);
1694 if (!NT_SUCCESS(Status
))
1696 DPRINT1("failed to import %s\n", ImportedName
);
1702 BOOLEAN WrongForwarder
;
1703 WrongForwarder
= FALSE
;
1704 if (ImportedModule
->Flags
& LDRP_IMAGE_NOT_AT_BASE
)
1706 TRACE_LDR("%wZ has stale binding to %s\n",
1707 &Module
->BaseDllName
, ImportedName
);
1711 TRACE_LDR("%wZ has correct binding to %wZ\n",
1712 &Module
->BaseDllName
, &ImportedModule
->BaseDllName
);
1714 if (BoundImportDescriptorCurrent
->NumberOfModuleForwarderRefs
)
1716 PIMAGE_BOUND_FORWARDER_REF BoundForwarderRef
;
1718 PLDR_DATA_TABLE_ENTRY ForwarderModule
;
1719 PCHAR ForwarderName
;
1721 BoundForwarderRef
= (PIMAGE_BOUND_FORWARDER_REF
)(BoundImportDescriptorCurrent
+ 1);
1722 for (i
= 0; i
< BoundImportDescriptorCurrent
->NumberOfModuleForwarderRefs
; i
++, BoundForwarderRef
++)
1724 ForwarderName
= (PCHAR
)BoundImportDescriptor
+ BoundForwarderRef
->OffsetModuleName
;
1725 TRACE_LDR("%wZ bound to %s via forwardes from %s\n",
1726 &Module
->BaseDllName
, ForwarderName
, ImportedName
);
1727 Status
= LdrpGetOrLoadModule(SearchPath
, ForwarderName
, &ForwarderModule
, TRUE
);
1728 if (!NT_SUCCESS(Status
))
1730 DPRINT1("failed to load %s\n", ForwarderName
);
1733 if (Module
== ImportedModule
)
1735 LdrpDecrementLoadCount(Module
, FALSE
);
1737 if (ForwarderModule
->TimeDateStamp
!= BoundForwarderRef
->TimeDateStamp
||
1738 ForwarderModule
->Flags
& LDRP_IMAGE_NOT_AT_BASE
)
1740 TRACE_LDR("%wZ has stale binding to %s\n",
1741 &Module
->BaseDllName
, ForwarderName
);
1742 WrongForwarder
= TRUE
;
1746 TRACE_LDR("%wZ has correct binding to %s\n",
1747 &Module
->BaseDllName
, ForwarderName
);
1751 if (WrongForwarder
||
1752 ImportedModule
->Flags
& LDRP_IMAGE_NOT_AT_BASE
)
1754 Status
= LdrpProcessImportDirectory(Module
, ImportedModule
, ImportedName
);
1755 if (!NT_SUCCESS(Status
))
1757 DPRINT1("failed to import %s\n", ImportedName
);
1761 else if (ImportedModule
->Flags
& LDRP_IMAGE_NOT_AT_BASE
)
1763 TRACE_LDR("Adjust imports for %s from %wZ\n",
1764 ImportedName
, &Module
->BaseDllName
);
1765 Status
= LdrpAdjustImportDirectory(Module
, ImportedModule
, ImportedName
);
1766 if (!NT_SUCCESS(Status
))
1768 DPRINT1("failed to adjust import entries for %s\n", ImportedName
);
1772 else if (WrongForwarder
)
1776 * Update only forwarders
1778 TRACE_LDR("Stale BIND %s from %wZ\n",
1779 ImportedName
, &Module
->BaseDllName
);
1780 Status
= LdrpProcessImportDirectory(Module
, ImportedModule
, ImportedName
);
1781 if (!NT_SUCCESS(Status
))
1783 DPRINT1("faild to import %s\n", ImportedName
);
1792 BoundImportDescriptorCurrent
+= BoundImportDescriptorCurrent
->NumberOfModuleForwarderRefs
+ 1;
1795 else if (ImportModuleDirectory
)
1797 DPRINT("ImportModuleDirectory %p\n", ImportModuleDirectory
);
1799 ImportModuleDirectoryCurrent
= ImportModuleDirectory
;
1800 while (ImportModuleDirectoryCurrent
->Name
)
1802 ImportedName
= (PCHAR
)Module
->DllBase
+ ImportModuleDirectoryCurrent
->Name
;
1803 TRACE_LDR("%wZ imports functions from %s\n", &Module
->BaseDllName
, ImportedName
);
1805 Status
= LdrpGetOrLoadModule(SearchPath
, ImportedName
, &ImportedModule
, TRUE
);
1806 if (!NT_SUCCESS(Status
))
1808 DPRINT1("failed to load %s\n", ImportedName
);
1811 if (Module
== ImportedModule
)
1813 LdrpDecrementLoadCount(Module
, FALSE
);
1816 TRACE_LDR("Initializing imports for %wZ from %s\n",
1817 &Module
->BaseDllName
, ImportedName
);
1818 Status
= LdrpProcessImportDirectoryEntry(Module
, ImportedModule
, ImportModuleDirectoryCurrent
);
1819 if (!NT_SUCCESS(Status
))
1821 DPRINT1("failed to import %s\n", ImportedName
);
1824 ImportModuleDirectoryCurrent
++;
1828 if (TlsDirectory
&& TlsSize
> 0)
1830 LdrpAcquireTlsSlot(Module
, TlsSize
, FALSE
);
1833 return STATUS_SUCCESS
;
1837 /**********************************************************************
1842 * 1. Relocate, if needed the EXE.
1843 * 2. Fixup any imported symbol.
1844 * 3. Compute the EXE's entry point.
1848 * Address at which the EXE's image
1852 * Handle of the section that contains
1856 * NULL on error; otherwise the entry point
1857 * to call for initializing the DLL.
1862 * 04.01.2004 hb Previous this function was used for all images (dll + exe).
1863 * Currently the function is only used for the exe.
1865 PEPFUNC
LdrPEStartup (PVOID ImageBase
,
1866 HANDLE SectionHandle
,
1867 PLDR_DATA_TABLE_ENTRY
* Module
,
1871 PEPFUNC EntryPoint
= NULL
;
1872 PIMAGE_DOS_HEADER DosHeader
;
1873 PIMAGE_NT_HEADERS NTHeaders
;
1874 PLDR_DATA_TABLE_ENTRY tmpModule
;
1876 DPRINT("LdrPEStartup(ImageBase %p SectionHandle %p)\n",
1877 ImageBase
, SectionHandle
);
1880 * Overlay DOS and WNT headers structures
1881 * to the DLL's image.
1883 DosHeader
= (PIMAGE_DOS_HEADER
) ImageBase
;
1884 NTHeaders
= (PIMAGE_NT_HEADERS
) ((ULONG_PTR
)ImageBase
+ DosHeader
->e_lfanew
);
1887 * If the base address is different from the
1888 * one the DLL is actually loaded, perform any
1891 if (ImageBase
!= (PVOID
) NTHeaders
->OptionalHeader
.ImageBase
)
1893 DPRINT("LDR: Performing relocations\n");
1894 Status
= LdrPerformRelocations(NTHeaders
, ImageBase
);
1895 if (!NT_SUCCESS(Status
))
1897 DPRINT1("LdrPerformRelocations() failed\n");
1904 *Module
= LdrAddModuleEntry(ImageBase
, NTHeaders
, FullDosName
);
1905 (*Module
)->SectionPointer
= SectionHandle
;
1909 Module
= &tmpModule
;
1910 Status
= LdrFindEntryForAddress(ImageBase
, Module
);
1911 if (!NT_SUCCESS(Status
))
1917 if (ImageBase
!= (PVOID
) NTHeaders
->OptionalHeader
.ImageBase
)
1919 (*Module
)->Flags
|= LDRP_IMAGE_NOT_AT_BASE
;
1923 * If the DLL's imports symbols from other
1924 * modules, fixup the imported calls entry points.
1926 DPRINT("About to fixup imports\n");
1927 Status
= LdrFixupImports(NULL
, *Module
);
1928 if (!NT_SUCCESS(Status
))
1930 DPRINT1("LdrFixupImports() failed for %wZ\n", &(*Module
)->BaseDllName
);
1933 DPRINT("Fixup done\n");
1934 RtlEnterCriticalSection(NtCurrentPeb()->LoaderLock
);
1935 Status
= LdrpInitializeTlsForProccess();
1936 if (NT_SUCCESS(Status
))
1938 Status
= LdrpAttachProcess();
1940 if (NT_SUCCESS(Status
))
1942 LdrpTlsCallback(*Module
, DLL_PROCESS_ATTACH
);
1946 RtlLeaveCriticalSection(NtCurrentPeb()->LoaderLock
);
1947 if (!NT_SUCCESS(Status
))
1953 * Compute the DLL's entry point's address.
1955 DPRINT("ImageBase = %p\n", ImageBase
);
1956 DPRINT("AddressOfEntryPoint = 0x%lx\n",(ULONG
)NTHeaders
->OptionalHeader
.AddressOfEntryPoint
);
1957 if (NTHeaders
->OptionalHeader
.AddressOfEntryPoint
!= 0)
1959 EntryPoint
= (PEPFUNC
) ((ULONG_PTR
)ImageBase
1960 + NTHeaders
->OptionalHeader
.AddressOfEntryPoint
);
1962 DPRINT("LdrPEStartup() = %p\n",EntryPoint
);
1967 LdrpLoadModule(IN PWSTR SearchPath OPTIONAL
,
1969 IN PUNICODE_STRING Name
,
1970 PLDR_DATA_TABLE_ENTRY
*Module
,
1971 PVOID
*BaseAddress OPTIONAL
)
1973 UNICODE_STRING AdjustedName
;
1974 UNICODE_STRING FullDosName
;
1976 PLDR_DATA_TABLE_ENTRY tmpModule
;
1977 HANDLE SectionHandle
;
1980 PIMAGE_NT_HEADERS NtHeaders
;
1981 BOOLEAN MappedAsDataFile
;
1985 Module
= &tmpModule
;
1987 /* adjust the full dll name */
1988 LdrAdjustDllName(&AdjustedName
, Name
, FALSE
);
1990 DPRINT("%wZ\n", &AdjustedName
);
1992 MappedAsDataFile
= FALSE
;
1993 /* Test if dll is already loaded */
1994 Status
= LdrFindEntryForName(&AdjustedName
, Module
, TRUE
);
1995 if (NT_SUCCESS(Status
))
1997 RtlFreeUnicodeString(&AdjustedName
);
1998 if (NULL
!= BaseAddress
)
2000 *BaseAddress
= (*Module
)->DllBase
;
2005 /* Open or create dll image section */
2006 Status
= LdrpMapKnownDll(&AdjustedName
, &FullDosName
, &SectionHandle
);
2007 if (!NT_SUCCESS(Status
))
2009 MappedAsDataFile
= (0 != (LoadFlags
& LOAD_LIBRARY_AS_DATAFILE
));
2010 Status
= LdrpMapDllImageFile(SearchPath
, &AdjustedName
, &FullDosName
,
2011 MappedAsDataFile
, &SectionHandle
);
2013 if (!NT_SUCCESS(Status
))
2015 DPRINT1("Failed to create or open dll section of '%wZ' (Status %lx)\n", &AdjustedName
, Status
);
2016 RtlFreeUnicodeString(&AdjustedName
);
2019 RtlFreeUnicodeString(&AdjustedName
);
2020 /* Map the dll into the process */
2023 Status
= NtMapViewOfSection(SectionHandle
,
2033 if (!NT_SUCCESS(Status
))
2035 DPRINT1("map view of section failed (Status 0x%08lx)\n", Status
);
2036 RtlFreeUnicodeString(&FullDosName
);
2037 NtClose(SectionHandle
);
2040 if (NULL
!= BaseAddress
)
2042 *BaseAddress
= ImageBase
;
2044 /* Get and check the NT headers */
2045 NtHeaders
= RtlImageNtHeader(ImageBase
);
2046 if (NtHeaders
== NULL
)
2048 DPRINT1("RtlImageNtHeaders() failed\n");
2049 NtUnmapViewOfSection (NtCurrentProcess (), ImageBase
);
2050 NtClose (SectionHandle
);
2051 RtlFreeUnicodeString(&FullDosName
);
2052 return STATUS_UNSUCCESSFUL
;
2054 DPRINT("Mapped %wZ at %x\n", &FullDosName
, ImageBase
);
2055 if (MappedAsDataFile
)
2057 ASSERT(NULL
!= BaseAddress
);
2058 if (NULL
!= BaseAddress
)
2060 *BaseAddress
= (PVOID
) ((char *) *BaseAddress
+ 1);
2063 RtlFreeUnicodeString(&FullDosName
);
2064 NtClose(SectionHandle
);
2065 return STATUS_SUCCESS
;
2067 /* If the base address is different from the
2068 * one the DLL is actually loaded, perform any
2070 if (ImageBase
!= (PVOID
) NtHeaders
->OptionalHeader
.ImageBase
)
2072 DPRINT1("Relocating (%lx -> %p) %wZ\n",
2073 NtHeaders
->OptionalHeader
.ImageBase
, ImageBase
, &FullDosName
);
2074 Status
= LdrPerformRelocations(NtHeaders
, ImageBase
);
2075 if (!NT_SUCCESS(Status
))
2077 DPRINT1("LdrPerformRelocations() failed\n");
2078 NtUnmapViewOfSection (NtCurrentProcess (), ImageBase
);
2079 NtClose (SectionHandle
);
2080 RtlFreeUnicodeString(&FullDosName
);
2081 return STATUS_UNSUCCESSFUL
;
2084 *Module
= LdrAddModuleEntry(ImageBase
, NtHeaders
, FullDosName
.Buffer
);
2085 (*Module
)->SectionPointer
= SectionHandle
;
2086 if (ImageBase
!= (PVOID
) NtHeaders
->OptionalHeader
.ImageBase
)
2088 (*Module
)->Flags
|= LDRP_IMAGE_NOT_AT_BASE
;
2090 if (NtHeaders
->FileHeader
.Characteristics
& IMAGE_FILE_DLL
)
2092 (*Module
)->Flags
|= LDRP_IMAGE_DLL
;
2094 /* fixup the imported calls entry points */
2095 Status
= LdrFixupImports(SearchPath
, *Module
);
2096 if (!NT_SUCCESS(Status
))
2098 DPRINT1("LdrFixupImports failed for %wZ, status=%x\n", &(*Module
)->BaseDllName
, Status
);
2101 #if defined(DBG) || defined(KDBG)
2102 LdrpLoadUserModuleSymbols(*Module
);
2103 #endif /* DBG || KDBG */
2104 RtlEnterCriticalSection(NtCurrentPeb()->LoaderLock
);
2105 InsertTailList(&NtCurrentPeb()->Ldr
->InInitializationOrderModuleList
,
2106 &(*Module
)->InInitializationOrderModuleList
);
2107 RtlLeaveCriticalSection (NtCurrentPeb()->LoaderLock
);
2109 return STATUS_SUCCESS
;
2113 LdrpUnloadModule(PLDR_DATA_TABLE_ENTRY Module
,
2116 PIMAGE_IMPORT_DESCRIPTOR ImportModuleDirectory
;
2117 PIMAGE_BOUND_IMPORT_DESCRIPTOR BoundImportDescriptor
;
2118 PIMAGE_BOUND_IMPORT_DESCRIPTOR BoundImportDescriptorCurrent
;
2120 PLDR_DATA_TABLE_ENTRY ImportedModule
;
2127 RtlEnterCriticalSection(NtCurrentPeb()->LoaderLock
);
2130 LoadCount
= LdrpDecrementLoadCount(Module
, Unload
);
2132 TRACE_LDR("Unload %wZ, LoadCount %d\n", &Module
->BaseDllName
, LoadCount
);
2136 /* ?????????????????? */
2138 else if (LoadCount
== 1)
2140 BoundImportDescriptor
= (PIMAGE_BOUND_IMPORT_DESCRIPTOR
)
2141 RtlImageDirectoryEntryToData(Module
->DllBase
,
2143 IMAGE_DIRECTORY_ENTRY_BOUND_IMPORT
,
2145 if (BoundImportDescriptor
)
2147 /* dereferencing all imported modules, use the bound import descriptor */
2148 BoundImportDescriptorCurrent
= BoundImportDescriptor
;
2149 while (BoundImportDescriptorCurrent
->OffsetModuleName
)
2151 ImportedName
= (PCHAR
)BoundImportDescriptor
+ BoundImportDescriptorCurrent
->OffsetModuleName
;
2152 TRACE_LDR("%wZ trys to unload %s\n", &Module
->BaseDllName
, ImportedName
);
2153 Status
= LdrpGetOrLoadModule(NULL
, ImportedName
, &ImportedModule
, FALSE
);
2154 if (!NT_SUCCESS(Status
))
2156 DPRINT1("unable to found imported modul %s\n", ImportedName
);
2160 if (Module
!= ImportedModule
)
2162 Status
= LdrpUnloadModule(ImportedModule
, FALSE
);
2163 if (!NT_SUCCESS(Status
))
2165 DPRINT1("unable to unload %s\n", ImportedName
);
2169 BoundImportDescriptorCurrent
++;
2174 ImportModuleDirectory
= (PIMAGE_IMPORT_DESCRIPTOR
)
2175 RtlImageDirectoryEntryToData(Module
->DllBase
,
2177 IMAGE_DIRECTORY_ENTRY_IMPORT
,
2179 if (ImportModuleDirectory
)
2181 /* dereferencing all imported modules, use the import descriptor */
2182 while (ImportModuleDirectory
->Name
)
2184 ImportedName
= (PCHAR
)Module
->DllBase
+ ImportModuleDirectory
->Name
;
2185 TRACE_LDR("%wZ trys to unload %s\n", &Module
->BaseDllName
, ImportedName
);
2186 Status
= LdrpGetOrLoadModule(NULL
, ImportedName
, &ImportedModule
, FALSE
);
2187 if (!NT_SUCCESS(Status
))
2189 DPRINT1("unable to found imported modul %s\n", ImportedName
);
2193 if (Module
!= ImportedModule
)
2195 Status
= LdrpUnloadModule(ImportedModule
, FALSE
);
2196 if (!NT_SUCCESS(Status
))
2198 DPRINT1("unable to unload %s\n", ImportedName
);
2202 ImportModuleDirectory
++;
2210 LdrpDetachProcess(FALSE
);
2211 RtlLeaveCriticalSection (NtCurrentPeb()->LoaderLock
);
2213 return STATUS_SUCCESS
;
2221 LdrUnloadDll (IN PVOID BaseAddress
)
2223 PLDR_DATA_TABLE_ENTRY Module
;
2226 if (BaseAddress
== NULL
)
2227 return STATUS_SUCCESS
;
2229 if (LdrMappedAsDataFile(&BaseAddress
))
2231 Status
= NtUnmapViewOfSection(NtCurrentProcess(), BaseAddress
);
2235 Status
= LdrFindEntryForAddress(BaseAddress
, &Module
);
2236 if (NT_SUCCESS(Status
))
2238 TRACE_LDR("LdrUnloadDll, , unloading %wZ\n", &Module
->BaseDllName
);
2239 Status
= LdrpUnloadModule(Module
, TRUE
);
2250 LdrDisableThreadCalloutsForDll(IN PVOID BaseAddress
)
2252 PLIST_ENTRY ModuleListHead
;
2254 PLDR_DATA_TABLE_ENTRY Module
;
2257 DPRINT("LdrDisableThreadCalloutsForDll (BaseAddress %p)\n", BaseAddress
);
2259 Status
= STATUS_DLL_NOT_FOUND
;
2260 RtlEnterCriticalSection (NtCurrentPeb()->LoaderLock
);
2261 ModuleListHead
= &NtCurrentPeb()->Ldr
->InLoadOrderModuleList
;
2262 Entry
= ModuleListHead
->Flink
;
2263 while (Entry
!= ModuleListHead
)
2265 Module
= CONTAINING_RECORD(Entry
, LDR_DATA_TABLE_ENTRY
, InLoadOrderModuleList
);
2267 DPRINT("BaseDllName %wZ BaseAddress %p\n", &Module
->BaseDllName
, Module
->DllBase
);
2269 if (Module
->DllBase
== BaseAddress
)
2271 if (Module
->TlsIndex
== 0xFFFF)
2273 Module
->Flags
|= LDRP_DONT_CALL_FOR_THREADS
;
2274 Status
= STATUS_SUCCESS
;
2278 Entry
= Entry
->Flink
;
2280 RtlLeaveCriticalSection (NtCurrentPeb()->LoaderLock
);
2288 LdrGetDllHandle(IN PWSTR DllPath OPTIONAL
,
2289 IN PULONG DllCharacteristics
,
2290 IN PUNICODE_STRING DllName
,
2291 OUT PVOID
*DllHandle
)
2293 PLDR_DATA_TABLE_ENTRY Module
;
2296 TRACE_LDR("LdrGetDllHandle, searching for %wZ from %S\n",
2297 DllName
, DllPath
? DllPath
: L
"");
2299 /* NULL is the current executable */
2300 if (DllName
== NULL
)
2302 *DllHandle
= ExeModule
->DllBase
;
2303 DPRINT("BaseAddress 0x%lx\n", *DllHandle
);
2304 return STATUS_SUCCESS
;
2307 Status
= LdrFindEntryForName(DllName
, &Module
, FALSE
);
2308 if (NT_SUCCESS(Status
))
2310 *DllHandle
= Module
->DllBase
;
2311 return STATUS_SUCCESS
;
2314 DPRINT("Failed to find dll %wZ\n", DllName
);
2316 return STATUS_DLL_NOT_FOUND
;
2324 LdrGetProcedureAddress (IN PVOID BaseAddress
,
2325 IN PANSI_STRING Name
,
2327 OUT PVOID
*ProcedureAddress
)
2329 if (Name
&& Name
->Length
)
2331 TRACE_LDR("LdrGetProcedureAddress by NAME - %Z\n", Name
);
2335 TRACE_LDR("LdrGetProcedureAddress by ORDINAL - %d\n", Ordinal
);
2338 DPRINT("LdrGetProcedureAddress (BaseAddress %p Name %Z Ordinal %lu ProcedureAddress %p)\n",
2339 BaseAddress
, Name
, Ordinal
, ProcedureAddress
);
2341 if (Name
&& Name
->Length
)
2344 *ProcedureAddress
= LdrGetExportByName(BaseAddress
, (PUCHAR
)Name
->Buffer
, 0xffff);
2345 if (*ProcedureAddress
!= NULL
)
2347 return STATUS_SUCCESS
;
2349 DPRINT("LdrGetProcedureAddress: Can't resolve symbol '%Z'\n", Name
);
2354 Ordinal
&= 0x0000FFFF;
2355 *ProcedureAddress
= LdrGetExportByOrdinal(BaseAddress
, (WORD
)Ordinal
);
2356 if (*ProcedureAddress
)
2358 return STATUS_SUCCESS
;
2360 DPRINT("LdrGetProcedureAddress: Can't resolve symbol @%lu\n", Ordinal
);
2362 return STATUS_PROCEDURE_NOT_FOUND
;
2365 /**********************************************************************
2370 * Unload dll's which are no longer referenced from others dll's
2381 * The loader lock must be held on enty.
2384 LdrpDetachProcess(BOOLEAN UnloadAll
)
2386 PLIST_ENTRY ModuleListHead
;
2388 PLDR_DATA_TABLE_ENTRY Module
;
2389 static ULONG CallingCount
= 0;
2391 DPRINT("LdrpDetachProcess() called for %wZ\n",
2392 &ExeModule
->BaseDllName
);
2396 ModuleListHead
= &NtCurrentPeb()->Ldr
->InInitializationOrderModuleList
;
2397 Entry
= ModuleListHead
->Blink
;
2398 while (Entry
!= ModuleListHead
)
2400 Module
= CONTAINING_RECORD(Entry
, LDR_DATA_TABLE_ENTRY
, InInitializationOrderModuleList
);
2401 if (((UnloadAll
&& Module
->LoadCount
== 0xFFFF) || Module
->LoadCount
== 0) &&
2402 Module
->Flags
& LDRP_ENTRY_PROCESSED
&&
2403 !(Module
->Flags
& LDRP_UNLOAD_IN_PROGRESS
))
2405 Module
->Flags
|= LDRP_UNLOAD_IN_PROGRESS
;
2406 if (Module
== LdrpLastModule
)
2408 LdrpLastModule
= NULL
;
2410 if (Module
->Flags
& LDRP_PROCESS_ATTACH_CALLED
)
2412 TRACE_LDR("Unload %wZ - Calling entry point at %x\n",
2413 &Module
->BaseDllName
, Module
->EntryPoint
);
2414 LdrpCallDllEntry(Module
, DLL_PROCESS_DETACH
, (PVOID
)(Module
->LoadCount
== 0xFFFF ? 1 : 0));
2418 TRACE_LDR("Unload %wZ\n", &Module
->BaseDllName
);
2420 Entry
= ModuleListHead
->Blink
;
2424 Entry
= Entry
->Blink
;
2428 if (CallingCount
== 1)
2430 Entry
= ModuleListHead
->Blink
;
2431 while (Entry
!= ModuleListHead
)
2433 Module
= CONTAINING_RECORD(Entry
, LDR_DATA_TABLE_ENTRY
, InInitializationOrderModuleList
);
2434 Entry
= Entry
->Blink
;
2435 if (Module
->Flags
& LDRP_UNLOAD_IN_PROGRESS
&&
2436 ((UnloadAll
&& Module
->LoadCount
!= 0xFFFF) || Module
->LoadCount
== 0))
2438 /* remove the module entry from the list */
2439 RemoveEntryList (&Module
->InLoadOrderModuleList
);
2440 RemoveEntryList (&Module
->InInitializationOrderModuleList
);
2442 NtUnmapViewOfSection (NtCurrentProcess (), Module
->DllBase
);
2443 NtClose (Module
->SectionPointer
);
2445 TRACE_LDR("%wZ unloaded\n", &Module
->BaseDllName
);
2447 RtlFreeUnicodeString (&Module
->FullDllName
);
2448 RtlFreeUnicodeString (&Module
->BaseDllName
);
2450 RtlFreeHeap (RtlGetProcessHeap (), 0, Module
);
2455 DPRINT("LdrpDetachProcess() done\n");
2458 /**********************************************************************
2463 * Initialize all dll's which are prepered for loading
2474 * The loader lock must be held on entry.
2478 LdrpAttachProcess(VOID
)
2480 PLIST_ENTRY ModuleListHead
;
2482 PLDR_DATA_TABLE_ENTRY Module
;
2484 NTSTATUS Status
= STATUS_SUCCESS
;
2486 DPRINT("LdrpAttachProcess() called for %wZ\n",
2487 &ExeModule
->BaseDllName
);
2489 ModuleListHead
= &NtCurrentPeb()->Ldr
->InInitializationOrderModuleList
;
2490 Entry
= ModuleListHead
->Flink
;
2491 while (Entry
!= ModuleListHead
)
2493 Module
= CONTAINING_RECORD(Entry
, LDR_DATA_TABLE_ENTRY
, InInitializationOrderModuleList
);
2494 if (!(Module
->Flags
& (LDRP_LOAD_IN_PROGRESS
|LDRP_UNLOAD_IN_PROGRESS
|LDRP_ENTRY_PROCESSED
)))
2496 Module
->Flags
|= LDRP_LOAD_IN_PROGRESS
;
2497 TRACE_LDR("%wZ loaded - Calling init routine at %x for process attaching\n",
2498 &Module
->BaseDllName
, Module
->EntryPoint
);
2499 Result
= LdrpCallDllEntry(Module
, DLL_PROCESS_ATTACH
, (PVOID
)(Module
->LoadCount
== 0xFFFF ? 1 : 0));
2502 Status
= STATUS_DLL_INIT_FAILED
;
2505 if (Module
->Flags
& LDRP_IMAGE_DLL
&& Module
->EntryPoint
!= 0)
2507 Module
->Flags
|= LDRP_PROCESS_ATTACH_CALLED
|LDRP_ENTRY_PROCESSED
;
2511 Module
->Flags
|= LDRP_ENTRY_PROCESSED
;
2513 Module
->Flags
&= ~LDRP_LOAD_IN_PROGRESS
;
2515 Entry
= Entry
->Flink
;
2518 DPRINT("LdrpAttachProcess() done\n");
2527 LdrShutdownProcess (VOID
)
2529 LdrpDetachProcess(TRUE
);
2530 return STATUS_SUCCESS
;
2538 LdrpAttachThread (VOID
)
2540 PLIST_ENTRY ModuleListHead
;
2542 PLDR_DATA_TABLE_ENTRY Module
;
2545 DPRINT("LdrpAttachThread() called for %wZ\n",
2546 &ExeModule
->BaseDllName
);
2548 RtlEnterCriticalSection (NtCurrentPeb()->LoaderLock
);
2550 Status
= LdrpInitializeTlsForThread();
2552 if (NT_SUCCESS(Status
))
2554 ModuleListHead
= &NtCurrentPeb()->Ldr
->InInitializationOrderModuleList
;
2555 Entry
= ModuleListHead
->Flink
;
2557 while (Entry
!= ModuleListHead
)
2559 Module
= CONTAINING_RECORD(Entry
, LDR_DATA_TABLE_ENTRY
, InInitializationOrderModuleList
);
2560 if (Module
->Flags
& LDRP_PROCESS_ATTACH_CALLED
&&
2561 !(Module
->Flags
& LDRP_DONT_CALL_FOR_THREADS
) &&
2562 !(Module
->Flags
& LDRP_UNLOAD_IN_PROGRESS
))
2564 TRACE_LDR("%wZ - Calling entry point at %x for thread attaching\n",
2565 &Module
->BaseDllName
, Module
->EntryPoint
);
2566 LdrpCallDllEntry(Module
, DLL_THREAD_ATTACH
, NULL
);
2568 Entry
= Entry
->Flink
;
2571 Entry
= NtCurrentPeb()->Ldr
->InLoadOrderModuleList
.Flink
;
2572 Module
= CONTAINING_RECORD(Entry
, LDR_DATA_TABLE_ENTRY
, InLoadOrderModuleList
);
2573 LdrpTlsCallback(Module
, DLL_THREAD_ATTACH
);
2576 RtlLeaveCriticalSection (NtCurrentPeb()->LoaderLock
);
2578 DPRINT("LdrpAttachThread() done\n");
2588 LdrShutdownThread (VOID
)
2590 PLIST_ENTRY ModuleListHead
;
2592 PLDR_DATA_TABLE_ENTRY Module
;
2594 DPRINT("LdrShutdownThread() called for %wZ\n",
2595 &ExeModule
->BaseDllName
);
2597 RtlEnterCriticalSection (NtCurrentPeb()->LoaderLock
);
2599 ModuleListHead
= &NtCurrentPeb()->Ldr
->InInitializationOrderModuleList
;
2600 Entry
= ModuleListHead
->Blink
;
2601 while (Entry
!= ModuleListHead
)
2603 Module
= CONTAINING_RECORD(Entry
, LDR_DATA_TABLE_ENTRY
, InInitializationOrderModuleList
);
2605 if (Module
->Flags
& LDRP_PROCESS_ATTACH_CALLED
&&
2606 !(Module
->Flags
& LDRP_DONT_CALL_FOR_THREADS
) &&
2607 !(Module
->Flags
& LDRP_UNLOAD_IN_PROGRESS
))
2609 TRACE_LDR("%wZ - Calling entry point at %x for thread detaching\n",
2610 &Module
->BaseDllName
, Module
->EntryPoint
);
2611 LdrpCallDllEntry(Module
, DLL_THREAD_DETACH
, NULL
);
2613 Entry
= Entry
->Blink
;
2616 RtlLeaveCriticalSection (NtCurrentPeb()->LoaderLock
);
2620 RtlFreeHeap (RtlGetProcessHeap(), 0, NtCurrentTeb()->ThreadLocalStoragePointer
);
2623 DPRINT("LdrShutdownThread() done\n");
2625 return STATUS_SUCCESS
;
2629 /***************************************************************************
2631 * LdrQueryProcessModuleInformation
2646 LdrQueryProcessModuleInformation(IN PRTL_PROCESS_MODULES ModuleInformation OPTIONAL
,
2647 IN ULONG Size OPTIONAL
,
2648 OUT PULONG ReturnedSize
)
2650 PLIST_ENTRY ModuleListHead
;
2652 PLDR_DATA_TABLE_ENTRY Module
;
2653 PRTL_PROCESS_MODULE_INFORMATION ModulePtr
= NULL
;
2654 NTSTATUS Status
= STATUS_SUCCESS
;
2655 ULONG UsedSize
= sizeof(ULONG
);
2656 ANSI_STRING AnsiString
;
2659 DPRINT("LdrQueryProcessModuleInformation() called\n");
2661 RtlEnterCriticalSection (NtCurrentPeb()->LoaderLock
);
2663 if (ModuleInformation
== NULL
|| Size
== 0)
2665 Status
= STATUS_INFO_LENGTH_MISMATCH
;
2669 ModuleInformation
->ModuleCount
= 0;
2670 ModulePtr
= &ModuleInformation
->ModuleEntry
[0];
2671 Status
= STATUS_SUCCESS
;
2674 ModuleListHead
= &NtCurrentPeb()->Ldr
->InLoadOrderModuleList
;
2675 Entry
= ModuleListHead
->Flink
;
2677 while (Entry
!= ModuleListHead
)
2679 Module
= CONTAINING_RECORD(Entry
, LDR_DATA_TABLE_ENTRY
, InLoadOrderModuleList
);
2681 DPRINT(" Module %wZ\n",
2682 &Module
->FullDllName
);
2684 if (UsedSize
> Size
)
2686 Status
= STATUS_INFO_LENGTH_MISMATCH
;
2688 else if (ModuleInformation
!= NULL
)
2690 ModulePtr
->Reserved
[0] = ModulePtr
->Reserved
[1] = 0; // FIXME: ??
2691 ModulePtr
->Base
= Module
->DllBase
;
2692 ModulePtr
->Size
= Module
->SizeOfImage
;
2693 ModulePtr
->Flags
= Module
->Flags
;
2694 ModulePtr
->Index
= 0; // FIXME: index ??
2695 ModulePtr
->Unknown
= 0; // FIXME: ??
2696 ModulePtr
->LoadCount
= Module
->LoadCount
;
2698 AnsiString
.Length
= 0;
2699 AnsiString
.MaximumLength
= 256;
2700 AnsiString
.Buffer
= ModulePtr
->ImageName
;
2701 RtlUnicodeStringToAnsiString(&AnsiString
,
2702 &Module
->FullDllName
,
2704 p
= strrchr(ModulePtr
->ImageName
, '\\');
2706 ModulePtr
->ModuleNameOffset
= p
- ModulePtr
->ImageName
+ 1;
2708 ModulePtr
->ModuleNameOffset
= 0;
2711 ModuleInformation
->ModuleCount
++;
2713 UsedSize
+= sizeof(RTL_PROCESS_MODULE_INFORMATION
);
2715 Entry
= Entry
->Flink
;
2718 RtlLeaveCriticalSection (NtCurrentPeb()->LoaderLock
);
2720 if (ReturnedSize
!= 0)
2721 *ReturnedSize
= UsedSize
;
2723 DPRINT("LdrQueryProcessModuleInformation() done\n");
2730 LdrpCheckImageChecksum (IN PVOID BaseAddress
,
2733 PIMAGE_NT_HEADERS Header
;
2740 Header
= RtlImageNtHeader (BaseAddress
);
2744 HeaderSum
= Header
->OptionalHeader
.CheckSum
;
2749 Ptr
= (PUSHORT
) BaseAddress
;
2750 for (i
= 0; i
< ImageSize
/ sizeof (USHORT
); i
++)
2753 if (HIWORD(Sum
) != 0)
2755 Sum
= LOWORD(Sum
) + HIWORD(Sum
);
2762 Sum
+= (ULONG
)*((PUCHAR
)Ptr
);
2763 if (HIWORD(Sum
) != 0)
2765 Sum
= LOWORD(Sum
) + HIWORD(Sum
);
2769 CalcSum
= (USHORT
)(LOWORD(Sum
) + HIWORD(Sum
));
2771 /* Subtract image checksum from calculated checksum. */
2772 /* fix low word of checksum */
2773 if (LOWORD(CalcSum
) >= LOWORD(HeaderSum
))
2775 CalcSum
-= LOWORD(HeaderSum
);
2779 CalcSum
= ((LOWORD(CalcSum
) - LOWORD(HeaderSum
)) & 0xFFFF) - 1;
2782 /* fix high word of checksum */
2783 if (LOWORD(CalcSum
) >= HIWORD(HeaderSum
))
2785 CalcSum
-= HIWORD(HeaderSum
);
2789 CalcSum
= ((LOWORD(CalcSum
) - HIWORD(HeaderSum
)) & 0xFFFF) - 1;
2792 /* add file length */
2793 CalcSum
+= ImageSize
;
2795 return (BOOLEAN
)(CalcSum
== HeaderSum
);
2799 * Compute size of an image as it is actually present in virt memory
2800 * (i.e. excluding NEVER_LOAD sections)
2803 LdrpGetResidentSize(PIMAGE_NT_HEADERS NTHeaders
)
2805 PIMAGE_SECTION_HEADER SectionHeader
;
2806 unsigned SectionIndex
;
2809 SectionHeader
= (PIMAGE_SECTION_HEADER
)((char *) &NTHeaders
->OptionalHeader
2810 + NTHeaders
->FileHeader
.SizeOfOptionalHeader
);
2812 for (SectionIndex
= 0; SectionIndex
< NTHeaders
->FileHeader
.NumberOfSections
; SectionIndex
++)
2814 if (0 == (SectionHeader
->Characteristics
& IMAGE_SCN_LNK_REMOVE
)
2815 && ResidentSize
< SectionHeader
->VirtualAddress
+ SectionHeader
->Misc
.VirtualSize
)
2817 ResidentSize
= SectionHeader
->VirtualAddress
+ SectionHeader
->Misc
.VirtualSize
;
2822 return ResidentSize
;
2826 /***************************************************************************
2828 * LdrVerifyImageMatchesChecksum
2843 LdrVerifyImageMatchesChecksum (IN HANDLE FileHandle
,
2848 FILE_STANDARD_INFORMATION FileInfo
;
2849 IO_STATUS_BLOCK IoStatusBlock
;
2850 HANDLE SectionHandle
;
2856 DPRINT ("LdrVerifyImageMatchesChecksum() called\n");
2858 Status
= NtCreateSection (&SectionHandle
,
2865 if (!NT_SUCCESS(Status
))
2867 DPRINT1 ("NtCreateSection() failed (Status %lx)\n", Status
);
2873 Status
= NtMapViewOfSection (SectionHandle
,
2874 NtCurrentProcess (),
2883 if (!NT_SUCCESS(Status
))
2885 DPRINT1 ("NtMapViewOfSection() failed (Status %lx)\n", Status
);
2886 NtClose (SectionHandle
);
2890 Status
= NtQueryInformationFile (FileHandle
,
2893 sizeof (FILE_STANDARD_INFORMATION
),
2894 FileStandardInformation
);
2895 if (!NT_SUCCESS(Status
))
2897 DPRINT1 ("NtMapViewOfSection() failed (Status %lx)\n", Status
);
2898 NtUnmapViewOfSection (NtCurrentProcess (),
2900 NtClose (SectionHandle
);
2904 Result
= LdrpCheckImageChecksum (BaseAddress
,
2905 FileInfo
.EndOfFile
.u
.LowPart
);
2906 if (Result
== FALSE
)
2908 Status
= STATUS_IMAGE_CHECKSUM_MISMATCH
;
2911 NtUnmapViewOfSection (NtCurrentProcess (),
2914 NtClose (SectionHandle
);
2920 /***************************************************************************
2922 * LdrQueryImageFileExecutionOptions
2937 LdrQueryImageFileExecutionOptions (IN PUNICODE_STRING SubKey
,
2938 IN PCWSTR ValueName
,
2941 IN ULONG BufferSize
,
2942 OUT PULONG ReturnedLength OPTIONAL
)
2944 PKEY_VALUE_PARTIAL_INFORMATION KeyInfo
;
2945 OBJECT_ATTRIBUTES ObjectAttributes
;
2946 UNICODE_STRING ValueNameString
;
2947 UNICODE_STRING KeyName
;
2948 WCHAR NameBuffer
[256];
2956 L
"\\Registry\\Machine\\Software\\Microsoft\\Windows NT\\CurrentVersion\\Image File Execution Options\\");
2957 Ptr
= wcsrchr (SubKey
->Buffer
, L
'\\');
2960 Ptr
= SubKey
->Buffer
;
2966 wcscat (NameBuffer
, Ptr
);
2967 RtlInitUnicodeString (&KeyName
,
2970 InitializeObjectAttributes (&ObjectAttributes
,
2972 OBJ_CASE_INSENSITIVE
,
2976 Status
= NtOpenKey (&KeyHandle
,
2979 if (!NT_SUCCESS(Status
))
2981 DPRINT ("NtOpenKey() failed (Status %lx)\n", Status
);
2985 KeyInfoSize
= sizeof(KEY_VALUE_PARTIAL_INFORMATION
) + 32;
2986 KeyInfo
= RtlAllocateHeap (RtlGetProcessHeap(),
2990 RtlInitUnicodeString (&ValueNameString
,
2992 Status
= NtQueryValueKey (KeyHandle
,
2994 KeyValuePartialInformation
,
2998 if (Status
== STATUS_BUFFER_OVERFLOW
)
3000 KeyInfoSize
= sizeof(KEY_VALUE_PARTIAL_INFORMATION
) + KeyInfo
->DataLength
;
3001 RtlFreeHeap (RtlGetProcessHeap(),
3004 KeyInfo
= RtlAllocateHeap (RtlGetProcessHeap(),
3007 if (KeyInfo
== NULL
)
3009 NtClose (KeyHandle
);
3013 Status
= NtQueryValueKey (KeyHandle
,
3015 KeyValuePartialInformation
,
3020 NtClose (KeyHandle
);
3022 if (!NT_SUCCESS(Status
))
3024 if (KeyInfo
!= NULL
)
3026 RtlFreeHeap (RtlGetProcessHeap(),
3033 if (KeyInfo
->Type
!= Type
)
3035 RtlFreeHeap (RtlGetProcessHeap(),
3038 return STATUS_OBJECT_TYPE_MISMATCH
;
3041 ResultSize
= BufferSize
;
3042 if (ResultSize
< KeyInfo
->DataLength
)
3044 Status
= STATUS_BUFFER_OVERFLOW
;
3048 ResultSize
= KeyInfo
->DataLength
;
3050 RtlCopyMemory (Buffer
,
3054 RtlFreeHeap (RtlGetProcessHeap(),
3058 if (ReturnedLength
!= NULL
)
3060 *ReturnedLength
= ResultSize
;
3067 PIMAGE_BASE_RELOCATION NTAPI
3068 LdrProcessRelocationBlock(IN PVOID Address
,
3070 IN PUSHORT TypeOffset
,
3079 for (i
= 0; i
< Count
; i
++)
3081 Offset
= *TypeOffset
& 0xFFF;
3082 Type
= *TypeOffset
>> 12;
3086 case IMAGE_REL_BASED_ABSOLUTE
:
3089 case IMAGE_REL_BASED_HIGH
:
3090 ShortPtr
= (PUSHORT
)((ULONG_PTR
)Address
+ Offset
);
3091 *ShortPtr
+= HIWORD(Delta
);
3094 case IMAGE_REL_BASED_LOW
:
3095 ShortPtr
= (PUSHORT
)((ULONG_PTR
)Address
+ Offset
);
3096 *ShortPtr
+= LOWORD(Delta
);
3099 case IMAGE_REL_BASED_HIGHLOW
:
3100 LongPtr
= (PULONG
)((ULONG_PTR
)Address
+ Offset
);
3104 case IMAGE_REL_BASED_HIGHADJ
:
3105 case IMAGE_REL_BASED_MIPS_JMPADDR
:
3107 DPRINT1("Unknown/unsupported fixup type %hu.\n", Type
);
3114 return (PIMAGE_BASE_RELOCATION
)TypeOffset
;