f62b93ef65ae4e080b5700c8742f2c022f5b11db
[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
14 #define NDEBUG
15 #include <debug.h>
16
17
18 /* GLOBALS *******************************************************************/
19
20 HANDLE ImageExecOptionsKey;
21 HANDLE Wow64ExecOptionsKey;
22 UNICODE_STRING ImageExecOptionsString = RTL_CONSTANT_STRING(L"\\Registry\\Machine\\Software\\Microsoft\\Windows NT\\CurrentVersion\\Image File Execution Options");
23 UNICODE_STRING Wow64OptionsString = RTL_CONSTANT_STRING(L"");
24 UNICODE_STRING NtDllString = RTL_CONSTANT_STRING(L"ntdll.dll");
25
26 BOOLEAN LdrpInLdrInit;
27 LONG LdrpProcessInitialized;
28 BOOLEAN LdrpLoaderLockInit;
29 BOOLEAN LdrpLdrDatabaseIsSetup;
30 BOOLEAN LdrpShutdownInProgress;
31 HANDLE LdrpShutdownThreadId;
32
33 BOOLEAN LdrpDllValidation;
34
35 PLDR_DATA_TABLE_ENTRY LdrpImageEntry;
36 PUNICODE_STRING LdrpTopLevelDllBeingLoaded;
37 WCHAR StringBuffer[156];
38 extern PTEB LdrpTopLevelDllBeingLoadedTeb; // defined in rtlsupp.c!
39 PLDR_DATA_TABLE_ENTRY LdrpCurrentDllInitializer;
40 PLDR_DATA_TABLE_ENTRY LdrpNtDllDataTableEntry;
41
42 RTL_BITMAP TlsBitMap;
43 RTL_BITMAP TlsExpansionBitMap;
44 RTL_BITMAP FlsBitMap;
45 BOOLEAN LdrpImageHasTls;
46 LIST_ENTRY LdrpTlsList;
47 ULONG LdrpNumberOfTlsEntries;
48 ULONG LdrpNumberOfProcessors;
49 PVOID NtDllBase;
50 extern LARGE_INTEGER RtlpTimeout;
51 BOOLEAN RtlpTimeoutDisable;
52 LIST_ENTRY LdrpHashTable[LDR_HASH_TABLE_ENTRIES];
53 LIST_ENTRY LdrpDllNotificationList;
54 HANDLE LdrpKnownDllObjectDirectory;
55 UNICODE_STRING LdrpKnownDllPath;
56 WCHAR LdrpKnownDllPathBuffer[128];
57 UNICODE_STRING LdrpDefaultPath;
58
59 PEB_LDR_DATA PebLdr;
60
61 RTL_CRITICAL_SECTION_DEBUG LdrpLoaderLockDebug;
62 RTL_CRITICAL_SECTION LdrpLoaderLock =
63 {
64 &LdrpLoaderLockDebug,
65 -1,
66 0,
67 0,
68 0,
69 0
70 };
71 RTL_CRITICAL_SECTION FastPebLock;
72
73 BOOLEAN ShowSnaps;
74
75 ULONG LdrpFatalHardErrorCount;
76 ULONG LdrpActiveUnloadCount;
77
78 //extern LIST_ENTRY RtlCriticalSectionList;
79
80 VOID NTAPI RtlpInitializeVectoredExceptionHandling(VOID);
81 VOID NTAPI RtlpInitDeferedCriticalSection(VOID);
82 VOID NTAPI RtlInitializeHeapManager(VOID);
83 extern BOOLEAN RtlpPageHeapEnabled;
84
85 ULONG RtlpDisableHeapLookaside; // TODO: Move to heap.c
86 ULONG RtlpShutdownProcessFlags; // TODO: Use it
87
88 NTSTATUS LdrPerformRelocations(PIMAGE_NT_HEADERS NTHeaders, PVOID ImageBase);
89 void actctx_init(void);
90 extern BOOLEAN RtlpUse16ByteSLists;
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(VOID)
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 (%p/%p)\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(&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, InMemoryOrderLinks);
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, %p/%p\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 (%p/%p)\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("[%p,%p] 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, InInitializationOrderLinks);
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("[%p,%p] 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 Entry */
843 LdrEntry = CONTAINING_RECORD(NextEntry, LDR_DATA_TABLE_ENTRY, InInitializationOrderLinks);
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 (g_ShimsEnabled)
905 {
906 VOID(NTAPI *SE_ProcessDying)();
907 SE_ProcessDying = RtlDecodeSystemPointer(g_pfnSE_ProcessDying);
908 SE_ProcessDying();
909 }
910
911 /* Tell the world */
912 if (ShowSnaps)
913 {
914 DPRINT1("\n");
915 }
916
917 /* Set the shutdown variables */
918 LdrpShutdownThreadId = NtCurrentTeb()->RealClientId.UniqueThread;
919 LdrpShutdownInProgress = TRUE;
920
921 /* Enter the Loader Lock */
922 RtlEnterCriticalSection(&LdrpLoaderLock);
923
924 /* Cleanup trace logging data (Etw) */
925 if (SharedUserData->TraceLogging)
926 {
927 /* FIXME */
928 DPRINT1("We don't support Etw yet.\n");
929 }
930
931 /* Start at the end */
932 ListHead = &Peb->Ldr->InInitializationOrderModuleList;
933 NextEntry = ListHead->Blink;
934 while (NextEntry != ListHead)
935 {
936 /* Get the current entry */
937 LdrEntry = CONTAINING_RECORD(NextEntry, LDR_DATA_TABLE_ENTRY, InInitializationOrderLinks);
938 NextEntry = NextEntry->Blink;
939
940 /* Make sure it's not ourselves */
941 if (Peb->ImageBaseAddress != LdrEntry->DllBase)
942 {
943 /* Get the entrypoint */
944 EntryPoint = LdrEntry->EntryPoint;
945
946 /* Check if we are ready to call it */
947 if (EntryPoint &&
948 (LdrEntry->Flags & LDRP_PROCESS_ATTACH_CALLED) &&
949 LdrEntry->Flags)
950 {
951 /* Set up the Act Ctx */
952 ActCtx.Size = sizeof(ActCtx);
953 ActCtx.Format = 1;
954 RtlZeroMemory(&ActCtx.Frame, sizeof(RTL_ACTIVATION_CONTEXT_STACK_FRAME));
955
956 /* Activate the ActCtx */
957 RtlActivateActivationContextUnsafeFast(&ActCtx,
958 LdrEntry->EntryPointActivationContext);
959
960 /* Check if it has TLS */
961 if (LdrEntry->TlsIndex)
962 {
963 /* Call TLS */
964 LdrpCallTlsInitializers(LdrEntry->DllBase, DLL_PROCESS_DETACH);
965 }
966
967 /* Call the Entrypoint */
968 DPRINT("%wZ - Calling entry point at %p for thread detaching\n",
969 &LdrEntry->BaseDllName, LdrEntry->EntryPoint);
970 LdrpCallInitRoutine(EntryPoint,
971 LdrEntry->DllBase,
972 DLL_PROCESS_DETACH,
973 (PVOID)1);
974
975 /* Deactivate the ActCtx */
976 RtlDeactivateActivationContextUnsafeFast(&ActCtx);
977 }
978 }
979 }
980
981 /* Check for TLS */
982 if (LdrpImageHasTls)
983 {
984 /* Set up the Act Ctx */
985 ActCtx.Size = sizeof(ActCtx);
986 ActCtx.Format = 1;
987 RtlZeroMemory(&ActCtx.Frame, sizeof(RTL_ACTIVATION_CONTEXT_STACK_FRAME));
988
989 /* Activate the ActCtx */
990 RtlActivateActivationContextUnsafeFast(&ActCtx,
991 LdrpImageEntry->EntryPointActivationContext);
992
993 /* Do TLS callbacks */
994 LdrpCallTlsInitializers(Peb->ImageBaseAddress, DLL_PROCESS_DETACH);
995
996 /* Deactivate the ActCtx */
997 RtlDeactivateActivationContextUnsafeFast(&ActCtx);
998 }
999
1000 /* FIXME: Do Heap detection and Etw final shutdown */
1001
1002 /* Release the lock */
1003 RtlLeaveCriticalSection(&LdrpLoaderLock);
1004 DPRINT("LdrpShutdownProcess() done\n");
1005
1006 return STATUS_SUCCESS;
1007 }
1008
1009 /*
1010 * @implemented
1011 */
1012 NTSTATUS
1013 NTAPI
1014 LdrShutdownThread(VOID)
1015 {
1016 PPEB Peb = NtCurrentPeb();
1017 PTEB Teb = NtCurrentTeb();
1018 PLDR_DATA_TABLE_ENTRY LdrEntry;
1019 PLIST_ENTRY NextEntry, ListHead;
1020 RTL_CALLER_ALLOCATED_ACTIVATION_CONTEXT_STACK_FRAME_EXTENDED ActCtx;
1021 PVOID EntryPoint;
1022
1023 DPRINT("LdrShutdownThread() called for %wZ\n",
1024 &LdrpImageEntry->BaseDllName);
1025
1026 /* Cleanup trace logging data (Etw) */
1027 if (SharedUserData->TraceLogging)
1028 {
1029 /* FIXME */
1030 DPRINT1("We don't support Etw yet.\n");
1031 }
1032
1033 /* Get the Ldr Lock */
1034 RtlEnterCriticalSection(&LdrpLoaderLock);
1035
1036 /* Start at the end */
1037 ListHead = &Peb->Ldr->InInitializationOrderModuleList;
1038 NextEntry = ListHead->Blink;
1039 while (NextEntry != ListHead)
1040 {
1041 /* Get the current entry */
1042 LdrEntry = CONTAINING_RECORD(NextEntry, LDR_DATA_TABLE_ENTRY, InInitializationOrderLinks);
1043 NextEntry = NextEntry->Blink;
1044
1045 /* Make sure it's not ourselves */
1046 if (Peb->ImageBaseAddress != LdrEntry->DllBase)
1047 {
1048 /* Check if we should call */
1049 if (!(LdrEntry->Flags & LDRP_DONT_CALL_FOR_THREADS) &&
1050 (LdrEntry->Flags & LDRP_PROCESS_ATTACH_CALLED) &&
1051 (LdrEntry->Flags & LDRP_IMAGE_DLL))
1052 {
1053 /* Get the entrypoint */
1054 EntryPoint = LdrEntry->EntryPoint;
1055
1056 /* Check if we are ready to call it */
1057 if (EntryPoint)
1058 {
1059 /* Set up the Act Ctx */
1060 ActCtx.Size = sizeof(ActCtx);
1061 ActCtx.Format = 1;
1062 RtlZeroMemory(&ActCtx.Frame, sizeof(RTL_ACTIVATION_CONTEXT_STACK_FRAME));
1063
1064 /* Activate the ActCtx */
1065 RtlActivateActivationContextUnsafeFast(&ActCtx,
1066 LdrEntry->EntryPointActivationContext);
1067
1068 /* Check if it has TLS */
1069 if (LdrEntry->TlsIndex)
1070 {
1071 /* Make sure we're not shutting down */
1072 if (!LdrpShutdownInProgress)
1073 {
1074 /* Call TLS */
1075 LdrpCallTlsInitializers(LdrEntry->DllBase, DLL_THREAD_DETACH);
1076 }
1077 }
1078
1079 /* Make sure we're not shutting down */
1080 if (!LdrpShutdownInProgress)
1081 {
1082 /* Call the Entrypoint */
1083 DPRINT("%wZ - Calling entry point at %p for thread detaching\n",
1084 &LdrEntry->BaseDllName, LdrEntry->EntryPoint);
1085 LdrpCallInitRoutine(EntryPoint,
1086 LdrEntry->DllBase,
1087 DLL_THREAD_DETACH,
1088 NULL);
1089 }
1090
1091 /* Deactivate the ActCtx */
1092 RtlDeactivateActivationContextUnsafeFast(&ActCtx);
1093 }
1094 }
1095 }
1096 }
1097
1098 /* Check for TLS */
1099 if (LdrpImageHasTls)
1100 {
1101 /* Set up the Act Ctx */
1102 ActCtx.Size = sizeof(ActCtx);
1103 ActCtx.Format = 1;
1104 RtlZeroMemory(&ActCtx.Frame, sizeof(RTL_ACTIVATION_CONTEXT_STACK_FRAME));
1105
1106 /* Activate the ActCtx */
1107 RtlActivateActivationContextUnsafeFast(&ActCtx,
1108 LdrpImageEntry->EntryPointActivationContext);
1109
1110 /* Do TLS callbacks */
1111 LdrpCallTlsInitializers(Peb->ImageBaseAddress, DLL_THREAD_DETACH);
1112
1113 /* Deactivate the ActCtx */
1114 RtlDeactivateActivationContextUnsafeFast(&ActCtx);
1115 }
1116
1117 /* Free TLS */
1118 LdrpFreeTls();
1119 RtlLeaveCriticalSection(&LdrpLoaderLock);
1120
1121 /* Check for expansion slots */
1122 if (Teb->TlsExpansionSlots)
1123 {
1124 /* Free expansion slots */
1125 RtlFreeHeap(RtlGetProcessHeap(), 0, Teb->TlsExpansionSlots);
1126 }
1127
1128 /* Check for FLS Data */
1129 if (Teb->FlsData)
1130 {
1131 /* FIXME */
1132 DPRINT1("We don't support FLS Data yet\n");
1133 }
1134
1135 /* Check for Fiber data */
1136 if (Teb->HasFiberData)
1137 {
1138 /* Free Fiber data*/
1139 RtlFreeHeap(RtlGetProcessHeap(), 0, Teb->NtTib.FiberData);
1140 Teb->NtTib.FiberData = NULL;
1141 }
1142
1143 /* Free the activation context stack */
1144 RtlFreeThreadActivationContextStack();
1145 DPRINT("LdrShutdownThread() done\n");
1146
1147 return STATUS_SUCCESS;
1148 }
1149
1150 NTSTATUS
1151 NTAPI
1152 LdrpInitializeTls(VOID)
1153 {
1154 PLIST_ENTRY NextEntry, ListHead;
1155 PLDR_DATA_TABLE_ENTRY LdrEntry;
1156 PIMAGE_TLS_DIRECTORY TlsDirectory;
1157 PLDRP_TLS_DATA TlsData;
1158 ULONG Size;
1159
1160 /* Initialize the TLS List */
1161 InitializeListHead(&LdrpTlsList);
1162
1163 /* Loop all the modules */
1164 ListHead = &NtCurrentPeb()->Ldr->InLoadOrderModuleList;
1165 NextEntry = ListHead->Flink;
1166 while (ListHead != NextEntry)
1167 {
1168 /* Get the entry */
1169 LdrEntry = CONTAINING_RECORD(NextEntry, LDR_DATA_TABLE_ENTRY, InLoadOrderLinks);
1170 NextEntry = NextEntry->Flink;
1171
1172 /* Get the TLS directory */
1173 TlsDirectory = RtlImageDirectoryEntryToData(LdrEntry->DllBase,
1174 TRUE,
1175 IMAGE_DIRECTORY_ENTRY_TLS,
1176 &Size);
1177
1178 /* Check if we have a directory */
1179 if (!TlsDirectory) continue;
1180
1181 /* Check if the image has TLS */
1182 if (!LdrpImageHasTls) LdrpImageHasTls = TRUE;
1183
1184 /* Show debug message */
1185 if (ShowSnaps)
1186 {
1187 DPRINT1("LDR: Tls Found in %wZ at %p\n",
1188 &LdrEntry->BaseDllName,
1189 TlsDirectory);
1190 }
1191
1192 /* Allocate an entry */
1193 TlsData = RtlAllocateHeap(RtlGetProcessHeap(), 0, sizeof(LDRP_TLS_DATA));
1194 if (!TlsData) return STATUS_NO_MEMORY;
1195
1196 /* Lock the DLL and mark it for TLS Usage */
1197 LdrEntry->LoadCount = -1;
1198 LdrEntry->TlsIndex = -1;
1199
1200 /* Save the cached TLS data */
1201 TlsData->TlsDirectory = *TlsDirectory;
1202 InsertTailList(&LdrpTlsList, &TlsData->TlsLinks);
1203
1204 /* Update the index */
1205 *(PLONG)TlsData->TlsDirectory.AddressOfIndex = LdrpNumberOfTlsEntries;
1206 TlsData->TlsDirectory.Characteristics = LdrpNumberOfTlsEntries++;
1207 }
1208
1209 /* Done setting up TLS, allocate entries */
1210 return LdrpAllocateTls();
1211 }
1212
1213 NTSTATUS
1214 NTAPI
1215 LdrpAllocateTls(VOID)
1216 {
1217 PTEB Teb = NtCurrentTeb();
1218 PLIST_ENTRY NextEntry, ListHead;
1219 PLDRP_TLS_DATA TlsData;
1220 SIZE_T TlsDataSize;
1221 PVOID *TlsVector;
1222
1223 /* Check if we have any entries */
1224 if (!LdrpNumberOfTlsEntries)
1225 return STATUS_SUCCESS;
1226
1227 /* Allocate the vector array */
1228 TlsVector = RtlAllocateHeap(RtlGetProcessHeap(),
1229 0,
1230 LdrpNumberOfTlsEntries * sizeof(PVOID));
1231 if (!TlsVector) return STATUS_NO_MEMORY;
1232 Teb->ThreadLocalStoragePointer = TlsVector;
1233
1234 /* Loop the TLS Array */
1235 ListHead = &LdrpTlsList;
1236 NextEntry = ListHead->Flink;
1237 while (NextEntry != ListHead)
1238 {
1239 /* Get the entry */
1240 TlsData = CONTAINING_RECORD(NextEntry, LDRP_TLS_DATA, TlsLinks);
1241 NextEntry = NextEntry->Flink;
1242
1243 /* Allocate this vector */
1244 TlsDataSize = TlsData->TlsDirectory.EndAddressOfRawData -
1245 TlsData->TlsDirectory.StartAddressOfRawData;
1246 TlsVector[TlsData->TlsDirectory.Characteristics] = RtlAllocateHeap(RtlGetProcessHeap(),
1247 0,
1248 TlsDataSize);
1249 if (!TlsVector[TlsData->TlsDirectory.Characteristics])
1250 {
1251 /* Out of memory */
1252 return STATUS_NO_MEMORY;
1253 }
1254
1255 /* Show debug message */
1256 if (ShowSnaps)
1257 {
1258 DPRINT1("LDR: TlsVector %p Index %lu = %p copied from %x to %p\n",
1259 TlsVector,
1260 TlsData->TlsDirectory.Characteristics,
1261 &TlsVector[TlsData->TlsDirectory.Characteristics],
1262 TlsData->TlsDirectory.StartAddressOfRawData,
1263 TlsVector[TlsData->TlsDirectory.Characteristics]);
1264 }
1265
1266 /* Copy the data */
1267 RtlCopyMemory(TlsVector[TlsData->TlsDirectory.Characteristics],
1268 (PVOID)TlsData->TlsDirectory.StartAddressOfRawData,
1269 TlsDataSize);
1270 }
1271
1272 /* Done */
1273 return STATUS_SUCCESS;
1274 }
1275
1276 VOID
1277 NTAPI
1278 LdrpFreeTls(VOID)
1279 {
1280 PLIST_ENTRY ListHead, NextEntry;
1281 PLDRP_TLS_DATA TlsData;
1282 PVOID *TlsVector;
1283 PTEB Teb = NtCurrentTeb();
1284
1285 /* Get a pointer to the vector array */
1286 TlsVector = Teb->ThreadLocalStoragePointer;
1287 if (!TlsVector) return;
1288
1289 /* Loop through it */
1290 ListHead = &LdrpTlsList;
1291 NextEntry = ListHead->Flink;
1292 while (NextEntry != ListHead)
1293 {
1294 TlsData = CONTAINING_RECORD(NextEntry, LDRP_TLS_DATA, TlsLinks);
1295 NextEntry = NextEntry->Flink;
1296
1297 /* Free each entry */
1298 if (TlsVector[TlsData->TlsDirectory.Characteristics])
1299 {
1300 RtlFreeHeap(RtlGetProcessHeap(),
1301 0,
1302 TlsVector[TlsData->TlsDirectory.Characteristics]);
1303 }
1304 }
1305
1306 /* Free the array itself */
1307 RtlFreeHeap(RtlGetProcessHeap(),
1308 0,
1309 TlsVector);
1310 }
1311
1312 NTSTATUS
1313 NTAPI
1314 LdrpInitializeApplicationVerifierPackage(PUNICODE_STRING ImagePathName, PPEB Peb, BOOLEAN SystemWide, BOOLEAN ReadAdvancedOptions)
1315 {
1316 /* If global flags request DPH, perform some additional actions */
1317 if (Peb->NtGlobalFlag & FLG_HEAP_PAGE_ALLOCS)
1318 {
1319 // TODO: Read advanced DPH flags from the registry if requested
1320 if (ReadAdvancedOptions)
1321 {
1322 UNIMPLEMENTED;
1323 }
1324
1325 /* Enable page heap */
1326 RtlpPageHeapEnabled = TRUE;
1327 }
1328
1329 return STATUS_SUCCESS;
1330 }
1331
1332 NTSTATUS
1333 NTAPI
1334 LdrpInitializeExecutionOptions(PUNICODE_STRING ImagePathName, PPEB Peb, PHANDLE OptionsKey)
1335 {
1336 NTSTATUS Status;
1337 HANDLE KeyHandle;
1338 ULONG ExecuteOptions, MinimumStackCommit = 0, GlobalFlag;
1339
1340 /* Return error if we were not provided a pointer where to save the options key handle */
1341 if (!OptionsKey) return STATUS_INVALID_HANDLE;
1342
1343 /* Zero initialize the options key pointer */
1344 *OptionsKey = NULL;
1345
1346 /* Open the options key */
1347 Status = LdrOpenImageFileOptionsKey(ImagePathName, 0, &KeyHandle);
1348
1349 /* Save it if it was opened successfully */
1350 if (NT_SUCCESS(Status))
1351 *OptionsKey = KeyHandle;
1352
1353 if (KeyHandle)
1354 {
1355 /* There are image specific options, read them starting with NXCOMPAT */
1356 Status = LdrQueryImageFileKeyOption(KeyHandle,
1357 L"ExecuteOptions",
1358 4,
1359 &ExecuteOptions,
1360 sizeof(ExecuteOptions),
1361 0);
1362
1363 if (NT_SUCCESS(Status))
1364 {
1365 /* TODO: Set execution options for the process */
1366 /*
1367 if (ExecuteOptions == 0)
1368 ExecuteOptions = 1;
1369 else
1370 ExecuteOptions = 2;
1371 ZwSetInformationProcess(NtCurrentProcess(),
1372 ProcessExecuteFlags,
1373 &ExecuteOptions,
1374 sizeof(ULONG));*/
1375
1376 }
1377
1378 /* Check if this image uses large pages */
1379 if (Peb->ImageUsesLargePages)
1380 {
1381 /* TODO: If it does, open large page key */
1382 UNIMPLEMENTED;
1383 }
1384
1385 /* Get various option values */
1386 LdrQueryImageFileKeyOption(KeyHandle,
1387 L"DisableHeapLookaside",
1388 REG_DWORD,
1389 &RtlpDisableHeapLookaside,
1390 sizeof(RtlpDisableHeapLookaside),
1391 NULL);
1392
1393 LdrQueryImageFileKeyOption(KeyHandle,
1394 L"ShutdownFlags",
1395 REG_DWORD,
1396 &RtlpShutdownProcessFlags,
1397 sizeof(RtlpShutdownProcessFlags),
1398 NULL);
1399
1400 LdrQueryImageFileKeyOption(KeyHandle,
1401 L"MinimumStackCommitInBytes",
1402 REG_DWORD,
1403 &MinimumStackCommit,
1404 sizeof(MinimumStackCommit),
1405 NULL);
1406
1407 /* Update PEB's minimum stack commit if it's lower */
1408 if (Peb->MinimumStackCommit < MinimumStackCommit)
1409 Peb->MinimumStackCommit = MinimumStackCommit;
1410
1411 /* Set the global flag */
1412 Status = LdrQueryImageFileKeyOption(KeyHandle,
1413 L"GlobalFlag",
1414 REG_DWORD,
1415 &GlobalFlag,
1416 sizeof(GlobalFlag),
1417 NULL);
1418
1419 if (NT_SUCCESS(Status))
1420 Peb->NtGlobalFlag = GlobalFlag;
1421 else
1422 GlobalFlag = 0;
1423
1424 /* Call AVRF if necessary */
1425 if (Peb->NtGlobalFlag & (FLG_POOL_ENABLE_TAIL_CHECK | FLG_HEAP_PAGE_ALLOCS))
1426 {
1427 Status = LdrpInitializeApplicationVerifierPackage(ImagePathName, Peb, TRUE, FALSE);
1428 if (!NT_SUCCESS(Status))
1429 {
1430 DPRINT1("AVRF: LdrpInitializeApplicationVerifierPackage failed with %08X\n", Status);
1431 }
1432 }
1433 }
1434 else
1435 {
1436 /* There are no image-specific options, so perform global initialization */
1437 if (Peb->NtGlobalFlag & (FLG_POOL_ENABLE_TAIL_CHECK | FLG_HEAP_PAGE_ALLOCS))
1438 {
1439 /* Initialize app verifier package */
1440 Status = LdrpInitializeApplicationVerifierPackage(ImagePathName, Peb, TRUE, FALSE);
1441 if (!NT_SUCCESS(Status))
1442 {
1443 DPRINT1("AVRF: LdrpInitializeApplicationVerifierPackage failed with %08X\n", Status);
1444 }
1445 }
1446 }
1447
1448 return STATUS_SUCCESS;
1449 }
1450
1451 VOID
1452 NTAPI
1453 LdrpValidateImageForMp(IN PLDR_DATA_TABLE_ENTRY LdrDataTableEntry)
1454 {
1455 UNIMPLEMENTED;
1456 }
1457
1458 NTSTATUS
1459 NTAPI
1460 LdrpInitializeProcess(IN PCONTEXT Context,
1461 IN PVOID SystemArgument1)
1462 {
1463 RTL_HEAP_PARAMETERS HeapParameters;
1464 ULONG ComSectionSize;
1465 //ANSI_STRING FunctionName = RTL_CONSTANT_STRING("BaseQueryModuleData");
1466 PVOID OldShimData;
1467 OBJECT_ATTRIBUTES ObjectAttributes;
1468 //UNICODE_STRING LocalFileName, FullImageName;
1469 HANDLE SymLinkHandle;
1470 //ULONG DebugHeapOnly;
1471 UNICODE_STRING CommandLine, NtSystemRoot, ImagePathName, FullPath, ImageFileName, KnownDllString;
1472 PPEB Peb = NtCurrentPeb();
1473 BOOLEAN IsDotNetImage = FALSE;
1474 BOOLEAN FreeCurDir = FALSE;
1475 //HANDLE CompatKey;
1476 PRTL_USER_PROCESS_PARAMETERS ProcessParameters;
1477 //LPWSTR ImagePathBuffer;
1478 ULONG ConfigSize;
1479 UNICODE_STRING CurrentDirectory;
1480 HANDLE OptionsKey;
1481 ULONG HeapFlags;
1482 PIMAGE_NT_HEADERS NtHeader;
1483 LPWSTR NtDllName = NULL;
1484 NTSTATUS Status, ImportStatus;
1485 NLSTABLEINFO NlsTable;
1486 PIMAGE_LOAD_CONFIG_DIRECTORY LoadConfig;
1487 PTEB Teb = NtCurrentTeb();
1488 PLIST_ENTRY ListHead;
1489 PLIST_ENTRY NextEntry;
1490 ULONG i;
1491 PWSTR ImagePath;
1492 ULONG DebugProcessHeapOnly = 0;
1493 PLDR_DATA_TABLE_ENTRY NtLdrEntry;
1494 PWCHAR Current;
1495 ULONG ExecuteOptions = 0;
1496 PVOID ViewBase;
1497
1498 /* Set a NULL SEH Filter */
1499 RtlSetUnhandledExceptionFilter(NULL);
1500
1501 /* Get the image path */
1502 ImagePath = Peb->ProcessParameters->ImagePathName.Buffer;
1503
1504 /* Check if it's not normalized */
1505 if (!(Peb->ProcessParameters->Flags & RTL_USER_PROCESS_PARAMETERS_NORMALIZED))
1506 {
1507 /* Normalize it*/
1508 ImagePath = (PWSTR)((ULONG_PTR)ImagePath + (ULONG_PTR)Peb->ProcessParameters);
1509 }
1510
1511 /* Create a unicode string for the Image Path */
1512 ImagePathName.Length = Peb->ProcessParameters->ImagePathName.Length;
1513 ImagePathName.MaximumLength = ImagePathName.Length + sizeof(WCHAR);
1514 ImagePathName.Buffer = ImagePath;
1515
1516 /* Get the NT Headers */
1517 NtHeader = RtlImageNtHeader(Peb->ImageBaseAddress);
1518
1519 /* Get the execution options */
1520 Status = LdrpInitializeExecutionOptions(&ImagePathName, Peb, &OptionsKey);
1521
1522 /* Check if this is a .NET executable */
1523 if (RtlImageDirectoryEntryToData(Peb->ImageBaseAddress,
1524 TRUE,
1525 IMAGE_DIRECTORY_ENTRY_COM_DESCRIPTOR,
1526 &ComSectionSize))
1527 {
1528 /* Remember this for later */
1529 IsDotNetImage = TRUE;
1530 }
1531
1532 /* Save the NTDLL Base address */
1533 NtDllBase = SystemArgument1;
1534
1535 /* If this is a Native Image */
1536 if (NtHeader->OptionalHeader.Subsystem == IMAGE_SUBSYSTEM_NATIVE)
1537 {
1538 /* Then do DLL Validation */
1539 LdrpDllValidation = TRUE;
1540 }
1541
1542 /* Save the old Shim Data */
1543 OldShimData = Peb->pShimData;
1544
1545 /* Clear it */
1546 Peb->pShimData = NULL;
1547
1548 /* Save the number of processors and CS Timeout */
1549 LdrpNumberOfProcessors = Peb->NumberOfProcessors;
1550 RtlpTimeout = Peb->CriticalSectionTimeout;
1551
1552 /* Normalize the parameters */
1553 ProcessParameters = RtlNormalizeProcessParams(Peb->ProcessParameters);
1554 if (ProcessParameters)
1555 {
1556 /* Save the Image and Command Line Names */
1557 ImageFileName = ProcessParameters->ImagePathName;
1558 CommandLine = ProcessParameters->CommandLine;
1559 }
1560 else
1561 {
1562 /* It failed, initialize empty strings */
1563 RtlInitUnicodeString(&ImageFileName, NULL);
1564 RtlInitUnicodeString(&CommandLine, NULL);
1565 }
1566
1567 /* Initialize NLS data */
1568 RtlInitNlsTables(Peb->AnsiCodePageData,
1569 Peb->OemCodePageData,
1570 Peb->UnicodeCaseTableData,
1571 &NlsTable);
1572
1573 /* Reset NLS Translations */
1574 RtlResetRtlTranslations(&NlsTable);
1575
1576 /* Get the Image Config Directory */
1577 LoadConfig = RtlImageDirectoryEntryToData(Peb->ImageBaseAddress,
1578 TRUE,
1579 IMAGE_DIRECTORY_ENTRY_LOAD_CONFIG,
1580 &ConfigSize);
1581
1582 /* Setup the Heap Parameters */
1583 RtlZeroMemory(&HeapParameters, sizeof(RTL_HEAP_PARAMETERS));
1584 HeapFlags = HEAP_GROWABLE;
1585 HeapParameters.Length = sizeof(RTL_HEAP_PARAMETERS);
1586
1587 /* Check if we have Configuration Data */
1588 if ((LoadConfig) && (ConfigSize == sizeof(IMAGE_LOAD_CONFIG_DIRECTORY)))
1589 {
1590 /* FIXME: Custom heap settings and misc. */
1591 DPRINT1("We don't support LOAD_CONFIG data yet\n");
1592 }
1593
1594 /* Check for custom affinity mask */
1595 if (Peb->ImageProcessAffinityMask)
1596 {
1597 /* Set it */
1598 Status = NtSetInformationProcess(NtCurrentProcess(),
1599 ProcessAffinityMask,
1600 &Peb->ImageProcessAffinityMask,
1601 sizeof(Peb->ImageProcessAffinityMask));
1602 }
1603
1604 /* Check if verbose debugging (ShowSnaps) was requested */
1605 ShowSnaps = Peb->NtGlobalFlag & FLG_SHOW_LDR_SNAPS;
1606
1607 /* Start verbose debugging messages right now if they were requested */
1608 if (ShowSnaps)
1609 {
1610 DPRINT1("LDR: PID: 0x%p started - '%wZ'\n",
1611 Teb->ClientId.UniqueProcess,
1612 &CommandLine);
1613 }
1614
1615 /* If the timeout is too long */
1616 if (RtlpTimeout.QuadPart < Int32x32To64(3600, -10000000))
1617 {
1618 /* Then disable CS Timeout */
1619 RtlpTimeoutDisable = TRUE;
1620 }
1621
1622 /* Initialize Critical Section Data */
1623 RtlpInitDeferedCriticalSection();
1624
1625 /* Initialize VEH Call lists */
1626 RtlpInitializeVectoredExceptionHandling();
1627
1628 /* Set TLS/FLS Bitmap data */
1629 Peb->FlsBitmap = &FlsBitMap;
1630 Peb->TlsBitmap = &TlsBitMap;
1631 Peb->TlsExpansionBitmap = &TlsExpansionBitMap;
1632
1633 /* Initialize FLS Bitmap */
1634 RtlInitializeBitMap(&FlsBitMap,
1635 Peb->FlsBitmapBits,
1636 FLS_MAXIMUM_AVAILABLE);
1637 RtlSetBit(&FlsBitMap, 0);
1638
1639 /* Initialize TLS Bitmap */
1640 RtlInitializeBitMap(&TlsBitMap,
1641 Peb->TlsBitmapBits,
1642 TLS_MINIMUM_AVAILABLE);
1643 RtlSetBit(&TlsBitMap, 0);
1644 RtlInitializeBitMap(&TlsExpansionBitMap,
1645 Peb->TlsExpansionBitmapBits,
1646 TLS_EXPANSION_SLOTS);
1647 RtlSetBit(&TlsExpansionBitMap, 0);
1648
1649 /* Initialize the Hash Table */
1650 for (i = 0; i < LDR_HASH_TABLE_ENTRIES; i++)
1651 {
1652 InitializeListHead(&LdrpHashTable[i]);
1653 }
1654
1655 /* Initialize the Loader Lock */
1656 // FIXME: What's the point of initing it manually, if two lines lower
1657 // a call to RtlInitializeCriticalSection() is being made anyway?
1658 //InsertTailList(&RtlCriticalSectionList, &LdrpLoaderLock.DebugInfo->ProcessLocksList);
1659 //LdrpLoaderLock.DebugInfo->CriticalSection = &LdrpLoaderLock;
1660 RtlInitializeCriticalSection(&LdrpLoaderLock);
1661 LdrpLoaderLockInit = TRUE;
1662
1663 /* Check if User Stack Trace Database support was requested */
1664 if (Peb->NtGlobalFlag & FLG_USER_STACK_TRACE_DB)
1665 {
1666 DPRINT1("We don't support user stack trace databases yet\n");
1667 }
1668
1669 /* Setup Fast PEB Lock */
1670 RtlInitializeCriticalSection(&FastPebLock);
1671 Peb->FastPebLock = &FastPebLock;
1672 //Peb->FastPebLockRoutine = (PPEBLOCKROUTINE)RtlEnterCriticalSection;
1673 //Peb->FastPebUnlockRoutine = (PPEBLOCKROUTINE)RtlLeaveCriticalSection;
1674
1675 /* Setup Callout Lock and Notification list */
1676 //RtlInitializeCriticalSection(&RtlpCalloutEntryLock);
1677 InitializeListHead(&LdrpDllNotificationList);
1678
1679 /* For old executables, use 16-byte aligned heap */
1680 if ((NtHeader->OptionalHeader.MajorSubsystemVersion <= 3) &&
1681 (NtHeader->OptionalHeader.MinorSubsystemVersion < 51))
1682 {
1683 HeapFlags |= HEAP_CREATE_ALIGN_16;
1684 }
1685
1686 /* Setup the Heap */
1687 RtlInitializeHeapManager();
1688 Peb->ProcessHeap = RtlCreateHeap(HeapFlags,
1689 NULL,
1690 NtHeader->OptionalHeader.SizeOfHeapReserve,
1691 NtHeader->OptionalHeader.SizeOfHeapCommit,
1692 NULL,
1693 &HeapParameters);
1694
1695 if (!Peb->ProcessHeap)
1696 {
1697 DPRINT1("Failed to create process heap\n");
1698 return STATUS_NO_MEMORY;
1699 }
1700
1701 /* Allocate an Activation Context Stack */
1702 Status = RtlAllocateActivationContextStack(&Teb->ActivationContextStackPointer);
1703 if (!NT_SUCCESS(Status)) return Status;
1704
1705 // FIXME: Loader private heap is missing
1706 //DPRINT1("Loader private heap is missing\n");
1707
1708 /* Check for Debug Heap */
1709 if (OptionsKey)
1710 {
1711 /* Query the setting */
1712 Status = LdrQueryImageFileKeyOption(OptionsKey,
1713 L"DebugProcessHeapOnly",
1714 REG_DWORD,
1715 &DebugProcessHeapOnly,
1716 sizeof(ULONG),
1717 NULL);
1718
1719 if (NT_SUCCESS(Status))
1720 {
1721 /* Reset DPH if requested */
1722 if (RtlpPageHeapEnabled && DebugProcessHeapOnly)
1723 {
1724 RtlpDphGlobalFlags &= ~DPH_FLAG_DLL_NOTIFY;
1725 RtlpPageHeapEnabled = FALSE;
1726 }
1727 }
1728 }
1729
1730 /* Build the NTDLL Path */
1731 FullPath.Buffer = StringBuffer;
1732 FullPath.Length = 0;
1733 FullPath.MaximumLength = sizeof(StringBuffer);
1734 RtlInitUnicodeString(&NtSystemRoot, SharedUserData->NtSystemRoot);
1735 RtlAppendUnicodeStringToString(&FullPath, &NtSystemRoot);
1736 RtlAppendUnicodeToString(&FullPath, L"\\System32\\");
1737
1738 /* Open the Known DLLs directory */
1739 RtlInitUnicodeString(&KnownDllString, L"\\KnownDlls");
1740 InitializeObjectAttributes(&ObjectAttributes,
1741 &KnownDllString,
1742 OBJ_CASE_INSENSITIVE,
1743 NULL,
1744 NULL);
1745 Status = ZwOpenDirectoryObject(&LdrpKnownDllObjectDirectory,
1746 DIRECTORY_QUERY | DIRECTORY_TRAVERSE,
1747 &ObjectAttributes);
1748
1749 /* Check if it exists */
1750 if (NT_SUCCESS(Status))
1751 {
1752 /* Open the Known DLLs Path */
1753 RtlInitUnicodeString(&KnownDllString, L"KnownDllPath");
1754 InitializeObjectAttributes(&ObjectAttributes,
1755 &KnownDllString,
1756 OBJ_CASE_INSENSITIVE,
1757 LdrpKnownDllObjectDirectory,
1758 NULL);
1759 Status = NtOpenSymbolicLinkObject(&SymLinkHandle,
1760 SYMBOLIC_LINK_QUERY,
1761 &ObjectAttributes);
1762 if (NT_SUCCESS(Status))
1763 {
1764 /* Query the path */
1765 LdrpKnownDllPath.Length = 0;
1766 LdrpKnownDllPath.MaximumLength = sizeof(LdrpKnownDllPathBuffer);
1767 LdrpKnownDllPath.Buffer = LdrpKnownDllPathBuffer;
1768 Status = ZwQuerySymbolicLinkObject(SymLinkHandle, &LdrpKnownDllPath, NULL);
1769 NtClose(SymLinkHandle);
1770 if (!NT_SUCCESS(Status))
1771 {
1772 DPRINT1("LDR: %s - failed call to ZwQuerySymbolicLinkObject with status %x\n", "", Status);
1773 return Status;
1774 }
1775 }
1776 }
1777
1778 /* Check if we failed */
1779 if (!NT_SUCCESS(Status))
1780 {
1781 /* Assume System32 */
1782 LdrpKnownDllObjectDirectory = NULL;
1783 RtlInitUnicodeString(&LdrpKnownDllPath, StringBuffer);
1784 LdrpKnownDllPath.Length -= sizeof(WCHAR);
1785 }
1786
1787 /* If we have process parameters, get the default path and current path */
1788 if (ProcessParameters)
1789 {
1790 /* Check if we have a Dll Path */
1791 if (ProcessParameters->DllPath.Length)
1792 {
1793 /* Get the path */
1794 LdrpDefaultPath = *(PUNICODE_STRING)&ProcessParameters->DllPath;
1795 }
1796 else
1797 {
1798 /* We need a valid path */
1799 DPRINT1("No valid DllPath was given!\n");
1800 LdrpInitFailure(STATUS_INVALID_PARAMETER);
1801 }
1802
1803 /* Set the current directory */
1804 CurrentDirectory = ProcessParameters->CurrentDirectory.DosPath;
1805
1806 /* Check if it's empty or invalid */
1807 if ((!CurrentDirectory.Buffer) ||
1808 (CurrentDirectory.Buffer[0] == UNICODE_NULL) ||
1809 (!CurrentDirectory.Length))
1810 {
1811 /* Allocate space for the buffer */
1812 CurrentDirectory.Buffer = RtlAllocateHeap(Peb->ProcessHeap,
1813 0,
1814 3 * sizeof(WCHAR) +
1815 sizeof(UNICODE_NULL));
1816 if (!CurrentDirectory.Buffer)
1817 {
1818 DPRINT1("LDR: LdrpInitializeProcess - unable to allocate current working directory buffer\n");
1819 // FIXME: And what?
1820 }
1821
1822 /* Copy the drive of the system root */
1823 RtlMoveMemory(CurrentDirectory.Buffer,
1824 SharedUserData->NtSystemRoot,
1825 3 * sizeof(WCHAR));
1826 CurrentDirectory.Buffer[3] = UNICODE_NULL;
1827 CurrentDirectory.Length = 3 * sizeof(WCHAR);
1828 CurrentDirectory.MaximumLength = CurrentDirectory.Length + sizeof(WCHAR);
1829
1830 FreeCurDir = TRUE;
1831 DPRINT("Using dynamically allocd curdir\n");
1832 }
1833 else
1834 {
1835 /* Use the local buffer */
1836 DPRINT("Using local system root\n");
1837 }
1838 }
1839
1840 /* Setup Loader Data */
1841 Peb->Ldr = &PebLdr;
1842 InitializeListHead(&PebLdr.InLoadOrderModuleList);
1843 InitializeListHead(&PebLdr.InMemoryOrderModuleList);
1844 InitializeListHead(&PebLdr.InInitializationOrderModuleList);
1845 PebLdr.Length = sizeof(PEB_LDR_DATA);
1846 PebLdr.Initialized = TRUE;
1847
1848 /* Allocate a data entry for the Image */
1849 LdrpImageEntry = LdrpAllocateDataTableEntry(Peb->ImageBaseAddress);
1850
1851 /* Set it up */
1852 LdrpImageEntry->EntryPoint = LdrpFetchAddressOfEntryPoint(LdrpImageEntry->DllBase);
1853 LdrpImageEntry->LoadCount = -1;
1854 LdrpImageEntry->EntryPointActivationContext = 0;
1855 LdrpImageEntry->FullDllName = ImageFileName;
1856
1857 if (IsDotNetImage)
1858 LdrpImageEntry->Flags = LDRP_COR_IMAGE;
1859 else
1860 LdrpImageEntry->Flags = 0;
1861
1862 /* Check if the name is empty */
1863 if (!ImageFileName.Buffer[0])
1864 {
1865 /* Use the same Base name */
1866 LdrpImageEntry->BaseDllName = LdrpImageEntry->FullDllName;
1867 }
1868 else
1869 {
1870 /* Find the last slash */
1871 Current = ImageFileName.Buffer;
1872 while (*Current)
1873 {
1874 if (*Current++ == '\\')
1875 {
1876 /* Set this path */
1877 NtDllName = Current;
1878 }
1879 }
1880
1881 /* Did we find anything? */
1882 if (!NtDllName)
1883 {
1884 /* Use the same Base name */
1885 LdrpImageEntry->BaseDllName = LdrpImageEntry->FullDllName;
1886 }
1887 else
1888 {
1889 /* Setup the name */
1890 LdrpImageEntry->BaseDllName.Length = (USHORT)((ULONG_PTR)ImageFileName.Buffer + ImageFileName.Length - (ULONG_PTR)NtDllName);
1891 LdrpImageEntry->BaseDllName.MaximumLength = LdrpImageEntry->BaseDllName.Length + sizeof(WCHAR);
1892 LdrpImageEntry->BaseDllName.Buffer = (PWSTR)((ULONG_PTR)ImageFileName.Buffer +
1893 (ImageFileName.Length - LdrpImageEntry->BaseDllName.Length));
1894 }
1895 }
1896
1897 /* Processing done, insert it */
1898 LdrpInsertMemoryTableEntry(LdrpImageEntry);
1899 LdrpImageEntry->Flags |= LDRP_ENTRY_PROCESSED;
1900
1901 /* Now add an entry for NTDLL */
1902 NtLdrEntry = LdrpAllocateDataTableEntry(SystemArgument1);
1903 NtLdrEntry->Flags = LDRP_IMAGE_DLL;
1904 NtLdrEntry->EntryPoint = LdrpFetchAddressOfEntryPoint(NtLdrEntry->DllBase);
1905 NtLdrEntry->LoadCount = -1;
1906 NtLdrEntry->EntryPointActivationContext = 0;
1907
1908 NtLdrEntry->FullDllName.Length = FullPath.Length;
1909 NtLdrEntry->FullDllName.MaximumLength = FullPath.MaximumLength;
1910 NtLdrEntry->FullDllName.Buffer = StringBuffer;
1911 RtlAppendUnicodeStringToString(&NtLdrEntry->FullDllName, &NtDllString);
1912
1913 NtLdrEntry->BaseDllName.Length = NtDllString.Length;
1914 NtLdrEntry->BaseDllName.MaximumLength = NtDllString.MaximumLength;
1915 NtLdrEntry->BaseDllName.Buffer = NtDllString.Buffer;
1916
1917 /* Processing done, insert it */
1918 LdrpNtDllDataTableEntry = NtLdrEntry;
1919 LdrpInsertMemoryTableEntry(NtLdrEntry);
1920
1921 /* Let the world know */
1922 if (ShowSnaps)
1923 {
1924 DPRINT1("LDR: NEW PROCESS\n");
1925 DPRINT1(" Image Path: %wZ (%wZ)\n", &LdrpImageEntry->FullDllName, &LdrpImageEntry->BaseDllName);
1926 DPRINT1(" Current Directory: %wZ\n", &CurrentDirectory);
1927 DPRINT1(" Search Path: %wZ\n", &LdrpDefaultPath);
1928 }
1929
1930 /* Link the Init Order List */
1931 InsertHeadList(&Peb->Ldr->InInitializationOrderModuleList,
1932 &LdrpNtDllDataTableEntry->InInitializationOrderLinks);
1933
1934 /* Initialize Wine's active context implementation for the current process */
1935 actctx_init();
1936
1937 /* Set the current directory */
1938 Status = RtlSetCurrentDirectory_U(&CurrentDirectory);
1939 if (!NT_SUCCESS(Status))
1940 {
1941 /* We failed, check if we should free it */
1942 if (FreeCurDir) RtlFreeUnicodeString(&CurrentDirectory);
1943
1944 /* Set it to the NT Root */
1945 CurrentDirectory = NtSystemRoot;
1946 RtlSetCurrentDirectory_U(&CurrentDirectory);
1947 }
1948 else
1949 {
1950 /* We're done with it, free it */
1951 if (FreeCurDir) RtlFreeUnicodeString(&CurrentDirectory);
1952 }
1953
1954 /* Check if we should look for a .local file */
1955 if (ProcessParameters->Flags & RTL_USER_PROCESS_PARAMETERS_LOCAL_DLL_PATH)
1956 {
1957 /* FIXME */
1958 DPRINT1("We don't support .local overrides yet\n");
1959 }
1960
1961 /* Check if the Application Verifier was enabled */
1962 if (Peb->NtGlobalFlag & FLG_POOL_ENABLE_TAIL_CHECK)
1963 {
1964 /* FIXME */
1965 DPRINT1("We don't support Application Verifier yet\n");
1966 }
1967
1968 if (IsDotNetImage)
1969 {
1970 /* FIXME */
1971 DPRINT1("We don't support .NET applications yet\n");
1972 }
1973
1974 /* FIXME: Load support for Terminal Services */
1975 if (NtHeader->OptionalHeader.Subsystem == IMAGE_SUBSYSTEM_WINDOWS_GUI)
1976 {
1977 /* Load kernel32 and call BasePostImportInit... */
1978 DPRINT("Unimplemented codepath!\n");
1979 }
1980
1981 /* Walk the IAT and load all the DLLs */
1982 ImportStatus = LdrpWalkImportDescriptor(LdrpDefaultPath.Buffer, LdrpImageEntry);
1983
1984 /* Check if relocation is needed */
1985 if (Peb->ImageBaseAddress != (PVOID)NtHeader->OptionalHeader.ImageBase)
1986 {
1987 DPRINT1("LDR: Performing EXE relocation\n");
1988
1989 /* Change the protection to prepare for relocation */
1990 ViewBase = Peb->ImageBaseAddress;
1991 Status = LdrpSetProtection(ViewBase, FALSE);
1992 if (!NT_SUCCESS(Status)) return Status;
1993
1994 /* Do the relocation */
1995 Status = LdrRelocateImageWithBias(ViewBase,
1996 0LL,
1997 NULL,
1998 STATUS_SUCCESS,
1999 STATUS_CONFLICTING_ADDRESSES,
2000 STATUS_INVALID_IMAGE_FORMAT);
2001 if (!NT_SUCCESS(Status))
2002 {
2003 DPRINT1("LdrRelocateImageWithBias() failed\n");
2004 return Status;
2005 }
2006
2007 /* Check if a start context was provided */
2008 if (Context)
2009 {
2010 DPRINT1("WARNING: Relocated EXE Context");
2011 UNIMPLEMENTED; // We should support this
2012 return STATUS_INVALID_IMAGE_FORMAT;
2013 }
2014
2015 /* Restore the protection */
2016 Status = LdrpSetProtection(ViewBase, TRUE);
2017 if (!NT_SUCCESS(Status)) return Status;
2018 }
2019
2020 /* Lock the DLLs */
2021 ListHead = &Peb->Ldr->InLoadOrderModuleList;
2022 NextEntry = ListHead->Flink;
2023 while (ListHead != NextEntry)
2024 {
2025 NtLdrEntry = CONTAINING_RECORD(NextEntry, LDR_DATA_TABLE_ENTRY, InLoadOrderLinks);
2026 NtLdrEntry->LoadCount = -1;
2027 NextEntry = NextEntry->Flink;
2028 }
2029
2030 /* Phase 0 is done */
2031 LdrpLdrDatabaseIsSetup = TRUE;
2032
2033 /* Check whether all static imports were properly loaded and return here */
2034 if (!NT_SUCCESS(ImportStatus)) return ImportStatus;
2035
2036 /* Initialize TLS */
2037 Status = LdrpInitializeTls();
2038 if (!NT_SUCCESS(Status))
2039 {
2040 DPRINT1("LDR: LdrpProcessInitialization failed to initialize TLS slots; status %x\n",
2041 Status);
2042 return Status;
2043 }
2044
2045 /* FIXME Mark the DLL Ranges for Stack Traces later */
2046
2047 /* Notify the debugger now */
2048 if (Peb->BeingDebugged)
2049 {
2050 /* Break */
2051 DbgBreakPoint();
2052
2053 /* Update show snaps again */
2054 ShowSnaps = Peb->NtGlobalFlag & FLG_SHOW_LDR_SNAPS;
2055 }
2056
2057 /* Validate the Image for MP Usage */
2058 if (LdrpNumberOfProcessors > 1) LdrpValidateImageForMp(LdrpImageEntry);
2059
2060 /* Check NX Options */
2061 if (SharedUserData->NXSupportPolicy == 1)
2062 {
2063 ExecuteOptions = 0xD;
2064 }
2065 else if (!SharedUserData->NXSupportPolicy)
2066 {
2067 ExecuteOptions = 0xA;
2068 }
2069
2070 /* Let Mm know */
2071 ZwSetInformationProcess(NtCurrentProcess(),
2072 ProcessExecuteFlags,
2073 &ExecuteOptions,
2074 sizeof(ULONG));
2075
2076 // FIXME: Should be done by Application Compatibility features,
2077 // by reading the registry, etc...
2078 // For now, this is the old code from ntdll!RtlGetVersion().
2079 RtlInitEmptyUnicodeString(&Peb->CSDVersion, NULL, 0);
2080 if (((Peb->OSCSDVersion >> 8) & 0xFF) != 0)
2081 {
2082 WCHAR szCSDVersion[128];
2083 LONG i;
2084 ULONG Length = ARRAYSIZE(szCSDVersion) - 1;
2085 i = _snwprintf(szCSDVersion, Length,
2086 L"Service Pack %d",
2087 ((Peb->OSCSDVersion >> 8) & 0xFF));
2088 if (i < 0)
2089 {
2090 /* Null-terminate if it was overflowed */
2091 szCSDVersion[Length] = UNICODE_NULL;
2092 }
2093
2094 Length *= sizeof(WCHAR);
2095 Peb->CSDVersion.Buffer = RtlAllocateHeap(RtlGetProcessHeap(),
2096 0,
2097 Length + sizeof(UNICODE_NULL));
2098 if (Peb->CSDVersion.Buffer)
2099 {
2100 Peb->CSDVersion.Length = Length;
2101 Peb->CSDVersion.MaximumLength = Length + sizeof(UNICODE_NULL);
2102
2103 RtlCopyMemory(Peb->CSDVersion.Buffer,
2104 szCSDVersion,
2105 Peb->CSDVersion.MaximumLength);
2106 Peb->CSDVersion.Buffer[Peb->CSDVersion.Length / sizeof(WCHAR)] = UNICODE_NULL;
2107 }
2108 }
2109
2110 /* Check if we had Shim Data */
2111 if (OldShimData)
2112 {
2113 /* Load the Shim Engine */
2114 Peb->AppCompatInfo = NULL;
2115 LdrpLoadShimEngine(OldShimData, &ImagePathName, OldShimData);
2116 }
2117 else
2118 {
2119 /* Check for Application Compatibility Goo */
2120 //LdrQueryApplicationCompatibilityGoo(hKey);
2121 DPRINT("Querying app compat hacks is missing!\n");
2122 }
2123
2124 /*
2125 * FIXME: Check for special images, SecuROM, SafeDisc and other NX-
2126 * incompatible images.
2127 */
2128
2129 /* Now call the Init Routines */
2130 Status = LdrpRunInitializeRoutines(Context);
2131 if (!NT_SUCCESS(Status))
2132 {
2133 DPRINT1("LDR: LdrpProcessInitialization failed running initialization routines; status %x\n",
2134 Status);
2135 return Status;
2136 }
2137
2138 /* Notify Shim Engine */
2139 if (g_ShimsEnabled)
2140 {
2141 VOID(NTAPI *SE_InstallAfterInit)(PUNICODE_STRING, PVOID);
2142 SE_InstallAfterInit = RtlDecodeSystemPointer(g_pfnSE_InstallAfterInit);
2143 SE_InstallAfterInit(&ImagePathName, OldShimData);
2144 }
2145
2146 /* Check if we have a user-defined Post Process Routine */
2147 if (NT_SUCCESS(Status) && Peb->PostProcessInitRoutine)
2148 {
2149 /* Call it */
2150 Peb->PostProcessInitRoutine();
2151 }
2152
2153 /* Close the key if we have one opened */
2154 if (OptionsKey) NtClose(OptionsKey);
2155
2156 /* Return status */
2157 return Status;
2158 }
2159
2160 VOID
2161 NTAPI
2162 LdrpInitFailure(NTSTATUS Status)
2163 {
2164 ULONG Response;
2165 PPEB Peb = NtCurrentPeb();
2166
2167 /* Print a debug message */
2168 DPRINT1("LDR: Process initialization failure for %wZ; NTSTATUS = %08lx\n",
2169 &Peb->ProcessParameters->ImagePathName, Status);
2170
2171 /* Raise a hard error */
2172 if (!LdrpFatalHardErrorCount)
2173 {
2174 ZwRaiseHardError(STATUS_APP_INIT_FAILURE, 1, 0, (PULONG_PTR)&Status, OptionOk, &Response);
2175 }
2176 }
2177
2178 VOID
2179 NTAPI
2180 LdrpInit(PCONTEXT Context,
2181 PVOID SystemArgument1,
2182 PVOID SystemArgument2)
2183 {
2184 LARGE_INTEGER Timeout;
2185 PTEB Teb = NtCurrentTeb();
2186 NTSTATUS Status, LoaderStatus = STATUS_SUCCESS;
2187 MEMORY_BASIC_INFORMATION MemoryBasicInfo;
2188 PPEB Peb = NtCurrentPeb();
2189
2190 DPRINT("LdrpInit() %p/%p\n",
2191 NtCurrentTeb()->RealClientId.UniqueProcess,
2192 NtCurrentTeb()->RealClientId.UniqueThread);
2193
2194 #ifdef _WIN64
2195 /* Set the SList header usage */
2196 RtlpUse16ByteSLists = SharedUserData->ProcessorFeatures[PF_COMPARE_EXCHANGE128];
2197 #endif /* _WIN64 */
2198
2199 /* Check if we have a deallocation stack */
2200 if (!Teb->DeallocationStack)
2201 {
2202 /* We don't, set one */
2203 Status = NtQueryVirtualMemory(NtCurrentProcess(),
2204 Teb->NtTib.StackLimit,
2205 MemoryBasicInformation,
2206 &MemoryBasicInfo,
2207 sizeof(MEMORY_BASIC_INFORMATION),
2208 NULL);
2209 if (!NT_SUCCESS(Status))
2210 {
2211 /* Fail */
2212 LdrpInitFailure(Status);
2213 RtlRaiseStatus(Status);
2214 return;
2215 }
2216
2217 /* Set the stack */
2218 Teb->DeallocationStack = MemoryBasicInfo.AllocationBase;
2219 }
2220
2221 /* Now check if the process is already being initialized */
2222 while (_InterlockedCompareExchange(&LdrpProcessInitialized,
2223 1,
2224 0) == 1)
2225 {
2226 /* Set the timeout to 30 milliseconds */
2227 Timeout.QuadPart = Int32x32To64(30, -10000);
2228
2229 /* Make sure the status hasn't changed */
2230 while (LdrpProcessInitialized == 1)
2231 {
2232 /* Do the wait */
2233 ZwDelayExecution(FALSE, &Timeout);
2234 }
2235 }
2236
2237 /* Check if we have already setup LDR data */
2238 if (!Peb->Ldr)
2239 {
2240 /* Setup the Loader Lock */
2241 Peb->LoaderLock = &LdrpLoaderLock;
2242
2243 /* Let other code know we're initializing */
2244 LdrpInLdrInit = TRUE;
2245
2246 /* Protect with SEH */
2247 _SEH2_TRY
2248 {
2249 /* Initialize the Process */
2250 LoaderStatus = LdrpInitializeProcess(Context,
2251 SystemArgument1);
2252
2253 /* Check for success and if MinimumStackCommit was requested */
2254 if (NT_SUCCESS(LoaderStatus) && Peb->MinimumStackCommit)
2255 {
2256 /* Enforce the limit */
2257 //LdrpTouchThreadStack(Peb->MinimumStackCommit);
2258 UNIMPLEMENTED;
2259 }
2260 }
2261 _SEH2_EXCEPT(EXCEPTION_EXECUTE_HANDLER)
2262 {
2263 /* Fail with the SEH error */
2264 LoaderStatus = _SEH2_GetExceptionCode();
2265 }
2266 _SEH2_END;
2267
2268 /* We're not initializing anymore */
2269 LdrpInLdrInit = FALSE;
2270
2271 /* Check if init worked */
2272 if (NT_SUCCESS(LoaderStatus))
2273 {
2274 /* Set the process as Initialized */
2275 _InterlockedIncrement(&LdrpProcessInitialized);
2276 }
2277 }
2278 else
2279 {
2280 /* Loader data is there... is this a fork() ? */
2281 if(Peb->InheritedAddressSpace)
2282 {
2283 /* Handle the fork() */
2284 //LoaderStatus = LdrpForkProcess();
2285 LoaderStatus = STATUS_NOT_IMPLEMENTED;
2286 UNIMPLEMENTED;
2287 }
2288 else
2289 {
2290 /* This is a new thread initializing */
2291 LdrpInitializeThread(Context);
2292 }
2293 }
2294
2295 /* All done, test alert the thread */
2296 NtTestAlert();
2297
2298 /* Return */
2299 if (!NT_SUCCESS(LoaderStatus))
2300 {
2301 /* Fail */
2302 LdrpInitFailure(LoaderStatus);
2303 RtlRaiseStatus(LoaderStatus);
2304 }
2305 }
2306
2307 /* EOF */