MethodBuilder.cs 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569
  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. [ComDefaultInterface (typeof (_MethodBuilder))]
  44. #endif
  45. [ClassInterface (ClassInterfaceType.None)]
  46. public sealed class MethodBuilder : MethodInfo, _MethodBuilder {
  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 ArgumentOutOfRangeException ("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 NET_2_0
  248. // do not allow zero length method body on MS.NET 2.0 (and higher)
  249. if (((ilgen == null) || (ILGenerator.Mono_GetCurrentOffset (ilgen) == 0)) && (code == null || code.Length == 0))
  250. #else
  251. if (((ilgen == null) || (ILGenerator.Mono_GetCurrentOffset (ilgen) == 0)) && (code == null))
  252. #endif
  253. throw new InvalidOperationException ("Method '" + Name + "' does not have a method body.");
  254. }
  255. if (ilgen != null)
  256. ilgen.label_fixup ();
  257. }
  258. internal void GenerateDebugInfo (ISymbolWriter symbolWriter)
  259. {
  260. if (ilgen != null && ilgen.HasDebugInfo) {
  261. SymbolToken token = new SymbolToken (GetToken().Token);
  262. symbolWriter.OpenMethod (token);
  263. symbolWriter.SetSymAttribute (token, "__name", System.Text.Encoding.UTF8.GetBytes (Name));
  264. ilgen.GenerateDebugInfo (symbolWriter);
  265. symbolWriter.CloseMethod ();
  266. }
  267. }
  268. public void SetCustomAttribute( CustomAttributeBuilder customBuilder) {
  269. if (customBuilder == null)
  270. throw new ArgumentNullException ("customBuilder");
  271. string attrname = customBuilder.Ctor.ReflectedType.FullName;
  272. if (attrname == "System.Runtime.CompilerServices.MethodImplAttribute") {
  273. byte[] data = customBuilder.Data;
  274. int impla; // the (stupid) ctor takes a short or an int ...
  275. impla = (int)data [2];
  276. impla |= ((int)data [3]) << 8;
  277. SetImplementationFlags ((MethodImplAttributes)impla);
  278. return;
  279. }
  280. if (attrname == "System.Runtime.InteropServices.DllImportAttribute") {
  281. CustomAttributeBuilder.CustomAttributeInfo attr = CustomAttributeBuilder.decode_cattr (customBuilder);
  282. bool preserveSig = true;
  283. /*
  284. * It would be easier to construct a DllImportAttribute from
  285. * the custom attribute builder, but the DllImportAttribute
  286. * does not contain all the information required here, ie.
  287. * - some parameters, like BestFitMapping has three values
  288. * ("on", "off", "missing"), but DllImportAttribute only
  289. * contains two (on/off).
  290. * - PreserveSig is true by default, while it is false by
  291. * default in DllImportAttribute.
  292. */
  293. pi_dll = (string)attr.ctorArgs [0];
  294. native_cc = System.Runtime.InteropServices.CallingConvention.Winapi;
  295. for (int i = 0; i < attr.namedParamNames.Length; ++i) {
  296. string name = attr.namedParamNames [i];
  297. object value = attr.namedParamValues [i];
  298. if (name == "CallingConvention")
  299. native_cc = (CallingConvention)value;
  300. else if (name == "CharSet")
  301. charset = (CharSet)value;
  302. else if (name == "EntryPoint")
  303. pi_entry = (string)value;
  304. else if (name == "ExactSpelling")
  305. ExactSpelling = (bool)value;
  306. else if (name == "SetLastError")
  307. SetLastError = (bool)value;
  308. else if (name == "PreserveSig")
  309. preserveSig = (bool)value;
  310. #if NET_1_1
  311. else if (name == "BestFitMapping")
  312. BestFitMapping = (bool)value;
  313. else if (name == "ThrowOnUnmappableChar")
  314. ThrowOnUnmappableChar = (bool)value;
  315. #endif
  316. }
  317. attrs |= MethodAttributes.PinvokeImpl;
  318. if (preserveSig)
  319. iattrs |= MethodImplAttributes.PreserveSig;
  320. return;
  321. }
  322. if (cattrs != null) {
  323. CustomAttributeBuilder[] new_array = new CustomAttributeBuilder [cattrs.Length + 1];
  324. cattrs.CopyTo (new_array, 0);
  325. new_array [cattrs.Length] = customBuilder;
  326. cattrs = new_array;
  327. } else {
  328. cattrs = new CustomAttributeBuilder [1];
  329. cattrs [0] = customBuilder;
  330. }
  331. }
  332. #if NET_2_0
  333. [ComVisible (true)]
  334. #endif
  335. public void SetCustomAttribute( ConstructorInfo con, byte[] binaryAttribute) {
  336. if (con == null)
  337. throw new ArgumentNullException ("con");
  338. if (binaryAttribute == null)
  339. throw new ArgumentNullException ("binaryAttribute");
  340. SetCustomAttribute (new CustomAttributeBuilder (con, binaryAttribute));
  341. }
  342. public void SetImplementationFlags( MethodImplAttributes attributes) {
  343. RejectIfCreated ();
  344. iattrs = attributes;
  345. }
  346. public void AddDeclarativeSecurity( SecurityAction action, PermissionSet pset) {
  347. if (pset == null)
  348. throw new ArgumentNullException ("pset");
  349. if ((action == SecurityAction.RequestMinimum) ||
  350. (action == SecurityAction.RequestOptional) ||
  351. (action == SecurityAction.RequestRefuse))
  352. throw new ArgumentException ("Request* values are not permitted", "action");
  353. RejectIfCreated ();
  354. if (permissions != null) {
  355. /* Check duplicate actions */
  356. foreach (RefEmitPermissionSet set in permissions)
  357. if (set.action == action)
  358. throw new InvalidOperationException ("Multiple permission sets specified with the same SecurityAction.");
  359. RefEmitPermissionSet[] new_array = new RefEmitPermissionSet [permissions.Length + 1];
  360. permissions.CopyTo (new_array, 0);
  361. permissions = new_array;
  362. }
  363. else
  364. permissions = new RefEmitPermissionSet [1];
  365. permissions [permissions.Length - 1] = new RefEmitPermissionSet (action, pset.ToXml ().ToString ());
  366. attrs |= MethodAttributes.HasSecurity;
  367. }
  368. #if NET_2_0
  369. [Obsolete ("An alternate API is available: Emit the MarshalAs custom attribute instead.")]
  370. #endif
  371. public void SetMarshal (UnmanagedMarshal unmanagedMarshal)
  372. {
  373. RejectIfCreated ();
  374. throw new NotImplementedException ();
  375. }
  376. [MonoTODO]
  377. public void SetSymCustomAttribute (string name, byte[] data)
  378. {
  379. RejectIfCreated ();
  380. throw new NotImplementedException ();
  381. }
  382. public override string ToString()
  383. {
  384. return "MethodBuilder [" + type.Name + "::" + name + "]";
  385. }
  386. [MonoTODO]
  387. public override bool Equals (object obj)
  388. {
  389. return base.Equals (obj);
  390. }
  391. public override int GetHashCode ()
  392. {
  393. return name.GetHashCode ();
  394. }
  395. internal override int get_next_table_index (object obj, int table, bool inc) {
  396. return type.get_next_table_index (obj, table, inc);
  397. }
  398. internal void set_override (MethodInfo mdecl) {
  399. override_method = mdecl;
  400. }
  401. private void RejectIfCreated () {
  402. if (type.is_created)
  403. throw new InvalidOperationException ("Type definition of the method is complete.");
  404. }
  405. private Exception NotSupported () {
  406. return new NotSupportedException ("The invoked member is not supported in a dynamic module.");
  407. }
  408. #if NET_2_0 || BOOTSTRAP_NET_2_0
  409. [MethodImplAttribute(MethodImplOptions.InternalCall)]
  410. public override extern MethodInfo MakeGenericMethod (Type [] types);
  411. public override bool Mono_IsInflatedMethod {
  412. get {
  413. return false;
  414. }
  415. }
  416. public override bool HasGenericParameters {
  417. get {
  418. return generic_params != null;
  419. }
  420. }
  421. public override Type[] GetGenericArguments ()
  422. {
  423. if (generic_params == null)
  424. return new Type [0];
  425. Type[] result = new Type [generic_params.Length];
  426. for (int i = 0; i < generic_params.Length; i++)
  427. result [i] = generic_params [i];
  428. return result;
  429. }
  430. public GenericTypeParameterBuilder[] DefineGenericParameters (params string[] names)
  431. {
  432. generic_params = new GenericTypeParameterBuilder [names.Length];
  433. for (int i = 0; i < names.Length; i++)
  434. generic_params [i] = new GenericTypeParameterBuilder (
  435. type, this, names [i], i);
  436. return generic_params;
  437. }
  438. public void SetGenericMethodSignature (MethodAttributes attributes, CallingConventions callingConvention, Type return_type, Type[] parameter_types)
  439. {
  440. RejectIfCreated ();
  441. this.attrs = attributes;
  442. this.call_conv = callingConvention;
  443. if ((attributes & MethodAttributes.Static) == 0)
  444. this.call_conv |= CallingConventions.HasThis;
  445. this.rtype = return_type;
  446. this.parameters = new Type [parameter_types.Length];
  447. System.Array.Copy (parameter_types, this.parameters, parameter_types.Length);
  448. }
  449. public void SetReturnType (Type returnType)
  450. {
  451. rtype = returnType;
  452. }
  453. public void SetParameters (params Type[] parameterTypes)
  454. {
  455. if (parameterTypes != null) {
  456. for (int i = 0; i < parameterTypes.Length; ++i)
  457. if (parameterTypes [i] == null)
  458. throw new ArgumentException ("Elements of the parameterTypes array cannot be null", "parameterTypes");
  459. this.parameters = new Type [parameterTypes.Length];
  460. System.Array.Copy (parameterTypes, this.parameters, parameterTypes.Length);
  461. }
  462. }
  463. public void SetSignature (Type returnType, Type[] returnTypeRequiredCustomModifiers, Type[] returnTypeOptionalCustomModifiers, Type[] parameterTypes, Type[][] parameterTypeRequiredCustomModifiers, Type[][] parameterTypeOptionalCustomModifiers) {
  464. SetReturnType (returnType);
  465. SetParameters (parameterTypes);
  466. this.returnModReq = returnTypeRequiredCustomModifiers;
  467. this.returnModOpt = returnTypeOptionalCustomModifiers;
  468. this.paramModReq = parameterTypeRequiredCustomModifiers;
  469. this.paramModOpt = parameterTypeOptionalCustomModifiers;
  470. }
  471. public override Module Module {
  472. get {
  473. return base.Module;
  474. }
  475. }
  476. #endif
  477. void _MethodBuilder.GetIDsOfNames([In] ref Guid riid, IntPtr rgszNames, uint cNames, uint lcid, IntPtr rgDispId)
  478. {
  479. throw new NotImplementedException ();
  480. }
  481. void _MethodBuilder.GetTypeInfo (uint iTInfo, uint lcid, IntPtr ppTInfo)
  482. {
  483. throw new NotImplementedException ();
  484. }
  485. void _MethodBuilder.GetTypeInfoCount (out uint pcTInfo)
  486. {
  487. throw new NotImplementedException ();
  488. }
  489. void _MethodBuilder.Invoke (uint dispIdMember, [In] ref Guid riid, uint lcid, short wFlags, IntPtr pDispParams, IntPtr pVarResult, IntPtr pExcepInfo, IntPtr puArgErr)
  490. {
  491. throw new NotImplementedException ();
  492. }
  493. }
  494. }