Module.cs 15 KB

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