Module.cs 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514
  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. #if NET_4_0
  47. public class Module : ISerializable, ICustomAttributeProvider, _Module {
  48. #else
  49. public partial class Module : ISerializable, ICustomAttributeProvider, _Module {
  50. #endif
  51. public static readonly TypeFilter FilterTypeName;
  52. public static readonly TypeFilter FilterTypeNameIgnoreCase;
  53. #pragma warning disable 649
  54. private IntPtr _impl; /* a pointer to a MonoImage */
  55. internal Assembly assembly;
  56. internal string fqname;
  57. internal string name;
  58. internal string scopename;
  59. internal bool is_resource;
  60. internal int token;
  61. #pragma warning restore 649
  62. const BindingFlags defaultBindingFlags =
  63. BindingFlags.Public | BindingFlags.Static | BindingFlags.Instance;
  64. static Module () {
  65. FilterTypeName = new TypeFilter (filter_by_type_name);
  66. FilterTypeNameIgnoreCase = new TypeFilter (filter_by_type_name_ignore_case);
  67. }
  68. #if NET_4_0
  69. protected
  70. #else
  71. internal
  72. #endif
  73. Module () {
  74. }
  75. public Assembly Assembly {
  76. get { return assembly; }
  77. }
  78. public virtual string FullyQualifiedName {
  79. get {
  80. #if !NET_2_1
  81. if (SecurityManager.SecurityEnabled) {
  82. new FileIOPermission (FileIOPermissionAccess.PathDiscovery, fqname).Demand ();
  83. }
  84. #endif
  85. return fqname;
  86. }
  87. }
  88. // Note: we do not ask for PathDiscovery because no path is returned here.
  89. // However MS Fx requires it (see FDBK23572 for details).
  90. public string Name {
  91. get { return name; }
  92. }
  93. public string ScopeName {
  94. get { return scopename; }
  95. }
  96. public ModuleHandle ModuleHandle {
  97. get {
  98. return new ModuleHandle (_impl);
  99. }
  100. }
  101. public extern int MetadataToken {
  102. [MethodImplAttribute (MethodImplOptions.InternalCall)]
  103. get;
  104. }
  105. public int MDStreamVersion {
  106. get {
  107. if (_impl == IntPtr.Zero)
  108. throw new NotSupportedException ();
  109. return GetMDStreamVersion (_impl);
  110. }
  111. }
  112. [MethodImplAttribute (MethodImplOptions.InternalCall)]
  113. internal static extern int GetMDStreamVersion (IntPtr module_handle);
  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 override string ToString ()
  234. {
  235. return name;
  236. }
  237. internal Guid MvId {
  238. get {
  239. return GetModuleVersionId ();
  240. }
  241. }
  242. public Guid ModuleVersionId {
  243. get {
  244. return GetModuleVersionId ();
  245. }
  246. }
  247. public void GetPEKind (out PortableExecutableKinds peKind, out ImageFileMachine machine) {
  248. ModuleHandle.GetPEKind (out peKind, out machine);
  249. }
  250. private Exception resolve_token_exception (int metadataToken, ResolveTokenError error, string tokenType) {
  251. if (error == ResolveTokenError.OutOfRange)
  252. return new ArgumentOutOfRangeException ("metadataToken", String.Format ("Token 0x{0:x} is not valid in the scope of module {1}", metadataToken, name));
  253. else
  254. 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");
  255. }
  256. private IntPtr[] ptrs_from_types (Type[] types) {
  257. if (types == null)
  258. return null;
  259. else {
  260. IntPtr[] res = new IntPtr [types.Length];
  261. for (int i = 0; i < types.Length; ++i) {
  262. if (types [i] == null)
  263. throw new ArgumentException ();
  264. res [i] = types [i].TypeHandle.Value;
  265. }
  266. return res;
  267. }
  268. }
  269. public FieldInfo ResolveField (int metadataToken) {
  270. return ResolveField (metadataToken, null, null);
  271. }
  272. public FieldInfo ResolveField (int metadataToken, Type [] genericTypeArguments, Type [] genericMethodArguments) {
  273. ResolveTokenError error;
  274. IntPtr handle = ResolveFieldToken (_impl, metadataToken, ptrs_from_types (genericTypeArguments), ptrs_from_types (genericMethodArguments), out error);
  275. if (handle == IntPtr.Zero)
  276. throw resolve_token_exception (metadataToken, error, "Field");
  277. else
  278. return FieldInfo.GetFieldFromHandle (new RuntimeFieldHandle (handle));
  279. }
  280. public MemberInfo ResolveMember (int metadataToken) {
  281. return ResolveMember (metadataToken, null, null);
  282. }
  283. public MemberInfo ResolveMember (int metadataToken, Type [] genericTypeArguments, Type [] genericMethodArguments) {
  284. ResolveTokenError error;
  285. MemberInfo m = ResolveMemberToken (_impl, metadataToken, ptrs_from_types (genericTypeArguments), ptrs_from_types (genericMethodArguments), out error);
  286. if (m == null)
  287. throw resolve_token_exception (metadataToken, error, "MemberInfo");
  288. else
  289. return m;
  290. }
  291. public MethodBase ResolveMethod (int metadataToken) {
  292. return ResolveMethod (metadataToken, null, null);
  293. }
  294. public MethodBase ResolveMethod (int metadataToken, Type [] genericTypeArguments, Type [] genericMethodArguments) {
  295. ResolveTokenError error;
  296. IntPtr handle = ResolveMethodToken (_impl, metadataToken, ptrs_from_types (genericTypeArguments), ptrs_from_types (genericMethodArguments), out error);
  297. if (handle == IntPtr.Zero)
  298. throw resolve_token_exception (metadataToken, error, "MethodBase");
  299. else
  300. return MethodBase.GetMethodFromHandleNoGenericCheck (new RuntimeMethodHandle (handle));
  301. }
  302. public string ResolveString (int metadataToken) {
  303. ResolveTokenError error;
  304. string s = ResolveStringToken (_impl, metadataToken, out error);
  305. if (s == null)
  306. throw resolve_token_exception (metadataToken, error, "string");
  307. else
  308. return s;
  309. }
  310. public Type ResolveType (int metadataToken) {
  311. return ResolveType (metadataToken, null, null);
  312. }
  313. public Type ResolveType (int metadataToken, Type [] genericTypeArguments, Type [] genericMethodArguments) {
  314. ResolveTokenError error;
  315. IntPtr handle = ResolveTypeToken (_impl, metadataToken, ptrs_from_types (genericTypeArguments), ptrs_from_types (genericMethodArguments), out error);
  316. if (handle == IntPtr.Zero)
  317. throw resolve_token_exception (metadataToken, error, "Type");
  318. else
  319. return Type.GetTypeFromHandle (new RuntimeTypeHandle (handle));
  320. }
  321. public byte[] ResolveSignature (int metadataToken) {
  322. ResolveTokenError error;
  323. byte[] res = ResolveSignature (_impl, metadataToken, out error);
  324. if (res == null)
  325. throw resolve_token_exception (metadataToken, error, "signature");
  326. else
  327. return res;
  328. }
  329. #if NET_4_0
  330. public virtual IList<CustomAttributeData> GetCustomAttributesData () {
  331. return CustomAttributeData.GetCustomAttributes (this);
  332. }
  333. #endif
  334. internal static Type MonoDebugger_ResolveType (Module module, int token)
  335. {
  336. ResolveTokenError error;
  337. IntPtr handle = ResolveTypeToken (module._impl, token, null, null, out error);
  338. if (handle == IntPtr.Zero)
  339. return null;
  340. else
  341. return Type.GetTypeFromHandle (new RuntimeTypeHandle (handle));
  342. }
  343. // Used by mcs, the symbol writer, and mdb through reflection
  344. internal static Guid Mono_GetGuid (Module module)
  345. {
  346. return module.GetModuleVersionId ();
  347. }
  348. internal virtual Guid GetModuleVersionId ()
  349. {
  350. return new Guid (GetGuidInternal ());
  351. }
  352. private static bool filter_by_type_name (Type m, object filterCriteria) {
  353. string s = (string)filterCriteria;
  354. if (s.EndsWith ("*"))
  355. return m.Name.StartsWith (s.Substring (0, s.Length - 1));
  356. else
  357. return m.Name == s;
  358. }
  359. private static bool filter_by_type_name_ignore_case (Type m, object filterCriteria) {
  360. string s = (string)filterCriteria;
  361. if (s.EndsWith ("*"))
  362. return m.Name.ToLower ().StartsWith (s.Substring (0, s.Length - 1).ToLower ());
  363. else
  364. return String.Compare (m.Name, s, true) == 0;
  365. }
  366. [MethodImplAttribute (MethodImplOptions.InternalCall)]
  367. internal extern IntPtr GetHINSTANCE ();
  368. [MethodImplAttribute (MethodImplOptions.InternalCall)]
  369. private extern string GetGuidInternal ();
  370. [MethodImplAttribute (MethodImplOptions.InternalCall)]
  371. private extern Type GetGlobalType ();
  372. [MethodImplAttribute (MethodImplOptions.InternalCall)]
  373. internal static extern IntPtr ResolveTypeToken (IntPtr module, int token, IntPtr[] type_args, IntPtr[] method_args, out ResolveTokenError error);
  374. [MethodImplAttribute (MethodImplOptions.InternalCall)]
  375. internal static extern IntPtr ResolveMethodToken (IntPtr module, int token, IntPtr[] type_args, IntPtr[] method_args, out ResolveTokenError error);
  376. [MethodImplAttribute (MethodImplOptions.InternalCall)]
  377. internal static extern IntPtr ResolveFieldToken (IntPtr module, int token, IntPtr[] type_args, IntPtr[] method_args, out ResolveTokenError error);
  378. [MethodImplAttribute (MethodImplOptions.InternalCall)]
  379. internal static extern string ResolveStringToken (IntPtr module, int token, out ResolveTokenError error);
  380. [MethodImplAttribute (MethodImplOptions.InternalCall)]
  381. internal static extern MemberInfo ResolveMemberToken (IntPtr module, int token, IntPtr[] type_args, IntPtr[] method_args, out ResolveTokenError error);
  382. [MethodImplAttribute (MethodImplOptions.InternalCall)]
  383. internal static extern byte[] ResolveSignature (IntPtr module, int metadataToken, out ResolveTokenError error);
  384. [MethodImplAttribute (MethodImplOptions.InternalCall)]
  385. internal static extern void GetPEKind (IntPtr module, out PortableExecutableKinds peKind, out ImageFileMachine machine);
  386. void _Module.GetIDsOfNames ([In] ref Guid riid, IntPtr rgszNames, uint cNames, uint lcid, IntPtr rgDispId)
  387. {
  388. throw new NotImplementedException ();
  389. }
  390. void _Module.GetTypeInfo (uint iTInfo, uint lcid, IntPtr ppTInfo)
  391. {
  392. throw new NotImplementedException ();
  393. }
  394. void _Module.GetTypeInfoCount (out uint pcTInfo)
  395. {
  396. throw new NotImplementedException ();
  397. }
  398. void _Module.Invoke (uint dispIdMember, [In] ref Guid riid, uint lcid, short wFlags, IntPtr pDispParams,
  399. IntPtr pVarResult, IntPtr pExcepInfo, IntPtr puArgErr)
  400. {
  401. throw new NotImplementedException ();
  402. }
  403. #if NET_4_0
  404. static Exception CreateNIE ()
  405. {
  406. return new NotImplementedException ("Derived classes must implement it");
  407. }
  408. public virtual bool IsResource()
  409. {
  410. throw CreateNIE ();
  411. }
  412. public virtual Type[] FindTypes(TypeFilter filter, object filterCriteria)
  413. {
  414. throw CreateNIE ();
  415. }
  416. #endif
  417. }
  418. }