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