summaryrefslogtreecommitdiff
path: root/src/vm/encee.cpp
blob: 7f1264334058442c2f21fc019577e37ee3d405bf (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
// ===========================================================================
// File: EnC.CPP
//

//
// Handles EditAndContinue support in the EE
// ===========================================================================


#include "common.h"
#include "dbginterface.h"
#include "dllimport.h"
#include "eeconfig.h"
#include "excep.h"
#include "stackwalk.h"

#ifdef EnC_SUPPORTED

// can't get this on the helper thread at runtime in ResolveField, so make it static and get when add a field.
#ifdef _DEBUG
static int g_BreakOnEnCResolveField = -1;
#endif

#ifndef DACCESS_COMPILE


// Module initialization occurs in two phases: the constructor phase and the Initialize phase.
//
// The constructor phase initializes just enough so that Destruct() can be safely called.
// It cannot throw or fail.
//
EditAndContinueModule::EditAndContinueModule(Assembly *pAssembly, mdToken moduleRef, PEFile *file)
  : Module(pAssembly, moduleRef, file)
{
    CONTRACTL
    {
        NOTHROW;
        GC_TRIGGERS;
        FORBID_FAULT;
    }
    CONTRACTL_END

    LOG((LF_ENC,LL_INFO100,"EACM::ctor 0x%x\n", this));
    
    m_applyChangesCount = CorDB_DEFAULT_ENC_FUNCTION_VERSION;
}

// Module initialization occurs in two phases: the constructor phase and the Initialize phase.
//
// The Initialize() phase completes the initialization after the constructor has run.
// It can throw exceptions but whether it throws or succeeds, it must leave the Module
// in a state where Destruct() can be safely called.
//
/*virtual*/
void EditAndContinueModule::Initialize(AllocMemTracker *pamTracker)
{
    CONTRACTL
    {
        THROWS;
        GC_TRIGGERS;
        INJECT_FAULT(COMPlusThrowOM(););
    }
    CONTRACTL_END

    LOG((LF_ENC,LL_INFO100,"EACM::Initialize 0x%x\n", this));
    Module::Initialize(pamTracker);
}

// Called when the module is being destroyed (eg. AD unload time)
void EditAndContinueModule::Destruct()
{
    LIMITED_METHOD_CONTRACT;
    LOG((LF_ENC,LL_EVERYTHING,"EACM::Destruct 0x%x\n", this));

    // Call the superclass's Destruct method...
    Module::Destruct();
}

//---------------------------------------------------------------------------------------
//
// ApplyEditAndContinue - updates this module for an EnC
//
// Arguments:
//    cbDeltaMD  - number of bytes pointed to by pDeltaMD
//    pDeltaMD   - pointer to buffer holding the delta metadata
//    cbDeltaIL  - number of bytes pointed to by pDeltaIL
//    pDeltaIL   - pointer to buffer holding the delta IL
//
// Return Value:
//    S_OK on success.
//    if the edit fails for any reason, at any point in this function, 
//    we are toasted, so return out and IDE will end debug session.
//

HRESULT EditAndContinueModule::ApplyEditAndContinue(
    DWORD cbDeltaMD,
    BYTE *pDeltaMD,
    DWORD cbDeltaIL,
    BYTE *pDeltaIL)
{
    CONTRACTL
    {
        THROWS;
        GC_NOTRIGGER;
        MODE_COOPERATIVE;
    }
    CONTRACTL_END;

    // Update the module's EnC version number
    ++m_applyChangesCount;

    LOG((LF_ENC, LL_INFO100, "EACM::AEAC:\n"));

#ifdef _DEBUG
    // Debugging hook to optionally break when this method is called
    static BOOL shouldBreak = -1;
    if (shouldBreak == -1)
        shouldBreak = CLRConfig::GetConfigValue(CLRConfig::INTERNAL_EncApplyChanges);
    if (shouldBreak > 0) {
        _ASSERTE(!"EncApplyChanges");
    }

    // Debugging hook to dump out all edits to dmeta and dil files
    static BOOL dumpChanges = -1;

    if (dumpChanges == -1)

        dumpChanges = CLRConfig::GetConfigValue(CLRConfig::INTERNAL_EncDumpApplyChanges);

    if (dumpChanges> 0) {
        SString fn;
        int ec;
        fn.Printf(W("ApplyChanges.%d.dmeta"), m_applyChangesCount);
        FILE *fp;
        ec = _wfopen_s(&fp, fn.GetUnicode(), W("wb"));
        _ASSERTE(SUCCEEDED(ec));
        fwrite(pDeltaMD, 1, cbDeltaMD, fp);
        fclose(fp);
        fn.Printf(W("ApplyChanges.%d.dil"), m_applyChangesCount);
        ec = _wfopen_s(&fp, fn.GetUnicode(), W("wb"));
        _ASSERTE(SUCCEEDED(ec));
        fwrite(pDeltaIL, 1, cbDeltaIL, fp);
        fclose(fp);
    }
#endif

    HRESULT hr = S_OK;
    HENUMInternal enumENC;

    BYTE *pLocalILMemory = NULL;
    IMDInternalImport *pMDImport = NULL;
    IMDInternalImport *pNewMDImport = NULL;

    CONTRACT_VIOLATION(GCViolation);    // SafeComHolder goes to preemptive mode, which will trigger a GC
    SafeComHolder<IMDInternalImportENC> pIMDInternalImportENC;
    SafeComHolder<IMetaDataEmit> pEmitter;

    // Apply the changes. Note that ApplyEditAndContinue() requires read/write metadata. If the metadata is
    // not already RW, then ApplyEditAndContinue() will perform the conversion, invalidate the current 
    // metadata importer, and return us a new one.  We can't let that happen. Other parts of the system are
    // already using the current metadata importer, some possibly in preemptive GC mode at this very moment.
    // Instead, we ensure that the metadata is RW by calling ConvertMDInternalToReadWrite(), which will make
    // a new importer if necessary and ensure that new accesses to the metadata use that while still managing
    // the lifetime of the old importer. Therefore, we can be sure that ApplyEditAndContinue() won't need to
    // make a new importer.

    // Ensure the metadata is RW.
    EX_TRY
    {
        // ConvertMetadataToRWForEnC should only ever be called on EnC capable files.
        _ASSERTE(IsEditAndContinueCapable()); // this also checks that the file is EnC capable
        GetFile()->ConvertMetadataToRWForEnC();
    }
    EX_CATCH_HRESULT(hr);

    IfFailGo(hr);

    // Grab the current importer.
    pMDImport = GetMDImport();

    // Apply the EnC delta to this module's metadata.
    IfFailGo(pMDImport->ApplyEditAndContinue(pDeltaMD, cbDeltaMD, &pNewMDImport));

    // The importer should not have changed!  We assert that, and back-stop in a retail build just to be sure.
    if (pNewMDImport != pMDImport) 
    {
        _ASSERTE( !"ApplyEditAndContinue should not have needed to create a new metadata importer!" );
        IfFailGo(CORDBG_E_ENC_INTERNAL_ERROR);
    }

    // get the delta interface
    IfFailGo(pMDImport->QueryInterface(IID_IMDInternalImportENC, (void **)&pIMDInternalImportENC));

    // get an emitter interface
    IfFailGo(GetMetaDataPublicInterfaceFromInternal(pMDImport, IID_IMetaDataEmit, (void **)&pEmitter));

    // Copy the deltaIL into our RVAable IL memory
    pLocalILMemory = new BYTE[cbDeltaIL];
    memcpy(pLocalILMemory, pDeltaIL, cbDeltaIL);

    // Enumerate all of the EnC delta tokens 
    memset(&enumENC, 0, sizeof(HENUMInternal));
    IfFailGo(pIMDInternalImportENC->EnumDeltaTokensInit(&enumENC));

    mdToken token;
    while (pIMDInternalImportENC->EnumNext(&enumENC, &token)) 
    {
        STRESS_LOG3(LF_ENC, LL_INFO100, "EACM::AEAC: updated token 0x%x; type 0x%x; rid 0x%x\n", token, TypeFromToken(token), RidFromToken(token));

        switch (TypeFromToken(token)) 
        {
            case mdtMethodDef:
                
                // MethodDef token - update/add a method
                LOG((LF_ENC, LL_INFO10000, "EACM::AEAC: Found method 0x%x\n", token));
        
                ULONG dwMethodRVA;  
                DWORD dwMethodFlags;
                IfFailGo(pMDImport->GetMethodImplProps(token, &dwMethodRVA, &dwMethodFlags));
                
                if (dwMethodRVA >= cbDeltaIL)
                {
                    LOG((LF_ENC, LL_INFO10000, "EACM::AEAC:   failure RVA of %d with cbDeltaIl %d\n", dwMethodRVA, cbDeltaIL));
                    IfFailGo(E_INVALIDARG);
                }
                
                SetDynamicIL(token, (TADDR)(pLocalILMemory + dwMethodRVA), FALSE);
                
                // use module to resolve to method
                MethodDesc *pMethod;
                pMethod = LookupMethodDef(token);
                if (pMethod)
                {
                    // Method exists already - update it
                    IfFailGo(UpdateMethod(pMethod));
                }
                else
                {
                    // This is a new method token - create a new method
                    IfFailGo(AddMethod(token));
                }

                break;
                
            case mdtFieldDef:
            
                // FieldDef token - add a new field
                LOG((LF_ENC, LL_INFO10000, "EACM::AEAC: Found field 0x%x\n", token));

                if (LookupFieldDef(token)) 
                {
                    // Field already exists - just ignore for now
                    continue;
                }

                // Field is new - add it 
                IfFailGo(AddField(token));
                break;
                
            case mdtTypeRef:
                EnsureTypeRefCanBeStored(token);
                break;

            case mdtAssemblyRef:
                EnsureAssemblyRefCanBeStored(token);
                break;
        }
    }

ErrExit:
    if (pIMDInternalImportENC)
        pIMDInternalImportENC->EnumClose(&enumENC);

    return hr;
}

//---------------------------------------------------------------------------------------
//
// UpdateMethod - called when a method has been updated by EnC.
//
// The module's metadata has already been updated.  Here we notify the 
// debugger of the update, and swap the new IL in as the current
// version of the method.
//
// Arguments:
//   pMethod  - the method being updated
//
// Return Value:
//    S_OK on success.
//    if the edit fails for any reason, at any point in this function, 
//    we are toasted, so return out and IDE will end debug session.
//
// Assumptions:
//    The CLR must be suspended for debugging.
//
HRESULT EditAndContinueModule::UpdateMethod(MethodDesc *pMethod)
{
    CONTRACTL
    {
        THROWS;
        GC_NOTRIGGER;
        MODE_COOPERATIVE;
    }
    CONTRACTL_END;

    // Notify the debugger of the update
    HRESULT hr = g_pDebugInterface->UpdateFunction(pMethod, m_applyChangesCount);
    if (FAILED(hr))
    {
        return hr;
    }

    // Notify the JIT that we've got new IL for this method
    // This will ensure that all new calls to the method will go to the new version.
    // The runtime does this by never backpatching the methodtable slots in EnC-enabled modules.
    LOG((LF_ENC, LL_INFO100000, "EACM::UM: Updating function %s to version %d\n", pMethod->m_pszDebugMethodName, m_applyChangesCount));

    // Reset any flags relevant to the old code
    //
    // Note that this only works since we've very carefullly made sure that _all_ references
    // to the Method's code must be to the call/jmp blob immediately in front of the
    // MethodDesc itself.  See MethodDesc::IsEnCMethod()
    //
    pMethod->Reset();

    return S_OK;
}

//---------------------------------------------------------------------------------------
//
// AddMethod - called when a new method is added by EnC.
//
// The module's metadata has already been updated.  Here we notify the 
// debugger of the update, and create and add a new MethodDesc to the class.
//
// Arguments:
//   token    - methodDef token for the method being added
//
// Return Value:
//    S_OK on success.
//    if the edit fails for any reason, at any point in this function, 
//    we are toasted, so return out and IDE will end debug session.
//
// Assumptions:
//    The CLR must be suspended for debugging.
//
HRESULT EditAndContinueModule::AddMethod(mdMethodDef token)
{
    CONTRACTL
    {
        THROWS;
        GC_NOTRIGGER;
        MODE_COOPERATIVE;
    }
    CONTRACTL_END;

    mdTypeDef   parentTypeDef;
    HRESULT hr = GetMDImport()->GetParentToken(token, &parentTypeDef); 
    if (FAILED(hr))
    {
        LOG((LF_ENC, LL_INFO100, "**Error** EnCModule::AM can't find parent token for method token %p\n", token));
        return E_FAIL;
    }

    // see if the class is loaded yet. 
    MethodTable * pParentType = LookupTypeDef(parentTypeDef).AsMethodTable();
    if (pParentType == NULL)
    {
        // Class isn't loaded yet, don't have to modify any existing EE data structures beyond the metadata.
        // Just notify debugger and return.
        LOG((LF_ENC, LL_INFO100, "EnCModule::AM class %p not loaded, our work is done\n", parentTypeDef));
        hr = g_pDebugInterface->UpdateNotYetLoadedFunction(token, this, m_applyChangesCount);
        return hr;
    }

    // Add the method to the runtime's Class data structures
    LOG((LF_ENC, LL_INFO100000, "EACM::AM: Adding function %p\n", token));
    MethodDesc *pMethod = NULL;
    hr = EEClass::AddMethod(pParentType, token, 0, &pMethod);

    if (FAILED(hr))
    {
        _ASSERTE(!"Failed to add function");
        LOG((LF_ENC, LL_INFO100000, "**Error** EACM::AM: Failed to add function %p  with hr 0x%x\n", token));
        return hr;
    }

    // Tell the debugger about the new method so it get's the version number properly
    hr = g_pDebugInterface->AddFunction(pMethod, m_applyChangesCount);
    if (FAILED(hr))
    {
        _ASSERTE(!"Failed to add function");
        LOG((LF_ENC, LL_INFO100000, "**Error** EACM::AF: Failed to add method %p to debugger with hr 0x%x\n", token));
    }
    
    return hr;    
}

//---------------------------------------------------------------------------------------
//
// AddField - called when a new field is added by EnC.
//
// The module's metadata has already been updated.  Here we notify the 
// debugger of the update, 
//
// Arguments:
//   token    - fieldDef for the field being added
//
// Return Value:
//    S_OK on success.
//    if the edit fails for any reason, at any point in this function, 
//    we are toasted, so return out and IDE will end debug session.
//
// Assumptions:
//    The CLR must be suspended for debugging.
//
HRESULT EditAndContinueModule::AddField(mdFieldDef token)
{
    CONTRACTL
    {
        THROWS;
        GC_NOTRIGGER;
        MODE_COOPERATIVE;
    }
    CONTRACTL_END;

    mdTypeDef   parentTypeDef;
    HRESULT hr = GetMDImport()->GetParentToken(token, &parentTypeDef); 

    if (FAILED(hr))
    {
        LOG((LF_ENC, LL_INFO100, "**Error** EnCModule::AF can't find parent token for field token %p\n", token));
        return E_FAIL;
    }

    // see if the class is loaded yet. If not we don't need to do anything.  When this class is 
    // loaded (with the updated metadata), it will have this field like any other normal field.
    // If the class hasn't been loaded, than the debugger shouldn't know anything about it
    // so there shouldn't be any harm in not notifying it of the update.  For completeness,
    // we may want to consider changing this to notify the debugger here as well.
    MethodTable * pParentType = LookupTypeDef(parentTypeDef).AsMethodTable();
    if (pParentType == NULL)
    {
        LOG((LF_ENC, LL_INFO100, "EnCModule::AF class %p not loaded, our work is done\n", parentTypeDef));
        return S_OK;
    }

    // Create a new EnCFieldDesc for the field and add it to the class
    LOG((LF_ENC, LL_INFO100000, "EACM::AM: Adding field %p\n", token));
    EnCFieldDesc *pField;
    hr = EEClass::AddField(pParentType, token, &pField);

    if (FAILED(hr))
    {
        LOG((LF_ENC, LL_INFO100000, "**Error** EACM::AF: Failed to add field %p to EE  with hr 0x%x\n", token));
        return hr;
    }

    // Tell the debugger about the new field
    hr = g_pDebugInterface->AddField(pField, m_applyChangesCount);
    if (FAILED(hr))
    {
        LOG((LF_ENC, LL_INFO100000, "**Error** EACM::AF: Failed to add field %p to debugger with hr 0x%x\n", token));
    }

#ifdef _DEBUG
    if (g_BreakOnEnCResolveField == -1)
    {
        g_BreakOnEnCResolveField = CLRConfig::GetConfigValue(CLRConfig::INTERNAL_EnCResolveField);
    }
#endif

    return hr;
}

//---------------------------------------------------------------------------------------
//
// JitUpdatedFunction - Jit the new version of a function for EnC.
//
// Arguments:
//  pMD          - the MethodDesc for the method we want to JIT
//  pOrigContext - context of thread pointing into original version of the function
//
// Return value:
//  Return the address of the newly jitted code or NULL on failure.
//
PCODE EditAndContinueModule::JitUpdatedFunction( MethodDesc *pMD,
                                                 CONTEXT *pOrigContext)
{
    CONTRACTL 
    {
        NOTHROW;
        GC_TRIGGERS;
        MODE_ANY;
    }
    CONTRACTL_END;    

    LOG((LF_ENC, LL_INFO100, "EnCModule::JitUpdatedFunction for %s\n",
        pMD->m_pszDebugMethodName));

    PCODE jittedCode = NULL;

    GCX_COOP();

#ifdef _DEBUG
    BOOL shouldBreak = CLRConfig::GetConfigValue(
                                          CLRConfig::INTERNAL_EncJitUpdatedFunction);
    if (shouldBreak > 0) {
        _ASSERTE(!"EncJitUpdatedFunction");
    }
#endif
    
    // Setup a frame so that has context for the exception
    // so that gc can crawl the stack and do the right thing.  
    _ASSERTE(pOrigContext);
    Thread *pCurThread = GetThread();
    _ASSERTE(pCurThread);
    FrameWithCookie<ResumableFrame> resFrame(pOrigContext);
    resFrame.Push(pCurThread);

    CONTEXT *pCtxTemp = NULL;
    // We need to zero out the filter context so a multi-threaded GC doesn't result
    // in somebody else tracing this thread & concluding that we're in JITted code.
    // We need to remove the filter context so that if we're in preemptive GC
    // mode, we'll either have the filter context, or the ResumableFrame,
    // but not both, set.
    // Since we're in cooperative mode here, we can swap the two non-atomically here.
    pCtxTemp = pCurThread->GetFilterContext();
    _ASSERTE(pCtxTemp != NULL); // currently called from within a filter context, protects us during GC-toggle.
    pCurThread->SetFilterContext(NULL); 
    
    // get the code address (may jit the fcn if not already jitted)
    EX_TRY {
        if (!pMD->IsPointingToNativeCode())
        {
            GCX_PREEMP();
            pMD->DoPrestub(NULL);
            LOG((LF_ENC, LL_INFO100, "EnCModule::ResumeInUpdatedFunction JIT successful\n"));
        }
        else
        {
            LOG((LF_ENC, LL_INFO100, "EnCModule::ResumeInUpdatedFunction function already JITed\n"));
        }
        jittedCode = pMD->GetNativeCode();
    } EX_CATCH {
#ifdef _DEBUG
        {
            // This is debug-only code to print out the error string, but SString can throw.
            // This function is no-throw, and we can't put an EX_TRY inside an EX_CATCH block, so
            // we just have the violation.
            CONTRACT_VIOLATION(ThrowsViolation);
        
            StackSString exceptionMessage;
            SString errorMessage;
            GetExceptionMessage(GET_THROWABLE(), exceptionMessage);
            errorMessage.AppendASCII("**Error: Probable rude edit.**\n\n"
                                "EnCModule::JITUpdatedFunction JIT failed with the following exception:\n\n");
            errorMessage.Append(exceptionMessage);
            StackScratchBuffer buffer;
            DbgAssertDialog(__FILE__, __LINE__, errorMessage.GetANSI(buffer));
            LOG((LF_ENC, LL_INFO100, errorMessage.GetANSI(buffer)));
        }
#endif        
    } EX_END_CATCH(SwallowAllExceptions)

    resFrame.Pop(pCurThread);

    // Restore the filter context here (see comment above)
    pCurThread->SetFilterContext(pCtxTemp); 
    
    return jittedCode;
}


//-----------------------------------------------------------------------------
// Called by EnC to resume the code in a new version of the function.
// This will:
// 1) jit the new function 
// 2) set the IP to newILOffset within that new function
// 3) adjust local variables (particularly enregistered vars) to the new func.
// It will not return.
//
// Params:
//  pMD - method desc for method being updated. This is not enc-version aware.
//  oldDebuggerFuncHandle - Debugger DJI to uniquely identify old function.
//    This is enc-version aware.
//  newILOffset - the IL offset to resume execution at within the new function.
//  pOrigContext - context of thread pointing into original version of the function.
//  
// This function must be called on the thread that's executing the old function.
// This function does not return. Instead, it will remap this thread directly
// to be executing the new function.
//-----------------------------------------------------------------------------
HRESULT EditAndContinueModule::ResumeInUpdatedFunction(
    MethodDesc *pMD, 
    void *oldDebuggerFuncHandle,
    SIZE_T newILOffset, 
    CONTEXT *pOrigContext)
{   
    LOG((LF_ENC, LL_INFO100, "EnCModule::ResumeInUpdatedFunction for %s at IL offset 0x%x, ", 
        pMD->m_pszDebugMethodName, newILOffset));

#ifdef _DEBUG
    BOOL shouldBreak = CLRConfig::GetConfigValue(
                                          CLRConfig::INTERNAL_EncResumeInUpdatedFunction);
    if (shouldBreak > 0) {
        _ASSERTE(!"EncResumeInUpdatedFunction");
    }
#endif

    HRESULT hr = E_FAIL;
    
    // JIT-compile the updated version of the method
    PCODE jittedCode = JitUpdatedFunction(pMD, pOrigContext);
    if ( jittedCode == NULL )
        return CORDBG_E_ENC_JIT_CANT_UPDATE;
    
    GCX_COOP();

    // This will create a new frame and copy old vars to it
    // need pointer to old & new code, old & new info

    EECodeInfo oldCodeInfo(GetIP(pOrigContext));
    _ASSERTE(oldCodeInfo.GetMethodDesc() == pMD);

    // Get the new native offset & IP from the new IL offset
    LOG((LF_ENC, LL_INFO10000, "EACM::RIUF: About to map IL forwards!\n"));
    SIZE_T newNativeOffset = 0;
    g_pDebugInterface->MapILInfoToCurrentNative(pMD, 
                                                newILOffset, 
                                                jittedCode, 
                                                &newNativeOffset);

    EECodeInfo newCodeInfo(jittedCode + newNativeOffset);
    _ASSERTE(newCodeInfo.GetMethodDesc() == pMD);

    _ASSERTE(newCodeInfo.GetRelOffset() == newNativeOffset);

    _ASSERTE(oldCodeInfo.GetCodeManager() == newCodeInfo.GetCodeManager());

    DWORD oldFrameSize = oldCodeInfo.GetFixedStackSize();
    DWORD newFrameSize = newCodeInfo.GetFixedStackSize();

    // FixContextAndResume() will replace the old stack frame of the function with the new
    // one and will initialize that new frame to null. Anything on the stack where that new
    // frame sits will be wiped out. This could include anything on the stack right up to or beyond our
    // current stack from in ResumeInUpdatedFunction. In order to prevent our current frame from being
    // trashed we determine the maximum amount that the stack could grow by and allocate this as a buffer using
    // alloca. Then we call FixContextAndResume which can safely rely on the stack because none of it's frames 
    // state or anything lower can be reached by the new frame. 

    if( newFrameSize > oldFrameSize) 
    {
        DWORD frameIncrement = newFrameSize - oldFrameSize;
        (void)alloca(frameIncrement);
    }

    // Ask the EECodeManager to actually fill in the context and stack for the new frame so that
    // values of locals etc. are preserved.
    LOG((LF_ENC, LL_INFO100, "EnCModule::ResumeInUpdatedFunction calling FixContextAndResume oldNativeOffset: 0x%x, newNativeOffset: 0x%x," 
        "oldFrameSize: 0x%x, newFrameSize: 0x%x\n", 
        oldCodeInfo.GetRelOffset(), newCodeInfo.GetRelOffset(), oldFrameSize, newFrameSize));

    FixContextAndResume(pMD, 
                        oldDebuggerFuncHandle,
                        pOrigContext,
                        &oldCodeInfo,
                        &newCodeInfo);

    // At this point we shouldn't have failed, so this is genuinely erroneous.
    LOG((LF_ENC, LL_ERROR, "**Error** EnCModule::ResumeInUpdatedFunction returned from ResumeAtJit"));
    _ASSERTE(!"Should not return from FixContextAndResume()");

    hr = E_FAIL;

    // If we fail for any reason we have already potentially trashed with new locals and we have also unwound any
    // Win32 handlers on the stack so cannot ever return from this function. 
    EEPOLICY_HANDLE_FATAL_ERROR(CORDBG_E_ENC_INTERNAL_ERROR);
}

//---------------------------------------------------------------------------------------
//
// FixContextAndResume - Modify the thread context for EnC remap and resume execution
// 
// Arguments:
//    pMD      - MethodDesc for the method being remapped
//    oldDebuggerFuncHandle - Debugger DJI to uniquely identify old function.
//    pContext - the thread's original CONTEXT when the remap opportunity was hit
//    pOldCodeInfo - collection of various information about the current frame state
//    pNewCodeInfo - information about how we want the frame state to be after the remap
//
// Return Value:
//    Doesn't return
//
// Notes:
//   WARNING: This method cannot access any stack-data below its frame on the stack
//   (i.e. anything allocated in a caller frame), so all stack-based arguments must 
//   EXPLICITLY be copied by value and this method cannot be inlined.  We may need to expand 
//   the stack frame to accomodate the new method, and so extra buffer space must have 
//   been allocated on the stack.  Note that passing a struct by value (via C++) is not
//   enough to ensure its data is really copied (on x64, large structs may internally be
//   passed by reference).  Thus we explicitly make copies of structs passed in, at the
//   beginning.
//

NOINLINE void EditAndContinueModule::FixContextAndResume(
        MethodDesc *pMD, 
        void *oldDebuggerFuncHandle,
        T_CONTEXT *pContext,
        EECodeInfo *pOldCodeInfo,
        EECodeInfo *pNewCodeInfo)
{
    STATIC_CONTRACT_MODE_COOPERATIVE;
    STATIC_CONTRACT_GC_TRIGGERS; // Sends IPC event
    STATIC_CONTRACT_THROWS;

    // Create local copies of all structs passed as arguments to prevent them from being overwritten
    CONTEXT context;
    memcpy(&context, pContext, sizeof(CONTEXT));
    pContext = &context;

#if defined(_TARGET_AMD64_)
    // Since we made a copy of the incoming CONTEXT in context, clear any new flags we
    // don't understand (like XSAVE), since we'll eventually be passing a CONTEXT based
    // on this copy to RtlRestoreContext, and this copy doesn't have the extra info
    // required by the XSAVE or other flags.
    // 
    // FUTURE: No reason to ifdef this for amd64-only, except to make this late fix as
    // surgical as possible.  Would be nice to enable this on x86 early in the next cycle.
    pContext->ContextFlags &= CONTEXT_ALL;
#endif // defined(_TARGET_AMD64_)        

    EECodeInfo oldCodeInfo;
    memcpy(&oldCodeInfo, pOldCodeInfo, sizeof(EECodeInfo));
    pOldCodeInfo = &oldCodeInfo;

    EECodeInfo newCodeInfo;
    memcpy(&newCodeInfo, pNewCodeInfo, sizeof(EECodeInfo));
    pNewCodeInfo = &newCodeInfo;

    const ICorDebugInfo::NativeVarInfo *pOldVarInfo = NULL;
    const ICorDebugInfo::NativeVarInfo *pNewVarInfo = NULL;
    SIZE_T oldVarInfoCount = 0;
    SIZE_T newVarInfoCount = 0;

    // Get the var info which the codemanager will use for updating 
    // enregistered variables correctly, or variables whose lifetimes differ
    // at the update point
    g_pDebugInterface->GetVarInfo(pMD, oldDebuggerFuncHandle, &oldVarInfoCount, &pOldVarInfo);
    g_pDebugInterface->GetVarInfo(pMD, NULL,                  &newVarInfoCount, &pNewVarInfo);

#ifdef _TARGET_X86_
    // save the frame pointer as FixContextForEnC might step on it.
    LPVOID oldSP = dac_cast<PTR_VOID>(GetSP(pContext));
    
    // need to pop the SEH records before write over the stack in FixContextForEnC
    PopSEHRecords(oldSP);
#endif

    // Ask the EECodeManager to actually fill in the context and stack for the new frame so that
    // values of locals etc. are preserved.
    HRESULT hr = pNewCodeInfo->GetCodeManager()->FixContextForEnC(
                    pContext,
                    pOldCodeInfo,
                    pOldVarInfo, oldVarInfoCount,
                    pNewCodeInfo,
                    pNewVarInfo, newVarInfoCount);

    // If FixContextForEnC succeeded, the stack is potentially trashed with any new locals and we have also unwound
    // any Win32 handlers on the stack so cannot ever return from this function. If FixContextForEnC failed, can't
    // assume that the stack is still intact so apply the proper policy for a fatal EE error to bring us down
    // "gracefully" (it's all relative).
    if (FAILED(hr))
    {
        LOG((LF_ENC, LL_INFO100, "**Error** EnCModule::ResumeInUpdatedFunction for FixContextForEnC failed\n"));
        EEPOLICY_HANDLE_FATAL_ERROR(hr);
    }

    // Set the new IP
    // Note that all we're really doing here is setting the IP register.  We unfortunately don't
    // share any code with the implementation of debugger SetIP, despite the similarities.
    LOG((LF_ENC, LL_INFO100, "EnCModule::ResumeInUpdatedFunction: Resume at EIP=0x%x\n", pNewCodeInfo->GetCodeAddress()));

    Thread *pCurThread = GetThread();
    _ASSERTE(pCurThread);

    pCurThread->SetFilterContext(pContext);
    SetIP(pContext, pNewCodeInfo->GetCodeAddress());

    // Notify the debugger that we're about to resume execution in the new version of the method
    HRESULT hrIgnore = g_pDebugInterface->RemapComplete(pMD, pNewCodeInfo->GetCodeAddress(), pNewCodeInfo->GetRelOffset());

    // Now jump into the new version of the method. Note that we can't just setup the filter context 
    // and return because we are potentially writing new vars onto the stack.
    pCurThread->SetFilterContext( NULL );

#if defined(_TARGET_X86_)        
    ResumeAtJit(pContext, oldSP);
#else
    RtlRestoreContext(pContext, NULL);
#endif

    // At this point we shouldn't have failed, so this is genuinely erroneous.
    LOG((LF_ENC, LL_ERROR, "**Error** EnCModule::ResumeInUpdatedFunction returned from ResumeAtJit"));
    _ASSERTE(!"Should not return from ResumeAtJit()");
}
#endif // #ifndef DACCESS_COMPILE

//---------------------------------------------------------------------------------------
// ResolveField - get a pointer to the value of a field that was added by EnC
//
// Arguments:
//   thisPointer  - For instance fields, a pointer to the object instance of interest.
//                  For static fields this is unused and should be NULL.
//   pFD          - FieldDesc describing the field we're interested in
//   fAllocateNew - If storage doesn't yet exist for this field and fAllocateNew is true
//                  then we will attempt to allocate the storage (throwing an exception
//                  if it fails).  Otherwise, if fAllocateNew is false, then we will just
//                  return NULL when the storage is not yet available.
//
// Return Value:
//      If storage doesn't yet exist for this field we return NULL, otherwise, we return a pointer 
//      to the contents of the field on success.  
//---------------------------------------------------------------------------------------
PTR_CBYTE EditAndContinueModule::ResolveField(OBJECTREF      thisPointer, 
                                              EnCFieldDesc * pFD)
{
    CONTRACTL
    {
        GC_NOTRIGGER; 
        NOTHROW;
        SUPPORTS_DAC;
    }
    CONTRACTL_END;
        
#ifdef _DEBUG
    if (g_BreakOnEnCResolveField == 1)
    {
        _ASSERTE( !"EditAndContinueModule::ResolveField");
    }
#endif

    // If it's static, we stash in the EnCFieldDesc
    if (pFD->IsStatic())
    {
        _ASSERTE( thisPointer == NULL );
        EnCAddedStaticField *pAddedStatic = pFD->GetStaticFieldData();
        if (!pAddedStatic)
        {
            return NULL;
        }
        
        _ASSERTE( pAddedStatic->m_pFieldDesc == pFD );
        return PTR_CBYTE(pAddedStatic->GetFieldData());
    }

    // not static so get it out of the syncblock
    SyncBlock * pBlock = NULL;

    // Get the SyncBlock, failing if not available
    pBlock = thisPointer->PassiveGetSyncBlock();
    if( pBlock == NULL )
    {
        return NULL;
    }

    EnCSyncBlockInfo * pEnCInfo = NULL;    

    // Attempt to get the EnC information from the sync block
    pEnCInfo = pBlock->GetEnCInfo();
    
    if (!pEnCInfo) 
    {
        // No EnC info on this object yet, fail since we don't want to allocate it
        return NULL;
    }

    // Lookup the actual field value from the EnCSyncBlockInfo
    return pEnCInfo->ResolveField(thisPointer, pFD);      
} // EditAndContinueModule::ResolveField

#ifndef DACCESS_COMPILE
//---------------------------------------------------------------------------------------
// ResolveOrAllocateField - get a pointer to the value of a field that was added by EnC, 
// allocating storage for it if necessary
//
// Arguments:
//   thisPointer  - For instance fields, a pointer to the object instance of interest.
//                  For static fields this is unused and should be NULL.
//   pFD          - FieldDesc describing the field we're interested in
// Return Value:
//      Returns a pointer to the contents of the field on success. This should only fail due 
//      to out-of-memory and will therefore throw an OOM exception.
//---------------------------------------------------------------------------------------
PTR_CBYTE EditAndContinueModule::ResolveOrAllocateField(OBJECTREF      thisPointer, 
                                                        EnCFieldDesc * pFD)
{
    CONTRACTL
    {
        GC_TRIGGERS; 
        THROWS;
    }
    CONTRACTL_END;
    
    // first try getting a pre-existing field
    PTR_CBYTE fieldAddr = ResolveField(thisPointer, pFD);
    if (fieldAddr != NULL)
    {
        return fieldAddr;
    }

    // we didn't find the field already allocated
    if (pFD->IsStatic())
    {
        _ASSERTE(thisPointer == NULL);
        EnCAddedStaticField * pAddedStatic = pFD->GetOrAllocateStaticFieldData();
        _ASSERTE(pAddedStatic->m_pFieldDesc == pFD);
        return PTR_CBYTE(pAddedStatic->GetFieldData());
    }

     // not static so get it out of the syncblock
    SyncBlock* pBlock = NULL;

    // Get the SyncBlock, creating it if necessary
    pBlock = thisPointer->GetSyncBlock();
    
    EnCSyncBlockInfo * pEnCInfo = NULL;    

    // Attempt to get the EnC information from the sync block
    pEnCInfo = pBlock->GetEnCInfo();

    if (!pEnCInfo) 
    {
        // Attach new EnC field info to this object.
        pEnCInfo = new EnCSyncBlockInfo;
        if (!pEnCInfo) 
        {
            COMPlusThrowOM();
        }
        pBlock->SetEnCInfo(pEnCInfo);
    }

    // Lookup the actual field value from the EnCSyncBlockInfo
    return pEnCInfo->ResolveOrAllocateField(thisPointer, pFD);      
} // EditAndContinueModule::ResolveOrAllocateField

#endif // !DACCESS_COMPILE

//-----------------------------------------------------------------------------
// Get or optionally create an EnCEEClassData object for the specified
// EEClass in this module.
// 
// Arguments:
//   pClass  - the EEClass of interest
//   getOnly - if false (the default), we'll create a new entry of none exists yet
//   
// Note: If called in a DAC build, GetOnly must be TRUE
//
PTR_EnCEEClassData EditAndContinueModule::GetEnCEEClassData(MethodTable * pMT, BOOL getOnly /*=FALSE*/ )
{
    CONTRACTL 
    {
        NOTHROW;
        GC_NOTRIGGER;
        SUPPORTS_DAC;
    } CONTRACTL_END;

#ifdef DACCESS_COMPILE
    _ASSERTE(getOnly == TRUE);
#endif // DACCESS_COMPILE

    DPTR(PTR_EnCEEClassData) ppData = m_ClassList.Table();
    DPTR(PTR_EnCEEClassData) ppLast = ppData + m_ClassList.Count();

    // Look for an existing entry for the specified class
    while (ppData < ppLast)
    {
        PREFIX_ASSUME(ppLast != NULL);
        if ((*ppData)->GetMethodTable() == pMT)
            return *ppData;
        ++ppData;
    }

    // No match found. Return now if we don't want to create a new entry
    if (getOnly)
    {
        return NULL;
    }

#ifndef DACCESS_COMPILE
    // Create a new entry and add it to the end our our table
    EnCEEClassData *pNewData = (EnCEEClassData*)(void*)pMT->GetLoaderAllocator()->GetLowFrequencyHeap()->AllocMem_NoThrow(S_SIZE_T(sizeof(EnCEEClassData)));
    pNewData->Init(pMT);
    ppData = m_ClassList.Append();
    if (!ppData)
        return NULL;
    *ppData = pNewData;
    return pNewData;
#else
    DacNotImpl();
    return NULL;
#endif
}

// Computes the address of this field within the object "o"
void *EnCFieldDesc::GetAddress( void *o)
{
#ifndef DACCESS_COMPILE
    CONTRACTL {
        THROWS;
        GC_TRIGGERS;
    } CONTRACTL_END;

    // can't throw through FieldDesc::GetInstanceField if FORBIDGC_LOADER_USE_ENABLED
    _ASSERTE(! FORBIDGC_LOADER_USE_ENABLED());

    EditAndContinueModule *pModule = (EditAndContinueModule*)GetModule();
    _ASSERTE(pModule->IsEditAndContinueEnabled());

    // EnC added fields aren't just at some static offset in the object like normal fields
    // are.  Get the EditAndContinueModule to compute the address for us.
    return (void *)pModule->ResolveOrAllocateField(ObjectToOBJECTREF((Object *)o), this);
#else
    DacNotImpl();
    return NULL;
#endif
}

#ifndef DACCESS_COMPILE

// Do simple field initialization 
// We do this when the process is suspended for debugging (in a GC_NOTRIGGER).
// Full initialization will be done in Fixup when the process is running.
void EnCFieldDesc::Init(mdFieldDef token, BOOL fIsStatic)
{
    CONTRACTL
    {
        THROWS;
        GC_NOTRIGGER;
        MODE_COOPERATIVE;
    }
    CONTRACTL_END;

    // Clear out the FieldDesc incase someone attempts to use any of the fields
    memset( this, 0, sizeof(EnCFieldDesc) );

    // Initialize our members
    m_pStaticFieldData = NULL;
    m_bNeedsFixup = TRUE;

    // Initialize the bare minimum of FieldDesc necessary for now
    if (fIsStatic) 
        FieldDesc::m_isStatic = TRUE;

    SetMemberDef(token);

    SetEnCNew();
}

// Allocate a new EnCAddedField instance and hook it up to hold the value for an instance 
// field which was added by EnC to the specified object.  This effectively adds a reference from
// the object to the new field value so that the field's lifetime is managed properly.
//
// Arguments:
//  pFD         - description of the field being added
//  thisPointer - object instance to attach the new field to
//
EnCAddedField *EnCAddedField::Allocate(OBJECTREF thisPointer, EnCFieldDesc *pFD)
{
    CONTRACTL 
    {
        THROWS;
        GC_TRIGGERS;
        MODE_COOPERATIVE;
    }
    CONTRACTL_END;

    LOG((LF_ENC, LL_INFO1000, "\tEnCAF:Allocate for this %p, FD %p\n", thisPointer, pFD->GetMemberDef()));

    // Create a new EnCAddedField instance
    EnCAddedField *pEntry = new EnCAddedField;
    pEntry->m_pFieldDesc = pFD;

    _ASSERTE(!pFD->GetApproxEnclosingMethodTable()->IsDomainNeutral());
    AppDomain *pDomain = (AppDomain*) pFD->GetApproxEnclosingMethodTable()->GetDomain();

    // We need to associate the contents of the new field with the object it is attached to 
    // in a way that mimics the lifetime behavior of a normal field reference.  Specifically,
    // when the object is collected, the field should also be collected (assuming there are no
    // other references), but references to the field shouldn't keep the object alive.
    // To acheive this, we have introduced the concept of a "dependent handle" which provides
    // the appropriate semantics.  The dependent handle has a weak reference to a "primary object"
    // (the object getting a new field in this case), and a strong reference to a secondary object.
    // When the primary object is collected, the reference to the secondary object is released.
    // See the definition of code:HNDTYPE_DEPENDENT and code:Ref_ScanDependentHandles for more details.
    //  
    // We create a helper object and store it as the secondary object in the dependant handle
    // so that its liveliness can be maintained along with the primary object.
    // The helper then contains an object reference to the real field value that we are adding. 
    // The reason for doing this is that we cannot hand out the handle address for
    // the OBJECTREF address so we need to hand out something else that is hooked up to the handle.

    GCPROTECT_BEGIN(thisPointer);
    MethodTable *pHelperMT = MscorlibBinder::GetClass(CLASS__ENC_HELPER);
    pEntry->m_FieldData = pDomain->CreateDependentHandle(thisPointer, AllocateObject(pHelperMT));
    GCPROTECT_END();

    LOG((LF_ENC, LL_INFO1000, "\tEnCAF:Allocate created dependent handle %p\n",pEntry->m_FieldData));

    // The EnC helper object stores a reference to the actual field value.  For fields which are
    // reference types, this is simply a normal object reference so we don't need to do anything
    // special here.

    if (pFD->GetFieldType() != ELEMENT_TYPE_CLASS) 
    {
        // The field is a value type so we need to create storage on the heap to hold a boxed
        // copy of the value and have the helper's objectref point there.  

        OBJECTREF obj = NULL;
        if (pFD->IsByValue()) 
        {
            // Create a boxed version of the value class. This allows the standard GC algorithm 
            // to take care of internal pointers into the value class.
            obj = AllocateObject(pFD->GetFieldTypeHandleThrowing().GetMethodTable());
        } 
        else 
        {
            // In the case of primitive types, we use a reference to a 1-element array on the heap.  
            // I'm not sure why we bother treating primitives specially, it seems like we should be able 
            // to just box any value type including primitives.            
            obj = AllocatePrimitiveArray(ELEMENT_TYPE_I1, GetSizeForCorElementType(pFD->GetFieldType()));
        }
        GCPROTECT_BEGIN (obj);

        // Get a FieldDesc for the object reference field in the EnC helper object (warning: triggers)
        FieldDesc *pHelperField = MscorlibBinder::GetField(FIELD__ENC_HELPER__OBJECT_REFERENCE);

        // store the empty boxed object into the helper object
        OBJECTREF pHelperObj = GetDependentHandleSecondary(pEntry->m_FieldData);
        OBJECTREF *pHelperRef = (OBJECTREF *)pHelperField->GetAddress( pHelperObj->GetAddress() );
        SetObjectReference( pHelperRef, obj, pDomain );

        GCPROTECT_END ();
    }

    return pEntry;
}
#endif // !DACCESS_COMPILE

//---------------------------------------------------------------------------------------
// EnCSyncBlockInfo::GetEnCFieldAddrFromHelperFieldDesc
// Gets the address of an EnC field accounting for its type: valuetype, class or primitive
// Arguments:
//     input:  pHelperFieldDesc - FieldDesc for the enc helper object
//             pHelper          - EnC helper (points to list of added fields)
//             pFD              - fieldDesc describing the field of interest
// Return value: the address of the EnC added field            
//---------------------------------------------------------------------------------------
PTR_CBYTE EnCSyncBlockInfo::GetEnCFieldAddrFromHelperFieldDesc(FieldDesc *        pHelperFieldDesc, 
                                                               OBJECTREF          pHelper, 
                                                               EnCFieldDesc *     pFD)
{
     WRAPPER_NO_CONTRACT;
     SUPPORTS_DAC;

    _ASSERTE(pHelperFieldDesc != NULL);
    _ASSERTE(pHelper != NULL);

    // Get the address of the reference inside the helper object which points to 
    // the field contents
    PTR_OBJECTREF pOR = dac_cast<PTR_OBJECTREF>(pHelperFieldDesc->GetAddress(pHelper->GetAddress())); 
    _ASSERTE(pOR != NULL);

    PTR_CBYTE retAddr = NULL;
    
    // Compute the address to the actual field contents based on the field type
    // See the description above Allocate for details
    if (pFD->IsByValue())
    {
        // field value is a value type, we store it boxed so get the pointer to the first field
        retAddr = dac_cast<PTR_CBYTE>((*pOR)->UnBox());
    }
    else if (pFD->GetFieldType() == ELEMENT_TYPE_CLASS)
    {
        // field value is a reference type, we store the objref directly
        retAddr = dac_cast<PTR_CBYTE>(pOR);
    }
    else
    {
        // field value is a primitive, we store it inside a 1-element array
        OBJECTREF objRef = *pOR;
        I1ARRAYREF primitiveArray = dac_cast<I1ARRAYREF>(objRef);
        retAddr = dac_cast<PTR_CBYTE>(primitiveArray->GetDirectPointerToNonObjectElements());
    }

    LOG((LF_ENC, LL_INFO1000, "\tEnCSBI:RF address of %s type member is %p\n", 
        (pFD->IsByValue() ? "ByValue" : pFD->GetFieldType() == ELEMENT_TYPE_CLASS ? "Class" : "Other"), retAddr));

    return retAddr;
} // EnCSyncBlockInfo::GetEnCFieldAddrFromHelperFieldDesc

//---------------------------------------------------------------------------------------
// EnCSyncBlockInfo::ResolveField
// Get the address of the data referenced by an instance field that was added with EnC
// Arguments:
//   thisPointer  - the object instance whose field to access
//   pFD          - fieldDesc describing the field of interest
// Return value: Returns a pointer to the data referenced by an EnC added instance field
//---------------------------------------------------------------------------------------
PTR_CBYTE EnCSyncBlockInfo::ResolveField(OBJECTREF thisPointer, EnCFieldDesc *pFD)
{
    CONTRACTL
    {
        GC_NOTRIGGER;
        NOTHROW;
        SUPPORTS_DAC;
    }
    CONTRACTL_END;

    // We should only be passed FieldDescs for instance fields
    _ASSERTE(!pFD->IsStatic());

    PTR_EnCAddedField pEntry = NULL;

    LOG((LF_ENC, LL_INFO1000, "EnCSBI:RF for this %p, FD %p\n", thisPointer, pFD->GetMemberDef()));

    // This list is not synchronized--it hasn't proved a problem, but we could conceivably see race conditions
    // arise here. 
    // Look for an entry for the requested field in our linked list
    pEntry = m_pList;
    while (pEntry && pEntry->m_pFieldDesc != pFD)
    {
        pEntry = pEntry->m_pNext;
    }
        
    if (!pEntry)
    {       
        // No existing entry - we have to return NULL
        return NULL;
    }

    // we found a matching entry in the list of EnCAddedFields
    // Get the EnC helper object (see the detailed description in Allocate above)
    OBJECTREF pHelper = GetDependentHandleSecondary(pEntry->m_FieldData);           
    _ASSERTE(pHelper != NULL);

    FieldDesc *pHelperFieldDesc = NULL;

    // We _HAVE_ to call GetExistingField b/c (a) we can't throw exceptions, and 
    // (b) we _DON'T_ want to run class init code, either.
    pHelperFieldDesc = MscorlibBinder::GetExistingField(FIELD__ENC_HELPER__OBJECT_REFERENCE);
    if (pHelperFieldDesc == NULL)
    {
        return NULL;
    }
    else
    {
        return GetEnCFieldAddrFromHelperFieldDesc(pHelperFieldDesc, pHelper, pFD);
    }
} // EnCSyncBlockInfo::ResolveField

#ifndef DACCESS_COMPILE
//---------------------------------------------------------------------------------------
// EnCSyncBlockInfo::ResolveOrAllocateField
// get the address of an EnC added field, allocating it if it doesn't yet exist
// Arguments:
//   thisPointer  - the object instance whose field to access
//   pFD          - fieldDesc describing the field of interest
// Return value: Returns a pointer to the data referenced by an instance field that was added with EnC
//---------------------------------------------------------------------------------------
PTR_CBYTE EnCSyncBlockInfo::ResolveOrAllocateField(OBJECTREF thisPointer, EnCFieldDesc *pFD)
{
    CONTRACTL
    {
        GC_TRIGGERS;
        WRAPPER(THROWS);
    }
    CONTRACTL_END;

    // We should only be passed FieldDescs for instance fields
    _ASSERTE( !pFD->IsStatic() );

    // first try to get the address of a pre-existing field (storage has already been allocated)
    PTR_CBYTE retAddr = ResolveField(thisPointer, pFD);

    if (retAddr != NULL)
    {
        return retAddr;
    }

    // if the field doesn't yet have available storage, we'll have to allocate it. 
    PTR_EnCAddedField pEntry = NULL;

    LOG((LF_ENC, LL_INFO1000, "EnCSBI:RF for this %p, FD %p\n", thisPointer, pFD->GetMemberDef()));

    // This list is not synchronized--it hasn't proved a problem, but we could conceivably see race conditions
    // arise here. 
    // Because we may have additions to the head of m_pList at any time, we have to keep searching this
    // until we either find a match or succeed in allocating a new entry and adding it to the list 
    do 
    {
        // Look for an entry for the requested field in our linked list (maybe it was just added)
        pEntry = m_pList;
        while (pEntry && pEntry->m_pFieldDesc != pFD)
        {
            pEntry = pEntry->m_pNext;
        }
            
        if (pEntry)
        {       
            // match found
            break;
        }
            
        // Allocate an entry and tie it to the object instance
        pEntry = EnCAddedField::Allocate(thisPointer, pFD);

        // put at front of list so the list is in order of most recently added
        pEntry->m_pNext = m_pList;
        if (FastInterlockCompareExchangePointer(&m_pList, pEntry, pEntry->m_pNext) == pEntry->m_pNext)  
            break;

        // There was a race and another thread modified the list here, so we need to try again
        // We should do this so rarely, and EnC perf is of relatively little
        // consequence, we should just be taking a lock here to simplify this code.
        // @todo - We leak a GC handle here. Allocate() above alloced a GC handle in m_FieldData. 
        // There's no dtor for pEntry to free it.
        delete pEntry;
    } while (TRUE);

    // we found a matching entry in the list of EnCAddedFields
    // Get the EnC helper object (see the detailed description in Allocate above)
    OBJECTREF pHelper = GetDependentHandleSecondary(pEntry->m_FieldData);           
    _ASSERTE(pHelper != NULL);

    FieldDesc * pHelperField = NULL;
    GCPROTECT_BEGIN (pHelper);
    pHelperField = MscorlibBinder::GetField(FIELD__ENC_HELPER__OBJECT_REFERENCE);
    GCPROTECT_END ();

    return GetEnCFieldAddrFromHelperFieldDesc(pHelperField, pHelper, pFD);
} // EnCSyncBlockInfo::ResolveOrAllocateField

// Free all the resources associated with the fields added to this object instance
// This is invoked after the object instance has been collected, and the SyncBlock is
// being reclaimed.
//
// Note, this is not threadsafe, and so should only be called when we know no-one else
// maybe using this SyncBlockInfo.
void EnCSyncBlockInfo::Cleanup()
{
    CONTRACTL
    {
        NOTHROW;
        GC_NOTRIGGER;
        SO_TOLERANT;
        MODE_ANY;
    }
    CONTRACTL_END;
    // Walk our linked list of all the fields that were added
    EnCAddedField *pEntry = m_pList;
    while (pEntry) 
    {
        // Clean up the handle we created in EnCAddedField::Allocate
        DestroyDependentHandle(*(OBJECTHANDLE*)&pEntry->m_FieldData);

        // Delete this list entry and move onto the next
        EnCAddedField *next = pEntry->m_pNext;
        delete pEntry;
        pEntry = next;
    }

    // Finally, delete the sync block info itself
    delete this;
}

// Allocate space to hold the value for the new static field
EnCAddedStaticField *EnCAddedStaticField::Allocate(EnCFieldDesc *pFD)
{
    CONTRACTL 
    {
        THROWS;
        GC_TRIGGERS;
    }
    CONTRACTL_END;

    _ASSERTE(!pFD->GetEnclosingMethodTable()->IsDomainNeutral());
    AppDomain *pDomain = (AppDomain*) pFD->GetApproxEnclosingMethodTable()->GetDomain();

    // Compute the size of the fieldData entry
    size_t fieldSize;
    if (pFD->IsByValue() || pFD->GetFieldType() == ELEMENT_TYPE_CLASS) {
        // We store references to reference types or boxed value types
        fieldSize = sizeof(OBJECTREF*);
    } else {
       // We store primitives inline
        fieldSize = GetSizeForCorElementType(pFD->GetFieldType());
    }

    // allocate an instance with space for the field data
    EnCAddedStaticField *pEntry = (EnCAddedStaticField *)
        (void*)pDomain->GetHighFrequencyHeap()->AllocMem(S_SIZE_T(offsetof(EnCAddedStaticField, m_FieldData)) + S_SIZE_T(fieldSize));
    pEntry->m_pFieldDesc = pFD;

    // Create a static objectref to point to the field contents, except for primitives
    // which will use the memory available in-line at m_FieldData for storage.
    // We use static object refs for static fields as these fields won't go away 
    // unless the module is unloaded, and they can easily be found by GC.
    if (pFD->IsByValue()) 
    {
        // create a boxed version of the value class.  This allows the standard GC
        // algorithm to take care of internal pointers in the value class.
        OBJECTREF **pOR = (OBJECTREF**)&pEntry->m_FieldData;
        *pOR = pDomain->AllocateStaticFieldObjRefPtrs(1);
        OBJECTREF obj = AllocateObject(pFD->GetFieldTypeHandleThrowing().GetMethodTable());
        SetObjectReference( *pOR, obj, pDomain );
    } 
    else if (pFD->GetFieldType() == ELEMENT_TYPE_CLASS) 
    {
        // references to reference-types are stored directly in the field data
        OBJECTREF **pOR = (OBJECTREF**)&pEntry->m_FieldData;
        *pOR = pDomain->AllocateStaticFieldObjRefPtrs(1);
    }

    return pEntry;
}
#endif // !DACCESS_COMPILE
// GetFieldData - return the ADDRESS where the field data is located
PTR_CBYTE EnCAddedStaticField::GetFieldData()
{
    LIMITED_METHOD_CONTRACT;
    SUPPORTS_DAC;

    if ( (m_pFieldDesc->IsByValue()) || (m_pFieldDesc->GetFieldType() == ELEMENT_TYPE_CLASS) ) 
    {
        // It's indirect via an ObjRef at m_FieldData. This is a TADDR, so we need to make a PTR_CBYTE from
        // the ObjRef
        return *(PTR_CBYTE *)&m_FieldData;
    } 
    else 
    {
        // An elementry type. It's stored directly in m_FieldData. In this case, we need to get the target
        // address of the m_FieldData data member and marshal it via the DAC. 
        return dac_cast<PTR_CBYTE>(PTR_HOST_MEMBER_TADDR(EnCAddedStaticField, this, m_FieldData));
    }
}

// Gets a pointer to the field's contents (assuming this is a static field)
// We'll return NULL if we don't yet have a pointer to the data. 
// Arguments: none
// Return value: address of the static field data if available or NULL otherwise
EnCAddedStaticField * EnCFieldDesc::GetStaticFieldData()
{
    CONTRACTL
    {
        GC_NOTRIGGER;
        NOTHROW; 
        SUPPORTS_DAC;
    }
    CONTRACTL_END;

    _ASSERTE(IsStatic());
        
    return m_pStaticFieldData;
}

#ifndef DACCESS_COMPILE
// Gets a pointer to the field's contents (assuming this is a static field)
// Arguments: none
// Return value: address of the field data. If  we don't yet have a pointer to the data, 
// this will allocate space to store it. 
// May throw OOM.
EnCAddedStaticField * EnCFieldDesc::GetOrAllocateStaticFieldData()
{
    CONTRACTL
    {
        GC_TRIGGERS;
        THROWS;
    }
    CONTRACTL_END;

    _ASSERTE(IsStatic());

    // If necessary and requested, allocate space for the static field data
    if (!m_pStaticFieldData)
    {
        m_pStaticFieldData = EnCAddedStaticField::Allocate(this);
    }
        
    return m_pStaticFieldData;
}
#endif // !DACCESS_COMPILE

#ifndef DACCESS_COMPILE
// Adds the provided new field to the appropriate linked list and updates the appropriate count
void EnCEEClassData::AddField(EnCAddedFieldElement *pAddedField)
{
    LIMITED_METHOD_CONTRACT;
    // Determine the appropriate field list and update the field counter
    EnCFieldDesc *pFD = &pAddedField->m_fieldDesc;
    EnCAddedFieldElement **pList;
    if (pFD->IsStatic())
    {
        ++m_dwNumAddedStaticFields;
        pList = &m_pAddedStaticFields;
    } 
    else
    {
        ++m_dwNumAddedInstanceFields;
        pList = &m_pAddedInstanceFields;
    }

    // If the list is empty, just add this field as the only entry
    if (*pList == NULL) 
    {
        *pList = pAddedField;
        return;
    }

    // Otherwise, add this field to the end of the field list
    EnCAddedFieldElement *pCur = *pList;
    while (pCur->m_next != NULL)
    {
        pCur = pCur->m_next;
    }        
    pCur->m_next = pAddedField;
}

#endif // #ifndef DACCESS_COMPILE

#ifdef DACCESS_COMPILE

void
EnCEEClassData::EnumMemoryRegions(CLRDataEnumMemoryFlags flags)
{
    SUPPORTS_DAC;
    DAC_ENUM_DTHIS();

    if (m_pMT.IsValid())
    {
        m_pMT->EnumMemoryRegions(flags);
    }

    PTR_EnCAddedFieldElement elt = m_pAddedInstanceFields;
    while (elt.IsValid())
    {
        elt.EnumMem();
        elt = elt->m_next;
    }
    elt = m_pAddedStaticFields;
    while (elt.IsValid())
    {
        elt.EnumMem();
        elt = elt->m_next;
    }
}

void
EditAndContinueModule::EnumMemoryRegions(CLRDataEnumMemoryFlags flags,
                                         bool enumThis)
{
    SUPPORTS_DAC;

    if (enumThis)
    {
        DAC_ENUM_VTHIS();
    }

    Module::EnumMemoryRegions(flags, false);

    m_ClassList.EnumMemoryRegions();

    DPTR(PTR_EnCEEClassData) classData = m_ClassList.Table();
    DPTR(PTR_EnCEEClassData) classLast = classData + m_ClassList.Count();
    
    while (classData.IsValid() && classData < classLast)
    {
        if ((*classData).IsValid())
        {
            (*classData)->EnumMemoryRegions(flags);
        }

        classData++;
    }
}

#endif // #ifdef DACCESS_COMPILE


// Create a field iterator which includes EnC fields in addition to the fields from an
// underlying ApproxFieldDescIterator.
//
// Arguments:
//   pMT           - MethodTable indicating the type of interest
//   iteratorType  - one of the ApproxFieldDescIterator::IteratorType values specifying which fields
//                   are of interest.
//   fixupEnC      - if true, then any partially-initialized EnC FieldDescs will be fixed up to be complete
//                   initialized FieldDescs as they are returned by Next().  This may load types and do 
//                   other things to trigger a GC.
//                   
EncApproxFieldDescIterator::EncApproxFieldDescIterator(MethodTable *pMT, int iteratorType, BOOL fixupEnC) :
      m_nonEnCIter( pMT, iteratorType )
{
    CONTRACTL
    {
        NOTHROW;
        GC_NOTRIGGER;
        SUPPORTS_DAC;
    }
    CONTRACTL_END

    m_fixupEnC = fixupEnC;

#ifndef DACCESS_COMPILE
    // can't fixup for EnC on the debugger thread
    _ASSERTE((g_pDebugInterface->GetRCThreadId() != GetCurrentThreadId()) || fixupEnC == FALSE);
#endif    

    m_pCurrListElem = NULL;
    m_encClassData = NULL;
    m_encFieldsReturned = 0;

    // If this is an EnC module, then grab a pointer to the EnC data
    if( pMT->GetModule()->IsEditAndContinueEnabled() )
    {
        PTR_EditAndContinueModule encMod = PTR_EditAndContinueModule(pMT->GetModule());
        m_encClassData = encMod->GetEnCEEClassData( pMT, TRUE);
    }
}

// Iterates through all fields, returns NULL when done.
PTR_FieldDesc EncApproxFieldDescIterator::Next()
{
    CONTRACTL
    {
        NOTHROW;
        if (m_fixupEnC) {GC_TRIGGERS;} else {GC_NOTRIGGER;}
        FORBID_FAULT;
        SUPPORTS_DAC;
    }
    CONTRACTL_END

    // If we still have non-EnC fields to look at, return one of them
    if( m_nonEnCIter.CountRemaining() > 0 )
    {
        _ASSERTE( m_encFieldsReturned == 0 );
        return m_nonEnCIter.Next();
    }

    // Get the next EnC field Desc if any
    PTR_EnCFieldDesc pFD = NextEnC();
    if( pFD == NULL )
    {
        // No more fields
        return NULL;
    }

#ifndef DACCESS_COMPILE
    // Fixup the fieldDesc if requested and necessary
    if ( m_fixupEnC && (pFD->NeedsFixup()) )
    {
        // if we get an OOM during fixup, the field will just not get fixed up
        EX_TRY
        {
            FAULT_NOT_FATAL();
            pFD->Fixup(pFD->GetMemberDef());
        }
        EX_CATCH
        {
        }
        EX_END_CATCH(SwallowAllExceptions)
    }

    // Either it's been fixed up so we can use it, or we're the Debugger RC thread, we can't fix it up,
    // but it's ok since our logic will check & make sure we don't try and use it.  If haven't asked to 
    // have the field fixed up, should never be trying to get at non-fixed up field in
    // this list. Can't simply fixup the field always because loading triggers GC and many 
    // code paths can't tolerate that.
    _ASSERTE( !(pFD->NeedsFixup()) ||
              ( g_pDebugInterface->GetRCThreadId() == GetCurrentThreadId() ) );
#endif

    return dac_cast<PTR_FieldDesc>(pFD);
}

// Iterate through EnC added fields.
// Returns NULL when done.
PTR_EnCFieldDesc EncApproxFieldDescIterator::NextEnC()
{
    CONTRACTL
    {
        NOTHROW;
        GC_NOTRIGGER;
        FORBID_FAULT;
        SUPPORTS_DAC;
    }
    CONTRACTL_END

    // If this module doesn't have any EnC data then there aren't any EnC fields
    if( m_encClassData == NULL )
    {
        return NULL;
    }

    BOOL doInst = ( GetIteratorType() & (int)ApproxFieldDescIterator::INSTANCE_FIELDS);
    BOOL doStatic = ( GetIteratorType() & (int)ApproxFieldDescIterator::STATIC_FIELDS);

    int cNumAddedInst    =  doInst ? m_encClassData->GetAddedInstanceFields() : 0;
    int cNumAddedStatics =  doStatic ? m_encClassData->GetAddedStaticFields() : 0; 

    // If we haven't returned anything yet
    if ( m_encFieldsReturned == 0 )
    {
        _ASSERTE(m_pCurrListElem == NULL);

        // We're at the start of the instance list.
        if ( doInst )
        {
            m_pCurrListElem = m_encClassData->m_pAddedInstanceFields;            
        }
    }

    // If we've finished the instance fields (or never wanted to do any)
    if ( m_encFieldsReturned == cNumAddedInst)
    {
        // We should be at the end of the instance list if doInst is true
        _ASSERTE(m_pCurrListElem == NULL);

        // We're at the start of the statics list.
        if ( doStatic )
        {
            m_pCurrListElem = m_encClassData->m_pAddedStaticFields; 
        }
    }        

    // If we don't have any elements to return, then we're done
    if (m_pCurrListElem == NULL)
    {
        // Verify that we returned the number we expected to
        _ASSERTE( m_encFieldsReturned == cNumAddedInst + cNumAddedStatics );
        return NULL;
    }

    // Advance the list pointer and return the element
    m_encFieldsReturned++;
    PTR_EnCFieldDesc fd = PTR_EnCFieldDesc(PTR_HOST_MEMBER_TADDR(EnCAddedFieldElement, m_pCurrListElem, m_fieldDesc));
    m_pCurrListElem = m_pCurrListElem->m_next;
    return fd;
}

#endif // EnC_SUPPORTED