This repository has been archived by the owner on Sep 24, 2020. It is now read-only.
/
CecilLoader.cs
2303 lines (2060 loc) · 81.4 KB
/
CecilLoader.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
// Copyright (c) AlphaSierraPapa for the SharpDevelop Team
//
// Permission is hereby granted, free of charge, to any person obtaining a copy of this
// software and associated documentation files (the "Software"), to deal in the Software
// without restriction, including without limitation the rights to use, copy, modify, merge,
// publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons
// to whom the Software is furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all copies or
// substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
// PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE
// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE.
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Threading;
using ICSharpCode.NRefactory.Documentation;
using ICSharpCode.NRefactory.Semantics;
using ICSharpCode.NRefactory.TypeSystem.Implementation;
using ICSharpCode.NRefactory.Utils;
using Mono.Cecil;
namespace ICSharpCode.NRefactory.TypeSystem
{
/// <summary>
/// Allows loading an IProjectContent from an already compiled assembly.
/// </summary>
/// <remarks>Instance methods are not thread-safe; you need to create multiple instances of CecilLoader
/// if you want to load multiple project contents in parallel.</remarks>
public class CecilLoader
{
/// <summary>
/// Version number of the cecil loader.
/// Should be incremented when fixing bugs in the cecil loader so that project contents cached on disk
/// (which might be incorrect due to the bug) are re-created.
/// </summary>
const int cecilLoaderVersion = 1;
#region Options
/// <summary>
/// Specifies whether to include internal members. The default is false.
/// </summary>
public bool IncludeInternalMembers { get; set; }
/// <summary>
/// Specifies whether to use lazy loading. The default is false.
/// If this property is set to true, the CecilLoader will not copy all the relevant information
/// out of the Cecil object model, but will maintain references to the Cecil objects.
/// This speeds up the loading process and avoids loading unnecessary information, but it causes
/// the Cecil objects to stay in memory (which can significantly increase memory usage).
/// It also prevents serialization of the Cecil-loaded type system.
/// </summary>
/// <remarks>
/// Because the type system can be used on multiple threads, but Cecil is not
/// thread-safe for concurrent read access, the CecilLoader will lock on the <see cref="ModuleDefinition"/> instance
/// for every delay-loading operation.
/// If you access the Cecil objects directly in your application, you may need to take the same lock.
/// </remarks>
public bool LazyLoad { get; set; }
/// <summary>
/// Gets/Sets the documentation provider that is used to retrieve the XML documentation for all members.
/// </summary>
public IDocumentationProvider DocumentationProvider { get; set; }
InterningProvider interningProvider;
/// <summary>
/// Gets/Sets the interning provider.
/// </summary>
public InterningProvider InterningProvider {
get { return interningProvider; }
set {
if (value == null)
throw new ArgumentNullException();
interningProvider = value;
}
}
/// <summary>
/// Gets/Sets the cancellation token used by the cecil loader.
/// </summary>
public CancellationToken CancellationToken { get; set; }
/// <summary>
/// This delegate gets executed whenever an entity was loaded.
/// </summary>
/// <remarks>
/// This callback may be to build a dictionary that maps between
/// entities and cecil objects.
/// Warning: if delay-loading is used and the type system is accessed by multiple threads,
/// the callback may be invoked concurrently on multiple threads.
/// </remarks>
public Action<IUnresolvedEntity, MemberReference> OnEntityLoaded { get; set; }
/// <summary>
/// Gets a value indicating whether this instance stores references to the cecil objects.
/// </summary>
/// <value>
/// <c>true</c> if this instance has references to the cecil objects; otherwise, <c>false</c>.
/// </value>
public bool HasCecilReferences { get { return typeSystemTranslationTable != null; } }
#endregion
ModuleDefinition currentModule;
CecilUnresolvedAssembly currentAssembly;
/// <summary>
/// Initializes a new instance of the <see cref="ICSharpCode.NRefactory.TypeSystem.CecilLoader"/> class.
/// </summary>
public CecilLoader()
{
// Enable interning by default.
this.InterningProvider = new SimpleInterningProvider();
}
/// <summary>
/// Initializes a new instance of the <see cref="ICSharpCode.NRefactory.TypeSystem.CecilLoader"/> class.
/// </summary>
/// <param name='createCecilReferences'>
/// If true references to the cecil objects are hold. In this case the cecil loader can do a type system -> cecil mapping.
/// </param>
[Obsolete("The built-in entity<->cecil mapping is obsolete. Use the OnEntityLoaded callback instead!")]
public CecilLoader(bool createCecilReferences) : this()
{
if (createCecilReferences)
typeSystemTranslationTable = new Dictionary<object, object> ();
}
/// <summary>
/// Creates a nested CecilLoader for lazy-loading.
/// </summary>
private CecilLoader(CecilLoader loader)
{
// use a shared typeSystemTranslationTable
this.typeSystemTranslationTable = loader.typeSystemTranslationTable;
this.IncludeInternalMembers = loader.IncludeInternalMembers;
this.LazyLoad = loader.LazyLoad;
this.OnEntityLoaded = loader.OnEntityLoaded;
this.currentModule = loader.currentModule;
this.currentAssembly = loader.currentAssembly;
// don't use interning - the interning provider is most likely not thread-safe
this.interningProvider = InterningProvider.Dummy;
// don't use cancellation for delay-loaded members
}
#region Load From AssemblyDefinition
/// <summary>
/// Loads the assembly definition into a project content.
/// </summary>
/// <returns>IProjectContent that represents the assembly</returns>
[CLSCompliant(false)]
public IUnresolvedAssembly LoadAssembly(AssemblyDefinition assemblyDefinition)
{
if (assemblyDefinition == null)
throw new ArgumentNullException("assemblyDefinition");
this.currentModule = assemblyDefinition.MainModule;
// Read assembly and module attributes
IList<IUnresolvedAttribute> assemblyAttributes = new List<IUnresolvedAttribute>();
IList<IUnresolvedAttribute> moduleAttributes = new List<IUnresolvedAttribute>();
AddAttributes(assemblyDefinition, assemblyAttributes);
AddAttributes(assemblyDefinition.MainModule, moduleAttributes);
assemblyAttributes = interningProvider.InternList(assemblyAttributes);
moduleAttributes = interningProvider.InternList(moduleAttributes);
this.currentAssembly = new CecilUnresolvedAssembly(assemblyDefinition.Name, this.DocumentationProvider);
currentAssembly.Location = assemblyDefinition.MainModule.FullyQualifiedName;
currentAssembly.AssemblyAttributes.AddRange(assemblyAttributes);
currentAssembly.ModuleAttributes.AddRange(assemblyAttributes);
// Register type forwarders:
foreach (ExportedType type in assemblyDefinition.MainModule.ExportedTypes) {
if (type.IsForwarder) {
int typeParameterCount;
string ns = type.Namespace;
string name = ReflectionHelper.SplitTypeParameterCountFromReflectionName(type.Name, out typeParameterCount);
ns = interningProvider.Intern(ns);
name = interningProvider.Intern(name);
var typeRef = new GetClassTypeReference(GetAssemblyReference(type.Scope), ns, name, typeParameterCount);
typeRef = interningProvider.Intern(typeRef);
var key = new TopLevelTypeName(ns, name, typeParameterCount);
currentAssembly.AddTypeForwarder(key, typeRef);
}
}
// Create and register all types:
CecilLoader cecilLoaderCloneForLazyLoading = LazyLoad ? new CecilLoader(this) : null;
List<TypeDefinition> cecilTypeDefs = new List<TypeDefinition>();
List<DefaultUnresolvedTypeDefinition> typeDefs = new List<DefaultUnresolvedTypeDefinition>();
foreach (ModuleDefinition module in assemblyDefinition.Modules) {
foreach (TypeDefinition td in module.Types) {
this.CancellationToken.ThrowIfCancellationRequested();
if (this.IncludeInternalMembers || (td.Attributes & TypeAttributes.VisibilityMask) == TypeAttributes.Public) {
string name = td.Name;
if (name.Length == 0)
continue;
if (this.LazyLoad) {
var t = new LazyCecilTypeDefinition(cecilLoaderCloneForLazyLoading, td);
currentAssembly.AddTypeDefinition(t);
RegisterCecilObject(t, td);
} else {
var t = CreateTopLevelTypeDefinition(td);
cecilTypeDefs.Add(td);
typeDefs.Add(t);
currentAssembly.AddTypeDefinition(t);
// The registration will happen after the members are initialized
}
}
}
}
// Initialize the type's members:
for (int i = 0; i < typeDefs.Count; i++) {
InitTypeDefinition(cecilTypeDefs[i], typeDefs[i]);
}
AddToTypeSystemTranslationTable(this.currentAssembly, assemblyDefinition);
// Freezing the assembly here is important:
// otherwise it will be frozen when a compilation is first created
// from it. But freezing has the effect of changing some collection instances
// (to ReadOnlyCollection). This hidden mutation was causing a crash
// when the FastSerializer was saving the assembly at the same time as
// the first compilation was created from it.
// By freezing the assembly now, we ensure it is usable on multiple
// threads without issues.
currentAssembly.Freeze();
var result = this.currentAssembly;
this.currentAssembly = null;
this.currentModule = null;
return result;
}
/// <summary>
/// Sets the current module.
/// This causes ReadTypeReference() to use <see cref="DefaultAssemblyReference.CurrentAssembly"/> for references
/// in that module.
/// </summary>
[CLSCompliant(false)]
public void SetCurrentModule(ModuleDefinition module)
{
this.currentModule = module;
}
/// <summary>
/// Loads a type from Cecil.
/// </summary>
/// <param name="typeDefinition">The Cecil TypeDefinition.</param>
/// <returns>ITypeDefinition representing the Cecil type.</returns>
[CLSCompliant(false)]
public IUnresolvedTypeDefinition LoadType(TypeDefinition typeDefinition)
{
if (typeDefinition == null)
throw new ArgumentNullException("typeDefinition");
var td = CreateTopLevelTypeDefinition(typeDefinition);
InitTypeDefinition(typeDefinition, td);
return td;
}
#endregion
#region IUnresolvedAssembly implementation
[Serializable, FastSerializerVersion(cecilLoaderVersion)]
sealed class CecilUnresolvedAssembly : DefaultUnresolvedAssembly, IDocumentationProvider
{
readonly IDocumentationProvider documentationProvider;
public CecilUnresolvedAssembly(AssemblyNameDefinition assemblyName, IDocumentationProvider documentationProvider)
: base(assemblyName.FullName)
{
Debug.Assert(assemblyName != null);
this.documentationProvider = documentationProvider;
}
DocumentationComment IDocumentationProvider.GetDocumentation(IEntity entity)
{
if (documentationProvider != null)
return documentationProvider.GetDocumentation(entity);
else
return null;
}
}
#endregion
#region Load Assembly From Disk
public IUnresolvedAssembly LoadAssemblyFile(string fileName)
{
if (fileName == null)
throw new ArgumentNullException("fileName");
var param = new ReaderParameters { AssemblyResolver = new DummyAssemblyResolver() };
AssemblyDefinition asm = AssemblyDefinition.ReadAssembly(fileName, param);
return LoadAssembly(asm);
}
// used to prevent Cecil from loading referenced assemblies
sealed class DummyAssemblyResolver : IAssemblyResolver
{
public AssemblyDefinition Resolve(AssemblyNameReference name)
{
return null;
}
public AssemblyDefinition Resolve(string fullName)
{
return null;
}
public AssemblyDefinition Resolve(AssemblyNameReference name, ReaderParameters parameters)
{
return null;
}
public AssemblyDefinition Resolve(string fullName, ReaderParameters parameters)
{
return null;
}
}
#endregion
#region Read Type Reference
/// <summary>
/// Reads a type reference.
/// </summary>
/// <param name="type">The Cecil type reference that should be converted into
/// a type system type reference.</param>
/// <param name="typeAttributes">Attributes associated with the Cecil type reference.
/// This is used to support the 'dynamic' type.</param>
[CLSCompliant(false)]
public ITypeReference ReadTypeReference(TypeReference type, ICustomAttributeProvider typeAttributes = null)
{
int typeIndex = 0;
return CreateType(type, typeAttributes, ref typeIndex);
}
ITypeReference CreateType(TypeReference type, ICustomAttributeProvider typeAttributes, ref int typeIndex)
{
while (type is OptionalModifierType || type is RequiredModifierType) {
type = ((TypeSpecification)type).ElementType;
}
if (type == null) {
return SpecialType.UnknownType;
}
if (type is Mono.Cecil.ByReferenceType) {
typeIndex++;
return interningProvider.Intern(
new ByReferenceTypeReference(
CreateType(
(type as Mono.Cecil.ByReferenceType).ElementType,
typeAttributes, ref typeIndex)));
} else if (type is Mono.Cecil.PointerType) {
typeIndex++;
return interningProvider.Intern(
new PointerTypeReference(
CreateType(
(type as Mono.Cecil.PointerType).ElementType,
typeAttributes, ref typeIndex)));
} else if (type is Mono.Cecil.ArrayType) {
typeIndex++;
return interningProvider.Intern(
new ArrayTypeReference(
CreateType(
(type as Mono.Cecil.ArrayType).ElementType,
typeAttributes, ref typeIndex),
(type as Mono.Cecil.ArrayType).Rank));
} else if (type is GenericInstanceType) {
GenericInstanceType gType = (GenericInstanceType)type;
ITypeReference baseType = CreateType(gType.ElementType, typeAttributes, ref typeIndex);
ITypeReference[] para = new ITypeReference[gType.GenericArguments.Count];
for (int i = 0; i < para.Length; ++i) {
typeIndex++;
para[i] = CreateType(gType.GenericArguments[i], typeAttributes, ref typeIndex);
}
return interningProvider.Intern(new ParameterizedTypeReference(baseType, para));
} else if (type is GenericParameter) {
GenericParameter typeGP = (GenericParameter)type;
return TypeParameterReference.Create(typeGP.Owner is MethodDefinition ? EntityType.Method : EntityType.TypeDefinition, typeGP.Position);
} else if (type.IsNested) {
ITypeReference typeRef = CreateType(type.DeclaringType, typeAttributes, ref typeIndex);
int partTypeParameterCount;
string namepart = ReflectionHelper.SplitTypeParameterCountFromReflectionName(type.Name, out partTypeParameterCount);
namepart = interningProvider.Intern(namepart);
return interningProvider.Intern(new NestedTypeReference(typeRef, namepart, partTypeParameterCount));
} else {
string ns = interningProvider.Intern(type.Namespace ?? string.Empty);
string name = type.Name;
if (name == null)
throw new InvalidOperationException("type.Name returned null. Type: " + type.ToString());
if (name == "Object" && ns == "System" && HasDynamicAttribute(typeAttributes, typeIndex)) {
return SpecialType.Dynamic;
} else {
int typeParameterCount;
name = ReflectionHelper.SplitTypeParameterCountFromReflectionName(name, out typeParameterCount);
name = interningProvider.Intern(name);
if (currentAssembly != null) {
IUnresolvedTypeDefinition c = currentAssembly.GetTypeDefinition(ns, name, typeParameterCount);
if (c != null)
return c;
}
return interningProvider.Intern(new GetClassTypeReference(GetAssemblyReference(type.Scope), ns, name, typeParameterCount));
}
}
}
IAssemblyReference GetAssemblyReference(IMetadataScope scope)
{
if (scope == null || scope == currentModule)
return DefaultAssemblyReference.CurrentAssembly;
else
return interningProvider.Intern(new DefaultAssemblyReference(scope.Name));
}
static bool HasDynamicAttribute(ICustomAttributeProvider attributeProvider, int typeIndex)
{
if (attributeProvider == null || !attributeProvider.HasCustomAttributes)
return false;
foreach (CustomAttribute a in attributeProvider.CustomAttributes) {
TypeReference type = a.AttributeType;
if (type.Name == "DynamicAttribute" && type.Namespace == "System.Runtime.CompilerServices") {
if (a.ConstructorArguments.Count == 1) {
CustomAttributeArgument[] values = a.ConstructorArguments[0].Value as CustomAttributeArgument[];
if (values != null && typeIndex < values.Length && values[typeIndex].Value is bool)
return (bool)values[typeIndex].Value;
}
return true;
}
}
return false;
}
#endregion
#region Read Attributes
#region Assembly Attributes
static readonly ITypeReference assemblyVersionAttributeTypeRef = typeof(System.Reflection.AssemblyVersionAttribute).ToTypeReference();
void AddAttributes(AssemblyDefinition assembly, IList<IUnresolvedAttribute> outputList)
{
if (assembly.HasCustomAttributes) {
AddCustomAttributes(assembly.CustomAttributes, outputList);
}
if (assembly.HasSecurityDeclarations) {
AddSecurityAttributes(assembly.SecurityDeclarations, outputList);
}
// AssemblyVersionAttribute
if (assembly.Name.Version != null) {
var assemblyVersion = new DefaultUnresolvedAttribute(assemblyVersionAttributeTypeRef, new[] { KnownTypeReference.String });
assemblyVersion.PositionalArguments.Add(CreateSimpleConstantValue(KnownTypeReference.String, assembly.Name.Version.ToString()));
outputList.Add(interningProvider.Intern(assemblyVersion));
}
}
IConstantValue CreateSimpleConstantValue(ITypeReference type, object value)
{
return interningProvider.Intern(new SimpleConstantValue(type, interningProvider.InternValue(value)));
}
#endregion
#region Module Attributes
void AddAttributes(ModuleDefinition module, IList<IUnresolvedAttribute> outputList)
{
if (module.HasCustomAttributes) {
AddCustomAttributes(module.CustomAttributes, outputList);
}
}
#endregion
#region Parameter Attributes
static readonly IUnresolvedAttribute inAttribute = new DefaultUnresolvedAttribute(typeof(InAttribute).ToTypeReference());
static readonly IUnresolvedAttribute outAttribute = new DefaultUnresolvedAttribute(typeof(OutAttribute).ToTypeReference());
void AddAttributes(ParameterDefinition parameter, DefaultUnresolvedParameter targetParameter)
{
if (!targetParameter.IsOut) {
if (parameter.IsIn)
targetParameter.Attributes.Add(inAttribute);
if (parameter.IsOut)
targetParameter.Attributes.Add(outAttribute);
}
if (parameter.HasCustomAttributes) {
AddCustomAttributes(parameter.CustomAttributes, targetParameter.Attributes);
}
if (parameter.HasMarshalInfo) {
targetParameter.Attributes.Add(ConvertMarshalInfo(parameter.MarshalInfo));
}
}
#endregion
#region Method Attributes
static readonly ITypeReference dllImportAttributeTypeRef = typeof(DllImportAttribute).ToTypeReference();
static readonly SimpleConstantValue trueValue = new SimpleConstantValue(KnownTypeReference.Boolean, true);
static readonly SimpleConstantValue falseValue = new SimpleConstantValue(KnownTypeReference.Boolean, false);
static readonly ITypeReference callingConventionTypeRef = typeof(CallingConvention).ToTypeReference();
static readonly IUnresolvedAttribute preserveSigAttribute = new DefaultUnresolvedAttribute(typeof(PreserveSigAttribute).ToTypeReference());
static readonly ITypeReference methodImplAttributeTypeRef = typeof(MethodImplAttribute).ToTypeReference();
static readonly ITypeReference methodImplOptionsTypeRef = typeof(MethodImplOptions).ToTypeReference();
static bool HasAnyAttributes(MethodDefinition methodDefinition)
{
if (methodDefinition.HasPInvokeInfo)
return true;
if ((methodDefinition.ImplAttributes & ~MethodImplAttributes.CodeTypeMask) != 0)
return true;
if (methodDefinition.MethodReturnType.HasFieldMarshal)
return true;
return methodDefinition.HasCustomAttributes || methodDefinition.MethodReturnType.HasCustomAttributes;
}
void AddAttributes(MethodDefinition methodDefinition, IList<IUnresolvedAttribute> attributes, IList<IUnresolvedAttribute> returnTypeAttributes)
{
MethodImplAttributes implAttributes = methodDefinition.ImplAttributes & ~MethodImplAttributes.CodeTypeMask;
#region DllImportAttribute
if (methodDefinition.HasPInvokeInfo && methodDefinition.PInvokeInfo != null) {
PInvokeInfo info = methodDefinition.PInvokeInfo;
var dllImport = new DefaultUnresolvedAttribute(dllImportAttributeTypeRef, new[] { KnownTypeReference.String });
dllImport.PositionalArguments.Add(CreateSimpleConstantValue(KnownTypeReference.String, info.Module.Name));
if (info.IsBestFitDisabled)
dllImport.AddNamedFieldArgument("BestFitMapping", falseValue);
if (info.IsBestFitEnabled)
dllImport.AddNamedFieldArgument("BestFitMapping", trueValue);
CallingConvention callingConvention;
switch (info.Attributes & PInvokeAttributes.CallConvMask) {
case (PInvokeAttributes)0:
Debug.WriteLine ("P/Invoke calling convention not set on:" + methodDefinition.FullName);
callingConvention = CallingConvention.StdCall;
break;
case PInvokeAttributes.CallConvCdecl:
callingConvention = CallingConvention.Cdecl;
break;
case PInvokeAttributes.CallConvFastcall:
callingConvention = CallingConvention.FastCall;
break;
case PInvokeAttributes.CallConvStdCall:
callingConvention = CallingConvention.StdCall;
break;
case PInvokeAttributes.CallConvThiscall:
callingConvention = CallingConvention.ThisCall;
break;
case PInvokeAttributes.CallConvWinapi:
callingConvention = CallingConvention.Winapi;
break;
default:
throw new NotSupportedException("unknown calling convention");
}
if (callingConvention != CallingConvention.Winapi)
dllImport.AddNamedFieldArgument("CallingConvention", CreateSimpleConstantValue(callingConventionTypeRef, (int)callingConvention));
CharSet charSet = CharSet.None;
switch (info.Attributes & PInvokeAttributes.CharSetMask) {
case PInvokeAttributes.CharSetAnsi:
charSet = CharSet.Ansi;
break;
case PInvokeAttributes.CharSetAuto:
charSet = CharSet.Auto;
break;
case PInvokeAttributes.CharSetUnicode:
charSet = CharSet.Unicode;
break;
}
if (charSet != CharSet.None)
dllImport.AddNamedFieldArgument("CharSet", CreateSimpleConstantValue(charSetTypeRef, (int)charSet));
if (!string.IsNullOrEmpty(info.EntryPoint) && info.EntryPoint != methodDefinition.Name)
dllImport.AddNamedFieldArgument("EntryPoint", CreateSimpleConstantValue(KnownTypeReference.String, info.EntryPoint));
if (info.IsNoMangle)
dllImport.AddNamedFieldArgument("ExactSpelling", trueValue);
if ((implAttributes & MethodImplAttributes.PreserveSig) == MethodImplAttributes.PreserveSig)
implAttributes &= ~MethodImplAttributes.PreserveSig;
else
dllImport.AddNamedFieldArgument("PreserveSig", falseValue);
if (info.SupportsLastError)
dllImport.AddNamedFieldArgument("SetLastError", trueValue);
if (info.IsThrowOnUnmappableCharDisabled)
dllImport.AddNamedFieldArgument("ThrowOnUnmappableChar", falseValue);
if (info.IsThrowOnUnmappableCharEnabled)
dllImport.AddNamedFieldArgument("ThrowOnUnmappableChar", trueValue);
attributes.Add(interningProvider.Intern(dllImport));
}
#endregion
#region PreserveSigAttribute
if (implAttributes == MethodImplAttributes.PreserveSig) {
attributes.Add(preserveSigAttribute);
implAttributes = 0;
}
#endregion
#region MethodImplAttribute
if (implAttributes != 0) {
var methodImpl = new DefaultUnresolvedAttribute(methodImplAttributeTypeRef, new[] { methodImplOptionsTypeRef });
methodImpl.PositionalArguments.Add(CreateSimpleConstantValue(methodImplOptionsTypeRef, (int)implAttributes));
attributes.Add(interningProvider.Intern(methodImpl));
}
#endregion
if (methodDefinition.HasCustomAttributes) {
AddCustomAttributes(methodDefinition.CustomAttributes, attributes);
}
if (methodDefinition.HasSecurityDeclarations) {
AddSecurityAttributes(methodDefinition.SecurityDeclarations, attributes);
}
if (methodDefinition.MethodReturnType.HasMarshalInfo) {
returnTypeAttributes.Add(ConvertMarshalInfo(methodDefinition.MethodReturnType.MarshalInfo));
}
if (methodDefinition.MethodReturnType.HasCustomAttributes) {
AddCustomAttributes(methodDefinition.MethodReturnType.CustomAttributes, returnTypeAttributes);
}
}
#endregion
#region Type Attributes
static readonly DefaultUnresolvedAttribute serializableAttribute = new DefaultUnresolvedAttribute(typeof(SerializableAttribute).ToTypeReference());
static readonly DefaultUnresolvedAttribute comImportAttribute = new DefaultUnresolvedAttribute(typeof(ComImportAttribute).ToTypeReference());
static readonly ITypeReference structLayoutAttributeTypeRef = typeof(StructLayoutAttribute).ToTypeReference();
static readonly ITypeReference layoutKindTypeRef = typeof(LayoutKind).ToTypeReference();
static readonly ITypeReference charSetTypeRef = typeof(CharSet).ToTypeReference();
void AddAttributes(TypeDefinition typeDefinition, IUnresolvedTypeDefinition targetEntity)
{
// SerializableAttribute
if (typeDefinition.IsSerializable)
targetEntity.Attributes.Add(serializableAttribute);
// ComImportAttribute
if (typeDefinition.IsImport)
targetEntity.Attributes.Add(comImportAttribute);
#region StructLayoutAttribute
LayoutKind layoutKind = LayoutKind.Auto;
switch (typeDefinition.Attributes & TypeAttributes.LayoutMask) {
case TypeAttributes.SequentialLayout:
layoutKind = LayoutKind.Sequential;
break;
case TypeAttributes.ExplicitLayout:
layoutKind = LayoutKind.Explicit;
break;
}
CharSet charSet = CharSet.None;
switch (typeDefinition.Attributes & TypeAttributes.StringFormatMask) {
case TypeAttributes.AnsiClass:
charSet = CharSet.Ansi;
break;
case TypeAttributes.AutoClass:
charSet = CharSet.Auto;
break;
case TypeAttributes.UnicodeClass:
charSet = CharSet.Unicode;
break;
}
LayoutKind defaultLayoutKind = (typeDefinition.IsValueType && !typeDefinition.IsEnum) ? LayoutKind.Sequential: LayoutKind.Auto;
if (layoutKind != defaultLayoutKind || charSet != CharSet.Ansi || typeDefinition.PackingSize > 0 || typeDefinition.ClassSize > 0) {
DefaultUnresolvedAttribute structLayout = new DefaultUnresolvedAttribute(structLayoutAttributeTypeRef, new[] { layoutKindTypeRef });
structLayout.PositionalArguments.Add(CreateSimpleConstantValue(layoutKindTypeRef, (int)layoutKind));
if (charSet != CharSet.Ansi) {
structLayout.AddNamedFieldArgument("CharSet", CreateSimpleConstantValue(charSetTypeRef, (int)charSet));
}
if (typeDefinition.PackingSize > 0) {
structLayout.AddNamedFieldArgument("Pack", CreateSimpleConstantValue(KnownTypeReference.Int32, (int)typeDefinition.PackingSize));
}
if (typeDefinition.ClassSize > 0) {
structLayout.AddNamedFieldArgument("Size", CreateSimpleConstantValue(KnownTypeReference.Int32, (int)typeDefinition.ClassSize));
}
targetEntity.Attributes.Add(interningProvider.Intern(structLayout));
}
#endregion
if (typeDefinition.HasCustomAttributes) {
AddCustomAttributes(typeDefinition.CustomAttributes, targetEntity.Attributes);
}
if (typeDefinition.HasSecurityDeclarations) {
AddSecurityAttributes(typeDefinition.SecurityDeclarations, targetEntity.Attributes);
}
}
#endregion
#region Field Attributes
static readonly ITypeReference fieldOffsetAttributeTypeRef = typeof(FieldOffsetAttribute).ToTypeReference();
static readonly IUnresolvedAttribute nonSerializedAttribute = new DefaultUnresolvedAttribute(typeof(NonSerializedAttribute).ToTypeReference());
void AddAttributes(FieldDefinition fieldDefinition, IUnresolvedEntity targetEntity)
{
// FieldOffsetAttribute
if (fieldDefinition.HasLayoutInfo) {
DefaultUnresolvedAttribute fieldOffset = new DefaultUnresolvedAttribute(fieldOffsetAttributeTypeRef, new[] { KnownTypeReference.Int32 });
fieldOffset.PositionalArguments.Add(CreateSimpleConstantValue(KnownTypeReference.Int32, fieldDefinition.Offset));
targetEntity.Attributes.Add(interningProvider.Intern(fieldOffset));
}
// NonSerializedAttribute
if (fieldDefinition.IsNotSerialized) {
targetEntity.Attributes.Add(nonSerializedAttribute);
}
if (fieldDefinition.HasMarshalInfo) {
targetEntity.Attributes.Add(ConvertMarshalInfo(fieldDefinition.MarshalInfo));
}
if (fieldDefinition.HasCustomAttributes) {
AddCustomAttributes(fieldDefinition.CustomAttributes, targetEntity.Attributes);
}
}
#endregion
#region Event Attributes
void AddAttributes(EventDefinition eventDefinition, IUnresolvedEntity targetEntity)
{
if (eventDefinition.HasCustomAttributes) {
AddCustomAttributes(eventDefinition.CustomAttributes, targetEntity.Attributes);
}
}
#endregion
#region Property Attributes
void AddAttributes(PropertyDefinition propertyDefinition, IUnresolvedEntity targetEntity)
{
if (propertyDefinition.HasCustomAttributes) {
AddCustomAttributes(propertyDefinition.CustomAttributes, targetEntity.Attributes);
}
}
#endregion
#region MarshalAsAttribute (ConvertMarshalInfo)
static readonly ITypeReference marshalAsAttributeTypeRef = typeof(MarshalAsAttribute).ToTypeReference();
static readonly ITypeReference unmanagedTypeTypeRef = typeof(UnmanagedType).ToTypeReference();
IUnresolvedAttribute ConvertMarshalInfo(MarshalInfo marshalInfo)
{
DefaultUnresolvedAttribute attr = new DefaultUnresolvedAttribute(marshalAsAttributeTypeRef, new[] { unmanagedTypeTypeRef });
attr.PositionalArguments.Add(CreateSimpleConstantValue(unmanagedTypeTypeRef, (int)marshalInfo.NativeType));
FixedArrayMarshalInfo fami = marshalInfo as FixedArrayMarshalInfo;
if (fami != null) {
attr.AddNamedFieldArgument("SizeConst", CreateSimpleConstantValue(KnownTypeReference.Int32, (int)fami.Size));
if (fami.ElementType != NativeType.None)
attr.AddNamedFieldArgument("ArraySubType", CreateSimpleConstantValue(unmanagedTypeTypeRef, (int)fami.ElementType));
}
SafeArrayMarshalInfo sami = marshalInfo as SafeArrayMarshalInfo;
if (sami != null && sami.ElementType != VariantType.None) {
attr.AddNamedFieldArgument("SafeArraySubType", CreateSimpleConstantValue(typeof(VarEnum).ToTypeReference(), (int)sami.ElementType));
}
ArrayMarshalInfo ami = marshalInfo as ArrayMarshalInfo;
if (ami != null) {
if (ami.ElementType != NativeType.Max)
attr.AddNamedFieldArgument("ArraySubType", CreateSimpleConstantValue(unmanagedTypeTypeRef, (int)ami.ElementType));
if (ami.Size >= 0)
attr.AddNamedFieldArgument("SizeConst", CreateSimpleConstantValue(KnownTypeReference.Int32, (int)ami.Size));
if (ami.SizeParameterMultiplier != 0 && ami.SizeParameterIndex >= 0)
attr.AddNamedFieldArgument("SizeParamIndex", CreateSimpleConstantValue(KnownTypeReference.Int16, (short)ami.SizeParameterIndex));
}
CustomMarshalInfo cmi = marshalInfo as CustomMarshalInfo;
if (cmi != null) {
attr.AddNamedFieldArgument("MarshalType", CreateSimpleConstantValue(KnownTypeReference.String, cmi.ManagedType.FullName));
if (!string.IsNullOrEmpty(cmi.Cookie))
attr.AddNamedFieldArgument("MarshalCookie", CreateSimpleConstantValue(KnownTypeReference.String, cmi.Cookie));
}
FixedSysStringMarshalInfo fssmi = marshalInfo as FixedSysStringMarshalInfo;
if (fssmi != null) {
attr.AddNamedFieldArgument("SizeConst", CreateSimpleConstantValue(KnownTypeReference.Int32, (int)fssmi.Size));
}
return InterningProvider.Intern(attr);
}
#endregion
#region Custom Attributes (ReadAttribute)
void AddCustomAttributes(Mono.Collections.Generic.Collection<CustomAttribute> attributes, IList<IUnresolvedAttribute> targetCollection)
{
foreach (var cecilAttribute in attributes) {
TypeReference type = cecilAttribute.AttributeType;
if (type.Namespace == "System.Runtime.CompilerServices") {
if (type.Name == "DynamicAttribute" || type.Name == "ExtensionAttribute")
continue;
} else if (type.Name == "ParamArrayAttribute" && type.Namespace == "System") {
continue;
}
targetCollection.Add(ReadAttribute(cecilAttribute));
}
}
[CLSCompliant(false)]
public IUnresolvedAttribute ReadAttribute(CustomAttribute attribute)
{
if (attribute == null)
throw new ArgumentNullException("attribute");
MethodReference ctor = attribute.Constructor;
ITypeReference attributeType = ReadTypeReference(attribute.AttributeType);
IList<ITypeReference> ctorParameterTypes = EmptyList<ITypeReference>.Instance;
if (ctor.HasParameters) {
ctorParameterTypes = new ITypeReference[ctor.Parameters.Count];
for (int i = 0; i < ctorParameterTypes.Count; i++) {
ctorParameterTypes[i] = ReadTypeReference(ctor.Parameters[i].ParameterType);
}
ctorParameterTypes = interningProvider.InternList(ctorParameterTypes);
}
return interningProvider.Intern(new CecilUnresolvedAttribute(attributeType, ctorParameterTypes, attribute.GetBlob()));
}
#endregion
#region CecilUnresolvedAttribute
static int GetBlobHashCode(byte[] blob)
{
unchecked {
int hash = 0;
foreach (byte b in blob) {
hash *= 257;
hash += b;
}
return hash;
}
}
static bool BlobEquals(byte[] a, byte[] b)
{
if (a.Length != b.Length)
return false;
for (int i = 0; i < a.Length; i++) {
if (a[i] != b[i])
return false;
}
return true;
}
[Serializable, FastSerializerVersion(cecilLoaderVersion)]
sealed class CecilUnresolvedAttribute : IUnresolvedAttribute, ISupportsInterning
{
internal readonly ITypeReference attributeType;
internal readonly IList<ITypeReference> ctorParameterTypes;
internal readonly byte[] blob;
public CecilUnresolvedAttribute(ITypeReference attributeType, IList<ITypeReference> ctorParameterTypes, byte[] blob)
{
Debug.Assert(attributeType != null);
Debug.Assert(ctorParameterTypes != null);
Debug.Assert(blob != null);
this.attributeType = attributeType;
this.ctorParameterTypes = ctorParameterTypes;
this.blob = blob;
}
DomRegion IUnresolvedAttribute.Region {
get { return DomRegion.Empty; }
}
IAttribute IUnresolvedAttribute.CreateResolvedAttribute(ITypeResolveContext context)
{
if (context.CurrentAssembly == null)
throw new InvalidOperationException("Cannot resolve CecilUnresolvedAttribute without a parent assembly");
return new CecilResolvedAttribute(context, this);
}
int ISupportsInterning.GetHashCodeForInterning()
{
return attributeType.GetHashCode() ^ ctorParameterTypes.GetHashCode() ^ GetBlobHashCode(blob);
}
bool ISupportsInterning.EqualsForInterning(ISupportsInterning other)
{
CecilUnresolvedAttribute o = other as CecilUnresolvedAttribute;
return o != null && attributeType == o.attributeType && ctorParameterTypes == o.ctorParameterTypes
&& BlobEquals(blob, o.blob);
}
}
#endregion
#region CecilResolvedAttribute
sealed class CecilResolvedAttribute : IAttribute
{
readonly ITypeResolveContext context;
readonly byte[] blob;
readonly IList<ITypeReference> ctorParameterTypes;
readonly IType attributeType;
IMethod constructor;
volatile bool constructorResolved;
IList<ResolveResult> positionalArguments;
IList<KeyValuePair<IMember, ResolveResult>> namedArguments;
public CecilResolvedAttribute(ITypeResolveContext context, CecilUnresolvedAttribute unresolved)
{
this.context = context;
this.blob = unresolved.blob;
this.ctorParameterTypes = unresolved.ctorParameterTypes;
this.attributeType = unresolved.attributeType.Resolve(context);
}
public CecilResolvedAttribute(ITypeResolveContext context, IType attributeType)
{
this.context = context;
this.attributeType = attributeType;
this.ctorParameterTypes = EmptyList<ITypeReference>.Instance;
}
public DomRegion Region {
get { return DomRegion.Empty; }
}
public IType AttributeType {
get { return attributeType; }
}
public IMethod Constructor {
get {
if (!constructorResolved) {
constructor = ResolveConstructor();
constructorResolved = true;
}
return constructor;
}
}
IMethod ResolveConstructor()
{
var parameterTypes = ctorParameterTypes.Resolve(context);
foreach (var ctor in attributeType.GetConstructors(m => m.Parameters.Count == parameterTypes.Count)) {
bool ok = true;
for (int i = 0; i < parameterTypes.Count; i++) {
if (!ctor.Parameters[i].Type.Equals(parameterTypes[i])) {
ok = false;
break;
}
}
if (ok)
return ctor;
}
return null;
}
public IList<ResolveResult> PositionalArguments {
get {
var result = LazyInit.VolatileRead(ref this.positionalArguments);
if (result != null) {
return result;
}
DecodeBlob();
return positionalArguments;
}
}
public IList<KeyValuePair<IMember, ResolveResult>> NamedArguments {
get {
var result = LazyInit.VolatileRead(ref this.namedArguments);
if (result != null) {
return result;
}
DecodeBlob();
return namedArguments;
}
}
public override string ToString()
{
return "[" + attributeType.ToString() + "(...)]";
}
void DecodeBlob()
{
var positionalArguments = new List<ResolveResult>();
var namedArguments = new List<KeyValuePair<IMember, ResolveResult>>();
DecodeBlob(positionalArguments, namedArguments);
Interlocked.CompareExchange(ref this.positionalArguments, positionalArguments, null);
Interlocked.CompareExchange(ref this.namedArguments, namedArguments, null);
}
void DecodeBlob(List<ResolveResult> positionalArguments, List<KeyValuePair<IMember, ResolveResult>> namedArguments)
{
if (blob == null)
return;
BlobReader reader = new BlobReader(blob, context.CurrentAssembly);
if (reader.ReadUInt16() != 0x0001) {
Debug.WriteLine("Unknown blob prolog");
return;
}
foreach (var ctorParameter in ctorParameterTypes.Resolve(context)) {
ResolveResult arg = reader.ReadFixedArg(ctorParameter);
positionalArguments.Add(arg);
if (arg.IsError) {
// After a decoding error, we must stop decoding the blob because
// we might have read too few bytes due to the error.
// Just fill up the remaining arguments with ErrorResolveResult: