Welcome to mirror list, hosted at ThFree Co, Russian Federation.

startup.cpp « Runtime « Native « src - github.com/mono/corert.git - Unnamed repository; edit this file 'description' to name the repository.
summaryrefslogtreecommitdiff
blob: 8a7b0c56cb0b288f7911cc68362e576317135eb6 (plain)
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
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#include "common.h"
#include "CommonTypes.h"
#include "CommonMacros.h"
#include "daccess.h"
#include "PalRedhawkCommon.h"
#include "PalRedhawk.h"
#include "rhassert.h"
#include "slist.h"
#include "gcrhinterface.h"
#include "varint.h"
#include "regdisplay.h"
#include "StackFrameIterator.h"
#include "thread.h"
#include "holder.h"
#include "Crst.h"
#include "event.h"
#include "RWLock.h"
#include "threadstore.h"
#include "threadstore.inl"
#include "RuntimeInstance.h"
#include "rhbinder.h"
#include "CachedInterfaceDispatch.h"
#include "RhConfig.h"
#include "stressLog.h"
#include "RestrictedCallouts.h"

#ifndef DACCESS_COMPILE

#ifdef PROFILE_STARTUP
unsigned __int64 g_startupTimelineEvents[NUM_STARTUP_TIMELINE_EVENTS] = { 0 };
#endif // PROFILE_STARTUP

HANDLE RtuCreateRuntimeInstance(HANDLE hPalInstance);


#ifdef PLATFORM_UNIX
Int32 __stdcall RhpHardwareExceptionHandler(UIntNative faultCode, UIntNative faultAddress, PAL_LIMITED_CONTEXT* palContext, UIntNative* arg0Reg, UIntNative* arg1Reg);
#else
Int32 __stdcall RhpVectoredExceptionHandler(PEXCEPTION_POINTERS pExPtrs);
#endif

void CheckForPalFallback();
void DetectCPUFeatures();

extern RhConfig * g_pRhConfig;

EXTERN_C bool g_fHasFastFxsave = false;

CrstStatic g_CastCacheLock;
CrstStatic g_ThunkPoolLock;

bool InitDLL(HANDLE hPalInstance)
{
    CheckForPalFallback();

#ifdef FEATURE_CACHED_INTERFACE_DISPATCH
    //
    // Initialize interface dispatch.
    //
    if (!InitializeInterfaceDispatch())
        return false;
#endif

    //
    // Initialize support for registering GC and HandleTable callouts.
    //
    if (!RestrictedCallouts::Initialize())
        return false;

#if !defined(APP_LOCAL_RUNTIME) && !defined(USE_PORTABLE_HELPERS)
#ifndef PLATFORM_UNIX
    PalAddVectoredExceptionHandler(1, RhpVectoredExceptionHandler);
#else
    PalSetHardwareExceptionHandler(RhpHardwareExceptionHandler);
#endif
#endif // !APP_LOCAL_RUNTIME && !USE_PORTABLE_HELPERS

    //
    // init per-instance state
    //
    HANDLE hRuntimeInstance = RtuCreateRuntimeInstance(hPalInstance);
    if (NULL == hRuntimeInstance)
        return false;
    STARTUP_TIMELINE_EVENT(NONGC_INIT_COMPLETE);

    // @TODO: currently we're always forcing a workstation GC.
    // @TODO: GC per-instance vs per-DLL state separation
    RedhawkGCInterface::GCType gcType = g_pRhConfig->GetUseServerGC()
        ? RedhawkGCInterface::GCType_Server
        : RedhawkGCInterface::GCType_Workstation;

    if (!RedhawkGCInterface::InitializeSubsystems(gcType))
        return false;

    STARTUP_TIMELINE_EVENT(GC_INIT_COMPLETE);

#ifdef STRESS_LOG
    UInt32 dwTotalStressLogSize = g_pRhConfig->GetTotalStressLogSize();
    UInt32 dwStressLogLevel = g_pRhConfig->GetStressLogLevel();

    unsigned facility = (unsigned)LF_ALL;
    unsigned dwPerThreadChunks = (dwTotalStressLogSize / 24) / STRESSLOG_CHUNK_SIZE;
    if (dwTotalStressLogSize != 0)
    {
        StressLog::Initialize(facility, dwStressLogLevel, 
                              dwPerThreadChunks * STRESSLOG_CHUNK_SIZE, 
                              (unsigned)dwTotalStressLogSize, hPalInstance);
    }
#endif // STRESS_LOG

    DetectCPUFeatures();

    if (!g_CastCacheLock.InitNoThrow(CrstType::CrstCastCache))
        return false;

    if (!g_ThunkPoolLock.InitNoThrow(CrstType::CrstCastCache))
        return false;

    return true;
}

