A
download comdynamic.cpp
Language: C++
Copyright: (c) 2006 Microsoft Corporation. All rights reserved.
LOC: 2044
Project Info
Shared Source Common Language Infrastructure(sscli20)
Server: Shared Source Common Language Infrastructure
Type: filesystem
...sscli20\sscli20\clr\src\vm\
   appdomain.cpp
   appdomain.hpp
   appdomain.inl
   appdomainhelper.cpp
   appdomainhelper.h
   appdomainnative.cpp
   appdomainnative.hpp
   appdomainstack.cpp
   appdomainstack.h
   appdomainstack.inl
   argslot.h
   array.cpp
   array.h
   assembly.cpp
   assembly.hpp
   assemblyname.cpp
   assemblyname.hpp
   assemblynative.cpp
   assemblynative.hpp
   assemblysink.cpp
   assemblysink.h
   assemblyspec.cpp
   assemblyspec.hpp
   binder.cpp
   binder.h
   cachelinealloc.cpp
   cachelinealloc.h
   ceeload.cpp
   ceeload.h
   ceeload.inl
   ceemain.cpp
   ceemain.h
   certificatecache.cpp
   certificatecache.h
   cgensys.h
   class.cpp
   class.h
   class.inl
   classloadlevel.h
   classnames.h
   clrex.cpp
   clrex.h
   clsload.cpp
   clsload.hpp
   clsload.inl
   codeman.cpp
   codeman.h
   codeman.inl
   comarrayhelpers.cpp
   comarrayhelpers.h
   comarrayinfo.cpp
   comarrayinfo.h
   comcallablewrapper.cpp
   comcallablewrapper.h
   comcurrency.cpp
   comcurrency.h
   comdatetime.cpp
   comdatetime.h
   comdecimal.cpp
   comdecimal.h
   comdelegate.cpp
   comdelegate.h
   comdynamic.cpp
   comdynamic.h
   comisolatedstorage.cpp
   comisolatedstorage.h
   commemoryfailpoint.cpp
   commemoryfailpoint.h
   commethodrental.cpp
   commethodrental.h
   commodule.cpp
   commodule.h
   common.cpp
   common.h
   comnumber.cpp
   comnumber.h
   comobject.cpp
   comobject.h
   comreflectioncache.hpp
   comreflectioncommon.cpp
   comreflectioncommon.h
   comstreams.cpp
   comstreams.h
   comstring.cpp
   comstring.h
   comstringbuffer.cpp
   comstringbuffer.h
   comstringcommon.h
   comsynchronizable.cpp
   comsynchronizable.h
   comsystem.cpp
   comsystem.h
   comthreadpool.cpp
   comthreadpool.h
   comutilnative.cpp
   comutilnative.h
   comvarargs.cpp
   comvarargs.h
   comvariant.cpp
   comvariant.h
   comwaithandle.cpp
   comwaithandle.h
   confighelper.cpp
   confighelper.h
   ...inedexecutionregion.cpp
   ...rainedexecutionregion.h
   context.h
   contexts.cpp
   contractimpl.cpp
   contractimpl.h
   corhost.cpp
   crossdomaincalls.cpp
   crossdomaincalls.h
   crst.cpp
   crst.h
   cryptapis.h
   ctxtcall.h
   customattribute.cpp
   customattribute.h
   custommarshalerinfo.cpp
   custommarshalerinfo.h
   dbginterface.h
   debugdebugger.cpp
   debugdebugger.h
   debughelp.cpp
   debuginfostore.cpp
   debuginfostore.h
   decodemd.cpp
   decodemd.h
   delegateinfo.h
   dllimport.cpp
   dllimport.h
   dllimportcallback.cpp
   dllimportcallback.h
   domainfile.cpp
   domainfile.h
   domainfile.inl
   dynamicmethod.cpp
   dynamicmethod.h
   ecall.cpp
   ecall.h
   ecmakey.h
   eecallconv.h
   eeconfig.cpp
   eeconfig.h
   eeconfigfactory.cpp
   eeconfigfactory.h
   eecontract.cpp
   eecontract.h
   eecontract.inl
   eedbginterface.h
   eedbginterfaceimpl.cpp
   eedbginterfaceimpl.h
   eedbginterfaceimpl.inl
   eehash.cpp
   eehash.h
   eemessagebox.cpp
   eemessagebox.h
   eepolicy.cpp
   eepolicy.h
   eeprofinterfaces.h
   eeprofinterfaces.inl
   ...rofinterfacewrapper.inl
   eetwain.cpp
   encee.h
   eventstore.cpp
   eventstore.hpp
   excep.cpp
   excep.h
   exceptmacros.h
   exinfo.cpp
   exinfo.h
   exstate.cpp
   exstate.h
   exstatecommon.h
   fcall.cpp
   fcall.h
   field.cpp
   field.h
   fieldmarshaler.cpp
   fieldmarshaler.h
   fjit_eetwain.cpp
   fjit_eetwain.h
   fptrstubs.cpp
   fptrstubs.h
   frames.cpp
   frames.h
   fusionbind.cpp
   fusioninit.cpp
   fusionsink.cpp
   fusionwrap.cpp
   fusionwrap.h
   gc.h
   gccommon.cpp
   gcdecode.cpp
   gcdesc.h
   gcee.cpp
   gceesvr.cpp
   gceewks.cpp
   gchost.cpp
   gcimpl.h
   gcscan.cpp
   gcscan.h
   gcsmp.cpp
   gcsmppriv.h
   gcsvr.cpp
   gcwks.cpp
   genericdict.cpp
   genericdict.h
   generics.cpp
   generics.h
   genmeth.cpp
   gmheap.cpp
   gmheap.hpp
   gms.h
   h2inc.pl
   handletable.cpp
   handletable.h
   handletable.inl
   handletablecache.cpp
   handletablecore.cpp
   handletablepriv.h
   handletablescan.cpp
   hash.cpp
   hash.h
   hostexecutioncontext.cpp
   hostexecutioncontext.h
   hosting.cpp
   hosting.h
   ibclogger.h
   ildump.h
   ilmarshalers.cpp
   ilmarshalers.h
   ilstubcache.cpp
   ilstubcache.h
   ilstubresolver.cpp
   ilstubresolver.h
   instmethhash.cpp
   instmethhash.h
   interopconverter.cpp
   interopconverter.h
   interoputil.cpp
   interoputil.h
   ...lidoverlappedwrappers.h
   invokeutil.cpp
   invokeutil.h
   jithelpers.cpp
   jitinterface.cpp
   jitinterface.h
   jitinterfacegen.cpp
   list.cpp
   list.h
   listlock.cpp
   listlock.h
   listlock.inl
   makefile.inc
   managedmdimport.cpp
   managedmdimport.hpp
   marshaler.h
   marshalnative.cpp
   marshalnative.h
   mdaassistants.h
   mdaassistantsptr.h
   memberload.cpp
   memberload.h
   message.cpp
   message.h
   metasig.h
   method.cpp
   method.hpp
   method.inl
   methodimpl.cpp
   methodimpl.h
   methoditer.cpp
   methoditer.h
   methodtable.cpp
   methodtable.h
   methodtable.inl
   ml.cpp
   ml.h
   mlcache.cpp
   mlcache.h
   mlgen.cpp
   mlgen.h
   mlinfo.cpp
   mlinfo.h
   mlopdef.h
   mscorlib.h
   mtypes.h
   namespace.h
   nativeoverlapped.cpp
   nativeoverlapped.h
   newcompressedstack.cpp
   newcompressedstack.h
   nsenums.h
   object.cpp
   object.h
   object.inl
   objectclone.cpp
   objectclone.h
   objecthandle.cpp
   objecthandle.h
   objectlist.cpp
   objectlist.h
   olevariant.cpp
   olevariant.h
   pefile.cpp
   pefile.h
   pefile.inl
   peimage.cpp
   peimage.h
   peimage.inl
   peimagelayout.cpp
   peimagelayout.h
   peimagelayout.inl
   pendingload.cpp
   pendingload.h
   precode.cpp
   precode.h
   prestub.cpp
   proftoeeinterfaceimpl.cpp
   proftoeeinterfaceimpl.h
   reflectclasswriter.cpp
   reflectclasswriter.h
   reflectioninvocation.cpp
   reflectioninvocation.h
   remoting.cpp
   remoting.h
   rexcep.h
   runtimeexceptionkind.h
   runtimehandles.cpp
   runtimehandles.h
   rwlock.cpp
   rwlock.h
   safehandle.cpp
   security.h
   security.inl
   securityattributes.cpp
   securityattributes.h
   securityconfig.cpp
   securityconfig.h
   securitydeclarative.cpp
   securitydeclarative.h
   securitydescriptor.cpp
   securitydescriptor.h
   ...descriptorappdomain.cpp
   ...tydescriptorappdomain.h
   ...ydescriptorassembly.cpp
   ...itydescriptorassembly.h
   securityhostprotection.cpp
   securityhostprotection.h
   securityimperative.cpp
   securityimperative.h
   securitymeta.cpp
   securitymeta.h
   securitypolicy.cpp
   securitypolicy.h
   securitystackwalk.cpp
   securitystackwalk.h
   ...transparentassembly.cpp
   ...tytransparentassembly.h
   sigformat.cpp
   sigformat.h
   siginfo.cpp
   siginfo.hpp
   simplerwlock.cpp
   simplerwlock.hpp
   sourceline.cpp
   sourceline.h
   sources.dac
   sources.inc
   specialstatics.h
   spinlock.cpp
   spinlock.h
   stackbuildersink.cpp
   stackbuildersink.h
   stackcompressor.cpp
   stackcompressor.h
   stackingallocator.cpp
   stackingallocator.h
   stackprobe.h
   stackprobe.inl
   stackwalk.cpp
   stackwalk.h
   stackwalktypes.h
   stringliteralmap.cpp
   stringliteralmap.h
   strongname.cpp
   stubgen.h
   stublink.cpp
   stublink.h
   stublink.inl
   stubmgr.cpp
   stubmgr.h
   syncblk.cpp
   syncblk.h
   syncblk.inl
   syncclean.cpp
   syncclean.hpp
   synch.cpp
   synch.h
   ...zationcontextnative.cpp
   ...nizationcontextnative.h
   testhookmgr.cpp
   testhookmgr.h
   thekey.h
   threads.cpp
   threads.h
   threads.inl
   tokeniter.cpp
   tokeniter.hpp
   typectxt.cpp
   typectxt.h
   typedesc.cpp
   typedesc.h
   typedesc.inl
   typehandle.cpp
   typehandle.h
   typehandle.inl
   typehash.cpp
   typehash.h
   typekey.h
   typeparse.cpp
   typeparse.h
   typestring.cpp
   typestring.h
   umthunkhash.cpp
   umthunkhash.h
   util.cpp
   util.hpp
   validator.cpp
   vars.cpp
   vars.hpp
   verifier.cpp
   verifier.hpp
   veropcodes.hpp
   vertable.h
   virtualcallstub.cpp
   virtualcallstub.h
   vmholder.h
   win32threadpool.cpp
   win32threadpool.h
   wrappers.h

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
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
// ==++==
// 
//   
//    Copyright (c) 2006 Microsoft Corporation.  All rights reserved.
//   
//    The use and distribution terms for this software are contained in the file
//    named license.txt, which can be found in the root of this distribution.
//    By using this software in any fashion, you are agreeing to be bound by the
//    terms of this license.
//   
//    You must not remove this notice, or any other, from this software.
//   
// 
// ==--==
////////////////////////////////////////////////////////////////////////////////
// COMDynamic.h
//  This module defines the native methods that are used for Dynamic IL generation  
//
// Date: November 1998
////////////////////////////////////////////////////////////////////////////////

#include "common.h"
#include "field.h"
#include "comdynamic.h"
#include "commodule.h"
#include "reflectclasswriter.h"
#include "corerror.h"
#include "iceefilegen.h"
#include "comstring.h"
#include "comdatetime.h"  // DateTime <-> OleAut date conversions
#include "strongname.h"
#include "ceefilegenwriter.h"
#include "typekey.h"


//This structure is used in CWSetMethodIL to walk the exceptions.
//It maps to M/R/Reflection/__ExceptionInstance.class
//DO NOT MOVE ANY OF THE FIELDS                                           
#include <pshpack1.h>
typedef struct {
    INT32 m_exceptionType;
    INT32 m_start;
    INT32 m_end;
    INT32 m_filterOffset;
    INT32 m_handle;
    INT32 m_handleEnd;
    INT32 m_type;
} ExceptionInstance;
#include <poppack.h>


//*************************************************************
// 
// Defining a type into metadata of this dynamic module
//
//*************************************************************
FCIMPL8(UINT32, COMDynamicWrite::CWCreateGenParam, 
    Object* refThisUNSAFE, StringObject* strFullNameUNSAFE, UINT32 tkDecl, UINT32 position, UINT32 attributes, I4Array* constraintsUNSAFE, 
    ReflectModuleBaseObject* moduleUNSAFE, INT32 tkTypeDef)
{
    CONTRACTL
    {
        THROWS;
        DISABLED(GC_TRIGGERS);
        MODE_COOPERATIVE;
        SO_TOLERANT;
    }
    CONTRACTL_END;
    
    mdTypeDef           classE = mdTokenNil; 
    
    struct _gc
    {
        OBJECTREF refThis;
        STRINGREF strFullName;
        I4ARRAYREF constraints;
        REFLECTMODULEBASEREF module;
    } gc;
    gc.refThis = (OBJECTREF) refThisUNSAFE;
    gc.strFullName = (STRINGREF) strFullNameUNSAFE;
    gc.constraints = (I4ARRAYREF) constraintsUNSAFE;
    gc.module = (REFLECTMODULEBASEREF) moduleUNSAFE;
    HELPER_METHOD_FRAME_BEGIN_RET_PROTECT(gc);

    HRESULT             hr;
    mdTypeRef           *crConstraints;
    RefClassWriter*     pRCW;   
    DWORD               numConstraints;
    REFLECTMODULEBASEREF pReflect;

    _ASSERTE(gc.module);
    // Get the module for the creator of the ClassWriter
    pReflect = (REFLECTMODULEBASEREF) gc.module;
    _ASSERTE(pReflect);

    Module* pModule = (Module*) pReflect->GetData();
    _ASSERTE(pModule); 

    pRCW = GetReflectionModule(pModule)->GetClassWriter();
    _ASSERTE(pRCW);

    // Set up the Interfaces
    if (gc.constraints!=NULL) {
        unsigned        i = 0;
        numConstraints = gc.constraints->GetNumComponents();
        if (numConstraints >= (UINT32_MAX / sizeof(mdTypeRef)))
            COMPlusThrow(kArgumentException);
        crConstraints = (mdTypeRef *)_alloca((numConstraints + 1) * sizeof(mdTypeRef));
        int *pConstraints = (int *)gc.constraints->GetDataPtr();
        for (i=0; i<numConstraints; i++) {
            crConstraints[i] = pConstraints[i];
        }
        crConstraints[i]=mdTypeRefNil;
    } else {
        crConstraints=NULL;
    }

    if (tkTypeDef == mdTokenNil)
    {
        hr = pRCW->GetEmitter()->DefineGenericParam(
            tkDecl, position, attributes, gc.strFullName->GetBuffer(), 0, crConstraints, &classE);
    }
    else
    {
        // redefine attributes
        hr = pRCW->GetEmitter()->SetGenericParamProps(
            tkTypeDef, (DWORD)-1, gc.strFullName->GetBuffer(), (DWORD)-1, crConstraints);
        classE = tkTypeDef;
    }

    if (FAILED(hr)) {
        _ASSERTE(!"DefineTypeDef Failed");
        COMPlusThrowHR(hr);    
    }

    //-[autocvtepi]-------------------------------------------------------
    HELPER_METHOD_FRAME_END();
    return (INT32)classE;    
}
FCIMPLEND


