Module.cs 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501
  1. //
  2. // System.Reflection/Module.cs
  3. //
  4. // Author:
  5. // Paolo Molaro ([email protected])
  6. //
  7. // (C) 2001 Ximian, Inc. http://www.ximian.com
  8. // Copyright (C) 2004-2005 Novell, Inc (http://www.novell.com)
  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. using System.Runtime.Serialization;
  30. using System.Security.Cryptography.X509Certificates;
  31. using System.Runtime.InteropServices;
  32. using System.Runtime.CompilerServices;
  33. using System.Security;
  34. using System.Security.Permissions;
  35. using System.Collections.Generic;
  36. namespace System.Reflection {
  37. internal enum ResolveTokenError {
  38. OutOfRange,
  39. BadTable,
  40. Other
  41. };
  42. [ComVisible (true)]
  43. [ComDefaultInterfaceAttribute (typeof (_Module))]
  44. [Serializable]
  45. [ClassInterfaceAttribute (ClassInterfaceType.None)]
  46. public class Module : ISerializable, ICustomAttributeProvider, _Module {
  47. public static readonly TypeFilter FilterTypeName;
  48. public static readonly TypeFilter FilterTypeNameIgnoreCase;
  49. #pragma warning disable 649
  50. private IntPtr _impl; /* a pointer to a MonoImage */
  51. internal Assembly assembly;
  52. internal string fqname;
  53. internal string name;
  54. internal string scopename;
  55. internal bool is_resource;
  56. internal int token;
  57. #pragma warning restore 649
  58. const BindingFlags defaultBindingFlags =
  59. BindingFlags.Public | BindingFlags.Static | BindingFlags.Instance;
  60. static Module () {
  61. FilterTypeName = new TypeFilter (filter_by_type_name);
  62. FilterTypeNameIgnoreCase = new TypeFilter (filter_by_type_name_ignore_case);
  63. }
  64. internal Module () {
  65. }
  66. public Assembly Assembly {
  67. get { return assembly; }
  68. }
  69. public virtual string FullyQualifiedName {
  70. get {
  71. #if !NET_2_1
  72. if (SecurityManager.SecurityEnabled) {
  73. new FileIOPermission (FileIOPermissionAccess.PathDiscovery, fqname).Demand ();
  74. }
  75. #endif
  76. return fqname;
  77. }
  78. }
  79. // Note: we do not ask for PathDiscovery because no path is returned here.
  80. // However MS Fx requires it (see FDBK23572 for details).
  81. public string Name {
  82. get { return name; }
  83. }
  84. public string ScopeName {
  85. get { return scopename; }
  86. }
  87. public ModuleHandle ModuleHandle {
  88. get {
  89. return new ModuleHandle (_impl);
  90. }
  91. }
  92. public extern int MetadataToken {
  93. [MethodImplAttribute (MethodImplOptions.InternalCall)]
  94. get;
  95. }
  96. public int MDStreamVersion {
  97. get {
  98. if (_impl == IntPtr.Zero)
  99. throw new NotSupportedException ();
  100. return GetMDStreamVersion (_impl);
  101. }
  102. }
  103. [MethodImplAttribute (MethodImplOptions.InternalCall)]
  104. internal static extern int GetMDStreamVersion (IntPtr module_handle);
  105. public virtual Type[] FindTypes(TypeFilter filter, object filterCriteria)
  106. {
  107. System.Collections.ArrayList filtered = new System.Collections.ArrayList ();
  108. Type[] types = GetTypes ();
  109. foreach (Type t in types)
  110. if (filter (t, filterCriteria))
  111. filtered.Add (t);
  112. return (Type[])filtered.ToArray (typeof(Type));
  113. }
  114. public virtual object[] GetCustomAttributes(bool inherit)
  115. {
  116. return MonoCustomAttrs.GetCustomAttributes (this, inherit);
  117. }
  118. public virtual object[] GetCustomAttributes(Type attributeType, bool inherit)
  119. {
  120. return MonoCustomAttrs.GetCustomAttributes (this, attributeType, inherit);
  121. }
  122. public FieldInfo GetField (string name)
  123. {
  124. if (IsResource ())
  125. return null;
  126. Type globalType = GetGlobalType ();
  127. return (globalType != null) ? globalType.GetField (name, BindingFlags.Public | BindingFlags.Static) : null;
  128. }
  129. public FieldInfo GetField (string name, BindingFlags bindingAttr)
  130. {
  131. if (IsResource ())
  132. return null;
  133. Type globalType = GetGlobalType ();
  134. return (globalType != null) ? globalType.GetField (name, bindingAttr) : null;
  135. }
  136. public FieldInfo[] GetFields ()
  137. {
  138. if (IsResource ())
  139. return new FieldInfo [0];
  140. Type globalType = GetGlobalType ();
  141. return (globalType != null) ? globalType.GetFields (BindingFlags.Public | BindingFlags.Static) : new FieldInfo [0];
  142. }
  143. public MethodInfo GetMethod (string name)
  144. {
  145. // Can't call the other overloads since they call Type.GetMethod () which does a null check on the 'types' array
  146. if (IsResource ())
  147. return null;
  148. Type globalType = GetGlobalType ();
  149. return (globalType != null) ? globalType.GetMethod (name) : null;
  150. }
  151. public MethodInfo GetMethod (string name, Type[] types)
  152. {
  153. return GetMethodImpl (name, defaultBindingFlags, null, CallingConventions.Any, types, null);
  154. }
  155. public MethodInfo GetMethod (string name, BindingFlags bindingAttr, Binder binder, CallingConventions callConvention, Type[] types, ParameterModifier[] modifiers)
  156. {
  157. return GetMethodImpl (name, bindingAttr, binder, callConvention, types, modifiers);
  158. }
  159. protected virtual MethodInfo GetMethodImpl (string name, BindingFlags bindingAttr, Binder binder, CallingConventions callConvention, Type[] types, ParameterModifier[] modifiers)
  160. {
  161. if (IsResource ())
  162. return null;
  163. Type globalType = GetGlobalType ();
  164. return (globalType != null) ? globalType.GetMethod (name, bindingAttr, binder, callConvention, types, modifiers) : null;
  165. }
  166. public MethodInfo[] GetMethods ()
  167. {
  168. if (IsResource ())
  169. return new MethodInfo [0];
  170. Type globalType = GetGlobalType ();
  171. return (globalType != null) ? globalType.GetMethods () : new MethodInfo [0];
  172. }
  173. public MethodInfo[] GetMethods (BindingFlags bindingFlags) {
  174. if (IsResource ())
  175. return new MethodInfo [0];
  176. Type globalType = GetGlobalType ();
  177. return (globalType != null) ? globalType.GetMethods (bindingFlags) : new MethodInfo [0];
  178. }
  179. public FieldInfo[] GetFields (BindingFlags bindingFlags)
  180. {
  181. if (IsResource ())
  182. return new FieldInfo [0];
  183. Type globalType = GetGlobalType ();
  184. return (globalType != null) ? globalType.GetFields (bindingFlags) : new FieldInfo [0];
  185. }
  186. [SecurityPermission (SecurityAction.LinkDemand, SerializationFormatter = true)]
  187. public virtual void GetObjectData (SerializationInfo info, StreamingContext context)
  188. {
  189. if (info == null)
  190. throw new ArgumentNullException ("info");
  191. UnitySerializationHolder.GetModuleData (this, info, context);
  192. }
  193. #if !NET_2_1
  194. public X509Certificate GetSignerCertificate ()
  195. {
  196. try {
  197. return X509Certificate.CreateFromSignedFile (assembly.Location);
  198. }
  199. catch {
  200. return null;
  201. }
  202. }
  203. #endif
  204. [ComVisible (true)]
  205. public virtual Type GetType(string className)
  206. {
  207. return GetType (className, false, false);
  208. }
  209. [ComVisible (true)]
  210. public virtual Type GetType(string className, bool ignoreCase)
  211. {
  212. return GetType (className, false, ignoreCase);
  213. }
  214. [ComVisible (true)]
  215. public virtual Type GetType(string className, bool throwOnError, bool ignoreCase)
  216. {
  217. if (className == null)
  218. throw new ArgumentNullException ("className");
  219. if (className == String.Empty)
  220. throw new ArgumentException ("Type name can't be empty");
  221. return assembly.InternalGetType (this, className, throwOnError, ignoreCase);
  222. }
  223. [MethodImplAttribute (MethodImplOptions.InternalCall)]
  224. private extern Type[] InternalGetTypes ();
  225. public virtual Type[] GetTypes()
  226. {
  227. return InternalGetTypes ();
  228. }
  229. public virtual bool IsDefined (Type attributeType, bool inherit)
  230. {
  231. return MonoCustomAttrs.IsDefined (this, attributeType, inherit);
  232. }
  233. public bool IsResource()
  234. {
  235. return is_resource;
  236. }
  237. public override string ToString ()
  238. {
  239. return name;
  240. }
  241. internal Guid MvId {
  242. get {
  243. return GetModuleVersionId ();
  244. }
  245. }
  246. public Guid ModuleVersionId {
  247. get {
  248. return GetModuleVersionId ();
  249. }
  250. }
  251. public void GetPEKind (out PortableExecutableKinds peKind, out ImageFileMachine machine) {
  252. ModuleHandle.GetPEKind (out peKind, out machine);
  253. }
  254. private Exception resolve_token_exception (int metadataToken, ResolveTokenError error, string tokenType) {
  255. if (error == ResolveTokenError.OutOfRange)
  256. return new ArgumentOutOfRangeException ("metadataToken", String.Format ("Token 0x{0:x} is not valid in the scope of module {1}", metadataToken, name));
  257. else
  258. return new ArgumentException (String.Format ("Token 0x{0:x} is not a valid {1} token in the scope of module {2}", metadataToken, tokenType, name), "metadataToken");
  259. }
  260. private IntPtr[] ptrs_from_types (Type[] types) {
  261. if (types == null)
  262. return null;
  263. else {
  264. IntPtr[] res = new IntPtr [types.Length];
  265. for (int i = 0; i < types.Length; ++i) {
  266. if (types [i] == null)
  267. throw new ArgumentException ();
  268. res [i] = types [i].TypeHandle.Value;
  269. }
  270. return res;
  271. }
  272. }
  273. public FieldInfo ResolveField (int metadataToken) {
  274. return ResolveField (metadataToken, null, null);
  275. }
  276. public FieldInfo ResolveField (int metadataToken, Type [] genericTypeArguments, Type [] genericMethodArguments) {
  277. ResolveTokenError error;
  278. IntPtr handle = ResolveFieldToken (_impl, metadataToken, ptrs_from_types (genericTypeArguments), ptrs_from_types (genericMethodArguments), out error);
  279. if (handle == IntPtr.Zero)
  280. throw resolve_token_exception (metadataToken, error, "Field");
  281. else
  282. return FieldInfo.GetFieldFromHandle (new RuntimeFieldHandle (handle));
  283. }
  284. public MemberInfo ResolveMember (int metadataToken) {
  285. return ResolveMember (metadataToken, null, null);
  286. }
  287. public MemberInfo ResolveMember (int metadataToken, Type [] genericTypeArguments, Type [] genericMethodArguments) {
  288. ResolveTokenError error;
  289. MemberInfo m = ResolveMemberToken (_impl, metadataToken, ptrs_from_types (genericTypeArguments), ptrs_from_types (genericMethodArguments), out error);
  290. if (m == null)
  291. throw resolve_token_exception (metadataToken, error, "MemberInfo");
  292. else
  293. return m;
  294. }
  295. public MethodBase ResolveMethod (int metadataToken) {
  296. return ResolveMethod (metadataToken, null, null);
  297. }
  298. public MethodBase ResolveMethod (int metadataToken, Type [] genericTypeArguments, Type [] genericMethodArguments) {
  299. ResolveTokenError error;
  300. IntPtr handle = ResolveMethodToken (_impl, metadataToken, ptrs_from_types (genericTypeArguments), ptrs_from_types (genericMethodArguments), out error);
  301. if (handle == IntPtr.Zero)
  302. throw resolve_token_exception (metadataToken, error, "MethodBase");
  303. else
  304. return MethodBase.GetMethodFromHandleNoGenericCheck (new RuntimeMethodHandle (handle));
  305. }
  306. public string ResolveString (int metadataToken) {
  307. ResolveTokenError error;
  308. string s = ResolveStringToken (_impl, metadataToken, out error);
  309. if (s == null)
  310. throw resolve_token_exception (metadataToken, error, "string");
  311. else
  312. return s;
  313. }
  314. public Type ResolveType (int metadataToken) {
  315. return ResolveType (metadataToken, null, null);
  316. }
  317. public Type ResolveType (int metadataToken, Type [] genericTypeArguments, Type [] genericMethodArguments) {
  318. ResolveTokenError error;
  319. IntPtr handle = ResolveTypeToken (_impl, metadataToken, ptrs_from_types (genericTypeArguments), ptrs_from_types (genericMethodArguments), out error);
  320. if (handle == IntPtr.Zero)
  321. throw resolve_token_exception (metadataToken, error, "Type");
  322. else
  323. return Type.GetTypeFromHandle (new RuntimeTypeHandle (handle));
  324. }
  325. public byte[] ResolveSignature (int metadataToken) {
  326. ResolveTokenError error;
  327. byte[] res = ResolveSignature (_impl, metadataToken, out error);
  328. if (res == null)
  329. throw resolve_token_exception (metadataToken, error, "signature");
  330. else
  331. return res;
  332. }
  333. #if NET_4_0
  334. public virtual IList<CustomAttributeData> GetCustomAttributesData () {
  335. return CustomAttributeData.GetCustomAttributes (this);
  336. }
  337. #endif
  338. internal static Type MonoDebugger_ResolveType (Module module, int token)
  339. {
  340. ResolveTokenError error;
  341. IntPtr handle = ResolveTypeToken (module._impl, token, null, null, out error);
  342. if (handle == IntPtr.Zero)
  343. return null;
  344. else
  345. return Type.GetTypeFromHandle (new RuntimeTypeHandle (handle));
  346. }
  347. // Used by mcs, the symbol writer, and mdb through reflection
  348. internal static Guid Mono_GetGuid (Module module)
  349. {
  350. return module.GetModuleVersionId ();
  351. }
  352. internal virtual Guid GetModuleVersionId ()
  353. {
  354. return new Guid (GetGuidInternal ());
  355. }
  356. private static bool filter_by_type_name (Type m, object filterCriteria) {
  357. string s = (string)filterCriteria;
  358. if (s.EndsWith ("*"))
  359. return m.Name.StartsWith (s.Substring (0, s.Length - 1));
  360. else
  361. return m.Name == s;
  362. }
  363. private static bool filter_by_type_name_ignore_case (Type m, object filterCriteria) {
  364. string s = (string)filterCriteria;
  365. if (s.EndsWith ("*"))
  366. return m.Name.ToLower ().StartsWith (s.Substring (0, s.Length - 1).ToLower ());
  367. else
  368. return String.Compare (m.Name, s, true) == 0;
  369. }
  370. [MethodImplAttribute (MethodImplOptions.InternalCall)]
  371. internal extern IntPtr GetHINSTANCE ();
  372. [MethodImplAttribute (MethodImplOptions.InternalCall)]
  373. private extern string GetGuidInternal ();
  374. [MethodImplAttribute (MethodImplOptions.InternalCall)]
  375. private extern Type GetGlobalType ();
  376. [MethodImplAttribute (MethodImplOptions.InternalCall)]
  377. internal static extern IntPtr ResolveTypeToken (IntPtr module, int token, IntPtr[] type_args, IntPtr[] method_args, out ResolveTokenError error);
  378. [MethodImplAttribute (MethodImplOptions.InternalCall)]
  379. internal static extern IntPtr ResolveMethodToken (IntPtr module, int token, IntPtr[] type_args, IntPtr[] method_args, out ResolveTokenError error);
  380. [MethodImplAttribute (MethodImplOptions.InternalCall)]
  381. internal static extern IntPtr ResolveFieldToken (IntPtr module, int token, IntPtr[] type_args, IntPtr[] method_args, out ResolveTokenError error);
  382. [MethodImplAttribute (MethodImplOptions.InternalCall)]
  383. internal static extern string ResolveStringToken (IntPtr module, int token, out ResolveTokenError error);
  384. [MethodImplAttribute (MethodImplOptions.InternalCall)]
  385. internal static extern MemberInfo ResolveMemberToken (IntPtr module, int token, IntPtr[] type_args, IntPtr[] method_args, out ResolveTokenError error);
  386. [MethodImplAttribute (MethodImplOptions.InternalCall)]
  387. internal static extern byte[] ResolveSignature (IntPtr module, int metadataToken, out ResolveTokenError error);
  388. [MethodImplAttribute (MethodImplOptions.InternalCall)]
  389. internal static extern void GetPEKind (IntPtr module, out PortableExecutableKinds peKind, out ImageFileMachine machine);
  390. void _Module.GetIDsOfNames ([In] ref Guid riid, IntPtr rgszNames, uint cNames, uint lcid, IntPtr rgDispId)
  391. {
  392. throw new NotImplementedException ();
  393. }
  394. void _Module.GetTypeInfo (uint iTInfo, uint lcid, IntPtr ppTInfo)
  395. {
  396. throw new NotImplementedException ();
  397. }
  398. void _Module.GetTypeInfoCount (out uint pcTInfo)
  399. {
  400. throw new NotImplementedException ();
  401. }
  402. void _Module.Invoke (uint dispIdMember, [In] ref Guid riid, uint lcid, short wFlags, IntPtr pDispParams,
  403. IntPtr pVarResult, IntPtr pExcepInfo, IntPtr puArgErr)
  404. {
  405. throw new NotImplementedException ();
  406. }
  407. }
  408. }