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)
12 * - Handle loading flags correctly
13 * - Handle errors correctly (unload dll's)
14 * - Implement a faster way to find modules (hash table)
18 /* INCLUDES *****************************************************************/
24 #define LDRP_PROCESS_CREATION_TIME 0xffff
25 #define RVA(m, b) ((PVOID)((ULONG_PTR)(b) + (ULONG_PTR)(m)))
27 /* GLOBALS *******************************************************************/
30 #define TRACE_LDR(...) if (RtlGetNtGlobalFlags() & FLG_SHOW_LDR_SNAPS) { DbgPrint("(LDR:%s:%d) ",__FILE__,__LINE__); DbgPrint(__VA_ARGS__); }
33 typedef struct _TLS_DATA
35 PVOID StartAddressOfRawData
;
38 PIMAGE_TLS_CALLBACK
*TlsAddressOfCallBacks
;
39 PLDR_DATA_TABLE_ENTRY Module
;
40 } TLS_DATA
, *PTLS_DATA
;
42 static BOOLEAN LdrpDllShutdownInProgress
= FALSE
;
43 static PTLS_DATA LdrpTlsArray
= NULL
;
44 static ULONG LdrpTlsCount
= 0;
45 static ULONG LdrpTlsSize
= 0;
46 static HANDLE LdrpKnownDllsDirHandle
= NULL
;
47 static UNICODE_STRING LdrpKnownDllPath
= {0, 0, NULL
};
48 static PLDR_DATA_TABLE_ENTRY LdrpLastModule
= NULL
;
49 extern PLDR_DATA_TABLE_ENTRY ExeModule
;
51 /* PROTOTYPES ****************************************************************/
53 static NTSTATUS
LdrFindEntryForName(PUNICODE_STRING Name
, PLDR_DATA_TABLE_ENTRY
*Module
, BOOLEAN Ref
);
54 static PVOID
LdrFixupForward(PCHAR ForwardName
);
55 static PVOID
LdrGetExportByName(PVOID BaseAddress
, PUCHAR SymbolName
, USHORT Hint
);
56 static NTSTATUS
LdrpLoadModule(IN PWSTR SearchPath OPTIONAL
,
58 IN PUNICODE_STRING Name
,
59 OUT PLDR_DATA_TABLE_ENTRY
*Module
,
60 OUT PVOID
*BaseAddress OPTIONAL
);
61 static NTSTATUS
LdrpAttachProcess(VOID
);
62 static VOID
LdrpDetachProcess(BOOLEAN UnloadAll
);
64 /* FUNCTIONS *****************************************************************/
67 LdrMappedAsDataFile(PVOID
*BaseAddress
)
69 if (0 != ((DWORD_PTR
) *BaseAddress
& (PAGE_SIZE
- 1)))
71 *BaseAddress
= (PVOID
) ((DWORD_PTR
) *BaseAddress
& ~ ((DWORD_PTR
) PAGE_SIZE
- 1));
78 static __inline LONG
LdrpDecrementLoadCount(PLDR_DATA_TABLE_ENTRY Module
, BOOLEAN Locked
)
83 RtlEnterCriticalSection (NtCurrentPeb()->LoaderLock
);
85 LoadCount
= Module
->LoadCount
;
86 if (Module
->LoadCount
> 0 && Module
->LoadCount
!= LDRP_PROCESS_CREATION_TIME
)
92 RtlLeaveCriticalSection(NtCurrentPeb()->LoaderLock
);
97 static __inline LONG
LdrpIncrementLoadCount(PLDR_DATA_TABLE_ENTRY Module
, BOOLEAN Locked
)
102 RtlEnterCriticalSection (NtCurrentPeb()->LoaderLock
);
104 LoadCount
= Module
->LoadCount
;
105 if (Module
->LoadCount
!= LDRP_PROCESS_CREATION_TIME
)
111 RtlLeaveCriticalSection(NtCurrentPeb()->LoaderLock
);
116 static __inline VOID
LdrpAcquireTlsSlot(PLDR_DATA_TABLE_ENTRY Module
, ULONG Size
, BOOLEAN Locked
)
120 RtlEnterCriticalSection (NtCurrentPeb()->LoaderLock
);
122 Module
->TlsIndex
= (SHORT
)LdrpTlsCount
;
127 RtlLeaveCriticalSection(NtCurrentPeb()->LoaderLock
);
131 static __inline VOID
LdrpTlsCallback(PLDR_DATA_TABLE_ENTRY Module
, ULONG dwReason
)
133 PIMAGE_TLS_CALLBACK
*TlsCallback
;
134 if (Module
->TlsIndex
!= 0xFFFF && Module
->LoadCount
== LDRP_PROCESS_CREATION_TIME
)
136 TlsCallback
= LdrpTlsArray
[Module
->TlsIndex
].TlsAddressOfCallBacks
;
141 TRACE_LDR("%wZ - Calling tls callback at %x\n",
142 &Module
->BaseDllName
, *TlsCallback
);
143 (*TlsCallback
)(Module
->DllBase
, dwReason
, NULL
);
150 static BOOLEAN
LdrpCallDllEntry(PLDR_DATA_TABLE_ENTRY Module
, DWORD dwReason
, PVOID lpReserved
)
152 if (!(Module
->Flags
& LDRP_IMAGE_DLL
) ||
153 Module
->EntryPoint
== 0)
157 LdrpTlsCallback(Module
, dwReason
);
158 return ((PDLLMAIN_FUNC
)Module
->EntryPoint
)(Module
->DllBase
, dwReason
, lpReserved
);
162 LdrpQueryAppPaths(IN PCWSTR ImageName
)
164 PKEY_VALUE_PARTIAL_INFORMATION KeyInfo
;
165 OBJECT_ATTRIBUTES ObjectAttributes
;
166 WCHAR SearchPathBuffer
[5*MAX_PATH
];
167 UNICODE_STRING ValueNameString
;
168 UNICODE_STRING KeyName
;
169 WCHAR NameBuffer
[MAX_PATH
];
177 _snwprintf(NameBuffer
,
178 sizeof(NameBuffer
) / sizeof(WCHAR
),
179 L
"\\Registry\\Machine\\Software\\Microsoft\\Windows\\CurrentVersion\\App Paths\\%s",
182 RtlInitUnicodeString(&KeyName
, NameBuffer
);
184 InitializeObjectAttributes(&ObjectAttributes
,
186 OBJ_CASE_INSENSITIVE
,
190 Status
= NtOpenKey(&KeyHandle
,
193 if (!NT_SUCCESS(Status
))
195 DPRINT ("NtOpenKey() failed (Status %lx)\n", Status
);
199 KeyInfoSize
= sizeof(KEY_VALUE_PARTIAL_INFORMATION
) + 256 * sizeof(WCHAR
);
201 KeyInfo
= RtlAllocateHeap(RtlGetProcessHeap(), 0, KeyInfoSize
);
204 DPRINT("RtlAllocateHeap() failed\n");
209 RtlInitUnicodeString(&ValueNameString
,
212 Status
= NtQueryValueKey(KeyHandle
,
214 KeyValuePartialInformation
,
219 if (!NT_SUCCESS(Status
))
222 RtlFreeHeap(RtlGetProcessHeap(), 0, KeyInfo
);
226 RtlCopyMemory(SearchPathBuffer
,
228 KeyInfo
->DataLength
);
230 /* Free KeyInfo memory, we won't need it anymore */
231 RtlFreeHeap(RtlGetProcessHeap(), 0, KeyInfo
);
233 /* Close the key handle */
236 /* get application running path */
237 wcscat(SearchPathBuffer
, L
";");
238 wcscat(SearchPathBuffer
, NtCurrentPeb()->ProcessParameters
->ImagePathName
.Buffer
); // FIXME: Don't rely on it being NULL-terminated!!!
240 /* Remove trailing backslash */
241 Backslash
= wcsrchr(SearchPathBuffer
, L
'\\');
242 if (Backslash
) Backslash
= L
'\0';
244 wcscat(SearchPathBuffer
, L
";");
246 wcscat(SearchPathBuffer
, SharedUserData
->NtSystemRoot
);
247 wcscat(SearchPathBuffer
, L
"\\system32;");
248 wcscat(SearchPathBuffer
, SharedUserData
->NtSystemRoot
);
249 wcscat(SearchPathBuffer
, L
";.");
251 /* Copy it to the heap allocd memory */
252 Path
= RtlAllocateHeap(RtlGetProcessHeap(),
254 wcslen(SearchPathBuffer
) * sizeof(WCHAR
));
258 DPRINT1("RtlAllocateHeap() failed\n");
262 wcscpy(Path
, SearchPathBuffer
);
268 LdrpInitializeTlsForThread(VOID
)
274 PTEB Teb
= NtCurrentTeb();
276 DPRINT("LdrpInitializeTlsForThread() called for %wZ\n", &ExeModule
->BaseDllName
);
278 Teb
->StaticUnicodeString
.Length
= 0;
279 Teb
->StaticUnicodeString
.MaximumLength
= sizeof(Teb
->StaticUnicodeBuffer
);
280 Teb
->StaticUnicodeString
.Buffer
= Teb
->StaticUnicodeBuffer
;
282 if (LdrpTlsCount
> 0)
284 TlsPointers
= RtlAllocateHeap(RtlGetProcessHeap(),
286 LdrpTlsCount
* sizeof(PVOID
) + LdrpTlsSize
);
287 if (TlsPointers
== NULL
)
289 DPRINT1("failed to allocate thread tls data\n");
290 return STATUS_NO_MEMORY
;
293 TlsData
= (PVOID
)((ULONG_PTR
)TlsPointers
+ LdrpTlsCount
* sizeof(PVOID
));
294 Teb
->ThreadLocalStoragePointer
= TlsPointers
;
296 TlsInfo
= LdrpTlsArray
;
297 for (i
= 0; i
< LdrpTlsCount
; i
++, TlsInfo
++)
299 TRACE_LDR("Initialize tls data for %wZ\n", &TlsInfo
->Module
->BaseDllName
);
300 TlsPointers
[i
] = TlsData
;
301 if (TlsInfo
->TlsDataSize
)
303 memcpy(TlsData
, TlsInfo
->StartAddressOfRawData
, TlsInfo
->TlsDataSize
);
304 TlsData
= (PVOID
)((ULONG_PTR
)TlsData
+ TlsInfo
->TlsDataSize
);
306 if (TlsInfo
->TlsZeroSize
)
308 memset(TlsData
, 0, TlsInfo
->TlsZeroSize
);
309 TlsData
= (PVOID
)((ULONG_PTR
)TlsData
+ TlsInfo
->TlsZeroSize
);
314 DPRINT("LdrpInitializeTlsForThread() done\n");
315 return STATUS_SUCCESS
;
319 LdrpInitializeTlsForProccess(VOID
)
321 PLIST_ENTRY ModuleListHead
;
323 PLDR_DATA_TABLE_ENTRY Module
;
324 PIMAGE_TLS_DIRECTORY TlsDirectory
;
328 DPRINT("LdrpInitializeTlsForProccess() called for %wZ\n", &ExeModule
->BaseDllName
);
330 if (LdrpTlsCount
> 0)
332 LdrpTlsArray
= RtlAllocateHeap(RtlGetProcessHeap(),
334 LdrpTlsCount
* sizeof(TLS_DATA
));
335 if (LdrpTlsArray
== NULL
)
337 DPRINT1("Failed to allocate global tls data\n");
338 return STATUS_NO_MEMORY
;
341 ModuleListHead
= &NtCurrentPeb()->Ldr
->InLoadOrderModuleList
;
342 Entry
= ModuleListHead
->Flink
;
343 while (Entry
!= ModuleListHead
)
345 Module
= CONTAINING_RECORD(Entry
, LDR_DATA_TABLE_ENTRY
, InLoadOrderLinks
);
346 if (Module
->LoadCount
== LDRP_PROCESS_CREATION_TIME
&&
347 Module
->TlsIndex
!= 0xFFFF)
349 TlsDirectory
= (PIMAGE_TLS_DIRECTORY
)
350 RtlImageDirectoryEntryToData(Module
->DllBase
,
352 IMAGE_DIRECTORY_ENTRY_TLS
,
354 ASSERT(Module
->TlsIndex
< LdrpTlsCount
);
355 TlsData
= &LdrpTlsArray
[Module
->TlsIndex
];
356 TlsData
->StartAddressOfRawData
= (PVOID
)TlsDirectory
->StartAddressOfRawData
;
357 TlsData
->TlsDataSize
= TlsDirectory
->EndAddressOfRawData
- TlsDirectory
->StartAddressOfRawData
;
358 TlsData
->TlsZeroSize
= TlsDirectory
->SizeOfZeroFill
;
359 if (TlsDirectory
->AddressOfCallBacks
)
360 TlsData
->TlsAddressOfCallBacks
= (PIMAGE_TLS_CALLBACK
*)TlsDirectory
->AddressOfCallBacks
;
362 TlsData
->TlsAddressOfCallBacks
= NULL
;
363 TlsData
->Module
= Module
;
365 DbgPrint("TLS directory for %wZ\n", &Module
->BaseDllName
);
366 DbgPrint("StartAddressOfRawData: %x\n", TlsDirectory
->StartAddressOfRawData
);
367 DbgPrint("EndAddressOfRawData: %x\n", TlsDirectory
->EndAddressOfRawData
);
368 DbgPrint("SizeOfRawData: %d\n", TlsDirectory
->EndAddressOfRawData
- TlsDirectory
->StartAddressOfRawData
);
369 DbgPrint("AddressOfIndex: %x\n", TlsDirectory
->AddressOfIndex
);
370 DbgPrint("AddressOfCallBacks: %x\n", TlsDirectory
->AddressOfCallBacks
);
371 DbgPrint("SizeOfZeroFill: %d\n", TlsDirectory
->SizeOfZeroFill
);
372 DbgPrint("Characteristics: %x\n", TlsDirectory
->Characteristics
);
376 * Is this region allways writable ?
378 *(PULONG
)TlsDirectory
->AddressOfIndex
= Module
->TlsIndex
;
380 Entry
= Entry
->Flink
;
384 DPRINT("LdrpInitializeTlsForProccess() done\n");
385 return STATUS_SUCCESS
;
391 OBJECT_ATTRIBUTES ObjectAttributes
;
392 UNICODE_STRING LinkTarget
;
398 DPRINT("LdrpInitLoader() called for %wZ\n", &ExeModule
->BaseDllName
);
400 /* Get handle to the 'KnownDlls' directory */
401 RtlInitUnicodeString(&Name
,
403 InitializeObjectAttributes(&ObjectAttributes
,
405 OBJ_CASE_INSENSITIVE
,
408 Status
= NtOpenDirectoryObject(&LdrpKnownDllsDirHandle
,
409 DIRECTORY_QUERY
| DIRECTORY_TRAVERSE
,
411 if (!NT_SUCCESS(Status
))
413 DPRINT("NtOpenDirectoryObject() failed (Status %lx)\n", Status
);
414 LdrpKnownDllsDirHandle
= NULL
;
418 /* Allocate target name string */
419 LinkTarget
.Length
= 0;
420 LinkTarget
.MaximumLength
= MAX_PATH
* sizeof(WCHAR
);
421 LinkTarget
.Buffer
= RtlAllocateHeap(RtlGetProcessHeap(),
423 MAX_PATH
* sizeof(WCHAR
));
424 if (LinkTarget
.Buffer
== NULL
)
426 NtClose(LdrpKnownDllsDirHandle
);
427 LdrpKnownDllsDirHandle
= NULL
;
431 RtlInitUnicodeString(&Name
,
433 InitializeObjectAttributes(&ObjectAttributes
,
435 OBJ_CASE_INSENSITIVE
,
436 LdrpKnownDllsDirHandle
,
438 Status
= NtOpenSymbolicLinkObject(&LinkHandle
,
439 SYMBOLIC_LINK_ALL_ACCESS
,
441 if (!NT_SUCCESS(Status
))
443 RtlFreeUnicodeString(&LinkTarget
);
444 NtClose(LdrpKnownDllsDirHandle
);
445 LdrpKnownDllsDirHandle
= NULL
;
449 Status
= NtQuerySymbolicLinkObject(LinkHandle
,
453 if (!NT_SUCCESS(Status
))
455 RtlFreeUnicodeString(&LinkTarget
);
456 NtClose(LdrpKnownDllsDirHandle
);
457 LdrpKnownDllsDirHandle
= NULL
;
460 RtlCreateUnicodeString(&LdrpKnownDllPath
,
463 RtlFreeUnicodeString(&LinkTarget
);
465 DPRINT("LdrpInitLoader() done\n");
469 /***************************************************************************
474 * Adjusts the name of a dll to a fully qualified name.
477 * FullDllName: Pointer to caller supplied storage for the fully
478 * qualified dll name.
479 * DllName: Pointer to the dll name.
480 * BaseName: TRUE: Only the file name is passed to FullDllName
481 * FALSE: The full path is preserved in FullDllName
489 * A given path is not affected by the adjustment, but the file
491 * ntdll --> ntdll.dll
493 * ntdll.xyz --> ntdll.xyz
496 LdrAdjustDllName (PUNICODE_STRING FullDllName
,
497 PUNICODE_STRING DllName
,
500 WCHAR Buffer
[MAX_PATH
];
505 Length
= DllName
->Length
/ sizeof(WCHAR
);
509 /* get the base dll name */
510 Pointer
= DllName
->Buffer
+ Length
;
517 while (Pointer
>= DllName
->Buffer
&& *Pointer
!= L
'\\' && *Pointer
!= L
'/');
520 Length
= Extension
- Pointer
;
521 memmove (Buffer
, Pointer
, Length
* sizeof(WCHAR
));
522 Buffer
[Length
] = L
'\0';
526 /* get the full dll name */
527 memmove (Buffer
, DllName
->Buffer
, DllName
->Length
);
528 Buffer
[DllName
->Length
/ sizeof(WCHAR
)] = L
'\0';
531 /* Build the DLL's absolute name */
532 Extension
= wcsrchr (Buffer
, L
'.');
533 if ((Extension
!= NULL
) && (*Extension
== L
'.'))
535 /* with extension - remove dot if it's the last character */
536 if (Buffer
[Length
- 1] == L
'.')
542 /* name without extension - assume that it is .dll */
543 memmove (Buffer
+ Length
, L
".dll", 10);
546 RtlCreateUnicodeString(FullDllName
, Buffer
);
549 PLDR_DATA_TABLE_ENTRY
550 LdrAddModuleEntry(PVOID ImageBase
,
551 PIMAGE_NT_HEADERS NTHeaders
,
554 PLDR_DATA_TABLE_ENTRY Module
;
556 Module
= RtlAllocateHeap(RtlGetProcessHeap(), 0, sizeof (LDR_DATA_TABLE_ENTRY
));
558 memset(Module
, 0, sizeof(LDR_DATA_TABLE_ENTRY
));
559 Module
->DllBase
= (PVOID
)ImageBase
;
560 Module
->EntryPoint
= (PVOID
)NTHeaders
->OptionalHeader
.AddressOfEntryPoint
;
561 if (Module
->EntryPoint
!= 0)
562 Module
->EntryPoint
= (PVOID
)((ULONG_PTR
)Module
->EntryPoint
+ (ULONG_PTR
)Module
->DllBase
);
563 Module
->SizeOfImage
= LdrpGetResidentSize(NTHeaders
);
564 if (NtCurrentPeb()->Ldr
->Initialized
== TRUE
)
566 /* loading while app is running */
567 Module
->LoadCount
= 1;
570 * loading while app is initializing
571 * dll must not be unloaded
573 Module
->LoadCount
= LDRP_PROCESS_CREATION_TIME
;
577 Module
->TlsIndex
= -1;
578 Module
->CheckSum
= NTHeaders
->OptionalHeader
.CheckSum
;
579 Module
->TimeDateStamp
= NTHeaders
->FileHeader
.TimeDateStamp
;
581 RtlCreateUnicodeString (&Module
->FullDllName
,
583 RtlCreateUnicodeString (&Module
->BaseDllName
,
584 wcsrchr(FullDosName
, L
'\\') + 1);
585 DPRINT ("BaseDllName %wZ\n", &Module
->BaseDllName
);
587 RtlEnterCriticalSection (NtCurrentPeb()->LoaderLock
);
588 InsertTailList(&NtCurrentPeb()->Ldr
->InLoadOrderModuleList
,
589 &Module
->InLoadOrderLinks
);
590 RtlLeaveCriticalSection(NtCurrentPeb()->LoaderLock
);
597 LdrpMapKnownDll(IN PUNICODE_STRING DllName
,
598 OUT PUNICODE_STRING FullDosName
,
599 OUT PHANDLE SectionHandle
)
601 OBJECT_ATTRIBUTES ObjectAttributes
;
604 DPRINT("LdrpMapKnownDll() called\n");
606 if (LdrpKnownDllsDirHandle
== NULL
)
608 DPRINT("Invalid 'KnownDlls' directory\n");
609 return STATUS_UNSUCCESSFUL
;
612 DPRINT("LdrpKnownDllPath '%wZ'\n", &LdrpKnownDllPath
);
614 InitializeObjectAttributes(&ObjectAttributes
,
616 OBJ_CASE_INSENSITIVE
,
617 LdrpKnownDllsDirHandle
,
619 Status
= NtOpenSection(SectionHandle
,
620 SECTION_MAP_READ
| SECTION_MAP_WRITE
| SECTION_MAP_EXECUTE
,
622 if (!NT_SUCCESS(Status
))
624 DPRINT("NtOpenSection() failed for '%wZ' (Status 0x%08lx)\n", DllName
, Status
);
628 FullDosName
->Length
= LdrpKnownDllPath
.Length
+ DllName
->Length
+ sizeof(WCHAR
);
629 FullDosName
->MaximumLength
= FullDosName
->Length
+ sizeof(WCHAR
);
630 FullDosName
->Buffer
= RtlAllocateHeap(RtlGetProcessHeap(),
632 FullDosName
->MaximumLength
);
633 if (FullDosName
->Buffer
== NULL
)
635 FullDosName
->Length
= 0;
636 FullDosName
->MaximumLength
= 0;
637 return STATUS_SUCCESS
;
640 wcscpy(FullDosName
->Buffer
, LdrpKnownDllPath
.Buffer
);
641 wcscat(FullDosName
->Buffer
, L
"\\");
642 wcscat(FullDosName
->Buffer
, DllName
->Buffer
);
644 DPRINT("FullDosName '%wZ'\n", FullDosName
);
646 DPRINT("LdrpMapKnownDll() done\n");
648 return STATUS_SUCCESS
;
653 LdrpMapDllImageFile(IN PWSTR SearchPath OPTIONAL
,
654 IN PUNICODE_STRING DllName
,
655 OUT PUNICODE_STRING FullDosName
,
656 IN BOOLEAN MapAsDataFile
,
657 OUT PHANDLE SectionHandle
)
659 WCHAR SearchPathBuffer
[MAX_PATH
];
660 WCHAR DosName
[MAX_PATH
];
661 UNICODE_STRING FullNtFileName
;
662 OBJECT_ATTRIBUTES FileObjectAttributes
;
664 char BlockBuffer
[1024];
665 PIMAGE_DOS_HEADER DosHeader
;
666 PIMAGE_NT_HEADERS NTHeaders
;
667 IO_STATUS_BLOCK IoStatusBlock
;
671 DPRINT("LdrpMapDllImageFile() called\n");
673 if (SearchPath
== NULL
)
675 /* get application running path */
677 wcscpy (SearchPathBuffer
, NtCurrentPeb()->ProcessParameters
->ImagePathName
.Buffer
);
679 len
= wcslen (SearchPathBuffer
);
681 while (len
&& SearchPathBuffer
[len
- 1] != L
'\\')
684 if (len
) SearchPathBuffer
[len
-1] = L
'\0';
686 wcscat (SearchPathBuffer
, L
";");
688 wcscat (SearchPathBuffer
, SharedUserData
->NtSystemRoot
);
689 wcscat (SearchPathBuffer
, L
"\\system32;");
690 wcscat (SearchPathBuffer
, SharedUserData
->NtSystemRoot
);
691 wcscat (SearchPathBuffer
, L
";.");
693 SearchPath
= SearchPathBuffer
;
696 if (RtlDosSearchPath_U (SearchPath
,
702 return STATUS_DLL_NOT_FOUND
;
704 if (!RtlDosPathNameToNtPathName_U (DosName
,
708 return STATUS_DLL_NOT_FOUND
;
710 DPRINT("FullNtFileName %wZ\n", &FullNtFileName
);
712 InitializeObjectAttributes(&FileObjectAttributes
,
718 DPRINT("Opening dll \"%wZ\"\n", &FullNtFileName
);
720 Status
= NtOpenFile(&FileHandle
,
721 GENERIC_READ
|SYNCHRONIZE
,
722 &FileObjectAttributes
,
725 FILE_SYNCHRONOUS_IO_NONALERT
);
726 if (!NT_SUCCESS(Status
))
728 DPRINT1("Dll open of %wZ failed: Status = 0x%08lx\n",
729 &FullNtFileName
, Status
);
730 RtlFreeHeap (RtlGetProcessHeap (),
732 FullNtFileName
.Buffer
);
735 RtlFreeHeap (RtlGetProcessHeap (),
737 FullNtFileName
.Buffer
);
742 Status
= NtReadFile(FileHandle
,
751 if (!NT_SUCCESS(Status
))
753 DPRINT("Dll header read failed: Status = 0x%08lx\n", Status
);
759 * Overlay DOS and NT headers structures to the
760 * buffer with DLL's header raw data.
762 DosHeader
= (PIMAGE_DOS_HEADER
) BlockBuffer
;
763 NTHeaders
= (PIMAGE_NT_HEADERS
) (BlockBuffer
+ DosHeader
->e_lfanew
);
765 * Check it is a PE image file.
767 if ((DosHeader
->e_magic
!= IMAGE_DOS_SIGNATURE
)
768 || (DosHeader
->e_lfanew
== 0L)
769 || (*(PULONG
)(NTHeaders
) != IMAGE_NT_SIGNATURE
))
771 DPRINT("NTDLL format invalid\n");
774 return STATUS_UNSUCCESSFUL
;
779 * Create a section for dll.
781 Status
= NtCreateSection(SectionHandle
,
786 MapAsDataFile
? SEC_COMMIT
: SEC_IMAGE
,
790 if (!NT_SUCCESS(Status
))
792 DPRINT("NTDLL create section failed: Status = 0x%08lx\n", Status
);
796 RtlCreateUnicodeString(FullDosName
,
804 /***************************************************************************
821 LdrLoadDll (IN PWSTR SearchPath OPTIONAL
,
822 IN PULONG LoadFlags OPTIONAL
,
823 IN PUNICODE_STRING Name
,
824 OUT PVOID
*BaseAddress
/* also known as HMODULE*, and PHANDLE 'DllHandle' */)
827 PLDR_DATA_TABLE_ENTRY Module
;
829 PPEB Peb
= NtCurrentPeb();
831 TRACE_LDR("LdrLoadDll, loading %wZ%s%S\n",
833 SearchPath
? L
" from " : L
"",
834 SearchPath
? SearchPath
: L
"");
836 Status
= LdrpLoadModule(SearchPath
, LoadFlags
? *LoadFlags
: 0, Name
, &Module
, BaseAddress
);
838 if (NT_SUCCESS(Status
) &&
839 (!LoadFlags
|| 0 == (*LoadFlags
& LOAD_LIBRARY_AS_DATAFILE
)))
841 if (!(Module
->Flags
& LDRP_PROCESS_ATTACH_CALLED
))
843 RtlEnterCriticalSection(Peb
->LoaderLock
);
844 Status
= LdrpAttachProcess();
845 RtlLeaveCriticalSection(Peb
->LoaderLock
);
849 if ((!Module
) && (NT_SUCCESS(Status
)))
852 *BaseAddress
= NT_SUCCESS(Status
) ? Module
->DllBase
: NULL
;
858 /***************************************************************************
860 * LdrFindEntryForAddress
875 LdrFindEntryForAddress(PVOID Address
,
876 PLDR_DATA_TABLE_ENTRY
*Module
)
878 PLIST_ENTRY ModuleListHead
;
880 PLDR_DATA_TABLE_ENTRY ModulePtr
;
882 DPRINT("LdrFindEntryForAddress(Address %p)\n", Address
);
884 if (NtCurrentPeb()->Ldr
== NULL
)
885 return(STATUS_NO_MORE_ENTRIES
);
887 RtlEnterCriticalSection(NtCurrentPeb()->LoaderLock
);
888 ModuleListHead
= &NtCurrentPeb()->Ldr
->InLoadOrderModuleList
;
889 Entry
= ModuleListHead
->Flink
;
890 if (Entry
== ModuleListHead
)
892 RtlLeaveCriticalSection(NtCurrentPeb()->LoaderLock
);
893 return(STATUS_NO_MORE_ENTRIES
);
896 while (Entry
!= ModuleListHead
)
898 ModulePtr
= CONTAINING_RECORD(Entry
, LDR_DATA_TABLE_ENTRY
, InLoadOrderLinks
);
900 DPRINT("Scanning %wZ at %p\n", &ModulePtr
->BaseDllName
, ModulePtr
->DllBase
);
902 if ((Address
>= ModulePtr
->DllBase
) &&
903 ((ULONG_PTR
)Address
<= ((ULONG_PTR
)ModulePtr
->DllBase
+ ModulePtr
->SizeOfImage
)))
906 RtlLeaveCriticalSection(NtCurrentPeb()->LoaderLock
);
907 return(STATUS_SUCCESS
);
910 Entry
= Entry
->Flink
;
913 DPRINT("Failed to find module entry.\n");
915 RtlLeaveCriticalSection(NtCurrentPeb()->LoaderLock
);
916 return(STATUS_NO_MORE_ENTRIES
);
920 /***************************************************************************
922 * LdrFindEntryForName
936 LdrFindEntryForName(PUNICODE_STRING Name
,
937 PLDR_DATA_TABLE_ENTRY
*Module
,
940 PLIST_ENTRY ModuleListHead
;
942 PLDR_DATA_TABLE_ENTRY ModulePtr
;
943 BOOLEAN ContainsPath
;
944 UNICODE_STRING AdjustedName
;
946 DPRINT("LdrFindEntryForName(Name %wZ)\n", Name
);
948 if (NtCurrentPeb()->Ldr
== NULL
)
949 return(STATUS_NO_MORE_ENTRIES
);
951 RtlEnterCriticalSection(NtCurrentPeb()->LoaderLock
);
952 ModuleListHead
= &NtCurrentPeb()->Ldr
->InLoadOrderModuleList
;
953 Entry
= ModuleListHead
->Flink
;
954 if (Entry
== ModuleListHead
)
956 RtlLeaveCriticalSection(NtCurrentPeb()->LoaderLock
);
957 return(STATUS_NO_MORE_ENTRIES
);
960 // NULL is the current process
964 RtlLeaveCriticalSection(NtCurrentPeb()->LoaderLock
);
965 return(STATUS_SUCCESS
);
968 ContainsPath
= (Name
->Length
>= 2 * sizeof(WCHAR
) && L
':' == Name
->Buffer
[1]);
969 LdrAdjustDllName (&AdjustedName
, Name
, !ContainsPath
);
973 if ((! ContainsPath
&&
974 0 == RtlCompareUnicodeString(&LdrpLastModule
->BaseDllName
, &AdjustedName
, TRUE
)) ||
976 0 == RtlCompareUnicodeString(&LdrpLastModule
->FullDllName
, &AdjustedName
, TRUE
)))
978 *Module
= LdrpLastModule
;
979 if (Ref
&& (*Module
)->LoadCount
!= LDRP_PROCESS_CREATION_TIME
)
981 (*Module
)->LoadCount
++;
983 RtlLeaveCriticalSection(NtCurrentPeb()->LoaderLock
);
984 RtlFreeUnicodeString(&AdjustedName
);
985 return(STATUS_SUCCESS
);
988 while (Entry
!= ModuleListHead
)
990 ModulePtr
= CONTAINING_RECORD(Entry
, LDR_DATA_TABLE_ENTRY
, InLoadOrderLinks
);
992 DPRINT("Scanning %wZ %wZ\n", &ModulePtr
->BaseDllName
, &AdjustedName
);
994 if ((! ContainsPath
&&
995 0 == RtlCompareUnicodeString(&ModulePtr
->BaseDllName
, &AdjustedName
, TRUE
)) ||
997 0 == RtlCompareUnicodeString(&ModulePtr
->FullDllName
, &AdjustedName
, TRUE
)))
999 *Module
= LdrpLastModule
= ModulePtr
;
1000 if (Ref
&& ModulePtr
->LoadCount
!= LDRP_PROCESS_CREATION_TIME
)
1002 ModulePtr
->LoadCount
++;
1004 RtlLeaveCriticalSection(NtCurrentPeb()->LoaderLock
);
1005 RtlFreeUnicodeString(&AdjustedName
);
1006 return(STATUS_SUCCESS
);
1009 Entry
= Entry
->Flink
;
1012 DPRINT("Failed to find dll %wZ\n", Name
);
1013 RtlLeaveCriticalSection(NtCurrentPeb()->LoaderLock
);
1014 RtlFreeUnicodeString(&AdjustedName
);
1015 return(STATUS_NO_MORE_ENTRIES
);
1018 /**********************************************************************
1034 LdrFixupForward(PCHAR ForwardName
)
1036 CHAR NameBuffer
[128];
1037 UNICODE_STRING DllName
;
1040 PLDR_DATA_TABLE_ENTRY Module
;
1043 strcpy(NameBuffer
, ForwardName
);
1044 p
= strchr(NameBuffer
, '.');
1049 DPRINT("Dll: %s Function: %s\n", NameBuffer
, p
+1);
1050 RtlCreateUnicodeStringFromAsciiz (&DllName
,
1053 Status
= LdrFindEntryForName (&DllName
, &Module
, FALSE
);
1055 * The caller (or the image) is responsible for loading of the dll, where the function is forwarded.
1057 if (!NT_SUCCESS(Status
))
1059 Status
= LdrLoadDll(NULL
,
1063 if (NT_SUCCESS(Status
))
1065 Status
= LdrFindEntryForName (&DllName
, &Module
, FALSE
);
1068 RtlFreeUnicodeString (&DllName
);
1069 if (!NT_SUCCESS(Status
))
1071 DPRINT1("LdrFixupForward: failed to load %s\n", NameBuffer
);
1075 DPRINT("BaseAddress: %p\n", Module
->DllBase
);
1077 return LdrGetExportByName(Module
->DllBase
, (PUCHAR
)(p
+1), -1);
1084 /**********************************************************************
1086 * LdrGetExportByOrdinal
1100 LdrGetExportByOrdinal (
1105 PIMAGE_EXPORT_DIRECTORY ExportDir
;
1106 ULONG ExportDirSize
;
1107 PDWORD
* ExFunctions
;
1110 ExportDir
= (PIMAGE_EXPORT_DIRECTORY
)
1111 RtlImageDirectoryEntryToData (BaseAddress
,
1113 IMAGE_DIRECTORY_ENTRY_EXPORT
,
1117 ExFunctions
= (PDWORD
*)
1120 ExportDir
->AddressOfFunctions
1123 "LdrGetExportByOrdinal(Ordinal %lu) = %p\n",
1125 RVA(BaseAddress
, ExFunctions
[Ordinal
- ExportDir
->Base
] )
1128 Function
= (0 != ExFunctions
[Ordinal
- ExportDir
->Base
]
1129 ? RVA(BaseAddress
, ExFunctions
[Ordinal
- ExportDir
->Base
] )
1132 if (((ULONG
)Function
>= (ULONG
)ExportDir
) &&
1133 ((ULONG
)Function
< (ULONG
)ExportDir
+ (ULONG
)ExportDirSize
))
1135 DPRINT("Forward: %s\n", (PCHAR
)Function
);
1136 Function
= LdrFixupForward((PCHAR
)Function
);
1143 /**********************************************************************
1145 * LdrGetExportByName
1156 * AddressOfNames and AddressOfNameOrdinals are paralell tables,
1157 * both with NumberOfNames entries.
1161 LdrGetExportByName(PVOID BaseAddress
,
1165 PIMAGE_EXPORT_DIRECTORY ExportDir
;
1166 PDWORD
* ExFunctions
;
1168 USHORT
* ExOrdinals
;
1173 ULONG ExportDirSize
;
1175 DPRINT("LdrGetExportByName %p %s %hu\n", BaseAddress
, SymbolName
, Hint
);
1177 ExportDir
= (PIMAGE_EXPORT_DIRECTORY
)
1178 RtlImageDirectoryEntryToData(BaseAddress
,
1180 IMAGE_DIRECTORY_ENTRY_EXPORT
,
1182 if (ExportDir
== NULL
)
1184 DPRINT1("LdrGetExportByName(): no export directory, "
1185 "can't lookup %s/%hu!\n", SymbolName
, Hint
);
1190 //The symbol names may be missing entirely
1191 if (ExportDir
->AddressOfNames
== 0)
1193 DPRINT("LdrGetExportByName(): symbol names missing entirely\n");
1198 * Get header pointers
1200 ExNames
= (PDWORD
*)RVA(BaseAddress
,
1201 ExportDir
->AddressOfNames
);
1202 ExOrdinals
= (USHORT
*)RVA(BaseAddress
,
1203 ExportDir
->AddressOfNameOrdinals
);
1204 ExFunctions
= (PDWORD
*)RVA(BaseAddress
,
1205 ExportDir
->AddressOfFunctions
);
1208 * Check the hint first
1210 if (Hint
< ExportDir
->NumberOfNames
)
1212 ExName
= RVA(BaseAddress
, ExNames
[Hint
]);
1213 if (strcmp(ExName
, (PCHAR
)SymbolName
) == 0)
1215 Ordinal
= ExOrdinals
[Hint
];
1216 Function
= RVA(BaseAddress
, ExFunctions
[Ordinal
]);
1217 if (((ULONG
)Function
>= (ULONG
)ExportDir
) &&
1218 ((ULONG
)Function
< (ULONG
)ExportDir
+ (ULONG
)ExportDirSize
))
1220 DPRINT("Forward: %s\n", (PCHAR
)Function
);
1221 Function
= LdrFixupForward((PCHAR
)Function
);
1222 if (Function
== NULL
)
1224 DPRINT1("LdrGetExportByName(): failed to find %s\n",SymbolName
);
1228 if (Function
!= NULL
)
1237 maxn
= ExportDir
->NumberOfNames
- 1;
1238 while (minn
<= maxn
)
1243 mid
= (minn
+ maxn
) / 2;
1245 ExName
= RVA(BaseAddress
, ExNames
[mid
]);
1246 res
= strcmp(ExName
, (PCHAR
)SymbolName
);
1249 Ordinal
= ExOrdinals
[mid
];
1250 Function
= RVA(BaseAddress
, ExFunctions
[Ordinal
]);
1251 if (((ULONG
)Function
>= (ULONG
)ExportDir
) &&
1252 ((ULONG
)Function
< (ULONG
)ExportDir
+ (ULONG
)ExportDirSize
))
1254 DPRINT("Forward: %s\n", (PCHAR
)Function
);
1255 Function
= LdrFixupForward((PCHAR
)Function
);
1256 if (Function
== NULL
)
1258 DPRINT1("LdrGetExportByName(): failed to find %s\n",SymbolName
);
1262 if (Function
!= NULL
)
1265 else if (minn
== maxn
)
1267 DPRINT("LdrGetExportByName(): binary search failed\n");
1280 DPRINT("LdrGetExportByName(): failed to find %s\n",SymbolName
);
1285 /**********************************************************************
1287 * LdrPerformRelocations
1290 * Relocate a DLL's memory image.
1302 LdrPerformRelocations(PIMAGE_NT_HEADERS NTHeaders
,
1305 PIMAGE_DATA_DIRECTORY RelocationDDir
;
1306 PIMAGE_BASE_RELOCATION RelocationDir
, RelocationEnd
;
1307 ULONG Count
, ProtectSize
, OldProtect
, OldProtect2
;
1308 PVOID Page
, ProtectPage
, ProtectPage2
;
1313 if (NTHeaders
->FileHeader
.Characteristics
& IMAGE_FILE_RELOCS_STRIPPED
)
1315 return STATUS_SUCCESS
;
1319 &NTHeaders
->OptionalHeader
.DataDirectory
[IMAGE_DIRECTORY_ENTRY_BASERELOC
];
1321 if (RelocationDDir
->VirtualAddress
== 0 || RelocationDDir
->Size
== 0)
1323 return STATUS_SUCCESS
;
1326 ProtectSize
= PAGE_SIZE
;
1327 Delta
= (ULONG_PTR
)ImageBase
- NTHeaders
->OptionalHeader
.ImageBase
;
1328 RelocationDir
= (PIMAGE_BASE_RELOCATION
)((ULONG_PTR
)ImageBase
+
1329 RelocationDDir
->VirtualAddress
);
1330 RelocationEnd
= (PIMAGE_BASE_RELOCATION
)((ULONG_PTR
)ImageBase
+
1331 RelocationDDir
->VirtualAddress
+ RelocationDDir
->Size
);
1333 while (RelocationDir
< RelocationEnd
&&
1334 RelocationDir
->SizeOfBlock
> 0)
1336 Count
= (RelocationDir
->SizeOfBlock
- sizeof(IMAGE_BASE_RELOCATION
)) /
1338 Page
= (PVOID
)((ULONG_PTR
)ImageBase
+ (ULONG_PTR
)RelocationDir
->VirtualAddress
);
1339 TypeOffset
= (PUSHORT
)(RelocationDir
+ 1);
1341 /* Unprotect the page(s) we're about to relocate. */
1343 Status
= NtProtectVirtualMemory(NtCurrentProcess(),
1348 if (!NT_SUCCESS(Status
))
1350 DPRINT1("Failed to unprotect relocation target.\n");
1354 if (RelocationDir
->VirtualAddress
+ PAGE_SIZE
<
1355 NTHeaders
->OptionalHeader
.SizeOfImage
)
1357 ProtectPage2
= (PVOID
)((ULONG_PTR
)ProtectPage
+ PAGE_SIZE
);
1358 Status
= NtProtectVirtualMemory(NtCurrentProcess(),
1363 if (!NT_SUCCESS(Status
))
1365 DPRINT1("Failed to unprotect relocation target (2).\n");
1366 NtProtectVirtualMemory(NtCurrentProcess(),
1376 ProtectPage2
= NULL
;
1379 RelocationDir
= LdrProcessRelocationBlock((ULONG_PTR
)Page
,
1383 if (RelocationDir
== NULL
)
1384 return STATUS_UNSUCCESSFUL
;
1386 /* Restore old page protection. */
1387 NtProtectVirtualMemory(NtCurrentProcess(),
1393 if (ProtectPage2
!= NULL
)
1395 NtProtectVirtualMemory(NtCurrentProcess(),
1403 return STATUS_SUCCESS
;
1407 LdrpGetOrLoadModule(PWCHAR SearchPath
,
1409 PLDR_DATA_TABLE_ENTRY
* Module
,
1412 ANSI_STRING AnsiDllName
;
1413 UNICODE_STRING DllName
;
1416 DPRINT("LdrpGetOrLoadModule() called for %s\n", Name
);
1418 RtlInitAnsiString(&AnsiDllName
, Name
);
1419 Status
= RtlAnsiStringToUnicodeString(&DllName
, &AnsiDllName
, TRUE
);
1420 if (!NT_SUCCESS(Status
))
1425 Status
= LdrFindEntryForName (&DllName
, Module
, Load
);
1426 if (Load
&& !NT_SUCCESS(Status
))
1428 Status
= LdrpLoadModule(SearchPath
,
1433 if (NT_SUCCESS(Status
))
1435 Status
= LdrFindEntryForName (&DllName
, Module
, FALSE
);
1437 if (!NT_SUCCESS(Status
))
1439 ULONG ErrorResponse
;
1440 ULONG_PTR ErrorParameter
= (ULONG_PTR
)&DllName
;
1442 DPRINT1("failed to load %wZ\n", &DllName
);
1443 NtRaiseHardError(STATUS_DLL_NOT_FOUND
,
1451 RtlFreeUnicodeString (&DllName
);
1456 RtlpRaiseImportNotFound(CHAR
*FuncName
, ULONG Ordinal
, PUNICODE_STRING DllName
)
1458 ULONG ErrorResponse
;
1459 ULONG_PTR ErrorParameters
[2];
1460 ANSI_STRING ProcNameAnsi
;
1461 UNICODE_STRING ProcName
;
1466 _snprintf(Buffer
, 8, "# %ld", Ordinal
);
1470 RtlInitAnsiString(&ProcNameAnsi
, FuncName
);
1471 RtlAnsiStringToUnicodeString(&ProcName
, &ProcNameAnsi
, TRUE
);
1472 ErrorParameters
[0] = (ULONG_PTR
)&ProcName
;
1473 ErrorParameters
[1] = (ULONG_PTR
)DllName
;
1474 NtRaiseHardError(STATUS_ENTRYPOINT_NOT_FOUND
,
1480 RtlFreeUnicodeString(&ProcName
);
1484 LdrpProcessImportDirectoryEntry(PLDR_DATA_TABLE_ENTRY Module
,
1485 PLDR_DATA_TABLE_ENTRY ImportedModule
,
1486 PIMAGE_IMPORT_DESCRIPTOR ImportModuleDirectory
)
1489 PVOID
* ImportAddressList
;
1490 PULONG FunctionNameList
;
1496 if (ImportModuleDirectory
== NULL
|| ImportModuleDirectory
->Name
== 0)
1498 return STATUS_UNSUCCESSFUL
;
1501 /* Get the import address list. */
1502 ImportAddressList
= (PVOID
*)((ULONG_PTR
)Module
->DllBase
+ (ULONG_PTR
)ImportModuleDirectory
->FirstThunk
);
1504 /* Get the list of functions to import. */
1505 if (ImportModuleDirectory
->OriginalFirstThunk
!= 0)
1507 FunctionNameList
= (PULONG
) ((ULONG_PTR
)Module
->DllBase
+ (ULONG_PTR
)ImportModuleDirectory
->OriginalFirstThunk
);
1511 FunctionNameList
= (PULONG
)((ULONG_PTR
)Module
->DllBase
+ (ULONG_PTR
)ImportModuleDirectory
->FirstThunk
);
1514 /* Get the size of IAT. */
1516 while (FunctionNameList
[IATSize
] != 0L)
1521 /* Unprotect the region we are about to write into. */
1522 IATBase
= (PVOID
)ImportAddressList
;
1523 IATSize
*= sizeof(PVOID
*);
1524 Status
= NtProtectVirtualMemory(NtCurrentProcess(),
1529 if (!NT_SUCCESS(Status
))
1531 DPRINT1("Failed to unprotect IAT.\n");
1535 /* Walk through function list and fixup addresses. */
1536 while (*FunctionNameList
!= 0L)
1538 if ((*FunctionNameList
) & 0x80000000)
1540 Ordinal
= (*FunctionNameList
) & 0x7fffffff;
1541 *ImportAddressList
= LdrGetExportByOrdinal(ImportedModule
->DllBase
, Ordinal
);
1542 if ((*ImportAddressList
) == NULL
)
1544 DPRINT1("Failed to import #%ld from %wZ\n", Ordinal
, &ImportedModule
->FullDllName
);
1545 RtlpRaiseImportNotFound(NULL
, Ordinal
, &ImportedModule
->FullDllName
);
1546 return STATUS_ENTRYPOINT_NOT_FOUND
;
1551 IMAGE_IMPORT_BY_NAME
*pe_name
;
1552 pe_name
= RVA(Module
->DllBase
, *FunctionNameList
);
1553 *ImportAddressList
= LdrGetExportByName(ImportedModule
->DllBase
, pe_name
->Name
, pe_name
->Hint
);
1554 if ((*ImportAddressList
) == NULL
)
1556 DPRINT1("Failed to import %s from %wZ\n", pe_name
->Name
, &ImportedModule
->FullDllName
);
1557 RtlpRaiseImportNotFound((CHAR
*)pe_name
->Name
, 0, &ImportedModule
->FullDllName
);
1558 return STATUS_ENTRYPOINT_NOT_FOUND
;
1561 ImportAddressList
++;
1565 /* Protect the region we are about to write into. */
1566 Status
= NtProtectVirtualMemory(NtCurrentProcess(),
1571 if (!NT_SUCCESS(Status
))
1573 DPRINT1("Failed to protect IAT.\n");
1577 return STATUS_SUCCESS
;
1581 LdrpProcessImportDirectory(
1582 PLDR_DATA_TABLE_ENTRY Module
,
1583 PLDR_DATA_TABLE_ENTRY ImportedModule
,
1587 PIMAGE_IMPORT_DESCRIPTOR ImportModuleDirectory
;
1591 DPRINT("LdrpProcessImportDirectory(%p '%wZ', '%s')\n",
1592 Module
, &Module
->BaseDllName
, ImportedName
);
1595 ImportModuleDirectory
= (PIMAGE_IMPORT_DESCRIPTOR
)
1596 RtlImageDirectoryEntryToData(Module
->DllBase
,
1598 IMAGE_DIRECTORY_ENTRY_IMPORT
,
1600 if (ImportModuleDirectory
== NULL
)
1602 return STATUS_UNSUCCESSFUL
;
1605 while (ImportModuleDirectory
->Name
)
1607 Name
= (PCHAR
)Module
->DllBase
+ ImportModuleDirectory
->Name
;
1608 if (0 == _stricmp(Name
, ImportedName
))
1610 Status
= LdrpProcessImportDirectoryEntry(Module
,
1612 ImportModuleDirectory
);
1613 if (!NT_SUCCESS(Status
))
1618 ImportModuleDirectory
++;
1622 return STATUS_SUCCESS
;
1627 LdrpAdjustImportDirectory(PLDR_DATA_TABLE_ENTRY Module
,
1628 PLDR_DATA_TABLE_ENTRY ImportedModule
,
1631 PIMAGE_IMPORT_DESCRIPTOR ImportModuleDirectory
;
1633 PVOID
* ImportAddressList
;
1636 PULONG FunctionNameList
;
1641 PIMAGE_NT_HEADERS NTHeaders
;
1645 DPRINT("LdrpAdjustImportDirectory(Module %p '%wZ', %p '%wZ', '%s')\n",
1646 Module
, &Module
->BaseDllName
, ImportedModule
, &ImportedModule
->BaseDllName
, ImportedName
);
1648 ImportModuleDirectory
= (PIMAGE_IMPORT_DESCRIPTOR
)
1649 RtlImageDirectoryEntryToData(Module
->DllBase
,
1651 IMAGE_DIRECTORY_ENTRY_IMPORT
,
1653 if (ImportModuleDirectory
== NULL
)
1655 return STATUS_UNSUCCESSFUL
;
1658 while (ImportModuleDirectory
->Name
)
1660 Name
= (PCHAR
)Module
->DllBase
+ ImportModuleDirectory
->Name
;
1661 if (0 == _stricmp(Name
, (PCHAR
)ImportedName
))
1664 /* Get the import address list. */
1665 ImportAddressList
= (PVOID
*)((ULONG_PTR
)Module
->DllBase
+ (ULONG_PTR
)ImportModuleDirectory
->FirstThunk
);
1667 /* Get the list of functions to import. */
1668 if (ImportModuleDirectory
->OriginalFirstThunk
!= 0)
1670 FunctionNameList
= (PULONG
) ((ULONG_PTR
)Module
->DllBase
+ (ULONG_PTR
)ImportModuleDirectory
->OriginalFirstThunk
);
1674 FunctionNameList
= (PULONG
)((ULONG_PTR
)Module
->DllBase
+ (ULONG_PTR
)ImportModuleDirectory
->FirstThunk
);
1677 /* Get the size of IAT. */
1679 while (FunctionNameList
[IATSize
] != 0L)
1684 /* Unprotect the region we are about to write into. */
1685 IATBase
= (PVOID
)ImportAddressList
;
1686 IATSize
*= sizeof(PVOID
*);
1687 Status
= NtProtectVirtualMemory(NtCurrentProcess(),
1692 if (!NT_SUCCESS(Status
))
1694 DPRINT1("Failed to unprotect IAT.\n");
1698 NTHeaders
= RtlImageNtHeader (ImportedModule
->DllBase
);
1699 Start
= (PVOID
)NTHeaders
->OptionalHeader
.ImageBase
;
1700 End
= (PVOID
)((ULONG_PTR
)Start
+ ImportedModule
->SizeOfImage
);
1701 Offset
= (ULONG
)((ULONG_PTR
)ImportedModule
->DllBase
- (ULONG_PTR
)Start
);
1703 /* Walk through function list and fixup addresses. */
1704 while (*FunctionNameList
!= 0L)
1706 if (*ImportAddressList
>= Start
&& *ImportAddressList
< End
)
1708 (*ImportAddressList
) = (PVOID
)((ULONG_PTR
)(*ImportAddressList
) + Offset
);
1710 ImportAddressList
++;
1714 /* Protect the region we are about to write into. */
1715 Status
= NtProtectVirtualMemory(NtCurrentProcess(),
1720 if (!NT_SUCCESS(Status
))
1722 DPRINT1("Failed to protect IAT.\n");
1726 ImportModuleDirectory
++;
1728 return STATUS_SUCCESS
;
1732 /**********************************************************************
1737 * Compute the entry point for every symbol the DLL imports
1738 * from other modules.
1750 LdrFixupImports(IN PWSTR SearchPath OPTIONAL
,
1751 IN PLDR_DATA_TABLE_ENTRY Module
)
1753 PIMAGE_IMPORT_DESCRIPTOR ImportModuleDirectory
;
1754 PIMAGE_IMPORT_DESCRIPTOR ImportModuleDirectoryCurrent
;
1755 PIMAGE_BOUND_IMPORT_DESCRIPTOR BoundImportDescriptor
;
1756 PIMAGE_BOUND_IMPORT_DESCRIPTOR BoundImportDescriptorCurrent
;
1757 PIMAGE_TLS_DIRECTORY TlsDirectory
;
1760 PLDR_DATA_TABLE_ENTRY ImportedModule
;
1765 DPRINT("LdrFixupImports(SearchPath %S, Module %p)\n", SearchPath
, Module
);
1767 /* Check for tls data */
1768 TlsDirectory
= (PIMAGE_TLS_DIRECTORY
)
1769 RtlImageDirectoryEntryToData(Module
->DllBase
,
1771 IMAGE_DIRECTORY_ENTRY_TLS
,
1775 TlsSize
= TlsDirectory
->EndAddressOfRawData
1776 - TlsDirectory
->StartAddressOfRawData
1777 + TlsDirectory
->SizeOfZeroFill
;
1779 if (TlsSize
> 0 && NtCurrentPeb()->Ldr
->Initialized
)
1781 TRACE_LDR("Trying to dynamically load %wZ which contains a TLS directory\n",
1782 &Module
->BaseDllName
);
1783 TlsDirectory
= NULL
;
1788 * Process each import module.
1790 ImportModuleDirectory
= (PIMAGE_IMPORT_DESCRIPTOR
)
1791 RtlImageDirectoryEntryToData(Module
->DllBase
,
1793 IMAGE_DIRECTORY_ENTRY_IMPORT
,
1796 BoundImportDescriptor
= (PIMAGE_BOUND_IMPORT_DESCRIPTOR
)
1797 RtlImageDirectoryEntryToData(Module
->DllBase
,
1799 IMAGE_DIRECTORY_ENTRY_BOUND_IMPORT
,
1802 if (BoundImportDescriptor
!= NULL
&& ImportModuleDirectory
== NULL
)
1804 DPRINT1("%wZ has only a bound import directory\n", &Module
->BaseDllName
);
1805 return STATUS_UNSUCCESSFUL
;
1807 if (BoundImportDescriptor
)
1809 DPRINT("BoundImportDescriptor %p\n", BoundImportDescriptor
);
1811 BoundImportDescriptorCurrent
= BoundImportDescriptor
;
1812 while (BoundImportDescriptorCurrent
->OffsetModuleName
)
1814 ImportedName
= (PCHAR
)BoundImportDescriptor
+ BoundImportDescriptorCurrent
->OffsetModuleName
;
1815 TRACE_LDR("%wZ bound to %s\n", &Module
->BaseDllName
, ImportedName
);
1816 Status
= LdrpGetOrLoadModule(SearchPath
, ImportedName
, &ImportedModule
, TRUE
);
1817 if (!NT_SUCCESS(Status
))
1819 DPRINT1("failed to load %s\n", ImportedName
);
1822 if (Module
== ImportedModule
)
1824 LdrpDecrementLoadCount(Module
, FALSE
);
1826 if (ImportedModule
->TimeDateStamp
!= BoundImportDescriptorCurrent
->TimeDateStamp
)
1828 TRACE_LDR("%wZ has stale binding to %wZ\n",
1829 &Module
->BaseDllName
, &ImportedModule
->BaseDllName
);
1830 Status
= LdrpProcessImportDirectory(Module
, ImportedModule
, ImportedName
);
1831 if (!NT_SUCCESS(Status
))
1833 DPRINT1("failed to import %s\n", ImportedName
);
1839 BOOLEAN WrongForwarder
;
1840 WrongForwarder
= FALSE
;
1841 if (ImportedModule
->Flags
& LDRP_IMAGE_NOT_AT_BASE
)
1843 TRACE_LDR("%wZ has stale binding to %s\n",
1844 &Module
->BaseDllName
, ImportedName
);
1848 TRACE_LDR("%wZ has correct binding to %wZ\n",
1849 &Module
->BaseDllName
, &ImportedModule
->BaseDllName
);
1851 if (BoundImportDescriptorCurrent
->NumberOfModuleForwarderRefs
)
1853 PIMAGE_BOUND_FORWARDER_REF BoundForwarderRef
;
1855 PLDR_DATA_TABLE_ENTRY ForwarderModule
;
1856 PCHAR ForwarderName
;
1858 BoundForwarderRef
= (PIMAGE_BOUND_FORWARDER_REF
)(BoundImportDescriptorCurrent
+ 1);
1859 for (i
= 0; i
< BoundImportDescriptorCurrent
->NumberOfModuleForwarderRefs
; i
++, BoundForwarderRef
++)
1861 ForwarderName
= (PCHAR
)BoundImportDescriptor
+ BoundForwarderRef
->OffsetModuleName
;
1862 TRACE_LDR("%wZ bound to %s via forwardes from %s\n",
1863 &Module
->BaseDllName
, ForwarderName
, ImportedName
);
1864 Status
= LdrpGetOrLoadModule(SearchPath
, ForwarderName
, &ForwarderModule
, TRUE
);
1865 if (!NT_SUCCESS(Status
))
1867 DPRINT1("failed to load %s\n", ForwarderName
);
1870 if (Module
== ImportedModule
)
1872 LdrpDecrementLoadCount(Module
, FALSE
);
1874 if (ForwarderModule
->TimeDateStamp
!= BoundForwarderRef
->TimeDateStamp
||
1875 ForwarderModule
->Flags
& LDRP_IMAGE_NOT_AT_BASE
)
1877 TRACE_LDR("%wZ has stale binding to %s\n",
1878 &Module
->BaseDllName
, ForwarderName
);
1879 WrongForwarder
= TRUE
;
1883 TRACE_LDR("%wZ has correct binding to %s\n",
1884 &Module
->BaseDllName
, ForwarderName
);
1888 if (WrongForwarder
||
1889 ImportedModule
->Flags
& LDRP_IMAGE_NOT_AT_BASE
)
1891 Status
= LdrpProcessImportDirectory(Module
, ImportedModule
, ImportedName
);
1892 if (!NT_SUCCESS(Status
))
1894 DPRINT1("failed to import %s\n", ImportedName
);
1898 else if (ImportedModule
->Flags
& LDRP_IMAGE_NOT_AT_BASE
)
1900 TRACE_LDR("Adjust imports for %s from %wZ\n",
1901 ImportedName
, &Module
->BaseDllName
);
1902 Status
= LdrpAdjustImportDirectory(Module
, ImportedModule
, ImportedName
);
1903 if (!NT_SUCCESS(Status
))
1905 DPRINT1("failed to adjust import entries for %s\n", ImportedName
);
1909 else if (WrongForwarder
)
1913 * Update only forwarders
1915 TRACE_LDR("Stale BIND %s from %wZ\n",
1916 ImportedName
, &Module
->BaseDllName
);
1917 Status
= LdrpProcessImportDirectory(Module
, ImportedModule
, ImportedName
);
1918 if (!NT_SUCCESS(Status
))
1920 DPRINT1("faild to import %s\n", ImportedName
);
1929 BoundImportDescriptorCurrent
+= BoundImportDescriptorCurrent
->NumberOfModuleForwarderRefs
+ 1;
1932 else if (ImportModuleDirectory
)
1934 DPRINT("ImportModuleDirectory %p\n", ImportModuleDirectory
);
1936 ImportModuleDirectoryCurrent
= ImportModuleDirectory
;
1937 while (ImportModuleDirectoryCurrent
->Name
)
1939 ImportedName
= (PCHAR
)Module
->DllBase
+ ImportModuleDirectoryCurrent
->Name
;
1940 TRACE_LDR("%wZ imports functions from %s\n", &Module
->BaseDllName
, ImportedName
);
1942 if (SearchPath
== NULL
)
1944 ModulePath
= LdrpQueryAppPaths(Module
->BaseDllName
.Buffer
);
1946 Status
= LdrpGetOrLoadModule(ModulePath
, ImportedName
, &ImportedModule
, TRUE
);
1947 if (ModulePath
!= NULL
) RtlFreeHeap(RtlGetProcessHeap(), 0, ModulePath
);
1948 if (NT_SUCCESS(Status
)) goto Success
;
1951 Status
= LdrpGetOrLoadModule(SearchPath
, ImportedName
, &ImportedModule
, TRUE
);
1952 if (!NT_SUCCESS(Status
))
1954 DPRINT1("failed to load %s\n", ImportedName
);
1958 if (Module
== ImportedModule
)
1960 LdrpDecrementLoadCount(Module
, FALSE
);
1963 TRACE_LDR("Initializing imports for %wZ from %s\n",
1964 &Module
->BaseDllName
, ImportedName
);
1965 Status
= LdrpProcessImportDirectoryEntry(Module
, ImportedModule
, ImportModuleDirectoryCurrent
);
1966 if (!NT_SUCCESS(Status
))
1968 DPRINT1("failed to import %s\n", ImportedName
);
1971 ImportModuleDirectoryCurrent
++;
1975 if (TlsDirectory
&& TlsSize
> 0)
1977 LdrpAcquireTlsSlot(Module
, TlsSize
, FALSE
);
1980 return STATUS_SUCCESS
;
1984 /**********************************************************************
1989 * 1. Relocate, if needed the EXE.
1990 * 2. Fixup any imported symbol.
1991 * 3. Compute the EXE's entry point.
1995 * Address at which the EXE's image
1999 * Handle of the section that contains
2003 * NULL on error; otherwise the entry point
2004 * to call for initializing the DLL.
2009 * 04.01.2004 hb Previous this function was used for all images (dll + exe).
2010 * Currently the function is only used for the exe.
2012 PEPFUNC
LdrPEStartup (PVOID ImageBase
,
2013 HANDLE SectionHandle
,
2014 PLDR_DATA_TABLE_ENTRY
* Module
,
2018 PEPFUNC EntryPoint
= NULL
;
2019 PIMAGE_DOS_HEADER DosHeader
;
2020 PIMAGE_NT_HEADERS NTHeaders
;
2021 PLDR_DATA_TABLE_ENTRY tmpModule
;
2023 DPRINT("LdrPEStartup(ImageBase %p SectionHandle %p)\n",
2024 ImageBase
, SectionHandle
);
2027 * Overlay DOS and WNT headers structures
2028 * to the DLL's image.
2030 DosHeader
= (PIMAGE_DOS_HEADER
) ImageBase
;
2031 NTHeaders
= (PIMAGE_NT_HEADERS
) ((ULONG_PTR
)ImageBase
+ DosHeader
->e_lfanew
);
2034 * If the base address is different from the
2035 * one the DLL is actually loaded, perform any
2038 if (ImageBase
!= (PVOID
) NTHeaders
->OptionalHeader
.ImageBase
)
2040 DPRINT("LDR: Performing relocations\n");
2041 Status
= LdrPerformRelocations(NTHeaders
, ImageBase
);
2042 if (!NT_SUCCESS(Status
))
2044 DPRINT1("LdrPerformRelocations() failed\n");
2051 *Module
= LdrAddModuleEntry(ImageBase
, NTHeaders
, FullDosName
);
2052 (*Module
)->SectionPointer
= SectionHandle
;
2056 Module
= &tmpModule
;
2057 Status
= LdrFindEntryForAddress(ImageBase
, Module
);
2058 if (!NT_SUCCESS(Status
))
2064 if (ImageBase
!= (PVOID
) NTHeaders
->OptionalHeader
.ImageBase
)
2066 (*Module
)->Flags
|= LDRP_IMAGE_NOT_AT_BASE
;
2070 * If the DLL's imports symbols from other
2071 * modules, fixup the imported calls entry points.
2073 DPRINT("About to fixup imports\n");
2074 Status
= LdrFixupImports(NULL
, *Module
);
2075 if (!NT_SUCCESS(Status
))
2077 DPRINT1("LdrFixupImports() failed for %wZ\n", &(*Module
)->BaseDllName
);
2080 DPRINT("Fixup done\n");
2081 RtlEnterCriticalSection(NtCurrentPeb()->LoaderLock
);
2082 Status
= LdrpInitializeTlsForProccess();
2083 if (NT_SUCCESS(Status
))
2085 Status
= LdrpAttachProcess();
2087 if (NT_SUCCESS(Status
))
2089 LdrpTlsCallback(*Module
, DLL_PROCESS_ATTACH
);
2093 RtlLeaveCriticalSection(NtCurrentPeb()->LoaderLock
);
2094 if (!NT_SUCCESS(Status
))
2100 * Compute the DLL's entry point's address.
2102 DPRINT("ImageBase = %p\n", ImageBase
);
2103 DPRINT("AddressOfEntryPoint = 0x%lx\n",(ULONG
)NTHeaders
->OptionalHeader
.AddressOfEntryPoint
);
2104 if (NTHeaders
->OptionalHeader
.AddressOfEntryPoint
!= 0)
2106 EntryPoint
= (PEPFUNC
) ((ULONG_PTR
)ImageBase
2107 + NTHeaders
->OptionalHeader
.AddressOfEntryPoint
);
2109 DPRINT("LdrPEStartup() = %p\n",EntryPoint
);
2114 LdrpLoadModule(IN PWSTR SearchPath OPTIONAL
,
2116 IN PUNICODE_STRING Name
,
2117 PLDR_DATA_TABLE_ENTRY
*Module
,
2118 PVOID
*BaseAddress OPTIONAL
)
2120 UNICODE_STRING AdjustedName
;
2121 UNICODE_STRING FullDosName
;
2123 PLDR_DATA_TABLE_ENTRY tmpModule
;
2124 HANDLE SectionHandle
;
2127 PIMAGE_NT_HEADERS NtHeaders
;
2128 BOOLEAN MappedAsDataFile
;
2129 PVOID ArbitraryUserPointer
;
2133 Module
= &tmpModule
;
2135 /* adjust the full dll name */
2136 LdrAdjustDllName(&AdjustedName
, Name
, FALSE
);
2138 DPRINT("%wZ\n", &AdjustedName
);
2140 MappedAsDataFile
= FALSE
;
2141 /* Test if dll is already loaded */
2142 Status
= LdrFindEntryForName(&AdjustedName
, Module
, TRUE
);
2143 if (NT_SUCCESS(Status
))
2145 RtlFreeUnicodeString(&AdjustedName
);
2146 if (NULL
!= BaseAddress
)
2148 *BaseAddress
= (*Module
)->DllBase
;
2153 /* Open or create dll image section */
2154 Status
= LdrpMapKnownDll(&AdjustedName
, &FullDosName
, &SectionHandle
);
2155 if (!NT_SUCCESS(Status
))
2157 MappedAsDataFile
= (0 != (LoadFlags
& LOAD_LIBRARY_AS_DATAFILE
));
2158 Status
= LdrpMapDllImageFile(SearchPath
, &AdjustedName
, &FullDosName
,
2159 MappedAsDataFile
, &SectionHandle
);
2161 if (!NT_SUCCESS(Status
))
2163 DPRINT1("Failed to create or open dll section of '%wZ' (Status %lx)\n", &AdjustedName
, Status
);
2164 RtlFreeUnicodeString(&AdjustedName
);
2167 RtlFreeUnicodeString(&AdjustedName
);
2168 /* Map the dll into the process */
2171 ArbitraryUserPointer
= NtCurrentTeb()->Tib
.ArbitraryUserPointer
;
2172 NtCurrentTeb()->Tib
.ArbitraryUserPointer
= FullDosName
.Buffer
;
2173 Status
= NtMapViewOfSection(SectionHandle
,
2183 NtCurrentTeb()->Tib
.ArbitraryUserPointer
= ArbitraryUserPointer
;
2184 if (!NT_SUCCESS(Status
))
2186 DPRINT1("map view of section failed (Status 0x%08lx)\n", Status
);
2187 RtlFreeUnicodeString(&FullDosName
);
2188 NtClose(SectionHandle
);
2191 if (NULL
!= BaseAddress
)
2193 *BaseAddress
= ImageBase
;
2195 if (!MappedAsDataFile
)
2197 /* Get and check the NT headers */
2198 NtHeaders
= RtlImageNtHeader(ImageBase
);
2199 if (NtHeaders
== NULL
)
2201 DPRINT1("RtlImageNtHeaders() failed\n");
2202 NtUnmapViewOfSection (NtCurrentProcess (), ImageBase
);
2203 NtClose (SectionHandle
);
2204 RtlFreeUnicodeString(&FullDosName
);
2205 return STATUS_UNSUCCESSFUL
;
2208 DPRINT("Mapped %wZ at %x\n", &FullDosName
, ImageBase
);
2209 if (MappedAsDataFile
)
2211 ASSERT(NULL
!= BaseAddress
);
2212 if (NULL
!= BaseAddress
)
2214 *BaseAddress
= (PVOID
) ((char *) *BaseAddress
+ 1);
2217 RtlFreeUnicodeString(&FullDosName
);
2218 NtClose(SectionHandle
);
2219 return STATUS_SUCCESS
;
2221 /* If the base address is different from the
2222 * one the DLL is actually loaded, perform any
2224 if (ImageBase
!= (PVOID
) NtHeaders
->OptionalHeader
.ImageBase
)
2226 DPRINT1("Relocating (%lx -> %p) %wZ\n",
2227 NtHeaders
->OptionalHeader
.ImageBase
, ImageBase
, &FullDosName
);
2228 Status
= LdrPerformRelocations(NtHeaders
, ImageBase
);
2229 if (!NT_SUCCESS(Status
))
2231 DPRINT1("LdrPerformRelocations() failed\n");
2232 NtUnmapViewOfSection (NtCurrentProcess (), ImageBase
);
2233 NtClose (SectionHandle
);
2234 RtlFreeUnicodeString(&FullDosName
);
2235 return STATUS_UNSUCCESSFUL
;
2238 *Module
= LdrAddModuleEntry(ImageBase
, NtHeaders
, FullDosName
.Buffer
);
2239 (*Module
)->SectionPointer
= SectionHandle
;
2240 if (ImageBase
!= (PVOID
) NtHeaders
->OptionalHeader
.ImageBase
)
2242 (*Module
)->Flags
|= LDRP_IMAGE_NOT_AT_BASE
;
2244 if (NtHeaders
->FileHeader
.Characteristics
& IMAGE_FILE_DLL
)
2246 (*Module
)->Flags
|= LDRP_IMAGE_DLL
;
2248 /* fixup the imported calls entry points */
2249 Status
= LdrFixupImports(SearchPath
, *Module
);
2250 if (!NT_SUCCESS(Status
))
2252 DPRINT1("LdrFixupImports failed for %wZ, status=%x\n", &(*Module
)->BaseDllName
, Status
);
2256 RtlEnterCriticalSection(NtCurrentPeb()->LoaderLock
);
2257 InsertTailList(&NtCurrentPeb()->Ldr
->InInitializationOrderModuleList
,
2258 &(*Module
)->InInitializationOrderModuleList
);
2259 RtlLeaveCriticalSection (NtCurrentPeb()->LoaderLock
);
2261 return STATUS_SUCCESS
;
2265 LdrpUnloadModule(PLDR_DATA_TABLE_ENTRY Module
,
2268 PIMAGE_IMPORT_DESCRIPTOR ImportModuleDirectory
;
2269 PIMAGE_BOUND_IMPORT_DESCRIPTOR BoundImportDescriptor
;
2270 PIMAGE_BOUND_IMPORT_DESCRIPTOR BoundImportDescriptorCurrent
;
2272 PLDR_DATA_TABLE_ENTRY ImportedModule
;
2279 RtlEnterCriticalSection(NtCurrentPeb()->LoaderLock
);
2282 LoadCount
= LdrpDecrementLoadCount(Module
, Unload
);
2284 TRACE_LDR("Unload %wZ, LoadCount %d\n", &Module
->BaseDllName
, LoadCount
);
2288 /* ?????????????????? */
2290 else if (!(Module
->Flags
& LDRP_STATIC_LINK
) && LoadCount
== 1)
2292 BoundImportDescriptor
= (PIMAGE_BOUND_IMPORT_DESCRIPTOR
)
2293 RtlImageDirectoryEntryToData(Module
->DllBase
,
2295 IMAGE_DIRECTORY_ENTRY_BOUND_IMPORT
,
2297 if (BoundImportDescriptor
)
2299 /* dereferencing all imported modules, use the bound import descriptor */
2300 BoundImportDescriptorCurrent
= BoundImportDescriptor
;
2301 while (BoundImportDescriptorCurrent
->OffsetModuleName
)
2303 ImportedName
= (PCHAR
)BoundImportDescriptor
+ BoundImportDescriptorCurrent
->OffsetModuleName
;
2304 TRACE_LDR("%wZ trys to unload %s\n", &Module
->BaseDllName
, ImportedName
);
2305 Status
= LdrpGetOrLoadModule(NULL
, ImportedName
, &ImportedModule
, FALSE
);
2306 if (!NT_SUCCESS(Status
))
2308 DPRINT1("unable to found imported modul %s\n", ImportedName
);
2312 if (Module
!= ImportedModule
)
2314 Status
= LdrpUnloadModule(ImportedModule
, FALSE
);
2315 if (!NT_SUCCESS(Status
))
2317 DPRINT1("unable to unload %s\n", ImportedName
);
2321 BoundImportDescriptorCurrent
++;
2326 ImportModuleDirectory
= (PIMAGE_IMPORT_DESCRIPTOR
)
2327 RtlImageDirectoryEntryToData(Module
->DllBase
,
2329 IMAGE_DIRECTORY_ENTRY_IMPORT
,
2331 if (ImportModuleDirectory
)
2333 /* dereferencing all imported modules, use the import descriptor */
2334 while (ImportModuleDirectory
->Name
)
2336 ImportedName
= (PCHAR
)Module
->DllBase
+ ImportModuleDirectory
->Name
;
2337 TRACE_LDR("%wZ trys to unload %s\n", &Module
->BaseDllName
, ImportedName
);
2338 Status
= LdrpGetOrLoadModule(NULL
, ImportedName
, &ImportedModule
, FALSE
);
2339 if (!NT_SUCCESS(Status
))
2341 DPRINT1("unable to found imported modul %s\n", ImportedName
);
2345 if (Module
!= ImportedModule
)
2347 Status
= LdrpUnloadModule(ImportedModule
, FALSE
);
2348 if (!NT_SUCCESS(Status
))
2350 DPRINT1("unable to unload %s\n", ImportedName
);
2354 ImportModuleDirectory
++;
2362 if (!(Module
->Flags
& LDRP_STATIC_LINK
))
2364 LdrpDetachProcess(FALSE
);
2367 RtlLeaveCriticalSection (NtCurrentPeb()->LoaderLock
);
2369 return STATUS_SUCCESS
;
2377 LdrUnloadDll (IN PVOID BaseAddress
)
2379 PLDR_DATA_TABLE_ENTRY Module
;
2382 if (BaseAddress
== NULL
)
2383 return STATUS_SUCCESS
;
2385 if (LdrMappedAsDataFile(&BaseAddress
))
2387 Status
= NtUnmapViewOfSection(NtCurrentProcess(), BaseAddress
);
2391 Status
= LdrFindEntryForAddress(BaseAddress
, &Module
);
2392 if (NT_SUCCESS(Status
))
2394 TRACE_LDR("LdrUnloadDll, , unloading %wZ\n", &Module
->BaseDllName
);
2395 Status
= LdrpUnloadModule(Module
, TRUE
);
2406 LdrDisableThreadCalloutsForDll(IN PVOID BaseAddress
)
2408 PLIST_ENTRY ModuleListHead
;
2410 PLDR_DATA_TABLE_ENTRY Module
;
2413 DPRINT("LdrDisableThreadCalloutsForDll (BaseAddress %p)\n", BaseAddress
);
2415 Status
= STATUS_DLL_NOT_FOUND
;
2416 RtlEnterCriticalSection (NtCurrentPeb()->LoaderLock
);
2417 ModuleListHead
= &NtCurrentPeb()->Ldr
->InLoadOrderModuleList
;
2418 Entry
= ModuleListHead
->Flink
;
2419 while (Entry
!= ModuleListHead
)
2421 Module
= CONTAINING_RECORD(Entry
, LDR_DATA_TABLE_ENTRY
, InLoadOrderLinks
);
2423 DPRINT("BaseDllName %wZ BaseAddress %p\n", &Module
->BaseDllName
, Module
->DllBase
);
2425 if (Module
->DllBase
== BaseAddress
)
2427 if (Module
->TlsIndex
== 0xFFFF)
2429 Module
->Flags
|= LDRP_DONT_CALL_FOR_THREADS
;
2430 Status
= STATUS_SUCCESS
;
2434 Entry
= Entry
->Flink
;
2436 RtlLeaveCriticalSection (NtCurrentPeb()->LoaderLock
);
2444 LdrGetDllHandle(IN PWSTR DllPath OPTIONAL
,
2445 IN PULONG DllCharacteristics
,
2446 IN PUNICODE_STRING DllName
,
2447 OUT PVOID
*DllHandle
)
2449 PLDR_DATA_TABLE_ENTRY Module
;
2452 TRACE_LDR("LdrGetDllHandle, searching for %wZ from %S\n",
2453 DllName
, DllPath
? DllPath
: L
"");
2455 /* NULL is the current executable */
2456 if (DllName
== NULL
)
2458 *DllHandle
= ExeModule
->DllBase
;
2459 DPRINT("BaseAddress 0x%lx\n", *DllHandle
);
2460 return STATUS_SUCCESS
;
2463 Status
= LdrFindEntryForName(DllName
, &Module
, FALSE
);
2464 if (NT_SUCCESS(Status
))
2466 *DllHandle
= Module
->DllBase
;
2467 return STATUS_SUCCESS
;
2470 DPRINT("Failed to find dll %wZ\n", DllName
);
2472 return STATUS_DLL_NOT_FOUND
;
2479 LdrAddRefDll(IN ULONG Flags
,
2480 IN PVOID BaseAddress
)
2482 PLIST_ENTRY ModuleListHead
;
2484 PLDR_DATA_TABLE_ENTRY Module
;
2487 if (Flags
& ~(LDR_PIN_MODULE
))
2489 return STATUS_INVALID_PARAMETER
;
2492 Status
= STATUS_DLL_NOT_FOUND
;
2493 RtlEnterCriticalSection (NtCurrentPeb()->LoaderLock
);
2494 ModuleListHead
= &NtCurrentPeb()->Ldr
->InLoadOrderModuleList
;
2495 Entry
= ModuleListHead
->Flink
;
2496 while (Entry
!= ModuleListHead
)
2498 Module
= CONTAINING_RECORD(Entry
, LDR_DATA_TABLE_ENTRY
, InLoadOrderLinks
);
2500 if (Module
->DllBase
== BaseAddress
)
2502 if (Flags
& LDR_PIN_MODULE
)
2504 Module
->Flags
|= LDRP_STATIC_LINK
;
2508 LdrpIncrementLoadCount(Module
,
2511 Status
= STATUS_SUCCESS
;
2514 Entry
= Entry
->Flink
;
2516 RtlLeaveCriticalSection (NtCurrentPeb()->LoaderLock
);
2524 RtlPcToFileHeader(IN PVOID PcValue
,
2527 PLIST_ENTRY ModuleListHead
;
2529 PLDR_DATA_TABLE_ENTRY Module
;
2530 PVOID ImageBase
= NULL
;
2532 RtlEnterCriticalSection (NtCurrentPeb()->LoaderLock
);
2533 ModuleListHead
= &NtCurrentPeb()->Ldr
->InLoadOrderModuleList
;
2534 Entry
= ModuleListHead
->Flink
;
2535 while (Entry
!= ModuleListHead
)
2537 Module
= CONTAINING_RECORD(Entry
, LDR_DATA_TABLE_ENTRY
, InLoadOrderLinks
);
2539 if ((ULONG_PTR
)PcValue
>= (ULONG_PTR
)Module
->DllBase
&&
2540 (ULONG_PTR
)PcValue
< (ULONG_PTR
)Module
->DllBase
+ Module
->SizeOfImage
)
2542 ImageBase
= Module
->DllBase
;
2545 Entry
= Entry
->Flink
;
2547 RtlLeaveCriticalSection (NtCurrentPeb()->LoaderLock
);
2549 *BaseOfImage
= ImageBase
;
2557 LdrGetProcedureAddress (IN PVOID BaseAddress
,
2558 IN PANSI_STRING Name
,
2560 OUT PVOID
*ProcedureAddress
)
2562 NTSTATUS Status
= STATUS_PROCEDURE_NOT_FOUND
;
2563 if (Name
&& Name
->Length
)
2565 TRACE_LDR("LdrGetProcedureAddress by NAME - %Z\n", Name
);
2569 TRACE_LDR("LdrGetProcedureAddress by ORDINAL - %d\n", Ordinal
);
2572 DPRINT("LdrGetProcedureAddress (BaseAddress %p Name %Z Ordinal %lu ProcedureAddress %p)\n",
2573 BaseAddress
, Name
, Ordinal
, ProcedureAddress
);
2577 if (Name
&& Name
->Length
)
2580 *ProcedureAddress
= LdrGetExportByName(BaseAddress
, (PUCHAR
)Name
->Buffer
, 0xffff);
2581 if (*ProcedureAddress
!= NULL
)
2583 Status
= STATUS_SUCCESS
;
2585 DPRINT("LdrGetProcedureAddress: Can't resolve symbol '%Z'\n", Name
);
2590 Ordinal
&= 0x0000FFFF;
2591 *ProcedureAddress
= LdrGetExportByOrdinal(BaseAddress
, (WORD
)Ordinal
);
2592 if (*ProcedureAddress
)
2594 Status
= STATUS_SUCCESS
;
2596 DPRINT("LdrGetProcedureAddress: Can't resolve symbol @%lu\n", Ordinal
);
2599 _SEH2_EXCEPT(EXCEPTION_EXECUTE_HANDLER
)
2601 Status
= STATUS_DLL_NOT_FOUND
;
2608 /**********************************************************************
2613 * Unload dll's which are no longer referenced from others dll's
2624 * The loader lock must be held on enty.
2627 LdrpDetachProcess(BOOLEAN UnloadAll
)
2629 PLIST_ENTRY ModuleListHead
;
2631 PLDR_DATA_TABLE_ENTRY Module
;
2632 static ULONG CallingCount
= 0;
2634 DPRINT("LdrpDetachProcess() called for %wZ\n",
2635 &ExeModule
->BaseDllName
);
2638 LdrpDllShutdownInProgress
= TRUE
;
2642 ModuleListHead
= &NtCurrentPeb()->Ldr
->InInitializationOrderModuleList
;
2643 Entry
= ModuleListHead
->Blink
;
2644 while (Entry
!= ModuleListHead
)
2646 Module
= CONTAINING_RECORD(Entry
, LDR_DATA_TABLE_ENTRY
, InInitializationOrderModuleList
);
2647 if (((UnloadAll
&& Module
->LoadCount
== LDRP_PROCESS_CREATION_TIME
) || Module
->LoadCount
== 0) &&
2648 Module
->Flags
& LDRP_ENTRY_PROCESSED
&&
2649 !(Module
->Flags
& LDRP_UNLOAD_IN_PROGRESS
))
2651 Module
->Flags
|= LDRP_UNLOAD_IN_PROGRESS
;
2652 if (Module
== LdrpLastModule
)
2654 LdrpLastModule
= NULL
;
2656 if (Module
->Flags
& LDRP_PROCESS_ATTACH_CALLED
)
2658 TRACE_LDR("Unload %wZ - Calling entry point at %x\n",
2659 &Module
->BaseDllName
, Module
->EntryPoint
);
2660 LdrpCallDllEntry(Module
, DLL_PROCESS_DETACH
, (PVOID
)(Module
->LoadCount
== LDRP_PROCESS_CREATION_TIME
? 1 : 0));
2664 TRACE_LDR("Unload %wZ\n", &Module
->BaseDllName
);
2666 Entry
= ModuleListHead
->Blink
;
2670 Entry
= Entry
->Blink
;
2674 if (CallingCount
== 1)
2676 Entry
= ModuleListHead
->Blink
;
2677 while (Entry
!= ModuleListHead
)
2679 Module
= CONTAINING_RECORD(Entry
, LDR_DATA_TABLE_ENTRY
, InInitializationOrderModuleList
);
2680 Entry
= Entry
->Blink
;
2681 if (Module
->Flags
& LDRP_UNLOAD_IN_PROGRESS
&&
2682 ((UnloadAll
&& Module
->LoadCount
!= LDRP_PROCESS_CREATION_TIME
) || Module
->LoadCount
== 0))
2684 /* remove the module entry from the list */
2685 RemoveEntryList (&Module
->InLoadOrderLinks
);
2686 RemoveEntryList (&Module
->InInitializationOrderModuleList
);
2688 NtUnmapViewOfSection (NtCurrentProcess (), Module
->DllBase
);
2689 NtClose (Module
->SectionPointer
);
2691 TRACE_LDR("%wZ unloaded\n", &Module
->BaseDllName
);
2693 RtlFreeUnicodeString (&Module
->FullDllName
);
2694 RtlFreeUnicodeString (&Module
->BaseDllName
);
2696 RtlFreeHeap (RtlGetProcessHeap (), 0, Module
);
2701 DPRINT("LdrpDetachProcess() done\n");
2704 /**********************************************************************
2709 * Initialize all dll's which are prepered for loading
2720 * The loader lock must be held on entry.
2724 LdrpAttachProcess(VOID
)
2726 PLIST_ENTRY ModuleListHead
;
2728 PLDR_DATA_TABLE_ENTRY Module
;
2730 NTSTATUS Status
= STATUS_SUCCESS
;
2732 DPRINT("LdrpAttachProcess() called for %wZ\n",
2733 &ExeModule
->BaseDllName
);
2735 ModuleListHead
= &NtCurrentPeb()->Ldr
->InInitializationOrderModuleList
;
2736 Entry
= ModuleListHead
->Flink
;
2737 while (Entry
!= ModuleListHead
)
2739 Module
= CONTAINING_RECORD(Entry
, LDR_DATA_TABLE_ENTRY
, InInitializationOrderModuleList
);
2740 if (!(Module
->Flags
& (LDRP_LOAD_IN_PROGRESS
|LDRP_UNLOAD_IN_PROGRESS
|LDRP_ENTRY_PROCESSED
)))
2742 Module
->Flags
|= LDRP_LOAD_IN_PROGRESS
;
2743 TRACE_LDR("%wZ loaded - Calling init routine at %x for process attaching\n",
2744 &Module
->BaseDllName
, Module
->EntryPoint
);
2745 Result
= LdrpCallDllEntry(Module
, DLL_PROCESS_ATTACH
, (PVOID
)(Module
->LoadCount
== LDRP_PROCESS_CREATION_TIME
? 1 : 0));
2748 Status
= STATUS_DLL_INIT_FAILED
;
2751 if (Module
->Flags
& LDRP_IMAGE_DLL
&& Module
->EntryPoint
!= 0)
2753 Module
->Flags
|= LDRP_PROCESS_ATTACH_CALLED
|LDRP_ENTRY_PROCESSED
;
2757 Module
->Flags
|= LDRP_ENTRY_PROCESSED
;
2759 Module
->Flags
&= ~LDRP_LOAD_IN_PROGRESS
;
2761 Entry
= Entry
->Flink
;
2764 DPRINT("LdrpAttachProcess() done\n");
2773 RtlDllShutdownInProgress (VOID
)
2775 return LdrpDllShutdownInProgress
;
2782 LdrShutdownProcess (VOID
)
2784 LdrpDetachProcess(TRUE
);
2785 return STATUS_SUCCESS
;
2793 LdrpAttachThread (VOID
)
2795 PLIST_ENTRY ModuleListHead
;
2797 PLDR_DATA_TABLE_ENTRY Module
;
2800 DPRINT("LdrpAttachThread() called for %wZ\n",
2801 &ExeModule
->BaseDllName
);
2803 RtlEnterCriticalSection (NtCurrentPeb()->LoaderLock
);
2805 Status
= LdrpInitializeTlsForThread();
2807 if (NT_SUCCESS(Status
))
2809 ModuleListHead
= &NtCurrentPeb()->Ldr
->InInitializationOrderModuleList
;
2810 Entry
= ModuleListHead
->Flink
;
2812 while (Entry
!= ModuleListHead
)
2814 Module
= CONTAINING_RECORD(Entry
, LDR_DATA_TABLE_ENTRY
, InInitializationOrderModuleList
);
2815 if (Module
->Flags
& LDRP_PROCESS_ATTACH_CALLED
&&
2816 !(Module
->Flags
& LDRP_DONT_CALL_FOR_THREADS
) &&
2817 !(Module
->Flags
& LDRP_UNLOAD_IN_PROGRESS
))
2819 TRACE_LDR("%wZ - Calling entry point at %x for thread attaching\n",
2820 &Module
->BaseDllName
, Module
->EntryPoint
);
2821 LdrpCallDllEntry(Module
, DLL_THREAD_ATTACH
, NULL
);
2823 Entry
= Entry
->Flink
;
2826 Entry
= NtCurrentPeb()->Ldr
->InLoadOrderModuleList
.Flink
;
2827 Module
= CONTAINING_RECORD(Entry
, LDR_DATA_TABLE_ENTRY
, InLoadOrderLinks
);
2828 LdrpTlsCallback(Module
, DLL_THREAD_ATTACH
);
2831 RtlLeaveCriticalSection (NtCurrentPeb()->LoaderLock
);
2833 DPRINT("LdrpAttachThread() done\n");
2843 LdrShutdownThread (VOID
)
2845 PLIST_ENTRY ModuleListHead
;
2847 PLDR_DATA_TABLE_ENTRY Module
;
2849 DPRINT("LdrShutdownThread() called for %wZ\n",
2850 &ExeModule
->BaseDllName
);
2852 RtlEnterCriticalSection (NtCurrentPeb()->LoaderLock
);
2854 ModuleListHead
= &NtCurrentPeb()->Ldr
->InInitializationOrderModuleList
;
2855 Entry
= ModuleListHead
->Blink
;
2856 while (Entry
!= ModuleListHead
)
2858 Module
= CONTAINING_RECORD(Entry
, LDR_DATA_TABLE_ENTRY
, InInitializationOrderModuleList
);
2860 if (Module
->Flags
& LDRP_PROCESS_ATTACH_CALLED
&&
2861 !(Module
->Flags
& LDRP_DONT_CALL_FOR_THREADS
) &&
2862 !(Module
->Flags
& LDRP_UNLOAD_IN_PROGRESS
))
2864 TRACE_LDR("%wZ - Calling entry point at %x for thread detaching\n",
2865 &Module
->BaseDllName
, Module
->EntryPoint
);
2866 LdrpCallDllEntry(Module
, DLL_THREAD_DETACH
, NULL
);
2868 Entry
= Entry
->Blink
;
2871 RtlLeaveCriticalSection (NtCurrentPeb()->LoaderLock
);
2875 RtlFreeHeap (RtlGetProcessHeap(), 0, NtCurrentTeb()->ThreadLocalStoragePointer
);
2878 DPRINT("LdrShutdownThread() done\n");
2880 return STATUS_SUCCESS
;
2884 /***************************************************************************
2886 * LdrQueryProcessModuleInformation
2901 LdrQueryProcessModuleInformation(IN PRTL_PROCESS_MODULES ModuleInformation OPTIONAL
,
2902 IN ULONG Size OPTIONAL
,
2903 OUT PULONG ReturnedSize
)
2905 PLIST_ENTRY ModuleListHead
;
2907 PLDR_DATA_TABLE_ENTRY Module
;
2908 PRTL_PROCESS_MODULE_INFORMATION ModulePtr
= NULL
;
2909 NTSTATUS Status
= STATUS_SUCCESS
;
2910 ULONG UsedSize
= sizeof(ULONG
);
2911 ANSI_STRING AnsiString
;
2914 DPRINT("LdrQueryProcessModuleInformation() called\n");
2915 // FIXME: This code is ultra-duplicated. see lib\rtl\dbgbuffer.c
2916 RtlEnterCriticalSection (NtCurrentPeb()->LoaderLock
);
2918 if (ModuleInformation
== NULL
|| Size
== 0)
2920 Status
= STATUS_INFO_LENGTH_MISMATCH
;
2924 ModuleInformation
->NumberOfModules
= 0;
2925 ModulePtr
= &ModuleInformation
->Modules
[0];
2926 Status
= STATUS_SUCCESS
;
2929 ModuleListHead
= &NtCurrentPeb()->Ldr
->InLoadOrderModuleList
;
2930 Entry
= ModuleListHead
->Flink
;
2932 while (Entry
!= ModuleListHead
)
2934 Module
= CONTAINING_RECORD(Entry
, LDR_DATA_TABLE_ENTRY
, InLoadOrderLinks
);
2936 DPRINT(" Module %wZ\n",
2937 &Module
->FullDllName
);
2939 if (UsedSize
> Size
)
2941 Status
= STATUS_INFO_LENGTH_MISMATCH
;
2943 else if (ModuleInformation
!= NULL
)
2945 ModulePtr
->Section
= 0;
2946 ModulePtr
->MappedBase
= NULL
; // FIXME: ??
2947 ModulePtr
->ImageBase
= Module
->DllBase
;
2948 ModulePtr
->ImageSize
= Module
->SizeOfImage
;
2949 ModulePtr
->Flags
= Module
->Flags
;
2950 ModulePtr
->LoadOrderIndex
= 0; // FIXME: ??
2951 ModulePtr
->InitOrderIndex
= 0; // FIXME: ??
2952 ModulePtr
->LoadCount
= Module
->LoadCount
;
2954 AnsiString
.Length
= 0;
2955 AnsiString
.MaximumLength
= 256;
2956 AnsiString
.Buffer
= ModulePtr
->FullPathName
;
2957 RtlUnicodeStringToAnsiString(&AnsiString
,
2958 &Module
->FullDllName
,
2961 p
= strrchr(ModulePtr
->FullPathName
, '\\');
2963 ModulePtr
->OffsetToFileName
= p
- ModulePtr
->FullPathName
+ 1;
2965 ModulePtr
->OffsetToFileName
= 0;
2968 ModuleInformation
->NumberOfModules
++;
2970 UsedSize
+= sizeof(RTL_PROCESS_MODULE_INFORMATION
);
2972 Entry
= Entry
->Flink
;
2975 RtlLeaveCriticalSection (NtCurrentPeb()->LoaderLock
);
2977 if (ReturnedSize
!= 0)
2978 *ReturnedSize
= UsedSize
;
2980 DPRINT("LdrQueryProcessModuleInformation() done\n");
2987 LdrpCheckImageChecksum (IN PVOID BaseAddress
,
2990 PIMAGE_NT_HEADERS Header
;
2997 Header
= RtlImageNtHeader (BaseAddress
);
3001 HeaderSum
= Header
->OptionalHeader
.CheckSum
;
3006 Ptr
= (PUSHORT
) BaseAddress
;
3007 for (i
= 0; i
< ImageSize
/ sizeof (USHORT
); i
++)
3010 if (HIWORD(Sum
) != 0)
3012 Sum
= LOWORD(Sum
) + HIWORD(Sum
);
3019 Sum
+= (ULONG
)*((PUCHAR
)Ptr
);
3020 if (HIWORD(Sum
) != 0)
3022 Sum
= LOWORD(Sum
) + HIWORD(Sum
);
3026 CalcSum
= (USHORT
)(LOWORD(Sum
) + HIWORD(Sum
));
3028 /* Subtract image checksum from calculated checksum. */
3029 /* fix low word of checksum */
3030 if (LOWORD(CalcSum
) >= LOWORD(HeaderSum
))
3032 CalcSum
-= LOWORD(HeaderSum
);
3036 CalcSum
= ((LOWORD(CalcSum
) - LOWORD(HeaderSum
)) & 0xFFFF) - 1;
3039 /* fix high word of checksum */
3040 if (LOWORD(CalcSum
) >= HIWORD(HeaderSum
))
3042 CalcSum
-= HIWORD(HeaderSum
);
3046 CalcSum
= ((LOWORD(CalcSum
) - HIWORD(HeaderSum
)) & 0xFFFF) - 1;
3049 /* add file length */
3050 CalcSum
+= ImageSize
;
3052 return (BOOLEAN
)(CalcSum
== HeaderSum
);
3056 * Compute size of an image as it is actually present in virt memory
3057 * (i.e. excluding NEVER_LOAD sections)
3060 LdrpGetResidentSize(PIMAGE_NT_HEADERS NTHeaders
)
3062 PIMAGE_SECTION_HEADER SectionHeader
;
3063 unsigned SectionIndex
;
3066 SectionHeader
= (PIMAGE_SECTION_HEADER
)((char *) &NTHeaders
->OptionalHeader
3067 + NTHeaders
->FileHeader
.SizeOfOptionalHeader
);
3069 for (SectionIndex
= 0; SectionIndex
< NTHeaders
->FileHeader
.NumberOfSections
; SectionIndex
++)
3071 if (0 == (SectionHeader
->Characteristics
& IMAGE_SCN_LNK_REMOVE
)
3072 && ResidentSize
< SectionHeader
->VirtualAddress
+ SectionHeader
->Misc
.VirtualSize
)
3074 ResidentSize
= SectionHeader
->VirtualAddress
+ SectionHeader
->Misc
.VirtualSize
;
3079 return ResidentSize
;
3083 /***************************************************************************
3085 * LdrVerifyImageMatchesChecksum
3100 LdrVerifyImageMatchesChecksum (IN HANDLE FileHandle
,
3105 FILE_STANDARD_INFORMATION FileInfo
;
3106 IO_STATUS_BLOCK IoStatusBlock
;
3107 HANDLE SectionHandle
;
3113 DPRINT ("LdrVerifyImageMatchesChecksum() called\n");
3115 Status
= NtCreateSection (&SectionHandle
,
3122 if (!NT_SUCCESS(Status
))
3124 DPRINT1 ("NtCreateSection() failed (Status %lx)\n", Status
);
3130 Status
= NtMapViewOfSection (SectionHandle
,
3131 NtCurrentProcess (),
3140 if (!NT_SUCCESS(Status
))
3142 DPRINT1 ("NtMapViewOfSection() failed (Status %lx)\n", Status
);
3143 NtClose (SectionHandle
);
3147 Status
= NtQueryInformationFile (FileHandle
,
3150 sizeof (FILE_STANDARD_INFORMATION
),
3151 FileStandardInformation
);
3152 if (!NT_SUCCESS(Status
))
3154 DPRINT1 ("NtMapViewOfSection() failed (Status %lx)\n", Status
);
3155 NtUnmapViewOfSection (NtCurrentProcess (),
3157 NtClose (SectionHandle
);
3161 Result
= LdrpCheckImageChecksum (BaseAddress
,
3162 FileInfo
.EndOfFile
.u
.LowPart
);
3163 if (Result
== FALSE
)
3165 Status
= STATUS_IMAGE_CHECKSUM_MISMATCH
;
3168 NtUnmapViewOfSection (NtCurrentProcess (),
3171 NtClose (SectionHandle
);
3177 /***************************************************************************
3179 * LdrQueryImageFileExecutionOptions
3194 LdrQueryImageFileExecutionOptions (IN PUNICODE_STRING SubKey
,
3195 IN PCWSTR ValueName
,
3198 IN ULONG BufferSize
,
3199 OUT PULONG ReturnedLength OPTIONAL
)
3201 PKEY_VALUE_PARTIAL_INFORMATION KeyInfo
;
3202 OBJECT_ATTRIBUTES ObjectAttributes
;
3203 UNICODE_STRING ValueNameString
;
3204 UNICODE_STRING KeyName
;
3205 WCHAR NameBuffer
[256];
3213 L
"\\Registry\\Machine\\Software\\Microsoft\\Windows NT\\CurrentVersion\\Image File Execution Options\\");
3214 Ptr
= wcsrchr (SubKey
->Buffer
, L
'\\');
3217 Ptr
= SubKey
->Buffer
;
3223 wcscat (NameBuffer
, Ptr
);
3224 RtlInitUnicodeString (&KeyName
,
3227 InitializeObjectAttributes (&ObjectAttributes
,
3229 OBJ_CASE_INSENSITIVE
,
3233 Status
= NtOpenKey (&KeyHandle
,
3236 if (!NT_SUCCESS(Status
))
3238 DPRINT ("NtOpenKey() failed (Status %lx)\n", Status
);
3242 KeyInfoSize
= sizeof(KEY_VALUE_PARTIAL_INFORMATION
) + 32;
3243 KeyInfo
= RtlAllocateHeap (RtlGetProcessHeap(),
3246 if (KeyInfo
== NULL
)
3248 NtClose (KeyHandle
);
3249 return STATUS_INSUFFICIENT_RESOURCES
;
3252 RtlInitUnicodeString (&ValueNameString
,
3254 Status
= NtQueryValueKey (KeyHandle
,
3256 KeyValuePartialInformation
,
3260 if (Status
== STATUS_BUFFER_OVERFLOW
)
3262 KeyInfoSize
= sizeof(KEY_VALUE_PARTIAL_INFORMATION
) + KeyInfo
->DataLength
;
3263 RtlFreeHeap (RtlGetProcessHeap(),
3266 KeyInfo
= RtlAllocateHeap (RtlGetProcessHeap(),
3269 if (KeyInfo
== NULL
)
3271 NtClose (KeyHandle
);
3272 return STATUS_INSUFFICIENT_RESOURCES
;
3275 Status
= NtQueryValueKey (KeyHandle
,
3277 KeyValuePartialInformation
,
3282 NtClose (KeyHandle
);
3284 if (!NT_SUCCESS(Status
))
3286 if (KeyInfo
!= NULL
)
3288 RtlFreeHeap (RtlGetProcessHeap(),
3295 if (KeyInfo
->Type
!= Type
)
3297 RtlFreeHeap (RtlGetProcessHeap(),
3300 return STATUS_OBJECT_TYPE_MISMATCH
;
3303 ResultSize
= BufferSize
;
3304 if (ResultSize
< KeyInfo
->DataLength
)
3306 Status
= STATUS_BUFFER_OVERFLOW
;
3310 ResultSize
= KeyInfo
->DataLength
;
3312 RtlCopyMemory (Buffer
,
3316 RtlFreeHeap (RtlGetProcessHeap(),
3320 if (ReturnedLength
!= NULL
)
3322 *ReturnedLength
= ResultSize
;
3329 PIMAGE_BASE_RELOCATION NTAPI
3330 LdrProcessRelocationBlock(IN ULONG_PTR Address
,
3332 IN PUSHORT TypeOffset
,
3341 for (i
= 0; i
< Count
; i
++)
3343 Offset
= *TypeOffset
& 0xFFF;
3344 Type
= *TypeOffset
>> 12;
3348 case IMAGE_REL_BASED_ABSOLUTE
:
3351 case IMAGE_REL_BASED_HIGH
:
3352 ShortPtr
= (PUSHORT
)((ULONG_PTR
)Address
+ Offset
);
3353 *ShortPtr
+= HIWORD(Delta
);
3356 case IMAGE_REL_BASED_LOW
:
3357 ShortPtr
= (PUSHORT
)((ULONG_PTR
)Address
+ Offset
);
3358 *ShortPtr
+= LOWORD(Delta
);
3361 case IMAGE_REL_BASED_HIGHLOW
:
3362 LongPtr
= (PULONG
)((ULONG_PTR
)Address
+ Offset
);
3366 case IMAGE_REL_BASED_HIGHADJ
:
3367 case IMAGE_REL_BASED_MIPS_JMPADDR
:
3369 DPRINT1("Unknown/unsupported fixup type %hu.\n", Type
);
3376 return (PIMAGE_BASE_RELOCATION
)TypeOffset
;
3381 LdrLockLoaderLock(IN ULONG Flags
,
3382 OUT PULONG Disposition OPTIONAL
,
3383 OUT PULONG Cookie OPTIONAL
)
3386 return STATUS_NOT_IMPLEMENTED
;
3391 LdrUnlockLoaderLock(IN ULONG Flags
,
3392 IN ULONG Cookie OPTIONAL
)
3395 return STATUS_NOT_IMPLEMENTED
;
3400 LdrUnloadAlternateResourceModule(IN PVOID BaseAddress
)