FCIMPL9(UINT32, COMDynamicWrite::CWCreateClass, 
    Object* refThisUNSAFE, StringObject* strFullNameUNSAFE, UINT32 parent, I4Array* interfacesUNSAFE, 
    UINT32 attr, ReflectModuleBaseObject* moduleUNSAFE, GUID guid, INT32 tkEnclosingType, INT32 tkTypeDef)
{
    CONTRACTL
    {
        THROWS;
        DISABLED(GC_TRIGGERS);
        MODE_COOPERATIVE;
        SO_TOLERANT;
    }
    CONTRACTL_END;
    
    mdTypeDef           classE = mdTokenNil; 
    
    struct _gc
    {
        OBJECTREF refThis;
        STRINGREF strFullName;
        I4ARRAYREF interfaces;
        REFLECTMODULEBASEREF module;
    } gc;
    gc.refThis = (OBJECTREF) refThisUNSAFE;
    gc.strFullName = (STRINGREF) strFullNameUNSAFE;
    gc.interfaces = (I4ARRAYREF) interfacesUNSAFE;
    gc.module = (REFLECTMODULEBASEREF) moduleUNSAFE;
    HELPER_METHOD_FRAME_BEGIN_RET_PROTECT(gc);
    //-[autocvtpro]-------------------------------------------------------

    HRESULT             hr;
    mdTypeRef           *crImplements;
    RefClassWriter*     pRCW;   
    DWORD               numInterfaces;
    GUID *              pGuid=NULL;
    REFLECTMODULEBASEREF pReflect;

    _ASSERTE(gc.module);
    // Get the module for the creator of the ClassWriter
    pReflect = (REFLECTMODULEBASEREF) gc.module;
    _ASSERTE(pReflect);

    Module* pModule = (Module*) pReflect->GetData();
    _ASSERTE(pModule); 

    pRCW = GetReflectionModule(pModule)->GetClassWriter();
    _ASSERTE(pRCW);

    // Set up the Interfaces
    if (gc.interfaces!=NULL) {
        unsigned        i = 0;

        numInterfaces = gc.interfaces->GetNumComponents();
        if (numInterfaces >= (UINT32_MAX / sizeof(mdTypeRef)))
            COMPlusThrow(kArgumentException);
        crImplements = (mdTypeRef *)_alloca((numInterfaces + 1) * sizeof(mdTypeRef));
        int *pImplements = (int *)gc.interfaces->GetDataPtr();
        for (i=0; i<numInterfaces; i++) {
            crImplements[i] = pImplements[i];
        }
        crImplements[i]=mdTypeRefNil;
    } else {
        crImplements=NULL;
    }

    //We know that this space has been allocated because value types cannot be null.
    //If both halves of the guid are 0, we were handed the empty guid and so should
    //pass null to DefineTypeDef.
    //
    if (((INT64 *)(&guid))[0]!=0 && ((INT64 *)(&guid))[1]!=0) {
        pGuid = &guid;
    }

    if (tkTypeDef == mdTokenNil)
    {
        if (RidFromToken(tkEnclosingType))
        {
            // defining nested type
            hr = pRCW->GetEmitter()->DefineNestedType(gc.strFullName->GetBuffer(), 
                                                   attr, 
                                                   parent == 0 ? mdTypeRefNil : parent, 
                                                   crImplements,  
                                                   tkEnclosingType,
                                                   &classE);
        }
        else
        {
            // top level type
            hr = pRCW->GetEmitter()->DefineTypeDef(gc.strFullName->GetBuffer(), 
                                                   attr, 
                                                   parent == 0 ? mdTypeRefNil : parent, 
                                                   crImplements,  
                                                   &classE);
        }
    }
    else
    {
        // redefine attributes
        hr = pRCW->GetEmitter()->SetTypeDefProps(tkTypeDef, 
                                               attr, 
                                               parent == 0 ? mdTypeRefNil : parent, 
                                               crImplements);
        classE = tkTypeDef;
    }


    if (hr == META_S_DUPLICATE) 
    {
        COMPlusThrow(kArgumentException, L"Argument_DuplicateTypeName");
    } 

    if (FAILED(hr)) {
        _ASSERTE(hr == E_OUTOFMEMORY || !"DefineTypeDef Failed");
        COMPlusThrowHR(hr);    
    }

    //-[autocvtepi]-------------------------------------------------------
    HELPER_METHOD_FRAME_END();
    return (INT32)classE;
}
FCIMPLEND

// CWSetParentType
// ClassWriter.InternalSetParentType -- This function will reset the parent class in metadata
FCIMPL3(void, COMDynamicWrite::CWSetParentType, UINT32 tdType, UINT32 tkParent, ReflectModuleBaseObject* moduleUNSAFE)
{
    CONTRACTL
    {
        THROWS;
        DISABLED(GC_TRIGGERS);
        MODE_COOPERATIVE;
        SO_TOLERANT;
    }
    CONTRACTL_END;
    
    REFLECTMODULEBASEREF      pReflect  = (REFLECTMODULEBASEREF) moduleUNSAFE;
    HELPER_METHOD_FRAME_BEGIN_1(pReflect);
    //-[autocvtpro]-------------------------------------------------------

    if (pReflect == NULL) 
        COMPlusThrow(kNullReferenceException, L"NullReference_This");

    HRESULT hr;   

    RefClassWriter* pRCW;   

    Module* pModule = (Module*) pReflect->GetData();
    _ASSERTE(pModule);

    pRCW = GetReflectionModule(pModule)->GetClassWriter(); 
    _ASSERTE(pRCW); 
    
    // Define the Method    
    IfFailGo( pRCW->GetEmitHelper()->SetTypeParent(tdType, tkParent) );
ErrExit:
    if (FAILED(hr)) {   
        _ASSERTE(!"DefineMethod Failed on Method"); 
        COMPlusThrowHR(hr);    
    }   

    //-[autocvtepi]-------------------------------------------------------
    HELPER_METHOD_FRAME_END();
}
FCIMPLEND

// CWAddInterfaceImpl
// ClassWriter.InternalAddInterfaceImpl -- This function will add another interface impl
FCIMPL3(void, COMDynamicWrite::CWAddInterfaceImpl, UINT32 tdType, UINT32 tkInterface, ReflectModuleBaseObject* moduleUNSAFE)
{
    CONTRACTL
    {
        THROWS;
        DISABLED(GC_TRIGGERS);
        MODE_COOPERATIVE;
        SO_TOLERANT;
    }
    CONTRACTL_END;
    
    REFLECTMODULEBASEREF      pReflect  = (REFLECTMODULEBASEREF) moduleUNSAFE;
    HELPER_METHOD_FRAME_BEGIN_1(pReflect);
    //-[autocvtpro]-------------------------------------------------------

    if (pReflect == NULL) 
        COMPlusThrow(kNullReferenceException, L"NullReference_This");

    HRESULT hr;   

    RefClassWriter* pRCW;   

    Module* pModule = (Module*) pReflect->GetData();
    _ASSERTE(pModule);

    pRCW = GetReflectionModule(pModule)->GetClassWriter(); 
    _ASSERTE(pRCW); 
    
    IfFailGo( pRCW->GetEmitHelper()->AddInterfaceImpl(tdType, tkInterface) );

ErrExit:
    if (FAILED(hr)) {   
        _ASSERTE(!"DefineMethod Failed on Method"); 
        COMPlusThrowHR(hr);    
    }   

    //-[autocvtepi]-------------------------------------------------------
    HELPER_METHOD_FRAME_END();
}
FCIMPLEND


// CWCreateMethod
// ClassWriter.CreateMethod -- This function will create a method within the class
FCIMPL4 (UINT32, COMDynamicWrite::CWCreateMethodSpec, UINT32 tkMethod, U1Array* signatureUNSAFE, UINT32 sigLength, ReflectModuleBaseObject* moduleUNSAFE)
{
    CONTRACTL
    {
        THROWS;
        DISABLED(GC_TRIGGERS);
        MODE_COOPERATIVE;
        SO_TOLERANT;
    }
    CONTRACTL_END;
    
    mdMethodDef memberE = mdTokenNil;
    
    struct _gc
    {
        U1ARRAYREF signature;
        REFLECTMODULEBASEREF module;
    } gc;
    gc.signature = (U1ARRAYREF) signatureUNSAFE;
    gc.module = (REFLECTMODULEBASEREF) moduleUNSAFE;
    HELPER_METHOD_FRAME_BEGIN_RET_PROTECT(gc);
    //-[autocvtpro]-------------------------------------------------------

    HRESULT hr; 
    PCCOR_SIGNATURE pcSig;
    
    RefClassWriter* pRCW;   

    REFLECTMODULEBASEREF      pReflect;
    pReflect = (REFLECTMODULEBASEREF) gc.module;
    _ASSERTE(pReflect);
    Module* pModule = (Module*) pReflect->GetData();
    _ASSERTE(pModule);

    pRCW = GetReflectionModule(pModule)->GetClassWriter(); 
    _ASSERTE(pRCW); 
    
    _ASSERTE(gc.signature);
    //Ask module for our signature.
    pcSig = (PCCOR_SIGNATURE)gc.signature->GetDataPtr();

    // Define the Method    
    IfFailGo( pRCW->GetEmitter()->DefineMethodSpec(tkMethod,      //ParentTypeDef
                                          pcSig,                    //Blob value of a COM+ signature
                                          sigLength,            //Size of the signature blob
                                          &memberE) );              //[OUT]methodToken


ErrExit:
    if (FAILED(hr)) 
        COMPlusThrowHR(hr);

    //-[autocvtepi]-------------------------------------------------------
    HELPER_METHOD_FRAME_END();
    return (INT32) memberE;
}
FCIMPLEND

FCIMPL6 (UINT32, COMDynamicWrite::CWCreateMethod, UINT32 handle, StringObject* nameUNSAFE, U1Array* signatureUNSAFE, UINT32 sigLength, UINT32 attributes, ReflectModuleBaseObject* moduleUNSAFE)
{
    CONTRACTL
    {
        THROWS;
        DISABLED(GC_TRIGGERS);
        MODE_COOPERATIVE;
        SO_TOLERANT;
    }
    CONTRACTL_END;
    
    mdMethodDef memberE = mdTokenNil;
    
    struct _gc
    {
        STRINGREF name;
        U1ARRAYREF signature;
        REFLECTMODULEBASEREF module;
    } gc;
    gc.name = (STRINGREF) nameUNSAFE;
    gc.signature = (U1ARRAYREF) signatureUNSAFE;
    gc.module = (REFLECTMODULEBASEREF) moduleUNSAFE;
    HELPER_METHOD_FRAME_BEGIN_RET_PROTECT(gc);
    //-[autocvtpro]-------------------------------------------------------

    HRESULT hr; 
    PCCOR_SIGNATURE pcSig;
    

    _ASSERTE(gc.name);   
    RefClassWriter* pRCW;   

    REFLECTMODULEBASEREF      pReflect;
    pReflect = (REFLECTMODULEBASEREF) gc.module;
    _ASSERTE(pReflect);
    Module* pModule = (Module*) pReflect->GetData();
    _ASSERTE(pModule);

    pRCW = GetReflectionModule(pModule)->GetClassWriter(); 
    _ASSERTE(pRCW); 
    
    _ASSERTE(gc.signature);
    //Ask module for our signature.
    pcSig = (PCCOR_SIGNATURE)gc.signature->GetDataPtr();

    // Define the Method    
    IfFailGo( pRCW->GetEmitter()->DefineMethod(handle,      //ParentTypeDef
                                          gc.name->GetBuffer(), //Name of Member
                                          attributes,               //Member Attributes (public, etc);
                                          pcSig,                    //Blob value of a COM+ signature
                                          sigLength,            //Size of the signature blob
                                          0,                        //Code RVA
                                          miIL | miManaged,         //Implementation Flags is default to managed IL
                                          &memberE) );              //[OUT]methodToken


ErrExit:
    if (FAILED(hr)) 
        COMPlusThrowHR(hr);

    //-[autocvtepi]-------------------------------------------------------
    HELPER_METHOD_FRAME_END();
    return (INT32) memberE;
}
FCIMPLEND

/*================================CWCreateField=================================
**Action:
**Returns:
**Arguments:
**Exceptions:
==============================================================================*/
FCIMPL6(mdFieldDef, COMDynamicWrite::CWCreateField, UINT32 handle, StringObject* nameUNSAFE, U1Array* signatureUNSAFE, UINT32 sigLength, UINT32 attr, ReflectModuleBaseObject* moduleUNSAFE)
{
    CONTRACTL
    {
        THROWS;
        DISABLED(GC_TRIGGERS);
        MODE_COOPERATIVE;
        SO_TOLERANT;
    }
    CONTRACTL_END;
    
    mdFieldDef retVal = mdTokenNil;
    struct _gc
    {
        STRINGREF name;
        U1ARRAYREF signature;
        REFLECTMODULEBASEREF module;
    } gc;
    gc.name = (STRINGREF) nameUNSAFE;
    gc.signature = (U1ARRAYREF) signatureUNSAFE;
    gc.module = (REFLECTMODULEBASEREF) moduleUNSAFE;
    HELPER_METHOD_FRAME_BEGIN_RET_PROTECT(gc);
    //-[autocvtpro]-------------------------------------------------------

    mdFieldDef FieldDef;
    HRESULT                     hr;
    PCCOR_SIGNATURE pcSig;
    RefClassWriter* pRCW;   

    _ASSERTE(gc.signature);

    //Verify the arguments that we can.
    if (gc.name==NULL) {
        COMPlusThrow(kArgumentNullException, L"ArgumentNull_String");
    }

    // Get the RefClassWriter
    REFLECTMODULEBASEREF      pReflect;
    pReflect = (REFLECTMODULEBASEREF) gc.module;
    _ASSERTE(pReflect);

    Module* pModule = (Module*) pReflect->GetData();
    _ASSERTE(pModule);

    pRCW = GetReflectionModule(pModule)->GetClassWriter();
    _ASSERTE(pRCW);

    //Ask module for our signature.
    pcSig = (PCCOR_SIGNATURE)gc.signature->GetDataPtr();

    //Emit the field.
    IfFailGo( pRCW->GetEmitter()->DefineField(handle, 
                                         gc.name->GetBuffer(), attr, pcSig,
                                         sigLength, ELEMENT_TYPE_VOID, NULL,
                                         (ULONG) -1, &FieldDef) );


ErrExit:
    if (FAILED(hr)) 
    {
        _ASSERTE(!"DefineField Failed");
        COMPlusThrowHR(hr);
    }    
    retVal = FieldDef;

    //-[autocvtepi]-------------------------------------------------------
    HELPER_METHOD_FRAME_END();
    return retVal;
}
FCIMPLEND