void CheckForPalFallback()
{
#ifdef _DEBUG
    UInt32 disallowSetting = g_pRhConfig->GetDisallowRuntimeServicesFallback();
    if (disallowSetting == 0)
        return;

    // The fallback provider doesn't implement write watch, so we check for the write watch capability as a 
    // proxy for whether or not we're using the fallback provider since we don't have direct access to this 
    // information from here.

    if (disallowSetting == 1)
    {
        // If RH_DisallowRuntimeServicesFallback is set to 1, we want to fail fast if we discover that we're 
        // running against the fallback provider.  
        if (!PalHasCapability(WriteWatchCapability))
            RhFailFast();
    }
    else if (disallowSetting == 2)
    {
        // If RH_DisallowRuntimeServicesFallback is set to 2, we want to fail fast if we discover that we're 
        // NOT running against the fallback provider.  
        if (PalHasCapability(WriteWatchCapability))
            RhFailFast();
    }
#endif // _DEBUG
}

void DetectCPUFeatures()
{
#if !defined(CORERT) // @TODO: CORERT: DetectCPUFeatures

#ifdef _X86_
    // We depend on fxsave / fxrstor.  These were added to Pentium II and later, so they're pretty well guaranteed to be
    // available, but we double-check anyway and fail fast if they are not supported.
    CPU_INFO cpuInfo;
    PalCpuIdEx(1, 0, &cpuInfo);
    if (!(cpuInfo.Edx & X86_FXSR))  
        RhFailFast();
#endif

#ifdef _AMD64_
    // AMD has a "fast" mode for fxsave/fxrstor, which omits the saving of xmm registers.  The OS will enable this mode
    // if it is supported.  So if we continue to use fxsave/fxrstor, we must manually save/restore the xmm registers.
    CPU_INFO cpuInfo;
    PalCpuIdEx(0x80000001, 0, &cpuInfo);
    if (cpuInfo.Edx & AMD_FFXSR)
        g_fHasFastFxsave = true;
#endif

#endif // !CORERT
}

#ifdef PROFILE_STARTUP
#define STD_OUTPUT_HANDLE ((UInt32)-11)

struct RegisterModuleTrace
{
    LARGE_INTEGER Begin;
    LARGE_INTEGER End;
};

const int NUM_REGISTER_MODULE_TRACES = 16;
int g_registerModuleCount = 0;

RegisterModuleTrace g_registerModuleTraces[NUM_REGISTER_MODULE_TRACES] = { 0 };

void AppendInt64(char * pBuffer, UInt32* pLen, UInt64 value)
{
    char localBuffer[20];
    int cch = 0;

    do
    {
        localBuffer[cch++] = '0' + (value % 10);
        value = value / 10;
    } while (value);

    for (int i = 0; i < cch; i++)
    {
        pBuffer[(*pLen)++] = localBuffer[cch - i - 1];
    }

    pBuffer[(*pLen)++] = ',';
    pBuffer[(*pLen)++] = ' ';
}
#endif // PROFILE_STARTUP

bool UninitDLL(HANDLE /*hModDLL*/)
{
#ifdef PROFILE_STARTUP
    char buffer[1024];

    UInt32 len = 0;

    AppendInt64(buffer, &len, g_startupTimelineEvents[PROCESS_ATTACH_BEGIN]);
    AppendInt64(buffer, &len, g_startupTimelineEvents[NONGC_INIT_COMPLETE]);
    AppendInt64(buffer, &len, g_startupTimelineEvents[GC_INIT_COMPLETE]);
    AppendInt64(buffer, &len, g_startupTimelineEvents[PROCESS_ATTACH_COMPLETE]);

    for (int i = 0; i < g_registerModuleCount; i++)
    {
        AppendInt64(buffer, &len, g_registerModuleTraces[i].Begin.QuadPart);
        AppendInt64(buffer, &len, g_registerModuleTraces[i].End.QuadPart);
    }

    buffer[len++] = '\n';

    fwrite(buffer, len, 1, stdout);
#endif // PROFILE_STARTUP
    return true;
}

