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
) + 1) * 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
)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;
577 * loading while app is initializing
578 * dll must not be unloaded
580 Module
->LoadCount
= LDRP_PROCESS_CREATION_TIME
;
584 Module
->TlsIndex
= -1;
585 Module
->CheckSum
= NTHeaders
->OptionalHeader
.CheckSum
;
586 Module
->TimeDateStamp
= NTHeaders
->FileHeader
.TimeDateStamp
;
588 RtlCreateUnicodeString (&Module
->FullDllName
,
590 RtlCreateUnicodeString (&Module
->BaseDllName
,
591 wcsrchr(FullDosName
, L
'\\') + 1);
592 DPRINT ("BaseDllName %wZ\n", &Module
->BaseDllName
);
594 RtlEnterCriticalSection (NtCurrentPeb()->LoaderLock
);
595 InsertTailList(&NtCurrentPeb()->Ldr
->InLoadOrderModuleList
,
596 &Module
->InLoadOrderLinks
);
597 RtlLeaveCriticalSection(NtCurrentPeb()->LoaderLock
);
604 LdrpMapKnownDll(IN PUNICODE_STRING DllName
,
605 OUT PUNICODE_STRING FullDosName
,
606 OUT PHANDLE SectionHandle
)
608 OBJECT_ATTRIBUTES ObjectAttributes
;
611 DPRINT("LdrpMapKnownDll() called\n");
613 if (LdrpKnownDllsDirHandle
== NULL
)
615 DPRINT("Invalid 'KnownDlls' directory\n");
616 return STATUS_UNSUCCESSFUL
;
619 DPRINT("LdrpKnownDllPath '%wZ'\n", &LdrpKnownDllPath
);
621 InitializeObjectAttributes(&ObjectAttributes
,
623 OBJ_CASE_INSENSITIVE
,
624 LdrpKnownDllsDirHandle
,
626 Status
= NtOpenSection(SectionHandle
,
627 SECTION_MAP_READ
| SECTION_MAP_WRITE
| SECTION_MAP_EXECUTE
,
629 if (!NT_SUCCESS(Status
))
631 DPRINT("NtOpenSection() failed for '%wZ' (Status 0x%08lx)\n", DllName
, Status
);
635 FullDosName
->Length
= LdrpKnownDllPath
.Length
+ DllName
->Length
+ sizeof(WCHAR
);
636 FullDosName
->MaximumLength
= FullDosName
->Length
+ sizeof(WCHAR
);
637 FullDosName
->Buffer
= RtlAllocateHeap(RtlGetProcessHeap(),
639 FullDosName
->MaximumLength
);
640 if (FullDosName
->Buffer
== NULL
)
642 FullDosName
->Length
= 0;
643 FullDosName
->MaximumLength
= 0;
644 return STATUS_SUCCESS
;
647 wcscpy(FullDosName
->Buffer
, LdrpKnownDllPath
.Buffer
);
648 wcscat(FullDosName
->Buffer
, L
"\\");
649 wcscat(FullDosName
->Buffer
, DllName
->Buffer
);
651 DPRINT("FullDosName '%wZ'\n", FullDosName
);
653 DPRINT("LdrpMapKnownDll() done\n");
655 return STATUS_SUCCESS
;
660 LdrpMapDllImageFile(IN PWSTR SearchPath OPTIONAL
,
661 IN PUNICODE_STRING DllName
,
662 OUT PUNICODE_STRING FullDosName
,
663 IN BOOLEAN MapAsDataFile
,
664 OUT PHANDLE SectionHandle
)
666 WCHAR
*SearchPathBuffer
= NULL
;
667 WCHAR
*ImagePathNameBufferPtr
= NULL
;
668 WCHAR DosName
[MAX_PATH
];
669 UNICODE_STRING FullNtFileName
;
670 UNICODE_STRING PathEnvironmentVar_U
;
671 UNICODE_STRING PathName_U
;
672 OBJECT_ATTRIBUTES FileObjectAttributes
;
674 char BlockBuffer
[1024];
675 PIMAGE_DOS_HEADER DosHeader
;
676 PIMAGE_NT_HEADERS NTHeaders
;
677 IO_STATUS_BLOCK IoStatusBlock
;
682 DPRINT("LdrpMapDllImageFile() called\n");
684 if (SearchPath
== NULL
)
686 /* get application running path */
687 ImagePathNameBufferPtr
= NtCurrentPeb()->ProcessParameters
->ImagePathName
.Buffer
;
689 /* Length of ImagePathName */
690 ImagePathLen
= wcslen(ImagePathNameBufferPtr
);
692 /* Subtract application name leaveing only the directory length */
693 while (ImagePathLen
&& ImagePathNameBufferPtr
[ImagePathLen
- 1] != L
'\\')
696 /* Length of directory + semicolon */
697 len
= ImagePathLen
+ 1;
699 /* Length of SystemRoot + "//system32" + semicolon*/
700 len
+= wcslen(SharedUserData
->NtSystemRoot
) + 10;
701 /* Length of SystemRoot + semicolon */
702 len
+= wcslen(SharedUserData
->NtSystemRoot
) + 1;
704 RtlInitUnicodeString (&PathName_U
, L
"PATH");
705 PathEnvironmentVar_U
.Length
= 0;
706 PathEnvironmentVar_U
.MaximumLength
= 0;
707 PathEnvironmentVar_U
.Buffer
= NULL
;
709 /* Get the path environment variable */
710 Status
= RtlQueryEnvironmentVariable_U(NULL
, &PathName_U
, &PathEnvironmentVar_U
);
712 /* Check that valid information was returned */
713 if ((Status
== STATUS_BUFFER_TOO_SMALL
) && (PathEnvironmentVar_U
.Length
> 0))
715 /* Allocate memory for the path env var */
716 PathEnvironmentVar_U
.Buffer
= RtlAllocateHeap(RtlGetProcessHeap(), HEAP_ZERO_MEMORY
, PathEnvironmentVar_U
.Length
+ sizeof(WCHAR
));
717 if (!PathEnvironmentVar_U
.Buffer
)
719 DPRINT1("Fatal! Out of Memory!!\n");
720 return STATUS_NO_MEMORY
;
722 PathEnvironmentVar_U
.MaximumLength
= PathEnvironmentVar_U
.Length
+ sizeof(WCHAR
);
725 Status
= RtlQueryEnvironmentVariable_U(NULL
, &PathName_U
, &PathEnvironmentVar_U
);
727 if (!NT_SUCCESS(Status
))
729 DPRINT1("Unable to get path environment string!\n");
732 /* Length of path evn var + semicolon */
733 len
+= (PathEnvironmentVar_U
.Length
/ sizeof(WCHAR
)) + 1;
736 /* Allocate the size needed to hold all the above paths + period */
737 SearchPathBuffer
= RtlAllocateHeap(RtlGetProcessHeap(), HEAP_ZERO_MEMORY
, (len
+ 2) * sizeof(WCHAR
));
738 if (!SearchPathBuffer
)
740 DPRINT1("Fatal! Out of Memory!!\n");
741 return STATUS_NO_MEMORY
;
744 wcsncpy(SearchPathBuffer
, ImagePathNameBufferPtr
, ImagePathLen
);
745 wcscat (SearchPathBuffer
, L
";");
746 wcscat (SearchPathBuffer
, SharedUserData
->NtSystemRoot
);
747 wcscat (SearchPathBuffer
, L
"\\system32;");
748 wcscat (SearchPathBuffer
, SharedUserData
->NtSystemRoot
);
749 wcscat (SearchPathBuffer
, L
";");
751 if (PathEnvironmentVar_U
.Buffer
)
753 wcscat (SearchPathBuffer
, PathEnvironmentVar_U
.Buffer
);
754 wcscat (SearchPathBuffer
, L
";");
755 RtlFreeHeap(RtlGetProcessHeap(), 0, PathEnvironmentVar_U
.Buffer
);
757 wcscat (SearchPathBuffer
, L
".");
759 SearchPath
= SearchPathBuffer
;
762 if (RtlDosSearchPath_U (SearchPath
,
769 /* try to find active context dll */
770 Status
= find_actctx_dll(DllName
->Buffer
, DosName
);
771 if(Status
== STATUS_SUCCESS
)
772 DPRINT("found %S for %S\n", DosName
,DllName
->Buffer
);
774 return STATUS_DLL_NOT_FOUND
;
777 if (!RtlDosPathNameToNtPathName_U (DosName
,
782 DPRINT("Dll %wZ not found!\n", DllName
);
783 return STATUS_DLL_NOT_FOUND
;
786 DPRINT("FullNtFileName %wZ\n", &FullNtFileName
);
788 InitializeObjectAttributes(&FileObjectAttributes
,
794 DPRINT("Opening dll \"%wZ\"\n", &FullNtFileName
);
796 Status
= NtOpenFile(&FileHandle
,
797 GENERIC_READ
|SYNCHRONIZE
,
798 &FileObjectAttributes
,
801 FILE_SYNCHRONOUS_IO_NONALERT
);
802 if (!NT_SUCCESS(Status
))
804 DPRINT1("Dll open of %wZ failed: Status = 0x%08lx\n",
805 &FullNtFileName
, Status
);
806 RtlFreeHeap (RtlGetProcessHeap (),
808 FullNtFileName
.Buffer
);
811 RtlFreeHeap (RtlGetProcessHeap (),
813 FullNtFileName
.Buffer
);
818 Status
= NtReadFile(FileHandle
,
827 if (!NT_SUCCESS(Status
))
829 DPRINT("Dll header read failed: Status = 0x%08lx\n", Status
);
835 * Overlay DOS and NT headers structures to the
836 * buffer with DLL's header raw data.
838 DosHeader
= (PIMAGE_DOS_HEADER
) BlockBuffer
;
839 NTHeaders
= (PIMAGE_NT_HEADERS
) (BlockBuffer
+ DosHeader
->e_lfanew
);
841 * Check it is a PE image file.
843 if ((DosHeader
->e_magic
!= IMAGE_DOS_SIGNATURE
)
844 || (DosHeader
->e_lfanew
== 0L)
845 || (*(PULONG
)(NTHeaders
) != IMAGE_NT_SIGNATURE
))
847 DPRINT("NTDLL format invalid\n");
850 return STATUS_UNSUCCESSFUL
;
855 * Create a section for dll.
857 Status
= NtCreateSection(SectionHandle
,
862 MapAsDataFile
? SEC_COMMIT
: SEC_IMAGE
,
866 if (!NT_SUCCESS(Status
))
868 DPRINT("NTDLL create section failed: Status = 0x%08lx\n", Status
);
872 RtlCreateUnicodeString(FullDosName
,
880 /***************************************************************************
897 LdrLoadDll (IN PWSTR SearchPath OPTIONAL
,
898 IN PULONG LoadFlags OPTIONAL
,
899 IN PUNICODE_STRING Name
,
900 OUT PVOID
*BaseAddress
/* also known as HMODULE*, and PHANDLE 'DllHandle' */)
903 PLDR_DATA_TABLE_ENTRY Module
;
905 PPEB Peb
= NtCurrentPeb();
907 TRACE_LDR("LdrLoadDll loading %wZ%S%S with flags %d\n",
909 SearchPath
? L
" from " : L
"",
910 SearchPath
? SearchPath
: L
"",
911 LoadFlags
? *LoadFlags
: 0);
913 Status
= LdrpLoadModule(SearchPath
, LoadFlags
? *LoadFlags
: 0, Name
, &Module
, BaseAddress
);
915 if (NT_SUCCESS(Status
) &&
916 (!LoadFlags
|| 0 == (*LoadFlags
& LOAD_LIBRARY_AS_DATAFILE
)))
918 if (!create_module_activation_context( Module
))
920 RtlActivateActivationContext(0, Module
->EntryPointActivationContext
, &cookie
);
923 if (!(Module
->Flags
& LDRP_PROCESS_ATTACH_CALLED
))
925 RtlEnterCriticalSection(Peb
->LoaderLock
);
926 Status
= LdrpAttachProcess();
927 RtlLeaveCriticalSection(Peb
->LoaderLock
);
929 if (Module
->EntryPointActivationContext
) RtlDeactivateActivationContext(0, cookie
);
932 if ((!Module
) && (NT_SUCCESS(Status
)))
935 *BaseAddress
= NT_SUCCESS(Status
) ? Module
->DllBase
: NULL
;
941 /***************************************************************************
943 * LdrFindEntryForAddress
958 LdrFindEntryForAddress(PVOID Address
,
959 PLDR_DATA_TABLE_ENTRY
*Module
)
961 PLIST_ENTRY ModuleListHead
;
963 PLDR_DATA_TABLE_ENTRY ModulePtr
;
965 DPRINT("LdrFindEntryForAddress(Address %p)\n", Address
);
967 if (NtCurrentPeb()->Ldr
== NULL
)
968 return(STATUS_NO_MORE_ENTRIES
);
970 RtlEnterCriticalSection(NtCurrentPeb()->LoaderLock
);
971 ModuleListHead
= &NtCurrentPeb()->Ldr
->InLoadOrderModuleList
;
972 Entry
= ModuleListHead
->Flink
;
973 if (Entry
== ModuleListHead
)
975 RtlLeaveCriticalSection(NtCurrentPeb()->LoaderLock
);
976 return(STATUS_NO_MORE_ENTRIES
);
979 while (Entry
!= ModuleListHead
)
981 ModulePtr
= CONTAINING_RECORD(Entry
, LDR_DATA_TABLE_ENTRY
, InLoadOrderLinks
);
983 DPRINT("Scanning %wZ at %p\n", &ModulePtr
->BaseDllName
, ModulePtr
->DllBase
);
985 if ((Address
>= ModulePtr
->DllBase
) &&
986 ((ULONG_PTR
)Address
<= ((ULONG_PTR
)ModulePtr
->DllBase
+ ModulePtr
->SizeOfImage
)))
989 RtlLeaveCriticalSection(NtCurrentPeb()->LoaderLock
);
990 return(STATUS_SUCCESS
);
993 Entry
= Entry
->Flink
;
996 DPRINT("Failed to find module entry.\n");
998 RtlLeaveCriticalSection(NtCurrentPeb()->LoaderLock
);
999 return(STATUS_NO_MORE_ENTRIES
);
1003 /***************************************************************************
1005 * LdrFindEntryForName
1019 LdrFindEntryForName(PUNICODE_STRING Name
,
1020 PLDR_DATA_TABLE_ENTRY
*Module
,
1023 PLIST_ENTRY ModuleListHead
;
1025 PLDR_DATA_TABLE_ENTRY ModulePtr
;
1026 BOOLEAN ContainsPath
;
1027 UNICODE_STRING AdjustedName
;
1029 DPRINT("LdrFindEntryForName(Name %wZ)\n", Name
);
1031 if (NtCurrentPeb()->Ldr
== NULL
)
1032 return(STATUS_NO_MORE_ENTRIES
);
1034 RtlEnterCriticalSection(NtCurrentPeb()->LoaderLock
);
1035 ModuleListHead
= &NtCurrentPeb()->Ldr
->InLoadOrderModuleList
;
1036 Entry
= ModuleListHead
->Flink
;
1037 if (Entry
== ModuleListHead
)
1039 RtlLeaveCriticalSection(NtCurrentPeb()->LoaderLock
);
1040 return(STATUS_NO_MORE_ENTRIES
);
1043 // NULL is the current process
1046 *Module
= ExeModule
;
1047 RtlLeaveCriticalSection(NtCurrentPeb()->LoaderLock
);
1048 return(STATUS_SUCCESS
);
1051 ContainsPath
= (Name
->Length
>= 2 * sizeof(WCHAR
) && L
':' == Name
->Buffer
[1]);
1052 LdrAdjustDllName (&AdjustedName
, Name
, !ContainsPath
);
1056 if ((!ContainsPath
&&
1057 0 == RtlCompareUnicodeString(&LdrpLastModule
->BaseDllName
, &AdjustedName
, TRUE
)) ||
1059 0 == RtlCompareUnicodeString(&LdrpLastModule
->FullDllName
, &AdjustedName
, TRUE
)))
1061 *Module
= LdrpLastModule
;
1062 if (Ref
&& (*Module
)->LoadCount
!= LDRP_PROCESS_CREATION_TIME
)
1064 (*Module
)->LoadCount
++;
1066 RtlLeaveCriticalSection(NtCurrentPeb()->LoaderLock
);
1067 RtlFreeUnicodeString(&AdjustedName
);
1068 return(STATUS_SUCCESS
);
1071 while (Entry
!= ModuleListHead
)
1073 ModulePtr
= CONTAINING_RECORD(Entry
, LDR_DATA_TABLE_ENTRY
, InLoadOrderLinks
);
1075 DPRINT("Scanning %wZ %wZ\n", &ModulePtr
->BaseDllName
, &AdjustedName
);
1077 if ((!ContainsPath
&&
1078 0 == RtlCompareUnicodeString(&ModulePtr
->BaseDllName
, &AdjustedName
, TRUE
)) ||
1080 0 == RtlCompareUnicodeString(&ModulePtr
->FullDllName
, &AdjustedName
, TRUE
)))
1082 *Module
= LdrpLastModule
= ModulePtr
;
1083 if (Ref
&& ModulePtr
->LoadCount
!= LDRP_PROCESS_CREATION_TIME
)
1085 ModulePtr
->LoadCount
++;
1087 RtlLeaveCriticalSection(NtCurrentPeb()->LoaderLock
);
1088 RtlFreeUnicodeString(&AdjustedName
);
1089 return(STATUS_SUCCESS
);
1092 Entry
= Entry
->Flink
;
1095 DPRINT("Failed to find dll %wZ\n", Name
);
1096 RtlLeaveCriticalSection(NtCurrentPeb()->LoaderLock
);
1097 RtlFreeUnicodeString(&AdjustedName
);
1098 return(STATUS_NO_MORE_ENTRIES
);
1101 /**********************************************************************
1117 LdrFixupForward(PCHAR ForwardName
)
1119 CHAR NameBuffer
[128];
1120 UNICODE_STRING DllName
;
1123 PLDR_DATA_TABLE_ENTRY Module
;
1126 strcpy(NameBuffer
, ForwardName
);
1127 p
= strchr(NameBuffer
, '.');
1132 DPRINT("Dll: %s Function: %s\n", NameBuffer
, p
+1);
1133 RtlCreateUnicodeStringFromAsciiz (&DllName
,
1136 Status
= LdrFindEntryForName (&DllName
, &Module
, FALSE
);
1138 * The caller (or the image) is responsible for loading of the dll, where the function is forwarded.
1140 if (!NT_SUCCESS(Status
))
1142 Status
= LdrLoadDll(NULL
, NULL
, &DllName
, &BaseAddress
);
1143 if (NT_SUCCESS(Status
))
1145 Status
= LdrFindEntryForName (&DllName
, &Module
, FALSE
);
1148 RtlFreeUnicodeString (&DllName
);
1149 if (!NT_SUCCESS(Status
))
1151 DPRINT1("LdrFixupForward: failed to load %s\n", NameBuffer
);
1155 DPRINT("BaseAddress: %p\n", Module
->DllBase
);
1157 return LdrGetExportByName(Module
->DllBase
, (PUCHAR
)(p
+1), -1);
1164 /**********************************************************************
1166 * LdrGetExportByOrdinal
1180 LdrGetExportByOrdinal (
1185 PIMAGE_EXPORT_DIRECTORY ExportDir
;
1186 ULONG ExportDirSize
;
1187 PDWORD
* ExFunctions
;
1190 ExportDir
= (PIMAGE_EXPORT_DIRECTORY
)
1191 RtlImageDirectoryEntryToData (BaseAddress
,
1193 IMAGE_DIRECTORY_ENTRY_EXPORT
,
1197 ExFunctions
= (PDWORD
*)RVA(BaseAddress
, ExportDir
->AddressOfFunctions
);
1198 DPRINT("LdrGetExportByOrdinal(Ordinal %lu) = %p\n",
1199 Ordinal
, RVA(BaseAddress
, ExFunctions
[Ordinal
- ExportDir
->Base
]));
1201 Function
= (0 != ExFunctions
[Ordinal
- ExportDir
->Base
]
1202 ? RVA(BaseAddress
, ExFunctions
[Ordinal
- ExportDir
->Base
] )
1205 if (((ULONG
)Function
>= (ULONG
)ExportDir
) &&
1206 ((ULONG
)Function
< (ULONG
)ExportDir
+ (ULONG
)ExportDirSize
))
1208 DPRINT("Forward: %s\n", (PCHAR
)Function
);
1209 Function
= LdrFixupForward((PCHAR
)Function
);
1216 /**********************************************************************
1218 * LdrGetExportByName
1229 * AddressOfNames and AddressOfNameOrdinals are paralell tables,
1230 * both with NumberOfNames entries.
1234 LdrGetExportByName(PVOID BaseAddress
,
1238 PIMAGE_EXPORT_DIRECTORY ExportDir
;
1239 PDWORD
*ExFunctions
;
1246 ULONG ExportDirSize
;
1248 DPRINT("LdrGetExportByName %p %s %hu\n", BaseAddress
, SymbolName
, Hint
);
1250 ExportDir
= (PIMAGE_EXPORT_DIRECTORY
)
1251 RtlImageDirectoryEntryToData(BaseAddress
,
1253 IMAGE_DIRECTORY_ENTRY_EXPORT
,
1255 if (ExportDir
== NULL
)
1257 DPRINT1("LdrGetExportByName(): no export directory, "
1258 "can't lookup %s/%hu!\n", SymbolName
, Hint
);
1263 //The symbol names may be missing entirely
1264 if (ExportDir
->AddressOfNames
== 0)
1266 DPRINT("LdrGetExportByName(): symbol names missing entirely\n");
1271 * Get header pointers
1273 ExNames
= (PDWORD
*)RVA(BaseAddress
, ExportDir
->AddressOfNames
);
1274 ExOrdinals
= (USHORT
*)RVA(BaseAddress
, ExportDir
->AddressOfNameOrdinals
);
1275 ExFunctions
= (PDWORD
*)RVA(BaseAddress
, ExportDir
->AddressOfFunctions
);
1278 * Check the hint first
1280 if (Hint
< ExportDir
->NumberOfNames
)
1282 ExName
= RVA(BaseAddress
, ExNames
[Hint
]);
1283 if (strcmp(ExName
, (PCHAR
)SymbolName
) == 0)
1285 Ordinal
= ExOrdinals
[Hint
];
1286 Function
= RVA(BaseAddress
, ExFunctions
[Ordinal
]);
1287 if (((ULONG
)Function
>= (ULONG
)ExportDir
) &&
1288 ((ULONG
)Function
< (ULONG
)ExportDir
+ (ULONG
)ExportDirSize
))
1290 DPRINT("Forward: %s\n", (PCHAR
)Function
);
1291 Function
= LdrFixupForward((PCHAR
)Function
);
1292 if (Function
== NULL
)
1294 DPRINT1("LdrGetExportByName(): failed to find %s\n",SymbolName
);
1298 if (Function
!= NULL
)
1307 maxn
= ExportDir
->NumberOfNames
- 1;
1308 while (minn
<= maxn
)
1313 mid
= (minn
+ maxn
) / 2;
1315 ExName
= RVA(BaseAddress
, ExNames
[mid
]);
1316 res
= strcmp(ExName
, (PCHAR
)SymbolName
);
1319 Ordinal
= ExOrdinals
[mid
];
1320 Function
= RVA(BaseAddress
, ExFunctions
[Ordinal
]);
1321 if (((ULONG
)Function
>= (ULONG
)ExportDir
) &&
1322 ((ULONG
)Function
< (ULONG
)ExportDir
+ (ULONG
)ExportDirSize
))
1324 DPRINT("Forward: %s\n", (PCHAR
)Function
);
1325 Function
= LdrFixupForward((PCHAR
)Function
);
1326 if (Function
== NULL
)
1328 DPRINT1("LdrGetExportByName(): failed to find %s\n",SymbolName
);
1332 if (Function
!= NULL
)
1335 else if (minn
== maxn
)
1337 DPRINT("LdrGetExportByName(): binary search failed\n");
1350 DPRINT("LdrGetExportByName(): failed to find %s\n",SymbolName
);
1355 /**********************************************************************
1357 * LdrPerformRelocations
1360 * Relocate a DLL's memory image.
1372 LdrPerformRelocations(PIMAGE_NT_HEADERS NTHeaders
,
1375 PIMAGE_DATA_DIRECTORY RelocationDDir
;
1376 PIMAGE_BASE_RELOCATION RelocationDir
, RelocationEnd
;
1377 ULONG Count
, ProtectSize
, OldProtect
, OldProtect2
;
1378 PVOID Page
, ProtectPage
, ProtectPage2
;
1383 if (NTHeaders
->FileHeader
.Characteristics
& IMAGE_FILE_RELOCS_STRIPPED
)
1385 return STATUS_SUCCESS
;
1389 &NTHeaders
->OptionalHeader
.DataDirectory
[IMAGE_DIRECTORY_ENTRY_BASERELOC
];
1391 if (RelocationDDir
->VirtualAddress
== 0 || RelocationDDir
->Size
== 0)
1393 return STATUS_SUCCESS
;
1396 ProtectSize
= PAGE_SIZE
;
1397 Delta
= (ULONG_PTR
)ImageBase
- NTHeaders
->OptionalHeader
.ImageBase
;
1398 RelocationDir
= (PIMAGE_BASE_RELOCATION
)((ULONG_PTR
)ImageBase
+
1399 RelocationDDir
->VirtualAddress
);
1400 RelocationEnd
= (PIMAGE_BASE_RELOCATION
)((ULONG_PTR
)ImageBase
+
1401 RelocationDDir
->VirtualAddress
+ RelocationDDir
->Size
);
1403 while (RelocationDir
< RelocationEnd
&&
1404 RelocationDir
->SizeOfBlock
> 0)
1406 Count
= (RelocationDir
->SizeOfBlock
- sizeof(IMAGE_BASE_RELOCATION
)) /
1408 Page
= (PVOID
)((ULONG_PTR
)ImageBase
+ (ULONG_PTR
)RelocationDir
->VirtualAddress
);
1409 TypeOffset
= (PUSHORT
)(RelocationDir
+ 1);
1411 /* Unprotect the page(s) we're about to relocate. */
1413 Status
= NtProtectVirtualMemory(NtCurrentProcess(),
1418 if (!NT_SUCCESS(Status
))
1420 DPRINT1("Failed to unprotect relocation target.\n");
1424 if (RelocationDir
->VirtualAddress
+ PAGE_SIZE
<
1425 NTHeaders
->OptionalHeader
.SizeOfImage
)
1427 ProtectPage2
= (PVOID
)((ULONG_PTR
)ProtectPage
+ PAGE_SIZE
);
1428 Status
= NtProtectVirtualMemory(NtCurrentProcess(),
1433 if (!NT_SUCCESS(Status
))
1435 DPRINT1("Failed to unprotect relocation target (2).\n");
1436 NtProtectVirtualMemory(NtCurrentProcess(),
1446 ProtectPage2
= NULL
;
1449 RelocationDir
= LdrProcessRelocationBlock((ULONG_PTR
)Page
,
1453 if (RelocationDir
== NULL
)
1454 return STATUS_UNSUCCESSFUL
;
1456 /* Restore old page protection. */
1457 NtProtectVirtualMemory(NtCurrentProcess(),
1463 if (ProtectPage2
!= NULL
)
1465 NtProtectVirtualMemory(NtCurrentProcess(),
1473 return STATUS_SUCCESS
;
1477 LdrpGetOrLoadModule(PWCHAR SearchPath
,
1479 PLDR_DATA_TABLE_ENTRY
* Module
,
1482 ANSI_STRING AnsiDllName
;
1483 UNICODE_STRING DllName
;
1486 DPRINT("LdrpGetOrLoadModule() called for %s\n", Name
);
1488 RtlInitAnsiString(&AnsiDllName
, Name
);
1489 Status
= RtlAnsiStringToUnicodeString(&DllName
, &AnsiDllName
, TRUE
);
1490 if (!NT_SUCCESS(Status
))
1495 Status
= LdrFindEntryForName (&DllName
, Module
, Load
);
1496 if (Load
&& !NT_SUCCESS(Status
))
1498 Status
= LdrpLoadModule(SearchPath
,
1503 if (NT_SUCCESS(Status
))
1505 Status
= LdrFindEntryForName (&DllName
, Module
, FALSE
);
1507 if (!NT_SUCCESS(Status
))
1509 ULONG ErrorResponse
;
1510 ULONG_PTR ErrorParameter
= (ULONG_PTR
)&AnsiDllName
;
1512 DPRINT1("failed to load %wZ\n", &DllName
);
1514 NtRaiseHardError(STATUS_DLL_NOT_FOUND
,
1522 RtlFreeUnicodeString (&DllName
);
1527 RtlpRaiseImportNotFound(CHAR
*FuncName
, ULONG Ordinal
, PUNICODE_STRING DllName
)
1529 ULONG ErrorResponse
;
1530 ULONG_PTR ErrorParameters
[2];
1531 ANSI_STRING ProcNameAnsi
;
1532 UNICODE_STRING ProcName
;
1537 _snprintf(Buffer
, 8, "# %ld", Ordinal
);
1541 RtlInitAnsiString(&ProcNameAnsi
, FuncName
);
1542 RtlAnsiStringToUnicodeString(&ProcName
, &ProcNameAnsi
, TRUE
);
1543 ErrorParameters
[0] = (ULONG_PTR
)&ProcName
;
1544 ErrorParameters
[1] = (ULONG_PTR
)DllName
;
1545 NtRaiseHardError(STATUS_ENTRYPOINT_NOT_FOUND
,
1551 RtlFreeUnicodeString(&ProcName
);
1555 LdrpProcessImportDirectoryEntry(PLDR_DATA_TABLE_ENTRY Module
,
1556 PLDR_DATA_TABLE_ENTRY ImportedModule
,
1557 PIMAGE_IMPORT_DESCRIPTOR ImportModuleDirectory
)
1560 PVOID
* ImportAddressList
;
1561 PULONG FunctionNameList
;
1567 if (ImportModuleDirectory
== NULL
|| ImportModuleDirectory
->Name
== 0)
1569 return STATUS_UNSUCCESSFUL
;
1572 /* Get the import address list. */
1573 ImportAddressList
= (PVOID
*)((ULONG_PTR
)Module
->DllBase
+
1574 (ULONG_PTR
)ImportModuleDirectory
->FirstThunk
);
1576 /* Get the list of functions to import. */
1577 if (ImportModuleDirectory
->OriginalFirstThunk
!= 0)
1579 FunctionNameList
= (PULONG
)((ULONG_PTR
)Module
->DllBase
+
1580 (ULONG_PTR
)ImportModuleDirectory
->OriginalFirstThunk
);
1584 FunctionNameList
= (PULONG
)((ULONG_PTR
)Module
->DllBase
+
1585 (ULONG_PTR
)ImportModuleDirectory
->FirstThunk
);
1588 /* Get the size of IAT. */
1590 while (FunctionNameList
[IATSize
] != 0L)
1595 /* No need to fixup anything if IAT is empty */
1596 if (IATSize
== 0) return STATUS_SUCCESS
;
1598 /* Unprotect the region we are about to write into. */
1599 IATBase
= (PVOID
)ImportAddressList
;
1600 IATSize
*= sizeof(PVOID
*);
1601 Status
= NtProtectVirtualMemory(NtCurrentProcess(),
1606 if (!NT_SUCCESS(Status
))
1608 DPRINT1("Failed to unprotect IAT.\n");
1612 /* Walk through function list and fixup addresses. */
1613 while (*FunctionNameList
!= 0L)
1615 if ((*FunctionNameList
) & 0x80000000)
1617 Ordinal
= (*FunctionNameList
) & 0x7fffffff;
1618 *ImportAddressList
= LdrGetExportByOrdinal(ImportedModule
->DllBase
,
1620 if ((*ImportAddressList
) == NULL
)
1622 DPRINT1("Failed to import #%ld from %wZ\n",
1623 Ordinal
, &ImportedModule
->FullDllName
);
1624 RtlpRaiseImportNotFound(NULL
, Ordinal
, &ImportedModule
->FullDllName
);
1625 return STATUS_ENTRYPOINT_NOT_FOUND
;
1630 IMAGE_IMPORT_BY_NAME
*pe_name
;
1631 pe_name
= RVA(Module
->DllBase
, *FunctionNameList
);
1632 *ImportAddressList
= LdrGetExportByName(ImportedModule
->DllBase
,
1635 if ((*ImportAddressList
) == NULL
)
1637 DPRINT1("Failed to import %s from %wZ\n",
1638 pe_name
->Name
, &ImportedModule
->FullDllName
);
1639 RtlpRaiseImportNotFound((CHAR
*)pe_name
->Name
,
1641 &ImportedModule
->FullDllName
);
1642 return STATUS_ENTRYPOINT_NOT_FOUND
;
1645 ImportAddressList
++;
1649 /* Protect the region we are about to write into. */
1650 Status
= NtProtectVirtualMemory(NtCurrentProcess(),
1655 if (!NT_SUCCESS(Status
))
1657 DPRINT1("Failed to protect IAT.\n");
1661 return STATUS_SUCCESS
;
1665 LdrpProcessImportDirectory(
1666 PLDR_DATA_TABLE_ENTRY Module
,
1667 PLDR_DATA_TABLE_ENTRY ImportedModule
,
1671 PIMAGE_IMPORT_DESCRIPTOR ImportModuleDirectory
;
1675 DPRINT("LdrpProcessImportDirectory(%p '%wZ', '%s')\n",
1676 Module
, &Module
->BaseDllName
, ImportedName
);
1679 ImportModuleDirectory
= (PIMAGE_IMPORT_DESCRIPTOR
)
1680 RtlImageDirectoryEntryToData(Module
->DllBase
,
1682 IMAGE_DIRECTORY_ENTRY_IMPORT
,
1684 if (ImportModuleDirectory
== NULL
)
1686 return STATUS_UNSUCCESSFUL
;
1689 while (ImportModuleDirectory
->Name
)
1691 Name
= (PCHAR
)Module
->DllBase
+ ImportModuleDirectory
->Name
;
1692 if (0 == _stricmp(Name
, ImportedName
))
1694 Status
= LdrpProcessImportDirectoryEntry(Module
,
1696 ImportModuleDirectory
);
1697 if (!NT_SUCCESS(Status
))
1702 ImportModuleDirectory
++;
1706 return STATUS_SUCCESS
;
1711 LdrpAdjustImportDirectory(PLDR_DATA_TABLE_ENTRY Module
,
1712 PLDR_DATA_TABLE_ENTRY ImportedModule
,
1715 PIMAGE_IMPORT_DESCRIPTOR ImportModuleDirectory
;
1717 PVOID
* ImportAddressList
;
1720 PULONG FunctionNameList
;
1725 PIMAGE_NT_HEADERS NTHeaders
;
1729 DPRINT("LdrpAdjustImportDirectory(Module %p '%wZ', %p '%wZ', '%s')\n",
1730 Module
, &Module
->BaseDllName
, ImportedModule
, &ImportedModule
->BaseDllName
, ImportedName
);
1732 ImportModuleDirectory
= (PIMAGE_IMPORT_DESCRIPTOR
)
1733 RtlImageDirectoryEntryToData(Module
->DllBase
,
1735 IMAGE_DIRECTORY_ENTRY_IMPORT
,
1737 if (ImportModuleDirectory
== NULL
)
1739 return STATUS_UNSUCCESSFUL
;
1742 while (ImportModuleDirectory
->Name
)
1744 Name
= (PCHAR
)Module
->DllBase
+ ImportModuleDirectory
->Name
;
1745 if (0 == _stricmp(Name
, (PCHAR
)ImportedName
))
1748 /* Get the import address list. */
1749 ImportAddressList
= (PVOID
*)((ULONG_PTR
)Module
->DllBase
+
1750 (ULONG_PTR
)ImportModuleDirectory
->FirstThunk
);
1752 /* Get the list of functions to import. */
1753 if (ImportModuleDirectory
->OriginalFirstThunk
!= 0)
1755 FunctionNameList
= (PULONG
)((ULONG_PTR
)Module
->DllBase
+
1756 (ULONG_PTR
)ImportModuleDirectory
->OriginalFirstThunk
);
1760 FunctionNameList
= (PULONG
)((ULONG_PTR
)Module
->DllBase
+
1761 (ULONG_PTR
)ImportModuleDirectory
->FirstThunk
);
1764 /* Get the size of IAT. */
1766 while (FunctionNameList
[IATSize
] != 0L)
1771 /* Unprotect the region we are about to write into. */
1772 IATBase
= (PVOID
)ImportAddressList
;
1773 IATSize
*= sizeof(PVOID
*);
1774 Status
= NtProtectVirtualMemory(NtCurrentProcess(),
1779 if (!NT_SUCCESS(Status
))
1781 DPRINT1("Failed to unprotect IAT.\n");
1785 NTHeaders
= RtlImageNtHeader (ImportedModule
->DllBase
);
1786 Start
= (PVOID
)NTHeaders
->OptionalHeader
.ImageBase
;
1787 End
= (PVOID
)((ULONG_PTR
)Start
+ ImportedModule
->SizeOfImage
);
1788 Offset
= (ULONG
)((ULONG_PTR
)ImportedModule
->DllBase
- (ULONG_PTR
)Start
);
1790 /* Walk through function list and fixup addresses. */
1791 while (*FunctionNameList
!= 0L)
1793 if (*ImportAddressList
>= Start
&& *ImportAddressList
< End
)
1795 (*ImportAddressList
) = (PVOID
)((ULONG_PTR
)(*ImportAddressList
) + Offset
);
1797 ImportAddressList
++;
1801 /* Protect the region we are about to write into. */
1802 Status
= NtProtectVirtualMemory(NtCurrentProcess(),
1807 if (!NT_SUCCESS(Status
))
1809 DPRINT1("Failed to protect IAT.\n");
1813 ImportModuleDirectory
++;
1815 return STATUS_SUCCESS
;
1819 /**********************************************************************
1824 * Compute the entry point for every symbol the DLL imports
1825 * from other modules.
1837 LdrFixupImports(IN PWSTR SearchPath OPTIONAL
,
1838 IN PLDR_DATA_TABLE_ENTRY Module
)
1840 PIMAGE_IMPORT_DESCRIPTOR ImportModuleDirectory
;
1841 PIMAGE_IMPORT_DESCRIPTOR ImportModuleDirectoryCurrent
;
1842 PIMAGE_BOUND_IMPORT_DESCRIPTOR BoundImportDescriptor
;
1843 PIMAGE_BOUND_IMPORT_DESCRIPTOR BoundImportDescriptorCurrent
;
1844 PIMAGE_TLS_DIRECTORY TlsDirectory
;
1846 NTSTATUS Status
= STATUS_SUCCESS
;
1847 PLDR_DATA_TABLE_ENTRY ImportedModule
;
1853 DPRINT("LdrFixupImports(SearchPath %S, Module %p)\n", SearchPath
, Module
);
1855 /* Check for tls data */
1856 TlsDirectory
= (PIMAGE_TLS_DIRECTORY
)
1857 RtlImageDirectoryEntryToData(Module
->DllBase
,
1859 IMAGE_DIRECTORY_ENTRY_TLS
,
1863 TlsSize
= TlsDirectory
->EndAddressOfRawData
1864 - TlsDirectory
->StartAddressOfRawData
1865 + TlsDirectory
->SizeOfZeroFill
;
1867 if (TlsSize
> 0 && NtCurrentPeb()->Ldr
->Initialized
)
1869 TRACE_LDR("Trying to dynamically load %wZ which contains a TLS directory\n",
1870 &Module
->BaseDllName
);
1871 TlsDirectory
= NULL
;
1875 if (!create_module_activation_context( Module
))
1877 if (Module
->EntryPointActivationContext
== NULL
)
1879 DPRINT("EntryPointActivationContext has not be allocated\n");
1880 DPRINT("Module->DllBaseName %wZ\n", Module
->BaseDllName
);
1882 RtlActivateActivationContext( 0, Module
->EntryPointActivationContext
, &cookie
);
1886 * Process each import module.
1888 ImportModuleDirectory
= (PIMAGE_IMPORT_DESCRIPTOR
)
1889 RtlImageDirectoryEntryToData(Module
->DllBase
,
1891 IMAGE_DIRECTORY_ENTRY_IMPORT
,
1894 BoundImportDescriptor
= (PIMAGE_BOUND_IMPORT_DESCRIPTOR
)
1895 RtlImageDirectoryEntryToData(Module
->DllBase
,
1897 IMAGE_DIRECTORY_ENTRY_BOUND_IMPORT
,
1900 if (BoundImportDescriptor
!= NULL
&& ImportModuleDirectory
== NULL
)
1902 DPRINT1("%wZ has only a bound import directory\n", &Module
->BaseDllName
);
1903 return STATUS_UNSUCCESSFUL
;
1905 if (BoundImportDescriptor
)
1907 DPRINT("BoundImportDescriptor %p\n", BoundImportDescriptor
);
1909 BoundImportDescriptorCurrent
= BoundImportDescriptor
;
1910 while (BoundImportDescriptorCurrent
->OffsetModuleName
)
1912 ImportedName
= (PCHAR
)BoundImportDescriptor
+
1913 BoundImportDescriptorCurrent
->OffsetModuleName
;
1914 TRACE_LDR("%wZ bound to %s\n", &Module
->BaseDllName
, ImportedName
);
1915 Status
= LdrpGetOrLoadModule(SearchPath
, ImportedName
, &ImportedModule
, TRUE
);
1916 if (!NT_SUCCESS(Status
))
1918 DPRINT1("failed to load %s\n", ImportedName
);
1921 if (Module
== ImportedModule
)
1923 LdrpDecrementLoadCount(Module
, FALSE
);
1925 if (ImportedModule
->TimeDateStamp
!= BoundImportDescriptorCurrent
->TimeDateStamp
)
1927 TRACE_LDR("%wZ has stale binding to %wZ\n",
1928 &Module
->BaseDllName
, &ImportedModule
->BaseDllName
);
1929 Status
= LdrpProcessImportDirectory(Module
, ImportedModule
, ImportedName
);
1930 if (!NT_SUCCESS(Status
))
1932 DPRINT1("failed to import %s\n", ImportedName
);
1938 BOOLEAN WrongForwarder
;
1939 WrongForwarder
= FALSE
;
1940 if (ImportedModule
->Flags
& LDRP_IMAGE_NOT_AT_BASE
)
1942 TRACE_LDR("%wZ has stale binding to %s\n",
1943 &Module
->BaseDllName
, ImportedName
);
1947 TRACE_LDR("%wZ has correct binding to %wZ\n",
1948 &Module
->BaseDllName
, &ImportedModule
->BaseDllName
);
1950 if (BoundImportDescriptorCurrent
->NumberOfModuleForwarderRefs
)
1952 PIMAGE_BOUND_FORWARDER_REF BoundForwarderRef
;
1954 PLDR_DATA_TABLE_ENTRY ForwarderModule
;
1955 PCHAR ForwarderName
;
1957 BoundForwarderRef
= (PIMAGE_BOUND_FORWARDER_REF
)(BoundImportDescriptorCurrent
+ 1);
1959 i
< BoundImportDescriptorCurrent
->NumberOfModuleForwarderRefs
;
1960 i
++, BoundForwarderRef
++)
1962 ForwarderName
= (PCHAR
)BoundImportDescriptor
+
1963 BoundForwarderRef
->OffsetModuleName
;
1964 TRACE_LDR("%wZ bound to %s via forwardes from %s\n",
1965 &Module
->BaseDllName
, ForwarderName
, ImportedName
);
1966 Status
= LdrpGetOrLoadModule(SearchPath
, ForwarderName
, &ForwarderModule
, TRUE
);
1967 if (!NT_SUCCESS(Status
))
1969 DPRINT1("failed to load %s\n", ForwarderName
);
1972 if (Module
== ImportedModule
)
1974 LdrpDecrementLoadCount(Module
, FALSE
);
1976 if (ForwarderModule
->TimeDateStamp
!= BoundForwarderRef
->TimeDateStamp
||
1977 ForwarderModule
->Flags
& LDRP_IMAGE_NOT_AT_BASE
)
1979 TRACE_LDR("%wZ has stale binding to %s\n",
1980 &Module
->BaseDllName
, ForwarderName
);
1981 WrongForwarder
= TRUE
;
1985 TRACE_LDR("%wZ has correct binding to %s\n",
1986 &Module
->BaseDllName
, ForwarderName
);
1990 if (WrongForwarder
||
1991 ImportedModule
->Flags
& LDRP_IMAGE_NOT_AT_BASE
)
1993 Status
= LdrpProcessImportDirectory(Module
, ImportedModule
, ImportedName
);
1994 if (!NT_SUCCESS(Status
))
1996 DPRINT1("failed to import %s\n", ImportedName
);
2000 else if (ImportedModule
->Flags
& LDRP_IMAGE_NOT_AT_BASE
)
2002 TRACE_LDR("Adjust imports for %s from %wZ\n",
2003 ImportedName
, &Module
->BaseDllName
);
2004 Status
= LdrpAdjustImportDirectory(Module
, ImportedModule
, ImportedName
);
2005 if (!NT_SUCCESS(Status
))
2007 DPRINT1("failed to adjust import entries for %s\n", ImportedName
);
2011 else if (WrongForwarder
)
2015 * Update only forwarders
2017 TRACE_LDR("Stale BIND %s from %wZ\n",
2018 ImportedName
, &Module
->BaseDllName
);
2019 Status
= LdrpProcessImportDirectory(Module
, ImportedModule
, ImportedName
);
2020 if (!NT_SUCCESS(Status
))
2022 DPRINT1("faild to import %s\n", ImportedName
);
2031 BoundImportDescriptorCurrent
+= BoundImportDescriptorCurrent
->NumberOfModuleForwarderRefs
+ 1;
2034 else if (ImportModuleDirectory
)
2036 DPRINT("ImportModuleDirectory %p\n", ImportModuleDirectory
);
2038 ImportModuleDirectoryCurrent
= ImportModuleDirectory
;
2039 while (ImportModuleDirectoryCurrent
->Name
)
2041 ImportedName
= (PCHAR
)Module
->DllBase
+ ImportModuleDirectoryCurrent
->Name
;
2042 TRACE_LDR("%wZ imports functions from %s\n", &Module
->BaseDllName
, ImportedName
);
2044 if (SearchPath
== NULL
)
2046 ModulePath
= LdrpQueryAppPaths(Module
->BaseDllName
.Buffer
);
2048 Status
= LdrpGetOrLoadModule(ModulePath
, ImportedName
, &ImportedModule
, TRUE
);
2049 if (ModulePath
!= NULL
) RtlFreeHeap(RtlGetProcessHeap(), 0, ModulePath
);
2050 if (NT_SUCCESS(Status
)) goto Success
;
2053 Status
= LdrpGetOrLoadModule(SearchPath
, ImportedName
, &ImportedModule
, TRUE
);
2054 if (!NT_SUCCESS(Status
))
2056 DPRINT1("failed to load %s\n", ImportedName
);
2060 if (Module
== ImportedModule
)
2062 LdrpDecrementLoadCount(Module
, FALSE
);
2065 TRACE_LDR("Initializing imports for %wZ from %s\n",
2066 &Module
->BaseDllName
, ImportedName
);
2067 Status
= LdrpProcessImportDirectoryEntry(Module
, ImportedModule
, ImportModuleDirectoryCurrent
);
2068 if (!NT_SUCCESS(Status
))
2070 DPRINT1("failed to import %s\n", ImportedName
);
2073 ImportModuleDirectoryCurrent
++;
2076 if (!NT_SUCCESS(Status
))
2078 NTSTATUS errorStatus
= Status
;
2080 while (ImportModuleDirectoryCurrent
>= ImportModuleDirectory
)
2082 ImportedName
= (PCHAR
)Module
->DllBase
+ ImportModuleDirectoryCurrent
->Name
;
2084 Status
= LdrpGetOrLoadModule(NULL
, ImportedName
, &ImportedModule
, FALSE
);
2085 if (NT_SUCCESS(Status
) && Module
!= ImportedModule
)
2087 Status
= LdrpUnloadModule(ImportedModule
, FALSE
);
2088 if (!NT_SUCCESS(Status
)) DPRINT1("unable to unload %s\n", ImportedName
);
2090 ImportModuleDirectoryCurrent
--;
2096 if (TlsDirectory
&& TlsSize
> 0)
2098 LdrpAcquireTlsSlot(Module
, TlsSize
, FALSE
);
2101 if (Module
->EntryPointActivationContext
) RtlDeactivateActivationContext( 0, cookie
);
2103 return STATUS_SUCCESS
;
2107 /**********************************************************************
2112 * 1. Relocate, if needed the EXE.
2113 * 2. Fixup any imported symbol.
2114 * 3. Compute the EXE's entry point.
2118 * Address at which the EXE's image
2122 * Handle of the section that contains
2126 * NULL on error; otherwise the entry point
2127 * to call for initializing the DLL.
2132 * 04.01.2004 hb Previous this function was used for all images (dll + exe).
2133 * Currently the function is only used for the exe.
2135 PEPFUNC
LdrPEStartup (PVOID ImageBase
,
2136 HANDLE SectionHandle
,
2137 PLDR_DATA_TABLE_ENTRY
* Module
,
2141 PEPFUNC EntryPoint
= NULL
;
2142 PIMAGE_DOS_HEADER DosHeader
;
2143 PIMAGE_NT_HEADERS NTHeaders
;
2144 PLDR_DATA_TABLE_ENTRY tmpModule
;
2145 PVOID ActivationContextStack
;
2147 DPRINT("LdrPEStartup(ImageBase %p SectionHandle %p)\n",
2148 ImageBase
, SectionHandle
);
2151 * Overlay DOS and WNT headers structures
2152 * to the DLL's image.
2154 DosHeader
= (PIMAGE_DOS_HEADER
) ImageBase
;
2155 NTHeaders
= (PIMAGE_NT_HEADERS
) ((ULONG_PTR
)ImageBase
+ DosHeader
->e_lfanew
);
2158 * If the base address is different from the
2159 * one the DLL is actually loaded, perform any
2162 if (ImageBase
!= (PVOID
)NTHeaders
->OptionalHeader
.ImageBase
)
2164 DPRINT("LDR: Performing relocations\n");
2165 Status
= LdrPerformRelocations(NTHeaders
, ImageBase
);
2166 if (!NT_SUCCESS(Status
))
2168 DPRINT1("LdrPerformRelocations() failed\n");
2175 *Module
= LdrAddModuleEntry(ImageBase
, NTHeaders
, FullDosName
);
2176 (*Module
)->SectionPointer
= SectionHandle
;
2180 Module
= &tmpModule
;
2181 Status
= LdrFindEntryForAddress(ImageBase
, Module
);
2182 if (!NT_SUCCESS(Status
))
2188 if (ImageBase
!= (PVOID
) NTHeaders
->OptionalHeader
.ImageBase
)
2190 (*Module
)->Flags
|= LDRP_IMAGE_NOT_AT_BASE
;
2193 /* Allocate memory for the ActivationContextStack */
2194 /* FIXME: Verify RtlAllocateActivationContextStack behavior */
2195 Status
= RtlAllocateActivationContextStack(&ActivationContextStack
);
2196 if (NT_SUCCESS(Status
))
2198 DPRINT("ActivationContextStack %x\n",ActivationContextStack
);
2199 DPRINT("ActiveFrame %x\n", ((PACTIVATION_CONTEXT_STACK
)ActivationContextStack
)->ActiveFrame
);
2200 NtCurrentTeb()->ActivationContextStackPointer
= ActivationContextStack
;
2201 NtCurrentTeb()->ActivationContextStackPointer
->ActiveFrame
= NULL
;
2204 DPRINT1("Warning: Unable to allocate ActivationContextStack\n");
2207 * If the DLL's imports symbols from other
2208 * modules, fixup the imported calls entry points.
2210 DPRINT("About to fixup imports\n");
2211 Status
= LdrFixupImports(NULL
, *Module
);
2212 if (!NT_SUCCESS(Status
))
2214 DPRINT1("LdrFixupImports() failed for %wZ\n", &(*Module
)->BaseDllName
);
2217 DPRINT("Fixup done\n");
2218 RtlEnterCriticalSection(NtCurrentPeb()->LoaderLock
);
2219 Status
= LdrpInitializeTlsForProccess();
2220 if (NT_SUCCESS(Status
))
2222 Status
= LdrpAttachProcess();
2224 if (NT_SUCCESS(Status
))
2226 LdrpTlsCallback(*Module
, DLL_PROCESS_ATTACH
);
2230 RtlLeaveCriticalSection(NtCurrentPeb()->LoaderLock
);
2231 if (!NT_SUCCESS(Status
))
2237 * Compute the DLL's entry point's address.
2239 DPRINT("ImageBase = %p\n", ImageBase
);
2240 DPRINT("AddressOfEntryPoint = 0x%lx\n",(ULONG
)NTHeaders
->OptionalHeader
.AddressOfEntryPoint
);
2241 if (NTHeaders
->OptionalHeader
.AddressOfEntryPoint
!= 0)
2243 EntryPoint
= (PEPFUNC
) ((ULONG_PTR
)ImageBase
2244 + NTHeaders
->OptionalHeader
.AddressOfEntryPoint
);
2246 DPRINT("LdrPEStartup() = %p\n",EntryPoint
);
2251 LdrpLoadModule(IN PWSTR SearchPath OPTIONAL
,
2253 IN PUNICODE_STRING Name
,
2254 PLDR_DATA_TABLE_ENTRY
*Module
,
2255 PVOID
*BaseAddress OPTIONAL
)
2257 UNICODE_STRING AdjustedName
;
2258 UNICODE_STRING FullDosName
;
2260 PLDR_DATA_TABLE_ENTRY tmpModule
;
2261 HANDLE SectionHandle
;
2264 PIMAGE_NT_HEADERS NtHeaders
;
2265 BOOLEAN MappedAsDataFile
;
2266 PVOID ArbitraryUserPointer
;
2270 Module
= &tmpModule
;
2272 /* adjust the full dll name */
2273 LdrAdjustDllName(&AdjustedName
, Name
, FALSE
);
2275 DPRINT("%wZ\n", &AdjustedName
);
2277 MappedAsDataFile
= FALSE
;
2278 /* Test if dll is already loaded */
2279 Status
= LdrFindEntryForName(&AdjustedName
, Module
, TRUE
);
2280 if (NT_SUCCESS(Status
))
2282 RtlFreeUnicodeString(&AdjustedName
);
2283 if (NULL
!= BaseAddress
)
2285 *BaseAddress
= (*Module
)->DllBase
;
2290 /* Open or create dll image section */
2291 Status
= LdrpMapKnownDll(&AdjustedName
, &FullDosName
, &SectionHandle
);
2292 if (!NT_SUCCESS(Status
))
2294 MappedAsDataFile
= (0 != (LoadFlags
& LOAD_LIBRARY_AS_DATAFILE
));
2295 Status
= LdrpMapDllImageFile(SearchPath
, &AdjustedName
, &FullDosName
,
2296 MappedAsDataFile
, &SectionHandle
);
2298 if (!NT_SUCCESS(Status
))
2300 DPRINT1("Failed to create or open dll section of '%wZ' (Status %lx)\n",
2301 &AdjustedName
, Status
);
2302 RtlFreeUnicodeString(&AdjustedName
);
2305 RtlFreeUnicodeString(&AdjustedName
);
2306 /* Map the dll into the process */
2309 ArbitraryUserPointer
= NtCurrentTeb()->NtTib
.ArbitraryUserPointer
;
2310 NtCurrentTeb()->NtTib
.ArbitraryUserPointer
= FullDosName
.Buffer
;
2311 Status
= NtMapViewOfSection(SectionHandle
,
2321 NtCurrentTeb()->NtTib
.ArbitraryUserPointer
= ArbitraryUserPointer
;
2322 if (!NT_SUCCESS(Status
))
2324 DPRINT1("map view of section failed (Status 0x%08lx)\n", Status
);
2325 RtlFreeUnicodeString(&FullDosName
);
2326 NtClose(SectionHandle
);
2329 if (NULL
!= BaseAddress
)
2331 *BaseAddress
= ImageBase
;
2333 if (!MappedAsDataFile
)
2335 /* Get and check the NT headers */
2336 NtHeaders
= RtlImageNtHeader(ImageBase
);
2337 if (NtHeaders
== NULL
)
2339 DPRINT1("RtlImageNtHeaders() failed\n");
2340 NtUnmapViewOfSection (NtCurrentProcess (), ImageBase
);
2341 NtClose (SectionHandle
);
2342 RtlFreeUnicodeString(&FullDosName
);
2343 return STATUS_UNSUCCESSFUL
;
2346 DPRINT("Mapped %wZ at %x\n", &FullDosName
, ImageBase
);
2347 if (MappedAsDataFile
)
2349 ASSERT(NULL
!= BaseAddress
);
2350 if (NULL
!= BaseAddress
)
2352 *BaseAddress
= (PVOID
) ((char *) *BaseAddress
+ 1);
2355 RtlFreeUnicodeString(&FullDosName
);
2356 NtClose(SectionHandle
);
2357 return STATUS_SUCCESS
;
2359 /* If the base address is different from the
2360 * one the DLL is actually loaded, perform any
2362 if (ImageBase
!= (PVOID
) NtHeaders
->OptionalHeader
.ImageBase
)
2364 DPRINT1("Relocating (%lx -> %p) %wZ\n",
2365 NtHeaders
->OptionalHeader
.ImageBase
, ImageBase
, &FullDosName
);
2366 Status
= LdrPerformRelocations(NtHeaders
, ImageBase
);
2367 if (!NT_SUCCESS(Status
))
2369 DPRINT1("LdrPerformRelocations() failed\n");
2370 NtUnmapViewOfSection (NtCurrentProcess (), ImageBase
);
2371 NtClose (SectionHandle
);
2372 RtlFreeUnicodeString(&FullDosName
);
2373 return STATUS_UNSUCCESSFUL
;
2376 *Module
= LdrAddModuleEntry(ImageBase
, NtHeaders
, FullDosName
.Buffer
);
2377 (*Module
)->SectionPointer
= SectionHandle
;
2378 if (ImageBase
!= (PVOID
) NtHeaders
->OptionalHeader
.ImageBase
)
2380 (*Module
)->Flags
|= LDRP_IMAGE_NOT_AT_BASE
;
2382 if (NtHeaders
->FileHeader
.Characteristics
& IMAGE_FILE_DLL
)
2384 (*Module
)->Flags
|= LDRP_IMAGE_DLL
;
2386 /* fixup the imported calls entry points */
2387 Status
= LdrFixupImports(SearchPath
, *Module
);
2388 if (!NT_SUCCESS(Status
))
2390 DPRINT1("LdrFixupImports failed for %wZ, status=%x\n", &(*Module
)->BaseDllName
, Status
);
2391 NtUnmapViewOfSection (NtCurrentProcess (), ImageBase
);
2392 NtClose (SectionHandle
);
2393 RtlFreeUnicodeString (&FullDosName
);
2394 RtlFreeUnicodeString (&(*Module
)->FullDllName
);
2395 RtlFreeUnicodeString (&(*Module
)->BaseDllName
);
2396 RemoveEntryList (&(*Module
)->InLoadOrderLinks
);
2400 RtlEnterCriticalSection(NtCurrentPeb()->LoaderLock
);
2401 InsertTailList(&NtCurrentPeb()->Ldr
->InInitializationOrderModuleList
,
2402 &(*Module
)->InInitializationOrderModuleList
);
2403 RtlLeaveCriticalSection (NtCurrentPeb()->LoaderLock
);
2405 return STATUS_SUCCESS
;
2409 LdrpUnloadModule(PLDR_DATA_TABLE_ENTRY Module
,
2412 PIMAGE_IMPORT_DESCRIPTOR ImportModuleDirectory
;
2413 PIMAGE_BOUND_IMPORT_DESCRIPTOR BoundImportDescriptor
;
2414 PIMAGE_BOUND_IMPORT_DESCRIPTOR BoundImportDescriptorCurrent
;
2416 PLDR_DATA_TABLE_ENTRY ImportedModule
;
2417 NTSTATUS Status
= 0;
2423 RtlEnterCriticalSection(NtCurrentPeb()->LoaderLock
);
2426 LoadCount
= LdrpDecrementLoadCount(Module
, Unload
);
2428 TRACE_LDR("Unload %wZ, LoadCount %d\n", &Module
->BaseDllName
, LoadCount
);
2432 /* ?????????????????? */
2434 else if (!(Module
->Flags
& LDRP_STATIC_LINK
) && LoadCount
== 1)
2436 BoundImportDescriptor
= (PIMAGE_BOUND_IMPORT_DESCRIPTOR
)
2437 RtlImageDirectoryEntryToData(Module
->DllBase
,
2439 IMAGE_DIRECTORY_ENTRY_BOUND_IMPORT
,
2441 if (BoundImportDescriptor
)
2443 /* dereferencing all imported modules, use the bound import descriptor */
2444 BoundImportDescriptorCurrent
= BoundImportDescriptor
;
2445 while (BoundImportDescriptorCurrent
->OffsetModuleName
)
2447 ImportedName
= (PCHAR
)BoundImportDescriptor
+ BoundImportDescriptorCurrent
->OffsetModuleName
;
2448 TRACE_LDR("%wZ trys to unload %s\n", &Module
->BaseDllName
, ImportedName
);
2449 Status
= LdrpGetOrLoadModule(NULL
, ImportedName
, &ImportedModule
, FALSE
);
2450 if (!NT_SUCCESS(Status
))
2452 DPRINT1("unable to found imported modul %s\n", ImportedName
);
2456 if (Module
!= ImportedModule
)
2458 Status
= LdrpUnloadModule(ImportedModule
, FALSE
);
2459 if (!NT_SUCCESS(Status
))
2461 DPRINT1("unable to unload %s\n", ImportedName
);
2465 BoundImportDescriptorCurrent
++;
2470 ImportModuleDirectory
= (PIMAGE_IMPORT_DESCRIPTOR
)
2471 RtlImageDirectoryEntryToData(Module
->DllBase
,
2473 IMAGE_DIRECTORY_ENTRY_IMPORT
,
2475 if (ImportModuleDirectory
)
2477 /* dereferencing all imported modules, use the import descriptor */
2478 while (ImportModuleDirectory
->Name
)
2480 ImportedName
= (PCHAR
)Module
->DllBase
+ ImportModuleDirectory
->Name
;
2481 TRACE_LDR("%wZ trys to unload %s\n", &Module
->BaseDllName
, ImportedName
);
2482 Status
= LdrpGetOrLoadModule(NULL
, ImportedName
, &ImportedModule
, FALSE
);
2483 if (!NT_SUCCESS(Status
))
2485 DPRINT1("unable to found imported modul %s\n", ImportedName
);
2489 if (Module
!= ImportedModule
)
2491 Status
= LdrpUnloadModule(ImportedModule
, FALSE
);
2492 if (!NT_SUCCESS(Status
))
2494 DPRINT1("unable to unload %s\n", ImportedName
);
2498 ImportModuleDirectory
++;
2506 if (!(Module
->Flags
& LDRP_STATIC_LINK
))
2508 LdrpDetachProcess(FALSE
);
2511 RtlLeaveCriticalSection (NtCurrentPeb()->LoaderLock
);
2513 return STATUS_SUCCESS
;
2521 LdrUnloadDll (IN PVOID BaseAddress
)
2523 PLDR_DATA_TABLE_ENTRY Module
;
2526 if (BaseAddress
== NULL
)
2527 return STATUS_SUCCESS
;
2529 if (LdrMappedAsDataFile(&BaseAddress
))
2531 Status
= NtUnmapViewOfSection(NtCurrentProcess(), BaseAddress
);
2535 Status
= LdrFindEntryForAddress(BaseAddress
, &Module
);
2536 if (NT_SUCCESS(Status
))
2538 TRACE_LDR("LdrUnloadDll, , unloading %wZ\n", &Module
->BaseDllName
);
2539 Status
= LdrpUnloadModule(Module
, TRUE
);
2550 LdrDisableThreadCalloutsForDll(IN PVOID BaseAddress
)
2552 PLIST_ENTRY ModuleListHead
;
2554 PLDR_DATA_TABLE_ENTRY Module
;
2557 DPRINT("LdrDisableThreadCalloutsForDll (BaseAddress %p)\n", BaseAddress
);
2559 Status
= STATUS_DLL_NOT_FOUND
;
2560 RtlEnterCriticalSection (NtCurrentPeb()->LoaderLock
);
2561 ModuleListHead
= &NtCurrentPeb()->Ldr
->InLoadOrderModuleList
;
2562 Entry
= ModuleListHead
->Flink
;
2563 while (Entry
!= ModuleListHead
)
2565 Module
= CONTAINING_RECORD(Entry
, LDR_DATA_TABLE_ENTRY
, InLoadOrderLinks
);
2567 DPRINT("BaseDllName %wZ BaseAddress %p\n", &Module
->BaseDllName
, Module
->DllBase
);
2569 if (Module
->DllBase
== BaseAddress
)
2571 if (Module
->TlsIndex
== 0xFFFF)
2573 Module
->Flags
|= LDRP_DONT_CALL_FOR_THREADS
;
2574 Status
= STATUS_SUCCESS
;
2578 Entry
= Entry
->Flink
;
2580 RtlLeaveCriticalSection (NtCurrentPeb()->LoaderLock
);
2588 LdrGetDllHandle(IN PWSTR DllPath OPTIONAL
,
2589 IN PULONG DllCharacteristics
,
2590 IN PUNICODE_STRING DllName
,
2591 OUT PVOID
*DllHandle
)
2593 PLDR_DATA_TABLE_ENTRY Module
;
2596 TRACE_LDR("LdrGetDllHandle, searching for %wZ from %S\n",
2597 DllName
, DllPath
? DllPath
: L
"");
2599 /* NULL is the current executable */
2600 if (DllName
== NULL
)
2602 *DllHandle
= ExeModule
->DllBase
;
2603 DPRINT("BaseAddress 0x%lx\n", *DllHandle
);
2604 return STATUS_SUCCESS
;
2607 Status
= LdrFindEntryForName(DllName
, &Module
, FALSE
);
2608 if (NT_SUCCESS(Status
))
2610 *DllHandle
= Module
->DllBase
;
2611 return STATUS_SUCCESS
;
2614 DPRINT("Failed to find dll %wZ\n", DllName
);
2616 return STATUS_DLL_NOT_FOUND
;
2623 LdrAddRefDll(IN ULONG Flags
,
2624 IN PVOID BaseAddress
)
2626 PLIST_ENTRY ModuleListHead
;
2628 PLDR_DATA_TABLE_ENTRY Module
;
2631 if (Flags
& ~(LDR_PIN_MODULE
))
2633 return STATUS_INVALID_PARAMETER
;
2636 Status
= STATUS_DLL_NOT_FOUND
;
2637 RtlEnterCriticalSection (NtCurrentPeb()->LoaderLock
);
2638 ModuleListHead
= &NtCurrentPeb()->Ldr
->InLoadOrderModuleList
;
2639 Entry
= ModuleListHead
->Flink
;
2640 while (Entry
!= ModuleListHead
)
2642 Module
= CONTAINING_RECORD(Entry
, LDR_DATA_TABLE_ENTRY
, InLoadOrderLinks
);
2644 if (Module
->DllBase
== BaseAddress
)
2646 if (Flags
& LDR_PIN_MODULE
)
2648 Module
->Flags
|= LDRP_STATIC_LINK
;
2652 LdrpIncrementLoadCount(Module
,
2655 Status
= STATUS_SUCCESS
;
2658 Entry
= Entry
->Flink
;
2660 RtlLeaveCriticalSection (NtCurrentPeb()->LoaderLock
);
2668 LdrGetProcedureAddress (IN PVOID BaseAddress
,
2669 IN PANSI_STRING Name
,
2671 OUT PVOID
*ProcedureAddress
)
2673 NTSTATUS Status
= STATUS_PROCEDURE_NOT_FOUND
;
2674 if (Name
&& Name
->Length
)
2676 TRACE_LDR("LdrGetProcedureAddress by NAME - %Z\n", Name
);
2680 TRACE_LDR("LdrGetProcedureAddress by ORDINAL - %d\n", Ordinal
);
2683 DPRINT("LdrGetProcedureAddress (BaseAddress %p Name %Z Ordinal %lu ProcedureAddress %p)\n",
2684 BaseAddress
, Name
, Ordinal
, ProcedureAddress
);
2688 if (Name
&& Name
->Length
)
2691 *ProcedureAddress
= LdrGetExportByName(BaseAddress
, (PUCHAR
)Name
->Buffer
, 0xffff);
2692 if (*ProcedureAddress
!= NULL
)
2694 Status
= STATUS_SUCCESS
;
2696 DPRINT("LdrGetProcedureAddress: Can't resolve symbol '%Z'\n", Name
);
2701 Ordinal
&= 0x0000FFFF;
2702 *ProcedureAddress
= LdrGetExportByOrdinal(BaseAddress
, (WORD
)Ordinal
);
2703 if (*ProcedureAddress
)
2705 Status
= STATUS_SUCCESS
;
2707 DPRINT("LdrGetProcedureAddress: Can't resolve symbol @%lu\n", Ordinal
);
2710 _SEH2_EXCEPT(EXCEPTION_EXECUTE_HANDLER
)
2712 Status
= STATUS_DLL_NOT_FOUND
;
2719 /**********************************************************************
2724 * Unload dll's which are no longer referenced from others dll's
2735 * The loader lock must be held on enty.
2738 LdrpDetachProcess(BOOLEAN UnloadAll
)
2740 PLIST_ENTRY ModuleListHead
;
2742 PLDR_DATA_TABLE_ENTRY Module
;
2743 static ULONG CallingCount
= 0;
2745 DPRINT("LdrpDetachProcess() called for %wZ\n",
2746 &ExeModule
->BaseDllName
);
2749 LdrpDllShutdownInProgress
= TRUE
;
2753 ModuleListHead
= &NtCurrentPeb()->Ldr
->InInitializationOrderModuleList
;
2754 Entry
= ModuleListHead
->Blink
;
2755 while (Entry
!= ModuleListHead
)
2757 Module
= CONTAINING_RECORD(Entry
, LDR_DATA_TABLE_ENTRY
, InInitializationOrderModuleList
);
2758 if (((UnloadAll
&& Module
->LoadCount
== LDRP_PROCESS_CREATION_TIME
) || Module
->LoadCount
== 0) &&
2759 Module
->Flags
& LDRP_ENTRY_PROCESSED
&&
2760 !(Module
->Flags
& LDRP_UNLOAD_IN_PROGRESS
))
2762 Module
->Flags
|= LDRP_UNLOAD_IN_PROGRESS
;
2763 if (Module
== LdrpLastModule
)
2765 LdrpLastModule
= NULL
;
2767 if (Module
->Flags
& LDRP_PROCESS_ATTACH_CALLED
)
2769 TRACE_LDR("Unload %wZ - Calling entry point at %x\n",
2770 &Module
->BaseDllName
, Module
->EntryPoint
);
2771 LdrpCallDllEntry(Module
,
2773 (PVOID
)(Module
->LoadCount
== LDRP_PROCESS_CREATION_TIME
? 1 : 0));
2777 TRACE_LDR("Unload %wZ\n", &Module
->BaseDllName
);
2779 Entry
= ModuleListHead
->Blink
;
2783 Entry
= Entry
->Blink
;
2787 if (CallingCount
== 1)
2789 Entry
= ModuleListHead
->Blink
;
2790 while (Entry
!= ModuleListHead
)
2792 Module
= CONTAINING_RECORD(Entry
, LDR_DATA_TABLE_ENTRY
, InInitializationOrderModuleList
);
2793 Entry
= Entry
->Blink
;
2794 if (Module
->Flags
& LDRP_UNLOAD_IN_PROGRESS
&&
2795 ((UnloadAll
&& Module
->LoadCount
!= LDRP_PROCESS_CREATION_TIME
) || Module
->LoadCount
== 0))
2797 /* remove the module entry from the list */
2798 RemoveEntryList (&Module
->InLoadOrderLinks
);
2799 RemoveEntryList (&Module
->InInitializationOrderModuleList
);
2801 NtUnmapViewOfSection (NtCurrentProcess (), Module
->DllBase
);
2802 NtClose (Module
->SectionPointer
);
2804 TRACE_LDR("%wZ unloaded\n", &Module
->BaseDllName
);
2806 RtlFreeUnicodeString (&Module
->FullDllName
);
2807 RtlFreeUnicodeString (&Module
->BaseDllName
);
2809 RtlFreeHeap (RtlGetProcessHeap (), 0, Module
);
2814 DPRINT("LdrpDetachProcess() done\n");
2817 /**********************************************************************
2822 * Initialize all dll's which are prepered for loading
2833 * The loader lock must be held on entry.
2837 LdrpAttachProcess(VOID
)
2839 PLIST_ENTRY ModuleListHead
;
2841 PLDR_DATA_TABLE_ENTRY Module
;
2843 NTSTATUS Status
= STATUS_SUCCESS
;
2845 DPRINT("LdrpAttachProcess() called for %wZ\n",
2846 &ExeModule
->BaseDllName
);
2848 ModuleListHead
= &NtCurrentPeb()->Ldr
->InInitializationOrderModuleList
;
2849 Entry
= ModuleListHead
->Flink
;
2850 while (Entry
!= ModuleListHead
)
2852 Module
= CONTAINING_RECORD(Entry
, LDR_DATA_TABLE_ENTRY
, InInitializationOrderModuleList
);
2853 if (!(Module
->Flags
& (LDRP_LOAD_IN_PROGRESS
|LDRP_UNLOAD_IN_PROGRESS
|LDRP_ENTRY_PROCESSED
)))
2855 Module
->Flags
|= LDRP_LOAD_IN_PROGRESS
;
2856 TRACE_LDR("%wZ loaded - Calling init routine at %x for process attaching\n",
2857 &Module
->BaseDllName
, Module
->EntryPoint
);
2858 Result
= LdrpCallDllEntry(Module
, DLL_PROCESS_ATTACH
, (PVOID
)(Module
->LoadCount
== LDRP_PROCESS_CREATION_TIME
? 1 : 0));
2861 Status
= STATUS_DLL_INIT_FAILED
;
2864 if (Module
->Flags
& LDRP_IMAGE_DLL
&& Module
->EntryPoint
!= 0)
2866 Module
->Flags
|= LDRP_PROCESS_ATTACH_CALLED
|LDRP_ENTRY_PROCESSED
;
2870 Module
->Flags
|= LDRP_ENTRY_PROCESSED
;
2872 Module
->Flags
&= ~LDRP_LOAD_IN_PROGRESS
;
2874 Entry
= Entry
->Flink
;
2877 DPRINT("LdrpAttachProcess() done\n");
2886 RtlDllShutdownInProgress (VOID
)
2888 return LdrpDllShutdownInProgress
;
2895 LdrShutdownProcess (VOID
)
2897 LdrpDetachProcess(TRUE
);
2898 return STATUS_SUCCESS
;
2906 LdrpAttachThread (VOID
)
2908 PLIST_ENTRY ModuleListHead
;
2910 PLDR_DATA_TABLE_ENTRY Module
;
2913 DPRINT("LdrpAttachThread() called for %wZ\n",
2914 &ExeModule
->BaseDllName
);
2916 RtlEnterCriticalSection (NtCurrentPeb()->LoaderLock
);
2918 Status
= LdrpInitializeTlsForThread();
2920 if (NT_SUCCESS(Status
))
2922 ModuleListHead
= &NtCurrentPeb()->Ldr
->InInitializationOrderModuleList
;
2923 Entry
= ModuleListHead
->Flink
;
2925 while (Entry
!= ModuleListHead
)
2927 Module
= CONTAINING_RECORD(Entry
, LDR_DATA_TABLE_ENTRY
, InInitializationOrderModuleList
);
2928 if (Module
->Flags
& LDRP_PROCESS_ATTACH_CALLED
&&
2929 !(Module
->Flags
& LDRP_DONT_CALL_FOR_THREADS
) &&
2930 !(Module
->Flags
& LDRP_UNLOAD_IN_PROGRESS
))
2932 TRACE_LDR("%wZ - Calling entry point at %x for thread attaching\n",
2933 &Module
->BaseDllName
, Module
->EntryPoint
);
2934 LdrpCallDllEntry(Module
, DLL_THREAD_ATTACH
, NULL
);
2936 Entry
= Entry
->Flink
;
2939 Entry
= NtCurrentPeb()->Ldr
->InLoadOrderModuleList
.Flink
;
2940 Module
= CONTAINING_RECORD(Entry
, LDR_DATA_TABLE_ENTRY
, InLoadOrderLinks
);
2941 LdrpTlsCallback(Module
, DLL_THREAD_ATTACH
);
2944 RtlLeaveCriticalSection (NtCurrentPeb()->LoaderLock
);
2946 DPRINT("LdrpAttachThread() done\n");
2956 LdrShutdownThread (VOID
)
2958 PLIST_ENTRY ModuleListHead
;
2960 PLDR_DATA_TABLE_ENTRY Module
;
2962 DPRINT("LdrShutdownThread() called for %wZ\n",
2963 &ExeModule
->BaseDllName
);
2965 RtlEnterCriticalSection (NtCurrentPeb()->LoaderLock
);
2967 ModuleListHead
= &NtCurrentPeb()->Ldr
->InInitializationOrderModuleList
;
2968 Entry
= ModuleListHead
->Blink
;
2969 while (Entry
!= ModuleListHead
)
2971 Module
= CONTAINING_RECORD(Entry
, LDR_DATA_TABLE_ENTRY
, InInitializationOrderModuleList
);
2973 if (Module
->Flags
& LDRP_PROCESS_ATTACH_CALLED
&&
2974 !(Module
->Flags
& LDRP_DONT_CALL_FOR_THREADS
) &&
2975 !(Module
->Flags
& LDRP_UNLOAD_IN_PROGRESS
))
2977 TRACE_LDR("%wZ - Calling entry point at %x for thread detaching\n",
2978 &Module
->BaseDllName
, Module
->EntryPoint
);
2979 LdrpCallDllEntry(Module
, DLL_THREAD_DETACH
, NULL
);
2981 Entry
= Entry
->Blink
;
2984 RtlLeaveCriticalSection (NtCurrentPeb()->LoaderLock
);
2988 RtlFreeHeap (RtlGetProcessHeap(), 0, NtCurrentTeb()->ThreadLocalStoragePointer
);
2991 DPRINT("LdrShutdownThread() done\n");
2993 return STATUS_SUCCESS
;
2997 /***************************************************************************
2999 * LdrQueryProcessModuleInformation
3014 LdrQueryProcessModuleInformation(IN PRTL_PROCESS_MODULES ModuleInformation OPTIONAL
,
3015 IN ULONG Size OPTIONAL
,
3016 OUT PULONG ReturnedSize
)
3018 PLIST_ENTRY ModuleListHead
;
3020 PLDR_DATA_TABLE_ENTRY Module
;
3021 PRTL_PROCESS_MODULE_INFORMATION ModulePtr
= NULL
;
3022 NTSTATUS Status
= STATUS_SUCCESS
;
3023 ULONG UsedSize
= sizeof(ULONG
);
3024 ANSI_STRING AnsiString
;
3027 DPRINT("LdrQueryProcessModuleInformation() called\n");
3028 // FIXME: This code is ultra-duplicated. see lib\rtl\dbgbuffer.c
3029 RtlEnterCriticalSection (NtCurrentPeb()->LoaderLock
);
3031 if (ModuleInformation
== NULL
|| Size
== 0)
3033 Status
= STATUS_INFO_LENGTH_MISMATCH
;
3037 ModuleInformation
->NumberOfModules
= 0;
3038 ModulePtr
= &ModuleInformation
->Modules
[0];
3039 Status
= STATUS_SUCCESS
;
3042 ModuleListHead
= &NtCurrentPeb()->Ldr
->InLoadOrderModuleList
;
3043 Entry
= ModuleListHead
->Flink
;
3045 while (Entry
!= ModuleListHead
)
3047 Module
= CONTAINING_RECORD(Entry
, LDR_DATA_TABLE_ENTRY
, InLoadOrderLinks
);
3049 DPRINT(" Module %wZ\n",
3050 &Module
->FullDllName
);
3052 if (UsedSize
> Size
)
3054 Status
= STATUS_INFO_LENGTH_MISMATCH
;
3056 else if (ModuleInformation
!= NULL
)
3058 ModulePtr
->Section
= 0;
3059 ModulePtr
->MappedBase
= NULL
; // FIXME: ??
3060 ModulePtr
->ImageBase
= Module
->DllBase
;
3061 ModulePtr
->ImageSize
= Module
->SizeOfImage
;
3062 ModulePtr
->Flags
= Module
->Flags
;
3063 ModulePtr
->LoadOrderIndex
= 0; // FIXME: ??
3064 ModulePtr
->InitOrderIndex
= 0; // FIXME: ??
3065 ModulePtr
->LoadCount
= Module
->LoadCount
;
3067 AnsiString
.Length
= 0;
3068 AnsiString
.MaximumLength
= 256;
3069 AnsiString
.Buffer
= ModulePtr
->FullPathName
;
3070 RtlUnicodeStringToAnsiString(&AnsiString
,
3071 &Module
->FullDllName
,
3074 p
= strrchr(ModulePtr
->FullPathName
, '\\');
3076 ModulePtr
->OffsetToFileName
= p
- ModulePtr
->FullPathName
+ 1;
3078 ModulePtr
->OffsetToFileName
= 0;
3081 ModuleInformation
->NumberOfModules
++;
3083 UsedSize
+= sizeof(RTL_PROCESS_MODULE_INFORMATION
);
3085 Entry
= Entry
->Flink
;
3088 RtlLeaveCriticalSection (NtCurrentPeb()->LoaderLock
);
3090 if (ReturnedSize
!= 0)
3091 *ReturnedSize
= UsedSize
;
3093 DPRINT("LdrQueryProcessModuleInformation() done\n");
3100 LdrpCheckImageChecksum (IN PVOID BaseAddress
,
3103 PIMAGE_NT_HEADERS Header
;
3110 Header
= RtlImageNtHeader (BaseAddress
);
3114 HeaderSum
= Header
->OptionalHeader
.CheckSum
;
3119 Ptr
= (PUSHORT
) BaseAddress
;
3120 for (i
= 0; i
< ImageSize
/ sizeof (USHORT
); i
++)
3123 if (HIWORD(Sum
) != 0)
3125 Sum
= LOWORD(Sum
) + HIWORD(Sum
);
3132 Sum
+= (ULONG
)*((PUCHAR
)Ptr
);
3133 if (HIWORD(Sum
) != 0)
3135 Sum
= LOWORD(Sum
) + HIWORD(Sum
);
3139 CalcSum
= (USHORT
)(LOWORD(Sum
) + HIWORD(Sum
));
3141 /* Subtract image checksum from calculated checksum. */
3142 /* fix low word of checksum */
3143 if (LOWORD(CalcSum
) >= LOWORD(HeaderSum
))
3145 CalcSum
-= LOWORD(HeaderSum
);
3149 CalcSum
= ((LOWORD(CalcSum
) - LOWORD(HeaderSum
)) & 0xFFFF) - 1;
3152 /* fix high word of checksum */
3153 if (LOWORD(CalcSum
) >= HIWORD(HeaderSum
))
3155 CalcSum
-= HIWORD(HeaderSum
);
3159 CalcSum
= ((LOWORD(CalcSum
) - HIWORD(HeaderSum
)) & 0xFFFF) - 1;
3162 /* add file length */
3163 CalcSum
+= ImageSize
;
3165 return (BOOLEAN
)(CalcSum
== HeaderSum
);
3169 * Compute size of an image as it is actually present in virt memory
3170 * (i.e. excluding NEVER_LOAD sections)
3173 LdrpGetResidentSize(PIMAGE_NT_HEADERS NTHeaders
)
3175 PIMAGE_SECTION_HEADER SectionHeader
;
3176 unsigned SectionIndex
;
3179 SectionHeader
= (PIMAGE_SECTION_HEADER
)((char *) &NTHeaders
->OptionalHeader
3180 + NTHeaders
->FileHeader
.SizeOfOptionalHeader
);
3182 for (SectionIndex
= 0;
3183 SectionIndex
< NTHeaders
->FileHeader
.NumberOfSections
;
3186 if (0 == (SectionHeader
->Characteristics
& IMAGE_SCN_LNK_REMOVE
)
3187 && ResidentSize
< SectionHeader
->VirtualAddress
+ SectionHeader
->Misc
.VirtualSize
)
3189 ResidentSize
= SectionHeader
->VirtualAddress
+ SectionHeader
->Misc
.VirtualSize
;
3194 return ResidentSize
;
3198 /***************************************************************************
3200 * LdrVerifyImageMatchesChecksum
3215 LdrVerifyImageMatchesChecksum (IN HANDLE FileHandle
,
3216 IN PLDR_CALLBACK Callback
,
3217 IN PVOID CallbackContext
,
3218 OUT PUSHORT ImageCharacterstics
)
3220 FILE_STANDARD_INFORMATION FileInfo
;
3221 IO_STATUS_BLOCK IoStatusBlock
;
3222 HANDLE SectionHandle
;
3228 DPRINT ("LdrVerifyImageMatchesChecksum() called\n");
3230 Status
= NtCreateSection (&SectionHandle
,
3237 if (!NT_SUCCESS(Status
))
3239 DPRINT1 ("NtCreateSection() failed (Status %lx)\n", Status
);
3245 Status
= NtMapViewOfSection (SectionHandle
,
3246 NtCurrentProcess (),
3255 if (!NT_SUCCESS(Status
))
3257 DPRINT1 ("NtMapViewOfSection() failed (Status %lx)\n", Status
);
3258 NtClose (SectionHandle
);
3262 Status
= NtQueryInformationFile(FileHandle
,
3265 sizeof (FILE_STANDARD_INFORMATION
),
3266 FileStandardInformation
);
3267 if (!NT_SUCCESS(Status
))
3269 DPRINT1 ("NtMapViewOfSection() failed (Status %lx)\n", Status
);
3270 NtUnmapViewOfSection (NtCurrentProcess(),
3272 NtClose (SectionHandle
);
3276 Result
= LdrpCheckImageChecksum(BaseAddress
,
3277 FileInfo
.EndOfFile
.u
.LowPart
);
3278 if (Result
== FALSE
)
3280 Status
= STATUS_IMAGE_CHECKSUM_MISMATCH
;
3283 NtUnmapViewOfSection (NtCurrentProcess(),
3286 NtClose(SectionHandle
);
3291 PIMAGE_BASE_RELOCATION
3293 LdrProcessRelocationBlock(
3294 IN ULONG_PTR Address
,
3296 IN PUSHORT TypeOffset
,
3299 return LdrProcessRelocationBlockLongLong(Address
, Count
, TypeOffset
, Delta
);
3304 LdrLockLoaderLock(IN ULONG Flags
,
3305 OUT PULONG Disposition OPTIONAL
,
3306 OUT PULONG Cookie OPTIONAL
)
3310 BOOLEAN CookieSet
= FALSE
;
3312 if ((Flags
!= 0x01) && (Flags
!= 0x02))
3313 return STATUS_INVALID_PARAMETER_1
;
3315 if (!Cookie
) return STATUS_INVALID_PARAMETER_3
;
3317 /* Set some defaults for failure while verifying params */
3322 if (Disposition
) *Dispositi