UINT32 ExceptionHandlingSize(unsigned uNumExceptions, COR_ILMETHOD_SECT_EH_CLAUSE_FAT* pClauses)
{
    CONTRACTL
    {
        THROWS;
        GC_TRIGGERS;
        MODE_ANY;
    }
    CONTRACTL_END;

   if (uNumExceptions == 0)
        return 0;

    // Speculatively compute the size for the slim version of the header.
    S_UINT32 uSmallSize = S_UINT32(sizeof(COR_ILMETHOD_SECT_EH_SMALL)) +
        (S_UINT32(sizeof(IMAGE_COR_ILMETHOD_SECT_EH_CLAUSE_SMALL)) * (S_UINT32(uNumExceptions - 1)));

    if (uSmallSize.IsOverflow())
        COMPlusThrowOM();

    if (uSmallSize.Value() > COR_ILMETHOD_SECT_SMALL_MAX_DATASIZE)
        goto FatCase;

    // Check whether any of the clauses won't fit in the slim case.
    for (UINT32 i = 0; i < uNumExceptions; i++) {
        COR_ILMETHOD_SECT_EH_CLAUSE_FAT* pFatClause = (COR_ILMETHOD_SECT_EH_CLAUSE_FAT*)&pClauses[i];
        if (pFatClause->GetTryOffset() > 0xFFFF ||
            pFatClause->GetTryLength() > 0xFF ||
            pFatClause->GetHandlerOffset() > 0xFFFF ||
            pFatClause->GetHandlerLength() > 0xFF) {
            goto FatCase;
        }
    }

    _ASSERTE(uSmallSize.Value() == COR_ILMETHOD_SECT_EH::Size(uNumExceptions, pClauses));
    return uSmallSize.Value();

 FatCase:
    S_UINT32 uFatSize = S_UINT32(sizeof(COR_ILMETHOD_SECT_EH_FAT)) +
        (S_UINT32(sizeof(IMAGE_COR_ILMETHOD_SECT_EH_CLAUSE_FAT)) * (S_UINT32(uNumExceptions - 1)));

    if (uFatSize.IsOverflow())
        COMPlusThrowOM();

    _ASSERTE(uFatSize.Value() == COR_ILMETHOD_SECT_EH::Size(uNumExceptions, pClauses));
    return uFatSize.Value();
}


// CWSetMethodIL
// ClassWriter.InternalSetMethodIL -- This function will create a method within the class
FCIMPL11(void, COMDynamicWrite::CWSetMethodIL,
                                        UINT32 handle,
                                        CLR_BOOL isInitLocal,
                                        U1Array* bodyUNSAFE,
                                        U1Array* localSigUNSAFE,
                                        UINT32 sigLength,
                                        UINT32 maxStackSize,
                                        UINT32 numExceptions,
                                        PTRArray* exceptionsUNSAFE,
                                        I4Array* tokenFixupsUNSAFE,
                                        I4Array* rvaFixupsUNSAFE,
                                        ReflectModuleBaseObject* moduleUNSAFE)
{
    CONTRACTL
    {
        THROWS;
        DISABLED(GC_TRIGGERS);
        MODE_COOPERATIVE;
        SO_TOLERANT;
    }
    CONTRACTL_END;
    
    struct _gc
    {
        U1ARRAYREF body;
        U1ARRAYREF localSig;
        PTRARRAYREF exceptions;
        I4ARRAYREF tokenFixups;
        I4ARRAYREF rvaFixups;
        REFLECTMODULEBASEREF module;
    } gc;
    gc.body = (U1ARRAYREF) bodyUNSAFE;
    gc.localSig = (U1ARRAYREF) localSigUNSAFE;
    gc.exceptions = (PTRARRAYREF) exceptionsUNSAFE;
    gc.tokenFixups = (I4ARRAYREF) tokenFixupsUNSAFE;
    gc.rvaFixups = (I4ARRAYREF) rvaFixupsUNSAFE;
    gc.module = (REFLECTMODULEBASEREF) moduleUNSAFE;
    HELPER_METHOD_FRAME_BEGIN_PROTECT(gc);
    //-[autocvtpro]-------------------------------------------------------

    HRESULT hr;
    HCEESECTION         ilSection;
    INT32               *piRelocs;
    INT32               relocCount=0;
    mdSignature         pmLocalSigToken;

    // Get the RefClassWriter   
    RefClassWriter*     pRCW;   

    REFLECTMODULEBASEREF pReflect;
    
    pReflect = (REFLECTMODULEBASEREF) gc.module;
    _ASSERTE(pReflect);

    Module* pModule = (Module*) pReflect->GetData();
    _ASSERTE(pModule);

    pRCW = GetReflectionModule(pModule)->GetClassWriter();
    _ASSERTE(pRCW);
    _ASSERTE(gc.localSig);

    PCCOR_SIGNATURE pcSig = (PCCOR_SIGNATURE)gc.localSig->GetDataPtr();
    _ASSERTE(*pcSig == IMAGE_CEE_CS_CALLCONV_LOCAL_SIG);

    if (sigLength==2 && pcSig[0]==0 && pcSig[1]==0) 
    { 
        
        //This is an empty local variable sig
        pmLocalSigToken=0;
    } 
    else 
    {
        if (FAILED(hr = pRCW->GetEmitter()->GetTokenFromSig( pcSig, sigLength, &pmLocalSigToken))) 
        {

            COMPlusThrowHR(hr);    
        }
    }

    COR_ILMETHOD_FAT fatHeader; 

    // set fatHeader.Flags to CorILMethod_InitLocals if user wants to zero init the stack frame.
    //
    fatHeader.SetFlags(isInitLocal ? CorILMethod_InitLocals : 0);
    fatHeader.SetMaxStack(maxStackSize);
    fatHeader.SetLocalVarSigTok(pmLocalSigToken);
    fatHeader.SetCodeSize((gc.body!=NULL)?gc.body->GetNumComponents():0);  
    bool moreSections            = (numExceptions != 0);    

    unsigned codeSizeAligned     = fatHeader.GetCodeSize();  
    if (moreSections)   
        codeSizeAligned          = (codeSizeAligned + 3) & ~3;    // to insure EH section aligned 
    unsigned headerSize          = COR_ILMETHOD::Size(&fatHeader, numExceptions != 0);    

    if (numExceptions >= (UINT32_MAX / sizeof(COR_ILMETHOD_SECT_EH_CLAUSE_FAT)) ||
        numExceptions >= (UINT32_MAX / sizeof(ULONG)))
        COMPlusThrow(kArgumentException);

    //Create the exception handlers.
    COR_ILMETHOD_SECT_EH_CLAUSE_FAT* clauses = numExceptions <= 0 ? NULL :
        (COR_ILMETHOD_SECT_EH_CLAUSE_FAT*)_alloca(sizeof(COR_ILMETHOD_SECT_EH_CLAUSE_FAT)*numExceptions);   

    if (numExceptions > 0) 
    {
        _ASSERTE(gc.exceptions); 
        _ASSERTE(gc.exceptions->GetNumComponents() == numExceptions);

        ExceptionInstance *exceptions = (ExceptionInstance *)gc.exceptions->GetDataPtr();
        for (unsigned int i = 0; i < numExceptions; i++) 
        {
            clauses[i].SetFlags((CorExceptionFlag)(exceptions[i].m_type));
            clauses[i].SetTryOffset(exceptions[i].m_start);
            clauses[i].SetTryLength(exceptions[i].m_end - exceptions[i].m_start);
            clauses[i].SetHandlerOffset(exceptions[i].m_handle);
            clauses[i].SetHandlerLength(exceptions[i].m_handleEnd - exceptions[i].m_handle);
            if (exceptions[i].m_type == COR_ILEXCEPTION_CLAUSE_FILTER)
            {
                clauses[i].SetFilterOffset(exceptions[i].m_filterOffset);
            }
            else if (exceptions[i].m_type!=COR_ILEXCEPTION_CLAUSE_FINALLY)
            {
                clauses[i].SetClassToken(exceptions[i].m_exceptionType);
            }
            else
            {
                clauses[i].SetClassToken(mdTypeRefNil);
            }
        }
    }
    
    unsigned ehSize          = ExceptionHandlingSize(numExceptions, clauses);    
    S_UINT32 totalSizeSafe   = S_UINT32(headerSize) + S_UINT32(codeSizeAligned) + S_UINT32(ehSize); 
    if (totalSizeSafe.IsOverflow())
        COMPlusThrowOM();
    UINT32 totalSize = totalSizeSafe.Value();
    ICeeGen* pGen = pRCW->GetCeeGen();
    BYTE* buf = NULL;
    ULONG methodRVA;
    pGen->AllocateMethodBuffer(totalSize, &buf, &methodRVA);    
    if (buf == NULL)
        COMPlusThrowOM();
        
    _ASSERTE(buf != NULL);
    _ASSERTE((((size_t) buf) & 3) == 0);   // header is dword aligned  

#ifdef _DEBUG
    BYTE* endbuf = &buf[totalSize];
#endif

    // Emit the header  
    buf += COR_ILMETHOD::Emit(headerSize, &fatHeader, moreSections, buf);   

    if (fatHeader.GetCodeSize()!=0) {
        memcpy(buf,gc.body->GetDataPtr(), fatHeader.GetCodeSize());
     }
    buf += codeSizeAligned;
        
    // Emit the eh  
    ULONG* ehTypeOffsets = 0;
    if (ehSize > 0) {
        // Allocate space for the the offsets to the TypeTokens in the Exception headers
        // in the IL stream.

        ehTypeOffsets = (ULONG *)_alloca(sizeof(ULONG) * numExceptions);
        
        // Emit the eh.  This will update the array ehTypeOffsets with offsets
        // to Exception type tokens.  The offsets are with reference to the
        // beginning of eh section.
        buf += COR_ILMETHOD_SECT_EH::Emit(ehSize, numExceptions, clauses,
                                          false, buf, ehTypeOffsets);
    }   
    _ASSERTE(buf == endbuf);    

    //Get the IL Section.
    if (FAILED(pGen->GetIlSection(&ilSection))) {
        _ASSERTE(!"Unable to get the .il Section.");
        COMPlusThrow(kArgumentNullException, L"InvalidOperation_InternalState");
    }

    // Token Fixup data...
    ULONG ilOffset = methodRVA + headerSize;

    //Add all of the relocs based on the info which I saved from ILGenerator.
    //Add the RVA Fixups
    if (gc.rvaFixups!=NULL) {
        relocCount = gc.rvaFixups->GetNumComponents();
        piRelocs = (INT32 *)gc.rvaFixups->GetDataPtr();
        for (int i=0; i<relocCount; i++) {
            if (FAILED(pGen->AddSectionReloc(ilSection, piRelocs[i] + ilOffset, ilSection,srRelocAbsolute))) {
                _ASSERTE(!"Unable to add RVA Reloc.");
                COMPlusThrow(kArgumentNullException, L"InvalidOperation_InternalState");
            }
        }
    }

    if (gc.tokenFixups!=NULL) {
        //Add the Token Fixups
        relocCount = gc.tokenFixups->GetNumComponents();
        piRelocs = (INT32 *)gc.tokenFixups->GetDataPtr();
        for (int i=0; i<relocCount; i++) {
            if (FAILED(pGen->AddSectionReloc(ilSection, piRelocs[i] + ilOffset, ilSection,srRelocMapToken))) {
                _ASSERTE(!"Unable to add Token Reloc.");
                COMPlusThrow(kArgumentNullException, L"InvalidOperation_InternalState");
            }
        }
    }

    if (ehTypeOffsets) {
        // Add token fixups for exception type tokens.
        for (unsigned int i=0; i < numExceptions; i++) {
            if (ehTypeOffsets[i] != (ULONG) -1) {
                if (FAILED(pGen->AddSectionReloc(
                            ilSection,
                            ehTypeOffsets[i] + codeSizeAligned + ilOffset,
                            ilSection,srRelocMapToken))) {
                    _ASSERTE(!"Unable to add Exception Type Token Reloc.");
                    COMPlusThrow(kArgumentNullException, L"InvalidOperation_InternalState");
                }
            }
        }
    }

    
    if (fatHeader.GetCodeSize()!=0) {
        DWORD       dwImplFlags;
        //Set the RVA of the method.
        pRCW->GetMDImport()->GetMethodImplProps( handle, NULL, &dwImplFlags );
        dwImplFlags |= miManaged | miIL;
        hr = pRCW->GetEmitter()->SetMethodProps(handle, (DWORD) -1, methodRVA, dwImplFlags);
        if (FAILED(hr)) {
            _ASSERTE(!"SetMethodProps Failed on Method");
            COMPlusThrow(kArgumentNullException, L"InvalidOperation_InternalState");
        }
    }

    //-[autocvtepi]-------------------------------------------------------
    HELPER_METHOD_FRAME_END();
}
FCIMPLEND

// CWTermCreateClass
// ClassWriter.TermCreateClass --
FCIMPL3(Object*, COMDynamicWrite::CWTermCreateClass, Object* refThisUNSAFE, UINT32 handle, ReflectModuleBaseObject* moduleUNSAFE)
{
    CONTRACTL
    {
        THROWS;
        DISABLED(GC_TRIGGERS);
        MODE_COOPERATIVE;
        SO_TOLERANT;
    }
    CONTRACTL_END;
    
    OBJECTREF refRetVal = NULL;
    OBJECTREF refThis = (OBJECTREF) refThisUNSAFE;
    REFLECTMODULEBASEREF module = (REFLECTMODULEBASEREF) moduleUNSAFE;
    HELPER_METHOD_FRAME_BEGIN_RET_ATTRIB_2(Frame::FRAME_ATTR_RETURNOBJ, refThis, module);
    //-[autocvtpro]-------------------------------------------------------

    RefClassWriter*         pRCW;   
    REFLECTMODULEBASEREF    pReflect;
    
    pReflect = (REFLECTMODULEBASEREF) module;
    _ASSERTE(pReflect);

    Module* pModule = (Module*) pReflect->GetData();
    _ASSERTE(pModule);

    pRCW = GetReflectionModule(pModule)->GetClassWriter(); 
    _ASSERTE(pRCW); 

    // Use the same service, regardless of whether we are generating a normal
    // class, or the special class for the module that holds global functions
    // & methods.
    GetReflectionModule(pModule)->AddClass(handle); 

    // manually load the class if it is not the global type
    if (!IsNilToken(handle))
    {
        TypeHandle typeHnd;
        {
            GCX_PREEMP();
            TypeKey typeKey(pModule, handle);
            typeHnd = pModule->GetClassLoader()->LoadTypeHandleForTypeKey(&typeKey, TypeHandle());
        }
        refRetVal = typeHnd.GetManagedClassObject();
    }

    //-[autocvtepi]-------------------------------------------------------
    HELPER_METHOD_FRAME_END();
    return OBJECTREFToObject(refRetVal);
}
FCIMPLEND


/*============================InternalSetPInvokeData============================
**Action:
**Returns:
**Arguments:
**Exceptions:
==============================================================================*/
FCIMPL6(void, COMDynamicWrite::InternalSetPInvokeData, ReflectModuleBaseObject* moduleUNSAFE, StringObject* dllNameUNSAFE, StringObject* functionNameUNSAFE, UINT32 token, UINT32 linkType, UINT32 linkFlags)
{
    CONTRACTL
    {
        THROWS;
        DISABLED(GC_TRIGGERS);
        MODE_COOPERATIVE;
        SO_TOLERANT;
    }
    CONTRACTL_END;
    
    struct _gc
    {
        REFLECTMODULEBASEREF module;
        STRINGREF dllName;
        STRINGREF functionName;
    } gc;
    gc.module = (REFLECTMODULEBASEREF) moduleUNSAFE;
    gc.dllName = (STRINGREF) dllNameUNSAFE;
    gc.functionName = (STRINGREF) functionNameUNSAFE;
    HELPER_METHOD_FRAME_BEGIN_PROTECT(gc);
    //-[autocvtpro]-------------------------------------------------------

    RefClassWriter      *pRCW;
    DWORD               dwMappingFlags = 0;
    mdModuleRef         mrImportDll = mdTokenNil;
    HRESULT             hr;

    _ASSERTE(gc.dllName);

    Module* pModule = (Module *)gc.module->GetData();
    _ASSERTE(pModule);

    pRCW = GetReflectionModule(pModule)->GetClassWriter(); 
    _ASSERTE(pRCW); 

    IfFailGo(pRCW->GetEmitter()->DefineModuleRef(gc.dllName->GetBufferNullable(), &mrImportDll));
    dwMappingFlags = linkType | linkFlags;
    IfFailGo(pRCW->GetEmitter()->DefinePinvokeMap(
        token,                        // the method token 
        dwMappingFlags,                     // the mapping flags
        gc.functionName->GetBuffer(),    // function name
        mrImportDll));

    pRCW->GetEmitter()->SetMethodProps(token, (DWORD) -1, 0x0, miIL);
ErrExit:
    if (FAILED(hr))
    {
        COMPlusThrowHR(hr);    
    }

    //-[autocvtepi]-------------------------------------------------------
    HELPER_METHOD_FRAME_END();
}
FCIMPLEND
    

/*============================CWDefineProperty============================
**Action:
**Returns:
**Arguments:
**Exceptions:
==============================================================================*/
FCIMPL8(UINT32, COMDynamicWrite::CWDefineProperty, ReflectModuleBaseObject* moduleUNSAFE, UINT32 handle, StringObject* nameUNSAFE, UINT32 attr, U1Array* signatureUNSAFE, UINT32 sigLength, UINT32 tkNotifyChanging, UINT32 tkNotifyChanged)
{
    CONTRACTL
    {
        THROWS;
        DISABLED(GC_TRIGGERS);
        MODE_COOPERATIVE;
        SO_TOLERANT;
    }
    CONTRACTL_END;
    
    mdProperty      pr = mdTokenNil; 
    
    struct _gc
    {
        REFLECTMODULEBASEREF module;
        STRINGREF name;
        U1ARRAYREF signature;
    } gc;
    gc.module = (REFLECTMODULEBASEREF) moduleUNSAFE;
    gc.name = (STRINGREF) nameUNSAFE;
    gc.signature = (U1ARRAYREF) signatureUNSAFE;
    HELPER_METHOD_FRAME_BEGIN_RET_PROTECT(gc);
    //-[autocvtpro]-------------------------------------------------------

    HRESULT         hr; 
    PCCOR_SIGNATURE pcSig;
    RefClassWriter* pRCW;   
    REFLECTMODULEBASEREF    pReflect; 
    Module          *pModule;

    // Get the RefClassWriter   
    pReflect = (REFLECTMODULEBASEREF) gc.module;
    _ASSERTE(pReflect);
    
    pModule = (Module*) pReflect->GetData();
    _ASSERTE(pModule);

    pRCW = GetReflectionModule(pModule)->GetClassWriter(); 
    _ASSERTE(pRCW); 
    
    _ASSERTE((gc.signature != NULL) && (gc.name!= NULL));

    //Ask module for our signature.
    pcSig = (PCCOR_SIGNATURE)gc.signature->GetDataPtr();

    // Define the Property
    hr = pRCW->GetEmitter()->DefineProperty(
            handle,                         // ParentTypeDef
            gc.name->GetBuffer(),           // Name of Member
            attr,                     // property Attributes (prDefaultProperty, etc);
            pcSig,                          // Blob value of a COM+ signature
            sigLength,                // Size of the signature blob
            ELEMENT_TYPE_VOID,              // don't specify the default value
            0,                              // no default value
            (ULONG) -1,                     // optional length
            mdMethodDefNil,                 // no setter
            mdMethodDefNil,                 // no getter
            NULL,                           // no other methods
            &pr);

    if (FAILED(hr)) {   
        _ASSERTE(!"DefineProperty Failed on Property"); 
        COMPlusThrowHR(hr);    
    }   

    //-[autocvtepi]-------------------------------------------------------
    HELPER_METHOD_FRAME_END();

    return (INT32)pr;
}
FCIMPLEND



/*============================CWDefineEvent============================
**Action:
**Returns:
**Arguments:
**Exceptions:
==============================================================================*/
FCIMPL5(UINT32, COMDynamicWrite::CWDefineEvent, ReflectModuleBaseObject* moduleUNSAFE, UINT32 handle, StringObject* nameUNSAFE, UINT32 attr, UINT32 eventtype)
{
    CONTRACTL
    {
        THROWS;
        DISABLED(GC_TRIGGERS);
        MODE_COOPERATIVE;
        SO_TOLERANT;
    }
    CONTRACTL_END;
    
    mdProperty      ev = mdTokenNil; 

    
    REFLECTMODULEBASEREF module = (REFLECTMODULEBASEREF) moduleUNSAFE;
    STRINGREF name = (STRINGREF) nameUNSAFE;
    HELPER_METHOD_FRAME_BEGIN_RET_2(module, name);
    //-[autocvtpro]-------------------------------------------------------

    HRESULT         hr; 
    RefClassWriter* pRCW;   
    REFLECTMODULEBASEREF    pReflect; 
    Module          *pModule;


    _ASSERTE(name);   

    // Get the RefClassWriter   
    pReflect = (REFLECTMODULEBASEREF) module;
    _ASSERTE(pReflect);
    
    pModule = (Module*) pReflect->GetData();
    _ASSERTE(pModule);

    pRCW = GetReflectionModule(pModule)->GetClassWriter(); 
    _ASSERTE(pRCW); 
    
    // Define the Event
    hr = pRCW->GetEmitHelper()->DefineEventHelper(
            handle,                 // ParentTypeDef
            name->GetBuffer(),      // Name of Member
            attr,                       // property Attributes (prDefaultProperty, etc);
            eventtype,              // the event type. Can be TypeDef or TypeRef
            &ev);

    if (FAILED(hr)) 
    {   
        _ASSERTE(!"DefineEvent Failed on Event"); 
        COMPlusThrowHR(hr);    
    }   

    //-[autocvtepi]-------------------------------------------------------
    HELPER_METHOD_FRAME_END();

    return (INT32)ev;
}
FCIMPLEND





/*============================CWDefineMethodSemantics============================
**Action:
**Returns:
**Arguments:
**Exceptions:
==============================================================================*/
FCIMPL4(void, COMDynamicWrite::CWDefineMethodSemantics, ReflectModuleBaseObject* moduleUNSAFE, UINT32 association, UINT32 attr, UINT32 method)
{
    CONTRACTL
    {
        THROWS;
        DISABLED(GC_TRIGGERS);
        MODE_COOPERATIVE;
        SO_TOLERANT;
    }
    CONTRACTL_END;
    
    REFLECTMODULEBASEREF module = (REFLECTMODULEBASEREF) moduleUNSAFE;
    HELPER_METHOD_FRAME_BEGIN_1(module);
    //-[autocvtpro]-------------------------------------------------------

    HRESULT         hr; 
    RefClassWriter* pRCW;   
    REFLECTMODULEBASEREF    pReflect; 
    Module          *pModule;

    // Get the RefClassWriter   
    pReflect = (REFLECTMODULEBASEREF) module;
    _ASSERTE(pReflect);
    
    pModule = (Module*) pReflect->GetData();
    _ASSERTE(pModule);

    pRCW = GetReflectionModule(pModule)->GetClassWriter(); 
    _ASSERTE(pRCW); 
    

    // Define the MethodSemantics
    hr = pRCW->GetEmitHelper()->DefineMethodSemanticsHelper(
            association,
            attr,
            method);
    if (FAILED(hr)) 
    {   
        _ASSERTE(!"DefineMethodSemantics Failed on "); 
        COMPlusThrowHR(hr);    
    }   

    //-[autocvtepi]-------------------------------------------------------
    HELPER_METHOD_FRAME_END();
}
FCIMPLEND


/*============================CWSetMethodImpl============================
** To set a Method's Implementation flags
==============================================================================*/
FCIMPL3(void, COMDynamicWrite::CWSetMethodImpl, ReflectModuleBaseObject* moduleUNSAFE, UINT32 tkMethod, UINT32 attr)
{
    CONTRACTL
    {
        THROWS;
        DISABLED(GC_TRIGGERS);
        MODE_COOPERATIVE;
        SO_TOLERANT;
    }
    CONTRACTL_END;
    
    REFLECTMODULEBASEREF module = (REFLECTMODULEBASEREF) moduleUNSAFE;
    HELPER_METHOD_FRAME_BEGIN_1(module);
    //-[autocvtpro]-------------------------------------------------------

    HRESULT         hr; 
    RefClassWriter* pRCW;   
    REFLECTMODULEBASEREF    pReflect; 
    Module          *pModule;

    // Get the RefClassWriter   
    pReflect = (REFLECTMODULEBASEREF) module;
    _ASSERTE(pReflect);
    
    pModule = (Module*) pReflect->GetData();
    _ASSERTE(pModule);

    pRCW = GetReflectionModule(pModule)->GetClassWriter(); 
    _ASSERTE(pRCW); 
    
    // Set the methodimpl flags
    hr = pRCW->GetEmitter()->SetMethodImplFlags(
            tkMethod,
            attr);                // change the impl flags
    if (FAILED(hr)) {   
        _ASSERTE(!"SetMethodImplFlags Failed"); 
        COMPlusThrowHR(hr);    
    }   

    //-[autocvtepi]-------------------------------------------------------
    HELPER_METHOD_FRAME_END();
}
FCIMPLEND


/*============================CWDefineMethodImpl============================
** Define a MethodImpl record
==============================================================================*/
FCIMPL4(void, COMDynamicWrite::CWDefineMethodImpl, ReflectModuleBaseObject* moduleUNSAFE, UINT32 tkType, UINT32 tkBody, UINT32 tkDecl)
{
    CONTRACTL
    {
        THROWS;
        DISABLED(GC_TRIGGERS);
        MODE_COOPERATIVE;
        SO_TOLERANT;
    }
    CONTRACTL_END;
    
    REFLECTMODULEBASEREF module = (REFLECTMODULEBASEREF) moduleUNSAFE;
    HELPER_METHOD_FRAME_BEGIN_1(module);
    //-[autocvtpro]-------------------------------------------------------

    HRESULT         hr; 
    RefClassWriter* pRCW;   
    REFLECTMODULEBASEREF    pReflect; 
    Module          *pModule;

    // Get the RefClassWriter   
    pReflect = (REFLECTMODULEBASEREF) module;
    _ASSERTE(pReflect);
    
    pModule = (Module*) pReflect->GetData();
    _ASSERTE(pModule);

    pRCW = GetReflectionModule(pModule)->GetClassWriter(); 
    _ASSERTE(pRCW); 
    
    // Set the methodimpl flags
    hr = pRCW->GetEmitter()->DefineMethodImpl(
            tkType,
            tkBody,
            tkDecl);                  // change the impl flags
    if (FAILED(hr)) {   
        _ASSERTE(!"DefineMethodImpl Failed"); 
        COMPlusThrowHR(hr);    
    }   

    //-[autocvtepi]-------------------------------------------------------
    HELPER_METHOD_FRAME_END();
}
FCIMPLEND


/*============================CWGetTokenFromSig============================
**Action:
**Returns:
**Arguments:
**Exceptions:
==============================================================================*/
FCIMPL3(int, COMDynamicWrite::CWGetTokenFromSig, ReflectModuleBaseObject* moduleUNSAFE, U1Array* signatureUNSAFE, UINT32 sigLength)
{
    CONTRACTL
    {
        THROWS;
        DISABLED(GC_TRIGGERS);
        MODE_COOPERATIVE;
        SO_TOLERANT;
    }
    CONTRACTL_END;
    
    int retVal = 0;
    REFLECTMODULEBASEREF module = (REFLECTMODULEBASEREF) moduleUNSAFE;
    U1ARRAYREF signature = (U1ARRAYREF) signatureUNSAFE;
    HELPER_METHOD_FRAME_BEGIN_RET_2(module, signature);
    //-[autocvtpro]-------------------------------------------------------

    HRESULT         hr; 
    mdSignature     sig; 
    PCCOR_SIGNATURE pcSig;
    RefClassWriter* pRCW;   
    REFLECTMODULEBASEREF    pReflect; 
    Module          *pModule;

    // Get the RefClassWriter   
    pReflect = (REFLECTMODULEBASEREF) module;
    _ASSERTE(pReflect);
    
    pModule = (Module*) pReflect->GetData();
    _ASSERTE(pModule);

    pRCW = GetReflectionModule(pModule)->GetClassWriter(); 
    _ASSERTE(pRCW); 
    
    _ASSERTE(signature);

    // get the signature
    pcSig = (PCCOR_SIGNATURE)signature->GetDataPtr();

    // Define the signature
    hr = pRCW->GetEmitter()->GetTokenFromSig(
            pcSig,                          // Signature blob
            sigLength,                      // blob length
            &sig);                          // returned token

    if (FAILED(hr)) {   
        _ASSERTE(!"GetTokenFromSig Failed"); 
        COMPlusThrowHR(hr);    
    }   


    // Return the token via the hidden param. 
    retVal = (INT32)sig;   

    //-[autocvtepi]-------------------------------------------------------
    HELPER_METHOD_FRAME_END();
    return retVal;
}
FCIMPLEND



