Merge to trunk HEAD(r36856)
[reactos.git] / reactos / dll / ntdll / ldr / utils.c
1 /*
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)
8 */
9
10 /*
11 * TODO:
12 * - Handle loading flags correctly
13 * - Handle errors correctly (unload dll's)
14 * - Implement a faster way to find modules (hash table)
15 * - any more ??
16 */
17
18 /* INCLUDES *****************************************************************/
19
20 #include <ntdll.h>
21 #define NDEBUG
22 #include <debug.h>
23
24 #define LDRP_PROCESS_CREATION_TIME 0x8000000
25
26 /* GLOBALS *******************************************************************/
27
28 #ifdef NDEBUG
29 #if defined(__GNUC__)
30 #define TRACE_LDR(args...) if (RtlGetNtGlobalFlags() & FLG_SHOW_LDR_SNAPS) { DbgPrint("(LDR:%s:%d) ",__FILE__,__LINE__); DbgPrint(args); }
31 #elif defined(_MSC_VER)
32 #define TRACE_LDR(args, ...) if (RtlGetNtGlobalFlags() & FLG_SHOW_LDR_SNAPS) { DbgPrint("(LDR:%s:%d) ",__FILE__,__LINE__); DbgPrint(__VA_ARGS__); }
33 #endif /* __GNUC__ */
34 #else
35 #define TRACE_LDR(args...) do { DbgPrint("(LDR:%s:%d) ",__FILE__,__LINE__); DbgPrint(args); } while(0)
36 #endif
37
38 typedef struct _TLS_DATA
39 {
40 PVOID StartAddressOfRawData;
41 DWORD TlsDataSize;
42 DWORD TlsZeroSize;
43 PIMAGE_TLS_CALLBACK TlsAddressOfCallBacks;
44 PLDR_DATA_TABLE_ENTRY Module;
45 } TLS_DATA, *PTLS_DATA;
46
47 static BOOLEAN LdrpDllShutdownInProgress = FALSE;
48 static PTLS_DATA LdrpTlsArray = NULL;
49 static ULONG LdrpTlsCount = 0;
50 static ULONG LdrpTlsSize = 0;
51 static HANDLE LdrpKnownDllsDirHandle = NULL;
52 static UNICODE_STRING LdrpKnownDllPath = {0, 0, NULL};
53 static PLDR_DATA_TABLE_ENTRY LdrpLastModule = NULL;
54 extern PLDR_DATA_TABLE_ENTRY ExeModule;
55
56 /* PROTOTYPES ****************************************************************/
57
58 static NTSTATUS LdrFindEntryForName(PUNICODE_STRING Name, PLDR_DATA_TABLE_ENTRY *Module, BOOLEAN Ref);
59 static PVOID LdrFixupForward(PCHAR ForwardName);
60 static PVOID LdrGetExportByName(PVOID BaseAddress, PUCHAR SymbolName, USHORT Hint);
61 static NTSTATUS LdrpLoadModule(IN PWSTR SearchPath OPTIONAL,
62 IN ULONG LoadFlags,
63 IN PUNICODE_STRING Name,
64 OUT PLDR_DATA_TABLE_ENTRY *Module,
65 OUT PVOID *BaseAddress OPTIONAL);
66 static NTSTATUS LdrpAttachProcess(VOID);
67 static VOID LdrpDetachProcess(BOOLEAN UnloadAll);
68
69 /* FUNCTIONS *****************************************************************/
70
71 #if defined(DBG) || defined(KDBG)
72
73 VOID
74 LdrpLoadUserModuleSymbols(PLDR_DATA_TABLE_ENTRY LdrModule)
75 {
76 NtSystemDebugControl(
77 SysDbgQueryVersion,
78 (PVOID)LdrModule,
79 0,
80 NULL,
81 0,
82 NULL);
83 }
84
85 #endif /* DBG || KDBG */
86
87 BOOLEAN
88 LdrMappedAsDataFile(PVOID *BaseAddress)
89 {
90 if (0 != ((DWORD_PTR) *BaseAddress & (PAGE_SIZE - 1)))
91 {
92 *BaseAddress = (PVOID) ((DWORD_PTR) *BaseAddress & ~ ((DWORD_PTR) PAGE_SIZE - 1));
93 return TRUE;
94 }
95
96 return FALSE;
97 }
98
99 static __inline LONG LdrpDecrementLoadCount(PLDR_DATA_TABLE_ENTRY Module, BOOLEAN Locked)
100 {
101 LONG LoadCount;
102 if (!Locked)
103 {
104 RtlEnterCriticalSection (NtCurrentPeb()->LoaderLock);
105 }
106 LoadCount = Module->LoadCount;
107 if (Module->LoadCount > 0 && Module->LoadCount != 0xFFFF)
108 {
109 Module->LoadCount--;
110 }
111 if (!Locked)
112 {
113 RtlLeaveCriticalSection(NtCurrentPeb()->LoaderLock);
114 }
115 return LoadCount;
116 }
117
118 static __inline LONG LdrpIncrementLoadCount(PLDR_DATA_TABLE_ENTRY Module, BOOLEAN Locked)
119 {
120 LONG LoadCount;
121 if (!Locked)
122 {
123 RtlEnterCriticalSection (NtCurrentPeb()->LoaderLock);
124 }
125 LoadCount = Module->LoadCount;
126 if (Module->LoadCount != 0xFFFF)
127 {
128 Module->LoadCount++;
129 }
130 if (!Locked)
131 {
132 RtlLeaveCriticalSection(NtCurrentPeb()->LoaderLock);
133 }
134 return LoadCount;
135 }
136
137 static __inline VOID LdrpAcquireTlsSlot(PLDR_DATA_TABLE_ENTRY Module, ULONG Size, BOOLEAN Locked)
138 {
139 if (!Locked)
140 {
141 RtlEnterCriticalSection (NtCurrentPeb()->LoaderLock);
142 }
143 Module->TlsIndex = (SHORT)LdrpTlsCount;
144 LdrpTlsCount++;
145 LdrpTlsSize += Size;
146 if (!Locked)
147 {
148 RtlLeaveCriticalSection(NtCurrentPeb()->LoaderLock);
149 }
150 }
151
152 static __inline VOID LdrpTlsCallback(PLDR_DATA_TABLE_ENTRY Module, ULONG dwReason)
153 {
154 PIMAGE_TLS_CALLBACK TlsCallback;
155 if (Module->TlsIndex != 0xFFFF && Module->LoadCount == 0xFFFF)
156 {
157 TlsCallback = LdrpTlsArray[Module->TlsIndex].TlsAddressOfCallBacks;
158 if (TlsCallback)
159 {
160 while (*TlsCallback)
161 {
162 TRACE_LDR("%wZ - Calling tls callback at %x\n",
163 &Module->BaseDllName, TlsCallback);
164 TlsCallback(Module->DllBase, dwReason, NULL);
165 TlsCallback = (PIMAGE_TLS_CALLBACK)((ULONG_PTR)TlsCallback + sizeof(PVOID));
166 }
167 }
168 }
169 }
170
171 static BOOLEAN LdrpCallDllEntry(PLDR_DATA_TABLE_ENTRY Module, DWORD dwReason, PVOID lpReserved)
172 {
173 if (!(Module->Flags & LDRP_IMAGE_DLL) ||
174 Module->EntryPoint == 0)
175 {
176 return TRUE;
177 }
178 LdrpTlsCallback(Module, dwReason);
179 return ((PDLLMAIN_FUNC)Module->EntryPoint)(Module->DllBase, dwReason, lpReserved);
180 }
181
182 static NTSTATUS
183 LdrpInitializeTlsForThread(VOID)
184 {
185 PVOID* TlsPointers;
186 PTLS_DATA TlsInfo;
187 PVOID TlsData;
188 ULONG i;
189 PTEB Teb = NtCurrentTeb();
190
191 DPRINT("LdrpInitializeTlsForThread() called for %wZ\n", &ExeModule->BaseDllName);
192
193 Teb->StaticUnicodeString.Length = 0;
194 Teb->StaticUnicodeString.MaximumLength = sizeof(Teb->StaticUnicodeBuffer);
195 Teb->StaticUnicodeString.Buffer = Teb->StaticUnicodeBuffer;
196
197 if (LdrpTlsCount > 0)
198 {
199 TlsPointers = RtlAllocateHeap(RtlGetProcessHeap(),
200 0,
201 LdrpTlsCount * sizeof(PVOID) + LdrpTlsSize);
202 if (TlsPointers == NULL)
203 {
204 DPRINT1("failed to allocate thread tls data\n");
205 return STATUS_NO_MEMORY;
206 }
207
208 TlsData = (PVOID)((ULONG_PTR)TlsPointers + LdrpTlsCount * sizeof(PVOID));
209 Teb->ThreadLocalStoragePointer = TlsPointers;
210
211 TlsInfo = LdrpTlsArray;
212 for (i = 0; i < LdrpTlsCount; i++, TlsInfo++)
213 {
214 TRACE_LDR("Initialize tls data for %wZ\n", &TlsInfo->Module->BaseDllName);
215 TlsPointers[i] = TlsData;
216 if (TlsInfo->TlsDataSize)
217 {
218 memcpy(TlsData, TlsInfo->StartAddressOfRawData, TlsInfo->TlsDataSize);
219 TlsData = (PVOID)((ULONG_PTR)TlsData + TlsInfo->TlsDataSize);
220 }
221 if (TlsInfo->TlsZeroSize)
222 {
223 memset(TlsData, 0, TlsInfo->TlsZeroSize);
224 TlsData = (PVOID)((ULONG_PTR)TlsData + TlsInfo->TlsZeroSize);
225 }
226 }
227 }
228 DPRINT("LdrpInitializeTlsForThread() done\n");
229 return STATUS_SUCCESS;
230 }
231
232 static NTSTATUS
233 LdrpInitializeTlsForProccess(VOID)
234 {
235 PLIST_ENTRY ModuleListHead;
236 PLIST_ENTRY Entry;
237 PLDR_DATA_TABLE_ENTRY Module;
238 PIMAGE_TLS_DIRECTORY TlsDirectory;
239 PTLS_DATA TlsData;
240 ULONG Size;
241
242 DPRINT("LdrpInitializeTlsForProccess() called for %wZ\n", &ExeModule->BaseDllName);
243
244 if (LdrpTlsCount > 0)
245 {
246 LdrpTlsArray = RtlAllocateHeap(RtlGetProcessHeap(),
247 0,
248 LdrpTlsCount * sizeof(TLS_DATA));
249 if (LdrpTlsArray == NULL)
250 {
251 DPRINT1("Failed to allocate global tls data\n");
252 return STATUS_NO_MEMORY;
253 }
254
255 ModuleListHead = &NtCurrentPeb()->Ldr->InLoadOrderModuleList;
256 Entry = ModuleListHead->Flink;
257 while (Entry != ModuleListHead)
258 {
259 Module = CONTAINING_RECORD(Entry, LDR_DATA_TABLE_ENTRY, InLoadOrderLinks);
260 if (Module->LoadCount == 0xFFFF &&
261 Module->TlsIndex != 0xFFFF)
262 {
263 TlsDirectory = (PIMAGE_TLS_DIRECTORY)
264 RtlImageDirectoryEntryToData(Module->DllBase,
265 TRUE,
266 IMAGE_DIRECTORY_ENTRY_TLS,
267 &Size);
268 ASSERT(Module->TlsIndex < LdrpTlsCount);
269 TlsData = &LdrpTlsArray[Module->TlsIndex];
270 TlsData->StartAddressOfRawData = (PVOID)(ULONG_PTR)TlsDirectory->StartAddressOfRawData;
271 TlsData->TlsDataSize = TlsDirectory->EndAddressOfRawData - TlsDirectory->StartAddressOfRawData;
272 TlsData->TlsZeroSize = TlsDirectory->SizeOfZeroFill;
273 if (TlsDirectory->AddressOfCallBacks)
274 TlsData->TlsAddressOfCallBacks = *(PIMAGE_TLS_CALLBACK*)TlsDirectory->AddressOfCallBacks;
275 else
276 TlsData->TlsAddressOfCallBacks = NULL;
277 TlsData->Module = Module;
278 #if 0
279 DbgPrint("TLS directory for %wZ\n", &Module->BaseDllName);
280 DbgPrint("StartAddressOfRawData: %x\n", TlsDirectory->StartAddressOfRawData);
281 DbgPrint("EndAddressOfRawData: %x\n", TlsDirectory->EndAddressOfRawData);
282 DbgPrint("SizeOfRawData: %d\n", TlsDirectory->EndAddressOfRawData - TlsDirectory->StartAddressOfRawData);
283 DbgPrint("AddressOfIndex: %x\n", TlsDirectory->AddressOfIndex);
284 DbgPrint("AddressOfCallBacks: %x (%x)\n", TlsDirectory->AddressOfCallBacks, *TlsDirectory->AddressOfCallBacks);
285 DbgPrint("SizeOfZeroFill: %d\n", TlsDirectory->SizeOfZeroFill);
286 DbgPrint("Characteristics: %x\n", TlsDirectory->Characteristics);
287 #endif
288 /*
289 * FIXME:
290 * Is this region allways writable ?
291 */
292 *(PULONG)TlsDirectory->AddressOfIndex = Module->TlsIndex;
293 }
294 Entry = Entry->Flink;
295 }
296 }
297 DPRINT("LdrpInitializeTlsForProccess() done\n");
298 return STATUS_SUCCESS;
299 }
300
301 VOID
302 LdrpInitLoader(VOID)
303 {
304 OBJECT_ATTRIBUTES ObjectAttributes;
305 UNICODE_STRING LinkTarget;
306 UNICODE_STRING Name;
307 HANDLE LinkHandle;
308 ULONG Length;
309 NTSTATUS Status;
310
311 DPRINT("LdrpInitLoader() called for %wZ\n", &ExeModule->BaseDllName);
312
313 /* Get handle to the 'KnownDlls' directory */
314 RtlInitUnicodeString(&Name,
315 L"\\KnownDlls");
316 InitializeObjectAttributes(&ObjectAttributes,
317 &Name,
318 OBJ_CASE_INSENSITIVE,
319 NULL,
320 NULL);
321 Status = NtOpenDirectoryObject(&LdrpKnownDllsDirHandle,
322 DIRECTORY_QUERY | DIRECTORY_TRAVERSE,
323 &ObjectAttributes);
324 if (!NT_SUCCESS(Status))
325 {
326 DPRINT("NtOpenDirectoryObject() failed (Status %lx)\n", Status);
327 LdrpKnownDllsDirHandle = NULL;
328 return;
329 }
330
331 /* Allocate target name string */
332 LinkTarget.Length = 0;
333 LinkTarget.MaximumLength = MAX_PATH * sizeof(WCHAR);
334 LinkTarget.Buffer = RtlAllocateHeap(RtlGetProcessHeap(),
335 0,
336 MAX_PATH * sizeof(WCHAR));
337 if (LinkTarget.Buffer == NULL)
338 {
339 NtClose(LdrpKnownDllsDirHandle);
340 LdrpKnownDllsDirHandle = NULL;
341 return;
342 }
343
344 RtlInitUnicodeString(&Name,
345 L"KnownDllPath");
346 InitializeObjectAttributes(&ObjectAttributes,
347 &Name,
348 OBJ_CASE_INSENSITIVE,
349 LdrpKnownDllsDirHandle,
350 NULL);
351 Status = NtOpenSymbolicLinkObject(&LinkHandle,
352 SYMBOLIC_LINK_ALL_ACCESS,
353 &ObjectAttributes);
354 if (!NT_SUCCESS(Status))
355 {
356 RtlFreeUnicodeString(&LinkTarget);
357 NtClose(LdrpKnownDllsDirHandle);
358 LdrpKnownDllsDirHandle = NULL;
359 return;
360 }
361
362 Status = NtQuerySymbolicLinkObject(LinkHandle,
363 &LinkTarget,
364 &Length);
365 NtClose(LinkHandle);
366 if (!NT_SUCCESS(Status))
367 {
368 RtlFreeUnicodeString(&LinkTarget);
369 NtClose(LdrpKnownDllsDirHandle);
370 LdrpKnownDllsDirHandle = NULL;
371 }
372
373 RtlCreateUnicodeString(&LdrpKnownDllPath,
374 LinkTarget.Buffer);
375
376 RtlFreeUnicodeString(&LinkTarget);
377
378 DPRINT("LdrpInitLoader() done\n");
379 }
380
381
382 /***************************************************************************
383 * NAME LOCAL
384 * LdrAdjustDllName
385 *
386 * DESCRIPTION
387 * Adjusts the name of a dll to a fully qualified name.
388 *
389 * ARGUMENTS
390 * FullDllName: Pointer to caller supplied storage for the fully
391 * qualified dll name.
392 * DllName: Pointer to the dll name.
393 * BaseName: TRUE: Only the file name is passed to FullDllName
394 * FALSE: The full path is preserved in FullDllName
395 *
396 * RETURN VALUE
397 * None
398 *
399 * REVISIONS
400 *
401 * NOTE
402 * A given path is not affected by the adjustment, but the file
403 * name only:
404 * ntdll --> ntdll.dll
405 * ntdll. --> ntdll
406 * ntdll.xyz --> ntdll.xyz
407 */
408 static VOID
409 LdrAdjustDllName (PUNICODE_STRING FullDllName,
410 PUNICODE_STRING DllName,
411 BOOLEAN BaseName)
412 {
413 WCHAR Buffer[MAX_PATH];
414 ULONG Length;
415 PWCHAR Extension;
416 PWCHAR Pointer;
417
418 Length = DllName->Length / sizeof(WCHAR);
419
420 if (BaseName)
421 {
422 /* get the base dll name */
423 Pointer = DllName->Buffer + Length;
424 Extension = Pointer;
425
426 do
427 {
428 --Pointer;
429 }
430 while (Pointer >= DllName->Buffer && *Pointer != L'\\' && *Pointer != L'/');
431
432 Pointer++;
433 Length = Extension - Pointer;
434 memmove (Buffer, Pointer, Length * sizeof(WCHAR));
435 Buffer[Length] = L'\0';
436 }
437 else
438 {
439 /* get the full dll name */
440 memmove (Buffer, DllName->Buffer, DllName->Length);
441 Buffer[DllName->Length / sizeof(WCHAR)] = L'\0';
442 }
443
444 /* Build the DLL's absolute name */
445 Extension = wcsrchr (Buffer, L'.');
446 if ((Extension != NULL) && (*Extension == L'.'))
447 {
448 /* with extension - remove dot if it's the last character */
449 if (Buffer[Length - 1] == L'.')
450 Length--;
451 Buffer[Length] = 0;
452 }
453 else
454 {
455 /* name without extension - assume that it is .dll */
456 memmove (Buffer + Length, L".dll", 10);
457 }
458
459 RtlCreateUnicodeString(FullDllName, Buffer);
460 }
461
462 PLDR_DATA_TABLE_ENTRY
463 LdrAddModuleEntry(PVOID ImageBase,
464 PIMAGE_NT_HEADERS NTHeaders,
465 PWSTR FullDosName)
466 {
467 PLDR_DATA_TABLE_ENTRY Module;
468
469 Module = RtlAllocateHeap(RtlGetProcessHeap(), 0, sizeof (LDR_DATA_TABLE_ENTRY));
470 ASSERT(Module);
471 memset(Module, 0, sizeof(LDR_DATA_TABLE_ENTRY));
472 Module->DllBase = (PVOID)ImageBase;
473 Module->EntryPoint = (PVOID)(ULONG_PTR)NTHeaders->OptionalHeader.AddressOfEntryPoint;
474 if (Module->EntryPoint != 0)
475 Module->EntryPoint = (PVOID)((ULONG_PTR)Module->EntryPoint + (ULONG_PTR)Module->DllBase);
476 Module->SizeOfImage = LdrpGetResidentSize(NTHeaders);
477 if (NtCurrentPeb()->Ldr->Initialized == TRUE)
478 {
479 /* loading while app is running */
480 Module->LoadCount = 1;
481 } else {
482 /*
483 * loading while app is initializing
484 * dll must not be unloaded
485 */
486 Module->LoadCount = 0xFFFF;
487 }
488
489 Module->Flags = 0;
490 Module->TlsIndex = -1;
491 Module->CheckSum = NTHeaders->OptionalHeader.CheckSum;
492 Module->TimeDateStamp = NTHeaders->FileHeader.TimeDateStamp;
493
494 RtlCreateUnicodeString (&Module->FullDllName,
495 FullDosName);
496 RtlCreateUnicodeString (&Module->BaseDllName,
497 wcsrchr(FullDosName, L'\\') + 1);
498 DPRINT ("BaseDllName %wZ\n", &Module->BaseDllName);
499
500 RtlEnterCriticalSection (NtCurrentPeb()->LoaderLock);
501 InsertTailList(&NtCurrentPeb()->Ldr->InLoadOrderModuleList,
502 &Module->InLoadOrderLinks);
503 RtlLeaveCriticalSection(NtCurrentPeb()->LoaderLock);
504
505 return(Module);
506 }
507
508
509 static NTSTATUS
510 LdrpMapKnownDll(IN PUNICODE_STRING DllName,
511 OUT PUNICODE_STRING FullDosName,
512 OUT PHANDLE SectionHandle)
513 {
514 OBJECT_ATTRIBUTES ObjectAttributes;
515 NTSTATUS Status;
516
517 DPRINT("LdrpMapKnownDll() called\n");
518
519 if (LdrpKnownDllsDirHandle == NULL)
520 {
521 DPRINT("Invalid 'KnownDlls' directory\n");
522 return STATUS_UNSUCCESSFUL;
523 }
524
525 DPRINT("LdrpKnownDllPath '%wZ'\n", &LdrpKnownDllPath);
526
527 InitializeObjectAttributes(&ObjectAttributes,
528 DllName,
529 OBJ_CASE_INSENSITIVE,
530 LdrpKnownDllsDirHandle,
531 NULL);
532 Status = NtOpenSection(SectionHandle,
533 SECTION_MAP_READ | SECTION_MAP_WRITE | SECTION_MAP_EXECUTE,
534 &ObjectAttributes);
535 if (!NT_SUCCESS(Status))
536 {
537 DPRINT("NtOpenSection() failed for '%wZ' (Status 0x%08lx)\n", DllName, Status);
538 return Status;
539 }
540
541 FullDosName->Length = LdrpKnownDllPath.Length + DllName->Length + sizeof(WCHAR);
542 FullDosName->MaximumLength = FullDosName->Length + sizeof(WCHAR);
543 FullDosName->Buffer = RtlAllocateHeap(RtlGetProcessHeap(),
544 0,
545 FullDosName->MaximumLength);
546 if (FullDosName->Buffer == NULL)
547 {
548 FullDosName->Length = 0;
549 FullDosName->MaximumLength = 0;
550 return STATUS_SUCCESS;
551 }
552
553 wcscpy(FullDosName->Buffer, LdrpKnownDllPath.Buffer);
554 wcscat(FullDosName->Buffer, L"\\");
555 wcscat(FullDosName->Buffer, DllName->Buffer);
556
557 DPRINT("FullDosName '%wZ'\n", FullDosName);
558
559 DPRINT("LdrpMapKnownDll() done\n");
560
561 return STATUS_SUCCESS;
562 }
563
564
565 static NTSTATUS
566 LdrpMapDllImageFile(IN PWSTR SearchPath OPTIONAL,
567 IN PUNICODE_STRING DllName,
568 OUT PUNICODE_STRING FullDosName,
569 IN BOOLEAN MapAsDataFile,
570 OUT PHANDLE SectionHandle)
571 {
572 WCHAR SearchPathBuffer[MAX_PATH];
573 WCHAR DosName[MAX_PATH];
574 UNICODE_STRING FullNtFileName;
575 OBJECT_ATTRIBUTES FileObjectAttributes;
576 HANDLE FileHandle;
577 char BlockBuffer [1024];
578 PIMAGE_DOS_HEADER DosHeader;
579 PIMAGE_NT_HEADERS NTHeaders;
580 IO_STATUS_BLOCK IoStatusBlock;
581 NTSTATUS Status;
582 ULONG len;
583
584 DPRINT("LdrpMapDllImageFile() called\n");
585
586 if (SearchPath == NULL)
587 {
588 /* get application running path */
589
590 wcscpy (SearchPathBuffer, NtCurrentPeb()->ProcessParameters->ImagePathName.Buffer);
591
592 len = wcslen (SearchPathBuffer);
593
594 while (len && SearchPathBuffer[len - 1] != L'\\')
595 len--;
596
597 if (len) SearchPathBuffer[len-1] = L'\0';
598
599 wcscat (SearchPathBuffer, L";");
600
601 wcscat (SearchPathBuffer, SharedUserData->NtSystemRoot);
602 wcscat (SearchPathBuffer, L"\\system32;");
603 wcscat (SearchPathBuffer, SharedUserData->NtSystemRoot);
604 wcscat (SearchPathBuffer, L";.");
605
606 SearchPath = SearchPathBuffer;
607 }
608
609 if (RtlDosSearchPath_U (SearchPath,
610 DllName->Buffer,
611 NULL,
612 MAX_PATH,
613 DosName,
614 NULL) == 0)
615 return STATUS_DLL_NOT_FOUND;
616
617
618 if (!RtlDosPathNameToNtPathName_U (DosName,
619 &FullNtFileName,
620 NULL,
621 NULL))
622 return STATUS_DLL_NOT_FOUND;
623
624 DPRINT("FullNtFileName %wZ\n", &FullNtFileName);
625
626 InitializeObjectAttributes(&FileObjectAttributes,
627 &FullNtFileName,
628 0,
629 NULL,
630 NULL);
631
632 DPRINT("Opening dll \"%wZ\"\n", &FullNtFileName);
633
634 Status = NtOpenFile(&FileHandle,
635 GENERIC_READ|SYNCHRONIZE,
636 &FileObjectAttributes,
637 &IoStatusBlock,
638 FILE_SHARE_READ,
639 FILE_SYNCHRONOUS_IO_NONALERT);
640 if (!NT_SUCCESS(Status))
641 {
642 DPRINT1("Dll open of %wZ failed: Status = 0x%08lx\n",
643 &FullNtFileName, Status);
644 RtlFreeHeap (RtlGetProcessHeap (),
645 0,
646 FullNtFileName.Buffer);
647 return Status;
648 }
649 RtlFreeHeap (RtlGetProcessHeap (),
650 0,
651 FullNtFileName.Buffer);
652
653 if (!MapAsDataFile)
654 {
655
656 Status = NtReadFile(FileHandle,
657 NULL,
658 NULL,
659 NULL,
660 &IoStatusBlock,
661 BlockBuffer,
662 sizeof(BlockBuffer),
663 NULL,
664 NULL);
665 if (!NT_SUCCESS(Status))
666 {
667 DPRINT("Dll header read failed: Status = 0x%08lx\n", Status);
668 NtClose(FileHandle);
669 return Status;
670 }
671
672 /*
673 * Overlay DOS and NT headers structures to the
674 * buffer with DLL's header raw data.
675 */
676 DosHeader = (PIMAGE_DOS_HEADER) BlockBuffer;
677 NTHeaders = (PIMAGE_NT_HEADERS) (BlockBuffer + DosHeader->e_lfanew);
678 /*
679 * Check it is a PE image file.
680 */
681 if ((DosHeader->e_magic != IMAGE_DOS_SIGNATURE)
682 || (DosHeader->e_lfanew == 0L)
683 || (*(PULONG)(NTHeaders) != IMAGE_NT_SIGNATURE))
684 {
685 DPRINT("NTDLL format invalid\n");
686 NtClose(FileHandle);
687
688 return STATUS_UNSUCCESSFUL;
689 }
690 }
691
692 /*
693 * Create a section for dll.
694 */
695 Status = NtCreateSection(SectionHandle,
696 SECTION_ALL_ACCESS,
697 NULL,
698 NULL,
699 PAGE_READONLY,
700 MapAsDataFile ? SEC_COMMIT : SEC_IMAGE,
701 FileHandle);
702 NtClose(FileHandle);
703
704 if (!NT_SUCCESS(Status))
705 {
706 DPRINT("NTDLL create section failed: Status = 0x%08lx\n", Status);
707 return Status;
708 }
709
710 RtlCreateUnicodeString(FullDosName,
711 DosName);
712
713 return Status;
714 }
715
716
717
718 /***************************************************************************
719 * NAME EXPORTED
720 * LdrLoadDll
721 *
722 * DESCRIPTION
723 *
724 * ARGUMENTS
725 *
726 * RETURN VALUE
727 *
728 * REVISIONS
729 *
730 * NOTE
731 *
732 * @implemented
733 */
734 NTSTATUS NTAPI
735 LdrLoadDll (IN PWSTR SearchPath OPTIONAL,
736 IN PULONG LoadFlags OPTIONAL,
737 IN PUNICODE_STRING Name,
738 OUT PVOID *BaseAddress /* also known as HMODULE*, and PHANDLE 'DllHandle' */)
739 {
740 NTSTATUS Status;
741 PLDR_DATA_TABLE_ENTRY Module;
742
743 PPEB Peb = NtCurrentPeb();
744
745 TRACE_LDR("LdrLoadDll, loading %wZ%s%S\n",
746 Name,
747 SearchPath ? L" from " : L"",
748 SearchPath ? SearchPath : L"");
749
750 Status = LdrpLoadModule(SearchPath, LoadFlags ? *LoadFlags : 0, Name, &Module, BaseAddress);
751
752 if (NT_SUCCESS(Status) &&
753 (!LoadFlags || 0 == (*LoadFlags & LOAD_LIBRARY_AS_DATAFILE)))
754 {
755 if (!(Module->Flags & LDRP_PROCESS_ATTACH_CALLED))
756 {
757 RtlEnterCriticalSection(Peb->LoaderLock);
758 Status = LdrpAttachProcess();
759 RtlLeaveCriticalSection(Peb->LoaderLock);
760 }
761 }
762
763 if ((!Module) && (NT_SUCCESS(Status)))
764 return Status;
765
766 *BaseAddress = NT_SUCCESS(Status) ? Module->DllBase : NULL;
767
768 return Status;
769 }
770
771
772 /***************************************************************************
773 * NAME EXPORTED
774 * LdrFindEntryForAddress
775 *
776 * DESCRIPTION
777 *
778 * ARGUMENTS
779 *
780 * RETURN VALUE
781 *
782 * REVISIONS
783 *
784 * NOTE
785 *
786 * @implemented
787 */
788 NTSTATUS NTAPI
789 LdrFindEntryForAddress(PVOID Address,
790 PLDR_DATA_TABLE_ENTRY *Module)
791 {
792 PLIST_ENTRY ModuleListHead;
793 PLIST_ENTRY Entry;
794 PLDR_DATA_TABLE_ENTRY ModulePtr;
795
796 DPRINT("LdrFindEntryForAddress(Address %p)\n", Address);
797
798 if (NtCurrentPeb()->Ldr == NULL)
799 return(STATUS_NO_MORE_ENTRIES);
800
801 RtlEnterCriticalSection(NtCurrentPeb()->LoaderLock);
802 ModuleListHead = &NtCurrentPeb()->Ldr->InLoadOrderModuleList;
803 Entry = ModuleListHead->Flink;
804 if (Entry == ModuleListHead)
805 {
806 RtlLeaveCriticalSection(NtCurrentPeb()->LoaderLock);
807 return(STATUS_NO_MORE_ENTRIES);
808 }
809
810 while (Entry != ModuleListHead)
811 {
812 ModulePtr = CONTAINING_RECORD(Entry, LDR_DATA_TABLE_ENTRY, InLoadOrderLinks);
813
814 DPRINT("Scanning %wZ at %p\n", &ModulePtr->BaseDllName, ModulePtr->DllBase);
815
816 if ((Address >= ModulePtr->DllBase) &&
817 ((ULONG_PTR)Address <= ((ULONG_PTR)ModulePtr->DllBase + ModulePtr->SizeOfImage)))
818 {
819 *Module = ModulePtr;
820 RtlLeaveCriticalSection(NtCurrentPeb()->LoaderLock);
821 return(STATUS_SUCCESS);
822 }
823
824 Entry = Entry->Flink;
825 }
826
827 DPRINT("Failed to find module entry.\n");
828
829 RtlLeaveCriticalSection(NtCurrentPeb()->LoaderLock);
830 return(STATUS_NO_MORE_ENTRIES);
831 }
832
833
834 /***************************************************************************
835 * NAME LOCAL
836 * LdrFindEntryForName
837 *
838 * DESCRIPTION
839 *
840 * ARGUMENTS
841 *
842 * RETURN VALUE
843 *
844 * REVISIONS
845 *
846 * NOTE
847 *
848 */
849 static NTSTATUS
850 LdrFindEntryForName(PUNICODE_STRING Name,
851 PLDR_DATA_TABLE_ENTRY *Module,
852 BOOLEAN Ref)
853 {
854 PLIST_ENTRY ModuleListHead;
855 PLIST_ENTRY Entry;
856 PLDR_DATA_TABLE_ENTRY ModulePtr;
857 BOOLEAN ContainsPath;
858 UNICODE_STRING AdjustedName;
859 unsigned i;
860
861 DPRINT("LdrFindEntryForName(Name %wZ)\n", Name);
862
863 if (NtCurrentPeb()->Ldr == NULL)
864 return(STATUS_NO_MORE_ENTRIES);
865
866 RtlEnterCriticalSection(NtCurrentPeb()->LoaderLock);
867 ModuleListHead = &NtCurrentPeb()->Ldr->InLoadOrderModuleList;
868 Entry = ModuleListHead->Flink;
869 if (Entry == ModuleListHead)
870 {
871 RtlLeaveCriticalSection(NtCurrentPeb()->LoaderLock);
872 return(STATUS_NO_MORE_ENTRIES);
873 }
874
875 // NULL is the current process
876 if (Name == NULL)
877 {
878 *Module = ExeModule;
879 RtlLeaveCriticalSection(NtCurrentPeb()->LoaderLock);
880 return(STATUS_SUCCESS);
881 }
882
883 LdrAdjustDllName (&AdjustedName, Name, FALSE);
884
885 ContainsPath = (AdjustedName.Length >= 2 * sizeof(WCHAR) && L':' == AdjustedName.Buffer[1]);
886 for (i = 0; ! ContainsPath && i < AdjustedName.Length / sizeof(WCHAR); i++)
887 {
888 ContainsPath = L'\\' == AdjustedName.Buffer[i] ||
889 L'/' == AdjustedName.Buffer[i];
890 }
891
892 if (LdrpLastModule)
893 {
894 if ((! ContainsPath &&
895 0 == RtlCompareUnicodeString(&LdrpLastModule->BaseDllName, &AdjustedName, TRUE)) ||
896 (ContainsPath &&
897 0 == RtlCompareUnicodeString(&LdrpLastModule->FullDllName, &AdjustedName, TRUE)))
898 {
899 *Module = LdrpLastModule;
900 if (Ref && (*Module)->LoadCount != 0xFFFF)
901 {
902 (*Module)->LoadCount++;
903 }
904 RtlLeaveCriticalSection(NtCurrentPeb()->LoaderLock);
905 RtlFreeUnicodeString(&AdjustedName);
906 return(STATUS_SUCCESS);
907 }
908 }
909 while (Entry != ModuleListHead)
910 {
911 ModulePtr = CONTAINING_RECORD(Entry, LDR_DATA_TABLE_ENTRY, InLoadOrderLinks);
912
913 DPRINT("Scanning %wZ %wZ\n", &ModulePtr->BaseDllName, &AdjustedName);
914
915 if ((! ContainsPath &&
916 0 == RtlCompareUnicodeString(&ModulePtr->BaseDllName, &AdjustedName, TRUE)) ||
917 (ContainsPath &&
918 0 == RtlCompareUnicodeString(&ModulePtr->FullDllName, &AdjustedName, TRUE)))
919 {
920 *Module = LdrpLastModule = ModulePtr;
921 if (Ref && ModulePtr->LoadCount != 0xFFFF)
922 {
923 ModulePtr->LoadCount++;
924 }
925 RtlLeaveCriticalSection(NtCurrentPeb()->LoaderLock);
926 RtlFreeUnicodeString(&AdjustedName);
927 return(STATUS_SUCCESS);
928 }
929
930 Entry = Entry->Flink;
931 }
932
933 DPRINT("Failed to find dll %wZ\n", Name);
934 RtlLeaveCriticalSection(NtCurrentPeb()->LoaderLock);
935 RtlFreeUnicodeString(&AdjustedName);
936 return(STATUS_NO_MORE_ENTRIES);
937 }
938
939 /**********************************************************************
940 * NAME LOCAL
941 * LdrFixupForward
942 *
943 * DESCRIPTION
944 *
945 * ARGUMENTS
946 *
947 * RETURN VALUE
948 *
949 * REVISIONS
950 *
951 * NOTE
952 *
953 */
954 static PVOID
955 LdrFixupForward(PCHAR ForwardName)
956 {
957 CHAR NameBuffer[128];
958 UNICODE_STRING DllName;
959 NTSTATUS Status;
960 PCHAR p;
961 PLDR_DATA_TABLE_ENTRY Module;
962 PVOID BaseAddress;
963
964 strcpy(NameBuffer, ForwardName);
965 p = strchr(NameBuffer, '.');
966 if (p != NULL)
967 {
968 *p = 0;
969
970 DPRINT("Dll: %s Function: %s\n", NameBuffer, p+1);
971 RtlCreateUnicodeStringFromAsciiz (&DllName,
972 NameBuffer);
973
974 Status = LdrFindEntryForName (&DllName, &Module, FALSE);
975 /* FIXME:
976 * The caller (or the image) is responsible for loading of the dll, where the function is forwarded.
977 */
978 if (!NT_SUCCESS(Status))
979 {
980 ULONG Flags = LDRP_PROCESS_CREATION_TIME;
981 Status = LdrLoadDll(NULL,
982 &Flags,
983 &DllName,
984 &BaseAddress);
985 if (NT_SUCCESS(Status))
986 {
987 Status = LdrFindEntryForName (&DllName, &Module, FALSE);
988 }
989 }
990 RtlFreeUnicodeString (&DllName);
991 if (!NT_SUCCESS(Status))
992 {
993 DPRINT1("LdrFixupForward: failed to load %s\n", NameBuffer);
994 return NULL;
995 }
996
997 DPRINT("BaseAddress: %p\n", Module->DllBase);
998
999 return LdrGetExportByName(Module->DllBase, (PUCHAR)(p+1), -1);
1000 }
1001
1002 return NULL;
1003 }
1004
1005
1006 /**********************************************************************
1007 * NAME LOCAL
1008 * LdrGetExportByOrdinal
1009 *
1010 * DESCRIPTION
1011 *
1012 * ARGUMENTS
1013 *
1014 * RETURN VALUE
1015 *
1016 * REVISIONS
1017 *
1018 * NOTE
1019 *
1020 */
1021 static PVOID
1022 LdrGetExportByOrdinal (
1023 PVOID BaseAddress,
1024 ULONG Ordinal
1025 )
1026 {
1027 PIMAGE_EXPORT_DIRECTORY ExportDir;
1028 ULONG ExportDirSize;
1029 PDWORD * ExFunctions;
1030 PVOID Function;
1031
1032 ExportDir = (PIMAGE_EXPORT_DIRECTORY)
1033 RtlImageDirectoryEntryToData (BaseAddress,
1034 TRUE,
1035 IMAGE_DIRECTORY_ENTRY_EXPORT,
1036 &ExportDirSize);
1037
1038
1039 ExFunctions = (PDWORD *)
1040 RVA(
1041 BaseAddress,
1042 ExportDir->AddressOfFunctions
1043 );
1044 DPRINT(
1045 "LdrGetExportByOrdinal(Ordinal %lu) = %p\n",
1046 Ordinal,
1047 RVA(BaseAddress, ExFunctions[Ordinal - ExportDir->Base] )
1048 );
1049
1050 Function = (0 != ExFunctions[Ordinal - ExportDir->Base]
1051 ? RVA(BaseAddress, ExFunctions[Ordinal - ExportDir->Base] )
1052 : NULL);
1053
1054 if (((ULONG_PTR)Function >= (ULONG_PTR)ExportDir) &&
1055 ((ULONG_PTR)Function < (ULONG_PTR)ExportDir + (ULONG_PTR)ExportDirSize))
1056 {
1057 DPRINT("Forward: %s\n", (PCHAR)Function);
1058 Function = LdrFixupForward((PCHAR)Function);
1059 }
1060
1061 return Function;
1062 }
1063
1064
1065 /**********************************************************************
1066 * NAME LOCAL
1067 * LdrGetExportByName
1068 *
1069 * DESCRIPTION
1070 *
1071 * ARGUMENTS
1072 *
1073 * RETURN VALUE
1074 *
1075 * REVISIONS
1076 *
1077 * NOTE
1078 * AddressOfNames and AddressOfNameOrdinals are paralell tables,
1079 * both with NumberOfNames entries.
1080 *
1081 */
1082 static PVOID
1083 LdrGetExportByName(PVOID BaseAddress,
1084 PUCHAR SymbolName,
1085 WORD Hint)
1086 {
1087 PIMAGE_EXPORT_DIRECTORY ExportDir;
1088 PDWORD * ExFunctions;
1089 PDWORD * ExNames;
1090 USHORT * ExOrdinals;
1091 PVOID ExName;
1092 ULONG Ordinal;
1093 PVOID Function;
1094 LONG minn, maxn;
1095 ULONG ExportDirSize;
1096
1097 DPRINT("LdrGetExportByName %p %s %hu\n", BaseAddress, SymbolName, Hint);
1098
1099 ExportDir = (PIMAGE_EXPORT_DIRECTORY)
1100 RtlImageDirectoryEntryToData(BaseAddress,
1101 TRUE,
1102 IMAGE_DIRECTORY_ENTRY_EXPORT,
1103 &ExportDirSize);
1104 if (ExportDir == NULL)
1105 {
1106 DPRINT1("LdrGetExportByName(): no export directory, "
1107 "can't lookup %s/%hu!\n", SymbolName, Hint);
1108 return NULL;
1109 }
1110
1111
1112 //The symbol names may be missing entirely
1113 if (ExportDir->AddressOfNames == 0)
1114 {
1115 DPRINT("LdrGetExportByName(): symbol names missing entirely\n");
1116 return NULL;
1117 }
1118
1119 /*
1120 * Get header pointers
1121 */
1122 ExNames = (PDWORD *)RVA(BaseAddress,
1123 ExportDir->AddressOfNames);
1124 ExOrdinals = (USHORT *)RVA(BaseAddress,
1125 ExportDir->AddressOfNameOrdinals);
1126 ExFunctions = (PDWORD *)RVA(BaseAddress,
1127 ExportDir->AddressOfFunctions);
1128
1129 /*
1130 * Check the hint first
1131 */
1132 if (Hint < ExportDir->NumberOfNames)
1133 {
1134 ExName = RVA(BaseAddress, ExNames[Hint]);
1135 if (strcmp(ExName, (PCHAR)SymbolName) == 0)
1136 {
1137 Ordinal = ExOrdinals[Hint];
1138 Function = RVA(BaseAddress, ExFunctions[Ordinal]);
1139 if (((ULONG_PTR)Function >= (ULONG_PTR)ExportDir) &&
1140 ((ULONG_PTR)Function < (ULONG_PTR)ExportDir + (ULONG_PTR)ExportDirSize))
1141 {
1142 DPRINT("Forward: %s\n", (PCHAR)Function);
1143 Function = LdrFixupForward((PCHAR)Function);
1144 if (Function == NULL)
1145 {
1146 DPRINT1("LdrGetExportByName(): failed to find %s\n",SymbolName);
1147 }
1148 return Function;
1149 }
1150 if (Function != NULL)
1151 return Function;
1152 }
1153 }
1154
1155 /*
1156 * Binary search
1157 */
1158 minn = 0;
1159 maxn = ExportDir->NumberOfNames - 1;
1160 while (minn <= maxn)
1161 {
1162 LONG mid;
1163 LONG res;
1164
1165 mid = (minn + maxn) / 2;
1166
1167 ExName = RVA(BaseAddress, ExNames[mid]);
1168 res = strcmp(ExName, (PCHAR)SymbolName);
1169 if (res == 0)
1170 {
1171 Ordinal = ExOrdinals[mid];
1172 Function = RVA(BaseAddress, ExFunctions[Ordinal]);
1173 if (((ULONG_PTR)Function >= (ULONG_PTR)ExportDir) &&
1174 ((ULONG_PTR)Function < (ULONG_PTR)ExportDir + (ULONG_PTR)ExportDirSize))
1175 {
1176 DPRINT("Forward: %s\n", (PCHAR)Function);
1177 Function = LdrFixupForward((PCHAR)Function);
1178 if (Function == NULL)
1179 {
1180 DPRINT1("LdrGetExportByName(): failed to find %s\n",SymbolName);
1181 }
1182 return Function;
1183 }
1184 if (Function != NULL)
1185 return Function;
1186 }
1187 else if (minn == maxn)
1188 {
1189 DPRINT("LdrGetExportByName(): binary search failed\n");
1190 break;
1191 }
1192 else if (res > 0)
1193 {
1194 maxn = mid - 1;
1195 }
1196 else
1197 {
1198 minn = mid + 1;
1199 }
1200 }
1201
1202 DPRINT("LdrGetExportByName(): failed to find %s\n",SymbolName);
1203 return (PVOID)NULL;
1204 }
1205
1206
1207 /**********************************************************************
1208 * NAME LOCAL
1209 * LdrPerformRelocations
1210 *
1211 * DESCRIPTION
1212 * Relocate a DLL's memory image.
1213 *
1214 * ARGUMENTS
1215 *
1216 * RETURN VALUE
1217 *
1218 * REVISIONS
1219 *
1220 * NOTE
1221 *
1222 */
1223 static NTSTATUS
1224 LdrPerformRelocations(PIMAGE_NT_HEADERS NTHeaders,
1225 PVOID ImageBase)
1226 {
1227 PIMAGE_DATA_DIRECTORY RelocationDDir;
1228 PIMAGE_BASE_RELOCATION RelocationDir, RelocationEnd;
1229 ULONG Count, ProtectSize, OldProtect, OldProtect2;
1230 PVOID Page, ProtectPage, ProtectPage2;
1231 PUSHORT TypeOffset;
1232 ULONG_PTR Delta;
1233 NTSTATUS Status;
1234
1235 if (NTHeaders->FileHeader.Characteristics & IMAGE_FILE_RELOCS_STRIPPED)
1236 {
1237 return STATUS_SUCCESS;
1238 }
1239
1240 RelocationDDir =
1241 &NTHeaders->OptionalHeader.DataDirectory[IMAGE_DIRECTORY_ENTRY_BASERELOC];
1242
1243 if (RelocationDDir->VirtualAddress == 0 || RelocationDDir->Size == 0)
1244 {
1245 return STATUS_SUCCESS;
1246 }
1247
1248 ProtectSize = PAGE_SIZE;
1249 Delta = (ULONG_PTR)ImageBase - NTHeaders->OptionalHeader.ImageBase;
1250 RelocationDir = (PIMAGE_BASE_RELOCATION)((ULONG_PTR)ImageBase +
1251 RelocationDDir->VirtualAddress);
1252 RelocationEnd = (PIMAGE_BASE_RELOCATION)((ULONG_PTR)ImageBase +
1253 RelocationDDir->VirtualAddress + RelocationDDir->Size);
1254
1255 while (RelocationDir < RelocationEnd &&
1256 RelocationDir->SizeOfBlock > 0)
1257 {
1258 Count = (RelocationDir->SizeOfBlock - sizeof(IMAGE_BASE_RELOCATION)) /
1259 sizeof(USHORT);
1260 Page = (PVOID)((ULONG_PTR)ImageBase + (ULONG_PTR)RelocationDir->VirtualAddress);
1261 TypeOffset = (PUSHORT)(RelocationDir + 1);
1262
1263 /* Unprotect the page(s) we're about to relocate. */
1264 ProtectPage = Page;
1265 Status = NtProtectVirtualMemory(NtCurrentProcess(),
1266 &ProtectPage,
1267 &ProtectSize,
1268 PAGE_READWRITE,
1269 &OldProtect);
1270 if (!NT_SUCCESS(Status))
1271 {
1272 DPRINT1("Failed to unprotect relocation target.\n");
1273 return Status;
1274 }
1275
1276 if (RelocationDir->VirtualAddress + PAGE_SIZE <
1277 NTHeaders->OptionalHeader.SizeOfImage)
1278 {
1279 ProtectPage2 = (PVOID)((ULONG_PTR)ProtectPage + PAGE_SIZE);
1280 Status = NtProtectVirtualMemory(NtCurrentProcess(),
1281 &ProtectPage2,
1282 &ProtectSize,
1283 PAGE_READWRITE,
1284 &OldProtect2);
1285 if (!NT_SUCCESS(Status))
1286 {
1287 DPRINT1("Failed to unprotect relocation target (2).\n");
1288 NtProtectVirtualMemory(NtCurrentProcess(),
1289 &ProtectPage,
1290 &ProtectSize,
1291 OldProtect,
1292 &OldProtect);
1293 return Status;
1294 }
1295 }
1296 else
1297 {
1298 ProtectPage2 = NULL;
1299 }
1300
1301 RelocationDir = LdrProcessRelocationBlock((ULONG_PTR)Page,
1302 Count,
1303 TypeOffset,
1304 Delta);
1305 if (RelocationDir == NULL)
1306 return STATUS_UNSUCCESSFUL;
1307
1308 /* Restore old page protection. */
1309 NtProtectVirtualMemory(NtCurrentProcess(),
1310 &ProtectPage,
1311 &ProtectSize,
1312 OldProtect,
1313 &OldProtect);
1314
1315 if (ProtectPage2 != NULL)
1316 {
1317 NtProtectVirtualMemory(NtCurrentProcess(),
1318 &ProtectPage2,
1319 &ProtectSize,
1320 OldProtect2,
1321 &OldProtect2);
1322 }
1323 }
1324
1325 return STATUS_SUCCESS;
1326 }
1327
1328 static NTSTATUS
1329 LdrpGetOrLoadModule(PWCHAR SearchPath,
1330 PCHAR Name,
1331 PLDR_DATA_TABLE_ENTRY* Module,
1332 BOOLEAN Load)
1333 {
1334 ANSI_STRING AnsiDllName;
1335 UNICODE_STRING DllName;
1336 NTSTATUS Status;
1337
1338 DPRINT("LdrpGetOrLoadModule() called for %s\n", Name);
1339
1340 RtlInitAnsiString(&AnsiDllName, Name);
1341 Status = RtlAnsiStringToUnicodeString(&DllName, &AnsiDllName, TRUE);
1342 if (!NT_SUCCESS(Status))
1343 {
1344 return Status;
1345 }
1346
1347 Status = LdrFindEntryForName (&DllName, Module, Load);
1348 if (Load && !NT_SUCCESS(Status))
1349 {
1350 Status = LdrpLoadModule(SearchPath,
1351 NtCurrentPeb()->Ldr->Initialized ? 0 : LDRP_PROCESS_CREATION_TIME,
1352 &DllName,
1353 Module,
1354 NULL);
1355 if (NT_SUCCESS(Status))
1356 {
1357 Status = LdrFindEntryForName (&DllName, Module, FALSE);
1358 }
1359 if (!NT_SUCCESS(Status))
1360 {
1361 ULONG ErrorResponse;
1362 ULONG_PTR ErrorParameter = (ULONG_PTR)&DllName;
1363
1364 DPRINT1("failed to load %wZ\n", &DllName);
1365 NtRaiseHardError(STATUS_DLL_NOT_FOUND,
1366 1,
1367 1,
1368 &ErrorParameter,
1369 OptionOk,
1370 &ErrorResponse);
1371 }
1372 }
1373 RtlFreeUnicodeString (&DllName);
1374 return Status;
1375 }
1376
1377 void
1378 RtlpRaiseImportNotFound(CHAR *FuncName, ULONG Ordinal, PUNICODE_STRING DllName)
1379 {
1380 ULONG ErrorResponse;
1381 ULONG_PTR ErrorParameters[2];
1382 ANSI_STRING ProcNameAnsi;
1383 UNICODE_STRING ProcName;
1384 CHAR Buffer[8];
1385
1386 if (!FuncName)
1387 {
1388 _snprintf(Buffer, 8, "# %ld", Ordinal);
1389 FuncName = Buffer;
1390 }
1391
1392 RtlInitAnsiString(&ProcNameAnsi, FuncName);
1393 RtlAnsiStringToUnicodeString(&ProcName, &ProcNameAnsi, TRUE);
1394 ErrorParameters[0] = (ULONG_PTR)&ProcName;
1395 ErrorParameters[1] = (ULONG_PTR)DllName;
1396 NtRaiseHardError(STATUS_ENTRYPOINT_NOT_FOUND,
1397 2,
1398 3,
1399 ErrorParameters,
1400 OptionOk,
1401 &ErrorResponse);
1402 RtlFreeUnicodeString(&ProcName);
1403 }
1404
1405 static NTSTATUS
1406 LdrpProcessImportDirectoryEntry(PLDR_DATA_TABLE_ENTRY Module,
1407 PLDR_DATA_TABLE_ENTRY ImportedModule,
1408 PIMAGE_IMPORT_DESCRIPTOR ImportModuleDirectory)
1409 {
1410 NTSTATUS Status;
1411 PVOID* ImportAddressList;
1412 PULONG FunctionNameList;
1413 PVOID IATBase;
1414 ULONG OldProtect;
1415 ULONG Ordinal;
1416 ULONG IATSize;
1417
1418 if (ImportModuleDirectory == NULL || ImportModuleDirectory->Name == 0)
1419 {
1420 return STATUS_UNSUCCESSFUL;
1421 }
1422
1423 /* Get the import address list. */
1424 ImportAddressList = (PVOID *)((ULONG_PTR)Module->DllBase + (ULONG_PTR)ImportModuleDirectory->FirstThunk);
1425
1426 /* Get the list of functions to import. */
1427 if (ImportModuleDirectory->OriginalFirstThunk != 0)
1428 {
1429 FunctionNameList = (PULONG) ((ULONG_PTR)Module->DllBase + (ULONG_PTR)ImportModuleDirectory->OriginalFirstThunk);
1430 }
1431 else
1432 {
1433 FunctionNameList = (PULONG)((ULONG_PTR)Module->DllBase + (ULONG_PTR)ImportModuleDirectory->FirstThunk);
1434 }
1435
1436 /* Get the size of IAT. */
1437 IATSize = 0;
1438 while (FunctionNameList[IATSize] != 0L)
1439 {
1440 IATSize++;
1441 }
1442
1443 /* Unprotect the region we are about to write into. */
1444 IATBase = (PVOID)ImportAddressList;
1445 IATSize *= sizeof(PVOID*);
1446 Status = NtProtectVirtualMemory(NtCurrentProcess(),
1447 &IATBase,
1448 &IATSize,
1449 PAGE_READWRITE,
1450 &OldProtect);
1451 if (!NT_SUCCESS(Status))
1452 {
1453 DPRINT1("Failed to unprotect IAT.\n");
1454 return(Status);
1455 }
1456
1457 /* Walk through function list and fixup addresses. */
1458 while (*FunctionNameList != 0L)
1459 {
1460 if ((*FunctionNameList) & 0x80000000)
1461 {
1462 Ordinal = (*FunctionNameList) & 0x7fffffff;
1463 *ImportAddressList = LdrGetExportByOrdinal(ImportedModule->DllBase, Ordinal);
1464 if ((*ImportAddressList) == NULL)
1465 {
1466 DPRINT1("Failed to import #%ld from %wZ\n", Ordinal, &ImportedModule->FullDllName);
1467 RtlpRaiseImportNotFound(NULL, Ordinal, &ImportedModule->FullDllName);
1468 return STATUS_ENTRYPOINT_NOT_FOUND;
1469 }
1470 }
1471 else
1472 {
1473 IMAGE_IMPORT_BY_NAME *pe_name;
1474 pe_name = RVA(Module->DllBase, *FunctionNameList);
1475 *ImportAddressList = LdrGetExportByName(ImportedModule->DllBase, pe_name->Name, pe_name->Hint);
1476 if ((*ImportAddressList) == NULL)
1477 {
1478 DPRINT1("Failed to import %s from %wZ\n", pe_name->Name, &ImportedModule->FullDllName);
1479 RtlpRaiseImportNotFound((CHAR*)pe_name->Name, 0, &ImportedModule->FullDllName);
1480 return STATUS_ENTRYPOINT_NOT_FOUND;
1481 }
1482 }
1483 ImportAddressList++;
1484 FunctionNameList++;
1485 }
1486
1487 /* Protect the region we are about to write into. */
1488 Status = NtProtectVirtualMemory(NtCurrentProcess(),
1489 &IATBase,
1490 &IATSize,
1491 OldProtect,
1492 &OldProtect);
1493 if (!NT_SUCCESS(Status))
1494 {
1495 DPRINT1("Failed to protect IAT.\n");
1496 return(Status);
1497 }
1498
1499 return STATUS_SUCCESS;
1500 }
1501
1502 static NTSTATUS
1503 LdrpProcessImportDirectory(
1504 PLDR_DATA_TABLE_ENTRY Module,
1505 PLDR_DATA_TABLE_ENTRY ImportedModule,
1506 PCHAR ImportedName)
1507 {
1508 NTSTATUS Status;
1509 PIMAGE_IMPORT_DESCRIPTOR ImportModuleDirectory;
1510 PCHAR Name;
1511 ULONG Size;
1512
1513 DPRINT("LdrpProcessImportDirectory(%p '%wZ', '%s')\n",
1514 Module, &Module->BaseDllName, ImportedName);
1515
1516
1517 ImportModuleDirectory = (PIMAGE_IMPORT_DESCRIPTOR)
1518 RtlImageDirectoryEntryToData(Module->DllBase,
1519 TRUE,
1520 IMAGE_DIRECTORY_ENTRY_IMPORT,
1521 &Size);
1522 if (ImportModuleDirectory == NULL)
1523 {
1524 return STATUS_UNSUCCESSFUL;
1525 }
1526
1527 while (ImportModuleDirectory->Name)
1528 {
1529 Name = (PCHAR)Module->DllBase + ImportModuleDirectory->Name;
1530 if (0 == _stricmp(Name, ImportedName))
1531 {
1532 Status = LdrpProcessImportDirectoryEntry(Module,
1533 ImportedModule,
1534 ImportModuleDirectory);
1535 if (!NT_SUCCESS(Status))
1536 {
1537 return Status;
1538 }
1539 }
1540 ImportModuleDirectory++;
1541 }
1542
1543
1544 return STATUS_SUCCESS;
1545 }
1546
1547
1548 static NTSTATUS
1549 LdrpAdjustImportDirectory(PLDR_DATA_TABLE_ENTRY Module,
1550 PLDR_DATA_TABLE_ENTRY ImportedModule,
1551 PCHAR ImportedName)
1552 {
1553 PIMAGE_IMPORT_DESCRIPTOR ImportModuleDirectory;
1554 NTSTATUS Status;
1555 PVOID* ImportAddressList;
1556 PVOID Start;
1557 PVOID End;
1558 PULONG FunctionNameList;
1559 PVOID IATBase;
1560 ULONG OldProtect;
1561 ULONG Offset;
1562 ULONG IATSize;
1563 PIMAGE_NT_HEADERS NTHeaders;
1564 PCHAR Name;
1565 ULONG Size;
1566
1567 DPRINT("LdrpAdjustImportDirectory(Module %p '%wZ', %p '%wZ', '%s')\n",
1568 Module, &Module->BaseDllName, ImportedModule, &ImportedModule->BaseDllName, ImportedName);
1569
1570 ImportModuleDirectory = (PIMAGE_IMPORT_DESCRIPTOR)
1571 RtlImageDirectoryEntryToData(Module->DllBase,
1572 TRUE,
1573 IMAGE_DIRECTORY_ENTRY_IMPORT,
1574 &Size);
1575 if (ImportModuleDirectory == NULL)
1576 {
1577 return STATUS_UNSUCCESSFUL;
1578 }
1579
1580 while (ImportModuleDirectory->Name)
1581 {
1582 Name = (PCHAR)Module->DllBase + ImportModuleDirectory->Name;
1583 if (0 == _stricmp(Name, (PCHAR)ImportedName))
1584 {
1585
1586 /* Get the import address list. */
1587 ImportAddressList = (PVOID *)((ULONG_PTR)Module->DllBase + (ULONG_PTR)ImportModuleDirectory->FirstThunk);
1588
1589 /* Get the list of functions to import. */
1590 if (ImportModuleDirectory->OriginalFirstThunk != 0)
1591 {
1592 FunctionNameList = (PULONG) ((ULONG_PTR)Module->DllBase + (ULONG_PTR)ImportModuleDirectory->OriginalFirstThunk);
1593 }
1594 else
1595 {
1596 FunctionNameList = (PULONG)((ULONG_PTR)Module->DllBase + (ULONG_PTR)ImportModuleDirectory->FirstThunk);
1597 }
1598
1599 /* Get the size of IAT. */
1600 IATSize = 0;
1601 while (FunctionNameList[IATSize] != 0L)
1602 {
1603 IATSize++;
1604 }
1605
1606 /* Unprotect the region we are about to write into. */
1607 IATBase = (PVOID)ImportAddressList;
1608 IATSize *= sizeof(PVOID*);
1609 Status = NtProtectVirtualMemory(NtCurrentProcess(),
1610 &IATBase,
1611 &IATSize,
1612 PAGE_READWRITE,
1613 &OldProtect);
1614 if (!NT_SUCCESS(Status))
1615 {
1616 DPRINT1("Failed to unprotect IAT.\n");
1617 return(Status);
1618 }
1619
1620 NTHeaders = RtlImageNtHeader (ImportedModule->DllBase);
1621 Start = (PVOID)NTHeaders->OptionalHeader.ImageBase;
1622 End = (PVOID)((ULONG_PTR)Start + ImportedModule->SizeOfImage);
1623 Offset = (ULONG)((ULONG_PTR)ImportedModule->DllBase - (ULONG_PTR)Start);
1624
1625 /* Walk through function list and fixup addresses. */
1626 while (*FunctionNameList != 0L)
1627 {
1628 if (*ImportAddressList >= Start && *ImportAddressList < End)
1629 {
1630 (*ImportAddressList) = (PVOID)((ULONG_PTR)(*ImportAddressList) + Offset);
1631 }
1632 ImportAddressList++;
1633 FunctionNameList++;
1634 }
1635
1636 /* Protect the region we are about to write into. */
1637 Status = NtProtectVirtualMemory(NtCurrentProcess(),
1638 &IATBase,
1639 &IATSize,
1640 OldProtect,
1641 &OldProtect);
1642 if (!NT_SUCCESS(Status))
1643 {
1644 DPRINT1("Failed to protect IAT.\n");
1645 return(Status);
1646 }
1647 }
1648 ImportModuleDirectory++;
1649 }
1650 return STATUS_SUCCESS;
1651 }
1652
1653
1654 /**********************************************************************
1655 * NAME LOCAL
1656 * LdrFixupImports
1657 *
1658 * DESCRIPTION
1659 * Compute the entry point for every symbol the DLL imports
1660 * from other modules.
1661 *
1662 * ARGUMENTS
1663 *
1664 * RETURN VALUE
1665 *
1666 * REVISIONS
1667 *
1668 * NOTE
1669 *
1670 */
1671 static NTSTATUS
1672 LdrFixupImports(IN PWSTR SearchPath OPTIONAL,
1673 IN PLDR_DATA_TABLE_ENTRY Module)
1674 {
1675 PIMAGE_IMPORT_DESCRIPTOR ImportModuleDirectory;
1676 PIMAGE_IMPORT_DESCRIPTOR ImportModuleDirectoryCurrent;
1677 PIMAGE_BOUND_IMPORT_DESCRIPTOR BoundImportDescriptor;
1678 PIMAGE_BOUND_IMPORT_DESCRIPTOR BoundImportDescriptorCurrent;
1679 PIMAGE_TLS_DIRECTORY TlsDirectory;
1680 ULONG TlsSize = 0;
1681 NTSTATUS Status;
1682 PLDR_DATA_TABLE_ENTRY ImportedModule;
1683 PCHAR ImportedName;
1684 ULONG Size;
1685
1686 DPRINT("LdrFixupImports(SearchPath %S, Module %p)\n", SearchPath, Module);
1687
1688 /* Check for tls data */
1689 TlsDirectory = (PIMAGE_TLS_DIRECTORY)
1690 RtlImageDirectoryEntryToData(Module->DllBase,
1691 TRUE,
1692 IMAGE_DIRECTORY_ENTRY_TLS,
1693 &Size);
1694 if (TlsDirectory)
1695 {
1696 TlsSize = TlsDirectory->EndAddressOfRawData
1697 - TlsDirectory->StartAddressOfRawData
1698 + TlsDirectory->SizeOfZeroFill;
1699 if (TlsSize > 0 &&
1700 NtCurrentPeb()->Ldr->Initialized)
1701 {
1702 TRACE_LDR("Trying to load dynamicly %wZ which contains a tls directory\n",
1703 &Module->BaseDllName);
1704 return STATUS_UNSUCCESSFUL;
1705 }
1706 }
1707 /*
1708 * Process each import module.
1709 */
1710 ImportModuleDirectory = (PIMAGE_IMPORT_DESCRIPTOR)
1711 RtlImageDirectoryEntryToData(Module->DllBase,
1712 TRUE,
1713 IMAGE_DIRECTORY_ENTRY_IMPORT,
1714 &Size);
1715
1716 BoundImportDescriptor = (PIMAGE_BOUND_IMPORT_DESCRIPTOR)
1717 RtlImageDirectoryEntryToData(Module->DllBase,
1718 TRUE,
1719 IMAGE_DIRECTORY_ENTRY_BOUND_IMPORT,
1720 &Size);
1721
1722 if (BoundImportDescriptor != NULL && ImportModuleDirectory == NULL)
1723 {
1724 DPRINT1("%wZ has only a bound import directory\n", &Module->BaseDllName);
1725 return STATUS_UNSUCCESSFUL;
1726 }
1727 if (BoundImportDescriptor)
1728 {
1729 DPRINT("BoundImportDescriptor %p\n", BoundImportDescriptor);
1730
1731 BoundImportDescriptorCurrent = BoundImportDescriptor;
1732 while (BoundImportDescriptorCurrent->OffsetModuleName)
1733 {
1734 ImportedName = (PCHAR)BoundImportDescriptor + BoundImportDescriptorCurrent->OffsetModuleName;
1735 TRACE_LDR("%wZ bound to %s\n", &Module->BaseDllName, ImportedName);
1736 Status = LdrpGetOrLoadModule(SearchPath, ImportedName, &ImportedModule, TRUE);
1737 if (!NT_SUCCESS(Status))
1738 {
1739 DPRINT1("failed to load %s\n", ImportedName);
1740 return Status;
1741 }
1742 if (Module == ImportedModule)
1743 {
1744 LdrpDecrementLoadCount(Module, FALSE);
1745 }
1746 if (ImportedModule->TimeDateStamp != BoundImportDescriptorCurrent->TimeDateStamp)
1747 {
1748 TRACE_LDR("%wZ has stale binding to %wZ\n",
1749 &Module->BaseDllName, &ImportedModule->BaseDllName);
1750 Status = LdrpProcessImportDirectory(Module, ImportedModule, ImportedName);
1751 if (!NT_SUCCESS(Status))
1752 {
1753 DPRINT1("failed to import %s\n", ImportedName);
1754 return Status;
1755 }
1756 }
1757 else
1758 {
1759 BOOLEAN WrongForwarder;
1760 WrongForwarder = FALSE;
1761 if (ImportedModule->Flags & LDRP_IMAGE_NOT_AT_BASE)
1762 {
1763 TRACE_LDR("%wZ has stale binding to %s\n",
1764 &Module->BaseDllName, ImportedName);
1765 }
1766 else
1767 {
1768 TRACE_LDR("%wZ has correct binding to %wZ\n",
1769 &Module->BaseDllName, &ImportedModule->BaseDllName);
1770 }
1771 if (BoundImportDescriptorCurrent->NumberOfModuleForwarderRefs)
1772 {
1773 PIMAGE_BOUND_FORWARDER_REF BoundForwarderRef;
1774 ULONG i;
1775 PLDR_DATA_TABLE_ENTRY ForwarderModule;
1776 PCHAR ForwarderName;
1777
1778 BoundForwarderRef = (PIMAGE_BOUND_FORWARDER_REF)(BoundImportDescriptorCurrent + 1);
1779 for (i = 0; i < BoundImportDescriptorCurrent->NumberOfModuleForwarderRefs; i++, BoundForwarderRef++)
1780 {
1781 ForwarderName = (PCHAR)BoundImportDescriptor + BoundForwarderRef->OffsetModuleName;
1782 TRACE_LDR("%wZ bound to %s via forwardes from %s\n",
1783 &Module->BaseDllName, ForwarderName, ImportedName);
1784 Status = LdrpGetOrLoadModule(SearchPath, ForwarderName, &ForwarderModule, TRUE);
1785 if (!NT_SUCCESS(Status))
1786 {
1787 DPRINT1("failed to load %s\n", ForwarderName);
1788 return Status;
1789 }
1790 if (Module == ImportedModule)
1791 {
1792 LdrpDecrementLoadCount(Module, FALSE);
1793 }
1794 if (ForwarderModule->TimeDateStamp != BoundForwarderRef->TimeDateStamp ||
1795 ForwarderModule->Flags & LDRP_IMAGE_NOT_AT_BASE)
1796 {
1797 TRACE_LDR("%wZ has stale binding to %s\n",
1798 &Module->BaseDllName, ForwarderName);
1799 WrongForwarder = TRUE;
1800 }
1801 else
1802 {
1803 TRACE_LDR("%wZ has correct binding to %s\n",
1804 &Module->BaseDllName, ForwarderName);
1805 }
1806 }
1807 }
1808 if (WrongForwarder ||
1809 ImportedModule->Flags & LDRP_IMAGE_NOT_AT_BASE)
1810 {
1811 Status = LdrpProcessImportDirectory(Module, ImportedModule, ImportedName);
1812 if (!NT_SUCCESS(Status))
1813 {
1814 DPRINT1("failed to import %s\n", ImportedName);
1815 return Status;
1816 }
1817 }
1818 else if (ImportedModule->Flags & LDRP_IMAGE_NOT_AT_BASE)
1819 {
1820 TRACE_LDR("Adjust imports for %s from %wZ\n",
1821 ImportedName, &Module->BaseDllName);
1822 Status = LdrpAdjustImportDirectory(Module, ImportedModule, ImportedName);
1823 if (!NT_SUCCESS(Status))
1824 {
1825 DPRINT1("failed to adjust import entries for %s\n", ImportedName);
1826 return Status;
1827 }
1828 }
1829 else if (WrongForwarder)
1830 {
1831 /*
1832 * FIXME:
1833 * Update only forwarders
1834 */
1835 TRACE_LDR("Stale BIND %s from %wZ\n",
1836 ImportedName, &Module->BaseDllName);
1837 Status = LdrpProcessImportDirectory(Module, ImportedModule, ImportedName);
1838 if (!NT_SUCCESS(Status))
1839 {
1840 DPRINT1("faild to import %s\n", ImportedName);
1841 return Status;
1842 }
1843 }
1844 else
1845 {
1846 /* nothing to do */
1847 }
1848 }
1849 BoundImportDescriptorCurrent += BoundImportDescriptorCurrent->NumberOfModuleForwarderRefs + 1;
1850 }
1851 }
1852 else if (ImportModuleDirectory)
1853 {
1854 DPRINT("ImportModuleDirectory %p\n", ImportModuleDirectory);
1855
1856 ImportModuleDirectoryCurrent = ImportModuleDirectory;
1857 while (ImportModuleDirectoryCurrent->Name)
1858 {
1859 ImportedName = (PCHAR)Module->DllBase + ImportModuleDirectoryCurrent->Name;
1860 TRACE_LDR("%wZ imports functions from %s\n", &Module->BaseDllName, ImportedName);
1861
1862 Status = LdrpGetOrLoadModule(SearchPath, ImportedName, &ImportedModule, TRUE);
1863 if (!NT_SUCCESS(Status))
1864 {
1865 DPRINT1("failed to load %s\n", ImportedName);
1866 return Status;
1867 }
1868 if (Module == ImportedModule)
1869 {
1870 LdrpDecrementLoadCount(Module, FALSE);
1871 }
1872
1873 TRACE_LDR("Initializing imports for %wZ from %s\n",
1874 &Module->BaseDllName, ImportedName);
1875 Status = LdrpProcessImportDirectoryEntry(Module, ImportedModule, ImportModuleDirectoryCurrent);
1876 if (!NT_SUCCESS(Status))
1877 {
1878 DPRINT1("failed to import %s\n", ImportedName);
1879 return Status;
1880 }
1881 ImportModuleDirectoryCurrent++;
1882 }
1883 }
1884
1885 if (TlsDirectory && TlsSize > 0)
1886 {
1887 LdrpAcquireTlsSlot(Module, TlsSize, FALSE);
1888 }
1889
1890 return STATUS_SUCCESS;
1891 }
1892
1893
1894 /**********************************************************************
1895 * NAME
1896 * LdrPEStartup
1897 *
1898 * DESCRIPTION
1899 * 1. Relocate, if needed the EXE.
1900 * 2. Fixup any imported symbol.
1901 * 3. Compute the EXE's entry point.
1902 *
1903 * ARGUMENTS
1904 * ImageBase
1905 * Address at which the EXE's image
1906 * is loaded.
1907 *
1908 * SectionHandle
1909 * Handle of the section that contains
1910 * the EXE's image.
1911 *
1912 * RETURN VALUE
1913 * NULL on error; otherwise the entry point
1914 * to call for initializing the DLL.
1915 *
1916 * REVISIONS
1917 *
1918 * NOTE
1919 * 04.01.2004 hb Previous this function was used for all images (dll + exe).
1920 * Currently the function is only used for the exe.
1921 */
1922 PEPFUNC LdrPEStartup (PVOID ImageBase,
1923 HANDLE SectionHandle,
1924 PLDR_DATA_TABLE_ENTRY* Module,
1925 PWSTR FullDosName)
1926 {
1927 NTSTATUS Status;
1928 PEPFUNC EntryPoint = NULL;
1929 PIMAGE_DOS_HEADER DosHeader;
1930 PIMAGE_NT_HEADERS NTHeaders;
1931 PLDR_DATA_TABLE_ENTRY tmpModule;
1932
1933 DPRINT("LdrPEStartup(ImageBase %p SectionHandle %p)\n",
1934 ImageBase, SectionHandle);
1935
1936 /*
1937 * Overlay DOS and WNT headers structures
1938 * to the DLL's image.
1939 */
1940 DosHeader = (PIMAGE_DOS_HEADER) ImageBase;
1941 NTHeaders = (PIMAGE_NT_HEADERS) ((ULONG_PTR)ImageBase + DosHeader->e_lfanew);
1942
1943 /*
1944 * If the base address is different from the
1945 * one the DLL is actually loaded, perform any
1946 * relocation.
1947 */
1948 if (ImageBase != (PVOID) NTHeaders->OptionalHeader.ImageBase)
1949 {
1950 DPRINT("LDR: Performing relocations\n");
1951 Status = LdrPerformRelocations(NTHeaders, ImageBase);
1952 if (!NT_SUCCESS(Status))
1953 {
1954 DPRINT1("LdrPerformRelocations() failed\n");
1955 return NULL;
1956 }
1957 }
1958
1959 if (Module != NULL)
1960 {
1961 *Module = LdrAddModuleEntry(ImageBase, NTHeaders, FullDosName);
1962 (*Module)->SectionPointer = SectionHandle;
1963 }
1964 else
1965 {
1966 Module = &tmpModule;
1967 Status = LdrFindEntryForAddress(ImageBase, Module);
1968 if (!NT_SUCCESS(Status))
1969 {
1970 return NULL;
1971 }
1972 }
1973
1974 if (ImageBase != (PVOID) NTHeaders->OptionalHeader.ImageBase)
1975 {
1976 (*Module)->Flags |= LDRP_IMAGE_NOT_AT_BASE;
1977 }
1978
1979 /*
1980 * If the DLL's imports symbols from other
1981 * modules, fixup the imported calls entry points.
1982 */
1983 DPRINT("About to fixup imports\n");
1984 Status = LdrFixupImports(NULL, *Module);
1985 if (!NT_SUCCESS(Status))
1986 {
1987 DPRINT1("LdrFixupImports() failed for %wZ\n", &(*Module)->BaseDllName);
1988 return NULL;
1989 }
1990 DPRINT("Fixup done\n");
1991 RtlEnterCriticalSection(NtCurrentPeb()->LoaderLock);
1992 Status = LdrpInitializeTlsForProccess();
1993 if (NT_SUCCESS(Status))
1994 {
1995 Status = LdrpAttachProcess();
1996 }
1997 if (NT_SUCCESS(Status))
1998 {
1999 LdrpTlsCallback(*Module, DLL_PROCESS_ATTACH);
2000 }
2001
2002
2003 RtlLeaveCriticalSection(NtCurrentPeb()->LoaderLock);
2004 if (!NT_SUCCESS(Status))
2005 {
2006 return NULL;
2007 }
2008
2009 /*
2010 * Compute the DLL's entry point's address.
2011 */
2012 DPRINT("ImageBase = %p\n", ImageBase);
2013 DPRINT("AddressOfEntryPoint = 0x%lx\n",(ULONG)NTHeaders->OptionalHeader.AddressOfEntryPoint);
2014 if (NTHeaders->OptionalHeader.AddressOfEntryPoint != 0)
2015 {
2016 EntryPoint = (PEPFUNC) ((ULONG_PTR)ImageBase
2017 + NTHeaders->OptionalHeader.AddressOfEntryPoint);
2018 }
2019 DPRINT("LdrPEStartup() = %p\n",EntryPoint);
2020 return EntryPoint;
2021 }
2022
2023 static NTSTATUS
2024 LdrpLoadModule(IN PWSTR SearchPath OPTIONAL,
2025 IN ULONG LoadFlags,
2026 IN PUNICODE_STRING Name,
2027 PLDR_DATA_TABLE_ENTRY *Module,
2028 PVOID *BaseAddress OPTIONAL)
2029 {
2030 UNICODE_STRING AdjustedName;
2031 UNICODE_STRING FullDosName;
2032 NTSTATUS Status;
2033 PLDR_DATA_TABLE_ENTRY tmpModule;
2034 HANDLE SectionHandle;
2035 SIZE_T ViewSize;
2036 PVOID ImageBase;
2037 PIMAGE_NT_HEADERS NtHeaders;
2038 BOOLEAN MappedAsDataFile;
2039 PVOID ArbitraryUserPointer;
2040
2041 if (Module == NULL)
2042 {
2043 Module = &tmpModule;
2044 }
2045 /* adjust the full dll name */
2046 LdrAdjustDllName(&AdjustedName, Name, FALSE);
2047
2048 DPRINT("%wZ\n", &AdjustedName);
2049
2050 MappedAsDataFile = FALSE;
2051 /* Test if dll is already loaded */
2052 Status = LdrFindEntryForName(&AdjustedName, Module, TRUE);
2053 if (NT_SUCCESS(Status))
2054 {
2055 RtlFreeUnicodeString(&AdjustedName);
2056 if (NULL != BaseAddress)
2057 {
2058 *BaseAddress = (*Module)->DllBase;
2059 }
2060 }
2061 else
2062 {
2063 /* Open or create dll image section */
2064 Status = LdrpMapKnownDll(&AdjustedName, &FullDosName, &SectionHandle);
2065 if (!NT_SUCCESS(Status))
2066 {
2067 MappedAsDataFile = (0 != (LoadFlags & LOAD_LIBRARY_AS_DATAFILE));
2068 Status = LdrpMapDllImageFile(SearchPath, &AdjustedName, &FullDosName,
2069 MappedAsDataFile, &SectionHandle);
2070 }
2071 if (!NT_SUCCESS(Status))
2072 {
2073 DPRINT1("Failed to create or open dll section of '%wZ' (Status %lx)\n", &AdjustedName, Status);
2074 RtlFreeUnicodeString(&AdjustedName);
2075 return Status;
2076 }
2077 RtlFreeUnicodeString(&AdjustedName);
2078 /* Map the dll into the process */
2079 ViewSize = 0;
2080 ImageBase = 0;
2081 ArbitraryUserPointer = NtCurrentTeb()->Tib.ArbitraryUserPointer;
2082 NtCurrentTeb()->Tib.ArbitraryUserPointer = FullDosName.Buffer;
2083 Status = NtMapViewOfSection(SectionHandle,
2084 NtCurrentProcess(),
2085 &ImageBase,
2086 0,
2087 0,
2088 NULL,
2089 &ViewSize,
2090 ViewShare,
2091 0,
2092 PAGE_READONLY);
2093 NtCurrentTeb()->Tib.ArbitraryUserPointer = ArbitraryUserPointer;
2094 if (!NT_SUCCESS(Status))
2095 {
2096 DPRINT1("map view of section failed (Status 0x%08lx)\n", Status);
2097 RtlFreeUnicodeString(&FullDosName);
2098 NtClose(SectionHandle);
2099 return(Status);
2100 }
2101 if (NULL != BaseAddress)
2102 {
2103 *BaseAddress = ImageBase;
2104 }
2105 if (!MappedAsDataFile)
2106 {
2107 /* Get and check the NT headers */
2108 NtHeaders = RtlImageNtHeader(ImageBase);
2109 if (NtHeaders == NULL)
2110 {
2111 DPRINT1("RtlImageNtHeaders() failed\n");
2112 NtUnmapViewOfSection (NtCurrentProcess (), ImageBase);
2113 NtClose (SectionHandle);
2114 RtlFreeUnicodeString(&FullDosName);
2115 return STATUS_UNSUCCESSFUL;
2116 }
2117 }
2118 DPRINT("Mapped %wZ at %x\n", &FullDosName, ImageBase);
2119 if (MappedAsDataFile)
2120 {
2121 ASSERT(NULL != BaseAddress);
2122 if (NULL != BaseAddress)
2123 {
2124 *BaseAddress = (PVOID) ((char *) *BaseAddress + 1);
2125 }
2126 *Module = NULL;
2127 RtlFreeUnicodeString(&FullDosName);
2128 NtClose(SectionHandle);
2129 return STATUS_SUCCESS;
2130 }
2131 /* If the base address is different from the
2132 * one the DLL is actually loaded, perform any
2133 * relocation. */
2134 if (ImageBase != (PVOID) NtHeaders->OptionalHeader.ImageBase)
2135 {
2136 DPRINT1("Relocating (%lx -> %p) %wZ\n",
2137 NtHeaders->OptionalHeader.ImageBase, ImageBase, &FullDosName);
2138 Status = LdrPerformRelocations(NtHeaders, ImageBase);
2139 if (!NT_SUCCESS(Status))
2140 {
2141 DPRINT1("LdrPerformRelocations() failed\n");
2142 NtUnmapViewOfSection (NtCurrentProcess (), ImageBase);
2143 NtClose (SectionHandle);
2144 RtlFreeUnicodeString(&FullDosName);
2145 return STATUS_UNSUCCESSFUL;
2146 }
2147 }
2148 *Module = LdrAddModuleEntry(ImageBase, NtHeaders, FullDosName.Buffer);
2149 (*Module)->SectionPointer = SectionHandle;
2150 if (ImageBase != (PVOID) NtHeaders->OptionalHeader.ImageBase)
2151 {
2152 (*Module)->Flags |= LDRP_IMAGE_NOT_AT_BASE;
2153 }
2154 if (NtHeaders->FileHeader.Characteristics & IMAGE_FILE_DLL)
2155 {
2156 (*Module)->Flags |= LDRP_IMAGE_DLL;
2157 }
2158 /* fixup the imported calls entry points */
2159 Status = LdrFixupImports(SearchPath, *Module);
2160 if (!NT_SUCCESS(Status))
2161 {
2162 DPRINT1("LdrFixupImports failed for %wZ, status=%x\n", &(*Module)->BaseDllName, Status);
2163 return Status;
2164 }
2165 #if defined(DBG) || defined(KDBG)
2166 LdrpLoadUserModuleSymbols(*Module);
2167 #endif /* DBG || KDBG */
2168 RtlEnterCriticalSection(NtCurrentPeb()->LoaderLock);
2169 InsertTailList(&NtCurrentPeb()->Ldr->InInitializationOrderModuleList,
2170 &(*Module)->InInitializationOrderModuleList);
2171 RtlLeaveCriticalSection (NtCurrentPeb()->LoaderLock);
2172 }
2173 return STATUS_SUCCESS;
2174 }
2175
2176 static NTSTATUS
2177 LdrpUnloadModule(PLDR_DATA_TABLE_ENTRY Module,
2178 BOOLEAN Unload)
2179 {
2180 PIMAGE_IMPORT_DESCRIPTOR ImportModuleDirectory;
2181 PIMAGE_BOUND_IMPORT_DESCRIPTOR BoundImportDescriptor;
2182 PIMAGE_BOUND_IMPORT_DESCRIPTOR BoundImportDescriptorCurrent;
2183 PCHAR ImportedName;
2184 PLDR_DATA_TABLE_ENTRY ImportedModule;
2185 NTSTATUS Status;
2186 LONG LoadCount;
2187 ULONG Size;
2188
2189 if (Unload)
2190 {
2191 RtlEnterCriticalSection(NtCurrentPeb()->LoaderLock);
2192 }
2193
2194 LoadCount = LdrpDecrementLoadCount(Module, Unload);
2195
2196 TRACE_LDR("Unload %wZ, LoadCount %d\n", &Module->BaseDllName, LoadCount);
2197
2198 if (LoadCount == 0)
2199 {
2200 /* ?????????????????? */
2201 }
2202 else if (!(Module->Flags & LDRP_STATIC_LINK) && LoadCount == 1)
2203 {
2204 BoundImportDescriptor = (PIMAGE_BOUND_IMPORT_DESCRIPTOR)
2205 RtlImageDirectoryEntryToData(Module->DllBase,
2206 TRUE,
2207 IMAGE_DIRECTORY_ENTRY_BOUND_IMPORT,
2208 &Size);
2209 if (BoundImportDescriptor)
2210 {
2211 /* dereferencing all imported modules, use the bound import descriptor */
2212 BoundImportDescriptorCurrent = BoundImportDescriptor;
2213 while (BoundImportDescriptorCurrent->OffsetModuleName)
2214 {
2215 ImportedName = (PCHAR)BoundImportDescriptor + BoundImportDescriptorCurrent->OffsetModuleName;
2216 TRACE_LDR("%wZ trys to unload %s\n", &Module->BaseDllName, ImportedName);
2217 Status = LdrpGetOrLoadModule(NULL, ImportedName, &ImportedModule, FALSE);
2218 if (!NT_SUCCESS(Status))
2219 {
2220 DPRINT1("unable to found imported modul %s\n", ImportedName);
2221 }
2222 else
2223 {
2224 if (Module != ImportedModule)
2225 {
2226 Status = LdrpUnloadModule(ImportedModule, FALSE);
2227 if (!NT_SUCCESS(Status))
2228 {
2229 DPRINT1("unable to unload %s\n", ImportedName);
2230 }
2231 }
2232 }
2233 BoundImportDescriptorCurrent++;
2234 }
2235 }
2236 else
2237 {
2238 ImportModuleDirectory = (PIMAGE_IMPORT_DESCRIPTOR)
2239 RtlImageDirectoryEntryToData(Module->DllBase,
2240 TRUE,
2241 IMAGE_DIRECTORY_ENTRY_IMPORT,
2242 &Size);
2243 if (ImportModuleDirectory)
2244 {
2245 /* dereferencing all imported modules, use the import descriptor */
2246 while (ImportModuleDirectory->Name)
2247 {
2248 ImportedName = (PCHAR)Module->DllBase + ImportModuleDirectory->Name;
2249 TRACE_LDR("%wZ trys to unload %s\n", &Module->BaseDllName, ImportedName);
2250 Status = LdrpGetOrLoadModule(NULL, ImportedName, &ImportedModule, FALSE);
2251 if (!NT_SUCCESS(Status))
2252 {
2253 DPRINT1("unable to found imported modul %s\n", ImportedName);
2254 }
2255 else
2256 {
2257 if (Module != ImportedModule)
2258 {
2259 Status = LdrpUnloadModule(ImportedModule, FALSE);
2260 if (!NT_SUCCESS(Status))
2261 {
2262 DPRINT1("unable to unload %s\n", ImportedName);
2263 }
2264 }
2265 }
2266 ImportModuleDirectory++;
2267 }
2268 }
2269 }
2270 }
2271
2272 if (Unload)
2273 {
2274 if (!(Module->Flags & LDRP_STATIC_LINK))
2275 {
2276 LdrpDetachProcess(FALSE);
2277 }
2278
2279 RtlLeaveCriticalSection (NtCurrentPeb()->LoaderLock);
2280 }
2281 return STATUS_SUCCESS;
2282
2283 }
2284
2285 /*
2286 * @implemented
2287 */
2288 NTSTATUS NTAPI
2289 LdrUnloadDll (IN PVOID BaseAddress)
2290 {
2291 PLDR_DATA_TABLE_ENTRY Module;
2292 NTSTATUS Status;
2293
2294 if (BaseAddress == NULL)
2295 return STATUS_SUCCESS;
2296
2297 if (LdrMappedAsDataFile(&BaseAddress))
2298 {
2299 Status = NtUnmapViewOfSection(NtCurrentProcess(), BaseAddress);
2300 }
2301 else
2302 {
2303 Status = LdrFindEntryForAddress(BaseAddress, &Module);
2304 if (NT_SUCCESS(Status))
2305 {
2306 TRACE_LDR("LdrUnloadDll, , unloading %wZ\n", &Module->BaseDllName);
2307 Status = LdrpUnloadModule(Module, TRUE);
2308 }
2309 }
2310
2311 return Status;
2312 }
2313
2314 /*
2315 * @implemented
2316 */
2317 NTSTATUS NTAPI
2318 LdrDisableThreadCalloutsForDll(IN PVOID BaseAddress)
2319 {
2320 PLIST_ENTRY ModuleListHead;
2321 PLIST_ENTRY Entry;
2322 PLDR_DATA_TABLE_ENTRY Module;
2323 NTSTATUS Status;
2324
2325 DPRINT("LdrDisableThreadCalloutsForDll (BaseAddress %p)\n", BaseAddress);
2326
2327 Status = STATUS_DLL_NOT_FOUND;
2328 RtlEnterCriticalSection (NtCurrentPeb()->LoaderLock);
2329 ModuleListHead = &NtCurrentPeb()->Ldr->InLoadOrderModuleList;
2330 Entry = ModuleListHead->Flink;
2331 while (Entry != ModuleListHead)
2332 {
2333 Module = CONTAINING_RECORD(Entry, LDR_DATA_TABLE_ENTRY, InLoadOrderLinks);
2334
2335 DPRINT("BaseDllName %wZ BaseAddress %p\n", &Module->BaseDllName, Module->DllBase);
2336
2337 if (Module->DllBase == BaseAddress)
2338 {
2339 if (Module->TlsIndex == 0xFFFF)
2340 {
2341 Module->Flags |= LDRP_DONT_CALL_FOR_THREADS;
2342 Status = STATUS_SUCCESS;
2343 }
2344 break;
2345 }
2346 Entry = Entry->Flink;
2347 }
2348 RtlLeaveCriticalSection (NtCurrentPeb()->LoaderLock);
2349 return Status;
2350 }
2351
2352 /*
2353 * @implemented
2354 */
2355 NTSTATUS NTAPI
2356 LdrGetDllHandle(IN PWSTR DllPath OPTIONAL,
2357 IN PULONG DllCharacteristics,
2358 IN PUNICODE_STRING DllName,
2359 OUT PVOID *DllHandle)
2360 {
2361 PLDR_DATA_TABLE_ENTRY Module;
2362 NTSTATUS Status;
2363
2364 TRACE_LDR("LdrGetDllHandle, searching for %wZ from %S\n",
2365 DllName, DllPath ? DllPath : L"");
2366
2367 /* NULL is the current executable */
2368 if (DllName == NULL)
2369 {
2370 *DllHandle = ExeModule->DllBase;
2371 DPRINT("BaseAddress 0x%lx\n", *DllHandle);
2372 return STATUS_SUCCESS;
2373 }
2374
2375 Status = LdrFindEntryForName(DllName, &Module, FALSE);
2376 if (NT_SUCCESS(Status))
2377 {
2378 *DllHandle = Module->DllBase;
2379 return STATUS_SUCCESS;
2380 }
2381
2382 DPRINT("Failed to find dll %wZ\n", DllName);
2383 *DllHandle = NULL;
2384 return STATUS_DLL_NOT_FOUND;
2385 }
2386
2387 /*
2388 * @implemented
2389 */
2390 NTSTATUS NTAPI
2391 LdrAddRefDll(IN ULONG Flags,
2392 IN PVOID BaseAddress)
2393 {
2394 PLIST_ENTRY ModuleListHead;
2395 PLIST_ENTRY Entry;
2396 PLDR_DATA_TABLE_ENTRY Module;
2397 NTSTATUS Status;
2398
2399 if (Flags & ~(LDR_PIN_MODULE))
2400 {
2401 return STATUS_INVALID_PARAMETER;
2402 }
2403
2404 Status = STATUS_DLL_NOT_FOUND;
2405 RtlEnterCriticalSection (NtCurrentPeb()->LoaderLock);
2406 ModuleListHead = &NtCurrentPeb()->Ldr->InLoadOrderModuleList;
2407 Entry = ModuleListHead->Flink;
2408 while (Entry != ModuleListHead)
2409 {
2410 Module = CONTAINING_RECORD(Entry, LDR_DATA_TABLE_ENTRY, InLoadOrderLinks);
2411
2412 if (Module->DllBase == BaseAddress)
2413 {
2414 if (Flags & LDR_PIN_MODULE)
2415 {
2416 Module->Flags |= LDRP_STATIC_LINK;
2417 }
2418 else
2419 {
2420 LdrpIncrementLoadCount(Module,
2421 FALSE);
2422 }
2423 Status = STATUS_SUCCESS;
2424 break;
2425 }
2426 Entry = Entry->Flink;
2427 }
2428 RtlLeaveCriticalSection (NtCurrentPeb()->LoaderLock);
2429 return Status;
2430 }
2431
2432 /*
2433 * @implemented
2434 */
2435 PVOID NTAPI
2436 RtlPcToFileHeader(IN PVOID PcValue,
2437 PVOID* BaseOfImage)
2438 {
2439 PLIST_ENTRY ModuleListHead;
2440 PLIST_ENTRY Entry;
2441 PLDR_DATA_TABLE_ENTRY Module;
2442 PVOID ImageBase = NULL;
2443
2444 RtlEnterCriticalSection (NtCurrentPeb()->LoaderLock);
2445 ModuleListHead = &NtCurrentPeb()->Ldr->InLoadOrderModuleList;
2446 Entry = ModuleListHead->Flink;
2447 while (Entry != ModuleListHead)
2448 {
2449 Module = CONTAINING_RECORD(Entry, LDR_DATA_TABLE_ENTRY, InLoadOrderLinks);
2450
2451 if ((ULONG_PTR)PcValue >= (ULONG_PTR)Module->DllBase &&
2452 (ULONG_PTR)PcValue < (ULONG_PTR)Module->DllBase + Module->SizeOfImage)
2453 {
2454 ImageBase = Module->DllBase;
2455 break;
2456 }
2457 Entry = Entry->Flink;
2458 }
2459 RtlLeaveCriticalSection (NtCurrentPeb()->LoaderLock);
2460
2461 *BaseOfImage = ImageBase;
2462 return ImageBase;
2463 }
2464
2465 /*
2466 * @implemented
2467 */
2468 NTSTATUS NTAPI
2469 LdrGetProcedureAddress (IN PVOID BaseAddress,
2470 IN PANSI_STRING Name,
2471 IN ULONG Ordinal,
2472 OUT PVOID *ProcedureAddress)
2473 {
2474 if (Name && Name->Length)
2475 {
2476 TRACE_LDR("LdrGetProcedureAddress by NAME - %Z\n", Name);
2477 }
2478 else
2479 {
2480 TRACE_LDR("LdrGetProcedureAddress by ORDINAL - %d\n", Ordinal);
2481 }
2482
2483 DPRINT("LdrGetProcedureAddress (BaseAddress %p Name %Z Ordinal %lu ProcedureAddress %p)\n",
2484 BaseAddress, Name, Ordinal, ProcedureAddress);
2485
2486 if (Name && Name->Length)
2487 {
2488 /* by name */
2489 *ProcedureAddress = LdrGetExportByName(BaseAddress, (PUCHAR)Name->Buffer, 0xffff);
2490 if (*ProcedureAddress != NULL)
2491 {
2492 return STATUS_SUCCESS;
2493 }
2494 DPRINT("LdrGetProcedureAddress: Can't resolve symbol '%Z'\n", Name);
2495 }
2496 else
2497 {
2498 /* by ordinal */
2499 Ordinal &= 0x0000FFFF;
2500 *ProcedureAddress = LdrGetExportByOrdinal(BaseAddress, (WORD)Ordinal);
2501 if (*ProcedureAddress)
2502 {
2503 return STATUS_SUCCESS;
2504 }
2505 DPRINT("LdrGetProcedureAddress: Can't resolve symbol @%lu\n", Ordinal);
2506 }
2507 return STATUS_PROCEDURE_NOT_FOUND;
2508 }
2509
2510 /**********************************************************************
2511 * NAME LOCAL
2512 * LdrpDetachProcess
2513 *
2514 * DESCRIPTION
2515 * Unload dll's which are no longer referenced from others dll's
2516 *
2517 * ARGUMENTS
2518 * none
2519 *
2520 * RETURN VALUE
2521 * none
2522 *
2523 * REVISIONS
2524 *
2525 * NOTE
2526 * The loader lock must be held on enty.
2527 */
2528 static VOID
2529 LdrpDetachProcess(BOOLEAN UnloadAll)
2530 {
2531 PLIST_ENTRY ModuleListHead;
2532 PLIST_ENTRY Entry;
2533 PLDR_DATA_TABLE_ENTRY Module;
2534 static ULONG CallingCount = 0;
2535
2536 DPRINT("LdrpDetachProcess() called for %wZ\n",
2537 &ExeModule->BaseDllName);
2538
2539 if (UnloadAll)
2540 LdrpDllShutdownInProgress = TRUE;
2541
2542 CallingCount++;
2543
2544 ModuleListHead = &NtCurrentPeb()->Ldr->InInitializationOrderModuleList;
2545 Entry = ModuleListHead->Blink;
2546 while (Entry != ModuleListHead)
2547 {
2548 Module = CONTAINING_RECORD(Entry, LDR_DATA_TABLE_ENTRY, InInitializationOrderModuleList);
2549 if (((UnloadAll && Module->LoadCount == 0xFFFF) || Module->LoadCount == 0) &&
2550 Module->Flags & LDRP_ENTRY_PROCESSED &&
2551 !(Module->Flags & LDRP_UNLOAD_IN_PROGRESS))
2552 {
2553 Module->Flags |= LDRP_UNLOAD_IN_PROGRESS;
2554 if (Module == LdrpLastModule)
2555 {
2556 LdrpLastModule = NULL;
2557 }
2558 if (Module->Flags & LDRP_PROCESS_ATTACH_CALLED)
2559 {
2560 TRACE_LDR("Unload %wZ - Calling entry point at %x\n",
2561 &Module->BaseDllName, Module->EntryPoint);
2562 LdrpCallDllEntry(Module, DLL_PROCESS_DETACH, (PVOID)(Module->LoadCount == 0xFFFF ? 1 : 0));
2563 }
2564 else
2565 {
2566 TRACE_LDR("Unload %wZ\n", &Module->BaseDllName);
2567 }
2568 Entry = ModuleListHead->Blink;
2569 }
2570 else
2571 {
2572 Entry = Entry->Blink;
2573 }
2574 }
2575
2576 if (CallingCount == 1)
2577 {
2578 Entry = ModuleListHead->Blink;
2579 while (Entry != ModuleListHead)
2580 {
2581 Module = CONTAINING_RECORD(Entry, LDR_DATA_TABLE_ENTRY, InInitializationOrderModuleList);
2582 Entry = Entry->Blink;
2583 if (Module->Flags & LDRP_UNLOAD_IN_PROGRESS &&
2584 ((UnloadAll && Module->LoadCount != 0xFFFF) || Module->LoadCount == 0))
2585 {
2586 /* remove the module entry from the list */
2587 RemoveEntryList (&Module->InLoadOrderLinks);
2588 RemoveEntryList (&Module->InInitializationOrderModuleList);
2589
2590 NtUnmapViewOfSection (NtCurrentProcess (), Module->DllBase);
2591 NtClose (Module->SectionPointer);
2592
2593 TRACE_LDR("%wZ unloaded\n", &Module->BaseDllName);
2594
2595 RtlFreeUnicodeString (&Module->FullDllName);
2596 RtlFreeUnicodeString (&Module->BaseDllName);
2597
2598 RtlFreeHeap (RtlGetProcessHeap (), 0, Module);
2599 }
2600 }
2601 }
2602 CallingCount--;
2603 DPRINT("LdrpDetachProcess() done\n");
2604 }
2605
2606 /**********************************************************************
2607 * NAME LOCAL
2608 * LdrpAttachProcess
2609 *
2610 * DESCRIPTION
2611 * Initialize all dll's which are prepered for loading
2612 *
2613 * ARGUMENTS
2614 * none
2615 *
2616 * RETURN VALUE
2617 * status
2618 *
2619 * REVISIONS
2620 *
2621 * NOTE
2622 * The loader lock must be held on entry.
2623 *
2624 */
2625 static NTSTATUS
2626 LdrpAttachProcess(VOID)
2627 {
2628 PLIST_ENTRY ModuleListHead;
2629 PLIST_ENTRY Entry;
2630 PLDR_DATA_TABLE_ENTRY Module;
2631 BOOLEAN Result;
2632 NTSTATUS Status = STATUS_SUCCESS;
2633
2634 DPRINT("LdrpAttachProcess() called for %wZ\n",
2635 &ExeModule->BaseDllName);
2636
2637 ModuleListHead = &NtCurrentPeb()->Ldr->InInitializationOrderModuleList;
2638 Entry = ModuleListHead->Flink;
2639 while (Entry != ModuleListHead)
2640 {
2641 Module = CONTAINING_RECORD(Entry, LDR_DATA_TABLE_ENTRY, InInitializationOrderModuleList);
2642 if (!(Module->Flags & (LDRP_LOAD_IN_PROGRESS|LDRP_UNLOAD_IN_PROGRESS|LDRP_ENTRY_PROCESSED)))
2643 {
2644 Module->Flags |= LDRP_LOAD_IN_PROGRESS;
2645 TRACE_LDR("%wZ loaded - Calling init routine at %x for process attaching\n",
2646 &Module->BaseDllName, Module->EntryPoint);
2647 Result = LdrpCallDllEntry(Module, DLL_PROCESS_ATTACH, (PVOID)(Module->LoadCount == 0xFFFF ? 1 : 0));
2648 if (!Result)
2649 {
2650 Status = STATUS_DLL_INIT_FAILED;
2651 break;
2652 }
2653 if (Module->Flags & LDRP_IMAGE_DLL && Module->EntryPoint != 0)
2654 {
2655 Module->Flags |= LDRP_PROCESS_ATTACH_CALLED|LDRP_ENTRY_PROCESSED;
2656 }
2657 else
2658 {
2659 Module->Flags |= LDRP_ENTRY_PROCESSED;
2660 }
2661 Module->Flags &= ~LDRP_LOAD_IN_PROGRESS;
2662 }
2663 Entry = Entry->Flink;
2664 }
2665
2666 DPRINT("LdrpAttachProcess() done\n");
2667
2668 return Status;
2669 }
2670
2671 /*
2672 * @implemented
2673 */
2674 BOOLEAN NTAPI
2675 RtlDllShutdownInProgress (VOID)
2676 {
2677 return LdrpDllShutdownInProgress;
2678 }
2679
2680 /*
2681 * @implemented
2682 */
2683 NTSTATUS NTAPI
2684 LdrShutdownProcess (VOID)
2685 {
2686 LdrpDetachProcess(TRUE);
2687 return STATUS_SUCCESS;
2688 }
2689
2690 /*
2691 * @implemented
2692 */
2693
2694 NTSTATUS
2695 LdrpAttachThread (VOID)
2696 {
2697 PLIST_ENTRY ModuleListHead;
2698 PLIST_ENTRY Entry;
2699 PLDR_DATA_TABLE_ENTRY Module;
2700 NTSTATUS Status;
2701
2702 DPRINT("LdrpAttachThread() called for %wZ\n",
2703 &ExeModule->BaseDllName);
2704
2705 RtlEnterCriticalSection (NtCurrentPeb()->LoaderLock);
2706
2707 Status = LdrpInitializeTlsForThread();
2708
2709 if (NT_SUCCESS(Status))
2710 {
2711 ModuleListHead = &NtCurrentPeb()->Ldr->InInitializationOrderModuleList;
2712 Entry = ModuleListHead->Flink;
2713
2714 while (Entry != ModuleListHead)
2715 {
2716 Module = CONTAINING_RECORD(Entry, LDR_DATA_TABLE_ENTRY, InInitializationOrderModuleList);
2717 if (Module->Flags & LDRP_PROCESS_ATTACH_CALLED &&
2718 !(Module->Flags & LDRP_DONT_CALL_FOR_THREADS) &&
2719 !(Module->Flags & LDRP_UNLOAD_IN_PROGRESS))
2720 {
2721 TRACE_LDR("%wZ - Calling entry point at %x for thread attaching\n",
2722 &Module->BaseDllName, Module->EntryPoint);
2723 LdrpCallDllEntry(Module, DLL_THREAD_ATTACH, NULL);
2724 }
2725 Entry = Entry->Flink;
2726 }
2727
2728 Entry = NtCurrentPeb()->Ldr->InLoadOrderModuleList.Flink;
2729 Module = CONTAINING_RECORD(Entry, LDR_DATA_TABLE_ENTRY, InLoadOrderLinks);
2730 LdrpTlsCallback(Module, DLL_THREAD_ATTACH);
2731 }
2732
2733 RtlLeaveCriticalSection (NtCurrentPeb()->LoaderLock);
2734
2735 DPRINT("LdrpAttachThread() done\n");
2736
2737 return Status;
2738 }
2739
2740
2741 /*
2742 * @implemented
2743 */
2744 NTSTATUS NTAPI
2745 LdrShutdownThread (VOID)
2746 {
2747 PLIST_ENTRY ModuleListHead;
2748 PLIST_ENTRY Entry;
2749 PLDR_DATA_TABLE_ENTRY Module;
2750
2751 DPRINT("LdrShutdownThread() called for %wZ\n",
2752 &ExeModule->BaseDllName);
2753
2754 RtlEnterCriticalSection (NtCurrentPeb()->LoaderLock);
2755
2756 ModuleListHead = &NtCurrentPeb()->Ldr->InInitializationOrderModuleList;
2757 Entry = ModuleListHead->Blink;
2758 while (Entry != ModuleListHead)
2759 {
2760 Module = CONTAINING_RECORD(Entry, LDR_DATA_TABLE_ENTRY, InInitializationOrderModuleList);
2761
2762 if (Module->Flags & LDRP_PROCESS_ATTACH_CALLED &&
2763 !(Module->Flags & LDRP_DONT_CALL_FOR_THREADS) &&
2764 !(Module->Flags & LDRP_UNLOAD_IN_PROGRESS))
2765 {
2766 TRACE_LDR("%wZ - Calling entry point at %x for thread detaching\n",
2767 &Module->BaseDllName, Module->EntryPoint);
2768 LdrpCallDllEntry(Module, DLL_THREAD_DETACH, NULL);
2769 }
2770 Entry = Entry->Blink;
2771 }
2772
2773 RtlLeaveCriticalSection (NtCurrentPeb()->LoaderLock);
2774
2775 if (LdrpTlsArray)
2776 {
2777 RtlFreeHeap (RtlGetProcessHeap(), 0, NtCurrentTeb()->ThreadLocalStoragePointer);
2778 }
2779
2780 DPRINT("LdrShutdownThread() done\n");
2781
2782 return STATUS_SUCCESS;
2783 }
2784
2785
2786 /***************************************************************************
2787 * NAME EXPORTED
2788 * LdrQueryProcessModuleInformation
2789 *
2790 * DESCRIPTION
2791 *
2792 * ARGUMENTS
2793 *
2794 * RETURN VALUE
2795 *
2796 * REVISIONS
2797 *
2798 * NOTE
2799 *
2800 * @implemented
2801 */
2802 NTSTATUS NTAPI
2803 LdrQueryProcessModuleInformation(IN PRTL_PROCESS_MODULES ModuleInformation OPTIONAL,
2804 IN ULONG Size OPTIONAL,
2805 OUT PULONG ReturnedSize)
2806 {
2807 PLIST_ENTRY ModuleListHead;
2808 PLIST_ENTRY Entry;
2809 PLDR_DATA_TABLE_ENTRY Module;
2810 PRTL_PROCESS_MODULE_INFORMATION ModulePtr = NULL;
2811 NTSTATUS Status = STATUS_SUCCESS;
2812 ULONG UsedSize = sizeof(ULONG);
2813 ANSI_STRING AnsiString;
2814 PCHAR p;
2815
2816 DPRINT("LdrQueryProcessModuleInformation() called\n");
2817 // FIXME: This code is ultra-duplicated. see lib\rtl\dbgbuffer.c
2818 RtlEnterCriticalSection (NtCurrentPeb()->LoaderLock);
2819
2820 if (ModuleInformation == NULL || Size == 0)
2821 {
2822 Status = STATUS_INFO_LENGTH_MISMATCH;
2823 }
2824 else
2825 {
2826 ModuleInformation->NumberOfModules = 0;
2827 ModulePtr = &ModuleInformation->Modules[0];
2828 Status = STATUS_SUCCESS;
2829 }
2830
2831 ModuleListHead = &NtCurrentPeb()->Ldr->InLoadOrderModuleList;
2832 Entry = ModuleListHead->Flink;
2833
2834 while (Entry != ModuleListHead)
2835 {
2836 Module = CONTAINING_RECORD(Entry, LDR_DATA_TABLE_ENTRY, InLoadOrderLinks);
2837
2838 DPRINT(" Module %wZ\n",
2839 &Module->FullDllName);
2840
2841 if (UsedSize > Size)
2842 {
2843 Status = STATUS_INFO_LENGTH_MISMATCH;
2844 }
2845 else if (ModuleInformation != NULL)
2846 {
2847 ModulePtr->Section = 0;
2848 ModulePtr->MappedBase = NULL; // FIXME: ??
2849 ModulePtr->ImageBase = Module->DllBase;
2850 ModulePtr->ImageSize = Module->SizeOfImage;
2851 ModulePtr->Flags = Module->Flags;
2852 ModulePtr->LoadOrderIndex = 0; // FIXME: ??
2853 ModulePtr->InitOrderIndex = 0; // FIXME: ??
2854 ModulePtr->LoadCount = Module->LoadCount;
2855
2856 AnsiString.Length = 0;
2857 AnsiString.MaximumLength = 256;
2858 AnsiString.Buffer = ModulePtr->FullPathName;
2859 RtlUnicodeStringToAnsiString(&AnsiString,
2860 &Module->FullDllName,
2861 FALSE);
2862
2863 p = strrchr(ModulePtr->FullPathName, '\\');
2864 if (p != NULL)
2865 ModulePtr->OffsetToFileName = p - ModulePtr->FullPathName + 1;
2866 else
2867 ModulePtr->OffsetToFileName = 0;
2868
2869 ModulePtr++;
2870 ModuleInformation->NumberOfModules++;
2871 }
2872 UsedSize += sizeof(RTL_PROCESS_MODULE_INFORMATION);
2873
2874 Entry = Entry->Flink;
2875 }
2876
2877 RtlLeaveCriticalSection (NtCurrentPeb()->LoaderLock);
2878
2879 if (ReturnedSize != 0)
2880 *ReturnedSize = UsedSize;
2881
2882 DPRINT("LdrQueryProcessModuleInformation() done\n");
2883
2884 return(Status);
2885 }
2886
2887
2888 static BOOLEAN
2889 LdrpCheckImageChecksum (IN PVOID BaseAddress,
2890 IN ULONG ImageSize)
2891 {
2892 PIMAGE_NT_HEADERS Header;
2893 PUSHORT Ptr;
2894 ULONG Sum;
2895 ULONG CalcSum;
2896 ULONG HeaderSum;
2897 ULONG i;
2898
2899 Header = RtlImageNtHeader (BaseAddress);
2900 if (Header == NULL)
2901 return FALSE;
2902
2903 HeaderSum = Header->OptionalHeader.CheckSum;
2904 if (HeaderSum == 0)
2905 return TRUE;
2906
2907 Sum = 0;
2908 Ptr = (PUSHORT) BaseAddress;
2909 for (i = 0; i < ImageSize / sizeof (USHORT); i++)
2910 {
2911 Sum += (ULONG)*Ptr;
2912 if (HIWORD(Sum) != 0)
2913 {
2914 Sum = LOWORD(Sum) + HIWORD(Sum);
2915 }
2916 Ptr++;
2917 }
2918
2919 if (ImageSize & 1)
2920 {
2921 Sum += (ULONG)*((PUCHAR)Ptr);
2922 if (HIWORD(Sum) != 0)
2923 {
2924 Sum = LOWORD(Sum) + HIWORD(Sum);
2925 }
2926 }
2927
2928 CalcSum = (USHORT)(LOWORD(Sum) + HIWORD(Sum));
2929
2930 /* Subtract image checksum from calculated checksum. */
2931 /* fix low word of checksum */
2932 if (LOWORD(CalcSum) >= LOWORD(HeaderSum))
2933 {
2934 CalcSum -= LOWORD(HeaderSum);
2935 }
2936 else
2937 {
2938 CalcSum = ((LOWORD(CalcSum) - LOWORD(HeaderSum)) & 0xFFFF) - 1;
2939 }
2940
2941 /* fix high word of checksum */
2942 if (LOWORD(CalcSum) >= HIWORD(HeaderSum))
2943 {
2944 CalcSum -= HIWORD(HeaderSum);
2945 }
2946 else
2947 {
2948 CalcSum = ((LOWORD(CalcSum) - HIWORD(HeaderSum)) & 0xFFFF) - 1;
2949 }
2950
2951 /* add file length */
2952 CalcSum += ImageSize;
2953
2954 return (BOOLEAN)(CalcSum == HeaderSum);
2955 }
2956
2957 /*
2958 * Compute size of an image as it is actually present in virt memory
2959 * (i.e. excluding NEVER_LOAD sections)
2960 */
2961 ULONG
2962 LdrpGetResidentSize(PIMAGE_NT_HEADERS NTHeaders)
2963 {
2964 PIMAGE_SECTION_HEADER SectionHeader;
2965 unsigned SectionIndex;
2966 ULONG ResidentSize;
2967
2968 SectionHeader = (PIMAGE_SECTION_HEADER)((char *) &NTHeaders->OptionalHeader
2969 + NTHeaders->FileHeader.SizeOfOptionalHeader);
2970 ResidentSize = 0;
2971 for (SectionIndex = 0; SectionIndex < NTHeaders->FileHeader.NumberOfSections; SectionIndex++)
2972 {
2973 if (0 == (SectionHeader->Characteristics & IMAGE_SCN_LNK_REMOVE)
2974 && ResidentSize < SectionHeader->VirtualAddress + SectionHeader->Misc.VirtualSize)
2975 {
2976 ResidentSize = SectionHeader->VirtualAddress + SectionHeader->Misc.VirtualSize;
2977 }
2978 SectionHeader++;
2979 }
2980
2981 return ResidentSize;
2982 }
2983
2984
2985 /***************************************************************************
2986 * NAME EXPORTED
2987 * LdrVerifyImageMatchesChecksum
2988 *
2989 * DESCRIPTION
2990 *
2991 * ARGUMENTS
2992 *
2993 * RETURN VALUE
2994 *
2995 * REVISIONS
2996 *
2997 * NOTE
2998 *
2999 * @implemented
3000 */
3001 NTSTATUS NTAPI
3002 LdrVerifyImageMatchesChecksum (IN HANDLE FileHandle,
3003 ULONG Unknown1,
3004 ULONG Unknown2,
3005 ULONG Unknown3)
3006 {
3007 FILE_STANDARD_INFORMATION FileInfo;
3008 IO_STATUS_BLOCK IoStatusBlock;
3009 HANDLE SectionHandle;
3010 SIZE_T ViewSize;
3011 PVOID BaseAddress;
3012 BOOLEAN Result;
3013 NTSTATUS Status;
3014
3015 DPRINT ("LdrVerifyImageMatchesChecksum() called\n");
3016
3017 Status = NtCreateSection (&SectionHandle,
3018 SECTION_MAP_READ,
3019 NULL,
3020 NULL,
3021 PAGE_READONLY,
3022 SEC_COMMIT,
3023 FileHandle);
3024 if (!NT_SUCCESS(Status))
3025 {
3026 DPRINT1 ("NtCreateSection() failed (Status %lx)\n", Status);
3027 return Status;
3028 }
3029
3030 ViewSize = 0;
3031 BaseAddress = NULL;
3032 Status = NtMapViewOfSection (SectionHandle,
3033 NtCurrentProcess (),
3034 &BaseAddress,
3035 0,
3036 0,
3037 NULL,
3038 &ViewSize,
3039 ViewShare,
3040 0,
3041 PAGE_READONLY);
3042 if (!NT_SUCCESS(Status))
3043 {
3044 DPRINT1 ("NtMapViewOfSection() failed (Status %lx)\n", Status);
3045 NtClose (SectionHandle);
3046 return Status;
3047 }
3048
3049 Status = NtQueryInformationFile (FileHandle,
3050 &IoStatusBlock,
3051 &FileInfo,
3052 sizeof (FILE_STANDARD_INFORMATION),
3053 FileStandardInformation);
3054 if (!NT_SUCCESS(Status))
3055 {
3056 DPRINT1 ("NtMapViewOfSection() failed (Status %lx)\n", Status);
3057 NtUnmapViewOfSection (NtCurrentProcess (),
3058 BaseAddress);
3059 NtClose (SectionHandle);
3060 return Status;
3061 }
3062
3063 Result = LdrpCheckImageChecksum (BaseAddress,
3064 FileInfo.EndOfFile.u.LowPart);
3065 if (Result == FALSE)
3066 {
3067 Status = STATUS_IMAGE_CHECKSUM_MISMATCH;
3068 }
3069
3070 NtUnmapViewOfSection (NtCurrentProcess (),
3071 BaseAddress);
3072
3073 NtClose (SectionHandle);
3074
3075 return Status;
3076 }
3077
3078
3079 /***************************************************************************
3080 * NAME EXPORTED
3081 * LdrQueryImageFileExecutionOptions
3082 *
3083 * DESCRIPTION
3084 *
3085 * ARGUMENTS
3086 *
3087 * RETURN VALUE
3088 *
3089 * REVISIONS
3090 *
3091 * NOTE
3092 *
3093 * @implemented
3094 */
3095 NTSTATUS NTAPI
3096 LdrQueryImageFileExecutionOptions (IN PUNICODE_STRING SubKey,
3097 IN PCWSTR ValueName,
3098 IN ULONG Type,
3099 OUT PVOID Buffer,
3100 IN ULONG BufferSize,
3101 OUT PULONG ReturnedLength OPTIONAL)
3102 {
3103 PKEY_VALUE_PARTIAL_INFORMATION KeyInfo;
3104 OBJECT_ATTRIBUTES ObjectAttributes;
3105 UNICODE_STRING ValueNameString;
3106 UNICODE_STRING KeyName;
3107 WCHAR NameBuffer[256];
3108 HANDLE KeyHandle;
3109 ULONG KeyInfoSize;
3110 ULONG ResultSize;
3111 PWCHAR Ptr;
3112 NTSTATUS Status;
3113
3114 wcscpy (NameBuffer,
3115 L"\\Registry\\Machine\\Software\\Microsoft\\Windows NT\\CurrentVersion\\Image File Execution Options\\");
3116 Ptr = wcsrchr (SubKey->Buffer, L'\\');
3117 if (Ptr == NULL)
3118 {
3119 Ptr = SubKey->Buffer;
3120 }
3121 else
3122 {
3123 Ptr++;
3124 }
3125 wcscat (NameBuffer, Ptr);
3126 RtlInitUnicodeString (&KeyName,
3127 NameBuffer);
3128
3129 InitializeObjectAttributes (&ObjectAttributes,
3130 &KeyName,
3131 OBJ_CASE_INSENSITIVE,
3132 NULL,
3133 NULL);
3134
3135 Status = NtOpenKey (&KeyHandle,
3136 KEY_READ,
3137 &ObjectAttributes);
3138 if (!NT_SUCCESS(Status))
3139 {
3140 DPRINT ("NtOpenKey() failed (Status %lx)\n", Status);
3141 return Status;
3142 }
3143
3144 KeyInfoSize = sizeof(KEY_VALUE_PARTIAL_INFORMATION) + 32;
3145 KeyInfo = RtlAllocateHeap (RtlGetProcessHeap(),
3146 HEAP_ZERO_MEMORY,
3147 KeyInfoSize);
3148 if (KeyInfo == NULL)
3149 {
3150 NtClose (KeyHandle);
3151 return STATUS_INSUFFICIENT_RESOURCES;
3152 }
3153
3154 RtlInitUnicodeString (&ValueNameString,
3155 (PWSTR)ValueName);
3156 Status = NtQueryValueKey (KeyHandle,
3157 &ValueNameString,
3158 KeyValuePartialInformation,
3159 KeyInfo,
3160 KeyInfoSize,
3161 &ResultSize);
3162 if (Status == STATUS_BUFFER_OVERFLOW)
3163 {
3164 KeyInfoSize = sizeof(KEY_VALUE_PARTIAL_INFORMATION) + KeyInfo->DataLength;
3165 RtlFreeHeap (RtlGetProcessHeap(),
3166 0,
3167 KeyInfo);
3168 KeyInfo = RtlAllocateHeap (RtlGetProcessHeap(),
3169 HEAP_ZERO_MEMORY,
3170 KeyInfoSize);
3171 if (KeyInfo == NULL)
3172 {
3173 NtClose (KeyHandle);
3174 return STATUS_INSUFFICIENT_RESOURCES;
3175 }
3176
3177 Status = NtQueryValueKey (KeyHandle,
3178 &ValueNameString,
3179 KeyValuePartialInformation,
3180 KeyInfo,
3181 KeyInfoSize,
3182 &ResultSize);
3183 }
3184 NtClose (KeyHandle);
3185
3186 if (!NT_SUCCESS(Status))
3187 {
3188 if (KeyInfo != NULL)
3189 {
3190 RtlFreeHeap (RtlGetProcessHeap(),
3191 0,
3192 KeyInfo);
3193 }
3194 return Status;
3195 }
3196
3197 if (KeyInfo->Type != Type)
3198 {
3199 RtlFreeHeap (RtlGetProcessHeap(),
3200 0,
3201 KeyInfo);
3202 return STATUS_OBJECT_TYPE_MISMATCH;
3203 }
3204
3205 ResultSize = BufferSize;
3206 if (ResultSize < KeyInfo->DataLength)
3207 {
3208 Status = STATUS_BUFFER_OVERFLOW;
3209 }
3210 else
3211 {
3212 ResultSize = KeyInfo->DataLength;
3213 }
3214 RtlCopyMemory (Buffer,
3215 &KeyInfo->Data,
3216 ResultSize);
3217
3218 RtlFreeHeap (RtlGetProcessHeap(),
3219 0,
3220 KeyInfo);
3221
3222 if (ReturnedLength != NULL)
3223 {
3224 *ReturnedLength = ResultSize;
3225 }
3226
3227 return Status;
3228 }
3229
3230
3231 PIMAGE_BASE_RELOCATION NTAPI
3232 LdrProcessRelocationBlock(IN ULONG_PTR Address,
3233 IN ULONG Count,
3234 IN PUSHORT TypeOffset,
3235 IN LONG_PTR Delta)
3236 {
3237 SHORT Offset;
3238 USHORT Type;
3239 USHORT i;
3240 PUSHORT ShortPtr;
3241 PULONG LongPtr;
3242
3243 for (i = 0; i < Count; i++)
3244 {
3245 Offset = *TypeOffset & 0xFFF;
3246 Type = *TypeOffset >> 12;
3247
3248 switch (Type)
3249 {
3250 case IMAGE_REL_BASED_ABSOLUTE:
3251 break;
3252
3253 case IMAGE_REL_BASED_HIGH:
3254 ShortPtr = (PUSHORT)((ULONG_PTR)Address + Offset);
3255 *ShortPtr += HIWORD(Delta);
3256 break;
3257
3258 case IMAGE_REL_BASED_LOW:
3259 ShortPtr = (PUSHORT)((ULONG_PTR)Address + Offset);
3260 *ShortPtr += LOWORD(Delta);
3261 break;
3262
3263 case IMAGE_REL_BASED_HIGHLOW:
3264 LongPtr = (PULONG)((ULONG_PTR)Address + Offset);
3265 *LongPtr += Delta;
3266 break;
3267
3268 case IMAGE_REL_BASED_HIGHADJ:
3269 case IMAGE_REL_BASED_MIPS_JMPADDR:
3270 default:
3271 DPRINT1("Unknown/unsupported fixup type %hu.\n", Type);
3272 return NULL;
3273 }
3274
3275 TypeOffset++;
3276 }
3277
3278 return (PIMAGE_BASE_RELOCATION)TypeOffset;
3279 }
3280
3281 NTSTATUS
3282 NTAPI
3283 LdrLockLoaderLock(IN ULONG Flags,
3284 OUT PULONG Disposition OPTIONAL,
3285 OUT PULONG Cookie OPTIONAL)
3286 {
3287 UNIMPLEMENTED;
3288 return STATUS_NOT_IMPLEMENTED;
3289 }
3290
3291 NTSTATUS
3292 NTAPI
3293 LdrUnlockLoaderLock(IN ULONG Flags,
3294 IN ULONG Cookie OPTIONAL)
3295 {
3296 UNIMPLEMENTED;
3297 return STATUS_NOT_IMPLEMENTED;
3298 }
3299
3300 BOOLEAN
3301 NTAPI
3302 LdrUnloadAlternateResourceModule(IN PVOID BaseAddress)
3303 {
3304 UNIMPLEMENTED;
3305 return FALSE;
3306 }