-
-
Notifications
You must be signed in to change notification settings - Fork 1.8k
/
Copy pathldrinit.c
2677 lines (2313 loc) · 88.2 KB
/
ldrinit.c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
* COPYRIGHT: See COPYING in the top level directory
* PROJECT: ReactOS NT User-Mode Library
* FILE: dll/ntdll/ldr/ldrinit.c
* PURPOSE: User-Mode Process/Thread Startup
* PROGRAMMERS: Alex Ionescu ([email protected])
* Aleksey Bragin ([email protected])
*/
/* INCLUDES *****************************************************************/
#include <ntdll.h>
#include <compat_undoc.h>
#include <compatguid_undoc.h>
#define NDEBUG
#include <debug.h>
/* GLOBALS *******************************************************************/
HANDLE ImageExecOptionsKey;
HANDLE Wow64ExecOptionsKey;
UNICODE_STRING ImageExecOptionsString = RTL_CONSTANT_STRING(L"\\Registry\\Machine\\Software\\Microsoft\\Windows NT\\CurrentVersion\\Image File Execution Options");
UNICODE_STRING Wow64OptionsString = RTL_CONSTANT_STRING(L"");
UNICODE_STRING NtDllString = RTL_CONSTANT_STRING(L"ntdll.dll");
UNICODE_STRING Kernel32String = RTL_CONSTANT_STRING(L"kernel32.dll");
const UNICODE_STRING LdrpDotLocal = RTL_CONSTANT_STRING(L".Local");
BOOLEAN LdrpInLdrInit;
LONG LdrpProcessInitialized;
BOOLEAN LdrpLoaderLockInit;
BOOLEAN LdrpLdrDatabaseIsSetup;
BOOLEAN LdrpShutdownInProgress;
HANDLE LdrpShutdownThreadId;
BOOLEAN LdrpDllValidation;
PLDR_DATA_TABLE_ENTRY LdrpImageEntry;
PUNICODE_STRING LdrpTopLevelDllBeingLoaded;
WCHAR StringBuffer[156];
extern PTEB LdrpTopLevelDllBeingLoadedTeb; // defined in rtlsupp.c!
PLDR_DATA_TABLE_ENTRY LdrpCurrentDllInitializer;
PLDR_DATA_TABLE_ENTRY LdrpNtDllDataTableEntry;
static NTSTATUS (WINAPI *Kernel32ProcessInitPostImportFunction)(VOID);
static BOOL (WINAPI *Kernel32BaseQueryModuleData)(IN LPSTR ModuleName, IN LPSTR Unk1, IN PVOID Unk2, IN PVOID Unk3, IN PVOID Unk4);
RTL_BITMAP TlsBitMap;
RTL_BITMAP TlsExpansionBitMap;
RTL_BITMAP FlsBitMap;
BOOLEAN LdrpImageHasTls;
LIST_ENTRY LdrpTlsList;
ULONG LdrpNumberOfTlsEntries;
ULONG LdrpNumberOfProcessors;
PVOID NtDllBase;
extern LARGE_INTEGER RtlpTimeout;
BOOLEAN RtlpTimeoutDisable;
PVOID LdrpHeap;
LIST_ENTRY LdrpHashTable[LDR_HASH_TABLE_ENTRIES];
LIST_ENTRY LdrpDllNotificationList;
HANDLE LdrpKnownDllObjectDirectory;
UNICODE_STRING LdrpKnownDllPath;
WCHAR LdrpKnownDllPathBuffer[128];
UNICODE_STRING LdrpDefaultPath;
PEB_LDR_DATA PebLdr;
RTL_CRITICAL_SECTION_DEBUG LdrpLoaderLockDebug;
RTL_CRITICAL_SECTION LdrpLoaderLock =
{
&LdrpLoaderLockDebug,
-1,
0,
0,
0,
0
};
RTL_CRITICAL_SECTION FastPebLock;
BOOLEAN ShowSnaps;
ULONG LdrpFatalHardErrorCount;
ULONG LdrpActiveUnloadCount;
//extern LIST_ENTRY RtlCriticalSectionList;
VOID NTAPI RtlpInitializeVectoredExceptionHandling(VOID);
VOID NTAPI RtlpInitDeferedCriticalSection(VOID);
VOID NTAPI RtlInitializeHeapManager(VOID);
ULONG RtlpDisableHeapLookaside; // TODO: Move to heap.c
ULONG RtlpShutdownProcessFlags; // TODO: Use it
NTSTATUS LdrPerformRelocations(PIMAGE_NT_HEADERS NTHeaders, PVOID ImageBase);
void actctx_init(PVOID* pOldShimData);
extern BOOLEAN RtlpUse16ByteSLists;
#ifdef _WIN64
#define DEFAULT_SECURITY_COOKIE 0x00002B992DDFA232ll
#else
#define DEFAULT_SECURITY_COOKIE 0xBB40E64E
#endif
/* FUNCTIONS *****************************************************************/
/*
* @implemented
*/
NTSTATUS
NTAPI
LdrOpenImageFileOptionsKey(IN PUNICODE_STRING SubKey,
IN BOOLEAN Wow64,
OUT PHANDLE NewKeyHandle)
{
PHANDLE RootKeyLocation;
HANDLE RootKey;
UNICODE_STRING SubKeyString;
OBJECT_ATTRIBUTES ObjectAttributes;
NTSTATUS Status;
PWCHAR p1;
/* Check which root key to open */
if (Wow64)
RootKeyLocation = &Wow64ExecOptionsKey;
else
RootKeyLocation = &ImageExecOptionsKey;
/* Get the current key */
RootKey = *RootKeyLocation;
/* Setup the object attributes */
InitializeObjectAttributes(&ObjectAttributes,
Wow64 ?
&Wow64OptionsString : &ImageExecOptionsString,
OBJ_CASE_INSENSITIVE,
NULL,
NULL);
/* Open the root key */
Status = ZwOpenKey(&RootKey, KEY_ENUMERATE_SUB_KEYS, &ObjectAttributes);
if (NT_SUCCESS(Status))
{
/* Write the key handle */
if (InterlockedCompareExchangePointer(RootKeyLocation, RootKey, NULL) != NULL)
{
/* Someone already opened it, use it instead */
NtClose(RootKey);
RootKey = *RootKeyLocation;
}
/* Extract the name */
SubKeyString = *SubKey;
p1 = (PWCHAR)((ULONG_PTR)SubKeyString.Buffer + SubKeyString.Length);
while (SubKeyString.Length)
{
if (p1[-1] == L'\\') break;
p1--;
SubKeyString.Length -= sizeof(*p1);
}
SubKeyString.Buffer = p1;
SubKeyString.Length = SubKey->Length - SubKeyString.Length;
/* Setup the object attributes */
InitializeObjectAttributes(&ObjectAttributes,
&SubKeyString,
OBJ_CASE_INSENSITIVE,
RootKey,
NULL);
/* Open the setting key */
Status = ZwOpenKey((PHANDLE)NewKeyHandle, GENERIC_READ, &ObjectAttributes);
}
/* Return to caller */
return Status;
}
/*
* @implemented
*/
NTSTATUS
NTAPI
LdrQueryImageFileKeyOption(IN HANDLE KeyHandle,
IN PCWSTR ValueName,
IN ULONG Type,
OUT PVOID Buffer,
IN ULONG BufferSize,
OUT PULONG ReturnedLength OPTIONAL)
{
ULONG KeyInfo[256];
UNICODE_STRING ValueNameString, IntegerString;
ULONG KeyInfoSize, ResultSize;
PKEY_VALUE_PARTIAL_INFORMATION KeyValueInformation = (PKEY_VALUE_PARTIAL_INFORMATION)&KeyInfo;
BOOLEAN FreeHeap = FALSE;
NTSTATUS Status;
/* Build a string for the value name */
Status = RtlInitUnicodeStringEx(&ValueNameString, ValueName);
if (!NT_SUCCESS(Status)) return Status;
/* Query the value */
Status = ZwQueryValueKey(KeyHandle,
&ValueNameString,
KeyValuePartialInformation,
KeyValueInformation,
sizeof(KeyInfo),
&ResultSize);
if (Status == STATUS_BUFFER_OVERFLOW)
{
/* Our local buffer wasn't enough, allocate one */
KeyInfoSize = sizeof(KEY_VALUE_PARTIAL_INFORMATION) +
KeyValueInformation->DataLength;
KeyValueInformation = RtlAllocateHeap(RtlGetProcessHeap(),
0,
KeyInfoSize);
if (KeyValueInformation != NULL)
{
/* Try again */
Status = ZwQueryValueKey(KeyHandle,
&ValueNameString,
KeyValuePartialInformation,
KeyValueInformation,
KeyInfoSize,
&ResultSize);
FreeHeap = TRUE;
}
else
{
/* Give up this time */
Status = STATUS_NO_MEMORY;
}
}
/* Check for success */
if (NT_SUCCESS(Status))
{
/* Handle binary data */
if (KeyValueInformation->Type == REG_BINARY)
{
/* Check validity */
if ((Buffer) && (KeyValueInformation->DataLength <= BufferSize))
{
/* Copy into buffer */
RtlMoveMemory(Buffer,
&KeyValueInformation->Data,
KeyValueInformation->DataLength);
}
else
{
Status = STATUS_BUFFER_OVERFLOW;
}
/* Copy the result length */
if (ReturnedLength) *ReturnedLength = KeyValueInformation->DataLength;
}
else if (KeyValueInformation->Type == REG_DWORD)
{
/* Check for valid type */
if (KeyValueInformation->Type != Type)
{
/* Error */
Status = STATUS_OBJECT_TYPE_MISMATCH;
}
else
{
/* Check validity */
if ((Buffer) &&
(BufferSize == sizeof(ULONG)) &&
(KeyValueInformation->DataLength <= BufferSize))
{
/* Copy into buffer */
RtlMoveMemory(Buffer,
&KeyValueInformation->Data,
KeyValueInformation->DataLength);
}
else
{
Status = STATUS_BUFFER_OVERFLOW;
}
/* Copy the result length */
if (ReturnedLength) *ReturnedLength = KeyValueInformation->DataLength;
}
}
else if (KeyValueInformation->Type != REG_SZ)
{
/* We got something weird */
Status = STATUS_OBJECT_TYPE_MISMATCH;
}
else
{
/* String, check what you requested */
if (Type == REG_DWORD)
{
/* Validate */
if (BufferSize != sizeof(ULONG))
{
/* Invalid size */
BufferSize = 0;
Status = STATUS_INFO_LENGTH_MISMATCH;
}
else
{
/* OK, we know what you want... */
IntegerString.Buffer = (PWSTR)KeyValueInformation->Data;
IntegerString.Length = (USHORT)KeyValueInformation->DataLength -
sizeof(WCHAR);
IntegerString.MaximumLength = (USHORT)KeyValueInformation->DataLength;
Status = RtlUnicodeStringToInteger(&IntegerString, 0, (PULONG)Buffer);
}
}
else
{
/* Validate */
if (KeyValueInformation->DataLength > BufferSize)
{
/* Invalid */
Status = STATUS_BUFFER_OVERFLOW;
}
else
{
/* Set the size */
BufferSize = KeyValueInformation->DataLength;
}
/* Copy the string */
RtlMoveMemory(Buffer, &KeyValueInformation->Data, BufferSize);
}
/* Copy the result length */
if (ReturnedLength) *ReturnedLength = KeyValueInformation->DataLength;
}
}
/* Check if buffer was in heap */
if (FreeHeap) RtlFreeHeap(RtlGetProcessHeap(), 0, KeyValueInformation);
/* Return status */
return Status;
}
/*
* @implemented
*/
NTSTATUS
NTAPI
LdrQueryImageFileExecutionOptionsEx(IN PUNICODE_STRING SubKey,
IN PCWSTR ValueName,
IN ULONG Type,
OUT PVOID Buffer,
IN ULONG BufferSize,
OUT PULONG ReturnedLength OPTIONAL,
IN BOOLEAN Wow64)
{
NTSTATUS Status;
HANDLE KeyHandle;
/* Open a handle to the key */
Status = LdrOpenImageFileOptionsKey(SubKey, Wow64, &KeyHandle);
/* Check for success */
if (NT_SUCCESS(Status))
{
/* Query the data */
Status = LdrQueryImageFileKeyOption(KeyHandle,
ValueName,
Type,
Buffer,
BufferSize,
ReturnedLength);
/* Close the key */
NtClose(KeyHandle);
}
/* Return to caller */
return Status;
}
/*
* @implemented
*/
NTSTATUS
NTAPI
LdrQueryImageFileExecutionOptions(IN PUNICODE_STRING SubKey,
IN PCWSTR ValueName,
IN ULONG Type,
OUT PVOID Buffer,
IN ULONG BufferSize,
OUT PULONG ReturnedLength OPTIONAL)
{
/* Call the newer function */
return LdrQueryImageFileExecutionOptionsEx(SubKey,
ValueName,
Type,
Buffer,
BufferSize,
ReturnedLength,
FALSE);
}
VOID
NTAPI
LdrpEnsureLoaderLockIsHeld(VOID)
{
// Ignored atm
}
PVOID
NTAPI
LdrpFetchAddressOfSecurityCookie(PVOID BaseAddress, ULONG SizeOfImage)
{
PIMAGE_LOAD_CONFIG_DIRECTORY ConfigDir;
ULONG DirSize;
PVOID Cookie = NULL;
/* Check NT header first */
if (!RtlImageNtHeader(BaseAddress)) return NULL;
/* Get the pointer to the config directory */
ConfigDir = RtlImageDirectoryEntryToData(BaseAddress,
TRUE,
IMAGE_DIRECTORY_ENTRY_LOAD_CONFIG,
&DirSize);
/* Check for sanity */
if (!ConfigDir ||
(DirSize != 64 && ConfigDir->Size != DirSize) ||
(ConfigDir->Size < 0x48))
return NULL;
/* Now get the cookie */
Cookie = (PVOID)ConfigDir->SecurityCookie;
/* Check this cookie */
if ((PCHAR)Cookie <= (PCHAR)BaseAddress ||
(PCHAR)Cookie >= (PCHAR)BaseAddress + SizeOfImage)
{
Cookie = NULL;
}
/* Return validated security cookie */
return Cookie;
}
PVOID
NTAPI
LdrpInitSecurityCookie(PLDR_DATA_TABLE_ENTRY LdrEntry)
{
PULONG_PTR Cookie;
LARGE_INTEGER Counter;
ULONG_PTR NewCookie;
/* Fetch address of the cookie */
Cookie = LdrpFetchAddressOfSecurityCookie(LdrEntry->DllBase, LdrEntry->SizeOfImage);
if (Cookie)
{
/* Check if it's a default one */
if ((*Cookie == DEFAULT_SECURITY_COOKIE) ||
(*Cookie == 0xBB40))
{
/* Make up a cookie from a bunch of values which may uniquely represent
current moment of time, environment, etc */
NtQueryPerformanceCounter(&Counter, NULL);
NewCookie = Counter.LowPart ^ Counter.HighPart;
NewCookie ^= (ULONG_PTR)NtCurrentTeb()->ClientId.UniqueProcess;
NewCookie ^= (ULONG_PTR)NtCurrentTeb()->ClientId.UniqueThread;
/* Loop like it's done in KeQueryTickCount(). We don't want to call it directly. */
while (SharedUserData->SystemTime.High1Time != SharedUserData->SystemTime.High2Time)
{
YieldProcessor();
};
/* Calculate the milliseconds value and xor it to the cookie */
NewCookie ^= Int64ShrlMod32(UInt32x32To64(SharedUserData->TickCountMultiplier, SharedUserData->TickCount.LowPart), 24) +
(SharedUserData->TickCountMultiplier * (SharedUserData->TickCount.High1Time << 8));
/* Make the cookie 16bit if necessary */
if (*Cookie == 0xBB40) NewCookie &= 0xFFFF;
/* If the result is 0 or the same as we got, just subtract one from the existing value
and that's it */
if ((NewCookie == 0) || (NewCookie == *Cookie))
{
NewCookie = *Cookie - 1;
}
/* Set the new cookie value */
*Cookie = NewCookie;
}
}
return Cookie;
}
VOID
NTAPI
LdrpInitializeThread(IN PCONTEXT Context)
{
PPEB Peb = NtCurrentPeb();
PLDR_DATA_TABLE_ENTRY LdrEntry;
PLIST_ENTRY NextEntry, ListHead;
RTL_CALLER_ALLOCATED_ACTIVATION_CONTEXT_STACK_FRAME_EXTENDED ActCtx;
NTSTATUS Status;
PVOID EntryPoint;
DPRINT("LdrpInitializeThread() called for %wZ (%p/%p)\n",
&LdrpImageEntry->BaseDllName,
NtCurrentTeb()->RealClientId.UniqueProcess,
NtCurrentTeb()->RealClientId.UniqueThread);
/* Allocate an Activation Context Stack */
DPRINT("ActivationContextStack %p\n", NtCurrentTeb()->ActivationContextStackPointer);
Status = RtlAllocateActivationContextStack(&NtCurrentTeb()->ActivationContextStackPointer);
if (!NT_SUCCESS(Status))
{
DPRINT1("Warning: Unable to allocate ActivationContextStack\n");
}
/* Make sure we are not shutting down */
if (LdrpShutdownInProgress) return;
/* Allocate TLS */
LdrpAllocateTls();
/* Start at the beginning */
ListHead = &Peb->Ldr->InMemoryOrderModuleList;
NextEntry = ListHead->Flink;
while (NextEntry != ListHead)
{
/* Get the current entry */
LdrEntry = CONTAINING_RECORD(NextEntry, LDR_DATA_TABLE_ENTRY, InMemoryOrderLinks);
/* Make sure it's not ourselves */
if (Peb->ImageBaseAddress != LdrEntry->DllBase)
{
/* Check if we should call */
if (!(LdrEntry->Flags & LDRP_DONT_CALL_FOR_THREADS))
{
/* Get the entrypoint */
EntryPoint = LdrEntry->EntryPoint;
/* Check if we are ready to call it */
if ((EntryPoint) &&
(LdrEntry->Flags & LDRP_PROCESS_ATTACH_CALLED) &&
(LdrEntry->Flags & LDRP_IMAGE_DLL))
{
/* Set up the Act Ctx */
ActCtx.Size = sizeof(ActCtx);
ActCtx.Format = 1;
RtlZeroMemory(&ActCtx.Frame, sizeof(RTL_ACTIVATION_CONTEXT_STACK_FRAME));
/* Activate the ActCtx */
RtlActivateActivationContextUnsafeFast(&ActCtx,
LdrEntry->EntryPointActivationContext);
_SEH2_TRY
{
/* Check if it has TLS */
if (LdrEntry->TlsIndex)
{
/* Make sure we're not shutting down */
if (!LdrpShutdownInProgress)
{
/* Call TLS */
LdrpCallTlsInitializers(LdrEntry, DLL_THREAD_ATTACH);
}
}
/* Make sure we're not shutting down */
if (!LdrpShutdownInProgress)
{
/* Call the Entrypoint */
DPRINT("%wZ - Calling entry point at %p for thread attaching, %p/%p\n",
&LdrEntry->BaseDllName, LdrEntry->EntryPoint,
NtCurrentTeb()->RealClientId.UniqueProcess,
NtCurrentTeb()->RealClientId.UniqueThread);
LdrpCallInitRoutine(LdrEntry->EntryPoint,
LdrEntry->DllBase,
DLL_THREAD_ATTACH,
NULL);
}
}
_SEH2_EXCEPT(EXCEPTION_EXECUTE_HANDLER)
{
DPRINT1("WARNING: Exception 0x%x during LdrpCallInitRoutine(DLL_THREAD_ATTACH) for %wZ\n",
_SEH2_GetExceptionCode(), &LdrEntry->BaseDllName);
}
_SEH2_END;
/* Deactivate the ActCtx */
RtlDeactivateActivationContextUnsafeFast(&ActCtx);
}
}
}
/* Next entry */
NextEntry = NextEntry->Flink;
}
/* Check for TLS */
if (LdrpImageHasTls && !LdrpShutdownInProgress)
{
/* Set up the Act Ctx */
ActCtx.Size = sizeof(ActCtx);
ActCtx.Format = 1;
RtlZeroMemory(&ActCtx.Frame, sizeof(RTL_ACTIVATION_CONTEXT_STACK_FRAME));
/* Activate the ActCtx */
RtlActivateActivationContextUnsafeFast(&ActCtx,
LdrpImageEntry->EntryPointActivationContext);
_SEH2_TRY
{
/* Do TLS callbacks */
LdrpCallTlsInitializers(LdrpImageEntry, DLL_THREAD_ATTACH);
}
_SEH2_EXCEPT(EXCEPTION_EXECUTE_HANDLER)
{
/* Do nothing */
}
_SEH2_END;
/* Deactivate the ActCtx */
RtlDeactivateActivationContextUnsafeFast(&ActCtx);
}
DPRINT("LdrpInitializeThread() done\n");
}
NTSTATUS
NTAPI
LdrpRunInitializeRoutines(IN PCONTEXT Context OPTIONAL)
{
PLDR_DATA_TABLE_ENTRY LocalArray[16];
PLIST_ENTRY ListHead;
PLIST_ENTRY NextEntry;
PLDR_DATA_TABLE_ENTRY LdrEntry, *LdrRootEntry, OldInitializer;
PVOID EntryPoint;
ULONG Count, i;
//ULONG BreakOnInit;
NTSTATUS Status = STATUS_SUCCESS;
PPEB Peb = NtCurrentPeb();
RTL_CALLER_ALLOCATED_ACTIVATION_CONTEXT_STACK_FRAME_EXTENDED ActCtx;
ULONG BreakOnDllLoad;
PTEB OldTldTeb;
BOOLEAN DllStatus;
DPRINT("LdrpRunInitializeRoutines() called for %wZ (%p/%p)\n",
&LdrpImageEntry->BaseDllName,
NtCurrentTeb()->RealClientId.UniqueProcess,
NtCurrentTeb()->RealClientId.UniqueThread);
/* Check the Loader Lock */
LdrpEnsureLoaderLockIsHeld();
/* Get the number of entries to call */
if ((Count = LdrpClearLoadInProgress()))
{
/* Check if we can use our local buffer */
if (Count > 16)
{
/* Allocate space for all the entries */
LdrRootEntry = RtlAllocateHeap(LdrpHeap,
0,
Count * sizeof(*LdrRootEntry));
if (!LdrRootEntry) return STATUS_NO_MEMORY;
}
else
{
/* Use our local array */
LdrRootEntry = LocalArray;
}
}
else
{
/* Don't need one */
LdrRootEntry = NULL;
}
/* Show debug message */
if (ShowSnaps)
{
DPRINT1("[%p,%p] LDR: Real INIT LIST for Process %wZ\n",
NtCurrentTeb()->RealClientId.UniqueThread,
NtCurrentTeb()->RealClientId.UniqueProcess,
&Peb->ProcessParameters->ImagePathName);
}
/* Loop in order */
ListHead = &Peb->Ldr->InInitializationOrderModuleList;
NextEntry = ListHead->Flink;
i = 0;
while (NextEntry != ListHead)
{
/* Get the Data Entry */
LdrEntry = CONTAINING_RECORD(NextEntry, LDR_DATA_TABLE_ENTRY, InInitializationOrderLinks);
/* Check if we have a Root Entry */
if (LdrRootEntry)
{
/* Check flags */
if (!(LdrEntry->Flags & LDRP_ENTRY_PROCESSED))
{
/* Setup the Cookie for the DLL */
LdrpInitSecurityCookie(LdrEntry);
/* Check for valid entrypoint */
if (LdrEntry->EntryPoint)
{
/* Write in array */
ASSERT(i < Count);
LdrRootEntry[i] = LdrEntry;
/* Display debug message */
if (ShowSnaps)
{
DPRINT1("[%p,%p] LDR: %wZ init routine %p\n",
NtCurrentTeb()->RealClientId.UniqueThread,
NtCurrentTeb()->RealClientId.UniqueProcess,
&LdrEntry->FullDllName,
LdrEntry->EntryPoint);
}
i++;
}
}
}
/* Set the flag */
LdrEntry->Flags |= LDRP_ENTRY_PROCESSED;
NextEntry = NextEntry->Flink;
}
Status = STATUS_SUCCESS;
/* If we got a context, then we have to call Kernel32 for TS support */
if (Context)
{
/* Check if we have one */
if (Kernel32ProcessInitPostImportFunction)
{
/* Call it */
Status = Kernel32ProcessInitPostImportFunction();
if (!NT_SUCCESS(Status))
{
DPRINT1("LDR: LdrpRunInitializeRoutines - Failed running kernel32 post-import function, Status=0x%08lx\n", Status);
}
}
/* Clear it */
Kernel32ProcessInitPostImportFunction = NULL;
}
/* No root entry? return */
if (!LdrRootEntry)
return Status;
/* Set the TLD TEB */
OldTldTeb = LdrpTopLevelDllBeingLoadedTeb;
LdrpTopLevelDllBeingLoadedTeb = NtCurrentTeb();
/* Loop */
i = 0;
while (i < Count)
{
/* Get an entry */
LdrEntry = LdrRootEntry[i];
/* FIXME: Verify NX Compat */
/* Move to next entry */
i++;
/* Get its entrypoint */
EntryPoint = LdrEntry->EntryPoint;
/* Are we being debugged? */
BreakOnDllLoad = 0;
if (Peb->BeingDebugged || Peb->ReadImageFileExecOptions)
{
/* Check if we should break on load */
Status = LdrQueryImageFileExecutionOptions(&LdrEntry->BaseDllName,
L"BreakOnDllLoad",
REG_DWORD,
&BreakOnDllLoad,
sizeof(ULONG),
NULL);
if (!NT_SUCCESS(Status)) BreakOnDllLoad = 0;
/* Reset status back to STATUS_SUCCESS */
Status = STATUS_SUCCESS;
}
/* Break if aksed */
if (BreakOnDllLoad)
{
/* Check if we should show a message */
if (ShowSnaps)
{
DPRINT1("LDR: %wZ loaded.", &LdrEntry->BaseDllName);
DPRINT1(" - About to call init routine at %p\n", EntryPoint);
}
/* Break in debugger */
DbgBreakPoint();
}
/* Make sure we have an entrypoint */
if (EntryPoint)
{
/* Save the old Dll Initializer and write the current one */
OldInitializer = LdrpCurrentDllInitializer;
LdrpCurrentDllInitializer = LdrEntry;
/* Set up the Act Ctx */
ActCtx.Size = sizeof(ActCtx);
ActCtx.Format = 1;
RtlZeroMemory(&ActCtx.Frame, sizeof(RTL_ACTIVATION_CONTEXT_STACK_FRAME));
/* Activate the ActCtx */
RtlActivateActivationContextUnsafeFast(&ActCtx,
LdrEntry->EntryPointActivationContext);
_SEH2_TRY
{
/* Check if it has TLS */
if (LdrEntry->TlsIndex && Context)
{
/* Call TLS */
LdrpCallTlsInitializers(LdrEntry, DLL_PROCESS_ATTACH);
}
/* Call the Entrypoint */
if (ShowSnaps)
{
DPRINT1("%wZ - Calling entry point at %p for DLL_PROCESS_ATTACH\n",
&LdrEntry->BaseDllName, EntryPoint);
}
DllStatus = LdrpCallInitRoutine(EntryPoint,
LdrEntry->DllBase,
DLL_PROCESS_ATTACH,
Context);
}
_SEH2_EXCEPT(EXCEPTION_EXECUTE_HANDLER)
{
DllStatus = FALSE;
DPRINT1("WARNING: Exception 0x%x during LdrpCallInitRoutine(DLL_PROCESS_ATTACH) for %wZ\n",
_SEH2_GetExceptionCode(), &LdrEntry->BaseDllName);
}
_SEH2_END;
/* Deactivate the ActCtx */
RtlDeactivateActivationContextUnsafeFast(&ActCtx);
/* Save the Current DLL Initializer */
LdrpCurrentDllInitializer = OldInitializer;
/* Mark the entry as processed */
LdrEntry->Flags |= LDRP_PROCESS_ATTACH_CALLED;
/* Fail if DLL init failed */
if (!DllStatus)
{
DPRINT1("LDR: DLL_PROCESS_ATTACH for dll \"%wZ\" (InitRoutine: %p) failed\n",
&LdrEntry->BaseDllName, EntryPoint);
Status = STATUS_DLL_INIT_FAILED;
goto Quickie;
}
}
}
/* Loop in order */
ListHead = &Peb->Ldr->InInitializationOrderModuleList;
NextEntry = NextEntry->Flink;
while (NextEntry != ListHead)
{
/* Get the Data Entry */
LdrEntry = CONTAINING_RECORD(NextEntry, LDR_DATA_TABLE_ENTRY, InInitializationOrderLinks);
/* FIXME: Verify NX Compat */
// LdrpCheckNXCompatibility()
/* Next entry */
NextEntry = NextEntry->Flink;
}
/* Check for TLS */
if (LdrpImageHasTls && Context)
{
/* Set up the Act Ctx */
ActCtx.Size = sizeof(ActCtx);
ActCtx.Format = 1;
RtlZeroMemory(&ActCtx.Frame, sizeof(RTL_ACTIVATION_CONTEXT_STACK_FRAME));
/* Activate the ActCtx */
RtlActivateActivationContextUnsafeFast(&ActCtx,
LdrpImageEntry->EntryPointActivationContext);
_SEH2_TRY
{
/* Do TLS callbacks */
LdrpCallTlsInitializers(LdrpImageEntry, DLL_PROCESS_ATTACH);
}
_SEH2_EXCEPT(EXCEPTION_EXECUTE_HANDLER)
{
/* Do nothing */
}
_SEH2_END;
/* Deactivate the ActCtx */
RtlDeactivateActivationContextUnsafeFast(&ActCtx);
}
Quickie:
/* Restore old TEB */
LdrpTopLevelDllBeingLoadedTeb = OldTldTeb;
/* Check if the array is in the heap */
if (LdrRootEntry != LocalArray)
{
/* Free the array */
RtlFreeHeap(LdrpHeap, 0, LdrRootEntry);
}
/* Return to caller */
DPRINT("LdrpRunInitializeRoutines() done\n");
return Status;
}
/*
* @implemented
*/
NTSTATUS
NTAPI
LdrShutdownProcess(VOID)
{
PPEB Peb = NtCurrentPeb();
PLDR_DATA_TABLE_ENTRY LdrEntry;
PLIST_ENTRY NextEntry, ListHead;
RTL_CALLER_ALLOCATED_ACTIVATION_CONTEXT_STACK_FRAME_EXTENDED ActCtx;
PVOID EntryPoint;
DPRINT("LdrShutdownProcess() called for %wZ\n", &LdrpImageEntry->BaseDllName);
if (LdrpShutdownInProgress) return STATUS_SUCCESS;
/* Tell the Shim Engine */
if (g_ShimsEnabled)
{
VOID(NTAPI *SE_ProcessDying)();
SE_ProcessDying = RtlDecodeSystemPointer(g_pfnSE_ProcessDying);
SE_ProcessDying();
}
/* Tell the world */
if (ShowSnaps)
{
DPRINT1("\n");
}
/* Set the shutdown variables */
LdrpShutdownThreadId = NtCurrentTeb()->RealClientId.UniqueThread;
LdrpShutdownInProgress = TRUE;
/* Enter the Loader Lock */
RtlEnterCriticalSection(&LdrpLoaderLock);
/* Cleanup trace logging data (Etw) */
if (SharedUserData->TraceLogging)
{
/* FIXME */
DPRINT1("We don't support Etw yet.\n");
}
/* Start at the end */
ListHead = &Peb->Ldr->InInitializationOrderModuleList;
NextEntry = ListHead->Blink;
while (NextEntry != ListHead)
{
/* Get the current entry */
LdrEntry = CONTAINING_RECORD(NextEntry, LDR_DATA_TABLE_ENTRY, InInitializationOrderLinks);
NextEntry = NextEntry->Blink;
/* Make sure it's not ourselves */
if (Peb->ImageBaseAddress != LdrEntry->DllBase)
{
/* Get the entrypoint */
EntryPoint = LdrEntry->EntryPoint;
/* Check if we are ready to call it */
if (EntryPoint &&
(LdrEntry->Flags & LDRP_PROCESS_ATTACH_CALLED) &&
LdrEntry->Flags)
{
/* Set up the Act Ctx */
ActCtx.Size = sizeof(ActCtx);
ActCtx.Format = 1;