/*============================CWSetParamInfo============================
**Action: Helper to set parameter information
**Returns:
**Arguments:
**Exceptions:
==============================================================================*/
FCIMPL5(int, COMDynamicWrite::CWSetParamInfo, ReflectModuleBaseObject* moduleUNSAFE, UINT32 tkMethod, UINT32 iSequence, UINT32 iAttributes, StringObject* strParamNameUNSAFE)
{
    CONTRACTL
    {
        THROWS;
        DISABLED(GC_TRIGGERS);
        MODE_COOPERATIVE;
        SO_TOLERANT;
    }
    CONTRACTL_END;
    
    int retVal = 0;
    REFLECTMODULEBASEREF module = (REFLECTMODULEBASEREF) moduleUNSAFE;
    STRINGREF strParamName = (STRINGREF) strParamNameUNSAFE;
    HELPER_METHOD_FRAME_BEGIN_RET_2(module, strParamName);
    //-[autocvtpro]-------------------------------------------------------

    HRESULT         hr; 
    RefClassWriter* pRCW;   
    REFLECTMODULEBASEREF    pReflect; 
    Module          *pModule;
    WCHAR*          wzParamName = strParamName->GetBufferNullable();  
    mdParamDef      pd;

    // Get the RefClassWriter   
    pReflect = (REFLECTMODULEBASEREF) module;
    _ASSERTE(pReflect);
    
    pModule = (Module*) pReflect->GetData();
    _ASSERTE(pModule);

    pRCW = GetReflectionModule(pModule)->GetClassWriter(); 
    _ASSERTE(pRCW); 
    
    // Set the methodimpl flags
    hr = pRCW->GetEmitter()->DefineParam(
            tkMethod,
            iSequence,            // sequence of the parameter
            wzParamName, 
            iAttributes,          // change the impl flags
            ELEMENT_TYPE_VOID,
            0,
            (ULONG) -1,
            &pd);
    if (FAILED(hr)) {   
        _ASSERTE(!"DefineParam Failed on "); 
        COMPlusThrowHR(hr);    
    }   
    retVal = (INT32)pd;   

    //-[autocvtepi]-------------------------------------------------------
    HELPER_METHOD_FRAME_END();
    return retVal;
}   // COMDynamicWrite::CWSetParamInfo
FCIMPLEND



/*============================CWSetMarshal============================
**Action: Helper to set marshal information
**Returns:
**Arguments:
**Exceptions:
==============================================================================*/
FCIMPL4(void, COMDynamicWrite::CWSetMarshal, ReflectModuleBaseObject* moduleUNSAFE, UINT32 tk, U1Array* ubMarshalUNSAFE, UINT32 cbMarshal)
{
    CONTRACTL
    {
        THROWS;
        DISABLED(GC_TRIGGERS);
        MODE_COOPERATIVE;
        SO_TOLERANT;
    }
    CONTRACTL_END;
    
    REFLECTMODULEBASEREF module = (REFLECTMODULEBASEREF) moduleUNSAFE;
    U1ARRAYREF ubMarshal = (U1ARRAYREF) ubMarshalUNSAFE;
    HELPER_METHOD_FRAME_BEGIN_2(module, ubMarshal);
    //-[autocvtpro]-------------------------------------------------------

    HRESULT         hr; 
    PCCOR_SIGNATURE pcMarshal;
    RefClassWriter* pRCW;   
    REFLECTMODULEBASEREF    pReflect; 
    Module          *pModule;

    // Get the RefClassWriter   
    pReflect = (REFLECTMODULEBASEREF) module;
    _ASSERTE(pReflect);
    
    pModule = (Module*) pReflect->GetData();
    _ASSERTE(pModule);

    pRCW = GetReflectionModule(pModule)->GetClassWriter(); 
    _ASSERTE(pRCW); 
    
    _ASSERTE(ubMarshal);

    // get the signature
    pcMarshal = (PCCOR_SIGNATURE)ubMarshal->GetDataPtr();

    // Define the signature
    hr = pRCW->GetEmitter()->SetFieldMarshal(
            tk,
            pcMarshal,                      // marshal blob
            cbMarshal);               // blob length

    if (FAILED(hr)) {   
        _ASSERTE(!"Set FieldMarshal is failing"); 
        COMPlusThrowHR(hr);    
    }   

    //-[autocvtepi]-------------------------------------------------------
    HELPER_METHOD_FRAME_END();
}   // COMDynamicWrite::CWSetMarshal
FCIMPLEND



/*============================CWSetConstantValue============================
**Action: Helper to set constant value to field or parameter
**Returns:
**Arguments:
**Exceptions:
==============================================================================*/
FCIMPL3(void, COMDynamicWrite::CWSetConstantValue, ReflectModuleBaseObject* moduleUNSAFE, UINT32 tk, VariantData* pvarValue)
{
    CONTRACTL
    {
        THROWS;
        DISABLED(GC_TRIGGERS);
        MODE_COOPERATIVE;
        SO_TOLERANT;
    }
    CONTRACTL_END;
    
    REFLECTMODULEBASEREF module = (REFLECTMODULEBASEREF) moduleUNSAFE;
    HELPER_METHOD_FRAME_BEGIN_1(module);
    //-[autocvtpro]-------------------------------------------------------

    HRESULT         hr; 
    REFLECTMODULEBASEREF    pReflect; 
    RefClassWriter* pRCW;   
    Module          *pModule;
    DWORD           dwCPlusTypeFlag = 0;
    void            *pValue = NULL;
    OBJECTREF       obj;
    INT64           data[1];
    int             strLen;


    // Get the RefClassWriter   
    pReflect = (REFLECTMODULEBASEREF) module;
    _ASSERTE(pReflect);
    
    pModule = (Module*) pReflect->GetData();
    _ASSERTE(pModule);

    pRCW = GetReflectionModule(pModule)->GetClassWriter(); 
    _ASSERTE(pRCW);

    data[0] = 0;
    pValue = data;
    dwCPlusTypeFlag = pvarValue->GetType();

    switch (dwCPlusTypeFlag)
    {
        case CV_BOOLEAN:
        case CV_I1:
        case CV_U1:
            *(INT8 *)pValue = pvarValue->GetDataAsInt8();
            break;

        case CV_I2:
        case CV_U2:
            *(INT16*)pValue = pvarValue->GetDataAsInt16();
            break;

        case CV_I4:
        case CV_U4:
        case CV_R4: 
            *(INT32 *)pValue = pvarValue->GetDataAsInt32();
            break;

        case CV_I8:
        case CV_U8:
        case CV_R8:
            *(INT64 *)pValue = pvarValue->GetDataAsInt64();
            break;

        case CV_DATETIME:
            // This will get us the tick counts for the datetime
            *(INT64 *)pValue = pvarValue->GetDataAsInt64();
            //date is a I8 representation
            dwCPlusTypeFlag = ELEMENT_TYPE_I8;
            break;

        case CV_CURRENCY:
            // currency is a I8 representation
            *(INT64 *)pValue = pvarValue->GetDataAsInt64();
            dwCPlusTypeFlag = ELEMENT_TYPE_I8;
            break;

        case CV_CHAR:
            // map to ELEMENT_TYPE_CHAR
            *(INT16 *)pValue = pvarValue->GetDataAsInt16();
            dwCPlusTypeFlag = ELEMENT_TYPE_CHAR;
            break;

        case CV_STRING:
            if (pvarValue->GetObjRef() == NULL) 
            {
                pValue = NULL;
            }
            else
            {
                RefInterpretGetStringValuesDangerousForGC((STRINGREF) (pvarValue->GetObjRef()), (WCHAR **)&pValue, &strLen);
            }
            dwCPlusTypeFlag = ELEMENT_TYPE_STRING;
            break;

        case CV_DECIMAL:
            // Decimal is 12 bytes. Don't know how to represent this
        case CV_OBJECT:
            // for DECIMAL and Object, we only support NULL default value.
            // This is a constraint from MetaData.
            //
            obj = pvarValue->GetObjRef();
            if ((obj!=NULL) && (obj->GetData()))
            {
                // can only accept the NULL object
                COMPlusThrow(kArgumentException, L"Argument_BadConstantValue");    
            }

            // fail through

        case CV_NULL:
            dwCPlusTypeFlag = ELEMENT_TYPE_CLASS;
            pValue = NULL;
            break;

        case CV_ENUM:
            // always map the enum value to a I4 value
            *(INT32 *)pValue = pvarValue->GetDataAsInt32();

            dwCPlusTypeFlag = ELEMENT_TYPE_I4;
            break;

        case CV_EMPTY:
            dwCPlusTypeFlag = ELEMENT_TYPE_CLASS;
            pValue = NULL;
            break;

        default:
        case CV_TIMESPAN:
            _ASSERTE(!"Not valid type!");

            // cannot specify default value
            COMPlusThrow(kArgumentException, L"Argument_BadConstantValue");    
            break;
    }

    if (TypeFromToken(tk) == mdtFieldDef)
    {
        hr = pRCW->GetEmitter()->SetFieldProps( 
            tk,                         // [IN] The FieldDef.
            ULONG_MAX,                  // [IN] Field attributes.
            dwCPlusTypeFlag,            // [IN] Flag for the value type, selected ELEMENT_TYPE_*
            pValue,                     // [IN] Constant value.
            (ULONG) -1);                // [IN] Optional length.
    }
    else if (TypeFromToken(tk) == mdtProperty)
    {
        hr = pRCW->GetEmitter()->SetPropertyProps( 
            tk,                         // [IN] The PropertyDef.
            ULONG_MAX,                  // [IN] Property attributes.
            dwCPlusTypeFlag,            // [IN] Flag for the value type, selected ELEMENT_TYPE_*
            pValue,                     // [IN] Constant value.
            (ULONG) -1,                 // [IN] Optional length.
            mdMethodDefNil,             // [IN] Getter method.
            mdMethodDefNil,             // [IN] Setter method.
            NULL);                      // [IN] Other methods.
    }
    else
    {
        hr = pRCW->GetEmitter()->SetParamProps( 
            tk,                   // [IN] The ParamDef.
            NULL,
            ULONG_MAX,                  // [IN] Parameter attributes.
            dwCPlusTypeFlag,            // [IN] Flag for the value type, selected ELEMENT_TYPE_*
            pValue,                     // [IN] Constant value.
            (ULONG) -1);                // [IN] Optional length.
    }
    if (FAILED(hr)) {   
        _ASSERTE(!"Set default value is failing"); 
        COMPlusThrow(kArgumentException, L"Argument_BadConstantValue");    
    }   

    //-[autocvtepi]-------------------------------------------------------
    HELPER_METHOD_FRAME_END();
}   // COMDynamicWrite::CWSetConstantValue
FCIMPLEND


/*============================CWSetFieldLayoutOffset============================
**Action: set fieldlayout of a field
**Returns:
**Arguments:
**Exceptions:
==============================================================================*/
FCIMPL3(void, COMDynamicWrite::CWSetFieldLayoutOffset, ReflectModuleBaseObject* moduleUNSAFE, UINT32 tkField, UINT32 iOffset)
{
    CONTRACTL
    {
        THROWS;
        DISABLED(GC_TRIGGERS);
        MODE_COOPERATIVE;
        SO_TOLERANT;
    }
    CONTRACTL_END;
    
    REFLECTMODULEBASEREF module = (REFLECTMODULEBASEREF) moduleUNSAFE;
    HELPER_METHOD_FRAME_BEGIN_1(module);
    //-[autocvtpro]-------------------------------------------------------

    HRESULT         hr; 
    RefClassWriter* pRCW;   
    REFLECTMODULEBASEREF    pReflect; 
    Module          *pModule;

    _ASSERTE(RidFromToken(tkField) != mdTokenNil);

    // Get the RefClassWriter   
    pReflect = (REFLECTMODULEBASEREF) module;
    _ASSERTE(pReflect);
    
    pModule = (Module*) pReflect->GetData();
    _ASSERTE(pModule);

    pRCW = GetReflectionModule(pModule)->GetClassWriter(); 
    _ASSERTE(pRCW); 
    
    // Set the field layout
    hr = pRCW->GetEmitHelper()->SetFieldLayoutHelper(
            tkField,                  // field 
            iOffset);                 // layout offset

    if (FAILED(hr)) {   
        _ASSERTE(!"SetFieldLayoutHelper failed");
        COMPlusThrowHR(hr);    
    }   

    //-[autocvtepi]-------------------------------------------------------
    HELPER_METHOD_FRAME_END();
}
FCIMPLEND


/*============================CWSetClassLayout============================
**Action:
**Returns:
**Arguments:
**Exceptions:
==============================================================================*/
FCIMPL4(void, COMDynamicWrite::CWSetClassLayout, ReflectModuleBaseObject* moduleUNSAFE, UINT32 handle, UINT32 iPackSize, UINT32 iTotalSize)
{
    CONTRACTL
    {
        THROWS;
        DISABLED(GC_TRIGGERS);
        MODE_COOPERATIVE;
        SO_TOLERANT;
    }
    CONTRACTL_END;
    
    REFLECTMODULEBASEREF module = (REFLECTMODULEBASEREF) moduleUNSAFE;
    HELPER_METHOD_FRAME_BEGIN_1(module);
    //-[autocvtpro]-------------------------------------------------------

    HRESULT         hr; 
    RefClassWriter* pRCW;   
    REFLECTMODULEBASEREF    pReflect; 
    Module          *pModule;


    _ASSERTE(handle);

    // Get the RefClassWriter   
    pReflect = (REFLECTMODULEBASEREF) module;
    _ASSERTE(pReflect);
    
    pModule = (Module*) pReflect->GetData();
    _ASSERTE(pModule);

    pRCW = GetReflectionModule(pModule)->GetClassWriter(); 
    _ASSERTE(pRCW); 
    
    // Define the packing size and total size of a class
    hr = pRCW->GetEmitter()->SetClassLayout(
            handle,                   // Typedef
            iPackSize,                // packing size
            NULL,                     // no field layout 
            iTotalSize);              // total size for the type

    if (FAILED(hr)) {   
        _ASSERTE(!"SetClassLayout failed");
        COMPlusThrowHR(hr);    
    }   

    //-[autocvtepi]-------------------------------------------------------
    HELPER_METHOD_FRAME_END();
}
FCIMPLEND

