This repository was archived by the owner on Mar 19, 2021. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 175
/
Copy pathWriter.cs
5717 lines (5672 loc) · 254 KB
/
Writer.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
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#if !NoWriter
using System;
using System.Collections;
#if CCINamespace
using Microsoft.Cci.Metadata;
#else
using System.Compiler.Metadata;
#endif
using System.Diagnostics;
using System.IO;
using System.Globalization;
using System.Runtime.InteropServices;
using System.Security;
#if !ROTOR
using System.Security.Cryptography;
#endif
using System.Text;
#if CCINamespace
namespace Microsoft.Cci{
#else
namespace System.Compiler{
#endif
#if !ROTOR
[ComImport, InterfaceType(ComInterfaceType.InterfaceIsIUnknown), Guid("B01FAFEB-C450-3A4D-BEEC-B4CEEC01E006"), SuppressUnmanagedCodeSecurity]
interface ISymUnmanagedDocumentWriter{
void SetSource(uint sourceSize, [MarshalAs(UnmanagedType.LPArray, SizeParamIndex=0)] byte[] source);
void SetCheckSum(ref Guid algorithmId, uint checkSumSize, [MarshalAs(UnmanagedType.LPArray, SizeParamIndex=1)] byte[] checkSum);
};
[ComImport, InterfaceType(ComInterfaceType.InterfaceIsIUnknown), Guid("2DE91396-3844-3B1D-8E91-41C24FD672EA"), SuppressUnmanagedCodeSecurity]
interface ISymUnmanagedWriter{
ISymUnmanagedDocumentWriter DefineDocument(string url, ref Guid language, ref Guid languageVendor, ref Guid documentType);
void SetUserEntryPoint(uint entryMethod);
void OpenMethod(uint method);
void CloseMethod();
uint OpenScope(uint startOffset);
void CloseScope(uint endOffset);
void SetScopeRange(uint scopeID, uint startOffset, uint endOffset);
void DefineLocalVariable(string name, uint attributes, uint cSig, IntPtr signature, uint addrKind, uint addr1, uint addr2, uint startOffset, uint endOffset);
void DefineParameter(string name, uint attributes, uint sequence, uint addrKind, uint addr1, uint addr2, uint addr3);
void DefineField(uint parent, string name, uint attributes, uint cSig, IntPtr signature, uint addrKind, uint addr1, uint addr2, uint addr3);
void DefineGlobalVariable(string name, uint attributes, uint cSig, IntPtr signature, uint addrKind, uint addr1, uint addr2, uint addr3);
void Close();
void SetSymAttribute(uint parent, string name, uint cData, IntPtr signature);
void OpenNamespace(string name);
void CloseNamespace();
void UsingNamespace(string fullName);
void SetMethodSourceRange(ISymUnmanagedDocumentWriter startDoc, uint startLine, uint startColumn, object endDoc, uint endLine, uint endColumn);
void Initialize([MarshalAs(UnmanagedType.IUnknown)]object emitter, string filename, [MarshalAs(UnmanagedType.IUnknown)]object pIStream, bool fFullBuild);
void GetDebugInfo(ref ImageDebugDirectory pIDD, uint cData, out uint pcData, IntPtr data);
void DefineSequencePoints(ISymUnmanagedDocumentWriter document, uint spCount,
[MarshalAs(UnmanagedType.LPArray, SizeParamIndex=1)] uint[] offsets,
[MarshalAs(UnmanagedType.LPArray, SizeParamIndex=1)] uint[] lines,
[MarshalAs(UnmanagedType.LPArray, SizeParamIndex=1)] uint[] columns,
[MarshalAs(UnmanagedType.LPArray, SizeParamIndex=1)] uint[] endLines,
[MarshalAs(UnmanagedType.LPArray, SizeParamIndex=1)] uint[] endColumns);
void RemapToken(uint oldToken, uint newToken);
void Initialize2([MarshalAs(UnmanagedType.IUnknown)]object emitter, string tempfilename, [MarshalAs(UnmanagedType.IUnknown)]object pIStream, bool fFullBuild, string finalfilename);
void DefineConstant(string name, object value, uint cSig, IntPtr signature);
}
struct ImageDebugDirectory{
internal int Characteristics;
internal int TimeDateStamp;
internal short MajorVersion;
internal short MinorVersion;
internal int Type;
internal int SizeOfData;
internal int AddressOfRawData;
internal int PointerToRawData;
public ImageDebugDirectory(bool zeroFill){
this.Characteristics = 0;
this.TimeDateStamp = 0;
this.MajorVersion = 0;
this.MinorVersion = 0;
this.Type = 0;
this.SizeOfData = 0;
this.AddressOfRawData = 0;
this.PointerToRawData = 0;
}
}
[ComVisible(true), ComImport, InterfaceType(ComInterfaceType.InterfaceIsIUnknown), Guid("BA3FEE4C-ECB9-4e41-83B7-183FA41CD859")]
unsafe public interface IMetaDataEmit{
void SetModuleProps(string szName);
void Save(string szFile, uint dwSaveFlags);
void SaveToStream(void* pIStream, uint dwSaveFlags);
uint GetSaveSize(uint fSave);
uint DefineTypeDef(char* szTypeDef, uint dwTypeDefFlags, uint tkExtends, uint* rtkImplements);
uint DefineNestedType(char* szTypeDef, uint dwTypeDefFlags, uint tkExtends, uint* rtkImplements, uint tdEncloser);
void SetHandler([MarshalAs(UnmanagedType.IUnknown), In]object pUnk);
uint DefineMethod(uint td, char* zName, uint dwMethodFlags, byte* pvSigBlob, uint cbSigBlob, uint ulCodeRVA, uint dwImplFlags);
void DefineMethodImpl(uint td, uint tkBody, uint tkDecl);
uint DefineTypeRefByName(uint tkResolutionScope, char* szName);
uint DefineImportType(IntPtr pAssemImport, void* pbHashValue, uint cbHashValue, IMetaDataImport pImport,
uint tdImport, IntPtr pAssemEmit);
uint DefineMemberRef(uint tkImport, string szName, byte* pvSigBlob, uint cbSigBlob);
uint DefineImportMember(IntPtr pAssemImport, void* pbHashValue, uint cbHashValue,
IMetaDataImport pImport, uint mbMember, IntPtr pAssemEmit, uint tkParent);
uint DefineEvent(uint td, string szEvent, uint dwEventFlags, uint tkEventType, uint mdAddOn, uint mdRemoveOn, uint mdFire, uint *rmdOtherMethods);
void SetClassLayout(uint td, uint dwPackSize, COR_FIELD_OFFSET* rFieldOffsets, uint ulClassSize);
void DeleteClassLayout(uint td);
void SetFieldMarshal(uint tk, byte* pvNativeType, uint cbNativeType);
void DeleteFieldMarshal(uint tk);
uint DefinePermissionSet (uint tk, uint dwAction, void* pvPermission, uint cbPermission);
void SetRVA(uint md, uint ulRVA);
uint GetTokenFromSig(byte* pvSig, uint cbSig);
uint DefineModuleRef(string szName);
void SetParent(uint mr, uint tk);
uint GetTokenFromTypeSpec(byte* pvSig, uint cbSig);
void SaveToMemory(void* pbData, uint cbData);
uint DefineUserString(string szString, uint cchString);
void DeleteToken(uint tkObj);
void SetMethodProps(uint md, uint dwMethodFlags, uint ulCodeRVA, uint dwImplFlags);
void SetTypeDefProps(uint td, uint dwTypeDefFlags, uint tkExtends, uint* rtkImplements);
void SetEventProps(uint ev, uint dwEventFlags, uint tkEventType, uint mdAddOn, uint mdRemoveOn, uint mdFire, uint* rmdOtherMethods);
uint SetPermissionSetProps(uint tk, uint dwAction, void* pvPermission, uint cbPermission);
void DefinePinvokeMap(uint tk, uint dwMappingFlags, string szImportName, uint mrImportDLL);
void SetPinvokeMap(uint tk, uint dwMappingFlags, string szImportName, uint mrImportDLL);
void DeletePinvokeMap(uint tk);
uint DefineCustomAttribute(uint tkObj, uint tkType, void* pCustomAttribute, uint cbCustomAttribute);
void SetCustomAttributeValue(uint pcv, void* pCustomAttribute, uint cbCustomAttribute);
uint DefineField(uint td, string szName, uint dwFieldFlags, byte* pvSigBlob, uint cbSigBlob, uint dwCPlusTypeFlag, void* pValue, uint cchValue);
uint DefineProperty(uint td, string szProperty, uint dwPropFlags, byte *pvSig, uint cbSig, uint dwCPlusTypeFlag,
void* pValue, uint cchValue, uint mdSetter, uint mdGetter, uint *rmdOtherMethods);
uint DefineParam(uint md, uint ulParamSeq, string szName, uint dwParamFlags, uint dwCPlusTypeFlag, void* pValue, uint cchValue);
void SetFieldProps(uint fd, uint dwFieldFlags, uint dwCPlusTypeFlag, void* pValue, uint cchValue);
void SetPropertyProps(uint pr, uint dwPropFlags, uint dwCPlusTypeFlag, void* pValue, uint cchValue, uint mdSetter, uint mdGetter, uint* rmdOtherMethods);
void SetParamProps(uint pd, string szName, uint dwParamFlags, uint dwCPlusTypeFlag, void* pValue, uint cchValue);
uint DefineSecurityAttributeSet(uint tkObj, IntPtr rSecAttrs, uint cSecAttrs);
void ApplyEditAndContinue([MarshalAs(UnmanagedType.IUnknown)]object pImport);
uint TranslateSigWithScope(IntPtr pAssemImport, void* pbHashValue, uint cbHashValue,
IMetaDataImport import, byte* pbSigBlob, uint cbSigBlob, IntPtr pAssemEmit, IMetaDataEmit emit, byte* pvTranslatedSig, uint cbTranslatedSigMax);
void SetMethodImplFlags(uint md, uint dwImplFlags);
void SetFieldRVA(uint fd, uint ulRVA);
void Merge(IMetaDataImport pImport, IntPtr pHostMapToken, [MarshalAs(UnmanagedType.IUnknown)]object pHandler);
void MergeEnd();
}
public struct COR_FIELD_OFFSET{
public uint ridOfField;
public uint ulOffset;
}
[ComVisible(true), ComImport, InterfaceType(ComInterfaceType.InterfaceIsIUnknown), Guid("7DAC8207-D3AE-4c75-9B67-92801A497D44")]
unsafe public interface IMetaDataImport{
[PreserveSig]void CloseEnum(uint hEnum);
uint CountEnum(uint hEnum);
void ResetEnum(uint hEnum, uint ulPos);
uint EnumTypeDefs(ref uint phEnum, [MarshalAs(UnmanagedType.LPArray, SizeParamIndex = 2)] uint[] rTypeDefs, uint cMax);
uint EnumInterfaceImpls(ref uint phEnum, uint td, [MarshalAs(UnmanagedType.LPArray, SizeParamIndex = 3)] uint[] rImpls, uint cMax);
uint EnumTypeRefs(ref uint phEnum, [MarshalAs(UnmanagedType.LPArray, SizeParamIndex = 2)] uint[] rTypeRefs, uint cMax);
uint FindTypeDefByName(string szTypeDef, uint tkEnclosingClass);
Guid GetScopeProps(StringBuilder szName, uint cchName, out uint pchName);
uint GetModuleFromScope();
uint GetTypeDefProps(uint td, IntPtr szTypeDef, uint cchTypeDef, out uint pchTypeDef, IntPtr pdwTypeDefFlags);
uint GetInterfaceImplProps(uint iiImpl, out uint pClass);
uint GetTypeRefProps(uint tr, out uint ptkResolutionScope, StringBuilder szName, uint cchName);
uint ResolveTypeRef(uint tr, [In] ref Guid riid, [MarshalAs(UnmanagedType.Interface)] out object ppIScope);
uint EnumMembers(ref uint phEnum, uint cl, [MarshalAs(UnmanagedType.LPArray, SizeParamIndex = 3)] uint[] rMembers, uint cMax);
uint EnumMembersWithName(ref uint phEnum, uint cl, string szName, [MarshalAs(UnmanagedType.LPArray, SizeParamIndex = 4)] uint[] rMembers, uint cMax);
uint EnumMethods(ref uint phEnum, uint cl, uint* rMethods, uint cMax);
uint EnumMethodsWithName(ref uint phEnum, uint cl, string szName, [MarshalAs(UnmanagedType.LPArray, SizeParamIndex = 4)] uint[] rMethods, uint cMax);
uint EnumFields(ref uint phEnum, uint cl, uint* rFields, uint cMax);
uint EnumFieldsWithName(ref uint phEnum, uint cl, string szName, [MarshalAs(UnmanagedType.LPArray, SizeParamIndex = 4)] uint[] rFields, uint cMax);
uint EnumParams(ref uint phEnum, uint mb, [MarshalAs(UnmanagedType.LPArray, SizeParamIndex = 3)] uint[] rParams, uint cMax);
uint EnumMemberRefs(ref uint phEnum, uint tkParent, [MarshalAs(UnmanagedType.LPArray, SizeParamIndex = 3)] uint[] rMemberRefs, uint cMax);
uint EnumMethodImpls(ref uint phEnum, uint td, [MarshalAs(UnmanagedType.LPArray, SizeParamIndex = 4)] uint[] rMethodBody,
[MarshalAs(UnmanagedType.LPArray, SizeParamIndex = 4)] uint[] rMethodDecl, uint cMax);
uint EnumPermissionSets(ref uint phEnum, uint tk, uint dwActions, [MarshalAs(UnmanagedType.LPArray, SizeParamIndex = 4)] uint[] rPermission,
uint cMax);
uint FindMember(uint td, string szName, [MarshalAs(UnmanagedType.LPArray, SizeParamIndex = 3)] byte[] pvSigBlob, uint cbSigBlob);
uint FindMethod(uint td, string szName, [MarshalAs(UnmanagedType.LPArray, SizeParamIndex = 3)] byte[] pvSigBlob, uint cbSigBlob);
uint FindField(uint td, string szName, [MarshalAs(UnmanagedType.LPArray, SizeParamIndex = 3)] byte[] pvSigBlob, uint cbSigBlob);
uint FindMemberRef(uint td, string szName, [MarshalAs(UnmanagedType.LPArray, SizeParamIndex = 3)] byte[] pvSigBlob, uint cbSigBlob);
uint GetMethodProps(uint mb, out uint pClass, IntPtr szMethod, uint cchMethod, out uint pchMethod, IntPtr pdwAttr,
IntPtr ppvSigBlob, IntPtr pcbSigBlob, IntPtr pulCodeRVA);
unsafe uint GetMemberRefProps(uint mr, ref uint ptk, StringBuilder szMember, uint cchMember, out uint pchMember, out byte* ppvSigBlob);
uint EnumProperties(ref uint phEnum, uint td, uint* rProperties, uint cMax);
uint EnumEvents(ref uint phEnum, uint td, uint* rEvents, uint cMax);
uint GetEventProps(uint ev, out uint pClass, StringBuilder szEvent, uint cchEvent, out uint pchEvent, out uint pdwEventFlags,
out uint ptkEventType, out uint pmdAddOn, out uint pmdRemoveOn, out uint pmdFire,
[MarshalAs(UnmanagedType.LPArray, SizeParamIndex = 11)] uint[] rmdOtherMethod, uint cMax);
uint EnumMethodSemantics(ref uint phEnum, uint mb, [MarshalAs(UnmanagedType.LPArray, SizeParamIndex = 3)] uint[] rEventProp, uint cMax);
uint GetMethodSemantics(uint mb, uint tkEventProp);
uint GetClassLayout(uint td, out uint pdwPackSize, [MarshalAs(UnmanagedType.LPArray, SizeParamIndex = 3)] COR_FIELD_OFFSET[] rFieldOffset, uint cMax, out uint pcFieldOffset);
unsafe uint GetFieldMarshal( uint tk, out byte* ppvNativeType);
uint GetRVA(uint tk, out uint pulCodeRVA);
unsafe uint GetPermissionSetProps(uint pm, out uint pdwAction, out void* ppvPermission);
unsafe uint GetSigFromToken(uint mdSig, out byte *ppvSig);
uint GetModuleRefProps(uint mur, StringBuilder szName, uint cchName);
uint EnumModuleRefs(ref uint phEnum, [MarshalAs(UnmanagedType.LPArray, SizeParamIndex = 2)] uint[] rModuleRefs, uint cmax);
unsafe uint GetTypeSpecFromToken(uint typespec, out byte * ppvSig);
uint GetNameFromToken(uint tk);
uint EnumUnresolvedMethods(ref uint phEnum, [MarshalAs(UnmanagedType.LPArray, SizeParamIndex = 2)] uint[] rMethods, uint cMax);
uint GetUserString(uint stk, StringBuilder szString, uint cchString);
uint GetPinvokeMap(uint tk, out uint pdwMappingFlags, StringBuilder szImportName, uint cchImportName, out uint pchImportName);
uint EnumSignatures(ref uint phEnum, [MarshalAs(UnmanagedType.LPArray, SizeParamIndex = 2)] uint[] rSignatures, uint cmax);
uint EnumTypeSpecs(ref uint phEnum, [MarshalAs(UnmanagedType.LPArray, SizeParamIndex = 2)] uint[] rTypeSpecs, uint cmax);
uint EnumUserStrings(ref uint phEnum, [MarshalAs(UnmanagedType.LPArray, SizeParamIndex = 2)] uint[] rStrings, uint cmax);
[PreserveSig]
int GetParamForMethodIndex(uint md, uint ulParamSeq, out uint pParam);
uint EnumCustomAttributes(ref uint phEnum, uint tk, uint tkType, [MarshalAs(UnmanagedType.LPArray, SizeParamIndex=4)] uint[] rCustomAttributes, uint cMax);
uint GetCustomAttributeProps(uint cv, out uint ptkObj, out uint ptkType, out void * ppBlob);
uint FindTypeRef(uint tkResolutionScope, string szName);
uint GetMemberProps(uint mb, out uint pClass, StringBuilder szMember, uint cchMember, out uint pchMember, out uint pdwAttr,
out byte* ppvSigBlob, out uint pcbSigBlob, out uint pulCodeRVA, out uint pdwImplFlags, out uint pdwCPlusTypeFlag, out void* ppValue);
uint GetFieldProps(uint mb, out uint pClass, StringBuilder szField, uint cchField, out uint pchField, out uint pdwAttr,
out byte* ppvSigBlob, out uint pcbSigBlob, out uint pdwCPlusTypeFlag, out void* ppValue);
uint GetPropertyProps(uint prop, out uint pClass, StringBuilder szProperty, uint cchProperty, out uint pchProperty, out uint pdwPropFlags,
out byte* ppvSig, out uint pbSig, out uint pdwCPlusTypeFlag, out void* ppDefaultValue, out uint pcchDefaultValue, out uint pmdSetter,
out uint pmdGetter, [MarshalAs(UnmanagedType.LPArray, SizeParamIndex = 14)] uint[] rmdOtherMethod, uint cMax);
uint GetParamProps(uint tk, out uint pmd, out uint pulSequence, StringBuilder szName, uint cchName, out uint pchName,
out uint pdwAttr, out uint pdwCPlusTypeFlag, out void* ppValue);
uint GetCustomAttributeByName(uint tkObj, string szName, out void* ppData);
[PreserveSig][return: MarshalAs(UnmanagedType.Bool)]
bool IsValidToken( uint tk);
uint GetNestedClassProps(uint tdNestedClass);
uint GetNativeCallConvFromSig(void* pvSig, uint cbSig);
int IsGlobal(uint pd);
}
[SuppressUnmanagedCodeSecurity]
internal sealed class Ir2md : IMetaDataEmit, IMetaDataImport{
#else
internal sealed class Ir2md{
#endif
private AssemblyNode assembly;
private Module/*!*/ module;
private MetadataWriter/*!*/ writer;
private bool UseGenerics = false;
private bool StripOptionalModifiersFromLocals {
get { return this.module.StripOptionalModifiersFromLocals; }
}
private BinaryWriter/*!*/ blobHeap = new BinaryWriter(new MemoryStream(), System.Text.Encoding.Unicode);
#if WHIDBEYwithGenerics || WHIDBEYwithGenericsAndIEqualityComparer
private Hashtable/*!*/ blobHeapIndex = new Hashtable(new ByteArrayKeyComparer());
#else
private Hashtable/*!*/ blobHeapIndex = new Hashtable(new ByteArrayHasher(), new ByteArrayComparer());
#endif
private Hashtable/*!*/ blobHeapStringIndex = new Hashtable();
private NodeList/*!*/ nodesWithCustomAttributes = new NodeList();
private int customAttributeCount = 0;
private NodeList/*!*/ nodesWithSecurityAttributes = new NodeList();
private int securityAttributeCount = 0;
private NodeList/*!*/ constantTableEntries = new NodeList();
private TrivialHashtable/*!*/ assemblyRefIndex = new TrivialHashtable();
private AssemblyReferenceList/*!*/ assemblyRefEntries = new AssemblyReferenceList();
private TypeNodeList/*!*/ classLayoutEntries = new TypeNodeList();
private TrivialHashtable/*!*/ documentMap = new TrivialHashtable();
private TrivialHashtable/*!*/ eventIndex = new TrivialHashtable();
private EventList/*!*/ eventEntries = new EventList();
private TrivialHashtable/*!*/ eventMapIndex = new TrivialHashtable();
private EventList/*!*/ eventMapEntries = new EventList();
private TrivialHashtable/*!*/ exceptionBlock = new TrivialHashtable();
private TrivialHashtable/*!*/ fieldIndex = new TrivialHashtable();
private FieldList/*!*/ fieldEntries = new FieldList();
private FieldList/*!*/ fieldLayoutEntries = new FieldList();
private FieldList/*!*/ fieldRvaEntries = new FieldList();
private Hashtable/*!*/ fileTableIndex = new Hashtable();
private ModuleList/*!*/ fileTableEntries = new ModuleList();
private Hashtable/*!*/ genericParamIndex = new Hashtable();
private MemberList/*!*/ genericParamEntries = new MemberList();
private TypeNodeList/*!*/ genericParameters = new TypeNodeList();
private TypeNodeList/*!*/ genericParamConstraintEntries = new TypeNodeList();
private ArrayList/*!*/ guidEntries = new ArrayList();
private Hashtable/*!*/ guidIndex = new Hashtable();
private MethodList/*!*/ implMapEntries = new MethodList();
private TypeNodeList/*!*/ interfaceEntries = new TypeNodeList();
private NodeList/*!*/ marshalEntries = new NodeList();
private TrivialHashtable<int>/*!*/ memberRefIndex = new TrivialHashtable<int>();
private MemberList/*!*/ memberRefEntries = new MemberList();
private TrivialHashtable/*!*/ methodBodiesHeapIndex = new TrivialHashtable();
private BinaryWriter/*!*/ methodBodiesHeap = new BinaryWriter(new MemoryStream());
private BinaryWriter/*!*/ methodBodyHeap;
private MethodList/*!*/ methodEntries = new MethodList();
private TrivialHashtable<int>/*!*/ methodIndex = new TrivialHashtable<int>();
private MethodList/*!*/ methodImplEntries = new MethodList();
private MethodInfo/*!*/ methodInfo;
#if !MinimalReader && !CodeContracts
private Method currentMethod;
#endif
private MemberList/*!*/ methodSemanticsEntries = new MemberList();
private MethodList/*!*/ methodSpecEntries = new MethodList();
private Hashtable/*!*/ methodSpecIndex = new Hashtable();
private ModuleReferenceList/*!*/ moduleRefEntries = new ModuleReferenceList();
private Hashtable/*!*/ moduleRefIndex = new Hashtable();
private TypeNodeList/*!*/ nestedClassEntries = new TypeNodeList();
private TrivialHashtable<int>/*!*/ paramIndex = new TrivialHashtable<int>();
private ParameterList/*!*/ paramEntries = new ParameterList();
private TrivialHashtable/*!*/ propertyIndex = new TrivialHashtable();
private PropertyList/*!*/ propertyEntries = new PropertyList();
private TrivialHashtable/*!*/ propertyMapIndex = new TrivialHashtable();
private PropertyList/*!*/ propertyMapEntries = new PropertyList();
private BinaryWriter/*!*/ resourceDataHeap = new BinaryWriter(new MemoryStream());
private BinaryWriter/*!*/ sdataHeap = new BinaryWriter(new MemoryStream());
#if !ROTOR
private ISymUnmanagedWriter symWriter = null;
#endif
private int stackHeight;
private int stackHeightMax;
private int stackHeightExitTotal;
private ArrayList/*!*/ standAloneSignatureEntries = new ArrayList();
private BinaryWriter/*!*/ stringHeap = new BinaryWriter(new MemoryStream());
private Hashtable/*!*/ stringHeapIndex = new Hashtable();
private BinaryWriter/*!*/ tlsHeap = new BinaryWriter(new MemoryStream());
private TrivialHashtable/*!*/ typeDefIndex = new TrivialHashtable();
private TypeNodeList/*!*/ typeDefEntries = new TypeNodeList();
private TrivialHashtable/*!*/ typeRefIndex = new TrivialHashtable();
private TypeNodeList/*!*/ typeRefEntries = new TypeNodeList();
private TrivialHashtable/*!*/ typeSpecIndex = new TrivialHashtable();
private TrivialHashtable/*!*/ structuralTypeSpecIndexFor = new TrivialHashtable();
private TypeNodeList/*!*/ typeSpecEntries = new TypeNodeList();
private TrivialHashtable/*!*/ typeParameterNumber = new TrivialHashtable();
private BinaryWriter/*!*/ userStringHeap = new BinaryWriter(new MemoryStream(), System.Text.Encoding.Unicode);
private Hashtable/*!*/ userStringHeapIndex = new Hashtable();
private byte[] PublicKey;
private int SignatureKeyLength;
internal Ir2md(Module/*!*/ module) {
this.assembly = module as AssemblyNode;
this.module = module;
//^ base();
this.blobHeap.Write((byte)0);
this.stringHeap.Write((byte)0);
this.userStringHeap.Write((byte)0);
if (this.assembly != null) {
this.PublicKey = this.assembly.PublicKeyOrToken;
this.SignatureKeyLength = 0;
for (int j = 0; j < this.assembly.Attributes.Count; j++) {
AttributeNode node = this.assembly.Attributes[j];
if (node == null) continue;
if (node.Type.ToString() == "System.Reflection.AssemblySignatureKeyAttribute") {
string rawString = node.GetPositionalArgument(0).ToString();
this.SignatureKeyLength = rawString.Length / 2;
}
}
}
}
internal static void WritePE(Module/*!*/ module, string debugSymbolsLocation, BinaryWriter/*!*/ writer) {
Ir2md ir2md = new Ir2md(module);
try{
ir2md.SetupMetadataWriter(debugSymbolsLocation);
MetadataWriter mdWriter = ir2md.writer;
mdWriter.WritePE(writer);
}finally{
#if !ROTOR
if (ir2md.symWriter != null)
ir2md.symWriter.Close();
#endif
ir2md.assembly = null;
ir2md.assemblyRefEntries = null;
ir2md.assemblyRefIndex = null;
ir2md.blobHeap = null;
ir2md.blobHeapIndex = null;
ir2md.blobHeapStringIndex = null;
ir2md.classLayoutEntries = null;
ir2md.constantTableEntries = null;
ir2md.documentMap = null;
ir2md.eventEntries = null;
ir2md.eventIndex = null;
ir2md.eventMapEntries = null;
ir2md.eventMapIndex = null;
ir2md.exceptionBlock = null;
ir2md.fieldEntries = null;
ir2md.fieldIndex = null;
ir2md.fieldLayoutEntries = null;
ir2md.fieldRvaEntries = null;
ir2md.fileTableEntries = null;
ir2md.fileTableIndex = null;
ir2md.genericParamConstraintEntries = null;
ir2md.genericParamEntries = null;
ir2md.genericParameters = null;
ir2md.genericParamIndex = null;
ir2md.guidEntries = null;
ir2md.guidIndex = null;
ir2md.implMapEntries = null;
ir2md.interfaceEntries = null;
ir2md.marshalEntries = null;
ir2md.memberRefEntries = null;
ir2md.memberRefIndex = null;
ir2md.methodBodiesHeap = null;
ir2md.methodBodiesHeapIndex = null;
ir2md.methodBodyHeap = null;
ir2md.methodEntries = null;
ir2md.methodImplEntries = null;
ir2md.methodIndex = null;
ir2md.methodInfo = null;
#if !MinimalReader && !CodeContracts
ir2md.currentMethod = null;
#endif
ir2md.methodSemanticsEntries = null;
ir2md.methodSpecEntries = null;
ir2md.methodSpecIndex = null;
ir2md.module = null;
ir2md.moduleRefEntries = null;
ir2md.moduleRefIndex = null;
ir2md.nestedClassEntries = null;
ir2md.nodesWithCustomAttributes = null;
ir2md.nodesWithSecurityAttributes = null;
ir2md.paramEntries = null;
ir2md.paramIndex = null;
ir2md.propertyEntries = null;
ir2md.propertyIndex = null;
ir2md.propertyMapEntries = null;
ir2md.propertyMapIndex = null;
ir2md.PublicKey = null;
ir2md.resourceDataHeap = null;
ir2md.sdataHeap = null;
ir2md.standAloneSignatureEntries = null;
ir2md.stringHeap = null;
ir2md.stringHeapIndex = null;
#if !ROTOR
ir2md.symWriter = null;
#endif
ir2md.tlsHeap = null;
ir2md.typeDefEntries = null;
ir2md.typeDefIndex = null;
ir2md.typeParameterNumber = null;
ir2md.typeRefEntries = null;
ir2md.typeRefIndex = null;
ir2md.typeSpecEntries = null;
ir2md.typeSpecIndex = null;
ir2md.unspecializedFieldFor = null;
ir2md.unspecializedMethodFor = null;
ir2md.userStringHeap = null;
ir2md.userStringHeapIndex = null;
ir2md.writer = null;
ir2md = null;
}
}
private static Guid IID_IUnknown = new Guid("00000000-0000-0000-C000-000000000046");
private static Guid IID_IClassFactory = new Guid("00000001-0000-0000-C000-000000000046");
[ComImport(), Guid("00000001-0000-0000-C000-000000000046"), InterfaceTypeAttribute(ComInterfaceType.InterfaceIsIUnknown)]
interface IClassFactory {
int CreateInstance(
[In, MarshalAs(UnmanagedType.Interface)] object unused,
[In] ref Guid refiid,
[MarshalAs(UnmanagedType.Interface)] out Object ppunk);
int LockServer(
int fLock);
}
delegate int GetClassObjectDelegate([In] ref Guid refclsid,
[In] ref Guid refiid,
[MarshalAs(UnmanagedType.Interface)] out IClassFactory ppUnk);
[DllImport("kernel32.dll", CharSet=CharSet.Ansi, BestFitMapping = false, ThrowOnUnmappableChar = true)]
private static extern int LoadLibrary(string lpFileName);
[DllImport("kernel32.dll", CharSet=CharSet.Ansi, BestFitMapping = false, ThrowOnUnmappableChar = true)]
private static extern GetClassObjectDelegate GetProcAddress(int hModule, string lpProcName);
private static object CrossCompileActivate(string server, Guid guid){
// Poor man's version of Activator.CreateInstance or CoCreate
object o = null;
int hmod = LoadLibrary(server);
if (hmod != 0){
GetClassObjectDelegate del = GetProcAddress(hmod, "DllGetClassObject");
if (del != null) {
IClassFactory icf;
int hr = del(ref guid, ref IID_IClassFactory, out icf);
if (hr == 0 && icf != null){
object temp = null;
hr = icf.CreateInstance(null, ref IID_IUnknown, out temp);
if (hr == 0) o = temp;
}
}
}
return o;
}
private void SetupMetadataWriter(string debugSymbolsLocation){
Version v = TargetPlatform.TargetVersion;
this.UseGenerics = TargetPlatform.UseGenerics;
#if !ROTOR
if (debugSymbolsLocation != null){
// If targeting RTM (Version.Major = 1 and Version.Minor = 0)
// then use Symwriter.pdb as ProgID else use CorSymWriter_SxS
// (Note that RTM version 1.0.3705 has Assembly version 1.0.3300,
// hence the <= 3705 expression. This also leaves room for RTM SP releases
// with slightly different build numbers).
Type t = null;
if (v.Major == 1 && v.Minor == 0 && v.Build <= 3705){
try{
t = Type.GetTypeFromProgID("Symwriter.pdb", false);
this.symWriter = (ISymUnmanagedWriter)Activator.CreateInstance(t);
if (this.symWriter != null)
this.symWriter.Initialize(this, debugSymbolsLocation, null, true);
}catch (Exception){
t = null;
this.symWriter = null;
}
}
if (t == null){
Debug.Assert(this.symWriter == null);
t = Type.GetTypeFromProgID("CorSymWriter_SxS", false);
if (t != null) {
Guid guid = t.GUID;
// If the compiler was built with Whidbey, then mscoree will pick a matching
// diasymreader.dll out of the Whidbey directory. But if we are cross-
// compiling, this is *NOT* what we want. Instead, we want to override
// the shim's logic and explicitly pick a diasymreader.dll from the place
// that matches the version of the output file we are emitting. This is
// strictly illegal by the CLR's rules. However, the CLR does not yet
// support cross-compilation, so we have little choice.
if (!UseGenerics) {
Version vcompiler = typeof(object).Assembly.GetName().Version;
if (vcompiler.Major >= 2) {
// This is the only cross-compilation case we currently support.
string server = Path.Combine(Path.GetDirectoryName(typeof(object).Assembly.Location),
"..\\v1.1.4322\\diasymreader.dll");
object o = CrossCompileActivate(server, guid);
this.symWriter = (ISymUnmanagedWriter)o;
}
}
if (this.symWriter == null) {
this.symWriter = (ISymUnmanagedWriter)Activator.CreateInstance(t);
}
if (this.symWriter != null)
this.symWriter.Initialize(this, debugSymbolsLocation, null, true);
} else {
throw new DebugSymbolsCouldNotBeWrittenException();
}
}
}
#endif
//Visit the module, building lists etc.
this.VisitModule(this.module);
//Use the lists to populate the tables in the metadata writer
#if !ROTOR
MetadataWriter writer = this.writer = new MetadataWriter(this.symWriter);
#else
MetadataWriter writer = this.writer = new MetadataWriter();
#endif
writer.UseGenerics = this.UseGenerics;
if (module.EntryPoint != null){
writer.entryPointToken = this.GetMethodToken(module.EntryPoint);
#if !ROTOR
if (this.symWriter != null) this.symWriter.SetUserEntryPoint((uint)writer.entryPointToken);
#endif
}
writer.dllCharacteristics = module.DllCharacteristics;
writer.moduleKind = module.Kind;
writer.peKind = module.PEKind;
writer.TrackDebugData = module.TrackDebugData;
writer.fileAlignment = module.FileAlignment;
if (writer.fileAlignment < 512) writer.fileAlignment = 512;
writer.PublicKey = this.PublicKey;
writer.SignatureKeyLength = this.SignatureKeyLength;
if (this.assembly != null) this.PopulateAssemblyTable();
this.PopulateClassLayoutTable();
this.PopulateConstantTable();
this.PopulateGenericParamTable(); //Needs to happen before PopulateCustomAttributeTable since it the latter refers to indices in the sorted table
this.PopulateCustomAttributeTable();
this.PopulateDeclSecurityTable();
this.PopulateEventMapTable();
this.PopulateEventTable();
this.PopulateExportedTypeTable();
this.PopulateFieldTable();
this.PopulateFieldLayoutTable();
this.PopulateFieldRVATable();
this.PopulateManifestResourceTable(); //This needs to happen before PopulateFileTable because resources are not visited separately
this.PopulateFileTable();
this.PopulateGenericParamConstraintTable();
this.PopulateImplMapTable();
this.PopulateInterfaceImplTable();
this.PopulateMarshalTable();
this.PopulateMethodTable();
this.PopulateMethodImplTable();
this.PopulateMemberRefTable();
this.PopulateMethodSemanticsTable();
this.PopulateMethodSpecTable();
this.PopulateModuleTable();
this.PopulateModuleRefTable();
this.PopulateNestedClassTable();
this.PopulateParamTable();
this.PopulatePropertyTable();
this.PopulatePropertyMapTable();
this.PopulateStandAloneSigTable();
this.PopulateTypeDefTable();
this.PopulateTypeRefTable();
this.PopulateTypeSpecTable();
this.PopulateGuidTable();
this.PopulateAssemblyRefTable();
this.writer.BlobHeap = (MemoryStream)this.blobHeap.BaseStream; //this.blobHeap = null;
this.writer.SdataHeap = (MemoryStream)this.sdataHeap.BaseStream; //this.sdataHeap = null;
this.writer.TlsHeap = (MemoryStream)this.tlsHeap.BaseStream; //this.tlsHeap = null;
this.writer.StringHeap = (MemoryStream)this.stringHeap.BaseStream; //this.stringHeap = null;
this.writer.UserstringHeap = (MemoryStream)this.userStringHeap.BaseStream; //this.userStringHeap = null;
this.writer.MethodBodiesHeap = (MemoryStream)this.methodBodiesHeap.BaseStream; //this.methodBodiesHeap = null;
this.writer.ResourceDataHeap = (MemoryStream)this.resourceDataHeap.BaseStream; //this.resourceDataHeap = null;
this.writer.Win32Resources = this.module.Win32Resources;
}
int GetAssemblyRefIndex(AssemblyNode/*!*/ assembly) {
if (assembly.Location == "unknown:location")
throw new InvalidOperationException(String.Format(CultureInfo.CurrentCulture,
ExceptionStrings.UnresolvedAssemblyReferenceNotAllowed, assembly.Name));
Object index = this.assemblyRefIndex[assembly.UniqueKey];
if (index == null){
index = this.assemblyRefEntries.Count+1;
AssemblyReference aref = new AssemblyReference(assembly);
if (this.module.UsePublicKeyTokensForAssemblyReferences){
aref.PublicKeyOrToken = aref.PublicKeyToken;
aref.HashValue = null;
aref.Flags = aref.Flags & ~AssemblyFlags.PublicKey;
}
this.assemblyRefEntries.Add(aref);
this.assemblyRefIndex[assembly.UniqueKey] = index;
}
return (int)index;
}
int GetBlobIndex(ExpressionList expressions, ParameterList parameters){
MemoryStream sig = new MemoryStream();
BinaryWriter signature = new BinaryWriter(sig);
this.WriteCustomAttributeSignature(expressions, parameters, false, signature);
byte[] sigBytes = sig.ToArray();
int length = sigBytes.Length;
int index = (int)this.blobHeap.BaseStream.Position;
Ir2md.WriteCompressedInt(this.blobHeap, length);
this.blobHeap.BaseStream.Write(sigBytes, 0, length);
return index;
}
void WriteCustomAttributeSignature(ExpressionList expressions, ParameterList parameters, bool onlyWriteNamedArguments, BinaryWriter signature) {
int n = parameters == null ? 0 : parameters.Count;
int m = expressions == null ? 0 : expressions.Count;
Debug.Assert(m >= n);
int numNamed = m > n ? m - n : 0;
if (onlyWriteNamedArguments) {
Ir2md.WriteCompressedInt(signature, numNamed);
}else{
signature.Write((short)1);
if (parameters != null && expressions != null) {
for (int i = 0; i < n; i++) {
Parameter p = parameters[i];
Expression e = expressions[i];
if (p == null || e == null) continue;
Literal l = e as Literal;
if (l == null) { Debug.Assert(false); continue; }
this.WriteCustomAttributeLiteral(signature, l, p.Type == CoreSystemTypes.Object);
}
}
signature.Write((short)numNamed);
}
if (expressions != null) {
for (int i = n; i < m; i++) {
Expression e = expressions[i];
NamedArgument narg = e as NamedArgument;
if (narg == null) { Debug.Assert(false); continue; }
signature.Write((byte)(narg.IsCustomAttributeProperty ? 0x54 : 0x53));
if (narg.ValueIsBoxed)
signature.Write((byte)ElementType.BoxedEnum);
else if (narg.Value.Type is EnumNode) {
signature.Write((byte)ElementType.Enum);
this.WriteSerializedTypeName(signature, narg.Value.Type);
} else if (narg.Value.Type == CoreSystemTypes.Type)
signature.Write((byte)ElementType.Type);
else if (narg.Value.Type is ArrayType) {
ArrayType arrT = (ArrayType)narg.Value.Type;
if (arrT.ElementType == CoreSystemTypes.Type) {
signature.Write((byte)ElementType.SzArray);
signature.Write((byte)ElementType.Type);
} else {
if (arrT.ElementType is EnumNode) {
signature.Write((byte)ElementType.SzArray);
signature.Write((byte)ElementType.Enum);
this.WriteSerializedTypeName(signature, arrT.ElementType);
} else {
this.WriteTypeSignature(signature, narg.Value.Type);
}
}
} else
this.WriteTypeSignature(signature, narg.Value.Type);
signature.Write(narg.Name.Name, false);
this.WriteCustomAttributeLiteral(signature, (Literal)narg.Value, narg.ValueIsBoxed);
}
}
}
int GetBlobIndex(byte[]/*!*/ blob) {
object indexOb = this.blobHeapIndex[blob];
if (indexOb != null) return (int)indexOb;
int index = (int)this.blobHeap.BaseStream.Position;
int length = blob.Length;
Ir2md.WriteCompressedInt(this.blobHeap, length);
this.blobHeap.BaseStream.Write(blob, 0, length);
this.blobHeapIndex[blob] = index;
return index;
}
int GetBlobIndex(string/*!*/ str) {
object indexOb = this.blobHeapStringIndex[str];
if (indexOb != null) return (int)indexOb;
int index = (int)this.blobHeap.BaseStream.Position;
this.blobHeap.Write((string)str);
this.blobHeapStringIndex[str] = index;
return index;
}
int GetBlobIndex(Field/*!*/ field) {
if (field != null && field.DeclaringType != null && field.DeclaringType.Template != null && field.DeclaringType.Template.IsGeneric)
field = this.GetUnspecializedField(field);
MemoryStream sig = new MemoryStream();
BinaryWriter signature = new BinaryWriter(sig);
signature.Write((byte)0x6);
TypeNode fieldType = field.Type;
if (field.IsVolatile && !(fieldType is RequiredModifier) && SystemTypes.IsVolatile != null)
{
fieldType = RequiredModifier.For(SystemTypes.IsVolatile, fieldType);
}
#if ExtendedRuntime
if (field.HasOutOfBandContract) fieldType = TypeNode.DeepStripModifiers(fieldType, null, SystemTypes.NonNullType);
#endif
if (fieldType == null) { Debug.Fail(""); fieldType = SystemTypes.Object; }
this.WriteTypeSignature(signature, fieldType, true);
return this.GetBlobIndex(sig.ToArray());
}
int GetBlobIndex(MarshallingInformation/*!*/ marshallingInformation) {
MemoryStream sig = new MemoryStream();
BinaryWriter signature = new BinaryWriter(sig);
signature.Write((byte)marshallingInformation.NativeType);
switch (marshallingInformation.NativeType){
case NativeType.SafeArray:
signature.Write((byte)marshallingInformation.ElementType);
if (marshallingInformation.Class != null && marshallingInformation.Class.Length > 0)
signature.Write(marshallingInformation.Class, false);
break;
case NativeType.LPArray:
signature.Write((byte)marshallingInformation.ElementType);
if (marshallingInformation.ParamIndex >= 0 || marshallingInformation.ElementSize > 0) {
if (marshallingInformation.ParamIndex < 0) {
Debug.Fail("MarshallingInformation.ElementSize > 0 should imply that ParamIndex >= 0");
marshallingInformation.ParamIndex = 0;
}
Ir2md.WriteCompressedInt(signature, marshallingInformation.ParamIndex);
}
if (marshallingInformation.ElementSize > 0){
Ir2md.WriteCompressedInt(signature, marshallingInformation.ElementSize);
if (marshallingInformation.NumberOfElements > 0)
Ir2md.WriteCompressedInt(signature, marshallingInformation.NumberOfElements);
}
break;
case NativeType.ByValArray:
Ir2md.WriteCompressedInt(signature, marshallingInformation.Size);
if (marshallingInformation.ElementType != NativeType.NotSpecified)
signature.Write((byte)marshallingInformation.ElementType);
break;
case NativeType.ByValTStr:
Ir2md.WriteCompressedInt(signature, marshallingInformation.Size);
break;
case NativeType.Interface:
if (marshallingInformation.Size > 0)
Ir2md.WriteCompressedInt(signature, marshallingInformation.Size);
break;
case NativeType.CustomMarshaler:
signature.Write((short)0);
signature.Write(marshallingInformation.Class);
signature.Write(marshallingInformation.Cookie);
break;
}
return this.GetBlobIndex(sig.ToArray());
}
int GetBlobIndex(Literal/*!*/ literal) {
int index = (int)this.blobHeap.BaseStream.Position;
TypeNode lType = literal.Type;
EnumNode eType = lType as EnumNode;
if (eType != null) lType = eType.UnderlyingType;
IConvertible ic = literal.Value as IConvertible;
if (ic == null) ic = "";
switch(lType.typeCode){
case ElementType.Boolean: this.blobHeap.Write((byte)1); this.blobHeap.Write(ic.ToBoolean(null)); break;
case ElementType.Char: this.blobHeap.Write((byte)2); this.blobHeap.Write(ic.ToChar(null)); break;
case ElementType.Int8: this.blobHeap.Write((byte)1); this.blobHeap.Write(ic.ToSByte(null)); break;
case ElementType.UInt8: this.blobHeap.Write((byte)1); this.blobHeap.Write(ic.ToByte(null)); break;
case ElementType.Int16: this.blobHeap.Write((byte)2); this.blobHeap.Write(ic.ToInt16(null)); break;
case ElementType.UInt16: this.blobHeap.Write((byte)2); this.blobHeap.Write(ic.ToUInt16(null)); break;
case ElementType.Int32: this.blobHeap.Write((byte)4); this.blobHeap.Write(ic.ToInt32(null)); break;
case ElementType.UInt32: this.blobHeap.Write((byte)4); this.blobHeap.Write(ic.ToUInt32(null)); break;
case ElementType.Int64: this.blobHeap.Write((byte)8); this.blobHeap.Write(ic.ToInt64(null)); break;
case ElementType.UInt64: this.blobHeap.Write((byte)8); this.blobHeap.Write(ic.ToUInt64(null)); break;
case ElementType.Single: this.blobHeap.Write((byte)4); this.blobHeap.Write(ic.ToSingle(null)); break;
case ElementType.Double: this.blobHeap.Write((byte)8); this.blobHeap.Write(ic.ToDouble(null)); break;
case ElementType.String: this.blobHeap.Write((string)literal.Value, false); break;
case ElementType.Array:
case ElementType.Class:
case ElementType.Object:
case ElementType.Reference:
case ElementType.SzArray: this.blobHeap.Write((byte)4); this.blobHeap.Write((int)0); break; //REVIEW: standard implies this should be 0, peverify thinks otherwise.
default: Debug.Assert(false, "Unexpected Literal type"); return 0;
}
return index;
}
int GetBlobIndex(FunctionPointer/*!*/ fp) {
MemoryStream sig = new MemoryStream();
BinaryWriter signature = new BinaryWriter(sig);
this.WriteMethodSignature(signature, fp);
return this.GetBlobIndex(sig.ToArray());
}
int GetBlobIndex(Method/*!*/ method, bool methodSpecSignature) {
MemoryStream sig = new MemoryStream();
BinaryWriter signature = new BinaryWriter(sig);
if (methodSpecSignature)
this.WriteMethodSpecSignature(signature, method);
else
this.WriteMethodSignature(signature, method);
return this.GetBlobIndex(sig.ToArray());
}
int GetBlobIndex(AttributeList/*!*/ securityAttributes) {
MemoryStream sig = new MemoryStream();
BinaryWriter signature = new BinaryWriter(sig);
signature.Write((byte)'.');
Ir2md.WriteCompressedInt(signature, securityAttributes.Count);
foreach (AttributeNode attr in securityAttributes)
this.WriteSecurityAttribute(signature, attr);
return this.GetBlobIndex(sig.ToArray());
}
private void WriteSecurityAttribute(BinaryWriter signature, AttributeNode attr) {
bool isAssemblyQualified = true;
string attrTypeName = this.GetSerializedTypeName(attr.Type, ref isAssemblyQualified);
if (!isAssemblyQualified) {
attrTypeName += ", "+attr.Type.DeclaringModule.ContainingAssembly.StrongName;
}
signature.Write(attrTypeName);
MemoryStream sig = new MemoryStream();
BinaryWriter casig = new BinaryWriter(sig);
MemberBinding mb = attr.Constructor as MemberBinding;
if (mb == null) return;
InstanceInitializer constructor = mb.BoundMember as InstanceInitializer;
if (constructor == null) return;
this.WriteCustomAttributeSignature(attr.Expressions, constructor.Parameters, true, casig);
byte[] sigBytes = sig.ToArray();
int length = sigBytes.Length;
Ir2md.WriteCompressedInt(signature, length);
signature.BaseStream.Write(sigBytes, 0, length);
}
int GetBlobIndex(Property/*!*/ prop) {
MemoryStream sig = new MemoryStream();
BinaryWriter signature = new BinaryWriter(sig);
this.WritePropertySignature(signature, prop);
return this.GetBlobIndex(sig.ToArray());
}
int GetBlobIndex(TypeNode/*!*/ type) {
MemoryStream sig = new MemoryStream();
BinaryWriter signature = new BinaryWriter(sig);
this.WriteTypeSignature(signature, type, true);
return this.GetBlobIndex(sig.ToArray());
}
int GetCustomAttributeParentCodedIndex(Node/*!*/ node) {
switch(node.NodeType){
case NodeType.InstanceInitializer:
case NodeType.StaticInitializer:
case NodeType.Method: return this.GetMethodIndex((Method)node)<<5;
case NodeType.Field: return (this.GetFieldIndex((Field)node)<<5)|1;
case NodeType.Parameter: return (this.GetParamIndex((Parameter)node)<<5)|4;
case NodeType.Class:
case NodeType.DelegateNode:
case NodeType.EnumNode:
case NodeType.Interface:
case NodeType.Struct:
#if !MinimalReader
case NodeType.TupleType:
case NodeType.TypeAlias:
case NodeType.TypeIntersection:
case NodeType.TypeUnion:
#endif
TypeNode t = (TypeNode)node;
if (this.IsStructural(t) && (!t.IsGeneric || (t.Template != null && t.ConsolidatedTemplateArguments != null && t.ConsolidatedTemplateArguments.Count > 0)))
return (this.GetTypeSpecIndex(t) << 5) | 13;
else
return (this.GetTypeDefIndex(t) << 5) | 3;
case NodeType.ClassParameter:
case NodeType.TypeParameter:
if (!this.UseGenerics) goto case NodeType.Class;
return (this.GetGenericParamIndex((TypeNode)node)<<5)|19;
case NodeType.Property: return (this.GetPropertyIndex((Property)node)<<5)|9;
case NodeType.Event: return (this.GetEventIndex((Event)node)<<5)|10;
case NodeType.Module: return (1 << 5) | 7;
case NodeType.Assembly: return (1 << 5) | 14;
default: Debug.Assert(false, "Unexpect custom attribute parent"); return 0;
}
}
#if !ROTOR
ISymUnmanagedDocumentWriter GetDocumentWriter(Document/*!*/ doc)
//^ requires this.symWriter != null;
{
int key = Identifier.For(doc.Name).UniqueIdKey;
object writer = this.documentMap[key];
if (writer == null){
writer = this.symWriter.DefineDocument(doc.Name, ref doc.Language, ref doc.LanguageVendor, ref doc.DocumentType);
this.documentMap[key] = writer;
}
return (ISymUnmanagedDocumentWriter)writer;
}
ISymUnmanagedDocumentWriter GetArbitraryDocWriter()
//^ requires this.symWriter != null;
{
foreach (var writer in this.documentMap.Values)
{
return (ISymUnmanagedDocumentWriter)writer;
}
return null;
}
#endif
int GetEventIndex(Event/*!*/ e) {
return (int)this.eventIndex[e.UniqueKey];
}
int GetFieldIndex(Field/*!*/ f) {
Object index = this.fieldIndex[f.UniqueKey];
if (index == null){
if (this.fieldEntries == null) return 1;
index = this.fieldEntries.Count+1;
this.fieldEntries.Add(f);
this.fieldIndex[f.UniqueKey] = index;
if (f.DefaultValue != null && !(f.DefaultValue.Value is Parameter))
this.constantTableEntries.Add(f);
if (!f.IsStatic && f.DeclaringType != null && (f.DeclaringType.Flags & TypeFlags.ExplicitLayout) != 0)
this.fieldLayoutEntries.Add(f);
if ((f.Flags & FieldFlags.HasFieldRVA) != 0)
this.fieldRvaEntries.Add(f);
if (f.MarshallingInformation != null)
this.marshalEntries.Add(f);
}
return (int)index;
}
int GetGenericParamIndex(TypeNode/*!*/ gp) {
return (int)this.genericParamIndex[gp.UniqueKey];
}
int GetFieldToken(Field/*!*/ f) {
if (f.DeclaringType == null || (f.DeclaringType.DeclaringModule == this.module && !this.IsStructural(f.DeclaringType)))
return 0x04000000 | this.GetFieldIndex(f);
else
return 0x0a000000 | this.GetMemberRefIndex(f);
}
bool IsStructural(TypeNode type){
if (type == null) return false;
if (this.UseGenerics && (type.IsGeneric || type.Template != null && type.Template.IsGeneric)) return true;
switch (type.NodeType){
case NodeType.ArrayType:
case NodeType.Pointer:
case NodeType.Reference:
case NodeType.OptionalModifier:
case NodeType.RequiredModifier:
return true;
case NodeType.ClassParameter:
case NodeType.TypeParameter:
return this.UseGenerics;
}
return false;
}
int GetFileTableIndex(Module/*!*/ module) {
Object index = this.fileTableIndex[module];
if (index == null){
index = this.fileTableEntries.Count+1;
this.fileTableEntries.Add(module);
this.fileTableIndex[module] = index;
}
return (int)index;
}
int GetGuidIndex(Guid guid){
Object index = this.guidIndex[guid];
if (index == null){
index = this.guidEntries.Count+1;
this.guidEntries.Add(guid);
this.guidIndex[guid] = index;
}
return (int)index;
}
internal int GetLocalVarIndex(Local/*!*/ loc) {
#if !MinimalReader
LocalBinding lb = loc as LocalBinding;
if (lb != null) loc = lb.BoundLocal;
#endif
if (this.StripOptionalModifiersFromLocals)
loc.Type = TypeNode.StripModifiers(loc.Type);
MethodInfo methInfo = this.methodInfo;
if (methInfo.localVarSignature == null){
methInfo.localVarSignature = new BinaryWriter(new MemoryStream());
methInfo.localVarSignature.Write((short)0);
methInfo.localVarIndex = new TrivialHashtable<int>();
methInfo.localVarSigTok = 0x11000000 | this.GetStandAloneSignatureIndex(methInfo.localVarSignature);
}
#if true
int index;
if (!methInfo.localVarIndex.TryGetValue(loc.UniqueKey, out index)) {
#else
object index = methInfo.localVarIndex[loc.UniqueKey];
if (index == null) {
#endif
methInfo.localVarIndex[loc.UniqueKey] = index = methInfo.localVarIndex.Count;
#if !ROTOR
int startPosition = 0;
if (this.symWriter != null && loc.Name != null && loc.Name.UniqueIdKey != Identifier.Empty.UniqueIdKey){
methInfo.debugLocals.Add(loc);
methInfo.signatureOffsets.Add(startPosition = methInfo.localVarSignature.BaseStream.Position);
if (loc.Pinned) methInfo.localVarSignature.Write((byte)ElementType.Pinned);
this.WriteTypeSignature(methInfo.localVarSignature, loc.Type, true);
methInfo.signatureLengths.Add(methInfo.localVarSignature.BaseStream.Position - startPosition);
}else{
#endif