void DllThreadAttach(HANDLE /*hPalInstance*/)
{
    // We do not call ThreadStore::AttachThread from here because the loader lock is held.  Instead, the 
    // threads themselves will do this on their first reverse pinvoke.
}

volatile bool g_processShutdownHasStarted = false;

void DllThreadDetach()
{
    // BEWARE: loader lock is held here!

    // Should have already received a call to FiberDetach for this thread's "home" fiber.
    Thread* pCurrentThread = ThreadStore::GetCurrentThreadIfAvailable();
    if (pCurrentThread != NULL && !pCurrentThread->IsDetached())
    {
        // Once shutdown starts, RuntimeThreadShutdown callbacks are ignored, implying that
        // it is no longer guaranteed that exiting threads will be detached.
        if (!g_processShutdownHasStarted)
        {
            ASSERT_UNCONDITIONALLY("Detaching thread whose home fiber has not been detached");
            RhFailFast();
        }
    }
}

void __stdcall RuntimeThreadShutdown(void* thread)
{
    // Note: loader lock is normally *not* held here!
    // The one exception is that the loader lock may be held during the thread shutdown callback
    // that is made for the single thread that runs the final stages of orderly process
    // shutdown (i.e., the thread that delivers the DLL_PROCESS_DETACH notifications when the
    // process is being torn down via an ExitProcess call).
    UNREFERENCED_PARAMETER(thread);
    ASSERT((Thread*)thread == ThreadStore::GetCurrentThread());

    if (!g_processShutdownHasStarted)
    {
        ThreadStore::DetachCurrentThread();
    }
}

COOP_PINVOKE_HELPER(UInt32_BOOL, RhpRegisterModule, (ModuleHeader *pModuleHeader))
{
#ifdef PROFILE_STARTUP
    if (g_registerModuleCount < NUM_REGISTER_MODULE_TRACES)
    {
        PalQueryPerformanceCounter(&g_registerModuleTraces[g_registerModuleCount].Begin);
    }
#endif // PROFILE_STARTUP

    RuntimeInstance * pInstance = GetRuntimeInstance();

    if (!pInstance->RegisterModule(pModuleHeader))
        return UInt32_FALSE;

#ifdef PROFILE_STARTUP
    if (g_registerModuleCount < NUM_REGISTER_MODULE_TRACES)
    {
        PalQueryPerformanceCounter(&g_registerModuleTraces[g_registerModuleCount].End);
        g_registerModuleCount++;
    }
#endif // PROFILE_STARTUP

    return UInt32_TRUE;
}

COOP_PINVOKE_HELPER(UInt32_BOOL, RhpEnableConservativeStackReporting, ())
{
    RuntimeInstance * pInstance = GetRuntimeInstance();
    if (!pInstance->EnableConservativeStackReporting())
        return UInt32_FALSE;

    return UInt32_TRUE;
}

#endif // !DACCESS_COMPILE

GPTR_IMPL_INIT(RuntimeInstance, g_pTheRuntimeInstance, NULL);

#ifndef DACCESS_COMPILE

//
// Creates a new runtime instance.
//
// @TODO: EXPORT
HANDLE RtuCreateRuntimeInstance(HANDLE hPalInstance)
{
    CreateHolder<RuntimeInstance> pRuntimeInstance = RuntimeInstance::Create(hPalInstance);
    if (NULL == pRuntimeInstance)
        return NULL;

    ASSERT_MSG(g_pTheRuntimeInstance == NULL, "multi-instances are not supported");
    g_pTheRuntimeInstance = pRuntimeInstance;

    pRuntimeInstance.SuppressRelease();
    return (HANDLE) pRuntimeInstance;
}

//
// Currently called only from a managed executable once Main returns, this routine does whatever is needed to
// cleanup managed state before exiting. There's not a lot here at the moment since we're always about to let
// the OS tear the process down anyway. 
//
// @TODO: Eventually we'll probably have a hosting API and explicit shutdown request. When that happens we'll
// something more sophisticated here since we won't be able to rely on the OS cleaning up after us.
//
COOP_PINVOKE_HELPER(void, RhpShutdown, ())
{
#ifdef FEATURE_PROFILING
    GetRuntimeInstance()->WriteProfileInfo();
#endif // FEATURE_PROFILING
    // Indicate that runtime shutdown is complete and that the caller is about to start shutting down the entire process.
    g_processShutdownHasStarted = true;
}

#endif // !DACCESS_COMPILE