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 FieldInfo GetField (string name)
  115. {
  116. if (IsResource ())
  117. return null;
  118. Type globalType = GetGlobalType ();
  119. return (globalType != null) ? globalType.GetField (name, BindingFlags.Public | BindingFlags.Static) : null;
  120. }
  121. public FieldInfo GetField (string name, BindingFlags bindingAttr)
  122. {
  123. if (IsResource ())
  124. return null;
  125. Type globalType = GetGlobalType ();
  126. return (globalType != null) ? globalType.GetField (name, bindingAttr) : null;
  127. }
  128. public FieldInfo[] GetFields ()
  129. {
  130. if (IsResource ())
  131. return new FieldInfo [0];
  132. Type globalType = GetGlobalType ();
  133. return (globalType != null) ? globalType.GetFields (BindingFlags.Public | BindingFlags.Static) : new FieldInfo [0];
  134. }
  135. public MethodInfo GetMethod (string name)
  136. {
  137. // Can't call the other overloads since they call Type.GetMethod () which does a null check on the 'types' array
  138. if (IsResource ())
  139. return null;
  140. Type globalType = GetGlobalType ();
  141. return (globalType != null) ? globalType.GetMethod (name) : null;
  142. }
  143. public MethodInfo GetMethod (string name, Type[] types)
  144. {
  145. return GetMethodImpl (name, defaultBindingFlags, null, CallingConventions.Any, types, null);
  146. }
  147. public MethodInfo GetMethod (string name, BindingFlags bindingAttr, Binder binder, CallingConventions callConvention, Type[] types, ParameterModifier[] modifiers)
  148. {
  149. return GetMethodImpl (name, bindingAttr, binder, callConvention, types, modifiers);
  150. }
  151. protected virtual MethodInfo GetMethodImpl (string name, BindingFlags bindingAttr, Binder binder, CallingConventions callConvention, Type[] types, ParameterModifier[] modifiers)
  152. {
  153. if (IsResource ())
  154. return null;
  155. Type globalType = GetGlobalType ();
  156. return (globalType != null) ? globalType.GetMethod (name, bindingAttr, binder, callConvention, types, modifiers) : null;
  157. }
  158. public MethodInfo[] GetMethods ()
  159. {
  160. if (IsResource ())
  161. return new MethodInfo [0];
  162. Type globalType = GetGlobalType ();
  163. return (globalType != null) ? globalType.GetMethods () : new MethodInfo [0];
  164. }
  165. public MethodInfo[] GetMethods (BindingFlags bindingFlags) {
  166. if (IsResource ())
  167. return new MethodInfo [0];
  168. Type globalType = GetGlobalType ();
  169. return (globalType != null) ? globalType.GetMethods (bindingFlags) : new MethodInfo [0];
  170. }
  171. public FieldInfo[] GetFields (BindingFlags bindingFlags)
  172. {
  173. if (IsResource ())
  174. return new FieldInfo [0];
  175. Type globalType = GetGlobalType ();
  176. return (globalType != null) ? globalType.GetFields (bindingFlags) : new FieldInfo [0];
  177. }
  178. [SecurityPermission (SecurityAction.LinkDemand, SerializationFormatter = true)]
  179. public virtual void GetObjectData (SerializationInfo info, StreamingContext context)
  180. {
  181. if (info == null)
  182. throw new ArgumentNullException ("info");
  183. UnitySerializationHolder.GetModuleData (this, info, context);
  184. }
  185. #if !NET_2_1
  186. public X509Certificate GetSignerCertificate ()
  187. {
  188. try {
  189. return X509Certificate.CreateFromSignedFile (assembly.Location);
  190. }
  191. catch {
  192. return null;
  193. }
  194. }
  195. #endif
  196. [ComVisible (true)]
  197. public virtual Type GetType(string className)
  198. {
  199. return GetType (className, false, false);
  200. }
  201. [ComVisible (true)]
  202. public virtual Type GetType(string className, bool ignoreCase)
  203. {
  204. return GetType (className, false, ignoreCase);
  205. }
  206. [ComVisible (true)]
  207. public virtual Type GetType(string className, bool throwOnError, bool ignoreCase)
  208. {
  209. if (className == null)
  210. throw new ArgumentNullException ("className");
  211. if (className == String.Empty)
  212. throw new ArgumentException ("Type name can't be empty");
  213. return assembly.InternalGetType (this, className, throwOnError, ignoreCase);
  214. }
  215. [MethodImplAttribute (MethodImplOptions.InternalCall)]
  216. private extern Type[] InternalGetTypes ();
  217. public virtual Type[] GetTypes()
  218. {
  219. return InternalGetTypes ();
  220. }
  221. public virtual bool IsDefined (Type attributeType, bool inherit)
  222. {
  223. return MonoCustomAttrs.IsDefined (this, attributeType, inherit);
  224. }
  225. public override string ToString ()
  226. {
  227. return name;
  228. }
  229. internal Guid MvId {
  230. get {
  231. return GetModuleVersionId ();
  232. }
  233. }
  234. public Guid ModuleVersionId {
  235. get {
  236. return GetModuleVersionId ();
  237. }
  238. }
  239. public void GetPEKind (out PortableExecutableKinds peKind, out ImageFileMachine machine) {
  240. ModuleHandle.GetPEKind (out peKind, out machine);
  241. }
  242. private Exception resolve_token_exception (int metadataToken, ResolveTokenError error, string tokenType) {
  243. if (error == ResolveTokenError.OutOfRange)
  244. return new ArgumentOutOfRangeException ("metadataToken", String.Format ("Token 0x{0:x} is not valid in the scope of module {1}", metadataToken, name));
  245. else
  246. 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");
  247. }
  248. private IntPtr[] ptrs_from_types (Type[] types) {
  249. if (types == null)
  250. return null;
  251. else {
  252. IntPtr[] res = new IntPtr [types.Length];
  253. for (int i = 0; i < types.Length; ++i) {
  254. if (types [i] == null)
  255. throw new ArgumentException ();
  256. res [i] = types [i].TypeHandle.Value;
  257. }
  258. return res;
  259. }
  260. }
  261. public FieldInfo ResolveField (int metadataToken) {
  262. return ResolveField (metadataToken, null, null);
  263. }
  264. public FieldInfo ResolveField (int metadataToken, Type [] genericTypeArguments, Type [] genericMethodArguments) {
  265. ResolveTokenError error;
  266. IntPtr handle = ResolveFieldToken (_impl, metadataToken, ptrs_from_types (genericTypeArguments), ptrs_from_types (genericMethodArguments), out error);
  267. if (handle == IntPtr.Zero)
  268. throw resolve_token_exception (metadataToken, error, "Field");
  269. else
  270. return FieldInfo.GetFieldFromHandle (new RuntimeFieldHandle (handle));
  271. }
  272. public MemberInfo ResolveMember (int metadataToken) {
  273. return ResolveMember (metadataToken, null, null);
  274. }
  275. public MemberInfo ResolveMember (int metadataToken, Type [] genericTypeArguments, Type [] genericMethodArguments) {
  276. ResolveTokenError error;
  277. MemberInfo m = ResolveMemberToken (_impl, metadataToken, ptrs_from_types (genericTypeArguments), ptrs_from_types (genericMethodArguments), out error);
  278. if (m == null)
  279. throw resolve_token_exception (metadataToken, error, "MemberInfo");
  280. else
  281. return m;
  282. }
  283. public MethodBase ResolveMethod (int metadataToken) {
  284. return ResolveMethod (metadataToken, null, null);
  285. }
  286. public MethodBase ResolveMethod (int metadataToken, Type [] genericTypeArguments, Type [] genericMethodArguments) {
  287. ResolveTokenError error;
  288. IntPtr handle = ResolveMethodToken (_impl, metadataToken, ptrs_from_types (genericTypeArguments), ptrs_from_types (genericMethodArguments), out error);
  289. if (handle == IntPtr.Zero)
  290. throw resolve_token_exception (metadataToken, error, "MethodBase");
  291. else
  292. return MethodBase.GetMethodFromHandleNoGenericCheck (new RuntimeMethodHandle (handle));
  293. }
  294. public string ResolveString (int metadataToken) {
  295. ResolveTokenError error;
  296. string s = ResolveStringToken (_impl, metadataToken, out error);
  297. if (s == null)
  298. throw resolve_token_exception (metadataToken, error, "string");
  299. else
  300. return s;
  301. }
  302. public Type ResolveType (int metadataToken) {
  303. return ResolveType (metadataToken, null, null);
  304. }
  305. public Type ResolveType (int metadataToken, Type [] genericTypeArguments, Type [] genericMethodArguments) {
  306. ResolveTokenError error;
  307. IntPtr handle = ResolveTypeToken (_impl, metadataToken, ptrs_from_types (genericTypeArguments), ptrs_from_types (genericMethodArguments), out error);
  308. if (handle == IntPtr.Zero)
  309. throw resolve_token_exception (metadataToken, error, "Type");
  310. else
  311. return Type.GetTypeFromHandle (new RuntimeTypeHandle (handle));
  312. }
  313. public byte[] ResolveSignature (int metadataToken) {
  314. ResolveTokenError error;
  315. byte[] res = ResolveSignature (_impl, metadataToken, out error);
  316. if (res == null)
  317. throw resolve_token_exception (metadataToken, error, "signature");
  318. else
  319. return res;
  320. }
  321. #if NET_4_0
  322. public virtual IList<CustomAttributeData> GetCustomAttributesData () {
  323. return CustomAttributeData.GetCustomAttributes (this);
  324. }
  325. #endif
  326. internal static Type MonoDebugger_ResolveType (Module module, int token)
  327. {
  328. ResolveTokenError error;
  329. IntPtr handle = ResolveTypeToken (module._impl, token, null, null, out error);
  330. if (handle == IntPtr.Zero)
  331. return null;
  332. else
  333. return Type.GetTypeFromHandle (new RuntimeTypeHandle (handle));
  334. }
  335. // Used by mcs, the symbol writer, and mdb through reflection
  336. internal static Guid Mono_GetGuid (Module module)
  337. {
  338. return module.GetModuleVersionId ();
  339. }
  340. internal virtual Guid GetModuleVersionId ()
  341. {
  342. return new Guid (GetGuidInternal ());
  343. }
  344. private static bool filter_by_type_name (Type m, object filterCriteria) {
  345. string s = (string)filterCriteria;
  346. if (s.EndsWith ("*"))
  347. return m.Name.StartsWith (s.Substring (0, s.Length - 1));
  348. else
  349. return m.Name == s;
  350. }
  351. private static bool filter_by_type_name_ignore_case (Type m, object filterCriteria) {
  352. string s = (string)filterCriteria;
  353. if (s.EndsWith ("*"))
  354. return m.Name.ToLower ().StartsWith (s.Substring (0, s.Length - 1).ToLower ());
  355. else
  356. return String.Compare (m.Name, s, true) == 0;
  357. }
  358. [MethodImplAttribute (MethodImplOptions.InternalCall)]
  359. internal extern IntPtr GetHINSTANCE ();
  360. [MethodImplAttribute (MethodImplOptions.InternalCall)]
  361. private extern string GetGuidInternal ();
  362. [MethodImplAttribute (MethodImplOptions.InternalCall)]
  363. private extern Type GetGlobalType ();
  364. [MethodImplAttribute (MethodImplOptions.InternalCall)]
  365. internal static extern IntPtr ResolveTypeToken (IntPtr module, int token, IntPtr[] type_args, IntPtr[] method_args, out ResolveTokenError error);
  366. [MethodImplAttribute (MethodImplOptions.InternalCall)]
  367. internal static extern IntPtr ResolveMethodToken (IntPtr module, int token, IntPtr[] type_args, IntPtr[] method_args, out ResolveTokenError error);
  368. [MethodImplAttribute (MethodImplOptions.InternalCall)]
  369. internal static extern IntPtr ResolveFieldToken (IntPtr module, int token, IntPtr[] type_args, IntPtr[] method_args, out ResolveTokenError error);
  370. [MethodImplAttribute (MethodImplOptions.InternalCall)]
  371. internal static extern string ResolveStringToken (IntPtr module, int token, out ResolveTokenError error);
  372. [MethodImplAttribute (MethodImplOptions.InternalCall)]
  373. internal static extern MemberInfo ResolveMemberToken (IntPtr module, int token, IntPtr[] type_args, IntPtr[] method_args, out ResolveTokenError error);
  374. [MethodImplAttribute (MethodImplOptions.InternalCall)]
  375. internal static extern byte[] ResolveSignature (IntPtr module, int metadataToken, out ResolveTokenError error);
  376. [MethodImplAttribute (MethodImplOptions.InternalCall)]
  377. internal static extern void GetPEKind (IntPtr module, out PortableExecutableKinds peKind, out ImageFileMachine machine);
  378. void _Module.GetIDsOfNames ([In] ref Guid riid, IntPtr rgszNames, uint cNames, uint lcid, IntPtr rgDispId)
  379. {
  380. throw new NotImplementedException ();
  381. }
  382. void _Module.GetTypeInfo (uint iTInfo, uint lcid, IntPtr ppTInfo)
  383. {
  384. throw new NotImplementedException ();
  385. }
  386. void _Module.GetTypeInfoCount (out uint pcTInfo)
  387. {
  388. throw new NotImplementedException ();
  389. }
  390. void _Module.Invoke (uint dispIdMember, [In] ref Guid riid, uint lcid, short wFlags, IntPtr pDispParams,
  391. IntPtr pVarResult, IntPtr pExcepInfo, IntPtr puArgErr)
  392. {
  393. throw new NotImplementedException ();
  394. }
  395. #if NET_4_0
  396. static Exception CreateNIE ()
  397. {
  398. return new NotImplementedException ("Derived classes must implement it");
  399. }
  400. public virtual bool IsResource()
  401. {
  402. throw CreateNIE ();
  403. }
  404. public virtual Type[] FindTypes(TypeFilter filter, object filterCriteria)
  405. {
  406. throw CreateNIE ();
  407. }
  408. public virtual object[] GetCustomAttributes(bool inherit)
  409. {
  410. throw CreateNIE ();
  411. }
  412. public virtual object[] GetCustomAttributes(Type attributeType, bool inherit)
  413. {
  414. throw CreateNIE ();
  415. }
  416. #endif
  417. }
  418. }