Merge pull request #1325 from madrang/CryptoToolsCtorCheck
[mono.git] / mcs / tools / linker / Mono.Linker.Steps / MarkStep.cs
1 //
2 // MarkStep.cs
3 //
4 // Author:
5 //   Jb Evain (jbevain@gmail.com)
6 //
7 // (C) 2006 Jb Evain
8 // (C) 2007 Novell, Inc.
9 //
10 // Permission is hereby granted, free of charge, to any person obtaining
11 // a copy of this software and associated documentation files (the
12 // "Software"), to deal in the Software without restriction, including
13 // without limitation the rights to use, copy, modify, merge, publish,
14 // distribute, sublicense, and/or sell copies of the Software, and to
15 // permit persons to whom the Software is furnished to do so, subject to
16 // the following conditions:
17 //
18 // The above copyright notice and this permission notice shall be
19 // included in all copies or substantial portions of the Software.
20 //
21 // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
22 // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
23 // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
24 // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
25 // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
26 // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
27 // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
28 //
29
30 using System;
31 using System.Collections;
32 using System.Linq;
33
34 using Mono.Cecil;
35 using Mono.Cecil.Cil;
36
37 namespace Mono.Linker.Steps {
38
39         public class MarkStep : IStep {
40
41                 protected LinkContext _context;
42                 protected Queue _methods;
43                 protected ArrayList _virtual_methods;
44
45                 public AnnotationStore Annotations {
46                         get { return _context.Annotations; }
47                 }
48
49                 public MarkStep ()
50                 {
51                         _methods = new Queue ();
52                         _virtual_methods = new ArrayList ();
53                 }
54
55                 public virtual void Process (LinkContext context)
56                 {
57                         _context = context;
58
59                         Initialize ();
60                         Process ();
61                 }
62
63                 void Initialize ()
64                 {
65                         foreach (AssemblyDefinition assembly in _context.GetAssemblies ())
66                                 InitializeAssembly (assembly);
67                 }
68
69                 protected virtual void InitializeAssembly (AssemblyDefinition assembly)
70                 {
71                         MarkAssembly (assembly);
72                         foreach (TypeDefinition type in assembly.MainModule.Types) {
73                                 if (!Annotations.IsMarked (type))
74                                         continue;
75
76                                 InitializeType (type);
77                         }
78                 }
79
80                 void InitializeType (TypeDefinition type)
81                 {
82                         MarkType (type);
83
84                         if (type.HasFields)
85                                 InitializeFields (type);
86                         if (type.HasMethods)
87                                 InitializeMethods (type.Methods);
88
89                         if (type.HasNestedTypes) {
90                                 foreach (var nested in type.NestedTypes) {
91                                         if (Annotations.IsMarked (nested))
92                                                 InitializeType (nested);
93                                 }
94                         }
95                 }
96
97                 void InitializeFields (TypeDefinition type)
98                 {
99                         foreach (FieldDefinition field in type.Fields)
100                                 if (Annotations.IsMarked (field))
101                                         MarkField (field);
102                 }
103
104                 void InitializeMethods (ICollection methods)
105                 {
106                         foreach (MethodDefinition method in methods)
107                                 if (Annotations.IsMarked (method))
108                                         EnqueueMethod (method);
109                 }
110
111                 void Process ()
112                 {
113                         if (QueueIsEmpty ())
114                                 throw new InvalidOperationException ("No entry methods");
115
116                         while (!QueueIsEmpty ()) {
117                                 ProcessQueue ();
118                                 ProcessVirtualMethods ();
119                         }
120                 }
121
122                 void ProcessQueue ()
123                 {
124                         while (!QueueIsEmpty ()) {
125                                 MethodDefinition method = (MethodDefinition) _methods.Dequeue ();
126                                 Annotations.Push (method);
127                                 ProcessMethod (method);
128                                 Annotations.Pop ();
129                         }
130                 }
131
132                 bool QueueIsEmpty ()
133                 {
134                         return _methods.Count == 0;
135                 }
136
137                 protected virtual void EnqueueMethod (MethodDefinition method)
138                 {
139                         _methods.Enqueue (method);
140                 }
141
142                 void ProcessVirtualMethods ()
143                 {
144                         foreach (MethodDefinition method in _virtual_methods)
145                                 ProcessVirtualMethod (method);
146                 }
147
148                 void ProcessVirtualMethod (MethodDefinition method)
149                 {
150                         IList overrides = Annotations.GetOverrides (method);
151                         if (overrides == null)
152                                 return;
153
154                         foreach (MethodDefinition @override in overrides)
155                                 ProcessOverride (@override);
156                 }
157
158                 void ProcessOverride (MethodDefinition method)
159                 {
160                         if (!Annotations.IsMarked (method.DeclaringType))
161                                 return;
162
163                         if (Annotations.IsProcessed (method))
164                                 return;
165
166                         if (Annotations.IsMarked (method))
167                                 return;
168
169                         MarkMethod (method);
170                         ProcessVirtualMethod (method);
171                 }
172
173                 void MarkMarshalSpec (IMarshalInfoProvider spec)
174                 {
175                         if (!spec.HasMarshalInfo)
176                                 return;
177
178                         var marshaler = spec.MarshalInfo as CustomMarshalInfo;
179                         if (marshaler == null)
180                                 return;
181
182                         MarkType (marshaler.ManagedType);
183                 }
184
185                 void MarkCustomAttributes (ICustomAttributeProvider provider)
186                 {
187                         if (!provider.HasCustomAttributes)
188                                 return;
189
190                         foreach (CustomAttribute ca in provider.CustomAttributes)
191                                 MarkCustomAttribute (ca);
192                 }
193
194                 protected virtual void MarkCustomAttribute (CustomAttribute ca)
195                 {
196                         MarkMethod (ca.Constructor);
197
198                         MarkCustomAttributeArguments (ca);
199
200                         TypeReference constructor_type = ca.Constructor.DeclaringType;
201                         TypeDefinition type = constructor_type.Resolve ();
202                         if (type == null)
203                                 throw new ResolutionException (constructor_type);
204
205                         MarkCustomAttributeProperties (ca, type);
206                         MarkCustomAttributeFields (ca, type);
207                 }
208
209                 protected void MarkSecurityDeclarations (ISecurityDeclarationProvider provider)
210                 {
211                         // most security declarations are removed (if linked) but user code might still have some
212                         // and if the attribtues references types then they need to be marked too
213                         if ((provider == null) || !provider.HasSecurityDeclarations)
214                                 return;
215
216                         foreach (var sd in provider.SecurityDeclarations)
217                                 MarkSecurityDeclaration (sd);
218                 }
219
220                 protected virtual void MarkSecurityDeclaration (SecurityDeclaration sd)
221                 {
222                         if (!sd.HasSecurityAttributes)
223                                 return;
224                         
225                         foreach (var sa in sd.SecurityAttributes)
226                                 MarkSecurityAttribute (sa);
227                 }
228
229                 protected virtual void MarkSecurityAttribute (SecurityAttribute sa)
230                 {
231                         TypeReference security_type = sa.AttributeType;
232                         TypeDefinition type = security_type.Resolve ();
233                         if (type == null)
234                                 throw new ResolutionException (security_type);
235                         
236                         MarkType (security_type);
237                         MarkSecurityAttributeProperties (sa, type);
238                         MarkSecurityAttributeFields (sa, type);
239                 }
240
241                 protected void MarkSecurityAttributeProperties (SecurityAttribute sa, TypeDefinition attribute)
242                 {
243                         if (!sa.HasProperties)
244                                 return;
245
246                         foreach (var named_argument in sa.Properties)
247                                 MarkCustomAttributeProperty (named_argument, attribute);
248                 }
249
250                 protected void MarkSecurityAttributeFields (SecurityAttribute sa, TypeDefinition attribute)
251                 {
252                         if (!sa.HasFields)
253                                 return;
254
255                         foreach (var named_argument in sa.Fields)
256                                 MarkCustomAttributeField (named_argument, attribute);
257                 }
258
259                 protected void MarkCustomAttributeProperties (CustomAttribute ca, TypeDefinition attribute)
260                 {
261                         if (!ca.HasProperties)
262                                 return;
263
264                         foreach (var named_argument in ca.Properties)
265                                 MarkCustomAttributeProperty (named_argument, attribute);
266                 }
267
268                 protected void MarkCustomAttributeProperty (CustomAttributeNamedArgument namedArgument, TypeDefinition attribute)
269                 {
270                         PropertyDefinition property = GetProperty (attribute, namedArgument.Name);
271                         if (property != null)
272                                 MarkMethod (property.SetMethod);
273
274                         MarkIfType (namedArgument.Argument);
275                 }
276
277                 PropertyDefinition GetProperty (TypeDefinition type, string propertyname)
278                 {
279                         while (type != null) {
280                                 PropertyDefinition property = type.Properties.FirstOrDefault (p => p.Name == propertyname);
281                                 if (property != null)
282                                         return property;
283
284                                 type = type.BaseType != null ? ResolveTypeDefinition (type.BaseType) : null;
285                         }
286
287                         return null;
288                 }
289
290                 protected void MarkCustomAttributeFields (CustomAttribute ca, TypeDefinition attribute)
291                 {
292                         if (!ca.HasFields)
293                                 return;
294
295                         foreach (var named_argument in ca.Fields)
296                                 MarkCustomAttributeField (named_argument, attribute);
297                 }
298
299                 protected void MarkCustomAttributeField (CustomAttributeNamedArgument namedArgument, TypeDefinition attribute)
300                 {
301                         FieldDefinition field = GetField (attribute, namedArgument.Name);
302                         if (field != null)
303                                 MarkField (field);
304
305                         MarkIfType (namedArgument.Argument);
306                 }
307
308                 FieldDefinition GetField (TypeDefinition type, string fieldname)
309                 {
310                         while (type != null) {
311                                 FieldDefinition field = type.Fields.FirstOrDefault (f => f.Name == fieldname);
312                                 if (field != null)
313                                         return field;
314
315                                 type = type.BaseType != null ? ResolveTypeDefinition (type.BaseType) : null;
316                         }
317
318                         return null;
319                 }
320
321                 void MarkCustomAttributeArguments (CustomAttribute ca)
322                 {
323                         if (!ca.HasConstructorArguments)
324                                 return;
325
326                         foreach (var argument in ca.ConstructorArguments)
327                                 MarkIfType (argument);
328                 }
329
330                 void MarkIfType (CustomAttributeArgument argument)
331                 {
332                         var at = argument.Type;
333                         if (at.IsArray) {
334                                 var et = at.GetElementType ();
335                                 if (et.Namespace != "System" || et.Name != "Type")
336                                         return;
337
338                                 MarkType (et);
339                                 foreach (var cac in (CustomAttributeArgument[]) argument.Value)
340                                         MarkWithResolvedScope ((TypeReference) cac.Value);
341                         } else if (at.Namespace == "System" && at.Name == "Type") {
342                                 MarkType (argument.Type);
343                                 MarkWithResolvedScope ((TypeReference) argument.Value);
344                         }
345                 }
346
347                 // custom attributes encoding means it's possible to have a scope that will point into a PCL facade
348                 // even if we (just before saving) will resolve all type references (bug #26752)
349                 void MarkWithResolvedScope (TypeReference type)
350                 {
351                         if (type == null)
352                                 return;
353
354                         // a GenericInstanceType can could contains generic arguments with scope that
355                         // needs to be updated out of the PCL facade (bug #28823)
356                         var git = (type as GenericInstanceType);
357                         if ((git != null) && git.HasGenericArguments) {
358                                 foreach (var ga in git.GenericArguments)
359                                         MarkWithResolvedScope (ga);
360                                 return;
361                         }
362                         // we cannot set the Scope of a TypeSpecification but it's element type can be set
363                         // e.g. System.String[] -> System.String
364                         var ts = (type as TypeSpecification);
365                         if (ts != null) {
366                                 MarkWithResolvedScope (ts.GetElementType ());
367                                 return;
368                         }
369
370                         var td = type.Resolve ();
371                         if (td != null)
372                                 type.Scope = td.Scope;
373                         MarkType (type);
374                 }
375
376                 protected bool CheckProcessed (IMetadataTokenProvider provider)
377                 {
378                         if (Annotations.IsProcessed (provider))
379                                 return true;
380
381                         Annotations.Processed (provider);
382                         return false;
383                 }
384
385                 protected void MarkAssembly (AssemblyDefinition assembly)
386                 {
387                         if (CheckProcessed (assembly))
388                                 return;
389
390                         ProcessModule (assembly);
391
392                         MarkCustomAttributes (assembly);
393                         MarkSecurityDeclarations (assembly);
394
395                         foreach (ModuleDefinition module in assembly.Modules)
396                                 MarkCustomAttributes (module);
397                 }
398
399                 void ProcessModule (AssemblyDefinition assembly)
400                 {
401                         // Pre-mark <Module> if there is any methods as they need to be executed 
402                         // at assembly load time
403                         foreach (TypeDefinition type in assembly.MainModule.Types)
404                         {
405                                 if (type.Name == "<Module>" && type.HasMethods)
406                                 {
407                                         MarkType (type);
408                                         break;
409                                 }
410                         }
411                 }
412
413                 protected void MarkField (FieldReference reference)
414                 {
415 //                      if (IgnoreScope (reference.DeclaringType.Scope))
416 //                              return;
417
418                         if (reference.DeclaringType is GenericInstanceType)
419                                 MarkType (reference.DeclaringType);
420
421                         FieldDefinition field = ResolveFieldDefinition (reference);
422
423                         if (field == null)
424                                 throw new ResolutionException (reference);
425
426                         if (CheckProcessed (field))
427                                 return;
428
429                         MarkType (field.DeclaringType);
430                         MarkType (field.FieldType);
431                         MarkCustomAttributes (field);
432                         MarkMarshalSpec (field);
433
434                         Annotations.Mark (field);
435                 }
436
437                 protected virtual bool IgnoreScope (IMetadataScope scope)
438                 {
439                         AssemblyDefinition assembly = ResolveAssembly (scope);
440                         return Annotations.GetAction (assembly) != AssemblyAction.Link;
441                 }
442
443                 FieldDefinition ResolveFieldDefinition (FieldReference field)
444                 {
445                         FieldDefinition fd = field as FieldDefinition;
446                         if (fd == null)
447                                 fd = field.Resolve ();
448
449                         return fd;
450                 }
451
452                 void MarkScope (IMetadataScope scope)
453                 {
454                         var provider = scope as IMetadataTokenProvider;
455                         if (provider == null)
456                                 return;
457
458                         Annotations.Mark (provider);
459                 }
460
461                 protected virtual void MarkSerializable (TypeDefinition type)
462                 {
463                         MarkDefaultConstructor (type);
464                         MarkMethodsIf (type.Methods, IsSpecialSerializationConstructorPredicate);
465                 }
466
467                 protected virtual TypeDefinition MarkType (TypeReference reference)
468                 {
469                         if (reference == null)
470                                 return null;
471
472                         reference = GetOriginalType (reference);
473
474                         if (reference is GenericParameter)
475                                 return null;
476
477 //                      if (IgnoreScope (reference.Scope))
478 //                              return;
479
480                         TypeDefinition type = ResolveTypeDefinition (reference);
481
482                         if (type == null)
483                                 throw new ResolutionException (reference);
484
485                         if (CheckProcessed (type))
486                                 return null;
487
488                         Annotations.Push (type);
489
490                         MarkScope (type.Scope);
491                         MarkType (type.BaseType);
492                         MarkType (type.DeclaringType);
493                         MarkCustomAttributes (type);
494                         MarkSecurityDeclarations (type);
495
496                         if (IsMulticastDelegate (type)) {
497                                 MarkMethodCollection (type.Methods);
498                         }
499
500                         if (IsSerializable (type))
501                                 MarkSerializable (type);
502
503                         MarkTypeSpecialCustomAttributes (type);
504
505                         MarkGenericParameterProvider (type);
506
507                         // keep fields for value-types and for classes with LayoutKind.Sequential or Explicit
508                         if (type.IsValueType || !type.IsAutoLayout)
509                                 MarkFields (type, type.IsEnum);
510
511                         if (type.HasInterfaces) {
512                                 foreach (TypeReference iface in type.Interfaces)
513                                         MarkType (iface);
514                         }
515
516                         if (type.HasMethods) {
517                                 MarkMethodsIf (type.Methods, IsVirtualAndHasPreservedParent);
518                                 MarkMethodsIf (type.Methods, IsStaticConstructorPredicate);
519                         }
520
521                         DoAdditionalTypeProcessing (type);
522
523                         Annotations.Pop ();
524
525                         Annotations.Mark (type);
526
527                         ApplyPreserveInfo (type);
528
529                         return type;
530                 }
531
532                 // Allow subclassers to mark additional things when marking a method
533                 protected virtual void DoAdditionalTypeProcessing (TypeDefinition method)
534                 {
535                 }
536
537                 void MarkTypeSpecialCustomAttributes (TypeDefinition type)
538                 {
539                         if (!type.HasCustomAttributes)
540                                 return;
541
542                         foreach (CustomAttribute attribute in type.CustomAttributes) {
543                                 switch (attribute.Constructor.DeclaringType.FullName) {
544                                 case "System.Xml.Serialization.XmlSchemaProviderAttribute":
545                                         MarkXmlSchemaProvider (type, attribute);
546                                         break;
547                                 }
548                         }
549                 }
550
551                 void MarkMethodSpecialCustomAttributes (MethodDefinition method)
552                 {
553                         if (!method.HasCustomAttributes)
554                                 return;
555
556                         foreach (CustomAttribute attribute in method.CustomAttributes) {
557                                 switch (attribute.Constructor.DeclaringType.FullName) {
558                                 case "System.Web.Services.Protocols.SoapHeaderAttribute":
559                                         MarkSoapHeader (method, attribute);
560                                         break;
561                                 }
562                         }
563                 }
564
565                 void MarkXmlSchemaProvider (TypeDefinition type, CustomAttribute attribute)
566                 {
567                         string method_name;
568                         if (!TryGetStringArgument (attribute, out method_name))
569                                 return;
570
571                         MarkNamedMethod (type, method_name);
572                 }
573
574                 static bool TryGetStringArgument (CustomAttribute attribute, out string argument)
575                 {
576                         argument = null;
577
578                         if (attribute.ConstructorArguments.Count < 1)
579                                 return false;
580
581                         argument = attribute.ConstructorArguments [0].Value as string;
582
583                         return argument != null;
584                 }
585
586                 protected int MarkNamedMethod (TypeDefinition type, string method_name)
587                 {
588                         if (!type.HasMethods)
589                                 return 0;
590
591                         int count = 0;
592                         foreach (MethodDefinition method in type.Methods) {
593                                 if (method.Name != method_name)
594                                         continue;
595
596                                 MarkMethod (method);
597                                 count++;
598                         }
599
600                         return count;
601                 }
602
603                 void MarkSoapHeader (MethodDefinition method, CustomAttribute attribute)
604                 {
605                         string member_name;
606                         if (!TryGetStringArgument (attribute, out member_name))
607                                 return;
608
609                         MarkNamedField (method.DeclaringType, member_name);
610                         MarkNamedProperty (method.DeclaringType, member_name);
611                 }
612
613                 void MarkNamedField (TypeDefinition type, string field_name)
614                 {
615                         if (!type.HasFields)
616                                 return;
617
618                         foreach (FieldDefinition field in type.Fields) {
619                                 if (field.Name != field_name)
620                                         continue;
621
622                                 MarkField (field);
623                         }
624                 }
625
626                 void MarkNamedProperty (TypeDefinition type, string property_name)
627                 {
628                         if (!type.HasProperties)
629                                 return;
630
631                         foreach (PropertyDefinition property in type.Properties) {
632                                 if (property.Name != property_name)
633                                         continue;
634
635                                 MarkMethod (property.GetMethod);
636                                 MarkMethod (property.SetMethod);
637                         }
638                 }
639
640                 void MarkGenericParameterProvider (IGenericParameterProvider provider)
641                 {
642                         if (!provider.HasGenericParameters)
643                                 return;
644
645                         foreach (GenericParameter parameter in provider.GenericParameters)
646                                 MarkGenericParameter (parameter);
647                 }
648
649                 void MarkGenericParameter (GenericParameter parameter)
650                 {
651                         MarkCustomAttributes (parameter);
652                         foreach (TypeReference constraint in parameter.Constraints)
653                                 MarkType (constraint);
654                 }
655
656                 bool IsVirtualAndHasPreservedParent (MethodDefinition method)
657                 {
658                         if (!method.IsVirtual)
659                                 return false;
660
661                         var base_list = Annotations.GetBaseMethods (method);
662                         if (base_list == null)
663                                 return false;
664
665                         foreach (MethodDefinition @base in base_list) {
666                                 if (IgnoreScope (@base.DeclaringType.Scope))
667                                         return true;
668
669                                 if (IsVirtualAndHasPreservedParent (@base))
670                                         return true;
671                         }
672
673                         return false;
674                 }
675
676                 static MethodPredicate IsSpecialSerializationConstructorPredicate = new MethodPredicate (IsSpecialSerializationConstructor);
677
678                 static bool IsSpecialSerializationConstructor (MethodDefinition method)
679                 {
680                         if (!IsConstructor (method))
681                                 return false;
682
683                         var parameters = method.Parameters;
684                         if (parameters.Count != 2)
685                                 return false;
686
687                         return parameters [0].ParameterType.Name == "SerializationInfo" &&
688                                 parameters [1].ParameterType.Name == "StreamingContext";
689                 }
690
691                 delegate bool MethodPredicate (MethodDefinition method);
692
693                 void MarkMethodsIf (ICollection methods, MethodPredicate predicate)
694                 {
695                         foreach (MethodDefinition method in methods)
696                                 if (predicate (method))
697                                         MarkMethod (method);
698                 }
699
700                 static MethodPredicate IsDefaultConstructorPredicate = new MethodPredicate (IsDefaultConstructor);
701
702                 static bool IsDefaultConstructor (MethodDefinition method)
703                 {
704                         return IsConstructor (method) && !method.HasParameters;
705                 }
706
707                 static bool IsConstructor (MethodDefinition method)
708                 {
709                         return method.IsConstructor && !method.IsStatic;
710                 }
711
712                 protected void MarkDefaultConstructor (TypeDefinition type)
713                 {
714                         if ((type == null) || !type.HasMethods)
715                                 return;
716
717                         MarkMethodsIf (type.Methods, IsDefaultConstructorPredicate);
718                 }
719
720                 static MethodPredicate IsStaticConstructorPredicate = new MethodPredicate (IsStaticConstructor);
721
722                 static bool IsStaticConstructor (MethodDefinition method)
723                 {
724                         return method.IsConstructor && method.IsStatic;
725                 }
726
727                 static bool IsSerializable (TypeDefinition td)
728                 {
729                         return (td.Attributes & TypeAttributes.Serializable) != 0;
730                 }
731
732                 static bool IsMulticastDelegate (TypeDefinition td)
733                 {
734                         return td.BaseType != null && td.BaseType.FullName == "System.MulticastDelegate";
735                 }
736
737                 protected TypeDefinition ResolveTypeDefinition (TypeReference type)
738                 {
739                         TypeDefinition td = type as TypeDefinition;
740                         if (td == null)
741                                 td = type.Resolve ();
742
743                         return td;
744                 }
745
746                 protected TypeReference GetOriginalType (TypeReference type)
747                 {
748                         while (type is TypeSpecification) {
749                                 GenericInstanceType git = type as GenericInstanceType;
750                                 if (git != null)
751                                         MarkGenericArguments (git);
752
753                                 var mod = type as IModifierType;
754                                 if (mod != null)
755                                         MarkModifierType (mod);
756
757                                 type = ((TypeSpecification) type).ElementType;
758                         }
759
760                         return type;
761                 }
762
763                 void MarkModifierType (IModifierType mod)
764                 {
765                         MarkType (mod.ModifierType);
766                 }
767
768                 void MarkGenericArguments (IGenericInstance instance)
769                 {
770                         foreach (TypeReference argument in instance.GenericArguments)
771                                 MarkType (argument);
772
773                         MarkGenericArgumentConstructors (instance);
774                 }
775
776                 void MarkGenericArgumentConstructors (IGenericInstance instance)
777                 {
778                         var arguments = instance.GenericArguments;
779
780                         var generic_element = GetGenericProviderFromInstance (instance);
781                         if (generic_element == null)
782                                 return;
783
784                         var parameters = generic_element.GenericParameters;
785
786                         if (arguments.Count != parameters.Count)
787                                 return;
788
789                         for (int i = 0; i < arguments.Count; i++) {
790                                 var argument = arguments [i];
791                                 var parameter = parameters [i];
792
793                                 if (!parameter.HasDefaultConstructorConstraint)
794                                         continue;
795
796                                 var argument_definition = ResolveTypeDefinition (argument);
797                                 if (argument_definition == null)
798                                         continue;
799
800                                 MarkMethodsIf (argument_definition.Methods, ctor => !ctor.IsStatic && !ctor.HasParameters);
801                         }
802                 }
803
804                 IGenericParameterProvider GetGenericProviderFromInstance (IGenericInstance instance)
805                 {
806                         var method = instance as GenericInstanceMethod;
807                         if (method != null)
808                                 return ResolveMethodDefinition (method.ElementMethod);
809
810                         var type = instance as GenericInstanceType;
811                         if (type != null)
812                                 return ResolveTypeDefinition (type.ElementType);
813
814                         return null;
815                 }
816
817                 void ApplyPreserveInfo (TypeDefinition type)
818                 {
819                         ApplyPreserveMethods (type);
820
821                         if (!Annotations.IsPreserved (type))
822                                 return;
823
824                         switch (Annotations.GetPreserve (type)) {
825                         case TypePreserve.All:
826                                 MarkFields (type, true);
827                                 MarkMethods (type);
828                                 break;
829                         case TypePreserve.Fields:
830                                 MarkFields (type, true);
831                                 break;
832                         case TypePreserve.Methods:
833                                 MarkMethods (type);
834                                 break;
835                         }
836                 }
837
838                 void ApplyPreserveMethods (TypeDefinition type)
839                 {
840                         var list = Annotations.GetPreservedMethods (type);
841                         if (list == null)
842                                 return;
843
844                         MarkMethodCollection (list);
845                 }
846
847                 void ApplyPreserveMethods (MethodDefinition method)
848                 {
849                         var list = Annotations.GetPreservedMethods (method);
850                         if (list == null)
851                                 return;
852
853                         MarkMethodCollection (list);
854                 }
855
856                 protected void MarkFields (TypeDefinition type, bool includeStatic)
857                 {
858                         if (!type.HasFields)
859                                 return;
860
861                         foreach (FieldDefinition field in type.Fields) {
862                                 if (!includeStatic && field.IsStatic)
863                                         continue;
864                                 MarkField (field);
865                         }
866                 }
867
868                 protected virtual void MarkMethods (TypeDefinition type)
869                 {
870                         if (type.HasMethods)
871                                 MarkMethodCollection (type.Methods);
872                 }
873
874                 void MarkMethodCollection (IEnumerable methods)
875                 {
876                         foreach (MethodDefinition method in methods)
877                                 MarkMethod (method);
878                 }
879
880                 protected virtual MethodDefinition MarkMethod (MethodReference reference)
881                 {
882                         reference = GetOriginalMethod (reference);
883
884                         if (reference.DeclaringType is ArrayType)
885                                 return null;
886
887                         Annotations.Push (reference);
888                         if (reference.DeclaringType is GenericInstanceType)
889                                 MarkType (reference.DeclaringType);
890
891 //                      if (IgnoreScope (reference.DeclaringType.Scope))
892 //                              return;
893
894                         MethodDefinition method = ResolveMethodDefinition (reference);
895
896                         if (method == null) {
897                                 Annotations.Pop ();
898                                 throw new ResolutionException (reference);
899                         }
900
901                         if (Annotations.GetAction (method) == MethodAction.Nothing)
902                                 Annotations.SetAction (method, MethodAction.Parse);
903
904                         EnqueueMethod (method);
905
906                         Annotations.Pop ();
907
908                         return method;
909                 }
910
911                 AssemblyDefinition ResolveAssembly (IMetadataScope scope)
912                 {
913                         AssemblyDefinition assembly = _context.Resolve (scope);
914                         MarkAssembly (assembly);
915                         return assembly;
916                 }
917
918                 protected MethodReference GetOriginalMethod (MethodReference method)
919                 {
920                         while (method is MethodSpecification) {
921                                 GenericInstanceMethod gim = method as GenericInstanceMethod;
922                                 if (gim != null)
923                                         MarkGenericArguments (gim);
924
925                                 method = ((MethodSpecification) method).ElementMethod;
926                         }
927
928                         return method;
929                 }
930
931                 MethodDefinition ResolveMethodDefinition (MethodReference method)
932                 {
933                         MethodDefinition md = method as MethodDefinition;
934                         if (md == null)
935                                 md = method.Resolve ();
936
937                         return md;
938                 }
939
940                 protected virtual void ProcessMethod (MethodDefinition method)
941                 {
942                         if (CheckProcessed (method))
943                                 return;
944
945                         MarkType (method.DeclaringType);
946                         MarkCustomAttributes (method);
947                         MarkSecurityDeclarations (method);
948
949                         MarkGenericParameterProvider (method);
950
951                         if (IsPropertyMethod (method))
952                                 MarkProperty (GetProperty (method));
953                         else if (IsEventMethod (method))
954                                 MarkEvent (GetEvent (method));
955
956                         if (method.HasParameters) {
957                                 foreach (ParameterDefinition pd in method.Parameters) {
958                                         MarkType (pd.ParameterType);
959                                         MarkCustomAttributes (pd);
960                                         MarkMarshalSpec (pd);
961                                 }
962                         }
963
964                         if (method.HasOverrides) {
965                                 foreach (MethodReference ov in method.Overrides)
966                                         MarkMethod (ov);
967                         }
968
969                         MarkMethodSpecialCustomAttributes (method);
970
971                         if (method.IsVirtual)
972                                 _virtual_methods.Add (method);
973
974                         MarkBaseMethods (method);
975
976                         MarkType (method.ReturnType);
977                         MarkCustomAttributes (method.MethodReturnType);
978                         MarkMarshalSpec (method.MethodReturnType);
979
980                         if (ShouldParseMethodBody (method))
981                                 MarkMethodBody (method.Body);
982
983                         DoAdditionalMethodProcessing (method);
984
985                         Annotations.Mark (method);
986
987                         ApplyPreserveMethods (method);
988                 }
989
990                 // Allow subclassers to mark additional things when marking a method
991                 protected virtual void DoAdditionalMethodProcessing (MethodDefinition method)
992                 {
993                 }
994
995                 void MarkBaseMethods (MethodDefinition method)
996                 {
997                         IList base_methods = Annotations.GetBaseMethods (method);
998                         if (base_methods == null)
999                                 return;
1000
1001                         foreach (MethodDefinition base_method in base_methods) {
1002                                 if (base_method.DeclaringType.IsInterface && !method.DeclaringType.IsInterface)
1003                                         continue;
1004
1005                                 MarkMethod (base_method);
1006                                 MarkBaseMethods (base_method);
1007                         }
1008                 }
1009
1010                 bool ShouldParseMethodBody (MethodDefinition method)
1011                 {
1012                         if (!method.HasBody)
1013                                 return false;
1014
1015                         AssemblyDefinition assembly = ResolveAssembly (method.DeclaringType.Scope);
1016                         return (Annotations.GetAction (method) == MethodAction.ForceParse ||
1017                                 (Annotations.GetAction (assembly) == AssemblyAction.Link && Annotations.GetAction (method) == MethodAction.Parse));
1018                 }
1019
1020                 static internal bool IsPropertyMethod (MethodDefinition md)
1021                 {
1022                         return (md.SemanticsAttributes & MethodSemanticsAttributes.Getter) != 0 ||
1023                                 (md.SemanticsAttributes & MethodSemanticsAttributes.Setter) != 0;
1024                 }
1025
1026                 static bool IsEventMethod (MethodDefinition md)
1027                 {
1028                         return (md.SemanticsAttributes & MethodSemanticsAttributes.AddOn) != 0 ||
1029                                 (md.SemanticsAttributes & MethodSemanticsAttributes.Fire) != 0 ||
1030                                 (md.SemanticsAttributes & MethodSemanticsAttributes.RemoveOn) != 0;
1031                 }
1032
1033                 static internal PropertyDefinition GetProperty (MethodDefinition md)
1034                 {
1035                         TypeDefinition declaringType = (TypeDefinition) md.DeclaringType;
1036                         foreach (PropertyDefinition prop in declaringType.Properties)
1037                                 if (prop.GetMethod == md || prop.SetMethod == md)
1038                                         return prop;
1039
1040                         return null;
1041                 }
1042
1043                 static EventDefinition GetEvent (MethodDefinition md)
1044                 {
1045                         TypeDefinition declaringType = (TypeDefinition) md.DeclaringType;
1046                         foreach (EventDefinition evt in declaringType.Events)
1047                                 if (evt.AddMethod == md || evt.InvokeMethod == md || evt.RemoveMethod == md)
1048                                         return evt;
1049
1050                         return null;
1051                 }
1052
1053                 protected void MarkProperty (PropertyDefinition prop)
1054                 {
1055                         MarkCustomAttributes (prop);
1056                 }
1057
1058                 protected void MarkEvent (EventDefinition evt)
1059                 {
1060                         MarkCustomAttributes (evt);
1061                         MarkMethodIfNotNull (evt.AddMethod);
1062                         MarkMethodIfNotNull (evt.InvokeMethod);
1063                         MarkMethodIfNotNull (evt.RemoveMethod);
1064                 }
1065
1066                 void MarkMethodIfNotNull (MethodReference method)
1067                 {
1068                         if (method == null)
1069                                 return;
1070
1071                         MarkMethod (method);
1072                 }
1073
1074                 protected virtual void MarkMethodBody (MethodBody body)
1075                 {
1076                         foreach (VariableDefinition var in body.Variables)
1077                                 MarkType (var.VariableType);
1078
1079                         foreach (ExceptionHandler eh in body.ExceptionHandlers)
1080                                 if (eh.HandlerType == ExceptionHandlerType.Catch)
1081                                         MarkType (eh.CatchType);
1082
1083                         foreach (Instruction instruction in body.Instructions)
1084                                 MarkInstruction (instruction);
1085                 }
1086
1087                 protected virtual void MarkInstruction (Instruction instruction)
1088                 {
1089                         switch (instruction.OpCode.OperandType) {
1090                         case OperandType.InlineField:
1091                                 MarkField ((FieldReference) instruction.Operand);
1092                                 break;
1093                         case OperandType.InlineMethod:
1094                                 MarkMethod ((MethodReference) instruction.Operand);
1095                                 break;
1096                         case OperandType.InlineTok:
1097                                 object token = instruction.Operand;
1098                                 if (token is TypeReference)
1099                                         MarkType ((TypeReference) token);
1100                                 else if (token is MethodReference)
1101                                         MarkMethod ((MethodReference) token);
1102                                 else
1103                                         MarkField ((FieldReference) token);
1104                                 break;
1105                         case OperandType.InlineType:
1106                                 MarkType ((TypeReference) instruction.Operand);
1107                                 break;
1108                         default:
1109                                 break;
1110                         }
1111                 }
1112         }
1113 }