/*===============================UpdateMethodRVAs===============================
**Action: Update the RVAs in all of the methods associated with a particular typedef
**        to prior to emitting them to a PE.
**Returns: Void
**Arguments:
**Exceptions:
==============================================================================*/
void COMDynamicWrite::UpdateMethodRVAs(IMetaDataEmit *pEmitNew,
                                  IMetaDataImport *pImportNew,
                                  ICeeFileGen *pCeeFileGen, 
                                  HCEEFILE ceeFile, 
                                  mdTypeDef td,
                                  HCEESECTION sdataSection)
{
    CONTRACTL
    {
        THROWS;
        GC_TRIGGERS;
        MODE_ANY;
    }
    CONTRACTL_END;
    

    HCORENUM    hEnum=0;
    ULONG       methRVA;
    ULONG       newMethRVA;
    ULONG       sdataSectionRVA = 0;
    mdMethodDef md;
    mdFieldDef  fd;
    ULONG       count;
    DWORD       dwFlags=0;
    DWORD       implFlags=0;
    HRESULT     hr;

    // Look at the typedef flags.  Skip tdimport classes.
    if (!IsNilToken(td))
    {
        IfFailGo(pImportNew->GetTypeDefProps(td, 0,0,0, &dwFlags, 0));
        if (IsTdImport(dwFlags))
            goto ErrExit;
    }
    
    //Get an enumerator and use it to walk all of the methods defined by td.
    while ((hr = pImportNew->EnumMethods(
        &hEnum, 
        td, 
        &md, 
        1, 
        &count)) == S_OK) {
        
        IfFailGo( pImportNew->GetMethodProps(
            md, 
            NULL, 
            NULL,           // don't get method name
            0, 
            NULL, 
            &dwFlags, 
            NULL, 
            NULL, 
            &methRVA, 
            &implFlags) );

        // If this method isn't implemented here, don't bother correcting it's RVA
        // Otherwise, get the correct RVA from our ICeeFileGen and put it back into our local
        // copy of the metadata
        //
        if ( IsMdAbstract(dwFlags) || IsMdPinvokeImpl(dwFlags) ||
             IsMiNative(implFlags) || IsMiRuntime(implFlags) ||
             IsMiForwardRef(implFlags))
        {
            continue;
        }
            
        IfFailGo( pCeeFileGen->GetMethodRVA(ceeFile, methRVA, &newMethRVA) );
        IfFailGo( pEmitNew->SetRVA(md, newMethRVA) );
    }
        
    if (hEnum) {
        pImportNew->CloseEnum( hEnum);
    }
    hEnum = 0;

    // Walk through all of the Field belongs to this TypeDef. If field is marked as fdHasFieldRVA, we need to update the
    // RVA value.
    while ((hr = pImportNew->EnumFields(
        &hEnum, 
        td, 
        &fd, 
        1, 
        &count)) == S_OK) {
        
        IfFailGo( pImportNew->GetFieldProps(
            fd, 
            NULL,           // don't need the parent class
            NULL,           // don't get method name
            0, 
            NULL, 
            &dwFlags,       // field flags
            NULL,           // don't need the signature
            NULL, 
            NULL,           // don't need the constant value
            0,
            NULL) );

        if ( IsFdHasFieldRVA(dwFlags) )
        {            
            if (sdataSectionRVA == 0)
            {
                IfFailGo( pCeeFileGen->GetSectionCreate (ceeFile, ".sdata", sdReadWrite, &(sdataSection)) );
                IfFailGo( pCeeFileGen->GetSectionRVA(sdataSection, &sdataSectionRVA) );
            }

            IfFailGo( pImportNew->GetRVA(fd, &methRVA, NULL) );
            newMethRVA = methRVA + sdataSectionRVA;
            IfFailGo( pEmitNew->SetFieldRVA(fd, newMethRVA) );
        }
    }
        
    if (hEnum) {
        pImportNew->CloseEnum( hEnum);
    }
    hEnum = 0;

ErrExit:
    if (FAILED(hr)) {   
        _ASSERTE(!"UpdateRVA failed");
        COMPlusThrowHR(hr);    
    }   
}

FCIMPL6(void, COMDynamicWrite::CWInternalCreateCustomAttribute, UINT32 token, UINT32 conTok, U1Array* blobUNSAFE, ReflectModuleBaseObject* moduleUNSAFE, CLR_BOOL toDisk, CLR_BOOL updateCompilerFlags)
{
    CONTRACTL
    {
        THROWS;
        DISABLED(GC_TRIGGERS);
        MODE_COOPERATIVE;
        SO_TOLERANT;
    }
    CONTRACTL_END;
    
    U1ARRAYREF blob = (U1ARRAYREF) blobUNSAFE;
    REFLECTMODULEBASEREF module = (REFLECTMODULEBASEREF) moduleUNSAFE;
    HELPER_METHOD_FRAME_BEGIN_2(blob, module);

    HRESULT hr;
    mdCustomAttribute retToken;

    // Get the RefClassWriter   
    REFLECTMODULEBASEREF    pReflect = (REFLECTMODULEBASEREF) module;
    _ASSERTE(pReflect);
    Module* pModule = (Module*) pReflect->GetData();
    _ASSERTE(pModule);

    RefClassWriter* pRCW = GetReflectionModule(pModule)->GetClassWriter();
    _ASSERTE(pRCW);

    if (toDisk && pRCW->GetOnDiskEmitter())
    {
        hr = pRCW->GetOnDiskEmitter()->DefineCustomAttribute(
                token,
                conTok,
                blob->GetDataPtr(),
                blob->GetNumComponents(),
                &retToken); 
    }
    else
    {
        hr = pRCW->GetEmitter()->DefineCustomAttribute(
                token,
                conTok,
                blob->GetDataPtr(),
                blob->GetNumComponents(),
                &retToken); 
    }

    if (SUCCEEDED(hr))
    {
        if (updateCompilerFlags)
        {
            ULONG size      = blob->GetNumComponents();
            BYTE* blobArray = blob->GetDataPtr();
            DWORD flags     = 0;
            DWORD mask      = ~(DACF_OBSOLETE_TRACK_JIT_INFO | DACF_IGNORE_PDBS | DACF_ALLOW_JIT_OPTS) & DACF_CONTROL_FLAGS_MASK;

            if ((size != 6) && (size != 8))
            {
                _ASSERTE("COMDynamicWrite::CWInternalCreateCustomAttribute - unexpected size for DebuggableAttribute\n");
            }
            else if ( !((blobArray[0] == 1) && (blobArray[1] == 0)) )
            {
                _ASSERTE("COMDynamicWrite::CWInternalCreateCustomAttribute - bad format for DebuggableAttribute\n");
            }

            if (blobArray[2] & 0x1)
            {
                flags |= DACF_OBSOLETE_TRACK_JIT_INFO;
            }

            if (blobArray[2] & 0x2)
            {
                flags |= DACF_IGNORE_PDBS;
            }

            if ( ((blobArray[2] & 0x1) == 0) || (blobArray[3] == 0) )
            {
                flags |= DACF_ALLOW_JIT_OPTS;
            }

            Assembly*       pAssembly       = pModule->GetAssembly();
            DomainAssembly* pDomainAssembly = pAssembly->GetDomainAssembly();
            
            // Dynamic assemblies should be 1:1 with DomainAssemblies.
            _ASSERTE(!pAssembly->IsDomainNeutral());

            DWORD actualFlags;
            actualFlags =  ((DWORD)pDomainAssembly->GetDebuggerInfoBits() & mask) | flags;
            pDomainAssembly->SetDebuggerInfoBits((DebuggerAssemblyControlFlags)actualFlags);

            actualFlags = ((DWORD)pAssembly->GetDebuggerInfoBits() & mask) | flags;
            pAssembly->SetDebuggerInfoBits((DebuggerAssemblyControlFlags)actualFlags);

            ModuleIterator i = pAssembly->IterateModules();
            while (i.Next())
            {
                actualFlags = ((DWORD)(i.GetModule()->GetDebuggerInfoBits()) & mask) | flags;
                i.GetModule()->SetDebuggerInfoBits((DebuggerAssemblyControlFlags)actualFlags);
            }
        }
    }
    else
    {
        GCX_PREEMP();

        // See if the metadata engine gave us any error information.
        SafeComHolder<IErrorInfo> pIErrInfo;
        BSTRHolder bstrMessage;
        if (SafeGetErrorInfo(&pIErrInfo) == S_OK)
        {
            if (SUCCEEDED(pIErrInfo->GetDescription(&bstrMessage)) && bstrMessage != NULL)
                COMPlusThrow(kArgumentException, IDS_EE_INVALID_CA_EX, bstrMessage);
        }

        COMPlusThrow(kArgumentException, IDS_EE_INVALID_CA);
    }

    HELPER_METHOD_FRAME_END();
}
FCIMPLEND

#define IMAGE_FILE_MACHINE_UNKNOWN           0
#define IMAGE_FILE_MACHINE_I386              0x014c  // Intel 386.
#define IMAGE_FILE_MACHINE_IA64              0x0200  // Intel 64
#define IMAGE_FILE_MACHINE_AMD64             0x8664  // AMD64 (K8)
#define IMAGE_FILE_MACHINE_CEE               0xC0EE

void ManagedBitnessFlagsToUnmanagedBitnessFlags(
    INT32 portableExecutableKind, INT32 imageFileMachine,
    DWORD* pPeFlags, DWORD* pCorhFlags)
{
    if (portableExecutableKind & peILonly)
        *pCorhFlags |= COMIMAGE_FLAGS_ILONLY;
    
    if (portableExecutableKind & pe32BitRequired)
        *pCorhFlags |= COMIMAGE_FLAGS_32BITREQUIRED;   
    
    *pPeFlags |= ICEE_CREATE_FILE_CORMAIN_STUB;
        
    if (imageFileMachine == IMAGE_FILE_MACHINE_I386)
        *pPeFlags |= ICEE_CREATE_MACHINE_I386|ICEE_CREATE_FILE_PE32;
    
    else if (imageFileMachine == IMAGE_FILE_MACHINE_IA64)
        *pPeFlags |= ICEE_CREATE_MACHINE_IA64|ICEE_CREATE_FILE_PE64;
    
    else if (imageFileMachine == IMAGE_FILE_MACHINE_AMD64)
        *pPeFlags |= ICEE_CREATE_MACHINE_AMD64|ICEE_CREATE_FILE_PE64;        
}

//=============================PreSavePEFile=====================================*/
// PreSave the PEFile
//==============================================================================*/
FCIMPL3(void, COMDynamicWrite::PreSavePEFile, Object* refThisUNSAFE, INT32 portableExecutableKind, INT32 imageFileMachine)
{    
    OBJECTREF refThis = (OBJECTREF) refThisUNSAFE;
    HELPER_METHOD_FRAME_BEGIN_1(refThis);

    CONTRACTL
    {
        THROWS;
        GC_TRIGGERS;
        MODE_COOPERATIVE;
        SO_TOLERANT;
    }
    CONTRACTL_END;

    if (refThis == NULL) 
        COMPlusThrow(kNullReferenceException, L"NullReference_This");

    RefClassWriter  *pRCW;   
    ICeeGen         *pICG;
    HCEEFILE        ceeFile=NULL;
    ICeeFileGen     *pCeeFileGen;

    SafeComHolder<IMetaDataDispenserEx> pDisp;
    SafeComHolder<IMetaDataEmit>   pEmitNew;
    
    IMetaDataEmit   *pEmit = NULL;
    IMetaDataImport *pImport = NULL;
    IUnknown        *pUnknown = NULL;
    
    SafeComHolder<IMapToken>      pIMapToken;
    
    REFLECTMODULEBASEREF pReflect;
    VARIANT         varOption;
    ISymUnmanagedWriter *pWriter = NULL;

    SafeComHolder<CSymMapToken>    pSymMapToken;
    
    CQuickArray<WCHAR> cqModuleName;
    ULONG           cchName;

    //Get the information for the Module and get the ICeeGen from it. 
    pReflect = (REFLECTMODULEBASEREF) refThis;    

    Module* pModule = (Module*) pReflect->GetData();
    _ASSERTE(pModule);

    pRCW = GetReflectionModule(pModule)->GetClassWriter(); 
    _ASSERTE(pRCW);

    pICG = pRCW->GetCeeGen();
    _ASSERTE(pICG);

    DWORD peFlags = 0, corhFlags = 0;

    ManagedBitnessFlagsToUnmanagedBitnessFlags(portableExecutableKind, imageFileMachine, &peFlags, &corhFlags);

    IfFailThrow ( pRCW->EnsureCeeFileGenCreated(corhFlags, peFlags) );

    pCeeFileGen = pRCW->GetCeeFileGen();
    ceeFile = pRCW->GetHCEEFILE();
    _ASSERTE(ceeFile && pCeeFileGen);

    // We should not have the on disk emitter yet
    if (pRCW->GetOnDiskEmitter() != NULL)
        pRCW->SetOnDiskEmitter(NULL);

    // Get the dispenser.
    IfFailThrow ( MetaDataGetDispenser(CLSID_CorMetaDataDispenser, IID_IMetaDataDispenserEx, (void**)&pDisp) );

    //Get the emitter and the importer
    pImport = pRCW->GetRWImporter();
    pEmit = pRCW->GetEmitter();
    _ASSERTE(pEmit && pImport);

    // Set the option on the dispenser turn on duplicate check for TypeDef and moduleRef
    V_VT(&varOption) = VT_UI4;
    V_I4(&varOption) = MDDupDefault | MDDupTypeDef | MDDupModuleRef | MDDupExportedType | MDDupAssemblyRef;
    IfFailThrow( pDisp->SetOption(MetaDataCheckDuplicatesFor, &varOption) );

    V_VT(&varOption) = VT_UI4;
    V_I4(&varOption) = MDRefToDefNone;
    IfFailThrow( pDisp->SetOption(MetaDataRefToDefCheck, &varOption) );

    //Define an empty scope
    IfFailThrow( pDisp->DefineScope(CLSID_CorMetaDataRuntime, 0, IID_IMetaDataEmit, (IUnknown**)&pEmitNew));

    // Token can move upon merge. Get the IMapToken from the CeeFileGen that is created for save
    // and pass it to merge to receive token movement notification.
    // Note that this is not a long term fix. We are relying on the fact that those tokens embedded
    // in PE cannot move after the merge. These tokens are TypeDef, TypeRef, MethodDef, FieldDef, MemberRef,
    // TypeSpec, UserString. If this is no longer true, we can break!
    //
    // Note that we don't need to release pIMapToken because it is not AddRef'ed in the GetIMapTokenIfaceEx.
    //
    IfFailThrow( pCeeFileGen->GetIMapTokenIfaceEx(ceeFile, pEmit, &pUnknown));

    IfFailThrow( SafeQueryInterface(pUnknown, IID_IMapToken, (IUnknown**) &pIMapToken));

    // get the unmanaged writer.
    pWriter = GetReflectionModule(pModule)->GetISymUnmanagedWriter();
    pSymMapToken = new CSymMapToken(pWriter, pIMapToken);
    
    //Merge the old tokens into the new (empty) scope
    //This is a copy.
    IfFailThrow( pEmitNew->Merge(pImport, pSymMapToken, NULL));
    IfFailThrow( pEmitNew->MergeEnd());

    // Update the Module name in the new scope.
    IfFailThrow(pImport->GetScopeProps(0, 0, &cchName, 0));
    IfFailThrow(cqModuleName.ReSizeNoThrow(cchName));
    IfFailThrow(pImport->GetScopeProps(cqModuleName.Ptr(), cchName, &cchName, 0));
    IfFailThrow(pEmitNew->SetModuleProps(cqModuleName.Ptr()));

    // cache the pEmitNew to RCW!!
    pRCW->SetOnDiskEmitter(pEmitNew);

    //-[autocvtepi]-------------------------------------------------------
    HELPER_METHOD_FRAME_END();
}
FCIMPLEND

