1 // Licensed to the .NET Foundation under one or more agreements.
2 // The .NET Foundation licenses this file to you under the MIT license.
8 // NGEN-specific infrastructure for writing PE files.
10 // ======================================================================================
15 #include "zaprelocs.h"
17 #include "zapinnerptr.h"
18 #include "zapwrapper.h"
20 #include "zapheaders.h"
21 #include "zapmetadata.h"
23 #include "zapimport.h"
25 #ifdef FEATURE_READYTORUN_COMPILER
26 #include "zapreadytorun.h"
31 // This is RTL_CONTAINS_FIELD from ntdef.h
32 #define CONTAINS_FIELD(Struct, Size, Field) \
33 ( (((PCHAR)(&(Struct)->Field)) + sizeof((Struct)->Field)) <= (((PCHAR)(Struct))+(Size)) )
35 /* --------------------------------------------------------------------------- *
36 * Destructor wrapper objects
37 * --------------------------------------------------------------------------- */
39 ZapImage::ZapImage(Zapper *zapper)
41 m_stats(new ZapperStats())
42 /* Everything else is initialized to 0 by default */
48 #ifdef ZAP_HASHTABLE_TUNING
49 // If ZAP_HASHTABLE_TUNING is defined, preallocate is overloaded to print the tuning constants
59 if (m_pModuleFileName != NULL)
60 delete [] m_pModuleFileName;
62 if (m_pMDImport != NULL)
63 m_pMDImport->Release();
65 if (m_pAssemblyEmit != NULL)
66 m_pAssemblyEmit->Release();
68 if (m_profileDataFile != NULL)
69 UnmapViewOfFile(m_profileDataFile);
72 m_pPreloader->Release();
74 if (m_pImportSectionsTable != NULL)
75 m_pImportSectionsTable->~ZapImportSectionsTable();
77 if (m_pGCInfoTable != NULL)
78 m_pGCInfoTable->~ZapGCInfoTable();
80 #ifdef FEATURE_EH_FUNCLETS
81 if (m_pUnwindDataTable != NULL)
82 m_pUnwindDataTable->~ZapUnwindDataTable();
85 if (m_pStubDispatchDataTable != NULL)
86 m_pStubDispatchDataTable->~ZapImportSectionSignatures();
88 if (m_pExternalMethodDataTable != NULL)
89 m_pExternalMethodDataTable->~ZapImportSectionSignatures();
91 if (m_pDynamicHelperDataTable != NULL)
92 m_pDynamicHelperDataTable->~ZapImportSectionSignatures();
94 if (m_pDebugInfoTable != NULL)
95 m_pDebugInfoTable->~ZapDebugInfoTable();
97 if (m_pVirtualSectionsTable != NULL)
98 m_pVirtualSectionsTable->~ZapVirtualSectionsTable();
100 if (m_pILMetaData != NULL)
101 m_pILMetaData->~ZapILMetaData();
103 if (m_pBaseRelocs != NULL)
104 m_pBaseRelocs->~ZapBaseRelocs();
106 if (m_pAssemblyMetaData != NULL)
107 m_pAssemblyMetaData->~ZapMetaData();
110 // Destruction of auxiliary tables in alphabetical order
113 if (m_pImportTable != NULL)
114 m_pImportTable->~ZapImportTable();
116 if (m_pInnerPtrs != NULL)
117 m_pInnerPtrs->~ZapInnerPtrTable();
119 if (m_pMethodEntryPoints != NULL)
120 m_pMethodEntryPoints->~ZapMethodEntryPointTable();
122 if (m_pWrappers != NULL)
123 m_pWrappers->~ZapWrapperTable();
126 void ZapImage::InitializeSections()
128 AllocateVirtualSections();
130 m_pCorHeader = new (GetHeap()) ZapCorHeader(this);
131 m_pHeaderSection->Place(m_pCorHeader);
133 SetDirectoryEntry(IMAGE_DIRECTORY_ENTRY_COMHEADER, m_pCorHeader);
135 m_pNativeHeader = new (GetHeap()) ZapNativeHeader(this);
136 m_pHeaderSection->Place(m_pNativeHeader);
138 m_pCodeManagerEntry = new (GetHeap()) ZapCodeManagerEntry(this);
139 m_pHeaderSection->Place(m_pCodeManagerEntry);
141 m_pImportSectionsTable = new (GetHeap()) ZapImportSectionsTable(this);
142 m_pImportTableSection->Place(m_pImportSectionsTable);
144 m_pExternalMethodDataTable = new (GetHeap()) ZapImportSectionSignatures(this, m_pExternalMethodThunkSection, m_pGCSection);
145 m_pExternalMethodDataSection->Place(m_pExternalMethodDataTable);
147 m_pStubDispatchDataTable = new (GetHeap()) ZapImportSectionSignatures(this, m_pStubDispatchCellSection, m_pGCSection);
148 m_pStubDispatchDataSection->Place(m_pStubDispatchDataTable);
150 m_pImportTable = new (GetHeap()) ZapImportTable(this);
152 m_pGCInfoTable = new (GetHeap()) ZapGCInfoTable(this);
153 m_pExceptionInfoLookupTable = new (GetHeap()) ZapExceptionInfoLookupTable(this);
155 #ifdef FEATURE_EH_FUNCLETS
156 m_pUnwindDataTable = new (GetHeap()) ZapUnwindDataTable(this);
159 m_pEEInfoTable = ZapBlob::NewAlignedBlob(this, NULL, sizeof(CORCOMPILE_EE_INFO_TABLE), TARGET_POINTER_SIZE);
160 m_pEETableSection->Place(m_pEEInfoTable);
163 // Allocate Helper table, and fill it out
166 m_pHelperThunks = new (GetHeap()) ZapNode * [CORINFO_HELP_COUNT];
168 m_pILMetaData = new (GetHeap()) ZapILMetaData(this);
169 m_pILMetaDataSection->Place(m_pILMetaData);
171 m_pDebugInfoTable = new (GetHeap()) ZapDebugInfoTable(this);
172 m_pDebugSection->Place(m_pDebugInfoTable);
174 m_pBaseRelocs = new (GetHeap()) ZapBaseRelocs(this);
175 m_pBaseRelocsSection->Place(m_pBaseRelocs);
177 SetDirectoryEntry(IMAGE_DIRECTORY_ENTRY_BASERELOC, m_pBaseRelocsSection);
180 // Initialization of auxiliary tables in alphabetical order
182 m_pInnerPtrs = new (GetHeap()) ZapInnerPtrTable(this);
183 m_pMethodEntryPoints = new (GetHeap()) ZapMethodEntryPointTable(this);
184 m_pWrappers = new (GetHeap()) ZapWrapperTable(this);
186 // Place the virtual sections tables in debug section. It exists for diagnostic purposes
187 // only and should not be touched under normal circumstances
188 m_pVirtualSectionsTable = new (GetHeap()) ZapVirtualSectionsTable(this);
189 m_pDebugSection->Place(m_pVirtualSectionsTable);
191 #ifndef ZAP_HASHTABLE_TUNING
196 #ifdef FEATURE_READYTORUN_COMPILER
197 void ZapImage::InitializeSectionsForReadyToRun()
199 AllocateVirtualSections();
201 // Preload sections are not used for ready to run. Clear the pointers to them to catch accidental use.
202 for (int i = 0; i < CORCOMPILE_SECTION_COUNT; i++)
203 m_pPreloadSections[i] = NULL;
205 m_pCorHeader = new (GetHeap()) ZapCorHeader(this);
206 m_pHeaderSection->Place(m_pCorHeader);
208 SetDirectoryEntry(IMAGE_DIRECTORY_ENTRY_COMHEADER, m_pCorHeader);
210 m_pNativeHeader = new (GetHeap()) ZapReadyToRunHeader(this);
211 m_pHeaderSection->Place(m_pNativeHeader);
213 m_pImportSectionsTable = new (GetHeap()) ZapImportSectionsTable(this);
214 m_pHeaderSection->Place(m_pImportSectionsTable);
217 #define COMPILER_NAME "CoreCLR"
219 const char* pCompilerIdentifier = COMPILER_NAME " " VER_FILEVERSION_STR;
220 ZapBlob * pCompilerIdentifierBlob = new (GetHeap()) ZapBlobPtr((PVOID)pCompilerIdentifier, strlen(pCompilerIdentifier) + 1);
222 GetReadyToRunHeader()->RegisterSection(ReadyToRunSectionType::CompilerIdentifier, pCompilerIdentifierBlob);
223 m_pHeaderSection->Place(pCompilerIdentifierBlob);
226 m_pImportTable = new (GetHeap()) ZapImportTable(this);
228 for (int i=0; i<ZapImportSectionType_Total; i++)
230 ZapVirtualSection * pSection;
231 if (i == ZapImportSectionType_Eager)
232 pSection = m_pDelayLoadInfoDelayListSectionEager;
234 if (i < ZapImportSectionType_Cold)
235 pSection = m_pDelayLoadInfoDelayListSectionHot;
237 pSection = m_pDelayLoadInfoDelayListSectionCold;
239 m_pDelayLoadInfoDataTable[i] = new (GetHeap()) ZapImportSectionSignatures(this, m_pDelayLoadInfoTableSection[i]);
240 pSection->Place(m_pDelayLoadInfoDataTable[i]);
243 m_pDynamicHelperDataTable = new (GetHeap()) ZapImportSectionSignatures(this, m_pDynamicHelperCellSection);
244 m_pDynamicHelperDataSection->Place(m_pDynamicHelperDataTable);
246 m_pExternalMethodDataTable = new (GetHeap()) ZapImportSectionSignatures(this, m_pExternalMethodCellSection, m_pGCSection);
247 m_pExternalMethodDataSection->Place(m_pExternalMethodDataTable);
249 m_pStubDispatchDataTable = new (GetHeap()) ZapImportSectionSignatures(this, m_pStubDispatchCellSection, m_pGCSection);
250 m_pStubDispatchDataSection->Place(m_pStubDispatchDataTable);
252 m_pGCInfoTable = new (GetHeap()) ZapGCInfoTable(this);
254 #ifdef FEATURE_EH_FUNCLETS
255 m_pUnwindDataTable = new (GetHeap()) ZapUnwindDataTable(this);
258 m_pILMetaData = new (GetHeap()) ZapILMetaData(this);
259 m_pILMetaDataSection->Place(m_pILMetaData);
261 m_pBaseRelocs = new (GetHeap()) ZapBaseRelocs(this);
262 m_pBaseRelocsSection->Place(m_pBaseRelocs);
264 SetDirectoryEntry(IMAGE_DIRECTORY_ENTRY_BASERELOC, m_pBaseRelocsSection);
267 // Initialization of auxiliary tables in alphabetical order
269 m_pInnerPtrs = new (GetHeap()) ZapInnerPtrTable(this);
271 m_pExceptionInfoLookupTable = new (GetHeap()) ZapExceptionInfoLookupTable(this);
274 // Always allocate slot for module - it is used to determine that the image is used
276 m_pImportTable->GetPlacedHelperImport(READYTORUN_HELPER_Module);
279 // Make sure the import sections table is in the image, so we can find the slot for module
281 _ASSERTE(m_pImportSectionsTable->GetSize() != 0);
282 GetReadyToRunHeader()->RegisterSection(ReadyToRunSectionType::ImportSections, m_pImportSectionsTable);
284 #endif // FEATURE_READYTORUN_COMPILER
287 #define DATA_MEM_READONLY IMAGE_SCN_MEM_READ
288 #define DATA_MEM_WRITABLE IMAGE_SCN_MEM_READ | IMAGE_SCN_MEM_WRITE
289 #define XDATA_MEM IMAGE_SCN_MEM_EXECUTE | IMAGE_SCN_MEM_READ | IMAGE_SCN_MEM_WRITE
290 #define TEXT_MEM IMAGE_SCN_MEM_EXECUTE | IMAGE_SCN_MEM_READ
292 void ZapImage::AllocateVirtualSections()
295 // Allocate all virtual sections in the order they will appear in the final image
297 // To maximize packing of the data in the native image, the number of named physical sections is minimized -
298 // the named physical sections are used just for memory protection control. All items with the same memory
299 // protection are packed together in one physical section.
306 DWORD access = DATA_MEM_WRITABLE;
308 ZapPhysicalSection * pDataSection = NewPhysicalSection(".data", IMAGE_SCN_CNT_INITIALIZED_DATA | access);
310 m_pPreloadSections[CORCOMPILE_SECTION_MODULE] = NewVirtualSection(pDataSection, IBCUnProfiledSection | HotRange | ModuleSection);
312 m_pEETableSection = NewVirtualSection(pDataSection, IBCUnProfiledSection | HotRange | EETableSection); // Could be marked bss if it makes sense
314 // These are all known to be hot or writeable
315 m_pPreloadSections[CORCOMPILE_SECTION_WRITE] = NewVirtualSection(pDataSection, IBCProfiledSection | HotRange | WriteDataSection);
316 m_pPreloadSections[CORCOMPILE_SECTION_HOT_WRITEABLE] = NewVirtualSection(pDataSection, IBCProfiledSection | HotRange | WriteableDataSection); // hot for reading, potentially written to
317 m_pPreloadSections[CORCOMPILE_SECTION_WRITEABLE] = NewVirtualSection(pDataSection, IBCProfiledSection | ColdRange | WriteableDataSection); // Cold based on IBC profiling data.
318 m_pPreloadSections[CORCOMPILE_SECTION_HOT] = NewVirtualSection(pDataSection, IBCProfiledSection | HotRange | DataSection);
320 m_pPreloadSections[CORCOMPILE_SECTION_RVA_STATICS_HOT] = NewVirtualSection(pDataSection, IBCProfiledSection | HotRange | RVAStaticsSection);
322 m_pDelayLoadInfoTableSection[ZapImportSectionType_Eager] = NewVirtualSection(pDataSection, IBCUnProfiledSection | HotRange | DelayLoadInfoTableEagerSection, TARGET_POINTER_SIZE);
325 // Allocate dynamic info tables
328 // Place the HOT CorCompileTables now, the cold ones would be placed later in this routine (after other HOT sections)
329 for (int i=0; i<ZapImportSectionType_Count; i++)
331 m_pDelayLoadInfoTableSection[i] = NewVirtualSection(pDataSection, IBCProfiledSection | HotRange | DelayLoadInfoTableSection, TARGET_POINTER_SIZE);
334 m_pDynamicHelperCellSection = NewVirtualSection(pDataSection, IBCProfiledSection | HotColdSortedRange | ExternalMethodDataSection, TARGET_POINTER_SIZE);
336 m_pExternalMethodCellSection = NewVirtualSection(pDataSection, IBCProfiledSection | HotColdSortedRange | ExternalMethodThunkSection, TARGET_POINTER_SIZE);
338 // m_pStubDispatchCellSection is deliberately placed directly after
339 // the last m_pDelayLoadInfoTableSection (all .data sections go together in the order indicated).
340 // We do this to place it as the last "hot, written" section. Why? Because
341 // we don't split the dispatch cells into hot/cold sections (we probably should),
342 // and so the section is actually half hot and half cold.
343 // But it turns out that the hot dispatch cells always come
344 // first (because the code that uses them is hot and gets compiled first).
345 // Thus m_pStubDispatchCellSection contains all hot cells at the front of
346 // this blob of data. By making them last in a grouping of written data we
347 // make sure the hot data is grouped with hot data in the
348 // m_pDelayLoadInfoTableSection sections.
350 m_pStubDispatchCellSection = NewVirtualSection(pDataSection, IBCProfiledSection | HotColdSortedRange | StubDispatchDataSection, TARGET_POINTER_SIZE);
352 // Earlier we placed the HOT corCompile tables. Now place the cold ones after the stub dispatch cell section.
353 for (int i=0; i<ZapImportSectionType_Count; i++)
355 m_pDelayLoadInfoTableSection[ZapImportSectionType_Cold + i] = NewVirtualSection(pDataSection, IBCProfiledSection | ColdRange | DelayLoadInfoTableSection, TARGET_POINTER_SIZE);
359 // Virtual sections that are moved to .cdata when we have profile data.
362 // This is everything that is assumed to be warm in the first strata
363 // of non-profiled scenarios. MethodTables related to objects etc.
364 m_pPreloadSections[CORCOMPILE_SECTION_WARM] = NewVirtualSection(pDataSection, IBCProfiledSection | WarmRange | EEDataSection, TARGET_POINTER_SIZE);
366 m_pPreloadSections[CORCOMPILE_SECTION_RVA_STATICS_COLD] = NewVirtualSection(pDataSection, IBCProfiledSection | ColdRange | RVAStaticsSection);
368 // In an ideal world these are cold in both profiled and the first strata
369 // of non-profiled scenarios (i.e. no reflection, etc.) The sections at the
370 // bottom correspond to further strata of non-profiled scenarios.
371 m_pPreloadSections[CORCOMPILE_SECTION_CLASS_COLD] = NewVirtualSection(pDataSection, IBCProfiledSection | ColdRange | ClassSection, TARGET_POINTER_SIZE);
372 m_pPreloadSections[CORCOMPILE_SECTION_CROSS_DOMAIN_INFO] = NewVirtualSection(pDataSection, IBCUnProfiledSection | ColdRange | CrossDomainInfoSection, TARGET_POINTER_SIZE);
373 m_pPreloadSections[CORCOMPILE_SECTION_METHOD_DESC_COLD] = NewVirtualSection(pDataSection, IBCProfiledSection | ColdRange | MethodDescSection, TARGET_POINTER_SIZE);
374 m_pPreloadSections[CORCOMPILE_SECTION_METHOD_DESC_COLD_WRITEABLE] = NewVirtualSection(pDataSection, IBCProfiledSection | ColdRange | MethodDescWriteableSection, TARGET_POINTER_SIZE);
375 m_pPreloadSections[CORCOMPILE_SECTION_MODULE_COLD] = NewVirtualSection(pDataSection, IBCProfiledSection | ColdRange | ModuleSection, TARGET_POINTER_SIZE);
376 m_pPreloadSections[CORCOMPILE_SECTION_DEBUG_COLD] = NewVirtualSection(pDataSection, IBCUnProfiledSection | ColdRange | DebugSection, TARGET_POINTER_SIZE);
379 // If we're instrumenting allocate a section for writing profile data
381 if (m_zapper->m_pOpt->m_compilerFlags.IsSet(CORJIT_FLAGS::CORJIT_FLAG_BBINSTR))
383 m_pInstrumentSection = NewVirtualSection(pDataSection, IBCUnProfiledSection | ColdRange | InstrumentSection, TARGET_POINTER_SIZE);
387 // No RWX pages in ready to run images
388 if (!IsReadyToRunCompilation())
390 DWORD access = XDATA_MEM;
395 ZapPhysicalSection * pXDataSection = NewPhysicalSection(".xdata", IMAGE_SCN_CNT_INITIALIZED_DATA | access);
397 // Some sections are placed in a sorted order. Hot items are placed first,
398 // then cold items. These sections are marked as HotColdSortedRange since
399 // they are neither completely hot, nor completely cold.
400 m_pVirtualImportThunkSection = NewVirtualSection(pXDataSection, IBCProfiledSection | HotColdSortedRange | VirtualImportThunkSection, HELPER_TABLE_ALIGN);
401 m_pExternalMethodThunkSection = NewVirtualSection(pXDataSection, IBCProfiledSection | HotColdSortedRange | ExternalMethodThunkSection, HELPER_TABLE_ALIGN);
402 m_pHelperTableSection = NewVirtualSection(pXDataSection, IBCProfiledSection | HotColdSortedRange| HelperTableSection, HELPER_TABLE_ALIGN);
404 // hot for writing, i.e. profiling has indicated a write to this item, so at least one write likely per item at some point
405 m_pPreloadSections[CORCOMPILE_SECTION_METHOD_PRECODE_WRITE] = NewVirtualSection(pXDataSection, IBCProfiledSection | HotRange | MethodPrecodeWriteSection, TARGET_POINTER_SIZE);
406 m_pPreloadSections[CORCOMPILE_SECTION_METHOD_PRECODE_HOT] = NewVirtualSection(pXDataSection, IBCProfiledSection | HotRange | MethodPrecodeSection, TARGET_POINTER_SIZE);
411 m_pPreloadSections[CORCOMPILE_SECTION_METHOD_PRECODE_COLD] = NewVirtualSection(pXDataSection, IBCProfiledSection | ColdRange | MethodPrecodeSection, TARGET_POINTER_SIZE);
412 m_pPreloadSections[CORCOMPILE_SECTION_METHOD_PRECODE_COLD_WRITEABLE] = NewVirtualSection(pXDataSection, IBCProfiledSection | ColdRange | MethodPrecodeWriteableSection, TARGET_POINTER_SIZE);
416 // code:NativeUnwindInfoLookupTable::LookupUnwindInfoForMethod and code:NativeImageJitManager::GetFunctionEntry expects
417 // sentinel value right after end of .pdata section.
418 static const DWORD dwRuntimeFunctionSectionSentinel = (DWORD)-1;
424 #if defined(TARGET_ARM)
425 // for ARM, put the resource section at the end if it's very large - this
426 // is because b and bl instructions have a limited distance range of +-16MB
427 // which we should not exceed if we can avoid it.
428 // we draw the limit at 1 MB resource size, somewhat arbitrarily
429 COUNT_T resourceSize;
430 m_ModuleDecoder.GetResources(&resourceSize);
431 BOOL bigResourceSection = resourceSize >= 1024*1024;
433 ZapPhysicalSection * pTextSection = NewPhysicalSection(".text", IMAGE_SCN_CNT_CODE | TEXT_MEM);
434 m_pTextSection = pTextSection;
436 // Marked as HotRange since it contains items that are always touched by
437 // the OS during NGEN image loading (i.e. VersionInfo)
438 m_pWin32ResourceSection = NewVirtualSection(pTextSection, IBCUnProfiledSection | HotRange | Win32ResourcesSection);
440 // Marked as a HotRange since it is always touched during Ngen image load.
441 m_pHeaderSection = NewVirtualSection(pTextSection, IBCUnProfiledSection | HotRange | HeaderSection);
443 // Marked as a HotRange since it is always touched during Ngen image binding.
444 m_pMetaDataSection = NewVirtualSection(pTextSection, IBCUnProfiledSection | HotRange | MetadataSection);
446 m_pImportTableSection = NewVirtualSection(pTextSection, IBCUnProfiledSection | HotRange | ImportTableSection, sizeof(DWORD));
448 m_pDelayLoadInfoDelayListSectionEager = NewVirtualSection(pTextSection, IBCUnProfiledSection | HotRange | DelayLoadInfoDelayListSection, sizeof(DWORD));
451 // GC Info for methods which were profiled hot AND had their GC Info touched during profiling
453 m_pHotTouchedGCSection = NewVirtualSection(pTextSection, IBCProfiledSection | HotRange | GCInfoSection, sizeof(DWORD));
455 m_pLazyHelperSection = NewVirtualSection(pTextSection, IBCUnProfiledSection | HotRange | HelperTableSection, MINIMUM_CODE_ALIGN);
456 m_pLazyHelperSection->SetDefaultFill(DEFAULT_CODE_BUFFER_INIT);
458 m_pLazyMethodCallHelperSection = NewVirtualSection(pTextSection, IBCUnProfiledSection | HotRange | HelperTableSection, MINIMUM_CODE_ALIGN);
459 m_pLazyMethodCallHelperSection->SetDefaultFill(DEFAULT_CODE_BUFFER_INIT);
461 int codeSectionAlign = DEFAULT_CODE_ALIGN;
463 m_pHotCodeSection = NewVirtualSection(pTextSection, IBCProfiledSection | HotRange | CodeSection, codeSectionAlign);
464 m_pHotCodeSection->SetDefaultFill(DEFAULT_CODE_BUFFER_INIT);
466 #if defined(FEATURE_EH_FUNCLETS)
467 m_pHotUnwindDataSection = NewVirtualSection(pTextSection, IBCProfiledSection | HotRange | UnwindDataSection, sizeof(DWORD)); // .rdata area
469 // All RuntimeFunctionSections have to be together for FEATURE_EH_FUNCLETS
470 m_pHotRuntimeFunctionSection = NewVirtualSection(pTextSection, IBCProfiledSection | HotRange | RuntimeFunctionSection, sizeof(DWORD)); // .pdata area
471 m_pRuntimeFunctionSection = NewVirtualSection(pTextSection, IBCProfiledSection | WarmRange | ColdRange | RuntimeFunctionSection, sizeof(DWORD));
472 m_pColdRuntimeFunctionSection = NewVirtualSection(pTextSection, IBCProfiledSection | IBCUnProfiledSection | ColdRange | RuntimeFunctionSection, sizeof(DWORD));
474 // The following sentinel section is just a padding for RuntimeFunctionSection - Apply same classification
475 NewVirtualSection(pTextSection, IBCProfiledSection | IBCUnProfiledSection | ColdRange | RuntimeFunctionSection, sizeof(DWORD))
476 ->Place(new (GetHeap()) ZapBlobPtr((PVOID)&dwRuntimeFunctionSectionSentinel, sizeof(DWORD)));
477 #endif // defined(FEATURE_EH_FUNCLETS)
479 m_pStubsSection = NewVirtualSection(pTextSection, IBCProfiledSection | HotColdSortedRange | StubsSection);
480 m_pReadOnlyDataSection = NewVirtualSection(pTextSection, IBCProfiledSection | HotColdSortedRange | ReadonlyDataSection);
482 m_pDynamicHelperDataSection = NewVirtualSection(pTextSection, IBCProfiledSection | HotColdSortedRange | ExternalMethodDataSection, sizeof(DWORD));
483 m_pExternalMethodDataSection = NewVirtualSection(pTextSection, IBCProfiledSection | HotColdSortedRange | ExternalMethodDataSection, sizeof(DWORD));
484 m_pStubDispatchDataSection = NewVirtualSection(pTextSection, IBCProfiledSection | HotColdSortedRange | StubDispatchDataSection, sizeof(DWORD));
486 m_pHotRuntimeFunctionLookupSection = NewVirtualSection(pTextSection, IBCProfiledSection | HotRange | RuntimeFunctionSection, sizeof(DWORD));
487 #if !defined(FEATURE_EH_FUNCLETS)
488 m_pHotRuntimeFunctionSection = NewVirtualSection(pTextSection, IBCProfiledSection | HotRange | RuntimeFunctionSection, sizeof(DWORD));
490 // The following sentinel section is just a padding for RuntimeFunctionSection - Apply same classification
491 NewVirtualSection(pTextSection, IBCProfiledSection | HotRange | RuntimeFunctionSection, sizeof(DWORD))
492 ->Place(new (GetHeap()) ZapBlobPtr((PVOID)&dwRuntimeFunctionSectionSentinel, sizeof(DWORD)));
494 m_pHotCodeMethodDescsSection = NewVirtualSection(pTextSection, IBCProfiledSection | HotRange | CodeManagerSection, sizeof(DWORD));
496 m_pDelayLoadInfoDelayListSectionHot = NewVirtualSection(pTextSection, IBCProfiledSection | HotRange | DelayLoadInfoDelayListSection, sizeof(DWORD));
499 // The hot set of read-only data structures. Note that read-only data structures are the things that we can (and aggressively do) intern
500 // to share between different owners. However, this can have a bad interaction with IBC, which performs its ordering optimizations without
501 // knowing that NGen may jumble around layout with interning. Thankfully, it is a relatively small percentage of the items that are duplicates
502 // (many of them used a great deal to add up to large interning savings). This means that we can track all of the interned items for which we
503 // actually find any duplicates and put those in a small section. For the rest, where there wasn't a duplicate in the entire image, we leave the
504 // singleton in its normal place in the READONLY_HOT section, which was selected carefully by IBC.
506 m_pPreloadSections[CORCOMPILE_SECTION_READONLY_SHARED_HOT] = NewVirtualSection(pTextSection, IBCProfiledSection | HotRange | ReadonlySharedSection, TARGET_POINTER_SIZE);
507 m_pPreloadSections[CORCOMPILE_SECTION_READONLY_HOT] = NewVirtualSection(pTextSection, IBCProfiledSection | HotRange | ReadonlySection, TARGET_POINTER_SIZE);
510 // GC Info for methods which were touched during profiling but didn't explicitly have
511 // their GC Info touched during profiling
513 m_pHotGCSection = NewVirtualSection(pTextSection, IBCProfiledSection | WarmRange | GCInfoSection, sizeof(DWORD));
515 #if !defined(TARGET_ARM)
516 // For ARM, put these sections more towards the end because bl/b instructions have limited displacement
519 m_pILSection = NewVirtualSection(pTextSection, IBCProfiledSection | HotColdSortedRange | ILSection, sizeof(DWORD));
521 //ILMetadata/Resources sections are reported as a statically known warm ranges for now.
522 m_pILMetaDataSection = NewVirtualSection(pTextSection, IBCProfiledSection | HotColdSortedRange | ILMetadataSection, sizeof(DWORD));
525 #if defined(TARGET_ARM)
526 if (!bigResourceSection) // for ARM, put the resource section at the end if it's very large - see comment above
528 m_pResourcesSection = NewVirtualSection(pTextSection, IBCUnProfiledSection | WarmRange | ResourcesSection);
531 // Allocate the unprofiled code section and code manager nibble map here
533 m_pCodeSection = NewVirtualSection(pTextSection, IBCProfiledSection | WarmRange | ColdRange | CodeSection, codeSectionAlign);
534 m_pCodeSection->SetDefaultFill(DEFAULT_CODE_BUFFER_INIT);
536 m_pRuntimeFunctionLookupSection = NewVirtualSection(pTextSection, IBCProfiledSection | WarmRange | ColdRange | RuntimeFunctionSection, sizeof(DWORD));
537 #if !defined(FEATURE_EH_FUNCLETS)
538 m_pRuntimeFunctionSection = NewVirtualSection(pTextSection, IBCProfiledSection | WarmRange | ColdRange | RuntimeFunctionSection, sizeof(DWORD));
540 // The following sentinel section is just a padding for RuntimeFunctionSection - Apply same classification
541 NewVirtualSection(pTextSection, IBCProfiledSection | WarmRange | ColdRange | RuntimeFunctionSection, sizeof(DWORD))
542 ->Place(new (GetHeap()) ZapBlobPtr((PVOID)&dwRuntimeFunctionSectionSentinel, sizeof(DWORD)));
544 m_pCodeMethodDescsSection = NewVirtualSection(pTextSection, IBCProfiledSection | WarmRange | ColdRange | CodeHeaderSection,sizeof(DWORD));
546 #ifdef FEATURE_READYTORUN_COMPILER
547 if (IsReadyToRunCompilation())
549 m_pAvailableTypesSection = NewVirtualSection(pTextSection, IBCUnProfiledSection | WarmRange | ReadonlySection);
550 m_pAttributePresenceSection = NewVirtualSection(pTextSection, IBCUnProfiledSection | WarmRange | ReadonlyDataSection, 16/* Must be 16 byte aligned */);
554 #if defined(FEATURE_EH_FUNCLETS)
555 m_pUnwindDataSection = NewVirtualSection(pTextSection, IBCProfiledSection | WarmRange | ColdRange | UnwindDataSection, sizeof(DWORD));
556 #endif // defined(FEATURE_EH_FUNCLETS)
558 m_pPreloadSections[CORCOMPILE_SECTION_READONLY_WARM] = NewVirtualSection(pTextSection, IBCProfiledSection | WarmRange | ReadonlySection, TARGET_POINTER_SIZE);
559 m_pPreloadSections[CORCOMPILE_SECTION_READONLY_VCHUNKS] = NewVirtualSection(pTextSection, IBCProfiledSection | WarmRange | ReadonlySection, TARGET_POINTER_SIZE);
560 m_pPreloadSections[CORCOMPILE_SECTION_READONLY_DICTIONARY] = NewVirtualSection(pTextSection, IBCProfiledSection | WarmRange | ReadonlySection, TARGET_POINTER_SIZE);
563 // GC Info for methods which were not touched in profiling
565 m_pGCSection = NewVirtualSection(pTextSection, IBCProfiledSection | ColdRange | GCInfoSection, sizeof(DWORD));
567 m_pDelayLoadInfoDelayListSectionCold = NewVirtualSection(pTextSection, IBCProfiledSection | ColdRange | DelayLoadInfoDelayListSection, sizeof(DWORD));
569 m_pPreloadSections[CORCOMPILE_SECTION_READONLY_COLD] = NewVirtualSection(pTextSection, IBCProfiledSection | ColdRange | ReadonlySection, TARGET_POINTER_SIZE);
572 // Allocate the cold code section near the end of the image
574 m_pColdCodeSection = NewVirtualSection(pTextSection, IBCProfiledSection | IBCUnProfiledSection | ColdRange | CodeSection, codeSectionAlign);
575 m_pColdCodeSection->SetDefaultFill(DEFAULT_CODE_BUFFER_INIT);
577 #if defined(TARGET_ARM)
578 // For ARM, put these sections more towards the end because bl/b instructions have limited displacement
581 m_pILSection = NewVirtualSection(pTextSection, IBCProfiledSection | HotColdSortedRange | ILSection, sizeof(DWORD));
583 //ILMetadata/Resources sections are reported as a statically known warm ranges for now.
584 m_pILMetaDataSection = NewVirtualSection(pTextSection, IBCProfiledSection | HotColdSortedRange | ILMetadataSection, sizeof(DWORD));
586 if (bigResourceSection) // for ARM, put the resource section at the end if it's very large - see comment above
587 m_pResourcesSection = NewVirtualSection(pTextSection, IBCUnProfiledSection | WarmRange | ResourcesSection);
589 m_pColdCodeMapSection = NewVirtualSection(pTextSection, IBCProfiledSection | IBCUnProfiledSection | ColdRange | CodeManagerSection, sizeof(DWORD));
591 #if !defined(FEATURE_EH_FUNCLETS)
592 m_pColdRuntimeFunctionSection = NewVirtualSection(pTextSection, IBCProfiledSection | IBCUnProfiledSection | ColdRange | RuntimeFunctionSection, sizeof(DWORD));
594 // The following sentinel section is just a padding for RuntimeFunctionSection - Apply same classification
595 NewVirtualSection(pTextSection, IBCProfiledSection | IBCUnProfiledSection | ColdRange | RuntimeFunctionSection, sizeof(DWORD))
596 ->Place(new (GetHeap()) ZapBlobPtr((PVOID)&dwRuntimeFunctionSectionSentinel, sizeof(DWORD)));
599 #if defined(FEATURE_EH_FUNCLETS)
600 m_pColdUnwindDataSection = NewVirtualSection(pTextSection, IBCProfiledSection | IBCUnProfiledSection | ColdRange | UnwindDataSection, sizeof(DWORD));
601 #endif // defined(FEATURE_EH_FUNCLETS)
604 // Allocate space for compressed LookupMaps (ridmaps). This needs to come after the .data physical
605 // section (which is currently true for the .text section) and late enough in the .text section to be
606 // after any structure referenced by the LookupMap (current MethodTables and MethodDescs). This is a
607 // hard requirement since the compression algorithm requires that all referenced data structures have
608 // been laid out by the time we come to lay out the compressed nodes.
610 m_pPreloadSections[CORCOMPILE_SECTION_COMPRESSED_MAPS] = NewVirtualSection(pTextSection, IBCProfiledSection | ColdRange | CompressedMapsSection, sizeof(DWORD));
612 m_pExceptionSection = NewVirtualSection(pTextSection, IBCProfiledSection | HotColdSortedRange | ExceptionSection, sizeof(DWORD));
615 // Debug info is sometimes used during exception handling to build stacktrace
617 m_pDebugSection = NewVirtualSection(pTextSection, IBCUnProfiledSection | ColdRange | DebugSection, sizeof(DWORD));
625 ZapPhysicalSection * pRelocSection = NewPhysicalSection(".reloc", IMAGE_SCN_CNT_INITIALIZED_DATA | IMAGE_SCN_MEM_DISCARDABLE | IMAGE_SCN_MEM_READ);
627 // .reloc section is always read by the OS when the image is opted in ASLR
628 // (Vista+ default behavior).
629 m_pBaseRelocsSection = NewVirtualSection(pRelocSection, IBCUnProfiledSection | HotRange | BaseRelocsSection);
634 void ZapImage::Preallocate()
636 COUNT_T cbILImage = m_ModuleDecoder.GetSize();
638 // Curb the estimate to handle corner cases gracefully
639 cbILImage = min(cbILImage, 50000000);
641 PREALLOCATE_HASHTABLE(ZapImage::m_CompiledMethods, 0.0050, cbILImage);
642 PREALLOCATE_HASHTABLE(ZapImage::m_ClassLayoutOrder, 0.0003, cbILImage);
645 // Preallocation of auxiliary tables in alphabetical order
647 m_pImportTable->Preallocate(cbILImage);
648 m_pInnerPtrs->Preallocate(cbILImage);
649 m_pMethodEntryPoints->Preallocate(cbILImage);
650 m_pWrappers->Preallocate(cbILImage);
652 if (m_pILMetaData != NULL)
653 m_pILMetaData->Preallocate(cbILImage);
654 m_pGCInfoTable->Preallocate(cbILImage);
655 #ifdef FEATURE_EH_FUNCLETS
656 m_pUnwindDataTable->Preallocate(cbILImage);
657 #endif // FEATURE_EH_FUNCLETS
658 m_pDebugInfoTable->Preallocate(cbILImage);
661 void ZapImage::SetVersionInfo(CORCOMPILE_VERSION_INFO * pVersionInfo)
663 m_pVersionInfo = new (GetHeap()) ZapVersionInfo(pVersionInfo);
664 m_pHeaderSection->Place(m_pVersionInfo);
667 void ZapImage::SetDependencies(CORCOMPILE_DEPENDENCY *pDependencies, DWORD cDependencies)
669 m_pDependencies = new (GetHeap()) ZapDependencies(pDependencies, cDependencies);
670 m_pHeaderSection->Place(m_pDependencies);
673 void ZapImage::SetPdbFileName(const SString &strFileName)
675 m_pdbFileName.Set(strFileName);
678 #ifdef FEATURE_EH_FUNCLETS
679 void ZapImage::SetRuntimeFunctionsDirectoryEntry()
682 // Runtime functions span multiple virtual sections and so there is no natural ZapNode * to cover them all.
683 // Create dummy ZapNode * that covers them all for IMAGE_DIRECTORY_ENTRY_EXCEPTION directory entry.
685 ZapVirtualSection * rgRuntimeFunctionSections[] = {
686 m_pHotRuntimeFunctionSection,
687 m_pRuntimeFunctionSection,
688 m_pColdRuntimeFunctionSection
691 DWORD dwTotalSize = 0, dwStartRVA = (DWORD)-1, dwEndRVA = 0;
693 for (size_t i = 0; i < _countof(rgRuntimeFunctionSections); i++)
695 ZapVirtualSection * pSection = rgRuntimeFunctionSections[i];
697 DWORD dwSize = pSection->GetSize();
701 DWORD dwRVA = pSection->GetRVA();
703 dwTotalSize += dwSize;
705 dwStartRVA = min(dwStartRVA, dwRVA);
706 dwEndRVA = max(dwEndRVA, dwRVA + dwSize);
709 if (dwTotalSize != 0)
711 // Verify that there are no holes between the sections
712 _ASSERTE(dwStartRVA + dwTotalSize == dwEndRVA);
714 ZapNode * pAllRuntimeFunctionSections = new (GetHeap()) ZapDummyNode(dwTotalSize);
715 pAllRuntimeFunctionSections->SetRVA(dwStartRVA);
717 // Write the address of the sorted pdata to the optionalHeader.DataDirectory
718 SetDirectoryEntry(IMAGE_DIRECTORY_ENTRY_EXCEPTION, pAllRuntimeFunctionSections);
721 #endif // FEATURE_EH_FUNCLETS
723 // Assign RVAs to all ZapNodes
724 void ZapImage::ComputeRVAs()
726 ZapWriter::ComputeRVAs();
728 if (!IsReadyToRunCompilation())
730 m_pMethodEntryPoints->Resolve();
731 m_pWrappers->Resolve();
734 m_pInnerPtrs->Resolve();
736 #ifdef FEATURE_EH_FUNCLETS
737 SetRuntimeFunctionsDirectoryEntry();
741 #ifdef FEATURE_SYMDIFF
742 if (CLRConfig::GetConfigValue(CLRConfig::INTERNAL_SymDiffDump))
744 COUNT_T curMethod = 0;
745 COUNT_T numMethods = m_MethodCompilationOrder.GetCount();
747 for (; curMethod < numMethods; curMethod++)
750 //if(curMethod >= m_iUntrainedMethod) fCold = true;
752 ZapMethodHeader * pMethod = m_MethodCompilationOrder[curMethod];
754 ZapBlobWithRelocs * pCode = fCold ? pMethod->m_pColdCode : pMethod->m_pCode;
759 CORINFO_METHOD_HANDLE handle = pMethod->GetHandle();
761 GetCompileInfo()->GetMethodDef(handle, &token);
762 GetSvcLogger()->Printf(W("(EntryPointRVAMap (MethodToken %0X) (RVA %0X) (SIZE %0X))\n"), token, pCode->GetRVA(), pCode->GetSize());
766 #endif // FEATURE_SYMDIFF
770 class ZapFileStream : public IStream
777 : m_hFile(INVALID_HANDLE_VALUE)
787 void SetHandle(HANDLE hFile)
789 _ASSERTE(m_hFile == INVALID_HANDLE_VALUE);
794 STDMETHODIMP_(ULONG) AddRef()
799 STDMETHODIMP_(ULONG) Release()
804 STDMETHODIMP QueryInterface(REFIID riid, LPVOID *ppv)
807 if (IsEqualIID(riid, IID_IUnknown) || IsEqualIID(riid, IID_IStream)) {
808 *ppv = static_cast<IStream *>(this);
816 // ISequentialStream methods:
817 STDMETHODIMP Read(void *pv, ULONG cb, ULONG *pcbRead)
823 STDMETHODIMP Write(void const *pv, ULONG cb, ULONG *pcbWritten)
827 _ASSERTE(m_hFile != INVALID_HANDLE_VALUE);
829 m_hasher.HashMore(pv, cb);
831 // We are calling with lpOverlapped == NULL so pcbWritten has to be present
832 // to prevent crashes in Win7 and below.
833 _ASSERTE(pcbWritten);
835 if (!::WriteFile(m_hFile, pv, cb, pcbWritten, NULL))
837 hr = HRESULT_FROM_GetLastError();
846 STDMETHODIMP Seek(LARGE_INTEGER dlibMove, DWORD dwOrigin, ULARGE_INTEGER *plibNewPosition)
850 _ASSERTE(m_hFile != INVALID_HANDLE_VALUE);
854 case STREAM_SEEK_SET:
855 dwFileOrigin = FILE_BEGIN;
858 case STREAM_SEEK_CUR:
859 dwFileOrigin = FILE_CURRENT;
862 case STREAM_SEEK_END:
863 dwFileOrigin = FILE_END;
870 if (!::SetFilePointerEx(m_hFile, dlibMove, (LARGE_INTEGER *)plibNewPosition, dwFileOrigin))
872 hr = HRESULT_FROM_GetLastError();
880 STDMETHODIMP SetSize(ULARGE_INTEGER libNewSize)
884 _ASSERTE(m_hFile != INVALID_HANDLE_VALUE);
886 hr = Seek(*(LARGE_INTEGER *)&libNewSize, FILE_BEGIN, NULL);
892 if (!::SetEndOfFile(m_hFile))
894 hr = HRESULT_FROM_GetLastError();
902 STDMETHODIMP CopyTo(IStream *pstm, ULARGE_INTEGER cb, ULARGE_INTEGER *pcbRead, ULARGE_INTEGER *pcbWritten)
908 STDMETHODIMP Commit(DWORD grfCommitFlags)
914 STDMETHODIMP Revert()
920 STDMETHODIMP LockRegion(ULARGE_INTEGER libOffset, ULARGE_INTEGER cb, DWORD dwLockType)
926 STDMETHODIMP UnlockRegion(ULARGE_INTEGER libOffset, ULARGE_INTEGER cb, DWORD dwLockType)
932 STDMETHODIMP Stat(STATSTG *pstatstg, DWORD grfStatFlag)
938 STDMETHODIMP Clone(IStream **ppIStream)
948 HANDLE hFile = m_hFile;
949 if (hFile != INVALID_HANDLE_VALUE)
951 m_hFile = INVALID_HANDLE_VALUE;
953 if (!::CloseHandle(hFile))
955 hr = HRESULT_FROM_GetLastError();
966 m_hFile = INVALID_HANDLE_VALUE;
969 void GetHash(MD5HASHDATA* pHash)
971 m_hasher.GetHashValue(pHash);
975 HANDLE ZapImage::GenerateFile(LPCWSTR wszOutputFileName, CORCOMPILE_NGEN_SIGNATURE * pNativeImageSig)
977 ZapFileStream outputStream;
979 HANDLE hFile = WszCreateFile(wszOutputFileName,
980 GENERIC_READ | GENERIC_WRITE,
981 FILE_SHARE_READ | FILE_SHARE_DELETE,
984 FILE_ATTRIBUTE_NORMAL | FILE_FLAG_SEQUENTIAL_SCAN,
987 if (hFile == INVALID_HANDLE_VALUE)
990 outputStream.SetHandle(hFile);
994 LARGE_INTEGER filePos;
996 if (m_pNativeHeader != NULL)
998 // Write back the updated CORCOMPILE_HEADER (relocs and guid is not correct the first time around)
999 filePos.QuadPart = m_pTextSection->GetFilePos() +
1000 (m_pNativeHeader->GetRVA() - m_pTextSection->GetRVA());
1001 IfFailThrow(outputStream.Seek(filePos, STREAM_SEEK_SET, NULL));
1002 m_pNativeHeader->Save(this);
1006 GUID signature = {0};
1008 static_assert_no_msg(sizeof(GUID) == sizeof(MD5HASHDATA));
1009 outputStream.GetHash((MD5HASHDATA*)&signature);
1012 // Write the debug directory entry for the NGEN PDB
1015 rsds.magic = VAL32(0x53445352); // "SDSR";
1017 // our PDB signature will be the same as our NGEN signature.
1018 // However we want the printed version of the GUID to be the same as the
1019 // byte dump of the signature so we swap bytes to make this work.
1021 // * See code:CCorSvcMgr::CreatePdb for where this is used.
1022 BYTE* asBytes = (BYTE*) &signature;
1023 rsds.signature.Data1 = ((asBytes[0] * 256 + asBytes[1]) * 256 + asBytes[2]) * 256 + asBytes[3];
1024 rsds.signature.Data2 = asBytes[4] * 256 + asBytes[5];
1025 rsds.signature.Data3 = asBytes[6] * 256 + asBytes[7];
1026 memcpy(&rsds.signature.Data4, &asBytes[8], 8);
1028 _ASSERTE(!m_pdbFileName.IsEmpty());
1029 ZeroMemory(&rsds.path[0], sizeof(rsds.path));
1030 if (WideCharToMultiByte(CP_UTF8,
1032 m_pdbFileName.GetUnicode(),
1033 m_pdbFileName.GetCount(),
1035 sizeof(rsds.path) - 1, // -1 to keep the buffer zero terminated
1040 ULONG cbWritten = 0;
1041 filePos.QuadPart = m_pTextSection->GetFilePos() + (m_pNGenPdbDebugData->GetRVA() - m_pTextSection->GetRVA());
1042 IfFailThrow(outputStream.Seek(filePos, STREAM_SEEK_SET, NULL));
1043 IfFailThrow(outputStream.Write(&rsds, sizeof rsds, &cbWritten));
1046 if (m_pVersionInfo != NULL)
1050 filePos.QuadPart = m_pTextSection->GetFilePos() +
1051 (m_pVersionInfo->GetRVA() - m_pTextSection->GetRVA()) +
1052 offsetof(CORCOMPILE_VERSION_INFO, signature);
1053 IfFailThrow(outputStream.Seek(filePos, STREAM_SEEK_SET, NULL));
1054 IfFailThrow(outputStream.Write(&signature, sizeof(signature), &cbWritten));
1056 if (pNativeImageSig != NULL)
1057 *pNativeImageSig = signature;
1061 _ASSERTE(pNativeImageSig == NULL);
1064 outputStream.SuppressClose();
1069 HANDLE ZapImage::SaveImage(LPCWSTR wszOutputFileName, LPCWSTR wszDllPath, CORCOMPILE_NGEN_SIGNATURE * pNativeImageSig)
1071 if(!IsReadyToRunCompilation() || IsLargeVersionBubbleEnabled())
1073 OutputManifestMetadata();
1078 // Create an empty export table. This makes tools like symchk not think
1079 // that native images are resource-only DLLs. It is important to NOT
1080 // be a resource-only DLL because those DLL's PDBS are not put up on the
1081 // symbol server and we want NGEN PDBS to be placed there.
1082 ZapPEExports* exports = new(GetHeap()) ZapPEExports(wszDllPath);
1083 m_pDebugSection->Place(exports);
1084 SetDirectoryEntry(IMAGE_DIRECTORY_ENTRY_EXPORT, exports);
1088 if (!IsReadyToRunCompilation())
1090 m_pPreloader->FixupRVAs();
1093 HANDLE hFile = GenerateFile(wszOutputFileName, pNativeImageSig);
1095 if (m_zapper->m_pOpt->m_verbose)
1097 PrintStats(wszOutputFileName);
1103 void ZapImage::PrintStats(LPCWSTR wszOutputFileName)
1105 #define ACCUM_SIZE(dest, src) if( src != NULL ) dest+= src->GetSize()
1106 ACCUM_SIZE(m_stats->m_gcInfoSize, m_pHotTouchedGCSection);
1107 ACCUM_SIZE(m_stats->m_gcInfoSize, m_pHotGCSection);
1108 ACCUM_SIZE(m_stats->m_gcInfoSize, m_pGCSection);
1109 #if defined(FEATURE_EH_FUNCLETS)
1110 ACCUM_SIZE(m_stats->m_unwindInfoSize, m_pUnwindDataSection);
1111 ACCUM_SIZE(m_stats->m_unwindInfoSize, m_pHotRuntimeFunctionSection);
1112 ACCUM_SIZE(m_stats->m_unwindInfoSize, m_pRuntimeFunctionSection);
1113 ACCUM_SIZE(m_stats->m_unwindInfoSize, m_pColdRuntimeFunctionSection);
1114 #endif // defined(FEATURE_EH_FUNCLETS)
1117 // Get the size of the input & output files
1121 WIN32_FIND_DATA inputData;
1122 FindHandleHolder inputHandle = WszFindFirstFile(m_pModuleFileName, &inputData);
1123 if (inputHandle != INVALID_HANDLE_VALUE)
1124 m_stats->m_inputFileSize = inputData.nFileSizeLow;
1128 WIN32_FIND_DATA outputData;
1129 FindHandleHolder outputHandle = WszFindFirstFile(wszOutputFileName, &outputData);
1130 if (outputHandle != INVALID_HANDLE_VALUE)
1131 m_stats->m_outputFileSize = outputData.nFileSizeLow;
1134 ACCUM_SIZE(m_stats->m_metadataSize, m_pAssemblyMetaData);
1136 DWORD dwPreloadSize = 0;
1137 for (int iSection = 0; iSection < CORCOMPILE_SECTION_COUNT; iSection++)
1138 ACCUM_SIZE(dwPreloadSize, m_pPreloadSections[iSection]);
1139 m_stats->m_preloadImageSize = dwPreloadSize;
1141 ACCUM_SIZE(m_stats->m_hotCodeMgrSize, m_pHotCodeMethodDescsSection);
1142 ACCUM_SIZE(m_stats->m_unprofiledCodeMgrSize, m_pCodeMethodDescsSection);
1143 ACCUM_SIZE(m_stats->m_coldCodeMgrSize, m_pHotRuntimeFunctionLookupSection);
1145 ACCUM_SIZE(m_stats->m_eeInfoTableSize, m_pEEInfoTable);
1146 ACCUM_SIZE(m_stats->m_helperTableSize, m_pHelperTableSection);
1147 ACCUM_SIZE(m_stats->m_dynamicInfoTableSize, m_pImportSectionsTable);
1149 ACCUM_SIZE(m_stats->m_dynamicInfoDelayListSize, m_pDelayLoadInfoDelayListSectionEager);
1150 ACCUM_SIZE(m_stats->m_dynamicInfoDelayListSize, m_pDelayLoadInfoDelayListSectionHot);
1151 ACCUM_SIZE(m_stats->m_dynamicInfoDelayListSize, m_pDelayLoadInfoDelayListSectionCold);
1153 ACCUM_SIZE(m_stats->m_debuggingTableSize, m_pDebugSection);
1154 ACCUM_SIZE(m_stats->m_headerSectionSize, m_pGCSection);
1155 ACCUM_SIZE(m_stats->m_codeSectionSize, m_pHotCodeSection);
1156 ACCUM_SIZE(m_stats->m_coldCodeSectionSize, m_pColdCodeSection);
1157 ACCUM_SIZE(m_stats->m_exceptionSectionSize, m_pExceptionSection);
1158 ACCUM_SIZE(m_stats->m_readOnlyDataSectionSize, m_pReadOnlyDataSection);
1159 ACCUM_SIZE(m_stats->m_relocSectionSize, m_pBaseRelocsSection);
1160 ACCUM_SIZE(m_stats->m_ILMetadataSize, m_pILMetaData);
1161 ACCUM_SIZE(m_stats->m_virtualImportThunkSize, m_pVirtualImportThunkSection);
1162 ACCUM_SIZE(m_stats->m_externalMethodThunkSize, m_pExternalMethodThunkSection);
1163 ACCUM_SIZE(m_stats->m_externalMethodDataSize, m_pExternalMethodDataSection);
1166 if (m_stats->m_failedMethods)
1167 m_zapper->Warning(W("Warning: %d methods (%d%%) could not be compiled.\n"),
1168 m_stats->m_failedMethods, (m_stats->m_failedMethods*100) / m_stats->m_methods);
1169 if (m_stats->m_failedILStubs)
1170 m_zapper->Warning(W("Warning: %d IL STUB methods could not be compiled.\n"),
1171 m_stats->m_failedMethods);
1172 m_stats->PrintStats();
1175 // Align native images to 64K
1176 const SIZE_T BASE_ADDRESS_ALIGNMENT = 0xffff;
1177 const double CODE_EXPANSION_FACTOR = 3.6;
1179 void ZapImage::CalculateZapBaseAddress()
1181 static SIZE_T nextBaseAddressForMultiModule;
1183 SIZE_T baseAddress = 0;
1186 // Read the actual preferred base address from the disk
1188 // Note that we are reopening the file here. We are not guaranteed to get the same file.
1189 // The worst thing that can happen is that we will read a bogus preferred base address from the file.
1190 HandleHolder hFile(WszCreateFile(m_pModuleFileName,
1192 FILE_SHARE_READ|FILE_SHARE_DELETE,
1195 FILE_ATTRIBUTE_NORMAL,
1197 if (hFile == INVALID_HANDLE_VALUE)
1200 HandleHolder hFileMap(WszCreateFileMapping(hFile, NULL, PAGE_READONLY, 0, 0, NULL));
1201 if (hFileMap == NULL)
1204 MapViewHolder base(MapViewOfFile(hFileMap, FILE_MAP_READ, 0, 0, 0));
1208 DWORD dwFileLen = SafeGetFileSize(hFile, 0);
1209 if (dwFileLen == INVALID_FILE_SIZE)
1212 PEDecoder peFlat((void *)base, (COUNT_T)dwFileLen);
1214 baseAddress = (SIZE_T) peFlat.GetPreferredBase();
1217 // See if the header has the linker's default preferred base address
1218 if (baseAddress == (SIZE_T) 0x00400000)
1220 if (m_fManifestModule)
1222 // Set the base address for the main assembly with the manifest
1224 if (!m_ModuleDecoder.IsDll())
1226 #if defined(TARGET_X86)
1227 // We use 30000000 for an exe
1228 baseAddress = 0x30000000;
1229 #elif defined(TARGET_64BIT)
1230 // We use 04000000 for an exe
1231 // which is remapped to 0x644`88000000 on x64
1232 baseAddress = 0x04000000;
1237 #if defined(TARGET_X86)
1238 // We start a 31000000 for the main assembly with the manifest
1239 baseAddress = 0x31000000;
1240 #elif defined(TARGET_64BIT)
1241 // We start a 05000000 for the main assembly with the manifest
1242 // which is remapped to 0x644`8A000000 on x64
1243 baseAddress = 0x05000000;
1247 else // is dependent assembly of a multi-module assembly
1249 // Set the base address for a dependent multi-module assembly
1251 // We should have already set the nextBaseAddressForMultiModule
1252 // when we compiled the manifest module
1253 _ASSERTE(nextBaseAddressForMultiModule != 0);
1254 baseAddress = nextBaseAddressForMultiModule;
1260 // For some assemblies we have to move the ngen image base address up
1261 // past the end of IL image so that that we don't have a conflict.
1263 // CoreCLR currently always loads both the IL and the native image, so
1264 // move the native image out of the way.
1266 baseAddress += m_ModuleDecoder.GetVirtualSize();
1270 if (m_zapper->GetCustomBaseAddress() != 0)
1272 //set baseAddress here from crossgen options
1273 baseAddress = m_zapper->GetCustomBaseAddress();
1276 // Round to a multiple of 64K
1277 // 64K is the allocation granularity of VirtualAlloc. (Officially this number is not a constant -
1278 // we should be querying the system for its allocation granularity, but we do this all over the place
1281 baseAddress = (baseAddress + BASE_ADDRESS_ALIGNMENT) & ~BASE_ADDRESS_ALIGNMENT;
1284 // Calculate the nextBaseAddressForMultiModule
1286 SIZE_T tempBaseAddress = baseAddress;
1287 tempBaseAddress += (SIZE_T) (CODE_EXPANSION_FACTOR * (double) m_ModuleDecoder.GetVirtualSize());
1288 tempBaseAddress += BASE_ADDRESS_ALIGNMENT;
1289 tempBaseAddress = (tempBaseAddress + BASE_ADDRESS_ALIGNMENT) & ~BASE_ADDRESS_ALIGNMENT;
1291 nextBaseAddressForMultiModule = tempBaseAddress;
1294 // Now we remap the 32-bit address range used for x86 and PE32 images into the
1295 // upper address range used on 64-bit platforms
1297 #if USE_UPPER_ADDRESS // Implies TARGET_64BIT
1298 if (baseAddress < 0x80000000)
1300 if (baseAddress < 0x40000000)
1301 baseAddress += 0x40000000; // We map [00000000..3fffffff] to [644'80000000..644'ffffffff]
1303 baseAddress -= 0x40000000; // We map [40000000..7fffffff] to [644'00000000..644'7fffffff]
1305 baseAddress *= UPPER_ADDRESS_MAPPING_FACTOR;
1306 baseAddress += CLR_UPPER_ADDRESS_MIN;
1310 // Apply the calculated base address.
1311 SetBaseAddress(baseAddress);
1313 m_NativeBaseAddress = baseAddress;
1316 void ZapImage::Open(CORINFO_MODULE_HANDLE hModule,
1317 IMetaDataAssemblyEmit *pEmit)
1319 m_hModule = hModule;
1320 m_fManifestModule = (hModule == m_zapper->m_pEECompileInfo->GetAssemblyModule(m_zapper->m_hAssembly));
1322 m_ModuleDecoder = *m_zapper->m_pEECompileInfo->GetModuleDecoder(hModule);
1326 // Get file name, and base address from module
1329 StackSString moduleFileName;
1330 m_zapper->m_pEECompileInfo->GetModuleFileName(hModule, moduleFileName);
1332 DWORD fileNameLength = moduleFileName.GetCount();
1333 m_pModuleFileName = new WCHAR[fileNameLength+1];
1334 wcscpy_s(m_pModuleFileName, fileNameLength+1, moduleFileName.GetUnicode());
1337 // Load the IBC Profile data for the assembly if it exists
1342 // Get metadata of module to be compiled
1344 m_pMDImport = m_zapper->m_pEECompileInfo->GetModuleMetaDataImport(m_hModule);
1345 _ASSERTE(m_pMDImport != NULL);
1348 // Open new assembly metadata data for writing. We may not use it,
1349 // if so we'll just discard it at the end.
1354 m_pAssemblyEmit = pEmit;
1358 // Hardwire the metadata version to be the current runtime version so that the ngen image
1359 // does not change when the directory runtime is installed in different directory (e.g. v2.0.x86chk vs. v2.0.80826).
1360 BSTRHolder strVersion(SysAllocString(CLR_METADATA_VERSION_L));
1361 VARIANT versionOption;
1362 V_VT(&versionOption) = VT_BSTR;
1363 V_BSTR(&versionOption) = strVersion;
1364 IfFailThrow(m_zapper->m_pMetaDataDispenser->SetOption(MetaDataRuntimeVersion, &versionOption));
1366 IfFailThrow(m_zapper->m_pMetaDataDispenser->
1367 DefineScope(CLSID_CorMetaDataRuntime, 0, IID_IMetaDataAssemblyEmit,
1368 (IUnknown **) &m_pAssemblyEmit));
1371 #ifdef FEATURE_READYTORUN_COMPILER
1372 if (IsReadyToRunCompilation())
1374 InitializeSectionsForReadyToRun();
1379 InitializeSections();
1382 // Set the module base address for the ngen native image
1383 CalculateZapBaseAddress();
1390 // Load the module and populate all the data-structures
1393 void ZapImage::Preload()
1396 CorProfileData * pProfileData = NewProfileData();
1397 m_pPreloader = m_zapper->m_pEECompileInfo->PreloadModule(m_hModule, this, pProfileData);
1404 void ZapImage::LinkPreload()
1406 m_pPreloader->Link();
1409 void ZapImage::OutputManifestMetadata()
1412 // Write out manifest metadata
1416 // First, see if we have useful metadata to store
1419 BOOL fMetadata = FALSE;
1421 if (m_pAssemblyEmit != NULL)
1424 // We may have added some assembly refs for exports.
1427 NonVMComHolder<IMetaDataAssemblyImport> pAssemblyImport;
1428 IfFailThrow(m_pAssemblyEmit->QueryInterface(IID_IMetaDataAssemblyImport,
1429 (void **)&pAssemblyImport));
1431 NonVMComHolder<IMetaDataImport> pImport;
1432 IfFailThrow(m_pAssemblyEmit->QueryInterface(IID_IMetaDataImport,
1433 (void **)&pImport));
1437 IfFailThrow(pAssemblyImport->EnumAssemblyRefs(&hEnum, NULL, 0, &cRefs));
1438 IfFailThrow(pImport->CountEnum(hEnum, &cRefs));
1439 pImport->CloseEnum(hEnum);
1445 // If we are the main module, we have the assembly def for the zap file.
1449 if (pAssemblyImport->GetAssemblyFromScope(&a) == S_OK)
1455 // Metadata creates a new MVID for every instantiation.
1456 // However, we want the generated ngen image to always be the same
1457 // for the same input. So set the metadata MVID to NGEN_IMAGE_MVID.
1459 NonVMComHolder<IMDInternalEmit> pMDInternalEmit;
1460 IfFailThrow(m_pAssemblyEmit->QueryInterface(IID_IMDInternalEmit,
1461 (void**)&pMDInternalEmit));
1463 IfFailThrow(pMDInternalEmit->ChangeMvid(NGEN_IMAGE_MVID));
1465 m_pAssemblyMetaData = new (GetHeap()) ZapMetaData();
1466 m_pAssemblyMetaData->SetMetaData(m_pAssemblyEmit);
1468 m_pMetaDataSection->Place(m_pAssemblyMetaData);
1472 void ZapImage::OutputTables()
1475 // Copy over any resources to the native image
1479 PVOID resource = (PVOID)m_ModuleDecoder.GetResources(&size);
1483 m_pResources = new (GetHeap()) ZapBlobPtr(resource, size);
1484 m_pResourcesSection->Place(m_pResources);
1487 CopyDebugDirEntry();
1488 CopyWin32Resources();
1490 if (m_pILMetaData != NULL)
1492 m_pILMetaData->CopyIL();
1493 m_pILMetaData->CopyMetaData();
1496 if (IsReadyToRunCompilation())
1498 m_pILMetaData->CopyRVAFields();
1501 // Copy over the timestamp from IL image for determinism
1502 SetTimeDateStamp(m_ModuleDecoder.GetTimeDateStamp());
1504 SetSubsystem(m_ModuleDecoder.GetSubsystem());
1507 USHORT dllCharacteristics = 0;
1509 #ifndef TARGET_64BIT
1510 dllCharacteristics |= IMAGE_DLLCHARACTERISTICS_NO_SEH;
1514 // Images without NX compat bit set fail to load on ARM
1515 dllCharacteristics |= IMAGE_DLLCHARACTERISTICS_NX_COMPAT;
1518 // Copy over selected DLL characteristics bits from IL image
1519 dllCharacteristics |= (m_ModuleDecoder.GetDllCharacteristics() &
1520 (IMAGE_DLLCHARACTERISTICS_NX_COMPAT | IMAGE_DLLCHARACTERISTICS_TERMINAL_SERVER_AWARE | IMAGE_DLLCHARACTERISTICS_APPCONTAINER));
1523 if (0 == CLRConfig::GetConfigValue(CLRConfig::INTERNAL_NoASLRForNgen))
1526 dllCharacteristics |= IMAGE_DLLCHARACTERISTICS_DYNAMIC_BASE;
1528 // Large address aware, required for High Entry VA, is always enabled for 64bit native images.
1529 dllCharacteristics |= IMAGE_DLLCHARACTERISTICS_HIGH_ENTROPY_VA;
1533 SetDllCharacteristics(dllCharacteristics);
1536 if (IsReadyToRunCompilation())
1539 SetSizeOfStackReserve(m_ModuleDecoder.GetSizeOfStackReserve());
1540 SetSizeOfStackCommit(m_ModuleDecoder.GetSizeOfStackCommit());
1543 #if defined(TARGET_UNIX) && !defined(TARGET_64BIT)
1544 // To minimize wasted VA space on 32-bit systems, align file to page boundaries (presumed to be 4K).
1545 SetFileAlignment(0x1000);
1546 #elif defined(TARGET_ARM) && defined(FEATURE_CORESYSTEM)
1547 if (!IsReadyToRunCompilation())
1549 // On ARM CoreSys builds, crossgen will use 4k file alignment, as requested by Phone perf team
1550 // to improve perf on phones with compressed system partitions.
1551 SetFileAlignment(0x1000);
1556 ZapImage::CompileStatus ZapImage::CompileProfileDataWorker(mdToken token, unsigned methodProfilingDataFlags)
1558 if ((TypeFromToken(token) != mdtMethodDef) ||
1559 (!m_pMDImport->IsValidToken(token)))
1561 m_zapper->Info(W("Warning: Invalid method token %08x in profile data.\n"), token);
1562 return NOT_COMPILED;
1566 static ConfigDWORD g_NgenOrder;
1568 if ((g_NgenOrder.val(CLRConfig::INTERNAL_NgenOrder) & 2) == 2)
1570 const ProfileDataHashEntry * foundEntry = profileDataHashTable.LookupPtr(token);
1572 if (foundEntry == NULL)
1573 return NOT_COMPILED;
1575 // The md must match.
1576 _ASSERTE(foundEntry->md == token);
1577 // The target position cannot be 0.
1578 _ASSERTE(foundEntry->pos > 0);
1582 // Now compile the method
1583 return TryCompileMethodDef(token, methodProfilingDataFlags);
1586 // ProfileDisableInlining
1587 // Before we start compiling any methods we may need to suppress the inlining
1588 // of certain methods based upon our profile data.
1589 // This method will arrange to disable this inlining.
1591 void ZapImage::ProfileDisableInlining()
1593 // We suppress the inlining of any Hot methods that have the ExcludeHotMethodCode flag.
1594 // We want such methods to be Jitted at runtime rather than compiled in the AOT native image.
1595 // The inlining of such a method also need to be suppressed.
1597 ProfileDataSection* methodProfileData = &(m_profileDataSections[MethodProfilingData]);
1598 if (methodProfileData->tableSize > 0)
1600 for (DWORD i = 0; i < methodProfileData->tableSize; i++)
1602 CORBBTPROF_TOKEN_INFO * pTokenInfo = &(methodProfileData->pTable[i]);
1603 unsigned methodProfilingDataFlags = pTokenInfo->flags;
1605 // Hot methods can be marked to be excluded from the AOT native image.
1606 // We also need to disable inlining of such methods.
1608 if ((methodProfilingDataFlags & (1 << DisableInlining)) != 0)
1610 // Disable the inlining of this method
1612 // @ToDo: Figure out how to disable inlining for this method.
1619 // Performs the compilation and placement for all methods in the "Hot" code region
1620 // Methods placed in this region typically correspond to all of the methods that were
1621 // executed during any of the profiling scenarios.
1623 void ZapImage::CompileHotRegion()
1625 // Compile all of the methods that were executed during profiling into the "Hot" code region.
1627 BeginRegion(CORINFO_REGION_HOT);
1629 CorProfileData* pProfileData = GetProfileData();
1631 ProfileDataSection* methodProfileData = &(m_profileDataSections[MethodProfilingData]);
1632 if (methodProfileData->tableSize > 0)
1634 // record the start of hot IBC methods.
1635 m_iIBCMethod = m_MethodCompilationOrder.GetCount();
1638 // Compile the hot methods in the order specified in the MethodProfilingData
1640 for (DWORD i = 0; i < methodProfileData->tableSize; i++)
1642 CompileStatus compileResult = NOT_COMPILED;
1643 CORBBTPROF_TOKEN_INFO * pTokenInfo = &(methodProfileData->pTable[i]);
1645 mdToken token = pTokenInfo->token;
1646 unsigned methodProfilingDataFlags = pTokenInfo->flags;
1647 _ASSERTE(methodProfilingDataFlags != 0);
1649 if (TypeFromToken(token) == mdtMethodDef)
1652 // Compile a non-generic method
1654 compileResult = CompileProfileDataWorker(token, methodProfilingDataFlags);
1656 else if (TypeFromToken(token) == ibcMethodSpec)
1659 // Compile a generic/parameterized method
1661 CORBBTPROF_BLOB_PARAM_SIG_ENTRY *pBlobSigEntry = pProfileData->GetBlobSigEntry(token);
1663 if (pBlobSigEntry == NULL)
1665 m_zapper->Info(W("Warning: Did not find definition for method token %08x in profile data.\n"), token);
1667 else // (pBlobSigEntry != NULL)
1669 _ASSERTE(pBlobSigEntry->blob.token == token);
1671 // decode method desc
1672 CORINFO_METHOD_HANDLE pMethod = m_pPreloader->FindMethodForProfileEntry(pBlobSigEntry);
1676 m_pPreloader->AddMethodToTransitiveClosureOfInstantiations(pMethod);
1678 compileResult = TryCompileInstantiatedMethod(pMethod, methodProfilingDataFlags);
1682 // This generic/parameterized method is not part of the native image
1683 // Either the IBC type specified no longer exists or it is a SIMD types
1684 // or the type can't be loaded in a ReadyToRun native image because of
1685 // a cross-module type dependencies.
1687 compileResult = COMPILE_EXCLUDED;
1692 // Update the 'flags' and 'compileResult' saved in the profileDataHashTable hash table.
1694 hashBBUpdateFlagsAndCompileResult(token, methodProfilingDataFlags, compileResult);
1696 // record the start of hot Generics methods.
1697 m_iGenericsMethod = m_MethodCompilationOrder.GetCount();
1700 // record the start of untrained code
1701 m_iUntrainedMethod = m_MethodCompilationOrder.GetCount();
1703 EndRegion(CORINFO_REGION_HOT);
1706 // CompileColdRegion
1707 // Performs the compilation and placement for all methods in the "Cold" code region
1708 // Methods placed in this region typically correspond to all of the methods that were
1709 // NOT executed during any of the profiling scenarios.
1711 void ZapImage::CompileColdRegion()
1713 // Compile all of the methods that were NOT executed during profiling into the "Cold" code region.
1716 BeginRegion(CORINFO_REGION_COLD);
1718 IMDInternalImport * pMDImport = m_pMDImport;
1720 HENUMInternalHolder hEnum(pMDImport);
1721 hEnum.EnumAllInit(mdtMethodDef);
1724 while (pMDImport->EnumNext(&hEnum, &md))
1727 // Compile the remaining methods that weren't compiled during the CompileHotRegion phase
1729 TryCompileMethodDef(md, 0);
1732 // Compile any generic code which lands in this LoaderModule
1733 // that resulted from the above compilations
1734 CORINFO_METHOD_HANDLE handle = m_pPreloader->NextUncompiledMethod();
1735 while (handle != NULL)
1737 TryCompileInstantiatedMethod(handle, 0);
1738 handle = m_pPreloader->NextUncompiledMethod();
1741 EndRegion(CORINFO_REGION_COLD);
1745 // Copy the IL for all method into the AOT native image
1747 void ZapImage::PlaceMethodIL()
1749 // Place the IL for all of the methods
1751 IMDInternalImport * pMDImport = m_pMDImport;
1752 HENUMInternalHolder hEnum(pMDImport);
1753 hEnum.EnumAllInit(mdtMethodDef);
1756 while (pMDImport->EnumNext(&hEnum, &md))
1758 if (m_pILMetaData != NULL)
1760 // Copy IL for all methods. We treat errors during copying IL
1761 // over as fatal error. These errors are typically caused by
1762 // corrupted IL images.
1764 m_pILMetaData->EmitMethodIL(md);
1769 void ZapImage::Compile()
1772 // Compile all of the methods for our AOT native image
1775 bool doNothingNgen = false;
1777 static ConfigDWORD fDoNothingNGen;
1778 doNothingNgen = !!fDoNothingNGen.val(CLRConfig::INTERNAL_ZapDoNothing);
1781 ProfileDisableInlining();
1787 CompileColdRegion();
1792 // Compute a preferred class layout order based on analyzing the graph
1793 // of which classes contain calls to other classes.
1794 ComputeClassLayoutOrder();
1796 // Sort the unprofiled methods by this preferred class layout, if available
1797 if (m_fHasClassLayoutOrder)
1799 SortUnprofiledMethodsByClassLayoutOrder();
1802 if (IsReadyToRunCompilation())
1804 // Pretend that no methods are trained, so that everything is in single code section
1805 // READYTORUN: FUTURE: More than one code section
1806 m_iUntrainedMethod = 0;
1809 OutputCode(ProfiledHot);
1810 OutputCode(Unprofiled);
1811 OutputCode(ProfiledCold);
1813 OutputCodeInfo(ProfiledHot);
1814 OutputCodeInfo(ProfiledCold); // actually both Unprofiled and ProfiledCold
1817 OutputProfileData();
1819 #ifdef FEATURE_READYTORUN_COMPILER
1820 if (IsReadyToRunCompilation())
1822 OutputEntrypointsTableForReadyToRun();
1823 OutputDebugInfoForReadyToRun();
1824 OutputTypesTableForReadyToRun(m_pMDImport);
1825 OutputAttributePresenceFilter(m_pMDImport);
1826 OutputInliningTableForReadyToRun();
1827 OutputProfileDataForReadyToRun();
1828 if (IsLargeVersionBubbleEnabled())
1830 OutputManifestMetadataForReadyToRun();
1840 struct CompileMethodStubContext
1843 unsigned methodProfilingDataFlags;
1844 ZapImage::CompileStatus enumCompileStubResult;
1846 CompileMethodStubContext(ZapImage * _image, unsigned _methodProfilingDataFlags)
1849 methodProfilingDataFlags = _methodProfilingDataFlags;
1850 enumCompileStubResult = ZapImage::NOT_COMPILED;
1854 //-----------------------------------------------------------------------------
1855 // This method is a callback function use to compile any IL_STUBS that are
1856 // associated with a normal IL method. It is called from CompileMethodStubIfNeeded
1857 // via the function pointer stored in the CompileMethodStubContext.
1858 // It handles the temporary change to the m_compilerFlags and removes any flags
1859 // that we don't want set when compiling IL_STUBS.
1860 //-----------------------------------------------------------------------------
1862 // static void __stdcall
1863 void ZapImage::TryCompileMethodStub(LPVOID pContext, CORINFO_METHOD_HANDLE hStub, CORJIT_FLAGS jitFlags)
1865 STANDARD_VM_CONTRACT;
1867 // The caller must always set the IL_STUB flag
1868 _ASSERTE(jitFlags.IsSet(CORJIT_FLAGS::CORJIT_FLAG_IL_STUB));
1870 CompileMethodStubContext *pCompileContext = reinterpret_cast<CompileMethodStubContext *>(pContext);
1871 ZapImage *pImage = pCompileContext->pImage;
1873 CORJIT_FLAGS oldFlags = pImage->m_zapper->m_pOpt->m_compilerFlags;
1875 CORJIT_FLAGS* pCompilerFlags = &pImage->m_zapper->m_pOpt->m_compilerFlags;
1876 pCompilerFlags->Add(jitFlags);
1877 pCompilerFlags->Clear(CORJIT_FLAGS::CORJIT_FLAG_PROF_ENTERLEAVE);
1878 pCompilerFlags->Clear(CORJIT_FLAGS::CORJIT_FLAG_DEBUG_CODE);
1879 pCompilerFlags->Clear(CORJIT_FLAGS::CORJIT_FLAG_DEBUG_EnC);
1880 pCompilerFlags->Clear(CORJIT_FLAGS::CORJIT_FLAG_DEBUG_INFO);
1882 mdMethodDef md = mdMethodDefNil;
1884 pCompileContext->enumCompileStubResult = pImage->TryCompileMethodWorker(hStub, md,
1885 pCompileContext->methodProfilingDataFlags);
1887 pImage->m_zapper->m_pOpt->m_compilerFlags = oldFlags;
1890 //-----------------------------------------------------------------------------
1891 // Helper for ZapImage::TryCompileMethodDef that indicates whether a given method def token refers to a
1892 // "vtable gap" method. These are pseudo-methods used to lay out the vtable for COM interop and as such don't
1893 // have any associated code (or even a method handle).
1894 //-----------------------------------------------------------------------------
1895 BOOL ZapImage::IsVTableGapMethod(mdMethodDef md)
1900 // Get method attributes and check that RTSpecialName was set for the method (this means the name has
1901 // semantic import to the runtime and must be formatted rigorously with one of a few well-known rules).
1902 // Note that we just return false on any failure path since this will just lead to our caller continuing
1903 // to throw the exception they were about to anyway.
1904 hr = m_pMDImport->GetMethodDefProps(md, &dwAttributes);
1905 if (FAILED(hr) || !IsMdRTSpecialName(dwAttributes))
1908 // Now check the name of the method. All vtable gap methods will have a prefix of "_VtblGap".
1910 PCCOR_SIGNATURE pvSigBlob;
1912 hr = m_pMDImport->GetNameAndSigOfMethodDef(md, &pvSigBlob, &cbSigBlob, &szMethod);
1913 if (FAILED(hr) || (strncmp(szMethod, "_VtblGap", 8) != 0))
1916 // If we make it to here we have a vtable gap method.
1920 //-----------------------------------------------------------------------------
1921 // This function is called for non-generic methods in the current assembly,
1922 // and for the typical "System.__Canon" instantiations of generic methods
1923 // in the current assembly.
1924 //-----------------------------------------------------------------------------
1926 ZapImage::CompileStatus ZapImage::TryCompileMethodDef(mdMethodDef md, unsigned methodProfilingDataFlags)
1928 _ASSERTE(!IsNilToken(md));
1930 CORINFO_METHOD_HANDLE handle = NULL;
1931 CompileStatus result = NOT_COMPILED;
1933 if (ShouldCompileMethodDef(md))
1935 handle = m_pPreloader->LookupMethodDef(md);
1936 if (handle == nullptr)
1938 result = LOOKUP_FAILED;
1943 result = COMPILE_EXCLUDED;
1949 // compile the method
1951 CompileStatus methodCompileStatus = TryCompileMethodWorker(handle, md, methodProfilingDataFlags);
1953 // Don't bother compiling the IL_STUBS if we failed to compile the parent IL method
1955 if (methodCompileStatus == COMPILE_SUCCEED)
1957 CompileMethodStubContext context(this, methodProfilingDataFlags);
1959 // compile stubs associated with the method
1960 m_pPreloader->GenerateMethodStubs(handle, m_zapper->m_pOpt->m_ngenProfileImage,
1961 &TryCompileMethodStub,
1965 return methodCompileStatus;
1969 //-----------------------------------------------------------------------------
1970 // This function is called for non-"System.__Canon" instantiations of generic methods.
1971 // These could be methods defined in other assemblies too.
1972 //-----------------------------------------------------------------------------
1974 ZapImage::CompileStatus ZapImage::TryCompileInstantiatedMethod(CORINFO_METHOD_HANDLE handle,
1975 unsigned methodProfilingDataFlags)
1977 if (IsReadyToRunCompilation())
1979 if (!GetCompileInfo()->IsInCurrentVersionBubble(m_zapper->m_pEEJitInfo->getMethodModule(handle)))
1980 return COMPILE_EXCLUDED;
1983 if (!ShouldCompileInstantiatedMethod(handle))
1984 return COMPILE_EXCLUDED;
1986 // If we compiling this method because it was specified by the IBC profile data
1987 // then issue a warning if this method is not on our uncompiled method list.
1989 if (methodProfilingDataFlags != 0)
1991 if (methodProfilingDataFlags & (1 << ReadMethodCode))
1993 // When we have stale IBC data the method could have been rejected from this image.
1994 if (!m_pPreloader->IsUncompiledMethod(handle))
1996 const char* szClsName;
1997 const char* szMethodName = m_zapper->m_pEEJitInfo->getMethodName(handle, &szClsName);
1999 SString fullname(SString::Utf8, szClsName);
2000 fullname.AppendUTF8(NAMESPACE_SEPARATOR_STR);
2001 fullname.AppendUTF8(szMethodName);
2003 m_zapper->Info(W("Warning: Invalid method instantiation in profile data: %s\n"), fullname.GetUnicode());
2005 return NOT_COMPILED;
2010 CompileStatus methodCompileStatus = TryCompileMethodWorker(handle, mdMethodDefNil, methodProfilingDataFlags);
2012 // Don't bother compiling the IL_STUBS if we failed to compile the parent IL method
2014 if (methodCompileStatus == COMPILE_SUCCEED)
2016 CompileMethodStubContext context(this, methodProfilingDataFlags);
2018 // compile stubs associated with the method
2019 m_pPreloader->GenerateMethodStubs(handle, m_zapper->m_pOpt->m_ngenProfileImage,
2020 &TryCompileMethodStub,
2024 return methodCompileStatus;
2027 //-----------------------------------------------------------------------------
2029 ZapImage::CompileStatus ZapImage::TryCompileMethodWorker(CORINFO_METHOD_HANDLE handle, mdMethodDef md,
2030 unsigned methodProfilingDataFlags)
2032 _ASSERTE(handle != NULL);
2034 if (m_zapper->m_pOpt->m_onlyOneMethod && (m_zapper->m_pOpt->m_onlyOneMethod != md))
2035 return NOT_COMPILED;
2037 if (GetCompileInfo()->HasCustomAttribute(handle, "System.Runtime.BypassNGenAttribute"))
2038 return NOT_COMPILED;
2040 #ifdef FEATURE_READYTORUN_COMPILER
2041 // This is a quick workaround to opt specific methods out of ReadyToRun compilation to work around bugs.
2042 if (IsReadyToRunCompilation())
2044 if (GetCompileInfo()->HasCustomAttribute(handle, "System.Runtime.BypassReadyToRunAttribute"))
2045 return NOT_COMPILED;
2049 // Do we have a profile entry for this method?
2051 if (methodProfilingDataFlags != 0)
2053 // Report the profiling data flags for layout of the EE data structures
2054 m_pPreloader->SetMethodProfilingFlags(handle, methodProfilingDataFlags);
2056 // Hot methods can be marked to be excluded from the AOT native image.
2057 // A Jitted method executes faster than a ReadyToRun compiled method.
2059 if ((methodProfilingDataFlags & (1 << ExcludeHotMethodCode)) != 0)
2061 // returning COMPILE_HOT_EXCLUDED excludes this method from the AOT native image
2062 return COMPILE_HOT_EXCLUDED;
2065 // Cold methods can be marked to be excluded from the AOT native image.
2066 // We can reduce the size of the AOT native image by selectively
2067 // excluding the code for some of the cold methods.
2069 if ((methodProfilingDataFlags & (1 << ExcludeColdMethodCode)) != 0)
2071 // returning COMPILE_COLD_EXCLUDED excludes this method from the AOT native image
2072 return COMPILE_COLD_EXCLUDED;
2075 // If the code was never executed based on the profile data
2076 // then don't compile this method now. Wait until later
2077 // when we are compiling the methods in the cold section.
2079 if ((methodProfilingDataFlags & (1 << ReadMethodCode)) == 0)
2081 // returning NOT_COMPILED will defer until later the compilation of this method
2082 return NOT_COMPILED;
2085 else // we are compiling methods for the cold region
2087 // Retrieve any information that we have about a previous compilation attempt of this method
2088 const ProfileDataHashEntry* pEntry = profileDataHashTable.LookupPtr(md);
2090 // When Partial Ngen is specified we will omit the AOT native code for every
2091 // method that does not have profile data
2093 if (pEntry == nullptr && m_zapper->m_pOpt->m_fPartialNGen)
2095 // returning COMPILE_COLD_EXCLUDED excludes this method from the AOT native image
2096 return COMPILE_COLD_EXCLUDED;
2099 if (pEntry != nullptr)
2101 if ((pEntry->status == COMPILE_HOT_EXCLUDED) || (pEntry->status == COMPILE_COLD_EXCLUDED))
2103 // returning COMPILE_HOT_EXCLUDED excludes this method from the AOT native image
2104 return pEntry->status;
2109 // Have we already compiled it?
2110 if (GetCompiledMethod(handle) != NULL)
2111 return ALREADY_COMPILED;
2113 _ASSERTE(m_zapper->m_pOpt->m_compilerFlags.IsSet(CORJIT_FLAGS::CORJIT_FLAG_IL_STUB) || IsNilToken(md) || handle == m_pPreloader->LookupMethodDef(md));
2115 CompileStatus result = NOT_COMPILED;
2117 CORINFO_MODULE_HANDLE module;
2119 // We only compile IL_STUBs from the current assembly
2120 if (m_zapper->m_pOpt->m_compilerFlags.IsSet(CORJIT_FLAGS::CORJIT_FLAG_IL_STUB))
2123 module = m_zapper->m_pEEJitInfo->getMethodModule(handle);
2125 ZapInfo zapInfo(this, md, handle, module, methodProfilingDataFlags);
2129 zapInfo.CompileMethod();
2130 result = COMPILE_SUCCEED;
2134 // Continue unwinding if fatal error was hit.
2135 if (FAILED(g_hrFatalError))
2136 ThrowHR(g_hrFatalError);
2138 Exception *ex = GET_EXCEPTION();
2139 HRESULT hrException = ex->GetHR();
2141 CorZapLogLevel level;
2143 #ifdef CROSSGEN_COMPILE
2144 // Warnings should not go to stderr during crossgen
2145 level = CORZAP_LOGLEVEL_WARNING;
2147 level = CORZAP_LOGLEVEL_ERROR;
2149 m_zapper->m_failed = TRUE;
2152 result = COMPILE_FAILED;
2154 #ifdef FEATURE_READYTORUN_COMPILER
2155 // NYI features in R2R - Stop crossgen from spitting unnecessary
2156 // messages to the console
2157 if (IsReadyToRunCompilation())
2159 // When compiling the method, we may receive an exception when the
2160 // method uses a feature that is Not Implemented for ReadyToRun
2161 // or a Type Load exception if the method uses a SIMD type.
2163 // We skip the compilation of such methods and we don't want to
2164 // issue a warning or error
2166 if ((hrException == E_NOTIMPL) || (hrException == (HRESULT)IDS_CLASSLOAD_GENERAL))
2168 result = NOT_COMPILED;
2169 level = CORZAP_LOGLEVEL_INFO;
2174 StackSString message;
2175 ex->GetMessage(message);
2177 // FileNotFound errors here can be converted into a single error string per ngen compile,
2178 // and the detailed error is available with verbose logging
2179 if (hrException == COR_E_FILENOTFOUND)
2181 StackSString logMessage(W("System.IO.FileNotFoundException: "));
2182 logMessage.Append(message);
2183 FileNotFoundError(logMessage.GetUnicode());
2184 level = CORZAP_LOGLEVEL_INFO;
2187 m_zapper->Print(level, W("%s while compiling method %s\n"), message.GetUnicode(), zapInfo.m_currentMethodName.GetUnicode());
2189 if ((result == COMPILE_FAILED) && (m_stats != NULL))
2191 if (!m_zapper->m_pOpt->m_compilerFlags.IsSet(CORJIT_FLAGS::CORJIT_FLAG_IL_STUB))
2192 m_stats->m_failedMethods++;
2194 m_stats->m_failedILStubs++;
2198 EX_END_CATCH(SwallowAllExceptions);
2204 // Should we compile this method, defined in the ngen'ing module?
2205 // Result is FALSE if any of the controls (only used by prejit.exe) exclude the method
2206 BOOL ZapImage::ShouldCompileMethodDef(mdMethodDef md)
2208 DWORD partialNGenStressVal = PartialNGenStressPercentage();
2209 if (partialNGenStressVal)
2211 _ASSERTE(partialNGenStressVal <= 100);
2212 DWORD methodPercentageVal = (md % 100) + 1;
2213 if (methodPercentageVal <= partialNGenStressVal)
2218 IfFailThrow(m_pMDImport->GetParentToken(md, &td));
2220 #ifdef FEATURE_COMINTEROP
2222 if (td != mdTypeDefNil)
2224 IfFailThrow(m_pMDImport->GetTypeDefProps(td, NULL, &tkExtends));
2226 mdAssembly tkAssembly;
2227 DWORD dwAssemblyFlags;
2229 IfFailThrow(m_pMDImport->GetAssemblyFromScope(&tkAssembly));
2230 if (TypeFromToken(tkAssembly) == mdtAssembly)
2232 IfFailThrow(m_pMDImport->GetAssemblyProps(tkAssembly,
2233 NULL, NULL, // Public Key
2234 NULL, // Hash Algorithm
2239 if (IsAfContentType_WindowsRuntime(dwAssemblyFlags))
2241 if (TypeFromToken(tkExtends) == mdtTypeRef)
2243 LPCSTR szNameSpace = NULL;
2244 LPCSTR szName = NULL;
2245 IfFailThrow(m_pMDImport->GetNameOfTypeRef(tkExtends, &szNameSpace, &szName));
2247 if (!strcmp(szNameSpace, "System") && !_stricmp((szName), "Attribute"))
2258 static ConfigMethodSet fZapOnly;
2259 fZapOnly.ensureInit(CLRConfig::INTERNAL_ZapOnly);
2261 static ConfigMethodSet fZapExclude;
2262 fZapExclude.ensureInit(CLRConfig::INTERNAL_ZapExclude);
2264 PCCOR_SIGNATURE pvSigBlob;
2267 // Get the name of the current method and its class
2269 IfFailThrow(m_pMDImport->GetNameAndSigOfMethodDef(md, &pvSigBlob, &cbSigBlob, &szMethod));
2271 LPCWSTR wszClass = W("");
2274 if (td != mdTypeDefNil)
2276 LPCSTR szNameSpace = NULL;
2277 LPCSTR szName = NULL;
2279 IfFailThrow(m_pMDImport->GetNameOfTypeDef(td, &szName, &szNameSpace));
2281 const SString nameSpace(SString::Utf8, szNameSpace);
2282 const SString name(SString::Utf8, szName);
2283 sClass.MakeFullNamespacePath(nameSpace, name);
2284 wszClass = sClass.GetUnicode();
2287 MAKE_UTF8PTR_FROMWIDE(szClass, wszClass);
2289 if (!fZapOnly.isEmpty() && !fZapOnly.contains(szMethod, szClass, pvSigBlob))
2291 LOG((LF_ZAP, LL_INFO1000, "Rejecting compilation of method %08x, %s::%s\n", md, szClass, szMethod));
2295 if (fZapExclude.contains(szMethod, szClass, pvSigBlob))
2297 LOG((LF_ZAP, LL_INFO1000, "Rejecting compilation of method %08x, %s::%s\n", md, szClass, szMethod));
2301 LOG((LF_ZAP, LL_INFO1000, "Compiling method %08x, %s::%s\n", md, szClass, szMethod));
2308 BOOL ZapImage::ShouldCompileInstantiatedMethod(CORINFO_METHOD_HANDLE handle)
2310 DWORD partialNGenStressVal = PartialNGenStressPercentage();
2311 if (partialNGenStressVal)
2313 _ASSERTE(partialNGenStressVal <= 100);
2314 DWORD methodPercentageVal = (m_zapper->m_pEEJitInfo->getMethodHash(handle) % 100) + 1;
2315 if (methodPercentageVal <= partialNGenStressVal)
2322 HRESULT ZapImage::PrintTokenDescription(CorZapLogLevel level, mdToken token)
2326 if (RidFromToken(token) == 0)
2329 LPCSTR szNameSpace = NULL;
2330 LPCSTR szName = NULL;
2332 if (m_pMDImport->IsValidToken(token))
2334 switch (TypeFromToken(token))
2339 IfFailRet(m_pMDImport->GetParentOfMemberRef(token, &parent));
2340 if (RidFromToken(parent) != 0)
2342 PrintTokenDescription(level, parent);
2343 m_zapper->Print(level, W("."));
2345 IfFailRet(m_pMDImport->GetNameAndSigOfMemberRef(token, NULL, NULL, &szName));
2352 IfFailRet(m_pMDImport->GetParentToken(token, &parent));
2353 if (RidFromToken(parent) != 0)
2355 PrintTokenDescription(level, parent);
2356 m_zapper->Print(level, W("."));
2358 IfFailRet(m_pMDImport->GetNameOfMethodDef(token, &szName));
2364 IfFailRet(m_pMDImport->GetNameOfTypeRef(token, &szNameSpace, &szName));
2370 IfFailRet(m_pMDImport->GetNameOfTypeDef(token, &szName, &szNameSpace));
2380 szName = "InvalidToken";
2385 if (szNameSpace != NULL)
2387 const SString nameSpace(SString::Utf8, szNameSpace);
2388 const SString name(SString::Utf8, szName);
2389 fullName.MakeFullNamespacePath(nameSpace, name);
2393 fullName.SetUTF8(szName);
2396 m_zapper->Print(level, W("%s"), fullName.GetUnicode());
2402 HRESULT ZapImage::LocateProfileData()
2404 if (m_zapper->m_pOpt->m_ignoreProfileData)
2410 // In the past, we have ignored profile data when instrumenting the assembly.
2411 // However, this creates significant differences between the tuning image and the eventual
2412 // optimized image (e.g. generic instantiations) which in turn leads to missed data during
2413 // training and cold touches during execution. Instead, we take advantage of any IBC data
2414 // the assembly already has and attempt to make the tuning image as close as possible to
2418 if (m_zapper->m_pOpt->m_compilerFlags.IsSet(CORJIT_FLAGS::CORJIT_FLAG_BBINSTR))
2423 // See if there's profile data in the resource section of the PE
2425 m_pRawProfileData = (BYTE*)m_ModuleDecoder.GetWin32Resource(W("PROFILE_DATA"), W("IBC"), &m_cRawProfileData);
2427 if ((m_pRawProfileData != NULL) && (m_cRawProfileData != 0))
2429 m_zapper->Info(W("Found embedded profile resource in %s.\n"), m_pModuleFileName);
2433 static ConfigDWORD g_UseIBCFile;
2434 if (g_UseIBCFile.val(CLRConfig::EXTERNAL_UseIBCFile) != 1)
2438 // Couldn't find profile resource--let's see if there's an ibc file to use instead
2443 LPWSTR ibcDir = CLRConfig::GetConfigValue(CLRConfig::EXTERNAL_IBCFileDir);
2446 LPCWSTR moduleFileName = wcsrchr(m_pModuleFileName, DIRECTORY_SEPARATOR_CHAR_W);
2448 path.Append(DIRECTORY_SEPARATOR_CHAR_W);
2449 path.Append(moduleFileName);
2453 path.Set(m_pModuleFileName); // the same directory as the IL dll
2456 SString::Iterator dot = path.End();
2457 if (path.FindBack(dot, '.'))
2459 SString slName(SString::Literal, "ibc");
2460 path.Replace(dot+1, path.End() - (dot+1), slName);
2462 HandleHolder hFile = WszCreateFile(path.GetUnicode(),
2467 FILE_ATTRIBUTE_NORMAL | FILE_FLAG_SEQUENTIAL_SCAN,
2469 if (hFile != INVALID_HANDLE_VALUE)
2471 HandleHolder hMapFile = WszCreateFileMapping(hFile, NULL, PAGE_READONLY, 0, 0, NULL);
2472 DWORD dwFileLen = SafeGetFileSize(hFile, 0);
2473 if (dwFileLen != INVALID_FILE_SIZE)
2475 if (hMapFile == NULL)
2477 m_zapper->Warning(W("Found profile data file %s, but could not open it"), path.GetUnicode());
2481 m_zapper->Info(W("Found ibc file %s.\n"), path.GetUnicode());
2483 m_profileDataFile = (BYTE*) MapViewOfFile(hMapFile, FILE_MAP_READ, 0, 0, 0);
2485 m_pRawProfileData = m_profileDataFile;
2486 m_cRawProfileData = dwFileLen;
2496 bool ZapImage::CanConvertIbcData()
2498 static ConfigDWORD g_iConvertIbcData;
2499 DWORD val = g_iConvertIbcData.val(CLRConfig::UNSUPPORTED_ConvertIbcData);
2503 HRESULT ZapImage::parseProfileData()
2505 if (m_pRawProfileData == NULL)
2510 ProfileReader profileReader(m_pRawProfileData, m_cRawProfileData);
2512 CORBBTPROF_FILE_HEADER *fileHeader;
2514 READ(fileHeader, CORBBTPROF_FILE_HEADER);
2515 if (fileHeader->HeaderSize < sizeof(CORBBTPROF_FILE_HEADER))
2517 _ASSERTE(!"HeaderSize is too small");
2521 // Read any extra header data. It will be needed for V3 files.
2523 DWORD extraHeaderDataSize = fileHeader->HeaderSize - sizeof(CORBBTPROF_FILE_HEADER);
2524 void *extraHeaderData = profileReader.Read(extraHeaderDataSize);
2526 bool convertFromV1 = false;
2527 bool minified = false;
2529 if (fileHeader->Magic != CORBBTPROF_MAGIC)
2531 _ASSERTE(!"ibcHeader contains bad values");
2535 // CoreCLR should never be presented with V1 IBC data.
2536 if (fileHeader->Version == CORBBTPROF_V3_VERSION)
2538 CORBBTPROF_FILE_OPTIONAL_HEADER *optionalHeader =
2539 (CORBBTPROF_FILE_OPTIONAL_HEADER *)extraHeaderData;
2541 if (!optionalHeader ||
2542 !CONTAINS_FIELD(optionalHeader, extraHeaderDataSize, Size) ||
2543 (optionalHeader->Size > extraHeaderDataSize))
2545 m_zapper->Info(W("Optional header missing or corrupt."));
2549 if (CONTAINS_FIELD(optionalHeader, optionalHeader->Size, FileFlags))
2551 minified = !!(optionalHeader->FileFlags & CORBBTPROF_FILE_FLAG_MINIFIED);
2553 if (!m_zapper->m_pOpt->m_fPartialNGenSet)
2555 m_zapper->m_pOpt->m_fPartialNGen = !!(optionalHeader->FileFlags & CORBBTPROF_FILE_FLAG_PARTIAL_NGEN);
2559 else if (fileHeader->Version != CORBBTPROF_V2_VERSION)
2561 m_zapper->Info(W("Discarding profile data with unknown version."));
2565 // This module has profile data (this ends up controlling the layout of physical and virtual
2566 // sections within the image, see ZapImage::AllocateVirtualSections.
2567 m_fHaveProfileData = true;
2568 m_zapper->m_pOpt->m_fHasAnyProfileData = true;
2570 CORBBTPROF_SECTION_TABLE_HEADER *sectionHeader;
2571 READ(sectionHeader, CORBBTPROF_SECTION_TABLE_HEADER);
2574 // Parse the section table
2577 for (ULONG i = 0; i < sectionHeader->NumEntries; i++)
2579 CORBBTPROF_SECTION_TABLE_ENTRY *entry;
2580 READ(entry,CORBBTPROF_SECTION_TABLE_ENTRY);
2582 SectionFormat format = sectionHeader->Entries[i].FormatID;
2583 _ASSERTE(format >= 0);
2591 if (format < LastTokenFlagSection)
2593 format = (SectionFormat) (format + 1);
2597 _ASSERTE(format < SectionFormatCount);
2599 if (format < SectionFormatCount)
2601 BYTE *start = m_pRawProfileData + sectionHeader->Entries[i].Data.Offset;
2602 BYTE *end = start + sectionHeader->Entries[i].Data.Size;
2604 if ((start > m_pRawProfileData) &&
2605 (end < m_pRawProfileData + m_cRawProfileData) &&
2608 _ASSERTE(m_profileDataSections[format].pData == 0);
2609 _ASSERTE(m_profileDataSections[format].dataSize == 0);
2611 m_profileDataSections[format].pData = start;
2612 m_profileDataSections[format].dataSize = (DWORD) (end - start);
2616 _ASSERTE(!"Invalid profile section offset or size");
2626 hr = convertProfileDataFromV1();
2634 hr = RehydrateProfileData();
2643 // For those sections that are collections of tokens, further parse that format to get
2644 // the token pointer and number of tokens
2647 for (int format = FirstTokenFlagSection; format < SectionFormatCount; format++)
2649 if (m_profileDataSections[format].pData)
2651 SEEK(((ULONG) (m_profileDataSections[format].pData - m_pRawProfileData)));
2653 CORBBTPROF_TOKEN_LIST_SECTION_HEADER *header;
2654 READ(header, CORBBTPROF_TOKEN_LIST_SECTION_HEADER);
2656 DWORD tableSize = header->NumTokens;
2657 DWORD dataSize = (m_profileDataSections[format].dataSize - sizeof(CORBBTPROF_TOKEN_LIST_SECTION_HEADER));
2658 DWORD expectedSize = tableSize * sizeof (CORBBTPROF_TOKEN_INFO);
2660 if (dataSize == expectedSize)
2662 BYTE * startOfTable = m_profileDataSections[format].pData + sizeof(CORBBTPROF_TOKEN_LIST_SECTION_HEADER);
2663 m_profileDataSections[format].tableSize = tableSize;
2664 m_profileDataSections[format].pTable = (CORBBTPROF_TOKEN_INFO *) startOfTable;
2668 _ASSERTE(!"Invalid CORBBTPROF_TOKEN_LIST_SECTION_HEADER header");
2675 ZapImage::ProfileDataSection * DataSection_ScenarioInfo = & m_profileDataSections[ScenarioInfo];
2676 if (DataSection_ScenarioInfo->pData != NULL)
2678 CORBBTPROF_SCENARIO_INFO_SECTION_HEADER * header = (CORBBTPROF_SCENARIO_INFO_SECTION_HEADER *) DataSection_ScenarioInfo->pData;
2679 m_profileDataNumRuns = header->TotalNumRuns;
2686 HRESULT ZapImage::convertProfileDataFromV1()
2688 if (m_pRawProfileData == NULL)
2694 // For those sections that are collections of tokens, further parse that format to get
2695 // the token pointer and number of tokens
2698 ProfileReader profileReader(m_pRawProfileData, m_cRawProfileData);
2700 for (SectionFormat format = FirstTokenFlagSection; format < SectionFormatCount; format = (SectionFormat) (format + 1))
2702 if (m_profileDataSections[format].pData)
2704 SEEK(((ULONG) (m_profileDataSections[format].pData - m_pRawProfileData)));
2706 CORBBTPROF_TOKEN_LIST_SECTION_HEADER *header;
2707 READ(header, CORBBTPROF_TOKEN_LIST_SECTION_HEADER);
2709 DWORD tableSize = header->NumTokens;
2713 m_profileDataSections[format].tableSize = 0;
2714 m_profileDataSections[format].pTable = NULL;
2718 DWORD dataSize = (m_profileDataSections[format].dataSize - sizeof(CORBBTPROF_TOKEN_LIST_SECTION_HEADER));
2719 DWORD expectedSize = tableSize * sizeof (CORBBTPROF_TOKEN_LIST_ENTRY_V1);
2721 if (dataSize == expectedSize)
2723 DWORD newDataSize = tableSize * sizeof (CORBBTPROF_TOKEN_INFO);
2725 if (newDataSize < dataSize)
2728 BYTE * startOfTable = new (GetHeap()) BYTE[newDataSize];
2730 CORBBTPROF_TOKEN_LIST_ENTRY_V1 * pOldEntry;
2731 CORBBTPROF_TOKEN_INFO * pNewEntry;
2733 pOldEntry = (CORBBTPROF_TOKEN_LIST_ENTRY_V1 *) (m_profileDataSections[format].pData + sizeof(CORBBTPROF_TOKEN_LIST_SECTION_HEADER));
2734 pNewEntry = (CORBBTPROF_TOKEN_INFO *) startOfTable;
2736 for (DWORD i=0; i<tableSize; i++)
2738 pNewEntry->token = pOldEntry->token;
2739 pNewEntry->flags = pOldEntry->flags;
2740 pNewEntry->scenarios = 1;
2745 m_profileDataSections[format].tableSize = tableSize;
2746 m_profileDataSections[format].pTable = (CORBBTPROF_TOKEN_INFO *) startOfTable;
2750 _ASSERTE(!"Invalid CORBBTPROF_TOKEN_LIST_SECTION_HEADER header");
2756 _ASSERTE(m_profileDataSections[ScenarioInfo].pData == 0);
2757 _ASSERTE(m_profileDataSections[ScenarioInfo].dataSize == 0);
2760 // Convert the MethodBlockCounts format from V1 to V2
2762 CORBBTPROF_METHOD_BLOCK_COUNTS_SECTION_HEADER_V1 * mbcSectionHeader = NULL;
2763 if (m_profileDataSections[MethodBlockCounts].pData)
2766 // Compute the size of the method block count stream
2768 BYTE * dstPtr = NULL;
2769 BYTE * srcPtr = m_profileDataSections[MethodBlockCounts].pData;
2770 DWORD maxSizeToRead = m_profileDataSections[MethodBlockCounts].dataSize;
2771 DWORD totalSizeNeeded = 0;
2772 DWORD totalSizeRead = 0;
2774 mbcSectionHeader = (CORBBTPROF_METHOD_BLOCK_COUNTS_SECTION_HEADER_V1 *) srcPtr;
2776 totalSizeRead += sizeof(CORBBTPROF_METHOD_BLOCK_COUNTS_SECTION_HEADER_V1);
2777 totalSizeNeeded += sizeof(CORBBTPROF_METHOD_BLOCK_COUNTS_SECTION_HEADER);
2778 srcPtr += sizeof(CORBBTPROF_METHOD_BLOCK_COUNTS_SECTION_HEADER_V1);
2780 if (totalSizeRead > maxSizeToRead)
2785 for (DWORD i=0; (i < mbcSectionHeader->NumMethods); i++)
2787 CORBBTPROF_METHOD_HEADER_V1* methodEntry = (CORBBTPROF_METHOD_HEADER_V1 *) srcPtr;
2789 DWORD sizeWrite = 0;
2791 sizeRead += methodEntry->HeaderSize;
2792 sizeRead += methodEntry->Size;
2793 sizeWrite += sizeof(CORBBTPROF_METHOD_HEADER);
2794 sizeWrite += methodEntry->Size;
2796 totalSizeRead += sizeRead;
2797 totalSizeNeeded += sizeWrite;
2799 if (totalSizeRead > maxSizeToRead)
2806 assert(totalSizeRead == maxSizeToRead);
2809 srcPtr = m_profileDataSections[MethodBlockCounts].pData;
2811 BYTE * newMethodData = new (GetHeap()) BYTE[totalSizeNeeded];
2813 dstPtr = newMethodData;
2815 memcpy(dstPtr, srcPtr, sizeof(CORBBTPROF_METHOD_BLOCK_COUNTS_SECTION_HEADER));
2816 srcPtr += sizeof(CORBBTPROF_METHOD_BLOCK_COUNTS_SECTION_HEADER_V1);
2817 dstPtr += sizeof(CORBBTPROF_METHOD_BLOCK_COUNTS_SECTION_HEADER);
2819 for (DWORD i=0; (i < mbcSectionHeader->NumMethods); i++)
2821 CORBBTPROF_METHOD_HEADER_V1 * methodEntryV1 = (CORBBTPROF_METHOD_HEADER_V1 *) srcPtr;
2822 CORBBTPROF_METHOD_HEADER * methodEntry = (CORBBTPROF_METHOD_HEADER *) dstPtr;
2824 DWORD sizeWrite = 0;
2826 methodEntry->method.token = methodEntryV1->MethodToken;
2827 methodEntry->method.ILSize = 0;
2828 methodEntry->method.cBlock = (methodEntryV1->Size / sizeof(CORBBTPROF_BLOCK_DATA));
2829 sizeRead += methodEntryV1->HeaderSize;
2830 sizeWrite += sizeof(CORBBTPROF_METHOD_HEADER);
2832 memcpy( dstPtr + sizeof(CORBBTPROF_METHOD_HEADER),
2833 srcPtr + sizeof(CORBBTPROF_METHOD_HEADER_V1),
2834 (methodEntry->method.cBlock * sizeof(CORBBTPROF_BLOCK_DATA)));
2835 sizeRead += methodEntryV1->Size;
2836 sizeWrite += (methodEntry->method.cBlock * sizeof(CORBBTPROF_BLOCK_DATA));
2838 methodEntry->size = sizeWrite;
2839 methodEntry->cDetail = 0;
2841 dstPtr += sizeWrite;
2844 m_profileDataSections[MethodBlockCounts].pData = newMethodData;
2845 m_profileDataSections[MethodBlockCounts].dataSize = totalSizeNeeded;
2849 // Allocate the scenario info section
2852 DWORD sizeNeeded = sizeof(CORBBTPROF_SCENARIO_INFO_SECTION_HEADER) + sizeof(CORBBTPROF_SCENARIO_HEADER);
2853 BYTE * newData = new (GetHeap()) BYTE[sizeNeeded];
2854 BYTE * dstPtr = newData;
2856 CORBBTPROF_SCENARIO_INFO_SECTION_HEADER *siHeader = (CORBBTPROF_SCENARIO_INFO_SECTION_HEADER *) dstPtr;
2858 if (mbcSectionHeader != NULL)
2859 siHeader->TotalNumRuns = mbcSectionHeader->NumRuns;
2861 siHeader->TotalNumRuns = 1;
2863 siHeader->NumScenarios = 1;
2865 dstPtr += sizeof(CORBBTPROF_SCENARIO_INFO_SECTION_HEADER);
2868 CORBBTPROF_SCENARIO_HEADER *sHeader = (CORBBTPROF_SCENARIO_HEADER *) dstPtr;
2870 sHeader->scenario.ordinal = 1;
2871 sHeader->scenario.mask = 1;
2872 sHeader->scenario.priority = 0;
2873 sHeader->scenario.numRuns = 0;
2874 sHeader->scenario.cName = 0;
2876 sHeader->size = sHeader->Size();
2878 dstPtr += sizeof(CORBBTPROF_SCENARIO_HEADER);
2880 m_profileDataSections[ScenarioInfo].pData = newData;
2881 m_profileDataSections[ScenarioInfo].dataSize = sizeNeeded;
2885 // Convert the BlobStream format from V1 to V2
2887 if (m_profileDataSections[BlobStream].dataSize > 0)
2890 // Compute the size of the blob stream
2893 BYTE * srcPtr = m_profileDataSections[BlobStream].pData;
2894 BYTE * dstPtr = NULL;
2895 DWORD maxSizeToRead = m_profileDataSections[BlobStream].dataSize;
2896 DWORD totalSizeNeeded = 0;
2897 DWORD totalSizeRead = 0;
2902 CORBBTPROF_BLOB_ENTRY_V1* blobEntry = (CORBBTPROF_BLOB_ENTRY_V1 *) srcPtr;
2903 DWORD sizeWrite = 0;
2906 if ((blobEntry->blobType >= MetadataStringPool) && (blobEntry->blobType <= MetadataUserStringPool))
2908 sizeWrite += sizeof(CORBBTPROF_BLOB_POOL_ENTRY);
2909 sizeWrite += blobEntry->cBuffer;
2910 sizeRead += sizeof(CORBBTPROF_BLOB_ENTRY_V1);
2911 sizeRead += blobEntry->cBuffer;
2913 else if ((blobEntry->blobType >= ParamTypeSpec) && (blobEntry->blobType <= ParamMethodSpec))
2915 sizeWrite += sizeof(CORBBTPROF_BLOB_PARAM_SIG_ENTRY);
2916 sizeWrite += blobEntry->cBuffer;
2917 if (blobEntry->blobType == ParamMethodSpec)
2919 sizeWrite -= 1; // Adjust for ENCODE_METHOD_SIG prefix removal
2921 sizeRead += sizeof(CORBBTPROF_BLOB_ENTRY_V1);
2922 sizeRead += blobEntry->cBuffer;
2924 else if (blobEntry->blobType == EndOfBlobStream)
2926 sizeWrite += sizeof(CORBBTPROF_BLOB_ENTRY);
2927 sizeRead += sizeof(CORBBTPROF_BLOB_ENTRY_V1);
2935 totalSizeNeeded += sizeWrite;
2936 totalSizeRead += sizeRead;
2938 if (sizeRead > maxSizeToRead)
2946 assert(totalSizeRead == maxSizeToRead);
2949 srcPtr = m_profileDataSections[BlobStream].pData;
2951 BYTE * newBlobData = new (GetHeap()) BYTE[totalSizeNeeded];
2953 dstPtr = newBlobData;
2958 CORBBTPROF_BLOB_ENTRY_V1* blobEntryV1 = (CORBBTPROF_BLOB_ENTRY_V1 *) srcPtr;
2959 DWORD sizeWrite = 0;
2962 if ((blobEntryV1->blobType >= MetadataStringPool) && (blobEntryV1->blobType <= MetadataUserStringPool))
2964 CORBBTPROF_BLOB_POOL_ENTRY* blobPoolEntry = (CORBBTPROF_BLOB_POOL_ENTRY*) dstPtr;
2966 blobPoolEntry->blob.type = blobEntryV1->blobType;
2967 blobPoolEntry->blob.size = sizeof(CORBBTPROF_BLOB_POOL_ENTRY) + blobEntryV1->cBuffer;
2968 blobPoolEntry->cBuffer = blobEntryV1->cBuffer;
2969 memcpy(blobPoolEntry->buffer, blobEntryV1->pBuffer, blobEntryV1->cBuffer);
2971 sizeWrite += sizeof(CORBBTPROF_BLOB_POOL_ENTRY);
2972 sizeWrite += blobEntryV1->cBuffer;
2973 sizeRead += sizeof(CORBBTPROF_BLOB_ENTRY_V1);
2974 sizeRead += blobEntryV1->cBuffer;
2976 else if ((blobEntryV1->blobType >= ParamTypeSpec) && (blobEntryV1->blobType <= ParamMethodSpec))
2978 CORBBTPROF_BLOB_PARAM_SIG_ENTRY* blobSigEntry = (CORBBTPROF_BLOB_PARAM_SIG_ENTRY*) dstPtr;
2980 blobSigEntry->blob.type = blobEntryV1->blobType;
2981 blobSigEntry->blob.size = sizeof(CORBBTPROF_BLOB_PARAM_SIG_ENTRY) + blobEntryV1->cBuffer;
2982 blobSigEntry->blob.token = 0;
2983 blobSigEntry->cSig = blobEntryV1->cBuffer;
2985 if (blobEntryV1->blobType == ParamMethodSpec)
2987 // Adjust cSig and blob.size
2988 blobSigEntry->cSig--;
2989 blobSigEntry->blob.size--;
2991 memcpy(blobSigEntry->sig, blobEntryV1->pBuffer, blobSigEntry->cSig);
2993 sizeWrite += sizeof(CORBBTPROF_BLOB_PARAM_SIG_ENTRY);
2994 sizeWrite += blobSigEntry->cSig;
2995 sizeRead += sizeof(CORBBTPROF_BLOB_ENTRY_V1);
2996 sizeRead += blobEntryV1->cBuffer;
2998 else if (blobEntryV1->blobType == EndOfBlobStream)
3000 CORBBTPROF_BLOB_ENTRY* blobEntry = (CORBBTPROF_BLOB_ENTRY*) dstPtr;
3002 blobEntry->type = blobEntryV1->blobType;
3003 blobEntry->size = sizeof(CORBBTPROF_BLOB_ENTRY);
3005 sizeWrite += sizeof(CORBBTPROF_BLOB_ENTRY);
3006 sizeRead += sizeof(CORBBTPROF_BLOB_ENTRY_V1);
3014 dstPtr += sizeWrite;
3017 m_profileDataSections[BlobStream].pData = newBlobData;
3018 m_profileDataSections[BlobStream].dataSize = totalSizeNeeded;
3022 m_profileDataSections[BlobStream].pData = NULL;
3023 m_profileDataSections[BlobStream].dataSize = 0;
3029 void ZapImage::RehydrateBasicBlockSection()
3031 ProfileDataSection §ion = m_profileDataSections[MethodBlockCounts];
3037 ProfileReader reader(section.pData, section.dataSize);
3039 m_profileDataNumRuns = reader.Read<unsigned int>();
3041 // The IBC data provides a hint to the number of basic blocks, which is
3042 // used here to determine how much space to allocate for the rehydrated
3044 unsigned int blockCountHint = reader.Read<unsigned int>();
3046 unsigned int numMethods = reader.Read<unsigned int>();
3048 unsigned int expectedLength =
3049 sizeof(CORBBTPROF_METHOD_BLOCK_COUNTS_SECTION_HEADER) +
3050 sizeof(CORBBTPROF_METHOD_HEADER) * numMethods +
3051 sizeof(CORBBTPROF_BLOCK_DATA) * blockCountHint;
3053 BinaryWriter writer(expectedLength, GetHeap());
3055 writer.Write(numMethods);
3057 mdToken lastMethodToken = 0x06000000;
3059 CORBBTPROF_METHOD_HEADER methodHeader;
3060 methodHeader.cDetail = 0;
3061 methodHeader.method.ILSize = 0;
3063 for (unsigned int i = 0; i < numMethods; ++i)
3065 // Translate the method header
3066 unsigned int size = reader.Read7BitEncodedInt();
3067 unsigned int startPosition = reader.GetCurrentPos();
3069 mdToken token = reader.ReadTokenWithMemory(lastMethodToken);
3070 unsigned int ilSize = reader.Read7BitEncodedInt();
3071 unsigned int firstBlockHitCount = reader.Read7BitEncodedInt();
3073 unsigned int numOtherBlocks = reader.Read7BitEncodedInt();
3075 methodHeader.method.cBlock = 1 + numOtherBlocks;
3076 methodHeader.method.token = token;
3077 methodHeader.method.ILSize = ilSize;
3078 methodHeader.size = (DWORD)methodHeader.Size();
3080 writer.Write(methodHeader);
3082 CORBBTPROF_BLOCK_DATA blockData;
3084 // The first block is handled specially.
3085 blockData.ILOffset = 0;
3086 blockData.ExecutionCount = firstBlockHitCount;
3088 writer.Write(blockData);
3090 // Translate the rest of the basic blocks
3091 for (unsigned int j = 0; j < numOtherBlocks; ++j)
3093 blockData.ILOffset = reader.Read7BitEncodedInt();
3094 blockData.ExecutionCount = reader.Read7BitEncodedInt();
3096 writer.Write(blockData);
3099 if (!reader.Seek(startPosition + size))
3105 // If the expected and actual lengths differ, the result will still be
3106 // correct but performance may suffer slightly because of reallocations.
3107 _ASSERTE(writer.GetWrittenSize() == expectedLength);
3109 section.pData = writer.GetBuffer();
3110 section.dataSize = writer.GetWrittenSize();
3113 void ZapImage::RehydrateTokenSection(int sectionFormat, unsigned int flagTable[255])
3115 ProfileDataSection §ion = m_profileDataSections[sectionFormat];
3116 ProfileReader reader(section.pData, section.dataSize);
3118 unsigned int numTokens = reader.Read<unsigned int>();
3120 unsigned int dataLength = sizeof(unsigned int) +
3121 numTokens * sizeof(CORBBTPROF_TOKEN_INFO);
3122 BinaryWriter writer(dataLength, GetHeap());
3124 writer.Write(numTokens);
3126 mdToken lastToken = (sectionFormat - FirstTokenFlagSection) << 24;
3128 CORBBTPROF_TOKEN_INFO tokenInfo;
3129 tokenInfo.scenarios = 1;
3131 for (unsigned int i = 0; i < numTokens; ++i)
3133 tokenInfo.token = reader.ReadTokenWithMemory(lastToken);
3134 tokenInfo.flags = reader.ReadFlagWithLookup(flagTable);
3136 writer.Write(tokenInfo);
3139 _ASSERTE(writer.GetWrittenSize() == dataLength);
3141 section.pData = writer.GetBuffer();
3142 section.dataSize = writer.GetWrittenSize();
3143 section.pTable = (CORBBTPROF_TOKEN_INFO *)(section.pData + sizeof(unsigned int));
3144 section.tableSize = numTokens;
3147 void ZapImage::RehydrateBlobStream()
3149 ProfileDataSection §ion = m_profileDataSections[BlobStream];
3151 ProfileReader reader(section.pData, section.dataSize);
3153 // Evidence suggests that rehydrating the blob stream in Framework binaries
3154 // increases the size from 1.5-2x. When this was written, 1.85x minimized
3155 // the amount of extra memory allocated (about 48K in the worst case).
3156 BinaryWriter writer((DWORD)(section.dataSize * 1.85f), GetHeap());
3158 mdToken LastBlobToken = 0;
3159 mdToken LastAssemblyToken = 0x23000000;
3160 mdToken LastExternalTypeToken = 0x62000000;
3161 mdToken LastExternalNamespaceToken = 0x61000000;
3162 mdToken LastExternalSignatureToken = 0x63000000;
3167 // Read the blob header.
3169 unsigned int sizeToRead = reader.Read7BitEncodedInt();
3170 unsigned int startPositionRead = reader.GetCurrentPos();
3172 blobType = reader.Read7BitEncodedInt();
3173 mdToken token = reader.ReadTokenWithMemory(LastBlobToken);
3175 // Write out the blob header.
3177 // Note the location in the write stream, and write a 0 there. Once
3178 // this blob has been written in its entirety, this location can be
3179 // used to calculate the real size and to go back to the right place
3182 unsigned int startPositionWrite = writer.GetWrittenSize();
3185 writer.Write(blobType);
3186 writer.Write(token);
3188 // All blobs (except the end-of-stream indicator) end as:
3189 // <data length> <data>
3190 // Two blob types (handled immediately below) include tokens as well.
3191 // Handle those first, then handle the common case.
3193 if (blobType == ExternalTypeDef)
3195 writer.Write(reader.ReadTokenWithMemory(LastAssemblyToken));
3196 writer.Write(reader.ReadTokenWithMemory(LastExternalTypeToken));
3197 writer.Write(reader.ReadTokenWithMemory(LastExternalNamespaceToken));
3199 else if (blobType == ExternalMethodDef)
3201 writer.Write(reader.ReadTokenWithMemory(LastExternalTypeToken));
3202 writer.Write(reader.ReadTokenWithMemory(LastExternalSignatureToken));
3205 if ((blobType >= MetadataStringPool) && (blobType < IllegalBlob))
3207 // This blob is of known type and ends with data.
3208 unsigned int dataLength = reader.Read7BitEncodedInt();
3209 char *data = (char *)reader.Read(dataLength);
3216 writer.Write(dataLength);
3217 writer.Write(data, dataLength);
3220 // Write the size for this blob.
3222 writer.WriteAt(startPositionWrite,
3223 writer.GetWrittenSize() - startPositionWrite);
3225 // Move to the next blob.
3227 if (!reader.Seek(startPositionRead + sizeToRead))
3232 while (blobType != EndOfBlobStream);
3234 section.pData = writer.GetBuffer();
3235 section.dataSize = writer.GetWrittenSize();
3238 HRESULT ZapImage::RehydrateProfileData()
3241 unsigned int flagTable[255];
3242 memset(flagTable, 0xFF, sizeof(flagTable));
3246 RehydrateBasicBlockSection();
3247 RehydrateBlobStream();
3248 for (int format = FirstTokenFlagSection;
3249 format < SectionFormatCount;
3252 if (m_profileDataSections[format].pData)
3254 RehydrateTokenSection(format, flagTable);
3258 EX_CATCH_HRESULT_NO_ERRORINFO(hr);
3263 HRESULT ZapImage::hashMethodBlockCounts()
3265 ProfileDataSection * DataSection_MethodBlockCounts = & m_profileDataSections[MethodBlockCounts];
3267 if (!DataSection_MethodBlockCounts->pData)
3272 ProfileReader profileReader(DataSection_MethodBlockCounts->pData, DataSection_MethodBlockCounts->dataSize);
3274 CORBBTPROF_METHOD_BLOCK_COUNTS_SECTION_HEADER *mbcHeader;
3275 READ(mbcHeader,CORBBTPROF_METHOD_BLOCK_COUNTS_SECTION_HEADER);
3277 for (DWORD i = 0; i < mbcHeader->NumMethods; i++)
3279 ProfileDataHashEntry newEntry;
3280 newEntry.pos = profileReader.GetCurrentPos();
3282 CORBBTPROF_METHOD_HEADER *methodHeader;
3283 READ(methodHeader,CORBBTPROF_METHOD_HEADER);
3284 newEntry.md = methodHeader->method.token;
3285 newEntry.size = methodHeader->size;
3287 newEntry.status = NOT_COMPILED;
3289 // Add the new entry to the table
3290 profileDataHashTable.Add(newEntry);
3292 // Skip the profileData so we can read the next method.
3294 READ_SIZE(profileData, void, (methodHeader->size - sizeof(CORBBTPROF_METHOD_HEADER)));
3300 void ZapImage::hashBBUpdateFlagsAndCompileResult(mdToken token, unsigned methodProfilingDataFlags, ZapImage::CompileStatus compileResult)
3302 // SHash only supports replacing an entry so we setup our newEntry and then perform a lookup
3304 ProfileDataHashEntry newEntry;
3305 newEntry.md = token;
3306 newEntry.flags = methodProfilingDataFlags;
3307 newEntry.status = compileResult;
3309 const ProfileDataHashEntry* pEntry = profileDataHashTable.LookupPtr(token);
3310 if (pEntry != nullptr)
3312 assert(pEntry->md == newEntry.md);
3313 assert(pEntry->flags == 0); // the flags should not be set at this point.
3315 // Copy and keep the two fields that were previously set
3316 newEntry.size = pEntry->size;
3317 newEntry.pos = pEntry->pos;
3319 else // We have a method that doesn't have basic block counts
3324 profileDataHashTable.AddOrReplace(newEntry);
3327 void ZapImage::LoadProfileData()
3329 HRESULT hr = E_FAIL;
3331 m_fHaveProfileData = false;
3332 m_pRawProfileData = NULL;
3333 m_cRawProfileData = 0;
3337 hr = LocateProfileData();
3341 hr = parseProfileData();
3344 hr = hashMethodBlockCounts();
3352 EX_END_CATCH(SwallowAllExceptions);
3356 m_fHaveProfileData = false;
3357 m_pRawProfileData = NULL;
3358 m_cRawProfileData = 0;
3362 m_zapper->Warning(W("Warning: Invalid profile data was ignored for %s\n"), m_pModuleFileName);
3366 #ifdef CROSSGEN_COMPILE
3367 if (m_zapper->m_pOpt->m_fPartialNGen && (m_pRawProfileData == NULL || m_cRawProfileData == 0))
3369 ThrowHR(CLR_E_CROSSGEN_NO_IBC_DATA_FOUND);
3374 // Initializes our form of the profile data stored in the assembly.
3376 CorProfileData * ZapImage::NewProfileData()
3378 this->m_pCorProfileData = new CorProfileData(&m_profileDataSections[0]);
3380 return this->m_pCorProfileData;
3383 // Returns the profile data stored in the assembly.
3385 CorProfileData * ZapImage::GetProfileData()
3387 _ASSERTE(this->m_pCorProfileData != NULL);
3389 return this->m_pCorProfileData;
3392 CorProfileData::CorProfileData(void * rawProfileData)
3394 ZapImage::ProfileDataSection * profileData = (ZapImage::ProfileDataSection *) rawProfileData;
3396 for (DWORD format = 0; format < SectionFormatCount; format++)
3398 this->profilingTokenFlagsData[format].count = profileData[format].tableSize;
3399 this->profilingTokenFlagsData[format].data = profileData[format].pTable;
3402 this->blobStream = (CORBBTPROF_BLOB_ENTRY *) profileData[BlobStream].pData;
3406 // Determines whether a method can be called directly from another method (without
3407 // going through the prestub) in the current module.
3408 // callerFtn=NULL implies any/unspecified caller in the current module.
3410 // Returns NULL if 'calleeFtn' cannot be called directly *at the current time*
3411 // Else returns the direct address that 'calleeFtn' can be called at.
3414 bool ZapImage::canIntraModuleDirectCall(
3415 CORINFO_METHOD_HANDLE callerFtn,
3416 CORINFO_METHOD_HANDLE targetFtn,
3417 CorInfoIndirectCallReason *pReason,
3418 CORINFO_ACCESS_FLAGS accessFlags/*=CORINFO_ACCESS_ANY*/)
3420 CorInfoIndirectCallReason reason;
3421 if (pReason == NULL)
3423 *pReason = CORINFO_INDIRECT_CALL_UNKNOWN;
3425 // The caller should have checked that the method is in current loader module
3426 _ASSERTE(m_hModule == m_zapper->m_pEECompileInfo->GetLoaderModuleForEmbeddableMethod(targetFtn));
3428 // No direct calls at all under some circumstances
3430 if (m_zapper->m_pOpt->m_compilerFlags.IsSet(CORJIT_FLAGS::CORJIT_FLAG_PROF_ENTERLEAVE)
3431 && !m_pPreloader->IsDynamicMethod(callerFtn))
3433 *pReason = CORINFO_INDIRECT_CALL_PROFILING;
3434 goto CALL_VIA_ENTRY_POINT;
3437 // Does the method's class have a cctor, etc?
3439 if (!m_pPreloader->CanSkipMethodPreparation(callerFtn, targetFtn, pReason, accessFlags))
3440 goto CALL_VIA_ENTRY_POINT;
3442 ZapMethodHeader * pMethod;
3443 pMethod = GetCompiledMethod(targetFtn);
3445 // If we have not compiled the method, then we can't call directly
3447 if (pMethod == NULL)
3449 *pReason = CORINFO_INDIRECT_CALL_NO_CODE;
3450 goto CALL_VIA_ENTRY_POINT;
3453 // Does the method have fixups?
3455 if (pMethod->HasFixups() != NULL)
3457 *pReason = CORINFO_INDIRECT_CALL_FIXUPS;
3458 goto CALL_VIA_ENTRY_POINT;
3462 const char* clsName, * methodName;
3463 methodName = m_zapper->m_pEEJitInfo->getMethodName(targetFtn, &clsName);
3464 LOG((LF_ZAP, LL_INFO10000, "getIntraModuleDirectCallAddr: Success %s::%s\n",
3465 clsName, methodName));
3470 CALL_VIA_ENTRY_POINT:
3473 methodName = m_zapper->m_pEEJitInfo->getMethodName(targetFtn, &clsName);
3474 LOG((LF_ZAP, LL_INFO10000, "getIntraModuleDirectCallAddr: Via EntryPoint %s::%s\n",
3475 clsName, methodName));
3485 void ZapImage::WriteReloc(PVOID pSrc, int offset, ZapNode * pTarget, int targetOffset, ZapRelocationType type)
3487 _ASSERTE(!IsWritingRelocs());
3489 _ASSERTE(m_pBaseRelocs != NULL);
3490 m_pBaseRelocs->WriteReloc(pSrc, offset, pTarget, targetOffset, type);
3493 ZapImage * ZapImage::GetZapImage()
3498 void ZapImage::FileNotFoundError(LPCWSTR pszMessage)
3500 SString message(pszMessage);
3502 for (COUNT_T i = 0; i < fileNotFoundErrorsTable.GetCount(); i++)
3504 // Check to see if same error has already been displayed for this ngen operation
3505 if (message.Equals(fileNotFoundErrorsTable[i]))
3509 CorZapLogLevel level;
3511 #ifdef CROSSGEN_COMPILE
3512 // Warnings should not go to stderr during crossgen
3513 level = CORZAP_LOGLEVEL_WARNING;
3515 level = CORZAP_LOGLEVEL_ERROR;
3518 m_zapper->Print(level, W("Warning: %s.\n"), pszMessage);
3520 fileNotFoundErrorsTable.Append(message);
3523 void ZapImage::Error(mdToken token, HRESULT hr, UINT resID, LPCWSTR message)
3525 // Missing dependencies are reported as fatal errors in code:CompilationDomain::BindAssemblySpec.
3526 // Avoid printing redundant error message for them.
3527 if (FAILED(g_hrFatalError))
3528 ThrowHR(g_hrFatalError);
3530 // COM introduces the notion of a vtable gap method, which is not a real method at all but instead
3531 // aids in the explicit layout of COM interop vtables. These methods have no implementation and no
3532 // direct runtime state tracking them. Trying to lookup a method handle for a vtable gap method will
3533 // throw an exception but we choose to let that happen and filter out the warning here in the
3534 // handler because (a) vtable gap methods are rare and (b) it's not all that cheap to identify them
3536 if ((TypeFromToken(token) == mdtMethodDef) && IsVTableGapMethod(token))
3541 CorZapLogLevel level = CORZAP_LOGLEVEL_ERROR;
3543 // Some warnings are demoted to informational level
3544 if (resID == IDS_EE_SIMD_NGEN_DISALLOWED)
3546 // Suppress printing of "Target-dependent SIMD vector types may not be used with ngen."
3547 level = CORZAP_LOGLEVEL_INFO;
3550 if (resID == IDS_EE_HWINTRINSIC_NGEN_DISALLOWED)
3552 // Suppress printing of "Hardware intrinsics may not be used with ngen."
3553 level = CORZAP_LOGLEVEL_INFO;
3556 #ifdef CROSSGEN_COMPILE
3557 if ((resID == IDS_IBC_MISSING_EXTERNAL_TYPE) ||
3558 (resID == IDS_IBC_MISSING_EXTERNAL_METHOD))
3560 // Suppress printing IBC related warnings except in verbose mode.
3561 if (m_zapper->m_pOpt->m_ignoreErrors && !m_zapper->m_pOpt->m_verbose)
3564 // Suppress printing of "The generic type/method specified by the IBC data is not available to this assembly"
3565 level = CORZAP_LOGLEVEL_INFO;
3569 if (m_zapper->m_pOpt->m_ignoreErrors)
3571 #ifdef CROSSGEN_COMPILE
3572 // Warnings should not go to stderr during crossgen
3573 if (level == CORZAP_LOGLEVEL_ERROR)
3575 level = CORZAP_LOGLEVEL_WARNING;
3578 m_zapper->Print(level, W("Warning: "));
3582 m_zapper->Print(level, W("Error: "));
3585 if (message != NULL)
3586 m_zapper->Print(level, W("%s"), message);
3588 m_zapper->PrintErrorMessage(level, hr);
3590 m_zapper->Print(level, W(" while resolving 0x%x - "), token);
3591 PrintTokenDescription(level, token);
3592 m_zapper->Print(level, W(".\n"));
3594 if (m_zapper->m_pOpt->m_ignoreErrors)
3600 ZapNode * ZapImage::GetInnerPtr(ZapNode * pNode, SSIZE_T offset)
3602 return m_pInnerPtrs->Get(pNode, offset);
3605 ZapNode * ZapImage::GetHelperThunk(CorInfoHelpFunc ftnNum)
3607 ZapNode * pHelperThunk = m_pHelperThunks[ftnNum];
3609 if (pHelperThunk == NULL)
3611 pHelperThunk = new (GetHeap()) ZapHelperThunk(ftnNum);
3613 pHelperThunk = GetInnerPtr(pHelperThunk, THUMB_CODE);
3615 m_pHelperThunks[ftnNum] = pHelperThunk;
3618 // Ensure that the thunk is placed
3619 ZapNode * pTarget = pHelperThunk;
3620 if (pTarget->GetType() == ZapNodeType_InnerPtr)
3621 pTarget = ((ZapInnerPtr *)pTarget)->GetBase();
3622 if (!pTarget->IsPlaced())
3623 m_pHelperTableSection->Place(pTarget);
3625 return pHelperThunk;
3629 // Compute a class-layout order based on a breadth-first traversal of
3630 // the class graph (based on what classes contain calls to other classes).
3631 // We cannot afford time or space to build the graph, so we do processing
3634 void ZapImage::ComputeClassLayoutOrder()
3636 // In order to make the computation efficient, we need to store per-class
3637 // intermediate values in the class layout field. These come in two forms:
3639 // - An entry with the UNSEEN_CLASS_FLAG set is one that is yet to be encountered.
3640 // - An entry with METHOD_INDEX_FLAG set is an index into the m_MethodCompilationOrder list
3641 // indicating where the unprofiled methods of this class begin
3643 // Both flags begin set (by InitializeClassLayoutOrder) since the value initialized is
3644 // the method index and the class has not been encountered by the algorithm.
3645 // When a class layout has been computed, both of these flags will have been stripped.
3648 // Early-out in the (probably impossible) case that these bits weren't available
3649 if (m_MethodCompilationOrder.GetCount() >= UNSEEN_CLASS_FLAG ||
3650 m_MethodCompilationOrder.GetCount() >= METHOD_INDEX_FLAG)
3655 // Allocate the queue for the breadth-first traversal.
3656 // Note that the use of UNSEEN_CLASS_FLAG ensures that no class is enqueued more
3657 // than once, so we can use that bound for the size of the queue.
3658 CORINFO_CLASS_HANDLE * classQueue = new CORINFO_CLASS_HANDLE[m_ClassLayoutOrder.GetCount()];
3660 unsigned classOrder = 0;
3661 for (COUNT_T i = m_iUntrainedMethod; i < m_MethodCompilationOrder.GetCount(); i++)
3663 unsigned classQueueNext = 0;
3664 unsigned classQueueEnd = 0;
3665 COUNT_T methodIndex = 0;
3668 // Find an unprocessed method to seed the next breadth-first traversal.
3671 ZapMethodHeader * pMethod = m_MethodCompilationOrder[i];
3672 const ClassLayoutOrderEntry * pEntry = m_ClassLayoutOrder.LookupPtr(pMethod->m_classHandle);
3675 if ((pEntry->m_order & UNSEEN_CLASS_FLAG) == 0)
3681 // Enqueue the method's class and start the traversal.
3684 classQueue[classQueueEnd++] = pMethod->m_classHandle;
3685 ((ClassLayoutOrderEntry *)pEntry)->m_order &= ~UNSEEN_CLASS_FLAG;
3687 while (classQueueNext < classQueueEnd)
3690 // Dequeue a class and pull out the index of its first method
3693 CORINFO_CLASS_HANDLE dequeuedClassHandle = classQueue[classQueueNext++];
3694 _ASSERTE(dequeuedClassHandle != NULL);
3696 pEntry = m_ClassLayoutOrder.LookupPtr(dequeuedClassHandle);
3698 _ASSERTE((pEntry->m_order & UNSEEN_CLASS_FLAG) == 0);
3699 _ASSERTE((pEntry->m_order & METHOD_INDEX_FLAG) != 0);
3701 methodIndex = pEntry->m_order & ~METHOD_INDEX_FLAG;
3702 _ASSERTE(methodIndex < m_MethodCompilationOrder.GetCount());
3705 // Set the real layout order of the class, and examine its unprofiled methods
3708 ((ClassLayoutOrderEntry *)pEntry)->m_order = ++classOrder;
3710 pMethod = m_MethodCompilationOrder[methodIndex];
3711 _ASSERTE(pMethod->m_classHandle == dequeuedClassHandle);
3713 while (pMethod->m_classHandle == dequeuedClassHandle)
3717 // For each unprofiled method, find target classes and enqueue any that haven't been seen
3720 ZapMethodHeader::PartialTargetMethodIterator it(pMethod);
3722 CORINFO_METHOD_HANDLE targetMethodHandle;
3723 while (it.GetNext(&targetMethodHandle))
3725 CORINFO_CLASS_HANDLE targetClassHandle = GetJitInfo()->getMethodClass(targetMethodHandle);
3726 if (targetClassHandle != pMethod->m_classHandle)
3728 pEntry = m_ClassLayoutOrder.LookupPtr(targetClassHandle);
3730 if (pEntry && (pEntry->m_order & UNSEEN_CLASS_FLAG) != 0)
3732 _ASSERTE(classQueueEnd < m_ClassLayoutOrder.GetCount());
3733 classQueue[classQueueEnd++] = targetClassHandle;
3735 ((ClassLayoutOrderEntry *)pEntry)->m_order &= ~UNSEEN_CLASS_FLAG;
3740 if (++methodIndex == m_MethodCompilationOrder.GetCount())
3745 pMethod = m_MethodCompilationOrder[methodIndex];
3750 for (COUNT_T i = m_iUntrainedMethod; i < m_MethodCompilationOrder.GetCount(); i++)
3752 ZapMethodHeader * pMethod = m_MethodCompilationOrder[i];
3753 pMethod->m_cachedLayoutOrder = LookupClassLayoutOrder(pMethod->m_classHandle);
3756 m_fHasClassLayoutOrder = true;
3758 delete [] classQueue;
3761 static int __cdecl LayoutOrderCmp(const void* a_, const void* b_)
3763 ZapMethodHeader * a = *((ZapMethodHeader**)a_);
3764 ZapMethodHeader * b = *((ZapMethodHeader**)b_);
3766 int layoutDiff = a->GetCachedLayoutOrder() - b->GetCachedLayoutOrder();
3767 if (layoutDiff != 0)
3770 // Use compilation order as secondary key to get predictable ordering within the bucket
3771 return a->GetCompilationOrder() - b->GetCompilationOrder();
3774 void ZapImage::SortUnprofiledMethodsByClassLayoutOrder()
3776 qsort(&m_MethodCompilationOrder[m_iUntrainedMethod], m_MethodCompilationOrder.GetCount() - m_iUntrainedMethod, sizeof(ZapMethodHeader *), LayoutOrderCmp);