-
Notifications
You must be signed in to change notification settings - Fork 4.9k
/
Copy pathceemain.cpp
2362 lines (1967 loc) · 77.7 KB
/
ceemain.cpp
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
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// ===========================================================================
// File: CEEMAIN.CPP
// ===========================================================================
//
//
//
// The CLR code base uses a hyperlink feature of the HyperAddin plugin for Visual Studio. If you don't see
// 'HyperAddin' in your Visual Studio menu bar you don't have this support. To get it type
//
// \\clrmain\tools\installCLRAddins
//
// After installing HyperAddin, your first run of VS should be as an administrator so HyperAddin can update
// some registry information.
//
// At this point the code: prefixes become hyperlinks in Visual Studio and life is good. See
// http://mswikis/clr/dev/Pages/CLR%20Team%20Commenting.aspx for more information
//
// There is a bug associated with Visual Studio where it does not recognise the hyperlink if there is a ::
// preceeding it on the same line. Since C++ uses :: as a namespace separator, this can often mean that the
// second hyperlink on a line does not work. To work around this it is better to use '.' instead of :: as
// the namespace separators in code: hyperlinks.
//
// #StartHere
// #TableOfContents The .NET Runtime Table of contents
//
// This comment is mean to be a nexus that allows you to jump quickly to various interesting parts of the
// runtime.
//
// You can refer to product studio bugs using urls like the following
// * http://bugcheck/bugs/DevDivBugs/2320.asp
// * http://bugcheck/bugs/VSWhidbey/601210.asp
//
// Dev10 Bugs can be added with URLs like the following (for Dev10 bug 671409)
// * http://tkbgitvstfat01:8090/wi.aspx?id=671409
//
//*************************************************************************************************
//
// * Introduction to the runtime file:../../Documentation/botr/botr-faq.md
//
// #MajorDataStructures. The major data structures associated with the runtime are
// * code:Thread (see file:threads.h#ThreadClass) - the additional thread state the runtime needs.
// * code:AppDomain - The managed version of a process
// * code:Assembly - The unit of deployment and versioning (may be several DLLs but often is only one).
// * code:Module - represents a Module (DLL or EXE).
// * code:MethodTable - represents the 'hot' part of a type (needed during normal execution)
// * code:EEClass - represents the 'cold' part of a type (used during compilation, interop, ...)
// * code:MethodDesc - represents a Method
// * code:FieldDesc - represents a Field.
// * code:Object - represents a object on the GC heap allocated with code:Alloc
//
// * ECMA specifications
// * Partition I Concepts
// http://download.microsoft.com/download/D/C/1/DC1B219F-3B11-4A05-9DA3-2D0F98B20917/Partition%20I%20Architecture.doc
// * Partition II Meta Data
// http://download.microsoft.com/download/D/C/1/DC1B219F-3B11-4A05-9DA3-2D0F98B20917/Partition%20II%20Metadata.doc
// * Partition III IL
// http://download.microsoft.com/download/D/C/1/DC1B219F-3B11-4A05-9DA3-2D0F98B20917/Partition%20III%20CIL.doc
//
// * Serge Liden (worked on the CLR and owned ILASM / ILDASM for a long time wrote a good book on IL
// * Expert .NET 2.0 IL Assembler http://www.amazon.com/Expert-NET-2-0-IL-Assembler/dp/1590596463
//
// * This is also a pretty nice overview of what the CLR is at
// http://msdn2.microsoft.com/en-us/netframework/aa497266.aspx
//
// * code:EEStartup - This routine must be called before any interesting runtime services are used. It is
// invoked as part of mscorwks's DllMain logic.
// * code:#EEShutDown - Code called before we shut down the EE.
//
// * file:..\inc\corhdr.h#ManagedHeader - From a data structure point of view, this is the entry point into
// the runtime. This is how all other data in the EXE are found.
//
// * code:ICorJitCompiler#EEToJitInterface - This is the interface from the the EE to the Just in time (JIT)
// compiler. The interface to the JIT is relatively simple (compileMethod), however the EE provides a
// rich set of callbacks so the JIT can get all the information it needs. See also
// file:../../Documentation/botr/ryujit-overview.md for general information on the JIT.
//
// * code:VirtualCallStubManager - This is the main class that implements interface dispatch
//
// * Precode - Every method needs entry point for other code to call even if that native code does not
// actually exist yet. To support this methods can have code:Precode that is an entry point that exists
// and will call the JIT compiler if the code does not yet exist.
//
// * NGEN - NGen stands for Native code GENeration and it is the runtime way of precompiling IL and IL
// Meta-data into native code and runtime data structures. At compilation time the most
// fundamental data structures is the code:ZapNode which represents something that needs to go into the
// NGEN image.
//
// * What is cooperative / preemtive mode ? file:threads.h#CooperativeMode and
// file:threads.h#SuspendingTheRuntime and file:../../Documentation/botr/threading.md
// * Garbage collection - file:gc.cpp#Overview and file:../../Documentation/botr/garbage-collection.md
// * code:AppDomain - The managed version of a process.
// * Calling Into the runtime (FCALLs QCalls) file:../../Documentation/botr/corelib.md
// * Exceptions - file:../../Documentation/botr/exceptions.md. The most important routine to start
// with is code:COMPlusFrameHandler which is the routine that we hook up to get called when an unmanaged
// exception happens.
// * Assembly Loading file:../../Documentation/botr/type-loader.md
// * Profiling file:../../Documentation/botr/profiling.md and file:../../Documentation/botr/profilability.md
// * FCALLS QCALLS (calling into the runtime from managed code)
// file:../../Documentation/botr/corelib.md
// * Event Tracing for Windows
// * file:../inc/eventtrace.h#EventTracing -
// * This is the main file dealing with event tracing in CLR
// * The implementation of this class is available in file:eventtrace.cpp
// * file:../inc/eventtrace.h#CEtwTracer - This is the main class dealing with event tracing in CLR.
// Follow the link for more information on how this feature has been implemented
// * http://mswikis/clr/dev/Pages/CLR%20ETW%20Events%20Wiki.aspx - Follow the link for more information on how to
// use this instrumentation feature.
// ----------------------------------------------------------------------------------------------------
// Features in the runtime that have been given hyperlinks
//
// * code:Nullable#NullableFeature - the Nullable<T> type has special runtime semantics associated with
// boxing this describes this feature.
#include "common.h"
#include "vars.hpp"
#include "log.h"
#include "ceemain.h"
#include "clsload.hpp"
#include "object.h"
#include "hash.h"
#include "ecall.h"
#include "ceemain.h"
#include "dllimport.h"
#include "syncblk.h"
#include "eeconfig.h"
#include "stublink.h"
#include "method.hpp"
#include "codeman.h"
#include "frames.h"
#include "threads.h"
#include "stackwalk.h"
#include "gcheaputilities.h"
#include "interoputil.h"
#include "fieldmarshaler.h"
#include "dbginterface.h"
#include "eedbginterfaceimpl.h"
#include "debugdebugger.h"
#include "cordbpriv.h"
#include "comdelegate.h"
#include "appdomain.hpp"
#include "eventtrace.h"
#include "corhost.h"
#include "binder.h"
#include "olevariant.h"
#include "comcallablewrapper.h"
#include "../dlls/mscorrc/resource.h"
#include "util.hpp"
#include "shimload.h"
#include "comthreadpool.h"
#include "posterror.h"
#include "virtualcallstub.h"
#include "strongnameinternal.h"
#include "syncclean.hpp"
#include "typeparse.h"
#include "debuginfostore.h"
#include "eemessagebox.h"
#include "finalizerthread.h"
#include "threadsuspend.h"
#include "disassembler.h"
#include "jithost.h"
#include "pgo.h"
#ifndef TARGET_UNIX
#include "dwreport.h"
#endif // !TARGET_UNIX
#include "stringarraylist.h"
#include "stubhelpers.h"
#ifdef FEATURE_STACK_SAMPLING
#include "stacksampler.h"
#endif
#ifndef CROSSGEN_COMPILE
#include "win32threadpool.h"
#endif
#include <shlwapi.h>
#include "bbsweep.h"
#ifdef FEATURE_COMINTEROP
#include "runtimecallablewrapper.h"
#include "notifyexternals.h"
#include "mngstdinterfaces.h"
#include "interoplibinterface.h"
#endif // FEATURE_COMINTEROP
#ifdef FEATURE_COMINTEROP_APARTMENT_SUPPORT
#include "olecontexthelpers.h"
#endif // FEATURE_COMINTEROP_APARTMENT_SUPPORT
#ifdef PROFILING_SUPPORTED
#include "proftoeeinterfaceimpl.h"
#include "profilinghelper.h"
#endif // PROFILING_SUPPORTED
#ifdef FEATURE_INTERPRETER
#include "interpreter.h"
#endif // FEATURE_INTERPRETER
#include "../binder/inc/coreclrbindercommon.h"
#ifdef FEATURE_PERFMAP
#include "perfmap.h"
#endif
#include "diagnosticserveradapter.h"
#include "eventpipeadapter.h"
#ifndef TARGET_UNIX
// Included for referencing __security_cookie
#include "process.h"
#endif // !TARGET_UNIX
#ifdef FEATURE_GDBJIT
#include "gdbjit.h"
#endif // FEATURE_GDBJIT
#include "genanalysis.h"
#ifndef CROSSGEN_COMPILE
static int GetThreadUICultureId(__out LocaleIDValue* pLocale); // TODO: This shouldn't use the LCID. We should rely on name instead
static HRESULT GetThreadUICultureNames(__inout StringArrayList* pCultureNames);
#endif // !CROSSGEN_COMPILE
HRESULT EEStartup();
#ifndef CROSSGEN_COMPILE
static void InitializeGarbageCollector();
#ifdef DEBUGGING_SUPPORTED
static void InitializeDebugger(void);
static void TerminateDebugger(void);
extern "C" HRESULT __cdecl CorDBGetInterface(DebugInterface** rcInterface);
#endif // DEBUGGING_SUPPORTED
#endif // !CROSSGEN_COMPILE
// g_coreclr_embedded indicates that coreclr is linked directly into the program
// g_hostpolicy_embedded indicates that the hostpolicy library is linked directly into the executable
// Note: that it can happen that the hostpolicy is embedded but coreclr isn't (on Windows singlefilehost is built that way)
#ifdef CORECLR_EMBEDDED
bool g_coreclr_embedded = true;
bool g_hostpolicy_embedded = true; // We always embed hostpolicy if coreclr is also embedded
#else
bool g_coreclr_embedded = false;
bool g_hostpolicy_embedded = false; // In this case the value may come from a runtime property and may change
#endif
// Remember how the last startup of EE went.
HRESULT g_EEStartupStatus = S_OK;
// Flag indicating if the EE has been started. This is set prior to initializing the default AppDomain, and so does not indicate that
// the EE is fully able to execute arbitrary managed code. To ensure the EE is fully started, call EnsureEEStarted rather than just
// checking this flag.
Volatile<BOOL> g_fEEStarted = FALSE;
// The OS thread ID of the thread currently performing EE startup, or 0 if there is no such thread.
DWORD g_dwStartupThreadId = 0;
// Event to synchronize EE shutdown.
static CLREvent * g_pEEShutDownEvent;
static DangerousNonHostedSpinLock g_EEStartupLock;
// ---------------------------------------------------------------------------
// %%Function: EnsureEEStarted()
//
// Description: Ensure the CLR is started.
// ---------------------------------------------------------------------------
HRESULT EnsureEEStarted()
{
CONTRACTL
{
NOTHROW;
GC_TRIGGERS;
MODE_PREEMPTIVE;
ENTRY_POINT;
}
CONTRACTL_END;
if (g_fEEShutDown)
return E_FAIL;
HRESULT hr = E_FAIL;
// On non x86 platforms, when we load CoreLib during EEStartup, we will
// re-enter _CorDllMain with a DLL_PROCESS_ATTACH for CoreLib. We are
// far enough in startup that this is allowed, however we don't want to
// re-start the startup code so we need to check to see if startup has
// been initiated or completed before we call EEStartup.
//
// We do however want to make sure other threads block until the EE is started,
// which we will do further down.
if (!g_fEEStarted)
{
BEGIN_ENTRYPOINT_NOTHROW;
#ifndef TARGET_UNIX
// The sooner we do this, the sooner we avoid probing registry entries.
// (Perf Optimization for VSWhidbey:113373.)
REGUTIL::InitOptionalConfigCache();
#endif
BOOL bStarted=FALSE;
{
DangerousNonHostedSpinLockHolder lockHolder(&g_EEStartupLock);
// Now that we've acquired the lock, check again to make sure we aren't in
// the process of starting the CLR or that it hasn't already been fully started.
// At this point, if startup has been inited we don't have anything more to do.
// And if EEStartup already failed before, we don't do it again.
if (!g_fEEStarted && !g_fEEInit && SUCCEEDED (g_EEStartupStatus))
{
g_dwStartupThreadId = GetCurrentThreadId();
EEStartup();
bStarted=g_fEEStarted;
hr = g_EEStartupStatus;
g_dwStartupThreadId = 0;
}
else
{
hr = g_EEStartupStatus;
if (SUCCEEDED(g_EEStartupStatus))
{
hr = S_FALSE;
}
}
}
END_ENTRYPOINT_NOTHROW;
}
else
{
//
// g_fEEStarted is TRUE, but startup may not be complete since we initialize the default AppDomain
// *after* setting that flag. g_fEEStarted is set inside of g_EEStartupLock, and that lock is
// not released until the EE is really started - so we can quickly check whether the EE is definitely
// started by checking if that lock is currently held. If it is not, then we know the other thread
// (that is actually doing the startup) has finished startup. If it is currently held, then we
// need to wait for the other thread to release it, which we do by simply acquiring the lock ourselves.
//
// We do not want to do this blocking if we are the thread currently performing EE startup. So we check
// that first.
//
// Note that the call to IsHeld here is an "acquire" barrier, as is acquiring the lock. And the release of
// the lock by the other thread is a "release" barrier, due to the volatile semantics in the lock's
// implementation. This assures us that once we observe the lock having been released, we are guaranteed
// to observe a fully-initialized EE.
//
// A note about thread affinity here: we're using the OS thread ID of the current thread without
// asking the host to pin us to this thread, as we did above. We can get away with this, because we are
// only interested in a particular thread ID (that of the "startup" thread) and *that* particular thread
// is already affinitized by the code above. So if we get that particular OS thread ID, we know for sure
// we are really the startup thread.
//
if (g_EEStartupLock.IsHeld() && g_dwStartupThreadId != GetCurrentThreadId())
{
DangerousNonHostedSpinLockHolder lockHolder(&g_EEStartupLock);
}
hr = g_EEStartupStatus;
if (SUCCEEDED(g_EEStartupStatus))
{
hr = S_FALSE;
}
}
return hr;
}
#ifndef CROSSGEN_COMPILE
#ifndef TARGET_UNIX
// This is our Ctrl-C, Ctrl-Break, etc. handler.
static BOOL WINAPI DbgCtrlCHandler(DWORD dwCtrlType)
{
WRAPPER_NO_CONTRACT;
#if defined(DEBUGGING_SUPPORTED)
// Note that if a managed-debugger is attached, it's actually attached with the native
// debugging pipeline and it will get a control-c notifications via native debug events.
// However, if we let the native debugging pipeline handle the event and send the notification
// to the debugger, then we break pre-V4 behaviour because we intercept handlers registered
// in-process. See Dev10 Bug 846455 for more information.
if (CORDebuggerAttached() &&
(dwCtrlType == CTRL_C_EVENT || dwCtrlType == CTRL_BREAK_EVENT))
{
return g_pDebugInterface->SendCtrlCToDebugger(dwCtrlType);
}
else
#endif // DEBUGGING_SUPPORTED
{
if (dwCtrlType == CTRL_CLOSE_EVENT || dwCtrlType == CTRL_SHUTDOWN_EVENT)
{
// Initiate shutdown so the ProcessExit handlers run
ForceEEShutdown(SCA_ReturnWhenShutdownComplete);
}
g_fInControlC = true; // only for weakening assertions in checked build.
return FALSE; // keep looking for a real handler.
}
}
#endif
// A host can specify that it only wants one version of hosting interface to be used.
BOOL g_singleVersionHosting;
void InitializeStartupFlags()
{
CONTRACTL {
NOTHROW;
GC_TRIGGERS;
MODE_ANY;
} CONTRACTL_END;
STARTUP_FLAGS flags = CorHost2::GetStartupFlags();
if (flags & STARTUP_CONCURRENT_GC)
g_IGCconcurrent = 1;
else
g_IGCconcurrent = 0;
g_heap_type = ((flags & STARTUP_SERVER_GC) && GetCurrentProcessCpuCount() > 1) ? GC_HEAP_SVR : GC_HEAP_WKS;
g_IGCHoardVM = (flags & STARTUP_HOARD_GC_VM) == 0 ? 0 : 1;
}
#endif // CROSSGEN_COMPILE
// BBSweepStartFunction is the first function to execute in the BBT sweeper thread.
// It calls WatchForSweepEvent where we wait until a sweep occurs.
DWORD __stdcall BBSweepStartFunction(LPVOID lpArgs)
{
CONTRACTL
{
THROWS;
GC_TRIGGERS;
MODE_PREEMPTIVE;
}
CONTRACTL_END;
class CLRBBSweepCallback : public ICLRBBSweepCallback
{
virtual HRESULT WriteProfileData()
{
BEGIN_ENTRYPOINT_NOTHROW
WRAPPER_NO_CONTRACT;
Module::WriteAllModuleProfileData(false);
END_ENTRYPOINT_NOTHROW;
return S_OK;
}
} clrCallback;
EX_TRY
{
g_BBSweep.WatchForSweepEvents(&clrCallback);
}
EX_CATCH
{
}
EX_END_CATCH(RethrowTerminalExceptions)
return 0;
}
//-----------------------------------------------------------------------------
void InitGSCookie()
{
CONTRACTL
{
THROWS;
GC_NOTRIGGER;
MODE_ANY;
}
CONTRACTL_END;
volatile GSCookie * pGSCookiePtr = GetProcessGSCookiePtr();
#ifdef TARGET_UNIX
// On Unix, the GS cookie is stored in a read only data segment
DWORD newProtection = PAGE_READWRITE;
#else // TARGET_UNIX
DWORD newProtection = PAGE_EXECUTE_READWRITE;
#endif // !TARGET_UNIX
DWORD oldProtection;
if(!ClrVirtualProtect((LPVOID)pGSCookiePtr, sizeof(GSCookie), newProtection, &oldProtection))
{
ThrowLastError();
}
#ifdef TARGET_UNIX
// PAL layer is unable to extract old protection for regions that were not allocated using VirtualAlloc
oldProtection = PAGE_READONLY;
#endif // TARGET_UNIX
#ifndef TARGET_UNIX
// The GSCookie cannot be in a writeable page
assert(((oldProtection & (PAGE_READWRITE|PAGE_WRITECOPY|PAGE_EXECUTE_READWRITE|
PAGE_EXECUTE_WRITECOPY|PAGE_WRITECOMBINE)) == 0));
// Forces VC cookie to be initialized.
void * pf = &__security_check_cookie;
pf = NULL;
GSCookie val = (GSCookie)(__security_cookie ^ GetTickCount());
#else // !TARGET_UNIX
// REVIEW: Need something better for PAL...
GSCookie val = (GSCookie)GetTickCount();
#endif // !TARGET_UNIX
#ifdef _DEBUG
// In _DEBUG, always use the same value to make it easier to search for the cookie
val = (GSCookie) BIT64_ONLY(0x9ABCDEF012345678) NOT_BIT64(0x12345678);
#endif
// To test if it is initialized. Also for ICorMethodInfo::getGSCookie()
if (val == 0)
val ++;
*pGSCookiePtr = val;
if(!ClrVirtualProtect((LPVOID)pGSCookiePtr, sizeof(GSCookie), oldProtection, &oldProtection))
{
ThrowLastError();
}
}
Volatile<BOOL> g_bIsGarbageCollectorFullyInitialized = FALSE;
void SetGarbageCollectorFullyInitialized()
{
LIMITED_METHOD_CONTRACT;
g_bIsGarbageCollectorFullyInitialized = TRUE;
}
// Tells whether the garbage collector is fully initialized
// Stronger than IsGCHeapInitialized
BOOL IsGarbageCollectorFullyInitialized()
{
LIMITED_METHOD_CONTRACT;
return g_bIsGarbageCollectorFullyInitialized;
}
// ---------------------------------------------------------------------------
// %%Function: EEStartupHelper
//
// Returns:
// S_OK - On success
//
// Description:
// Reserved to initialize the EE runtime engine explicitly.
// ---------------------------------------------------------------------------
#ifndef IfFailGotoLog
#define IfFailGotoLog(EXPR, LABEL) \
do { \
hr = (EXPR);\
if(FAILED(hr)) { \
STRESS_LOG2(LF_STARTUP, LL_ALWAYS, "%s failed with code %x", #EXPR, hr);\
goto LABEL; \
} \
else \
STRESS_LOG1(LF_STARTUP, LL_ALWAYS, "%s completed", #EXPR);\
} while (0)
#endif
#ifndef IfFailGoLog
#define IfFailGoLog(EXPR) IfFailGotoLog(EXPR, ErrExit)
#endif
#ifndef CROSSGEN_COMPILE
#ifdef TARGET_UNIX
void EESocketCleanupHelper(bool isExecutingOnAltStack)
{
CONTRACTL
{
GC_NOTRIGGER;
MODE_ANY;
} CONTRACTL_END;
if (isExecutingOnAltStack)
{
GetThread()->SetExecutingOnAltStack();
}
// Close the debugger transport socket first
if (g_pDebugInterface != NULL)
{
g_pDebugInterface->CleanupTransportSocket();
}
// Close the diagnostic server socket.
#ifdef FEATURE_PERFTRACING
DiagnosticServerAdapter::Shutdown();
#endif // FEATURE_PERFTRACING
}
#endif // TARGET_UNIX
#endif // CROSSGEN_COMPILE
void EEStartupHelper()
{
CONTRACTL
{
THROWS;
GC_TRIGGERS;
MODE_ANY;
} CONTRACTL_END;
#ifdef ENABLE_CONTRACTS_IMPL
{
extern void ContractRegressionCheck();
ContractRegressionCheck();
}
#endif
HRESULT hr = S_OK;
static ConfigDWORD breakOnEELoad;
EX_TRY
{
g_fEEInit = true;
#ifndef CROSSGEN_COMPILE
// We cache the SystemInfo for anyone to use throughout the life of the EE.
GetSystemInfo(&g_SystemInfo);
// Set callbacks so that LoadStringRC knows which language our
// threads are in so that it can return the proper localized string.
// TODO: This shouldn't rely on the LCID (id), but only the name
SetResourceCultureCallbacks(GetThreadUICultureNames,
GetThreadUICultureId);
#ifndef TARGET_UNIX
::SetConsoleCtrlHandler(DbgCtrlCHandler, TRUE/*add*/);
#endif
#endif // CROSSGEN_COMPILE
// SString initialization
// This needs to be done before config because config uses SString::Empty()
SString::Startup();
IfFailGo(EEConfig::Setup());
#ifndef CROSSGEN_COMPILE
#ifdef HOST_WINDOWS
InitializeCrashDump();
#endif // HOST_WINDOWS
// Initialize Numa and CPU group information
// Need to do this as early as possible. Used by creating object handle
// table inside Ref_Initialization() before GC is initialized.
NumaNodeInfo::InitNumaNodeInfo();
#ifndef TARGET_UNIX
CPUGroupInfo::EnsureInitialized();
#endif // !TARGET_UNIX
// Initialize global configuration settings based on startup flags
// This needs to be done before the EE has started
InitializeStartupFlags();
ThreadpoolMgr::StaticInitialize();
MethodDescBackpatchInfoTracker::StaticInitialize();
CodeVersionManager::StaticInitialize();
TieredCompilationManager::StaticInitialize();
CallCountingManager::StaticInitialize();
OnStackReplacementManager::StaticInitialize();
InitThreadManager();
STRESS_LOG0(LF_STARTUP, LL_ALWAYS, "Returned successfully from InitThreadManager");
#ifdef FEATURE_PERFTRACING
// Initialize the event pipe.
EventPipeAdapter::Initialize();
#endif // FEATURE_PERFTRACING
GenAnalysis::Initialize();
#ifdef TARGET_UNIX
PAL_SetShutdownCallback(EESocketCleanupHelper);
#endif // TARGET_UNIX
#ifdef STRESS_LOG
if (CLRConfig::GetConfigValue(CLRConfig::UNSUPPORTED_StressLog, g_pConfig->StressLog()) != 0) {
unsigned facilities = CLRConfig::GetConfigValue(CLRConfig::INTERNAL_LogFacility, LF_ALL);
unsigned level = CLRConfig::GetConfigValue(CLRConfig::EXTERNAL_LogLevel, LL_INFO1000);
unsigned bytesPerThread = CLRConfig::GetConfigValue(CLRConfig::UNSUPPORTED_StressLogSize, STRESSLOG_CHUNK_SIZE * 4);
unsigned totalBytes = CLRConfig::GetConfigValue(CLRConfig::UNSUPPORTED_TotalStressLogSize, STRESSLOG_CHUNK_SIZE * 1024);
CLRConfigStringHolder logFilename = CLRConfig::GetConfigValue(CLRConfig::UNSUPPORTED_StressLogFilename);
StressLog::Initialize(facilities, level, bytesPerThread, totalBytes, GetClrModuleBase(), logFilename);
g_pStressLog = &StressLog::theLog;
}
#endif
#ifdef FEATURE_PERFTRACING
DiagnosticServerAdapter::Initialize();
DiagnosticServerAdapter::PauseForDiagnosticsMonitor();
#endif // FEATURE_PERFTRACING
#ifdef FEATURE_GDBJIT
// Initialize gdbjit
NotifyGdb::Initialize();
#endif // FEATURE_GDBJIT
#ifdef FEATURE_EVENT_TRACE
// Initialize event tracing early so we can trace CLR startup time events.
InitializeEventTracing();
// Fire the EE startup ETW event
ETWFireEvent(EEStartupStart_V1);
#endif // FEATURE_EVENT_TRACE
InitGSCookie();
Frame::Init();
#endif // CROSSGEN_COMPILE
#ifdef LOGGING
InitializeLogging();
#endif
#ifdef FEATURE_PERFMAP
PerfMap::Initialize();
#endif
#ifdef FEATURE_PGO
PgoManager::Initialize();
#endif
STRESS_LOG0(LF_STARTUP, LL_ALWAYS, "===================EEStartup Starting===================");
#ifndef CROSSGEN_COMPILE
#ifndef TARGET_UNIX
IfFailGoLog(EnsureRtlFunctions());
#endif // !TARGET_UNIX
InitEventStore();
#endif
// Initialize the default Assembly Binder and the binder infrastructure
IfFailGoLog(CCoreCLRBinderHelper::Init());
if (g_pConfig != NULL)
{
IfFailGoLog(g_pConfig->sync());
}
// Fire the runtime information ETW event
ETW::InfoLog::RuntimeInformation(ETW::InfoLog::InfoStructs::Normal);
if (breakOnEELoad.val(CLRConfig::UNSUPPORTED_BreakOnEELoad) == 1)
{
#ifdef _DEBUG
_ASSERTE(!"Start loading EE!");
#else
DebugBreak();
#endif
}
#ifdef ENABLE_STARTUP_DELAY
PREFIX_ASSUME(NULL != g_pConfig);
if (g_pConfig->StartupDelayMS())
{
ClrSleepEx(g_pConfig->StartupDelayMS(), FALSE);
}
#endif
#if USE_DISASSEMBLER
if ((g_pConfig->GetGCStressLevel() & (EEConfig::GCSTRESS_INSTR_JIT | EEConfig::GCSTRESS_INSTR_NGEN)) != 0)
{
Disassembler::StaticInitialize();
if (!Disassembler::IsAvailable())
{
fprintf(stderr, "External disassembler is not available.\n");
IfFailGo(E_FAIL);
}
}
#endif // USE_DISASSEMBLER
// Monitors, Crsts, and SimpleRWLocks all use the same spin heuristics
// Cache the (potentially user-overridden) values now so they are accessible from asm routines
InitializeSpinConstants();
#ifndef CROSSGEN_COMPILE
// Cross-process named objects are not supported in PAL
// (see CorUnix::InternalCreateEvent - src/pal/src/synchobj/event.cpp)
#if !defined(TARGET_UNIX)
// Initialize the sweeper thread.
if (g_pConfig->GetZapBBInstr() != NULL)
{
DWORD threadID;
HANDLE hBBSweepThread = ::CreateThread(NULL,
0,
(LPTHREAD_START_ROUTINE) BBSweepStartFunction,
NULL,
0,
&threadID);
_ASSERTE(hBBSweepThread);
g_BBSweep.SetBBSweepThreadHandle(hBBSweepThread);
}
#endif // TARGET_UNIX
#ifdef FEATURE_INTERPRETER
Interpreter::Initialize();
#endif // FEATURE_INTERPRETER
StubManager::InitializeStubManagers();
#ifndef TARGET_UNIX
{
// Record mscorwks geometry
PEDecoder pe(GetClrModuleBase());
g_runtimeLoadedBaseAddress = (SIZE_T)pe.GetBase();
g_runtimeVirtualSize = (SIZE_T)pe.GetVirtualSize();
InitCodeAllocHint(g_runtimeLoadedBaseAddress, g_runtimeVirtualSize, GetRandomInt(64));
}
#endif // !TARGET_UNIX
#endif // CROSSGEN_COMPILE
// Set up the cor handle map. This map is used to load assemblies in
// memory instead of using the normal system load
PEImage::Startup();
AccessCheckOptions::Startup();
CoreLibBinder::Startup();
Stub::Init();
StubLinkerCPU::Init();
#ifndef CROSSGEN_COMPILE
InitializeGarbageCollector();
if (!GCHandleUtilities::GetGCHandleManager()->Initialize())
{
IfFailGo(E_OUTOFMEMORY);
}
g_pEEShutDownEvent = new CLREvent();
g_pEEShutDownEvent->CreateManualEvent(FALSE);
VirtualCallStubManager::InitStatic();
#endif // CROSSGEN_COMPILE
// Setup the domains. Threads are started in a default domain.
// Static initialization
PEAssembly::Attach();
BaseDomain::Attach();
SystemDomain::Attach();
// Start up the EE intializing all the global variables
ECall::Init();
COMDelegate::Init();
ExecutionManager::Init();
JitHost::Init();
#ifndef CROSSGEN_COMPILE
#ifndef TARGET_UNIX
if (!RegisterOutOfProcessWatsonCallbacks())
{
IfFailGo(E_FAIL);
}
#endif // !TARGET_UNIX
#ifdef DEBUGGING_SUPPORTED
if(!NingenEnabled())
{
// Initialize the debugging services. This must be done before any
// EE thread objects are created, and before any classes or
// modules are loaded.
InitializeDebugger(); // throws on error
}
#endif // DEBUGGING_SUPPORTED
#ifdef PROFILING_SUPPORTED
// Initialize the profiling services.
hr = ProfilingAPIUtility::InitializeProfiling();
_ASSERTE(SUCCEEDED(hr));
IfFailGo(hr);
#endif // PROFILING_SUPPORTED
InitializeExceptionHandling();
//
// Install our global exception filter
//
if (!InstallUnhandledExceptionFilter())
{
IfFailGo(E_FAIL);
}
// throws on error
SetupThread();
#ifdef DEBUGGING_SUPPORTED
// Notify debugger once the first thread is created to finish initialization.
if (g_pDebugInterface != NULL)
{
g_pDebugInterface->StartupPhase2(GetThread());
}
#endif
InitPreStubManager();
#ifdef FEATURE_COMINTEROP
InitializeComInterop();
#endif // FEATURE_COMINTEROP
StubHelpers::Init();
// Before setting up the execution manager initialize the first part
// of the JIT helpers.
InitJITHelpers1();
InitJITHelpers2();
SyncBlockCache::Attach();
// Set up the sync block
SyncBlockCache::Start();
StackwalkCache::Init();
// This isn't done as part of InitializeGarbageCollector() above because it
// requires write barriers to have been set up on x86, which happens as part
// of InitJITHelpers1.
hr = g_pGCHeap->Initialize();
IfFailGo(hr);
#ifdef FEATURE_PERFTRACING
// Finish setting up rest of EventPipe - specifically enable SampleProfiler if it was requested at startup.
// SampleProfiler needs to cooperate with the GC which hasn't fully finished setting up in the first part of the
// EventPipe initialization, so this is done after the GC has been fully initialized.
EventPipeAdapter::FinishInitialize();
#endif // FEATURE_PERFTRACING
// This isn't done as part of InitializeGarbageCollector() above because thread
// creation requires AppDomains to have been set up.
FinalizerThread::FinalizerThreadCreate();
// Now we really have fully initialized the garbage collector
SetGarbageCollectorFullyInitialized();
#ifdef DEBUGGING_SUPPORTED
// Make a call to publish the DefaultDomain for the debugger
// This should be done before assemblies/modules are loaded into it (i.e. SystemDomain::Init)
// and after its OK to switch GC modes and syncronize for sending events to the debugger.
// @dbgtodo synchronization: this can probably be simplified in V3
LOG((LF_CORDB | LF_SYNC | LF_STARTUP, LL_INFO1000, "EEStartup: adding default domain 0x%x\n",
SystemDomain::System()->DefaultDomain()));
SystemDomain::System()->PublishAppDomainAndInformDebugger(SystemDomain::System()->DefaultDomain());
#endif
#ifdef HAVE_GCCOVER
MethodDesc::Init();
#endif
#endif // CROSSGEN_COMPILE
Assembly::Initialize();
#if defined(HOST_OSX) && defined(HOST_ARM64)
PAL_JITWriteEnable(true);
#endif // defined(HOST_OSX) && defined(HOST_ARM64)