91da7b35ae45e7f339b541e8a7e54f97955a2862
[platform/upstream/coreclr.git] / src / vm / ceeload.h
1 // Licensed to the .NET Foundation under one or more agreements.
2 // The .NET Foundation licenses this file to you under the MIT license.
3 // See the LICENSE file in the project root for more information.
4 // ===========================================================================
5 // File: CEELOAD.H
6 //
7
8 //
9 // CEELOAD.H defines the class use to represent the PE file
10 // ===========================================================================
11
12 #ifndef CEELOAD_H_
13 #define CEELOAD_H_
14
15 #include "common.h"
16 #include "vars.hpp" // for LPCUTF8
17 #include "hash.h"
18 #include "clsload.hpp"
19 #include "cgensys.h"
20 #include "corsym.h"
21 #include "typehandle.h"
22 #include "arraylist.h"
23 #include "pefile.h"
24 #include "typehash.h"
25 #include "contractimpl.h"
26 #include "bitmask.h"
27 #include "instmethhash.h"
28 #include "eetwain.h"    // For EnumGCRefs (we should probably move that somewhere else, but can't
29                         // find anything better (modulo common or vars.hpp)
30 #include "classloadlevel.h"
31 #include "precode.h"
32 #include "corbbtprof.h"
33 #include "ilstubcache.h"
34 #include "classhash.h"
35
36 #ifdef FEATURE_PREJIT
37 #include "corcompile.h"
38 #include "dataimage.h"
39 #include <gcinfodecoder.h>
40 #endif // FEATURE_PREJIT
41
42 #ifdef FEATURE_COMINTEROP
43 #include "winrttypenameconverter.h"
44 #endif // FEATURE_COMINTEROP
45
46 #ifdef FEATURE_READYTORUN
47 #include "readytoruninfo.h"
48 #endif
49
50 #include "ilinstrumentation.h"
51
52 class PELoader;
53 class Stub;
54 class MethodDesc;
55 class FieldDesc;
56 class Crst;
57 class ClassConverter;
58 class RefClassWriter;
59 class ReflectionModule;
60 class EEStringData;
61 class MethodDescChunk;
62 class SigTypeContext;
63 class Assembly;
64 class BaseDomain;
65 class AppDomain;
66 class CompilationDomain;
67 class DomainModule;
68 struct DomainLocalModule;
69 class SystemDomain;
70 class Module;
71 class SString;
72 class Pending;
73 class MethodTable;
74 class AppDomain;
75 class DynamicMethodTable;
76 class CodeVersionManager;
77 class CallCounter;
78 class TieredCompilationManager;
79 #ifdef FEATURE_PREJIT
80 class CerNgenRootTable;
81 struct MethodContextElement;
82 class TypeHandleList;
83 class ProfileEmitter;
84 class TrackingMap;
85 struct MethodInModule;
86 class PersistentInlineTrackingMapNGen;
87
88 // Hash table parameter of available classes (name -> module/class) hash
89 #define AVAILABLE_CLASSES_HASH_BUCKETS 1024
90 #define AVAILABLE_CLASSES_HASH_BUCKETS_COLLECTIBLE 128
91 #define PARAMTYPES_HASH_BUCKETS 23
92 #define PARAMMETHODS_HASH_BUCKETS 11
93 #define METHOD_STUBS_HASH_BUCKETS 11
94 #define GUID_TO_TYPE_HASH_BUCKETS 16
95             
96 // The native symbol reader dll name
97 #if defined(_AMD64_)
98 #define NATIVE_SYMBOL_READER_DLL W("Microsoft.DiaSymReader.Native.amd64.dll")
99 #elif defined(_X86_)
100 #define NATIVE_SYMBOL_READER_DLL W("Microsoft.DiaSymReader.Native.x86.dll")
101 #elif defined(_ARM_)
102 #define NATIVE_SYMBOL_READER_DLL W("Microsoft.DiaSymReader.Native.arm.dll")
103 #elif defined(_ARM64_)
104 // Use diasymreader until the package has an arm64 version - issue #7360
105 //#define NATIVE_SYMBOL_READER_DLL W("Microsoft.DiaSymReader.Native.arm64.dll")
106 #define NATIVE_SYMBOL_READER_DLL W("diasymreader.dll")
107 #endif
108
109 typedef DPTR(PersistentInlineTrackingMapNGen) PTR_PersistentInlineTrackingMapNGen;
110
111 extern VerboseLevel g_CorCompileVerboseLevel;
112 #endif  // FEATURE_PREJIT
113
114 //
115 // LookupMaps are used to implement RID maps
116 // It is a linked list of nodes, each handling a successive (and consecutive)
117 // range of RIDs.
118 //
119 // LookupMapBase is non-type safe implementation of the worker methods. LookupMap is type 
120 // safe wrapper around it.
121 //
122
123 typedef DPTR(struct LookupMapBase) PTR_LookupMapBase;
124
125 #ifdef FEATURE_PREJIT
126
127 //
128 // LookupMap cold entry compression support
129 //
130 // A lookup map (the cold section) is notionally an array of pointer values indexed by rid. The pointers are
131 // generally to data structures such as MethodTables or MethodDescs. When we compress such a table (at ngen
132 // time) we wish to avoid direct pointers, since these would need to be fixed up due to image base
133 // relocations. Instead we store RVAs (Relative Virtual Addresses). Unlike regular RVAs our base address is
134 // the map address itself (as opposed to the module base). We do this purely out of convenience since
135 // LookupMaps don't store the module base address.
136 //
137 // It turns out that very often the value pointers (and hence the value RVAs) are related to each other:
138 // adjacent map entries often point to data structures that were allocated next to or close to each other. The
139 // compression algorithm takes advantage of this fact: instead of storing value RVAs we store the deltas
140 // between RVAs. So the nth value in the table is composed of the addition of the deltas from the preceding (n
141 // - 1) entries. Since the deltas are often small (especially when we take structure alignment into account
142 // and realize that we can discard the lower 2 or 3 bits of the delta) we can store them in a compressed
143 // manner by discarding the insignificant leading zero bits in each value.
144 //
145 // So now we imagine our compressed table to be a sequence of entries, each entry being a variably sized delta
146 // from the previous entry. As a result we need some means to encode how large each delta in the table is. We
147 // could use a fixed size field (a 5-bit length field would be able to encode any length between 1 and 32
148 // bits, say). This is troublesome since although most entry values are close in value there are a few
149 // (usually a minority) that require much larger deltas (hot/cold data splitting based on profiling can cause
150 // this for instance). For most tables this would force us to use a large fixed-size length field for every
151 // entry, just to deal with the relatively uncommon worst case (5 bits would be enough, but many entry deltas
152 // can be encoded in 2 or 3 bits).
153 //
154 // Instead we utilize a compromise: we store all delta lengths with a small number of bits
155 // (kLookupMapLengthBits below). Instead of encoding the length directly this value indexes a per-map table of
156 // possible delta encoding lengths. During ngen we calculate the optimal value for each entry in this encoding
157 // length table. The advantage here is that it lets us encode both best case and worst case delta lengths with
158 // a fixed size but small field. The disadvantage is that some deltas will be encoded with more bits than they
159 // strictly need.
160 //
161 // This still leaves the problem of runtime lookup performance. Touches to the cold section of a LookupMap
162 // aren't all that critical (after all the data is meant to be cold), but looking up the last entry of a map
163 // with 22 thousand entries (roughly what the MethodDefToDesc map in mscorlib is sized at at the time of
164 // writing) is still likely to so inefficient as to be noticeable. Remember that the issue is that we have to
165 // decode all predecessor entries in order to compute the value of a given entry in the table.
166 //
167 // To address this we introduce an index to each compressed map. The index contains an entry for each
168 // kLookupMapIndexStride'th entry in the compressed map. The index entry consists of the RVA of the
169 // corresponding table value and the bit offset into the compressed map at which the data for the next entry
170 // commences. Thus we can use the index to find a value within kLookupMapIndexStride entries of our target and
171 // then proceed to decode only the last few compressed entries to finish the job. This reduces the lookup to a
172 // constant time operation once more (given a reasonable value for kLookupMapIndexStride).
173 //
174 // The main areas in which this algorithm can be tuned are the number of bits used as an index into the
175 // encoding lengths table (kLookupMapLengthBits) and the frequency with which entries are bookmarked in the
176 // index (kLookupMapIndexStride). The current values have been set based on looking at models of mscorlib,
177 // PresentationCore and PresentationFramework built from the actual ridmap data in their ngen images and
178 // methodically trying different values in order to maximize compression or balance size versus likely runtime
179 // performance. An alternative strategy was considered using direct (non-length prefix) encoding of the
180 // deltas with a couple of variantions on probability-based variable length encoding (completely unbalanced
181 // tree and completely balanced tree with pessimally encoded worst case escapes). But these were found to
182 // yield best case results similar to the above but with more complex processing required at ngen (optimal
183 // results for these algorithms are achieved when you have enough resources to build a probability map of your
184 // entire data).
185 //
186 // Note that not all lookup tables are suitable for compression. In fact we compress only TypeDefToMethodTable
187 // and MethodDefToDesc tables. For one thing this optimization only brings benefits to larger tables. But more
188 // importantly we cannot mutate compressed entries (for obvious reasons). Many of the lookup maps are only
189 // partially populated at ngen time or otherwise might be updated at runtime and thus are not candidates.
190 //
191 // In the threshhold timeframe (predicted to be .Net 4.5.3 at the time of writing), we added profiler support
192 // for adding new types to NGEN images. Historically we could always do this for jitted images, but one of the
193 // blockers for NGEN were the compressed RID maps. We worked around that by supporting multi-node maps in which
194 // the first node is compressed, but all future nodes are uncompressed. The NGENed portion will all land in the
195 // compressed node, while the new profiler added data will land in the uncompressed portion. Note this could 
196 // probably be leveraged for other dynamic scenarios such as a limited form of EnC, but nothing further has
197 // been implemented at this time.
198 //
199
200 // Some useful constants used when compressing tables.
201 enum {
202     kLookupMapLengthBits    = 2,                            // Bits used to encode an index into a table of possible value lengths
203     kLookupMapLengthEntries = 1 << kLookupMapLengthBits,    // Number of entries in the encoding table above
204     kLookupMapIndexStride   = 0x10,                         // The range of table entries covered by one index entry (power of two for faster hash lookup)
205     kBitsPerRVA             = sizeof(DWORD) * 8,            // Bits in an (uncompressed) table value RVA (RVAs
206                                                             // currently still 32-bit even on 64-bit platforms)
207 #ifdef _WIN64
208     kFlagBits               = 3,                            // Number of bits at the bottom of a value
209                                                             // pointer that may be used for flags
210 #else // _WIN64
211     kFlagBits               = 2,
212 #endif // _WIN64
213
214 };
215
216 #endif // FEATURE_PREJIT
217
218 struct LookupMapBase
219 {
220     DPTR(LookupMapBase) pNext;
221
222     ArrayDPTR(TADDR)    pTable;
223
224     // Number of elements in this node (only RIDs less than this value can be present in this node)
225     DWORD               dwCount;
226
227     // Set of flags that the map supports writing on top of the data value
228     TADDR               supportedFlags;
229
230 #ifdef FEATURE_PREJIT
231     struct  HotItem
232     {
233         DWORD   rid;
234         TADDR   value;
235         static int __cdecl Cmp(const void* a_, const void* b_);
236     };
237     DWORD               dwNumHotItems;
238     ArrayDPTR(HotItem)  hotItemList;
239     PTR_TADDR FindHotItemValuePtr(DWORD rid);
240
241     //
242     // Compressed map support
243     //
244     PTR_CBYTE           pIndex;             // Bookmark for every kLookupMapIndexStride'th entry in the table
245     DWORD               cIndexEntryBits;    // Number of bits in every index entry
246     DWORD               cbTable;            // Number of bytes of compressed table data at pTable
247     DWORD               cbIndex;            // Number of bytes of index data at pIndex
248     BYTE                rgEncodingLengths[kLookupMapLengthEntries]; // Table of delta encoding lengths for
249                                                                     // compressed values
250
251     // Returns true if this map instance is compressed (this can only happen at runtime when running against
252     // an ngen image). Currently and for the forseeable future only TypeDefToMethodTable and MethodDefToDesc
253     // tables can be compressed.
254     bool MapIsCompressed()
255     {
256         LIMITED_METHOD_DAC_CONTRACT;
257         return pIndex != NULL;
258     }
259
260 protected:
261     // Internal routine used to iterate though one entry in the compressed table.
262     INT32 GetNextCompressedEntry(BitStreamReader *pTableStream, INT32 iLastValue);
263
264 public:
265     // Public method used to retrieve the full value (non-RVA) of a compressed table entry.
266     TADDR GetValueFromCompressedMap(DWORD rid);
267
268 #ifndef DACCESS_COMPILE
269     void CreateHotItemList(DataImage *image, CorProfileData *profileData, int table, BOOL fSkipNullEntries = FALSE);
270     void Save(DataImage *image, DataImage::ItemKind kind, CorProfileData *profileData, int table, BOOL fCopyValues = FALSE);
271     void SaveUncompressedMap(DataImage *image, DataImage::ItemKind kind, BOOL fCopyValues = FALSE);
272     void ConvertSavedMapToUncompressed(DataImage *image, DataImage::ItemKind kind);
273     void Fixup(DataImage *image, BOOL fFixupEntries = TRUE);
274 #endif // !DACCESS_COMPILE
275
276 #ifdef _DEBUG
277     void    CheckConsistentHotItemList();
278 #endif
279
280 #endif // FEATURE_PREJIT
281
282 #ifdef DACCESS_COMPILE
283     void EnumMemoryRegions(CLRDataEnumMemoryFlags flags,
284                            bool enumThis);
285     void ListEnumMemoryRegions(CLRDataEnumMemoryFlags flags);
286 #endif // DACCESS_COMPILE
287
288     PTR_TADDR GetIndexPtr(DWORD index)
289     {
290         LIMITED_METHOD_DAC_CONTRACT;
291 #ifdef FEATURE_PREJIT
292         _ASSERTE(!MapIsCompressed());
293 #endif // FEATURE_PREJIT
294         _ASSERTE(index < dwCount);
295         return dac_cast<PTR_TADDR>(pTable) + index;
296     }
297
298     PTR_TADDR GetElementPtr(DWORD rid);
299     PTR_TADDR GrowMap(Module * pModule, DWORD rid);
300
301     // Get number of RIDs that this table can store
302     DWORD GetSize();
303
304 #ifdef _DEBUG
305     void DebugGetRidMapOccupancy(DWORD *pdwOccupied, DWORD *pdwSize);
306 #endif
307 };
308
309 #define NO_MAP_FLAGS ((TADDR)0)
310
311 template <typename TYPE>
312 struct LookupMap : LookupMapBase
313 {
314     static TYPE GetValueAt(PTR_TADDR pValue, TADDR* pFlags, TADDR supportedFlags);
315
316 #ifndef DACCESS_COMPILE
317     static void SetValueAt(PTR_TADDR pValue, TYPE value, TADDR flags);
318 #endif // DACCESS_COMPILE
319
320     TYPE GetElement(DWORD rid, TADDR* pFlags);
321     void SetElement(DWORD rid, TYPE value, TADDR flags);
322     BOOL TrySetElement(DWORD rid, TYPE value, TADDR flags);
323     void AddElement(Module * pModule, DWORD rid, TYPE value, TADDR flags);
324     void EnsureElementCanBeStored(Module * pModule, DWORD rid);
325     DWORD Find(TYPE value, TADDR* flags);
326
327
328 public:
329
330     //
331     // Retrieve the value associated with a rid
332     //
333     TYPE GetElement(DWORD rid)
334     {
335         WRAPPER_NO_CONTRACT;
336         SUPPORTS_DAC;
337
338         return GetElement(rid, NULL);
339     }
340
341     TYPE GetElementAndFlags(DWORD rid, TADDR* pFlags)
342     {
343         WRAPPER_NO_CONTRACT;
344         SUPPORTS_DAC;
345
346         _ASSERTE(pFlags != NULL);
347
348         return GetElement(rid, pFlags);
349     }
350
351     //
352     // Stores an association in a map that has been previously grown to
353     // the required size. Will never throw or fail.
354     //
355     void SetElement(DWORD rid, TYPE value)
356     {
357         WRAPPER_NO_CONTRACT;
358         SUPPORTS_DAC;
359
360         SetElement(rid, value, 0);
361     }
362
363     void SetElementWithFlags(DWORD rid, TYPE value, TADDR flags)
364     {
365         WRAPPER_NO_CONTRACT;
366         SUPPORTS_DAC;
367
368         // Validate flags: that they are in the predefined range and that the range does not collide with value
369         _ASSERTE((flags & supportedFlags) == flags);
370         _ASSERTE((dac_cast<TADDR>(value) & supportedFlags) == 0);
371
372         SetElement(rid, value, flags);
373     }
374
375 #ifndef DACCESS_COMPILE
376     void AddFlag(DWORD rid, TADDR flag)
377     {
378         WRAPPER_NO_CONTRACT;
379
380         _ASSERTE((flag & supportedFlags) == flag);
381         _ASSERTE(!MapIsCompressed());
382         _ASSERTE(dwNumHotItems == 0);
383
384         PTR_TADDR pElement = GetElementPtr(rid);
385         _ASSERTE(pElement);
386
387         if (!pElement)
388         {
389             return;
390         }
391
392         TADDR existingFlags;
393         TYPE existingValue = GetValueAt(pElement, &existingFlags, supportedFlags);
394         SetValueAt(pElement, existingValue, existingFlags | flag);
395     }
396 #endif // DACCESS_COMPILE
397
398     //
399     // Try to store an association in a map. Will never throw or fail.
400     //
401     BOOL TrySetElement(DWORD rid, TYPE value)
402     {
403         WRAPPER_NO_CONTRACT;
404
405         return TrySetElement(rid, value, 0);
406     }
407
408     BOOL TrySetElementWithFlags(DWORD rid, TYPE value, TADDR flags)
409     {
410         WRAPPER_NO_CONTRACT;
411
412         // Validate flags: that they are in the predefined range and that the range does not collide with value
413         _ASSERTE((flags & supportedFlags) == flags);
414         _ASSERTE((dac_cast<TADDR>(value) & supportedFlags) == 0);
415
416         return TrySetElement(rid, value, flags);
417     }
418     
419     //
420     // Stores an association in a map. Grows the map as necessary.
421     //
422     void AddElement(Module * pModule, DWORD rid, TYPE value)
423     {
424         WRAPPER_NO_CONTRACT;
425
426         AddElement(pModule, rid, value, 0);
427     }
428
429     void AddElementWithFlags(Module * pModule, DWORD rid, TYPE value, TADDR flags)
430     {
431         WRAPPER_NO_CONTRACT;
432
433         // Validate flags: that they are in the predefined range and that the range does not collide with value
434         _ASSERTE((flags & supportedFlags) == flags);
435         _ASSERTE((dac_cast<TADDR>(value) & supportedFlags) == 0);
436
437         AddElement(pModule, rid, value, flags);
438     }
439
440     //
441     // Find the given value in the table and return its RID
442     //
443     DWORD Find(TYPE value)
444     {
445         WRAPPER_NO_CONTRACT;
446
447         return Find(value, NULL);
448     }
449
450     DWORD FindWithFlags(TYPE value, TADDR flags)
451     {
452         WRAPPER_NO_CONTRACT;
453
454         // Validate flags: that they are in the predefined range and that the range does not collide with value
455         _ASSERTE((flags & supportedFlags) == flags);
456         _ASSERTE((dac_cast<TADDR>(value) & supportedFlags) == 0);
457
458         return Find(value, &flags);
459     }
460
461     class Iterator
462     {
463     public:
464         Iterator(LookupMap* map);
465
466         BOOL Next();
467
468         TYPE GetElement()
469         {
470             WRAPPER_NO_CONTRACT;
471             SUPPORTS_DAC;
472
473             return GetElement(NULL);
474         }
475         
476         TYPE GetElementAndFlags(TADDR* pFlags)
477         {
478             WRAPPER_NO_CONTRACT;
479             SUPPORTS_DAC;
480
481             return GetElement(pFlags);
482         }
483
484     private:
485         TYPE GetElement(TADDR* pFlags);
486         
487         LookupMap* m_map;
488         DWORD m_index;
489 #ifdef FEATURE_PREJIT
490         // Support for iterating compressed maps.
491         INT32 m_currentEntry;           // RVA of current entry value
492         BitStreamReader m_tableStream;  // Our current context in the compressed bit stream
493 #endif // FEATURE_PREJIT
494     };
495 };
496
497 // Place holder types for RID maps that store cross-module references
498
499 class TypeRef { };
500 typedef DPTR(class TypeRef) PTR_TypeRef;
501
502 class MemberRef { };
503 typedef DPTR(class MemberRef) PTR_MemberRef;
504
505
506 // flag used to mark member ref pointers to field descriptors in the member ref cache
507 #define IS_FIELD_MEMBER_REF ((TADDR)0x00000002)
508
509
510 #ifdef FEATURE_PREJIT
511 //
512 // NGen image layout information that we need to quickly access at runtime
513 //
514 typedef DPTR(struct NGenLayoutInfo) PTR_NGenLayoutInfo;
515 struct NGenLayoutInfo
516 {
517     // One range for each hot, unprofiled, cold code sections
518     MemoryRange             m_CodeSections[3];
519
520     // Pointer to the RUNTIME_FUNCTION table for hot, unprofiled, and cold code sections.
521     PTR_RUNTIME_FUNCTION    m_pRuntimeFunctions[3];
522
523     // Number of RUNTIME_FUNCTIONs for hot, unprofiled, and cold code sections.
524     DWORD                   m_nRuntimeFunctions[3];
525
526     // A parallel arrays of MethodDesc RVAs for hot and unprofiled methods. Both of the array are parallel for m_pRuntimeFunctions
527     // The first array is for hot methods. The second array is for unprofiled methods.
528     PTR_DWORD               m_MethodDescs[2];
529
530     // Lookup table to speed up RUNTIME_FUNCTION lookup.
531     // The first array is for hot methods. The second array is for unprofiled methods.
532     // Number of elements is m_UnwindInfoLookupTableEntryCount + 1.
533     // Last element of the lookup table is a sentinal entry that's good to cover the rest of the code section.
534     // Values are indices into m_pRuntimeFunctions array.
535     PTR_DWORD               m_UnwindInfoLookupTable[2];
536
537     // Count of lookup entries in m_UnwindInfoLookupTable
538     DWORD                   m_UnwindInfoLookupTableEntryCount[2];
539
540     // Map for matching the cold code with hot code. Index is relative position of RUNTIME_FUNCTION within the section.
541     PTR_CORCOMPILE_COLD_METHOD_ENTRY m_ColdCodeMap;
542
543     // One range for each hot, cold, write, hot writeable, and cold writeable precode sections
544     MemoryRange             m_Precodes[4];
545
546     MemoryRange             m_JumpStubs;
547     MemoryRange             m_StubLinkStubs;
548     MemoryRange             m_VirtualMethodThunks;
549     MemoryRange             m_ExternalMethodThunks;
550     MemoryRange             m_ExceptionInfoLookupTable;
551
552     PCODE                   m_pPrestubJumpStub;
553 #ifdef HAS_FIXUP_PRECODE
554     PCODE                   m_pPrecodeFixupJumpStub;
555 #endif
556     PCODE                   m_pVirtualImportFixupJumpStub;
557     PCODE                   m_pExternalMethodFixupJumpStub;
558     DWORD                   m_rvaFilterPersonalityRoutine;
559 };
560 #endif // FEATURE_PREJIT
561
562
563 //
564 // VASigCookies are allocated to encapsulate a varargs call signature.
565 // A reference to the cookie is embedded in the code stream.  Cookies
566 // are shared amongst call sites with identical signatures in the same
567 // module
568 //
569
570 typedef DPTR(struct VASigCookie) PTR_VASigCookie;
571 typedef DPTR(PTR_VASigCookie) PTR_PTR_VASigCookie;
572 struct VASigCookie
573 {
574     // The JIT wants knows that the size of the arguments comes first
575     // so please keep this field first
576     unsigned        sizeOfArgs;             // size of argument list
577     Volatile<PCODE> pNDirectILStub;         // will be use if target is NDirect (tag == 0)
578     PTR_Module      pModule;
579     Signature       signature;
580 };
581
582 //
583 // VASigCookies are allocated in VASigCookieBlocks to amortize
584 // allocation cost and allow proper bookkeeping.
585 //
586
587 struct VASigCookieBlock
588 {
589     enum {
590 #ifdef _DEBUG
591         kVASigCookieBlockSize = 2
592 #else // !_DEBUG
593         kVASigCookieBlockSize = 20
594 #endif // !_DEBUG
595     };
596
597     VASigCookieBlock    *m_Next;
598     UINT                 m_numcookies;
599     VASigCookie          m_cookies[kVASigCookieBlockSize];
600 };
601
602 // This lookup table persists the information about boxed statics into the ngen'ed image
603 // which allows one to the type static initialization without touching expensive EEClasses. Note
604 // that since the persisted info is stored at ngen time as opposed to class layout time,
605 // in jitted scenarios we would still touch EEClasses. This imples that the variables which store
606 // this info in the EEClasses are still present.
607
608 // We used this table to store more data require to run cctors in the past (it explains the name),
609 // but we are only using it for boxed statics now. Boxed statics are rare. The complexity may not
610 // be worth the gains. We should consider removing this cache and avoid the complexity.
611
612 typedef DPTR(struct ClassCtorInfoEntry) PTR_ClassCtorInfoEntry;
613 struct ClassCtorInfoEntry
614 {
615     DWORD firstBoxedStaticOffset;
616     DWORD firstBoxedStaticMTIndex;
617     WORD numBoxedStatics;
618     WORD hasFixedAddressVTStatics; // This is WORD avoid padding in the datastructure. It is really bool.
619 };
620
621 #define MODULE_CTOR_ELEMENTS 256
622 struct ModuleCtorInfo
623 {
624     DWORD                   numElements;
625     DWORD                   numLastAllocated;
626     DWORD                   numElementsHot;
627     DPTR(RelativePointer<PTR_MethodTable>) ppMT; // size is numElements
628     PTR_ClassCtorInfoEntry  cctorInfoHot;   // size is numElementsHot
629     PTR_ClassCtorInfoEntry  cctorInfoCold;  // size is numElements-numElementsHot
630
631     PTR_DWORD               hotHashOffsets;  // Indices to the start of each "hash region" in the hot part of the ppMT array. 
632     PTR_DWORD               coldHashOffsets; // Indices to the start of each "hash region" in the cold part of the ppMT array. 
633     DWORD                   numHotHashes;
634     DWORD                   numColdHashes;
635
636     ArrayDPTR(RelativeFixupPointer<PTR_MethodTable>) ppHotGCStaticsMTs;            // hot table
637     ArrayDPTR(RelativeFixupPointer<PTR_MethodTable>) ppColdGCStaticsMTs;           // cold table
638
639     DWORD                   numHotGCStaticsMTs;
640     DWORD                   numColdGCStaticsMTs;
641
642 #ifdef DACCESS_COMPILE
643     void EnumMemoryRegions(CLRDataEnumMemoryFlags flags);
644 #endif
645
646     typedef enum {HOT, COLD} REGION;
647     FORCEINLINE DWORD GenerateHash(PTR_MethodTable pMT, REGION region)
648     {
649         SUPPORTS_DAC;
650
651         DWORD tmp1  = pMT->GetTypeDefRid();
652         DWORD tmp2  = pMT->GetNumVirtuals();
653         DWORD tmp3  = pMT->GetNumInterfaces();
654
655         tmp1        = (tmp1 << 7) + (tmp1 << 0); // 10000001
656         tmp2        = (tmp2 << 6) + (tmp2 << 1); // 01000010
657         tmp3        = (tmp3 << 4) + (tmp3 << 3); // 00011000
658
659         tmp1       ^= (tmp1 >> 4);               // 10001001 0001
660         tmp2       ^= (tmp2 >> 4);               // 01000110 0010   
661         tmp3       ^= (tmp3 >> 4);               // 00011001 1000
662
663         DWORD hashVal = tmp1 + tmp2 + tmp3;
664
665         if (region == HOT)
666             hashVal     &= (numHotHashes - 1);   // numHotHashes is required to be a power of two
667         else
668             hashVal     &= (numColdHashes - 1);  // numColdHashes is required to be a power of two
669
670         return hashVal;
671     };
672
673     ArrayDPTR(RelativeFixupPointer<PTR_MethodTable>) GetGCStaticMTs(DWORD index);
674
675     PTR_MethodTable GetMT(DWORD i)
676     {
677         LIMITED_METHOD_DAC_CONTRACT;
678         return ppMT[i].GetValue(dac_cast<TADDR>(ppMT) + i * sizeof(RelativePointer<PTR_MethodTable>));
679     }
680
681 #ifdef FEATURE_PREJIT
682
683     void AddElement(MethodTable *pMethodTable);
684     void Save(DataImage *image, CorProfileData *profileData);
685     void Fixup(DataImage *image);
686
687     class ClassCtorInfoEntryArraySort : public CQuickSort<DWORD>
688     {
689     private:
690         DPTR(RelativePointer<PTR_MethodTable>) m_pBase1;
691
692     public:
693         //Constructor
694         ClassCtorInfoEntryArraySort(DWORD *base, DPTR(RelativePointer<PTR_MethodTable>) base1, int count)
695           : CQuickSort<DWORD>(base, count)
696         {
697             WRAPPER_NO_CONTRACT;
698
699             m_pBase1 = base1;
700         }
701         
702         //Returns -1,0,or 1 if first's nativeStartOffset is less than, equal to, or greater than second's
703         FORCEINLINE int Compare(DWORD *first, DWORD *second)
704         {
705             LIMITED_METHOD_CONTRACT;
706         
707             if (*first < *second)
708                 return -1;
709             else if (*first == *second)
710                 return 0;
711             else
712                 return 1;
713         }
714         
715 #ifndef DACCESS_COMPILE
716         // Swap is overwriten so that we can sort both the MethodTable pointer
717         // array and the ClassCtorInfoEntry array in parrallel.
718         FORCEINLINE void Swap(SSIZE_T iFirst, SSIZE_T iSecond)
719         {
720             LIMITED_METHOD_CONTRACT;
721
722             DWORD sTemp;
723             PTR_MethodTable sTemp1;
724
725             if (iFirst == iSecond) return;
726
727             sTemp = m_pBase[iFirst];
728             m_pBase[iFirst] = m_pBase[iSecond];
729             m_pBase[iSecond] = sTemp;
730
731             sTemp1 = m_pBase1[iFirst].GetValueMaybeNull();
732             m_pBase1[iFirst].SetValueMaybeNull(m_pBase1[iSecond].GetValueMaybeNull());
733             m_pBase1[iSecond].SetValueMaybeNull(sTemp1);
734         }
735 #endif // !DACCESS_COMPILE
736     };
737 #endif // FEATURE_PREJIT
738 };
739
740
741
742 #ifdef FEATURE_PREJIT
743
744 // For IBC Profiling we collect signature blobs for instantiated types.
745 // For such instantiated types and methods we create our own ibc token
746 // 
747 // For instantiated types, there also may be no corresponding type token 
748 // or method token for the instantiated types or method in our module.
749 // For these cases we create our own ibc token definition that is used
750 // to refer to these external types and methods.  We have to handle 
751 // external nested types and namespaces and method signatures.
752 //
753 //    ParamTypeSpec               = 4,    // Instantiated Type Signature
754 //    ParamMethodSpec             = 5,    // Instantiated Method Signature
755 //    ExternalNamespaceDef        = 6,    // External Namespace Token Definition 
756 //    ExternalTypeDef             = 7,    // External Type Token Definition
757 //    ExternalSignatureDef        = 8,    // External Signature Definition
758 //    ExternalMethodDef           = 9,    // External Method Token Definition
759 //
760 // typedef DPTR(class ProfilingBlobEntry) PTR_ProfilingBlobEntry;
761 class ProfilingBlobEntry
762 {
763 public:
764     virtual ~ProfilingBlobEntry() { LIMITED_METHOD_CONTRACT; };
765     virtual bool              IsEqual(const ProfilingBlobEntry *  other) const = 0;  // Pure Virtual
766     virtual size_t            Hash()        const                              = 0;
767     virtual BlobType          kind()        const                              = 0;
768     virtual size_t            varSize()     const                              = 0;
769     virtual void              newToken()                                       = 0;
770     mdToken                   token()       const { LIMITED_METHOD_CONTRACT; return m_token; }
771
772 protected:
773     mdToken                   m_token;
774 };
775
776 class TypeSpecBlobEntry : public ProfilingBlobEntry
777 {
778 public:
779     TypeSpecBlobEntry(DWORD _cbSig, PCCOR_SIGNATURE _pSig);
780     
781     virtual ~TypeSpecBlobEntry()                  { LIMITED_METHOD_CONTRACT;  delete [] m_pSig; }
782     virtual BlobType          kind()        const { LIMITED_METHOD_CONTRACT;  return ParamTypeSpec; }
783     virtual size_t            varSize()     const { LIMITED_METHOD_CONTRACT;  return sizeof(COR_SIGNATURE) * m_cbSig; }
784     virtual void              newToken()          { LIMITED_METHOD_CONTRACT;  m_token = ++s_lastTypeSpecToken; }
785     DWORD                     flags()       const { LIMITED_METHOD_CONTRACT;  return m_flags; }
786     DWORD                     cbSig()       const { LIMITED_METHOD_CONTRACT;  return m_cbSig; }
787     PCCOR_SIGNATURE           pSig()        const { LIMITED_METHOD_CONTRACT;  return m_pSig;  }
788     void                      orFlag(DWORD flag)  { LIMITED_METHOD_CONTRACT;  m_flags |= flag; }
789     static size_t             HashInit()          { LIMITED_METHOD_CONTRACT;  return 156437; }    
790
791     virtual bool              IsEqual(const ProfilingBlobEntry *  other) const;
792     virtual size_t            Hash()        const;
793
794     static const TypeSpecBlobEntry *  FindOrAdd(PTR_Module      pModule, 
795                                                 DWORD           _cbSig, 
796                                                 PCCOR_SIGNATURE _pSig);
797
798 private:
799     DWORD                     m_flags;
800     DWORD                     m_cbSig;
801     PCCOR_SIGNATURE           m_pSig;
802     
803     static idTypeSpec         s_lastTypeSpecToken;   
804 };
805
806 class MethodSpecBlobEntry : public ProfilingBlobEntry
807 {
808 public:
809     MethodSpecBlobEntry(DWORD _cbSig, PCCOR_SIGNATURE _pSig);
810     
811     virtual ~MethodSpecBlobEntry()                { LIMITED_METHOD_CONTRACT;  delete [] m_pSig; }
812     virtual BlobType          kind()        const { LIMITED_METHOD_CONTRACT;  return ParamMethodSpec; }
813     virtual size_t            varSize()     const { LIMITED_METHOD_CONTRACT;  return sizeof(COR_SIGNATURE) * m_cbSig; }
814     virtual void              newToken()          { LIMITED_METHOD_CONTRACT;  m_token = ++s_lastMethodSpecToken; }
815     DWORD                     flags()       const { LIMITED_METHOD_CONTRACT;  return m_flags; }
816     DWORD                     cbSig()       const { LIMITED_METHOD_CONTRACT;  return m_cbSig; }
817     PCCOR_SIGNATURE           pSig()        const { LIMITED_METHOD_CONTRACT;  return m_pSig;  }
818     void                      orFlag(DWORD flag)  { LIMITED_METHOD_CONTRACT;  m_flags |= flag; }
819     static size_t             HashInit()          { LIMITED_METHOD_CONTRACT;  return 187751; }    
820     
821     virtual bool              IsEqual(const ProfilingBlobEntry *  other) const;
822     virtual size_t            Hash()        const;
823     
824     static const MethodSpecBlobEntry *  FindOrAdd(PTR_Module      pModule, 
825                                                   DWORD           _cbSig, 
826                                                   PCCOR_SIGNATURE _pSig);
827
828 private:
829     DWORD                     m_flags;
830     DWORD                     m_cbSig;
831     PCCOR_SIGNATURE           m_pSig;
832     
833     static idTypeSpec  s_lastMethodSpecToken;   
834 };
835
836 class ExternalNamespaceBlobEntry : public ProfilingBlobEntry
837 {
838 public:
839     ExternalNamespaceBlobEntry(LPCSTR _pName);
840     
841     virtual ~ExternalNamespaceBlobEntry()         { LIMITED_METHOD_CONTRACT;  delete [] m_pName; }
842     virtual BlobType          kind()        const { LIMITED_METHOD_CONTRACT;  return ExternalNamespaceDef; }
843     virtual size_t            varSize()     const { LIMITED_METHOD_CONTRACT;  return sizeof(CHAR) * m_cbName; }
844     virtual void              newToken()          { LIMITED_METHOD_CONTRACT;  m_token = ++s_lastExternalNamespaceToken; }
845     DWORD                     cbName()      const { LIMITED_METHOD_CONTRACT;  return m_cbName; }
846     LPCSTR                    pName()       const { LIMITED_METHOD_CONTRACT;  return m_pName;  }
847     static size_t             HashInit()          { LIMITED_METHOD_CONTRACT;  return 225307; }    
848     
849     virtual bool              IsEqual(const ProfilingBlobEntry *  other) const;
850     virtual size_t            Hash()        const;
851
852     static const ExternalNamespaceBlobEntry *  FindOrAdd(PTR_Module pModule, LPCSTR _pName);
853
854 private:
855     DWORD                     m_cbName;
856     LPCSTR                    m_pName;
857     
858     static idExternalNamespace s_lastExternalNamespaceToken;   
859 };
860
861 class ExternalTypeBlobEntry : public ProfilingBlobEntry
862 {
863 public:
864     ExternalTypeBlobEntry(mdToken _assemblyRef,  mdToken _nestedClass,
865                           mdToken _nameSpace,    LPCSTR  _pName);
866
867     virtual ~ExternalTypeBlobEntry()              { LIMITED_METHOD_CONTRACT;  delete [] m_pName; }
868     virtual BlobType          kind()        const { LIMITED_METHOD_CONTRACT;  return ExternalTypeDef; }
869     virtual size_t            varSize()     const { LIMITED_METHOD_CONTRACT;  return sizeof(CHAR) * m_cbName; }
870     virtual void              newToken()          { LIMITED_METHOD_CONTRACT;  m_token = ++s_lastExternalTypeToken; }
871     mdToken                   assemblyRef() const { LIMITED_METHOD_CONTRACT;  return m_assemblyRef; }
872     mdToken                   nestedClass() const { LIMITED_METHOD_CONTRACT;  return m_nestedClass; }
873     mdToken                   nameSpace()   const { LIMITED_METHOD_CONTRACT;  return m_nameSpace; }
874     DWORD                     cbName()      const { LIMITED_METHOD_CONTRACT;  return m_cbName; }
875     LPCSTR                    pName()       const { LIMITED_METHOD_CONTRACT;  return m_pName;  }
876     static size_t             HashInit()          { LIMITED_METHOD_CONTRACT;  return 270371; }    
877
878     virtual bool              IsEqual(const ProfilingBlobEntry *  other) const;
879     virtual size_t            Hash()        const;
880
881     static const ExternalTypeBlobEntry *  FindOrAdd(PTR_Module pModule, 
882                                                     mdToken    _assemblyRef, 
883                                                     mdToken    _nestedClass,
884                                                     mdToken    _nameSpace, 
885                                                     LPCSTR     _pName);
886
887 private:
888     mdToken                   m_assemblyRef;
889     mdToken                   m_nestedClass;
890     mdToken                   m_nameSpace;
891     DWORD                     m_cbName;
892     LPCSTR                    m_pName;
893     
894     static idExternalType     s_lastExternalTypeToken;
895 };
896
897 class ExternalSignatureBlobEntry : public ProfilingBlobEntry
898 {
899 public:
900     ExternalSignatureBlobEntry(DWORD _cbSig, PCCOR_SIGNATURE _pSig);
901
902     virtual ~ExternalSignatureBlobEntry()         { LIMITED_METHOD_CONTRACT;  delete [] m_pSig; }
903     virtual BlobType          kind()        const { LIMITED_METHOD_CONTRACT;  return ExternalSignatureDef; }
904     virtual size_t            varSize()     const { LIMITED_METHOD_CONTRACT;  return sizeof(COR_SIGNATURE) * m_cbSig; }
905     virtual void              newToken()          { LIMITED_METHOD_CONTRACT;  m_token = ++s_lastExternalSignatureToken; }
906     DWORD                     cbSig()       const { LIMITED_METHOD_CONTRACT;  return m_cbSig; }
907     PCCOR_SIGNATURE           pSig()        const { LIMITED_METHOD_CONTRACT;  return m_pSig;  }
908     static size_t             HashInit()          { LIMITED_METHOD_CONTRACT;  return 324449; }    
909     
910     virtual bool              IsEqual(const ProfilingBlobEntry *  other) const;
911     virtual size_t            Hash()        const;
912
913     static const ExternalSignatureBlobEntry *  FindOrAdd(PTR_Module      pModule, 
914                                                          DWORD           _cbSig, 
915                                                          PCCOR_SIGNATURE _pSig);
916
917 private:
918     DWORD                     m_cbSig;
919     PCCOR_SIGNATURE           m_pSig;
920     
921     static idExternalSignature s_lastExternalSignatureToken;   
922 };
923
924 class ExternalMethodBlobEntry : public ProfilingBlobEntry
925 {
926 public:
927     ExternalMethodBlobEntry(mdToken _nestedClass, mdToken _signature, LPCSTR _pName);
928     
929     virtual ~ExternalMethodBlobEntry()            { LIMITED_METHOD_CONTRACT;  delete [] m_pName; }
930     virtual BlobType          kind()        const { LIMITED_METHOD_CONTRACT;  return ExternalMethodDef; }
931     virtual size_t            varSize()     const { LIMITED_METHOD_CONTRACT;  return sizeof(CHAR) * m_cbName; }
932     virtual void              newToken()          { LIMITED_METHOD_CONTRACT;  m_token = ++s_lastExternalMethodToken; }
933     mdToken                   nestedClass() const { LIMITED_METHOD_CONTRACT;  return m_nestedClass; }
934     mdToken                   signature()   const { LIMITED_METHOD_CONTRACT;  return m_signature; }
935     DWORD                     cbName()      const { LIMITED_METHOD_CONTRACT;  return m_cbName; }
936     LPCSTR                    pName()       const { LIMITED_METHOD_CONTRACT;  return m_pName;  }
937     static size_t             HashInit()          { LIMITED_METHOD_CONTRACT;  return 389357; }    
938     
939     virtual bool              IsEqual(const ProfilingBlobEntry *  other) const;
940     virtual size_t            Hash()        const;
941
942     static const ExternalMethodBlobEntry *  FindOrAdd(PTR_Module pModule, 
943                                                       mdToken    _nestedClass,
944                                                       mdToken    _signature, 
945                                                       LPCSTR     _pName);
946
947 private:
948     mdToken                   m_nestedClass;
949     mdToken                   m_signature;
950     DWORD                     m_cbName;
951     LPCSTR                    m_pName;
952     
953     static idExternalMethod   s_lastExternalMethodToken;   
954 };
955
956 struct IbcNameHandle
957 {
958     mdToken  tkIbcNameSpace; 
959     mdToken  tkIbcNestedClass;
960
961     LPCSTR   szName; 
962     LPCSTR   szNamespace;
963     mdToken  tkEnclosingClass;
964 };
965
966 //
967 // Hashtable of ProfilingBlobEntry *
968 //
969 class ProfilingBlobTraits : public NoRemoveSHashTraits<DefaultSHashTraits<ProfilingBlobEntry *> >
970 {
971 public:
972     typedef ProfilingBlobEntry *  key_t;
973
974     static key_t GetKey(element_t e)
975     {
976         LIMITED_METHOD_CONTRACT;
977         return e;
978     }
979     static BOOL Equals(key_t k1, key_t k2)
980     {
981         LIMITED_METHOD_CONTRACT;
982         return k1->IsEqual(k2);
983     }
984     static count_t Hash(key_t k)
985     {
986         LIMITED_METHOD_CONTRACT;
987         return (count_t) k->Hash();
988     }
989     static const element_t Null() 
990     { 
991         LIMITED_METHOD_CONTRACT; 
992         return NULL; 
993     }
994
995     static bool IsNull(const element_t &e) 
996     { 
997         LIMITED_METHOD_CONTRACT; 
998         return (e == NULL);
999     }
1000 };
1001
1002 typedef SHash<ProfilingBlobTraits> ProfilingBlobTable;
1003 typedef DPTR(ProfilingBlobTable) PTR_ProfilingBlobTable;
1004
1005
1006 #define METHODTABLE_RESTORE_REASON() \
1007     RESTORE_REASON_FUNC(CanNotPreRestoreHardBindToParentMethodTable) \
1008     RESTORE_REASON_FUNC(CanNotPreRestoreHardBindToCanonicalMethodTable) \
1009     RESTORE_REASON_FUNC(CrossModuleNonCanonicalMethodTable) \
1010     RESTORE_REASON_FUNC(CanNotHardBindToInstanceMethodTableChain) \
1011     RESTORE_REASON_FUNC(GenericsDictionaryNeedsRestore) \
1012     RESTORE_REASON_FUNC(InterfaceIsGeneric) \
1013     RESTORE_REASON_FUNC(CrossModuleGenericsStatics) \
1014     RESTORE_REASON_FUNC(ComImportStructDependenciesNeedRestore) \
1015     RESTORE_REASON_FUNC(CrossAssembly) \
1016     RESTORE_REASON_FUNC(ArrayElement) \
1017     RESTORE_REASON_FUNC(ProfilingEnabled)
1018
1019 #undef RESTORE_REASON_FUNC
1020 #define RESTORE_REASON_FUNC(s) s ,
1021 typedef enum
1022 {
1023
1024     METHODTABLE_RESTORE_REASON()
1025
1026     TotalMethodTables
1027 } MethodTableRestoreReason;
1028 #undef RESTORE_REASON_FUNC
1029
1030 class NgenStats
1031 {
1032 public:
1033     NgenStats()
1034     {
1035         LIMITED_METHOD_CONTRACT;
1036         memset (MethodTableRestoreNumReasons, 0, sizeof(DWORD)*(TotalMethodTables+1));
1037     }
1038
1039     DWORD MethodTableRestoreNumReasons[TotalMethodTables + 1];
1040 };
1041 #endif // FEATURE_PREJIT
1042
1043 //
1044 // A Module is the primary unit of code packaging in the runtime.  It
1045 // corresponds mostly to an OS executable image, although other kinds
1046 // of modules exist.
1047 //
1048 class UMEntryThunk;
1049
1050 // Hashtable of absolute addresses of IL blobs for dynamics, keyed by token
1051
1052  struct  DynamicILBlobEntry
1053 {
1054     mdToken     m_methodToken;
1055     TADDR       m_il;
1056 };
1057
1058 class DynamicILBlobTraits : public NoRemoveSHashTraits<DefaultSHashTraits<DynamicILBlobEntry> >
1059 {
1060 public:
1061     typedef mdToken key_t;
1062
1063     static key_t GetKey(element_t e)
1064     {
1065         LIMITED_METHOD_CONTRACT;
1066         SUPPORTS_DAC;
1067         return e.m_methodToken;
1068     }
1069     static BOOL Equals(key_t k1, key_t k2)
1070     {
1071         LIMITED_METHOD_CONTRACT;
1072         SUPPORTS_DAC;
1073         return k1 == k2;
1074     }
1075     static count_t Hash(key_t k)
1076     {
1077         LIMITED_METHOD_CONTRACT;
1078         SUPPORTS_DAC;
1079         return (count_t)(size_t)k;
1080     }
1081     static const element_t Null() 
1082     { 
1083         LIMITED_METHOD_CONTRACT; 
1084         SUPPORTS_DAC;
1085         DynamicILBlobEntry e; 
1086         e.m_il = TADDR(0);
1087         e.m_methodToken = 0; 
1088         return e; 
1089     }
1090     static bool IsNull(const element_t &e) 
1091     { 
1092         LIMITED_METHOD_CONTRACT; 
1093         SUPPORTS_DAC;
1094         return e.m_methodToken == 0;
1095     }
1096 };
1097
1098 typedef SHash<DynamicILBlobTraits> DynamicILBlobTable;
1099 typedef DPTR(DynamicILBlobTable) PTR_DynamicILBlobTable;
1100
1101
1102 // ESymbolFormat specified the format used by a symbol stream
1103 typedef enum 
1104 {
1105     eSymbolFormatNone,      /* symbol format to use not yet determined */
1106     eSymbolFormatPDB,       /* PDB format from diasymreader.dll - only safe for trusted scenarios */
1107     eSymbolFormatILDB       /* ILDB format from ildbsymbols.dll */
1108 }ESymbolFormat;
1109
1110
1111 #ifdef FEATURE_COMINTEROP
1112
1113 //---------------------------------------------------------------------------------------
1114 //
1115 // The type of each entry in the Guid to MT hash
1116 //
1117 typedef DPTR(GUID) PTR_GUID;
1118 typedef DPTR(struct GuidToMethodTableEntry) PTR_GuidToMethodTableEntry;
1119 struct GuidToMethodTableEntry
1120 {
1121     PTR_GUID        m_Guid;
1122     PTR_MethodTable m_pMT;
1123 };
1124
1125 //---------------------------------------------------------------------------------------
1126 //
1127 // The hash type itself
1128 //
1129 typedef DPTR(class GuidToMethodTableHashTable) PTR_GuidToMethodTableHashTable;
1130 class GuidToMethodTableHashTable : public NgenHashTable<GuidToMethodTableHashTable, GuidToMethodTableEntry, 4>
1131 {
1132 public:
1133     typedef NgenHashTable<GuidToMethodTableHashTable, GuidToMethodTableEntry, 4> Base_t;
1134     friend class Base_t;
1135
1136 #ifndef DACCESS_COMPILE
1137
1138 private:
1139     GuidToMethodTableHashTable(Module *pModule, LoaderHeap *pHeap, DWORD cInitialBuckets)
1140         : Base_t(pModule, pHeap, cInitialBuckets)
1141     { LIMITED_METHOD_CONTRACT; }
1142
1143 public:
1144     static GuidToMethodTableHashTable* Create(Module* pModule, DWORD cInitialBuckets, AllocMemTracker *pamTracker);
1145
1146     GuidToMethodTableEntry * InsertValue(PTR_GUID pGuid, PTR_MethodTable pMT, BOOL bReplaceIfFound, AllocMemTracker *pamTracker);
1147
1148 #endif // !DACCESS_COMPILE
1149
1150 public:
1151     typedef Base_t::LookupContext LookupContext;
1152
1153     PTR_MethodTable GetValue(const GUID * pGuid, LookupContext *pContext);
1154     GuidToMethodTableEntry * FindItem(const GUID * pGuid, LookupContext *pContext);
1155
1156 private:
1157     BOOL CompareKeys(PTR_GuidToMethodTableEntry pEntry, const GUID * pGuid);
1158     static DWORD Hash(const GUID * pGuid);
1159
1160 public:
1161     // An iterator for the table
1162     struct Iterator
1163     {
1164     public:
1165         Iterator() : m_pTable(NULL), m_fIterating(false)
1166         { LIMITED_METHOD_DAC_CONTRACT; }
1167         Iterator(GuidToMethodTableHashTable * pTable) : m_pTable(pTable), m_fIterating(false)
1168         { LIMITED_METHOD_DAC_CONTRACT; }
1169
1170     private:
1171         friend class GuidToMethodTableHashTable;
1172
1173         GuidToMethodTableHashTable * m_pTable;
1174         BaseIterator              m_sIterator;
1175         bool                      m_fIterating;
1176     };
1177
1178     BOOL FindNext(Iterator *it, GuidToMethodTableEntry **ppEntry);
1179     DWORD GetCount();
1180
1181 #ifdef DACCESS_COMPILE
1182     // do not save this in mini-/heap-dumps
1183     void EnumMemoryRegions(CLRDataEnumMemoryFlags flags)
1184     { SUPPORTS_DAC; }
1185     void EnumMemoryRegionsForEntry(GuidToMethodTableEntry *pEntry, CLRDataEnumMemoryFlags flags)
1186     { SUPPORTS_DAC; }
1187 #endif // DACCESS_COMPILE
1188
1189 #if defined(FEATURE_PREJIT) && !defined(DACCESS_COMPILE)
1190
1191 public:
1192     void Save(DataImage *pImage, CorProfileData *pProfileData);
1193     void Fixup(DataImage *pImage);
1194
1195 private:
1196     // We save all entries
1197     bool ShouldSave(DataImage *pImage, GuidToMethodTableEntry *pEntry)
1198     { LIMITED_METHOD_CONTRACT; return true; }
1199
1200     bool IsHotEntry(GuidToMethodTableEntry *pEntry, CorProfileData *pProfileData)
1201     { LIMITED_METHOD_CONTRACT; return false; }
1202
1203     bool SaveEntry(DataImage *pImage, CorProfileData *pProfileData, 
1204                         GuidToMethodTableEntry *pOldEntry, GuidToMethodTableEntry *pNewEntry, 
1205                         EntryMappingTable *pMap);
1206
1207     void FixupEntry(DataImage *pImage, GuidToMethodTableEntry *pEntry, void *pFixupBase, DWORD cbFixupOffset);
1208     
1209 #endif // FEATURE_PREJIT && !DACCESS_COMPILE
1210
1211 };
1212
1213 #endif // FEATURE_COMINTEROP
1214
1215
1216 //Hash for MemberRef to Desc tables (fieldDesc or MethodDesc)
1217 typedef DPTR(struct MemberRefToDescHashEntry) PTR_MemberRefToDescHashEntry;
1218
1219 struct MemberRefToDescHashEntry
1220 {
1221     TADDR m_value;
1222 };
1223
1224 typedef DPTR(class MemberRefToDescHashTable) PTR_MemberRefToDescHashTable;
1225
1226 #define MEMBERREF_MAP_INITIAL_SIZE 10
1227
1228 class MemberRefToDescHashTable: public NgenHashTable<MemberRefToDescHashTable, MemberRefToDescHashEntry, 2>
1229 {
1230         friend class NgenHashTable<MemberRefToDescHashTable, MemberRefToDescHashEntry, 2>;
1231 #ifndef DACCESS_COMPILE
1232
1233 private:
1234     MemberRefToDescHashTable(Module *pModule, LoaderHeap *pHeap, DWORD cInitialBuckets):
1235        NgenHashTable<MemberRefToDescHashTable, MemberRefToDescHashEntry, 2>(pModule, pHeap, cInitialBuckets) 
1236     { LIMITED_METHOD_CONTRACT; }
1237
1238 public:
1239
1240     static MemberRefToDescHashTable* Create(Module *pModule, DWORD cInitialBuckets, AllocMemTracker *pamTracker);
1241
1242     MemberRefToDescHashEntry* Insert(mdMemberRef token, MethodDesc *value);
1243     MemberRefToDescHashEntry* Insert(mdMemberRef token , FieldDesc *value);
1244 #endif //!DACCESS_COMPILE
1245
1246 public:
1247     typedef NgenHashTable<MemberRefToDescHashTable, MemberRefToDescHashEntry, 2>::LookupContext LookupContext;
1248
1249     PTR_MemberRef GetValue(mdMemberRef token, BOOL *pfIsMethod);
1250
1251 #ifdef DACCESS_COMPILE
1252
1253     void EnumMemoryRegions(CLRDataEnumMemoryFlags flags)
1254     {
1255         WRAPPER_NO_CONTRACT;
1256         BaseEnumMemoryRegions(flags);
1257     }
1258
1259     void EnumMemoryRegionsForEntry(MemberRefToDescHashEntry *pEntry, CLRDataEnumMemoryFlags flags)
1260     { SUPPORTS_DAC; }
1261
1262 #endif
1263
1264 #if defined(FEATURE_PREJIT) && !defined(DACCESS_COMPILE)
1265
1266     void Fixup(DataImage *pImage)
1267     {
1268         WRAPPER_NO_CONTRACT;
1269         BaseFixup(pImage);
1270     }
1271
1272     void Save(DataImage *pImage, CorProfileData *pProfileData);
1273
1274
1275 private:
1276     bool ShouldSave(DataImage *pImage, MemberRefToDescHashEntry *pEntry)
1277     {
1278         return IsHotEntry(pEntry, NULL);
1279     }
1280
1281     bool IsHotEntry(MemberRefToDescHashEntry *pEntry, CorProfileData *pProfileData) // yes according to IBC data
1282     {
1283                 LIMITED_METHOD_CONTRACT;
1284
1285         _ASSERTE(pEntry != NULL);
1286                 // Low order bit of data field indicates a hot entry.
1287                 return (pEntry->m_value & 0x1) != 0;
1288
1289     }
1290
1291
1292     bool SaveEntry(DataImage *pImage, CorProfileData *pProfileData, 
1293                         MemberRefToDescHashEntry *pOldEntry, MemberRefToDescHashEntry *pNewEntry, 
1294                         EntryMappingTable *pMap)
1295     {
1296         //The entries are mutable
1297         return FALSE;
1298     }
1299
1300     void FixupEntry(DataImage *pImage, MemberRefToDescHashEntry *pEntry, void *pFixupBase, DWORD cbFixupOffset);
1301
1302 #endif
1303 };
1304
1305 #ifdef FEATURE_READYTORUN
1306 typedef DPTR(class ReadyToRunInfo)      PTR_ReadyToRunInfo;
1307 #endif
1308
1309 struct ThreadLocalModule;
1310
1311 // A code:Module represents a DLL or EXE file loaded from the disk. It could either be a IL module or a
1312 // Native code (NGEN module). A module live in a code:Assembly
1313 // 
1314 // Some important fields are
1315 //    * code:Module.m_file - this points at a code:PEFile that understands the layout of a PE file. The most
1316 //        important part is getting at the code:Module (see file:..\inc\corhdr.h#ManagedHeader) from there
1317 //        you can get at the Meta-data and IL)
1318 //    * code:Module.m_pAvailableClasses - this is a table that lets you look up the types (the code:EEClass)
1319 //        for all the types in the module
1320 //        
1321 // See file:..\inc\corhdr.h#ManagedHeader for more on the layout of managed exectuable files. 
1322
1323 class Module
1324 {
1325 #ifdef DACCESS_COMPILE
1326     friend class ClrDataAccess;
1327     friend class NativeImageDumper;
1328 #endif
1329
1330     friend class DataImage;
1331
1332     VPTR_BASE_CONCRETE_VTABLE_CLASS(Module)
1333
1334 private:
1335     PTR_CUTF8               m_pSimpleName; // Cached simple name for better performance and easier diagnostics
1336
1337     PTR_PEFile              m_file;
1338
1339     MethodDesc              *m_pDllMain;
1340
1341     enum {
1342         // These are the values set in m_dwTransientFlags.
1343         // Note that none of these flags survive a prejit save/restore.
1344
1345         MODULE_IS_TENURED           = 0x00000001,   // Set once we know for sure the Module will not be freed until the appdomain itself exits
1346         M_CER_ROOT_TABLE_ON_HEAP    = 0x00000002,   // Set when m_pCerNgenRootTable is allocated from heap (at ngen time)
1347         CLASSES_FREED               = 0x00000004,
1348         IS_EDIT_AND_CONTINUE        = 0x00000008,   // is EnC Enabled for this module
1349
1350         IS_PROFILER_NOTIFIED        = 0x00000010,
1351         IS_ETW_NOTIFIED             = 0x00000020,
1352
1353         //
1354         // Note: the order of these must match the order defined in
1355         // cordbpriv.h for DebuggerAssemblyControlFlags. The three
1356         // values below should match the values defined in
1357         // DebuggerAssemblyControlFlags when shifted right
1358         // DEBUGGER_INFO_SHIFT bits.
1359         //
1360         DEBUGGER_USER_OVERRIDE_PRIV = 0x00000400,
1361         DEBUGGER_ALLOW_JIT_OPTS_PRIV= 0x00000800,
1362         DEBUGGER_TRACK_JIT_INFO_PRIV= 0x00001000,
1363         DEBUGGER_ENC_ENABLED_PRIV   = 0x00002000,   // this is what was attempted to be set.  IS_EDIT_AND_CONTINUE is actual result.
1364         DEBUGGER_PDBS_COPIED        = 0x00004000,
1365         DEBUGGER_IGNORE_PDBS        = 0x00008000,
1366         DEBUGGER_INFO_MASK_PRIV     = 0x0000Fc00,
1367         DEBUGGER_INFO_SHIFT_PRIV    = 10,
1368
1369         // Used to indicate that this module has had it's IJW fixups properly installed.
1370         IS_IJW_FIXED_UP             = 0x00080000,
1371         IS_BEING_UNLOADED           = 0x00100000,
1372
1373         // Used to indicate that the module is loaded sufficiently for generic candidate instantiations to work
1374         MODULE_READY_FOR_TYPELOAD  = 0x00200000,
1375
1376         // Used during NGen only
1377         TYPESPECS_TRIAGED           = 0x40000000,
1378         MODULE_SAVED                = 0x80000000,
1379     };
1380
1381     enum {
1382         // These are the values set in m_dwPersistedFlags.  These will survive
1383         // a prejit save/restore
1384         // unused                   = 0x00000001,
1385         COMPUTED_GLOBAL_CLASS       = 0x00000002,
1386
1387         // This flag applies to assembly, but it is stored so it can be cached in ngen image
1388         COMPUTED_STRING_INTERNING   = 0x00000004,
1389         NO_STRING_INTERNING         = 0x00000008,
1390
1391         // This flag applies to assembly, but it is stored so it can be cached in ngen image
1392         COMPUTED_WRAP_EXCEPTIONS    = 0x00000010,
1393         WRAP_EXCEPTIONS             = 0x00000020,
1394
1395         // This flag applies to assembly, but it is stored so it can be cached in ngen image
1396         COMPUTED_RELIABILITY_CONTRACT=0x00000040,
1397
1398         // This flag applies to assembly, but is also stored here so that it can be cached in ngen image
1399         COLLECTIBLE_MODULE          = 0x00000080,
1400
1401         // Caches metadata version
1402         COMPUTED_IS_PRE_V4_ASSEMBLY = 0x00000100,
1403         IS_PRE_V4_ASSEMBLY          = 0x00000200,
1404
1405         //If attribute value has been cached before
1406         DEFAULT_DLL_IMPORT_SEARCH_PATHS_IS_CACHED   = 0x00000400,
1407
1408         //If module has default dll import search paths attribute
1409         DEFAULT_DLL_IMPORT_SEARCH_PATHS_STATUS      = 0x00000800,
1410
1411         //If attribute value has been cached before
1412         NEUTRAL_RESOURCES_LANGUAGE_IS_CACHED = 0x00001000,
1413
1414         //If m_MethodDefToPropertyInfoMap has been generated
1415         COMPUTED_METHODDEF_TO_PROPERTYINFO_MAP = 0x00002000,
1416
1417         // Low level system assembly. Used by preferred zap module computation.
1418         LOW_LEVEL_SYSTEM_ASSEMBLY_BY_NAME = 0x00004000,
1419     };
1420
1421     Volatile<DWORD>          m_dwTransientFlags;
1422     Volatile<DWORD>          m_dwPersistedFlags;
1423
1424     // Linked list of VASig cookie blocks: protected by m_pStubListCrst
1425     VASigCookieBlock        *m_pVASigCookieBlock;
1426
1427     PTR_Assembly            m_pAssembly;
1428     mdFile                  m_moduleRef;
1429
1430     CrstExplicitInit        m_Crst;
1431     CrstExplicitInit        m_FixupCrst;
1432
1433     // Debugging symbols reader interface. This will only be
1434     // initialized if needed, either by the debugging subsystem or for
1435     // an exception.
1436     ISymUnmanagedReader *   m_pISymUnmanagedReader;
1437
1438     // The reader lock is used to serialize all creation of symbol readers.
1439     // It does NOT seralize all access to the readers since we freely give
1440     // out references to the reader outside this class.  Instead, once a
1441     // reader object is created, it is entirely read-only and so thread-safe.
1442     CrstExplicitInit        m_ISymUnmanagedReaderCrst;
1443
1444     // Storage for the in-memory symbol stream if any
1445     // Debugger may retrieve this from out-of-process.
1446     PTR_CGrowableStream     m_pIStreamSym;
1447
1448     // Format the above stream is in (if any)
1449     ESymbolFormat           m_symbolFormat;
1450
1451     // Active dependencies
1452     ArrayList               m_activeDependencies;
1453
1454     SynchronizedBitMask     m_unconditionalDependencies;
1455     ULONG                   m_dwNumberOfActivations;
1456
1457     // For protecting additions to the heap
1458     CrstExplicitInit        m_LookupTableCrst;
1459
1460     #define TYPE_DEF_MAP_ALL_FLAGS                    ((TADDR)0x00000001)
1461         #define ZAPPED_TYPE_NEEDS_NO_RESTORE          ((TADDR)0x00000001)
1462
1463     #define TYPE_REF_MAP_ALL_FLAGS                    NO_MAP_FLAGS
1464         // For type ref map, 0x1 cannot be used as a flag: reserved for FIXUP_POINTER_INDIRECTION bit
1465         // For type ref map, 0x2 cannot be used as a flag: reserved for TypeHandle to signify TypeDesc
1466
1467     #define METHOD_DEF_MAP_ALL_FLAGS                  NO_MAP_FLAGS
1468
1469     #define FIELD_DEF_MAP_ALL_FLAGS                   NO_MAP_FLAGS
1470
1471     #define MEMBER_REF_MAP_ALL_FLAGS                  ((TADDR)0x00000003)
1472         // For member ref hash table, 0x1 is reserved for IsHot bit
1473         #define IS_FIELD_MEMBER_REF                   ((TADDR)0x00000002)      // denotes that target is a FieldDesc
1474
1475     #define GENERIC_PARAM_MAP_ALL_FLAGS               NO_MAP_FLAGS
1476
1477     #define GENERIC_TYPE_DEF_MAP_ALL_FLAGS            ((TADDR)0x00000001)
1478         #define ZAPPED_GENERIC_TYPE_NEEDS_NO_RESTORE  ((TADDR)0x00000001)
1479
1480     #define FILE_REF_MAP_ALL_FLAGS                    NO_MAP_FLAGS
1481         // For file ref map, 0x1 cannot be used as a flag: reserved for FIXUP_POINTER_INDIRECTION bit
1482
1483     #define MANIFEST_MODULE_MAP_ALL_FLAGS             NO_MAP_FLAGS
1484         // For manifest module map, 0x1 cannot be used as a flag: reserved for FIXUP_POINTER_INDIRECTION bit
1485
1486     #define PROPERTY_INFO_MAP_ALL_FLAGS               NO_MAP_FLAGS
1487
1488     // Linear mapping from TypeDef token to MethodTable *
1489     // For generic types, IsGenericTypeDefinition() is true i.e. instantiation at formals
1490     LookupMap<PTR_MethodTable>      m_TypeDefToMethodTableMap;
1491
1492     // Linear mapping from TypeRef token to TypeHandle *
1493     LookupMap<PTR_TypeRef>          m_TypeRefToMethodTableMap;
1494
1495     // Linear mapping from MethodDef token to MethodDesc *
1496     // For generic methods, IsGenericTypeDefinition() is true i.e. instantiation at formals
1497     LookupMap<PTR_MethodDesc>       m_MethodDefToDescMap;
1498
1499     // Linear mapping from FieldDef token to FieldDesc*
1500     LookupMap<PTR_FieldDesc>        m_FieldDefToDescMap;
1501
1502     // mapping from MemberRef token to MethodDesc*, FieldDesc*
1503     PTR_MemberRefToDescHashTable        m_pMemberRefToDescHashTable;
1504
1505     // Linear mapping from GenericParam token to TypeVarTypeDesc*
1506     LookupMap<PTR_TypeVarTypeDesc>  m_GenericParamToDescMap;
1507
1508     // Linear mapping from TypeDef token to the MethodTable * for its canonical generic instantiation
1509     // If the type is not generic, the entry is guaranteed to be NULL.  This means we are paying extra
1510     // space in order to use the LookupMap infrastructure, but what it buys us is IBC support and
1511     // a compressed format for NGen that makes up for it.
1512     LookupMap<PTR_MethodTable>      m_GenericTypeDefToCanonMethodTableMap;
1513
1514     // Mapping from File token to Module *
1515     LookupMap<PTR_Module>           m_FileReferencesMap;
1516
1517     // Mapping of AssemblyRef token to Module *
1518     LookupMap<PTR_Module>           m_ManifestModuleReferencesMap;
1519
1520     // Mapping from MethodDef token to pointer-sized value encoding property information
1521     LookupMap<SIZE_T>           m_MethodDefToPropertyInfoMap;
1522
1523     // IL stub cache with fabricated MethodTable parented by this module.
1524     ILStubCache                *m_pILStubCache;
1525
1526     ULONG m_DefaultDllImportSearchPathsAttributeValue;
1527
1528      LPCUTF8 m_pszCultureName;
1529      ULONG m_CultureNameLength;
1530      INT16 m_FallbackLocation;
1531
1532 #ifdef PROFILING_SUPPORTED_DATA 
1533      // a wrapper for the underlying PEFile metadata emitter which validates that the metadata edits being
1534      // made are supported modifications to the type system
1535      VolatilePtr<IMetaDataEmit> m_pValidatedEmitter;
1536 #endif
1537
1538 public:
1539     LookupMap<PTR_MethodTable>::Iterator EnumerateTypeDefs()
1540     {
1541         LIMITED_METHOD_CONTRACT;
1542         SUPPORTS_DAC;
1543
1544         return LookupMap<PTR_MethodTable>::Iterator(&m_TypeDefToMethodTableMap);
1545     }
1546
1547     // Hash of available types by name
1548     PTR_EEClassHashTable    m_pAvailableClasses;
1549
1550     // Hashtable of generic type instances
1551     PTR_EETypeHashTable     m_pAvailableParamTypes;
1552
1553     // For protecting additions to m_pInstMethodHashTable
1554     CrstExplicitInit        m_InstMethodHashTableCrst;
1555
1556     // Hashtable of instantiated methods and per-instantiation static methods
1557     PTR_InstMethodHashTable m_pInstMethodHashTable;
1558
1559 #ifdef FEATURE_PREJIT
1560     // Mapping from tokens to IL marshaling stubs (NGEN only).
1561     PTR_StubMethodHashTable m_pStubMethodHashTable;
1562 #endif // FEATURE_PREJIT
1563
1564     // This is used by the Debugger. We need to store a dword
1565     // for a count of JMC functions. This is a count, not a pointer.
1566     // We'll pass the address of this field
1567     // off to the jit, which will include it in probes injected for
1568     // debuggable code.
1569     // This means we need the dword at the time a function is jitted.
1570     // The Debugger has its own module structure, but those aren't created
1571     // if a debugger isn't attached.
1572     // We put it here instead of in the debugger's module because:
1573     // 1) we need a module structure that's around even when the debugger
1574     // isn't attached... so we use the EE's module.
1575     // 2) Needs to be here for ngen
1576     DWORD                   m_dwDebuggerJMCProbeCount;
1577
1578     // We can skip the JMC probes if we know that a module has no JMC stuff
1579     // inside. So keep a strict count of all functions inside us.
1580     bool HasAnyJMCFunctions();
1581     void IncJMCFuncCount();
1582     void DecJMCFuncCount();
1583
1584     // Get and set the default JMC status of this module.
1585     bool GetJMCStatus();
1586     void SetJMCStatus(bool fStatus);
1587
1588     // If this is a dynamic module, eagerly serialize the metadata so that it is available for DAC.
1589     // This is a nop for non-dynamic modules.
1590     void UpdateDynamicMetadataIfNeeded();
1591
1592 #ifdef _DEBUG
1593     //
1594     // We call these methods to seal/unseal the
1595     // lists: m_pAvailableClasses and m_pAvailableParamTypes 
1596     // 
1597     // When they are sealed ClassLoader::PublishType cannot 
1598     // add new generic types or methods
1599     //   
1600     void SealGenericTypesAndMethods();
1601     void UnsealGenericTypesAndMethods();
1602 #endif
1603
1604 private:
1605     // Set the given bit on m_dwTransientFlags. Return true if we won the race to set the bit.
1606     BOOL SetTransientFlagInterlocked(DWORD dwFlag);
1607
1608     // Invoke fusion hooks into host to fetch PDBs
1609     void FetchPdbsFromHost();
1610
1611     // Cannoically-cased hashtable of the available class names for
1612     // case insensitive lookup.  Contains pointers into
1613     // m_pAvailableClasses.
1614     PTR_EEClassHashTable    m_pAvailableClassesCaseIns;
1615
1616     // Pointer to binder, if we have one
1617     friend class MscorlibBinder;
1618     PTR_MscorlibBinder      m_pBinder;
1619
1620 public:
1621     BOOL IsCollectible()
1622     {
1623         LIMITED_METHOD_DAC_CONTRACT;
1624         return (m_dwPersistedFlags & COLLECTIBLE_MODULE) != 0;
1625     }
1626
1627 #ifdef FEATURE_READYTORUN
1628 private:
1629     PTR_ReadyToRunInfo      m_pReadyToRunInfo;
1630 #endif
1631
1632 #ifdef FEATURE_PREJIT
1633
1634 private:
1635     PTR_NGenLayoutInfo      m_pNGenLayoutInfo;
1636
1637     PTR_ProfilingBlobTable  m_pProfilingBlobTable;   // While performing IBC instrumenting this hashtable is populated with the External defs
1638     CorProfileData *        m_pProfileData;          // While ngen-ing with IBC optimizations this contains a link to the IBC data for the assembly
1639
1640     // Profile information
1641     BOOL                            m_nativeImageProfiling;
1642     CORCOMPILE_METHOD_PROFILE_LIST *m_methodProfileList;
1643
1644 #if defined(FEATURE_COMINTEROP)
1645         public:
1646
1647         #ifndef DACCESS_COMPILE
1648             BOOL CanCacheWinRTTypeByGuid(MethodTable *pMT);
1649             void CacheWinRTTypeByGuid(PTR_MethodTable pMT, PTR_GuidInfo pgi = NULL);
1650         #endif // !DACCESS_COMPILE
1651
1652             PTR_MethodTable LookupTypeByGuid(const GUID & guid);
1653             void GetCachedWinRTTypes(SArray<PTR_MethodTable> * pTypes, SArray<GUID> * pGuids);
1654
1655         private:
1656             PTR_GuidToMethodTableHashTable m_pGuidToTypeHash;   // A map from GUID to Type, for the "WinRT-interesting" types
1657
1658 #endif // defined(FEATURE_COMINTEROP)
1659
1660 #endif // FEATURE_PREJIT
1661
1662     // Module wide static fields information
1663     ModuleCtorInfo          m_ModuleCtorInfo;
1664
1665 #ifdef FEATURE_PREJIT
1666     struct TokenProfileData
1667     {
1668         static TokenProfileData *CreateNoThrow(void);
1669
1670         TokenProfileData()
1671             // We need a critical section that can be entered in both preemptive and cooperative modes.
1672             // Hopefully this restriction can be removed in the future.
1673             : crst(CrstSaveModuleProfileData, CRST_UNSAFE_ANYMODE)
1674         {
1675             WRAPPER_NO_CONTRACT;
1676         }
1677
1678         ~TokenProfileData()
1679         {
1680             WRAPPER_NO_CONTRACT;
1681         }
1682
1683         Crst crst;
1684
1685         struct Formats
1686         {
1687             CQuickArray<CORBBTPROF_TOKEN_INFO>   tokenArray;
1688             RidBitmap                   tokenBitmaps[CORBBTPROF_TOKEN_MAX_NUM_FLAGS];
1689         } m_formats[SectionFormatCount];
1690
1691     } *m_tokenProfileData;
1692
1693     // Stats for prejit log
1694     NgenStats                *m_pNgenStats;
1695 #endif // FEATURE_PREJIT
1696
1697
1698 protected:
1699
1700     void CreateDomainThunks();
1701
1702 protected:
1703     void DoInit(AllocMemTracker *pamTracker, LPCWSTR szName);
1704
1705 protected:
1706 #ifndef DACCESS_COMPILE
1707     virtual void Initialize(AllocMemTracker *pamTracker, LPCWSTR szName = NULL);
1708     void InitializeForProfiling();
1709 #ifdef FEATURE_PREJIT 
1710     void InitializeNativeImage(AllocMemTracker* pamTracker);
1711 #endif
1712 #endif
1713
1714     void AllocateMaps();
1715
1716 #ifdef _DEBUG
1717     void DebugLogRidMapOccupancy();
1718 #endif // _DEBUG
1719
1720     static HRESULT VerifyFile(PEFile *file, BOOL fZap);
1721
1722  public:
1723     static Module *Create(Assembly *pAssembly, mdFile kFile, PEFile *pFile, AllocMemTracker *pamTracker);
1724
1725  protected:
1726     Module(Assembly *pAssembly, mdFile moduleRef, PEFile *file);
1727
1728
1729  public:
1730 #ifndef DACCESS_COMPILE
1731     virtual void Destruct();
1732 #ifdef  FEATURE_PREJIT
1733     void DeleteNativeCodeRanges();
1734 #endif
1735 #endif
1736
1737     PTR_LoaderAllocator GetLoaderAllocator();
1738
1739     PTR_PEFile GetFile() const { LIMITED_METHOD_DAC_CONTRACT; return m_file; }
1740
1741     static size_t GetFileOffset() { LIMITED_METHOD_CONTRACT; return offsetof(Module, m_file); }
1742
1743     BOOL IsManifest();
1744
1745     void ApplyMetaData();
1746
1747     void FixupVTables();
1748
1749     void FreeClassTables();
1750
1751 #ifdef DACCESS_COMPILE
1752     virtual void EnumMemoryRegions(CLRDataEnumMemoryFlags flags,
1753                                    bool enumThis);
1754 #endif // DACCESS_COMPILE
1755
1756     ReflectionModule *GetReflectionModule() const
1757     {
1758         LIMITED_METHOD_CONTRACT;
1759         SUPPORTS_DAC;
1760
1761         _ASSERTE(IsReflection());
1762         return dac_cast<PTR_ReflectionModule>(this);
1763     }
1764
1765     PTR_Assembly GetAssembly() const;
1766
1767     int GetClassLoaderIndex()
1768     {
1769         LIMITED_METHOD_CONTRACT;
1770
1771         return RidFromToken(m_moduleRef);
1772     }
1773
1774     MethodTable *GetGlobalMethodTable();
1775     bool         NeedsGlobalMethodTable();
1776
1777     // Only for non-manifest modules
1778     DomainModule *GetDomainModule(AppDomain *pDomain);
1779     DomainModule *FindDomainModule(AppDomain *pDomain);
1780
1781     // This works for manifest modules too
1782     DomainFile *GetDomainFile(AppDomain *pDomain);
1783     DomainFile *FindDomainFile(AppDomain *pDomain);
1784
1785     // Operates on assembly of module
1786     DomainAssembly *GetDomainAssembly(AppDomain *pDomain);
1787     DomainAssembly *FindDomainAssembly(AppDomain *pDomain);
1788
1789     // Versions which rely on the current AppDomain (N/A for DAC builds)
1790 #ifndef DACCESS_COMPILE
1791     DomainModule * GetDomainModule()         { WRAPPER_NO_CONTRACT; return GetDomainModule(GetAppDomain()); }
1792     DomainFile * GetDomainFile()             { WRAPPER_NO_CONTRACT; return GetDomainFile(GetAppDomain()); }
1793     DomainAssembly * GetDomainAssembly()     { WRAPPER_NO_CONTRACT; return GetDomainAssembly(GetAppDomain()); }
1794 #endif
1795
1796     void SetDomainFile(DomainFile *pDomainFile);
1797
1798     OBJECTREF GetExposedObject();
1799
1800     ClassLoader *GetClassLoader();
1801     PTR_BaseDomain GetDomain();
1802 #ifdef FEATURE_CODE_VERSIONING
1803     CodeVersionManager * GetCodeVersionManager();
1804 #endif
1805 #ifdef FEATURE_TIERED_COMPILATION
1806     CallCounter * GetCallCounter();
1807 #endif
1808
1809     mdFile GetModuleRef()
1810     {
1811         LIMITED_METHOD_CONTRACT;
1812
1813         return m_moduleRef;
1814     }
1815
1816
1817     BOOL IsResource() const { WRAPPER_NO_CONTRACT; SUPPORTS_DAC; return GetFile()->IsResource(); }
1818     BOOL IsPEFile() const { WRAPPER_NO_CONTRACT; return !GetFile()->IsDynamic(); }
1819     BOOL IsReflection() const { WRAPPER_NO_CONTRACT; SUPPORTS_DAC; return GetFile()->IsDynamic(); }
1820     BOOL IsIbcOptimized() const { WRAPPER_NO_CONTRACT; return GetFile()->IsIbcOptimized(); }
1821     // Returns true iff the debugger can see this module.
1822     BOOL IsVisibleToDebugger();
1823
1824
1825     BOOL IsEditAndContinueEnabled() 
1826     { 
1827         LIMITED_METHOD_CONTRACT; 
1828         SUPPORTS_DAC;
1829         // We are seeing cases where this flag is set for a module that is not an EditAndContinueModule.  This should
1830         // never happen unless the module is EditAndContinueCapable, in which case we would have created an EditAndContinueModule
1831         // not a Module.  
1832         //_ASSERTE((m_dwTransientFlags & IS_EDIT_AND_CONTINUE) == 0 || IsEditAndContinueCapable());
1833         return (IsEditAndContinueCapable()) && ((m_dwTransientFlags & IS_EDIT_AND_CONTINUE) != 0); 
1834     }
1835
1836     BOOL IsEditAndContinueCapable();
1837     
1838     BOOL IsIStream() { LIMITED_METHOD_CONTRACT; return GetFile()->IsIStream(); }
1839
1840     BOOL IsSystem() { WRAPPER_NO_CONTRACT; SUPPORTS_DAC; return m_file->IsSystem(); }
1841
1842     static BOOL IsEditAndContinueCapable(Assembly *pAssembly, PEFile *file);
1843
1844     void EnableEditAndContinue()
1845     {
1846         LIMITED_METHOD_CONTRACT;
1847         SUPPORTS_DAC;
1848         // _ASSERTE(IsEditAndContinueCapable());
1849         LOG((LF_ENC, LL_INFO100, "EnableEditAndContinue: this:0x%x, %s\n", this, GetDebugName()));
1850         m_dwTransientFlags |= IS_EDIT_AND_CONTINUE;
1851     }
1852
1853     void DisableEditAndContinue()
1854     {
1855         LIMITED_METHOD_CONTRACT;
1856         SUPPORTS_DAC;
1857         // don't _ASSERTE(IsEditAndContinueCapable());
1858         LOG((LF_ENC, LL_INFO100, "DisableEditAndContinue: this:0x%x, %s\n", this, GetDebugName()));
1859         m_dwTransientFlags = m_dwTransientFlags.Load() & (~IS_EDIT_AND_CONTINUE);
1860     }
1861
1862     BOOL IsTenured()
1863     {
1864         LIMITED_METHOD_CONTRACT;
1865         return m_dwTransientFlags & MODULE_IS_TENURED;
1866     }
1867
1868 #ifndef DACCESS_COMPILE
1869     VOID SetIsTenured()
1870     {
1871         LIMITED_METHOD_CONTRACT;
1872         FastInterlockOr(&m_dwTransientFlags, MODULE_IS_TENURED);
1873     }
1874
1875     // CAUTION: This should only be used as backout code if an assembly is unsuccessfully
1876     //          added to the shared domain assembly map.
1877     VOID UnsetIsTenured()
1878     {
1879         LIMITED_METHOD_CONTRACT;
1880         FastInterlockAnd(&m_dwTransientFlags, ~MODULE_IS_TENURED);
1881     }
1882 #endif // !DACCESS_COMPILE
1883
1884
1885     // This means the module has been sufficiently fixed up/security checked
1886     // that type loads can occur in domains. This is not sufficient to indicate
1887     // that domain-specific types can be loaded when applied to domain-neutral modules
1888     BOOL IsReadyForTypeLoad()
1889     {
1890         LIMITED_METHOD_CONTRACT;
1891         return m_dwTransientFlags & MODULE_READY_FOR_TYPELOAD;
1892     }
1893
1894 #ifndef DACCESS_COMPILE
1895     VOID SetIsReadyForTypeLoad()
1896     {
1897         LIMITED_METHOD_CONTRACT;
1898         FastInterlockOr(&m_dwTransientFlags, MODULE_READY_FOR_TYPELOAD);
1899     }
1900 #endif
1901
1902     BOOL IsLowLevelSystemAssemblyByName()
1903     {
1904         LIMITED_METHOD_CONTRACT;
1905         // The flag is set during initialization, so we can skip the memory barrier
1906         return m_dwPersistedFlags.LoadWithoutBarrier() & LOW_LEVEL_SYSTEM_ASSEMBLY_BY_NAME;
1907     }
1908
1909 #ifndef DACCESS_COMPILE
1910     VOID EnsureActive();
1911     VOID EnsureAllocated();    
1912     VOID EnsureLibraryLoaded();
1913 #endif
1914
1915     CHECK CheckActivated();
1916     ULONG GetNumberOfActivations();
1917     ULONG IncrementNumberOfActivations();
1918
1919     IMDInternalImport *GetMDImport() const
1920     {
1921         WRAPPER_NO_CONTRACT;
1922         SUPPORTS_DAC;
1923
1924 #ifdef DACCESS_COMPILE
1925         if (IsReflection())
1926         {
1927             return DacGetMDImport(GetReflectionModule(), true);
1928         }
1929 #endif // DACCESS_COMPILE
1930         return m_file->GetPersistentMDImport();
1931     }
1932
1933 #ifndef DACCESS_COMPILE
1934     IMetaDataEmit *GetEmitter()
1935     {
1936         WRAPPER_NO_CONTRACT;
1937
1938         return m_file->GetEmitter();
1939     }
1940
1941 #if defined(PROFILING_SUPPORTED) && !defined(CROSSGEN_COMPILE) 
1942     IMetaDataEmit *GetValidatedEmitter();
1943 #endif
1944
1945     IMetaDataImport2 *GetRWImporter()
1946     {
1947         WRAPPER_NO_CONTRACT;
1948
1949         return m_file->GetRWImporter();
1950     }
1951
1952     IMetaDataAssemblyImport *GetAssemblyImporter()
1953     {
1954         WRAPPER_NO_CONTRACT;
1955
1956         return m_file->GetAssemblyImporter();
1957     }
1958
1959     HRESULT GetReadablePublicMetaDataInterface(DWORD dwOpenFlags, REFIID riid, LPVOID * ppvInterface);
1960 #endif // !DACCESS_COMPILE
1961
1962     BOOL IsWindowsRuntimeModule();
1963
1964     BOOL IsInCurrentVersionBubble();
1965
1966     LPCWSTR GetPathForErrorMessages();
1967
1968
1969 #ifdef FEATURE_ISYM_READER
1970     // Gets an up-to-date symbol reader for this module, lazily creating it if necessary
1971     // The caller must call Release
1972     ISymUnmanagedReader *GetISymUnmanagedReader(void);
1973     ISymUnmanagedReader *GetISymUnmanagedReaderNoThrow(void);
1974 #endif // FEATURE_ISYM_READER
1975
1976     // Save a copy of the provided debugging symbols in the InMemorySymbolStream.
1977     // These are used by code:Module::GetInMemorySymbolStream and code:Module.GetISymUnmanagedReader
1978     // This can only be called during module creation, before anyone may have tried to create a reader.
1979     void SetSymbolBytes(LPCBYTE pSyms, DWORD cbSyms);
1980
1981     // Does the current configuration permit reading of symbols for this module?
1982     // Note that this may require calling into managed code (to resolve security policy).
1983     BOOL IsSymbolReadingEnabled(void);
1984
1985     BOOL IsPersistedObject(void *address);
1986
1987
1988     // Get the in-memory symbol stream for this module, if any.
1989     // If none, this will return null.  This is used by modules loaded in-memory (eg. from a byte-array)
1990     // and by dynamic modules.  Callers that actually do anything with the return value will almost
1991     // certainly want to check GetInMemorySymbolStreamFormat to know how to interpret the bytes
1992     // in the stream.
1993     PTR_CGrowableStream GetInMemorySymbolStream()
1994     {
1995         LIMITED_METHOD_CONTRACT;
1996         SUPPORTS_DAC;
1997
1998         // Symbol format should be "none" if-and-only-if our stream is null
1999         // If this fails, it may mean somebody is trying to examine this module after 
2000         // code:Module::Destruct has been called.
2001         _ASSERTE( (m_symbolFormat == eSymbolFormatNone) == (m_pIStreamSym == NULL) );
2002
2003         return m_pIStreamSym;
2004     }
2005
2006     // Get the format of the in-memory symbol stream for this module, or 
2007     // eSymbolFormatNone if no in-memory symbols.
2008     ESymbolFormat GetInMemorySymbolStreamFormat()
2009     {
2010         LIMITED_METHOD_CONTRACT;
2011         SUPPORTS_DAC;
2012
2013         // Symbol format should be "none" if-and-only-if our stream is null
2014         // If this fails, it may mean somebody is trying to examine this module after 
2015         // code:Module::Destruct has been called.
2016         _ASSERTE( (m_symbolFormat == eSymbolFormatNone) == (m_pIStreamSym == NULL) );
2017
2018         return m_symbolFormat;
2019     }
2020
2021 #ifndef DACCESS_COMPILE
2022     // Set the in-memory stream for debug symbols
2023     // This must only be called when there is no existing stream.
2024     // This takes an AddRef on the supplied stream.
2025     void SetInMemorySymbolStream(CGrowableStream *pStream, ESymbolFormat symbolFormat)
2026     {
2027         LIMITED_METHOD_CONTRACT;
2028
2029         // Must have provided valid stream data
2030         CONSISTENCY_CHECK(pStream != NULL);
2031         CONSISTENCY_CHECK(symbolFormat != eSymbolFormatNone);
2032
2033         // we expect set to only be called once
2034         CONSISTENCY_CHECK(m_pIStreamSym == NULL);
2035         CONSISTENCY_CHECK(m_symbolFormat == eSymbolFormatNone);    
2036
2037         m_symbolFormat = symbolFormat;
2038         m_pIStreamSym = pStream;
2039         m_pIStreamSym->AddRef();
2040     }
2041
2042     // Release and clear the in-memory symbol stream if any
2043     void ClearInMemorySymbolStream()
2044     {      
2045         LIMITED_METHOD_CONTRACT;
2046         if( m_pIStreamSym != NULL )
2047         {
2048             m_pIStreamSym->Release();
2049             m_pIStreamSym = NULL;
2050             // We could set m_symbolFormat to eSymbolFormatNone to be consistent with not having
2051             // a stream, but no-one should be trying to look at it after destruct time, so it's
2052             // better to leave it inconsistent and get an ASSERT if someone tries to examine the
2053             // module's sybmol stream after the module was destructed.
2054         }
2055     }
2056
2057     // Release the symbol reader if any
2058     // Caller is responsible for aquiring the reader lock if this could occur
2059     // concurrently with other uses of the reader (i.e. not shutdown/unload time)
2060     void ReleaseISymUnmanagedReader(void);
2061
2062     virtual void ReleaseILData();
2063
2064
2065 #endif // DACCESS_COMPILE
2066
2067     // IL stub cache
2068     ILStubCache* GetILStubCache();
2069
2070     // Classes
2071     void AddClass(mdTypeDef classdef);
2072     void BuildClassForModule();
2073     PTR_EEClassHashTable GetAvailableClassHash()
2074     {
2075         LIMITED_METHOD_CONTRACT;
2076         SUPPORTS_DAC; 
2077         {
2078             // IsResource() may lock when accessing metadata, but this is only in debug,
2079             // for the assert below
2080             CONTRACT_VIOLATION(TakesLockViolation);
2081
2082             _ASSERTE(!IsResource());
2083         }
2084
2085         return m_pAvailableClasses;
2086     }
2087 #ifndef DACCESS_COMPILE
2088     void SetAvailableClassHash(EEClassHashTable *pAvailableClasses)
2089     {
2090         LIMITED_METHOD_CONTRACT;
2091         {
2092             // IsResource() may lock when accessing metadata, but this is only in debug,
2093             // for the assert below
2094             CONTRACT_VIOLATION(TakesLockViolation);
2095
2096             _ASSERTE(!IsResource());
2097         }
2098         m_pAvailableClasses = pAvailableClasses;
2099     }
2100 #endif // !DACCESS_COMPILE
2101     PTR_EEClassHashTable GetAvailableClassCaseInsHash()
2102     {
2103         LIMITED_METHOD_CONTRACT;
2104         SUPPORTS_DAC;
2105         {
2106             // IsResource() may lock when accessing metadata, but this is only in debug,
2107             // for the assert below
2108             CONTRACT_VIOLATION(TakesLockViolation);
2109
2110             _ASSERTE(!IsResource());
2111         }
2112         return m_pAvailableClassesCaseIns;
2113     }
2114 #ifndef DACCESS_COMPILE
2115     void SetAvailableClassCaseInsHash(EEClassHashTable *pAvailableClassesCaseIns)
2116     {
2117         LIMITED_METHOD_CONTRACT;
2118         {
2119             // IsResource() may lock when accessing metadata, but this is only in debug,
2120             // for the assert below
2121             CONTRACT_VIOLATION(TakesLockViolation);
2122
2123             _ASSERTE(!IsResource());
2124         }
2125         m_pAvailableClassesCaseIns = pAvailableClassesCaseIns;
2126     }
2127 #endif // !DACCESS_COMPILE
2128
2129     // Constructed types tables
2130     EETypeHashTable *GetAvailableParamTypes()
2131     {
2132         LIMITED_METHOD_CONTRACT;
2133         SUPPORTS_DAC;
2134         {
2135             // IsResource() may lock when accessing metadata, but this is only in debug,
2136             // for the assert below
2137             CONTRACT_VIOLATION(TakesLockViolation);
2138
2139             _ASSERTE(!IsResource());
2140         }
2141         return m_pAvailableParamTypes;
2142     }
2143
2144     InstMethodHashTable *GetInstMethodHashTable()
2145     {
2146         LIMITED_METHOD_CONTRACT;
2147         {
2148             // IsResource() may lock when accessing metadata, but this is only in debug,
2149             // for the assert below
2150             CONTRACT_VIOLATION(TakesLockViolation);
2151
2152             _ASSERTE(!IsResource());
2153         }
2154         return m_pInstMethodHashTable;
2155     }
2156
2157 #ifdef FEATURE_PREJIT    
2158     // Gets or creates the token -> IL stub MethodDesc hash.
2159     StubMethodHashTable *GetStubMethodHashTable();
2160 #endif // FEATURE_PREJIT    
2161
2162     // Creates a new Method table for an array.  Used to make type handles
2163     // Note that if kind == SZARRAY or ARRAY, we get passed the GENERIC_ARRAY
2164     // needed to create the array.  That way we dont need to load classes during
2165     // the class load, which avoids the need for a 'being loaded' list
2166     MethodTable* CreateArrayMethodTable(TypeHandle elemType, CorElementType kind, unsigned rank, class AllocMemTracker *pamTracker);
2167
2168     // This is called from CreateArrayMethodTable
2169     MethodTable* CreateGenericArrayMethodTable(TypeHandle elemType);
2170
2171     // string helper
2172     void InitializeStringData(DWORD token, EEStringData *pstrData, CQuickBytes *pqb);
2173
2174     // Resolving
2175     OBJECTHANDLE ResolveStringRef(DWORD Token, BaseDomain *pDomain, bool bNeedToSyncWithFixups);
2176 #ifdef FEATURE_PREJIT
2177     OBJECTHANDLE ResolveStringRefHelper(DWORD token, BaseDomain *pDomain, PTR_CORCOMPILE_IMPORT_SECTION pSection, EEStringData *strData);
2178 #endif
2179     
2180     CHECK CheckStringRef(RVA rva);
2181
2182     // Module/Assembly traversal
2183     Assembly * GetAssemblyIfLoaded(
2184             mdAssemblyRef       kAssemblyRef, 
2185             LPCSTR              szWinRtNamespace = NULL, 
2186             LPCSTR              szWinRtClassName = NULL, 
2187             IMDInternalImport * pMDImportOverride = NULL,
2188             BOOL                fDoNotUtilizeExtraChecks = FALSE,
2189             ICLRPrivBinder      *pBindingContextForLoadedAssembly = NULL
2190             );
2191
2192 private:
2193     // Helper function used by GetAssemblyIfLoaded. Do not call directly.
2194     Assembly *GetAssemblyIfLoadedFromNativeAssemblyRefWithRefDefMismatch(mdAssemblyRef kAssemblyRef, BOOL *pfDiscoveredAssemblyRefMatchesTargetDefExactly);
2195 public:
2196
2197     DomainAssembly * LoadAssembly(
2198             AppDomain *   pDomain, 
2199             mdAssemblyRef kAssemblyRef, 
2200             LPCUTF8       szWinRtTypeNamespace = NULL,
2201             LPCUTF8       szWinRtTypeClassName = NULL);
2202     Module *GetModuleIfLoaded(mdFile kFile, BOOL onlyLoadedInAppDomain, BOOL loadAllowed);
2203     DomainFile *LoadModule(AppDomain *pDomain, mdFile kFile, BOOL loadResources = TRUE, BOOL bindOnly = FALSE);
2204     PTR_Module LookupModule(mdToken kFile, BOOL loadResources = TRUE); //wrapper over GetModuleIfLoaded, takes modulerefs as well
2205     DWORD GetAssemblyRefFlags(mdAssemblyRef tkAssemblyRef);
2206
2207     bool HasBindableIdentity(mdAssemblyRef tkAssemblyRef)
2208     { 
2209         WRAPPER_NO_CONTRACT; 
2210         return !IsAfContentType_WindowsRuntime(GetAssemblyRefFlags(tkAssemblyRef)); 
2211     }
2212
2213     // RID maps
2214     TypeHandle LookupTypeDef(mdTypeDef token, ClassLoadLevel *pLoadLevel = NULL)
2215     {
2216         LIMITED_METHOD_DAC_CONTRACT;
2217
2218         BAD_FORMAT_NOTHROW_ASSERT(TypeFromToken(token) == mdtTypeDef);
2219
2220         g_IBCLogger.LogRidMapAccess( MakePair( this, token ) );
2221
2222         TADDR flags;
2223         TypeHandle th = TypeHandle(m_TypeDefToMethodTableMap.GetElementAndFlags(RidFromToken(token), &flags));
2224
2225         if (pLoadLevel && !th.IsNull())
2226         {
2227             if (!IsCompilationProcess() && (flags & ZAPPED_TYPE_NEEDS_NO_RESTORE))
2228             {
2229                 // Make sure the flag is consistent with the target data and implies the load level we think it does
2230                 _ASSERTE(th.AsMethodTable()->IsPreRestored());
2231                 _ASSERTE(th.GetLoadLevel() == CLASS_LOADED);
2232
2233                 *pLoadLevel = CLASS_LOADED;
2234             }
2235             else
2236             {
2237                 *pLoadLevel = th.GetLoadLevel();
2238             }
2239         }
2240
2241         return th;
2242     }
2243
2244     TypeHandle LookupFullyCanonicalInstantiation(mdTypeDef token, ClassLoadLevel *pLoadLevel = NULL)
2245     {
2246         LIMITED_METHOD_DAC_CONTRACT;
2247
2248         BAD_FORMAT_NOTHROW_ASSERT(TypeFromToken(token) == mdtTypeDef);
2249
2250         g_IBCLogger.LogRidMapAccess( MakePair( this, token ) );
2251
2252         TADDR flags;
2253         TypeHandle th = TypeHandle(m_GenericTypeDefToCanonMethodTableMap.GetElementAndFlags(RidFromToken(token), &flags));
2254
2255         if (pLoadLevel && !th.IsNull())
2256         {
2257             if (!IsCompilationProcess() && (flags & ZAPPED_GENERIC_TYPE_NEEDS_NO_RESTORE))
2258             {
2259                 // Make sure the flag is consistent with the target data and implies the load level we think it does
2260                 _ASSERTE(th.AsMethodTable()->IsPreRestored());
2261                 _ASSERTE(th.GetLoadLevel() == CLASS_LOADED);
2262
2263                 *pLoadLevel = CLASS_LOADED;
2264             }
2265             else
2266             {
2267                 *pLoadLevel = th.GetLoadLevel();
2268             }
2269         }
2270
2271         return th;
2272     }
2273
2274 #ifndef DACCESS_COMPILE
2275     VOID EnsureTypeDefCanBeStored(mdTypeDef token)
2276     {
2277         WRAPPER_NO_CONTRACT; // THROWS/GC_NOTRIGGER/INJECT_FAULT()/MODE_ANY
2278         m_TypeDefToMethodTableMap.EnsureElementCanBeStored(this, RidFromToken(token));
2279     }
2280
2281     void EnsuredStoreTypeDef(mdTypeDef token, TypeHandle value)
2282     {
2283         WRAPPER_NO_CONTRACT; // NOTHROW/GC_NOTRIGGER/FORBID_FAULT/MODE_ANY
2284
2285         _ASSERTE(TypeFromToken(token) == mdtTypeDef);
2286         m_TypeDefToMethodTableMap.SetElement(RidFromToken(token), value.AsMethodTable());
2287     }
2288
2289 #endif // !DACCESS_COMPILE
2290
2291     TypeHandle LookupTypeRef(mdTypeRef token);
2292
2293     mdTypeRef LookupTypeRefByMethodTable(MethodTable *pMT);
2294
2295     mdMemberRef LookupMemberRefByMethodDesc(MethodDesc *pMD);
2296
2297 #ifndef DACCESS_COMPILE
2298     //
2299     // Increase the size of the TypeRef-to-MethodTable LookupMap to make sure the specified token
2300     // can be stored.  Note that nothing is actually added to the LookupMap at this point.
2301     //
2302     // Arguments:
2303     //    token - the TypeRef metadata token we need to accommodate
2304     //
2305
2306     void EnsureTypeRefCanBeStored(mdTypeRef token)
2307     {
2308         WRAPPER_NO_CONTRACT; // THROWS/GC_NOTRIGGER/INJECT_FAULT()/MODE_ANY
2309
2310         _ASSERTE(TypeFromToken(token) == mdtTypeRef);
2311         m_TypeRefToMethodTableMap.EnsureElementCanBeStored(this, RidFromToken(token));
2312     }
2313
2314     void StoreTypeRef(mdTypeRef token, TypeHandle value)
2315     {
2316         WRAPPER_NO_CONTRACT;
2317
2318         _ASSERTE(TypeFromToken(token) == mdtTypeRef);
2319
2320         g_IBCLogger.LogRidMapAccess( MakePair( this, token ) );
2321
2322         // The TypeRef cache is strictly a lookaside cache. If we get an OOM trying to grow the table,
2323         // we cannot abort the load. (This will cause fatal errors during gc promotion.)
2324         m_TypeRefToMethodTableMap.TrySetElement(RidFromToken(token), 
2325             dac_cast<PTR_TypeRef>(value.AsTAddr()));
2326     }
2327 #endif // !DACCESS_COMPILE
2328
2329     MethodDesc *LookupMethodDef(mdMethodDef token);
2330
2331 #ifndef DACCESS_COMPILE
2332     void EnsureMethodDefCanBeStored(mdMethodDef token)
2333     {
2334         WRAPPER_NO_CONTRACT; // THROWS/GC_NOTRIGGER/INJECT_FAULT()/MODE_ANY
2335         m_MethodDefToDescMap.EnsureElementCanBeStored(this, RidFromToken(token));
2336     }
2337
2338     void EnsuredStoreMethodDef(mdMethodDef token, MethodDesc *value)
2339     {
2340         WRAPPER_NO_CONTRACT; // NOTHROW/GC_NOTRIGGER/FORBID_FAULT/MODE_ANY
2341
2342         _ASSERTE(TypeFromToken(token) == mdtMethodDef);
2343         m_MethodDefToDescMap.SetElement(RidFromToken(token), value);
2344     }
2345 #endif // !DACCESS_COMPILE
2346
2347 #ifndef DACCESS_COMPILE
2348     FieldDesc *LookupFieldDef(mdFieldDef token)
2349     {
2350         WRAPPER_NO_CONTRACT;
2351
2352         _ASSERTE(TypeFromToken(token) == mdtFieldDef);
2353         return m_FieldDefToDescMap.GetElement(RidFromToken(token));
2354     }
2355 #else // DACCESS_COMPILE
2356     // FieldDesc isn't defined at this point so PTR_FieldDesc can't work.
2357     FieldDesc *LookupFieldDef(mdFieldDef token);
2358 #endif // DACCESS_COMPILE
2359
2360 #ifndef DACCESS_COMPILE
2361     void EnsureFieldDefCanBeStored(mdFieldDef token)
2362     {
2363         WRAPPER_NO_CONTRACT; // THROWS/GC_NOTRIGGER/INJECT_FAULT()/MODE_ANY
2364         m_FieldDefToDescMap.EnsureElementCanBeStored(this, RidFromToken(token));
2365     }
2366
2367     void EnsuredStoreFieldDef(mdFieldDef token, FieldDesc *value)
2368     {
2369         WRAPPER_NO_CONTRACT; // NOTHROW/GC_NOTRIGGER/FORBID_FAULT/MODE_ANY
2370
2371         _ASSERTE(TypeFromToken(token) == mdtFieldDef);
2372         m_FieldDefToDescMap.SetElement(RidFromToken(token), value);
2373     }
2374 #endif // !DACCESS_COMPILE
2375
2376     FORCEINLINE TADDR LookupMemberRef(mdMemberRef token, BOOL *pfIsMethod)
2377     {
2378         WRAPPER_NO_CONTRACT;
2379
2380         _ASSERTE(TypeFromToken(token) == mdtMemberRef);
2381
2382         TADDR pResult = dac_cast<TADDR>(m_pMemberRefToDescHashTable->GetValue(token, pfIsMethod));
2383         g_IBCLogger.LogRidMapAccess( MakePair( this, token ) );
2384         return pResult;
2385     }
2386     MethodDesc *LookupMemberRefAsMethod(mdMemberRef token);
2387 #ifndef DACCESS_COMPILE
2388     void StoreMemberRef(mdMemberRef token, FieldDesc *value)
2389     {
2390         WRAPPER_NO_CONTRACT;
2391
2392         _ASSERTE(TypeFromToken(token) == mdtMemberRef);
2393         CrstHolder ch(this->GetLookupTableCrst());
2394         m_pMemberRefToDescHashTable->Insert(token, value);
2395     }
2396     void StoreMemberRef(mdMemberRef token, MethodDesc *value)
2397     {
2398         WRAPPER_NO_CONTRACT;
2399
2400         _ASSERTE(TypeFromToken(token) == mdtMemberRef);
2401         CrstHolder ch(this->GetLookupTableCrst());
2402         m_pMemberRefToDescHashTable->Insert(token, value);
2403     }
2404 #endif // !DACCESS_COMPILE
2405
2406     PTR_TypeVarTypeDesc LookupGenericParam(mdGenericParam token)
2407     {
2408         WRAPPER_NO_CONTRACT;
2409
2410         _ASSERTE(TypeFromToken(token) == mdtGenericParam);
2411         return m_GenericParamToDescMap.GetElement(RidFromToken(token));
2412     }
2413 #ifndef DACCESS_COMPILE
2414     void StoreGenericParamThrowing(mdGenericParam token, TypeVarTypeDesc *value)
2415     {
2416         WRAPPER_NO_CONTRACT;
2417
2418         _ASSERTE(TypeFromToken(token) == mdtGenericParam);
2419         m_GenericParamToDescMap.AddElement(this, RidFromToken(token), value);
2420     }
2421 #endif // !DACCESS_COMPILE
2422
2423     PTR_Module LookupFile(mdFile token)
2424     {
2425         WRAPPER_NO_CONTRACT;
2426         SUPPORTS_DAC;
2427
2428         _ASSERTE(TypeFromToken(token) == mdtFile);
2429         return m_FileReferencesMap.GetElement(RidFromToken(token));
2430     }
2431
2432
2433 #ifndef DACCESS_COMPILE
2434     void EnsureFileCanBeStored(mdFile token)
2435     {
2436         WRAPPER_NO_CONTRACT; // THROWS/GC_NOTRIGGER/INJECT_FAULT()/MODE_ANY
2437
2438         _ASSERTE(TypeFromToken(token) == mdtFile);
2439         m_FileReferencesMap.EnsureElementCanBeStored(this, RidFromToken(token));
2440     }
2441
2442     void EnsuredStoreFile(mdFile token, Module *value)
2443     {
2444         WRAPPER_NO_CONTRACT; // NOTHROW/GC_NOTRIGGER/FORBID_FAULT
2445
2446
2447         _ASSERTE(TypeFromToken(token) == mdtFile);
2448         m_FileReferencesMap.SetElement(RidFromToken(token), value);
2449     }
2450
2451
2452     void StoreFileThrowing(mdFile token, Module *value)
2453     {
2454         WRAPPER_NO_CONTRACT;
2455
2456
2457         _ASSERTE(TypeFromToken(token) == mdtFile);
2458         m_FileReferencesMap.AddElement(this, RidFromToken(token), value);
2459     }
2460
2461     BOOL StoreFileNoThrow(mdFile token, Module *value)
2462     {
2463         WRAPPER_NO_CONTRACT;
2464
2465         _ASSERTE(TypeFromToken(token) == mdtFile);
2466         return m_FileReferencesMap.TrySetElement(RidFromToken(token), value);
2467     }
2468
2469     mdAssemblyRef FindManifestModule(Module *value)
2470     {
2471         WRAPPER_NO_CONTRACT;
2472
2473         return m_ManifestModuleReferencesMap.Find(value) | mdtAssembly;
2474     }
2475 #endif // !DACCESS_COMPILE
2476
2477     DWORD GetFileMax() { LIMITED_METHOD_DAC_CONTRACT;  return m_FileReferencesMap.GetSize(); }
2478
2479     Assembly *LookupAssemblyRef(mdAssemblyRef token);
2480
2481 #ifndef DACCESS_COMPILE
2482     //
2483     // Increase the size of the AssemblyRef-to-Module LookupMap to make sure the specified token
2484     // can be stored.  Note that nothing is actually added to the LookupMap at this point.
2485     //
2486     // Arguments:
2487     //    token - the AssemblyRef metadata token we need to accommodate
2488     //
2489
2490     void EnsureAssemblyRefCanBeStored(mdAssemblyRef token)
2491     {
2492         WRAPPER_NO_CONTRACT; // THROWS/GC_NOTRIGGER/INJECT_FAULT()/MODE_ANY
2493
2494         _ASSERTE(TypeFromToken(token) == mdtAssemblyRef);
2495         m_ManifestModuleReferencesMap.EnsureElementCanBeStored(this, RidFromToken(token));
2496     }
2497
2498     void ForceStoreAssemblyRef(mdAssemblyRef token, Assembly *value);
2499     void StoreAssemblyRef(mdAssemblyRef token, Assembly *value);
2500
2501     mdAssemblyRef FindAssemblyRef(Assembly *targetAssembly);
2502
2503     void          CreateAssemblyRefByNameTable(AllocMemTracker *pamTracker);
2504     bool          HasReferenceByName(LPCUTF8 pModuleName);
2505
2506 #endif // !DACCESS_COMPILE
2507
2508 #ifdef FEATURE_PREJIT
2509     void FinalizeLookupMapsPreSave(DataImage *image);
2510 #endif
2511
2512     DWORD GetAssemblyRefMax() {LIMITED_METHOD_CONTRACT;  return m_ManifestModuleReferencesMap.GetSize(); }
2513
2514     MethodDesc *FindMethodThrowing(mdToken pMethod);
2515     MethodDesc *FindMethod(mdToken pMethod);
2516
2517     void PopulatePropertyInfoMap();
2518     HRESULT GetPropertyInfoForMethodDef(mdMethodDef md, mdProperty *ppd, LPCSTR *pName, ULONG *pSemantic);
2519
2520     #define NUM_PROPERTY_SET_HASHES 4
2521 #ifdef FEATURE_PREJIT
2522     void PrecomputeMatchingProperties(DataImage *image);
2523 #endif
2524     BOOL MightContainMatchingProperty(mdProperty tkProperty, ULONG nameHash);
2525
2526 private:
2527     ArrayDPTR(BYTE)    m_propertyNameSet;
2528     DWORD              m_nPropertyNameSet;
2529
2530 public:
2531
2532     // Debugger stuff
2533     BOOL NotifyDebuggerLoad(AppDomain *pDomain, DomainFile * pDomainFile, int level, BOOL attaching);
2534     void NotifyDebuggerUnload(AppDomain *pDomain);
2535
2536     void SetDebuggerInfoBits(DebuggerAssemblyControlFlags newBits);
2537
2538     DebuggerAssemblyControlFlags GetDebuggerInfoBits(void)
2539     {
2540         LIMITED_METHOD_CONTRACT;
2541         SUPPORTS_DAC;
2542
2543         return (DebuggerAssemblyControlFlags)((m_dwTransientFlags &
2544                                                DEBUGGER_INFO_MASK_PRIV) >>
2545                                               DEBUGGER_INFO_SHIFT_PRIV);
2546     }
2547
2548 #ifdef PROFILING_SUPPORTED
2549     BOOL IsProfilerNotified() {LIMITED_METHOD_CONTRACT;  return (m_dwTransientFlags & IS_PROFILER_NOTIFIED) != 0; }
2550     void NotifyProfilerLoadFinished(HRESULT hr);
2551 #endif // PROFILING_SUPPORTED
2552
2553     BOOL HasInlineTrackingMap();
2554     COUNT_T GetInliners(PTR_Module inlineeOwnerMod, mdMethodDef inlineeTkn, COUNT_T inlinersSize, MethodInModule inliners[], BOOL *incompleteData);
2555
2556 public:
2557     void NotifyEtwLoadFinished(HRESULT hr);
2558
2559     // Get any cached ITypeLib* for the module.
2560     ITypeLib *GetTypeLib();
2561     // Cache the ITypeLib*, if one is not already cached.
2562     void SetTypeLib(ITypeLib *pITLB);
2563     ITypeLib *GetTypeLibTCE();
2564     void SetTypeLibTCE(ITypeLib *pITLB);
2565
2566     // Enregisters a VASig.
2567     VASigCookie *GetVASigCookie(Signature vaSignature);
2568
2569     // DLL entry point
2570     MethodDesc *GetDllEntryPoint()
2571     {
2572         LIMITED_METHOD_CONTRACT;
2573         return m_pDllMain;
2574     }
2575     void SetDllEntryPoint(MethodDesc *pMD)
2576     {
2577         LIMITED_METHOD_CONTRACT;
2578         m_pDllMain = pMD;
2579     }
2580
2581     BOOL CanExecuteCode();
2582
2583
2584     // This data is only valid for NGEN'd modules, and for modules we're creating at NGEN time.
2585     ModuleCtorInfo* GetZapModuleCtorInfo()
2586     {
2587         LIMITED_METHOD_DAC_CONTRACT;
2588         
2589         return &m_ModuleCtorInfo;
2590     }
2591
2592  private:
2593
2594
2595  public:
2596 #ifndef DACCESS_COMPILE
2597     BOOL Equals(Module *pModule) { WRAPPER_NO_CONTRACT; return m_file->Equals(pModule->m_file); }
2598     BOOL Equals(PEFile *pFile) { WRAPPER_NO_CONTRACT; return m_file->Equals(pFile); }
2599 #endif // !DACCESS_COMPILE
2600
2601     LPCUTF8 GetSimpleName()
2602     { 
2603         WRAPPER_NO_CONTRACT;
2604         _ASSERTE(m_pSimpleName != NULL);
2605         return m_pSimpleName;
2606     }
2607
2608     HRESULT GetScopeName(LPCUTF8 * pszName) { WRAPPER_NO_CONTRACT; return m_file->GetScopeName(pszName); }
2609     const SString &GetPath() { WRAPPER_NO_CONTRACT; return m_file->GetPath(); }
2610
2611 #ifdef LOGGING
2612     LPCWSTR GetDebugName() { WRAPPER_NO_CONTRACT; return m_file->GetDebugName(); }
2613 #endif
2614
2615     BOOL IsILOnly() { WRAPPER_NO_CONTRACT; return m_file->IsILOnly(); }
2616
2617 #ifdef FEATURE_PREJIT
2618     BOOL HasNativeImage() 
2619     { 
2620         WRAPPER_NO_CONTRACT;
2621         SUPPORTS_DAC;
2622         return m_file->HasNativeImage(); 
2623     }
2624     
2625     PEImageLayout *GetNativeImage()
2626     {
2627         CONTRACT(PEImageLayout *)
2628         {
2629             PRECONDITION(m_file->HasNativeImage());
2630             POSTCONDITION(CheckPointer(RETVAL));
2631             NOTHROW;
2632             GC_NOTRIGGER;
2633             SUPPORTS_DAC;
2634             CANNOT_TAKE_LOCK;
2635             SO_TOLERANT;
2636         }
2637         CONTRACT_END;
2638
2639         RETURN m_file->GetLoadedNative();
2640     }
2641 #else
2642     BOOL HasNativeImage()
2643     {
2644         LIMITED_METHOD_CONTRACT;
2645         return FALSE;
2646     }
2647
2648     PEImageLayout * GetNativeImage()
2649     {
2650         // Should never get here
2651         PRECONDITION(HasNativeImage());
2652         return NULL;
2653     }
2654 #endif // FEATURE_PREJIT
2655
2656
2657     BOOL            HasNativeOrReadyToRunImage();
2658     PEImageLayout * GetNativeOrReadyToRunImage();
2659     PTR_CORCOMPILE_IMPORT_SECTION GetImportSections(COUNT_T *pCount);
2660     PTR_CORCOMPILE_IMPORT_SECTION GetImportSectionFromIndex(COUNT_T index);
2661     PTR_CORCOMPILE_IMPORT_SECTION GetImportSectionForRVA(RVA rva);
2662
2663     // These are overridden by reflection modules
2664     virtual TADDR GetIL(RVA il);
2665
2666     virtual PTR_VOID GetRvaField(RVA field, BOOL fZapped);
2667     CHECK CheckRvaField(RVA field);
2668     CHECK CheckRvaField(RVA field, COUNT_T size);
2669
2670     const void *GetInternalPInvokeTarget(RVA target)
2671     { WRAPPER_NO_CONTRACT; return m_file->GetInternalPInvokeTarget(target); }
2672
2673     BOOL HasTls();
2674     BOOL IsRvaFieldTls(DWORD field);
2675     UINT32 GetFieldTlsOffset(DWORD field);
2676     UINT32 GetTlsIndex();
2677
2678     BOOL IsSigInIL(PCCOR_SIGNATURE signature);
2679
2680     mdToken GetEntryPointToken();
2681
2682     BYTE *GetProfilerBase();
2683
2684
2685     // Active transition path management
2686     // 
2687     // This list keeps track of module which we have active transition
2688     // paths to.  An active transition path is where we move from
2689     // active execution in one module to another module without
2690     // involving triggering the file loader to ensure that the
2691     // destination module is active.  We must explicitly list these
2692     // relationships so the the loader can ensure that the activation
2693     // constraints are a priori satisfied.
2694     //
2695     // Conditional vs. Unconditional describes how we deal with
2696     // activation failure of a dependency.  In the unconditional case,
2697     // we propagate the activation failure to the depending module.
2698     // In the conditional case, we activate a "trigger" in the active
2699     // transition path which will cause the path to fail in particular
2700     // app domains where the destination module failed to activate.
2701     // (This trigger in the path typically has a perf cost even in the
2702     // nonfailing case.)
2703     //
2704     // In either case we must try to perform the activation eagerly -
2705     // even in the conditional case we have to know whether to turn on
2706     // the trigger or not before we let the active transition path
2707     // execute.
2708
2709     void AddActiveDependency(Module *pModule, BOOL unconditional);
2710
2711     // Active dependency iterator
2712     class DependencyIterator
2713     {
2714       protected:
2715         ArrayList::Iterator m_i;
2716         COUNT_T             m_index;
2717         SynchronizedBitMask* m_unconditionalFlags;
2718
2719         friend class Module;
2720
2721         DependencyIterator(ArrayList *list, SynchronizedBitMask *unconditionalFlags)
2722           : m_index((COUNT_T)-1),
2723             m_unconditionalFlags(unconditionalFlags)
2724         {
2725             WRAPPER_NO_CONTRACT;
2726             m_i = list->Iterate();
2727         }
2728
2729       public:
2730         Module *GetDependency()
2731         {
2732             return ((FixupPointer<PTR_Module> *)m_i.GetElementPtr())->GetValue();
2733         }
2734
2735         BOOL Next()
2736         {
2737             LIMITED_METHOD_CONTRACT;
2738             while (m_i.Next())
2739             {
2740                 ++m_index;
2741
2742 #ifdef FEATURE_PREJIT
2743                 // When iterating all dependencies, we do not restore any tokens
2744                 // as we want to be lazy.
2745                 PTR_Module pModule = ((FixupPointer<PTR_Module> *)m_i.GetElementPtr())->GetValue();
2746                 if (!CORCOMPILE_IS_POINTER_TAGGED(dac_cast<TADDR>(pModule)))
2747                     return TRUE;
2748
2749 #else
2750                 return TRUE;
2751 #endif
2752
2753             }
2754             return FALSE;
2755         }
2756         BOOL IsUnconditional()
2757         {
2758             if (m_unconditionalFlags == NULL)
2759                 return TRUE;
2760             else
2761                 return m_unconditionalFlags->TestBit(m_index);
2762         }
2763     };
2764
2765     DependencyIterator IterateActiveDependencies()
2766     {
2767         WRAPPER_NO_CONTRACT;
2768         return DependencyIterator(&m_activeDependencies, &m_unconditionalDependencies);
2769     }
2770
2771     BOOL HasActiveDependency(Module *pModule);
2772     BOOL HasUnconditionalActiveDependency(Module *pModule);
2773
2774     // Turn triggers from this module into runtime checks
2775     void EnableModuleFailureTriggers(Module *pModule, AppDomain *pDomain);
2776
2777 #ifdef FEATURE_PREJIT
2778     BOOL IsZappedCode(PCODE code);
2779     BOOL IsZappedPrecode(PCODE code);
2780
2781     CORCOMPILE_DEBUG_ENTRY GetMethodDebugInfoOffset(MethodDesc *pMD);
2782     PTR_BYTE GetNativeDebugInfo(MethodDesc * pMD);
2783
2784     // The methods below must be called when loading back an ngen'ed image for any fields that
2785     // might be an encoded token (rather than a hard pointer) and/or need a restore operation
2786     //
2787     static void RestoreMethodTablePointerRaw(PTR_MethodTable * ppMT,
2788                                              Module *pContainingModule = NULL,
2789                                              ClassLoadLevel level = CLASS_LOADED);
2790     static void RestoreTypeHandlePointerRaw(TypeHandle *pHandle,
2791                                             Module *pContainingModule = NULL,
2792                                             ClassLoadLevel level = CLASS_LOADED);
2793     static void RestoreMethodDescPointerRaw(PTR_MethodDesc * ppMD,
2794                                             Module *pContainingModule = NULL,
2795                                             ClassLoadLevel level = CLASS_LOADED);
2796
2797     static void RestoreMethodTablePointer(FixupPointer<PTR_MethodTable> * ppMT,
2798                                           Module *pContainingModule = NULL,
2799                                           ClassLoadLevel level = CLASS_LOADED);
2800     static void RestoreTypeHandlePointer(FixupPointer<TypeHandle> *pHandle,
2801                                          Module *pContainingModule = NULL,
2802                                          ClassLoadLevel level = CLASS_LOADED);
2803     static void RestoreMethodDescPointer(FixupPointer<PTR_MethodDesc> * ppMD,
2804                                           Module *pContainingModule = NULL,
2805                                           ClassLoadLevel level = CLASS_LOADED);
2806
2807     static void RestoreMethodTablePointer(RelativeFixupPointer<PTR_MethodTable> * ppMT,
2808                                           Module *pContainingModule = NULL,
2809                                          ClassLoadLevel level = CLASS_LOADED);
2810     static void RestoreTypeHandlePointer(RelativeFixupPointer<TypeHandle> *pHandle,
2811                                          Module *pContainingModule = NULL,
2812                                       ClassLoadLevel level = CLASS_LOADED);
2813     static void RestoreMethodDescPointer(RelativeFixupPointer<PTR_MethodDesc> * ppMD,
2814                                          Module *pContainingModule = NULL,
2815                                          ClassLoadLevel level = CLASS_LOADED);
2816     static void RestoreFieldDescPointer(RelativeFixupPointer<PTR_FieldDesc> * ppFD);
2817
2818     static void RestoreModulePointer(RelativeFixupPointer<PTR_Module> * ppModule, Module *pContainingModule);
2819
2820     static PTR_Module RestoreModulePointerIfLoaded(DPTR(RelativeFixupPointer<PTR_Module>) ppModule, Module *pContainingModule);
2821
2822     PCCOR_SIGNATURE GetEncodedSig(RVA fixupRva, Module **ppDefiningModule);
2823     PCCOR_SIGNATURE GetEncodedSigIfLoaded(RVA fixupRva, Module **ppDefiningModule);
2824
2825     BYTE *GetNativeFixupBlobData(RVA fixup);
2826
2827     IMDInternalImport *GetNativeAssemblyImport(BOOL loadAllowed = TRUE);
2828
2829     BOOL FixupNativeEntry(CORCOMPILE_IMPORT_SECTION * pSection, SIZE_T fixupIndex, SIZE_T *fixup);
2830
2831     //this split exists to support new CLR Dump functionality in DAC.  The
2832     //template removes any indirections.
2833     BOOL FixupDelayList(TADDR pFixupList);
2834
2835     template<typename Ptr, typename FixupNativeEntryCallback>
2836     BOOL FixupDelayListAux(TADDR pFixupList,
2837                            Ptr pThis, FixupNativeEntryCallback pfnCB,
2838                            PTR_CORCOMPILE_IMPORT_SECTION pImportSections, COUNT_T nImportSections,
2839                            PEDecoder * pNativeImage);
2840     void RunEagerFixups();
2841
2842     IMDInternalImport *GetNativeFixupImport();
2843     Module *GetModuleFromIndex(DWORD ix);
2844     Module *GetModuleFromIndexIfLoaded(DWORD ix);
2845
2846     // This is to rebuild stub dispatch maps to module-local values.
2847     void UpdateStubDispatchTypeTable(DataImage *image);
2848
2849     void SetProfileData(CorProfileData * profileData);
2850     CorProfileData *GetProfileData();
2851
2852     mdTypeDef     LookupIbcTypeToken(  Module *   pExternalModule, mdToken ibcToken, SString* optionalFullNameOut = NULL);
2853     mdMethodDef   LookupIbcMethodToken(TypeHandle enclosingType,   mdToken ibcToken, SString* optionalFullNameOut = NULL);
2854
2855     TypeHandle    LoadIBCTypeHelper(DataImage *image, CORBBTPROF_BLOB_PARAM_SIG_ENTRY *pBlobSigEntry);
2856     MethodDesc *  LoadIBCMethodHelper(DataImage *image, CORBBTPROF_BLOB_PARAM_SIG_ENTRY *pBlobSigEntry);
2857  
2858
2859     void ExpandAll(DataImage *image);
2860     // profileData may be different than the profileData passed in to
2861     // ExpandAll() depending on more information that may now be available
2862     // (after all the methods have been compiled)
2863
2864     void Save(DataImage *image);
2865     void Arrange(DataImage *image);
2866     void PlaceType(DataImage *image, TypeHandle th, DWORD profilingFlags);
2867     void PlaceMethod(DataImage *image, MethodDesc *pMD, DWORD profilingFlags);
2868     void Fixup(DataImage *image);
2869
2870     bool AreAllClassesFullyLoaded();
2871
2872     // Precompute type-specific auxiliary information saved into NGen image
2873     void PrepareTypesForSave(DataImage *image);
2874
2875     static void SaveMethodTable(DataImage *image,
2876                                 MethodTable *pMT,
2877                                 DWORD profilingFlags);
2878
2879     static void SaveTypeHandle(DataImage *image,
2880                                TypeHandle t,
2881                                DWORD profilingFlags);
2882
2883 private:
2884     static BOOL CanEagerBindTo(Module *targetModule, Module *pPreferredZapModule, void *address);
2885 public:
2886
2887     static PTR_Module ComputePreferredZapModule(Module * pDefinitionModule,        // the module that declares the generic type or method
2888                                                 Instantiation classInst,           // the type arguments to the type (if any)
2889                                                 Instantiation methodInst = Instantiation()); // the type arguments to the method (if any)
2890
2891     static PTR_Module ComputePreferredZapModuleHelper(Module * pDefinitionModule,
2892                                                       Instantiation classInst,
2893                                                       Instantiation methodInst);
2894
2895     static PTR_Module ComputePreferredZapModule(TypeKey * pKey);
2896
2897     // Return true if types or methods of this instantiation are *always* precompiled and saved
2898     // in the preferred zap module
2899     // At present, only true for <__Canon,...,__Canon> instantiation
2900     static BOOL IsAlwaysSavedInPreferredZapModule(Instantiation classInst,
2901                                                   Instantiation methodInst = Instantiation());
2902
2903     static PTR_Module GetPreferredZapModuleForTypeHandle(TypeHandle t);
2904     static PTR_Module GetPreferredZapModuleForMethodTable(MethodTable * pMT);
2905     static PTR_Module GetPreferredZapModuleForMethodDesc(const MethodDesc * pMD);
2906     static PTR_Module GetPreferredZapModuleForFieldDesc(FieldDesc * pFD);
2907     static PTR_Module GetPreferredZapModuleForTypeDesc(PTR_TypeDesc pTD);
2908
2909     void PrepopulateDictionaries(DataImage *image, BOOL nonExpansive);
2910
2911
2912     void LoadTokenTables();
2913     void LoadHelperTable();
2914
2915     PTR_NGenLayoutInfo GetNGenLayoutInfo()
2916     {
2917         LIMITED_METHOD_DAC_CONTRACT;
2918         return m_pNGenLayoutInfo;
2919     }
2920
2921     PCODE GetPrestubJumpStub()
2922     { 
2923         LIMITED_METHOD_DAC_CONTRACT; 
2924
2925         if (!m_pNGenLayoutInfo)
2926             return NULL;
2927
2928         return m_pNGenLayoutInfo->m_pPrestubJumpStub;
2929     }
2930
2931 #ifdef HAS_FIXUP_PRECODE
2932     PCODE GetPrecodeFixupJumpStub()
2933     { 
2934         LIMITED_METHOD_DAC_CONTRACT; 
2935
2936         if (!m_pNGenLayoutInfo)
2937             return NULL;
2938
2939         return m_pNGenLayoutInfo->m_pPrecodeFixupJumpStub;
2940     }
2941 #endif
2942
2943     BOOL IsVirtualImportThunk(PCODE code)
2944     {
2945         LIMITED_METHOD_DAC_CONTRACT;
2946
2947         if (!m_pNGenLayoutInfo)
2948             return FALSE;
2949
2950         return m_pNGenLayoutInfo->m_VirtualMethodThunks.IsInRange(code);
2951     }
2952
2953     ICorJitInfo::ProfileBuffer * AllocateProfileBuffer(mdToken _token, DWORD _size, DWORD _ILSize);
2954     HANDLE OpenMethodProfileDataLogFile(GUID mvid);
2955     static void ProfileDataAllocateTokenLists(ProfileEmitter * pEmitter, TokenProfileData* pTokenProfileData);
2956     HRESULT WriteMethodProfileDataLogFile(bool cleanup);
2957     static void WriteAllModuleProfileData(bool cleanup);
2958     void SetMethodProfileList(CORCOMPILE_METHOD_PROFILE_LIST * value)
2959     {
2960         m_methodProfileList = value;
2961     }
2962
2963     void CreateProfilingData();
2964     void DeleteProfilingData();
2965
2966     PTR_ProfilingBlobTable GetProfilingBlobTable();
2967
2968     void LogTokenAccess(mdToken token, SectionFormat format, ULONG flagNum);
2969     void LogTokenAccess(mdToken token, ULONG flagNum);
2970
2971     BOOL AreTypeSpecsTriaged()
2972     {
2973         return m_dwTransientFlags & TYPESPECS_TRIAGED;
2974     }
2975
2976     void SetTypeSpecsTriaged()
2977     {
2978         FastInterlockOr(&m_dwTransientFlags, TYPESPECS_TRIAGED);
2979     }
2980
2981     BOOL IsModuleSaved()
2982     {
2983         return m_dwTransientFlags & MODULE_SAVED;
2984     }
2985
2986     void SetIsModuleSaved()
2987     {
2988         FastInterlockOr(&m_dwTransientFlags, MODULE_SAVED);
2989     }
2990
2991 #endif  // FEATURE_PREJIT
2992
2993     BOOL IsReadyToRun()
2994     {
2995         LIMITED_METHOD_DAC_CONTRACT;
2996
2997 #ifdef FEATURE_READYTORUN
2998         return m_pReadyToRunInfo != NULL;
2999 #else
3000         return FALSE;
3001 #endif
3002     }
3003
3004 #ifdef FEATURE_READYTORUN
3005     PTR_ReadyToRunInfo GetReadyToRunInfo()
3006     {
3007         LIMITED_METHOD_DAC_CONTRACT;
3008         return m_pReadyToRunInfo;
3009     }
3010 #endif
3011
3012 #ifdef _DEBUG
3013     //Similar to the ExpandAll we use for NGen, this forces jitting of all methods in a module.  This is
3014     //used for debug purposes though.
3015     void ExpandAll();
3016 #endif
3017
3018     BOOL IsIJWFixedUp() { return m_dwTransientFlags & IS_IJW_FIXED_UP; }
3019     void SetIsIJWFixedUp();
3020
3021     BOOL IsBeingUnloaded() { return m_dwTransientFlags & IS_BEING_UNLOADED; }
3022     void   SetBeingUnloaded();
3023     void   StartUnload();
3024     
3025
3026 public:
3027     idTypeSpec   LogInstantiatedType(TypeHandle typeHnd, ULONG flagNum);
3028     idMethodSpec LogInstantiatedMethod(const MethodDesc * md, ULONG flagNum);
3029
3030     static DWORD EncodeModuleHelper(void* pModuleContext, Module *pReferencedModule);
3031     static void  TokenDefinitionHelper(void* pModuleContext, Module *pReferencedModule, DWORD index, mdToken* token);
3032
3033 public:
3034     MethodTable* MapZapType(UINT32 typeID);
3035
3036     void SetDynamicIL(mdToken token, TADDR blobAddress, BOOL fTemporaryOverride);
3037     TADDR GetDynamicIL(mdToken token, BOOL fAllowTemporary);
3038
3039     // store and retrieve the instrumented IL offset mapping for a particular method
3040 #if !defined(DACCESS_COMPILE)
3041     void SetInstrumentedILOffsetMapping(mdMethodDef token, InstrumentedILOffsetMapping mapping);
3042 #endif // !DACCESS_COMPILE
3043     InstrumentedILOffsetMapping GetInstrumentedILOffsetMapping(mdMethodDef token);
3044
3045 public:
3046     // This helper returns to offsets for the slots/bytes/handles. They return the offset in bytes from the beggining
3047     // of the 1st GC pointer in the statics block for the module.
3048     void        GetOffsetsForRegularStaticData(
3049                     mdTypeDef cl,
3050                     BOOL bDynamic,
3051                     DWORD dwGCStaticHandles,
3052                     DWORD dwNonGCStaticBytes,
3053                     DWORD * pOutStaticHandleOffset,
3054                     DWORD * pOutNonGCStaticOffset);
3055
3056     void        GetOffsetsForThreadStaticData(
3057                     mdTypeDef cl,
3058                     BOOL bDynamic,
3059                     DWORD dwGCStaticHandles,
3060                     DWORD dwNonGCStaticBytes,
3061                     DWORD * pOutStaticHandleOffset,
3062                     DWORD * pOutNonGCStaticOffset);
3063
3064
3065     BOOL        IsStaticStoragePrepared(mdTypeDef tkType);
3066
3067     DWORD       GetNumGCThreadStaticHandles()
3068     {
3069         return m_dwMaxGCThreadStaticHandles;;
3070     }
3071
3072     CrstBase*           GetFixupCrst()
3073     {
3074         return &m_FixupCrst;
3075     }
3076
3077     void                AllocateRegularStaticHandles(AppDomain* pDomainMT);
3078
3079     void                FreeModuleIndex();
3080
3081     DWORD               GetDomainLocalModuleSize()
3082     {
3083         return m_dwRegularStaticsBlockSize;
3084     }
3085
3086     DWORD               GetThreadLocalModuleSize()
3087     {
3088         return m_dwThreadStaticsBlockSize;
3089     }
3090
3091     DWORD               AllocateDynamicEntry(MethodTable *pMT);
3092
3093     // We need this for the jitted shared case,
3094     inline MethodTable* GetDynamicClassMT(DWORD dynamicClassID);
3095
3096     static BOOL IsEncodedModuleIndex(SIZE_T ModuleID)
3097     {
3098         LIMITED_METHOD_DAC_CONTRACT;
3099         
3100         // We should never see encoded module index in CoreCLR
3101         _ASSERTE((ModuleID&1)==0);
3102         return FALSE;
3103     }
3104
3105     static SIZE_T IndexToID(ModuleIndex index)
3106     {
3107         LIMITED_METHOD_CONTRACT
3108             
3109         return (index.m_dwIndex << 1) | 1;
3110     }
3111
3112     static ModuleIndex IDToIndex(SIZE_T ModuleID)
3113     {
3114         LIMITED_METHOD_CONTRACT
3115         SUPPORTS_DAC;
3116             
3117         _ASSERTE(IsEncodedModuleIndex(ModuleID));
3118         ModuleIndex index(ModuleID >> 1);
3119
3120         return index;
3121     }
3122
3123     static ModuleIndex AllocateModuleIndex();
3124     static void FreeModuleIndex(ModuleIndex index);
3125
3126     ModuleIndex          GetModuleIndex()
3127     {
3128         LIMITED_METHOD_DAC_CONTRACT;
3129         return m_ModuleIndex;
3130     }
3131
3132     SIZE_T               GetModuleID()
3133     {
3134         LIMITED_METHOD_DAC_CONTRACT;
3135         return dac_cast<TADDR>(m_ModuleID);
3136     }
3137
3138     SIZE_T *             GetAddrModuleID()
3139     {
3140         LIMITED_METHOD_CONTRACT;
3141         return (SIZE_T*) &m_ModuleID;
3142     }
3143
3144     static SIZE_T       GetOffsetOfModuleID()
3145     {
3146         LIMITED_METHOD_CONTRACT;
3147         return offsetof(Module, m_ModuleID);
3148     }
3149
3150     PTR_DomainLocalModule   GetDomainLocalModule(AppDomain *pDomain);
3151
3152 #ifndef DACCESS_COMPILE
3153     PTR_DomainLocalModule   GetDomainLocalModule()  { WRAPPER_NO_CONTRACT; return GetDomainLocalModule(NULL); };
3154 #endif
3155
3156 #ifdef FEATURE_PREJIT
3157     NgenStats *GetNgenStats()
3158     {
3159         LIMITED_METHOD_CONTRACT;
3160         return m_pNgenStats;
3161     }
3162 #endif // FEATURE_PREJIT
3163
3164     // LoaderHeap for storing IJW thunks
3165     PTR_LoaderHeap           m_pThunkHeap;
3166
3167     // Self-initializing accessor for IJW thunk heap
3168     LoaderHeap              *GetThunkHeap();
3169     // Self-initializing accessor for domain-independent IJW thunk heap
3170     LoaderHeap              *GetDllThunkHeap();
3171
3172     void            EnumRegularStaticGCRefs        (AppDomain* pAppDomain, promote_func* fn, ScanContext* sc);
3173
3174 protected:    
3175
3176     void            BuildStaticsOffsets     (AllocMemTracker *pamTracker);
3177     void            AllocateStatics         (AllocMemTracker *pamTracker);
3178
3179     // ModuleID is quite ugly. We should try to switch to using ModuleIndex instead
3180     // where appropriate, and we should clean up code that uses ModuleID
3181     PTR_DomainLocalModule   m_ModuleID;       // MultiDomain case: tagged (low bit 1) ModuleIndex
3182                                               // SingleDomain case: pointer to domain local module
3183
3184     ModuleIndex             m_ModuleIndex;
3185
3186     // reusing the statics area of a method table to store
3187     // these for the non domain neutral case, but they're now unified
3188     // it so that we don't have different code paths for this.
3189     PTR_DWORD               m_pRegularStaticOffsets;        // Offset of statics in each class
3190     PTR_DWORD               m_pThreadStaticOffsets;         // Offset of ThreadStatics in each class
3191
3192     // All types with RID <= this value have static storage allocated within the module by AllocateStatics
3193     // If AllocateStatics hasn't run yet, the value is 0
3194     RID                     m_maxTypeRidStaticsAllocated;
3195
3196     // @NICE: see if we can remove these fields
3197     DWORD                   m_dwMaxGCRegularStaticHandles;  // Max number of handles we can have.
3198     DWORD                   m_dwMaxGCThreadStaticHandles;
3199
3200     // Size of the precomputed statics block. This includes class init bytes, gc handles and non gc statics
3201     DWORD                   m_dwRegularStaticsBlockSize;
3202     DWORD                   m_dwThreadStaticsBlockSize;
3203
3204     // For 'dynamic' statics (Reflection and generics)
3205     SIZE_T                  m_cDynamicEntries;              // Number of used entries in DynamicStaticsInfo table
3206     SIZE_T                  m_maxDynamicEntries;            // Size of table itself, including unused entries
3207
3208     // Info we need for dynamic statics that we can store per-module (ie, no need for it to be duplicated
3209     // per appdomain)
3210     struct DynamicStaticsInfo
3211     {
3212         MethodTable*        pEnclosingMT;                   // Enclosing type; necessarily in this loader module
3213     };
3214     DynamicStaticsInfo*     m_pDynamicStaticsInfo;          // Table with entry for each dynamic ID
3215
3216
3217 public:
3218     //-----------------------------------------------------------------------------------------
3219     // If true,  strings only need to be interned at a per module basis, instead of at a
3220     // per appdomain basis, which is the default. Use the module accessor so you don't need
3221     // to touch the metadata in the ngen case
3222     //-----------------------------------------------------------------------------------------
3223     BOOL                    IsNoStringInterning();
3224
3225     //-----------------------------------------------------------------------------------------
3226     // Returns a BOOL to indicate if we have computed whether compiler has instructed us to
3227     // wrap the non-CLS compliant exceptions or not.
3228     //-----------------------------------------------------------------------------------------
3229     BOOL                    IsRuntimeWrapExceptionsStatusComputed();
3230
3231     //-----------------------------------------------------------------------------------------
3232     // If true,  any non-CLSCompliant exceptions (i.e. ones which derive from something other
3233     // than System.Exception) are wrapped in a RuntimeWrappedException instance.  In other
3234     // words, they become compliant
3235     //-----------------------------------------------------------------------------------------
3236     BOOL                    IsRuntimeWrapExceptions();
3237
3238     BOOL                    HasDefaultDllImportSearchPathsAttribute();
3239
3240     BOOL IsDefaultDllImportSearchPathsAttributeCached()
3241     {
3242         LIMITED_METHOD_CONTRACT;
3243         return (m_dwPersistedFlags & DEFAULT_DLL_IMPORT_SEARCH_PATHS_IS_CACHED) != 0;
3244     }
3245
3246     ULONG DefaultDllImportSearchPathsAttributeCachedValue()
3247     {
3248         LIMITED_METHOD_CONTRACT;
3249         return m_DefaultDllImportSearchPathsAttributeValue & 0xFFFFFFFD;
3250     }
3251
3252     BOOL DllImportSearchAssemblyDirectory()
3253     {
3254         LIMITED_METHOD_CONTRACT;
3255         return (m_DefaultDllImportSearchPathsAttributeValue & 0x2) != 0;
3256     }
3257
3258     //-----------------------------------------------------------------------------------------
3259     // True iff metadata version string is 1.* or 2.*.
3260     // @TODO (post-Dev10): All places that need this information should call this function
3261     // instead of parsing the version themselves.
3262     //-----------------------------------------------------------------------------------------
3263     BOOL                    IsPreV4Assembly();
3264
3265
3266     //-----------------------------------------------------------------------------------------
3267     // Parse/Return NeutralResourcesLanguageAttribute if it exists (updates Module member variables at ngen time)
3268     //-----------------------------------------------------------------------------------------
3269     BOOL                    GetNeutralResourcesLanguage(LPCUTF8 * cultureName, ULONG * cultureNameLength, INT16 * fallbackLocation, BOOL cacheAttribute);
3270
3271 protected:
3272
3273
3274     // initialize Crst controlling the Dynamic IL hashtables
3275     void                    InitializeDynamicILCrst();
3276
3277 public:
3278
3279     CrstBase *GetLookupTableCrst()
3280     {
3281         LIMITED_METHOD_CONTRACT;
3282         return &m_LookupTableCrst;
3283     }
3284
3285 private:
3286
3287     // This struct stores the data used by the managed debugging infrastructure.  If it turns out that 
3288     // the debugger is increasing the size of the Module class by too much, we can consider allocating
3289     // this struct lazily on demand.
3290     struct DebuggerSpecificData
3291     {
3292         // Mutex protecting update access to the DynamicILBlobTable and TemporaryILBlobTable
3293         PTR_Crst                 m_pDynamicILCrst;
3294     
3295                                                 // maps tokens for EnC/dynamics/reflection emit to their corresponding IL blobs
3296                                                 // this map *always* overrides the Metadata RVA
3297         PTR_DynamicILBlobTable   m_pDynamicILBlobTable;
3298
3299                                                 // maps tokens for to their corresponding overriden IL blobs
3300                                                 // this map conditionally overrides the Metadata RVA and the DynamicILBlobTable
3301         PTR_DynamicILBlobTable   m_pTemporaryILBlobTable;
3302
3303         // hash table storing any profiler-provided instrumented IL offset mapping
3304         PTR_ILOffsetMappingTable m_pILOffsetMappingTable;
3305
3306         // Strict count of # of methods in this module that are JMC-enabled.
3307         LONG    m_cTotalJMCFuncs;
3308
3309         // The default JMC status for methods in this module.
3310         // Individual methods can be overridden.
3311         bool    m_fDefaultJMCStatus;
3312     };
3313
3314     DebuggerSpecificData  m_debuggerSpecificData;
3315
3316     // This is a compressed read only copy of m_inlineTrackingMap, which is being saved to NGEN image.
3317     PTR_PersistentInlineTrackingMapNGen m_pPersistentInlineTrackingMapNGen;
3318
3319
3320     LPCSTR               *m_AssemblyRefByNameTable;  // array that maps mdAssemblyRef tokens into their simple name
3321     DWORD                 m_AssemblyRefByNameCount;  // array size
3322
3323 #if defined(FEATURE_PREJIT)
3324     // a.dll calls a method in b.dll and that method call a method in c.dll. When ngening
3325     // a.dll it is possible then method in b.dll can be inlined. When that happens a.ni.dll stores
3326     // an added native metadata which has information about assemblyRef to c.dll
3327     // Now due to facades, this scenario is very common. This led to lots of calls to 
3328     // binder to get the module corresponding to assemblyRef in native metadata. 
3329     // Adding a lookup map to cache assembly ptr so that AssemblySpec::LoadAssembly()
3330     // is not called for each fixup
3331
3332     PTR_Assembly           *m_NativeMetadataAssemblyRefMap; 
3333 #endif // defined(FEATURE_PREJIT)
3334
3335 public:
3336 #if !defined(DACCESS_COMPILE) && defined(FEATURE_PREJIT)
3337     PTR_Assembly GetNativeMetadataAssemblyRefFromCache(DWORD rid)
3338     {
3339         PTR_Assembly * NativeMetadataAssemblyRefMap = VolatileLoadWithoutBarrier(&m_NativeMetadataAssemblyRefMap);
3340
3341         if (NativeMetadataAssemblyRefMap == NULL)
3342             return NULL;
3343
3344         _ASSERTE(rid <= GetNativeAssemblyImport()->GetCountWithTokenKind(mdtAssemblyRef));
3345         return NativeMetadataAssemblyRefMap[rid - 1];
3346     }
3347
3348     void SetNativeMetadataAssemblyRefInCache(DWORD rid, PTR_Assembly pAssembly);
3349 #endif // !defined(DACCESS_COMPILE) && defined(FEATURE_PREJIT)
3350 };
3351
3352 //
3353 // A ReflectionModule is a module created by reflection
3354 //
3355
3356 class ReflectionModule : public Module
3357 {
3358     VPTR_VTABLE_CLASS(ReflectionModule, Module)
3359
3360  public:
3361     HCEESECTION m_sdataSection;
3362
3363  protected:
3364     ICeeGen * m_pCeeFileGen;
3365 private:
3366     Assembly             *m_pCreatingAssembly;
3367     ISymUnmanagedWriter  *m_pISymUnmanagedWriter;
3368     RefClassWriter       *m_pInMemoryWriter;
3369
3370
3371     // Simple Critical Section used for basic leaf-lock operatons.
3372     CrstExplicitInit        m_CrstLeafLock;
3373
3374     // Buffer of Metadata storage for dynamic modules. May be NULL. This provides a reasonable way for
3375     // the debugger to get metadata of dynamic modules from out of process.
3376     // A dynamic module will eagerly serialize its metadata to this buffer.
3377     PTR_SBuffer m_pDynamicMetadata;
3378     
3379     // If true, does not eagerly serialize metadata in code:ReflectionModule.CaptureModuleMetaDataToMemory.
3380     // This is used to allow bulk emitting types without re-emitting the metadata between each type. 
3381     bool m_fSuppressMetadataCapture;
3382
3383     // If true, then only other transient modules can depend on this module.
3384     bool m_fIsTransient;
3385
3386 #if !defined DACCESS_COMPILE && !defined CROSSGEN_COMPILE
3387     // Returns true iff metadata capturing is suppressed
3388     bool IsMetadataCaptureSuppressed();
3389
3390     // Toggle whether CaptureModuleMetaDataToMemory should do antyhing. This can be an important perf win to
3391     // allow batching up metadata capture. Use SuppressMetadataCaptureHolder to ensure they're balanced.
3392     // These are not nestable.
3393     void SuppressMetadataCapture();
3394     void ResumeMetadataCapture();
3395
3396     // Glue functions for holders.
3397     static void SuppressCaptureWrapper(ReflectionModule * pModule)
3398     {
3399         pModule->SuppressMetadataCapture();
3400     }
3401     static void ResumeCaptureWrapper(ReflectionModule * pModule)
3402     {
3403         pModule->ResumeMetadataCapture();
3404     }
3405
3406     ReflectionModule(Assembly *pAssembly, mdFile token, PEFile *pFile);
3407 #endif // !DACCESS_COMPILE && !CROSSGEN_COMPILE
3408
3409 public:
3410
3411 #ifdef DACCESS_COMPILE
3412     // Accessor to expose m_pDynamicMetadata to debugger.
3413     PTR_SBuffer GetDynamicMetadataBuffer() const;
3414 #endif
3415
3416 #if !defined DACCESS_COMPILE && !defined CROSSGEN_COMPILE
3417     static ReflectionModule *Create(Assembly *pAssembly, PEFile *pFile, AllocMemTracker *pamTracker, LPCWSTR szName, BOOL fIsTransient);
3418     void Initialize(AllocMemTracker *pamTracker, LPCWSTR szName);
3419     void Destruct();
3420
3421     void ReleaseILData();
3422 #endif // !DACCESS_COMPILE && !CROSSGEN_COMPILE
3423
3424     // Overides functions to access sections
3425     virtual TADDR GetIL(RVA target);
3426     virtual PTR_VOID GetRvaField(RVA rva, BOOL fZapped);
3427
3428     Assembly* GetCreatingAssembly( void )
3429     {
3430         LIMITED_METHOD_CONTRACT;
3431
3432         return m_pCreatingAssembly;
3433     }
3434
3435     void SetCreatingAssembly( Assembly* assembly )
3436     {
3437         LIMITED_METHOD_CONTRACT;
3438
3439         m_pCreatingAssembly = assembly;
3440     }
3441
3442     ICeeGen *GetCeeGen() {LIMITED_METHOD_CONTRACT;  return m_pCeeFileGen; }
3443
3444     RefClassWriter *GetClassWriter()
3445     {
3446         LIMITED_METHOD_CONTRACT;
3447
3448         return m_pInMemoryWriter;
3449     }
3450
3451     ISymUnmanagedWriter *GetISymUnmanagedWriter()
3452     {
3453         LIMITED_METHOD_CONTRACT;
3454         return m_pISymUnmanagedWriter;
3455     }
3456
3457     // Note: we now use the same writer instance for the life of a module,
3458     // so there should no longer be any need for the extra indirection.
3459     ISymUnmanagedWriter **GetISymUnmanagedWriterAddr()
3460     {
3461         LIMITED_METHOD_CONTRACT;
3462
3463         // We must have setup the writer before trying to get
3464         // the address for it. Any calls to this before a
3465         // SetISymUnmanagedWriter are very incorrect.
3466         _ASSERTE(m_pISymUnmanagedWriter != NULL);
3467
3468         return &m_pISymUnmanagedWriter;
3469     }
3470
3471     bool IsTransient()
3472     {
3473         LIMITED_METHOD_CONTRACT;
3474
3475         return m_fIsTransient;
3476     }
3477
3478     void SetIsTransient(bool fIsTransient)
3479     {
3480         LIMITED_METHOD_CONTRACT;
3481
3482         m_fIsTransient = fIsTransient;
3483     }
3484
3485 #ifndef DACCESS_COMPILE
3486 #ifndef CROSSGEN_COMPILE
3487
3488     typedef Wrapper<
3489         ReflectionModule*, 
3490         ReflectionModule::SuppressCaptureWrapper, 
3491         ReflectionModule::ResumeCaptureWrapper> SuppressMetadataCaptureHolder;
3492 #endif // !CROSSGEN_COMPILE
3493
3494     HRESULT SetISymUnmanagedWriter(ISymUnmanagedWriter *pWriter)
3495     {
3496         CONTRACTL
3497         {
3498             NOTHROW;
3499             GC_NOTRIGGER;
3500             INJECT_FAULT(return E_OUTOFMEMORY;);
3501         }
3502         CONTRACTL_END
3503
3504
3505         // Setting to NULL when we've never set a writer before should
3506         // do nothing.
3507         if ((pWriter == NULL) && (m_pISymUnmanagedWriter == NULL))
3508             return S_OK;
3509
3510         if (m_pISymUnmanagedWriter != NULL)
3511         {
3512             // We shouldn't be trying to replace an existing writer anymore
3513             _ASSERTE( pWriter == NULL );
3514
3515             m_pISymUnmanagedWriter->Release();
3516         }
3517         
3518         m_pISymUnmanagedWriter = pWriter;
3519         return S_OK;
3520     }
3521 #endif // !DACCESS_COMPILE
3522
3523     // Eagerly serialize the metadata to a buffer that the debugger can retrieve.
3524     void CaptureModuleMetaDataToMemory();
3525 };
3526
3527 // Module holders
3528 FORCEINLINE void VoidModuleDestruct(Module *pModule)
3529 {
3530 #ifndef DACCESS_COMPILE
3531     if (g_fEEStarted)
3532         pModule->Destruct();
3533 #endif
3534 }
3535
3536 typedef Wrapper<Module*, DoNothing, VoidModuleDestruct, 0> ModuleHolder;
3537
3538
3539
3540 FORCEINLINE void VoidReflectionModuleDestruct(ReflectionModule *pModule)
3541 {
3542 #ifndef DACCESS_COMPILE
3543     pModule->Destruct();
3544 #endif
3545 }
3546
3547 typedef Wrapper<ReflectionModule*, DoNothing, VoidReflectionModuleDestruct, 0> ReflectionModuleHolder;
3548
3549
3550
3551 //----------------------------------------------------------------------
3552 // VASigCookieEx (used to create a fake VASigCookie for unmanaged->managed
3553 // calls to vararg functions. These fakes are distinguished from the
3554 // real thing by having a null mdVASig.
3555 //----------------------------------------------------------------------
3556 struct VASigCookieEx : public VASigCookie
3557 {
3558     const BYTE *m_pArgs;        // pointer to first unfixed unmanaged arg
3559 };
3560
3561 inline bool IsSingleAppDomain()
3562 {
3563     // CoreCLR always runs as single AppDomain
3564     return true;
3565 }
3566
3567 #endif // !CEELOAD_H_