summaryrefslogtreecommitdiff
path: root/src/vm/securityconfig.cpp
blob: 9c7970db8c8c20521e4aecb36ca1becb6e3bd521 (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
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
// 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.
//
// File: SecurityConfig.cpp
//

//
//   Native implementation for security config access and manipulation
//


// #SecurityConfigFormat
// 
// The security config system resides outside of the rest
// of the config system since our needs are different.  The
// unmanaged portion of the security config system is only
// concerned with data file/cache file pairs, not what they
// are used for.  It performs all the duties of reading data
// from the disk, saving data back to the disk, and maintaining
// the policy and quick cache data structures.
//
// FILE FORMAT
//
// The data file is a purely opaque blob for the unmanaged
// code; however, the cache file is constructed and maintained
// completely in the unmanaged code.  It's format is as follows:
//
// CacheHeader
//  |
//  +-- dummyFileTime (FILETIME, 8 bytes) = this exists to make sure we don't read old format cache files. Must be set to {1, 0}.
//  |
//  +-- version (DWORD) = The version of this config file.
//  |
//  +-- configFileTime (FILETIME, 8 bytes) = The file time of the config file associated with this cache file.
//  |
//  +-- isSecurityOn (DWORD, 4 bytes) = This is currently not used.
//  |
//  +-- quickCache (DWORD, 4 bytes) = Used as a bitfield to maintain the information for the QuickCache.  See the QuickCache section for more details.
//  |
//  +-- registryExtensionsInfo (struct RegistryExtensionsInfo) = Indicates whether this cache file was generated in the presence of registry extensions.
//  |
//  +-- numEntries (DWORD, 4 bytes) = The number of policy cache entries in the latter portion of this cache file.
//  |
//  +-- sizeConfig (DWORD, 4 bytes) = The size of the config information stored in the latter portion of this cache file.
//
// Config Data (if any)
//     The cache file can include an entire copy of this
//     information in the adjoining config file.  This is
//     necessary since the cache often allows us to make
//     policy decisions without having parsed the data in 
//     the config file.  In order to guarantee that the config
//     data used by this process is not altered in the
//     meantime, we need to store the data in a readonly
//     location.  Due to the design of the caching system
//     the cache file is locked when it is opened and therefore
//     is the perfect place to store this information.  The
//     other alternative is to hold it in memory, but since
//     this can amount to many kilobytes of data we decided
//     on this design.
//
// List of CacheEntries
//  |
//  +-- CacheEntry
//  |    |
//  |    +-- numItemsInKey (DWORD, 4 bytes) = The number of evidence objects serialized in the key blob
//  |    |
//  |    +-- keySize (DWORD, 4 bytes) = The number of bytes in the key blob.
//  |    |
//  |    +-- dataSize (DWORD, 4 bytes) = The number of bytes in the data blob.
//  |    |     
//  |    +-- keyBlob (raw) = A raw blob representing the serialized evidence.
//  |    |
//  |    +-- dataBlob (raw) = A raw blob representing an XML serialized PolicyStatement
//  |
//  +-- ...

#include "common.h"

#ifdef FEATURE_CAS_POLICY

#include "securityconfig.h"

// Header version of the cache file.
#define CONFIG_VERSION 2
// This controls the maximum size of the cache file.
#define MAX_CACHEFILE_SIZE (1 << 20)

#define SIZE_OF_ENTRY( X )   sizeof( CacheEntryHeader ) + X->header.keySize + X->header.dataSize
#define MAX_NUM_LENGTH 16

WCHAR* SecurityConfig::wcscatDWORD( __out_ecount(cchdst) __out_z WCHAR* dst, size_t cchdst, DWORD num )
{
    CONTRACTL
    {
        NOTHROW;
        GC_NOTRIGGER;
        MODE_ANY;
    }
    CONTRACTL_END

    _ASSERTE( SecurityConfig::dataLock_.OwnedByCurrentThread() );

    static WCHAR buffer[MAX_NUM_LENGTH];

    buffer[MAX_NUM_LENGTH-1] = W('\0');

    size_t index = MAX_NUM_LENGTH-2;

    if (num == 0)
    {
        buffer[index--] = W('0');
    }
    else
    {
        while (num != 0)
        {
            buffer[index--] = (WCHAR)(W('0') + (num % 10));
            num = num / 10;
        }
    }

    wcscat_s( dst, cchdst, buffer + index + 1 );

    return dst;
}

inline WCHAR * Wszdup(const WCHAR * str)
{
    CONTRACTL
    {
        THROWS;
        GC_NOTRIGGER;
        MODE_ANY;
    }
    CONTRACTL_END;

    size_t len = wcslen(str) + 1;
    WCHAR * ret = new WCHAR[len];
    wcscpy_s(ret, len, str);
    return ret;
}

struct CacheHeader
{
    FILETIME dummyFileTime;
    DWORD version;
    FILETIME configFileTime;
    DWORD isSecurityOn, quickCache;
    SecurityConfig::RegistryExtensionsInfo registryExtensionsInfo;
    DWORD numEntries, sizeConfig;

    CacheHeader() : isSecurityOn( (DWORD) -1 ), quickCache( 0 ), numEntries( 0 ), sizeConfig( 0 )
    {
        WRAPPER_NO_CONTRACT;
        memset( &this->configFileTime, 0, sizeof( configFileTime ) );
        dummyFileTime.dwLowDateTime = 1;
        dummyFileTime.dwHighDateTime = 0;
        version = CONFIG_VERSION;
        memset(&registryExtensionsInfo, 0, sizeof(registryExtensionsInfo));
        _ASSERTE( IsValid() && "CacheHeader constructor should make it valid" );
    };

    bool IsValid()
    {
        LIMITED_METHOD_CONTRACT;
        return dummyFileTime.dwLowDateTime == 1 &&
               dummyFileTime.dwHighDateTime == 0 &&
               version == CONFIG_VERSION;
    }
};

struct CacheEntryHeader
{
    DWORD numItemsInKey;
    DWORD keySize;
    DWORD dataSize;
};

struct CacheEntry
{
    CacheEntryHeader header;
    BYTE* key;
    BYTE* data;
    DWORD cachePosition;
    BOOL used;

    CacheEntry() : key( NULL ), data( NULL ), used( FALSE ) 
    {
        LIMITED_METHOD_CONTRACT;
    };

    ~CacheEntry( void )
    {
        WRAPPER_NO_CONTRACT;
        delete [] key;
        delete [] data;
    }
};

struct Data
{
    enum State
    {
        None = 0x0,
        UsingCacheFile = 0x1,
        CopyCacheFile = 0x2,
        CacheUpdated = 0x4,
        UsingConfigFile = 0x10,
        CacheExhausted = 0x20,
        NewConfigFile = 0x40
    };

    INT32 id;
    WCHAR* configFileName;
    WCHAR* cacheFileName;
    WCHAR* cacheFileNameTemp;

    LPBYTE configData;
    DWORD  configDataSize;
    FILETIME configFileTime;
    FILETIME cacheFileTime;
    CacheHeader header;
    ArrayList* oldCacheEntries;
    ArrayList* newCacheEntries;
    State state;
    DWORD cacheCurrentPosition;
    HANDLE cache;
    PBYTE configBuffer;
    DWORD  sizeConfig;
    SecurityConfig::ConfigRetval initRetval;
    DWORD newEntriesSize;

    Data( INT32 id )
        : id( id ),
          configFileName( NULL ),
          cacheFileName( NULL ),
          configData( NULL ),
          oldCacheEntries( new ArrayList ),
          newCacheEntries( new ArrayList ),
          state( Data::None ),
          cache( INVALID_HANDLE_VALUE ),
          configBuffer( NULL ),
          newEntriesSize( 0 )
    {
        LIMITED_METHOD_CONTRACT;
    }

    Data( INT32 id, STRINGREF* configFile )
        : id( id ),
          cacheFileName( NULL ),
          configData( NULL ),
          oldCacheEntries( new ArrayList ),
          newCacheEntries( new ArrayList ),
          state( Data::None ),
          cache( INVALID_HANDLE_VALUE ),
          configBuffer( NULL ),
          newEntriesSize( 0 )
    {
        CONTRACTL {
            THROWS;
            GC_NOTRIGGER;
            MODE_ANY;
            PRECONDITION(*configFile != NULL);
        } CONTRACTL_END;

        configFileName = Wszdup( (*configFile)->GetBuffer() );
        cacheFileName = NULL;
        cacheFileNameTemp = NULL;
    }

    Data( INT32 id, STRINGREF* configFile, STRINGREF* cacheFile )
        : id( id ),
          configData( NULL ),
          oldCacheEntries( new ArrayList ),
          newCacheEntries( new ArrayList ),
          state( Data::None ),
          cache( INVALID_HANDLE_VALUE ),
          configBuffer( NULL ),
          newEntriesSize( 0 )
    {
        CONTRACTL {
            THROWS;
            GC_NOTRIGGER;
            MODE_ANY;
            PRECONDITION(*configFile != NULL);
        } CONTRACTL_END;

        configFileName = Wszdup( (*configFile)->GetBuffer() );

        if (cacheFile != NULL)
        {
            // Since temp cache files can stick around even after the process that
            // created them, we want to make sure they are fairly unique (if they
            // aren't, we'll just fail to save cache information, which is not good
            // but it won't cause anyone to crash or anything).  The unique name
            // algorithm used here is to append the process id and tick count to
            // the name of the cache file.

            cacheFileName = Wszdup( (*cacheFile)->GetBuffer() );
            size_t len = wcslen( cacheFileName ) + 1 + 2 * MAX_NUM_LENGTH;
            cacheFileNameTemp = new WCHAR[len];
            wcscpy_s( cacheFileNameTemp, len, cacheFileName );
            wcscat_s( cacheFileNameTemp, len, W(".") );
            SecurityConfig::wcscatDWORD( cacheFileNameTemp, len, GetCurrentProcessId() );
            wcscat_s( cacheFileNameTemp, len, W(".") );
            SecurityConfig::wcscatDWORD( cacheFileNameTemp, len, GetTickCount() );
        }
        else
        {
            cacheFileName = NULL;
            cacheFileNameTemp = NULL;
        }
    }

    Data( INT32 id, const WCHAR* configFile, const WCHAR* cacheFile )
        : id( id ),
          configData( NULL ),
          oldCacheEntries( new ArrayList ),
          newCacheEntries( new ArrayList ),
          state( Data::None ),
          cache( INVALID_HANDLE_VALUE ),
          configBuffer( NULL ),
          newEntriesSize( 0 )

    {
        CONTRACTL {
            THROWS;
            GC_NOTRIGGER;
            MODE_ANY;
            PRECONDITION(*configFile != NULL);
        } CONTRACTL_END;

        configFileName = Wszdup( configFile );

        if (cacheFile != NULL)
        {
            cacheFileName = Wszdup( cacheFile );
            size_t len = wcslen( cacheFileName ) + 1 + 2 * MAX_NUM_LENGTH;
            cacheFileNameTemp = new WCHAR[len];
            wcscpy_s( cacheFileNameTemp, len, cacheFileName );
            wcscat_s( cacheFileNameTemp, len, W(".") );
            SecurityConfig::wcscatDWORD( cacheFileNameTemp, len, GetCurrentProcessId() );
            wcscat_s( cacheFileNameTemp, len, W(".") );
            SecurityConfig::wcscatDWORD( cacheFileNameTemp, len, GetTickCount() );
        }
        else
        {
            cacheFileName = NULL;
            cacheFileNameTemp = NULL;
        }
    }

    void Reset( void )
    {
        CONTRACTL {
            THROWS;
            GC_NOTRIGGER;
            MODE_ANY;
        } CONTRACTL_END;

        delete [] configBuffer;
        configBuffer = NULL;

        if (cache != INVALID_HANDLE_VALUE)
        {
            CloseHandle( cache );
            cache = INVALID_HANDLE_VALUE;
        }

        if (cacheFileNameTemp != NULL)
        {
            // Note: we don't check a return value here as the worst thing that
            // happens is we leave a spurious cache file.

            WszDeleteFile( cacheFileNameTemp );
        }

        if (configData != NULL)
            delete [] configData;
        configData = NULL;

        DeleteAllEntries();
        header = CacheHeader();

        oldCacheEntries = new ArrayList();
        newCacheEntries = new ArrayList();

    }

    void Cleanup( void )
    {
        CONTRACTL {
            NOTHROW;
            GC_NOTRIGGER;
            MODE_ANY;
        } CONTRACTL_END;

        if (cache != INVALID_HANDLE_VALUE)
        {
            CloseHandle( cache );
            cache = INVALID_HANDLE_VALUE;
        }

        if (cacheFileNameTemp != NULL)
        {
            // Note: we don't check a return value here as the worst thing that
            // happens is we leave a spurious cache file.

            WszDeleteFile( cacheFileNameTemp );
        }
    }

    ~Data( void )
    {
        CONTRACTL {
            NOTHROW;
            GC_NOTRIGGER;
            MODE_ANY;
        } CONTRACTL_END;

        Cleanup();
        delete [] configBuffer;

        delete [] configFileName;
        delete [] cacheFileName;
        delete [] cacheFileNameTemp;

        if (configData != NULL)
            delete [] configData;
        DeleteAllEntries();
    }

    void DeleteAllEntries( void );
};

void Data::DeleteAllEntries( void )
{
    CONTRACTL {
        NOTHROW;
        GC_NOTRIGGER;
        MODE_ANY;
    } CONTRACTL_END;

    ArrayList::Iterator iter;

    if (oldCacheEntries != NULL)
    {
        iter = oldCacheEntries->Iterate();

        while (iter.Next())
        {
            delete (CacheEntry*) iter.GetElement();
        }

        delete oldCacheEntries;
        oldCacheEntries = NULL;
    }

    if (newCacheEntries != NULL)
    {
        iter = newCacheEntries->Iterate();

        while (iter.Next())
        {
            delete (CacheEntry*) iter.GetElement();
        }

        delete newCacheEntries;
        newCacheEntries = NULL;
    }
}

void* SecurityConfig::GetData( INT32 id )
{
    CONTRACTL
    {
        NOTHROW;
        GC_NOTRIGGER;
        MODE_ANY;
    }
    CONTRACTL_END

    ArrayList::Iterator iter = entries_.Iterate();

    while (iter.Next())
    {
        Data* data = (Data*)iter.GetElement();

        if (data->id == id)
        {
            return data;
        }
    }

    return NULL;
}

static BOOL CacheOutOfDate( FILETIME* configFileTime, __in_z WCHAR* configFileName, __in_z_opt WCHAR* cacheFileName )
{
    CONTRACTL
    {
        NOTHROW;
        GC_NOTRIGGER;
        MODE_PREEMPTIVE;
    }
    CONTRACTL_END

    BOOL retval = TRUE;
    BOOL deleteFile = FALSE;

    HandleHolder config(WszCreateFile( configFileName, GENERIC_READ, FILE_SHARE_READ, NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL ));

    if (config.GetValue() == INVALID_HANDLE_VALUE)
    {
        goto CLEANUP;
    }

    // Get the last write time for both files.

    FILETIME newConfigTime;

    if (!GetFileTime( config.GetValue(), NULL, NULL, &newConfigTime ))
    {
        goto CLEANUP;
    }

    if (CompareFileTime( configFileTime, &newConfigTime ) != 0)
    {
        // Cache is dated.  Delete the cache.
        deleteFile = TRUE;
        goto CLEANUP;
    }

    retval = FALSE;

CLEANUP:
    // Note: deleting this file is a perf optimization so that
    // we don't have to do this file time comparison next time.
    // Therefore, if it fails for some reason we just loss a
    // little perf.

    if (deleteFile && cacheFileName != NULL)
        WszDeleteFile( cacheFileName );

    return retval;
}

static BOOL CacheOutOfDate( FILETIME* cacheFileTime, HANDLE cache, __in_z_opt WCHAR* cacheFileName )
{
    CONTRACTL
    {
        NOTHROW;
        GC_NOTRIGGER;
        MODE_PREEMPTIVE;
    }
    CONTRACTL_END

    BOOL retval = TRUE;

    // Get the last write time for both files.

    FILETIME newCacheTime;

    if (!GetFileTime( cache, NULL, NULL, &newCacheTime ))
    {
        goto CLEANUP;
    }

    if (CompareFileTime( cacheFileTime, &newCacheTime ) != 0)
    {
        // Cache is dated.  Delete the cache.
        // Note: deleting this file is a perf optimization so that
        // we don't have to do this file time comparison next time.
        // Therefore, if it fails for some reason we just loss a
        // little perf.

        if (cacheFileName != NULL)
        {
            CloseHandle( cache );
            WszDeleteFile( cacheFileName );
        }
        goto CLEANUP;
    }

    retval = FALSE;

CLEANUP:
    return retval;
}

static BOOL CacheOutOfDate( FILETIME* configTime, FILETIME* cachedConfigTime )
{
    CONTRACTL
    {
        NOTHROW;
        GC_NOTRIGGER;
        MODE_PREEMPTIVE;
    }
    CONTRACTL_END

    DWORD result = CompareFileTime( configTime, cachedConfigTime );

    return result != 0;
}

static DWORD GetShareFlags()
{
    LIMITED_METHOD_CONTRACT;

    return FILE_SHARE_READ | FILE_SHARE_DELETE;
}

static DWORD WriteFileData( HANDLE file, LPCBYTE data, DWORD size )
{
    CONTRACTL
    {
        NOTHROW;
        GC_TRIGGERS;
        MODE_ANY;
    }
    CONTRACTL_END

    DWORD totalBytesWritten = 0;
    DWORD bytesWritten;

    do
    {
        if (WriteFile( file, data, size - totalBytesWritten, &bytesWritten, NULL ) == 0)
        {
            return E_FAIL;
        }
        if (bytesWritten == 0)
        {
            return E_FAIL;
        }
        totalBytesWritten += bytesWritten;
    } while (totalBytesWritten < size);

    return S_OK;
}

// the data argument to this function can be a pointer to GC heap. 
// We do ensure cooperative mode before we call this function using a pointer to GC heap,
// so we can't change GC mode inside this function. 
// Greg will look into the ways to pin the object.

static DWORD ReadFileData( HANDLE file, PBYTE data, DWORD size )
{
    CONTRACTL
    {
        NOTHROW;
        GC_TRIGGERS;
        MODE_ANY;
    }
    CONTRACTL_END

    DWORD totalBytesRead = 0;
    DWORD bytesRead;
    do
    {
        if (ReadFile( file, data, size - totalBytesRead, &bytesRead, NULL ) == 0)
        {
            return E_FAIL;
        }

        if (bytesRead == 0)
        {
            return E_FAIL;
        }
        
        totalBytesRead += bytesRead;
        
    } while (totalBytesRead < size);
    
    return S_OK;
}

SecurityConfig::ConfigRetval SecurityConfig::InitData( INT32 id, const WCHAR* configFileName, const WCHAR* cacheFileName )
{
    STANDARD_VM_CONTRACT;

    Data* data = (Data*)GetData( id );
    if (data != NULL)
    {
        return data->initRetval;
    }

    if (configFileName == NULL || wcslen( configFileName ) == 0)
    {
        return NoFile;
    }

    {
        CrstHolder ch( &dataLock_ );
        data = new (nothrow) Data( id, configFileName, cacheFileName );
    }

    if (data == NULL)
    {
         return NoFile;
    }

    return InitData( data, TRUE );
}


SecurityConfig::ConfigRetval SecurityConfig::InitData( void* configDataParam, BOOL addToList )
{
    STANDARD_VM_CONTRACT;

    _ASSERTE( configDataParam != NULL );

    Data* data = (Data*) configDataParam;
    DWORD cacheSize;
    DWORD configSize;
    ConfigRetval retval = NoFile;
    DWORD shareFlags;

    shareFlags = GetShareFlags();

    // Crack open the config file.

    HandleHolder config(WszCreateFile( data->configFileName, GENERIC_READ, shareFlags, NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL ));
    if (config == INVALID_HANDLE_VALUE || !GetFileTime( config, NULL, NULL, &data->configFileTime ))
    {
        memset( &data->configFileTime, 0, sizeof( data->configFileTime ) );
    }
    else
    {
        data->state = (Data::State)(Data::UsingConfigFile | data->state);
    }

    // If we want a cache file, try to open that up.
    // Note: we do not use a holder for data->cache because the new holder for data will
    // delete the entire data structure which includes closing this handle as necessary.

    if (data->cacheFileName != NULL)
        data->cache = WszCreateFile( data->cacheFileName, GENERIC_READ, shareFlags, NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL );
    
    if (data->cache == INVALID_HANDLE_VALUE)
    {
        goto READ_DATA;
    }

    // Validate that the cache file is in a good form by checking
    // that it is at least big enough to contain a header.

    cacheSize = SafeGetFileSize( data->cache, NULL );
    
    if (cacheSize == 0xFFFFFFFF)
    {
        goto READ_DATA;
    }
    
    if (cacheSize < sizeof( CacheHeader ))
    {
        goto READ_DATA;
    }

    // Finally read the data from the file into the buffer.
    
    if (ReadFileData( data->cache, (BYTE*)&data->header, sizeof( CacheHeader ) ) != S_OK)
    {
        goto READ_DATA;
    }

    if (!data->header.IsValid())
    {
        goto READ_DATA;
    }

    // Check to make sure the cache file and the config file
    // match up by comparing the actual file time of the config
    // file and the config file time stored in the cache file.

    if (CacheOutOfDate( &data->configFileTime, &data->header.configFileTime ))
    {
        goto READ_DATA;
    }

    if (!GetFileTime( data->cache, NULL, NULL, &data->cacheFileTime ))
    {
        goto READ_DATA;
    }

    // Set the file pointer to after both the header and config data (if any) so
    // that we are ready to read cache entries.

    if (SetFilePointer( data->cache, sizeof( CacheHeader ) + data->header.sizeConfig, NULL, FILE_BEGIN ) == INVALID_SET_FILE_POINTER)
    {
        goto READ_DATA;
    }

    data->cacheCurrentPosition = sizeof( CacheHeader ) + data->header.sizeConfig;
    data->state = (Data::State)(Data::UsingCacheFile | Data::CopyCacheFile | data->state);

    retval = (ConfigRetval)(retval | CacheFile);

READ_DATA:
    // If we are not using the cache file but we successfully opened it, we need
    // to close it now.  In addition, we need to reset the cache information
    // stored in the Data object to make sure there is no spill over.

    if (data->cache != INVALID_HANDLE_VALUE && (data->state & Data::UsingCacheFile) == 0)
    {
        CloseHandle( data->cache );
        data->header = CacheHeader();
        data->cache = INVALID_HANDLE_VALUE;
    }

    if (config != INVALID_HANDLE_VALUE)
    {
        configSize = SafeGetFileSize( config, NULL );
    
        if (configSize == 0xFFFFFFFF)
        {
            goto ADD_DATA;
        }

        // Be paranoid and only use the cache file version if we find that it has the correct sized
        // blob in it.

        if ((data->state & Data::UsingCacheFile) != 0 && configSize == data->header.sizeConfig)
        {
            goto ADD_DATA;
        }
        else
        {
            if (data->cache != INVALID_HANDLE_VALUE)
            {
                CloseHandle( data->cache );
                data->header = CacheHeader();
                data->cache = INVALID_HANDLE_VALUE;
                data->state = (Data::State)(data->state & ~(Data::UsingCacheFile));
            }

            data->configData = new BYTE[configSize];
            if (ReadFileData( config, data->configData, configSize ) != S_OK)
            {
                goto ADD_DATA;
            }
            data->configDataSize = configSize;
        }
        retval = (ConfigRetval)(retval | ConfigFile);
    }

ADD_DATA:
    {
        CrstHolder ch(&dataLock_);

        if (addToList)
        {
            IfFailThrow(entries_.Append(data));
        }
    }

    _ASSERTE( data );
    data->initRetval = retval;

    return retval;

};

static CacheEntry* LoadNextEntry( HANDLE cache, Data* data )
{
    STANDARD_VM_CONTRACT;

    if ((data->state & Data::CacheExhausted) != 0)
        return NULL;

    NewHolder<CacheEntry> entry(new CacheEntry());

    if (SetFilePointer( cache, data->cacheCurrentPosition, NULL, FILE_BEGIN ) == INVALID_SET_FILE_POINTER)
    {
        return NULL;
    }

        if (ReadFileData( cache, (BYTE*)&entry.GetValue()->header, sizeof( CacheEntryHeader ) ) != S_OK)
    {
        return NULL;
    }

    entry.GetValue()->cachePosition = data->cacheCurrentPosition + sizeof( entry.GetValue()->header );

    data->cacheCurrentPosition += sizeof( entry.GetValue()->header ) + entry.GetValue()->header.keySize + entry.GetValue()->header.dataSize;

    if (SetFilePointer( cache, entry.GetValue()->header.keySize + entry->header.dataSize, NULL, FILE_CURRENT ) == INVALID_SET_FILE_POINTER)
    {
        return NULL;
    }

    // We append a partially populated entry. CompareEntry is robust enough to handle this.
    IfFailThrow(data->oldCacheEntries->Append( entry ));

    return entry.Extract();
}

static BOOL WriteEntry( HANDLE cache, CacheEntry* entry, HANDLE oldCache = NULL )
{
    STANDARD_VM_CONTRACT;

    if (WriteFileData( cache, (BYTE*)&entry->header, sizeof( CacheEntryHeader ) ) != S_OK)
    {
        return FALSE;
    }

    if (entry->key == NULL)
    {
        _ASSERTE (oldCache != NULL);

        // We were lazy in reading the entry. Read the key now.
        entry->key = new BYTE[entry->header.keySize];

        _ASSERTE (cache != INVALID_HANDLE_VALUE);

        if (SetFilePointer( oldCache, entry->cachePosition, NULL, FILE_BEGIN ) == INVALID_SET_FILE_POINTER)
            return NULL;

        if (ReadFileData( oldCache, entry->key, entry->header.keySize ) != S_OK)
        {
            return NULL;
        }

        entry->cachePosition += entry->header.keySize;
    }

    _ASSERTE( entry->key != NULL );

    if (entry->data == NULL)
    {
        _ASSERTE (oldCache != NULL);

        // We were lazy in reading the entry. Read the data also.
        entry->data = new BYTE[entry->header.dataSize];

        if (SetFilePointer( oldCache, entry->cachePosition, NULL, FILE_BEGIN ) == INVALID_SET_FILE_POINTER)
            return NULL;

        if (ReadFileData( oldCache, entry->data, entry->header.dataSize ) != S_OK)
            return NULL;

        entry->cachePosition += entry->header.dataSize;
    }

    _ASSERT( entry->data != NULL );

    if (WriteFileData( cache, entry->key, entry->header.keySize ) != S_OK)
    {
        return FALSE;
    }

    if (WriteFileData( cache, entry->data, entry->header.dataSize ) != S_OK)
    {
        return FALSE;
    }

    return TRUE;
}

BOOL SecurityConfig::SaveCacheData( INT32 id )
{
    CONTRACTL
    {
        THROWS;
        GC_TRIGGERS;
        MODE_ANY;
    }
    CONTRACTL_END

    GCX_PREEMP();

    // Note: this function should only be called at EEShutdown time.
    // This is because we need to close the current cache file in
    // order to delete it.  If it ever became necessary to do
    // cache saves while a process we still executing managed code
    // it should be possible to create a locking scheme for usage
    // of the cache handle with very little reordering of the below
    // (as it should always be possible for us to have a live copy of
    // the file and yet still be making the swap).

    HandleHolder cache;
    HandleHolder config;
    CacheHeader header;
    BOOL retval = FALSE;
    BOOL fWriteSucceeded = FALSE;
    DWORD numEntriesWritten = 0;
    DWORD amountWritten = 0;
    DWORD sizeConfig = 0;
    NewHolder<BYTE> configBuffer;
    BOOL useConfigData = FALSE;

    Data* data = (Data*)GetData( id );

    // If there is not data by the id or there is no
    // cache file name associated with the data, then fail.

    if (data == NULL || data->cacheFileName == NULL)
        return FALSE;

    // If we haven't added anything new to the cache
    // then just return success.

    if ((data->state & Data::CacheUpdated) == 0)
        return TRUE;

    // If the config file has changed since the process started
    // then our cache data is no longer valid.  We'll just
    // return success in this case.

    if ((data->state & Data::UsingConfigFile) != 0 && CacheOutOfDate( &data->configFileTime, data->configFileName, NULL ))
        return TRUE;

    DWORD fileNameLength = (DWORD)wcslen( data->cacheFileName );

    NewArrayHolder<WCHAR> newFileName(new WCHAR[fileNameLength + 5]);

    swprintf_s( newFileName.GetValue(), fileNameLength + 5, W("%s%s"), data->cacheFileName, W(".new") );

    cache.Assign( WszCreateFile( newFileName, GENERIC_WRITE, 0, NULL, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL ) ); 

    for (DWORD RetryCount = 0; RetryCount < 5; RetryCount++)
    {
        if (cache != INVALID_HANDLE_VALUE)
        {
            break;
        }
        else
        {
            DWORD error = GetLastError();

            if (error == ERROR_PATH_NOT_FOUND)
            {
                // The directory does not exist, iterate through and try to create it.

                WCHAR* currentChar = newFileName;

                // Skip the first backslash

                while (*currentChar != W('\0'))
                {
                    if (*currentChar == W('\\') || *currentChar == W('/'))
                    {
                        currentChar++;
                        break;
                    }
                    currentChar++;
                }

                // Iterate through trying to create each subdirectory.

                while (*currentChar != W('\0'))
                {
                    if (*currentChar == W('\\') || *currentChar == W('/'))
                    {
                        *currentChar = W('\0');

                        if (!WszCreateDirectory( newFileName, NULL ))
                        {
                            error = GetLastError();

                            if (error != ERROR_ACCESS_DENIED && error != ERROR_INVALID_NAME && error != ERROR_ALREADY_EXISTS)
                            {
                                goto CLEANUP;
                            }
                        }

                        *currentChar = W('\\');
                    }
                    currentChar++;
                }

                // Try the file creation again
                continue;
            }
        }

        // CreateFile failed.  Sleep a little and retry, in case a
        // virus scanner caused the creation to fail.
        ClrSleepEx(10, FALSE);
    }

    if (cache.GetValue() == INVALID_HANDLE_VALUE)
        goto CLEANUP;

    // This code seems complicated only because of the
    // number of cases that we are trying to handle.  All we
    // are trying to do is determine the amount of space to
    // leave for the config information.

    // If we saved out a new config file during this run, use
    // the config size stored in the Data object itself.

        if (data->configData != NULL)
        {
            useConfigData = TRUE;
        }

    if ((data->state & Data::NewConfigFile) != 0)
    {
        sizeConfig = data->sizeConfig;
    }

    // If we have a cache file, then use the size stored in the
    // cache header.

    else if ((data->state & Data::UsingCacheFile) != 0)
    {
        sizeConfig = data->header.sizeConfig;
    }

    // If we read in the config data, use the size of the
    // managed byte array that it is stored in.

    else if (useConfigData)
    {
        sizeConfig = data->configDataSize;
    }

    // Otherwise, check the config file itself to get the size.

    else
    {
        DWORD shareFlags;

        shareFlags = GetShareFlags();

        config.Assign( WszCreateFile( data->configFileName, GENERIC_READ, shareFlags, NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL ) );

        if (config == INVALID_HANDLE_VALUE)
        {
            sizeConfig = 0;
        }
        else
        {
            sizeConfig = SafeGetFileSize( config, NULL );

            if (sizeConfig == 0xFFFFFFFF)
            {
                sizeConfig = 0;
            }
        }
    }

    // First write the entries.

    if (SetFilePointer( cache, sizeof( CacheHeader ) + sizeConfig, NULL, FILE_BEGIN ) == INVALID_SET_FILE_POINTER)
    {
        goto CLEANUP;
    }

    // We're going to write out the cache entries in a modified
    // least recently used order, throwing out any that end up
    // taking us past our hardcoded max file size.

    {
        // First, write the entries from the cache file that were used.
        // We do this because presumably these are system assemblies
        // and other assemblies used by a number of applications.

        ArrayList::Iterator iter;

        if ((data->state & Data::UsingCacheFile) != 0)
        {
            iter = data->oldCacheEntries->Iterate();

            while (iter.Next() && amountWritten < MAX_CACHEFILE_SIZE)
            {
                CacheEntry* currentEntry = (CacheEntry*)iter.GetElement();

                if (currentEntry->used)
                {
                    if(!WriteEntry( cache, currentEntry, data->cache ))
                    {
                        goto CLEANUP;
                    }

                    amountWritten += SIZE_OF_ENTRY( currentEntry );
                    numEntriesWritten++;
                }
            }
        }

        // Second, write any new cache entries to the file.  These are
        // more likely to be assemblies specific to this app.

        iter = data->newCacheEntries->Iterate();

        while (iter.Next() && amountWritten < MAX_CACHEFILE_SIZE)
        {
            CacheEntry* currentEntry = (CacheEntry*)iter.GetElement();

            if (!WriteEntry( cache, currentEntry ))
            {
                goto CLEANUP;
            }

            amountWritten += SIZE_OF_ENTRY( currentEntry );
            numEntriesWritten++;
        }

        // Third, if we are using the cache file, write the old entries
        // that were not used this time around.

        if ((data->state & Data::UsingCacheFile) != 0)
        {
            // First, write the ones that we already have partially loaded

            iter = data->oldCacheEntries->Iterate();

            while (iter.Next() && amountWritten < MAX_CACHEFILE_SIZE)
            {
                CacheEntry* currentEntry = (CacheEntry*)iter.GetElement();

                if (!currentEntry->used)
                {
                    if(!WriteEntry( cache, currentEntry, data->cache ))
                    {
                        goto CLEANUP;
                    }

                    amountWritten += SIZE_OF_ENTRY( currentEntry );
                    numEntriesWritten++;
                }
            }

            while (amountWritten < MAX_CACHEFILE_SIZE)
            {
                CacheEntry* entry = LoadNextEntry( data->cache, data );

                if (entry == NULL)
                    break;

                if (!WriteEntry( cache, entry, data->cache ))
                {
                    goto CLEANUP;
                }

                amountWritten += SIZE_OF_ENTRY( entry );
                numEntriesWritten++;
            }
        }

        fWriteSucceeded = TRUE;
    }


    if (!fWriteSucceeded)
    {
        CloseHandle( cache.GetValue() );
        cache.SuppressRelease();
        WszDeleteFile( newFileName );
        goto CLEANUP;
    }

    // End with writing the header.

    header.configFileTime = data->configFileTime;
    header.isSecurityOn = 1;
    header.numEntries = numEntriesWritten;
    header.quickCache = data->header.quickCache;
    header.sizeConfig = sizeConfig;

    if (SetFilePointer( cache, 0, NULL, FILE_BEGIN ) == INVALID_SET_FILE_POINTER)
    {
        // Couldn't move to the beginning of the file
        goto CLEANUP;
    }

    if (WriteFileData( cache, (PBYTE)&header, sizeof( header ) ) != S_OK)
    {
        // Couldn't write header info.
        goto CLEANUP;
    }

    if (sizeConfig != 0)
    {
        if ((data->state & Data::NewConfigFile) != 0)
        {
            if (WriteFileData( cache, data->configBuffer, sizeConfig ) != S_OK)
            {
                goto CLEANUP;
            }
        }
        else
        {
            if (data->configData != NULL)
            {
                if (WriteFileData( cache, data->configData, sizeConfig ) != S_OK)
                {
                    goto CLEANUP;
                }
            }
            else if ((data->state & Data::UsingCacheFile) != 0)
            {
                configBuffer.Assign( new BYTE[sizeConfig] );

                if (SetFilePointer( data->cache, sizeof( CacheHeader ), NULL, FILE_BEGIN ) == INVALID_SET_FILE_POINTER)
                {
                    goto CLEANUP;
                }

                if (ReadFileData( data->cache, configBuffer.GetValue(), sizeConfig ) != S_OK)
                {
                    goto CLEANUP;
                }

                if (WriteFileData( cache, configBuffer.GetValue(), sizeConfig ) != S_OK)
                {
                    goto CLEANUP;
                }
            }
            else
            {
                configBuffer.Assign( new BYTE[sizeConfig] );

                if (SetFilePointer( config, 0, NULL, FILE_BEGIN ) == INVALID_SET_FILE_POINTER)
                {
                    goto CLEANUP;
                }

                if (ReadFileData( config, configBuffer.GetValue(), sizeConfig ) != S_OK)
                {
                    goto CLEANUP;
                }

                if (WriteFileData( cache, configBuffer.GetValue(), sizeConfig ) != S_OK)
                {
                    goto CLEANUP;
                }
            }
        }
    }

    // Flush the file buffers to make sure
    // we get full write through.

    FlushFileBuffers( cache.GetValue() );

    CloseHandle( cache );
    cache.SuppressRelease();
    CloseHandle( data->cache );
    data->cache = INVALID_HANDLE_VALUE;

    // Move the existing file out of the way
    // Note: use MoveFile because we know it will never cross
    // device boundaries.

    // Note: the delete file can fail, but we can't really do anything
    // if it does so just ignore any failures.
    WszDeleteFile( data->cacheFileNameTemp );

    // Try to move the existing cache file out of the way.  However, if we can't
    // then try to delete it.  If it can't be deleted then just bail out.
    if (!WszMoveFile( data->cacheFileName, data->cacheFileNameTemp ) &&
        (!Assembly::FileNotFound(HRESULT_FROM_WIN32(GetLastError()))) &&
        !WszDeleteFile( data->cacheFileName ))
    {
        if (!Assembly::FileNotFound(HRESULT_FROM_WIN32(GetLastError())))
            goto CLEANUP;
    }

    // Move the new file into position

    if (!WszMoveFile( newFileName, data->cacheFileName ))
    {
        goto CLEANUP;
    }

    retval = TRUE;

CLEANUP:
    if (retval)
        cache.SuppressRelease();

    return retval;

}

void QCALLTYPE SecurityConfig::ResetCacheData(INT32 id)
{
    QCALL_CONTRACT;

    BEGIN_QCALL;

    Data* data = (Data*)GetData( id );

    if (data != NULL)
    {
        CrstHolder ch(&dataLock_);

        data->DeleteAllEntries();

        data->oldCacheEntries = new ArrayList;
        data->newCacheEntries = new ArrayList;

        data->header = CacheHeader();
        data->state = (Data::State)(~(Data::CopyCacheFile | Data::UsingCacheFile) & data->state);

        HandleHolder config(WszCreateFile( data->configFileName, GENERIC_READ, GetShareFlags(), NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL ));

        if (config.GetValue() != INVALID_HANDLE_VALUE)
        {
        VERIFY(GetFileTime( config, NULL, NULL, &data->configFileTime ));
        VERIFY(GetFileTime( config, NULL, NULL, &data->header.configFileTime ));
    }
}

    END_QCALL;
}

HRESULT QCALLTYPE SecurityConfig::SaveDataByte(LPCWSTR wszConfigPath, LPCBYTE pbData, DWORD cbData)
{
    QCALL_CONTRACT;

    HRESULT retval = E_FAIL;

    BEGIN_QCALL;

    HandleHolder newFile(INVALID_HANDLE_VALUE);

    int RetryCount;
    DWORD error = 0;
    DWORD fileNameLength = (DWORD) wcslen(wszConfigPath);

    NewArrayHolder<WCHAR> newFileName(new WCHAR[fileNameLength + 5]);
    NewArrayHolder<WCHAR> oldFileName(new WCHAR[fileNameLength + 5]);

    swprintf_s( newFileName.GetValue(), fileNameLength + 5, W("%s%s"), wszConfigPath, W(".new") );
    swprintf_s( oldFileName.GetValue(), fileNameLength + 5, W("%s%s"), wszConfigPath, W(".old") );

    // Create the new file.
    for (RetryCount = 0; RetryCount < 5; RetryCount++) {
        newFile.Assign( WszCreateFile( newFileName, GENERIC_WRITE, 0, NULL, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL ) );
    
        if (newFile != INVALID_HANDLE_VALUE)
            break;
        else
        {
            error = GetLastError();

            if (error == ERROR_PATH_NOT_FOUND)
            {
                // The directory does not exist, iterate through and try to create it.

                WCHAR* currentChar = newFileName;

                // Skip the first backslash

                while (*currentChar != W('\0'))
                {
                    if (*currentChar == W('\\') || *currentChar == W('/'))
                    {
                        currentChar++;
                        break;
                    }
                    currentChar++;
                }

                // Iterate through trying to create each subdirectory.

                while (*currentChar != W('\0'))
                {
                    if (*currentChar == W('\\') || *currentChar == W('/'))
                    {
                        *currentChar = W('\0');

                        if (!WszCreateDirectory( newFileName, NULL ))
                        {
                            error = GetLastError();

                            if (error != ERROR_ACCESS_DENIED && error != ERROR_ALREADY_EXISTS)
                            {
                                goto CLEANUP;
                            }
                        }

                        *currentChar = W('\\');
                    }
                    currentChar++;
                }

                // Try the file creation again
                continue;
            }
        }

        // CreateFile failed.  Sleep a little and retry, in case a
        // virus scanner caused the creation to fail.
        ClrSleepEx(10, FALSE);
    }

    if (newFile == INVALID_HANDLE_VALUE) {
        goto CLEANUP;
    }

    // Write the data into it.
    if ((retval = WriteFileData(newFile.GetValue(), pbData, cbData)) != S_OK)
    {
        // Write failed, destroy the file and bail.
        // Note: if the delete fails, we always do a CREATE_NEW
        // for this file so that should take care of it.  If not
        // we'll fail to write out future cache files.
        CloseHandle( newFile.GetValue() );
        newFile.SuppressRelease();
        WszDeleteFile( newFileName );
        goto CLEANUP;
    }

    if (!FlushFileBuffers(newFile.GetValue()))
    {
        error = GetLastError();
        goto CLEANUP;
    }

    CloseHandle( newFile.GetValue() );
    newFile.SuppressRelease();

    // Move the existing file out of the way
    if (!WszMoveFileEx( wszConfigPath, oldFileName, MOVEFILE_REPLACE_EXISTING | MOVEFILE_COPY_ALLOWED ))
    {
        // If move fails for a reason other than not being able to find the file, bail out.
        // Also, if the old file didn't exist, we have no need to delete it.
        HRESULT hrMove = HRESULT_FROM_WIN32(GetLastError()); 
        if (!Assembly::FileNotFound(hrMove))
        {
            retval = hrMove;
            WszDeleteFile(wszConfigPath);
                goto CLEANUP;
        }
    }

    // Move the new file into position

    if (!WszMoveFileEx( newFileName, wszConfigPath, MOVEFILE_REPLACE_EXISTING | MOVEFILE_COPY_ALLOWED ))
    {
        error = GetLastError();
        goto CLEANUP;
    }

    retval = S_OK;

CLEANUP:
    if (retval == E_FAIL && error != 0)
        retval = HRESULT_FROM_WIN32(error);

    END_QCALL;

    return retval;
}

BOOL QCALLTYPE SecurityConfig::RecoverData(INT32 id)
    {
    QCALL_CONTRACT;

    BOOL retval = FALSE;

    BEGIN_QCALL;

    Data* data = (Data*)GetData( id );

    if (data == NULL)
        goto CLEANUP;

    {
        DWORD fileNameLength = (DWORD)wcslen( data->configFileName );

        NewArrayHolder<WCHAR> tempFileName(new WCHAR[fileNameLength + 10]);
        NewArrayHolder<WCHAR> oldFileName(new WCHAR[fileNameLength + 5]);

        swprintf_s( tempFileName.GetValue(), fileNameLength + 10, W("%s%s"), data->configFileName, W(".old.temp") );
        swprintf_s( oldFileName.GetValue(), fileNameLength + 5, W("%s%s"), data->configFileName, W(".old") );

        HandleHolder oldFile(WszCreateFile( oldFileName, 0, 0, NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL ));

        if (oldFile.GetValue() == INVALID_HANDLE_VALUE)
        {
            goto CLEANUP;
        }

        CloseHandle( oldFile );
        oldFile.SuppressRelease();

        if (!WszMoveFile( data->configFileName, tempFileName ))
        {
            goto CLEANUP;
        }

        if (!WszMoveFile( oldFileName, data->configFileName ))
        {
            goto CLEANUP;
        }

        if (!WszMoveFile( tempFileName, oldFileName ))
        {
            goto CLEANUP;
        }
    }

    // We need to do some work to reset the unmanaged data object
    // so that the managed side of things behaves like you'd expect.
    // This basically means cleaning up the open resources and
    // doing the work to init on a different set of files.

    data->Reset();
    InitData( data, FALSE );

    retval = TRUE;

CLEANUP:
    END_QCALL;

    return retval;
}

BOOL SecurityConfig::GetQuickCacheEntry( INT32 id, QuickCacheEntryType type )
{
    CONTRACTL
    {
        NOTHROW;
        GC_NOTRIGGER;
        MODE_ANY;
    }
    CONTRACTL_END

    //
    // If there is no config file for this level, then we'll assume the default
    // security policy is in effect. This could happen for example if there is
    // user profile loaded or if the config file is not present.
    //

    Data* data = (Data*)GetData( id );
    if (data == NULL || ((data->state & Data::UsingConfigFile) == 0))
        return (type == FullTrustZoneMyComputer); // MyComputer gets FT by default.

    if ((data->state & Data::UsingCacheFile) == 0)
        return FALSE;

    return (data->header.quickCache & type);
}

void QCALLTYPE SecurityConfig::SetQuickCache(INT32 id, QuickCacheEntryType type)
{
    QCALL_CONTRACT;

    BEGIN_QCALL;

    Data* data = (Data*)GetData( id );

    if (data != NULL && (DWORD) type != data->header.quickCache)
    {
        CrstHolder ch(&dataLock_);

        data->state = (Data::State)(Data::CacheUpdated | data->state);
        data->header.quickCache = type;
    }

    END_QCALL;
}

static HANDLE OpenCacheFile( Data* data )
{
    STANDARD_VM_CONTRACT;

    CrstHolder ch(&SecurityConfig::dataLock_);

    if (data->cache != INVALID_HANDLE_VALUE)
        return data->cache;

    _ASSERTE( FALSE && "This case should never happen" );

    data->cache = WszCreateFile( data->cacheFileName, GENERIC_READ | GENERIC_WRITE, FILE_SHARE_READ | FILE_SHARE_WRITE, NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL );
    if (data->cache == INVALID_HANDLE_VALUE)
        return NULL;

    // Check whether the cache has changed since we first looked at it.
    // If it has but the config file hasn't, then we need to start fresh.
    // However, if the config file has changed then we have to ignore it.

    if (CacheOutOfDate( &data->cacheFileTime, data->cache, NULL ))
    {
        if (CacheOutOfDate( &data->configFileTime, data->configFileName, NULL ))
            return NULL;

        if (ReadFileData( data->cache, (BYTE*)&data->header, sizeof( CacheHeader ) ) != S_OK)
            return NULL;

        data->cacheCurrentPosition = sizeof( CacheHeader );

        if (data->oldCacheEntries != NULL)
        {
            ArrayList::Iterator iter = data->oldCacheEntries->Iterate();
            while (iter.Next())
            {
                delete (CacheEntry*)iter.GetElement();
            }
            delete data->oldCacheEntries;
            data->oldCacheEntries = new ArrayList();
        }
    }

    return data->cache;
}

static BYTE* CompareEntry( CacheEntry* entry, DWORD numEvidence, DWORD evidenceSize, LPCBYTE evidenceBlock, HANDLE cache, DWORD* size)
{
    STANDARD_VM_CONTRACT;

    _ASSERTE (entry);

    if (entry->header.numItemsInKey == numEvidence &&
        entry->header.keySize == evidenceSize)
    {
        if (entry->key == NULL)
        {
            // We were lazy in reading the entry. Read the key now.
            entry->key = new BYTE[entry->header.keySize];

            _ASSERTE (cache != INVALID_HANDLE_VALUE);

            if (SetFilePointer( cache, entry->cachePosition, NULL, FILE_BEGIN ) == INVALID_SET_FILE_POINTER)
                return NULL;

            if (ReadFileData( cache, entry->key, entry->header.keySize ) != S_OK)
                return NULL;

            entry->cachePosition += entry->header.keySize;
        }

        _ASSERTE (entry->key);

        if (memcmp( entry->key, evidenceBlock, entry->header.keySize ) == 0)
        {
            if (entry->data == NULL)
            {
                // We were lazy in reading the entry. Read the data also.
                entry->data = new BYTE[entry->header.dataSize];

                if (SetFilePointer( cache, entry->cachePosition, NULL, FILE_BEGIN ) == INVALID_SET_FILE_POINTER)
                    return NULL;

                if (ReadFileData( cache, entry->data, entry->header.dataSize ) != S_OK)
                    return NULL;

                entry->cachePosition += entry->header.dataSize;
            }

            entry->used = TRUE;
            *size = entry->header.dataSize;

            return entry->data;
        }
    }
    return NULL;
}

BOOL QCALLTYPE SecurityConfig::GetCacheEntry(INT32 id, DWORD numEvidence, LPCBYTE pEvidence, DWORD cbEvidence, QCall::ObjectHandleOnStack retPolicy)
{
    QCALL_CONTRACT;

    BOOL success = FALSE;

    BEGIN_QCALL;

    HANDLE cache = INVALID_HANDLE_VALUE;

    BYTE* retval = NULL;
    DWORD size = (DWORD) -1;

    Data* data = (Data*)GetData( id );

    if (data == NULL)
    {
        goto CLEANUP;
    }

    {

        ArrayList::Iterator iter;

        if ((data->state & Data::UsingCacheFile) == 0)
        {
            // We know we don't have anything in the config file, so
            // let's just look through the new entries to make sure we
            // aren't getting any repeats.

            // Then try the existing new entries

            iter = data->newCacheEntries->Iterate();

            while (iter.Next())
            {
                // newCacheEntries do not need the cache file so pass in NULL.
                retval = CompareEntry( (CacheEntry*)iter.GetElement(), numEvidence, cbEvidence, pEvidence, NULL, &size );

                if (retval != NULL)
                {
                    success = TRUE;
                    goto CLEANUP;
                }
            }

            goto CLEANUP;
        }

        // Its possible that the old entries were not read in completely
        // so we keep the cache file open before iterating through the
        // old entries.

        cache = OpenCacheFile( data );

        if ( cache == NULL )
        {
            goto CLEANUP;
        }

        // First, iterator over the old entries

        {
            CrstHolder ch(&dataLock_);

            iter = data->oldCacheEntries->Iterate();
            while (iter.Next())
            {
                retval = CompareEntry( (CacheEntry*)iter.GetElement(), numEvidence, cbEvidence, pEvidence, cache, &size );
                if (retval != NULL)
                {
                    success = TRUE;
                    goto CLEANUP;
                }
            }

            // LockHolder goes out of scope here
        }

        // Then try the existing new entries
        iter = data->newCacheEntries->Iterate();
        while (iter.Next())
        {
            // newCacheEntries do not need the cache file so pass in NULL.
            retval = CompareEntry( (CacheEntry*)iter.GetElement(), numEvidence, cbEvidence, pEvidence, NULL, &size );
            if (retval != NULL)
            {
                success = TRUE;
                goto CLEANUP;
            }
        }

        // Finally, try loading existing entries from the file

        {
            CrstHolder ch(&dataLock_);

            if (SetFilePointer( cache, data->cacheCurrentPosition, NULL, FILE_BEGIN ) == INVALID_SET_FILE_POINTER)
            {
                goto CLEANUP;
            }

            do
            {
                CacheEntry* entry = LoadNextEntry( cache, data );
                if (entry == NULL)
                {
                    data->state = (Data::State)(Data::CacheExhausted | data->state);
                    break;
                }

                retval = CompareEntry( entry, numEvidence, cbEvidence, pEvidence, cache, &size );
                if (retval != NULL)
                {
                    success = TRUE;
                    break;
                }
            } while (TRUE);

            // LockHolder goes out of scope here
        }
    }

CLEANUP:
    if (success && retval != NULL)
    {
        _ASSERTE( size != (DWORD) -1 );
        retPolicy.SetByteArray(retval, size);
    }

    END_QCALL;

    return success;
}

void QCALLTYPE SecurityConfig::AddCacheEntry(INT32 id, DWORD numEvidence, LPCBYTE pEvidence, DWORD cbEvidence, LPCBYTE pPolicy, DWORD cbPolicy)
{
    QCALL_CONTRACT;

    BEGIN_QCALL;

    Data* data = (Data*)GetData( id );

    DWORD sizeOfEntry = 0;
    NewHolder<CacheEntry> entry;

    if (data == NULL)
    {
        goto lExit;
    }

    // In order to limit how large a long running app can become,
    // we limit the total memory held by the new cache entries list.
    // For now this limit corresponds with how large the max cache file
    // can be.

    sizeOfEntry = cbEvidence + cbPolicy + sizeof( CacheEntryHeader );

    if (data->newEntriesSize + sizeOfEntry >= MAX_CACHEFILE_SIZE)
    {
        goto lExit;
    }

    entry = new CacheEntry();

    entry->header.numItemsInKey = numEvidence;
    entry->header.keySize = cbEvidence;
    entry->header.dataSize = cbPolicy;

    entry->key = new BYTE[entry->header.keySize];
    entry->data = new BYTE[entry->header.dataSize];

    memcpyNoGCRefs(entry->key, pEvidence, cbEvidence);
    memcpyNoGCRefs(entry->data, pPolicy, cbPolicy);

    {
        CrstHolder ch(&dataLock_);

        // Check the size again to handle the race.
        if (data->newEntriesSize + sizeOfEntry < MAX_CACHEFILE_SIZE)
        {
            data->state = (Data::State)(Data::CacheUpdated | data->state);
            IfFailThrow(data->newCacheEntries->Append( entry.GetValue() ));
            entry.SuppressRelease();
            data->newEntriesSize += sizeOfEntry;
        }
    }

lExit: ;

    END_QCALL;
}

ArrayListStatic SecurityConfig::entries_;
CrstStatic      SecurityConfig::dataLock_;

void SecurityConfig::Init( void )
{
    CONTRACTL
    {
        THROWS;
        GC_NOTRIGGER;
        MODE_ANY;
    }
    CONTRACTL_END

    dataLock_.Init(CrstSecurityPolicyCache);
    entries_.Init();
}

void SecurityConfig::Cleanup( void )
{
    CONTRACTL
    {
        NOTHROW;
        GC_TRIGGERS;
        MODE_ANY;
    }
    CONTRACTL_END

    ArrayList::Iterator iter = entries_.Iterate();

    GCX_PREEMP();

    CrstHolder ch(&dataLock_);

    while (iter.Next())
    {
        ((Data*) iter.GetElement())->Cleanup();
    }
}

void SecurityConfig::Delete( void )
{
    CONTRACTL
    {
        NOTHROW;
        GC_NOTRIGGER;
        MODE_ANY;
    }
    CONTRACTL_END

    ArrayList::Iterator iter = entries_.Iterate();

    while (iter.Next())
    {
        delete (Data*) iter.GetElement();
    }

    entries_.Destroy();
    dataLock_.Destroy();
}

void QCALLTYPE SecurityConfig::_GetMachineDirectory(QCall::StringHandleOnStack retDirectory)
{
    QCALL_CONTRACT;

    BEGIN_QCALL;

    WCHAR machine[MAX_LONGPATH];

    HRESULT hr = GetMachineDirectory(machine, MAX_LONGPATH);
    if (FAILED(hr))
        ThrowHR(hr);

    retDirectory.Set(machine);

    END_QCALL;
}

void QCALLTYPE SecurityConfig::_GetUserDirectory(QCall::StringHandleOnStack retDirectory)
{
    QCALL_CONTRACT;

    BEGIN_QCALL;

    WCHAR user[MAX_LONGPATH];

    BOOL result = GetUserDirectory(user, MAX_LONGPATH);
    if (result)
        retDirectory.Set(user);

    END_QCALL;
}

HRESULT SecurityConfig::GetMachineDirectory(__out_ecount(bufferCount) __out_z WCHAR* buffer, size_t bufferCount)
{
    STANDARD_VM_CONTRACT;

    HRESULT hr;

    DWORD length = (DWORD)bufferCount;
    hr = GetInternalSystemDirectory(buffer, &length);
    if (FAILED(hr))
        return hr;
    
    // Make sure we have enough buffer to concat the string.
    // Note the length including the terminating zero. 
    if((bufferCount - wcslen(buffer) - 1) < wcslen(W("config\\")))
        return HRESULT_FROM_WIN32(ERROR_INSUFFICIENT_BUFFER);

    wcscat_s(buffer, bufferCount, W("config\\"));

    return S_OK;
}

BOOL SecurityConfig::GetVIUserDirectory(__out_ecount(bufferCount) __out_z WCHAR* buffer, size_t bufferCount)
{
    STANDARD_VM_CONTRACT;

    WCHAR scratchBuffer[MAX_LONGPATH];
    BOOL retval = FALSE;

    DWORD size = MAX_LONGPATH;

    if (!GetUserDir(buffer, bufferCount, TRUE))
        goto CLEANUP;

    wcscpy_s( scratchBuffer, COUNTOF(scratchBuffer), W("\\Microsoft\\CLR Security Config\\") );

    if (bufferCount < wcslen( buffer ) + wcslen( scratchBuffer ) + 1)
    {
        goto CLEANUP;
    }

    wcscat_s( buffer, bufferCount, scratchBuffer );

    retval = TRUE;

CLEANUP:
    return retval;
}

BOOL SecurityConfig::GetUserDirectory(__out_ecount(bufferCount) __out_z WCHAR* buffer, size_t bufferCount)
{
    STANDARD_VM_CONTRACT;

    StackSString ssScratchBuffer;
    BOOL retval = FALSE;

    WCHAR* wszScratchBuffer = ssScratchBuffer.OpenUnicodeBuffer( (COUNT_T)bufferCount );
    retval = GetVIUserDirectory(wszScratchBuffer, bufferCount);
    ssScratchBuffer.CloseBuffer( (COUNT_T)wcslen( wszScratchBuffer ) );

    if (!retval)
        return retval;

    ssScratchBuffer.Append( W("v") );
    ssScratchBuffer.Append( VER_PRODUCTVERSION_NO_QFE_STR_L );
    ssScratchBuffer.Append( W("\\") );

#ifdef _WIN64
    ssScratchBuffer.Append( W("64bit\\") );
#endif // _WIN64

    if (ssScratchBuffer.GetCount() + 1 > bufferCount)
        return FALSE;

    wcscpy_s( buffer, bufferCount, ssScratchBuffer.GetUnicode() );

    return TRUE;
}

BOOL QCALLTYPE SecurityConfig::WriteToEventLog(LPCWSTR wszMessage)
{
    QCALL_CONTRACT;

    BOOL retVal = FALSE;

    BEGIN_QCALL;

    retVal = ReportEventCLR(
                EVENTLOG_WARNING_TYPE,      // event type 
                0,                          // category 
                (DWORD)1000,                // event identifier 
                NULL,                       // no user security identifier 
                &StackSString(wszMessage)); // message to log

    END_QCALL

    return retVal;
}

#ifdef _DEBUG
HRESULT QCALLTYPE SecurityConfig::DebugOut(LPCWSTR wszFileName, LPCWSTR wszMessage)
{
    HRESULT retVal = E_FAIL;

    QCALL_CONTRACT;

    BEGIN_QCALL;

    HandleHolder file(WszCreateFile( wszFileName, GENERIC_WRITE, 0, NULL, OPEN_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL ));

    if (file == INVALID_HANDLE_VALUE)
    {
        goto lExit;
    }

    SetFilePointer( file, 0, NULL, FILE_END );

    DWORD cbMessage;
    DWORD cbWritten;

    cbMessage = (DWORD)wcslen(wszMessage) * sizeof(WCHAR);
    if (!WriteFile( file, wszMessage, cbMessage, &cbWritten, NULL ))
    {
        goto lExit;
    }

    if (cbMessage != cbWritten)
    {
        goto lExit;
    }

    retVal = S_OK;

lExit: ;
    END_QCALL;

    return retVal;
}
#endif

#endif // FEATURE_CAS_POLICY