Initial commit
[mono.git] / mcs / class / referencesource / mscorlib / system / reflection / module.cs
1 // ==++==
2 // 
3 //   Copyright (c) Microsoft Corporation.  All rights reserved.
4 // 
5 // ==--==
6 ////////////////////////////////////////////////////////////////////////////////
7 // <OWNER>[....]</OWNER>
8 // <OWNER>[....]</OWNER>
9 // 
10
11 namespace System.Reflection 
12 {
13     using System;
14     using System.Diagnostics.SymbolStore;
15     using System.Runtime.Remoting;
16     using System.Runtime.InteropServices;
17     using System.Runtime.Serialization;
18     using System.Collections;
19     using System.Collections.Generic;
20     using System.Threading;
21     using System.Runtime.CompilerServices;
22     using System.Security;
23     using System.Security.Permissions;
24     using System.IO;
25     using System.Globalization;
26     using System.Runtime.Versioning;
27     using System.Diagnostics.Contracts;
28
29     [Serializable]
30     [Flags] 
31     [System.Runtime.InteropServices.ComVisible(true)]
32     public enum PortableExecutableKinds 
33     {
34         NotAPortableExecutableImage = 0x0,
35
36         ILOnly                      = 0x1,
37         
38         Required32Bit               = 0x2,
39
40         PE32Plus                    = 0x4,
41         
42         Unmanaged32Bit              = 0x8,
43
44         [ComVisible(false)]
45         Preferred32Bit              = 0x10,
46     }
47     
48     [Serializable] 
49     [System.Runtime.InteropServices.ComVisible(true)]
50     public enum ImageFileMachine 
51     {
52         I386    = 0x014c,
53             
54         IA64    = 0x0200,
55         
56         AMD64   = 0x8664,
57
58         ARM     = 0x01c4,
59     }
60
61     [Serializable]
62     [ClassInterface(ClassInterfaceType.None)]
63     [ComDefaultInterface(typeof(_Module))]
64     [System.Runtime.InteropServices.ComVisible(true)]
65 #pragma warning disable 618
66     [PermissionSetAttribute(SecurityAction.InheritanceDemand, Unrestricted = true)]
67 #pragma warning restore 618
68     public abstract class Module : _Module, ISerializable, ICustomAttributeProvider
69     {   
70         #region Static Constructor
71         static Module()
72         {
73             __Filters _fltObj;
74             _fltObj = new __Filters();
75             FilterTypeName = new TypeFilter(_fltObj.FilterTypeName);
76             FilterTypeNameIgnoreCase = new TypeFilter(_fltObj.FilterTypeNameIgnoreCase);
77         }        
78         #endregion
79
80         #region Constructor
81         protected Module() 
82         {
83         }
84         #endregion
85
86         #region Public Statics
87         public static readonly TypeFilter FilterTypeName;
88         public static readonly TypeFilter FilterTypeNameIgnoreCase;
89
90 #if !FEATURE_CORECLR
91         public static bool operator ==(Module left, Module right)
92         {
93             if (ReferenceEquals(left, right))
94                 return true;
95
96             if ((object)left == null || (object)right == null ||
97                 left is RuntimeModule || right is RuntimeModule)
98             {
99                 return false;
100             }
101
102             return left.Equals(right);
103         }
104
105         public static bool operator !=(Module left, Module right)
106         {
107             return !(left == right);
108         }
109 #endif // !FEATURE_CORECLR
110 #if FEATURE_NETCORE || !FEATURE_CORECLR        
111         public override bool Equals(object o)
112         {
113             return base.Equals(o);
114         }
115
116         public override int GetHashCode()
117         {
118             return base.GetHashCode();
119         }
120 #endif //FEATURE_NETCORE || !FEATURE_CORECLR
121         #endregion
122
123         #region Literals
124         private const BindingFlags DefaultLookup = BindingFlags.Instance | BindingFlags.Static | BindingFlags.Public;
125         #endregion
126
127         #region object overrides
128         public override String ToString()
129         {
130             return ScopeName;
131         }
132         #endregion
133
134         public virtual IEnumerable<CustomAttributeData> CustomAttributes
135         {
136             get
137             {
138                 return GetCustomAttributesData();
139             }
140         }
141         #region ICustomAttributeProvider Members
142         public virtual Object[] GetCustomAttributes(bool inherit)
143         {
144             throw new NotImplementedException();
145         }
146
147         public virtual Object[] GetCustomAttributes(Type attributeType, bool inherit)
148         {
149             throw new NotImplementedException();
150         }
151
152         public virtual bool IsDefined(Type attributeType, bool inherit)
153         {
154             throw new NotImplementedException();
155         }
156
157         public virtual IList<CustomAttributeData> GetCustomAttributesData()
158         {
159             throw new NotImplementedException();
160         }
161         #endregion
162
163         #region public instances members
164         public MethodBase ResolveMethod(int metadataToken)
165         {
166             return ResolveMethod(metadataToken, null, null);
167         }
168
169         public virtual MethodBase ResolveMethod(int metadataToken, Type[] genericTypeArguments, Type[] genericMethodArguments)
170         {
171             // This API was made virtual in V4. Code compiled against V2 might use
172             // "call" rather than "callvirt" to call it.
173             // This makes sure those code still works.
174             RuntimeModule rtModule = this as RuntimeModule;
175             if (rtModule != null)
176                 return rtModule.ResolveMethod(metadataToken, genericTypeArguments, genericMethodArguments);
177
178             throw new NotImplementedException();
179         }
180
181         public FieldInfo ResolveField(int metadataToken)
182         {
183             return ResolveField(metadataToken, null, null);
184         }
185
186         public virtual FieldInfo ResolveField(int metadataToken, Type[] genericTypeArguments, Type[] genericMethodArguments)
187         {
188             // This API was made virtual in V4. Code compiled against V2 might use
189             // "call" rather than "callvirt" to call it.
190             // This makes sure those code still works.
191             RuntimeModule rtModule = this as RuntimeModule;
192             if (rtModule != null)
193                 return rtModule.ResolveField(metadataToken, genericTypeArguments, genericMethodArguments);
194
195             throw new NotImplementedException();
196         }
197
198         public Type ResolveType(int metadataToken)
199         {
200             return ResolveType(metadataToken, null, null);
201         }
202
203         public virtual Type ResolveType(int metadataToken, Type[] genericTypeArguments, Type[] genericMethodArguments)
204         {
205             // This API was made virtual in V4. Code compiled against V2 might use
206             // "call" rather than "callvirt" to call it.
207             // This makes sure those code still works.
208             RuntimeModule rtModule = this as RuntimeModule;
209             if (rtModule != null)
210                 return rtModule.ResolveType(metadataToken, genericTypeArguments, genericMethodArguments);
211
212             throw new NotImplementedException();
213         }
214
215         public MemberInfo ResolveMember(int metadataToken)
216         {
217             return ResolveMember(metadataToken, null, null);
218         }
219
220         public virtual MemberInfo ResolveMember(int metadataToken, Type[] genericTypeArguments, Type[] genericMethodArguments)
221         {
222             // This API was made virtual in V4. Code compiled against V2 might use
223             // "call" rather than "callvirt" to call it.
224             // This makes sure those code still works.
225             RuntimeModule rtModule = this as RuntimeModule;
226             if (rtModule != null)
227                 return rtModule.ResolveMember(metadataToken, genericTypeArguments, genericMethodArguments);
228
229             throw new NotImplementedException();
230         }
231
232         public virtual byte[] ResolveSignature(int metadataToken)
233         {
234             // This API was made virtual in V4. Code compiled against V2 might use
235             // "call" rather than "callvirt" to call it.
236             // This makes sure those code still works.
237             RuntimeModule rtModule = this as RuntimeModule;
238             if (rtModule != null)
239                 return rtModule.ResolveSignature(metadataToken);
240
241             throw new NotImplementedException();
242         }
243
244         public virtual string ResolveString(int metadataToken)
245         {
246             // This API was made virtual in V4. Code compiled against V2 might use
247             // "call" rather than "callvirt" to call it.
248             // This makes sure those code still works.
249             RuntimeModule rtModule = this as RuntimeModule;
250             if (rtModule != null)
251                 return rtModule.ResolveString(metadataToken);
252
253             throw new NotImplementedException();
254         }
255
256         public virtual void GetPEKind(out PortableExecutableKinds peKind, out ImageFileMachine machine)
257         {
258             // This API was made virtual in V4. Code compiled against V2 might use
259             // "call" rather than "callvirt" to call it.
260             // This makes sure those code still works.
261             RuntimeModule rtModule = this as RuntimeModule;
262             if (rtModule != null)
263                 rtModule.GetPEKind(out peKind, out machine);
264
265             throw new NotImplementedException();
266         }
267
268         public virtual int MDStreamVersion
269         {
270             get
271             {
272                 // This API was made virtual in V4. Code compiled against V2 might use
273                 // "call" rather than "callvirt" to call it.
274                 // This makes sure those code still works.
275                 RuntimeModule rtModule = this as RuntimeModule;
276                 if (rtModule != null)
277                     return rtModule.MDStreamVersion;
278
279                 throw new NotImplementedException();
280             }
281         }
282
283         [System.Security.SecurityCritical]  // auto-generated_required
284         public virtual void GetObjectData(SerializationInfo info, StreamingContext context)
285         {
286             throw new NotImplementedException();
287         }
288
289         [System.Runtime.InteropServices.ComVisible(true)]
290         public virtual Type GetType(String className, bool ignoreCase)
291         {
292             return GetType(className, false, ignoreCase);
293         }
294
295         [System.Runtime.InteropServices.ComVisible(true)]
296         public virtual Type GetType(String className) {
297             return GetType(className, false, false);
298         }
299
300         [System.Runtime.InteropServices.ComVisible(true)]
301         public virtual Type GetType(String className, bool throwOnError, bool ignoreCase)
302         {
303             throw new NotImplementedException();
304         }
305
306         public virtual String FullyQualifiedName 
307         {
308 #if FEATURE_CORECLR
309             [System.Security.SecurityCritical] // auto-generated
310 #endif
311             [ResourceExposure(ResourceScope.Machine)]
312             [ResourceConsumption(ResourceScope.Machine)]
313             get
314             {
315                 throw new NotImplementedException();
316             }
317         }
318
319         public virtual Type[] FindTypes(TypeFilter filter,Object filterCriteria)
320         {
321             Type[] c = GetTypes();
322             int cnt = 0;
323             for (int i = 0;i<c.Length;i++) {
324                 if (filter!=null && !filter(c[i],filterCriteria))
325                     c[i] = null;
326                 else
327                     cnt++;
328             }
329             if (cnt == c.Length)
330                 return c;
331             
332             Type[] ret = new Type[cnt];
333             cnt=0;
334             for (int i=0;i<c.Length;i++) {
335                 if (c[i] != null)
336                     ret[cnt++] = c[i];
337             }
338             return ret;
339         }
340
341         public virtual Type[] GetTypes()
342         {
343             throw new NotImplementedException();
344         }
345
346         public virtual Guid ModuleVersionId
347         {
348             get
349             {
350                 // This API was made virtual in V4. Code compiled against V2 might use
351                 // "call" rather than "callvirt" to call it.
352                 // This makes sure those code still works.
353                 RuntimeModule rtModule = this as RuntimeModule;
354                 if (rtModule != null)
355                     return rtModule.ModuleVersionId;
356
357                 throw new NotImplementedException();
358             }
359         }
360
361         public virtual int MetadataToken
362         {
363             get
364             {
365                 // This API was made virtual in V4. Code compiled against V2 might use
366                 // "call" rather than "callvirt" to call it.
367                 // This makes sure those code still works.
368                 RuntimeModule rtModule = this as RuntimeModule;
369                 if (rtModule != null)
370                     return rtModule.MetadataToken;
371
372                 throw new NotImplementedException();
373             }
374         }
375
376         public virtual bool IsResource()
377         {
378             // This API was made virtual in V4. Code compiled against V2 might use
379             // "call" rather than "callvirt" to call it.
380             // This makes sure those code still works.
381             RuntimeModule rtModule = this as RuntimeModule;
382             if (rtModule != null)
383                 return rtModule.IsResource();
384
385             throw new NotImplementedException();
386         }
387
388         public FieldInfo[] GetFields()
389         {
390             return GetFields(Module.DefaultLookup);
391         }
392
393         public virtual FieldInfo[] GetFields(BindingFlags bindingFlags)
394         {
395             // This API was made virtual in V4. Code compiled against V2 might use
396             // "call" rather than "callvirt" to call it.
397             // This makes sure those code still works.
398             RuntimeModule rtModule = this as RuntimeModule;
399             if (rtModule != null)
400                 return rtModule.GetFields(bindingFlags);
401
402             throw new NotImplementedException();
403         }
404
405         public FieldInfo GetField(String name)
406         {
407             return GetField(name,Module.DefaultLookup);
408         }
409
410         public virtual FieldInfo GetField(String name, BindingFlags bindingAttr)
411         {
412             // This API was made virtual in V4. Code compiled against V2 might use
413             // "call" rather than "callvirt" to call it.
414             // This makes sure those code still works.
415             RuntimeModule rtModule = this as RuntimeModule;
416             if (rtModule != null)
417                 return rtModule.GetField(name, bindingAttr);
418
419             throw new NotImplementedException();
420         }
421
422         public MethodInfo[] GetMethods()
423         {
424             return GetMethods(Module.DefaultLookup);
425         }
426         
427         public virtual MethodInfo[] GetMethods(BindingFlags bindingFlags)
428         {
429             // This API was made virtual in V4. Code compiled against V2 might use
430             // "call" rather than "callvirt" to call it.
431             // This makes sure those code still works.
432             RuntimeModule rtModule = this as RuntimeModule;
433             if (rtModule != null)
434                 return rtModule.GetMethods(bindingFlags);
435
436             throw new NotImplementedException();
437         }
438
439         public MethodInfo GetMethod(
440             String name, BindingFlags bindingAttr, Binder binder, CallingConventions callConvention, Type[] types, ParameterModifier[] modifiers)
441         {
442             if (name == null)
443                 throw new ArgumentNullException("name");
444
445             if (types == null)
446                 throw new ArgumentNullException("types");
447             Contract.EndContractBlock();
448
449             for (int i = 0; i < types.Length; i++)
450             {
451                 if (types[i] == null)
452                     throw new ArgumentNullException("types");
453             }
454
455             return GetMethodImpl(name, bindingAttr, binder, callConvention, types, modifiers);
456         }
457
458         public MethodInfo GetMethod(String name, Type[] types)
459         {
460             if (name == null)
461                 throw new ArgumentNullException("name");
462
463             if (types == null)
464                 throw new ArgumentNullException("types");
465             Contract.EndContractBlock();
466
467             for (int i = 0; i < types.Length; i++)
468             {
469                 if (types[i] == null)
470                     throw new ArgumentNullException("types");
471             }
472
473             return GetMethodImpl(name, Module.DefaultLookup, null, CallingConventions.Any, types, null);
474         }
475
476         public MethodInfo GetMethod(String name)
477         {
478             if (name == null)
479                 throw new ArgumentNullException("name");
480             Contract.EndContractBlock();
481
482             return GetMethodImpl(name, Module.DefaultLookup, null, CallingConventions.Any,
483                 null, null);
484         }
485
486         protected virtual MethodInfo GetMethodImpl(String name, BindingFlags bindingAttr, Binder binder,
487             CallingConventions callConvention, Type[] types, ParameterModifier[] modifiers)
488         {
489             throw new NotImplementedException();
490         }
491
492         public virtual String ScopeName
493         {
494             get
495             {
496                 // This API was made virtual in V4. Code compiled against V2 might use
497                 // "call" rather than "callvirt" to call it.
498                 // This makes sure those code still works.
499                 RuntimeModule rtModule = this as RuntimeModule;
500                 if (rtModule != null)
501                     return rtModule.ScopeName;
502
503                 throw new NotImplementedException();
504             }
505         }
506
507         public virtual String Name 
508         {
509             [ResourceExposure(ResourceScope.None)]
510             [ResourceConsumption(ResourceScope.Machine, ResourceScope.Machine)]
511             get 
512             {
513                 // This API was made virtual in V4. Code compiled against V2 might use
514                 // "call" rather than "callvirt" to call it.
515                 // This makes sure those code still works.
516                 RuntimeModule rtModule = this as RuntimeModule;
517                 if (rtModule != null)
518                     return rtModule.Name;
519
520                 throw new NotImplementedException();
521             }
522         }
523
524         public virtual Assembly Assembly 
525         { 
526             [Pure]
527             get
528             {
529                 // This API was made virtual in V4. Code compiled against V2 might use
530                 // "call" rather than "callvirt" to call it.
531                 // This makes sure those code still works.
532                 RuntimeModule rtModule = this as RuntimeModule;
533                 if (rtModule != null)
534                     return rtModule.Assembly;
535
536                 throw new NotImplementedException();
537             }
538         }
539
540         // This API never fails, it will return an empty handle for non-runtime handles and 
541         // a valid handle for reflection only modules.
542         public ModuleHandle ModuleHandle
543         {
544             get 
545             {
546                 return GetModuleHandle();
547             }
548         }
549
550         // Used to provide implementation and overriding point for ModuleHandle.
551         // To get a module handle inside mscorlib, use GetNativeHandle instead.
552         internal virtual ModuleHandle GetModuleHandle()
553         {
554             return ModuleHandle.EmptyHandle;
555         }
556
557 #if FEATURE_X509 && FEATURE_CAS_POLICY
558         public virtual System.Security.Cryptography.X509Certificates.X509Certificate GetSignerCertificate()
559         {
560             throw new NotImplementedException();
561         }
562 #endif // FEATURE_X509 && FEATURE_CAS_POLICY
563         #endregion
564
565         void _Module.GetTypeInfoCount(out uint pcTInfo)
566         {
567             throw new NotImplementedException();
568         }
569
570         void _Module.GetTypeInfo(uint iTInfo, uint lcid, IntPtr ppTInfo)
571         {
572             throw new NotImplementedException();
573         }
574
575         void _Module.GetIDsOfNames([In] ref Guid riid, IntPtr rgszNames, uint cNames, uint lcid, IntPtr rgDispId)
576         {
577             throw new NotImplementedException();
578         }
579
580         void _Module.Invoke(uint dispIdMember, [In] ref Guid riid, uint lcid, short wFlags, IntPtr pDispParams, IntPtr pVarResult, IntPtr pExcepInfo, IntPtr puArgErr)
581         {
582             throw new NotImplementedException();
583         }
584     }
585
586 #if !FEATURE_CORECLR
587     [System.Runtime.ForceTokenStabilization]
588 #endif //!FEATURE_CORECLR
589     [Serializable]
590     internal class RuntimeModule : Module
591     {
592         internal RuntimeModule() { throw new NotSupportedException(); }
593
594         #region FCalls
595         [System.Security.SecurityCritical]  // auto-generated
596         [ResourceExposure(ResourceScope.None)]
597         [DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)]
598                 [SuppressUnmanagedCodeSecurity]
599         private extern static void GetType(RuntimeModule module, String className, bool ignoreCase, bool throwOnError, ObjectHandleOnStack type);
600
601         [System.Security.SecurityCritical]
602         [ResourceExposure(ResourceScope.None)]
603         [DllImport(JitHelpers.QCall)]
604         [SuppressUnmanagedCodeSecurity]
605         private static extern bool nIsTransientInternal(RuntimeModule module);
606
607         [System.Security.SecurityCritical]  // auto-generated
608         [ResourceExposure(ResourceScope.None)]
609         [DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)]
610         [SuppressUnmanagedCodeSecurity]
611         private extern static void GetScopeName(RuntimeModule module, StringHandleOnStack retString);
612
613         [System.Security.SecurityCritical]  // auto-generated
614         [ResourceExposure(ResourceScope.Machine)]
615         [DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)]
616         [SuppressUnmanagedCodeSecurity]
617         private extern static void GetFullyQualifiedName(RuntimeModule module, StringHandleOnStack retString);
618
619         [System.Security.SecurityCritical]  // auto-generated
620         [ResourceExposure(ResourceScope.None)]
621         [MethodImplAttribute(MethodImplOptions.InternalCall)]
622         private extern static RuntimeType[] GetTypes(RuntimeModule module);
623
624         [System.Security.SecuritySafeCritical]  // auto-generated
625         internal RuntimeType[] GetDefinedTypes()
626         {
627             return GetTypes(GetNativeHandle());
628         }
629
630         [System.Security.SecuritySafeCritical]  // auto-generated
631         [ResourceExposure(ResourceScope.None)]
632         [MethodImplAttribute(MethodImplOptions.InternalCall)]
633         private extern static bool IsResource(RuntimeModule module);
634
635 #if FEATURE_X509 && FEATURE_CAS_POLICY
636         [System.Security.SecurityCritical]  // auto-generated
637         [ResourceExposure(ResourceScope.None)]
638         [DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)]
639         [SuppressUnmanagedCodeSecurity]
640         static private extern void GetSignerCertificate(RuntimeModule module, ObjectHandleOnStack retData);
641 #endif // FEATURE_X509 && FEATURE_CAS_POLICY
642         #endregion
643
644         #region Module overrides
645         private static RuntimeTypeHandle[] ConvertToTypeHandleArray(Type[] genericArguments)
646         {
647             if (genericArguments == null) 
648                 return null;
649
650             int size = genericArguments.Length;
651             RuntimeTypeHandle[] typeHandleArgs = new RuntimeTypeHandle[size];
652             for (int i = 0; i < size; i++) 
653             {
654                 Type typeArg = genericArguments[i];
655                 if (typeArg == null) 
656                     throw new ArgumentException(Environment.GetResourceString("Argument_InvalidGenericInstArray"));
657                 typeArg = typeArg.UnderlyingSystemType;
658                 if (typeArg == null) 
659                     throw new ArgumentException(Environment.GetResourceString("Argument_InvalidGenericInstArray"));
660                 if (!(typeArg is RuntimeType)) 
661                     throw new ArgumentException(Environment.GetResourceString("Argument_InvalidGenericInstArray"));
662                 typeHandleArgs[i] = typeArg.GetTypeHandleInternal();
663             }
664             return typeHandleArgs;
665         }
666
667         [System.Security.SecuritySafeCritical]  // auto-generated
668         public override byte[] ResolveSignature(int metadataToken)
669         {
670             MetadataToken tk = new MetadataToken(metadataToken);
671
672             if (!MetadataImport.IsValidToken(tk))
673                 throw new ArgumentOutOfRangeException("metadataToken",
674                     Environment.GetResourceString("Argument_InvalidToken", tk, this));
675
676             if (!tk.IsMemberRef && !tk.IsMethodDef && !tk.IsTypeSpec && !tk.IsSignature && !tk.IsFieldDef)
677                 throw new ArgumentException(Environment.GetResourceString("Argument_InvalidToken", tk, this),
678                                             "metadataToken");
679
680             ConstArray signature;
681             if (tk.IsMemberRef)
682                 signature = MetadataImport.GetMemberRefProps(metadataToken);
683             else
684                 signature = MetadataImport.GetSignatureFromToken(metadataToken);
685
686             byte[] sig = new byte[signature.Length];
687
688             for (int i = 0; i < signature.Length; i++)
689                 sig[i] = signature[i];
690
691             return sig;
692         }
693
694         [System.Security.SecuritySafeCritical]  // auto-generated
695         public override MethodBase ResolveMethod(int metadataToken, Type[] genericTypeArguments, Type[] genericMethodArguments)
696         {
697             MetadataToken tk = new MetadataToken(metadataToken);
698
699             if (!MetadataImport.IsValidToken(tk))
700                 throw new ArgumentOutOfRangeException("metadataToken",
701                     Environment.GetResourceString("Argument_InvalidToken", tk, this));
702
703             RuntimeTypeHandle[] typeArgs = ConvertToTypeHandleArray(genericTypeArguments);
704             RuntimeTypeHandle[] methodArgs = ConvertToTypeHandleArray(genericMethodArguments);
705
706             try 
707             {
708                 if (!tk.IsMethodDef && !tk.IsMethodSpec)
709                 {
710                     if (!tk.IsMemberRef)
711                         throw new ArgumentException("metadataToken",
712                             Environment.GetResourceString("Argument_ResolveMethod", tk, this));
713
714                     unsafe
715                     {
716                         ConstArray sig = MetadataImport.GetMemberRefProps(tk);
717                         
718                         if (*(MdSigCallingConvention*)sig.Signature.ToPointer() == MdSigCallingConvention.Field)
719                             throw new ArgumentException("metadataToken", 
720                                 Environment.GetResourceString("Argument_ResolveMethod", tk, this));
721                     }
722                 }
723
724                 IRuntimeMethodInfo methodHandle = ModuleHandle.ResolveMethodHandleInternal(GetNativeHandle(), tk, typeArgs, methodArgs);
725                 Type declaringType = RuntimeMethodHandle.GetDeclaringType(methodHandle);
726     
727                 if (declaringType.IsGenericType || declaringType.IsArray)
728                 {
729                     MetadataToken tkDeclaringType = new MetadataToken(MetadataImport.GetParentToken(tk));
730                 
731                     if (tk.IsMethodSpec)
732                         tkDeclaringType = new MetadataToken(MetadataImport.GetParentToken(tkDeclaringType));
733                 
734                     declaringType = ResolveType(tkDeclaringType, genericTypeArguments, genericMethodArguments);
735                 }
736
737                 return System.RuntimeType.GetMethodBase(declaringType as RuntimeType, methodHandle);    
738             } 
739             catch (BadImageFormatException e) 
740             {
741                 throw new ArgumentException(Environment.GetResourceString("Argument_BadImageFormatExceptionResolve"), e);
742             }
743         }
744
745         [System.Security.SecurityCritical]  // auto-generated
746         private FieldInfo ResolveLiteralField(int metadataToken, Type[] genericTypeArguments, Type[] genericMethodArguments)
747         {
748             MetadataToken tk = new MetadataToken(metadataToken);
749
750             if (!MetadataImport.IsValidToken(tk) || !tk.IsFieldDef)
751                 throw new ArgumentOutOfRangeException("metadataToken",
752                     String.Format(CultureInfo.CurrentUICulture, Environment.GetResourceString("Argument_InvalidToken", tk, this)));
753
754             int tkDeclaringType;
755             string fieldName;
756
757             fieldName = MetadataImport.GetName(tk).ToString();
758             tkDeclaringType = MetadataImport.GetParentToken(tk);
759
760             Type declaringType = ResolveType(tkDeclaringType, genericTypeArguments, genericMethodArguments);
761
762             declaringType.GetFields();
763
764             try
765             {
766                 return declaringType.GetField(fieldName, 
767                     BindingFlags.Static | BindingFlags.Instance | 
768                     BindingFlags.Public | BindingFlags.NonPublic | 
769                     BindingFlags.DeclaredOnly);
770             }
771             catch
772             {
773                 throw new ArgumentException(Environment.GetResourceString("Argument_ResolveField", tk, this), "metadataToken");
774             }
775         }
776
777         [System.Security.SecuritySafeCritical]  // auto-generated
778         public override FieldInfo ResolveField(int metadataToken, Type[] genericTypeArguments, Type[] genericMethodArguments)
779         {
780             MetadataToken tk = new MetadataToken(metadataToken);
781
782             if (!MetadataImport.IsValidToken(tk))
783                 throw new ArgumentOutOfRangeException("metadataToken",
784                     Environment.GetResourceString("Argument_InvalidToken", tk, this));
785
786             RuntimeTypeHandle[] typeArgs = ConvertToTypeHandleArray(genericTypeArguments);
787             RuntimeTypeHandle[] methodArgs = ConvertToTypeHandleArray(genericMethodArguments);
788
789             try 
790             {
791                 IRuntimeFieldInfo fieldHandle = null;
792             
793                 if (!tk.IsFieldDef)
794                 {
795                     if (!tk.IsMemberRef)
796                         throw new ArgumentException("metadataToken",
797                             Environment.GetResourceString("Argument_ResolveField", tk, this));
798
799                     unsafe 
800                     {
801                         ConstArray sig = MetadataImport.GetMemberRefProps(tk);
802                         
803                         if (*(MdSigCallingConvention*)sig.Signature.ToPointer() != MdSigCallingConvention.Field)
804                             throw new ArgumentException("metadataToken",
805                                 Environment.GetResourceString("Argument_ResolveField", tk, this));                            
806                     }
807
808                     fieldHandle = ModuleHandle.ResolveFieldHandleInternal(GetNativeHandle(), tk, typeArgs, methodArgs);
809                 }
810
811                 fieldHandle = ModuleHandle.ResolveFieldHandleInternal(GetNativeHandle(), metadataToken, typeArgs, methodArgs);
812                 RuntimeType declaringType = RuntimeFieldHandle.GetApproxDeclaringType(fieldHandle.Value);
813                 
814                 if (declaringType.IsGenericType || declaringType.IsArray)
815                 {
816                     int tkDeclaringType = ModuleHandle.GetMetadataImport(GetNativeHandle()).GetParentToken(metadataToken);
817                     declaringType = (RuntimeType)ResolveType(tkDeclaringType, genericTypeArguments, genericMethodArguments);
818                 }
819
820                 return System.RuntimeType.GetFieldInfo(declaringType, fieldHandle);
821             }
822             catch(MissingFieldException)
823             {
824                 return ResolveLiteralField(tk, genericTypeArguments, genericMethodArguments);
825             }
826             catch (BadImageFormatException e) 
827             {
828                 throw new ArgumentException(Environment.GetResourceString("Argument_BadImageFormatExceptionResolve"), e);
829             }           
830         }
831
832         [System.Security.SecuritySafeCritical]  // auto-generated
833         public override Type ResolveType(int metadataToken, Type[] genericTypeArguments, Type[] genericMethodArguments)
834         {
835             MetadataToken tk = new MetadataToken(metadataToken);
836
837             if (tk.IsGlobalTypeDefToken)
838                 throw new ArgumentException(Environment.GetResourceString("Argument_ResolveModuleType", tk), "metadataToken");
839             
840             if (!MetadataImport.IsValidToken(tk))
841                 throw new ArgumentOutOfRangeException("metadataToken",
842                     Environment.GetResourceString("Argument_InvalidToken", tk, this));
843
844             if (!tk.IsTypeDef && !tk.IsTypeSpec && !tk.IsTypeRef)
845                 throw new ArgumentException(Environment.GetResourceString("Argument_ResolveType", tk, this), "metadataToken");
846
847             RuntimeTypeHandle[] typeArgs = ConvertToTypeHandleArray(genericTypeArguments);
848             RuntimeTypeHandle[] methodArgs = ConvertToTypeHandleArray(genericMethodArguments);
849
850             try 
851             {
852                 Type t = GetModuleHandle().ResolveTypeHandle(metadataToken, typeArgs, methodArgs).GetRuntimeType();
853                     
854                 if (t == null)
855                     throw new ArgumentException(Environment.GetResourceString("Argument_ResolveType", tk, this), "metadataToken");
856
857                 return t;
858             } 
859             catch (BadImageFormatException e) 
860             {
861                 throw new ArgumentException(Environment.GetResourceString("Argument_BadImageFormatExceptionResolve"), e);
862             }
863         }
864
865         [System.Security.SecuritySafeCritical]  // auto-generated
866         public override MemberInfo ResolveMember(int metadataToken, Type[] genericTypeArguments, Type[] genericMethodArguments)
867         {
868             MetadataToken tk = new MetadataToken(metadataToken);
869
870             if (tk.IsProperty)
871                 throw new ArgumentException(Environment.GetResourceString("InvalidOperation_PropertyInfoNotAvailable"));
872
873             if (tk.IsEvent)
874                 throw new ArgumentException(Environment.GetResourceString("InvalidOperation_EventInfoNotAvailable"));
875
876             if (tk.IsMethodSpec || tk.IsMethodDef)
877                 return ResolveMethod(metadataToken, genericTypeArguments, genericMethodArguments);
878
879             if (tk.IsFieldDef)
880                 return ResolveField(metadataToken, genericTypeArguments, genericMethodArguments);
881
882             if (tk.IsTypeRef || tk.IsTypeDef || tk.IsTypeSpec)
883                 return ResolveType(metadataToken, genericTypeArguments, genericMethodArguments);
884
885             if (tk.IsMemberRef)
886             {
887                 if (!MetadataImport.IsValidToken(tk))
888                     throw new ArgumentOutOfRangeException("metadataToken",
889                         Environment.GetResourceString("Argument_InvalidToken", tk, this));
890
891                 ConstArray sig = MetadataImport.GetMemberRefProps(tk);
892
893                 unsafe 
894                 {
895                     if (*(MdSigCallingConvention*)sig.Signature.ToPointer() == MdSigCallingConvention.Field)
896                     {
897                         return ResolveField(tk, genericTypeArguments, genericMethodArguments);
898                     }
899                     else
900                     {
901                         return ResolveMethod(tk, genericTypeArguments, genericMethodArguments);
902                     }
903                 }                
904             }
905
906             throw new ArgumentException("metadataToken",
907                 Environment.GetResourceString("Argument_ResolveMember", tk, this));
908         }
909
910         [System.Security.SecuritySafeCritical]  // auto-generated
911         public override string ResolveString(int metadataToken)
912         {
913             MetadataToken tk = new MetadataToken(metadataToken);
914             if (!tk.IsString)
915                 throw new ArgumentException(
916                     String.Format(CultureInfo.CurrentUICulture, Environment.GetResourceString("Argument_ResolveString"), metadataToken, ToString()));
917
918             if (!MetadataImport.IsValidToken(tk))
919                 throw new ArgumentOutOfRangeException("metadataToken",
920                     String.Format(CultureInfo.CurrentUICulture, Environment.GetResourceString("Argument_InvalidToken", tk, this)));
921
922             string str = MetadataImport.GetUserString(metadataToken);
923             
924             if (str == null)                
925                 throw new ArgumentException(
926                     String.Format(CultureInfo.CurrentUICulture, Environment.GetResourceString("Argument_ResolveString"), metadataToken, ToString()));
927
928             return str;
929         }
930
931         public override void GetPEKind(out PortableExecutableKinds peKind, out ImageFileMachine machine)
932         {
933             ModuleHandle.GetPEKind(GetNativeHandle(), out peKind, out machine);
934         }
935
936         public override int MDStreamVersion
937         {
938             [System.Security.SecuritySafeCritical]  // auto-generated
939             get
940             {
941                 return ModuleHandle.GetMDStreamVersion(GetNativeHandle());
942             }
943         }
944         #endregion
945
946         #region Data Members
947         #pragma warning disable 169
948         // If you add any data members, you need to update the native declaration ReflectModuleBaseObject.
949         private RuntimeType m_runtimeType;
950         private RuntimeAssembly m_runtimeAssembly;
951         private IntPtr m_pRefClass;
952 #if !FEATURE_CORECLR
953         [System.Runtime.ForceTokenStabilization]
954 #endif //!FEATURE_CORECLR
955         private IntPtr m_pData;
956         private IntPtr m_pGlobals;
957         private IntPtr m_pFields;
958 #pragma warning restore 169
959         #endregion
960
961         #region Protected Virtuals
962         protected override MethodInfo GetMethodImpl(String name, BindingFlags bindingAttr, Binder binder,
963             CallingConventions callConvention, Type[] types, ParameterModifier[] modifiers)
964         {
965             return GetMethodInternal(name, bindingAttr, binder, callConvention, types, modifiers);
966         }
967
968         internal MethodInfo GetMethodInternal(String name, BindingFlags bindingAttr, Binder binder,
969             CallingConventions callConvention, Type[] types, ParameterModifier[] modifiers)
970         {
971             if (RuntimeType == null)
972                 return null;
973
974             if (types == null)
975             {
976                 return RuntimeType.GetMethod(name, bindingAttr);
977             }
978             else
979             {
980                 return RuntimeType.GetMethod(name, bindingAttr, binder, callConvention, types, modifiers);
981             }
982         }
983         #endregion
984
985         #region Internal Members
986         internal RuntimeType RuntimeType
987         {
988             get
989             {
990                 if (m_runtimeType == null)
991                     m_runtimeType = ModuleHandle.GetModuleType(GetNativeHandle());
992
993                 return m_runtimeType;
994             }
995         }
996
997         [System.Security.SecuritySafeCritical]
998         internal bool IsTransientInternal()
999         {
1000             return RuntimeModule.nIsTransientInternal(this.GetNativeHandle());
1001         }
1002         
1003         internal MetadataImport MetadataImport
1004         {
1005             [System.Security.SecurityCritical]  // auto-generated
1006             get
1007             {
1008                 unsafe
1009                 {
1010                     return ModuleHandle.GetMetadataImport(GetNativeHandle());
1011                 }
1012             }
1013         }
1014         #endregion
1015
1016         #region ICustomAttributeProvider Members
1017         public override Object[] GetCustomAttributes(bool inherit)
1018         {
1019             return CustomAttribute.GetCustomAttributes(this, typeof(object) as RuntimeType);
1020         }
1021
1022         public override Object[] GetCustomAttributes(Type attributeType, bool inherit)
1023         {
1024             if (attributeType == null)
1025                 throw new ArgumentNullException("attributeType");
1026             Contract.EndContractBlock();
1027
1028             RuntimeType attributeRuntimeType = attributeType.UnderlyingSystemType as RuntimeType;
1029
1030             if (attributeRuntimeType == null) 
1031                 throw new ArgumentException(Environment.GetResourceString("Arg_MustBeType"),"attributeType");
1032
1033             return CustomAttribute.GetCustomAttributes(this, attributeRuntimeType);
1034         }
1035     
1036         [System.Security.SecuritySafeCritical]  // auto-generated
1037         public override bool IsDefined(Type attributeType, bool inherit)
1038         {
1039             if (attributeType == null)
1040                 throw new ArgumentNullException("attributeType");
1041             Contract.EndContractBlock();
1042
1043             RuntimeType attributeRuntimeType = attributeType.UnderlyingSystemType as RuntimeType;
1044
1045             if (attributeRuntimeType == null) 
1046                 throw new ArgumentException(Environment.GetResourceString("Arg_MustBeType"),"attributeType");
1047
1048             return CustomAttribute.IsDefined(this, attributeRuntimeType);
1049         }
1050
1051         public override IList<CustomAttributeData> GetCustomAttributesData()
1052         {
1053             return CustomAttributeData.GetCustomAttributesInternal(this);
1054         }
1055         #endregion
1056
1057         #region Public Virtuals
1058         [System.Security.SecurityCritical]  // auto-generated_required
1059         public override void GetObjectData(SerializationInfo info, StreamingContext context)
1060         {
1061             if (info == null)
1062             {
1063                 throw new ArgumentNullException("info");
1064             }
1065             Contract.EndContractBlock();
1066             UnitySerializationHolder.GetUnitySerializationInfo(info, UnitySerializationHolder.ModuleUnity, this.ScopeName, this.GetRuntimeAssembly());
1067         }
1068
1069         [System.Security.SecuritySafeCritical]  // auto-generated
1070         [System.Runtime.InteropServices.ComVisible(true)]
1071         public override Type GetType(String className, bool throwOnError, bool ignoreCase)
1072         {
1073             // throw on null strings regardless of the value of "throwOnError"
1074             if (className == null)
1075                 throw new ArgumentNullException("className");
1076
1077             RuntimeType retType = null;
1078             GetType(GetNativeHandle(), className, throwOnError, ignoreCase, JitHelpers.GetObjectHandleOnStack(ref retType));
1079             return retType;
1080         }
1081
1082         [System.Security.SecurityCritical]  // auto-generated
1083         internal string GetFullyQualifiedName()
1084         {
1085             String fullyQualifiedName = null;
1086             GetFullyQualifiedName(GetNativeHandle(), JitHelpers.GetStringHandleOnStack(ref fullyQualifiedName));
1087             return fullyQualifiedName;
1088         }
1089
1090         public override String FullyQualifiedName
1091         {
1092 #if FEATURE_CORECLR
1093             [System.Security.SecurityCritical] // auto-generated
1094 #else
1095             [System.Security.SecuritySafeCritical]
1096 #endif
1097             [ResourceExposure(ResourceScope.Machine)]
1098             [ResourceConsumption(ResourceScope.Machine)]
1099             get
1100             {
1101                 String fullyQualifiedName = GetFullyQualifiedName();
1102                 
1103                 if (fullyQualifiedName != null) {
1104                     bool checkPermission = true;
1105                     try {
1106                         Path.GetFullPathInternal(fullyQualifiedName);
1107                     }
1108                     catch(ArgumentException) {
1109                         checkPermission = false;
1110                     }
1111                     if (checkPermission) {
1112                         new FileIOPermission( FileIOPermissionAccess.PathDiscovery, fullyQualifiedName ).Demand();
1113                     }
1114                 }
1115
1116                 return fullyQualifiedName;
1117             }
1118         }
1119
1120         [System.Security.SecuritySafeCritical]  // auto-generated
1121         public override Type[] GetTypes()
1122         {
1123             return GetTypes(GetNativeHandle());
1124         }
1125
1126         #endregion
1127
1128         #region Public Members
1129
1130         public override Guid ModuleVersionId
1131         {
1132             [System.Security.SecuritySafeCritical]  // auto-generated
1133             get
1134             {
1135                 unsafe
1136                 {
1137                     Guid mvid;
1138                     MetadataImport.GetScopeProps(out mvid);
1139                     return mvid;
1140                 }
1141             }
1142         }
1143
1144         public override int MetadataToken
1145         {
1146             [System.Security.SecuritySafeCritical]  // auto-generated
1147             get
1148             {
1149                 return ModuleHandle.GetToken(GetNativeHandle());
1150             }
1151         }
1152
1153         public override bool IsResource()
1154         {
1155             return IsResource(GetNativeHandle());
1156         }
1157
1158         public override FieldInfo[] GetFields(BindingFlags bindingFlags)
1159         {
1160             if (RuntimeType == null)
1161                 return new FieldInfo[0];
1162
1163             return RuntimeType.GetFields(bindingFlags);
1164         }
1165
1166         public override FieldInfo GetField(String name, BindingFlags bindingAttr)
1167         {
1168             if (name == null)
1169                 throw new ArgumentNullException("name");
1170
1171             if (RuntimeType == null)
1172                 return null;
1173
1174             return RuntimeType.GetField(name, bindingAttr);
1175         }
1176
1177         public override MethodInfo[] GetMethods(BindingFlags bindingFlags)
1178         {
1179             if (RuntimeType == null)
1180                 return new MethodInfo[0];
1181         
1182             return RuntimeType.GetMethods(bindingFlags);           
1183         }
1184
1185         public override String ScopeName
1186         {
1187             [System.Security.SecuritySafeCritical]  // auto-generated
1188             get
1189             {
1190                 string scopeName = null;
1191                 GetScopeName(GetNativeHandle(), JitHelpers.GetStringHandleOnStack(ref scopeName));
1192                 return scopeName;
1193             }
1194         }
1195
1196         public override String Name
1197         {
1198             [ResourceExposure(ResourceScope.None)]
1199             [ResourceConsumption(ResourceScope.Machine, ResourceScope.Machine)]
1200             [System.Security.SecuritySafeCritical]  // auto-generated
1201             get
1202             {
1203                 String s = GetFullyQualifiedName();
1204
1205 #if !FEATURE_PAL
1206                 int i = s.LastIndexOf('\\');
1207 #else
1208                 int i = s.LastIndexOf(System.IO.Path.DirectorySeparatorChar);
1209 #endif
1210                 if (i == -1)
1211                     return s;
1212
1213                 return new String(s.ToCharArray(), i + 1, s.Length - i - 1);
1214             }
1215         }
1216
1217         public override Assembly Assembly
1218         {
1219             [Pure]
1220             get 
1221             {
1222                 return GetRuntimeAssembly();
1223             }
1224         }
1225         
1226         internal RuntimeAssembly GetRuntimeAssembly()
1227         {
1228             return m_runtimeAssembly;
1229         }
1230
1231
1232         internal override ModuleHandle GetModuleHandle()
1233         {
1234             return new ModuleHandle(this);
1235         }
1236
1237         internal RuntimeModule GetNativeHandle()
1238         {
1239             return this;
1240         }
1241
1242 #if FEATURE_X509 && FEATURE_CAS_POLICY
1243         [System.Security.SecuritySafeCritical]  // auto-generated
1244         public override System.Security.Cryptography.X509Certificates.X509Certificate GetSignerCertificate()
1245         {
1246             byte[] data = null;
1247             GetSignerCertificate(GetNativeHandle(), JitHelpers.GetObjectHandleOnStack(ref data));
1248             return (data != null) ? new System.Security.Cryptography.X509Certificates.X509Certificate(data) : null;
1249         }
1250 #endif // FEATURE_X509 && FEATURE_CAS_POLICY
1251         #endregion
1252     }
1253 }