summaryrefslogtreecommitdiff
path: root/src/dlls/mscoree/mscoree.cpp
blob: f33f0955e437ab5cd861e1479d341204818d6d73 (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
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
// 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.
//*****************************************************************************
// MSCoree.cpp
//*****************************************************************************
#include "stdafx.h"                     // Standard header.

#include <utilcode.h>                   // Utility helpers.
#include <posterror.h>                  // Error handlers
#define INIT_GUIDS  
#include <corpriv.h>
#include <winwrap.h>
#include <mscoree.h>
#include "shimload.h"
#include "metadataexports.h"
#include "ex.h"

#include "product_version.h"

#ifdef FEATURE_COMINTEROP
#include "ComCallUnmarshal.h"
#endif // FEATURE_COMINTEROP

#include "clrprivhosting.h"

#ifdef FEATURE_PROFAPI_ATTACH_DETACH
#include "../../vm/profattach.h"
#endif // FEATURE_PROFAPI_ATTACH_DETACH

#include <dbgenginemetrics.h>

// Locals.
BOOL STDMETHODCALLTYPE EEDllMain( // TRUE on success, FALSE on error.
                       HINSTANCE    hInst,                  // Instance handle of the loaded module.
                       DWORD        dwReason,               // Reason for loading.
                       LPVOID       lpReserved);                // Unused.

// Globals.
HINSTANCE g_hThisInst;  // This library.

#ifndef CROSSGEN_COMPILE
//*****************************************************************************
// Handle lifetime of loaded library.
//*****************************************************************************

#include <shlwapi.h>

#include <process.h> // for __security_init_cookie()

extern "C" IExecutionEngine* __stdcall IEE();

#ifdef NO_CRT_INIT
#define _CRT_INIT(hInstance, dwReason, lpReserved) (TRUE)
#else
extern "C" BOOL WINAPI _CRT_INIT(HANDLE hInstance, DWORD dwReason, LPVOID lpReserved);
#endif

extern "C" BOOL WINAPI DllMain(HANDLE hInstance, DWORD dwReason, LPVOID lpReserved);

// For the CoreClr, this is the real DLL entrypoint. We make ourselves the first entrypoint as
// we need to capture coreclr's hInstance before the C runtine initializes. This function
// will capture hInstance, let the C runtime initialize and then invoke the "classic"
// DllMain that initializes everything else.
extern "C" BOOL WINAPI CoreDllMain(HANDLE hInstance, DWORD dwReason, LPVOID lpReserved)
{
    STATIC_CONTRACT_NOTHROW;

    BOOL result;
    switch (dwReason)
    {
        case DLL_PROCESS_ATTACH:
#ifndef FEATURE_PAL        
            // Make sure the /GS security cookie is initialized before we call anything else.
            // BinScope detects the call to __security_init_cookie in its "Has Non-GS-friendly
            // Initialization" check and makes it pass.
            __security_init_cookie();
#endif // FEATURE_PAL        

            // It's critical that we invoke InitUtilCode() before the CRT initializes. 
            // We have a lot of global ctors that will break if we let the CRT initialize without
            // this step having been done.

            CoreClrCallbacks cccallbacks;
            cccallbacks.m_hmodCoreCLR               = (HINSTANCE)hInstance;
            cccallbacks.m_pfnIEE                    = IEE;
            cccallbacks.m_pfnGetCORSystemDirectory  = GetCORSystemDirectoryInternaL;
            cccallbacks.m_pfnGetCLRFunction         = GetCLRFunction;
            InitUtilcode(cccallbacks);

            if (!(result = _CRT_INIT(hInstance, dwReason, lpReserved)))
            {
                // CRT_INIT may fail to initialize the CRT heap. Make sure we don't continue 
                // down a path that would trigger an AV and tear down the host process
                break;
            }
            result = DllMain(hInstance, dwReason, lpReserved);
            break;
        
        case DLL_THREAD_ATTACH:
            _CRT_INIT(hInstance, dwReason, lpReserved);
            result = DllMain(hInstance, dwReason, lpReserved);
            break;

        case DLL_PROCESS_DETACH: // intentional fallthru
        case DLL_THREAD_DETACH:
            result = DllMain(hInstance, dwReason, lpReserved);
            _CRT_INIT(hInstance, dwReason, lpReserved);
            break;

        default:
            result = FALSE;  // it'd be an OS bug if we got here - not much we can do.
            break;   
    }
    return result;
}

extern "C"
BOOL WINAPI DllMain(HANDLE hInstance, DWORD dwReason, LPVOID lpReserved)
{
    STATIC_CONTRACT_NOTHROW;

    switch (dwReason)
    {
    case DLL_PROCESS_ATTACH:
        {
            // Save the module handle.
            g_hThisInst = (HINSTANCE)hInstance;

            // Prevent buffer-overruns
            // If buffer is overrun, it is possible the saved callback has been trashed.
            // The callback is unsafe.
            //SetBufferOverrunHandler();
            if (!EEDllMain((HINSTANCE)hInstance, dwReason, lpReserved))
            {
                return FALSE;
            }
        }
        break;

    case DLL_PROCESS_DETACH:
        {
            EEDllMain((HINSTANCE)hInstance, dwReason, lpReserved);
        }
        break;

    case DLL_THREAD_DETACH:
        {
            EEDllMain((HINSTANCE)hInstance, dwReason, lpReserved);
        }
        break;
    }

    return TRUE;
}

#ifdef FEATURE_COMINTEROP
// ---------------------------------------------------------------------------
// %%Function: DllCanUnloadNowInternal  
// 
// Returns:
//  S_FALSE                 - Indicating that COR, once loaded, may not be
//                            unloaded.
// ---------------------------------------------------------------------------
STDAPI DllCanUnloadNowInternal(void)
{
    STATIC_CONTRACT_NOTHROW;
    STATIC_CONTRACT_ENTRY_POINT;    

    //we should never unload unless the process is dying
    return S_FALSE;
}  // DllCanUnloadNowInternal

// ---------------------------------------------------------------------------
// %%Function: DllRegisterServerInternal 
// 
// Description:
//  Registers
// ---------------------------------------------------------------------------
STDAPI DllRegisterServerInternal(HINSTANCE hMod, LPCWSTR version)
{

    CONTRACTL{
        NOTHROW;
        GC_NOTRIGGER;
        ENTRY_POINT;
        PRECONDITION(CheckPointer(version));
    } CONTRACTL_END;

    return S_OK;
}  // DllRegisterServerInternal

// ---------------------------------------------------------------------------
// %%Function: DllUnregisterServerInternal      
// ---------------------------------------------------------------------------
STDAPI DllUnregisterServerInternal(void)
{

    CONTRACTL
    {
        GC_NOTRIGGER;
        NOTHROW;
        ENTRY_POINT;
    }
    CONTRACTL_END;

    return S_OK;
    
}  // DllUnregisterServerInternal
#endif // FEATURE_COMINTEROP

#endif // CROSSGEN_COMPILE

HINSTANCE GetModuleInst()
{
    LIMITED_METHOD_CONTRACT;
    return (g_hThisInst);
}

// ---------------------------------------------------------------------------
// %%Function: MetaDataGetDispenser
// This function gets the Dispenser interface given the CLSID and REFIID.
// ---------------------------------------------------------------------------
STDAPI MetaDataGetDispenser(            // Return HRESULT
    REFCLSID    rclsid,                 // The class to desired.
    REFIID      riid,                   // Interface wanted on class factory.
    LPVOID FAR  *ppv)                   // Return interface pointer here.
{

    CONTRACTL {
        NOTHROW;
        GC_NOTRIGGER;
        ENTRY_POINT;
        PRECONDITION(CheckPointer(ppv));
    } CONTRACTL_END;
    
    NonVMComHolder<IClassFactory> pcf(NULL);
    HRESULT hr;
    BEGIN_ENTRYPOINT_NOTHROW;

    IfFailGo(MetaDataDllGetClassObject(rclsid, IID_IClassFactory, (void **) &pcf));
    hr = pcf->CreateInstance(NULL, riid, ppv);

ErrExit:
    END_ENTRYPOINT_NOTHROW;

    return (hr);
}

// ---------------------------------------------------------------------------
// %%Function: GetMetaDataInternalInterface
// This function gets the IMDInternalImport given the metadata on memory.
// ---------------------------------------------------------------------------
STDAPI  GetMetaDataInternalInterface(
    LPVOID      pData,                  // [IN] in memory metadata section
    ULONG       cbData,                 // [IN] size of the metadata section
    DWORD       flags,                  // [IN] MDInternal_OpenForRead or MDInternal_OpenForENC
    REFIID      riid,                   // [IN] desired interface
    void        **ppv)                  // [OUT] returned interface
{
    CONTRACTL{
        NOTHROW;
        GC_NOTRIGGER;
        ENTRY_POINT;
        PRECONDITION(CheckPointer(pData));
        PRECONDITION(CheckPointer(ppv));
    } CONTRACTL_END;

    HRESULT hr = S_OK;
    BEGIN_ENTRYPOINT_NOTHROW;

    hr = GetMDInternalInterface(pData, cbData, flags, riid, ppv);

    END_ENTRYPOINT_NOTHROW;
    return hr;
}

// ---------------------------------------------------------------------------
// %%Function: GetMetaDataInternalInterfaceFromPublic
// This function gets the internal scopeless interface given the public
// scopeless interface.
// ---------------------------------------------------------------------------
STDAPI  GetMetaDataInternalInterfaceFromPublic(
    IUnknown    *pv,                    // [IN] Given interface.
    REFIID      riid,                   // [IN] desired interface
    void        **ppv)                  // [OUT] returned interface
{
    CONTRACTL{
        NOTHROW;
        GC_NOTRIGGER;
        ENTRY_POINT;
        PRECONDITION(CheckPointer(pv));
        PRECONDITION(CheckPointer(ppv));
    } CONTRACTL_END;
    
    HRESULT hr = S_OK;
    BEGIN_ENTRYPOINT_NOTHROW;

    hr = GetMDInternalInterfaceFromPublic(pv, riid, ppv);

    END_ENTRYPOINT_NOTHROW;
    return hr;
}

// ---------------------------------------------------------------------------
// %%Function: GetMetaDataPublicInterfaceFromInternal
// This function gets the public scopeless interface given the internal
// scopeless interface.
// ---------------------------------------------------------------------------
STDAPI  GetMetaDataPublicInterfaceFromInternal(
    void        *pv,                    // [IN] Given interface.
    REFIID      riid,                   // [IN] desired interface.
    void        **ppv)                  // [OUT] returned interface
{
    CONTRACTL{
        NOTHROW;
        GC_NOTRIGGER;
        PRECONDITION(CheckPointer(pv));
        PRECONDITION(CheckPointer(ppv));
        ENTRY_POINT;
    } CONTRACTL_END;
    
    HRESULT hr = S_OK;
    BEGIN_ENTRYPOINT_NOTHROW;

    hr = GetMDPublicInterfaceFromInternal(pv, riid, ppv);

    END_ENTRYPOINT_NOTHROW;
    return hr;
}


// ---------------------------------------------------------------------------
// %%Function: ReopenMetaDataWithMemory
// This function gets the public scopeless interface given the internal
// scopeless interface.
// ---------------------------------------------------------------------------
STDAPI ReOpenMetaDataWithMemory(
    void        *pUnk,                  // [IN] Given scope. public interfaces
    LPCVOID     pData,                  // [in] Location of scope data.
    ULONG       cbData)                 // [in] Size of the data pointed to by pData.
{
    CONTRACTL{
        NOTHROW;
        GC_NOTRIGGER;
        ENTRY_POINT;
        PRECONDITION(CheckPointer(pUnk));
        PRECONDITION(CheckPointer(pData));
    } CONTRACTL_END;

    HRESULT hr = S_OK;    

    BEGIN_ENTRYPOINT_NOTHROW;
    hr = MDReOpenMetaDataWithMemory(pUnk, pData, cbData);
    END_ENTRYPOINT_NOTHROW;
    return hr;
}

// ---------------------------------------------------------------------------
// %%Function: ReopenMetaDataWithMemoryEx
// This function gets the public scopeless interface given the internal
// scopeless interface.
// ---------------------------------------------------------------------------
STDAPI ReOpenMetaDataWithMemoryEx(
    void        *pUnk,                  // [IN] Given scope. public interfaces
    LPCVOID     pData,                  // [in] Location of scope data.
    ULONG       cbData,                 // [in] Size of the data pointed to by pData.
    DWORD       dwReOpenFlags)          // [in] ReOpen flags              
{
    CONTRACTL{
        NOTHROW;
        GC_NOTRIGGER;
        ENTRY_POINT;
        PRECONDITION(CheckPointer(pUnk));
        PRECONDITION(CheckPointer(pData));
    } CONTRACTL_END;

    HRESULT hr = S_OK;    

    BEGIN_ENTRYPOINT_NOTHROW;
    hr = MDReOpenMetaDataWithMemoryEx(pUnk, pData, cbData, dwReOpenFlags);
    END_ENTRYPOINT_NOTHROW;
    return hr;
}


#ifndef CROSSGEN_COMPILE
// ---------------------------------------------------------------------------
// %%Function: CoInitializeCor
// 
// Parameters:
//  fFlags                  - Initialization flags for the engine.  See the
//                              COINITICOR enumerator for valid values.
// 
// Returns:
//  S_OK                    - On success
// 
// Description:
//  Reserved to initialize the Cor runtime engine explicitly.  This currently
//  does nothing.
// ---------------------------------------------------------------------------
STDAPI CoInitializeCor(DWORD fFlags)
{
    WRAPPER_NO_CONTRACT;

    BEGIN_ENTRYPOINT_NOTHROW;

    // Since the CLR doesn't currently support being unloaded, we don't hold a ref
    // count and don't even pretend to try to unload.
    END_ENTRYPOINT_NOTHROW;

    return (S_OK);
}

// ---------------------------------------------------------------------------
// %%Function: CoUninitializeCor
// 
// Parameters:
//  none
// 
// Returns:
//  Nothing
// 
// Description:
//  Function to indicate the client is done with the CLR. This currently does
//  nothing.
// ---------------------------------------------------------------------------
STDAPI_(void)   CoUninitializeCor(void)
{
    WRAPPER_NO_CONTRACT;

    BEGIN_ENTRYPOINT_VOIDRET;

    // Since the CLR doesn't currently support being unloaded, we don't hold a ref
    // count and don't even pretend to try to unload.
    END_ENTRYPOINT_VOIDRET;

}

// Undef LoadStringRC & LoadStringRCEx so we can export these functions.
#undef LoadStringRC
#undef LoadStringRCEx

// ---------------------------------------------------------------------------
// %%Function: LoadStringRC
// 
// Parameters:
//  none
// 
// Returns:
//  Nothing
// 
// Description:
//  Function to load a resource based on it's ID.
// ---------------------------------------------------------------------------
STDAPI LoadStringRC(
    UINT iResourceID, 
    __out_ecount(iMax) __out_z LPWSTR szBuffer, 
    int iMax, 
    int bQuiet
)
{
    WRAPPER_NO_CONTRACT;

    HRESULT hr = S_OK;

    if (NULL == szBuffer)
        return E_INVALIDARG;
    if (0 == iMax)
        return E_INVALIDARG;
    
    BEGIN_ENTRYPOINT_NOTHROW;
    hr = UtilLoadStringRC(iResourceID, szBuffer, iMax, bQuiet);
    END_ENTRYPOINT_NOTHROW;
    return hr;
}

// ---------------------------------------------------------------------------
// %%Function: LoadStringRCEx
// 
// Parameters:
//  none
// 
// Returns:
//  Nothing
// 
// Description:
//  Ex version of the function to load a resource based on it's ID.
// ---------------------------------------------------------------------------
#ifdef FEATURE_USE_LCID
STDAPI LoadStringRCEx(
    LCID lcid,
    UINT iResourceID, 
    __out_ecount(iMax) __out_z LPWSTR szBuffer, 
    int iMax, 
    int bQuiet,
    int *pcwchUsed
)
{
    WRAPPER_NO_CONTRACT;
    HRESULT hr = S_OK;

    if (NULL == szBuffer)
        return E_INVALIDARG;
    if (0 == iMax)
        return E_INVALIDARG;
    
    BEGIN_ENTRYPOINT_NOTHROW;   
    hr = UtilLoadStringRCEx(lcid, iResourceID, szBuffer, iMax, bQuiet, pcwchUsed);
    END_ENTRYPOINT_NOTHROW;
    return hr;
}
#endif
// Redefine them as errors to prevent people from using these from inside the rest of the compilation unit.
#define LoadStringRC __error("From inside the CLR, use UtilLoadStringRC; LoadStringRC is only meant to be exported.")
#define LoadStringRCEx __error("From inside the CLR, use UtilLoadStringRCEx; LoadStringRC is only meant to be exported.")

#endif // CROSSGEN_COMPILE




// Note that there are currently two callers of this function: code:CCompRC.LoadLibrary
// and code:CorLaunchApplication.
STDAPI GetRequestedRuntimeInfoInternal(LPCWSTR pExe, 
                               LPCWSTR pwszVersion,
                               LPCWSTR pConfigurationFile, 
                               DWORD startupFlags,
                               DWORD runtimeInfoFlags, 
                                __out_ecount_opt(dwDirectory) LPWSTR pDirectory,
                               DWORD dwDirectory, 
                               __out_opt DWORD *pdwDirectoryLength, 
                               __out_ecount_opt(cchBuffer) LPWSTR pVersion, 
                               DWORD cchBuffer, 
                               __out_opt DWORD* pdwLength)
{
    CONTRACTL
    {
        NOTHROW;
        GC_NOTRIGGER;
        ENTRY_POINT;
        PRECONDITION( pVersion != NULL && cchBuffer > 0);
    } CONTRACTL_END;

    // for simplicity we will cheat and return the entire system directory in pDirectory
    pVersion[0] = 0;
    if (pdwLength != NULL)
        *pdwLength = 0;
    HRESULT hr;

    BEGIN_SO_INTOLERANT_CODE_NO_THROW_CHECK_THREAD(SetLastError(COR_E_STACKOVERFLOW); return COR_E_STACKOVERFLOW;)
    EX_TRY
    {

        PathString pDirectoryPath;

        hr = GetCORSystemDirectoryInternaL(pDirectoryPath);
        *pdwLength = pDirectoryPath.GetCount() + 1;
        if (dwDirectory >= *pdwLength)
        {
            wcscpy_s(pDirectory, pDirectoryPath.GetCount() + 1, pDirectoryPath);
        }
        else
        {
            hr = E_FAIL;
        }
        
    }
    EX_CATCH_HRESULT(hr);
    END_SO_INTOLERANT_CODE

    return hr;
}

// Replacement for legacy shim API GetCORRequiredVersion(...) used in linked libraries.
// Used in code:TiggerStorage::GetDefaultVersion#CallTo_CLRRuntimeHostInternal_GetImageVersionString.
HRESULT 
CLRRuntimeHostInternal_GetImageVersionString(
    __out_ecount_opt(*pcchBuffer) LPWSTR wszBuffer, 
    __inout                       DWORD *pcchBuffer)
{
    // Simply forward the call to the ICLRRuntimeHostInternal implementation.
    STATIC_CONTRACT_WRAPPER;

    HRESULT hr = GetCORVersionInternal(wszBuffer, *pcchBuffer, pcchBuffer);
    
    return hr;
} // CLRRuntimeHostInternal_GetImageVersionString

STDAPI GetCORSystemDirectoryInternaL(SString& pBuffer)
{
    CONTRACTL {
        NOTHROW;
        GC_NOTRIGGER;
        ENTRY_POINT;        
    } CONTRACTL_END;

    HRESULT hr = S_OK;
    BEGIN_ENTRYPOINT_NOTHROW;
    
        
#ifdef CROSSGEN_COMPILE

    if (WszGetModuleFileName(NULL, pBuffer) > 0)
    {     
        hr = CopySystemDirectory(pBuffer, pBuffer);    
    }
    else {
        hr = HRESULT_FROM_GetLastError();
    }
        
#else
       
    if (!PAL_GetPALDirectoryWrapper(pBuffer)) {
        hr = HRESULT_FROM_GetLastError();
    }
#endif

    END_ENTRYPOINT_NOTHROW;
    return hr;
}

//
// Returns version of the runtime (null-terminated).
// 
// Arguments:
//    pBuffer - [out] Output buffer allocated by caller of size cchBuffer.
//    cchBuffer - Size of pBuffer in characters.
//    pdwLength - [out] Size of the version string in characters (incl. null-terminator). Will be filled 
//                even if ERROR_INSUFFICIENT_BUFFER is returned.
// 
// Return Value:
//    S_OK - Output buffer contains the version string.
//    HRESULT_FROM_WIN32(ERROR_INSUFFICIENT_BUFFER) - *pdwLength contains required size of the buffer in 
//                                                    characters.

STDAPI GetCORVersionInternal(
__out_ecount_z_opt(cchBuffer) LPWSTR pBuffer, 
                              DWORD cchBuffer,
                        __out DWORD *pdwLength)
{
    CONTRACTL {
        NOTHROW;
        GC_NOTRIGGER;
        ENTRY_POINT;
        PRECONDITION(CheckPointer(pBuffer, NULL_OK));
        PRECONDITION(CheckPointer(pdwLength));
    } CONTRACTL_END;
        
    HRESULT hr;
    BEGIN_ENTRYPOINT_NOTHROW;
    
    if ((pBuffer != NULL) && (cchBuffer > 0))
    {   // Initialize the output for case the function fails
        *pBuffer = W('\0');
    }

#define VERSION_NUMBER_NOSHIM W("v") QUOTE_MACRO_L(VER_MAJORVERSION.VER_MINORVERSION.VER_PRODUCTBUILD)

    DWORD length = (DWORD)(wcslen(VERSION_NUMBER_NOSHIM) + 1);
    if (length > cchBuffer)
    {
        hr = HRESULT_FROM_WIN32(ERROR_INSUFFICIENT_BUFFER);
    }
    else
    {
        if (pBuffer == NULL)
        {
            hr = E_POINTER;
        }
        else
        {
            CopyMemory(pBuffer, VERSION_NUMBER_NOSHIM, length * sizeof(WCHAR));
            hr = S_OK;
        }
    }
    *pdwLength = length;

    END_ENTRYPOINT_NOTHROW;
    return hr;

}

static DWORD g_dwSystemDirectory = 0;
static WCHAR * g_pSystemDirectory = NULL;

HRESULT GetInternalSystemDirectory(__out_ecount_part_opt(*pdwLength,*pdwLength) LPWSTR buffer, __inout DWORD* pdwLength)
{
    CONTRACTL {
        NOTHROW;
        GC_NOTRIGGER;
        PRECONDITION(CheckPointer(buffer, NULL_OK));
        PRECONDITION(CheckPointer(pdwLength));
    } CONTRACTL_END;
    
    if (g_dwSystemDirectory == 0)
        SetInternalSystemDirectory();

    //
    // g_dwSystemDirectory includes the NULL in its count!
    //
    if(*pdwLength < g_dwSystemDirectory) 
    {
        *pdwLength = g_dwSystemDirectory;
        return HRESULT_FROM_WIN32(ERROR_INSUFFICIENT_BUFFER);
    }

    if (buffer != NULL)
    {
        //
        // wcsncpy_s will automatically append a null and g_dwSystemDirectory 
        // includes the null in its count, so we have to subtract 1.
        //
        wcsncpy_s(buffer, *pdwLength, g_pSystemDirectory, g_dwSystemDirectory-1);
    }
    *pdwLength = g_dwSystemDirectory;
    return S_OK;
}


LPCWSTR GetInternalSystemDirectory(__out DWORD* pdwLength)
{
    LIMITED_METHOD_CONTRACT;

    if (g_dwSystemDirectory == 0)
    {
        SetInternalSystemDirectory();
    }
    
    if (pdwLength != NULL)
    {
        * pdwLength = g_dwSystemDirectory;
    }

    return g_pSystemDirectory;
}


HRESULT SetInternalSystemDirectory()
 {
    CONTRACTL {
        NOTHROW;
        GC_NOTRIGGER;
    } CONTRACTL_END;

    HRESULT hr = S_OK;
    if(g_dwSystemDirectory == 0) {

        DWORD len = 0;
        NewArrayHolder<WCHAR> pSystemDirectory;
        EX_TRY{

            // use local buffer for thread safety
            PathString wzSystemDirectory;
            
            hr = GetCORSystemDirectoryInternaL(wzSystemDirectory);

            if (FAILED(hr)) {
                wzSystemDirectory.Set(W('\0'));
            }

            pSystemDirectory = wzSystemDirectory.GetCopyOfUnicodeString();
            if (pSystemDirectory == NULL)
            {
               hr =  HRESULT_FROM_WIN32(ERROR_NOT_ENOUGH_MEMORY);
            }
            len = wzSystemDirectory.GetCount() + 1;

        }
        EX_CATCH_HRESULT(hr);

        // publish results idempotently with correct memory ordering
        g_pSystemDirectory = pSystemDirectory.Extract();
        
        (void)InterlockedExchange((LONG *)&g_dwSystemDirectory, len);
    }

    return hr;
}

#if defined(CROSSGEN_COMPILE)
void SetMscorlibPath(LPCWSTR wzSystemDirectory)
{
    DWORD len = (DWORD)wcslen(wzSystemDirectory);
    bool appendSeparator = wzSystemDirectory[len-1] != DIRECTORY_SEPARATOR_CHAR_W;
    DWORD lenAlloc = appendSeparator ? len+2 : len+1;
    if (g_dwSystemDirectory < lenAlloc)
    {
        delete [] g_pSystemDirectory;
        g_pSystemDirectory = new (nothrow) WCHAR[lenAlloc];
        
        if (g_pSystemDirectory == NULL)
        {
            SetLastError(ERROR_NOT_ENOUGH_MEMORY);
            return;
        }
    }
    
    wcscpy_s(g_pSystemDirectory, len+1, wzSystemDirectory);
    
    if(appendSeparator)
    {
        g_pSystemDirectory[len] = DIRECTORY_SEPARATOR_CHAR_W;
        g_pSystemDirectory[len+1] = W('\0');
        g_dwSystemDirectory = len + 1;
    }
    else
    {
        g_dwSystemDirectory = len;
    }
}
#endif