-
Notifications
You must be signed in to change notification settings - Fork 587
/
Copy pathMetadata.cs
3842 lines (3422 loc) · 125 KB
/
Metadata.cs
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
// dnlib: See LICENSE.txt for more info
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Text;
using dnlib.DotNet.Emit;
using dnlib.DotNet.MD;
using dnlib.DotNet.Pdb;
using dnlib.DotNet.Pdb.Portable;
using dnlib.IO;
using dnlib.PE;
namespace dnlib.DotNet.Writer {
/// <summary>
/// <see cref="Metadata"/> flags
/// </summary>
[Flags]
public enum MetadataFlags : uint {
/// <summary>
/// Preserves all rids in the <c>TypeRef</c> table
/// </summary>
PreserveTypeRefRids = 1,
/// <summary>
/// Preserves all rids in the <c>TypeDef</c> table
/// </summary>
PreserveTypeDefRids = 2,
/// <summary>
/// Preserves all rids in the <c>Field</c> table
/// </summary>
PreserveFieldRids = 4,
/// <summary>
/// Preserves all rids in the <c>Method</c> table
/// </summary>
PreserveMethodRids = 8,
/// <summary>
/// Preserves all rids in the <c>Param</c> table
/// </summary>
PreserveParamRids = 0x10,
/// <summary>
/// Preserves all rids in the <c>MemberRef</c> table
/// </summary>
PreserveMemberRefRids = 0x20,
/// <summary>
/// Preserves all rids in the <c>StandAloneSig</c> table
/// </summary>
PreserveStandAloneSigRids = 0x40,
/// <summary>
/// Preserves all rids in the <c>Event</c> table
/// </summary>
PreserveEventRids = 0x80,
/// <summary>
/// Preserves all rids in the <c>Property</c> table
/// </summary>
PreservePropertyRids = 0x100,
/// <summary>
/// Preserves all rids in the <c>TypeSpec</c> table
/// </summary>
PreserveTypeSpecRids = 0x200,
/// <summary>
/// Preserves all rids in the <c>MethodSpec</c> table
/// </summary>
PreserveMethodSpecRids = 0x400,
/// <summary>
/// Preserves all method rids, i.e., <c>Method</c>, <c>MemberRef</c> and
/// <c>MethodSpec</c> rids.
/// </summary>
PreserveAllMethodRids = PreserveMethodRids | PreserveMemberRefRids | PreserveMethodSpecRids,
/// <summary>
/// Preserves all rids in the following tables: <c>TypeRef</c>, <c>TypeDef</c>,
/// <c>Field</c>, <c>Method</c>, <c>Param</c>, <c>MemberRef</c>, <c>StandAloneSig</c>,
/// <c>Event</c>, <c>Property</c>, <c>TypeSpec</c>, <c>MethodSpec</c>
/// </summary>
PreserveRids = PreserveTypeRefRids |
PreserveTypeDefRids |
PreserveFieldRids |
PreserveMethodRids |
PreserveParamRids |
PreserveMemberRefRids |
PreserveStandAloneSigRids |
PreserveEventRids |
PreservePropertyRids |
PreserveTypeSpecRids |
PreserveMethodSpecRids,
/// <summary>
/// Preserves all offsets in the #Strings heap (the original #Strings heap will be saved
/// in the new file). Type names, field names, and other non-user strings are stored
/// in the #Strings heap.
/// </summary>
PreserveStringsOffsets = 0x800,
/// <summary>
/// Preserves all offsets in the #US heap (the original #US heap will be saved
/// in the new file). User strings (referenced by the ldstr instruction) are stored in
/// the #US heap.
/// </summary>
PreserveUSOffsets = 0x1000,
/// <summary>
/// Preserves all offsets in the #Blob heap (the original #Blob heap will be saved
/// in the new file). Custom attributes, signatures and other blobs are stored in the
/// #Blob heap.
/// </summary>
PreserveBlobOffsets = 0x2000,
/// <summary>
/// Preserves the extra data that is present after the original signature in the #Blob
/// heap. This extra data shouldn't be present but might be present if an obfuscator
/// has added this extra data and is eg. using it to decrypt stuff.
/// </summary>
PreserveExtraSignatureData = 0x4000,
/// <summary>
/// Preserves as much as possible
/// </summary>
PreserveAll = PreserveRids | PreserveStringsOffsets | PreserveUSOffsets |
PreserveBlobOffsets | PreserveExtraSignatureData,
/// <summary>
/// The original method body's max stack field should be used and a new one should not
/// be calculated.
/// </summary>
KeepOldMaxStack = 0x8000,
/// <summary>
/// Always create the #GUID heap even if it's empty
/// </summary>
AlwaysCreateGuidHeap = 0x10000,
/// <summary>
/// Always create the #Strings heap even if it's empty
/// </summary>
AlwaysCreateStringsHeap = 0x20000,
/// <summary>
/// Always create the #US heap even if it's empty
/// </summary>
AlwaysCreateUSHeap = 0x40000,
/// <summary>
/// Always create the #Blob heap even if it's empty
/// </summary>
AlwaysCreateBlobHeap = 0x80000,
/// <summary>
/// DEPRECATED:
/// Sort the InterfaceImpl table the same way Roslyn sorts it. Roslyn doesn't sort it
/// according to the ECMA spec, see https://github.com/dotnet/roslyn/issues/3905
/// </summary>
RoslynSortInterfaceImpl = 0x100000,
/// <summary>
/// Don't write method bodies
/// </summary>
NoMethodBodies = 0x200000,
/// <summary>
/// Don't write .NET resources
/// </summary>
NoDotNetResources = 0x400000,
/// <summary>
/// Don't write field data
/// </summary>
NoFieldData = 0x800000,
/// <summary>
/// Serialized type names stored in custom attributes are optimized if the types
/// exist in the core library (eg. mscorlib/System.Private.CoreLib).
/// Instead of storing type-name + assembly-name, only type-name is stored. This results in
/// slightly smaller assemblies.
/// <br/>
/// <br/>
/// If it's a type in the current module, the type name is optimized and no assembly name is stored in the custom attribute.
/// <br/>
/// <br/>
/// This is disabled by default. It's safe to enable if the reference core assembly
/// is the same as the runtime core assembly (eg. it's mscorlib.dll and .NET Framework,
/// but not .NET Core / .NET Standard).
/// </summary>
OptimizeCustomAttributeSerializedTypeNames = 0x1000000,
}
/// <summary>
/// Metadata heaps event args
/// </summary>
public readonly struct MetadataHeapsAddedEventArgs {
/// <summary>
/// Gets the metadata writer
/// </summary>
public Metadata Metadata { get; }
/// <summary>
/// Gets all heaps
/// </summary>
public List<IHeap> Heaps { get; }
/// <summary>
/// Constructor
/// </summary>
/// <param name="metadata">Metadata writer</param>
/// <param name="heaps">All heaps</param>
public MetadataHeapsAddedEventArgs(Metadata metadata, List<IHeap> heaps) {
Metadata = metadata ?? throw new ArgumentNullException(nameof(metadata));
Heaps = heaps ?? throw new ArgumentNullException(nameof(heaps));
}
}
/// <summary>
/// <see cref="Metadata"/> options
/// </summary>
public sealed class MetadataOptions {
MetadataHeaderOptions metadataHeaderOptions;
MetadataHeaderOptions debugMetadataHeaderOptions;
TablesHeapOptions tablesHeapOptions;
List<IHeap> customHeaps;
/// <summary>
/// Gets/sets the <see cref="MetadataHeader"/> options. This is never <c>null</c>.
/// </summary>
public MetadataHeaderOptions MetadataHeaderOptions {
get => metadataHeaderOptions ??= new MetadataHeaderOptions();
set => metadataHeaderOptions = value;
}
/// <summary>
/// Gets/sets the debug (portable PDB) <see cref="MetadataHeader"/> options. This is never <c>null</c>.
/// </summary>
public MetadataHeaderOptions DebugMetadataHeaderOptions {
get => debugMetadataHeaderOptions ??= MetadataHeaderOptions.CreatePortablePdbV1_0();
set => debugMetadataHeaderOptions = value;
}
/// <summary>
/// Gets/sets the <see cref="TablesHeap"/> options. This is never <c>null</c>.
/// </summary>
public TablesHeapOptions TablesHeapOptions {
get => tablesHeapOptions ??= new TablesHeapOptions();
set => tablesHeapOptions = value;
}
/// <summary>
/// Gets/sets the debug (portable PDB) <see cref="TablesHeap"/> options. This is never <c>null</c>.
/// </summary>
public TablesHeapOptions DebugTablesHeapOptions {
get => tablesHeapOptions ??= TablesHeapOptions.CreatePortablePdbV1_0();
set => tablesHeapOptions = value;
}
/// <summary>
/// Various options
/// </summary>
public MetadataFlags Flags;
/// <summary>
/// Extra heaps to add to the metadata. Also see <see cref="MetadataHeapsAdded"/> and <see cref="PreserveHeapOrder(ModuleDef, bool)"/>
/// </summary>
public List<IHeap> CustomHeaps => customHeaps ??= new List<IHeap>();
/// <summary>
/// Raised after all heaps have been added. The caller can sort the list if needed
/// </summary>
public event EventHandler2<MetadataHeapsAddedEventArgs> MetadataHeapsAdded;
internal void RaiseMetadataHeapsAdded(MetadataHeapsAddedEventArgs e) => MetadataHeapsAdded?.Invoke(e.Metadata, e);
/// <summary>
/// Preserves the original order of heaps, and optionally adds all custom heaps to <see cref="CustomHeaps"/>.
/// </summary>
/// <param name="module">Original module with the heaps</param>
/// <param name="addCustomHeaps">If true, all custom streams are added to <see cref="CustomHeaps"/></param>
public void PreserveHeapOrder(ModuleDef module, bool addCustomHeaps) {
if (module is null)
throw new ArgumentNullException(nameof(module));
if (module is ModuleDefMD mod) {
if (addCustomHeaps) {
var otherStreams = mod.Metadata.AllStreams.Where(a => a.GetType() == typeof(CustomDotNetStream)).Select(a => new DataReaderHeap(a));
CustomHeaps.AddRange(otherStreams.OfType<IHeap>());
}
var streamToOrder = new Dictionary<DotNetStream, int>(mod.Metadata.AllStreams.Count);
for (int i = 0, order = 0; i < mod.Metadata.AllStreams.Count; i++) {
var stream = mod.Metadata.AllStreams[i];
if (stream.StartOffset == 0)
continue;
streamToOrder.Add(stream, order++);
}
var nameToOrder = new Dictionary<string, int>(mod.Metadata.AllStreams.Count, StringComparer.Ordinal);
for (int i = 0, order = 0; i < mod.Metadata.AllStreams.Count; i++) {
var stream = mod.Metadata.AllStreams[i];
if (stream.StartOffset == 0)
continue;
bool isKnownStream = stream is BlobStream || stream is GuidStream ||
stream is PdbStream || stream is StringsStream || stream is TablesStream || stream is USStream;
if (!nameToOrder.ContainsKey(stream.Name) || isKnownStream)
nameToOrder[stream.Name] = order;
order++;
}
MetadataHeapsAdded += (s, e) => {
e.Heaps.Sort((a, b) => {
int oa = GetOrder(streamToOrder, nameToOrder, a);
int ob = GetOrder(streamToOrder, nameToOrder, b);
int c = oa - ob;
if (c != 0)
return c;
return StringComparer.Ordinal.Compare(a.Name, b.Name);
});
};
}
}
static int GetOrder(Dictionary<DotNetStream, int> streamToOrder, Dictionary<string, int> nameToOrder, IHeap heap) {
if (heap is DataReaderHeap drHeap && drHeap.OptionalOriginalStream is DotNetStream dnHeap && streamToOrder.TryGetValue(dnHeap, out int order))
return order;
if (nameToOrder.TryGetValue(heap.Name, out order))
return order;
return int.MaxValue;
}
/// <summary>
/// Default constructor
/// </summary>
public MetadataOptions() {
}
/// <summary>
/// Constructor
/// </summary>
/// <param name="flags">Flags</param>
public MetadataOptions(MetadataFlags flags) => Flags = flags;
/// <summary>
/// Constructor
/// </summary>
/// <param name="mdhOptions">Meta data header options</param>
public MetadataOptions(MetadataHeaderOptions mdhOptions) => metadataHeaderOptions = mdhOptions;
/// <summary>
/// Constructor
/// </summary>
/// <param name="mdhOptions">Meta data header options</param>
/// <param name="flags">Flags</param>
public MetadataOptions(MetadataHeaderOptions mdhOptions, MetadataFlags flags) {
Flags = flags;
metadataHeaderOptions = mdhOptions;
}
}
sealed class DataWriterContext {
public readonly MemoryStream OutStream;
public readonly DataWriter Writer;
public DataWriterContext() {
OutStream = new MemoryStream();
Writer = new DataWriter(OutStream);
}
}
/// <summary>
/// Portable PDB metadata kind
/// </summary>
public enum DebugMetadataKind {
/// <summary>
/// No debugging metadata
/// </summary>
None,
/// <summary>
/// Standalone / embedded portable PDB metadata
/// </summary>
Standalone,
}
/// <summary>
/// Metadata writer event args
/// </summary>
public readonly struct MetadataWriterEventArgs {
/// <summary>
/// Gets the metadata writer
/// </summary>
public Metadata Metadata { get; }
/// <summary>
/// Gets the event
/// </summary>
public MetadataEvent Event { get; }
/// <summary>
/// Constructor
/// </summary>
/// <param name="metadata">Writer</param>
/// <param name="event">Event</param>
public MetadataWriterEventArgs(Metadata metadata, MetadataEvent @event) {
Metadata = metadata ?? throw new ArgumentNullException(nameof(metadata));
Event = @event;
}
}
/// <summary>
/// Metadata writer progress event args
/// </summary>
public readonly struct MetadataProgressEventArgs {
/// <summary>
/// Gets the metadata writer
/// </summary>
public Metadata Metadata { get; }
/// <summary>
/// Gets the progress, 0.0 - 1.0
/// </summary>
public double Progress { get; }
/// <summary>
/// Constructor
/// </summary>
/// <param name="metadata">Writer</param>
/// <param name="progress">Progress, 0.0 - 1.0</param>
public MetadataProgressEventArgs(Metadata metadata, double progress) {
if (progress < 0 || progress > 1)
throw new ArgumentOutOfRangeException(nameof(progress));
Metadata = metadata ?? throw new ArgumentNullException(nameof(metadata));
Progress = progress;
}
}
/// <summary>
/// .NET meta data
/// </summary>
public abstract class Metadata : IReuseChunk, ISignatureWriterHelper, ITokenProvider, ICustomAttributeWriterHelper, IPortablePdbCustomDebugInfoWriterHelper, IWriterError2 {
uint length;
FileOffset offset;
RVA rva;
readonly MetadataOptions options;
ILogger logger;
readonly MetadataErrorContext errorContext;
readonly NormalMetadata debugMetadata;
readonly bool isStandaloneDebugMetadata;
internal readonly ModuleDef module;
internal readonly UniqueChunkList<ByteArrayChunk> constants;
internal readonly MethodBodyChunks methodBodies;
internal readonly NetResources netResources;
internal readonly MetadataHeader metadataHeader;
internal readonly PdbHeap pdbHeap;
internal readonly TablesHeap tablesHeap;
internal readonly StringsHeap stringsHeap;
internal readonly USHeap usHeap;
internal readonly GuidHeap guidHeap;
internal readonly BlobHeap blobHeap;
internal TypeDef[] allTypeDefs;
internal readonly Rows<ModuleDef> moduleDefInfos = new Rows<ModuleDef>();
internal readonly SortedRows<InterfaceImpl, RawInterfaceImplRow> interfaceImplInfos = new SortedRows<InterfaceImpl, RawInterfaceImplRow>();
internal readonly SortedRows<IHasConstant, RawConstantRow> hasConstantInfos = new SortedRows<IHasConstant, RawConstantRow>();
internal readonly SortedRows<CustomAttribute, RawCustomAttributeRow> customAttributeInfos = new SortedRows<CustomAttribute, RawCustomAttributeRow>();
internal readonly SortedRows<IHasFieldMarshal, RawFieldMarshalRow> fieldMarshalInfos = new SortedRows<IHasFieldMarshal, RawFieldMarshalRow>();
internal readonly SortedRows<DeclSecurity, RawDeclSecurityRow> declSecurityInfos = new SortedRows<DeclSecurity, RawDeclSecurityRow>();
internal readonly SortedRows<TypeDef, RawClassLayoutRow> classLayoutInfos = new SortedRows<TypeDef, RawClassLayoutRow>();
internal readonly SortedRows<FieldDef, RawFieldLayoutRow> fieldLayoutInfos = new SortedRows<FieldDef, RawFieldLayoutRow>();
internal readonly Rows<TypeDef> eventMapInfos = new Rows<TypeDef>();
internal readonly Rows<TypeDef> propertyMapInfos = new Rows<TypeDef>();
internal readonly SortedRows<MethodDef, RawMethodSemanticsRow> methodSemanticsInfos = new SortedRows<MethodDef, RawMethodSemanticsRow>();
internal readonly SortedRows<MethodDef, RawMethodImplRow> methodImplInfos = new SortedRows<MethodDef, RawMethodImplRow>();
internal readonly Rows<ModuleRef> moduleRefInfos = new Rows<ModuleRef>();
internal readonly SortedRows<IMemberForwarded, RawImplMapRow> implMapInfos = new SortedRows<IMemberForwarded, RawImplMapRow>();
internal readonly SortedRows<FieldDef, RawFieldRVARow> fieldRVAInfos = new SortedRows<FieldDef, RawFieldRVARow>();
internal readonly Rows<AssemblyDef> assemblyInfos = new Rows<AssemblyDef>();
internal readonly Rows<AssemblyRef> assemblyRefInfos = new Rows<AssemblyRef>();
internal readonly Rows<FileDef> fileDefInfos = new Rows<FileDef>();
internal readonly Rows<ExportedType> exportedTypeInfos = new Rows<ExportedType>();
internal readonly Rows<Resource> manifestResourceInfos = new Rows<Resource>();
internal readonly SortedRows<TypeDef, RawNestedClassRow> nestedClassInfos = new SortedRows<TypeDef, RawNestedClassRow>();
internal readonly SortedRows<GenericParam, RawGenericParamRow> genericParamInfos = new SortedRows<GenericParam, RawGenericParamRow>();
internal readonly SortedRows<GenericParamConstraint, RawGenericParamConstraintRow> genericParamConstraintInfos = new SortedRows<GenericParamConstraint, RawGenericParamConstraintRow>();
internal readonly Dictionary<MethodDef, MethodBody> methodToBody = new Dictionary<MethodDef, MethodBody>();
internal readonly Dictionary<MethodDef, NativeMethodBody> methodToNativeBody = new Dictionary<MethodDef, NativeMethodBody>();
internal readonly Dictionary<EmbeddedResource, DataReaderChunk> embeddedResourceToByteArray = new Dictionary<EmbeddedResource, DataReaderChunk>();
readonly Dictionary<FieldDef, ByteArrayChunk> fieldToInitialValue = new Dictionary<FieldDef, ByteArrayChunk>();
readonly Rows<PdbDocument> pdbDocumentInfos = new Rows<PdbDocument>();
bool methodDebugInformationInfosUsed;
readonly SortedRows<PdbScope, RawLocalScopeRow> localScopeInfos = new SortedRows<PdbScope, RawLocalScopeRow>();
readonly Rows<PdbLocal> localVariableInfos = new Rows<PdbLocal>();
readonly Rows<PdbConstant> localConstantInfos = new Rows<PdbConstant>();
readonly Rows<PdbImportScope> importScopeInfos = new Rows<PdbImportScope>();
readonly SortedRows<PdbCustomDebugInfo, RawStateMachineMethodRow> stateMachineMethodInfos = new SortedRows<PdbCustomDebugInfo, RawStateMachineMethodRow>();
readonly SortedRows<PdbCustomDebugInfo, RawCustomDebugInformationRow> customDebugInfos = new SortedRows<PdbCustomDebugInfo, RawCustomDebugInformationRow>();
readonly List<DataWriterContext> binaryWriterContexts = new List<DataWriterContext>();
readonly List<SerializerMethodContext> serializerMethodContexts = new List<SerializerMethodContext>();
readonly List<MethodDef> exportedMethods = new List<MethodDef>();
/// <summary>
/// Raised at various times when writing the metadata
/// </summary>
public event EventHandler2<MetadataWriterEventArgs> MetadataEvent;
/// <summary>
/// Raised when the progress is updated
/// </summary>
public event EventHandler2<MetadataProgressEventArgs> ProgressUpdated;
/// <summary>
/// Gets/sets the logger
/// </summary>
public ILogger Logger {
get => logger;
set => logger = value;
}
/// <summary>
/// Gets the module
/// </summary>
public ModuleDef Module => module;
/// <summary>
/// Gets the constants
/// </summary>
public UniqueChunkList<ByteArrayChunk> Constants => constants;
/// <summary>
/// Gets the method body chunks
/// </summary>
public MethodBodyChunks MethodBodyChunks => methodBodies;
/// <summary>
/// Gets the .NET resources
/// </summary>
public NetResources NetResources => netResources;
/// <summary>
/// Gets the MD header
/// </summary>
public MetadataHeader MetadataHeader => metadataHeader;
/// <summary>
/// Gets the tables heap. Access to this heap is not recommended, but is useful if you
/// want to add random table entries.
/// </summary>
public TablesHeap TablesHeap => tablesHeap;
/// <summary>
/// Gets the #Strings heap. Access to this heap is not recommended, but is useful if you
/// want to add random strings.
/// </summary>
public StringsHeap StringsHeap => stringsHeap;
/// <summary>
/// Gets the #US heap. Access to this heap is not recommended, but is useful if
/// you want to add random user strings.
/// </summary>
public USHeap USHeap => usHeap;
/// <summary>
/// Gets the #GUID heap. Access to this heap is not recommended, but is useful if you
/// want to add random GUIDs.
/// </summary>
public GuidHeap GuidHeap => guidHeap;
/// <summary>
/// Gets the #Blob heap. Access to this heap is not recommended, but is useful if you
/// want to add random blobs.
/// </summary>
public BlobHeap BlobHeap => blobHeap;
/// <summary>
/// Gets the #Pdb heap. It's only used if it's portable PDB metadata
/// </summary>
public PdbHeap PdbHeap => pdbHeap;
/// <summary>
/// Gets all exported methods
/// </summary>
public List<MethodDef> ExportedMethods => exportedMethods;
/// <summary>
/// The public key that should be used instead of the one in <see cref="AssemblyDef"/>.
/// </summary>
internal byte[] AssemblyPublicKey { get; set; }
internal sealed class SortedRows<T, TRow> where T : class where TRow : struct {
public List<Info> infos = new List<Info>();
Dictionary<T, uint> toRid = new Dictionary<T, uint>();
bool isSorted;
public struct Info {
public readonly T data;
public /*readonly*/ TRow row;
public Info(T data, ref TRow row) {
this.data = data;
this.row = row;
}
}
public void Add(T data, TRow row) {
if (isSorted)
throw new ModuleWriterException($"Adding a row after it's been sorted. Table: {row.GetType()}");
infos.Add(new Info(data, ref row));
toRid[data] = (uint)toRid.Count + 1;
}
public void Sort(Comparison<Info> comparison) {
infos.Sort(CreateComparison(comparison));
toRid.Clear();
for (int i = 0; i < infos.Count; i++)
toRid[infos[i].data] = (uint)i + 1;
isSorted = true;
}
Comparison<Info> CreateComparison(Comparison<Info> comparison) =>
(a, b) => {
int c = comparison(a, b);
if (c != 0)
return c;
// Make sure it's a stable sort
return toRid[a.data].CompareTo(toRid[b.data]);
};
public uint Rid(T data) => toRid[data];
public bool TryGetRid(T data, out uint rid) {
if (data is null) {
rid = 0;
return false;
}
return toRid.TryGetValue(data, out rid);
}
}
internal sealed class Rows<T> where T : class {
Dictionary<T, uint> dict = new Dictionary<T, uint>();
public int Count => dict.Count;
public bool TryGetRid(T value, out uint rid) {
if (value is null) {
rid = 0;
return false;
}
return dict.TryGetValue(value, out rid);
}
public bool Exists(T value) => dict.ContainsKey(value);
public void Add(T value, uint rid) => dict.Add(value, rid);
public uint Rid(T value) => dict[value];
public void SetRid(T value, uint rid) => dict[value] = rid;
}
/// <summary>
/// Creates a <see cref="Metadata"/> instance
/// </summary>
/// <param name="module">Module</param>
/// <param name="constants">Constants list</param>
/// <param name="methodBodies">Method bodies list</param>
/// <param name="netResources">.NET resources list</param>
/// <param name="options">Options</param>
/// <param name="debugKind">Debug metadata kind</param>
/// <returns>A new <see cref="Metadata"/> instance</returns>
public static Metadata Create(ModuleDef module, UniqueChunkList<ByteArrayChunk> constants, MethodBodyChunks methodBodies, NetResources netResources, MetadataOptions options = null, DebugMetadataKind debugKind = DebugMetadataKind.None) {
if (options is null)
options = new MetadataOptions();
if ((options.Flags & MetadataFlags.PreserveRids) != 0 && module is ModuleDefMD)
return new PreserveTokensMetadata(module, constants, methodBodies, netResources, options, debugKind, false);
return new NormalMetadata(module, constants, methodBodies, netResources, options, debugKind, false);
}
/// <inheritdoc/>
public FileOffset FileOffset => offset;
/// <inheritdoc/>
public RVA RVA => rva;
/// <summary>
/// Gets the <see cref="MetadataFlags.PreserveTypeRefRids"/> bit
/// </summary>
public bool PreserveTypeRefRids => (options.Flags & MetadataFlags.PreserveTypeRefRids) != 0;
/// <summary>
/// Gets the <see cref="MetadataFlags.PreserveTypeDefRids"/> bit
/// </summary>
public bool PreserveTypeDefRids => (options.Flags & MetadataFlags.PreserveTypeDefRids) != 0;
/// <summary>
/// Gets the <see cref="MetadataFlags.PreserveFieldRids"/> bit
/// </summary>
public bool PreserveFieldRids => (options.Flags & MetadataFlags.PreserveFieldRids) != 0;
/// <summary>
/// Gets the <see cref="MetadataFlags.PreserveMethodRids"/> bit
/// </summary>
public bool PreserveMethodRids => (options.Flags & MetadataFlags.PreserveMethodRids) != 0;
/// <summary>
/// Gets the <see cref="MetadataFlags.PreserveParamRids"/> bit
/// </summary>
public bool PreserveParamRids => (options.Flags & MetadataFlags.PreserveParamRids) != 0;
/// <summary>
/// Gets the <see cref="MetadataFlags.PreserveMemberRefRids"/> bit
/// </summary>
public bool PreserveMemberRefRids => (options.Flags & MetadataFlags.PreserveMemberRefRids) != 0;
/// <summary>
/// Gets the <see cref="MetadataFlags.PreserveStandAloneSigRids"/> bit
/// </summary>
public bool PreserveStandAloneSigRids => (options.Flags & MetadataFlags.PreserveStandAloneSigRids) != 0;
/// <summary>
/// Gets the <see cref="MetadataFlags.PreserveEventRids"/> bit
/// </summary>
public bool PreserveEventRids => (options.Flags & MetadataFlags.PreserveEventRids) != 0;
/// <summary>
/// Gets the <see cref="MetadataFlags.PreservePropertyRids"/> bit
/// </summary>
public bool PreservePropertyRids => (options.Flags & MetadataFlags.PreservePropertyRids) != 0;
/// <summary>
/// Gets the <see cref="MetadataFlags.PreserveTypeSpecRids"/> bit
/// </summary>
public bool PreserveTypeSpecRids => (options.Flags & MetadataFlags.PreserveTypeSpecRids) != 0;
/// <summary>
/// Gets the <see cref="MetadataFlags.PreserveMethodSpecRids"/> bit
/// </summary>
public bool PreserveMethodSpecRids => (options.Flags & MetadataFlags.PreserveMethodSpecRids) != 0;
/// <summary>
/// Gets/sets the <see cref="MetadataFlags.PreserveStringsOffsets"/> bit
/// </summary>
public bool PreserveStringsOffsets {
get => (options.Flags & MetadataFlags.PreserveStringsOffsets) != 0;
set {
if (value)
options.Flags |= MetadataFlags.PreserveStringsOffsets;
else
options.Flags &= ~MetadataFlags.PreserveStringsOffsets;
}
}
/// <summary>
/// Gets/sets the <see cref="MetadataFlags.PreserveUSOffsets"/> bit
/// </summary>
public bool PreserveUSOffsets {
get => (options.Flags & MetadataFlags.PreserveUSOffsets) != 0;
set {
if (value)
options.Flags |= MetadataFlags.PreserveUSOffsets;
else
options.Flags &= ~MetadataFlags.PreserveUSOffsets;
}
}
/// <summary>
/// Gets/sets the <see cref="MetadataFlags.PreserveBlobOffsets"/> bit
/// </summary>
public bool PreserveBlobOffsets {
get => (options.Flags & MetadataFlags.PreserveBlobOffsets) != 0;
set {
if (value)
options.Flags |= MetadataFlags.PreserveBlobOffsets;
else
options.Flags &= ~MetadataFlags.PreserveBlobOffsets;
}
}
/// <summary>
/// Gets/sets the <see cref="MetadataFlags.PreserveExtraSignatureData"/> bit
/// </summary>
public bool PreserveExtraSignatureData {
get => (options.Flags & MetadataFlags.PreserveExtraSignatureData) != 0;
set {
if (value)
options.Flags |= MetadataFlags.PreserveExtraSignatureData;
else
options.Flags &= ~MetadataFlags.PreserveExtraSignatureData;
}
}
/// <summary>
/// Gets/sets the <see cref="MetadataFlags.KeepOldMaxStack"/> bit
/// </summary>
public bool KeepOldMaxStack {
get => (options.Flags & MetadataFlags.KeepOldMaxStack) != 0;
set {
if (value)
options.Flags |= MetadataFlags.KeepOldMaxStack;
else
options.Flags &= ~MetadataFlags.KeepOldMaxStack;
}
}
/// <summary>
/// Gets/sets the <see cref="MetadataFlags.AlwaysCreateGuidHeap"/> bit
/// </summary>
public bool AlwaysCreateGuidHeap {
get => (options.Flags & MetadataFlags.AlwaysCreateGuidHeap) != 0;
set {
if (value)
options.Flags |= MetadataFlags.AlwaysCreateGuidHeap;
else
options.Flags &= ~MetadataFlags.AlwaysCreateGuidHeap;
}
}
/// <summary>
/// Gets/sets the <see cref="MetadataFlags.AlwaysCreateStringsHeap"/> bit
/// </summary>
public bool AlwaysCreateStringsHeap {
get => (options.Flags & MetadataFlags.AlwaysCreateStringsHeap) != 0;
set {
if (value)
options.Flags |= MetadataFlags.AlwaysCreateStringsHeap;
else
options.Flags &= ~MetadataFlags.AlwaysCreateStringsHeap;
}
}
/// <summary>
/// Gets/sets the <see cref="MetadataFlags.AlwaysCreateUSHeap"/> bit
/// </summary>
public bool AlwaysCreateUSHeap {
get => (options.Flags & MetadataFlags.AlwaysCreateUSHeap) != 0;
set {
if (value)
options.Flags |= MetadataFlags.AlwaysCreateUSHeap;
else
options.Flags &= ~MetadataFlags.AlwaysCreateUSHeap;
}
}
/// <summary>
/// Gets/sets the <see cref="MetadataFlags.AlwaysCreateBlobHeap"/> bit
/// </summary>
public bool AlwaysCreateBlobHeap {
get => (options.Flags & MetadataFlags.AlwaysCreateBlobHeap) != 0;
set {
if (value)
options.Flags |= MetadataFlags.AlwaysCreateBlobHeap;
else
options.Flags &= ~MetadataFlags.AlwaysCreateBlobHeap;
}
}
/// <summary>
/// Gets/sets the <see cref="MetadataFlags.RoslynSortInterfaceImpl"/> bit
/// </summary>
public bool RoslynSortInterfaceImpl {
get => (options.Flags & MetadataFlags.RoslynSortInterfaceImpl) != 0;
set {
if (value)
options.Flags |= MetadataFlags.RoslynSortInterfaceImpl;
else
options.Flags &= ~MetadataFlags.RoslynSortInterfaceImpl;
}
}
/// <summary>
/// Gets/sets the <see cref="MetadataFlags.NoMethodBodies"/> bit
/// </summary>
public bool NoMethodBodies {
get => (options.Flags & MetadataFlags.NoMethodBodies) != 0;
set {
if (value)
options.Flags |= MetadataFlags.NoMethodBodies;
else
options.Flags &= ~MetadataFlags.NoMethodBodies;
}
}
/// <summary>
/// Gets/sets the <see cref="MetadataFlags.NoDotNetResources"/> bit
/// </summary>
public bool NoDotNetResources {
get => (options.Flags & MetadataFlags.NoDotNetResources) != 0;
set {
if (value)
options.Flags |= MetadataFlags.NoDotNetResources;
else
options.Flags &= ~MetadataFlags.NoDotNetResources;
}
}
/// <summary>
/// Gets/sets the <see cref="MetadataFlags.NoFieldData"/> bit
/// </summary>
public bool NoFieldData {
get => (options.Flags & MetadataFlags.NoFieldData) != 0;
set {
if (value)
options.Flags |= MetadataFlags.NoFieldData;
else
options.Flags &= ~MetadataFlags.NoFieldData;
}
}
/// <summary>
/// Gets/sets the <see cref="MetadataFlags.OptimizeCustomAttributeSerializedTypeNames"/> bit
/// </summary>
public bool OptimizeCustomAttributeSerializedTypeNames {
get => (options.Flags & MetadataFlags.OptimizeCustomAttributeSerializedTypeNames) != 0;
set {
if (value)
options.Flags |= MetadataFlags.OptimizeCustomAttributeSerializedTypeNames;
else
options.Flags &= ~MetadataFlags.OptimizeCustomAttributeSerializedTypeNames;
}
}
/// <summary>
/// If <c>true</c>, use the original Field RVAs. If it has no RVA, assume it's a new
/// field value and create a new Field RVA.
/// </summary>
internal bool KeepFieldRVA { get; set; }
/// <summary>
/// Gets the number of methods that will be written.
/// </summary>
protected abstract int NumberOfMethods { get; }
internal Metadata(ModuleDef module, UniqueChunkList<ByteArrayChunk> constants, MethodBodyChunks methodBodies, NetResources netResources, MetadataOptions options, DebugMetadataKind debugKind, bool isStandaloneDebugMetadata) {
this.module = module;
this.constants = constants;
this.methodBodies = methodBodies;
this.netResources = netResources;
this.options = options ?? new MetadataOptions();
metadataHeader = new MetadataHeader(isStandaloneDebugMetadata ? this.options.DebugMetadataHeaderOptions : this.options.MetadataHeaderOptions);
tablesHeap = new TablesHeap(this, isStandaloneDebugMetadata ? this.options.DebugTablesHeapOptions : this.options.TablesHeapOptions);
stringsHeap = new StringsHeap();
usHeap = new USHeap();
guidHeap = new GuidHeap();
blobHeap = new BlobHeap();
pdbHeap = new PdbHeap();
errorContext = new MetadataErrorContext();
this.isStandaloneDebugMetadata = isStandaloneDebugMetadata;
switch (debugKind) {
case DebugMetadataKind.None:
break;
case DebugMetadataKind.Standalone:
Debug.Assert(!isStandaloneDebugMetadata);
//TODO: Refactor this into a smaller class
debugMetadata = new NormalMetadata(module, constants, methodBodies, netResources, options, DebugMetadataKind.None, true);
break;
default:
throw new ArgumentOutOfRangeException(nameof(debugKind));
}
}
/// <summary>
/// Gets the new rid
/// </summary>
/// <param name="module">Value</param>
/// <returns>Its new rid or <c>0</c></returns>
public uint GetRid(ModuleDef module) {
moduleDefInfos.TryGetRid(module, out uint rid);
return rid;
}
/// <summary>
/// Gets the new rid
/// </summary>
/// <param name="tr">Value</param>
/// <returns>Its new rid or <c>0</c></returns>
public abstract uint GetRid(TypeRef tr);
/// <summary>
/// Gets the new rid
/// </summary>
/// <param name="td">Value</param>
/// <returns>Its new rid or <c>0</c></returns>
public abstract uint GetRid(TypeDef td);
/// <summary>
/// Gets the new rid
/// </summary>
/// <param name="fd">Value</param>
/// <returns>Its new rid or <c>0</c></returns>
public abstract uint GetRid(FieldDef fd);
/// <summary>
/// Gets the new rid
/// </summary>
/// <param name="md">Value</param>
/// <returns>Its new rid or <c>0</c></returns>
public abstract uint GetRid(MethodDef md);
/// <summary>