//=============================SavePEFile=====================================*/
// Save the PEFile to disk
//==============================================================================*/
FCIMPL5(void, COMDynamicWrite::SavePEFile, Object* refThisUNSAFE, StringObject* peNameUNSAFE, UINT32 entryPoint, UINT32 fileKind, CLR_BOOL isManifestFile)
{
    CONTRACTL
    {
        THROWS;
        DISABLED(GC_TRIGGERS);
        MODE_COOPERATIVE;
        SO_TOLERANT;
    }
    CONTRACTL_END;
    
    OBJECTREF refThis = (OBJECTREF) refThisUNSAFE;
    STRINGREF peName = (STRINGREF) peNameUNSAFE;
    HELPER_METHOD_FRAME_BEGIN_2(refThis, peName);
    
    //-[autocvtpro]-------------------------------------------------------
    if (refThis == NULL) 
        COMPlusThrow(kNullReferenceException, L"NullReference_This");

    RefClassWriter  *pRCW;   
    ICeeGen         *pICG;
    HCEEFILE        ceeFile=NULL;
    ICeeFileGen     *pCeeFileGen;
    HRESULT         hr=S_OK;
    HCORENUM        hTypeDefs=0;
    mdTypeDef       td;
    ULONG           count;
    IMetaDataEmit   *pEmitNew = 0;
    IMetaDataImport *pImportNew = 0;
    REFLECTMODULEBASEREF pReflect;
    Assembly        *pAssembly;
    ULONG           newMethRVA;
    DWORD           metaDataSize;   
    BYTE            *metaData;
    ULONG           metaDataOffset;
    HCEESECTION     pILSection;
    ISymUnmanagedWriter *pWriter = NULL;
    StackSString filename; // local copy of peName


    if (peName==NULL)
        COMPlusThrow(kArgumentNullException, L"ArgumentNull_String");
    if (peName->GetStringLength()==0)
        COMPlusThrow(kFormatException, L"Format_StringZeroLength");

    //Get the information for the Module and get the ICeeGen from it. 
    pReflect = (REFLECTMODULEBASEREF) refThis;
    
    Module* pModule = (Module*) pReflect->GetData();
    _ASSERTE(pModule);

    // make a local copy of peName
    peName->GetSString (filename);

    // We are going to call out to unmanaged code at this point so we need to
    // transition to preemptive GC mode.
    GCX_PREEMP();

    pAssembly = pModule->GetAssembly();
    _ASSERTE( pAssembly );

    pRCW = GetReflectionModule(pModule)->GetClassWriter(); 
    _ASSERTE(pRCW);

    pICG = pRCW->GetCeeGen(); //This method is actually misnamed. It returns an ICeeGen.
    _ASSERTE(pICG);

    pCeeFileGen = pRCW->GetCeeFileGen();
    ceeFile = pRCW->GetHCEEFILE();
    _ASSERTE(ceeFile && pCeeFileGen);

    pEmitNew = pRCW->GetOnDiskEmitter();
    _ASSERTE(pEmitNew);

    //Get the emitter and the importer 

    if (pAssembly->IsDynamic() && isManifestFile)
    {
        // manifest is stored in this file

        // Allocate space for a strong name signature if an originator was supplied
        // (this doesn't strong name the assembly, but it makes it possible to do so
        // as a post processing step).
        if (pAssembly->IsStrongNamed())
            IfFailGo(pAssembly->AllocateStrongNameSignature(pCeeFileGen, ceeFile));
    }

    //Set the Output FileName
    IfFailGo( pCeeFileGen->SetOutputFileName(ceeFile, (LPWSTR)filename.GetUnicode()) );
    
    //Set the Entry Point or throw the dll switch if we're creating a dll.
    if (entryPoint!=0) 
    {
        IfFailGo( pCeeFileGen->SetEntryPoint(ceeFile, entryPoint) );
    }

    switch (fileKind)
    {
        case Dll:
        {
            IfFailGo( pCeeFileGen->SetDllSwitch(ceeFile, true) );
            break;
        }
        case WindowApplication:
        {
            // window application. Set the SubSystem
            IfFailGo( pCeeFileGen->SetSubsystem(ceeFile, IMAGE_SUBSYSTEM_WINDOWS_GUI, CEE_IMAGE_SUBSYSTEM_MAJOR_VERSION, CEE_IMAGE_SUBSYSTEM_MINOR_VERSION) );
            break;
        }
        case ConsoleApplication:
        {
            // Console application. Set the SubSystem
            IfFailGo( pCeeFileGen->SetSubsystem(ceeFile, IMAGE_SUBSYSTEM_WINDOWS_CUI, CEE_IMAGE_SUBSYSTEM_MAJOR_VERSION, CEE_IMAGE_SUBSYSTEM_MINOR_VERSION) );
            break;
        }
        default:
        {
            _ASSERTE("Unknown file kind!");
            break;
        }
    }

    IfFailGo( pCeeFileGen->GetIlSection(ceeFile, &pILSection) );
    IfFailGo( pEmitNew->GetSaveSize(cssAccurate, &metaDataSize) );
    IfFailGo( pCeeFileGen->GetSectionBlock(pILSection, metaDataSize, sizeof(DWORD), (void**) &metaData) );
    IfFailGo( pCeeFileGen->GetSectionDataLen(pILSection, &metaDataOffset) );
    metaDataOffset -= metaDataSize;

    // get the unmanaged writer.
    pWriter = GetReflectionModule(pModule)->GetISymUnmanagedWriter();
    IfFailGo( EmitDebugInfoBegin(pModule, pCeeFileGen, ceeFile, pILSection, filename.GetUnicode (), pWriter) );

    if (pAssembly->IsDynamic() && pRCW->m_ulResourceSize)
    {
        // There are manifest in this file

        IfFailGo( pCeeFileGen->GetMethodRVA(ceeFile, 0, &newMethRVA) );            

        // Point to manifest resource
        IfFailGo( pCeeFileGen->SetManifestEntry( ceeFile, pRCW->m_ulResourceSize, newMethRVA ) );
    }

    IfFailGo( pCeeFileGen->LinkCeeFile(ceeFile) );

    // Get the import interface from the new Emit interface.
    IfFailGo( pEmitNew->QueryInterface(IID_IMetaDataImport, (void **)&pImportNew));


    //Enumerate the TypeDefs and update method RVAs.
    while ((hr = pImportNew->EnumTypeDefs( &hTypeDefs, &td, 1, &count)) == S_OK) 
    {
        UpdateMethodRVAs(pEmitNew, pImportNew, pCeeFileGen, ceeFile, td, ((ReflectionModule*) pModule)->m_sdataSection);
    }

    if (hTypeDefs) 
    {
        pImportNew->CloseEnum(hTypeDefs);
    }
    hTypeDefs=0;
    
    //Update Global Methods.
    UpdateMethodRVAs(pEmitNew, pImportNew, pCeeFileGen, ceeFile, 0, ((ReflectionModule*) pModule)->m_sdataSection);
    

    //Emit the MetaData 
    // IfFailGo( pCeeFileGen->EmitMetaDataEx(ceeFile, pEmitNew));
    IfFailGo( pCeeFileGen->EmitMetaDataAt(ceeFile, pEmitNew, pILSection, metaDataOffset, metaData, metaDataSize) );

    // finish the debugging info emitting after the metadata save so that token remap will be caught correctly
    IfFailGo( EmitDebugInfoEnd(pModule, pCeeFileGen, ceeFile, pILSection, filename.GetUnicode (), pWriter) );

    //Generate the CeeFile
    IfFailGo(pCeeFileGen->GenerateCeeFile(ceeFile) );

    // Strong name sign the resulting assembly if required.
    if (pAssembly->IsDynamic() && isManifestFile && pAssembly->IsStrongNamed())
        IfFailGo(pAssembly->SignWithStrongName((LPWSTR)filename.GetUnicode()));

ErrExit:

    pRCW->SetOnDiskEmitter(NULL);

    //Release the interfaces.  This should free some of the associated resources.
    if (pImportNew)
        pImportNew->Release();

    //Release our interfaces if we allocated them to begin with
    pRCW->DestroyCeeFileGen();

    //Check all file IO errors. If so, throw IOException. Otherwise, just throw the hr.
    if (FAILED(hr))
    {
        if (HRESULT_FACILITY(hr) == FACILITY_WIN32)
        {
            if (IsWin32IOError(HRESULT_CODE(hr)))
            {
                SString hrMessage;
                GenerateTopLevelHRExceptionMessage(hr, hrMessage);
                COMPlusThrowHR(COR_E_IO, IDS_EE_GENERIC, hrMessage.GetUnicode());
            }
            else
            {
                COMPlusThrowHR(hr);
            }
        }
        COMPlusThrowHR(hr);
    }

    //-[autocvtepi]-------------------------------------------------------
    HELPER_METHOD_FRAME_END();
}
FCIMPLEND

//=============================EmitDebugInfoBegin============================*/
// Phase 1 of emit debugging directory and symbol file.
//===========================================================================*/
HRESULT COMDynamicWrite::EmitDebugInfoBegin(Module *pModule,
                                       ICeeFileGen *pCeeFileGen,
                                       HCEEFILE ceeFile,
                                       HCEESECTION pILSection,
                                       const WCHAR *filename,
                                       ISymUnmanagedWriter *pWriter)
{
    CONTRACT(HRESULT) {
        NOTHROW;
        GC_NOTRIGGER;
        MODE_ANY; 
        INJECT_FAULT(COMPlusThrowOM());

        PRECONDITION(CheckPointer(pWriter, NULL_OK));
        PRECONDITION(CheckPointer(pCeeFileGen));
        PRECONDITION(CheckPointer(pModule));

        POSTCONDITION(SUCCEEDED(RETVAL));
    }
    CONTRACT_END;

    HRESULT hr = S_OK;  

    // If we were emitting symbols for this dynamic module, go ahead
    // and fill out the debug directory and save off the symbols now.
    if (pWriter != NULL)
    {
        IMAGE_DEBUG_DIRECTORY  debugDirIDD;
        DWORD                  debugDirDataSize;
        BYTE                  *debugDirData;

        // Grab the debug info.
        IfFailGo(pWriter->GetDebugInfo(NULL, 0, &debugDirDataSize, NULL));

            
        // Is there any debug info to emit?
        if (debugDirDataSize > 0)
        {
            // Make some room for the data.
            debugDirData = (BYTE*)_alloca(debugDirDataSize);

            // Actually get the data now.
            IfFailGo(pWriter->GetDebugInfo(&debugDirIDD,
                                             debugDirDataSize,
                                             NULL,
                                             debugDirData));


            // Grab the timestamp of the PE file.
            DWORD fileTimeStamp;


            IfFailGo(pCeeFileGen->GetFileTimeStamp(ceeFile, &fileTimeStamp));


            // Fill in the directory entry.
            debugDirIDD.TimeDateStamp = VAL32(fileTimeStamp);
            debugDirIDD.AddressOfRawData = 0;

            // Grab memory in the section for our stuff.
            HCEESECTION sec = pILSection;
            BYTE *de;

            IfFailGo(pCeeFileGen->GetSectionBlock(sec,
                                                    sizeof(debugDirIDD) +
                                                    debugDirDataSize,
                                                    4,
                                                    (void**) &de) );


            // Where did we get that memory?
            ULONG deOffset;
            IfFailGo(pCeeFileGen->GetSectionDataLen(sec, &deOffset));


            deOffset -= (sizeof(debugDirIDD) + debugDirDataSize);

            // Setup a reloc so that the address of the raw data is
            // setup correctly.
            debugDirIDD.PointerToRawData = VAL32(deOffset + sizeof(debugDirIDD));
                    
            IfFailGo(pCeeFileGen->AddSectionReloc(
                                          sec,
                                          deOffset +
                                          offsetof(IMAGE_DEBUG_DIRECTORY, PointerToRawData),
                                          sec, srRelocFilePos));


                    
            // Emit the directory entry.
            IfFailGo(pCeeFileGen->SetDirectoryEntry(
                                          ceeFile,
                                          sec,
                                          IMAGE_DIRECTORY_ENTRY_DEBUG,
                                          sizeof(debugDirIDD),
                                          deOffset));


            // Copy the debug directory into the section.
            memcpy(de, &debugDirIDD, sizeof(debugDirIDD));
            memcpy(de + sizeof(debugDirIDD), debugDirData, debugDirDataSize);

        }
    }
ErrExit:
    RETURN(hr);
}


