summaryrefslogtreecommitdiff
path: root/src/inc/legacyactivationshimutil.h
blob: a15839bdba72156e88d6c9d2e9144a7fb63257af (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
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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
//
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
//
//
// LegacyActivationShim.h
//
// This file allows simple migration from .NET Runtime v2 Host Activation APIs
// to the .NET Runtime v4 Host Activation APIs through simple shim functions.

#ifndef __LEGACYACTIVATIONSHIMUTIL_H__
#define __LEGACYACTIVATIONSHIMUTIL_H__

// To minimize how much we perturb sources that we are included in, we make sure that
// all macros we define/redefine are restored at the end of the header.
#pragma push_macro("SELECTANY")
#pragma push_macro("_TEXT_ENCODE")
#pragma push_macro("countof")
#pragma push_macro("UNUSED")

#ifndef _MSC_VER
#error "LegacyActivationShim.h cannot be used on non-MS compilers"
#endif

// ---SELECTANY------------------------------------------------------------------------------------
#undef SELECTANY
#define SELECTANY extern __declspec(selectany)

// Allow users of these headers to provide custom 'LoadLibrary' implementation (e.g. WszLoadLibrary).
// Example of usage is in ndp\clr\src\fusion\tools\viewer.
#ifndef LEGACY_ACTIVATION_SHIM_LOAD_LIBRARY
#define LEGACY_ACTIVATION_SHIM_LOAD_LIBRARY ::LoadLibrary
#endif

// _T macro alternative to make strings ASCII/UNICODE
#undef _TEXT_ENCODE
#ifdef UNICODE
#define _TEXT_ENCODE(str) L ## str
#else //!UNICODE
#define _TEXT_ENCODE(str) str
#endif //!UNICODE

// countof ... number of items in an array
#ifndef countof
#define countof(x) (sizeof(x) / sizeof(x[0]))
#endif countof

#ifndef UNUSED
#define UNUSED(var) ((void)(var))
#endif //UNUSED

#ifndef __LEGACYACTIVATIONSHIM_H__
    #error Error: Include LegacyActivationShim.h or LegacyActivationShimDelayLoad.h instead of directly including LegacyActivationShimUtil.h
#endif // __LEGACYACTIVATIONSHIM_H__

// ---PLACEMENT NEW--------------------------------------------------------------------------------
#ifndef __PLACEMENT_NEW_INLINE
#define __PLACEMENT_NEW_INLINE
// Inline placement new
inline void* operator new(size_t, void *_Where)
{	// construct array with placement at _Where
    return (_Where);
}

// delete if placement new fails
inline void operator delete(void *, void *)
{
}
#endif __PLACEMENT_NEW_INLINE

// ---LEGACYACTIVATON NAMESPACE--------------------------------------------------------------------
namespace LegacyActivationShim
{
    // ---UTIL NAMESPACE---------------------------------------------------------------------------
    namespace Util
    {
        // ---INTERLOCKEDCOMPAREEXCHANGEPOINTERT---------------------------------------------------
        // Variation on InterlockedCompareExchangePointer that adds some type safety.
        // Added 'T' to end of name because an identical name to the original function
        // confuses GCC
        template <typename T>
        inline
        T InterlockedCompareExchangePointerT(
            T volatile* destination,
            T exchange,
            T comparand)
        {
#ifdef __UtilCode_h__
            // Utilcode has redefined InterlockedCompareExchangePointer
            return ::InterlockedCompareExchangeT(destination, exchange, comparand);
#else // __UtilCode_h__
            return reinterpret_cast<T>(InterlockedCompareExchangePointer(
                (PVOID volatile *)(destination),
                (PVOID)(exchange),
                (PVOID)(comparand)));
#endif // __UtilCode_h__ else
        }

        // ---PlacementNewDeleteHelper-------------------------------------------------------------
        template <typename TYPE, bool IS_CLASS>
        class PlacementNewDeleteHelper;

        template <typename TYPE>
        class PlacementNewDeleteHelper<TYPE, true>
        {
        public:
            // Some environments #define New and Delete, so name these functions
            // Construct and Destruct to keep them unique.
            static void Construct(TYPE const & value, void *pvWhere)
                { new (pvWhere) TYPE(value); }

            static void Destruct(TYPE & value)
                { value.~TYPE(); }
        };

        template <typename TYPE>
        class PlacementNewDeleteHelper<TYPE, false>
        {
        public:
            static void Construct(TYPE const & value, void *pvWhere)
                { *reinterpret_cast<TYPE *>(pvWhere) = value; }

            static void Destruct(TYPE &)
                { }
        };

        // ---HOLDERBASE---------------------------------------------------------------------------
        template <typename TYPE>
        class HolderBase
        {
        public:
            // Relies on implicit default constructor, which permits zero-init static
            // object declaration. Do not define one.
            // HolderBase() {}

        protected:
            char    m_value[sizeof(TYPE)];

            inline
            TYPE & GetRef()
                { return *reinterpret_cast<TYPE *>(&m_value[0]); }

            inline
            TYPE & GetPtr()
                { return reinterpret_cast<TYPE *>(&m_value[0]); }

            inline
            void Construct(TYPE const & value)
                { PlacementNewDeleteHelper<TYPE, __is_class(TYPE)>::Construct(value, (void *)&m_value[0]); }

            inline
            void Destruct()
                { PlacementNewDeleteHelper<TYPE, __is_class(TYPE)>::Destruct(GetRef()); }
        };

        // ---HOLDER-------------------------------------------------------------------------------
        template <typename TYPE, void (*ASSIGNF)(TYPE &), void (*RELEASEF)(TYPE &)>
        class Holder : public HolderBase<TYPE>
        {
        protected:
            bool    m_assigned;
            bool    m_suppressed;

        public:
            inline
            Holder() : m_assigned(false), m_suppressed(false)
                {}

            inline
            Holder(TYPE const & value) : m_assigned(false), m_suppressed(false)
                { Assign(value); }

            inline
            ~Holder()
                { Release(); }

            inline
            void Assign(TYPE const & value)
            {
                Release();
                Construct(value);
                m_assigned = true;
                (*ASSIGNF)(GetValue());
            }

            inline
            void Release()
            {
                if (m_assigned)
                {
                    if (!m_suppressed)
                    {
                        (*RELEASEF)(GetValue());
                    }
                    m_assigned = false;
                    m_suppressed = false;
                    Destruct();
                }
            }

            inline
            void SuppressRelease()
            {
                m_suppressed = m_assigned;
            }

            inline
            TYPE & GetValue()
            {
                // _ASSERTE(m_assigned);
                return GetRef();
            }

            inline
            bool IsAssigned()
                { return m_assigned; }
        };

        // ---ZEROINITGLOBALHOLDER-----------------------------------------------------------------
        // This class should ONLY be used for global (file scope) variables. It relies on zero
        // initialized data in the image. This will fail miserably for other scenarios, as the
        // memory used for the object may not be zero-initialized, which will result in incorrect
        // behaviour.
        template <typename TYPE, void (*ASSIGNF)(TYPE &), void (*RELEASEF)(TYPE &)>
        class ZeroInitGlobalHolder : public HolderBase<TYPE>
        {
        protected:
            bool    m_assigned;

        public:
            // Relies on implicit default constructor, which permits zero-init static
            // field declaration. Do not define an explicit constructor.
            // ZeroInitGlobalHolder() {}

            inline
            ~ZeroInitGlobalHolder()
                { Release(); }

            inline
            void Assign(TYPE const & value)
            {
                Release();
                Construct(value);
                m_assigned = true;
                (*ASSIGNF)(GetValue());
            }

            inline
            void Release()
            {
                if (m_assigned)
                {
                    (*RELEASEF)(GetValue());
                    m_assigned = false;
                    Destruct();
                }
            }

            inline
            TYPE & GetValue()
            {
                // _ASSERTE(m_assigned);
                return GetRef();
            }

            inline
            bool IsAssigned()
            { return m_assigned; }

            inline
            void ClearUnsafe()
            { m_assigned = false; }
        };

        // ---DONOTHINGHELPER----------------------------------------------------------------------
        template <typename TYPE>
        inline
        void DoNothingHelper(TYPE & value)
            { UNUSED(value); }

        // ---RELEASEHELPER------------------------------------------------------------------------
        template <typename TYPE>
        inline
        void ReleaseHelper(TYPE & value)
            { value->Release(); }

        // ---RELEASEHOLDER------------------------------------------------------------------------
        template <typename TYPE>
        class ReleaseHolder
            : public Holder< TYPE, &DoNothingHelper<TYPE>, &ReleaseHelper<TYPE> >
        {
          public:
            inline
            ReleaseHolder(TYPE & value)
                : Holder< TYPE, &DoNothingHelper<TYPE>, &ReleaseHelper<TYPE> >(value)
                {}

            ReleaseHolder()
                : Holder< TYPE, &DoNothingHelper<TYPE>, &ReleaseHelper<TYPE> >()
            {}
        };

        // ---ZEROINITGLOBALRELEASEHOLDER----------------------------------------------------------
        template <typename TYPE>
        class ZeroInitGlobalReleaseHolder
            : public ZeroInitGlobalHolder< TYPE, &DoNothingHelper<TYPE>, &ReleaseHelper<TYPE> >
        {
        };

        // ---FREELIBRARYHELPER--------------------------------------------------------------------
        inline
        void FreeLibraryHelper(HMODULE & hMod)
        {
            FreeLibrary(hMod);
        }

        // ---HMODULEHOLDER------------------------------------------------------------------------
        class HMODULEHolder
            : public Holder< HMODULE, &DoNothingHelper<HMODULE>, &FreeLibraryHelper >
        {
          public:
            inline
            HMODULEHolder(HMODULE value)
                : Holder< HMODULE, &DoNothingHelper<HMODULE>, &FreeLibraryHelper >(value)
                {}

            HMODULEHolder()
                : Holder< HMODULE, &DoNothingHelper<HMODULE>, &FreeLibraryHelper >()
                {}
        };

        // ---ZEROINITHMODULEHOLDER----------------------------------------------------------------
        class ZeroInitGlobalHMODULEHolder
            : public ZeroInitGlobalHolder< HMODULE, &DoNothingHelper<HMODULE>, &FreeLibraryHelper >
        {
        };

        // ---DELAYLOADFUNCTOR---------------------------------------------------------------------
        // T must be a function typedef.
        // For example, "typedef int X(short i); DelayLoadFunctor<X> pfnX;"
        template <typename T>
        class DelayLoadFunctor
        {
        private:
            HMODULEHolder m_hModHolder;
            T * m_proc;

        public:
            HRESULT Init(LPCTSTR wzDllName, LPCSTR szProcName)
            {
                // Load module
                HMODULE hMod = LEGACY_ACTIVATION_SHIM_LOAD_LIBRARY(wzDllName);
                if (hMod == NULL)
                    return HRESULT_FROM_WIN32(::GetLastError());
                HMODULEHolder hModHolder(hMod);

                // Load proc address
                T * proc = reinterpret_cast<T *>(::GetProcAddress(hMod, szProcName));
                if (proc == NULL)
                    return HRESULT_FROM_WIN32(::GetLastError());

                // Store results
                hModHolder.SuppressRelease();
                m_hModHolder.Assign(hMod);
                m_proc = proc;

                return S_OK;
            }

            HRESULT Init(HMODULE hMod, LPCSTR szProcName)
            {
                // Load proc address
                T * proc = reinterpret_cast<T *>(::GetProcAddress(hMod, szProcName));
                if (proc == NULL)
                    return HRESULT_FROM_WIN32(::GetLastError());

                // Store result
                m_proc = proc;

                // Success
                return S_OK;
            }

            T& operator()()
            {
                return *m_proc;
            }
        };

        // ---ZEROINITGLOBALSPINLOCK----------------------------------------------------------------
        class ZeroInitGlobalSpinLock
        {
        private:
            enum LOCK_STATE
            {
                UNLOCKED = 0,
                LOCKED = 1
            };

            LONG volatile m_lock;

            static inline void Lock(ZeroInitGlobalSpinLock*& lock)
            {
                while (InterlockedExchange(&lock->m_lock, LOCKED) == LOCKED)
                {
                    ::SwitchToThread();
                }
            }

            static inline void Unlock(ZeroInitGlobalSpinLock*& lock)
                { InterlockedExchange(&lock->m_lock, UNLOCKED); }

        public:
            typedef LegacyActivationShim::Util::Holder<ZeroInitGlobalSpinLock*,
                     &ZeroInitGlobalSpinLock::Lock,
                     &ZeroInitGlobalSpinLock::Unlock>
                Holder;
        };

        // ---MSCOREEDATA--------------------------------------------------------------------------
        SELECTANY HMODULE                     g_hModMscoree = NULL;
        SELECTANY ZeroInitGlobalHMODULEHolder g_hModMscoreeHolder;

        // ---GETMSCOREE---------------------------------------------------------------------------
        inline
        HRESULT GetMSCOREE(HMODULE *pMscoree)
        {
            if (g_hModMscoree == NULL)
            {
                HMODULE hModMscoree = LEGACY_ACTIVATION_SHIM_LOAD_LIBRARY(_TEXT_ENCODE("mscoree.dll"));
                if (hModMscoree == NULL)
                    return HRESULT_FROM_WIN32(GetLastError());
                HMODULEHolder hModMscoreeHolder(hModMscoree);

                if (LegacyActivationShim::Util::InterlockedCompareExchangePointerT<HMODULE>(
                    &g_hModMscoree, hModMscoree, NULL) == NULL)
                {
                    g_hModMscoreeHolder.ClearUnsafe();
                    g_hModMscoreeHolder.Assign(g_hModMscoree);
                    hModMscoreeHolder.SuppressRelease();
                }
            }

            *pMscoree = g_hModMscoree;
            return S_OK;
        }

        // ---MSCOREEFUNCTOR-----------------------------------------------------------------------
        template <typename T>
        class MscoreeFunctor : public DelayLoadFunctor<T>
        {
        public:
            HRESULT Init(LPCSTR szProcName)
            {
                HRESULT hr = S_OK;
                HMODULE hModMscoree = NULL;
                IfHrFailRet(GetMSCOREE(&hModMscoree));

                return DelayLoadFunctor<T>::Init(hModMscoree, szProcName);
            }
        };

        // ---CALLCLRCREATEINSTANCE------------------------------------------------------------------
        inline 
        HRESULT CallCLRCreateInstance(
            REFCLSID clsid, 
            REFIID   riid, 
            LPVOID  *ppInterface)
        {
            HRESULT hr = S_OK;
            HMODULE hMscoree = NULL;
            IfHrFailRet(GetMSCOREE(&hMscoree));

            typedef HRESULT (__stdcall *CLRCreateInstance_pfn) (
                REFCLSID clsid, 
                REFIID   riid, 
                LPVOID  *ppInterface);

            CLRCreateInstance_pfn pfnCLRCreateInstance =
               reinterpret_cast<CLRCreateInstance_pfn>(GetProcAddress(hMscoree, "CLRCreateInstance"));

            if (pfnCLRCreateInstance == NULL)
                return HRESULT_FROM_WIN32(GetLastError());

            return (*pfnCLRCreateInstance)(
                clsid, 
                riid, 
                ppInterface);
        }

        // ---CLRMETAHOST INTERFACE DATA-----------------------------------------------------------
        SELECTANY ICLRMetaHost* g_pCLRMetaHost = NULL;
        SELECTANY ZeroInitGlobalReleaseHolder<ICLRMetaHost*> g_hCLRMetaHost;

        // ---GETCLRMETAHOST-----------------------------------------------------------------------
        // NOTE: Does not AddRef returned interface pointer.
        inline
        HRESULT GetCLRMetaHost(
            /*out*/ ICLRMetaHost **ppCLRMetaHost)
        {
            HRESULT hr = S_OK;

            if (g_pCLRMetaHost == NULL)
            {
                ICLRMetaHost *pMetaHost = NULL;
                IfHrFailRet(CallCLRCreateInstance(CLSID_CLRMetaHost,
                                     IID_ICLRMetaHost,
                                     reinterpret_cast<LPVOID *>(&pMetaHost)));
                ReleaseHolder<ICLRMetaHost*> hMetaHost(pMetaHost);

                //
                // Great - we got an ICLRMetaHost. Now publish this to
                // g_pCLRMetaHost in a thread-safe way.
                //

                if (LegacyActivationShim::Util::InterlockedCompareExchangePointerT<ICLRMetaHost *>(
                        &g_pCLRMetaHost, pMetaHost, NULL) == NULL)
                {
                    // Successful publish. In this case, we also assign to the
                    // holder to ensure that the interface is released when the
                    // image is unloaded.
                    g_hCLRMetaHost.ClearUnsafe();
                    g_hCLRMetaHost.Assign(g_pCLRMetaHost);
                    hMetaHost.SuppressRelease(); // Keep it AddRef'ed for the g_hCLRMetaHost
                }
            }

            *ppCLRMetaHost = g_pCLRMetaHost;

            return hr;
        }

        // ---HasNewActivationAPIs-----------------------------------------------------------------
        SELECTANY ULONG g_fHasNewActivationAPIs = ULONG(-1);

        inline
        bool HasNewActivationAPIs()
        {
            if (g_fHasNewActivationAPIs == ULONG(-1))
            {
                ICLRMetaHost *pMetaHost = NULL;
                HRESULT hr = GetCLRMetaHost(&pMetaHost);
                InterlockedCompareExchange((LONG volatile *)&g_fHasNewActivationAPIs, (LONG)(SUCCEEDED(hr)), ULONG(-1));
            }

            return g_fHasNewActivationAPIs != 0;
        }

        // ---CLRMETAHOSTPOLICY INTERFACE DATA-----------------------------------------------------
        SELECTANY ICLRMetaHostPolicy* g_pCLRMetaHostPolicy = NULL;
        SELECTANY ZeroInitGlobalReleaseHolder<ICLRMetaHostPolicy*> g_hCLRMetaHostPolicy;

        // ---GETCLRMETAHOSTPOLICY-----------------------------------------------------------------
        // NOTE: Does not AddRef returned interface pointer.
        inline
        HRESULT GetCLRMetaHostPolicy(
            /*out*/ ICLRMetaHostPolicy **ppICLRMetaHostPolicy)
        {
            HRESULT hr = S_OK;

            if (g_pCLRMetaHostPolicy == NULL)
            {
                ICLRMetaHostPolicy *pMetaHostPolicy = NULL;
                IfHrFailRet(CallCLRCreateInstance(CLSID_CLRMetaHostPolicy,
                                     IID_ICLRMetaHostPolicy,
                                     reinterpret_cast<LPVOID *>(&pMetaHostPolicy)));
                ReleaseHolder<ICLRMetaHostPolicy*> hMetaHostPolicy(pMetaHostPolicy);

                //
                // Great - we got an ICLRMetaHostPolicy. Now publish this to
                // g_pCLRMetaHostPolicy in a thread-safe way.
                //

                if (LegacyActivationShim::Util::InterlockedCompareExchangePointerT<ICLRMetaHostPolicy*>(
                        &g_pCLRMetaHostPolicy, pMetaHostPolicy, NULL) == NULL)
                {
                    // Successful publish. In this case, we also assign to the
                    // holder to ensure that the interface is released when the
                    // image is unloaded.
                    g_hCLRMetaHostPolicy.ClearUnsafe();
                    g_hCLRMetaHostPolicy.Assign(g_pCLRMetaHostPolicy);
                    hMetaHostPolicy.SuppressRelease();
                }
            }

            *ppICLRMetaHostPolicy = g_pCLRMetaHostPolicy;

            return hr;
        }

        // ---RUNTIMEINFO DATA---------------------------------------------------------------------
        struct RuntimeInfo
        {
            ICLRRuntimeInfo *m_pRuntimeInfo;

            DWORD   m_cchImageVersion;
            WCHAR   m_wszImageVersion[512];

            inline
            void Init()
            {
                m_pRuntimeInfo = NULL;
                m_cchImageVersion = countof(m_wszImageVersion);
                m_wszImageVersion[0] = L'\0';
            }

            inline
            void Release()
            {
                if (m_pRuntimeInfo != NULL)
                {
                    m_pRuntimeInfo->Release();
                    m_pRuntimeInfo = NULL;
                }
            }
        };

        SELECTANY LONG                   g_runtimeInfoIsInitialized = FALSE;
        SELECTANY RuntimeInfo            g_runtimeInfo;
        SELECTANY ZeroInitGlobalSpinLock g_runtimeInfoLock;
        SELECTANY ZeroInitGlobalReleaseHolder<RuntimeInfo*> g_hRuntimeInfo;

        // ---GETCLRRUNTIMEINFOHELPER--------------------------------------------------------------
        // Logic:
        //     1. Try to bind using ICLRMetaHostPolicy::GetRequestedRuntime and incoming arguments.
        //     2. Try to bind using ICLRMetaHostPolicy::GetRequestedRuntime and "v4.0.0" and
        //        upgrade policy.
        //     3. Try to bind to latest using GetRequestedRuntimeInfo.

        inline
        HRESULT GetCLRRuntimeInfoHelper(
            /*out*/ ICLRRuntimeInfo **ppCLRRuntimeInfo,
            LPCWSTR  pEXE = NULL,
            IStream *pIStream = NULL,
            __inout_ecount_opt(*pcchVersion) LPWSTR wszVersion = NULL,
            DWORD   *pcchVersion = NULL,
            __out_ecount_opt(*pcchImageVersion) LPWSTR wszImageVersion = NULL,
            DWORD   *pcchImageVersion = NULL)
        {
            HRESULT hr = S_OK;

            //
            // 1. Try policy-based binding first, which will incorporate config files and such.
            //

            ICLRMetaHostPolicy *pMetaHostPolicy = NULL;
            IfHrFailRet(GetCLRMetaHostPolicy(&pMetaHostPolicy));

            DWORD dwConfigFlags = 0;

            hr = pMetaHostPolicy->GetRequestedRuntime(
                METAHOST_POLICY_USE_PROCESS_IMAGE_PATH,
                pEXE,
                pIStream,
                wszVersion,
                pcchVersion,
                wszImageVersion,
                pcchImageVersion,
                &dwConfigFlags,
                IID_ICLRRuntimeInfo,
                reinterpret_cast<LPVOID *>(ppCLRRuntimeInfo));

            if (hr != S_OK &&
                pEXE == NULL &&
                pIStream == NULL &&
                wszVersion == NULL)
            {   //
                // 2. Try to bind using ICLRMetaHostPolicy::GetRequestedRuntime and "v4.0.0" and upgrade policy.
                //

                WCHAR _wszVersion[256];  // We can't use new in this header, so just pick an obscenely long version string length of 256
                DWORD _cchVersion = countof(_wszVersion);
                wcscpy_s(_wszVersion, _cchVersion, L"v4.0.0");
                hr = pMetaHostPolicy->GetRequestedRuntime(
                    static_cast<METAHOST_POLICY_FLAGS>(METAHOST_POLICY_USE_PROCESS_IMAGE_PATH |
                                                       METAHOST_POLICY_APPLY_UPGRADE_POLICY),
                    pEXE,
                    pIStream, // (is NULL)
                    _wszVersion,
                    &_cchVersion,
                    wszImageVersion,
                    pcchImageVersion,
                    &dwConfigFlags,
                    IID_ICLRRuntimeInfo,
                    reinterpret_cast<LPVOID *>(ppCLRRuntimeInfo));
            }

            if (hr != S_OK &&
                pEXE == NULL &&
                pIStream == NULL &&
                wszVersion == NULL)
            {   //
                // 3. Try to bind using GetRequestedRuntimeInfo(NULL)
                //

                typedef HRESULT __stdcall GetRequestedRuntimeInfo_t(
                    LPCWSTR pExe,
                    LPCWSTR pwszVersion,
                    LPCWSTR pConfigurationFile,
                    DWORD startupFlags,
                    DWORD runtimeInfoFlags,
                    LPWSTR pDirectory,
                    DWORD dwDirectory,
                    DWORD *dwDirectoryLength,
                    LPWSTR pVersion,
                    DWORD cchBuffer,
                    DWORD* dwlength);

                HMODULE hMscoree = NULL;
                IfHrFailRet(GetMSCOREE(&hMscoree));

                // We're using GetRequestedRuntimeInfo here because it is the only remaining API
                // that will not be Whidbey-capped and will allow "bind to latest" semantics. This
                // is cheating a bit, but should work for now. The alternative is to use
                // ICLRMetaHost::EnumerateRuntimes to achieve the same result.
                DelayLoadFunctor<GetRequestedRuntimeInfo_t> GetRequestedRuntimeInfoFN;
                IfHrFailRet(GetRequestedRuntimeInfoFN.Init(hMscoree, "GetRequestedRuntimeInfo"));

                WCHAR szDir_[_MAX_PATH];
                DWORD cchDir_ = countof(szDir_);
                WCHAR szVersion_[_MAX_PATH];
                DWORD cchVersion_ = countof(szVersion_);
                DWORD dwInfoFlags_ = RUNTIME_INFO_UPGRADE_VERSION 
                                   | RUNTIME_INFO_DONT_SHOW_ERROR_DIALOG;

                IfHrFailRet(GetRequestedRuntimeInfoFN()(
                    NULL,
                    NULL,
                    NULL,
                    0,
                    dwInfoFlags_,
                    szDir_,
                    cchDir_,
                    &cchDir_,
                    szVersion_,
                    cchVersion_,
                    &cchVersion_));

                // Unable to get a version to try to load.
                if (hr != S_OK)
                {
                    return CLR_E_SHIM_RUNTIMELOAD;
                }

                ICLRMetaHost *pMetaHost = NULL;
                IfHrFailRet(GetCLRMetaHost(&pMetaHost));

                hr = pMetaHost->GetRuntime(szVersion_,
                                           IID_ICLRRuntimeInfo,
                                           reinterpret_cast<LPVOID *>(ppCLRRuntimeInfo));

                if (hr != S_OK)
                {
                    return CLR_E_SHIM_RUNTIMELOAD;
                }

                if (wszImageVersion != NULL)
                {
                    wcsncpy_s(wszImageVersion, *pcchImageVersion, szVersion_, cchVersion_);
                    *pcchImageVersion = cchVersion_;
                }
            }

            if (hr == S_OK &&
                (dwConfigFlags & METAHOST_CONFIG_FLAGS_LEGACY_V2_ACTIVATION_POLICY_MASK) ==
                METAHOST_CONFIG_FLAGS_LEGACY_V2_ACTIVATION_POLICY_TRUE)
            {   // If the config requested that the runtime be bound as the legacy runtime.
                IfHrFailRet((*ppCLRRuntimeInfo)->BindAsLegacyV2Runtime());
            }

            return hr;
        }

        // ---GETRUNTIMEINFO-----------------------------------------------------------------------
        inline
        HRESULT GetRuntimeInfo(
            /*out*/ RuntimeInfo **ppRuntimeInfo,
            LPCWSTR  pEXE = NULL,
            IStream *pIStream = NULL,
            __inout_ecount_opt(*pcchVersion) LPWSTR wszVersion = NULL,
            DWORD   *pcchVersion = NULL)
        {
            HRESULT hr = S_OK;

            if (!g_runtimeInfoIsInitialized)
            {
                ZeroInitGlobalSpinLock::Holder lock(&g_runtimeInfoLock);
                if (!g_runtimeInfoIsInitialized)
                {
                    g_runtimeInfo.Init();

                    IfHrFailRet(GetCLRRuntimeInfoHelper(
                        &g_runtimeInfo.m_pRuntimeInfo,
                        pEXE,
                        pIStream,
                        wszVersion,
                        pcchVersion,
                        g_runtimeInfo.m_wszImageVersion,
                        &g_runtimeInfo.m_cchImageVersion));
                        
                    //
                    // Initialized - now publish.
                    //

                    g_hRuntimeInfo.ClearUnsafe();
                    g_hRuntimeInfo.Assign(&g_runtimeInfo);
                    InterlockedExchange(&g_runtimeInfoIsInitialized, TRUE);
                }
            }

            //
            // Return the struct
            //

            *ppRuntimeInfo = &g_runtimeInfo;
            return hr;
        }

        // --------BINDTOV4------------------------------------------------------------------------
        // Used by hosted DLLs that require the use of v4 for all their
        // LegacyActivationShim calls. Can (and should) be called from DllMain,
        // provided the DLL has a static (non-delayload) dependency on mscoree.dll.
        inline
        HRESULT BindToV4()
        {
            HRESULT hr = E_FAIL;

            if (!g_runtimeInfoIsInitialized)
            {
                ZeroInitGlobalSpinLock::Holder lock(&g_runtimeInfoLock);
                if (!g_runtimeInfoIsInitialized)
                {
                    ICLRMetaHostPolicy *pMetaHostPolicy = NULL;
                    IfHrFailRet(GetCLRMetaHostPolicy(&pMetaHostPolicy));

                    g_runtimeInfo.Init();

                    //
                    // Try to bind using ICLRMetaHostPolicy::GetRequestedRuntime and "v4.0.0" and upgrade policy.
                    //

                    WCHAR _wszVersion[256];  // We can't use new in this header, so just pick an obscenely long version string length of 256
                    DWORD _cchVersion = countof(_wszVersion);
                    wcscpy_s(_wszVersion, _cchVersion, L"v4.0.0");

                    IfHrFailRet(pMetaHostPolicy->GetRequestedRuntime(
                        METAHOST_POLICY_APPLY_UPGRADE_POLICY,
                        NULL, // image path
                        NULL, // config stream
                        _wszVersion,
                        &_cchVersion,
                        g_runtimeInfo.m_wszImageVersion,
                        &g_runtimeInfo.m_cchImageVersion,
                        NULL, // config flags
                        IID_ICLRRuntimeInfo,
                        reinterpret_cast<LPVOID *>(&g_runtimeInfo.m_pRuntimeInfo)));

                    //
                    // Initialized - now publish.
                    //

                    g_hRuntimeInfo.ClearUnsafe();
                    g_hRuntimeInfo.Assign(&g_runtimeInfo);
                    InterlockedExchange(&g_runtimeInfoIsInitialized, TRUE);
                    
                    hr = S_OK;
                }
            }

            return hr;
        }

        // ---GETCLRRUNTIMEINFO--------------------------------------------------------------------
        inline
        HRESULT GetCLRRuntimeInfo(
            /*out*/ ICLRRuntimeInfo **ppCLRRuntimeInfo,
            LPCWSTR  pEXE = NULL,
            IStream *pIStream = NULL,
            __inout_ecount_opt(*pcchVersion) LPWSTR wszVersion = NULL,
            DWORD   *pcchVersion = NULL)
        {
            HRESULT hr = S_OK;

            RuntimeInfo *pRuntimeInfo = NULL;
            IfHrFailRet(GetRuntimeInfo(&pRuntimeInfo, pEXE, pIStream, wszVersion, pcchVersion));

            *ppCLRRuntimeInfo = pRuntimeInfo->m_pRuntimeInfo;
            return hr;
        }

        // ---GetConfigImageVersion----------------------------------------------------------------
        inline
        HRESULT GetConfigImageVersion(
            __out_ecount(*pcchBuffer) LPWSTR wzBuffer,
            DWORD *pcchBuffer)
        {
            HRESULT hr = S_OK;

            RuntimeInfo *pRuntimeInfo = NULL;
            IfHrFailRet(GetRuntimeInfo(&pRuntimeInfo));

            DWORD cchBuffer = *pcchBuffer;
            *pcchBuffer = pRuntimeInfo->m_cchImageVersion;

            if (cchBuffer <= pRuntimeInfo->m_cchImageVersion)
            {
                wcsncpy_s(
                    wzBuffer,
                    cchBuffer,
                    pRuntimeInfo->m_wszImageVersion,
                    pRuntimeInfo->m_cchImageVersion);
            }
            else
            {
                IfHrFailRet(HRESULT_FROM_WIN32(ERROR_INSUFFICIENT_BUFFER));
            }

            return hr;
        }

        // ---ICLRSTRONGNAME INTERFACE DATA--------------------------------------------------------
        SELECTANY ICLRStrongName* g_pCLRStrongName = NULL;
        SELECTANY ZeroInitGlobalReleaseHolder<ICLRStrongName*>  g_hCLRStrongName;

        // ---GETCLRSTRONGNAME---------------------------------------------------------------------
        // NOTE: Does not AddRef returned interface pointer.
        inline
        HRESULT GetCLRStrongName(
            /*out*/ ICLRStrongName **ppCLRStrongName)
        {
            HRESULT hr = S_OK;

            if (g_pCLRStrongName == NULL)
            {
                ICLRRuntimeInfo *pInfo = NULL;
                IfHrFailRet(GetCLRRuntimeInfo(&pInfo));

                ICLRStrongName *pStrongName;
                
                IfHrFailRet(pInfo->GetInterface(
                    CLSID_CLRStrongName,
                    IID_ICLRStrongName,
                    reinterpret_cast<LPVOID *>(&pStrongName)));

                //
                // Great - we got an ICLRStrongName. Now publish this to
                // g_pCLRStrongName in a thread-safe way.
                //

                if (LegacyActivationShim::Util::InterlockedCompareExchangePointerT<ICLRStrongName *>(
                        &g_pCLRStrongName, pStrongName, NULL) == NULL)
                {
                    // Successful publish. In this case, we also assign to the
                    // holder to ensure that the interface is released when the
                    // image is unloaded.
                    g_hCLRStrongName.ClearUnsafe();
                    g_hCLRStrongName.Assign(g_pCLRStrongName);
                }
                else
                {
                    // We were beat to the punch, don't publish this interface
                    // and make sure we use the published value for consistency.
                    pStrongName->Release();
                }
            }

            *ppCLRStrongName = g_pCLRStrongName;
            return hr;
        }

        // ---ICLRSTRONGNAME2 INTERFACE DATA--------------------------------------------------------
        SELECTANY ICLRStrongName2* g_pCLRStrongName2 = NULL;
        SELECTANY ZeroInitGlobalReleaseHolder<ICLRStrongName2*>  g_hCLRStrongName2;

        // ---GETCLRSTRONGNAME2---------------------------------------------------------------------
        // NOTE: Does not AddRef returned interface pointer.
        inline
        HRESULT GetCLRStrongName2(
            /*out*/ ICLRStrongName2 **ppCLRStrongName2)
        {
            HRESULT hr = S_OK;

            if (g_pCLRStrongName2 == NULL)
            {
                ICLRRuntimeInfo *pInfo = NULL;
                IfHrFailRet(GetCLRRuntimeInfo(&pInfo));

                ICLRStrongName2 *pStrongName;
                
                IfHrFailRet(pInfo->GetInterface(
                    CLSID_CLRStrongName,
                    IID_ICLRStrongName2,
                    reinterpret_cast<LPVOID *>(&pStrongName)));

                //
                // Great - we got an ICLRStrongName2. Now publish this to
                // g_pCLRStrongName2 in a thread-safe way.
                //

                if (LegacyActivationShim::Util::InterlockedCompareExchangePointerT<ICLRStrongName2 *>(
                        &g_pCLRStrongName2, pStrongName, NULL) == NULL)
                {
                    // Successful publish. In this case, we also assign to the
                    // holder to ensure that the interface is released when the
                    // image is unloaded.
                    g_hCLRStrongName2.ClearUnsafe();
                    g_hCLRStrongName2.Assign(g_pCLRStrongName2);
                }
                else
                {
                    // We were beat to the punch, don't publish this interface
                    // and make sure we use the published value for consistency.
                    pStrongName->Release();
                }
            }

            *ppCLRStrongName2 = g_pCLRStrongName2;
            return hr;
        }

        // ---AddStartupFlags------------------------------------------------------------------------------
        inline
        HRESULT AddStartupFlags(
            ICLRRuntimeInfo *pInfo,
            LPCWSTR wszBuildFlavor,
            DWORD dwStartupFlags,
            LPCWSTR wszHostConfigFile)
        {
            if (wszBuildFlavor != NULL &&
                (wszBuildFlavor[0] == L's' || wszBuildFlavor[0] == L'S') &&
                (wszBuildFlavor[1] == L'v' || wszBuildFlavor[1] == L'V') &&
                (wszBuildFlavor[2] == L'r' || wszBuildFlavor[2] == L'R') &&
                 wszBuildFlavor[3] == 0)
            {
                dwStartupFlags |= STARTUP_SERVER_GC;
            }

            HRESULT hr = S_OK;

            DWORD dwEffectiveStartupFlags = 0;
            IfHrFailRet(pInfo->GetDefaultStartupFlags(&dwEffectiveStartupFlags, NULL, NULL));
            
            // Startup flags at this point are either default (i.e. STARTUP_CONCURRENT_GC)
            // or have been set based on a config file. We want to clear the concurrent
            // GC flag because we are supplying non-defaults, and combine them with the
            // user supplied flags. Note that STARTUP_CONCURRENT_GC is never set as part
            // of reading a config so we are not losing any information here.

            dwEffectiveStartupFlags &= ~STARTUP_CONCURRENT_GC;
            dwEffectiveStartupFlags |= dwStartupFlags;

            return pInfo->SetDefaultStartupFlags(dwEffectiveStartupFlags, wszHostConfigFile);
        }

        // ------------------------------------------------------------------------------------------------
        SELECTANY HMODULE                     g_hShlwapi = NULL;
        SELECTANY ZeroInitGlobalHMODULEHolder g_hShlwapiHolder;

        // ------------------------------------------------------------------------------------------------
        inline
        HRESULT CreateIStreamFromFile(
            LPCWSTR wszFilePath,
            IStream **ppIStream)
        {
            HRESULT hr = S_OK;
            *ppIStream = NULL;

            if (g_hShlwapi == NULL)
            {
                HMODULE hShlwapi = LEGACY_ACTIVATION_SHIM_LOAD_LIBRARY(_TEXT_ENCODE("shlwapi.dll"));
                if (hShlwapi == NULL)
                    return HRESULT_FROM_WIN32(GetLastError());
                HMODULEHolder hShlwapiHolder(hShlwapi);

                if (LegacyActivationShim::Util::InterlockedCompareExchangePointerT<HMODULE>(
                    &g_hShlwapi, hShlwapi, NULL) == NULL)
                {
                    g_hShlwapiHolder.ClearUnsafe();
                    g_hShlwapiHolder.Assign(hShlwapi);
                    hShlwapiHolder.SuppressRelease();
                }
            }

            typedef HRESULT (__stdcall * SHCreateStreamOnFile_pfn)(
                LPCWSTR wszFile,
                DWORD grfMode,
                IStream **ppstm);

            SHCreateStreamOnFile_pfn pCreateStreamOnFile =
                reinterpret_cast<SHCreateStreamOnFile_pfn>(GetProcAddress(g_hShlwapi, "SHCreateStreamOnFileW"));

            if (pCreateStreamOnFile == NULL)
                return HRESULT_FROM_WIN32(GetLastError());

            //_ASSERTE(pCreateStreamOnFile != NULL);

            // Create IStream
            IStream* pStream(NULL);
            IfHrFailRet((*pCreateStreamOnFile)(wszFilePath, 0 /*STGM_READ*/, &pStream));
            ReleaseHolder<IStream*> hStream(pStream);

            // Success, prevent release and assign IStream to out parameter
            *ppIStream = pStream;
            hStream.SuppressRelease();

            return S_OK;
        }
    }; // namespace Util
}; // namespace LegacyActivationShim

#pragma pop_macro("UNUSED")
#pragma pop_macro("countof")
#pragma pop_macro("_TEXT_ENCODE")
#pragma pop_macro("SELECTANY")

#endif // __LEGACYACTIVATIONSHIMUTIL_H__