forked from dotnet/runtime
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathReadyToRunReader.cs
More file actions
1654 lines (1478 loc) · 67.1 KB
/
ReadyToRunReader.cs
File metadata and controls
1654 lines (1478 loc) · 67.1 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.IO;
using System.Linq;
using System.Reflection.Metadata;
using System.Reflection.Metadata.Ecma335;
using System.Reflection.PortableExecutable;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Text;
using Internal.ReadyToRunConstants;
using Internal.Runtime;
using Debug = System.Diagnostics.Debug;
namespace ILCompiler.Reflection.ReadyToRun
{
/// <summary>
/// based on <a href="https://github.com/dotnet/runtime/blob/main/src/coreclr/inc/pedecoder.h">src/inc/pedecoder.h</a> IMAGE_FILE_MACHINE_NATIVE_OS_OVERRIDE
/// </summary>
public enum OperatingSystem
{
Apple = 0x4644,
FreeBSD = 0xADC4,
Linux = 0x7B79,
NetBSD = 0x1993,
SunOS = 0x1992,
Windows = 0,
Unknown = -1
}
public struct InstanceMethod
{
public byte Bucket;
public ReadyToRunMethod Method;
public InstanceMethod(byte bucket, ReadyToRunMethod method)
{
Bucket = bucket;
Method = method;
}
}
public class ReadyToRunAssembly
{
private ReadyToRunReader _reader;
internal List<string> _availableTypes;
internal List<ReadyToRunMethod> _methods;
internal ReadyToRunAssembly(ReadyToRunReader reader)
{
_reader = reader;
}
public IReadOnlyList<string> AvailableTypes
{
get
{
_reader.EnsureAvailableTypes();
return _availableTypes;
}
}
public IReadOnlyList<ReadyToRunMethod> Methods
{
get
{
_reader.EnsureMethods();
return _methods;
}
}
}
public sealed class ReadyToRunReader
{
public const int GuidByteSize = 16;
private const string SystemModuleName = "System.Private.CoreLib";
/// <summary>
/// MetadataReader for the system module (normally System.Private.CoreLib)
/// </summary>
private IAssemblyMetadata _systemModuleReader;
private readonly IAssemblyResolver _assemblyResolver;
/// <summary>
/// Reference assembly cache indexed by module indices as used in signatures
/// </summary>
private List<IAssemblyMetadata> _assemblyCache;
// Header
private OperatingSystem _operatingSystem;
private Machine _machine;
private int _pointerSize;
private bool _composite;
private ulong _imageBase;
private int _readyToRunHeaderRVA;
private string _ownerCompositeExecutable;
private ReadyToRunHeader _readyToRunHeader;
private List<ReadyToRunCoreHeader> _readyToRunAssemblyHeaders;
private List<ReadyToRunAssembly> _readyToRunAssemblies;
// DebugInfo
private Dictionary<int, int> _runtimeFunctionIdToDebugOffset;
// ManifestReferences
private MetadataReader _manifestReader;
private List<AssemblyReferenceHandle> _manifestReferences;
private Dictionary<string, int> _manifestReferenceAssemblies;
private IAssemblyMetadata _manifestAssemblyMetadata;
// ExceptionInfo
private Dictionary<int, EHInfo> _runtimeFunctionToEHInfo;
// Methods
private List<InstanceMethod> _instanceMethods;
// PgoData
private Dictionary<PgoInfoKey, PgoInfo> _pgoInfos;
// ImportSections
private List<ReadyToRunImportSection> _importSections;
private Dictionary<int, ReadyToRunSignature> _importSignatures;
// CompilerIdentifier
private string _compilerIdentifier;
/// <summary>
/// Underlying PE image reader is used to access raw PE structures like header
/// or section list.
/// </summary>
public PEReader CompositeReader { get; private set; }
/// <summary>
/// Byte array containing the ReadyToRun image
/// </summary>
public byte[] Image { get; private set; }
private PinningReference ImagePin;
/// <summary>
/// Name of the image file
/// </summary>
public string Filename { get; private set; }
/// <summary>
/// Extra reference assemblies parsed from the manifest metadata.
/// Only used by R2R assemblies with larger version bubble.
/// The manifest contains extra assembly references created by resolved
/// inlines and facades (non-existent in the source MSIL).
/// In module overrides, these assembly references are represented
/// by indices larger than the number of AssemblyRef rows in MetadataReader.
/// The list originates in the top-level R2R image and is copied
/// to all reference assemblies for the sake of simplicity.
/// </summary>
public Dictionary<string, int> ManifestReferenceAssemblies
{
get
{
EnsureManifestReferenceAssemblies();
return _manifestReferenceAssemblies;
}
}
/// <summary>
/// The type of target machine
/// </summary>
public Machine Machine
{
get
{
EnsureHeader();
return _machine;
}
}
/// <summary>
/// Targeting operating system for the R2R executable
/// </summary>
public OperatingSystem OperatingSystem
{
get
{
EnsureHeader();
return _operatingSystem;
}
}
/// <summary>
/// Size of a pointer on the architecture
/// </summary>
public int TargetPointerSize
{
get
{
EnsureHeader();
return _pointerSize;
}
}
/// <summary>
/// Return true when the executable is a composite R2R image.
/// </summary>
public bool Composite
{
get
{
EnsureHeader();
return _composite;
}
}
/// <summary>
/// Starting with R2R version 6.3, component assemblies start at index 2 in manifest metadata
/// (rowid = 1 represents the manifest metadata itself).
/// </summary>
public bool ComponentAssemblyIndicesStartAtTwo
{
get
{
EnsureHeader();
return _readyToRunHeader.MajorVersion > 6 || (_readyToRunHeader.MajorVersion == 6 && _readyToRunHeader.MinorVersion >= 3);
}
}
public int ComponentAssemblyIndexOffset => (ComponentAssemblyIndicesStartAtTwo ? 2 : 1);
/// <summary>
/// The preferred address of the first byte of image when loaded into memory;
/// must be a multiple of 64K.
/// </summary>
public ulong ImageBase
{
get
{
EnsureHeader();
return _imageBase;
}
}
/// <summary>
/// The ReadyToRun header
/// </summary>
public ReadyToRunHeader ReadyToRunHeader
{
get
{
EnsureHeader();
return _readyToRunHeader;
}
}
public IReadOnlyList<ReadyToRunCoreHeader> ReadyToRunAssemblyHeaders
{
get
{
EnsureHeader();
return _readyToRunAssemblyHeaders;
}
}
public IReadOnlyList<ReadyToRunAssembly> ReadyToRunAssemblies
{
get
{
EnsureHeader();
return _readyToRunAssemblies;
}
}
public string OwnerCompositeExecutable
{
get
{
EnsureHeader();
return _ownerCompositeExecutable;
}
}
/// <summary>
/// Parsed instance entrypoint table entries.
/// </summary>
public IReadOnlyList<InstanceMethod> InstanceMethods
{
get
{
EnsureMethods();
return _instanceMethods;
}
}
/// <summary>
/// The compiler identifier string from READYTORUN_SECTION_COMPILER_IDENTIFIER
/// </summary>
public string CompilerIdentifier
{
get
{
EnsureCompilerIdentifier();
return _compilerIdentifier;
}
}
/// <summary>
/// List of import sections present in the R2R executable.
/// </summary>
public IReadOnlyList<ReadyToRunImportSection> ImportSections
{
get
{
EnsureImportSections();
return _importSections;
}
}
/// <summary>
/// Map from import cell addresses to their symbolic names.
/// </summary>
public IReadOnlyDictionary<int, ReadyToRunSignature> ImportSignatures
{
get
{
EnsureImportSections();
return _importSignatures;
}
}
public bool ValidateDebugInfo;
internal Dictionary<int, int> RuntimeFunctionToDebugInfo
{
get
{
EnsureDebugInfo();
return _runtimeFunctionIdToDebugOffset;
}
}
internal Dictionary<int, EHInfo> RuntimeFunctionToEHInfo
{
get
{
EnsureExceptionInfo();
return _runtimeFunctionToEHInfo;
}
}
internal List<AssemblyReferenceHandle> ManifestReferences
{
get
{
EnsureManifestReferences();
return _manifestReferences;
}
}
internal MetadataReader ManifestReader
{
get
{
EnsureManifestReferences();
return _manifestReader;
}
}
internal IAssemblyMetadata R2RManifestMetadata
{
get
{
EnsureManifestReferences();
return _manifestAssemblyMetadata;
}
}
/// <summary>
/// Minimally initializes the R2R reader.
/// </summary>
/// <param name="assemblyResolver">Assembly resolver</param>
/// <param name="metadata">Assembly metadata</param>
/// <param name="peReader">PE image</param>
/// <param name="filename">PE file name</param>
public ReadyToRunReader(IAssemblyResolver assemblyResolver, IAssemblyMetadata metadata, PEReader peReader, string filename)
{
_assemblyResolver = assemblyResolver;
CompositeReader = peReader;
Filename = filename;
Initialize(metadata);
}
/// <summary>
/// Minimally initializes the R2R reader.
/// </summary>
/// <param name="assemblyResolver">Assembly resolver</param>
/// <param name="metadata">Assembly metadata</param>
/// <param name="peReader">PE image</param>
/// <param name="filename">PE file name</param>
/// <param name="content">PE image content</param>
public ReadyToRunReader(IAssemblyResolver assemblyResolver, IAssemblyMetadata metadata, PEReader peReader, string filename, ReadOnlyMemory<byte> content)
{
_assemblyResolver = assemblyResolver;
CompositeReader = peReader;
Filename = filename;
Image = ConvertToArray(content);
Initialize(metadata);
}
/// <summary>
/// Minimally initializes the R2R reader.
/// </summary>
/// <param name="assemblyResolver">Assembly resolver</param>
/// <param name="filename">PE file name</param>
public unsafe ReadyToRunReader(IAssemblyResolver assemblyResolver, string filename)
{
_assemblyResolver = assemblyResolver;
Filename = filename;
Initialize(metadata: null);
}
/// <summary>
/// Minimally initializes the R2R reader.
/// </summary>
/// <param name="assemblyResolver">Assembly resolver</param>
/// <param name="filename">PE file name</param>
/// <param name="content">PE image content</param>
public unsafe ReadyToRunReader(IAssemblyResolver assemblyResolver, string filename, ReadOnlyMemory<byte> content)
{
_assemblyResolver = assemblyResolver;
Filename = filename;
Image = ConvertToArray(content);
Initialize(metadata: null);
}
private unsafe byte[] ConvertToArray(ReadOnlyMemory<byte> content)
{
if (MemoryMarshal.TryGetArray(content, out ArraySegment<byte> segment))
{
return segment.Array;
}
else
{
return content.ToArray();
}
}
public static bool IsReadyToRunImage(PEReader peReader)
{
if (peReader.PEHeaders == null)
return false;
if (peReader.PEHeaders.CorHeader == null)
return false;
if ((peReader.PEHeaders.CorHeader.Flags & CorFlags.ILLibrary) == 0)
{
return peReader.TryGetReadyToRunHeader(out _);
}
else
{
return peReader.PEHeaders.CorHeader.ManagedNativeHeaderDirectory.Size != 0;
}
}
class PinningReference
{
GCHandle _pinnedObject;
public PinningReference(object o)
{
_pinnedObject = GCHandle.Alloc(o, GCHandleType.Pinned);
}
~PinningReference()
{
if (_pinnedObject.IsAllocated)
_pinnedObject.Free();
}
}
private unsafe void Initialize(IAssemblyMetadata metadata)
{
_assemblyCache = new List<IAssemblyMetadata>();
if (CompositeReader == null)
{
byte[] image = null;
if (Image == null)
{
image = File.ReadAllBytes(Filename);
Image = image;
}
else
{
image = Image;
}
ImagePin = new PinningReference(image);
CompositeReader = new PEReader(Unsafe.As<byte[], ImmutableArray<byte>>(ref image));
}
else
{
ImmutableArray<byte> content = CompositeReader.GetEntireImage().GetContent();
Image = Unsafe.As<ImmutableArray<byte>, byte[]>(ref content);
ImagePin = new PinningReference(Image);
}
if (metadata == null && CompositeReader.HasMetadata)
{
metadata = new StandaloneAssemblyMetadata(CompositeReader);
}
if (metadata != null)
{
if ((CompositeReader.PEHeaders.CorHeader.Flags & CorFlags.ILLibrary) == 0)
{
if (!TryLocateNativeReadyToRunHeader())
throw new BadImageFormatException("The file is not a ReadyToRun image");
Debug.Assert(Composite);
}
else
{
_assemblyCache.Add(metadata);
DirectoryEntry r2rHeaderDirectory = CompositeReader.PEHeaders.CorHeader.ManagedNativeHeaderDirectory;
_readyToRunHeaderRVA = r2rHeaderDirectory.RelativeVirtualAddress;
Debug.Assert(!Composite);
}
}
else if (!TryLocateNativeReadyToRunHeader())
{
throw new BadImageFormatException($"ECMA metadata / RTR_HEADER not found in file '{Filename}'");
}
}
internal void EnsureMethods()
{
EnsureHeader();
if (_instanceMethods != null)
{
return;
}
if (ReadyToRunHeader.Sections.TryGetValue(ReadyToRunSectionType.PgoInstrumentationData, out _))
{
ParsePgoMethods();
}
_instanceMethods = new List<InstanceMethod>();
foreach (ReadyToRunAssembly assembly in _readyToRunAssemblies)
{
assembly._methods = new List<ReadyToRunMethod>();
}
if (ReadyToRunHeader.Sections.TryGetValue(ReadyToRunSectionType.RuntimeFunctions, out ReadyToRunSection runtimeFunctionSection))
{
int runtimeFunctionSize = CalculateRuntimeFunctionSize();
int nRuntimeFunctions = runtimeFunctionSection.Size / runtimeFunctionSize;
bool[] isEntryPoint = new bool[nRuntimeFunctions];
IDictionary<int, int[]> dHotColdMap = new Dictionary<int, int[]>();
int firstColdRuntimeFunction = nRuntimeFunctions;
if (ReadyToRunHeader.Sections.TryGetValue(ReadyToRunSectionType.HotColdMap, out ReadyToRunSection hotColdMapSection))
{
int count = hotColdMapSection.Size / 8;
int hotColdMapOffset = GetOffset(hotColdMapSection.RelativeVirtualAddress);
List<List<int>> mHotColdMap = new List<List<int>>();
for (int i = 0; i < count; i++)
{
mHotColdMap.Add(new List<int> { NativeReader.ReadInt32(Image, ref hotColdMapOffset), NativeReader.ReadInt32(Image, ref hotColdMapOffset) });
}
for (int i = 0; i < count - 1; i++)
{
dHotColdMap.Add(mHotColdMap[i][1], Enumerable.Range(mHotColdMap[i][0], (mHotColdMap[i + 1][0] - mHotColdMap[i][0])).ToArray());
}
dHotColdMap.Add(mHotColdMap[count - 1][1], Enumerable.Range(mHotColdMap[count - 1][0], (nRuntimeFunctions - mHotColdMap[count - 1][0])).ToArray());
firstColdRuntimeFunction = mHotColdMap[0][0];
}
//initialize R2RMethods
ParseMethodDefEntrypoints((section, reader) => ParseMethodDefEntrypointsSection(section, reader, isEntryPoint));
ParseInstanceMethodEntrypoints(isEntryPoint);
CountRuntimeFunctions(isEntryPoint, dHotColdMap, firstColdRuntimeFunction);
}
}
private Dictionary<int, ReadyToRunMethod> _runtimeFunctionToMethod = null;
private void EnsureEntrypointRuntimeFunctionToReadyToRunMethodDict()
{
EnsureMethods();
if (_runtimeFunctionToMethod == null)
{
_runtimeFunctionToMethod = new Dictionary<int, ReadyToRunMethod>();
foreach (var method in Methods)
{
if (!_runtimeFunctionToMethod.ContainsKey(method.EntryPointRuntimeFunctionId))
_runtimeFunctionToMethod.Add(method.EntryPointRuntimeFunctionId, method);
}
}
}
public IReadOnlyDictionary<TMethod, ReadyToRunMethod> GetCustomMethodToRuntimeFunctionMapping<TType, TMethod, TGenericContext>(IR2RSignatureTypeProvider<TType, TMethod, TGenericContext> provider)
{
EnsureEntrypointRuntimeFunctionToReadyToRunMethodDict();
Dictionary<TMethod, ReadyToRunMethod> customMethods = new Dictionary<TMethod, ReadyToRunMethod>();
if (ReadyToRunHeader.Sections.TryGetValue(ReadyToRunSectionType.RuntimeFunctions, out ReadyToRunSection runtimeFunctionSection))
{
ParseMethodDefEntrypoints((section, reader) => ParseMethodDefEntrypointsSectionCustom<TType, TMethod, TGenericContext>(provider, customMethods, section, reader));
ParseInstanceMethodEntrypointsCustom<TType, TMethod, TGenericContext>(provider, customMethods);
}
return customMethods;
}
private bool TryLocateNativeReadyToRunHeader()
{
_composite = CompositeReader.TryGetReadyToRunHeader(out _readyToRunHeaderRVA);
return _composite;
}
private IAssemblyMetadata GetSystemModuleMetadataReader()
{
if (_systemModuleReader == null)
{
if (_assemblyResolver != null)
{
_systemModuleReader = _assemblyResolver.FindAssembly(SystemModuleName, Filename);
}
}
return _systemModuleReader;
}
public IAssemblyMetadata GetGlobalMetadata()
{
EnsureHeader();
return (_composite ? null : _assemblyCache[0]);
}
public string GetGlobalAssemblyName()
{
MetadataReader mdReader = GetGlobalMetadata().MetadataReader;
return mdReader.GetString(mdReader.GetAssemblyDefinition().Name);
}
private unsafe void EnsureHeader()
{
if (_readyToRunHeader != null)
{
return;
}
uint machine = (uint)CompositeReader.PEHeaders.CoffHeader.Machine;
_operatingSystem = OperatingSystem.Unknown;
foreach (OperatingSystem os in Enum.GetValues(typeof(OperatingSystem)))
{
_machine = (Machine)(machine ^ (uint)os);
if (Enum.IsDefined(typeof(Machine), _machine))
{
_operatingSystem = os;
break;
}
}
if (_operatingSystem == OperatingSystem.Unknown)
{
throw new BadImageFormatException($"Invalid Machine: {machine}");
}
switch (_machine)
{
case Machine.I386:
case Machine.Arm:
case Machine.Thumb:
case Machine.ArmThumb2:
_pointerSize = 4;
break;
case Machine.Amd64:
case Machine.Arm64:
case Machine.LoongArch64:
case Machine.RiscV64:
_pointerSize = 8;
break;
default:
throw new NotImplementedException(Machine.ToString());
}
_imageBase = CompositeReader.PEHeaders.PEHeader.ImageBase;
// Initialize R2RHeader
Debug.Assert(_readyToRunHeaderRVA != 0);
int r2rHeaderOffset = GetOffset(_readyToRunHeaderRVA);
_readyToRunHeader = new ReadyToRunHeader(Image, _readyToRunHeaderRVA, r2rHeaderOffset);
FindOwnerCompositeExecutable();
_readyToRunAssemblies = new List<ReadyToRunAssembly>();
if (_composite)
{
ParseComponentAssemblies();
}
else
{
_readyToRunAssemblies.Add(new ReadyToRunAssembly(this));
}
}
private void EnsureDebugInfo()
{
if (_runtimeFunctionIdToDebugOffset != null)
{
return;
}
_runtimeFunctionIdToDebugOffset = new Dictionary<int, int>();
if (!ReadyToRunHeader.Sections.TryGetValue(ReadyToRunSectionType.DebugInfo, out ReadyToRunSection debugInfoSection))
{
return;
}
int debugInfoSectionOffset = GetOffset(debugInfoSection.RelativeVirtualAddress);
NativeArray debugInfoArray = new NativeArray(Image, (uint)debugInfoSectionOffset);
for (uint i = 0; i < debugInfoArray.GetCount(); ++i)
{
int offset = 0;
if (!debugInfoArray.TryGetAt(Image, i, ref offset))
{
continue;
}
_runtimeFunctionIdToDebugOffset.Add((int)i, offset);
}
}
private unsafe void EnsureManifestReferences()
{
if (_manifestReferences != null)
{
return;
}
_manifestReferences = new List<AssemblyReferenceHandle>();
if (ReadyToRunHeader.Sections.TryGetValue(ReadyToRunSectionType.ManifestMetadata, out ReadyToRunSection manifestMetadata))
{
fixed (byte* image = Image)
{
_manifestReader = new MetadataReader(image + GetOffset(manifestMetadata.RelativeVirtualAddress), manifestMetadata.Size);
_manifestAssemblyMetadata = new ManifestAssemblyMetadata(CompositeReader, _manifestReader);
int assemblyRefCount = _manifestReader.GetTableRowCount(TableIndex.AssemblyRef);
for (int assemblyRefIndex = 1; assemblyRefIndex <= assemblyRefCount; assemblyRefIndex++)
{
AssemblyReferenceHandle asmRefHandle = MetadataTokens.AssemblyReferenceHandle(assemblyRefIndex);
_manifestReferences.Add(asmRefHandle);
}
}
}
}
private void EnsureManifestReferenceAssemblies()
{
if (_manifestReferenceAssemblies != null)
{
return;
}
EnsureManifestReferences();
_manifestReferenceAssemblies = new Dictionary<string, int>(_manifestReferences.Count);
for (int assemblyIndex = 0; assemblyIndex < _manifestReferences.Count; assemblyIndex++)
{
string assemblyName = ManifestReader.GetString(ManifestReader.GetAssemblyReference(_manifestReferences[assemblyIndex]).Name);
_manifestReferenceAssemblies.Add(assemblyName, assemblyIndex);
}
}
private unsafe void EnsureExceptionInfo()
{
if (_runtimeFunctionToEHInfo != null)
{
return;
}
_runtimeFunctionToEHInfo = new Dictionary<int, EHInfo>();
if (ReadyToRunHeader.Sections.TryGetValue(ReadyToRunSectionType.ExceptionInfo, out ReadyToRunSection exceptionInfoSection))
{
int offset = GetOffset(exceptionInfoSection.RelativeVirtualAddress);
int length = exceptionInfoSection.Size;
int methodRva = BitConverter.ToInt32(Image, offset);
int ehInfoRva = BitConverter.ToInt32(Image, offset + sizeof(uint));
while ((length -= 2 * sizeof(uint)) >= 8)
{
offset += 2 * sizeof(uint);
int nextMethodRva = BitConverter.ToInt32(Image, offset);
int nextEhInfoRva = BitConverter.ToInt32(Image, offset + sizeof(uint));
_runtimeFunctionToEHInfo.Add(methodRva, new EHInfo(this, ehInfoRva, methodRva, GetOffset(ehInfoRva), (nextEhInfoRva - ehInfoRva) / EHClause.Length));
methodRva = nextMethodRva;
ehInfoRva = nextEhInfoRva;
}
}
}
/// <summary>
/// Each runtime function entry has 3 fields for Amd64 machines (StartAddress, EndAddress, UnwindRVA), otherwise 2 fields (StartAddress, UnwindRVA)
/// </summary>
internal int CalculateRuntimeFunctionSize()
{
if (Machine == Machine.Amd64)
{
return 3 * sizeof(int);
}
return 2 * sizeof(int);
}
/// <summary>
/// Initialize non-generic R2RMethods with method signatures from MethodDefHandle, and runtime function indices from MethodDefEntryPoints
/// </summary>
private void ParseMethodDefEntrypoints(Action<ReadyToRunSection, IAssemblyMetadata> methodDefSectionReader)
{
ReadyToRunSection methodEntryPointSection;
if (ReadyToRunHeader.Sections.TryGetValue(ReadyToRunSectionType.MethodDefEntryPoints, out methodEntryPointSection))
{
methodDefSectionReader(methodEntryPointSection, GetGlobalMetadata());
}
else if (ReadyToRunAssemblyHeaders != null)
{
for (int assemblyIndex = 0; assemblyIndex < ReadyToRunAssemblyHeaders.Count; assemblyIndex++)
{
if (ReadyToRunAssemblyHeaders[assemblyIndex].Sections.TryGetValue(ReadyToRunSectionType.MethodDefEntryPoints, out methodEntryPointSection))
{
methodDefSectionReader(methodEntryPointSection, OpenReferenceAssembly(assemblyIndex + ComponentAssemblyIndexOffset));
}
}
}
}
/// <summary>
/// Parse a single method def entrypoint section. For composite R2R images, this method is called multiple times
/// are method entrypoints are stored separately for each component assembly of the composite R2R executable.
/// </summary>
/// <param name="section">Method entrypoint section to parse</param>
/// <param name="componentReader">Assembly metadata reader representing this method entrypoint section</param>
/// <param name="isEntryPoint">Set to true for each runtime function index representing a method entrypoint</param>
private void ParseMethodDefEntrypointsSection(ReadyToRunSection section, IAssemblyMetadata componentReader, bool[] isEntryPoint)
{
int assemblyIndex = GetAssemblyIndex(section);
int methodDefEntryPointsOffset = GetOffset(section.RelativeVirtualAddress);
NativeArray methodEntryPoints = new NativeArray(Image, (uint)methodDefEntryPointsOffset);
uint nMethodEntryPoints = methodEntryPoints.GetCount();
for (uint rid = 1; rid <= nMethodEntryPoints; rid++)
{
int offset = 0;
if (methodEntryPoints.TryGetAt(Image, rid - 1, ref offset))
{
EntityHandle methodHandle = MetadataTokens.MethodDefinitionHandle((int)rid);
int runtimeFunctionId;
int? fixupOffset;
GetRuntimeFunctionIndexFromOffset(offset, out runtimeFunctionId, out fixupOffset);
ReadyToRunMethod method = new ReadyToRunMethod(this, componentReader, methodHandle, runtimeFunctionId, owningType: null, constrainedType: null, instanceArgs: null, fixupOffset: fixupOffset);
if (method.EntryPointRuntimeFunctionId < 0 || method.EntryPointRuntimeFunctionId >= isEntryPoint.Length)
{
throw new BadImageFormatException("EntryPointRuntimeFunctionId out of bounds");
}
isEntryPoint[method.EntryPointRuntimeFunctionId] = true;
_readyToRunAssemblies[assemblyIndex]._methods.Add(method);
}
}
}
/// <summary>
/// Parse a single method def entrypoint section. For composite R2R images, this method is called multiple times
/// are method entrypoints are stored separately for each component assembly of the composite R2R executable.
/// </summary>
/// <param name="section">Method entrypoint section to parse</param>
/// <param name="metadataReader">ECMA metadata reader representing this method entrypoint section</param>
/// <param name="isEntryPoint">Set to true for each runtime function index representing a method entrypoint</param>
private void ParseMethodDefEntrypointsSectionCustom<TType, TMethod, TGenericContext>(IR2RSignatureTypeProvider<TType, TMethod, TGenericContext> provider, Dictionary<TMethod, ReadyToRunMethod> foundMethods, ReadyToRunSection section, IAssemblyMetadata metadataReader)
{
int methodDefEntryPointsOffset = GetOffset(section.RelativeVirtualAddress);
NativeArray methodEntryPoints = new NativeArray(Image, (uint)methodDefEntryPointsOffset);
uint nMethodEntryPoints = methodEntryPoints.GetCount();
for (uint rid = 1; rid <= nMethodEntryPoints; rid++)
{
int offset = 0;
if (methodEntryPoints.TryGetAt(Image, rid - 1, ref offset))
{
EntityHandle methodHandle = MetadataTokens.MethodDefinitionHandle((int)rid);
int runtimeFunctionId;
int? fixupOffset;
GetRuntimeFunctionIndexFromOffset(offset, out runtimeFunctionId, out fixupOffset);
ReadyToRunMethod r2rMethod = _runtimeFunctionToMethod[runtimeFunctionId];
var customMethod = provider.GetMethodFromMethodDef(metadataReader.MetadataReader, MetadataTokens.MethodDefinitionHandle((int)rid), default(TType));
if (!Object.ReferenceEquals(customMethod, null) && !foundMethods.ContainsKey(customMethod))
foundMethods.Add(customMethod, r2rMethod);
}
}
}
/// <summary>
/// Initialize generic method instances with argument types and runtime function indices from InstanceMethodEntrypoints
/// </summary>
private void ParseInstanceMethodEntrypointsCustom<TType, TMethod, TGenericContext>(IR2RSignatureTypeProvider<TType, TMethod, TGenericContext> provider, Dictionary<TMethod, ReadyToRunMethod> foundMethods)
{
if (!ReadyToRunHeader.Sections.TryGetValue(ReadyToRunSectionType.InstanceMethodEntryPoints, out ReadyToRunSection instMethodEntryPointSection))
{
return;
}
int instMethodEntryPointsOffset = GetOffset(instMethodEntryPointSection.RelativeVirtualAddress);
NativeParser parser = new NativeParser(Image, (uint)instMethodEntryPointsOffset);
NativeHashtable instMethodEntryPoints = new NativeHashtable(Image, parser, (uint)(instMethodEntryPointsOffset + instMethodEntryPointSection.Size));
NativeHashtable.AllEntriesEnumerator allEntriesEnum = instMethodEntryPoints.EnumerateAllEntries();
NativeParser curParser = allEntriesEnum.GetNext();
while (!curParser.IsNull())
{
IAssemblyMetadata mdReader = GetGlobalMetadata();
var decoder = new R2RSignatureDecoder<TType, TMethod, TGenericContext>(provider, default(TGenericContext), mdReader?.MetadataReader, this, (int)curParser.Offset);
TMethod customMethod = decoder.ParseMethod();
int runtimeFunctionId;
int? fixupOffset;
GetRuntimeFunctionIndexFromOffset((int)decoder.Offset, out runtimeFunctionId, out fixupOffset);
ReadyToRunMethod r2rMethod = _runtimeFunctionToMethod[runtimeFunctionId];
if (!Object.ReferenceEquals(customMethod, null) && !foundMethods.ContainsKey(customMethod))
foundMethods.Add(customMethod, r2rMethod);
curParser = allEntriesEnum.GetNext();
}
}
/// <summary>
/// Initialize generic method instances with argument types and runtime function indices from InstanceMethodEntrypoints
/// </summary>
private void ParseInstanceMethodEntrypoints(bool[] isEntryPoint)
{
if (!ReadyToRunHeader.Sections.TryGetValue(ReadyToRunSectionType.InstanceMethodEntryPoints, out ReadyToRunSection instMethodEntryPointSection))
{
return;
}
int instMethodEntryPointsOffset = GetOffset(instMethodEntryPointSection.RelativeVirtualAddress);
NativeParser parser = new NativeParser(Image, (uint)instMethodEntryPointsOffset);
NativeHashtable instMethodEntryPoints = new NativeHashtable(Image, parser, (uint)(instMethodEntryPointsOffset + instMethodEntryPointSection.Size));
NativeHashtable.AllEntriesEnumerator allEntriesEnum = instMethodEntryPoints.EnumerateAllEntries();
NativeParser curParser = allEntriesEnum.GetNext();
while (!curParser.IsNull())
{
IAssemblyMetadata mdReader = GetGlobalMetadata();
bool updateMDReaderFromOwnerType = true;
SignatureFormattingOptions dummyOptions = new SignatureFormattingOptions();
SignatureDecoder decoder = new SignatureDecoder(_assemblyResolver, dummyOptions, mdReader?.MetadataReader, this, (int)curParser.Offset);
string owningType = null;
uint methodFlags = decoder.ReadUInt();
if ((methodFlags & (uint)ReadyToRunMethodSigFlags.READYTORUN_METHOD_SIG_UpdateContext) != 0)
{
int moduleIndex = (int)decoder.ReadUInt();
mdReader = OpenReferenceAssembly(moduleIndex);
decoder = new SignatureDecoder(_assemblyResolver, dummyOptions, mdReader.MetadataReader, this, (int)curParser.Offset);
decoder.ReadUInt(); // Skip past methodFlags
decoder.ReadUInt(); // And moduleIndex
updateMDReaderFromOwnerType = false;
}
if ((methodFlags & (uint)ReadyToRunMethodSigFlags.READYTORUN_METHOD_SIG_OwnerType) != 0)
{
if (updateMDReaderFromOwnerType)
{
mdReader = decoder.GetMetadataReaderFromModuleOverride() ?? mdReader;
if ((_composite) && mdReader == null)
{
// The only types that don't have module overrides on them in composite images are primitive types within the system module
mdReader = GetSystemModuleMetadataReader();
}
}
owningType = decoder.ReadTypeSignatureNoEmit();
}
if ((methodFlags & (uint)ReadyToRunMethodSigFlags.READYTORUN_METHOD_SIG_SlotInsteadOfToken) != 0)
{
throw new NotImplementedException();
}
EntityHandle methodHandle;
int rid = (int)decoder.ReadUInt();
if ((methodFlags & (uint)ReadyToRunMethodSigFlags.READYTORUN_METHOD_SIG_MemberRefToken) != 0)
{
methodHandle = MetadataTokens.MemberReferenceHandle(rid);
}
else
{
methodHandle = MetadataTokens.MethodDefinitionHandle(rid);
}