summaryrefslogtreecommitdiff
path: root/src/vm/securitydeclarative.cpp
blob: 0cff572d424b393414b2cdb4b8a450597aec9b7a (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
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
// 

// 


#include "common.h"

#include "security.h"
#include "securitydeclarative.inl"
#include "eventtrace.h"

#ifdef FEATURE_REMOTING
#include "remoting.h"
#endif // FEATURE_REMOTING


//-----------------------------------------------------------------------------
//
//
//     CODE FOR MAKING THE SECURITY STUB AT JIT-TIME
//
//
//-----------------------------------------------------------------------------


enum DeclSecMergeMethod
{
    DS_METHOD_OVERRIDE,
    DS_CLASS_OVERRIDE,
    DS_UNION,
    DS_INTERSECT,
    DS_APPLY_METHOD_THEN_CLASS, // not supported with stack modifier actions
    DS_APPLY_CLASS_THEN_METHOD, // not supported with stack modifier actions
    DS_NOT_APPLICABLE, // action not supported on both method and class
};

// (Note: The values that are DS_NOT_APPLICABLE are not hooked up to
// this table, so changing one of those values will have no effect)
const DeclSecMergeMethod g_DeclSecClassAndMethodMergeTable[] =
{
    DS_NOT_APPLICABLE, // dclActionNil = 0
    DS_NOT_APPLICABLE, // dclRequest = 1
    DS_UNION, // dclDemand = 2
    DS_METHOD_OVERRIDE, // dclAssert = 3
    DS_UNION, // dclDeny = 4
    DS_INTERSECT, // dclPermitOnly = 5
    DS_NOT_APPLICABLE, // dclLinktimeCheck = 6
    DS_NOT_APPLICABLE, // dclInheritanceCheck = 7
    DS_NOT_APPLICABLE, // dclRequestMinimum = 8
    DS_NOT_APPLICABLE, // dclRequestOptional = 9
    DS_NOT_APPLICABLE, // dclRequestRefuse = 10
    DS_NOT_APPLICABLE, // dclPrejitGrant = 11
    DS_NOT_APPLICABLE, // dclPrejitDenied = 12
    DS_UNION, // dclNonCasDemand = 13
    DS_NOT_APPLICABLE, // dclNonCasLinkDemand = 14
    DS_NOT_APPLICABLE, // dclNonCasInheritance = 15
};

// This table specifies the order in which runtime declarative actions will be performed
// (Note that for stack-modifying actions, this means the order in which they are applied to the
//  frame descriptor, not the order in which they are evaluated when a demand is performed.
//  That order is determined by the code in System.Security.FrameSecurityDescriptor.)
const CorDeclSecurity g_RuntimeDeclSecOrderTable[] =
{
    dclPermitOnly, // 5
    dclDeny, // 4
    dclAssert, // 3
    dclDemand, // 2
    dclNonCasDemand, // 13
};

#define DECLSEC_RUNTIME_ACTION_COUNT (sizeof(g_RuntimeDeclSecOrderTable) / sizeof(CorDeclSecurity))


TokenDeclActionInfo* TokenDeclActionInfo::Init(DWORD dwAction, PsetCacheEntry *pPCE)
{
    CONTRACTL {
        THROWS;
        GC_TRIGGERS;
        MODE_ANY;
        INJECT_FAULT(COMPlusThrowOM(););
    } CONTRACTL_END;

    AppDomain                   *pDomain        = GetAppDomain();

    TokenDeclActionInfo *pTemp = 
        static_cast<TokenDeclActionInfo*>((void*)pDomain->GetLowFrequencyHeap()
                            ->AllocMem(S_SIZE_T(sizeof(TokenDeclActionInfo))));

    pTemp->dwDeclAction = dwAction;
    pTemp->pPCE = pPCE;
    pTemp->pNext = NULL;

    return pTemp;
}

void TokenDeclActionInfo::LinkNewDeclAction(TokenDeclActionInfo** ppActionList, CorDeclSecurity action, PsetCacheEntry *pPCE)
{
    CONTRACTL {
        THROWS;
        GC_TRIGGERS;
        MODE_ANY;
        INJECT_FAULT(COMPlusThrowOM(););
    } CONTRACTL_END;

    TokenDeclActionInfo *temp = Init(DclToFlag(action), pPCE);
    if (!(*ppActionList))
        *ppActionList = temp;
    else
    {
        temp->pNext = *ppActionList;
        *ppActionList = temp;
    }
}

DeclActionInfo *DeclActionInfo::Init(MethodDesc *pMD, DWORD dwAction, PsetCacheEntry *pPCE)
{
    CONTRACTL {
        THROWS;
        GC_TRIGGERS;
        MODE_ANY;
        INJECT_FAULT(COMPlusThrowOM(););
    } CONTRACTL_END;

    DeclActionInfo *pTemp = (DeclActionInfo *)(void*)pMD->GetDomainSpecificLoaderAllocator()->GetLowFrequencyHeap()->AllocMem(S_SIZE_T(sizeof(DeclActionInfo)));

    pTemp->dwDeclAction = dwAction;
    pTemp->pPCE = pPCE;
    pTemp->pNext = NULL;

    return pTemp;
}

void LinkNewDeclAction(DeclActionInfo** ppActionList, CorDeclSecurity action, PsetCacheEntry *pPCE, MethodDesc *pMeth)
{
    CONTRACTL {
        THROWS;
        GC_TRIGGERS;
        MODE_ANY;
        INJECT_FAULT(COMPlusThrowOM(););
    } CONTRACTL_END;

    DeclActionInfo *temp = DeclActionInfo::Init(pMeth, DclToFlag(action), pPCE);
    if (!(*ppActionList))
        *ppActionList = temp;
    else
    {
        // Add overrides to the end of the list, all others to the front
        if (IsDclActionAnyStackModifier(action))
        {
            DeclActionInfo *w = *ppActionList;
            while (w->pNext != NULL)
                w = w->pNext;
            w->pNext = temp;
        }
        else
        {
            temp->pNext = *ppActionList;
            *ppActionList = temp;
        }
    }
}

void SecurityDeclarative::AddDeclAction(CorDeclSecurity action, PsetCacheEntry *pClassPCE, PsetCacheEntry *pMethodPCE, DeclActionInfo** ppActionList, MethodDesc *pMeth)
{
    CONTRACTL {
        THROWS;
        GC_TRIGGERS;
        MODE_ANY;
        INJECT_FAULT(COMPlusThrowOM(););
    } CONTRACTL_END;

    if(pClassPCE == NULL)
    {
        if(pMethodPCE == NULL)
            return;
        LinkNewDeclAction(ppActionList, action, pMethodPCE, pMeth);
        return;
    }
    else if(pMethodPCE == NULL)
    {
        LinkNewDeclAction(ppActionList, action, pClassPCE, pMeth);
        return;
    }

    // Merge class and method declarations
    switch(g_DeclSecClassAndMethodMergeTable[action])
    {
    case DS_METHOD_OVERRIDE:
        LinkNewDeclAction(ppActionList, action, pMethodPCE, pMeth);
        break;

    case DS_CLASS_OVERRIDE:
        LinkNewDeclAction(ppActionList, action, pClassPCE, pMeth);
        break;

    case DS_UNION:
#ifdef FEATURE_CAS_POLICY
        LinkNewDeclAction(ppActionList, action, SecurityAttributes::MergePermissionSets(pClassPCE, pMethodPCE, false, action), pMeth);
#else // FEATURE_CAS_POLICY
        _ASSERTE(!"Declarative permission sets may not be unioned together in CoreCLR. Are you attempting to have a declarative demand or deny on both a method and its enclosing class?");
#endif // FEATURE_CAS_POLICY
        break;

    case DS_INTERSECT:
#ifdef FEATURE_CAS_POLICY
        LinkNewDeclAction(ppActionList, action, SecurityAttributes::MergePermissionSets(pClassPCE, pMethodPCE, true, action), pMeth);
#else // FEATURE_CAS_POLICY
        _ASSERTE(!"Declarative permission sets may not be intersected in CoreCLR. Are you attempting to have a declarative permit only on both a method and its enclosing class?");
#endif // FEATURE_CAS_POLICY
        break;

    case DS_APPLY_METHOD_THEN_CLASS:
        LinkNewDeclAction(ppActionList, action, pClassPCE, pMeth); // note: order reversed because LinkNewDeclAction inserts at beginning of list
        LinkNewDeclAction(ppActionList, action, pMethodPCE, pMeth);
        break;

    case DS_APPLY_CLASS_THEN_METHOD:
        LinkNewDeclAction(ppActionList, action, pMethodPCE, pMeth); // note: order reversed because LinkNewDeclAction inserts at beginning of list
        LinkNewDeclAction(ppActionList, action, pClassPCE, pMeth);
        break;

    case DS_NOT_APPLICABLE:
        _ASSERTE(!"not a runtime action");
        break;

    default:
        _ASSERTE(!"unexpected merge type");
        break;
    }
}


// Here we see what declarative actions are needed everytime a method is called,
// and create a list of these actions, which will be emitted as an argument to
// DoDeclarativeSecurity
DeclActionInfo* SecurityDeclarative::DetectDeclActions(MethodDesc *pMeth, DWORD dwDeclFlags)
{
    CONTRACTL {
        THROWS;
        GC_TRIGGERS;
        MODE_ANY;
        INJECT_FAULT(COMPlusThrowOM(););
    } CONTRACTL_END;

    GCX_COOP();

    DeclActionInfo              *pDeclActions = NULL;

    IMDInternalImport *pInternalImport = pMeth->GetMDImport();

    // Lets check the Ndirect/Interop cases first
    if (dwDeclFlags & DECLSEC_UNMNGD_ACCESS_DEMAND)
    {
        HRESULT hr = S_FALSE;
        if (pMeth->HasSuppressUnmanagedCodeAccessAttr())
        {
            dwDeclFlags &= ~DECLSEC_UNMNGD_ACCESS_DEMAND;
        }
        else
        {
            MethodTable * pMT = pMeth->GetMethodTable();
            EEClass * pClass = pMT->GetClass();

            // If speculatively true then check the CA

            if (pClass->HasSuppressUnmanagedCodeAccessAttr())
            {
#ifdef FEATURE_CORECLR
                hr = S_OK;
#else
                hr = pInternalImport->GetCustomAttributeByName(pMT->GetCl(),
                                                               COR_SUPPRESS_UNMANAGED_CODE_CHECK_ATTRIBUTE_ANSI,
                                                               NULL,
                                                               NULL);
#endif // FEATURE_CORECLR
                if (hr != S_OK)
                {
                    g_IBCLogger.LogEEClassCOWTableAccess(pMT);
                    pClass->SetDoesNotHaveSuppressUnmanagedCodeAccessAttr();
                }
            }
            _ASSERTE(SUCCEEDED(hr));
            if (hr == S_OK)
                dwDeclFlags &= ~DECLSEC_UNMNGD_ACCESS_DEMAND;
        }
        // Check if now there are no actions left
        if (dwDeclFlags == 0)
            return NULL;

        if (dwDeclFlags & DECLSEC_UNMNGD_ACCESS_DEMAND)
        {
            // A NDirect/Interop demand is required.
            DeclActionInfo *temp = DeclActionInfo::Init(pMeth, DECLSEC_UNMNGD_ACCESS_DEMAND, NULL);
            if (!pDeclActions)
                pDeclActions = temp;
            else
            {
                temp->pNext = pDeclActions;
                pDeclActions = temp;
            }
        }
    } // if DECLSEC_UNMNGD_ACCESS_DEMAND

    // Find class declarations
    PsetCacheEntry* classSetPermissions[dclMaximumValue + 1];
    DetectDeclActionsOnToken(pMeth->GetMethodTable()->GetCl(), dwDeclFlags, classSetPermissions, pInternalImport);

    // Find method declarations
    PsetCacheEntry* methodSetPermissions[dclMaximumValue + 1];
    DetectDeclActionsOnToken(pMeth->GetMemberDef(), dwDeclFlags, methodSetPermissions, pInternalImport);

    // Make sure the g_DeclSecClassAndMethodMergeTable is okay
    _ASSERTE(sizeof(g_DeclSecClassAndMethodMergeTable) == sizeof(DeclSecMergeMethod) * (dclMaximumValue + 1) &&
            "g_DeclSecClassAndMethodMergeTable wrong size!");

    // Merge class and method runtime declarations into a single linked list of set indexes
    int i;
    for(i = DECLSEC_RUNTIME_ACTION_COUNT - 1; i >= 0; i--) // note: the loop uses reverse order because AddDeclAction inserts at beginning of the list
    {
        CorDeclSecurity action = g_RuntimeDeclSecOrderTable[i];
        _ASSERTE(action > dclActionNil && action <= dclMaximumValue && "action out of range");
        AddDeclAction(action, classSetPermissions[action], methodSetPermissions[action], &pDeclActions, pMeth);
    }

    return pDeclActions;
}

void SecurityDeclarative::DetectDeclActionsOnToken(mdToken tk, DWORD dwDeclFlags, PsetCacheEntry** pSets, IMDInternalImport *pInternalImport)
{
    CONTRACTL {
        THROWS;
        GC_TRIGGERS;
        MODE_COOPERATIVE;
    } CONTRACTL_END;
    
    // Make sure the DCL to Flag table is okay
    _ASSERTE(DclToFlag(dclDemand) == DECLSEC_DEMANDS &&
             sizeof(DCL_FLAG_MAP) == sizeof(DWORD) * (dclMaximumValue + 1) &&
             "DCL_FLAG_MAP out of sync with CorDeclSecurity!");

    // Initialize the array
    int i;
    for(i = 0; i < dclMaximumValue + 1; i++)
        pSets[i] = NULL;

    // Look up declarations on the token for each SecurityAction
    DWORD dwAction;
    for (dwAction = 0; dwAction <= dclMaximumValue; dwAction++)
    {
        // don't bother with actions that are not in the requested mask
        CorDeclSecurity action = (CorDeclSecurity)dwAction;
        DWORD dwActionFlag = DclToFlag(action);
        if ((dwDeclFlags & dwActionFlag) == 0)
            continue;

        // Load the PermissionSet or PermissionSetCollection from the security action table in the metadata
        PsetCacheEntry *pPCE;
        HRESULT hr = SecurityAttributes::GetDeclaredPermissions(pInternalImport, tk, action, NULL, &pPCE);
        if (hr != S_OK) // returns S_FALSE if it didn't find anything in the metadata
            continue;

        pSets[dwAction] = pPCE;
    }
}

// Returns TRUE if there is a possibility that a token has declarations of the type specified by 'action'
// Returns FALSE if it can determine that the token definately does not.
BOOL SecurityDeclarative::TokenMightHaveDeclarations(IMDInternalImport *pInternalImport, mdToken token, CorDeclSecurity action)
{
    CONTRACTL {
        NOTHROW;
        GC_NOTRIGGER;
        MODE_ANY;
    } CONTRACTL_END;

    HRESULT hr = S_OK;
    HENUMInternal hEnumDcl;
    DWORD cDcl;

    // Check if the token has declarations for
    // the action specified.
    hr = pInternalImport->EnumPermissionSetsInit(
        token,
        action,
        &hEnumDcl);

    if (FAILED(hr) || hr == S_FALSE)
    {
        // PermissionSets for non-CAS actions are special cases because they may be mixed with
        // the set for the corresponding CAS action in a serialized CORSEC_PSET
        if(action == dclNonCasDemand || action == dclNonCasLinkDemand || action == dclNonCasInheritance)
        {
            // See if the corresponding CAS action has permissions
            BOOL fDoCheck = FALSE;
            if(action == dclNonCasDemand)
                    fDoCheck = TokenMightHaveDeclarations(pInternalImport, token, dclDemand);
            else if(action == dclNonCasLinkDemand)
                    fDoCheck = TokenMightHaveDeclarations(pInternalImport, token, dclLinktimeCheck);
            else if(action == dclNonCasInheritance)
                    fDoCheck = TokenMightHaveDeclarations(pInternalImport, token, dclInheritanceCheck);
            if(fDoCheck)
            {
                // We can't tell for sure if there are declarations unless we deserializing something
                // (which is too expensive), so we'll just return TRUE
                return TRUE;
            /*
                OBJECTREF refPermSet = NULL;
                DWORD dwIndex = ~0;
                hr = SecurityAttributes::GetDeclaredPermissionsWithCache(pInternalImport, token, action, &refPermSet, &dwIndex);
                if(refPermSet != NULL)
                {
                    _ASSERTE(dwIndex != (~0));
                    return TRUE;
                }
            */
            }
        }
        pInternalImport->EnumClose(&hEnumDcl);
        return FALSE;
    }

    cDcl = pInternalImport->EnumGetCount(&hEnumDcl);
    pInternalImport->EnumClose(&hEnumDcl);

    return (cDcl > 0);
}


bool SecurityDeclarative::BlobMightContainNonCasPermission(PBYTE pbAttrSet, ULONG cbAttrSet, DWORD dwAction, bool* pHostProtectionOnly)
{
    CONTRACTL {
        THROWS;
    } CONTRACTL_END;

    // Deserialize the CORSEC_ATTRSET
    CORSEC_ATTRSET attrSet;
    HRESULT hr = BlobToAttributeSet(pbAttrSet, cbAttrSet, &attrSet, dwAction);
    if(FAILED(hr))
        COMPlusThrowHR(hr);

    // this works because SecurityAttributes::CanUnrestrictedOverride only returns
    // true if the attribute set contains only well-known non-CAS permissions
    return !SecurityAttributes::ContainsBuiltinCASPermsOnly(&attrSet, pHostProtectionOnly);
}

// Accumulate status of declarative security.
HRESULT SecurityDeclarative::GetDeclarationFlags(IMDInternalImport *pInternalImport, mdToken token, DWORD* pdwFlags, DWORD* pdwNullFlags, BOOL* pfHasSuppressUnmanagedCodeAccessAttr /*[IN:TRUE if Pinvoke/Cominterop][OUT:FALSE if doesn't have attr]*/)
{
    CONTRACTL {
        THROWS;
        GC_TRIGGERS;
        MODE_ANY;
        INJECT_FAULT(COMPlusThrowOM(););
    } CONTRACTL_END;

    HENUMInternal   hEnumDcl;
    HRESULT         hr;
    DWORD           dwFlags = 0;
    DWORD           dwNullFlags = 0;

    _ASSERTE(pdwFlags);
    *pdwFlags = 0;

    if (pdwNullFlags)
        *pdwNullFlags = 0;

    hr = pInternalImport->EnumPermissionSetsInit(token, dclActionNil, &hEnumDcl);
    if (FAILED(hr))
        goto Exit;

    if (hr == S_OK)
    {
        //Look through the security action table in the metadata for declared permission sets
        mdPermission    perms;
        DWORD           dwAction;
        DWORD           dwDclFlags;
        ULONG           cbPerm;
        PBYTE           pbPerm;
        while (pInternalImport->EnumNext(&hEnumDcl, &perms))
        {
            hr = pInternalImport->GetPermissionSetProps(
                perms, 
                &dwAction, 
                (const void**)&pbPerm, 
                &cbPerm);
            if (FAILED(hr))
            {
                goto Exit;
            }
            
            dwDclFlags = DclToFlag(dwAction);
            
            if ((cbPerm > 0) && (pbPerm[0] == LAZY_DECL_SEC_FLAG)) // indicates a serialized CORSEC_PSET
            {
                bool hostProtectionOnly; // gets initialized in call to BlobMightContainNonCasPermission
                if (BlobMightContainNonCasPermission(pbPerm, cbPerm, dwAction, &hostProtectionOnly))
                {
                    switch (dwAction)
                    {
                        case dclDemand:
                            dwFlags |= DclToFlag(dclNonCasDemand);
                            break;
                        case dclLinktimeCheck:
                            dwFlags |= DclToFlag(dclNonCasLinkDemand);
                            break;
                        case dclInheritanceCheck:
                            dwFlags |= DclToFlag(dclNonCasInheritance);
                            break;
                    }
                }
                else
                {
                    if (hostProtectionOnly)
                    {
                        // If this is a linkcheck for HostProtection only, let's capture that in the flags. 
                        // Subsequently, this will be captured in the bit mask on EEClass/MethodDesc
                        // and used when deciding whether to insert runtime callouts for transparency
                        dwDclFlags |= DECLSEC_LINK_CHECKS_HPONLY;
                    }
                }
            }
            
            dwFlags |= dwDclFlags;
        }
    }
    pInternalImport->EnumClose(&hEnumDcl);

    // Disable any runtime checking of UnmanagedCode permission if the correct
    // custom attribute is present.
    // By default, check except when told not to by the passed in BOOL*

    BOOL hasSuppressUnmanagedCodeAccessAttr;
    if (pfHasSuppressUnmanagedCodeAccessAttr == NULL)
    {
#ifdef FEATURE_CORECLR
        hasSuppressUnmanagedCodeAccessAttr = TRUE;
#else
        hasSuppressUnmanagedCodeAccessAttr = 
          (pInternalImport->GetCustomAttributeByName(token,
                                                     COR_SUPPRESS_UNMANAGED_CODE_CHECK_ATTRIBUTE_ANSI,
                                                     NULL,
                                                     NULL) == S_OK);
#endif
    }
    else
        hasSuppressUnmanagedCodeAccessAttr = *pfHasSuppressUnmanagedCodeAccessAttr;
        

    if (hasSuppressUnmanagedCodeAccessAttr)
    {
        dwFlags |= DECLSEC_UNMNGD_ACCESS_DEMAND;
        dwNullFlags |= DECLSEC_UNMNGD_ACCESS_DEMAND;
    }

    *pdwFlags = dwFlags;
    if (pdwNullFlags)
        *pdwNullFlags = dwNullFlags;

Exit:
    return hr;
}

void SecurityDeclarative::ClassInheritanceCheck(MethodTable *pClass, MethodTable *pParent)
{
    CONTRACTL
    {
        STANDARD_VM_CHECK;
        PRECONDITION(CheckPointer(pClass));
        PRECONDITION(CheckPointer(pParent));
        PRECONDITION(!pClass->IsInterface());
    }
    CONTRACTL_END;

    // Regular check since Fast path check didn't succeed
    TypeSecurityDescriptor typeSecDesc(pParent);
    typeSecDesc.InvokeInheritanceChecks(pClass);
}

void SecurityDeclarative::MethodInheritanceCheck(MethodDesc *pMethod, MethodDesc *pParent)
{
    CONTRACTL
    {
        STANDARD_VM_CHECK;
        PRECONDITION(CheckPointer(pMethod));
        PRECONDITION(CheckPointer(pParent));
        INJECT_FAULT(COMPlusThrowOM(););
    }
    CONTRACTL_END;

    // Regular check since Fast path check didn't succeed    
    MethodSecurityDescriptor MDSecDesc(pParent); 
    MDSecDesc.InvokeInheritanceChecks(pMethod);
}

#ifndef CROSSGEN_COMPILE
//-----------------------------------------------------------------------------
//
//
//     CODE FOR PERFORMING JIT-TIME CHECKS
//
//
//-----------------------------------------------------------------------------


#ifdef FEATURE_CAS_POLICY
void DECLSPEC_NORETURN SecurityDeclarative::ThrowHPException(EApiCategories protectedCategories, EApiCategories demandedCategories)
{
    CONTRACTL {
        THROWS;
        GC_TRIGGERS;
        MODE_COOPERATIVE;
        INJECT_FAULT(COMPlusThrowOM(););
    } CONTRACTL_END;

    OBJECTREF hpException = NULL;
    GCPROTECT_BEGIN(hpException);

    MethodTable* pMT = MscorlibBinder::GetClass(CLASS__HOST_PROTECTION_EXCEPTION);
    hpException = (OBJECTREF) AllocateObject(pMT);


    MethodDescCallSite ctor(METHOD__HOST_PROTECTION_EXCEPTION__CTOR);

    ARG_SLOT arg[3] = { 
        ObjToArgSlot(hpException),
        protectedCategories,
        demandedCategories
    };
    ctor.Call(arg);
    
    COMPlusThrow(hpException);

    GCPROTECT_END();
}
#endif // FEATURE_CAS_POLICY




// Retrieve all linktime demands sets for a method. This includes both CAS and
// non-CAS sets for LDs at the class and the method level, so we could get up to
// four sets.
void SecurityDeclarative::RetrieveLinktimeDemands(MethodDesc  *pMD,
                                       OBJECTREF   *pClassCas,
                                       OBJECTREF   *pClassNonCas,
                                       OBJECTREF   *pMethodCas,
                                       OBJECTREF   *pMethodNonCas)
{
    CONTRACTL {
        THROWS;
        GC_TRIGGERS;
        MODE_COOPERATIVE;
        INJECT_FAULT(COMPlusThrowOM(););
    } CONTRACTL_END;

#ifdef FEATURE_CAS_POLICY
    MethodTable * pMT = pMD->GetMethodTable();

    // Class level first.
    if (pMT->GetClass()->RequiresLinktimeCheck())
        *pClassCas = TypeSecurityDescriptor::GetLinktimePermissions(pMT, pClassNonCas);

    // Then the method level.
    if (IsMdHasSecurity(pMD->GetAttrs()))
        *pMethodCas = MethodSecurityDescriptor::GetLinktimePermissions(pMD,  pMethodNonCas);
#endif
}

//
// Determine the reason why a method has been marked as requiring a link time check
//
// Arguments:
//    pMD                  - the method to figure out what link checks are needed for
//    pClassCasDemands     - [out, optional] the CAS link demands found on the class containing the method
//    pClassNonCasDemands  - [out, optional] the non-CAS link demands found on the class containing the method
//    pMethodCasDemands    - [out, optional] the CAS link demands found on the method itself
//    pMethodNonCasDemands - [out, optional] the non-CAS link demands found on the method itself
//    
// Return Value:
//    Flags indicating why the method has a link time check requirement
//

// static
LinktimeCheckReason SecurityDeclarative::GetLinktimeCheckReason(MethodDesc *pMD,
                                                                OBJECTREF  *pClassCasDemands,
                                                                OBJECTREF  *pClassNonCasDemands,
                                                                OBJECTREF  *pMethodCasDemands,
                                                                OBJECTREF  *pMethodNonCasDemands)
{
    CONTRACTL
    {
        THROWS;
        GC_TRIGGERS;
        MODE_COOPERATIVE;
        PRECONDITION(CheckPointer(pMD));
        PRECONDITION(CheckPointer(pClassCasDemands, NULL_OK));
        PRECONDITION(CheckPointer(pClassNonCasDemands, NULL_OK));
        PRECONDITION(CheckPointer(pMethodCasDemands, NULL_OK));
        PRECONDITION(CheckPointer(pMethodNonCasDemands, NULL_OK));
        PRECONDITION(pMD->RequiresLinktimeCheck());
    }
    CONTRACTL_END;

    LinktimeCheckReason reason = LinktimeCheckReason_None;

    ModuleSecurityDescriptor *pMSD = ModuleSecurityDescriptor::GetModuleSecurityDescriptor(pMD->GetAssembly());

    // If the method does not allow partially trusted callers, then the check is because we need to ensure all
    // callers are fully trusted.
    if (!pMSD->IsAPTCA())
    {
        reason |= LinktimeCheckReason_AptcaCheck;
    }

    //
    // If the method has a LinkDemand on it for either CAS or non-CAS permissions, get those and set the
    // flags for the appropriate type of permission.
    //

    struct gc
    {
        OBJECTREF refClassCasDemands;
        OBJECTREF refClassNonCasDemands;
        OBJECTREF refMethodCasDemands;
        OBJECTREF refMethodNonCasDemands;
    }
    gc;
    ZeroMemory(&gc, sizeof(gc));

    GCPROTECT_BEGIN(gc);

    // Fetch link demand sets from all the places in metadata where we might
    // find them (class and method). These might be split into CAS and non-CAS
    // sets as well.
    Security::RetrieveLinktimeDemands(pMD,
                                      &gc.refClassCasDemands,
                                      &gc.refClassNonCasDemands,
                                      &gc.refMethodCasDemands,
                                      &gc.refMethodNonCasDemands);

    if (gc.refClassCasDemands != NULL || gc.refMethodCasDemands != NULL)
    {
        reason |= LinktimeCheckReason_CasDemand;

        if (pClassCasDemands != NULL)
        {
            *pClassCasDemands = gc.refClassCasDemands;
        }
        if (pMethodCasDemands != NULL)
        {
            *pMethodCasDemands = gc.refMethodCasDemands;
        }
    }

    if (gc.refClassNonCasDemands != NULL || gc.refMethodNonCasDemands != NULL)
    {
        reason |= LinktimeCheckReason_NonCasDemand;

        if (pClassNonCasDemands != NULL)
        {
            *pClassNonCasDemands = gc.refClassNonCasDemands;
        }

        if (pMethodNonCasDemands != NULL)
        {
            *pMethodNonCasDemands = gc.refMethodNonCasDemands;
        }

    }

    GCPROTECT_END();

    //
    // Check to see if the target of the method is unmanaged code
    //
    // We detect linktime checks for UnmanagedCode in three cases:
    //   o  P/Invoke calls.
    //   o  Calls through an interface that have a suppress runtime check attribute on them (these are almost
    //      certainly interop calls).
    //   o  Interop calls made through method impls.
    //

    if (pMD->IsNDirect())
    {
        reason |= LinktimeCheckReason_NativeCodeCall;
    }
#ifdef FEATURE_COMINTEROP
    else if (pMD->IsComPlusCall() && !pMD->IsInterface())
    {
        reason |= LinktimeCheckReason_NativeCodeCall;
    }
    else if (pMD->IsInterface())
    {
        // We also consider calls to interfaces that contain the SuppressUnmanagedCodeSecurity attribute to
        // be COM calls, so check for those.
        bool fSuppressUnmanagedCheck =
            pMD->GetMDImport()->GetCustomAttributeByName(pMD->GetMethodTable()->GetCl(),
                                                         COR_SUPPRESS_UNMANAGED_CODE_CHECK_ATTRIBUTE_ANSI,
                                                         NULL,
                                                         NULL) == S_OK ||
            pMD->GetMDImport()->GetCustomAttributeByName(pMD->GetMemberDef(),
                                                         COR_SUPPRESS_UNMANAGED_CODE_CHECK_ATTRIBUTE_ANSI,
                                                         NULL,
                                                         NULL) == S_OK;
        if (fSuppressUnmanagedCheck)
        {
            reason |= LinktimeCheckReason_NativeCodeCall;
        }
    }
#endif // FEATURE_COMINTEROP

    return reason;
}

#ifdef FEATURE_CAS_POLICY
// Issue an inheritance demand against the target assembly

// static
void SecurityDeclarative::InheritanceDemand(Assembly *pTargetAssembly, OBJECTREF refDemand)
{
    CONTRACTL
    {
        THROWS;
        MODE_COOPERATIVE;
        GC_TRIGGERS;
        PRECONDITION(CheckPointer(pTargetAssembly));
        PRECONDITION(refDemand != NULL);
    }
    CONTRACTL_END;

    struct
    {
        OBJECTREF refDemand;
    }
    gc;
    ZeroMemory(&gc, sizeof(gc));
    gc.refDemand = refDemand;

    GCPROTECT_BEGIN(gc);

    IAssemblySecurityDescriptor *pTargetASD = pTargetAssembly->GetSecurityDescriptor();
    SecurityStackWalk::LinkOrInheritanceCheck(pTargetASD,
                                              gc.refDemand,
                                              pTargetAssembly,
                                              dclInheritanceCheck);
    GCPROTECT_END();
}

// static
void SecurityDeclarative::InheritanceLinkDemandCheck(Assembly *pTargetAssembly, MethodDesc * pMDLinkDemand)
{
    CONTRACTL
    {
        STANDARD_VM_CHECK;
        PRECONDITION(CheckPointer(pTargetAssembly));
        PRECONDITION(CheckPointer(pMDLinkDemand));
    }
    CONTRACTL_END;

    GCX_COOP();
    struct
    {
        OBJECTREF refClassCas;
        OBJECTREF refClassNonCas;
        OBJECTREF refMethodCas;
        OBJECTREF refMethodNonCas;
    }
    gc;
    ZeroMemory(&gc, sizeof(gc));

    GCPROTECT_BEGIN(gc);

    Security::RetrieveLinktimeDemands(pMDLinkDemand,
                                        &gc.refClassCas,
                                        &gc.refClassNonCas,
                                        &gc.refMethodCas,
                                        &gc.refMethodNonCas);

    if (gc.refClassCas != NULL)
    {
        InheritanceDemand(pTargetAssembly, gc.refClassCas);
    }

    if (gc.refMethodCas != NULL)
    {
        InheritanceDemand(pTargetAssembly, gc.refMethodCas);
    }

    GCPROTECT_END();
}

// Issue a FullTrust inheritance demand against the target assembly

// static
void SecurityDeclarative::FullTrustInheritanceDemand(Assembly *pTargetAssembly)
{
    CONTRACTL
    {
        STANDARD_VM_CHECK;
        PRECONDITION(CheckPointer(pTargetAssembly));
    }
    CONTRACTL_END;

    GCX_COOP();

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

    GCPROTECT_BEGIN(gc);

    gc.refFullTrust = Security::CreatePermissionSet(TRUE);
    InheritanceDemand(pTargetAssembly, gc.refFullTrust);

    GCPROTECT_END();
}

// Issue a FullTrust link demand against the target assembly

// static
void SecurityDeclarative::FullTrustLinkDemand(Assembly *pTargetAssembly)
{
    CONTRACTL
    {
        THROWS;
        MODE_COOPERATIVE;
        GC_TRIGGERS;
        PRECONDITION(CheckPointer(pTargetAssembly));
    }
    CONTRACTL_END;

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

    GCPROTECT_BEGIN(gc);

    gc.refFullTrust = Security::CreatePermissionSet(TRUE);
    IAssemblySecurityDescriptor *pTargetASD = pTargetAssembly->GetSecurityDescriptor();
    SecurityStackWalk::LinkOrInheritanceCheck(pTargetASD,
                                              gc.refFullTrust,
                                              pTargetAssembly,
                                              dclLinktimeCheck);
    GCPROTECT_END();
}

// Used by interop to simulate the effect of link demands when the caller is
// in fact script constrained by an appdomain setup by IE.
void SecurityDeclarative::CheckLinkDemandAgainstAppDomain(MethodDesc *pMD)
{
    CONTRACTL {
        THROWS;
        GC_TRIGGERS;
        MODE_COOPERATIVE;
        INJECT_FAULT(COMPlusThrowOM(););
    } CONTRACTL_END;

    if (!pMD->RequiresLinktimeCheck())
        return;

    // Find the outermost (closest to caller) appdomain. This
    // represents the domain in which the unmanaged caller is
    // considered to "live" (or, at least, be constrained by).
    AppDomain *pDomain = GetThread()->GetInitialDomain();

    // The link check is only performed if this app domain has
    // security permissions associated with it, which will be
    // the case for all IE scripting callers that have got this
    // far because we automatically reported our managed classes
    // as "safe for scripting".
    // 
    // We also can't do the check if the AppDomain isn't fully
    // setup yet, since we might not have a domain grant set.
    // This is acceptable, since the only code that should run
    // during AppDomain creation is fully trusted.
    IApplicationSecurityDescriptor *pSecDesc = pDomain->GetSecurityDescriptor();
    if (pSecDesc == NULL || pSecDesc->IsInitializationInProgress() || pSecDesc->IsDefaultAppDomain())
        return;

    struct _gc
    {
        OBJECTREF refGrant;
        OBJECTREF refRefused;
        OBJECTREF refClassNonCasDemands;
        OBJECTREF refClassCasDemands;
        OBJECTREF refMethodNonCasDemands;
        OBJECTREF refMethodCasDemands;
        OBJECTREF refAssembly;
    } gc;
    ZeroMemory(&gc, sizeof(gc));

    GCPROTECT_BEGIN(gc);


    // Fetch link demand sets from all the places in metadata where we might
    // find them (class and method). These might be split into CAS and non-CAS
    // sets as well.
    SecurityDeclarative::RetrieveLinktimeDemands(pMD,
                                      &gc.refClassCasDemands,
                                      &gc.refClassNonCasDemands,
                                      &gc.refMethodCasDemands,
                                      &gc.refMethodNonCasDemands);

    // Check CAS link demands.
    bool fGotGrantSet = false;
    if (gc.refClassCasDemands != NULL || gc.refMethodCasDemands != NULL)
    {
        // Get grant (and possibly denied) sets from the app
        // domain.
        gc.refGrant = pSecDesc->GetGrantedPermissionSet(NULL);
        fGotGrantSet = true;
        gc.refAssembly = pMD->GetAssembly()->GetExposedObject();

        if (gc.refClassCasDemands != NULL)
            SecurityStackWalk::CheckSetHelper(&gc.refClassCasDemands,
                                                        &gc.refGrant,
                                                        &gc.refRefused,
                                                        pDomain,
                                                        pMD,
                                                        &gc.refAssembly,
                                                        dclLinktimeCheck);

        if (gc.refMethodCasDemands != NULL)
            SecurityStackWalk::CheckSetHelper(&gc.refMethodCasDemands,
                                                        &gc.refGrant,
                                                        &gc.refRefused,
                                                        pDomain,
                                                        pMD,
                                                        &gc.refAssembly,
                                                        dclLinktimeCheck);

    }

    // Non-CAS demands are not applied against a grant
    // set, they're standalone.
    if (gc.refClassNonCasDemands != NULL)
        CheckNonCasDemand(&gc.refClassNonCasDemands);

    if (gc.refMethodNonCasDemands != NULL)
        CheckNonCasDemand(&gc.refMethodNonCasDemands);

#ifndef FEATURE_CORECLR   
    // On CORECLR, we do this from the JIT callouts if the caller is transparent: if caller is critical, no checks needed

    // We perform automatic linktime checks for UnmanagedCode in three cases:
    //   o  P/Invoke calls (shouldn't get these here, but let's be paranoid).
    //   o  Calls through an interface that have a suppress runtime check
    //      attribute on them (these are almost certainly interop calls).
    //   o  Interop calls made through method impls.
    // Just walk the stack in these cases, they'll be extremely rare and the
    // perf delta isn't that huge.
    if (pMD->IsNDirect() ||
        (pMD->IsInterface() &&
         (pMD->GetMDImport()->GetCustomAttributeByName(pMD->GetMethodTable()->GetCl(),
                                                      COR_SUPPRESS_UNMANAGED_CODE_CHECK_ATTRIBUTE_ANSI,
                                                      NULL,
                                                      NULL) == S_OK ||
          pMD->GetMDImport()->GetCustomAttributeByName(pMD->GetMemberDef(),
                                                      COR_SUPPRESS_UNMANAGED_CODE_CHECK_ATTRIBUTE_ANSI,
                                                      NULL,
                                                      NULL) == S_OK) ) ||
        (pMD->IsComPlusCall() && !pMD->IsInterface()))
        SecurityStackWalk::SpecialDemand(SSWT_LATEBOUND_LINKDEMAND, SECURITY_UNMANAGED_CODE);
#endif // FEATURE_CORECLR

    GCPROTECT_END();
}

























//-----------------------------------------------------------------------------
//
//
//     CODE FOR PERFORMING RUN-TIME CHECKS
//
//
//-----------------------------------------------------------------------------

void SecurityDeclarative::EnsureAssertAllowed(MethodDesc *pMeth, MethodSecurityDescriptor *pMSD)
{
    CONTRACTL {
        THROWS;
        GC_TRIGGERS;
        MODE_COOPERATIVE;
        INJECT_FAULT(COMPlusThrowOM(););
        PRECONDITION(CheckPointer(pMeth));
        PRECONDITION(pMSD == NULL || pMSD->GetMethod() == pMeth);
    } CONTRACTL_END;

    // Check if this Assembly has permission to assert 
    if (pMSD == NULL || !pMSD->CanAssert()) // early out if we have an MSD and we already have checked this permission
    {
        Module* pModule = pMeth->GetModule();
        PREFIX_ASSUME_MSG(pModule != NULL, "Should be a Module pointer here");

        if (!Security::CanAssert(pModule))
            SecurityPolicy::ThrowSecurityException(g_SecurityPermissionClassName, SPFLAGSASSERTION);
    }

    // Check if the Method is allowed to assert based on transparent/critical classification
    if (!SecurityTransparent::IsAllowedToAssert(pMeth) && Security::IsTransparencyEnforcementEnabled())
    {
#ifdef _DEBUG
        if (g_pConfig->LogTransparencyErrors())
        {
            SecurityTransparent::LogTransparencyError(pMeth, "Transparent method using a security assert");
        }
#endif // _DEBUG
        // if assembly is transparent fail the ASSERT operations
        COMPlusThrow(kInvalidOperationException, W("InvalidOperation_AssertTransparentCode"));
    }

    return;
}

void SecurityDeclarative::InvokeDeclarativeActions (MethodDesc *pMeth, DeclActionInfo *pActions, MethodSecurityDescriptor *pMSD)
{
    CONTRACTL {
        THROWS;
        GC_TRIGGERS;
        MODE_COOPERATIVE;
        INJECT_FAULT(COMPlusThrowOM(););
    } CONTRACTL_END;

    OBJECTREF       refPermSet = NULL;
    ARG_SLOT           arg = 0;

    // If we get a real PermissionSet, then invoke the action.
    switch (pActions->dwDeclAction)
    {
    case DECLSEC_DEMANDS:
        SecurityStackWalk::DemandSet(SSWT_DECLARATIVE_DEMAND, pActions->pPCE, dclDemand);
        break;

    case DECLSEC_ASSERTIONS:
        EnsureAssertAllowed(pMeth, pMSD);
        GetThread()->IncrementAssertCount();
                break;

    case DECLSEC_DENIALS:
    case DECLSEC_PERMITONLY:
        GetThread()->IncrementOverridesCount();
        break;

    case DECLSEC_NONCAS_DEMANDS:
        refPermSet = pActions->pPCE->CreateManagedPsetObject (dclNonCasDemand);
        if (refPermSet == NULL)
            break;
        if(!((PERMISSIONSETREF)refPermSet)->CheckedForNonCas() ||((PERMISSIONSETREF)refPermSet)->ContainsNonCas())
        {
            GCPROTECT_BEGIN(refPermSet);
            MethodDescCallSite demand(METHOD__PERMISSION_SET__DEMAND_NON_CAS, &refPermSet);

            arg = ObjToArgSlot(refPermSet);
            demand.Call(&arg);
            GCPROTECT_END();
        }
        break;

    default:
        _ASSERTE(!"Unknown action requested in InvokeDeclarativeActions");
        break;

    } // switch
}


//
// CODE FOR PERFORMING RUN-TIME CHECKS
//
extern LPVOID GetSecurityObjectForFrameInternal(StackCrawlMark *stackMark, INT32 create, OBJECTREF *pRefSecDesc);    

namespace 
{
    inline void UpdateFrameSecurityObj(DWORD dwAction, OBJECTREF *refPermSet, OBJECTREF * pSecObj)
    {
        CONTRACTL {
            THROWS;
            GC_TRIGGERS;
            MODE_COOPERATIVE;
            INJECT_FAULT(COMPlusThrowOM(););
        } CONTRACTL_END;

        GetSecurityObjectForFrameInternal(NULL, true, pSecObj);

        FRAMESECDESCREF fsdRef = (FRAMESECDESCREF)*pSecObj;
        switch (dwAction)
        {
        // currently we require declarative security to store the data in both the fields in the FSD
            case dclAssert:
                fsdRef->SetDeclarativeAssertions(*refPermSet);  
                {
                    PERMISSIONSETREF psRef = (PERMISSIONSETREF)*refPermSet;
                    if (psRef != NULL && psRef->IsUnrestricted())
                        fsdRef->SetAssertFT(TRUE);
                }
                break;

            case dclDeny:
                fsdRef->SetDeclarativeDenials(*refPermSet);
                break;

            case dclPermitOnly:            
                fsdRef->SetDeclarativeRestrictions(*refPermSet);
                break;

            default:
                _ASSERTE(0 && "Unreached, add code to handle if reached here...");
                break;
        }
    }
}

void SecurityDeclarative::InvokeDeclarativeStackModifiers(MethodDesc * pMeth, DeclActionInfo * pActions, OBJECTREF * pSecObj)
{
    CONTRACTL {
        THROWS;
        GC_TRIGGERS;
        MODE_COOPERATIVE;
        INJECT_FAULT(COMPlusThrowOM(););
    } CONTRACTL_END;

    OBJECTREF       refPermSet = NULL;

    // If we get a real PermissionSet, then invoke the action.
    switch (pActions->dwDeclAction)
    {
    case DECLSEC_DEMANDS:
    case DECLSEC_NONCAS_DEMANDS:
        // Nothing to do for demands
        break;

    case DECLSEC_ASSERTIONS:
        refPermSet = pActions->pPCE->CreateManagedPsetObject (dclAssert);
        if (refPermSet == NULL)
            break;
        GCPROTECT_BEGIN(refPermSet);
        // Now update the frame security object
        UpdateFrameSecurityObj(dclAssert, &refPermSet, pSecObj);
        GCPROTECT_END();
        break;

    case DECLSEC_DENIALS:
        // Update the frame security object
        refPermSet = pActions->pPCE->CreateManagedPsetObject (dclDeny);
 
        if (refPermSet == NULL)
            break;

        GCPROTECT_BEGIN(refPermSet);

#ifdef FEATURE_CAS_POLICY
        // Deny is only valid if we're in legacy CAS mode
        IApplicationSecurityDescriptor *pSecDesc = GetAppDomain()->GetSecurityDescriptor();
        if (!pSecDesc->IsLegacyCasPolicyEnabled())
        {
            COMPlusThrow(kNotSupportedException, W("NotSupported_CasDeny"));
        }
#endif // FEATURE_CAS_POLICY

        UpdateFrameSecurityObj(dclDeny, &refPermSet, pSecObj);

        GCPROTECT_END();
        break;

    case DECLSEC_PERMITONLY:
        // Update the frame security object
        refPermSet = pActions->pPCE->CreateManagedPsetObject (dclPermitOnly);

        if (refPermSet == NULL)
            break;
        GCPROTECT_BEGIN(refPermSet);
        UpdateFrameSecurityObj(dclPermitOnly, &refPermSet, pSecObj);
        GCPROTECT_END();
        break;


    default:
        _ASSERTE(!"Unknown action requested in InvokeDeclarativeStackModifiers");
        break;

    } // switch
}

void SecurityDeclarative::DoDeclarativeActions(MethodDesc *pMeth, DeclActionInfo *pActions, LPVOID pSecObj, MethodSecurityDescriptor *pMSD)
{
    CONTRACTL {
        THROWS;
        GC_TRIGGERS;
        MODE_COOPERATIVE;
        INJECT_FAULT(COMPlusThrowOM(););
    } CONTRACTL_END;

#ifndef FEATURE_CAS_POLICY
    // In the CoreCLR, we don't support CAS actions outside mscorlib.
    // However, we do have to expose certain types in mscorlib due to compiler requirements 
    // (c# compiler requires us to expose SecurityPermission/SecurityAction etc so that it can
    // insert a RequestMinimum for SkipVerification).
    // This means that code outside mscorlib could construct IL that has declarative security
    // in it. This is not a security issue - even if they try to create IL that asserts for
    // permissions they don't have, it's not going to work for the same reasons it didn't in the desktop.
    // However, we could have bugs like DDB 120109 where they can cause Demands to fail etc.
    // So for goodness, we're not going to do any runtime declarative work on assemblies other than mscorlib.
    if (!pMeth->GetModule()->IsSystem())
    {
        // Non-mscorlib code reached... exit
        return;
    }
#endif //!FEATURE_CAS_POLICY
    

    // --------------------------------------------------------------------------- //
    //          D E C L A R A T I V E   S E C U R I T Y   D E M A N D S            //
    // --------------------------------------------------------------------------- //
    // The frame is now fully formed, arguments have been copied into place,
    // and synchronization monitors have been entered if necessary.  At this
    // point, we are prepared for something to throw an exception, so we may
    // check for declarative security demands and execute them.  We need a
    // well-formed frame and synchronization domain to accept security excep-
    // tions thrown by the SecurityManager.  We MAY need argument values in
    // the frame so that the arguments may be finalized if security throws an
    // exception across them (unknown).  
    if (pActions != NULL && pActions->dwDeclAction == DECLSEC_UNMNGD_ACCESS_DEMAND &&
        pActions->pNext == NULL)
    {
        /* We special-case the security check on single pinvoke/interop calls
           so we can avoid setting up the GCFrame */

        SecurityStackWalk::SpecialDemand(SSWT_DECLARATIVE_DEMAND, SECURITY_UNMANAGED_CODE);
        return;
    }
    else
    {
#ifdef FEATURE_COMPRESSEDSTACK
        // If this is an anonymously hosted dynamic method, there aren't any direct modifiers, but if it has a compressed stack that
        // might have modifiers, mark that there are modifiers so we make sure to do a stack walk
        if(SecurityStackWalk::MethodIsAnonymouslyHostedDynamicMethodWithCSToEvaluate(pMeth)) 
        {
            // We don't know how many asserts or overrides might be in the compressed stack,
            // but we just need to increment the counters to ensure optimizations don't skip CS evaluation
            GetThread()->IncrementAssertCount();
            GetThread()->IncrementOverridesCount();
        }
#endif // FEATURE_COMPRESSEDSTACK

        for (/**/; pActions; pActions = pActions->pNext)
        {
            if (pActions->dwDeclAction == DECLSEC_UNMNGD_ACCESS_DEMAND)
            {
                SecurityStackWalk::SpecialDemand(SSWT_DECLARATIVE_DEMAND, SECURITY_UNMANAGED_CODE);
            }
            else
            {
                InvokeDeclarativeActions(pMeth, pActions, pMSD);
            }
        }

    }
}
void SecurityDeclarative::DoDeclarativeStackModifiers(MethodDesc *pMeth, AppDomain* pAppDomain, LPVOID pSecObj)
{
    CONTRACTL {
        THROWS;
        GC_TRIGGERS;
        MODE_COOPERATIVE;
        INJECT_FAULT(COMPlusThrowOM(););
    } CONTRACTL_END;

#ifndef FEATURE_CAS_POLICY
    // In the CoreCLR, we don't support CAS actions outside mscorlib.
    // However, we do have to expose certain types in mscorlib due to compiler requirements 
    // (c# compiler requires us to expose SecurityPermission/SecurityAction etc so that it can
    // insert a RequestMinimum for SkipVerification).
    // This means that code outside mscorlib could construct IL that has declarative security
    // in it. This is not a security issue - even if they try to create IL that asserts for
    // permissions they don't have, it's not going to work for the same reasons it didn't in the desktop.
    // However, we could have bugs like DDB 120109 where they can cause Demands to fail etc.
    // So for goodness, we're not going to do any runtime declarative work on assemblies other than mscorlib.
    if (!pMeth->GetModule()->IsSystem())
    {
        // Non-mscorlib code reached... exit
        return;
    }
#endif //!FEATURE_CAS_POLICY
        
    
    AppDomain* pCurrentDomain = GetAppDomain();
    
    if (pCurrentDomain != pAppDomain)
    {
        ENTER_DOMAIN_PTR(pAppDomain, ADV_RUNNINGIN)
        {
            DoDeclarativeStackModifiersInternal(pMeth, pSecObj);
        }
        END_DOMAIN_TRANSITION;
    }
    else
    {
        DoDeclarativeStackModifiersInternal(pMeth, pSecObj);
            }
        }

void SecurityDeclarative::DoDeclarativeStackModifiersInternal(MethodDesc *pMeth, LPVOID pSecObj)
{
    CONTRACTL {
        THROWS;
        GC_TRIGGERS;
        MODE_COOPERATIVE;
        INJECT_FAULT(COMPlusThrowOM(););
    } CONTRACTL_END;

    Object** ppSecObject = (Object**) pSecObj;
    _ASSERTE(pMeth->IsInterceptedForDeclSecurity() && !pMeth->IsInterceptedForDeclSecurityCASDemandsOnly());

    MethodSecurityDescriptor MDSecDesc(pMeth);
    MethodSecurityDescriptor::LookupOrCreateMethodSecurityDescriptor(&MDSecDesc);
    DeclActionInfo* pActions = MDSecDesc.GetRuntimeDeclActionInfo();

    OBJECTREF fsdRef = ObjectToOBJECTREF(*ppSecObject);
    GCPROTECT_BEGIN(fsdRef);

    for (/**/; pActions; pActions = pActions->pNext)
    {
        InvokeDeclarativeStackModifiers(pMeth, pActions, &fsdRef);
    }
    // If we had just NON-CAS demands, we'd come here but not create an FSD.
    if (fsdRef != NULL)
    {
        ((FRAMESECDESCREF)(fsdRef))->SetDeclSecComputed(TRUE);

        if (*ppSecObject == NULL)
        {
            // we came in with a NULL FSD and the FSD got created here...so we need to copy it back
            // If we had come in with a non-NULL FSD, that would have been updated and this (shallow/pointer) copy
            // would not be necessary
            *ppSecObject = OBJECTREFToObject(fsdRef);
    }
}

    GCPROTECT_END();
}


void SecurityDeclarative::CheckNonCasDemand(OBJECTREF *prefDemand)
{
    CONTRACTL {
        THROWS;
        GC_TRIGGERS;
        MODE_COOPERATIVE;
        PRECONDITION(IsProtectedByGCFrame (prefDemand));
    } CONTRACTL_END;

    if(((PERMISSIONSETREF)*prefDemand)->CheckedForNonCas())
    {
        if(!((PERMISSIONSETREF)*prefDemand)->ContainsNonCas())
            return;
    }
    MethodDescCallSite demand(METHOD__PERMISSION_SET__DEMAND_NON_CAS, prefDemand);
    ARG_SLOT arg = ObjToArgSlot(*prefDemand);
    demand.Call(&arg);
}

#endif // FEATURE_CAS_POLICY

#endif // CROSSGEN_COMPILE