2 * COPYRIGHT: See COPYING in the top level directory
3 * PROJECT: ReactOS kernel
4 * FILE: lib/ntdll/ldr/utils.c
5 * PURPOSE: Process startup for PE executables
6 * PROGRAMMERS: Jean Michault
7 * Rex Jolliff (rex@lvcablemodem.com)
13 * - Handle loading flags correctly
14 * - Handle errors correctly (unload dll's)
15 * - Implement a faster way to find modules (hash table)
19 /* INCLUDES *****************************************************************/
25 #define LDRP_PROCESS_CREATION_TIME 0xffff
26 #define RVA(m, b) ((PVOID)((ULONG_PTR)(b) + (ULONG_PTR)(m)))
28 /* GLOBALS *******************************************************************/
31 #define TRACE_LDR(...) if (RtlGetNtGlobalFlags() & FLG_SHOW_LDR_SNAPS) { DbgPrint("(LDR:%s:%d) ",__FILE__,__LINE__); DbgPrint(__VA_ARGS__); }
34 typedef struct _TLS_DATA
36 PVOID StartAddressOfRawData
;
39 PIMAGE_TLS_CALLBACK
*TlsAddressOfCallBacks
;
40 PLDR_DATA_TABLE_ENTRY Module
;
41 } TLS_DATA
, *PTLS_DATA
;
43 static BOOLEAN LdrpDllShutdownInProgress
= FALSE
;
44 static PTLS_DATA LdrpTlsArray
= NULL
;
45 static ULONG LdrpTlsCount
= 0;
46 static ULONG LdrpTlsSize
= 0;
47 static HANDLE LdrpKnownDllsDirHandle
= NULL
;
48 static UNICODE_STRING LdrpKnownDllPath
= {0, 0, NULL
};
49 static PLDR_DATA_TABLE_ENTRY LdrpLastModule
= NULL
;
50 extern PLDR_DATA_TABLE_ENTRY ExeModule
;
52 /* PROTOTYPES ****************************************************************/
54 static NTSTATUS
LdrFindEntryForName(PUNICODE_STRING Name
, PLDR_DATA_TABLE_ENTRY
*Module
, BOOLEAN Ref
);
55 static PVOID
LdrFixupForward(PCHAR ForwardName
);
56 static PVOID
LdrGetExportByName(PVOID BaseAddress
, PUCHAR SymbolName
, USHORT Hint
);
57 static NTSTATUS
LdrpLoadModule(IN PWSTR SearchPath OPTIONAL
,
59 IN PUNICODE_STRING Name
,
60 OUT PLDR_DATA_TABLE_ENTRY
*Module
,
61 OUT PVOID
*BaseAddress OPTIONAL
);
62 static NTSTATUS
LdrpAttachProcess(VOID
);
63 static VOID
LdrpDetachProcess(BOOLEAN UnloadAll
);
64 static NTSTATUS
LdrpUnloadModule(PLDR_DATA_TABLE_ENTRY Module
, BOOLEAN Unload
);
66 NTSTATUS
find_actctx_dll( LPCWSTR libname
, WCHAR
*fulldosname
);
67 NTSTATUS
create_module_activation_context( LDR_DATA_TABLE_ENTRY
*module
);
69 /* FUNCTIONS *****************************************************************/
72 LdrMappedAsDataFile(PVOID
*BaseAddress
)
74 if (0 != ((DWORD_PTR
) *BaseAddress
& (PAGE_SIZE
- 1)))
76 *BaseAddress
= (PVOID
) ((DWORD_PTR
) *BaseAddress
& ~ ((DWORD_PTR
) PAGE_SIZE
- 1));
83 static __inline LONG
LdrpDecrementLoadCount(PLDR_DATA_TABLE_ENTRY Module
, BOOLEAN Locked
)
88 RtlEnterCriticalSection (NtCurrentPeb()->LoaderLock
);
90 LoadCount
= Module
->LoadCount
;
91 if (Module
->LoadCount
> 0 && Module
->LoadCount
!= LDRP_PROCESS_CREATION_TIME
)
97 RtlLeaveCriticalSection(NtCurrentPeb()->LoaderLock
);
102 static __inline LONG
LdrpIncrementLoadCount(PLDR_DATA_TABLE_ENTRY Module
, BOOLEAN Locked
)
107 RtlEnterCriticalSection (NtCurrentPeb()->LoaderLock
);
109 LoadCount
= Module
->LoadCount
;
110 if (Module
->LoadCount
!= LDRP_PROCESS_CREATION_TIME
)
116 RtlLeaveCriticalSection(NtCurrentPeb()->LoaderLock
);
121 static __inline VOID
LdrpAcquireTlsSlot(PLDR_DATA_TABLE_ENTRY Module
, ULONG Size
, BOOLEAN Locked
)
125 RtlEnterCriticalSection (NtCurrentPeb()->LoaderLock
);
127 Module
->TlsIndex
= (SHORT
)LdrpTlsCount
;
132 RtlLeaveCriticalSection(NtCurrentPeb()->LoaderLock
);
136 static __inline VOID
LdrpTlsCallback(PLDR_DATA_TABLE_ENTRY Module
, ULONG dwReason
)
138 PIMAGE_TLS_CALLBACK
*TlsCallback
;
139 if (Module
->TlsIndex
!= 0xFFFF && Module
->LoadCount
== LDRP_PROCESS_CREATION_TIME
)
141 TlsCallback
= LdrpTlsArray
[Module
->TlsIndex
].TlsAddressOfCallBacks
;
146 TRACE_LDR("%wZ - Calling tls callback at %x\n",
147 &Module
->BaseDllName
, *TlsCallback
);
148 (*TlsCallback
)(Module
->DllBase
, dwReason
, NULL
);
155 static BOOLEAN
LdrpCallDllEntry(PLDR_DATA_TABLE_ENTRY Module
, DWORD dwReason
, PVOID lpReserved
)
157 if (!(Module
->Flags
& LDRP_IMAGE_DLL
) ||
158 Module
->EntryPoint
== 0)
162 LdrpTlsCallback(Module
, dwReason
);
163 return ((PDLLMAIN_FUNC
)Module
->EntryPoint
)(Module
->DllBase
, dwReason
, lpReserved
);
167 LdrpQueryAppPaths(IN PCWSTR ImageName
)
169 PKEY_VALUE_PARTIAL_INFORMATION KeyInfo
;
170 OBJECT_ATTRIBUTES ObjectAttributes
;
171 WCHAR SearchPathBuffer
[5*MAX_PATH
];
172 UNICODE_STRING ValueNameString
;
173 UNICODE_STRING KeyName
;
174 WCHAR NameBuffer
[MAX_PATH
];
182 _snwprintf(NameBuffer
,
183 sizeof(NameBuffer
) / sizeof(WCHAR
),
184 L
"\\Registry\\Machine\\Software\\Microsoft\\Windows\\CurrentVersion\\App Paths\\%s",
187 RtlInitUnicodeString(&KeyName
, NameBuffer
);
189 InitializeObjectAttributes(&ObjectAttributes
,
191 OBJ_CASE_INSENSITIVE
,
195 Status
= NtOpenKey(&KeyHandle
,
198 if (!NT_SUCCESS(Status
))
200 DPRINT ("NtOpenKey() failed (Status %lx)\n", Status
);
204 KeyInfoSize
= sizeof(KEY_VALUE_PARTIAL_INFORMATION
) + 256 * sizeof(WCHAR
);
206 KeyInfo
= RtlAllocateHeap(RtlGetProcessHeap(), 0, KeyInfoSize
);
209 DPRINT("RtlAllocateHeap() failed\n");
214 RtlInitUnicodeString(&ValueNameString
,
217 Status
= NtQueryValueKey(KeyHandle
,
219 KeyValuePartialInformation
,
224 if (!NT_SUCCESS(Status
))
227 RtlFreeHeap(RtlGetProcessHeap(), 0, KeyInfo
);
231 RtlCopyMemory(SearchPathBuffer
,
233 KeyInfo
->DataLength
);
235 /* Free KeyInfo memory, we won't need it anymore */
236 RtlFreeHeap(RtlGetProcessHeap(), 0, KeyInfo
);
238 /* Close the key handle */
241 /* get application running path */
242 wcscat(SearchPathBuffer
, L
";");
243 wcscat(SearchPathBuffer
, NtCurrentPeb()->ProcessParameters
->ImagePathName
.Buffer
); // FIXME: Don't rely on it being NULL-terminated!!!
245 /* Remove trailing backslash */
246 Backslash
= wcsrchr(SearchPathBuffer
, L
'\\');
247 if (Backslash
) Backslash
= L
'\0';
249 wcscat(SearchPathBuffer
, L
";");
251 wcscat(SearchPathBuffer
, SharedUserData
->NtSystemRoot
);
252 wcscat(SearchPathBuffer
, L
"\\system32;");
253 wcscat(SearchPathBuffer
, SharedUserData
->NtSystemRoot
);
254 wcscat(SearchPathBuffer
, L
";.");
256 /* Copy it to the heap allocd memory */
257 Path
= RtlAllocateHeap(RtlGetProcessHeap(),
259 wcslen(SearchPathBuffer
) * sizeof(WCHAR
));
263 DPRINT1("RtlAllocateHeap() failed\n");
267 wcscpy(Path
, SearchPathBuffer
);
273 LdrpInitializeTlsForThread(VOID
)
279 PTEB Teb
= NtCurrentTeb();
281 DPRINT("LdrpInitializeTlsForThread() called for %wZ\n", &ExeModule
->BaseDllName
);
283 Teb
->StaticUnicodeString
.Length
= 0;
284 Teb
->StaticUnicodeString
.MaximumLength
= sizeof(Teb
->StaticUnicodeBuffer
);
285 Teb
->StaticUnicodeString
.Buffer
= Teb
->StaticUnicodeBuffer
;
287 if (LdrpTlsCount
> 0)
289 TlsPointers
= RtlAllocateHeap(RtlGetProcessHeap(),
291 LdrpTlsCount
* sizeof(PVOID
) + LdrpTlsSize
);
292 if (TlsPointers
== NULL
)
294 DPRINT1("failed to allocate thread tls data\n");
295 return STATUS_NO_MEMORY
;
298 TlsData
= (PVOID
)((ULONG_PTR
)TlsPointers
+ LdrpTlsCount
* sizeof(PVOID
));
299 Teb
->ThreadLocalStoragePointer
= TlsPointers
;
301 TlsInfo
= LdrpTlsArray
;
302 for (i
= 0; i
< LdrpTlsCount
; i
++, TlsInfo
++)
304 TRACE_LDR("Initialize tls data for %wZ\n", &TlsInfo
->Module
->BaseDllName
);
305 TlsPointers
[i
] = TlsData
;
306 if (TlsInfo
->TlsDataSize
)
308 memcpy(TlsData
, TlsInfo
->StartAddressOfRawData
, TlsInfo
->TlsDataSize
);
309 TlsData
= (PVOID
)((ULONG_PTR
)TlsData
+ TlsInfo
->TlsDataSize
);
311 if (TlsInfo
->TlsZeroSize
)
313 memset(TlsData
, 0, TlsInfo
->TlsZeroSize
);
314 TlsData
= (PVOID
)((ULONG_PTR
)TlsData
+ TlsInfo
->TlsZeroSize
);
319 DPRINT("LdrpInitializeTlsForThread() done\n");
320 return STATUS_SUCCESS
;
324 LdrpInitializeTlsForProccess(VOID
)
326 PLIST_ENTRY ModuleListHead
;
328 PLDR_DATA_TABLE_ENTRY Module
;
329 PIMAGE_TLS_DIRECTORY TlsDirectory
;
333 DPRINT("LdrpInitializeTlsForProccess() called for %wZ\n", &ExeModule
->BaseDllName
);
335 if (LdrpTlsCount
> 0)
337 LdrpTlsArray
= RtlAllocateHeap(RtlGetProcessHeap(),
339 LdrpTlsCount
* sizeof(TLS_DATA
));
340 if (LdrpTlsArray
== NULL
)
342 DPRINT1("Failed to allocate global tls data\n");
343 return STATUS_NO_MEMORY
;
346 ModuleListHead
= &NtCurrentPeb()->Ldr
->InLoadOrderModuleList
;
347 Entry
= ModuleListHead
->Flink
;
348 while (Entry
!= ModuleListHead
)
350 Module
= CONTAINING_RECORD(Entry
, LDR_DATA_TABLE_ENTRY
, InLoadOrderLinks
);
351 if (Module
->LoadCount
== LDRP_PROCESS_CREATION_TIME
&&
352 Module
->TlsIndex
!= 0xFFFF)
354 TlsDirectory
= (PIMAGE_TLS_DIRECTORY
)
355 RtlImageDirectoryEntryToData(Module
->DllBase
,
357 IMAGE_DIRECTORY_ENTRY_TLS
,
359 ASSERT(Module
->TlsIndex
< LdrpTlsCount
);
360 TlsData
= &LdrpTlsArray
[Module
->TlsIndex
];
361 TlsData
->StartAddressOfRawData
= (PVOID
)TlsDirectory
->StartAddressOfRawData
;
362 TlsData
->TlsDataSize
= TlsDirectory
->EndAddressOfRawData
- TlsDirectory
->StartAddressOfRawData
;
363 TlsData
->TlsZeroSize
= TlsDirectory
->SizeOfZeroFill
;
364 if (TlsDirectory
->AddressOfCallBacks
)
365 TlsData
->TlsAddressOfCallBacks
= (PIMAGE_TLS_CALLBACK
*)TlsDirectory
->AddressOfCallBacks
;
367 TlsData
->TlsAddressOfCallBacks
= NULL
;
368 TlsData
->Module
= Module
;
370 DbgPrint("TLS directory for %wZ\n", &Module
->BaseDllName
);
371 DbgPrint("StartAddressOfRawData: %x\n", TlsDirectory
->StartAddressOfRawData
);
372 DbgPrint("EndAddressOfRawData: %x\n", TlsDirectory
->EndAddressOfRawData
);
373 DbgPrint("SizeOfRawData: %d\n", TlsDirectory
->EndAddressOfRawData
- TlsDirectory
->StartAddressOfRawData
);
374 DbgPrint("AddressOfIndex: %x\n", TlsDirectory
->AddressOfIndex
);
375 DbgPrint("AddressOfCallBacks: %x\n", TlsDirectory
->AddressOfCallBacks
);
376 DbgPrint("SizeOfZeroFill: %d\n", TlsDirectory
->SizeOfZeroFill
);
377 DbgPrint("Characteristics: %x\n", TlsDirectory
->Characteristics
);
381 * Is this region allways writable ?
383 *(PULONG
)TlsDirectory
->AddressOfIndex
= Module
->TlsIndex
;
385 Entry
= Entry
->Flink
;
389 DPRINT("LdrpInitializeTlsForProccess() done\n");
390 return STATUS_SUCCESS
;
396 OBJECT_ATTRIBUTES ObjectAttributes
;
397 UNICODE_STRING LinkTarget
;
403 DPRINT("LdrpInitLoader() called for %wZ\n", &ExeModule
->BaseDllName
);
405 /* Get handle to the 'KnownDlls' directory */
406 RtlInitUnicodeString(&Name
,
408 InitializeObjectAttributes(&ObjectAttributes
,
410 OBJ_CASE_INSENSITIVE
,
413 Status
= NtOpenDirectoryObject(&LdrpKnownDllsDirHandle
,
414 DIRECTORY_QUERY
| DIRECTORY_TRAVERSE
,
416 if (!NT_SUCCESS(Status
))
418 DPRINT("NtOpenDirectoryObject() failed (Status %lx)\n", Status
);
419 LdrpKnownDllsDirHandle
= NULL
;
423 /* Allocate target name string */
424 LinkTarget
.Length
= 0;
425 LinkTarget
.MaximumLength
= MAX_PATH
* sizeof(WCHAR
);
426 LinkTarget
.Buffer
= RtlAllocateHeap(RtlGetProcessHeap(),
428 MAX_PATH
* sizeof(WCHAR
));
429 if (LinkTarget
.Buffer
== NULL
)
431 NtClose(LdrpKnownDllsDirHandle
);
432 LdrpKnownDllsDirHandle
= NULL
;
436 RtlInitUnicodeString(&Name
,
438 InitializeObjectAttributes(&ObjectAttributes
,
440 OBJ_CASE_INSENSITIVE
,
441 LdrpKnownDllsDirHandle
,
443 Status
= NtOpenSymbolicLinkObject(&LinkHandle
,
444 SYMBOLIC_LINK_ALL_ACCESS
,
446 if (!NT_SUCCESS(Status
))
448 RtlFreeUnicodeString(&LinkTarget
);
449 NtClose(LdrpKnownDllsDirHandle
);
450 LdrpKnownDllsDirHandle
= NULL
;
454 Status
= NtQuerySymbolicLinkObject(LinkHandle
,
458 if (!NT_SUCCESS(Status
))
460 RtlFreeUnicodeString(&LinkTarget
);
461 NtClose(LdrpKnownDllsDirHandle
);
462 LdrpKnownDllsDirHandle
= NULL
;
465 RtlCreateUnicodeString(&LdrpKnownDllPath
,
468 RtlFreeUnicodeString(&LinkTarget
);
470 DPRINT("LdrpInitLoader() done\n");
474 /***************************************************************************
479 * Adjusts the name of a dll to a fully qualified name.
482 * FullDllName: Pointer to caller supplied storage for the fully
483 * qualified dll name.
484 * DllName: Pointer to the dll name.
485 * BaseName: TRUE: Only the file name is passed to FullDllName
486 * FALSE: The full path is preserved in FullDllName
494 * A given path is not affected by the adjustment, but the file
496 * ntdll --> ntdll.dll
498 * ntdll.xyz --> ntdll.xyz
501 LdrAdjustDllName (PUNICODE_STRING FullDllName
,
502 PUNICODE_STRING DllName
,
505 WCHAR Buffer
[MAX_PATH
];
510 Length
= DllName
->Length
/ sizeof(WCHAR
);
514 /* get the base dll name */
515 Pointer
= DllName
->Buffer
+ Length
;
522 while (Pointer
>= DllName
->Buffer
&& *Pointer
!= L
'\\' && *Pointer
!= L
'/');
525 Length
= Extension
- Pointer
;
526 memmove (Buffer
, Pointer
, Length
* sizeof(WCHAR
));
527 Buffer
[Length
] = L
'\0';
531 /* get the full dll name */
532 memmove (Buffer
, DllName
->Buffer
, DllName
->Length
);
533 Buffer
[DllName
->Length
/ sizeof(WCHAR
)] = L
'\0';
536 /* Build the DLL's absolute name */
537 Extension
= wcsrchr (Buffer
, L
'.');
538 if ((Extension
!= NULL
) && (*Extension
== L
'.'))
540 /* with extension - remove dot if it's the last character */
541 if (Buffer
[Length
- 1] == L
'.')
547 /* name without extension - assume that it is .dll */
548 memmove (Buffer
+ Length
, L
".dll", 10);
551 RtlCreateUnicodeString(FullDllName
, Buffer
);
554 PLDR_DATA_TABLE_ENTRY
555 LdrAddModuleEntry(PVOID ImageBase
,
556 PIMAGE_NT_HEADERS NTHeaders
,
559 PLDR_DATA_TABLE_ENTRY Module
;
561 Module
= RtlAllocateHeap(RtlGetProcessHeap(), 0, sizeof (LDR_DATA_TABLE_ENTRY
));
563 memset(Module
, 0, sizeof(LDR_DATA_TABLE_ENTRY
));
564 Module
->DllBase
= (PVOID
)ImageBase
;
565 Module
->EntryPoint
= (PVOID
)(ULONG_PTR
)NTHeaders
->OptionalHeader
.AddressOfEntryPoint
;
566 if (Module
->EntryPoint
!= 0)
567 Module
->EntryPoint
= (PVOID
)((ULONG_PTR
)Module
->EntryPoint
+ (ULONG_PTR
)Module
->DllBase
);
568 Module
->SizeOfImage
= LdrpGetResidentSize(NTHeaders
);
569 if (NtCurrentPeb()->Ldr
->Initialized
== TRUE
)
571 /* loading while app is running */
572 Module
->LoadCount
= 1;
575 * loading while app is initializing
576 * dll must not be unloaded
578 Module
->LoadCount
= LDRP_PROCESS_CREATION_TIME
;
582 Module
->TlsIndex
= -1;
583 Module
->CheckSum
= NTHeaders
->OptionalHeader
.CheckSum
;
584 Module
->TimeDateStamp
= NTHeaders
->FileHeader
.TimeDateStamp
;
586 RtlCreateUnicodeString (&Module
->FullDllName
,
588 RtlCreateUnicodeString (&Module
->BaseDllName
,
589 wcsrchr(FullDosName
, L
'\\') + 1);
590 DPRINT ("BaseDllName %wZ\n", &Module
->BaseDllName
);
592 RtlEnterCriticalSection (NtCurrentPeb()->LoaderLock
);
593 InsertTailList(&NtCurrentPeb()->Ldr
->InLoadOrderModuleList
,
594 &Module
->InLoadOrderLinks
);
595 RtlLeaveCriticalSection(NtCurrentPeb()->LoaderLock
);
602 LdrpMapKnownDll(IN PUNICODE_STRING DllName
,
603 OUT PUNICODE_STRING FullDosName
,
604 OUT PHANDLE SectionHandle
)
606 OBJECT_ATTRIBUTES ObjectAttributes
;
609 DPRINT("LdrpMapKnownDll() called\n");
611 if (LdrpKnownDllsDirHandle
== NULL
)
613 DPRINT("Invalid 'KnownDlls' directory\n");
614 return STATUS_UNSUCCESSFUL
;
617 DPRINT("LdrpKnownDllPath '%wZ'\n", &LdrpKnownDllPath
);
619 InitializeObjectAttributes(&ObjectAttributes
,
621 OBJ_CASE_INSENSITIVE
,
622 LdrpKnownDllsDirHandle
,
624 Status
= NtOpenSection(SectionHandle
,
625 SECTION_MAP_READ
| SECTION_MAP_WRITE
| SECTION_MAP_EXECUTE
,
627 if (!NT_SUCCESS(Status
))
629 DPRINT("NtOpenSection() failed for '%wZ' (Status 0x%08lx)\n", DllName
, Status
);
633 FullDosName
->Length
= LdrpKnownDllPath
.Length
+ DllName
->Length
+ sizeof(WCHAR
);
634 FullDosName
->MaximumLength
= FullDosName
->Length
+ sizeof(WCHAR
);
635 FullDosName
->Buffer
= RtlAllocateHeap(RtlGetProcessHeap(),
637 FullDosName
->MaximumLength
);
638 if (FullDosName
->Buffer
== NULL
)
640 FullDosName
->Length
= 0;
641 FullDosName
->MaximumLength
= 0;
642 return STATUS_SUCCESS
;
645 wcscpy(FullDosName
->Buffer
, LdrpKnownDllPath
.Buffer
);
646 wcscat(FullDosName
->Buffer
, L
"\\");
647 wcscat(FullDosName
->Buffer
, DllName
->Buffer
);
649 DPRINT("FullDosName '%wZ'\n", FullDosName
);
651 DPRINT("LdrpMapKnownDll() done\n");
653 return STATUS_SUCCESS
;
658 LdrpMapDllImageFile(IN PWSTR SearchPath OPTIONAL
,
659 IN PUNICODE_STRING DllName
,
660 OUT PUNICODE_STRING FullDosName
,
661 IN BOOLEAN MapAsDataFile
,
662 OUT PHANDLE SectionHandle
)
664 WCHAR
*SearchPathBuffer
= NULL
;
665 WCHAR
*ImagePathNameBufferPtr
= NULL
;
666 WCHAR DosName
[MAX_PATH
];
667 UNICODE_STRING FullNtFileName
;
668 UNICODE_STRING PathEnvironmentVar_U
;
669 UNICODE_STRING PathName_U
;
670 OBJECT_ATTRIBUTES FileObjectAttributes
;
672 char BlockBuffer
[1024];
673 PIMAGE_DOS_HEADER DosHeader
;
674 PIMAGE_NT_HEADERS NTHeaders
;
675 IO_STATUS_BLOCK IoStatusBlock
;
680 DPRINT("LdrpMapDllImageFile() called\n");
682 if (SearchPath
== NULL
)
684 /* get application running path */
685 ImagePathNameBufferPtr
= NtCurrentPeb()->ProcessParameters
->ImagePathName
.Buffer
;
687 /* Length of ImagePathName */
688 ImagePathLen
= wcslen(ImagePathNameBufferPtr
);
690 /* Subtract application name leaveing only the directory length */
691 while (ImagePathLen
&& ImagePathNameBufferPtr
[ImagePathLen
- 1] != L
'\\')
694 /* Length of directory + semicolon */
695 len
= ImagePathLen
+ 1;
697 /* Length of SystemRoot + "//system32" + semicolon*/
698 len
+= wcslen(SharedUserData
->NtSystemRoot
) + 10;
699 /* Length of SystemRoot + semicolon */
700 len
+= wcslen(SharedUserData
->NtSystemRoot
) + 1;
702 RtlInitUnicodeString (&PathName_U
, L
"PATH");
703 PathEnvironmentVar_U
.Length
= 0;
704 PathEnvironmentVar_U
.MaximumLength
= 0;
705 PathEnvironmentVar_U
.Buffer
= NULL
;
707 /* Get the path environment variable */
708 Status
= RtlQueryEnvironmentVariable_U(NULL
, &PathName_U
, &PathEnvironmentVar_U
);
710 /* Check that valid information was returned */
711 if ((Status
== STATUS_BUFFER_TOO_SMALL
) && (PathEnvironmentVar_U
.Length
> 0))
713 /* Allocate memory for the path env var */
714 PathEnvironmentVar_U
.Buffer
= RtlAllocateHeap(RtlGetProcessHeap(), HEAP_ZERO_MEMORY
, PathEnvironmentVar_U
.Length
+ sizeof(WCHAR
));
715 if (!PathEnvironmentVar_U
.Buffer
)
717 DPRINT1("Fatal! Out of Memory!!\n");
718 return STATUS_NO_MEMORY
;
720 PathEnvironmentVar_U
.MaximumLength
= PathEnvironmentVar_U
.Length
+ sizeof(WCHAR
);
723 Status
= RtlQueryEnvironmentVariable_U(NULL
, &PathName_U
, &PathEnvironmentVar_U
);
725 if (!NT_SUCCESS(Status
))
727 DPRINT1("Unable to get path environment string!\n");
730 /* Length of path evn var + semicolon */
731 len
+= (PathEnvironmentVar_U
.Length
/ sizeof(WCHAR
)) + 1;
734 /* Allocate the size needed to hold all the above paths + period */
735 SearchPathBuffer
= RtlAllocateHeap(RtlGetProcessHeap(), HEAP_ZERO_MEMORY
, (len
+ 2) * sizeof(WCHAR
));
736 if (!SearchPathBuffer
)
738 DPRINT1("Fatal! Out of Memory!!\n");
739 return STATUS_NO_MEMORY
;
742 wcsncpy(SearchPathBuffer
, ImagePathNameBufferPtr
, ImagePathLen
);
743 wcscat (SearchPathBuffer
, L
";");
744 wcscat (SearchPathBuffer
, SharedUserData
->NtSystemRoot
);
745 wcscat (SearchPathBuffer
, L
"\\system32;");
746 wcscat (SearchPathBuffer
, SharedUserData
->NtSystemRoot
);
747 wcscat (SearchPathBuffer
, L
";");
749 if (PathEnvironmentVar_U
.Buffer
)
751 wcscat (SearchPathBuffer
, PathEnvironmentVar_U
.Buffer
);
752 wcscat (SearchPathBuffer
, L
";");
753 RtlFreeHeap(RtlGetProcessHeap(), 0, PathEnvironmentVar_U
.Buffer
);
755 wcscat (SearchPathBuffer
, L
".");
757 SearchPath
= SearchPathBuffer
;
760 if (RtlDosSearchPath_U (SearchPath
,
767 /* try to find active context dll */
768 Status
= find_actctx_dll(DllName
->Buffer
, DosName
);
769 if(Status
== STATUS_SUCCESS
)
770 DPRINT("found %S for %S\n", DosName
,DllName
->Buffer
);
772 return STATUS_DLL_NOT_FOUND
;
775 if (!RtlDosPathNameToNtPathName_U (DosName
,
780 DPRINT("Dll %wZ not found!\n", DllName
);
781 return STATUS_DLL_NOT_FOUND
;
784 DPRINT("FullNtFileName %wZ\n", &FullNtFileName
);
786 InitializeObjectAttributes(&FileObjectAttributes
,
792 DPRINT("Opening dll \"%wZ\"\n", &FullNtFileName
);
794 Status
= NtOpenFile(&FileHandle
,
795 GENERIC_READ
|SYNCHRONIZE
,
796 &FileObjectAttributes
,
799 FILE_SYNCHRONOUS_IO_NONALERT
);
800 if (!NT_SUCCESS(Status
))
802 DPRINT1("Dll open of %wZ failed: Status = 0x%08lx\n",
803 &FullNtFileName
, Status
);
804 RtlFreeHeap (RtlGetProcessHeap (),
806 FullNtFileName
.Buffer
);
809 RtlFreeHeap (RtlGetProcessHeap (),
811 FullNtFileName
.Buffer
);
816 Status
= NtReadFile(FileHandle
,
825 if (!NT_SUCCESS(Status
))
827 DPRINT("Dll header read failed: Status = 0x%08lx\n", Status
);
833 * Overlay DOS and NT headers structures to the
834 * buffer with DLL's header raw data.
836 DosHeader
= (PIMAGE_DOS_HEADER
) BlockBuffer
;
837 NTHeaders
= (PIMAGE_NT_HEADERS
) (BlockBuffer
+ DosHeader
->e_lfanew
);
839 * Check it is a PE image file.
841 if ((DosHeader
->e_magic
!= IMAGE_DOS_SIGNATURE
)
842 || (DosHeader
->e_lfanew
== 0L)
843 || (*(PULONG
)(NTHeaders
) != IMAGE_NT_SIGNATURE
))
845 DPRINT("NTDLL format invalid\n");
848 return STATUS_UNSUCCESSFUL
;
853 * Create a section for dll.
855 Status
= NtCreateSection(SectionHandle
,
860 MapAsDataFile
? SEC_COMMIT
: SEC_IMAGE
,
864 if (!NT_SUCCESS(Status
))
866 DPRINT("NTDLL create section failed: Status = 0x%08lx\n", Status
);
870 RtlCreateUnicodeString(FullDosName
,
878 /***************************************************************************
895 LdrLoadDll (IN PWSTR SearchPath OPTIONAL
,
896 IN PULONG LoadFlags OPTIONAL
,
897 IN PUNICODE_STRING Name
,
898 OUT PVOID
*BaseAddress
/* also known as HMODULE*, and PHANDLE 'DllHandle' */)
901 PLDR_DATA_TABLE_ENTRY Module
;
903 PPEB Peb
= NtCurrentPeb();
905 TRACE_LDR("LdrLoadDll loading %wZ%S%S with flags %d\n",
907 SearchPath
? L
" from " : L
"",
908 SearchPath
? SearchPath
: L
"",
909 LoadFlags
? *LoadFlags
: 0);
911 Status
= LdrpLoadModule(SearchPath
, LoadFlags
? *LoadFlags
: 0, Name
, &Module
, BaseAddress
);
913 if (NT_SUCCESS(Status
) &&
914 (!LoadFlags
|| 0 == (*LoadFlags
& LOAD_LIBRARY_AS_DATAFILE
)))
916 if (!create_module_activation_context( Module
))
918 RtlActivateActivationContext(0, Module
->EntryPointActivationContext
, &cookie
);
921 if (!(Module
->Flags
& LDRP_PROCESS_ATTACH_CALLED
))
923 RtlEnterCriticalSection(Peb
->LoaderLock
);
924 Status
= LdrpAttachProcess();
925 RtlLeaveCriticalSection(Peb
->LoaderLock
);
927 if (Module
->EntryPointActivationContext
) RtlDeactivateActivationContext(0, cookie
);
930 if ((!Module
) && (NT_SUCCESS(Status
)))
933 *BaseAddress
= NT_SUCCESS(Status
) ? Module
->DllBase
: NULL
;
939 /***************************************************************************
941 * LdrFindEntryForAddress
956 LdrFindEntryForAddress(PVOID Address
,
957 PLDR_DATA_TABLE_ENTRY
*Module
)
959 PLIST_ENTRY ModuleListHead
;
961 PLDR_DATA_TABLE_ENTRY ModulePtr
;
963 DPRINT("LdrFindEntryForAddress(Address %p)\n", Address
);
965 if (NtCurrentPeb()->Ldr
== NULL
)
966 return(STATUS_NO_MORE_ENTRIES
);
968 RtlEnterCriticalSection(NtCurrentPeb()->LoaderLock
);
969 ModuleListHead
= &NtCurrentPeb()->Ldr
->InLoadOrderModuleList
;
970 Entry
= ModuleListHead
->Flink
;
971 if (Entry
== ModuleListHead
)
973 RtlLeaveCriticalSection(NtCurrentPeb()->LoaderLock
);
974 return(STATUS_NO_MORE_ENTRIES
);
977 while (Entry
!= ModuleListHead
)
979 ModulePtr
= CONTAINING_RECORD(Entry
, LDR_DATA_TABLE_ENTRY
, InLoadOrderLinks
);
981 DPRINT("Scanning %wZ at %p\n", &ModulePtr
->BaseDllName
, ModulePtr
->DllBase
);
983 if ((Address
>= ModulePtr
->DllBase
) &&
984 ((ULONG_PTR
)Address
<= ((ULONG_PTR
)ModulePtr
->DllBase
+ ModulePtr
->SizeOfImage
)))
987 RtlLeaveCriticalSection(NtCurrentPeb()->LoaderLock
);
988 return(STATUS_SUCCESS
);
991 Entry
= Entry
->Flink
;
994 DPRINT("Failed to find module entry.\n");
996 RtlLeaveCriticalSection(NtCurrentPeb()->LoaderLock
);
997 return(STATUS_NO_MORE_ENTRIES
);
1001 /***************************************************************************
1003 * LdrFindEntryForName
1017 LdrFindEntryForName(PUNICODE_STRING Name
,
1018 PLDR_DATA_TABLE_ENTRY
*Module
,
1021 PLIST_ENTRY ModuleListHead
;
1023 PLDR_DATA_TABLE_ENTRY ModulePtr
;
1024 BOOLEAN ContainsPath
;
1025 UNICODE_STRING AdjustedName
;
1027 DPRINT("LdrFindEntryForName(Name %wZ)\n", Name
);
1029 if (NtCurrentPeb()->Ldr
== NULL
)
1030 return(STATUS_NO_MORE_ENTRIES
);
1032 RtlEnterCriticalSection(NtCurrentPeb()->LoaderLock
);
1033 ModuleListHead
= &NtCurrentPeb()->Ldr
->InLoadOrderModuleList
;
1034 Entry
= ModuleListHead
->Flink
;
1035 if (Entry
== ModuleListHead
)
1037 RtlLeaveCriticalSection(NtCurrentPeb()->LoaderLock
);
1038 return(STATUS_NO_MORE_ENTRIES
);
1041 // NULL is the current process
1044 *Module
= ExeModule
;
1045 RtlLeaveCriticalSection(NtCurrentPeb()->LoaderLock
);
1046 return(STATUS_SUCCESS
);
1049 ContainsPath
= (Name
->Length
>= 2 * sizeof(WCHAR
) && L
':' == Name
->Buffer
[1]);
1050 LdrAdjustDllName (&AdjustedName
, Name
, !ContainsPath
);
1054 if ((! ContainsPath
&&
1055 0 == RtlCompareUnicodeString(&LdrpLastModule
->BaseDllName
, &AdjustedName
, TRUE
)) ||
1057 0 == RtlCompareUnicodeString(&LdrpLastModule
->FullDllName
, &AdjustedName
, TRUE
)))
1059 *Module
= LdrpLastModule
;
1060 if (Ref
&& (*Module
)->LoadCount
!= LDRP_PROCESS_CREATION_TIME
)
1062 (*Module
)->LoadCount
++;
1064 RtlLeaveCriticalSection(NtCurrentPeb()->LoaderLock
);
1065 RtlFreeUnicodeString(&AdjustedName
);
1066 return(STATUS_SUCCESS
);
1069 while (Entry
!= ModuleListHead
)
1071 ModulePtr
= CONTAINING_RECORD(Entry
, LDR_DATA_TABLE_ENTRY
, InLoadOrderLinks
);
1073 DPRINT("Scanning %wZ %wZ\n", &ModulePtr
->BaseDllName
, &AdjustedName
);
1075 if ((! ContainsPath
&&
1076 0 == RtlCompareUnicodeString(&ModulePtr
->BaseDllName
, &AdjustedName
, TRUE
)) ||
1078 0 == RtlCompareUnicodeString(&ModulePtr
->FullDllName
, &AdjustedName
, TRUE
)))
1080 *Module
= LdrpLastModule
= ModulePtr
;
1081 if (Ref
&& ModulePtr
->LoadCount
!= LDRP_PROCESS_CREATION_TIME
)
1083 ModulePtr
->LoadCount
++;
1085 RtlLeaveCriticalSection(NtCurrentPeb()->LoaderLock
);
1086 RtlFreeUnicodeString(&AdjustedName
);
1087 return(STATUS_SUCCESS
);
1090 Entry
= Entry
->Flink
;
1093 DPRINT("Failed to find dll %wZ\n", Name
);
1094 RtlLeaveCriticalSection(NtCurrentPeb()->LoaderLock
);
1095 RtlFreeUnicodeString(&AdjustedName
);
1096 return(STATUS_NO_MORE_ENTRIES
);
1099 /**********************************************************************
1115 LdrFixupForward(PCHAR ForwardName
)
1117 CHAR NameBuffer
[128];
1118 UNICODE_STRING DllName
;
1121 PLDR_DATA_TABLE_ENTRY Module
;
1124 strcpy(NameBuffer
, ForwardName
);
1125 p
= strchr(NameBuffer
, '.');
1130 DPRINT("Dll: %s Function: %s\n", NameBuffer
, p
+1);
1131 RtlCreateUnicodeStringFromAsciiz (&DllName
,
1134 Status
= LdrFindEntryForName (&DllName
, &Module
, FALSE
);
1136 * The caller (or the image) is responsible for loading of the dll, where the function is forwarded.
1138 if (!NT_SUCCESS(Status
))
1140 Status
= LdrLoadDll(NULL
,
1144 if (NT_SUCCESS(Status
))
1146 Status
= LdrFindEntryForName (&DllName
, &Module
, FALSE
);
1149 RtlFreeUnicodeString (&DllName
);
1150 if (!NT_SUCCESS(Status
))
1152 DPRINT1("LdrFixupForward: failed to load %s\n", NameBuffer
);
1156 DPRINT("BaseAddress: %p\n", Module
->DllBase
);
1158 return LdrGetExportByName(Module
->DllBase
, (PUCHAR
)(p
+1), -1);
1165 /**********************************************************************
1167 * LdrGetExportByOrdinal
1181 LdrGetExportByOrdinal (
1186 PIMAGE_EXPORT_DIRECTORY ExportDir
;
1187 ULONG ExportDirSize
;
1188 PDWORD
* ExFunctions
;
1191 ExportDir
= (PIMAGE_EXPORT_DIRECTORY
)
1192 RtlImageDirectoryEntryToData (BaseAddress
,
1194 IMAGE_DIRECTORY_ENTRY_EXPORT
,
1198 ExFunctions
= (PDWORD
*)
1201 ExportDir
->AddressOfFunctions
1204 "LdrGetExportByOrdinal(Ordinal %lu) = %p\n",
1206 RVA(BaseAddress
, ExFunctions
[Ordinal
- ExportDir
->Base
] )
1209 Function
= (0 != ExFunctions
[Ordinal
- ExportDir
->Base
]
1210 ? RVA(BaseAddress
, ExFunctions
[Ordinal
- ExportDir
->Base
] )
1213 if (((ULONG_PTR
)Function
>= (ULONG_PTR
)ExportDir
) &&
1214 ((ULONG_PTR
)Function
< (ULONG_PTR
)ExportDir
+ (ULONG_PTR
)ExportDirSize
))
1216 DPRINT("Forward: %s\n", (PCHAR
)Function
);
1217 Function
= LdrFixupForward((PCHAR
)Function
);
1224 /**********************************************************************
1226 * LdrGetExportByName
1237 * AddressOfNames and AddressOfNameOrdinals are paralell tables,
1238 * both with NumberOfNames entries.
1242 LdrGetExportByName(PVOID BaseAddress
,
1246 PIMAGE_EXPORT_DIRECTORY ExportDir
;
1247 PDWORD
* ExFunctions
;
1249 USHORT
* ExOrdinals
;
1254 ULONG ExportDirSize
;
1256 DPRINT("LdrGetExportByName %p %s %hu\n", BaseAddress
, SymbolName
, Hint
);
1258 ExportDir
= (PIMAGE_EXPORT_DIRECTORY
)
1259 RtlImageDirectoryEntryToData(BaseAddress
,
1261 IMAGE_DIRECTORY_ENTRY_EXPORT
,
1263 if (ExportDir
== NULL
)
1265 DPRINT1("LdrGetExportByName(): no export directory, "
1266 "can't lookup %s/%hu!\n", SymbolName
, Hint
);
1271 //The symbol names may be missing entirely
1272 if (ExportDir
->AddressOfNames
== 0)
1274 DPRINT("LdrGetExportByName(): symbol names missing entirely\n");
1279 * Get header pointers
1281 ExNames
= (PDWORD
*)RVA(BaseAddress
,
1282 ExportDir
->AddressOfNames
);
1283 ExOrdinals
= (USHORT
*)RVA(BaseAddress
,
1284 ExportDir
->AddressOfNameOrdinals
);
1285 ExFunctions
= (PDWORD
*)RVA(BaseAddress
,
1286 ExportDir
->AddressOfFunctions
);
1289 * Check the hint first
1291 if (Hint
< ExportDir
->NumberOfNames
)
1293 ExName
= RVA(BaseAddress
, ExNames
[Hint
]);
1294 if (strcmp(ExName
, (PCHAR
)SymbolName
) == 0)
1296 Ordinal
= ExOrdinals
[Hint
];
1297 Function
= RVA(BaseAddress
, ExFunctions
[Ordinal
]);
1298 if (((ULONG_PTR
)Function
>= (ULONG_PTR
)ExportDir
) &&
1299 ((ULONG_PTR
)Function
< (ULONG_PTR
)ExportDir
+ (ULONG_PTR
)ExportDirSize
))
1301 DPRINT("Forward: %s\n", (PCHAR
)Function
);
1302 Function
= LdrFixupForward((PCHAR
)Function
);
1303 if (Function
== NULL
)
1305 DPRINT1("LdrGetExportByName(): failed to find %s\n",SymbolName
);
1309 if (Function
!= NULL
)
1318 maxn
= ExportDir
->NumberOfNames
- 1;
1319 while (minn
<= maxn
)
1324 mid
= (minn
+ maxn
) / 2;
1326 ExName
= RVA(BaseAddress
, ExNames
[mid
]);
1327 res
= strcmp(ExName
, (PCHAR
)SymbolName
);
1330 Ordinal
= ExOrdinals
[mid
];
1331 Function
= RVA(BaseAddress
, ExFunctions
[Ordinal
]);
1332 if (((ULONG_PTR
)Function
>= (ULONG_PTR
)ExportDir
) &&
1333 ((ULONG_PTR
)Function
< (ULONG_PTR
)ExportDir
+ (ULONG_PTR
)ExportDirSize
))
1335 DPRINT("Forward: %s\n", (PCHAR
)Function
);
1336 Function
= LdrFixupForward((PCHAR
)Function
);
1337 if (Function
== NULL
)
1339 DPRINT1("LdrGetExportByName(): failed to find %s\n",SymbolName
);
1343 if (Function
!= NULL
)
1346 else if (minn
== maxn
)
1348 DPRINT("LdrGetExportByName(): binary search failed\n");
1361 DPRINT("LdrGetExportByName(): failed to find %s\n",SymbolName
);
1366 /**********************************************************************
1368 * LdrPerformRelocations
1371 * Relocate a DLL's memory image.
1383 LdrPerformRelocations(PIMAGE_NT_HEADERS NTHeaders
,
1386 PIMAGE_DATA_DIRECTORY RelocationDDir
;
1387 PIMAGE_BASE_RELOCATION RelocationDir
, RelocationEnd
;
1388 ULONG Count
, OldProtect
, OldProtect2
;
1390 PVOID Page
, ProtectPage
, ProtectPage2
;
1395 if (NTHeaders
->FileHeader
.Characteristics
& IMAGE_FILE_RELOCS_STRIPPED
)
1397 return STATUS_SUCCESS
;
1401 &NTHeaders
->OptionalHeader
.DataDirectory
[IMAGE_DIRECTORY_ENTRY_BASERELOC
];
1403 if (RelocationDDir
->VirtualAddress
== 0 || RelocationDDir
->Size
== 0)
1405 return STATUS_SUCCESS
;
1408 ProtectSize
= PAGE_SIZE
;
1409 Delta
= (ULONG_PTR
)ImageBase
- NTHeaders
->OptionalHeader
.ImageBase
;
1410 RelocationDir
= (PIMAGE_BASE_RELOCATION
)((ULONG_PTR
)ImageBase
+
1411 RelocationDDir
->VirtualAddress
);
1412 RelocationEnd
= (PIMAGE_BASE_RELOCATION
)((ULONG_PTR
)ImageBase
+
1413 RelocationDDir
->VirtualAddress
+ RelocationDDir
->Size
);
1415 while (RelocationDir
< RelocationEnd
&&
1416 RelocationDir
->SizeOfBlock
> 0)
1418 Count
= (RelocationDir
->SizeOfBlock
- sizeof(IMAGE_BASE_RELOCATION
)) /
1420 Page
= (PVOID
)((ULONG_PTR
)ImageBase
+ (ULONG_PTR
)RelocationDir
->VirtualAddress
);
1421 TypeOffset
= (PUSHORT
)(RelocationDir
+ 1);
1423 /* Unprotect the page(s) we're about to relocate. */
1425 Status
= NtProtectVirtualMemory(NtCurrentProcess(),
1430 if (!NT_SUCCESS(Status
))
1432 DPRINT1("Failed to unprotect relocation target.\n");
1436 if (RelocationDir
->VirtualAddress
+ PAGE_SIZE
<
1437 NTHeaders
->OptionalHeader
.SizeOfImage
)
1439 ProtectPage2
= (PVOID
)((ULONG_PTR
)ProtectPage
+ PAGE_SIZE
);
1440 Status
= NtProtectVirtualMemory(NtCurrentProcess(),
1445 if (!NT_SUCCESS(Status
))
1447 DPRINT1("Failed to unprotect relocation target (2).\n");
1448 NtProtectVirtualMemory(NtCurrentProcess(),
1458 ProtectPage2
= NULL
;
1461 RelocationDir
= LdrProcessRelocationBlock((ULONG_PTR
)Page
,
1465 if (RelocationDir
== NULL
)
1466 return STATUS_UNSUCCESSFUL
;
1468 /* Restore old page protection. */
1469 NtProtectVirtualMemory(NtCurrentProcess(),
1475 if (ProtectPage2
!= NULL
)
1477 NtProtectVirtualMemory(NtCurrentProcess(),
1485 return STATUS_SUCCESS
;
1489 LdrpGetOrLoadModule(PWCHAR SearchPath
,
1491 PLDR_DATA_TABLE_ENTRY
* Module
,
1494 ANSI_STRING AnsiDllName
;
1495 UNICODE_STRING DllName
;
1498 DPRINT("LdrpGetOrLoadModule() called for %s\n", Name
);
1500 RtlInitAnsiString(&AnsiDllName
, Name
);
1501 Status
= RtlAnsiStringToUnicodeString(&DllName
, &AnsiDllName
, TRUE
);
1502 if (!NT_SUCCESS(Status
))
1507 Status
= LdrFindEntryForName (&DllName
, Module
, Load
);
1508 if (Load
&& !NT_SUCCESS(Status
))
1510 Status
= LdrpLoadModule(SearchPath
,
1515 if (NT_SUCCESS(Status
))
1517 Status
= LdrFindEntryForName (&DllName
, Module
, FALSE
);
1519 if (!NT_SUCCESS(Status
))
1521 ULONG ErrorResponse
;
1522 ULONG_PTR ErrorParameter
= (ULONG_PTR
)&DllName
;
1524 DPRINT1("failed to load %wZ\n", &DllName
);
1526 NtRaiseHardError(STATUS_DLL_NOT_FOUND
,
1534 RtlFreeUnicodeString (&DllName
);
1539 RtlpRaiseImportNotFound(CHAR
*FuncName
, ULONG Ordinal
, PUNICODE_STRING DllName
)
1541 ULONG ErrorResponse
;
1542 ULONG_PTR ErrorParameters
[2];
1543 ANSI_STRING ProcNameAnsi
;
1544 UNICODE_STRING ProcName
;
1549 _snprintf(Buffer
, 8, "# %ld", Ordinal
);
1553 RtlInitAnsiString(&ProcNameAnsi
, FuncName
);
1554 RtlAnsiStringToUnicodeString(&ProcName
, &ProcNameAnsi
, TRUE
);
1555 ErrorParameters
[0] = (ULONG_PTR
)&ProcName
;
1556 ErrorParameters
[1] = (ULONG_PTR
)DllName
;
1557 NtRaiseHardError(STATUS_ENTRYPOINT_NOT_FOUND
,
1563 RtlFreeUnicodeString(&ProcName
);
1567 LdrpProcessImportDirectoryEntry(PLDR_DATA_TABLE_ENTRY Module
,
1568 PLDR_DATA_TABLE_ENTRY ImportedModule
,
1569 PIMAGE_IMPORT_DESCRIPTOR ImportModuleDirectory
)
1572 PVOID
* ImportAddressList
;
1573 PULONG FunctionNameList
;
1579 if (ImportModuleDirectory
== NULL
|| ImportModuleDirectory
->Name
== 0)
1581 return STATUS_UNSUCCESSFUL
;
1584 /* Get the import address list. */
1585 ImportAddressList
= (PVOID
*)((ULONG_PTR
)Module
->DllBase
+ (ULONG_PTR
)ImportModuleDirectory
->FirstThunk
);
1587 /* Get the list of functions to import. */
1588 if (ImportModuleDirectory
->OriginalFirstThunk
!= 0)
1590 FunctionNameList
= (PULONG
) ((ULONG_PTR
)Module
->DllBase
+ (ULONG_PTR
)ImportModuleDirectory
->OriginalFirstThunk
);
1594 FunctionNameList
= (PULONG
)((ULONG_PTR
)Module
->DllBase
+ (ULONG_PTR
)ImportModuleDirectory
->FirstThunk
);
1597 /* Get the size of IAT. */
1599 while (FunctionNameList
[IATSize
] != 0L)
1604 /* Unprotect the region we are about to write into. */
1605 IATBase
= (PVOID
)ImportAddressList
;
1606 IATSize
*= sizeof(PVOID
*);
1607 Status
= NtProtectVirtualMemory(NtCurrentProcess(),
1612 if (!NT_SUCCESS(Status
))
1614 DPRINT1("Failed to unprotect IAT.\n");
1618 /* Walk through function list and fixup addresses. */
1619 while (*FunctionNameList
!= 0L)
1621 if ((*FunctionNameList
) & 0x80000000)
1623 Ordinal
= (*FunctionNameList
) & 0x7fffffff;
1624 *ImportAddressList
= LdrGetExportByOrdinal(ImportedModule
->DllBase
, Ordinal
);
1625 if ((*ImportAddressList
) == NULL
)
1627 DPRINT1("Failed to import #%ld from %wZ\n", Ordinal
, &ImportedModule
->FullDllName
);
1628 RtlpRaiseImportNotFound(NULL
, Ordinal
, &ImportedModule
->FullDllName
);
1629 return STATUS_ENTRYPOINT_NOT_FOUND
;
1634 IMAGE_IMPORT_BY_NAME
*pe_name
;
1635 pe_name
= RVA(Module
->DllBase
, *FunctionNameList
);
1636 *ImportAddressList
= LdrGetExportByName(ImportedModule
->DllBase
, pe_name
->Name
, pe_name
->Hint
);
1637 if ((*ImportAddressList
) == NULL
)
1639 DPRINT1("Failed to import %s from %wZ\n", pe_name
->Name
, &ImportedModule
->FullDllName
);
1640 RtlpRaiseImportNotFound((CHAR
*)pe_name
->Name
, 0, &ImportedModule
->FullDllName
);
1641 return STATUS_ENTRYPOINT_NOT_FOUND
;
1644 ImportAddressList
++;
1648 /* Protect the region we are about to write into. */
1649 Status
= NtProtectVirtualMemory(NtCurrentProcess(),
1654 if (!NT_SUCCESS(Status
))
1656 DPRINT1("Failed to protect IAT.\n");
1660 return STATUS_SUCCESS
;
1664 LdrpProcessImportDirectory(
1665 PLDR_DATA_TABLE_ENTRY Module
,
1666 PLDR_DATA_TABLE_ENTRY ImportedModule
,
1670 PIMAGE_IMPORT_DESCRIPTOR ImportModuleDirectory
;
1674 DPRINT("LdrpProcessImportDirectory(%p '%wZ', '%s')\n",
1675 Module
, &Module
->BaseDllName
, ImportedName
);
1678 ImportModuleDirectory
= (PIMAGE_IMPORT_DESCRIPTOR
)
1679 RtlImageDirectoryEntryToData(Module
->DllBase
,
1681 IMAGE_DIRECTORY_ENTRY_IMPORT
,
1683 if (ImportModuleDirectory
== NULL
)
1685 return STATUS_UNSUCCESSFUL
;
1688 while (ImportModuleDirectory
->Name
)
1690 Name
= (PCHAR
)Module
->DllBase
+ ImportModuleDirectory
->Name
;
1691 if (0 == _stricmp(Name
, ImportedName
))
1693 Status
= LdrpProcessImportDirectoryEntry(Module
,
1695 ImportModuleDirectory
);
1696 if (!NT_SUCCESS(Status
))
1701 ImportModuleDirectory
++;
1705 return STATUS_SUCCESS
;
1710 LdrpAdjustImportDirectory(PLDR_DATA_TABLE_ENTRY Module
,
1711 PLDR_DATA_TABLE_ENTRY ImportedModule
,
1714 PIMAGE_IMPORT_DESCRIPTOR ImportModuleDirectory
;
1716 PVOID
* ImportAddressList
;
1719 PULONG FunctionNameList
;
1724 PIMAGE_NT_HEADERS NTHeaders
;
1728 DPRINT("LdrpAdjustImportDirectory(Module %p '%wZ', %p '%wZ', '%s')\n",
1729 Module
, &Module
->BaseDllName
, ImportedModule
, &ImportedModule
->BaseDllName
, ImportedName
);
1731 ImportModuleDirectory
= (PIMAGE_IMPORT_DESCRIPTOR
)
1732 RtlImageDirectoryEntryToData(Module
->DllBase
,
1734 IMAGE_DIRECTORY_ENTRY_IMPORT
,
1736 if (ImportModuleDirectory
== NULL
)
1738 return STATUS_UNSUCCESSFUL
;
1741 while (ImportModuleDirectory
->Name
)
1743 Name
= (PCHAR
)Module
->DllBase
+ ImportModuleDirectory
->Name
;
1744 if (0 == _stricmp(Name
, (PCHAR
)ImportedName
))
1747 /* Get the import address list. */
1748 ImportAddressList
= (PVOID
*)((ULONG_PTR
)Module
->DllBase
+ (ULONG_PTR
)ImportModuleDirectory
->FirstThunk
);
1750 /* Get the list of functions to import. */
1751 if (ImportModuleDirectory
->OriginalFirstThunk
!= 0)
1753 FunctionNameList
= (PULONG
) ((ULONG_PTR
)Module
->DllBase
+ (ULONG_PTR
)ImportModuleDirectory
->OriginalFirstThunk
);
1757 FunctionNameList
= (PULONG
)((ULONG_PTR
)Module
->DllBase
+ (ULONG_PTR
)ImportModuleDirectory
->FirstThunk
);
1760 /* Get the size of IAT. */
1762 while (FunctionNameList
[IATSize
] != 0L)
1767 /* Unprotect the region we are about to write into. */
1768 IATBase
= (PVOID
)ImportAddressList
;
1769 IATSize
*= sizeof(PVOID
*);
1770 Status
= NtProtectVirtualMemory(NtCurrentProcess(),
1775 if (!NT_SUCCESS(Status
))
1777 DPRINT1("Failed to unprotect IAT.\n");
1781 NTHeaders
= RtlImageNtHeader (ImportedModule
->DllBase
);
1782 Start
= (PVOID
)NTHeaders
->OptionalHeader
.ImageBase
;
1783 End
= (PVOID
)((ULONG_PTR
)Start
+ ImportedModule
->SizeOfImage
);
1784 Offset
= (ULONG
)((ULONG_PTR
)ImportedModule
->DllBase
- (ULONG_PTR
)Start
);
1786 /* Walk through function list and fixup addresses. */
1787 while (*FunctionNameList
!= 0L)
1789 if (*ImportAddressList
>= Start
&& *ImportAddressList
< End
)
1791 (*ImportAddressList
) = (PVOID
)((ULONG_PTR
)(*ImportAddressList
) + Offset
);
1793 ImportAddressList
++;
1797 /* Protect the region we are about to write into. */
1798 Status
= NtProtectVirtualMemory(NtCurrentProcess(),
1803 if (!NT_SUCCESS(Status
))
1805 DPRINT1("Failed to protect IAT.\n");
1809 ImportModuleDirectory
++;
1811 return STATUS_SUCCESS
;
1815 /**********************************************************************
1820 * Compute the entry point for every symbol the DLL imports
1821 * from other modules.
1833 LdrFixupImports(IN PWSTR SearchPath OPTIONAL
,
1834 IN PLDR_DATA_TABLE_ENTRY Module
)
1836 PIMAGE_IMPORT_DESCRIPTOR ImportModuleDirectory
;
1837 PIMAGE_IMPORT_DESCRIPTOR ImportModuleDirectoryCurrent
;
1838 PIMAGE_BOUND_IMPORT_DESCRIPTOR BoundImportDescriptor
;
1839 PIMAGE_BOUND_IMPORT_DESCRIPTOR BoundImportDescriptorCurrent
;
1840 PIMAGE_TLS_DIRECTORY TlsDirectory
;
1842 NTSTATUS Status
= STATUS_SUCCESS
;
1843 PLDR_DATA_TABLE_ENTRY ImportedModule
;
1849 DPRINT("LdrFixupImports(SearchPath %S, Module %p)\n", SearchPath
, Module
);
1851 /* Check for tls data */
1852 TlsDirectory
= (PIMAGE_TLS_DIRECTORY
)
1853 RtlImageDirectoryEntryToData(Module
->DllBase
,
1855 IMAGE_DIRECTORY_ENTRY_TLS
,
1859 TlsSize
= TlsDirectory
->EndAddressOfRawData
1860 - TlsDirectory
->StartAddressOfRawData
1861 + TlsDirectory
->SizeOfZeroFill
;
1863 if (TlsSize
> 0 && NtCurrentPeb()->Ldr
->Initialized
)
1865 TRACE_LDR("Trying to dynamically load %wZ which contains a TLS directory\n",
1866 &Module
->BaseDllName
);
1867 TlsDirectory
= NULL
;
1871 if (!create_module_activation_context( Module
))
1873 if (Module
->EntryPointActivationContext
== NULL
)
1875 DPRINT("EntryPointActivationContext has not be allocated\n");
1876 DPRINT("Module->DllBaseName %wZ\n", Module
->BaseDllName
);
1878 RtlActivateActivationContext( 0, Module
->EntryPointActivationContext
, &cookie
);
1882 * Process each import module.
1884 ImportModuleDirectory
= (PIMAGE_IMPORT_DESCRIPTOR
)
1885 RtlImageDirectoryEntryToData(Module
->DllBase
,
1887 IMAGE_DIRECTORY_ENTRY_IMPORT
,
1890 BoundImportDescriptor
= (PIMAGE_BOUND_IMPORT_DESCRIPTOR
)
1891 RtlImageDirectoryEntryToData(Module
->DllBase
,
1893 IMAGE_DIRECTORY_ENTRY_BOUND_IMPORT
,
1896 if (BoundImportDescriptor
!= NULL
&& ImportModuleDirectory
== NULL
)
1898 DPRINT1("%wZ has only a bound import directory\n", &Module
->BaseDllName
);
1899 return STATUS_UNSUCCESSFUL
;
1901 if (BoundImportDescriptor
)
1903 DPRINT("BoundImportDescriptor %p\n", BoundImportDescriptor
);
1905 BoundImportDescriptorCurrent
= BoundImportDescriptor
;
1906 while (BoundImportDescriptorCurrent
->OffsetModuleName
)
1908 ImportedName
= (PCHAR
)BoundImportDescriptor
+ BoundImportDescriptorCurrent
->OffsetModuleName
;
1909 TRACE_LDR("%wZ bound to %s\n", &Module
->BaseDllName
, ImportedName
);
1910 Status
= LdrpGetOrLoadModule(SearchPath
, ImportedName
, &ImportedModule
, TRUE
);
1911 if (!NT_SUCCESS(Status
))
1913 DPRINT1("failed to load %s\n", ImportedName
);
1916 if (Module
== ImportedModule
)
1918 LdrpDecrementLoadCount(Module
, FALSE
);
1920 if (ImportedModule
->TimeDateStamp
!= BoundImportDescriptorCurrent
->TimeDateStamp
)
1922 TRACE_LDR("%wZ has stale binding to %wZ\n",
1923 &Module
->BaseDllName
, &ImportedModule
->BaseDllName
);
1924 Status
= LdrpProcessImportDirectory(Module
, ImportedModule
, ImportedName
);
1925 if (!NT_SUCCESS(Status
))
1927 DPRINT1("failed to import %s\n", ImportedName
);
1933 BOOLEAN WrongForwarder
;
1934 WrongForwarder
= FALSE
;
1935 if (ImportedModule
->Flags
& LDRP_IMAGE_NOT_AT_BASE
)
1937 TRACE_LDR("%wZ has stale binding to %s\n",
1938 &Module
->BaseDllName
, ImportedName
);
1942 TRACE_LDR("%wZ has correct binding to %wZ\n",
1943 &Module
->BaseDllName
, &ImportedModule
->BaseDllName
);
1945 if (BoundImportDescriptorCurrent
->NumberOfModuleForwarderRefs
)
1947 PIMAGE_BOUND_FORWARDER_REF BoundForwarderRef
;
1949 PLDR_DATA_TABLE_ENTRY ForwarderModule
;
1950 PCHAR ForwarderName
;
1952 BoundForwarderRef
= (PIMAGE_BOUND_FORWARDER_REF
)(BoundImportDescriptorCurrent
+ 1);
1953 for (i
= 0; i
< BoundImportDescriptorCurrent
->NumberOfModuleForwarderRefs
; i
++, BoundForwarderRef
++)
1955 ForwarderName
= (PCHAR
)BoundImportDescriptor
+ BoundForwarderRef
->OffsetModuleName
;
1956 TRACE_LDR("%wZ bound to %s via forwardes from %s\n",
1957 &Module
->BaseDllName
, ForwarderName
, ImportedName
);
1958 Status
= LdrpGetOrLoadModule(SearchPath
, ForwarderName
, &ForwarderModule
, TRUE
);
1959 if (!NT_SUCCESS(Status
))
1961 DPRINT1("failed to load %s\n", ForwarderName
);
1964 if (Module
== ImportedModule
)
1966 LdrpDecrementLoadCount(Module
, FALSE
);
1968 if (ForwarderModule
->TimeDateStamp
!= BoundForwarderRef
->TimeDateStamp
||
1969 ForwarderModule
->Flags
& LDRP_IMAGE_NOT_AT_BASE
)
1971 TRACE_LDR("%wZ has stale binding to %s\n",
1972 &Module
->BaseDllName
, ForwarderName
);
1973 WrongForwarder
= TRUE
;
1977 TRACE_LDR("%wZ has correct binding to %s\n",
1978 &Module
->BaseDllName
, ForwarderName
);
1982 if (WrongForwarder
||
1983 ImportedModule
->Flags
& LDRP_IMAGE_NOT_AT_BASE
)
1985 Status
= LdrpProcessImportDirectory(Module
, ImportedModule
, ImportedName
);
1986 if (!NT_SUCCESS(Status
))
1988 DPRINT1("failed to import %s\n", ImportedName
);
1992 else if (ImportedModule
->Flags
& LDRP_IMAGE_NOT_AT_BASE
)
1994 TRACE_LDR("Adjust imports for %s from %wZ\n",
1995 ImportedName
, &Module
->BaseDllName
);
1996 Status
= LdrpAdjustImportDirectory(Module
, ImportedModule
, ImportedName
);
1997 if (!NT_SUCCESS(Status
))
1999 DPRINT1("failed to adjust import entries for %s\n", ImportedName
);
2003 else if (WrongForwarder
)
2007 * Update only forwarders
2009 TRACE_LDR("Stale BIND %s from %wZ\n",
2010 ImportedName
, &Module
->BaseDllName
);
2011 Status
= LdrpProcessImportDirectory(Module
, ImportedModule
, ImportedName
);
2012 if (!NT_SUCCESS(Status
))
2014 DPRINT1("faild to import %s\n", ImportedName
);
2023 BoundImportDescriptorCurrent
+= BoundImportDescriptorCurrent
->NumberOfModuleForwarderRefs
+ 1;
2026 else if (ImportModuleDirectory
)
2028 DPRINT("ImportModuleDirectory %p\n", ImportModuleDirectory
);
2030 ImportModuleDirectoryCurrent
= ImportModuleDirectory
;
2031 while (ImportModuleDirectoryCurrent
->Name
)
2033 ImportedName
= (PCHAR
)Module
->DllBase
+ ImportModuleDirectoryCurrent
->Name
;
2034 TRACE_LDR("%wZ imports functions from %s\n", &Module
->BaseDllName
, ImportedName
);
2036 if (SearchPath
== NULL
)
2038 ModulePath
= LdrpQueryAppPaths(Module
->BaseDllName
.Buffer
);
2040 Status
= LdrpGetOrLoadModule(ModulePath
, ImportedName
, &ImportedModule
, TRUE
);
2041 if (ModulePath
!= NULL
) RtlFreeHeap(RtlGetProcessHeap(), 0, ModulePath
);
2042 if (NT_SUCCESS(Status
)) goto Success
;
2045 Status
= LdrpGetOrLoadModule(SearchPath
, ImportedName
, &ImportedModule
, TRUE
);
2046 if (!NT_SUCCESS(Status
))
2048 DPRINT1("failed to load %s\n", ImportedName
);
2052 if (Module
== ImportedModule
)
2054 LdrpDecrementLoadCount(Module
, FALSE
);
2057 TRACE_LDR("Initializing imports for %wZ from %s\n",
2058 &Module
->BaseDllName
, ImportedName
);
2059 Status
= LdrpProcessImportDirectoryEntry(Module
, ImportedModule
, ImportModuleDirectoryCurrent
);
2060 if (!NT_SUCCESS(Status
))
2062 DPRINT1("failed to import %s\n", ImportedName
);
2065 ImportModuleDirectoryCurrent
++;
2068 if (!NT_SUCCESS(Status
))
2070 NTSTATUS errorStatus
= Status
;
2072 while (ImportModuleDirectoryCurrent
>= ImportModuleDirectory
)
2074 ImportedName
= (PCHAR
)Module
->DllBase
+ ImportModuleDirectoryCurrent
->Name
;
2076 Status
= LdrpGetOrLoadModule(NULL
, ImportedName
, &ImportedModule
, FALSE
);
2077 if (NT_SUCCESS(Status
) && Module
!= ImportedModule
)
2079 Status
= LdrpUnloadModule(ImportedModule
, FALSE
);
2080 if (!NT_SUCCESS(Status
)) DPRINT1("unable to unload %s\n", ImportedName
);
2082 ImportModuleDirectoryCurrent
--;
2088 if (TlsDirectory
&& TlsSize
> 0)
2090 LdrpAcquireTlsSlot(Module
, TlsSize
, FALSE
);
2093 if (Module
->EntryPointActivationContext
) RtlDeactivateActivationContext( 0, cookie
);
2095 return STATUS_SUCCESS
;
2099 /**********************************************************************
2104 * 1. Relocate, if needed the EXE.
2105 * 2. Fixup any imported symbol.
2106 * 3. Compute the EXE's entry point.
2110 * Address at which the EXE's image
2114 * Handle of the section that contains
2118 * NULL on error; otherwise the entry point
2119 * to call for initializing the DLL.
2124 * 04.01.2004 hb Previous this function was used for all images (dll + exe).
2125 * Currently the function is only used for the exe.
2127 PEPFUNC
LdrPEStartup (PVOID ImageBase
,
2128 HANDLE SectionHandle
,
2129 PLDR_DATA_TABLE_ENTRY
* Module
,
2133 PEPFUNC EntryPoint
= NULL
;
2134 PIMAGE_DOS_HEADER DosHeader
;
2135 PIMAGE_NT_HEADERS NTHeaders
;
2136 PLDR_DATA_TABLE_ENTRY tmpModule
;
2137 PVOID ActivationContextStack
;
2139 DPRINT("LdrPEStartup(ImageBase %p SectionHandle %p)\n",
2140 ImageBase
, SectionHandle
);
2143 * Overlay DOS and WNT headers structures
2144 * to the DLL's image.
2146 DosHeader
= (PIMAGE_DOS_HEADER
) ImageBase
;
2147 NTHeaders
= (PIMAGE_NT_HEADERS
) ((ULONG_PTR
)ImageBase
+ DosHeader
->e_lfanew
);
2150 * If the base address is different from the
2151 * one the DLL is actually loaded, perform any
2154 if (ImageBase
!= (PVOID
) NTHeaders
->OptionalHeader
.ImageBase
)
2156 DPRINT("LDR: Performing relocations\n");
2157 Status
= LdrPerformRelocations(NTHeaders
, ImageBase
);
2158 if (!NT_SUCCESS(Status
))
2160 DPRINT1("LdrPerformRelocations() failed\n");
2167 *Module
= LdrAddModuleEntry(ImageBase
, NTHeaders
, FullDosName
);
2168 (*Module
)->SectionPointer
= SectionHandle
;
2172 Module
= &tmpModule
;
2173 Status
= LdrFindEntryForAddress(ImageBase
, Module
);
2174 if (!NT_SUCCESS(Status
))
2180 if (ImageBase
!= (PVOID
) NTHeaders
->OptionalHeader
.ImageBase
)
2182 (*Module
)->Flags
|= LDRP_IMAGE_NOT_AT_BASE
;
2185 /* Allocate memory for the ActivationContextStack */
2186 /* FIXME: Verify RtlAllocateActivationContextStack behavior */
2187 Status
= RtlAllocateActivationContextStack(&ActivationContextStack
);
2188 if (NT_SUCCESS(Status
))
2190 DPRINT("ActivationContextStack %x\n",ActivationContextStack
);
2191 DPRINT("ActiveFrame %x\n", ((PACTIVATION_CONTEXT_STACK
)ActivationContextStack
)->ActiveFrame
);
2192 NtCurrentTeb()->ActivationContextStackPointer
= ActivationContextStack
;
2193 NtCurrentTeb()->ActivationContextStackPointer
->ActiveFrame
= NULL
;
2196 DPRINT1("Warning: Unable to allocate ActivationContextStack\n");
2199 * If the DLL's imports symbols from other
2200 * modules, fixup the imported calls entry points.
2202 DPRINT("About to fixup imports\n");
2203 Status
= LdrFixupImports(NULL
, *Module
);
2204 if (!NT_SUCCESS(Status
))
2206 DPRINT1("LdrFixupImports() failed for %wZ\n", &(*Module
)->BaseDllName
);
2209 DPRINT("Fixup done\n");
2210 RtlEnterCriticalSection(NtCurrentPeb()->LoaderLock
);
2211 Status
= LdrpInitializeTlsForProccess();
2212 if (NT_SUCCESS(Status
))
2214 Status
= LdrpAttachProcess();
2216 if (NT_SUCCESS(Status
))
2218 LdrpTlsCallback(*Module
, DLL_PROCESS_ATTACH
);
2222 RtlLeaveCriticalSection(NtCurrentPeb()->LoaderLock
);
2223 if (!NT_SUCCESS(Status
))
2229 * Compute the DLL's entry point's address.
2231 DPRINT("ImageBase = %p\n", ImageBase
);
2232 DPRINT("AddressOfEntryPoint = 0x%lx\n",(ULONG
)NTHeaders
->OptionalHeader
.AddressOfEntryPoint
);
2233 if (NTHeaders
->OptionalHeader
.AddressOfEntryPoint
!= 0)
2235 EntryPoint
= (PEPFUNC
) ((ULONG_PTR
)ImageBase
2236 + NTHeaders
->OptionalHeader
.AddressOfEntryPoint
);
2238 DPRINT("LdrPEStartup() = %p\n",EntryPoint
);
2243 LdrpLoadModule(IN PWSTR SearchPath OPTIONAL
,
2245 IN PUNICODE_STRING Name
,
2246 PLDR_DATA_TABLE_ENTRY
*Module
,
2247 PVOID
*BaseAddress OPTIONAL
)
2249 UNICODE_STRING AdjustedName
;
2250 UNICODE_STRING FullDosName
;
2252 PLDR_DATA_TABLE_ENTRY tmpModule
;
2253 HANDLE SectionHandle
;
2256 PIMAGE_NT_HEADERS NtHeaders
;
2257 BOOLEAN MappedAsDataFile
;
2258 PVOID ArbitraryUserPointer
;
2262 Module
= &tmpModule
;
2264 /* adjust the full dll name */
2265 LdrAdjustDllName(&AdjustedName
, Name
, FALSE
);
2267 DPRINT("%wZ\n", &AdjustedName
);
2269 MappedAsDataFile
= FALSE
;
2270 /* Test if dll is already loaded */
2271 Status
= LdrFindEntryForName(&AdjustedName
, Module
, TRUE
);
2272 if (NT_SUCCESS(Status
))
2274 RtlFreeUnicodeString(&AdjustedName
);
2275 if (NULL
!= BaseAddress
)
2277 *BaseAddress
= (*Module
)->DllBase
;
2282 /* Open or create dll image section */
2283 Status
= LdrpMapKnownDll(&AdjustedName
, &FullDosName
, &SectionHandle
);
2284 if (!NT_SUCCESS(Status
))
2286 MappedAsDataFile
= (0 != (LoadFlags
& LOAD_LIBRARY_AS_DATAFILE
));
2287 Status
= LdrpMapDllImageFile(SearchPath
, &AdjustedName
, &FullDosName
,
2288 MappedAsDataFile
, &SectionHandle
);
2290 if (!NT_SUCCESS(Status
))
2292 DPRINT1("Failed to create or open dll section of '%wZ' (Status %lx)\n", &AdjustedName
, Status
);
2293 RtlFreeUnicodeString(&AdjustedName
);
2296 RtlFreeUnicodeString(&AdjustedName
);
2297 /* Map the dll into the process */
2300 ArbitraryUserPointer
= NtCurrentTeb()->NtTib
.ArbitraryUserPointer
;
2301 NtCurrentTeb()->NtTib
.ArbitraryUserPointer
= FullDosName
.Buffer
;
2302 Status
= NtMapViewOfSection(SectionHandle
,
2312 NtCurrentTeb()->NtTib
.ArbitraryUserPointer
= ArbitraryUserPointer
;
2313 if (!NT_SUCCESS(Status
))
2315 DPRINT1("map view of section failed (Status 0x%08lx)\n", Status
);
2316 RtlFreeUnicodeString(&FullDosName
);
2317 NtClose(SectionHandle
);
2320 if (NULL
!= BaseAddress
)
2322 *BaseAddress
= ImageBase
;
2324 if (!MappedAsDataFile
)
2326 /* Get and check the NT headers */
2327 NtHeaders
= RtlImageNtHeader(ImageBase
);
2328 if (NtHeaders
== NULL
)
2330 DPRINT1("RtlImageNtHeaders() failed\n");
2331 NtUnmapViewOfSection (NtCurrentProcess (), ImageBase
);
2332 NtClose (SectionHandle
);
2333 RtlFreeUnicodeString(&FullDosName
);
2334 return STATUS_UNSUCCESSFUL
;
2337 DPRINT("Mapped %wZ at %x\n", &FullDosName
, ImageBase
);
2338 if (MappedAsDataFile
)
2340 ASSERT(NULL
!= BaseAddress
);
2341 if (NULL
!= BaseAddress
)
2343 *BaseAddress
= (PVOID
) ((char *) *BaseAddress
+ 1);
2346 RtlFreeUnicodeString(&FullDosName
);
2347 NtClose(SectionHandle
);
2348 return STATUS_SUCCESS
;
2350 /* If the base address is different from the
2351 * one the DLL is actually loaded, perform any
2353 if (ImageBase
!= (PVOID
) NtHeaders
->OptionalHeader
.ImageBase
)
2355 DPRINT1("Relocating (%lx -> %p) %wZ\n",
2356 NtHeaders
->OptionalHeader
.ImageBase
, ImageBase
, &FullDosName
);
2357 Status
= LdrPerformRelocations(NtHeaders
, ImageBase
);
2358 if (!NT_SUCCESS(Status
))
2360 DPRINT1("LdrPerformRelocations() failed\n");
2361 NtUnmapViewOfSection (NtCurrentProcess (), ImageBase
);
2362 NtClose (SectionHandle
);
2363 RtlFreeUnicodeString(&FullDosName
);
2364 return STATUS_UNSUCCESSFUL
;
2367 *Module
= LdrAddModuleEntry(ImageBase
, NtHeaders
, FullDosName
.Buffer
);
2368 (*Module
)->SectionPointer
= SectionHandle
;
2369 if (ImageBase
!= (PVOID
) NtHeaders
->OptionalHeader
.ImageBase
)
2371 (*Module
)->Flags
|= LDRP_IMAGE_NOT_AT_BASE
;
2373 if (NtHeaders
->FileHeader
.Characteristics
& IMAGE_FILE_DLL
)
2375 (*Module
)->Flags
|= LDRP_IMAGE_DLL
;
2377 /* fixup the imported calls entry points */
2378 Status
= LdrFixupImports(SearchPath
, *Module
);
2379 if (!NT_SUCCESS(Status
))
2381 DPRINT1("LdrFixupImports failed for %wZ, status=%x\n", &(*Module
)->BaseDllName
, Status
);
2382 NtUnmapViewOfSection (NtCurrentProcess (), ImageBase
);
2383 NtClose (SectionHandle
);
2384 RtlFreeUnicodeString (&FullDosName
);
2385 RtlFreeUnicodeString (&(*Module
)->FullDllName
);
2386 RtlFreeUnicodeString (&(*Module
)->BaseDllName
);
2387 RemoveEntryList (&(*Module
)->InLoadOrderLinks
);
2388 RtlFreeHeap (RtlGetProcessHeap (), 0, Module
);
2392 RtlEnterCriticalSection(NtCurrentPeb()->LoaderLock
);
2393 InsertTailList(&NtCurrentPeb()->Ldr
->InInitializationOrderModuleList
,
2394 &(*Module
)->InInitializationOrderLinks
);
2395 RtlLeaveCriticalSection (NtCurrentPeb()->LoaderLock
);
2397 return STATUS_SUCCESS
;
2401 LdrpUnloadModule(PLDR_DATA_TABLE_ENTRY Module
,
2404 PIMAGE_IMPORT_DESCRIPTOR ImportModuleDirectory
;
2405 PIMAGE_BOUND_IMPORT_DESCRIPTOR BoundImportDescriptor
;
2406 PIMAGE_BOUND_IMPORT_DESCRIPTOR BoundImportDescriptorCurrent
;
2408 PLDR_DATA_TABLE_ENTRY ImportedModule
;
2409 NTSTATUS Status
= 0;
2415 RtlEnterCriticalSection(NtCurrentPeb()->LoaderLock
);
2418 LoadCount
= LdrpDecrementLoadCount(Module
, Unload
);
2420 TRACE_LDR("Unload %wZ, LoadCount %d\n", &Module
->BaseDllName
, LoadCount
);
2424 /* ?????????????????? */
2426 else if (!(Module
->Flags
& LDRP_STATIC_LINK
) && LoadCount
== 1)
2428 BoundImportDescriptor
= (PIMAGE_BOUND_IMPORT_DESCRIPTOR
)
2429 RtlImageDirectoryEntryToData(Module
->DllBase
,
2431 IMAGE_DIRECTORY_ENTRY_BOUND_IMPORT
,
2433 if (BoundImportDescriptor
)
2435 /* dereferencing all imported modules, use the bound import descriptor */
2436 BoundImportDescriptorCurrent
= BoundImportDescriptor
;
2437 while (BoundImportDescriptorCurrent
->OffsetModuleName
)
2439 ImportedName
= (PCHAR
)BoundImportDescriptor
+ BoundImportDescriptorCurrent
->OffsetModuleName
;
2440 TRACE_LDR("%wZ trys to unload %s\n", &Module
->BaseDllName
, ImportedName
);
2441 Status
= LdrpGetOrLoadModule(NULL
, ImportedName
, &ImportedModule
, FALSE
);
2442 if (!NT_SUCCESS(Status
))
2444 DPRINT1("unable to found imported modul %s\n", ImportedName
);
2448 if (Module
!= ImportedModule
)
2450 Status
= LdrpUnloadModule(ImportedModule
, FALSE
);
2451 if (!NT_SUCCESS(Status
))
2453 DPRINT1("unable to unload %s\n", ImportedName
);
2457 BoundImportDescriptorCurrent
++;
2462 ImportModuleDirectory
= (PIMAGE_IMPORT_DESCRIPTOR
)
2463 RtlImageDirectoryEntryToData(Module
->DllBase
,
2465 IMAGE_DIRECTORY_ENTRY_IMPORT
,
2467 if (ImportModuleDirectory
)
2469 /* dereferencing all imported modules, use the import descriptor */
2470 while (ImportModuleDirectory
->Name
)
2472 ImportedName
= (PCHAR
)Module
->DllBase
+ ImportModuleDirectory
->Name
;
2473 TRACE_LDR("%wZ trys to unload %s\n", &Module
->BaseDllName
, ImportedName
);
2474 Status
= LdrpGetOrLoadModule(NULL
, ImportedName
, &ImportedModule
, FALSE
);
2475 if (!NT_SUCCESS(Status
))
2477 DPRINT1("unable to found imported modul %s\n", ImportedName
);
2481 if (Module
!= ImportedModule
)
2483 Status
= LdrpUnloadModule(ImportedModule
, FALSE
);
2484 if (!NT_SUCCESS(Status
))
2486 DPRINT1("unable to unload %s\n", ImportedName
);
2490 ImportModuleDirectory
++;
2498 if (!(Module
->Flags
& LDRP_STATIC_LINK
))
2500 LdrpDetachProcess(FALSE
);
2503 RtlLeaveCriticalSection (NtCurrentPeb()->LoaderLock
);
2505 return STATUS_SUCCESS
;
2513 LdrUnloadDll (IN PVOID BaseAddress
)
2515 PLDR_DATA_TABLE_ENTRY Module
;
2518 if (BaseAddress
== NULL
)
2519 return STATUS_SUCCESS
;
2521 if (LdrMappedAsDataFile(&BaseAddress
))
2523 Status
= NtUnmapViewOfSection(NtCurrentProcess(), BaseAddress
);
2527 Status
= LdrFindEntryForAddress(BaseAddress
, &Module
);
2528 if (NT_SUCCESS(Status
))
2530 TRACE_LDR("LdrUnloadDll, , unloading %wZ\n", &Module
->BaseDllName
);
2531 Status
= LdrpUnloadModule(Module
, TRUE
);
2542 LdrDisableThreadCalloutsForDll(IN PVOID BaseAddress
)
2544 PLIST_ENTRY ModuleListHead
;
2546 PLDR_DATA_TABLE_ENTRY Module
;
2549 DPRINT("LdrDisableThreadCalloutsForDll (BaseAddress %p)\n", BaseAddress
);
2551 Status
= STATUS_DLL_NOT_FOUND
;
2552 RtlEnterCriticalSection (NtCurrentPeb()->LoaderLock
);
2553 ModuleListHead
= &NtCurrentPeb()->Ldr
->InLoadOrderModuleList
;
2554 Entry
= ModuleListHead
->Flink
;
2555 while (Entry
!= ModuleListHead
)
2557 Module
= CONTAINING_RECORD(Entry
, LDR_DATA_TABLE_ENTRY
, InLoadOrderLinks
);
2559 DPRINT("BaseDllName %wZ BaseAddress %p\n", &Module
->BaseDllName
, Module
->DllBase
);
2561 if (Module
->DllBase
== BaseAddress
)
2563 if (Module
->TlsIndex
== 0xFFFF)
2565 Module
->Flags
|= LDRP_DONT_CALL_FOR_THREADS
;
2566 Status
= STATUS_SUCCESS
;
2570 Entry
= Entry
->Flink
;
2572 RtlLeaveCriticalSection (NtCurrentPeb()->LoaderLock
);
2580 LdrGetDllHandle(IN PWSTR DllPath OPTIONAL
,
2581 IN PULONG DllCharacteristics
,
2582 IN PUNICODE_STRING DllName
,
2583 OUT PVOID
*DllHandle
)
2585 PLDR_DATA_TABLE_ENTRY Module
;
2588 TRACE_LDR("LdrGetDllHandle, searching for %wZ from %S\n",
2589 DllName
, DllPath
? DllPath
: L
"");
2591 /* NULL is the current executable */
2592 if (DllName
== NULL
)
2594 *DllHandle
= ExeModule
->DllBase
;
2595 DPRINT("BaseAddress 0x%lx\n", *DllHandle
);
2596 return STATUS_SUCCESS
;
2599 Status
= LdrFindEntryForName(DllName
, &Module
, FALSE
);
2600 if (NT_SUCCESS(Status
))
2602 *DllHandle
= Module
->DllBase
;
2603 return STATUS_SUCCESS
;
2606 DPRINT("Failed to find dll %wZ\n", DllName
);
2608 return STATUS_DLL_NOT_FOUND
;
2615 LdrAddRefDll(IN ULONG Flags
,
2616 IN PVOID BaseAddress
)
2618 PLIST_ENTRY ModuleListHead
;
2620 PLDR_DATA_TABLE_ENTRY Module
;
2623 if (Flags
& ~(LDR_PIN_MODULE
))
2625 return STATUS_INVALID_PARAMETER
;
2628 Status
= STATUS_DLL_NOT_FOUND
;
2629 RtlEnterCriticalSection (NtCurrentPeb()->LoaderLock
);
2630 ModuleListHead
= &NtCurrentPeb()->Ldr
->InLoadOrderModuleList
;
2631 Entry
= ModuleListHead
->Flink
;
2632 while (Entry
!= ModuleListHead
)
2634 Module
= CONTAINING_RECORD(Entry
, LDR_DATA_TABLE_ENTRY
, InLoadOrderLinks
);
2636 if (Module
->DllBase
== BaseAddress
)
2638 if (Flags
& LDR_PIN_MODULE
)
2640 Module
->Flags
|= LDRP_STATIC_LINK
;
2644 LdrpIncrementLoadCount(Module
,
2647 Status
= STATUS_SUCCESS
;
2650 Entry
= Entry
->Flink
;
2652 RtlLeaveCriticalSection (NtCurrentPeb()->LoaderLock
);
2660 RtlPcToFileHeader(IN PVOID PcValue
,
2663 PLIST_ENTRY ModuleListHead
;
2665 PLDR_DATA_TABLE_ENTRY Module
;
2666 PVOID ImageBase
= NULL
;
2668 RtlEnterCriticalSection (NtCurrentPeb()->LoaderLock
);
2669 ModuleListHead
= &NtCurrentPeb()->Ldr
->InLoadOrderModuleList
;
2670 Entry
= ModuleListHead
->Flink
;
2671 while (Entry
!= ModuleListHead
)
2673 Module
= CONTAINING_RECORD(Entry
, LDR_DATA_TABLE_ENTRY
, InLoadOrderLinks
);
2675 if ((ULONG_PTR
)PcValue
>= (ULONG_PTR
)Module
->DllBase
&&
2676 (ULONG_PTR
)PcValue
< (ULONG_PTR
)Module
->DllBase
+ Module
->SizeOfImage
)
2678 ImageBase
= Module
->DllBase
;
2681 Entry
= Entry
->Flink
;
2683 RtlLeaveCriticalSection (NtCurrentPeb()->LoaderLock
);
2685 *BaseOfImage
= ImageBase
;
2693 LdrGetProcedureAddress (IN PVOID BaseAddress
,
2694 IN PANSI_STRING Name
,
2696 OUT PVOID
*ProcedureAddress
)
2698 NTSTATUS Status
= STATUS_PROCEDURE_NOT_FOUND
;
2699 if (Name
&& Name
->Length
)
2701 TRACE_LDR("LdrGetProcedureAddress by NAME - %Z\n", Name
);
2705 TRACE_LDR("LdrGetProcedureAddress by ORDINAL - %d\n", Ordinal
);
2708 DPRINT("LdrGetProcedureAddress (BaseAddress %p Name %Z Ordinal %lu ProcedureAddress %p)\n",
2709 BaseAddress
, Name
, Ordinal
, ProcedureAddress
);
2713 if (Name
&& Name
->Length
)
2716 *ProcedureAddress
= LdrGetExportByName(BaseAddress
, (PUCHAR
)Name
->Buffer
, 0xffff);
2717 if (*ProcedureAddress
!= NULL
)
2719 Status
= STATUS_SUCCESS
;
2721 DPRINT("LdrGetProcedureAddress: Can't resolve symbol '%Z'\n", Name
);
2726 Ordinal
&= 0x0000FFFF;
2727 *ProcedureAddress
= LdrGetExportByOrdinal(BaseAddress
, (WORD
)Ordinal
);
2728 if (*ProcedureAddress
)
2730 Status
= STATUS_SUCCESS
;
2732 DPRINT("LdrGetProcedureAddress: Can't resolve symbol @%lu\n", Ordinal
);
2735 _SEH2_EXCEPT(EXCEPTION_EXECUTE_HANDLER
)
2737 Status
= STATUS_DLL_NOT_FOUND
;
2744 /**********************************************************************
2749 * Unload dll's which are no longer referenced from others dll's
2760 * The loader lock must be held on enty.
2763 LdrpDetachProcess(BOOLEAN UnloadAll
)
2765 PLIST_ENTRY ModuleListHead
;
2767 PLDR_DATA_TABLE_ENTRY Module
;
2768 static ULONG CallingCount
= 0;
2770 DPRINT("LdrpDetachProcess() called for %wZ\n",
2771 &ExeModule
->BaseDllName
);
2774 LdrpDllShutdownInProgress
= TRUE
;
2778 ModuleListHead
= &NtCurrentPeb()->Ldr
->InInitializationOrderModuleList
;
2779 Entry
= ModuleListHead
->Blink
;
2780 while (Entry
!= ModuleListHead
)
2782 Module
= CONTAINING_RECORD(Entry
, LDR_DATA_TABLE_ENTRY
, InInitializationOrderLinks
);
2783 if (((UnloadAll
&& Module
->LoadCount
== LDRP_PROCESS_CREATION_TIME
) || Module
->LoadCount
== 0) &&
2784 Module
->Flags
& LDRP_ENTRY_PROCESSED
&&
2785 !(Module
->Flags
& LDRP_UNLOAD_IN_PROGRESS
))
2787 Module
->Flags
|= LDRP_UNLOAD_IN_PROGRESS
;
2788 if (Module
== LdrpLastModule
)
2790 LdrpLastModule
= NULL
;
2792 if (Module
->Flags
& LDRP_PROCESS_ATTACH_CALLED
)
2794 TRACE_LDR("Unload %wZ - Calling entry point at %x\n",
2795 &Module
->BaseDllName
, Module
->EntryPoint
);
2796 LdrpCallDllEntry(Module
, DLL_PROCESS_DETACH
, (PVOID
)(INT_PTR
)(Module
->LoadCount
== LDRP_PROCESS_CREATION_TIME
? 1 : 0));
2800 TRACE_LDR("Unload %wZ\n", &Module
->BaseDllName
);
2802 Entry
= ModuleListHead
->Blink
;
2806 Entry
= Entry
->Blink
;
2810 if (CallingCount
== 1)
2812 Entry
= ModuleListHead
->Blink
;
2813 while (Entry
!= ModuleListHead
)
2815 Module
= CONTAINING_RECORD(Entry
, LDR_DATA_TABLE_ENTRY
, InInitializationOrderLinks
);
2816 Entry
= Entry
->Blink
;
2817 if (Module
->Flags
& LDRP_UNLOAD_IN_PROGRESS
&&
2818 ((UnloadAll
&& Module
->LoadCount
!= LDRP_PROCESS_CREATION_TIME
) || Module
->LoadCount
== 0))
2820 /* remove the module entry from the list */
2821 RemoveEntryList (&Module
->InLoadOrderLinks
);
2822 RemoveEntryList (&Module
->InInitializationOrderLinks
);
2824 NtUnmapViewOfSection (NtCurrentProcess (), Module
->DllBase
);
2825 NtClose (Module
->SectionPointer
);
2827 TRACE_LDR("%wZ unloaded\n", &Module
->BaseDllName
);
2829 RtlFreeUnicodeString (&Module
->FullDllName
);
2830 RtlFreeUnicodeString (&Module
->BaseDllName
);
2832 RtlFreeHeap (RtlGetProcessHeap (), 0, Module
);
2837 DPRINT("LdrpDetachProcess() done\n");
2840 /**********************************************************************
2845 * Initialize all dll's which are prepered for loading
2856 * The loader lock must be held on entry.
2860 LdrpAttachProcess(VOID
)
2862 PLIST_ENTRY ModuleListHead
;
2864 PLDR_DATA_TABLE_ENTRY Module
;
2866 NTSTATUS Status
= STATUS_SUCCESS
;
2868 DPRINT("LdrpAttachProcess() called for %wZ\n",
2869 &ExeModule
->BaseDllName
);
2871 ModuleListHead
= &NtCurrentPeb()->Ldr
->InInitializationOrderModuleList
;
2872 Entry
= ModuleListHead
->Flink
;
2873 while (Entry
!= ModuleListHead
)
2875 Module
= CONTAINING_RECORD(Entry
, LDR_DATA_TABLE_ENTRY
, InInitializationOrderLinks
);
2876 if (!(Module
->Flags
& (LDRP_LOAD_IN_PROGRESS
|LDRP_UNLOAD_IN_PROGRESS
|LDRP_ENTRY_PROCESSED
)))
2878 Module
->Flags
|= LDRP_LOAD_IN_PROGRESS
;
2879 TRACE_LDR("%wZ loaded - Calling init routine at %x for process attaching\n",
2880 &Module
->BaseDllName
, Module
->EntryPoint
);
2881 Result
= LdrpCallDllEntry(Module
, DLL_PROCESS_ATTACH
, (PVOID
)(INT_PTR
)(Module
->LoadCount
== LDRP_PROCESS_CREATION_TIME
? 1 : 0));
2884 Status
= STATUS_DLL_INIT_FAILED
;
2887 if (Module
->Flags
& LDRP_IMAGE_DLL
&& Module
->EntryPoint
!= 0)
2889 Module
->Flags
|= LDRP_PROCESS_ATTACH_CALLED
|LDRP_ENTRY_PROCESSED
;
2893 Module
->Flags
|= LDRP_ENTRY_PROCESSED
;
2895 Module
->Flags
&= ~LDRP_LOAD_IN_PROGRESS
;
2897 Entry
= Entry
->Flink
;
2900 DPRINT("LdrpAttachProcess() done\n");
2909 RtlDllShutdownInProgress (VOID
)
2911 return LdrpDllShutdownInProgress
;
2918 LdrShutdownProcess (VOID
)
2920 LdrpDetachProcess(TRUE
);
2921 return STATUS_SUCCESS
;
2929 LdrpAttachThread (VOID
)
2931 PLIST_ENTRY ModuleListHead
;
2933 PLDR_DATA_TABLE_ENTRY Module
;
2936 DPRINT("LdrpAttachThread() called for %wZ\n",
2937 &ExeModule
->BaseDllName
);
2939 RtlEnterCriticalSection (NtCurrentPeb()->LoaderLock
);
2941 Status
= LdrpInitializeTlsForThread();
2943 if (NT_SUCCESS(Status
))
2945 ModuleListHead
= &NtCurrentPeb()->Ldr
->InInitializationOrderModuleList
;
2946 Entry
= ModuleListHead
->Flink
;
2948 while (Entry
!= ModuleListHead
)
2950 Module
= CONTAINING_RECORD(Entry
, LDR_DATA_TABLE_ENTRY
, InInitializationOrderLinks
);
2951 if (Module
->Flags
& LDRP_PROCESS_ATTACH_CALLED
&&
2952 !(Module
->Flags
& LDRP_DONT_CALL_FOR_THREADS
) &&
2953 !(Module
->Flags
& LDRP_UNLOAD_IN_PROGRESS
))
2955 TRACE_LDR("%wZ - Calling entry point at %x for thread attaching\n",
2956 &Module
->BaseDllName
, Module
->EntryPoint
);
2957 LdrpCallDllEntry(Module
, DLL_THREAD_ATTACH
, NULL
);
2959 Entry
= Entry
->Flink
;
2962 Entry
= NtCurrentPeb()->Ldr
->InLoadOrderModuleList
.Flink
;
2963 Module
= CONTAINING_RECORD(Entry
, LDR_DATA_TABLE_ENTRY
, InLoadOrderLinks
);
2964 LdrpTlsCallback(Module
, DLL_THREAD_ATTACH
);
2967 RtlLeaveCriticalSection (NtCurrentPeb()->LoaderLock
);
2969 DPRINT("LdrpAttachThread() done\n");
2979 LdrShutdownThread (VOID
)
2981 PLIST_ENTRY ModuleListHead
;
2983 PLDR_DATA_TABLE_ENTRY Module
;
2985 DPRINT("LdrShutdownThread() called for %wZ\n",
2986 &ExeModule
->BaseDllName
);
2988 RtlEnterCriticalSection (NtCurrentPeb()->LoaderLock
);
2990 ModuleListHead
= &NtCurrentPeb()->Ldr
->InInitializationOrderModuleList
;
2991 Entry
= ModuleListHead
->Blink
;
2992 while (Entry
!= ModuleListHead
)
2994 Module
= CONTAINING_RECORD(Entry
, LDR_DATA_TABLE_ENTRY
, InInitializationOrderLinks
);
2996 if (Module
->Flags
& LDRP_PROCESS_ATTACH_CALLED
&&
2997 !(Module
->Flags
& LDRP_DONT_CALL_FOR_THREADS
) &&
2998 !(Module
->Flags
& LDRP_UNLOAD_IN_PROGRESS
))
3000 TRACE_LDR("%wZ - Calling entry point at %x for thread detaching\n",
3001 &Module
->BaseDllName
, Module
->EntryPoint
);
3002 LdrpCallDllEntry(Module
, DLL_THREAD_DETACH
, NULL
);
3004 Entry
= Entry
->Blink
;
3007 RtlLeaveCriticalSection (NtCurrentPeb()->LoaderLock
);
3011 RtlFreeHeap (RtlGetProcessHeap(), 0, NtCurrentTeb()->ThreadLocalStoragePointer
);
3014 DPRINT("LdrShutdownThread() done\n");
3016 return STATUS_SUCCESS
;
3020 /***************************************************************************
3022 * LdrQueryProcessModuleInformation
3037 LdrQueryProcessModuleInformation(IN PRTL_PROCESS_MODULES ModuleInformation OPTIONAL
,
3038 IN ULONG Size OPTIONAL
,
3039 OUT PULONG ReturnedSize
)
3041 PLIST_ENTRY ModuleListHead
;
3043 PLDR_DATA_TABLE_ENTRY Module
;
3044 PRTL_PROCESS_MODULE_INFORMATION ModulePtr
= NULL
;
3045 NTSTATUS Status
= STATUS_SUCCESS
;
3046 ULONG UsedSize
= sizeof(ULONG
);
3047 ANSI_STRING AnsiString
;
3050 DPRINT("LdrQueryProcessModuleInformation() called\n");
3051 // FIXME: This code is ultra-duplicated. see lib\rtl\dbgbuffer.c
3052 RtlEnterCriticalSection (NtCurrentPeb()->LoaderLock
);
3054 if (ModuleInformation
== NULL
|| Size
== 0)
3056 Status
= STATUS_INFO_LENGTH_MISMATCH
;
3060 ModuleInformation
->NumberOfModules
= 0;
3061 ModulePtr
= &ModuleInformation
->Modules
[0];
3062 Status
= STATUS_SUCCESS
;
3065 ModuleListHead
= &NtCurrentPeb()->Ldr
->InLoadOrderModuleList
;
3066 Entry
= ModuleListHead
->Flink
;
3068 while (Entry
!= ModuleListHead
)
3070 Module
= CONTAINING_RECORD(Entry
, LDR_DATA_TABLE_ENTRY
, InLoadOrderLinks
);
3072 DPRINT(" Module %wZ\n",
3073 &Module
->FullDllName
);
3075 if (UsedSize
> Size
)
3077 Status
= STATUS_INFO_LENGTH_MISMATCH
;
3079 else if (ModuleInformation
!= NULL
)
3081 ModulePtr
->Section
= 0;
3082 ModulePtr
->MappedBase
= NULL
; // FIXME: ??
3083 ModulePtr
->ImageBase
= Module
->DllBase
;
3084 ModulePtr
->ImageSize
= Module
->SizeOfImage
;
3085 ModulePtr
->Flags
= Module
->Flags
;
3086 ModulePtr
->LoadOrderIndex
= 0; // FIXME: ??
3087 ModulePtr
->InitOrderIndex
= 0; // FIXME: ??
3088 ModulePtr
->LoadCount
= Module
->LoadCount
;
3090 AnsiString
.Length
= 0;
3091 AnsiString
.MaximumLength
= 256;
3092 AnsiString
.Buffer
= ModulePtr
->FullPathName
;
3093 RtlUnicodeStringToAnsiString(&AnsiString
,
3094 &Module
->FullDllName
,
3097 p
= strrchr(ModulePtr
->FullPathName
, '\\');
3099 ModulePtr
->OffsetToFileName
= p
- ModulePtr
->FullPathName
+ 1;
3101 ModulePtr
->OffsetToFileName
= 0;
3104 ModuleInformation
->NumberOfModules
++;
3106 UsedSize
+= sizeof(RTL_PROCESS_MODULE_INFORMATION
);
3108 Entry
= Entry
->Flink
;
3111 RtlLeaveCriticalSection (NtCurrentPeb()->LoaderLock
);
3113 if (ReturnedSize
!= 0)
3114 *ReturnedSize
= UsedSize
;
3116 DPRINT("LdrQueryProcessModuleInformation() done\n");
3123 LdrpCheckImageChecksum (IN PVOID BaseAddress
,
3126 PIMAGE_NT_HEADERS Header
;
3133 Header
= RtlImageNtHeader (BaseAddress
);
3137 HeaderSum
= Header
->OptionalHeader
.CheckSum
;
3142 Ptr
= (PUSHORT
) BaseAddress
;
3143 for (i
= 0; i
< ImageSize
/ sizeof (USHORT
); i
++)
3146 if (HIWORD(Sum
) != 0)
3148 Sum
= LOWORD(Sum
) + HIWORD(Sum
);
3155 Sum
+= (ULONG
)*((PUCHAR
)Ptr
);
3156 if (HIWORD(Sum
) != 0)
3158 Sum
= LOWORD(Sum
) + HIWORD(Sum
);
3162 CalcSum
= (USHORT
)(LOWORD(Sum
) + HIWORD(Sum
));
3164 /* Subtract image checksum from calculated checksum. */
3165 /* fix low word of checksum */
3166 if (LOWORD(CalcSum
) >= LOWORD(HeaderSum
))
3168 CalcSum
-= LOWORD(HeaderSum
);
3172 CalcSum
= ((LOWORD(CalcSum
) - LOWORD(HeaderSum
)) & 0xFFFF) - 1;
3175 /* fix high word of checksum */
3176 if (LOWORD(CalcSum
) >= HIWORD(HeaderSum
))
3178 CalcSum
-= HIWORD(HeaderSum
);
3182 CalcSum
= ((LOWORD(CalcSum
) - HIWORD(HeaderSum
)) & 0xFFFF) - 1;
3185 /* add file length */
3186 CalcSum
+= ImageSize
;
3188 return (BOOLEAN
)(CalcSum
== HeaderSum
);
3192 * Compute size of an image as it is actually present in virt memory
3193 * (i.e. excluding NEVER_LOAD sections)
3196 LdrpGetResidentSize(PIMAGE_NT_HEADERS NTHeaders
)
3198 PIMAGE_SECTION_HEADER SectionHeader
;
3199 unsigned SectionIndex
;
3202 SectionHeader
= (PIMAGE_SECTION_HEADER
)((char *) &NTHeaders
->OptionalHeader
3203 + NTHeaders
->FileHeader
.SizeOfOptionalHeader
);
3205 for (SectionIndex
= 0; SectionIndex
< NTHeaders
->FileHeader
.NumberOfSections
; SectionIndex
++)
3207 if (0 == (SectionHeader
->Characteristics
& IMAGE_SCN_LNK_REMOVE
)
3208 && ResidentSize
< SectionHeader
->VirtualAddress
+ SectionHeader
->Misc
.VirtualSize
)
3210 ResidentSize
= SectionHeader
->VirtualAddress
+ SectionHeader
->Misc
.VirtualSize
;
3215 return ResidentSize
;
3219 /***************************************************************************
3221 * LdrVerifyImageMatchesChecksum
3236 LdrVerifyImageMatchesChecksum (IN HANDLE FileHandle
,
3241 FILE_STANDARD_INFORMATION FileInfo
;
3242 IO_STATUS_BLOCK IoStatusBlock
;
3243 HANDLE SectionHandle
;
3249 DPRINT ("LdrVerifyImageMatchesChecksum() called\n");
3251 Status
= NtCreateSection (&SectionHandle
,
3258 if (!NT_SUCCESS(Status
))
3260 DPRINT1 ("NtCreateSection() failed (Status %lx)\n", Status
);
3266 Status
= NtMapViewOfSection (SectionHandle
,
3267 NtCurrentProcess (),
3276 if (!NT_SUCCESS(Status
))
3278 DPRINT1 ("NtMapViewOfSection() failed (Status %lx)\n", Status
);
3279 NtClose (SectionHandle
);
3283 Status
= NtQueryInformationFile (FileHandle
,
3286 sizeof (FILE_STANDARD_INFORMATION
),
3287 FileStandardInformation
);
3288 if (!NT_SUCCESS(Status
))
3290 DPRINT1 ("NtMapViewOfSection() failed (Status %lx)\n", Status
);
3291 NtUnmapViewOfSection (NtCurrentProcess (),
3293 NtClose (SectionHandle
);
3297 Result
= LdrpCheckImageChecksum (BaseAddress
,
3298 FileInfo
.EndOfFile
.u
.LowPart
);
3299 if (Result
== FALSE
)
3301 Status
= STATUS_IMAGE_CHECKSUM_MISMATCH
;
3304 NtUnmapViewOfSection (NtCurrentProcess (),
3307 NtClose (SectionHandle
);
3313 /***************************************************************************
3315 * LdrQueryImageFileExecutionOptions
3330 LdrQueryImageFileExecutionOptions (IN PUNICODE_STRING SubKey
,
3331 IN PCWSTR ValueName
,
3334 IN ULONG BufferSize
,
3335 OUT PULONG ReturnedLength OPTIONAL
)
3337 PKEY_VALUE_PARTIAL_INFORMATION KeyInfo
;
3338 OBJECT_ATTRIBUTES ObjectAttributes
;
3339 UNICODE_STRING ValueNameString
;
3340 UNICODE_STRING KeyName
;
3341 WCHAR NameBuffer
[256];
3349 L
"\\Registry\\Machine\\Software\\Microsoft\\Windows NT\\CurrentVersion\\Image File Execution Options\\");
3350 Ptr
= wcsrchr (SubKey
->Buffer
, L
'\\');
3353 Ptr
= SubKey
->Buffer
;
3359 wcscat (NameBuffer
, Ptr
);
3360 RtlInitUnicodeString (&KeyName
,
3363 InitializeObjectAttributes (&ObjectAttributes
,
3365 OBJ_CASE_INSENSITIVE
,
3369 Status
= NtOpenKey (&KeyHandle
,
3372 if (!NT_SUCCESS(Status
))
3374 DPRINT ("NtOpenKey() failed (Status %lx)\n", Status
);
3378 KeyInfoSize
= sizeof(KEY_VALUE_PARTIAL_INFORMATION
) + 32;
3379 KeyInfo
= RtlAllocateHeap (RtlGetProcessHeap(),
3382 if (KeyInfo
== NULL
)
3384 NtClose (KeyHandle
);
3385 return STATUS_INSUFFICIENT_RESOURCES
;
3388 RtlInitUnicodeString (&ValueNameString
,
3390 Status
= NtQueryValueKey (KeyHandle
,
3392 KeyValuePartialInformation
,
3396 if (Status
== STATUS_BUFFER_OVERFLOW
)
3398 KeyInfoSize
= sizeof(KEY_VALUE_PARTIAL_INFORMATION
) + KeyInfo
->DataLength
;
3399 RtlFreeHeap (RtlGetProcessHeap(),
3402 KeyInfo
= RtlAllocateHeap (RtlGetProcessHeap(),
3405 if (KeyInfo
== NULL
)
3407 NtClose (KeyHandle
);
3408 return STATUS_INSUFFICIENT_RESOURCES
;
3411 Status
= NtQueryValueKey (KeyHandle
,
3413 KeyValuePartialInformation
,
3418 NtClose (KeyHandle
);
3420 if (!NT_SUCCESS(Status
))
3422 if (KeyInfo
!= NULL
)
3424 RtlFreeHeap (RtlGetProcessHeap(),
3431 if (KeyInfo
->Type
!= Type
)
3433 RtlFreeHeap (RtlGetProcessHeap(),
3436 return STATUS_OBJECT_TYPE_MISMATCH
;
3439 ResultSize
= BufferSize
;
3440 if (ResultSize
< KeyInfo
->DataLength
)
3442 Status
= STATUS_BUFFER_OVERFLOW
;
3446 ResultSize
= KeyInfo
->DataLength
;
3448 RtlCopyMemory (Buffer
,
3452 RtlFreeHeap (RtlGetProcessHeap(),
3456 if (ReturnedLength
!= NULL
)
3458 *ReturnedLength
= ResultSize
;
3465 PIMAGE_BASE_RELOCATION NTAPI
3466 LdrProcessRelocationBlock(IN ULONG_PTR Address
,
3468 IN PUSHORT TypeOffset
,
3477 for (i
= 0; i
< Count
; i
++)
3479 Offset
= *TypeOffset
& 0xFFF;
3480 Type
= *TypeOffset
>> 12;
3484 case IMAGE_REL_BASED_ABSOLUTE
:
3487 case IMAGE_REL_BASED_HIGH
:
3488 ShortPtr
= (PUSHORT
)((ULONG_PTR
)Address
+ Offset
);
3489 *ShortPtr
+= HIWORD(Delta
);
3492 case IMAGE_REL_BASED_LOW
:
3493 ShortPtr
= (PUSHORT
)((ULONG_PTR
)Address
+ Offset
);
3494 *ShortPtr
+= LOWORD(Delta
);
3497 case IMAGE_REL_BASED_HIGHLOW
:
3498 LongPtr
= (PULONG
)((ULONG_PTR
)Address
+ Offset
);
3502 case IMAGE_REL_BASED_DIR64
:
3503 LongPtr
= (PULONG
)((ULONG_PTR
)Address
+ Offset
);
3508 case IMAGE_REL_BASED_HIGHADJ
:
3509 case IMAGE_REL_BASED_MIPS_JMPADDR
:
3511 DPRINT1("Unknown/unsupported fixup type %hu.\n", Type
);
3518 return (PIMAGE_BASE_RELOCATION
)TypeOffset
;
3523 LdrLockLoaderLock(IN ULONG Flags
,
3524 OUT PULONG Disposition OPTIONAL
,
3525 OUT PULONG Cookie OPTIONAL
)
3529 BOOLEAN CookieSet
= FALSE
;
3531 if ((Flags
!= 0x01) && (Flags
!= 0x02))
3532 return STATUS_INVALID_PARAMETER_1
;
3534 if (!Cookie
) return STATUS_INVALID_PARAMETER_3
;
3536 /* Set some defaults for failure while verifying params */
3541 if (Disposition
) *Disposition
= 0;
3543 _SEH2_EXCEPT(EXCEPTION_EXECUTE_HANDLER
)
3546 Status
= STATUS_INVALID_PARAMETER_3
;
3548 Status
= STATUS_INVALID_PARAMETER_2
;
3554 DPRINT1("Warning: Reporting errors with exception not supported yet!\n");
3555 RtlEnterCriticalSection(NtCurrentPeb()->LoaderLock
);
3556 Status
= STATUS_SUCCESS
;
3561 if (!Disposition
) return STATUS_INVALID_PARAMETER_2
;
3563 Ret
= RtlTryEnterCriticalSection(NtCurrentPeb()->LoaderLock
);
3566 *Disposition
= 0x01;
3568 *Disposition
= 0x02;
3570 Status
= STATUS_SUCCESS
;
3573 /* FIXME: Cookie is based on part of the thread id */
3574 *Cookie
= (ULONG_PTR
)NtCurrentTeb()->RealClientId
.UniqueThread
;
3580 LdrUnlockLoaderLock(IN ULONG Flags
,
3581 IN ULONG Cookie OPTIONAL
)
3584 return STATUS_INVALID_PARAMETER_1
;
3586 if (Cookie
!= (ULONG_PTR
)NtCurrentTeb()->RealClientId
.UniqueThread
)
3587 return STATUS_INVALID_PARAMETER_2
;
3589 RtlLeaveCriticalSection(NtCurrentPeb()->LoaderLock
);
3591 return STATUS_SUCCESS
;
3596 LdrUnloadAlternateResourceModule(IN PVOID BaseAddress
)