Sync with trunk r58151 to bring the latest changes from Amine and Timo.
[reactos.git] / dll / ntdll / ldr / ldrinit.c
1 /*
2 * COPYRIGHT: See COPYING in the top level directory
3 * PROJECT: ReactOS NT User-Mode Library
4 * FILE: dll/ntdll/ldr/ldrinit.c
5 * PURPOSE: User-Mode Process/Thread Startup
6 * PROGRAMMERS: Alex Ionescu (alex@relsoft.net)
7 * Aleksey Bragin (aleksey@reactos.org)
8 */
9
10 /* INCLUDES *****************************************************************/
11
12 #include <ntdll.h>
13 #include <callback.h>
14
15 #define NDEBUG
16 #include <debug.h>
17
18
19 /* GLOBALS *******************************************************************/
20
21 HANDLE ImageExecOptionsKey;
22 HANDLE Wow64ExecOptionsKey;
23 UNICODE_STRING ImageExecOptionsString = RTL_CONSTANT_STRING(L"\\Registry\\Machine\\Software\\Microsoft\\Windows NT\\CurrentVersion\\Image File Execution Options");
24 UNICODE_STRING Wow64OptionsString = RTL_CONSTANT_STRING(L"");
25 UNICODE_STRING NtDllString = RTL_CONSTANT_STRING(L"ntdll.dll");
26
27 BOOLEAN LdrpInLdrInit;
28 LONG LdrpProcessInitialized;
29 BOOLEAN LdrpLoaderLockInit;
30 BOOLEAN LdrpLdrDatabaseIsSetup;
31 BOOLEAN LdrpShutdownInProgress;
32 HANDLE LdrpShutdownThreadId;
33
34 BOOLEAN LdrpDllValidation;
35
36 PLDR_DATA_TABLE_ENTRY LdrpImageEntry;
37 PUNICODE_STRING LdrpTopLevelDllBeingLoaded;
38 WCHAR StringBuffer[156];
39 extern PTEB LdrpTopLevelDllBeingLoadedTeb; // defined in rtlsupp.c!
40 PLDR_DATA_TABLE_ENTRY LdrpCurrentDllInitializer;
41 PLDR_DATA_TABLE_ENTRY LdrpNtDllDataTableEntry;
42
43 RTL_BITMAP TlsBitMap;
44 RTL_BITMAP TlsExpansionBitMap;
45 RTL_BITMAP FlsBitMap;
46 BOOLEAN LdrpImageHasTls;
47 LIST_ENTRY LdrpTlsList;
48 ULONG LdrpNumberOfTlsEntries;
49 ULONG LdrpNumberOfProcessors;
50 PVOID NtDllBase;
51 LARGE_INTEGER RtlpTimeout;
52 BOOLEAN RtlpTimeoutDisable;
53 LIST_ENTRY LdrpHashTable[LDR_HASH_TABLE_ENTRIES];
54 LIST_ENTRY LdrpDllNotificationList;
55 HANDLE LdrpKnownDllObjectDirectory;
56 UNICODE_STRING LdrpKnownDllPath;
57 WCHAR LdrpKnownDllPathBuffer[128];
58 UNICODE_STRING LdrpDefaultPath;
59
60 PEB_LDR_DATA PebLdr;
61
62 RTL_CRITICAL_SECTION_DEBUG LdrpLoaderLockDebug;
63 RTL_CRITICAL_SECTION LdrpLoaderLock =
64 {
65 &LdrpLoaderLockDebug,
66 -1,
67 0,
68 0,
69 0,
70 0
71 };
72 RTL_CRITICAL_SECTION FastPebLock;
73
74 BOOLEAN ShowSnaps;
75
76 ULONG LdrpFatalHardErrorCount;
77 ULONG LdrpActiveUnloadCount;
78
79 //extern LIST_ENTRY RtlCriticalSectionList;
80
81 VOID RtlpInitializeVectoredExceptionHandling(VOID);
82 VOID NTAPI RtlpInitDeferedCriticalSection(VOID);
83 VOID RtlInitializeHeapManager(VOID);
84 extern BOOLEAN RtlpPageHeapEnabled;
85
86 ULONG RtlpDisableHeapLookaside; // TODO: Move to heap.c
87 ULONG RtlpShutdownProcessFlags; // TODO: Use it
88
89 NTSTATUS LdrPerformRelocations(PIMAGE_NT_HEADERS NTHeaders, PVOID ImageBase);
90 void actctx_init(void);
91
92 #ifdef _WIN64
93 #define DEFAULT_SECURITY_COOKIE 0x00002B992DDFA232ll
94 #else
95 #define DEFAULT_SECURITY_COOKIE 0xBB40E64E
96 #endif
97
98 /* FUNCTIONS *****************************************************************/
99
100 /*
101 * @implemented
102 */
103 NTSTATUS
104 NTAPI
105 LdrOpenImageFileOptionsKey(IN PUNICODE_STRING SubKey,
106 IN BOOLEAN Wow64,
107 OUT PHANDLE NewKeyHandle)
108 {
109 PHANDLE RootKeyLocation;
110 HANDLE RootKey;
111 UNICODE_STRING SubKeyString;
112 OBJECT_ATTRIBUTES ObjectAttributes;
113 NTSTATUS Status;
114 PWCHAR p1;
115
116 /* Check which root key to open */
117 if (Wow64)
118 RootKeyLocation = &Wow64ExecOptionsKey;
119 else
120 RootKeyLocation = &ImageExecOptionsKey;
121
122 /* Get the current key */
123 RootKey = *RootKeyLocation;
124
125 /* Setup the object attributes */
126 InitializeObjectAttributes(&ObjectAttributes,
127 Wow64 ?
128 &Wow64OptionsString : &ImageExecOptionsString,
129 OBJ_CASE_INSENSITIVE,
130 NULL,
131 NULL);
132
133 /* Open the root key */
134 Status = ZwOpenKey(&RootKey, KEY_ENUMERATE_SUB_KEYS, &ObjectAttributes);
135 if (NT_SUCCESS(Status))
136 {
137 /* Write the key handle */
138 if (_InterlockedCompareExchange((LONG*)RootKeyLocation, (LONG)RootKey, 0) != 0)
139 {
140 /* Someone already opened it, use it instead */
141 NtClose(RootKey);
142 RootKey = *RootKeyLocation;
143 }
144
145 /* Extract the name */
146 SubKeyString = *SubKey;
147 p1 = (PWCHAR)((ULONG_PTR)SubKeyString.Buffer + SubKeyString.Length);
148 while (SubKeyString.Length)
149 {
150 if (p1[-1] == L'\\') break;
151 p1--;
152 SubKeyString.Length -= sizeof(*p1);
153 }
154 SubKeyString.Buffer = p1;
155 SubKeyString.Length = SubKey->Length - SubKeyString.Length;
156
157 /* Setup the object attributes */
158 InitializeObjectAttributes(&ObjectAttributes,
159 &SubKeyString,
160 OBJ_CASE_INSENSITIVE,
161 RootKey,
162 NULL);
163
164 /* Open the setting key */
165 Status = ZwOpenKey((PHANDLE)NewKeyHandle, GENERIC_READ, &ObjectAttributes);
166 }
167
168 /* Return to caller */
169 return Status;
170 }
171
172 /*
173 * @implemented
174 */
175 NTSTATUS
176 NTAPI
177 LdrQueryImageFileKeyOption(IN HANDLE KeyHandle,
178 IN PCWSTR ValueName,
179 IN ULONG Type,
180 OUT PVOID Buffer,
181 IN ULONG BufferSize,
182 OUT PULONG ReturnedLength OPTIONAL)
183 {
184 ULONG KeyInfo[256];
185 UNICODE_STRING ValueNameString, IntegerString;
186 ULONG KeyInfoSize, ResultSize;
187 PKEY_VALUE_PARTIAL_INFORMATION KeyValueInformation = (PKEY_VALUE_PARTIAL_INFORMATION)&KeyInfo;
188 BOOLEAN FreeHeap = FALSE;
189 NTSTATUS Status;
190
191 /* Build a string for the value name */
192 Status = RtlInitUnicodeStringEx(&ValueNameString, ValueName);
193 if (!NT_SUCCESS(Status)) return Status;
194
195 /* Query the value */
196 Status = ZwQueryValueKey(KeyHandle,
197 &ValueNameString,
198 KeyValuePartialInformation,
199 KeyValueInformation,
200 sizeof(KeyInfo),
201 &ResultSize);
202 if (Status == STATUS_BUFFER_OVERFLOW)
203 {
204 /* Our local buffer wasn't enough, allocate one */
205 KeyInfoSize = sizeof(KEY_VALUE_PARTIAL_INFORMATION) +
206 KeyValueInformation->DataLength;
207 KeyValueInformation = RtlAllocateHeap(RtlGetProcessHeap(),
208 0,
209 KeyInfoSize);
210 if (KeyValueInformation != NULL)
211 {
212 /* Try again */
213 Status = ZwQueryValueKey(KeyHandle,
214 &ValueNameString,
215 KeyValuePartialInformation,
216 KeyValueInformation,
217 KeyInfoSize,
218 &ResultSize);
219 FreeHeap = TRUE;
220 }
221 else
222 {
223 /* Give up this time */
224 Status = STATUS_NO_MEMORY;
225 }
226 }
227
228 /* Check for success */
229 if (NT_SUCCESS(Status))
230 {
231 /* Handle binary data */
232 if (KeyValueInformation->Type == REG_BINARY)
233 {
234 /* Check validity */
235 if ((Buffer) && (KeyValueInformation->DataLength <= BufferSize))
236 {
237 /* Copy into buffer */
238 RtlMoveMemory(Buffer,
239 &KeyValueInformation->Data,
240 KeyValueInformation->DataLength);
241 }
242 else
243 {
244 Status = STATUS_BUFFER_OVERFLOW;
245 }
246
247 /* Copy the result length */
248 if (ReturnedLength) *ReturnedLength = KeyValueInformation->DataLength;
249 }
250 else if (KeyValueInformation->Type == REG_DWORD)
251 {
252 /* Check for valid type */
253 if (KeyValueInformation->Type != Type)
254 {
255 /* Error */
256 Status = STATUS_OBJECT_TYPE_MISMATCH;
257 }
258 else
259 {
260 /* Check validity */
261 if ((Buffer) &&
262 (BufferSize == sizeof(ULONG)) &&
263 (KeyValueInformation->DataLength <= BufferSize))
264 {
265 /* Copy into buffer */
266 RtlMoveMemory(Buffer,
267 &KeyValueInformation->Data,
268 KeyValueInformation->DataLength);
269 }
270 else
271 {
272 Status = STATUS_BUFFER_OVERFLOW;
273 }
274
275 /* Copy the result length */
276 if (ReturnedLength) *ReturnedLength = KeyValueInformation->DataLength;
277 }
278 }
279 else if (KeyValueInformation->Type != REG_SZ)
280 {
281 /* We got something weird */
282 Status = STATUS_OBJECT_TYPE_MISMATCH;
283 }
284 else
285 {
286 /* String, check what you requested */
287 if (Type == REG_DWORD)
288 {
289 /* Validate */
290 if (BufferSize != sizeof(ULONG))
291 {
292 /* Invalid size */
293 BufferSize = 0;
294 Status = STATUS_INFO_LENGTH_MISMATCH;
295 }
296 else
297 {
298 /* OK, we know what you want... */
299 IntegerString.Buffer = (PWSTR)KeyValueInformation->Data;
300 IntegerString.Length = (USHORT)KeyValueInformation->DataLength -
301 sizeof(WCHAR);
302 IntegerString.MaximumLength = (USHORT)KeyValueInformation->DataLength;
303 Status = RtlUnicodeStringToInteger(&IntegerString, 0, (PULONG)Buffer);
304 }
305 }
306 else
307 {
308 /* Validate */
309 if (KeyValueInformation->DataLength > BufferSize)
310 {
311 /* Invalid */
312 Status = STATUS_BUFFER_OVERFLOW;
313 }
314 else
315 {
316 /* Set the size */
317 BufferSize = KeyValueInformation->DataLength;
318 }
319
320 /* Copy the string */
321 RtlMoveMemory(Buffer, &KeyValueInformation->Data, BufferSize);
322 }
323
324 /* Copy the result length */
325 if (ReturnedLength) *ReturnedLength = KeyValueInformation->DataLength;
326 }
327 }
328
329 /* Check if buffer was in heap */
330 if (FreeHeap) RtlFreeHeap(RtlGetProcessHeap(), 0, KeyValueInformation);
331
332 /* Return status */
333 return Status;
334 }
335
336 /*
337 * @implemented
338 */
339 NTSTATUS
340 NTAPI
341 LdrQueryImageFileExecutionOptionsEx(IN PUNICODE_STRING SubKey,
342 IN PCWSTR ValueName,
343 IN ULONG Type,
344 OUT PVOID Buffer,
345 IN ULONG BufferSize,
346 OUT PULONG ReturnedLength OPTIONAL,
347 IN BOOLEAN Wow64)
348 {
349 NTSTATUS Status;
350 HANDLE KeyHandle;
351
352 /* Open a handle to the key */
353 Status = LdrOpenImageFileOptionsKey(SubKey, Wow64, &KeyHandle);
354
355 /* Check for success */
356 if (NT_SUCCESS(Status))
357 {
358 /* Query the data */
359 Status = LdrQueryImageFileKeyOption(KeyHandle,
360 ValueName,
361 Type,
362 Buffer,
363 BufferSize,
364 ReturnedLength);
365
366 /* Close the key */
367 NtClose(KeyHandle);
368 }
369
370 /* Return to caller */
371 return Status;
372 }
373
374 /*
375 * @implemented
376 */
377 NTSTATUS
378 NTAPI
379 LdrQueryImageFileExecutionOptions(IN PUNICODE_STRING SubKey,
380 IN PCWSTR ValueName,
381 IN ULONG Type,
382 OUT PVOID Buffer,
383 IN ULONG BufferSize,
384 OUT PULONG ReturnedLength OPTIONAL)
385 {
386 /* Call the newer function */
387 return LdrQueryImageFileExecutionOptionsEx(SubKey,
388 ValueName,
389 Type,
390 Buffer,
391 BufferSize,
392 ReturnedLength,
393 FALSE);
394 }
395
396 VOID
397 NTAPI
398 LdrpEnsureLoaderLockIsHeld()
399 {
400 // Ignored atm
401 }
402
403 PVOID
404 NTAPI
405 LdrpFetchAddressOfSecurityCookie(PVOID BaseAddress, ULONG SizeOfImage)
406 {
407 PIMAGE_LOAD_CONFIG_DIRECTORY ConfigDir;
408 ULONG DirSize;
409 PVOID Cookie = NULL;
410
411 /* Check NT header first */
412 if (!RtlImageNtHeader(BaseAddress)) return NULL;
413
414 /* Get the pointer to the config directory */
415 ConfigDir = RtlImageDirectoryEntryToData(BaseAddress,
416 TRUE,
417 IMAGE_DIRECTORY_ENTRY_LOAD_CONFIG,
418 &DirSize);
419
420 /* Check for sanity */
421 if (!ConfigDir ||
422 (DirSize != 64 && ConfigDir->Size != DirSize) ||
423 (ConfigDir->Size < 0x48))
424 return NULL;
425
426 /* Now get the cookie */
427 Cookie = (PVOID)ConfigDir->SecurityCookie;
428
429 /* Check this cookie */
430 if ((PCHAR)Cookie <= (PCHAR)BaseAddress ||
431 (PCHAR)Cookie >= (PCHAR)BaseAddress + SizeOfImage)
432 {
433 Cookie = NULL;
434 }
435
436 /* Return validated security cookie */
437 return Cookie;
438 }
439
440 PVOID
441 NTAPI
442 LdrpInitSecurityCookie(PLDR_DATA_TABLE_ENTRY LdrEntry)
443 {
444 PULONG_PTR Cookie;
445 LARGE_INTEGER Counter;
446 ULONG_PTR NewCookie;
447
448 /* Fetch address of the cookie */
449 Cookie = LdrpFetchAddressOfSecurityCookie(LdrEntry->DllBase, LdrEntry->SizeOfImage);
450
451 if (Cookie)
452 {
453 /* Check if it's a default one */
454 if ((*Cookie == DEFAULT_SECURITY_COOKIE) ||
455 (*Cookie == 0xBB40))
456 {
457 /* Make up a cookie from a bunch of values which may uniquely represent
458 current moment of time, environment, etc */
459 NtQueryPerformanceCounter(&Counter, NULL);
460
461 NewCookie = Counter.LowPart ^ Counter.HighPart;
462 NewCookie ^= (ULONG)NtCurrentTeb()->ClientId.UniqueProcess;
463 NewCookie ^= (ULONG)NtCurrentTeb()->ClientId.UniqueThread;
464
465 /* Loop like it's done in KeQueryTickCount(). We don't want to call it directly. */
466 while (SharedUserData->SystemTime.High1Time != SharedUserData->SystemTime.High2Time)
467 {
468 YieldProcessor();
469 };
470
471 /* Calculate the milliseconds value and xor it to the cookie */
472 NewCookie ^= Int64ShrlMod32(UInt32x32To64(SharedUserData->TickCountMultiplier, SharedUserData->TickCount.LowPart), 24) +
473 (SharedUserData->TickCountMultiplier * (SharedUserData->TickCount.High1Time << 8));
474
475 /* Make the cookie 16bit if necessary */
476 if (*Cookie == 0xBB40) NewCookie &= 0xFFFF;
477
478 /* If the result is 0 or the same as we got, just subtract one from the existing value
479 and that's it */
480 if ((NewCookie == 0) || (NewCookie == *Cookie))
481 {
482 NewCookie = *Cookie - 1;
483 }
484
485 /* Set the new cookie value */
486 *Cookie = NewCookie;
487 }
488 }
489
490 return Cookie;
491 }
492
493 VOID
494 NTAPI
495 LdrpInitializeThread(IN PCONTEXT Context)
496 {
497 PPEB Peb = NtCurrentPeb();
498 PLDR_DATA_TABLE_ENTRY LdrEntry;
499 PLIST_ENTRY NextEntry, ListHead;
500 RTL_CALLER_ALLOCATED_ACTIVATION_CONTEXT_STACK_FRAME_EXTENDED ActCtx;
501 NTSTATUS Status;
502 PVOID EntryPoint;
503
504 DPRINT("LdrpInitializeThread() called for %wZ (%lx/%lx)\n",
505 &LdrpImageEntry->BaseDllName,
506 NtCurrentTeb()->RealClientId.UniqueProcess,
507 NtCurrentTeb()->RealClientId.UniqueThread);
508
509 /* Allocate an Activation Context Stack */
510 DPRINT("ActivationContextStack %p\n", NtCurrentTeb()->ActivationContextStackPointer);
511 Status = RtlAllocateActivationContextStack((PVOID*)&NtCurrentTeb()->ActivationContextStackPointer);
512 if (!NT_SUCCESS(Status))
513 {
514 DPRINT1("Warning: Unable to allocate ActivationContextStack\n");
515 }
516
517 /* Make sure we are not shutting down */
518 if (LdrpShutdownInProgress) return;
519
520 /* Allocate TLS */
521 LdrpAllocateTls();
522
523 /* Start at the beginning */
524 ListHead = &Peb->Ldr->InMemoryOrderModuleList;
525 NextEntry = ListHead->Flink;
526 while (NextEntry != ListHead)
527 {
528 /* Get the current entry */
529 LdrEntry = CONTAINING_RECORD(NextEntry, LDR_DATA_TABLE_ENTRY, InMemoryOrderModuleList);
530
531 /* Make sure it's not ourselves */
532 if (Peb->ImageBaseAddress != LdrEntry->DllBase)
533 {
534 /* Check if we should call */
535 if (!(LdrEntry->Flags & LDRP_DONT_CALL_FOR_THREADS))
536 {
537 /* Get the entrypoint */
538 EntryPoint = LdrEntry->EntryPoint;
539
540 /* Check if we are ready to call it */
541 if ((EntryPoint) &&
542 (LdrEntry->Flags & LDRP_PROCESS_ATTACH_CALLED) &&
543 (LdrEntry->Flags & LDRP_IMAGE_DLL))
544 {
545 /* Set up the Act Ctx */
546 ActCtx.Size = sizeof(ActCtx);
547 ActCtx.Format = 1;
548 RtlZeroMemory(&ActCtx.Frame, sizeof(RTL_ACTIVATION_CONTEXT_STACK_FRAME));
549
550 /* Activate the ActCtx */
551 RtlActivateActivationContextUnsafeFast(&ActCtx,
552 LdrEntry->EntryPointActivationContext);
553
554 /* Check if it has TLS */
555 if (LdrEntry->TlsIndex)
556 {
557 /* Make sure we're not shutting down */
558 if (!LdrpShutdownInProgress)
559 {
560 /* Call TLS */
561 LdrpCallTlsInitializers(LdrEntry->DllBase, DLL_THREAD_ATTACH);
562 }
563 }
564
565 /* Make sure we're not shutting down */
566 if (!LdrpShutdownInProgress)
567 {
568 /* Call the Entrypoint */
569 DPRINT("%wZ - Calling entry point at %p for thread attaching, %lx/%lx\n",
570 &LdrEntry->BaseDllName, LdrEntry->EntryPoint,
571 NtCurrentTeb()->RealClientId.UniqueProcess,
572 NtCurrentTeb()->RealClientId.UniqueThread);
573 LdrpCallInitRoutine(LdrEntry->EntryPoint,
574 LdrEntry->DllBase,
575 DLL_THREAD_ATTACH,
576 NULL);
577 }
578
579 /* Deactivate the ActCtx */
580 RtlDeactivateActivationContextUnsafeFast(&ActCtx);
581 }
582 }
583 }
584
585 /* Next entry */
586 NextEntry = NextEntry->Flink;
587 }
588
589 /* Check for TLS */
590 if (LdrpImageHasTls && !LdrpShutdownInProgress)
591 {
592 /* Set up the Act Ctx */
593 ActCtx.Size = sizeof(ActCtx);
594 ActCtx.Format = 1;
595 RtlZeroMemory(&ActCtx.Frame, sizeof(RTL_ACTIVATION_CONTEXT_STACK_FRAME));
596
597 /* Activate the ActCtx */
598 RtlActivateActivationContextUnsafeFast(&ActCtx,
599 LdrpImageEntry->EntryPointActivationContext);
600
601 /* Do TLS callbacks */
602 LdrpCallTlsInitializers(Peb->ImageBaseAddress, DLL_THREAD_ATTACH);
603
604 /* Deactivate the ActCtx */
605 RtlDeactivateActivationContextUnsafeFast(&ActCtx);
606 }
607
608 DPRINT("LdrpInitializeThread() done\n");
609 }
610
611 NTSTATUS
612 NTAPI
613 LdrpRunInitializeRoutines(IN PCONTEXT Context OPTIONAL)
614 {
615 PLDR_DATA_TABLE_ENTRY LocalArray[16];
616 PLIST_ENTRY ListHead;
617 PLIST_ENTRY NextEntry;
618 PLDR_DATA_TABLE_ENTRY LdrEntry, *LdrRootEntry, OldInitializer;
619 PVOID EntryPoint;
620 ULONG Count, i;
621 //ULONG BreakOnInit;
622 NTSTATUS Status = STATUS_SUCCESS;
623 PPEB Peb = NtCurrentPeb();
624 RTL_CALLER_ALLOCATED_ACTIVATION_CONTEXT_STACK_FRAME_EXTENDED ActCtx;
625 ULONG BreakOnDllLoad;
626 PTEB OldTldTeb;
627 BOOLEAN DllStatus;
628
629 DPRINT("LdrpRunInitializeRoutines() called for %wZ (%lx/%lx)\n",
630 &LdrpImageEntry->BaseDllName,
631 NtCurrentTeb()->RealClientId.UniqueProcess,
632 NtCurrentTeb()->RealClientId.UniqueThread);
633
634 /* Check the Loader Lock */
635 LdrpEnsureLoaderLockIsHeld();
636
637 /* Get the number of entries to call */
638 if ((Count = LdrpClearLoadInProgress()))
639 {
640 /* Check if we can use our local buffer */
641 if (Count > 16)
642 {
643 /* Allocate space for all the entries */
644 LdrRootEntry = RtlAllocateHeap(RtlGetProcessHeap(),
645 0,
646 Count * sizeof(*LdrRootEntry));
647 if (!LdrRootEntry) return STATUS_NO_MEMORY;
648 }
649 else
650 {
651 /* Use our local array */
652 LdrRootEntry = LocalArray;
653 }
654 }
655 else
656 {
657 /* Don't need one */
658 LdrRootEntry = NULL;
659 }
660
661 /* Show debug message */
662 if (ShowSnaps)
663 {
664 DPRINT1("[%x,%x] LDR: Real INIT LIST for Process %wZ\n",
665 NtCurrentTeb()->RealClientId.UniqueThread,
666 NtCurrentTeb()->RealClientId.UniqueProcess,
667 &Peb->ProcessParameters->ImagePathName);
668 }
669
670 /* Loop in order */
671 ListHead = &Peb->Ldr->InInitializationOrderModuleList;
672 NextEntry = ListHead->Flink;
673 i = 0;
674 while (NextEntry != ListHead)
675 {
676 /* Get the Data Entry */
677 LdrEntry = CONTAINING_RECORD(NextEntry, LDR_DATA_TABLE_ENTRY, InInitializationOrderModuleList);
678
679 /* Check if we have a Root Entry */
680 if (LdrRootEntry)
681 {
682 /* Check flags */
683 if (!(LdrEntry->Flags & LDRP_ENTRY_PROCESSED))
684 {
685 /* Setup the Cookie for the DLL */
686 LdrpInitSecurityCookie(LdrEntry);
687
688 /* Check for valid entrypoint */
689 if (LdrEntry->EntryPoint)
690 {
691 /* Write in array */
692 ASSERT(i < Count);
693 LdrRootEntry[i] = LdrEntry;
694
695 /* Display debug message */
696 if (ShowSnaps)
697 {
698 DPRINT1("[%x,%x] LDR: %wZ init routine %p\n",
699 NtCurrentTeb()->RealClientId.UniqueThread,
700 NtCurrentTeb()->RealClientId.UniqueProcess,
701 &LdrEntry->FullDllName,
702 LdrEntry->EntryPoint);
703 }
704 i++;
705 }
706 }
707 }
708
709 /* Set the flag */
710 LdrEntry->Flags |= LDRP_ENTRY_PROCESSED;
711 NextEntry = NextEntry->Flink;
712 }
713
714 /* If we got a context, then we have to call Kernel32 for TS support */
715 if (Context)
716 {
717 /* Check if we have one */
718 //if (Kernel32ProcessInitPostImportfunction)
719 //{
720 /* Call it */
721 //Kernel32ProcessInitPostImportfunction();
722 //}
723
724 /* Clear it */
725 //Kernel32ProcessInitPostImportfunction = NULL;
726 //UNIMPLEMENTED;
727 }
728
729 /* No root entry? return */
730 if (!LdrRootEntry) return STATUS_SUCCESS;
731
732 /* Set the TLD TEB */
733 OldTldTeb = LdrpTopLevelDllBeingLoadedTeb;
734 LdrpTopLevelDllBeingLoadedTeb = NtCurrentTeb();
735
736 /* Loop */
737 i = 0;
738 while (i < Count)
739 {
740 /* Get an entry */
741 LdrEntry = LdrRootEntry[i];
742
743 /* FIXME: Verify NX Compat */
744
745 /* Move to next entry */
746 i++;
747
748 /* Get its entrypoint */
749 EntryPoint = LdrEntry->EntryPoint;
750
751 /* Are we being debugged? */
752 BreakOnDllLoad = 0;
753 if (Peb->BeingDebugged || Peb->ReadImageFileExecOptions)
754 {
755 /* Check if we should break on load */
756 Status = LdrQueryImageFileExecutionOptions(&LdrEntry->BaseDllName,
757 L"BreakOnDllLoad",
758 REG_DWORD,
759 &BreakOnDllLoad,
760 sizeof(ULONG),
761 NULL);
762 if (!NT_SUCCESS(Status)) BreakOnDllLoad = 0;
763
764 /* Reset status back to STATUS_SUCCESS */
765 Status = STATUS_SUCCESS;
766 }
767
768 /* Break if aksed */
769 if (BreakOnDllLoad)
770 {
771 /* Check if we should show a message */
772 if (ShowSnaps)
773 {
774 DPRINT1("LDR: %wZ loaded.", &LdrEntry->BaseDllName);
775 DPRINT1(" - About to call init routine at %p\n", EntryPoint);
776 }
777
778 /* Break in debugger */
779 DbgBreakPoint();
780 }
781
782 /* Make sure we have an entrypoint */
783 if (EntryPoint)
784 {
785 /* Save the old Dll Initializer and write the current one */
786 OldInitializer = LdrpCurrentDllInitializer;
787 LdrpCurrentDllInitializer = LdrEntry;
788
789 /* Set up the Act Ctx */
790 ActCtx.Size = sizeof(ActCtx);
791 ActCtx.Format = 1;
792 RtlZeroMemory(&ActCtx.Frame, sizeof(RTL_ACTIVATION_CONTEXT_STACK_FRAME));
793
794 /* Activate the ActCtx */
795 RtlActivateActivationContextUnsafeFast(&ActCtx,
796 LdrEntry->EntryPointActivationContext);
797
798 /* Check if it has TLS */
799 if (LdrEntry->TlsIndex && Context)
800 {
801 /* Call TLS */
802 LdrpCallTlsInitializers(LdrEntry->DllBase, DLL_PROCESS_ATTACH);
803 }
804
805 /* Call the Entrypoint */
806 if (ShowSnaps)
807 {
808 DPRINT1("%wZ - Calling entry point at %p for DLL_PROCESS_ATTACH\n",
809 &LdrEntry->BaseDllName, EntryPoint);
810 }
811 DllStatus = LdrpCallInitRoutine(EntryPoint,
812 LdrEntry->DllBase,
813 DLL_PROCESS_ATTACH,
814 Context);
815
816 /* Deactivate the ActCtx */
817 RtlDeactivateActivationContextUnsafeFast(&ActCtx);
818
819 /* Save the Current DLL Initializer */
820 LdrpCurrentDllInitializer = OldInitializer;
821
822 /* Mark the entry as processed */
823 LdrEntry->Flags |= LDRP_PROCESS_ATTACH_CALLED;
824
825 /* Fail if DLL init failed */
826 if (!DllStatus)
827 {
828 DPRINT1("LDR: DLL_PROCESS_ATTACH for dll \"%wZ\" (InitRoutine: %p) failed\n",
829 &LdrEntry->BaseDllName, EntryPoint);
830
831 Status = STATUS_DLL_INIT_FAILED;
832 goto Quickie;
833 }
834 }
835 }
836
837 /* Loop in order */
838 ListHead = &Peb->Ldr->InInitializationOrderModuleList;
839 NextEntry = NextEntry->Flink;
840 while (NextEntry != ListHead)
841 {
842 /* Get the Data Entrry */
843 LdrEntry = CONTAINING_RECORD(NextEntry, LDR_DATA_TABLE_ENTRY, InInitializationOrderModuleList);
844
845 /* FIXME: Verify NX Compat */
846 // LdrpCheckNXCompatibility()
847
848 /* Next entry */
849 NextEntry = NextEntry->Flink;
850 }
851
852 /* Check for TLS */
853 if (LdrpImageHasTls && Context)
854 {
855 /* Set up the Act Ctx */
856 ActCtx.Size = sizeof(ActCtx);
857 ActCtx.Format = 1;
858 RtlZeroMemory(&ActCtx.Frame, sizeof(RTL_ACTIVATION_CONTEXT_STACK_FRAME));
859
860 /* Activate the ActCtx */
861 RtlActivateActivationContextUnsafeFast(&ActCtx,
862 LdrpImageEntry->EntryPointActivationContext);
863
864 /* Do TLS callbacks */
865 LdrpCallTlsInitializers(Peb->ImageBaseAddress, DLL_PROCESS_ATTACH);
866
867 /* Deactivate the ActCtx */
868 RtlDeactivateActivationContextUnsafeFast(&ActCtx);
869 }
870
871 Quickie:
872 /* Restore old TEB */
873 LdrpTopLevelDllBeingLoadedTeb = OldTldTeb;
874
875 /* Check if the array is in the heap */
876 if (LdrRootEntry != LocalArray)
877 {
878 /* Free the array */
879 RtlFreeHeap(RtlGetProcessHeap(), 0, LdrRootEntry);
880 }
881
882 /* Return to caller */
883 DPRINT("LdrpRunInitializeRoutines() done\n");
884 return Status;
885 }
886
887 /*
888 * @implemented
889 */
890 NTSTATUS
891 NTAPI
892 LdrShutdownProcess(VOID)
893 {
894 PPEB Peb = NtCurrentPeb();
895 PLDR_DATA_TABLE_ENTRY LdrEntry;
896 PLIST_ENTRY NextEntry, ListHead;
897 RTL_CALLER_ALLOCATED_ACTIVATION_CONTEXT_STACK_FRAME_EXTENDED ActCtx;
898 PVOID EntryPoint;
899
900 DPRINT("LdrShutdownProcess() called for %wZ\n", &LdrpImageEntry->BaseDllName);
901 if (LdrpShutdownInProgress) return STATUS_SUCCESS;
902
903 /* Tell the Shim Engine */
904 //if (ShimsEnabled)
905 //{
906 /* FIXME */
907 //}
908
909 /* Tell the world */
910 if (ShowSnaps)
911 {
912 DPRINT1("\n");
913 }
914
915 /* Set the shutdown variables */
916 LdrpShutdownThreadId = NtCurrentTeb()->RealClientId.UniqueThread;
917 LdrpShutdownInProgress = TRUE;
918
919 /* Enter the Loader Lock */
920 RtlEnterCriticalSection(&LdrpLoaderLock);
921
922 /* Cleanup trace logging data (Etw) */
923 if (SharedUserData->TraceLogging)
924 {
925 /* FIXME */
926 DPRINT1("We don't support Etw yet.\n");
927 }
928
929 /* Start at the end */
930 ListHead = &Peb->Ldr->InInitializationOrderModuleList;
931 NextEntry = ListHead->Blink;
932 while (NextEntry != ListHead)
933 {
934 /* Get the current entry */
935 LdrEntry = CONTAINING_RECORD(NextEntry, LDR_DATA_TABLE_ENTRY, InInitializationOrderModuleList);
936 NextEntry = NextEntry->Blink;
937
938 /* Make sure it's not ourselves */
939 if (Peb->ImageBaseAddress != LdrEntry->DllBase)
940 {
941 /* Get the entrypoint */
942 EntryPoint = LdrEntry->EntryPoint;
943
944 /* Check if we are ready to call it */
945 if (EntryPoint &&
946 (LdrEntry->Flags & LDRP_PROCESS_ATTACH_CALLED) &&
947 LdrEntry->Flags)
948 {
949 /* Set up the Act Ctx */
950 ActCtx.Size = sizeof(ActCtx);
951 ActCtx.Format = 1;
952 RtlZeroMemory(&ActCtx.Frame, sizeof(RTL_ACTIVATION_CONTEXT_STACK_FRAME));
953
954 /* Activate the ActCtx */
955 RtlActivateActivationContextUnsafeFast(&ActCtx,
956 LdrEntry->EntryPointActivationContext);
957
958 /* Check if it has TLS */
959 if (LdrEntry->TlsIndex)
960 {
961 /* Call TLS */
962 LdrpCallTlsInitializers(LdrEntry->DllBase, DLL_PROCESS_DETACH);
963 }
964
965 /* Call the Entrypoint */
966 DPRINT("%wZ - Calling entry point at %x for thread detaching\n",
967 &LdrEntry->BaseDllName, LdrEntry->EntryPoint);
968 LdrpCallInitRoutine(EntryPoint,
969 LdrEntry->DllBase,
970 DLL_PROCESS_DETACH,
971 (PVOID)1);
972
973 /* Deactivate the ActCtx */
974 RtlDeactivateActivationContextUnsafeFast(&ActCtx);
975 }
976 }
977 }
978
979 /* Check for TLS */
980 if (LdrpImageHasTls)
981 {
982 /* Set up the Act Ctx */
983 ActCtx.Size = sizeof(ActCtx);
984 ActCtx.Format = 1;
985 RtlZeroMemory(&ActCtx.Frame, sizeof(RTL_ACTIVATION_CONTEXT_STACK_FRAME));
986
987 /* Activate the ActCtx */
988 RtlActivateActivationContextUnsafeFast(&ActCtx,
989 LdrpImageEntry->EntryPointActivationContext);
990
991 /* Do TLS callbacks */
992 LdrpCallTlsInitializers(Peb->ImageBaseAddress, DLL_PROCESS_DETACH);
993
994 /* Deactivate the ActCtx */
995 RtlDeactivateActivationContextUnsafeFast(&ActCtx);
996 }
997
998 /* FIXME: Do Heap detection and Etw final shutdown */
999
1000 /* Release the lock */
1001 RtlLeaveCriticalSection(&LdrpLoaderLock);
1002 DPRINT("LdrpShutdownProcess() done\n");
1003
1004 return STATUS_SUCCESS;
1005 }
1006
1007 /*
1008 * @implemented
1009 */
1010 NTSTATUS
1011 NTAPI
1012 LdrShutdownThread(VOID)
1013 {
1014 PPEB Peb = NtCurrentPeb();
1015 PTEB Teb = NtCurrentTeb();
1016 PLDR_DATA_TABLE_ENTRY LdrEntry;
1017 PLIST_ENTRY NextEntry, ListHead;
1018 RTL_CALLER_ALLOCATED_ACTIVATION_CONTEXT_STACK_FRAME_EXTENDED ActCtx;
1019 PVOID EntryPoint;
1020
1021 DPRINT("LdrShutdownThread() called for %wZ\n",
1022 &LdrpImageEntry->BaseDllName);
1023
1024 /* Cleanup trace logging data (Etw) */
1025 if (SharedUserData->TraceLogging)
1026 {
1027 /* FIXME */
1028 DPRINT1("We don't support Etw yet.\n");
1029 }
1030
1031 /* Get the Ldr Lock */
1032 RtlEnterCriticalSection(&LdrpLoaderLock);
1033
1034 /* Start at the end */
1035 ListHead = &Peb->Ldr->InInitializationOrderModuleList;
1036 NextEntry = ListHead->Blink;
1037 while (NextEntry != ListHead)
1038 {
1039 /* Get the current entry */
1040 LdrEntry = CONTAINING_RECORD(NextEntry, LDR_DATA_TABLE_ENTRY, InInitializationOrderModuleList);
1041 NextEntry = NextEntry->Blink;
1042
1043 /* Make sure it's not ourselves */
1044 if (Peb->ImageBaseAddress != LdrEntry->DllBase)
1045 {
1046 /* Check if we should call */
1047 if (!(LdrEntry->Flags & LDRP_DONT_CALL_FOR_THREADS) &&
1048 (LdrEntry->Flags & LDRP_PROCESS_ATTACH_CALLED) &&
1049 (LdrEntry->Flags & LDRP_IMAGE_DLL))
1050 {
1051 /* Get the entrypoint */
1052 EntryPoint = LdrEntry->EntryPoint;
1053
1054 /* Check if we are ready to call it */
1055 if (EntryPoint)
1056 {
1057 /* Set up the Act Ctx */
1058 ActCtx.Size = sizeof(ActCtx);
1059 ActCtx.Format = 1;
1060 RtlZeroMemory(&ActCtx.Frame, sizeof(RTL_ACTIVATION_CONTEXT_STACK_FRAME));
1061
1062 /* Activate the ActCtx */
1063 RtlActivateActivationContextUnsafeFast(&ActCtx,
1064 LdrEntry->EntryPointActivationContext);
1065
1066 /* Check if it has TLS */
1067 if (LdrEntry->TlsIndex)
1068 {
1069 /* Make sure we're not shutting down */
1070 if (!LdrpShutdownInProgress)
1071 {
1072 /* Call TLS */
1073 LdrpCallTlsInitializers(LdrEntry->DllBase, DLL_THREAD_DETACH);
1074 }
1075 }
1076
1077 /* Make sure we're not shutting down */
1078 if (!LdrpShutdownInProgress)
1079 {
1080 /* Call the Entrypoint */
1081 DPRINT("%wZ - Calling entry point at %x for thread detaching\n",
1082 &LdrEntry->BaseDllName, LdrEntry->EntryPoint);
1083 LdrpCallInitRoutine(EntryPoint,
1084 LdrEntry->DllBase,
1085 DLL_THREAD_DETACH,
1086 NULL);
1087 }
1088
1089 /* Deactivate the ActCtx */
1090 RtlDeactivateActivationContextUnsafeFast(&ActCtx);
1091 }
1092 }
1093 }
1094 }
1095
1096 /* Check for TLS */
1097 if (LdrpImageHasTls)
1098 {
1099 /* Set up the Act Ctx */
1100 ActCtx.Size = sizeof(ActCtx);
1101 ActCtx.Format = 1;
1102 RtlZeroMemory(&ActCtx.Frame, sizeof(RTL_ACTIVATION_CONTEXT_STACK_FRAME));
1103
1104 /* Activate the ActCtx */
1105 RtlActivateActivationContextUnsafeFast(&ActCtx,
1106 LdrpImageEntry->EntryPointActivationContext);
1107
1108 /* Do TLS callbacks */
1109 LdrpCallTlsInitializers(Peb->ImageBaseAddress, DLL_THREAD_DETACH);
1110
1111 /* Deactivate the ActCtx */
1112 RtlDeactivateActivationContextUnsafeFast(&ActCtx);
1113 }
1114
1115 /* Free TLS */
1116 LdrpFreeTls();
1117 RtlLeaveCriticalSection(&LdrpLoaderLock);
1118
1119 /* Check for expansion slots */
1120 if (Teb->TlsExpansionSlots)
1121 {
1122 /* Free expansion slots */
1123 RtlFreeHeap(RtlGetProcessHeap(), 0, Teb->TlsExpansionSlots);
1124 }
1125
1126 /* Check for FLS Data */
1127 if (Teb->FlsData)
1128 {
1129 /* FIXME */
1130 DPRINT1("We don't support FLS Data yet\n");
1131 }
1132
1133 /* Check for Fiber data */
1134 if (Teb->HasFiberData)
1135 {
1136 /* Free Fiber data*/
1137 RtlFreeHeap(RtlGetProcessHeap(), 0, Teb->NtTib.FiberData);
1138 Teb->NtTib.FiberData = NULL;
1139 }
1140
1141 /* Free the activation context stack */
1142 RtlFreeThreadActivationContextStack();
1143 DPRINT("LdrShutdownThread() done\n");
1144
1145 return STATUS_SUCCESS;
1146 }
1147
1148 NTSTATUS
1149 NTAPI
1150 LdrpInitializeTls(VOID)
1151 {
1152 PLIST_ENTRY NextEntry, ListHead;
1153 PLDR_DATA_TABLE_ENTRY LdrEntry;
1154 PIMAGE_TLS_DIRECTORY TlsDirectory;
1155 PLDRP_TLS_DATA TlsData;
1156 ULONG Size;
1157
1158 /* Initialize the TLS List */
1159 InitializeListHead(&LdrpTlsList);
1160
1161 /* Loop all the modules */
1162 ListHead = &NtCurrentPeb()->Ldr->InLoadOrderModuleList;
1163 NextEntry = ListHead->Flink;
1164 while (ListHead != NextEntry)
1165 {
1166 /* Get the entry */
1167 LdrEntry = CONTAINING_RECORD(NextEntry, LDR_DATA_TABLE_ENTRY, InLoadOrderLinks);
1168 NextEntry = NextEntry->Flink;
1169
1170 /* Get the TLS directory */
1171 TlsDirectory = RtlImageDirectoryEntryToData(LdrEntry->DllBase,
1172 TRUE,
1173 IMAGE_DIRECTORY_ENTRY_TLS,
1174 &Size);
1175
1176 /* Check if we have a directory */
1177 if (!TlsDirectory) continue;
1178
1179 /* Check if the image has TLS */
1180 if (!LdrpImageHasTls) LdrpImageHasTls = TRUE;
1181
1182 /* Show debug message */
1183 if (ShowSnaps)
1184 {
1185 DPRINT1("LDR: Tls Found in %wZ at %p\n",
1186 &LdrEntry->BaseDllName,
1187 TlsDirectory);
1188 }
1189
1190 /* Allocate an entry */
1191 TlsData = RtlAllocateHeap(RtlGetProcessHeap(), 0, sizeof(LDRP_TLS_DATA));
1192 if (!TlsData) return STATUS_NO_MEMORY;
1193
1194 /* Lock the DLL and mark it for TLS Usage */
1195 LdrEntry->LoadCount = -1;
1196 LdrEntry->TlsIndex = -1;
1197
1198 /* Save the cached TLS data */
1199 TlsData->TlsDirectory = *TlsDirectory;
1200 InsertTailList(&LdrpTlsList, &TlsData->TlsLinks);
1201
1202 /* Update the index */
1203 *(PLONG)TlsData->TlsDirectory.AddressOfIndex = LdrpNumberOfTlsEntries;
1204 TlsData->TlsDirectory.Characteristics = LdrpNumberOfTlsEntries++;
1205 }
1206
1207 /* Done setting up TLS, allocate entries */
1208 return LdrpAllocateTls();
1209 }
1210
1211 NTSTATUS
1212 NTAPI
1213 LdrpAllocateTls(VOID)
1214 {
1215 PTEB Teb = NtCurrentTeb();
1216 PLIST_ENTRY NextEntry, ListHead;
1217 PLDRP_TLS_DATA TlsData;
1218 SIZE_T TlsDataSize;
1219 PVOID *TlsVector;
1220
1221 /* Check if we have any entries */
1222 if (!LdrpNumberOfTlsEntries)
1223 return STATUS_SUCCESS;
1224
1225 /* Allocate the vector array */
1226 TlsVector = RtlAllocateHeap(RtlGetProcessHeap(),
1227 0,
1228 LdrpNumberOfTlsEntries * sizeof(PVOID));
1229 if (!TlsVector) return STATUS_NO_MEMORY;
1230 Teb->ThreadLocalStoragePointer = TlsVector;
1231
1232 /* Loop the TLS Array */
1233 ListHead = &LdrpTlsList;
1234 NextEntry = ListHead->Flink;
1235 while (NextEntry != ListHead)
1236 {
1237 /* Get the entry */
1238 TlsData = CONTAINING_RECORD(NextEntry, LDRP_TLS_DATA, TlsLinks);
1239 NextEntry = NextEntry->Flink;
1240
1241 /* Allocate this vector */
1242 TlsDataSize = TlsData->TlsDirectory.EndAddressOfRawData -
1243 TlsData->TlsDirectory.StartAddressOfRawData;
1244 TlsVector[TlsData->TlsDirectory.Characteristics] = RtlAllocateHeap(RtlGetProcessHeap(),
1245 0,
1246 TlsDataSize);
1247 if (!TlsVector[TlsData->TlsDirectory.Characteristics])
1248 {
1249 /* Out of memory */
1250 return STATUS_NO_MEMORY;
1251 }
1252
1253 /* Show debug message */
1254 if (ShowSnaps)
1255 {
1256 DPRINT1("LDR: TlsVector %x Index %d = %x copied from %x to %x\n",
1257 TlsVector,
1258 TlsData->TlsDirectory.Characteristics,
1259 &TlsVector[TlsData->TlsDirectory.Characteristics],
1260 TlsData->TlsDirectory.StartAddressOfRawData,
1261 TlsVector[TlsData->TlsDirectory.Characteristics]);
1262 }
1263
1264 /* Copy the data */
1265 RtlCopyMemory(TlsVector[TlsData->TlsDirectory.Characteristics],
1266 (PVOID)TlsData->TlsDirectory.StartAddressOfRawData,
1267 TlsDataSize);
1268 }
1269
1270 /* Done */
1271 return STATUS_SUCCESS;
1272 }
1273
1274 VOID
1275 NTAPI
1276 LdrpFreeTls(VOID)
1277 {
1278 PLIST_ENTRY ListHead, NextEntry;
1279 PLDRP_TLS_DATA TlsData;
1280 PVOID *TlsVector;
1281 PTEB Teb = NtCurrentTeb();
1282
1283 /* Get a pointer to the vector array */
1284 TlsVector = Teb->ThreadLocalStoragePointer;
1285 if (!TlsVector) return;
1286
1287 /* Loop through it */
1288 ListHead = &LdrpTlsList;
1289 NextEntry = ListHead->Flink;
1290 while (NextEntry != ListHead)
1291 {
1292 TlsData = CONTAINING_RECORD(NextEntry, LDRP_TLS_DATA, TlsLinks);
1293 NextEntry = NextEntry->Flink;
1294
1295 /* Free each entry */
1296 if (TlsVector[TlsData->TlsDirectory.Characteristics])
1297 {
1298 RtlFreeHeap(RtlGetProcessHeap(),
1299 0,
1300 TlsVector[TlsData->TlsDirectory.Characteristics]);
1301 }
1302 }
1303
1304 /* Free the array itself */
1305 RtlFreeHeap(RtlGetProcessHeap(),
1306 0,
1307 TlsVector);
1308 }
1309
1310 NTSTATUS
1311 NTAPI
1312 LdrpInitializeApplicationVerifierPackage(PUNICODE_STRING ImagePathName, PPEB Peb, BOOLEAN SystemWide, BOOLEAN ReadAdvancedOptions)
1313 {
1314 /* If global flags request DPH, perform some additional actions */
1315 if (Peb->NtGlobalFlag & FLG_HEAP_PAGE_ALLOCS)
1316 {
1317 // TODO: Read advanced DPH flags from the registry if requested
1318 if (ReadAdvancedOptions)
1319 {
1320 UNIMPLEMENTED;
1321 }
1322
1323 /* Enable page heap */
1324 RtlpPageHeapEnabled = TRUE;
1325 }
1326
1327 return STATUS_SUCCESS;
1328 }
1329
1330 NTSTATUS
1331 NTAPI
1332 LdrpInitializeExecutionOptions(PUNICODE_STRING ImagePathName, PPEB Peb, PHANDLE OptionsKey)
1333 {
1334 NTSTATUS Status;
1335 HANDLE KeyHandle;
1336 ULONG ExecuteOptions, MinimumStackCommit = 0, GlobalFlag;
1337
1338 /* Return error if we were not provided a pointer where to save the options key handle */
1339 if (!OptionsKey) return STATUS_INVALID_HANDLE;
1340
1341 /* Zero initialize the optinos key pointer */
1342 *OptionsKey = NULL;
1343
1344 /* Open the options key */
1345 Status = LdrOpenImageFileOptionsKey(ImagePathName, 0, &KeyHandle);
1346
1347 /* Save it if it was opened successfully */
1348 if (NT_SUCCESS(Status))
1349 *OptionsKey = KeyHandle;
1350
1351 if (KeyHandle)
1352 {
1353 /* There are image specific options, read them starting with NXCOMPAT */
1354 Status = LdrQueryImageFileKeyOption(KeyHandle,
1355 L"ExecuteOptions",
1356 4,
1357 &ExecuteOptions,
1358 sizeof(ExecuteOptions),
1359 0);
1360
1361 if (NT_SUCCESS(Status))
1362 {
1363 /* TODO: Set execution options for the process */
1364 /*
1365 if (ExecuteOptions == 0)
1366 ExecuteOptions = 1;
1367 else
1368 ExecuteOptions = 2;
1369 ZwSetInformationProcess(NtCurrentProcess(),
1370 ProcessExecuteFlags,
1371 &ExecuteOptions,
1372 sizeof(ULONG));*/
1373
1374 }
1375
1376 /* Check if this image uses large pages */
1377 if (Peb->ImageUsesLargePages)
1378 {
1379 /* TODO: If it does, open large page key */
1380 UNIMPLEMENTED;
1381 }
1382
1383 /* Get various option values */
1384 LdrQueryImageFileKeyOption(KeyHandle,
1385 L"DisableHeapLookaside",
1386 REG_DWORD,
1387 &RtlpDisableHeapLookaside,
1388 sizeof(RtlpDisableHeapLookaside),
1389 NULL);
1390
1391 LdrQueryImageFileKeyOption(KeyHandle,
1392 L"ShutdownFlags",
1393 REG_DWORD,
1394 &RtlpShutdownProcessFlags,
1395 sizeof(RtlpShutdownProcessFlags),
1396 NULL);
1397
1398 LdrQueryImageFileKeyOption(KeyHandle,
1399 L"MinimumStackCommitInBytes",
1400 REG_DWORD,
1401 &MinimumStackCommit,
1402 sizeof(MinimumStackCommit),
1403 NULL);
1404
1405 /* Update PEB's minimum stack commit if it's lower */
1406 if (Peb->MinimumStackCommit < MinimumStackCommit)
1407 Peb->MinimumStackCommit = MinimumStackCommit;
1408
1409 /* Set the global flag */
1410 Status = LdrQueryImageFileKeyOption(KeyHandle,
1411 L"GlobalFlag",
1412 REG_DWORD,
1413 &GlobalFlag,
1414 sizeof(GlobalFlag),
1415 NULL);
1416
1417 if (NT_SUCCESS(Status))
1418 Peb->NtGlobalFlag = GlobalFlag;
1419 else
1420 GlobalFlag = 0;
1421
1422 /* Call AVRF if necessary */
1423 if (Peb->NtGlobalFlag & (FLG_POOL_ENABLE_TAIL_CHECK | FLG_HEAP_PAGE_ALLOCS))
1424 {
1425 Status = LdrpInitializeApplicationVerifierPackage(ImagePathName, Peb, TRUE, FALSE);
1426 if (!NT_SUCCESS(Status))
1427 {
1428 DPRINT1("AVRF: LdrpInitializeApplicationVerifierPackage failed with %08X\n", Status);
1429 }
1430 }
1431 }
1432 else
1433 {
1434 /* There are no image-specific options, so perform global initialization */
1435 if (Peb->NtGlobalFlag & (FLG_POOL_ENABLE_TAIL_CHECK | FLG_HEAP_PAGE_ALLOCS))
1436 {
1437 /* Initialize app verifier package */
1438 Status = LdrpInitializeApplicationVerifierPackage(ImagePathName, Peb, TRUE, FALSE);
1439 if (!NT_SUCCESS(Status))
1440 {
1441 DPRINT1("AVRF: LdrpInitializeApplicationVerifierPackage failed with %08X\n", Status);
1442 }
1443 }
1444 }
1445
1446 return STATUS_SUCCESS;
1447 }
1448
1449 VOID
1450 NTAPI
1451 LdrpValidateImageForMp(IN PLDR_DATA_TABLE_ENTRY LdrDataTableEntry)
1452 {
1453 UNIMPLEMENTED;
1454 }
1455
1456 NTSTATUS
1457 NTAPI
1458 LdrpInitializeProcess(IN PCONTEXT Context,
1459 IN PVOID SystemArgument1)
1460 {
1461 RTL_HEAP_PARAMETERS HeapParameters;
1462 ULONG ComSectionSize;
1463 //ANSI_STRING FunctionName = RTL_CONSTANT_STRING("BaseQueryModuleData");
1464 PVOID OldShimData;
1465 OBJECT_ATTRIBUTES ObjectAttributes;
1466 //UNICODE_STRING LocalFileName, FullImageName;
1467 HANDLE SymLinkHandle;
1468 //ULONG DebugHeapOnly;
1469 UNICODE_STRING CommandLine, NtSystemRoot, ImagePathName, FullPath, ImageFileName, KnownDllString;
1470 PPEB Peb = NtCurrentPeb();
1471 BOOLEAN IsDotNetImage = FALSE;
1472 BOOLEAN FreeCurDir = FALSE;
1473 //HANDLE CompatKey;
1474 PRTL_USER_PROCESS_PARAMETERS ProcessParameters;
1475 //LPWSTR ImagePathBuffer;
1476 ULONG ConfigSize;
1477 UNICODE_STRING CurrentDirectory;
1478 HANDLE OptionsKey;
1479 ULONG HeapFlags;
1480 PIMAGE_NT_HEADERS NtHeader;
1481 LPWSTR NtDllName = NULL;
1482 NTSTATUS Status, ImportStatus;
1483 NLSTABLEINFO NlsTable;
1484 PIMAGE_LOAD_CONFIG_DIRECTORY LoadConfig;
1485 PTEB Teb = NtCurrentTeb();
1486 PLIST_ENTRY ListHead;
1487 PLIST_ENTRY NextEntry;
1488 ULONG i;
1489 PWSTR ImagePath;
1490 ULONG DebugProcessHeapOnly = 0;
1491 PLDR_DATA_TABLE_ENTRY NtLdrEntry;
1492 PWCHAR Current;
1493 ULONG ExecuteOptions = 0;
1494 PVOID ViewBase;
1495
1496 /* Set a NULL SEH Filter */
1497 RtlSetUnhandledExceptionFilter(NULL);
1498
1499 /* Get the image path */
1500 ImagePath = Peb->ProcessParameters->ImagePathName.Buffer;
1501
1502 /* Check if it's not normalized */
1503 if (!(Peb->ProcessParameters->Flags & RTL_USER_PROCESS_PARAMETERS_NORMALIZED))
1504 {
1505 /* Normalize it*/
1506 ImagePath = (PWSTR)((ULONG_PTR)ImagePath + (ULONG_PTR)Peb->ProcessParameters);
1507 }
1508
1509 /* Create a unicode string for the Image Path */
1510 ImagePathName.Length = Peb->ProcessParameters->ImagePathName.Length;
1511 ImagePathName.MaximumLength = ImagePathName.Length + sizeof(WCHAR);
1512 ImagePathName.Buffer = ImagePath;
1513
1514 /* Get the NT Headers */
1515 NtHeader = RtlImageNtHeader(Peb->ImageBaseAddress);
1516
1517 /* Get the execution options */
1518 Status = LdrpInitializeExecutionOptions(&ImagePathName, Peb, &OptionsKey);
1519
1520 /* Check if this is a .NET executable */
1521 if (RtlImageDirectoryEntryToData(Peb->ImageBaseAddress,
1522 TRUE,
1523 IMAGE_DIRECTORY_ENTRY_COM_DESCRIPTOR,
1524 &ComSectionSize))
1525 {
1526 /* Remeber this for later */
1527 IsDotNetImage = TRUE;
1528 }
1529
1530 /* Save the NTDLL Base address */
1531 NtDllBase = SystemArgument1;
1532
1533 /* If this is a Native Image */
1534 if (NtHeader->OptionalHeader.Subsystem == IMAGE_SUBSYSTEM_NATIVE)
1535 {
1536 /* Then do DLL Validation */
1537 LdrpDllValidation = TRUE;
1538 }
1539
1540 /* Save the old Shim Data */
1541 OldShimData = Peb->pShimData;
1542
1543 /* Clear it */
1544 Peb->pShimData = NULL;
1545
1546 /* Save the number of processors and CS Timeout */
1547 LdrpNumberOfProcessors = Peb->NumberOfProcessors;
1548 RtlpTimeout = Peb->CriticalSectionTimeout;
1549
1550 /* Normalize the parameters */
1551 ProcessParameters = RtlNormalizeProcessParams(Peb->ProcessParameters);
1552 if (ProcessParameters)
1553 {
1554 /* Save the Image and Command Line Names */
1555 ImageFileName = ProcessParameters->ImagePathName;
1556 CommandLine = ProcessParameters->CommandLine;
1557 }
1558 else
1559 {
1560 /* It failed, initialize empty strings */
1561 RtlInitUnicodeString(&ImageFileName, NULL);
1562 RtlInitUnicodeString(&CommandLine, NULL);
1563 }
1564
1565 /* Initialize NLS data */
1566 RtlInitNlsTables(Peb->AnsiCodePageData,
1567 Peb->OemCodePageData,
1568 Peb->UnicodeCaseTableData,
1569 &NlsTable);
1570
1571 /* Reset NLS Translations */
1572 RtlResetRtlTranslations(&NlsTable);
1573
1574 /* Get the Image Config Directory */
1575 LoadConfig = RtlImageDirectoryEntryToData(Peb->ImageBaseAddress,
1576 TRUE,
1577 IMAGE_DIRECTORY_ENTRY_LOAD_CONFIG,
1578 &ConfigSize);
1579
1580 /* Setup the Heap Parameters */
1581 RtlZeroMemory(&HeapParameters, sizeof(RTL_HEAP_PARAMETERS));
1582 HeapFlags = HEAP_GROWABLE;
1583 HeapParameters.Length = sizeof(RTL_HEAP_PARAMETERS);
1584
1585 /* Check if we have Configuration Data */
1586 if ((LoadConfig) && (ConfigSize == sizeof(IMAGE_LOAD_CONFIG_DIRECTORY)))
1587 {
1588 /* FIXME: Custom heap settings and misc. */
1589 DPRINT1("We don't support LOAD_CONFIG data yet\n");
1590 }
1591
1592 /* Check for custom affinity mask */
1593 if (Peb->ImageProcessAffinityMask)
1594 {
1595 /* Set it */
1596 Status = NtSetInformationProcess(NtCurrentProcess(),
1597 ProcessAffinityMask,
1598 &Peb->ImageProcessAffinityMask,
1599 sizeof(Peb->ImageProcessAffinityMask));
1600 }
1601
1602 /* Check if verbose debugging (ShowSnaps) was requested */
1603 ShowSnaps = Peb->NtGlobalFlag & FLG_SHOW_LDR_SNAPS;
1604
1605 /* Start verbose debugging messages right now if they were requested */
1606 if (ShowSnaps)
1607 {
1608 DPRINT1("LDR: PID: 0x%x started - '%wZ'\n",
1609 Teb->ClientId.UniqueProcess,
1610 &CommandLine);
1611 }
1612
1613 /* If the timeout is too long */
1614 if (RtlpTimeout.QuadPart < Int32x32To64(3600, -10000000))
1615 {
1616 /* Then disable CS Timeout */
1617 RtlpTimeoutDisable = TRUE;
1618 }
1619
1620 /* Initialize Critical Section Data */
1621 RtlpInitDeferedCriticalSection();
1622
1623 /* Initialize VEH Call lists */
1624 RtlpInitializeVectoredExceptionHandling();
1625
1626 /* Set TLS/FLS Bitmap data */
1627 Peb->FlsBitmap = &FlsBitMap;
1628 Peb->TlsBitmap = &TlsBitMap;
1629 Peb->TlsExpansionBitmap = &TlsExpansionBitMap;
1630
1631 /* Initialize FLS Bitmap */
1632 RtlInitializeBitMap(&FlsBitMap,
1633 Peb->FlsBitmapBits,
1634 FLS_MAXIMUM_AVAILABLE);
1635 RtlSetBit(&FlsBitMap, 0);
1636
1637 /* Initialize TLS Bitmap */
1638 RtlInitializeBitMap(&TlsBitMap,
1639 Peb->TlsBitmapBits,
1640 TLS_MINIMUM_AVAILABLE);
1641 RtlSetBit(&TlsBitMap, 0);
1642 RtlInitializeBitMap(&TlsExpansionBitMap,
1643 Peb->TlsExpansionBitmapBits,
1644 TLS_EXPANSION_SLOTS);
1645 RtlSetBit(&TlsExpansionBitMap, 0);
1646
1647 /* Initialize the Hash Table */
1648 for (i = 0; i < LDR_HASH_TABLE_ENTRIES; i++)
1649 {
1650 InitializeListHead(&LdrpHashTable[i]);
1651 }
1652
1653 /* Initialize the Loader Lock */
1654 // FIXME: What's the point of initing it manually, if two lines lower
1655 // a call to RtlInitializeCriticalSection() is being made anyway?
1656 //InsertTailList(&RtlCriticalSectionList, &LdrpLoaderLock.DebugInfo->ProcessLocksList);
1657 //LdrpLoaderLock.DebugInfo->CriticalSection = &LdrpLoaderLock;
1658 RtlInitializeCriticalSection(&LdrpLoaderLock);
1659 LdrpLoaderLockInit = TRUE;
1660
1661 /* Check if User Stack Trace Database support was requested */
1662 if (Peb->NtGlobalFlag & FLG_USER_STACK_TRACE_DB)
1663 {
1664 DPRINT1("We don't support user stack trace databases yet\n");
1665 }
1666
1667 /* Setup Fast PEB Lock */
1668 RtlInitializeCriticalSection(&FastPebLock);
1669 Peb->FastPebLock = &FastPebLock;
1670 //Peb->FastPebLockRoutine = (PPEBLOCKROUTINE)RtlEnterCriticalSection;
1671 //Peb->FastPebUnlockRoutine = (PPEBLOCKROUTINE)RtlLeaveCriticalSection;
1672
1673 /* Setup Callout Lock and Notification list */
1674 //RtlInitializeCriticalSection(&RtlpCalloutEntryLock);
1675 InitializeListHead(&LdrpDllNotificationList);
1676
1677 /* For old executables, use 16-byte aligned heap */
1678 if ((NtHeader->OptionalHeader.MajorSubsystemVersion <= 3) &&
1679 (NtHeader->OptionalHeader.MinorSubsystemVersion < 51))
1680 {
1681 HeapFlags |= HEAP_CREATE_ALIGN_16;
1682 }
1683
1684 /* Setup the Heap */
1685 RtlInitializeHeapManager();
1686 Peb->ProcessHeap = RtlCreateHeap(HeapFlags,
1687 NULL,
1688 NtHeader->OptionalHeader.SizeOfHeapReserve,
1689 NtHeader->OptionalHeader.SizeOfHeapCommit,
1690 NULL,
1691 &HeapParameters);
1692
1693 if (!Peb->ProcessHeap)
1694 {
1695 DPRINT1("Failed to create process heap\n");
1696 return STATUS_NO_MEMORY;
1697 }
1698
1699 // FIXME: Is it located properly?
1700 /* Initialize table of callbacks for the kernel. */
1701 Peb->KernelCallbackTable = RtlAllocateHeap(RtlGetProcessHeap(),
1702 0,
1703 sizeof(PVOID) *
1704 (USER32_CALLBACK_MAXIMUM + 1));
1705 if (!Peb->KernelCallbackTable)
1706 {
1707 DPRINT1("Failed to create callback table\n");
1708 ZwTerminateProcess(NtCurrentProcess(), STATUS_INSUFFICIENT_RESOURCES);
1709 }
1710
1711 /* Allocate an Activation Context Stack */
1712 Status = RtlAllocateActivationContextStack((PVOID *)&Teb->ActivationContextStackPointer);
1713 if (!NT_SUCCESS(Status)) return Status;
1714
1715 // FIXME: Loader private heap is missing
1716 //DPRINT1("Loader private heap is missing\n");
1717
1718 /* Check for Debug Heap */
1719 if (OptionsKey)
1720 {
1721 /* Query the setting */
1722 Status = LdrQueryImageFileKeyOption(OptionsKey,
1723 L"DebugProcessHeapOnly",
1724 REG_DWORD,
1725 &DebugProcessHeapOnly,
1726 sizeof(ULONG),
1727 NULL);
1728
1729 if (NT_SUCCESS(Status))
1730 {
1731 /* Reset DPH if requested */
1732 if (RtlpPageHeapEnabled && DebugProcessHeapOnly)
1733 {
1734 RtlpDphGlobalFlags &= ~DPH_FLAG_DLL_NOTIFY;
1735 RtlpPageHeapEnabled = FALSE;
1736 }
1737 }
1738 }
1739
1740 /* Build the NTDLL Path */
1741 FullPath.Buffer = StringBuffer;
1742 FullPath.Length = 0;
1743 FullPath.MaximumLength = sizeof(StringBuffer);
1744 RtlInitUnicodeString(&NtSystemRoot, SharedUserData->NtSystemRoot);
1745 RtlAppendUnicodeStringToString(&FullPath, &NtSystemRoot);
1746 RtlAppendUnicodeToString(&FullPath, L"\\System32\\");
1747
1748 /* Open the Known DLLs directory */
1749 RtlInitUnicodeString(&KnownDllString, L"\\KnownDlls");
1750 InitializeObjectAttributes(&ObjectAttributes,
1751 &KnownDllString,
1752 OBJ_CASE_INSENSITIVE,
1753 NULL,
1754 NULL);
1755 Status = ZwOpenDirectoryObject(&LdrpKnownDllObjectDirectory,
1756 DIRECTORY_QUERY | DIRECTORY_TRAVERSE,
1757 &ObjectAttributes);
1758
1759 /* Check if it exists */
1760 if (NT_SUCCESS(Status))
1761 {
1762 /* Open the Known DLLs Path */
1763 RtlInitUnicodeString(&KnownDllString, L"KnownDllPath");
1764 InitializeObjectAttributes(&ObjectAttributes,
1765 &KnownDllString,
1766 OBJ_CASE_INSENSITIVE,
1767 LdrpKnownDllObjectDirectory,
1768 NULL);
1769 Status = NtOpenSymbolicLinkObject(&SymLinkHandle,
1770 SYMBOLIC_LINK_QUERY,
1771 &ObjectAttributes);
1772 if (NT_SUCCESS(Status))
1773 {
1774 /* Query the path */
1775 LdrpKnownDllPath.Length = 0;
1776 LdrpKnownDllPath.MaximumLength = sizeof(LdrpKnownDllPathBuffer);
1777 LdrpKnownDllPath.Buffer = LdrpKnownDllPathBuffer;
1778 Status = ZwQuerySymbolicLinkObject(SymLinkHandle, &LdrpKnownDllPath, NULL);
1779 NtClose(SymLinkHandle);
1780 if (!NT_SUCCESS(Status))
1781 {
1782 DPRINT1("LDR: %s - failed call to ZwQuerySymbolicLinkObject with status %x\n", "", Status);
1783 return Status;
1784 }
1785 }
1786 }
1787
1788 /* Check if we failed */
1789 if (!NT_SUCCESS(Status))
1790 {
1791 /* Aassume System32 */
1792 LdrpKnownDllObjectDirectory = NULL;
1793 RtlInitUnicodeString(&LdrpKnownDllPath, StringBuffer);
1794 LdrpKnownDllPath.Length -= sizeof(WCHAR);
1795 }
1796
1797 /* If we have process parameters, get the default path and current path */
1798 if (ProcessParameters)
1799 {
1800 /* Check if we have a Dll Path */
1801 if (ProcessParameters->DllPath.Length)
1802 {
1803 /* Get the path */
1804 LdrpDefaultPath = *(PUNICODE_STRING)&ProcessParameters->DllPath;
1805 }
1806 else
1807 {
1808 /* We need a valid path */
1809 DPRINT1("No valid DllPath was given!\n");
1810 LdrpInitFailure(STATUS_INVALID_PARAMETER);
1811 }
1812
1813 /* Set the current directory */
1814 CurrentDirectory = ProcessParameters->CurrentDirectory.DosPath;
1815
1816 /* Check if it's empty or invalid */
1817 if ((!CurrentDirectory.Buffer) ||
1818 (CurrentDirectory.Buffer[0] == UNICODE_NULL) ||
1819 (!CurrentDirectory.Length))
1820 {
1821 /* Allocate space for the buffer */
1822 CurrentDirectory.Buffer = RtlAllocateHeap(Peb->ProcessHeap,
1823 0,
1824 3 * sizeof(WCHAR) +
1825 sizeof(UNICODE_NULL));
1826 if (!CurrentDirectory.Buffer)
1827 {
1828 DPRINT1("LDR: LdrpInitializeProcess - unable to allocate current working directory buffer\n");
1829 // FIXME: And what?
1830 }
1831
1832 /* Copy the drive of the system root */
1833 RtlMoveMemory(CurrentDirectory.Buffer,
1834 SharedUserData->NtSystemRoot,
1835 3 * sizeof(WCHAR));
1836 CurrentDirectory.Buffer[3] = UNICODE_NULL;
1837 CurrentDirectory.Length = 3 * sizeof(WCHAR);
1838 CurrentDirectory.MaximumLength = CurrentDirectory.Length + sizeof(WCHAR);
1839
1840 FreeCurDir = TRUE;
1841 DPRINT("Using dynamically allocd curdir\n");
1842 }
1843 else
1844 {
1845 /* Use the local buffer */
1846 DPRINT("Using local system root\n");
1847 }
1848 }
1849
1850 /* Setup Loader Data */
1851 Peb->Ldr = &PebLdr;
1852 InitializeListHead(&PebLdr.InLoadOrderModuleList);
1853 InitializeListHead(&PebLdr.InMemoryOrderModuleList);
1854 InitializeListHead(&PebLdr.InInitializationOrderModuleList);
1855 PebLdr.Length = sizeof(PEB_LDR_DATA);
1856 PebLdr.Initialized = TRUE;
1857
1858 /* Allocate a data entry for the Image */
1859 LdrpImageEntry = NtLdrEntry = LdrpAllocateDataTableEntry(Peb->ImageBaseAddress);
1860
1861 /* Set it up */
1862 NtLdrEntry->EntryPoint = LdrpFetchAddressOfEntryPoint(NtLdrEntry->DllBase);
1863 NtLdrEntry->LoadCount = -1;
1864 NtLdrEntry->EntryPointActivationContext = 0;
1865 NtLdrEntry->FullDllName = ImageFileName;
1866
1867 if (IsDotNetImage)
1868 NtLdrEntry->Flags = LDRP_COR_IMAGE;
1869 else
1870 NtLdrEntry->Flags = 0;
1871
1872 /* Check if the name is empty */
1873 if (!ImageFileName.Buffer[0])
1874 {
1875 /* Use the same Base name */
1876 NtLdrEntry->BaseDllName = NtLdrEntry->FullDllName;
1877 }
1878 else
1879 {
1880 /* Find the last slash */
1881 Current = ImageFileName.Buffer;
1882 while (*Current)
1883 {
1884 if (*Current++ == '\\')
1885 {
1886 /* Set this path */
1887 NtDllName = Current;
1888 }
1889 }
1890
1891 /* Did we find anything? */
1892 if (!NtDllName)
1893 {
1894 /* Use the same Base name */
1895 NtLdrEntry->BaseDllName = NtLdrEntry->FullDllName;
1896 }
1897 else
1898 {
1899 /* Setup the name */
1900 NtLdrEntry->BaseDllName.Length = (USHORT)((ULONG_PTR)ImageFileName.Buffer + ImageFileName.Length - (ULONG_PTR)NtDllName);
1901 NtLdrEntry->BaseDllName.MaximumLength = NtLdrEntry->BaseDllName.Length + sizeof(WCHAR);
1902 NtLdrEntry->BaseDllName.Buffer = (PWSTR)((ULONG_PTR)ImageFileName.Buffer +
1903 (ImageFileName.Length - NtLdrEntry->BaseDllName.Length));
1904 }
1905 }
1906
1907 /* Processing done, insert it */
1908 LdrpInsertMemoryTableEntry(NtLdrEntry);
1909 NtLdrEntry->Flags |= LDRP_ENTRY_PROCESSED;
1910
1911 /* Now add an entry for NTDLL */
1912 NtLdrEntry = LdrpAllocateDataTableEntry(SystemArgument1);
1913 NtLdrEntry->Flags = LDRP_IMAGE_DLL;
1914 NtLdrEntry->EntryPoint = LdrpFetchAddressOfEntryPoint(NtLdrEntry->DllBase);
1915 NtLdrEntry->LoadCount = -1;
1916 NtLdrEntry->EntryPointActivationContext = 0;
1917
1918 NtLdrEntry->FullDllName.Length = FullPath.Length;
1919 NtLdrEntry->FullDllName.MaximumLength = FullPath.MaximumLength;
1920 NtLdrEntry->FullDllName.Buffer = StringBuffer;
1921 RtlAppendUnicodeStringToString(&NtLdrEntry->FullDllName, &NtDllString);
1922
1923 NtLdrEntry->BaseDllName.Length = NtDllString.Length;
1924 NtLdrEntry->BaseDllName.MaximumLength = NtDllString.MaximumLength;
1925 NtLdrEntry->BaseDllName.Buffer = NtDllString.Buffer;
1926
1927 /* Processing done, insert it */
1928 LdrpNtDllDataTableEntry = NtLdrEntry;
1929 LdrpInsertMemoryTableEntry(NtLdrEntry);
1930
1931 /* Let the world know */
1932 if (ShowSnaps)
1933 {
1934 DPRINT1("LDR: NEW PROCESS\n");
1935 DPRINT1(" Image Path: %wZ (%wZ)\n", &LdrpImageEntry->FullDllName, &LdrpImageEntry->BaseDllName);
1936 DPRINT1(" Current Directory: %wZ\n", &CurrentDirectory);
1937 DPRINT1(" Search Path: %wZ\n", &LdrpDefaultPath);
1938 }
1939
1940 /* Link the Init Order List */
1941 InsertHeadList(&Peb->Ldr->InInitializationOrderModuleList,
1942 &LdrpNtDllDataTableEntry->InInitializationOrderModuleList);
1943
1944 /* Initialize Wine's active context implementation for the current process */
1945 actctx_init();
1946
1947 /* Set the current directory */
1948 Status = RtlSetCurrentDirectory_U(&CurrentDirectory);
1949 if (!NT_SUCCESS(Status))
1950 {
1951 /* We failed, check if we should free it */
1952 if (FreeCurDir) RtlFreeUnicodeString(&CurrentDirectory);
1953
1954 /* Set it to the NT Root */
1955 CurrentDirectory = NtSystemRoot;
1956 RtlSetCurrentDirectory_U(&CurrentDirectory);
1957 }
1958 else
1959 {
1960 /* We're done with it, free it */
1961 if (FreeCurDir) RtlFreeUnicodeString(&CurrentDirectory);
1962 }
1963
1964 /* Check if we should look for a .local file */
1965 if (ProcessParameters->Flags & RTL_USER_PROCESS_PARAMETERS_LOCAL_DLL_PATH)
1966 {
1967 /* FIXME */
1968 DPRINT1("We don't support .local overrides yet\n");
1969 }
1970
1971 /* Check if the Application Verifier was enabled */
1972 if (Peb->NtGlobalFlag & FLG_POOL_ENABLE_TAIL_CHECK)
1973 {
1974 /* FIXME */
1975 DPRINT1("We don't support Application Verifier yet\n");
1976 }
1977
1978 if (IsDotNetImage)
1979 {
1980 /* FIXME */
1981 DPRINT1("We don't support .NET applications yet\n");
1982 }
1983
1984 /* FIXME: Load support for Terminal Services */
1985 if (NtHeader->OptionalHeader.Subsystem == IMAGE_SUBSYSTEM_WINDOWS_GUI)
1986 {
1987 /* Load kernel32 and call BasePostImportInit... */
1988 DPRINT("Unimplemented codepath!\n");
1989 }
1990
1991 /* Walk the IAT and load all the DLLs */
1992 ImportStatus = LdrpWalkImportDescriptor(LdrpDefaultPath.Buffer, LdrpImageEntry);
1993
1994 /* Check if relocation is needed */
1995 if (Peb->ImageBaseAddress != (PVOID)NtHeader->OptionalHeader.ImageBase)
1996 {
1997 DPRINT1("LDR: Performing EXE relocation\n");
1998
1999 /* Change the protection to prepare for relocation */
2000 ViewBase = Peb->ImageBaseAddress;
2001 Status = LdrpSetProtection(ViewBase, FALSE);
2002 if (!NT_SUCCESS(Status)) return Status;
2003
2004 /* Do the relocation */
2005 Status = LdrRelocateImageWithBias(ViewBase,
2006 0LL,
2007 NULL,
2008 STATUS_SUCCESS,
2009 STATUS_CONFLICTING_ADDRESSES,
2010 STATUS_INVALID_IMAGE_FORMAT);
2011 if (!NT_SUCCESS(Status))
2012 {
2013 DPRINT1("LdrRelocateImageWithBias() failed\n");
2014 return Status;
2015 }
2016
2017 /* Check if a start context was provided */
2018 if (Context)
2019 {
2020 DPRINT1("WARNING: Relocated EXE Context");
2021 UNIMPLEMENTED; // We should support this
2022 return STATUS_INVALID_IMAGE_FORMAT;
2023 }
2024
2025 /* Restore the protection */
2026 Status = LdrpSetProtection(ViewBase, TRUE);
2027 if (!NT_SUCCESS(Status)) return Status;
2028 }
2029
2030 /* Lock the DLLs */
2031 ListHead = &Peb->Ldr->InLoadOrderModuleList;
2032 NextEntry = ListHead->Flink;
2033 while (ListHead != NextEntry)
2034 {
2035 NtLdrEntry = CONTAINING_RECORD(NextEntry, LDR_DATA_TABLE_ENTRY, InLoadOrderLinks);
2036 NtLdrEntry->LoadCount = -1;
2037 NextEntry = NextEntry->Flink;
2038 }
2039
2040 /* Phase 0 is done */
2041 LdrpLdrDatabaseIsSetup = TRUE;
2042
2043 /* Check whether all static imports were properly loaded and return here */
2044 if (!NT_SUCCESS(ImportStatus)) return ImportStatus;
2045
2046 /* Initialize TLS */
2047 Status = LdrpInitializeTls();
2048 if (!NT_SUCCESS(Status))
2049 {
2050 DPRINT1("LDR: LdrpProcessInitialization failed to initialize TLS slots; status %x\n",
2051 Status);
2052 return Status;
2053 }
2054
2055 /* FIXME Mark the DLL Ranges for Stack Traces later */
2056
2057 /* Notify the debugger now */
2058 if (Peb->BeingDebugged)
2059 {
2060 /* Break */
2061 DbgBreakPoint();
2062
2063 /* Update show snaps again */
2064 ShowSnaps = Peb->NtGlobalFlag & FLG_SHOW_LDR_SNAPS;
2065 }
2066
2067 /* Validate the Image for MP Usage */
2068 if (LdrpNumberOfProcessors > 1) LdrpValidateImageForMp(LdrpImageEntry);
2069
2070 /* Check NX Options */
2071 if (SharedUserData->NXSupportPolicy == 1)
2072 {
2073 ExecuteOptions = 0xD;
2074 }
2075 else if (!SharedUserData->NXSupportPolicy)
2076 {
2077 ExecuteOptions = 0xA;
2078 }
2079
2080 /* Let Mm know */
2081 ZwSetInformationProcess(NtCurrentProcess(),
2082 ProcessExecuteFlags,
2083 &ExecuteOptions,
2084 sizeof(ULONG));
2085
2086 /* Check if we had Shim Data */
2087 if (OldShimData)
2088 {
2089 /* Load the Shim Engine */
2090 Peb->AppCompatInfo = NULL;
2091 //LdrpLoadShimEngine(OldShimData, ImagePathName, OldShimData);
2092 DPRINT1("We do not support shims yet\n");
2093 }
2094 else
2095 {
2096 /* Check for Application Compatibility Goo */
2097 //LdrQueryApplicationCompatibilityGoo(hKey);
2098 DPRINT("Querying app compat hacks is missing!\n");
2099 }
2100
2101 /*
2102 * FIXME: Check for special images, SecuROM, SafeDisc and other NX-
2103 * incompatible images.
2104 */
2105
2106 /* Now call the Init Routines */
2107 Status = LdrpRunInitializeRoutines(Context);
2108 if (!NT_SUCCESS(Status))
2109 {
2110 DPRINT1("LDR: LdrpProcessInitialization failed running initialization routines; status %x\n",
2111 Status);
2112 return Status;
2113 }
2114
2115 /* FIXME: Unload the Shim Engine if it was loaded */
2116
2117 /* Check if we have a user-defined Post Process Routine */
2118 if (NT_SUCCESS(Status) && Peb->PostProcessInitRoutine)
2119 {
2120 /* Call it */
2121 Peb->PostProcessInitRoutine();
2122 }
2123
2124 /* Close the key if we have one opened */
2125 if (OptionsKey) NtClose(OptionsKey);
2126
2127 /* Return status */
2128 return Status;
2129 }
2130
2131 VOID
2132 NTAPI
2133 LdrpInitFailure(NTSTATUS Status)
2134 {
2135 ULONG Response;
2136 PPEB Peb = NtCurrentPeb();
2137
2138 /* Print a debug message */
2139 DPRINT1("LDR: Process initialization failure for %wZ; NTSTATUS = %08lx\n",
2140 &Peb->ProcessParameters->ImagePathName, Status);
2141
2142 /* Raise a hard error */
2143 if (!LdrpFatalHardErrorCount)
2144 {
2145 ZwRaiseHardError(STATUS_APP_INIT_FAILURE, 1, 0, (PULONG_PTR)&Status, OptionOk, &Response);
2146 }
2147 }
2148
2149 VOID
2150 NTAPI
2151 LdrpInit(PCONTEXT Context,
2152 PVOID SystemArgument1,
2153 PVOID SystemArgument2)
2154 {
2155 LARGE_INTEGER Timeout;
2156 PTEB Teb = NtCurrentTeb();
2157 NTSTATUS Status, LoaderStatus = STATUS_SUCCESS;
2158 MEMORY_BASIC_INFORMATION MemoryBasicInfo;
2159 PPEB Peb = NtCurrentPeb();
2160
2161 DPRINT("LdrpInit() %lx/%lx\n",
2162 NtCurrentTeb()->RealClientId.UniqueProcess,
2163 NtCurrentTeb()->RealClientId.UniqueThread);
2164
2165 /* Check if we have a deallocation stack */
2166 if (!Teb->DeallocationStack)
2167 {
2168 /* We don't, set one */
2169 Status = NtQueryVirtualMemory(NtCurrentProcess(),
2170 Teb->NtTib.StackLimit,
2171 MemoryBasicInformation,
2172 &MemoryBasicInfo,
2173 sizeof(MEMORY_BASIC_INFORMATION),
2174 NULL);
2175 if (!NT_SUCCESS(Status))
2176 {
2177 /* Fail */
2178 LdrpInitFailure(Status);
2179 RtlRaiseStatus(Status);
2180 return;
2181 }
2182
2183 /* Set the stack */
2184 Teb->DeallocationStack = MemoryBasicInfo.AllocationBase;
2185 }
2186
2187 /* Now check if the process is already being initialized */
2188 while (_InterlockedCompareExchange(&LdrpProcessInitialized,
2189 1,
2190 0) == 1)
2191 {
2192 /* Set the timeout to 30 seconds */
2193 Timeout.QuadPart = Int32x32To64(30, -10000);
2194
2195 /* Make sure the status hasn't changed */
2196 while (!LdrpProcessInitialized)
2197 {
2198 /* Do the wait */
2199 ZwDelayExecution(FALSE, &Timeout);
2200 }
2201 }
2202
2203 /* Check if we have already setup LDR data */
2204 if (!Peb->Ldr)
2205 {
2206 /* Setup the Loader Lock */
2207 Peb->LoaderLock = &LdrpLoaderLock;
2208
2209 /* Let other code know we're initializing */
2210 LdrpInLdrInit = TRUE;
2211
2212 /* Protect with SEH */
2213 _SEH2_TRY
2214 {
2215 /* Initialize the Process */
2216 LoaderStatus = LdrpInitializeProcess(Context,
2217 SystemArgument1);
2218
2219 /* Check for success and if MinimumStackCommit was requested */
2220 if (NT_SUCCESS(LoaderStatus) && Peb->MinimumStackCommit)
2221 {
2222 /* Enforce the limit */
2223 //LdrpTouchThreadStack(Peb->MinimumStackCommit);
2224 UNIMPLEMENTED;
2225 }
2226 }
2227 _SEH2_EXCEPT(EXCEPTION_EXECUTE_HANDLER)
2228 {
2229 /* Fail with the SEH error */
2230 LoaderStatus = _SEH2_GetExceptionCode();
2231 }
2232 _SEH2_END;
2233
2234 /* We're not initializing anymore */
2235 LdrpInLdrInit = FALSE;
2236
2237 /* Check if init worked */
2238 if (NT_SUCCESS(LoaderStatus))
2239 {
2240 /* Set the process as Initialized */
2241 _InterlockedIncrement(&LdrpProcessInitialized);
2242 }
2243 }
2244 else
2245 {
2246 /* Loader data is there... is this a fork() ? */
2247 if(Peb->InheritedAddressSpace)
2248 {
2249 /* Handle the fork() */
2250 //LoaderStatus = LdrpForkProcess();
2251 LoaderStatus = STATUS_NOT_IMPLEMENTED;
2252 UNIMPLEMENTED;
2253 }
2254 else
2255 {
2256 /* This is a new thread initializing */
2257 LdrpInitializeThread(Context);
2258 }
2259 }
2260
2261 /* All done, test alert the thread */
2262 NtTestAlert();
2263
2264 /* Return */
2265 if (!NT_SUCCESS(LoaderStatus))
2266 {
2267 /* Fail */
2268 LdrpInitFailure(LoaderStatus);
2269 RtlRaiseStatus(LoaderStatus);
2270 }
2271 }
2272
2273 /* EOF */