summaryrefslogtreecommitdiff
path: root/src/vm/newcompressedstack.cpp
blob: 245a006f1e4072d45cd44e7f52911806510d001b (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
//
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
//
// 


// 

#include "common.h"
#ifdef FEATURE_COMPRESSEDSTACK

#include "newcompressedstack.h"
#include "security.h"
#ifdef FEATURE_REMOTING
#include "appdomainhelper.h"
#endif
#include "securitystackwalk.h"
#include "appdomainstack.inl"
#include "appdomain.inl"


DomainCompressedStack::DomainCompressedStack(ADID domainID)
:   m_DomainID(domainID),
    m_ignoreAD(FALSE),
    m_dwOverridesCount(0),
    m_dwAssertCount(0),
    m_Homogeneous(FALSE)
{
    WRAPPER_NO_CONTRACT;    
}

BOOL DomainCompressedStack::IsAssemblyPresent(ISharedSecurityDescriptor* ssd)
{
    CONTRACTL 
    {
        MODE_ANY;
        GC_NOTRIGGER;
        NOTHROW;
    }CONTRACTL_END;


    // Only checks the first level and does not recurse into compressed stacks
    void* pEntry = NULL;

    if (m_EntryList.GetCount() == 0)
        return FALSE;
    
    // Quick check the last entry we added - common case
    pEntry = m_EntryList.Get(m_EntryList.GetCount() - 1);
    if (pEntry == (void *)SET_LOW_BIT(ssd))
        return TRUE;

    // Go thru the whole list now - is this optimal?
    ArrayList::Iterator iter = m_EntryList.Iterate();

    while (iter.Next())
    {
        pEntry = iter.GetElement();
        if (pEntry == (void *)SET_LOW_BIT(ssd))
            return TRUE;
    }
    return FALSE;
}    

void DomainCompressedStack::AddEntry(void * ptr)
{
    CONTRACTL
    {
        THROWS;
        GC_NOTRIGGER;
        MODE_ANY;
    }
    CONTRACTL_END;

    IfFailThrow(m_EntryList.Append(ptr));
    
}
VOID FrameSecurityDescriptorCopyFrom(FRAMESECDESCREF newFsdRef, FRAMESECDESCREF fsd)
{
    CONTRACTL
    {
        NOTHROW;
        GC_NOTRIGGER;
        SO_TOLERANT;
        MODE_COOPERATIVE;
    }
    CONTRACTL_END;
    newFsdRef->SetImperativeAssertions(fsd->GetImperativeAssertions());
    newFsdRef->SetImperativeDenials(fsd->GetImperativeDenials());
    newFsdRef->SetImperativeRestrictions(fsd->GetImperativeRestrictions());
    newFsdRef->SetDeclarativeAssertions(fsd->GetDeclarativeAssertions());
    newFsdRef->SetDeclarativeDenials(fsd->GetDeclarativeDenials());
    newFsdRef->SetDeclarativeRestrictions(fsd->GetDeclarativeRestrictions());
    newFsdRef->SetAssertAllPossible(fsd->HasAssertAllPossible());
    newFsdRef->SetAssertFT(fsd->HasAssertFT()); 
}

void DomainCompressedStack::AddFrameEntry(AppDomain *pAppDomain, FRAMESECDESCREF fsdRef, BOOL bIsAHDMFrame, OBJECTREF dynamicResolverRef)
{
    CONTRACTL
    {
        THROWS;
        GC_TRIGGERS;
        MODE_COOPERATIVE;
    }
    CONTRACTL_END;

    ENTER_DOMAIN_PTR(pAppDomain,ADV_RUNNINGIN) //have it on the stack
    {
        struct gc
        {
            OBJECTREF fsdRef;
            OBJECTREF newFsdRef;
            OBJECTREF dynamicResolverRef;
        } gc;
        ZeroMemory( &gc, sizeof( gc ) );
        gc.fsdRef = (OBJECTREF)fsdRef;
        gc.dynamicResolverRef = dynamicResolverRef;
        
        GCPROTECT_BEGIN(gc);

        static MethodTable* pMethFrameSecDesc = NULL;
        if (pMethFrameSecDesc == NULL)
            pMethFrameSecDesc = MscorlibBinder::GetClass(CLASS__FRAME_SECURITY_DESCRIPTOR);

        static MethodTable* pMethFrameSecDescWCS = NULL;
        if (pMethFrameSecDescWCS == NULL)
            pMethFrameSecDescWCS = MscorlibBinder::GetClass(CLASS__FRAME_SECURITY_DESCRIPTOR_WITH_RESOLVER);

        if(!bIsAHDMFrame)
        {
            gc.newFsdRef = AllocateObject(pMethFrameSecDesc);
        }
        else
        {
            gc.newFsdRef = AllocateObject(pMethFrameSecDescWCS);
        }

        // We will not call the ctor and instead patch up the object based on the fsdRef passed in
        FRAMESECDESCREF newFsdRef = (FRAMESECDESCREF)gc.newFsdRef;
        FRAMESECDESCREF fsdRef1 = (FRAMESECDESCREF)gc.fsdRef;
        if(fsdRef1 != NULL)
        {
            FrameSecurityDescriptorCopyFrom(newFsdRef, fsdRef1);
        }
        if(bIsAHDMFrame)
        {
            _ASSERTE(gc.dynamicResolverRef != NULL);
            ((FRAMESECDESWITHRESOLVERCREF)newFsdRef)->SetDynamicMethodResolver(gc.dynamicResolverRef);
        }
        OBJECTHANDLEHolder  tmpHnd(pAppDomain->CreateHandle(gc.newFsdRef)); 
    
        AddEntry((void*)tmpHnd);
        tmpHnd.SuppressRelease();
        GCPROTECT_END();
    
    }
    END_DOMAIN_TRANSITION;

}


void DomainCompressedStack::Destroy(void)
{
    CONTRACTL
    {
        NOTHROW;
        GC_NOTRIGGER;
        MODE_ANY;
    }
    CONTRACTL_END;

    // Clear Domain info (handles etc.) if the AD has not been unloaded.
    ClearDomainInfo();
    return;
}

FCIMPL1(DWORD, DomainCompressedStack::GetDescCount, DomainCompressedStack* dcs)
{
    FCALL_CONTRACT;

    FCUnique(0x42);

    return dcs->m_EntryList.GetCount();
}
FCIMPLEND

FCIMPL3(void, DomainCompressedStack::GetDomainPermissionSets, DomainCompressedStack* dcs, OBJECTREF* ppGranted, OBJECTREF* ppDenied)
{
    FCALL_CONTRACT;

    HELPER_METHOD_FRAME_BEGIN_0();

    *ppGranted = NULL;
    *ppDenied  = NULL;

    AppDomain* appDomain = SystemDomain::GetAppDomainFromId(dcs->GetMyDomain(),ADV_RUNNINGIN);
    if (appDomain == NULL)
    {
        // this might be the unloading AD
        AppDomain *pUnloadingDomain = SystemDomain::System()->AppDomainBeingUnloaded();
        if (pUnloadingDomain && pUnloadingDomain->GetId() == dcs->m_DomainID)
        {
#ifdef _DEBUG
            CheckADValidity(pUnloadingDomain, ADV_RUNNINGIN);
#endif
            appDomain = pUnloadingDomain;
        }
    }
    _ASSERTE(appDomain != NULL);
    if (appDomain != NULL)
    {
        IApplicationSecurityDescriptor * pAppSecDesc = appDomain->GetSecurityDescriptor();
        _ASSERTE(pAppSecDesc != NULL);
        if (pAppSecDesc != NULL)
        {
            *ppGranted = pAppSecDesc->GetGrantedPermissionSet(ppDenied);
        }
    }

    HELPER_METHOD_FRAME_END();
}
FCIMPLEND
    
FCIMPL6(FC_BOOL_RET, DomainCompressedStack::GetDescriptorInfo, DomainCompressedStack* dcs, DWORD index, OBJECTREF* ppGranted, OBJECTREF* ppDenied, OBJECTREF* ppAssembly, OBJECTREF* ppFSD)
{
    FCALL_CONTRACT;

    _ASSERTE(dcs != NULL);
    AppDomain* pCurrentDomain = GetAppDomain();
    BOOL bRetVal = FALSE;

    HELPER_METHOD_FRAME_BEGIN_RET_0()
    *ppGranted = NULL;
    *ppDenied  = NULL;
    *ppAssembly = NULL;
    *ppFSD = NULL;
    void* pEntry = dcs->m_EntryList.Get(index);
    _ASSERTE(pEntry != NULL);
    if (IS_LOW_BIT_SET(pEntry))
    {
        // Assembly found
        SharedSecurityDescriptor* pSharedSecDesc = (SharedSecurityDescriptor* )UNSET_LOW_BIT(pEntry);
        Assembly* pAssembly = pSharedSecDesc->GetAssembly();
        IAssemblySecurityDescriptor* pAsmSecDesc = pAssembly->GetSecurityDescriptor( pCurrentDomain );
        *ppGranted = pAsmSecDesc->GetGrantedPermissionSet(ppDenied);
        *ppAssembly = pAssembly->GetExposedObject();
    }
    else
    {
        //FSD
        OBJECTHANDLE objHnd = (OBJECTHANDLE)pEntry;
        if (objHnd == NULL)
        {
            // throw an ADUnloaded exception which we will catch and then look at the serializedBlob
           COMPlusThrow(kAppDomainUnloadedException);
        }
        *ppFSD = ObjectFromHandle(objHnd);
        bRetVal = TRUE;
    }
    HELPER_METHOD_FRAME_END();
    
    FC_RETURN_BOOL(bRetVal);
}
FCIMPLEND

FCIMPL1(FC_BOOL_RET, DomainCompressedStack::IgnoreDomain, DomainCompressedStack* dcs)
{
    FCALL_CONTRACT;
    
    _ASSERTE(dcs != NULL);
    
    FC_RETURN_BOOL(dcs->IgnoreDomainInternal());
}
FCIMPLEND

BOOL DomainCompressedStack::IgnoreDomainInternal()
{
    CONTRACTL
    {
        NOTHROW;
        GC_NOTRIGGER;
        MODE_COOPERATIVE;
        SO_TOLERANT;
    }
    CONTRACTL_END;

    if (m_ignoreAD)
        return TRUE;

    AppDomainFromIDHolder appDomain(GetMyDomain(), TRUE);
    if (!appDomain.IsUnloaded())
    {
        IApplicationSecurityDescriptor *pAppSecDesc = appDomain->GetSecurityDescriptor();
        _ASSERTE(pAppSecDesc != NULL);
        if (pAppSecDesc != NULL)
        {
            return pAppSecDesc->IsDefaultAppDomain() || pAppSecDesc->IsInitializationInProgress();
        }
    }
    
    return FALSE;
}


/*
    Note that this function is called only once: when the managed PLS is being created.
    It's possible that 2 threads could race at that point: only downside of that is that they will both do the work. No races.
    Also, we'll never be operating on a DCS whose domain is not on the current callstack. This eliminates all kinds of ADU/demand eval races.
*/
OBJECTREF DomainCompressedStack::GetDomainCompressedStackInternal(AppDomain *pDomain)
{
     CONTRACTL
    {
        THROWS;
        GC_TRIGGERS;
        MODE_COOPERATIVE;
    }
    CONTRACTL_END;

    // If  we are going to skip this AppDomain, and there is nothing to compress, then we can skip building the DCS.
    if (m_EntryList.GetCount() == 0 && IgnoreDomainInternal())
        return NULL;

    AppDomain* pCurrentDomain = GetAppDomain();

    NewArrayHolder<BYTE> pbtmpSerializedObject(NULL);
#ifndef FEATURE_CORECLR
    DWORD cbtmpSerializedObject = 0;
#endif

        struct gc
        {
            OBJECTREF refRetVal;
        } gc;
        ZeroMemory( &gc, sizeof( gc ) );
        
    GCPROTECT_BEGIN( gc );

    // Create object
    ENTER_DOMAIN_ID (GetMyDomain()) //on the stack
    {

        // Go ahead and create the object
#ifdef FEATURE_CORECLR // ignore other appdomains
        if (GetAppDomain() == pCurrentDomain)
#endif        
        {
        MethodDescCallSite createManagedObject(METHOD__DOMAIN_COMPRESSED_STACK__CREATE_MANAGED_OBJECT);
        ARG_SLOT args[] = {PtrToArgSlot(this)};
        gc.refRetVal = createManagedObject.Call_RetOBJECTREF(args);
        }

#ifndef FEATURE_CORECLR 
                // Do we want to marshal this object also?
        if (GetAppDomain() != pCurrentDomain)
        {
                    // Serialize to a blob;
                    AppDomainHelper::MarshalObject(GetAppDomain(), &gc.refRetVal, &pbtmpSerializedObject, &cbtmpSerializedObject);
            if (pbtmpSerializedObject == NULL)
            {
                // this is an error: possibly an OOM prevented the blob from getting created.
                // We could return null and let the managed code use a fully restricted object or throw here.
                // Let's throw here...
                COMPlusThrow(kSecurityException);
            }
        }
#endif
                    
    }
    END_DOMAIN_TRANSITION

#ifndef FEATURE_CORECLR // should never happen for core clr
    if (GetMyDomain() != pCurrentDomain->GetId())
    {
        AppDomainHelper::UnmarshalObject(pCurrentDomain,pbtmpSerializedObject, cbtmpSerializedObject, &gc.refRetVal);
    }
#endif

    GCPROTECT_END();
   
    return gc.refRetVal;
}


void DomainCompressedStack::ClearDomainInfo(void)
{
    CONTRACTL
    {
        NOTHROW;
        GC_NOTRIGGER;
        MODE_ANY;
    }
    CONTRACTL_END;


    // So, assume mutual exclusion holds and no races occur here


    // Now it is time to go NULL out any ObjectHandle we're using in the list of entries
    ArrayList::Iterator iter = m_EntryList.Iterate();

    while (iter.Next())
    {
        void* pEntry = iter.GetElement();
        if (!IS_LOW_BIT_SET(pEntry))
        {
            DestroyHandle((OBJECTHANDLE)pEntry);
        }
        pEntry = NULL;         
    }


    // Always clear the index into the domain object list and the domainID.
    m_DomainID = ADID(INVALID_APPDOMAIN_ID);    
    return;
}

NewCompressedStack::NewCompressedStack()
:     m_DCSListCount(0),
      m_currentDCS(NULL),
      m_pCtxTxFrame(NULL),
      m_CSAD(ADID(INVALID_APPDOMAIN_ID)),      
      m_ADStack(GetThread()->GetAppDomainStack()),
      m_dwOverridesCount(0),
      m_dwAssertCount(0)
{
    CONTRACTL
    {
        THROWS;
        GC_NOTRIGGER;
        MODE_ANY;
    }
    CONTRACTL_END;

    _ASSERTE(m_ADStack.GetNumDomains() > 0);
    m_ADStack.InitDomainIteration(&adStackIndex);
    m_DCSList = new DomainCompressedStack*[m_ADStack.GetNumDomains()];
    memset(m_DCSList, 0, (m_ADStack.GetNumDomains()*sizeof(DomainCompressedStack*)));
    
}


void NewCompressedStack::Destroy( CLR_BOOL bEntriesOnly )
{
    CONTRACTL
    {
        NOTHROW;
        GC_NOTRIGGER;
        MODE_ANY;
    }
    CONTRACTL_END;
    
    if (m_DCSList != NULL)
    {
        m_currentDCS = NULL;
        m_pCtxTxFrame = NULL;
        for (DWORD i=0; i< m_ADStack.GetNumDomains(); i++)
        {
            DomainCompressedStack* dcs = m_DCSList[i];
            if (dcs != NULL)
            {
                dcs->Destroy();
                delete dcs;
            }
        }
        delete[] m_DCSList;
        m_DCSList = NULL;
    }
    if (!bEntriesOnly)
        delete this;

}


void NewCompressedStack::ProcessAppDomainTransition(void)
{
    CONTRACTL {
        THROWS;
        GC_TRIGGERS;
        MODE_COOPERATIVE;
    } CONTRACTL_END;

    // Get the current adstack entry. Note that the first time we enter this function, adStackIndex will 
    // equal the size of the adstack array (similar to what happens in IEnumerator).
    // So the initial pEntry will be NULL
    AppDomainStackEntry *pEntry = 
        (adStackIndex == m_ADStack.GetNumDomains() ? NULL : m_ADStack.GetCurrentDomainEntryOnStack(adStackIndex));

    // Updated the value on the ADStack for current domain
    if (pEntry != NULL)
    {
        DWORD domainOverrides_measured = (m_currentDCS == NULL?0:m_currentDCS->GetOverridesCount());
        DWORD domainAsserts_measured = (m_currentDCS == NULL?0:m_currentDCS->GetAssertCount());
        if (pEntry->m_dwOverridesCount != domainOverrides_measured || pEntry->m_dwAsserts != domainAsserts_measured)
        {
            m_ADStack.UpdateDomainOnStack(adStackIndex, domainAsserts_measured, domainOverrides_measured);
            GetThread()->UpdateDomainOnStack(adStackIndex, domainAsserts_measured, domainOverrides_measured);
        }
    }

    // Move the domain index forward if this is not the last entry
    if (adStackIndex > 0)
    m_ADStack.GetNextDomainEntryOnStack(&adStackIndex);
    m_currentDCS = NULL;

    return;
    
}
DWORD NewCompressedStack::ProcessFrame(AppDomain* pAppDomain, Assembly* pAssembly, MethodDesc* pFunc, ISharedSecurityDescriptor* pSsd, FRAMESECDESCREF* pFsdRef)
{
    // This function will be called each time we hit a new stack frame in a stack walk.

    CONTRACTL {
        THROWS;
        GC_TRIGGERS;
        MODE_COOPERATIVE;
        PRECONDITION(CheckPointer(pAppDomain));
        PRECONDITION(CheckPointer(pSsd));
    } CONTRACTL_END;

    // Get the current adstack entry. Note that the first time we enter this function, adStackIndex will 
    // equal the size of the adstack array (similar to what happens in IEnumerator).
    // So the initial pEntry will be NULL
    AppDomainStackEntry *pEntry = 
        (adStackIndex == m_ADStack.GetNumDomains() ? NULL : m_ADStack.GetCurrentDomainEntryOnStack(adStackIndex));


    _ASSERTE(pEntry != NULL);
    PREFIX_ASSUME(pEntry != NULL);
    FRAMESECDESCREF FsdRef = (pFsdRef!=NULL?*pFsdRef:NULL);
    DWORD dwFlags = 0;
    if (FsdRef != NULL)
    {
            
        if (FsdRef->HasAssertFT())
            dwFlags |= CORSEC_FT_ASSERT;
    }

    BOOL bIsAHDMFrame = FALSE;
    
    if((pFunc != NULL) && !CLRConfig::GetConfigValue(CLRConfig::UNSUPPORTED_Security_DisableAnonymouslyHostedDynamicMethodCreatorSecurityCheck))
    {
        ENTER_DOMAIN_PTR(pAppDomain, ADV_RUNNINGIN)
        {
            bIsAHDMFrame = SecurityStackWalk::MethodIsAnonymouslyHostedDynamicMethodWithCSToEvaluate(pFunc);
        }
        END_DOMAIN_TRANSITION;
    }

    if (!bIsAHDMFrame && ((pEntry->IsFullyTrustedWithNoStackModifiers()) ||
        (m_currentDCS != NULL && m_currentDCS->m_Homogeneous)))
    {
        // Nothing to do in this entire AD. 
        return dwFlags;
    }
    
    ADID dNewDomainID = pAppDomain->GetId();
    BOOL bAddSSD = (!pSsd->IsSystem() && !IsAssemblyPresent(dNewDomainID, pSsd));
    BOOL bHasStackModifiers = FALSE;
    DWORD overridesCount = 0;
    DWORD assertCount = 0;

    
    if (FsdRef != NULL)
    {
        overridesCount += FsdRef->GetOverridesCount();
        assertCount += FsdRef->GetAssertCount();
    }

    // If this is an AHDM frame with a CS to evaluate, it may have overrides or asserts,
    // so treat it as if it does
    if(bIsAHDMFrame)
    {
        overridesCount++;
        assertCount++;
    }

    bHasStackModifiers = ( (assertCount + overridesCount) > 0);

    //
    // We need to add a new DCS if we don't already have one for this AppDomain.  If we've reached this
    // point, either:
    //   * the AppDomain is partially trusted
    //   * the AppDomain is fully trusted, but may have stack modifiers in play
    //   * we're running in legacy mode where FullTrust doesn't mean FullTrust
    //   
    // If the domain is partially trusted, we'll always need to capture it. If we got this far due to a
    // fully trusted domain that might have stack modifiers, we only have to capture if there really were
    // stack walk modifiers.  In the legacy mode case, we need to capture the domain if we had stack
    // modifiers or we needed to add the shared security descriptor.
    //

    BOOL bCreateDCS = (m_currentDCS == NULL || m_currentDCS->m_DomainID != dNewDomainID);
    if (pAppDomain->GetSecurityDescriptor()->IsFullyTrusted())
    {
        bCreateDCS &= (bAddSSD || bHasStackModifiers);
    }

    if (bCreateDCS)
    {
        CreateDCS(dNewDomainID);
    }

     // Add the ISharedSecurityDescriptor (Assembly) to the list if it is not already present in the list
    if (bAddSSD)
    {
        m_currentDCS->AddEntry((void*)SET_LOW_BIT(pSsd));
        if (pEntry->IsHomogeneousWithNoStackModifiers())
            m_currentDCS->m_Homogeneous = TRUE;
    }    
    if (bHasStackModifiers)
    {
        OBJECTREF dynamicResolverRef = NULL;
        if(bIsAHDMFrame)
        {            
            _ASSERTE(pFunc->IsLCGMethod());
            dynamicResolverRef = pFunc->AsDynamicMethodDesc()->GetLCGMethodResolver()->GetManagedResolver();
        }

        // We need to add the FSD entry here 
        m_currentDCS->AddFrameEntry(pAppDomain, FsdRef, bIsAHDMFrame, dynamicResolverRef);
        m_currentDCS->m_dwOverridesCount += overridesCount;
        m_currentDCS->m_dwAssertCount += assertCount;
        m_dwOverridesCount += overridesCount;
        m_dwAssertCount += assertCount;
    }
    return dwFlags;
}

// Build a CompressedStack given that all domains on the stack are homogeneous with no stack modifiers
FCIMPL1(void, NewCompressedStack::FCallGetHomogeneousPLS, Object* hgPLSUnsafe)
{
    FCALL_CONTRACT;
    
    OBJECTREF refHomogeneousPLS = (OBJECTREF)hgPLSUnsafe;

    HELPER_METHOD_FRAME_BEGIN_1(refHomogeneousPLS); 


    // Walk the adstack and update the grantSetUnion
    AppDomainStack* pADStack = GetThread()->GetAppDomainStackPointer();
    DWORD dwAppDomainIndex;
    pADStack->InitDomainIteration(&dwAppDomainIndex);

#ifdef FEATURE_REMOTING // without remoting we need only current appdomain
    while (dwAppDomainIndex != 0)
#endif        
    {
        AppDomainStackEntry* pEntry = pADStack->GetNextDomainEntryOnStack(&dwAppDomainIndex);
        _ASSERTE(pEntry != NULL);
        
        pEntry->UpdateHomogeneousPLS(&refHomogeneousPLS);
    }
    
        
    HELPER_METHOD_FRAME_END();
    return ;
}
FCIMPLEND;

// Special case of ProcessFrame called with the CS at the base of the thread
void NewCompressedStack::ProcessCS(AppDomain* pAppDomain, COMPRESSEDSTACKREF csRef, Frame *pFrame)
{
    CONTRACTL {
        THROWS;
        GC_TRIGGERS;
        MODE_COOPERATIVE;
        PRECONDITION(CheckPointer(pAppDomain));
    } CONTRACTL_END;

    _ASSERTE(csRef != NULL && "Shouldn't call this function if CS is NULL");
    ADID dNewDomainID = pAppDomain->GetId();
    NewCompressedStack* pCS = (NewCompressedStack* )csRef->GetUnmanagedCompressedStack();
    if (csRef->IsEmptyPLS() && (pCS == NULL || pCS->GetDCSListCount() == 0))
    {
        // Do nothing - empty inner CS
        return;
    }

    // Let's special case the 1-domain CS that has no inner CSs here
    // Check for:
    // 1. == 1 DCS 
    // 2. DCS is in correct AD (it's possible that pCS is AD-X and it has only one DCS in AD-Y, because AD-X has only mscorlib frames
    // 3. No inner CS
    if ( pCS != NULL &&
         pCS->GetDCSListCount() == 1 &&
         pCS->m_DCSList != NULL &&
         pCS->m_currentDCS != NULL &&
         pCS->m_currentDCS->m_DomainID == dNewDomainID &&
         pCS->m_CSAD == ADID(INVALID_APPDOMAIN_ID))
    {
        ProcessSingleDomainNCS(pCS, pAppDomain);
    }
    else
    {

        // set flag to ignore Domain grant set if the current DCS is the same as the one with the CS
        if (m_currentDCS != NULL && m_currentDCS->m_DomainID == dNewDomainID)
        {
            m_currentDCS->m_ignoreAD = TRUE;
        }

        // Update overrides/asserts
        if (pCS != NULL)
        {
            m_dwOverridesCount += pCS->GetOverridesCount();
            m_dwAssertCount += pCS->GetAssertCount();
        }
        

        // Do we need to store the CtxTransitionFrame or did we get the CS from the thread?
        if (pFrame != NULL)
        {
            _ASSERTE(csRef == SecurityStackWalk::GetCSFromContextTransitionFrame(pFrame));
            // Use data from the CtxTxFrame
            m_pCtxTxFrame = pFrame;
        }
        m_CSAD = dNewDomainID;
    }

}
void NewCompressedStack::ProcessSingleDomainNCS(NewCompressedStack *pCS, AppDomain* pAppDomain)
{
    
    CONTRACTL {
        THROWS;
        GC_TRIGGERS;
        MODE_COOPERATIVE;
        PRECONDITION(CheckPointer(pAppDomain));
    } CONTRACTL_END;

    _ASSERTE(pCS->GetDCSListCount() <= 1 && pCS->m_CSAD == ADID(INVALID_APPDOMAIN_ID));
    ADID newDomainID = pAppDomain->GetId();
    DomainCompressedStack* otherDCS = pCS->m_currentDCS;

    if (otherDCS == NULL)
        return;
    if (m_currentDCS == NULL)
        CreateDCS(newDomainID);


    // Iterate thru the entryList in the current DCS
    ArrayList::Iterator iter = otherDCS->m_EntryList.Iterate();
    while (iter.Next())
    {
        void* pEntry = iter.GetElement();
        if (IS_LOW_BIT_SET(pEntry))
        {
            if (!IsAssemblyPresent(newDomainID, (ISharedSecurityDescriptor*)UNSET_LOW_BIT(pEntry)))
            {
                //Add the assembly
                m_currentDCS->AddEntry(pEntry);
            }
        }
        else
        {
            // FrameSecurityDescriptor 
            OBJECTHANDLE objHnd = (OBJECTHANDLE)pEntry;
            OBJECTREF fsdRef = ObjectFromHandle(objHnd);
            OBJECTHANDLEHolder  tmpHnd(pAppDomain->CreateHandle(fsdRef)); 

            m_currentDCS->AddEntry((void*)tmpHnd);
            tmpHnd.SuppressRelease();
            
        }
            
    }    

    m_currentDCS->m_dwOverridesCount += pCS->m_dwOverridesCount;
    m_currentDCS->m_dwAssertCount += pCS->m_dwAssertCount;
    m_dwOverridesCount += pCS->m_dwOverridesCount;
    m_dwAssertCount += pCS->m_dwAssertCount;    
}
void NewCompressedStack::CreateDCS(ADID domainID)
{
    CONTRACTL {
        THROWS;
        GC_NOTRIGGER;
        MODE_ANY;
    } CONTRACTL_END;

    _ASSERTE(adStackIndex < m_ADStack.GetNumDomains());
    _ASSERTE (m_DCSList != NULL);
    m_DCSList[adStackIndex] = new DomainCompressedStack(domainID);
    m_currentDCS = m_DCSList[adStackIndex];
    m_DCSListCount++;

    return;
}


BOOL NewCompressedStack::IsAssemblyPresent(ADID domainID, ISharedSecurityDescriptor* pSsd)
{
    CONTRACTL
    {
        NOTHROW;
        GC_NOTRIGGER;
        MODE_ANY;
    }
    CONTRACTL_END;

    _ASSERTE(domainID != ADID(INVALID_APPDOMAIN_ID) && "Don't pass invalid domain");

    BOOL bEntryPresent = FALSE;
    
    for(DWORD i=0; i < m_ADStack.GetNumDomains(); i++)
    {

        DomainCompressedStack* pTmpDCS = m_DCSList[i];
        
        if (pTmpDCS != NULL && pTmpDCS->m_DomainID == domainID && pTmpDCS->IsAssemblyPresent(pSsd))
        {
            bEntryPresent = TRUE;
            break;
        }
    }
    return bEntryPresent;
}


BOOL NewCompressedStack::IsDCSContained(DomainCompressedStack *pDCS)
{
    CONTRACTL
    {
        NOTHROW;
        GC_NOTRIGGER;
        MODE_ANY;
    }
    CONTRACTL_END;

    // return FALSE if no DCS or DCS is for a domain that has been unloaded
    if (pDCS == NULL || pDCS->m_DomainID == ADID(INVALID_APPDOMAIN_ID))
        return FALSE;
    

    
    // Iterate thru the entryList in the current DCS
    ArrayList::Iterator iter = pDCS->m_EntryList.Iterate();
    while (iter.Next())
    {
        void* pEntry = iter.GetElement();
        if (IS_LOW_BIT_SET(pEntry))
        {
            // We only check Assemblies.
            if (!IsAssemblyPresent(pDCS->m_DomainID, (ISharedSecurityDescriptor*)UNSET_LOW_BIT(pEntry)))
            return FALSE;
        }    
    }    
    return TRUE;
}

BOOL NewCompressedStack::IsNCSContained(NewCompressedStack *pCS)
{
    CONTRACTL
    {
        NOTHROW;
        GC_NOTRIGGER;
        MODE_ANY;
    }
    CONTRACTL_END;

    // Check if the first level of pCS is contained in this.
    if (pCS == NULL)
        return TRUE;

    // Return FALSE if there are any overrides or asserts
    if (pCS->GetOverridesCount() > 0)
        return FALSE;
    // Return FALSE if there is an inner CS
    if (pCS->m_CSAD != ADID(INVALID_APPDOMAIN_ID))
        return FALSE;
     
     for(DWORD i=0; i < m_ADStack.GetNumDomains(); i++)
     {
         DomainCompressedStack *pDCS = (DomainCompressedStack *) m_DCSList[i];
         if (!IsDCSContained(pDCS))
            return FALSE;
     }
     return TRUE;
     
}


// If there is a compressed stack present in the captured CompressedStack, return that CS in the current domain
OBJECTREF NewCompressedStack::GetCompressedStackInner()
{
    _ASSERTE(m_CSAD != ADID(INVALID_APPDOMAIN_ID));

    AppDomain* pCurrentDomain = GetAppDomain();
    NewArrayHolder<BYTE> pbtmpSerializedObject(NULL);


    OBJECTREF refRetVal = NULL;

    if (pCurrentDomain->GetId()== m_CSAD)
    {
        // we're in the right domain already 
        if (m_pCtxTxFrame == NULL)
        {
            // Get CS from the thread
            refRetVal = GetThread()->GetCompressedStack();
        }
        else
        {
            // Get CS from a Ctx transition frame
            refRetVal = (OBJECTREF)SecurityStackWalk::GetCSFromContextTransitionFrame(m_pCtxTxFrame);
            _ASSERTE(refRetVal != NULL); //otherwise we would not have saved the frame in the CB data
        }
    }
    else
#ifndef FEATURE_CORECLR // should never happen for core clr        
    {
        DWORD cbtmpSerializedObject = 0;
        GCPROTECT_BEGIN (refRetVal);          
        // need to marshal the CS over into the current AD
        ENTER_DOMAIN_ID(m_CSAD);
        {
            if (m_pCtxTxFrame == NULL)
            {

                // Get CS from the thread
                refRetVal = GetThread()->GetCompressedStack();
            }
            else
            {
                // Get CS from a Ctx transition frame
                refRetVal = (OBJECTREF)SecurityStackWalk::GetCSFromContextTransitionFrame(m_pCtxTxFrame);
                _ASSERTE(refRetVal != NULL); //otherwise we would not have saved the frame in the CB data
            }
            AppDomainHelper::MarshalObject(GetAppDomain(), &refRetVal, &pbtmpSerializedObject, &cbtmpSerializedObject);
        }
        END_DOMAIN_TRANSITION
        refRetVal = NULL;
        AppDomainHelper::UnmarshalObject(pCurrentDomain,pbtmpSerializedObject, cbtmpSerializedObject, &refRetVal);
        GCPROTECT_END ();
        _ASSERTE(refRetVal != NULL); //otherwise we would not have saved the frame in the CB data
    }
#else 
    {
        UNREACHABLE();
    }
#endif // !FEATURE_CORECLR

    return refRetVal;

}

// == Now begin the functions used in building Demand evaluation of a compressed stack
FCIMPL1(DWORD, NewCompressedStack::FCallGetDCSCount, SafeHandle* hcsUNSAFE)
{
    FCALL_CONTRACT;

    DWORD dwRet = 0;
    if (hcsUNSAFE != NULL)
    {
        SAFEHANDLE hcsSAFE = (SAFEHANDLE) hcsUNSAFE;

        HELPER_METHOD_FRAME_BEGIN_RET_1(hcsSAFE);     

        NewCompressedStack* ncs = (NewCompressedStack *)hcsSAFE->GetHandle();
        
        dwRet = ncs->m_ADStack.GetNumDomains();
        HELPER_METHOD_FRAME_END();
    }

    return dwRet;
    
}
FCIMPLEND


FCIMPL2(FC_BOOL_RET, NewCompressedStack::FCallIsImmediateCompletionCandidate, SafeHandle* hcsUNSAFE, OBJECTREF *innerCS)
{
    FCALL_CONTRACT;

    BOOL bRet = FALSE;
    if (hcsUNSAFE != NULL)
    {
        SAFEHANDLE hcsSAFE = (SAFEHANDLE) hcsUNSAFE;

        HELPER_METHOD_FRAME_BEGIN_RET_1(hcsSAFE); 

        *innerCS = NULL;

        NewCompressedStack* ncs = (NewCompressedStack *)hcsSAFE->GetHandle();

        if (ncs != NULL)
        {
            // Non-FT case

            // Is there an inner CS?
            BOOL bHasCS = (ncs->m_CSAD != ADID(INVALID_APPDOMAIN_ID));

            // Is there is a DCS not in the current AD
            BOOL bHasOtherAppDomain = FALSE;
            if (ncs->m_DCSList != NULL)
            {
                for(DWORD i=0; i < ncs->m_ADStack.GetNumDomains(); i++)
                {
                    DomainCompressedStack* dcs = ncs->m_DCSList[i];
                    if (dcs != NULL && dcs->GetMyDomain() != GetAppDomain()->GetId())
                    {
                        bHasOtherAppDomain = TRUE;
                        break;
                    }
                }
            }
            if (bHasCS)
            {


                *innerCS = ncs->GetCompressedStackInner();
                ncs->m_pCtxTxFrame = NULL; // Clear the CtxTxFrame ASAP
         
            }
            bRet = bHasOtherAppDomain||bHasCS;
        }
        
        HELPER_METHOD_FRAME_END();
    }
    
    FC_RETURN_BOOL(bRet);
}
FCIMPLEND


FCIMPL2(Object*, NewCompressedStack::GetDomainCompressedStack, SafeHandle* hcsUNSAFE, DWORD index)
{
    FCALL_CONTRACT;

    OBJECTREF refRetVal = NULL;
    if (hcsUNSAFE != NULL)
    {
        SAFEHANDLE hcsSAFE = (SAFEHANDLE) hcsUNSAFE;

        HELPER_METHOD_FRAME_BEGIN_RET_2(refRetVal, hcsSAFE); 



        NewCompressedStack* ncs = (NewCompressedStack *)hcsSAFE->GetHandle();

        // First we check to see if the DCS at index i has a blob. If so, deserialize it into the current AD and return it. Else try create it
        DomainCompressedStack* dcs = ncs->m_DCSList[index];
        if (dcs != NULL)
        {
            refRetVal = dcs->GetDomainCompressedStackInternal(NULL);
        }
        
        HELPER_METHOD_FRAME_END();
    }

    return OBJECTREFToObject(refRetVal);
   
}
FCIMPLEND

FCIMPL1(void, NewCompressedStack::DestroyDCSList, SafeHandle* hcsUNSAFE)
{
    FCALL_CONTRACT;

    SAFEHANDLE hcsSAFE = (SAFEHANDLE) hcsUNSAFE;

    HELPER_METHOD_FRAME_BEGIN_1(hcsSAFE); 

    NewCompressedStack* ncs = (NewCompressedStack *)hcsSAFE->GetHandle();

    ncs->Destroy(TRUE);

    HELPER_METHOD_FRAME_END();

}
FCIMPLEND
#endif // #ifdef FEATURE_COMPRESSEDSTACK