[AVIFIL32]
[reactos.git] / reactos / 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 extern 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 NTAPI 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 (%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, 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, %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, 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("[%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 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 %p 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 %p 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 %p Index %lu = %p copied from %x to %p\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%p 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 /* Allocate an Activation Context Stack */
1700 Status = RtlAllocateActivationContextStack(&Teb->ActivationContextStackPointer);
1701 if (!NT_SUCCESS(Status)) return Status;
1702
1703 // FIXME: Loader private heap is missing
1704 //DPRINT1("Loader private heap is missing\n");
1705
1706 /* Check for Debug Heap */
1707 if (OptionsKey)
1708 {
1709 /* Query the setting */
1710 Status = LdrQueryImageFileKeyOption(OptionsKey,
1711 L"DebugProcessHeapOnly",
1712 REG_DWORD,
1713 &DebugProcessHeapOnly,
1714 sizeof(ULONG),
1715 NULL);
1716
1717 if (NT_SUCCESS(Status))
1718 {
1719 /* Reset DPH if requested */
1720 if (RtlpPageHeapEnabled && DebugProcessHeapOnly)
1721 {
1722 RtlpDphGlobalFlags &= ~DPH_FLAG_DLL_NOTIFY;
1723 RtlpPageHeapEnabled = FALSE;
1724 }
1725 }
1726 }
1727
1728 /* Build the NTDLL Path */
1729 FullPath.Buffer = StringBuffer;
1730 FullPath.Length = 0;
1731 FullPath.MaximumLength = sizeof(StringBuffer);
1732 RtlInitUnicodeString(&NtSystemRoot, SharedUserData->NtSystemRoot);
1733 RtlAppendUnicodeStringToString(&FullPath, &NtSystemRoot);
1734 RtlAppendUnicodeToString(&FullPath, L"\\System32\\");
1735
1736 /* Open the Known DLLs directory */
1737 RtlInitUnicodeString(&KnownDllString, L"\\KnownDlls");
1738 InitializeObjectAttributes(&ObjectAttributes,
1739 &KnownDllString,
1740 OBJ_CASE_INSENSITIVE,
1741 NULL,
1742 NULL);
1743 Status = ZwOpenDirectoryObject(&LdrpKnownDllObjectDirectory,
1744 DIRECTORY_QUERY | DIRECTORY_TRAVERSE,
1745 &ObjectAttributes);
1746
1747 /* Check if it exists */
1748 if (NT_SUCCESS(Status))
1749 {
1750 /* Open the Known DLLs Path */
1751 RtlInitUnicodeString(&KnownDllString, L"KnownDllPath");
1752 InitializeObjectAttributes(&ObjectAttributes,
1753 &KnownDllString,
1754 OBJ_CASE_INSENSITIVE,
1755 LdrpKnownDllObjectDirectory,
1756 NULL);
1757 Status = NtOpenSymbolicLinkObject(&SymLinkHandle,
1758 SYMBOLIC_LINK_QUERY,
1759 &ObjectAttributes);
1760 if (NT_SUCCESS(Status))
1761 {
1762 /* Query the path */
1763 LdrpKnownDllPath.Length = 0;
1764 LdrpKnownDllPath.MaximumLength = sizeof(LdrpKnownDllPathBuffer);
1765 LdrpKnownDllPath.Buffer = LdrpKnownDllPathBuffer;
1766 Status = ZwQuerySymbolicLinkObject(SymLinkHandle, &LdrpKnownDllPath, NULL);
1767 NtClose(SymLinkHandle);
1768 if (!NT_SUCCESS(Status))
1769 {
1770 DPRINT1("LDR: %s - failed call to ZwQuerySymbolicLinkObject with status %x\n", "", Status);
1771 return Status;
1772 }
1773 }
1774 }
1775
1776 /* Check if we failed */
1777 if (!NT_SUCCESS(Status))
1778 {
1779 /* Aassume System32 */
1780 LdrpKnownDllObjectDirectory = NULL;
1781 RtlInitUnicodeString(&LdrpKnownDllPath, StringBuffer);
1782 LdrpKnownDllPath.Length -= sizeof(WCHAR);
1783 }
1784
1785 /* If we have process parameters, get the default path and current path */
1786 if (ProcessParameters)
1787 {
1788 /* Check if we have a Dll Path */
1789 if (ProcessParameters->DllPath.Length)
1790 {
1791 /* Get the path */
1792 LdrpDefaultPath = *(PUNICODE_STRING)&ProcessParameters->DllPath;
1793 }
1794 else
1795 {
1796 /* We need a valid path */
1797 DPRINT1("No valid DllPath was given!\n");
1798 LdrpInitFailure(STATUS_INVALID_PARAMETER);
1799 }
1800
1801 /* Set the current directory */
1802 CurrentDirectory = ProcessParameters->CurrentDirectory.DosPath;
1803
1804 /* Check if it's empty or invalid */
1805 if ((!CurrentDirectory.Buffer) ||
1806 (CurrentDirectory.Buffer[0] == UNICODE_NULL) ||
1807 (!CurrentDirectory.Length))
1808 {
1809 /* Allocate space for the buffer */
1810 CurrentDirectory.Buffer = RtlAllocateHeap(Peb->ProcessHeap,
1811 0,
1812 3 * sizeof(WCHAR) +
1813 sizeof(UNICODE_NULL));
1814 if (!CurrentDirectory.Buffer)
1815 {
1816 DPRINT1("LDR: LdrpInitializeProcess - unable to allocate current working directory buffer\n");
1817 // FIXME: And what?
1818 }
1819
1820 /* Copy the drive of the system root */
1821 RtlMoveMemory(CurrentDirectory.Buffer,
1822 SharedUserData->NtSystemRoot,
1823 3 * sizeof(WCHAR));
1824 CurrentDirectory.Buffer[3] = UNICODE_NULL;
1825 CurrentDirectory.Length = 3 * sizeof(WCHAR);
1826 CurrentDirectory.MaximumLength = CurrentDirectory.Length + sizeof(WCHAR);
1827
1828 FreeCurDir = TRUE;
1829 DPRINT("Using dynamically allocd curdir\n");
1830 }
1831 else
1832 {
1833 /* Use the local buffer */
1834 DPRINT("Using local system root\n");
1835 }
1836 }
1837
1838 /* Setup Loader Data */
1839 Peb->Ldr = &PebLdr;
1840 InitializeListHead(&PebLdr.InLoadOrderModuleList);
1841 InitializeListHead(&PebLdr.InMemoryOrderModuleList);
1842 InitializeListHead(&PebLdr.InInitializationOrderModuleList);
1843 PebLdr.Length = sizeof(PEB_LDR_DATA);
1844 PebLdr.Initialized = TRUE;
1845
1846 /* Allocate a data entry for the Image */
1847 LdrpImageEntry = NtLdrEntry = LdrpAllocateDataTableEntry(Peb->ImageBaseAddress);
1848
1849 /* Set it up */
1850 NtLdrEntry->EntryPoint = LdrpFetchAddressOfEntryPoint(NtLdrEntry->DllBase);
1851 NtLdrEntry->LoadCount = -1;
1852 NtLdrEntry->EntryPointActivationContext = 0;
1853 NtLdrEntry->FullDllName = ImageFileName;
1854
1855 if (IsDotNetImage)
1856 NtLdrEntry->Flags = LDRP_COR_IMAGE;
1857 else
1858 NtLdrEntry->Flags = 0;
1859
1860 /* Check if the name is empty */
1861 if (!ImageFileName.Buffer[0])
1862 {
1863 /* Use the same Base name */
1864 NtLdrEntry->BaseDllName = NtLdrEntry->FullDllName;
1865 }
1866 else
1867 {
1868 /* Find the last slash */
1869 Current = ImageFileName.Buffer;
1870 while (*Current)
1871 {
1872 if (*Current++ == '\\')
1873 {
1874 /* Set this path */
1875 NtDllName = Current;
1876 }
1877 }
1878
1879 /* Did we find anything? */
1880 if (!NtDllName)
1881 {
1882 /* Use the same Base name */
1883 NtLdrEntry->BaseDllName = NtLdrEntry->FullDllName;
1884 }
1885 else
1886 {
1887 /* Setup the name */
1888 NtLdrEntry->BaseDllName.Length = (USHORT)((ULONG_PTR)ImageFileName.Buffer + ImageFileName.Length - (ULONG_PTR)NtDllName);
1889 NtLdrEntry->BaseDllName.MaximumLength = NtLdrEntry->BaseDllName.Length + sizeof(WCHAR);
1890 NtLdrEntry->BaseDllName.Buffer = (PWSTR)((ULONG_PTR)ImageFileName.Buffer +
1891 (ImageFileName.Length - NtLdrEntry->BaseDllName.Length));
1892 }
1893 }
1894
1895 /* Processing done, insert it */
1896 LdrpInsertMemoryTableEntry(NtLdrEntry);
1897 NtLdrEntry->Flags |= LDRP_ENTRY_PROCESSED;
1898
1899 /* Now add an entry for NTDLL */
1900 NtLdrEntry = LdrpAllocateDataTableEntry(SystemArgument1);
1901 NtLdrEntry->Flags = LDRP_IMAGE_DLL;
1902 NtLdrEntry->EntryPoint = LdrpFetchAddressOfEntryPoint(NtLdrEntry->DllBase);
1903 NtLdrEntry->LoadCount = -1;
1904 NtLdrEntry->EntryPointActivationContext = 0;
1905
1906 NtLdrEntry->FullDllName.Length = FullPath.Length;
1907 NtLdrEntry->FullDllName.MaximumLength = FullPath.MaximumLength;
1908 NtLdrEntry->FullDllName.Buffer = StringBuffer;
1909 RtlAppendUnicodeStringToString(&NtLdrEntry->FullDllName, &NtDllString);
1910
1911 NtLdrEntry->BaseDllName.Length = NtDllString.Length;
1912 NtLdrEntry->BaseDllName.MaximumLength = NtDllString.MaximumLength;
1913 NtLdrEntry->BaseDllName.Buffer = NtDllString.Buffer;
1914
1915 /* Processing done, insert it */
1916 LdrpNtDllDataTableEntry = NtLdrEntry;
1917 LdrpInsertMemoryTableEntry(NtLdrEntry);
1918
1919 /* Let the world know */
1920 if (ShowSnaps)
1921 {
1922 DPRINT1("LDR: NEW PROCESS\n");
1923 DPRINT1(" Image Path: %wZ (%wZ)\n", &LdrpImageEntry->FullDllName, &LdrpImageEntry->BaseDllName);
1924 DPRINT1(" Current Directory: %wZ\n", &CurrentDirectory);
1925 DPRINT1(" Search Path: %wZ\n", &LdrpDefaultPath);
1926 }
1927
1928 /* Link the Init Order List */
1929 InsertHeadList(&Peb->Ldr->InInitializationOrderModuleList,
1930 &LdrpNtDllDataTableEntry->InInitializationOrderModuleList);
1931
1932 /* Initialize Wine's active context implementation for the current process */
1933 actctx_init();
1934
1935 /* Set the current directory */
1936 Status = RtlSetCurrentDirectory_U(&CurrentDirectory);
1937 if (!NT_SUCCESS(Status))
1938 {
1939 /* We failed, check if we should free it */
1940 if (FreeCurDir) RtlFreeUnicodeString(&CurrentDirectory);
1941
1942 /* Set it to the NT Root */
1943 CurrentDirectory = NtSystemRoot;
1944 RtlSetCurrentDirectory_U(&CurrentDirectory);
1945 }
1946 else
1947 {
1948 /* We're done with it, free it */
1949 if (FreeCurDir) RtlFreeUnicodeString(&CurrentDirectory);
1950 }
1951
1952 /* Check if we should look for a .local file */
1953 if (ProcessParameters->Flags & RTL_USER_PROCESS_PARAMETERS_LOCAL_DLL_PATH)
1954 {
1955 /* FIXME */
1956 DPRINT1("We don't support .local overrides yet\n");
1957 }
1958
1959 /* Check if the Application Verifier was enabled */
1960 if (Peb->NtGlobalFlag & FLG_POOL_ENABLE_TAIL_CHECK)
1961 {
1962 /* FIXME */
1963 DPRINT1("We don't support Application Verifier yet\n");
1964 }
1965
1966 if (IsDotNetImage)
1967 {
1968 /* FIXME */
1969 DPRINT1("We don't support .NET applications yet\n");
1970 }
1971
1972 /* FIXME: Load support for Terminal Services */
1973 if (NtHeader->OptionalHeader.Subsystem == IMAGE_SUBSYSTEM_WINDOWS_GUI)
1974 {
1975 /* Load kernel32 and call BasePostImportInit... */
1976 DPRINT("Unimplemented codepath!\n");
1977 }
1978
1979 /* Walk the IAT and load all the DLLs */
1980 ImportStatus = LdrpWalkImportDescriptor(LdrpDefaultPath.Buffer, LdrpImageEntry);
1981
1982 /* Check if relocation is needed */
1983 if (Peb->ImageBaseAddress != (PVOID)NtHeader->OptionalHeader.ImageBase)
1984 {
1985 DPRINT1("LDR: Performing EXE relocation\n");
1986
1987 /* Change the protection to prepare for relocation */
1988 ViewBase = Peb->ImageBaseAddress;
1989 Status = LdrpSetProtection(ViewBase, FALSE);
1990 if (!NT_SUCCESS(Status)) return Status;
1991
1992 /* Do the relocation */
1993 Status = LdrRelocateImageWithBias(ViewBase,
1994 0LL,
1995 NULL,
1996 STATUS_SUCCESS,
1997 STATUS_CONFLICTING_ADDRESSES,
1998 STATUS_INVALID_IMAGE_FORMAT);
1999 if (!NT_SUCCESS(Status))
2000 {
2001 DPRINT1("LdrRelocateImageWithBias() failed\n");
2002 return Status;
2003 }
2004
2005 /* Check if a start context was provided */
2006 if (Context)
2007 {
2008 DPRINT1("WARNING: Relocated EXE Context");
2009 UNIMPLEMENTED; // We should support this
2010 return STATUS_INVALID_IMAGE_FORMAT;
2011 }
2012
2013 /* Restore the protection */
2014 Status = LdrpSetProtection(ViewBase, TRUE);
2015 if (!NT_SUCCESS(Status)) return Status;
2016 }
2017
2018 /* Lock the DLLs */
2019 ListHead = &Peb->Ldr->InLoadOrderModuleList;
2020 NextEntry = ListHead->Flink;
2021 while (ListHead != NextEntry)
2022 {
2023 NtLdrEntry = CONTAINING_RECORD(NextEntry, LDR_DATA_TABLE_ENTRY, InLoadOrderLinks);
2024 NtLdrEntry->LoadCount = -1;
2025 NextEntry = NextEntry->Flink;
2026 }
2027
2028 /* Phase 0 is done */
2029 LdrpLdrDatabaseIsSetup = TRUE;
2030
2031 /* Check whether all static imports were properly loaded and return here */
2032 if (!NT_SUCCESS(ImportStatus)) return ImportStatus;
2033
2034 /* Initialize TLS */
2035 Status = LdrpInitializeTls();
2036 if (!NT_SUCCESS(Status))
2037 {
2038 DPRINT1("LDR: LdrpProcessInitialization failed to initialize TLS slots; status %x\n",
2039 Status);
2040 return Status;
2041 }
2042
2043 /* FIXME Mark the DLL Ranges for Stack Traces later */
2044
2045 /* Notify the debugger now */
2046 if (Peb->BeingDebugged)
2047 {
2048 /* Break */
2049 DbgBreakPoint();
2050
2051 /* Update show snaps again */
2052 ShowSnaps = Peb->NtGlobalFlag & FLG_SHOW_LDR_SNAPS;
2053 }
2054
2055 /* Validate the Image for MP Usage */
2056 if (LdrpNumberOfProcessors > 1) LdrpValidateImageForMp(LdrpImageEntry);
2057
2058 /* Check NX Options */
2059 if (SharedUserData->NXSupportPolicy == 1)
2060 {
2061 ExecuteOptions = 0xD;
2062 }
2063 else if (!SharedUserData->NXSupportPolicy)
2064 {
2065 ExecuteOptions = 0xA;
2066 }
2067
2068 /* Let Mm know */
2069 ZwSetInformationProcess(NtCurrentProcess(),
2070 ProcessExecuteFlags,
2071 &ExecuteOptions,
2072 sizeof(ULONG));
2073
2074 /* Check if we had Shim Data */
2075 if (OldShimData)
2076 {
2077 /* Load the Shim Engine */
2078 Peb->AppCompatInfo = NULL;
2079 //LdrpLoadShimEngine(OldShimData, ImagePathName, OldShimData);
2080 DPRINT1("We do not support shims yet\n");
2081 }
2082 else
2083 {
2084 /* Check for Application Compatibility Goo */
2085 //LdrQueryApplicationCompatibilityGoo(hKey);
2086 DPRINT("Querying app compat hacks is missing!\n");
2087 }
2088
2089 /*
2090 * FIXME: Check for special images, SecuROM, SafeDisc and other NX-
2091 * incompatible images.
2092 */
2093
2094 /* Now call the Init Routines */
2095 Status = LdrpRunInitializeRoutines(Context);
2096 if (!NT_SUCCESS(Status))
2097 {
2098 DPRINT1("LDR: LdrpProcessInitialization failed running initialization routines; status %x\n",
2099 Status);
2100 return Status;
2101 }
2102
2103 /* FIXME: Unload the Shim Engine if it was loaded */
2104
2105 /* Check if we have a user-defined Post Process Routine */
2106 if (NT_SUCCESS(Status) && Peb->PostProcessInitRoutine)
2107 {
2108 /* Call it */
2109 Peb->PostProcessInitRoutine();
2110 }
2111
2112 /* Close the key if we have one opened */
2113 if (OptionsKey) NtClose(OptionsKey);
2114
2115 /* Return status */
2116 return Status;
2117 }
2118
2119 VOID
2120 NTAPI
2121 LdrpInitFailure(NTSTATUS Status)
2122 {
2123 ULONG Response;
2124 PPEB Peb = NtCurrentPeb();
2125
2126 /* Print a debug message */
2127 DPRINT1("LDR: Process initialization failure for %wZ; NTSTATUS = %08lx\n",
2128 &Peb->ProcessParameters->ImagePathName, Status);
2129
2130 /* Raise a hard error */
2131 if (!LdrpFatalHardErrorCount)
2132 {
2133 ZwRaiseHardError(STATUS_APP_INIT_FAILURE, 1, 0, (PULONG_PTR)&Status, OptionOk, &Response);
2134 }
2135 }
2136
2137 VOID
2138 NTAPI
2139 LdrpInit(PCONTEXT Context,
2140 PVOID SystemArgument1,
2141 PVOID SystemArgument2)
2142 {
2143 LARGE_INTEGER Timeout;
2144 PTEB Teb = NtCurrentTeb();
2145 NTSTATUS Status, LoaderStatus = STATUS_SUCCESS;
2146 MEMORY_BASIC_INFORMATION MemoryBasicInfo;
2147 PPEB Peb = NtCurrentPeb();
2148
2149 DPRINT("LdrpInit() %p/%p\n",
2150 NtCurrentTeb()->RealClientId.UniqueProcess,
2151 NtCurrentTeb()->RealClientId.UniqueThread);
2152
2153 /* Check if we have a deallocation stack */
2154 if (!Teb->DeallocationStack)
2155 {
2156 /* We don't, set one */
2157 Status = NtQueryVirtualMemory(NtCurrentProcess(),
2158 Teb->NtTib.StackLimit,
2159 MemoryBasicInformation,
2160 &MemoryBasicInfo,
2161 sizeof(MEMORY_BASIC_INFORMATION),
2162 NULL);
2163 if (!NT_SUCCESS(Status))
2164 {
2165 /* Fail */
2166 LdrpInitFailure(Status);
2167 RtlRaiseStatus(Status);
2168 return;
2169 }
2170
2171 /* Set the stack */
2172 Teb->DeallocationStack = MemoryBasicInfo.AllocationBase;
2173 }
2174
2175 /* Now check if the process is already being initialized */
2176 while (_InterlockedCompareExchange(&LdrpProcessInitialized,
2177 1,
2178 0) == 1)
2179 {
2180 /* Set the timeout to 30 seconds */
2181 Timeout.QuadPart = Int32x32To64(30, -10000);
2182
2183 /* Make sure the status hasn't changed */
2184 while (!LdrpProcessInitialized)
2185 {
2186 /* Do the wait */
2187 ZwDelayExecution(FALSE, &Timeout);
2188 }
2189 }
2190
2191 /* Check if we have already setup LDR data */
2192 if (!Peb->Ldr)
2193 {
2194 /* Setup the Loader Lock */
2195 Peb->LoaderLock = &LdrpLoaderLock;
2196
2197 /* Let other code know we're initializing */
2198 LdrpInLdrInit = TRUE;
2199
2200 /* Protect with SEH */
2201 _SEH2_TRY
2202 {
2203 /* Initialize the Process */
2204 LoaderStatus = LdrpInitializeProcess(Context,
2205 SystemArgument1);
2206
2207 /* Check for success and if MinimumStackCommit was requested */
2208 if (NT_SUCCESS(LoaderStatus) && Peb->MinimumStackCommit)
2209 {
2210 /* Enforce the limit */
2211 //LdrpTouchThreadStack(Peb->MinimumStackCommit);
2212 UNIMPLEMENTED;
2213 }
2214 }
2215 _SEH2_EXCEPT(EXCEPTION_EXECUTE_HANDLER)
2216 {
2217 /* Fail with the SEH error */
2218 LoaderStatus = _SEH2_GetExceptionCode();
2219 }
2220 _SEH2_END;
2221
2222 /* We're not initializing anymore */
2223 LdrpInLdrInit = FALSE;
2224
2225 /* Check if init worked */
2226 if (NT_SUCCESS(LoaderStatus))
2227 {
2228 /* Set the process as Initialized */
2229 _InterlockedIncrement(&LdrpProcessInitialized);
2230 }
2231 }
2232 else
2233 {
2234 /* Loader data is there... is this a fork() ? */
2235 if(Peb->InheritedAddressSpace)
2236 {
2237 /* Handle the fork() */
2238 //LoaderStatus = LdrpForkProcess();
2239 LoaderStatus = STATUS_NOT_IMPLEMENTED;
2240 UNIMPLEMENTED;
2241 }
2242 else
2243 {
2244 /* This is a new thread initializing */
2245 LdrpInitializeThread(Context);
2246 }
2247 }
2248
2249 /* All done, test alert the thread */
2250 NtTestAlert();
2251
2252 /* Return */
2253 if (!NT_SUCCESS(LoaderStatus))
2254 {
2255 /* Fail */
2256 LdrpInitFailure(LoaderStatus);
2257 RtlRaiseStatus(LoaderStatus);
2258 }
2259 }
2260
2261 /* EOF */