//=============================EmitDebugInfoEnd==============================*/
// Phase 2 of emit debugging directory and symbol file.
//===========================================================================*/
HRESULT COMDynamicWrite::EmitDebugInfoEnd(Module *pModule,
                                          ICeeFileGen *pCeeFileGen,
                                          HCEEFILE ceeFile,
                                          HCEESECTION pILSection,
                                          const WCHAR *filename,
                                          ISymUnmanagedWriter *pWriter)
{
    CONTRACT(HRESULT) {
        NOTHROW;
        GC_TRIGGERS;
        MODE_ANY;
        INJECT_FAULT(CONTRACT_RETURN(E_OUTOFMEMORY));

        PRECONDITION(CheckPointer(pWriter, NULL_OK));
        PRECONDITION(CheckPointer(pCeeFileGen));
        PRECONDITION(CheckPointer(pModule));
    }
    CONTRACT_END;
    
    HRESULT hr = S_OK;
    GCX_PREEMP();

    CGrowableStream *pStream = NULL;

    // If we were emitting symbols for this dynamic module, go ahead
    // and fill out the debug directory and save off the symbols now.
    if (pWriter != NULL)
    {
        // Now go ahead and save off the symbol file and release the
        // writer.
        IfFailGo( pWriter->Close() );




        // How big of a stream to we have now?
        pStream = pModule->GetInMemorySymbolStream();
        _ASSERTE(pStream != NULL);

        STATSTG SizeData = {0};
        DWORD streamSize = 0;

        IfFailGo(pStream->Stat(&SizeData, STATFLAG_NONAME));

        streamSize = SizeData.cbSize.u.LowPart;

        if (SizeData.cbSize.u.HighPart > 0)
        {
            IfFailGo( E_OUTOFMEMORY );

        }

        SIZE_T fnLen = wcslen(filename);
        const WCHAR *dot = wcsrchr(filename, L'.');
        SIZE_T dotOffset = dot - filename;

        if (dot && (fnLen - dotOffset >= 4))
        {
            //size_t len = (fnLen + 2) * sizeof(WCHAR);
            size_t len = fnLen + 2;
            WCHAR *fn = (WCHAR*)_alloca(len * sizeof(WCHAR));
            wcscpy_s(fn, len, filename);
            fn[dotOffset + 1] = L'i';
            fn[dotOffset + 2] = L'l';
            fn[dotOffset + 3] = L'd';
            fn[dotOffset + 4] = L'b';
            fn[dotOffset + 5] = L'\0';

            HandleHolder pdbFile(WszCreateFile(fn,
                                               GENERIC_WRITE,
                                               0,
                                               NULL,
                                               CREATE_ALWAYS,
                                               FILE_ATTRIBUTE_NORMAL,
                                               NULL));

            if (pdbFile != INVALID_HANDLE_VALUE)
            {
                DWORD dummy;
                BOOL succ = WriteFile(pdbFile,
                                      pStream->GetBuffer(),
                                      streamSize,
                                      &dummy, NULL);

                if (!succ)
                {
                    IfFailGo( HRESULT_FROM_GetLastError() );

                }

            }
            else
            {
                IfFailGo( HRESULT_FROM_GetLastError() );

            }
        }
        else
        {
            IfFailGo( E_INVALIDARG );

        }
    }

ErrExit:
    // No one else will ever need this writer again...
    GetReflectionModule(pModule)->SetISymUnmanagedWriter(NULL);
//    GetReflectionModule(pModule)->SetSymbolStream(NULL);

    RETURN(hr);
}



//=============================SetResourceCounts=====================================*/
// ecall for setting the number of embedded resources to be stored in this module
//==============================================================================*/
FCIMPL2(void, COMDynamicWrite::SetResourceCounts, Object* refThisUNSAFE, UINT32 iCount)
{
    CONTRACTL
    {
        THROWS;
        DISABLED(GC_TRIGGERS);
        MODE_COOPERATIVE;
        SO_TOLERANT;
    }
    CONTRACTL_END;
    
    OBJECTREF refThis = (OBJECTREF) refThisUNSAFE;
    HELPER_METHOD_FRAME_BEGIN_1(refThis);
    //-[autocvtpro]-------------------------------------------------------

    if (refThis == NULL) 
        COMPlusThrow(kNullReferenceException, L"NullReference_This");

    REFLECTMODULEBASEREF pReflect;
    RefClassWriter  *pRCW;   

    //Get the information for the Module and get the ICeeGen from it. 
    pReflect = (REFLECTMODULEBASEREF) refThis;
    
    Module* pModule = (Module*) pReflect->GetData();
    _ASSERTE(pModule);

    pRCW = GetReflectionModule(pModule)->GetClassWriter(); 
    _ASSERTE(pRCW);
    
    //-[autocvtepi]-------------------------------------------------------
    HELPER_METHOD_FRAME_END();
}
FCIMPLEND

//=============================AddResource=====================================*/
// ecall for adding embedded resource to this module
//==============================================================================*/
FCIMPL8(void, COMDynamicWrite::AddResource, Object* refThisUNSAFE, StringObject* strNameUNSAFE, U1Array* byteResUNSAFE, UINT32 iByteCount, UINT32 uFileTk, UINT32 iAttribute, INT32 portableExecutableKind, INT32 imageFileMachine)
{
    CONTRACTL
    {
        THROWS;
        DISABLED(GC_TRIGGERS);
        MODE_COOPERATIVE;
        SO_TOLERANT;
    }
    CONTRACTL_END;
    
    struct _gc
    {
        OBJECTREF refThis;
        STRINGREF strName;
        U1ARRAYREF byteRes;
    } gc;
    gc.refThis = (OBJECTREF) refThisUNSAFE;
    gc.strName = (STRINGREF) strNameUNSAFE;
    gc.byteRes = (U1ARRAYREF) byteResUNSAFE;
    HELPER_METHOD_FRAME_BEGIN_PROTECT(gc);
    //-[autocvtpro]-------------------------------------------------------

    if (gc.refThis == NULL) 
        COMPlusThrow(kNullReferenceException, L"NullReference_This");

    REFLECTMODULEBASEREF pReflect;
    RefClassWriter  *pRCW;   
    ICeeGen         *pICG;
    HCEEFILE        ceeFile=NULL;
    ICeeFileGen     *pCeeFileGen;
    HRESULT         hr=S_OK;
    HCEESECTION     hSection;
    ULONG           ulOffset;
    BYTE            *pbBuffer;
    IMetaDataAssemblyEmit *pAssemEmitter = NULL;
    Assembly        *pAssembly;
    mdManifestResource mr;
    mdFile          tkFile;
    IMetaDataEmit   *pOnDiskEmit;
    IMetaDataAssemblyEmit *pOnDiskAssemblyEmit = NULL;

    DWORD peFlags = 0, corhFlags = 0;
    ManagedBitnessFlagsToUnmanagedBitnessFlags(portableExecutableKind, imageFileMachine, &peFlags, &corhFlags);   

    //Get the information for the Module and get the ICeeGen from it. 
    pReflect = (REFLECTMODULEBASEREF) gc.refThis;
    
    Module* pModule = (Module*) pReflect->GetData();
    _ASSERTE(pModule);

    pRCW = GetReflectionModule(pModule)->GetClassWriter(); 
    _ASSERTE(pRCW);

    pICG = pRCW->GetCeeGen(); //This method is actually misnamed. It returns an ICeeGen.
    _ASSERTE(pICG);

    pAssembly = pModule->GetAssembly();
    _ASSERTE( pAssembly && pAssembly->IsDynamic() );

    IfFailGo( pRCW->EnsureCeeFileGenCreated(corhFlags, peFlags) );

    pCeeFileGen = pRCW->GetCeeFileGen();
    ceeFile = pRCW->GetHCEEFILE();
    _ASSERTE(ceeFile && pCeeFileGen);

    pOnDiskEmit = pRCW->GetOnDiskEmitter();

    // First, put it into .rdata section. The only reason that we choose .rdata section at
    // this moment is because this is the first section on the PE file. We don't need to deal with
    // reloc. Actually, I don't know how to deal with the reloc with CeeFileGen given that the reloc
    // position is not in the same file!

    // Get the .rdata section
    IfFailGo( pCeeFileGen->GetRdataSection(ceeFile, &hSection) );

    // the current section data length is the RVA
    IfFailGo( pCeeFileGen->GetSectionDataLen(hSection, &ulOffset) );

    // Allocate a block of space fromt he .rdata section
    IfFailGo( pCeeFileGen->GetSectionBlock(
        hSection,           // from .rdata section
        iByteCount + sizeof(DWORD),   // number of bytes that we need
        1,                  // alignment
        (void**) &pbBuffer) ); 

    // now copy over the resource
    memcpy( pbBuffer, &iByteCount, sizeof(DWORD) );
    memcpy( pbBuffer + sizeof(DWORD), gc.byteRes->GetDataPtr(), iByteCount );

    // track the total resource size so far. The size is actually the offset into the section
    // after writing the resource out
    pCeeFileGen->GetSectionDataLen(hSection, &pRCW->m_ulResourceSize);
    tkFile = RidFromToken(uFileTk) ? uFileTk : mdFileNil;
    if (tkFile != mdFileNil)
    {
        IfFailGo( pOnDiskEmit->QueryInterface(IID_IMetaDataAssemblyEmit, (void **) &pOnDiskAssemblyEmit) );
        
        // The resource is stored in a file other than the manifest file
        IfFailGo(pOnDiskAssemblyEmit->DefineManifestResource(
                 gc.strName->GetBuffer(),
                 mdFileNil,              // implementation -- should be file token of this module in the manifest
                 ulOffset,               // offset to this file -- need to be adjusted upon save
                 iAttribute,       // resource flag
                 &mr));                  // manifest resource token
    }

    // Add an entry into the ManifestResource table for this resource
    // The RVA is ulOffset
    pAssemEmitter = pAssembly->GetOnDiskMDAssemblyEmitter();
    IfFailGo(pAssemEmitter->DefineManifestResource(
        gc.strName->GetBuffer(),
        tkFile,                 // implementation -- should be file token of this module in the manifest
        ulOffset,               // offset to this file -- need to be adjusted upon save
        iAttribute,             // resource flag
        &mr));                  // manifest resource token

    pRCW->m_tkFile = tkFile;

ErrExit:
    if (pAssemEmitter)
        pAssemEmitter->Release();
    if (pOnDiskAssemblyEmit)
        pOnDiskAssemblyEmit->Release();
    if (FAILED(hr)) 
    {
        COMPlusThrowHR(hr);
    }

    //-[autocvtepi]-------------------------------------------------------
    HELPER_METHOD_FRAME_END();
}
FCIMPLEND

//============================AddDeclarativeSecurity============================*/
// Add a declarative security serialized blob and a security action code to a
// given parent (class or method).
//==============================================================================*/
FCIMPL4(void, COMDynamicWrite::CWAddDeclarativeSecurity, ReflectModuleBaseObject* moduleUNSAFE, UINT32 tk, DWORD action, U1Array* blobUNSAFE)
{
    CONTRACTL
    {
        THROWS;
        DISABLED(GC_TRIGGERS);
        MODE_COOPERATIVE;
        SO_TOLERANT;
    }
    CONTRACTL_END;
    
    REFLECTMODULEBASEREF module = (REFLECTMODULEBASEREF) moduleUNSAFE;
    U1ARRAYREF blob = (U1ARRAYREF) blobUNSAFE;
    HELPER_METHOD_FRAME_BEGIN_2(module, blob);
    //-[autocvtpro]-------------------------------------------------------

    HRESULT                 hr;
    RefClassWriter*         pRCW;   
    REFLECTMODULEBASEREF    pReflect;
    Module*                 pModule;
    mdPermission            tkPermission;
    void const*             pData;
    DWORD                   cbData;

    pReflect = (REFLECTMODULEBASEREF) module;
    pModule = (Module*) pReflect->GetData();
    pRCW = GetReflectionModule(pModule)->GetClassWriter();

    if (blob != NULL) {
        pData = blob->GetDataPtr();
        cbData = blob->GetNumComponents();
    } else {
        pData = NULL;
        cbData = 0;
    }

    IfFailGo( pRCW->GetEmitHelper()->AddDeclarativeSecurityHelper(tk,
                                                             action,
                                                             pData,
                                                             cbData,
                                                             &tkPermission) );
ErrExit:
    if (FAILED(hr)) 
    {
        _ASSERTE(!"AddDeclarativeSecurity failed");
        COMPlusThrowHR(hr);
    }
    else if (hr == META_S_DUPLICATE)
    {
        COMPlusThrow(kInvalidOperationException, IDS_EE_DUPLICATE_DECLSEC);
    }

    //-[autocvtepi]-------------------------------------------------------
    HELPER_METHOD_FRAME_END();
}
FCIMPLEND


CSymMapToken::CSymMapToken(ISymUnmanagedWriter *pWriter, IMapToken *pMapToken)
{
    CONTRACTL {
        NOTHROW;
        GC_NOTRIGGER;
        // we know that the com implementation is ours so we use mode-any to simplify
        // having to switch mode 
        MODE_ANY; 
        FORBID_FAULT;
    }
    CONTRACTL_END;

    m_cRef = 1;
    m_pWriter = pWriter;
    m_pMapToken = pMapToken;
    if (m_pWriter)
        m_pWriter->AddRef();
    if (m_pMapToken)
        m_pMapToken->AddRef();
} // CSymMapToken::CSymMapToken()



//*********************************************************************
//
// CSymMapToken's destructor
//
//*********************************************************************
CSymMapToken::~CSymMapToken()
{
    CONTRACTL {
        NOTHROW;
        GC_NOTRIGGER;
        // we know that the com implementation is ours so we use mode-any to simplify
        // having to switch mode 
        MODE_ANY; 
        FORBID_FAULT;
    }
    CONTRACTL_END;

    if (m_pWriter)
        m_pWriter->Release();
    if (m_pMapToken)
        m_pMapToken->Release();
}   // CSymMapToken::~CMapToken()


ULONG CSymMapToken::AddRef()
{
    CONTRACTL {
        NOTHROW;
        GC_NOTRIGGER;
        MODE_ANY; 
        FORBID_FAULT;
    }
    CONTRACTL_END;

    return InterlockedIncrement(&m_cRef);
} // CSymMapToken::AddRef()



ULONG CSymMapToken::Release()
{
    CONTRACTL {
        NOTHROW;
        GC_NOTRIGGER;
        MODE_ANY; 
        FORBID_FAULT;
    }
    CONTRACTL_END;

    ULONG cRef = InterlockedDecrement(&m_cRef);
    if (!cRef)
        delete this;
    return (cRef);
} // CSymMapToken::Release()


HRESULT CSymMapToken::QueryInterface(REFIID riid, void **ppUnk)
{
    CONTRACTL {
        NOTHROW;
        GC_NOTRIGGER;
        MODE_ANY; 
        FORBID_FAULT;
    }
    CONTRACTL_END;

    *ppUnk = 0;

    if (riid == IID_IMapToken)
        *ppUnk = (IUnknown *) (IMapToken *) this;
    else
        return (E_NOINTERFACE);
    AddRef();
    return (S_OK);
}   // CSymMapToken::QueryInterface



//*********************************************************************
//
// catching the token mapping
//
//*********************************************************************
HRESULT CSymMapToken::Map(
    mdToken     tkFrom, 
    mdToken     tkTo)
{
    CONTRACTL {
        NOTHROW;
        GC_NOTRIGGER;
        MODE_ANY; 
        FORBID_FAULT;
    }
    CONTRACTL_END;

    HRESULT         hr = NOERROR;
    if (m_pWriter)
        IfFailGo( m_pWriter->RemapToken(tkFrom, tkTo) );
    if (m_pMapToken)
        IfFailGo( m_pMapToken->Map(tkFrom, tkTo) );
ErrExit:
    return hr;
}

About Koders | Resources | Downloads | Support | Black Duck | Terms of Service | DMCA | Privacy Policy | Contact Us