MethodBuilder.cs 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511
  1. //
  2. // System.Reflection.Emit/MethodBuilder.cs
  3. //
  4. // Author:
  5. // Paolo Molaro ([email protected])
  6. //
  7. // (C) 2001 Ximian, Inc. http://www.ximian.com
  8. //
  9. //
  10. // Copyright (C) 2004 Novell, Inc (http://www.novell.com)
  11. //
  12. // Permission is hereby granted, free of charge, to any person obtaining
  13. // a copy of this software and associated documentation files (the
  14. // "Software"), to deal in the Software without restriction, including
  15. // without limitation the rights to use, copy, modify, merge, publish,
  16. // distribute, sublicense, and/or sell copies of the Software, and to
  17. // permit persons to whom the Software is furnished to do so, subject to
  18. // the following conditions:
  19. //
  20. // The above copyright notice and this permission notice shall be
  21. // included in all copies or substantial portions of the Software.
  22. //
  23. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
  24. // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
  25. // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
  26. // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
  27. // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
  28. // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
  29. // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
  30. //
  31. using System;
  32. using System.Reflection;
  33. using System.Reflection.Emit;
  34. using System.Globalization;
  35. using System.Security;
  36. using System.Security.Permissions;
  37. using System.Runtime.CompilerServices;
  38. using System.Runtime.InteropServices;
  39. using System.Diagnostics.SymbolStore;
  40. namespace System.Reflection.Emit {
  41. #if NET_2_0
  42. [ComVisible (true)]
  43. [ClassInterfaceAttribute (ClassInterfaceType.None)]
  44. [ComDefaultInterfaceAttribute (typeof (_MethodBuilder))]
  45. #endif
  46. public sealed class MethodBuilder : MethodInfo {
  47. private RuntimeMethodHandle mhandle;
  48. private Type rtype;
  49. private Type[] parameters;
  50. private MethodAttributes attrs;
  51. private MethodImplAttributes iattrs;
  52. private string name;
  53. private int table_idx;
  54. private byte[] code;
  55. private ILGenerator ilgen;
  56. private TypeBuilder type;
  57. private ParameterBuilder[] pinfo;
  58. private CustomAttributeBuilder[] cattrs;
  59. private MethodInfo override_method;
  60. private string pi_dll;
  61. private string pi_entry;
  62. private CharSet charset;
  63. private uint extra_flags; /* this encodes set_last_error etc */
  64. private CallingConvention native_cc;
  65. private CallingConventions call_conv;
  66. private bool init_locals = true;
  67. private IntPtr generic_container;
  68. #if NET_2_0 || BOOTSTRAP_NET_2_0
  69. private GenericTypeParameterBuilder[] generic_params;
  70. #else
  71. private Object generic_params; /* so offsets are the same */
  72. #endif
  73. private Type[] returnModReq;
  74. private Type[] returnModOpt;
  75. private Type[][] paramModReq;
  76. private Type[][] paramModOpt;
  77. private RefEmitPermissionSet[] permissions;
  78. internal MethodBuilder (TypeBuilder tb, string name, MethodAttributes attributes, CallingConventions callingConvention, Type returnType, Type[] returnModReq, Type[] returnModOpt, Type[] parameterTypes, Type[][] paramModReq, Type[][] paramModOpt) {
  79. this.name = name;
  80. this.attrs = attributes;
  81. this.call_conv = callingConvention;
  82. this.rtype = returnType;
  83. this.returnModReq = returnModReq;
  84. this.returnModOpt = returnModOpt;
  85. this.paramModReq = paramModReq;
  86. this.paramModOpt = paramModOpt;
  87. // The MSDN docs does not specify this, but the MS MethodBuilder
  88. // appends a HasThis flag if the method is not static
  89. if ((attributes & MethodAttributes.Static) == 0)
  90. this.call_conv |= CallingConventions.HasThis;
  91. if (parameterTypes != null) {
  92. for (int i = 0; i < parameterTypes.Length; ++i)
  93. if (parameterTypes [i] == null)
  94. throw new ArgumentException ("Elements of the parameterTypes array cannot be null", "parameterTypes");
  95. this.parameters = new Type [parameterTypes.Length];
  96. System.Array.Copy (parameterTypes, this.parameters, parameterTypes.Length);
  97. }
  98. type = tb;
  99. table_idx = get_next_table_index (this, 0x06, true);
  100. //Console.WriteLine ("index for "+name+" set to "+table_idx.ToString());
  101. }
  102. internal MethodBuilder (TypeBuilder tb, string name, MethodAttributes attributes,
  103. CallingConventions callingConvention, Type returnType, Type[] returnModReq, Type[] returnModOpt, Type[] parameterTypes, Type[][] paramModReq, Type[][] paramModOpt,
  104. String dllName, String entryName, CallingConvention nativeCConv, CharSet nativeCharset)
  105. : this (tb, name, attributes, callingConvention, returnType, returnModReq, returnModOpt, parameterTypes, paramModReq, paramModOpt) {
  106. pi_dll = dllName;
  107. pi_entry = entryName;
  108. native_cc = nativeCConv;
  109. charset = nativeCharset;
  110. }
  111. public bool InitLocals {
  112. get {return init_locals;}
  113. set {init_locals = value;}
  114. }
  115. internal TypeBuilder TypeBuilder {
  116. get {return type;}
  117. }
  118. public override RuntimeMethodHandle MethodHandle {
  119. get {
  120. throw NotSupported ();
  121. }
  122. }
  123. public override Type ReturnType {get {return rtype;}}
  124. public override Type ReflectedType {get {return type;}}
  125. public override Type DeclaringType {get {return type;}}
  126. public override string Name {get {return name;}}
  127. public override MethodAttributes Attributes {get {return attrs;}}
  128. public override ICustomAttributeProvider ReturnTypeCustomAttributes {
  129. get {return null;}
  130. }
  131. public override CallingConventions CallingConvention {
  132. get { return call_conv; }
  133. }
  134. [MonoTODO]
  135. public string Signature {
  136. get {
  137. throw new NotImplementedException ();
  138. }
  139. }
  140. /* Used by mcs */
  141. internal bool BestFitMapping {
  142. set {
  143. extra_flags = (uint) ((extra_flags & ~0x30) | (value ? 0x10 : 0x20));
  144. }
  145. }
  146. /* Used by mcs */
  147. internal bool ThrowOnUnmappableChar {
  148. set {
  149. extra_flags = (uint) ((extra_flags & ~0x3000) | (value ? 0x1000 : 0x2000));
  150. }
  151. }
  152. /* Used by mcs */
  153. internal bool ExactSpelling {
  154. set {
  155. extra_flags = (uint) ((extra_flags & ~0x01) | (value ? 0x01 : 0x00));
  156. }
  157. }
  158. /* Used by mcs */
  159. internal bool SetLastError {
  160. set {
  161. extra_flags = (uint) ((extra_flags & ~0x40) | (value ? 0x40 : 0x00));
  162. }
  163. }
  164. public MethodToken GetToken() {
  165. return new MethodToken(0x06000000 | table_idx);
  166. }
  167. public override MethodInfo GetBaseDefinition() {
  168. return this;
  169. }
  170. public override MethodImplAttributes GetMethodImplementationFlags() {
  171. return iattrs;
  172. }
  173. public override ParameterInfo[] GetParameters() {
  174. if (!type.is_created)
  175. throw NotSupported ();
  176. if (parameters == null)
  177. return null;
  178. ParameterInfo[] retval = new ParameterInfo [parameters.Length];
  179. for (int i = 0; i < parameters.Length; i++) {
  180. retval [i] = new ParameterInfo (pinfo == null ? null : pinfo [i + 1], parameters [i], this, i + 1);
  181. }
  182. return retval;
  183. }
  184. internal override int GetParameterCount ()
  185. {
  186. if (parameters == null)
  187. return 0;
  188. return parameters.Length;
  189. }
  190. public Module GetModule () {
  191. return type.Module;
  192. }
  193. public void CreateMethodBody( byte[] il, int count) {
  194. if ((il != null) && ((count < 0) || (count > il.Length)))
  195. throw new ArgumentException ("Index was out of range. Must be non-negative and less than the size of the collection.");
  196. if ((code != null) || type.is_created)
  197. throw new InvalidOperationException ("Type definition of the method is complete.");
  198. if (il == null)
  199. code = null;
  200. else {
  201. code = new byte [count];
  202. System.Array.Copy(il, code, count);
  203. }
  204. }
  205. public override Object Invoke(Object obj, BindingFlags invokeAttr, Binder binder, Object[] parameters, CultureInfo culture) {
  206. throw NotSupported ();
  207. }
  208. public override bool IsDefined (Type attribute_type, bool inherit) {
  209. throw NotSupported ();
  210. }
  211. public override object[] GetCustomAttributes( bool inherit) {
  212. throw NotSupported ();
  213. }
  214. public override object[] GetCustomAttributes( Type attributeType, bool inherit) {
  215. throw NotSupported ();
  216. }
  217. public ILGenerator GetILGenerator () {
  218. return GetILGenerator (64);
  219. }
  220. public ILGenerator GetILGenerator (int size) {
  221. if (((iattrs & MethodImplAttributes.CodeTypeMask) !=
  222. MethodImplAttributes.IL) ||
  223. ((iattrs & MethodImplAttributes.ManagedMask) !=
  224. MethodImplAttributes.Managed))
  225. throw new InvalidOperationException ("Method body should not exist.");
  226. if (ilgen != null)
  227. return ilgen;
  228. ilgen = new ILGenerator (type.Module, ((ModuleBuilder)type.Module).GetTokenGenerator (), size);
  229. return ilgen;
  230. }
  231. public ParameterBuilder DefineParameter (int position, ParameterAttributes attributes, string strParamName)
  232. {
  233. RejectIfCreated ();
  234. //
  235. // Extension: Mono allows position == 0 for the return attribute
  236. //
  237. if ((position < 0) || (position > parameters.Length))
  238. throw new ArgumentOutOfRangeException ("position");
  239. ParameterBuilder pb = new ParameterBuilder (this, position, attributes, strParamName);
  240. if (pinfo == null)
  241. pinfo = new ParameterBuilder [parameters.Length + 1];
  242. pinfo [position] = pb;
  243. return pb;
  244. }
  245. internal void fixup () {
  246. if (((attrs & (MethodAttributes.Abstract | MethodAttributes.PinvokeImpl)) == 0) && ((iattrs & (MethodImplAttributes.Runtime | MethodImplAttributes.InternalCall)) == 0)) {
  247. if (((ilgen == null) || (ILGenerator.Mono_GetCurrentOffset (ilgen) == 0)) && (code == null))
  248. throw new InvalidOperationException ("Method '" + Name + "' does not have a method body.");
  249. }
  250. if (ilgen != null)
  251. ilgen.label_fixup ();
  252. }
  253. internal void GenerateDebugInfo (ISymbolWriter symbolWriter)
  254. {
  255. if (ilgen != null && ilgen.HasDebugInfo) {
  256. SymbolToken token = new SymbolToken (GetToken().Token);
  257. symbolWriter.OpenMethod (token);
  258. symbolWriter.SetSymAttribute (token, "__name", System.Text.Encoding.UTF8.GetBytes (Name));
  259. ilgen.GenerateDebugInfo (symbolWriter);
  260. symbolWriter.CloseMethod ();
  261. }
  262. }
  263. public void SetCustomAttribute( CustomAttributeBuilder customBuilder) {
  264. if (customBuilder == null)
  265. throw new ArgumentNullException ("customBuilder");
  266. string attrname = customBuilder.Ctor.ReflectedType.FullName;
  267. if (attrname == "System.Runtime.CompilerServices.MethodImplAttribute") {
  268. byte[] data = customBuilder.Data;
  269. int impla; // the (stupid) ctor takes a short or an int ...
  270. impla = (int)data [2];
  271. impla |= ((int)data [3]) << 8;
  272. SetImplementationFlags ((MethodImplAttributes)impla);
  273. return;
  274. }
  275. if (attrname == "System.Runtime.InteropServices.DllImportAttribute") {
  276. CustomAttributeBuilder.CustomAttributeInfo attr = CustomAttributeBuilder.decode_cattr (customBuilder);
  277. bool preserveSig = true;
  278. /*
  279. * It would be easier to construct a DllImportAttribute from
  280. * the custom attribute builder, but the DllImportAttribute
  281. * does not contain all the information required here, ie.
  282. * - some parameters, like BestFitMapping has three values
  283. * ("on", "off", "missing"), but DllImportAttribute only
  284. * contains two (on/off).
  285. * - PreserveSig is true by default, while it is false by
  286. * default in DllImportAttribute.
  287. */
  288. pi_dll = (string)attr.ctorArgs [0];
  289. native_cc = System.Runtime.InteropServices.CallingConvention.Winapi;
  290. for (int i = 0; i < attr.namedParamNames.Length; ++i) {
  291. string name = attr.namedParamNames [i];
  292. object value = attr.namedParamValues [i];
  293. if (name == "CallingConvention")
  294. native_cc = (CallingConvention)value;
  295. else if (name == "CharSet")
  296. charset = (CharSet)value;
  297. else if (name == "EntryPoint")
  298. pi_entry = (string)value;
  299. else if (name == "ExactSpelling")
  300. ExactSpelling = (bool)value;
  301. else if (name == "SetLastError")
  302. SetLastError = (bool)value;
  303. else if (name == "PreserveSig")
  304. preserveSig = (bool)value;
  305. #if NET_1_1
  306. else if (name == "BestFitMapping")
  307. BestFitMapping = (bool)value;
  308. else if (name == "ThrowOnUnmappableChar")
  309. ThrowOnUnmappableChar = (bool)value;
  310. #endif
  311. }
  312. attrs |= MethodAttributes.PinvokeImpl;
  313. if (preserveSig)
  314. iattrs |= MethodImplAttributes.PreserveSig;
  315. return;
  316. }
  317. if (cattrs != null) {
  318. CustomAttributeBuilder[] new_array = new CustomAttributeBuilder [cattrs.Length + 1];
  319. cattrs.CopyTo (new_array, 0);
  320. new_array [cattrs.Length] = customBuilder;
  321. cattrs = new_array;
  322. } else {
  323. cattrs = new CustomAttributeBuilder [1];
  324. cattrs [0] = customBuilder;
  325. }
  326. }
  327. #if NET_2_0
  328. [ComVisible (true)]
  329. #endif
  330. public void SetCustomAttribute( ConstructorInfo con, byte[] binaryAttribute) {
  331. if (con == null)
  332. throw new ArgumentNullException ("con");
  333. if (binaryAttribute == null)
  334. throw new ArgumentNullException ("binaryAttribute");
  335. SetCustomAttribute (new CustomAttributeBuilder (con, binaryAttribute));
  336. }
  337. public void SetImplementationFlags( MethodImplAttributes attributes) {
  338. RejectIfCreated ();
  339. iattrs = attributes;
  340. }
  341. public void AddDeclarativeSecurity( SecurityAction action, PermissionSet pset) {
  342. if (pset == null)
  343. throw new ArgumentNullException ("pset");
  344. if ((action == SecurityAction.RequestMinimum) ||
  345. (action == SecurityAction.RequestOptional) ||
  346. (action == SecurityAction.RequestRefuse))
  347. throw new ArgumentException ("Request* values are not permitted", "action");
  348. RejectIfCreated ();
  349. if (permissions != null) {
  350. /* Check duplicate actions */
  351. foreach (RefEmitPermissionSet set in permissions)
  352. if (set.action == action)
  353. throw new InvalidOperationException ("Multiple permission sets specified with the same SecurityAction.");
  354. RefEmitPermissionSet[] new_array = new RefEmitPermissionSet [permissions.Length + 1];
  355. permissions.CopyTo (new_array, 0);
  356. permissions = new_array;
  357. }
  358. else
  359. permissions = new RefEmitPermissionSet [1];
  360. permissions [permissions.Length - 1] = new RefEmitPermissionSet (action, pset.ToXml ().ToString ());
  361. attrs |= MethodAttributes.HasSecurity;
  362. }
  363. #if NET_2_0
  364. [Obsolete ("An alternate API is available: Emit the MarshalAs custom attribute instead.")]
  365. #endif
  366. public void SetMarshal (UnmanagedMarshal unmanagedMarshal)
  367. {
  368. RejectIfCreated ();
  369. throw new NotImplementedException ();
  370. }
  371. [MonoTODO]
  372. public void SetSymCustomAttribute (string name, byte[] data)
  373. {
  374. RejectIfCreated ();
  375. throw new NotImplementedException ();
  376. }
  377. public override string ToString()
  378. {
  379. return "MethodBuilder [" + type.Name + "::" + name + "]";
  380. }
  381. [MonoTODO]
  382. public override bool Equals (object obj)
  383. {
  384. return base.Equals (obj);
  385. }
  386. public override int GetHashCode ()
  387. {
  388. return name.GetHashCode ();
  389. }
  390. internal override int get_next_table_index (object obj, int table, bool inc) {
  391. return type.get_next_table_index (obj, table, inc);
  392. }
  393. internal void set_override (MethodInfo mdecl) {
  394. override_method = mdecl;
  395. }
  396. private void RejectIfCreated () {
  397. if (type.is_created)
  398. throw new InvalidOperationException ("Type definition of the method is complete.");
  399. }
  400. private Exception NotSupported () {
  401. return new NotSupportedException ("The invoked member is not supported in a dynamic module.");
  402. }
  403. #if NET_2_0 || BOOTSTRAP_NET_2_0
  404. [MethodImplAttribute(MethodImplOptions.InternalCall)]
  405. public override extern MethodInfo BindGenericParameters (Type [] types);
  406. public override bool Mono_IsInflatedMethod {
  407. get {
  408. return false;
  409. }
  410. }
  411. public override bool HasGenericParameters {
  412. get {
  413. return generic_params != null;
  414. }
  415. }
  416. public override Type[] GetGenericArguments ()
  417. {
  418. if (generic_params == null)
  419. return new Type [0];
  420. Type[] result = new Type [generic_params.Length];
  421. for (int i = 0; i < generic_params.Length; i++)
  422. result [i] = generic_params [i];
  423. return result;
  424. }
  425. public GenericTypeParameterBuilder[] DefineGenericParameters (params string[] names)
  426. {
  427. generic_params = new GenericTypeParameterBuilder [names.Length];
  428. for (int i = 0; i < names.Length; i++)
  429. generic_params [i] = new GenericTypeParameterBuilder (
  430. type, this, names [i], i);
  431. return generic_params;
  432. }
  433. public void SetGenericMethodSignature (MethodAttributes attributes, CallingConventions callingConvention, Type return_type, Type[] parameter_types)
  434. {
  435. RejectIfCreated ();
  436. this.attrs = attributes;
  437. this.call_conv = callingConvention;
  438. if ((attributes & MethodAttributes.Static) == 0)
  439. this.call_conv |= CallingConventions.HasThis;
  440. this.rtype = return_type;
  441. this.parameters = new Type [parameter_types.Length];
  442. System.Array.Copy (parameter_types, this.parameters, parameter_types.Length);
  443. }
  444. #endif
  445. }
  446. }