MethodBuilder.cs 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575
  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. #if NET_2_0
  318. if (attrname == "System.Runtime.CompilerServices.SpecialNameAttribute") {
  319. attrs |= MethodAttributes.SpecialName;
  320. return;
  321. }
  322. #endif
  323. attrs |= MethodAttributes.PinvokeImpl;
  324. if (preserveSig)
  325. iattrs |= MethodImplAttributes.PreserveSig;
  326. return;
  327. }
  328. if (cattrs != null) {
  329. CustomAttributeBuilder[] new_array = new CustomAttributeBuilder [cattrs.Length + 1];
  330. cattrs.CopyTo (new_array, 0);
  331. new_array [cattrs.Length] = customBuilder;
  332. cattrs = new_array;
  333. } else {
  334. cattrs = new CustomAttributeBuilder [1];
  335. cattrs [0] = customBuilder;
  336. }
  337. }
  338. #if NET_2_0
  339. [ComVisible (true)]
  340. #endif
  341. public void SetCustomAttribute( ConstructorInfo con, byte[] binaryAttribute) {
  342. if (con == null)
  343. throw new ArgumentNullException ("con");
  344. if (binaryAttribute == null)
  345. throw new ArgumentNullException ("binaryAttribute");
  346. SetCustomAttribute (new CustomAttributeBuilder (con, binaryAttribute));
  347. }
  348. public void SetImplementationFlags( MethodImplAttributes attributes) {
  349. RejectIfCreated ();
  350. iattrs = attributes;
  351. }
  352. public void AddDeclarativeSecurity( SecurityAction action, PermissionSet pset) {
  353. if (pset == null)
  354. throw new ArgumentNullException ("pset");
  355. if ((action == SecurityAction.RequestMinimum) ||
  356. (action == SecurityAction.RequestOptional) ||
  357. (action == SecurityAction.RequestRefuse))
  358. throw new ArgumentException ("Request* values are not permitted", "action");
  359. RejectIfCreated ();
  360. if (permissions != null) {
  361. /* Check duplicate actions */
  362. foreach (RefEmitPermissionSet set in permissions)
  363. if (set.action == action)
  364. throw new InvalidOperationException ("Multiple permission sets specified with the same SecurityAction.");
  365. RefEmitPermissionSet[] new_array = new RefEmitPermissionSet [permissions.Length + 1];
  366. permissions.CopyTo (new_array, 0);
  367. permissions = new_array;
  368. }
  369. else
  370. permissions = new RefEmitPermissionSet [1];
  371. permissions [permissions.Length - 1] = new RefEmitPermissionSet (action, pset.ToXml ().ToString ());
  372. attrs |= MethodAttributes.HasSecurity;
  373. }
  374. #if NET_2_0
  375. [Obsolete ("An alternate API is available: Emit the MarshalAs custom attribute instead.")]
  376. #endif
  377. public void SetMarshal (UnmanagedMarshal unmanagedMarshal)
  378. {
  379. RejectIfCreated ();
  380. throw new NotImplementedException ();
  381. }
  382. [MonoTODO]
  383. public void SetSymCustomAttribute (string name, byte[] data)
  384. {
  385. RejectIfCreated ();
  386. throw new NotImplementedException ();
  387. }
  388. public override string ToString()
  389. {
  390. return "MethodBuilder [" + type.Name + "::" + name + "]";
  391. }
  392. [MonoTODO]
  393. public override bool Equals (object obj)
  394. {
  395. return base.Equals (obj);
  396. }
  397. public override int GetHashCode ()
  398. {
  399. return name.GetHashCode ();
  400. }
  401. internal override int get_next_table_index (object obj, int table, bool inc) {
  402. return type.get_next_table_index (obj, table, inc);
  403. }
  404. internal void set_override (MethodInfo mdecl) {
  405. override_method = mdecl;
  406. }
  407. private void RejectIfCreated () {
  408. if (type.is_created)
  409. throw new InvalidOperationException ("Type definition of the method is complete.");
  410. }
  411. private Exception NotSupported () {
  412. return new NotSupportedException ("The invoked member is not supported in a dynamic module.");
  413. }
  414. #if NET_2_0 || BOOTSTRAP_NET_2_0
  415. [MethodImplAttribute(MethodImplOptions.InternalCall)]
  416. public override extern MethodInfo MakeGenericMethod (Type [] types);
  417. public override bool Mono_IsInflatedMethod {
  418. get {
  419. return false;
  420. }
  421. }
  422. public override bool HasGenericParameters {
  423. get {
  424. return generic_params != null;
  425. }
  426. }
  427. public override Type[] GetGenericArguments ()
  428. {
  429. if (generic_params == null)
  430. return new Type [0];
  431. Type[] result = new Type [generic_params.Length];
  432. for (int i = 0; i < generic_params.Length; i++)
  433. result [i] = generic_params [i];
  434. return result;
  435. }
  436. public GenericTypeParameterBuilder[] DefineGenericParameters (params string[] names)
  437. {
  438. generic_params = new GenericTypeParameterBuilder [names.Length];
  439. for (int i = 0; i < names.Length; i++)
  440. generic_params [i] = new GenericTypeParameterBuilder (
  441. type, this, names [i], i);
  442. return generic_params;
  443. }
  444. public void SetGenericMethodSignature (MethodAttributes attributes, CallingConventions callingConvention, Type return_type, Type[] parameter_types)
  445. {
  446. RejectIfCreated ();
  447. this.attrs = attributes;
  448. this.call_conv = callingConvention;
  449. if ((attributes & MethodAttributes.Static) == 0)
  450. this.call_conv |= CallingConventions.HasThis;
  451. this.rtype = return_type;
  452. this.parameters = new Type [parameter_types.Length];
  453. System.Array.Copy (parameter_types, this.parameters, parameter_types.Length);
  454. }
  455. public void SetReturnType (Type returnType)
  456. {
  457. rtype = returnType;
  458. }
  459. public void SetParameters (params Type[] parameterTypes)
  460. {
  461. if (parameterTypes != null) {
  462. for (int i = 0; i < parameterTypes.Length; ++i)
  463. if (parameterTypes [i] == null)
  464. throw new ArgumentException ("Elements of the parameterTypes array cannot be null", "parameterTypes");
  465. this.parameters = new Type [parameterTypes.Length];
  466. System.Array.Copy (parameterTypes, this.parameters, parameterTypes.Length);
  467. }
  468. }
  469. public void SetSignature (Type returnType, Type[] returnTypeRequiredCustomModifiers, Type[] returnTypeOptionalCustomModifiers, Type[] parameterTypes, Type[][] parameterTypeRequiredCustomModifiers, Type[][] parameterTypeOptionalCustomModifiers) {
  470. SetReturnType (returnType);
  471. SetParameters (parameterTypes);
  472. this.returnModReq = returnTypeRequiredCustomModifiers;
  473. this.returnModOpt = returnTypeOptionalCustomModifiers;
  474. this.paramModReq = parameterTypeRequiredCustomModifiers;
  475. this.paramModOpt = parameterTypeOptionalCustomModifiers;
  476. }
  477. public override Module Module {
  478. get {
  479. return base.Module;
  480. }
  481. }
  482. #endif
  483. void _MethodBuilder.GetIDsOfNames([In] ref Guid riid, IntPtr rgszNames, uint cNames, uint lcid, IntPtr rgDispId)
  484. {
  485. throw new NotImplementedException ();
  486. }
  487. void _MethodBuilder.GetTypeInfo (uint iTInfo, uint lcid, IntPtr ppTInfo)
  488. {
  489. throw new NotImplementedException ();
  490. }
  491. void _MethodBuilder.GetTypeInfoCount (out uint pcTInfo)
  492. {
  493. throw new NotImplementedException ();
  494. }
  495. void _MethodBuilder.Invoke (uint dispIdMember, [In] ref Guid riid, uint lcid, short wFlags, IntPtr pDispParams, IntPtr pVarResult, IntPtr pExcepInfo, IntPtr puArgErr)
  496. {
  497. throw new NotImplementedException ();
  498. }
  499. }
  500. }