ModuleBuilder.cs 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734
  1. //
  2. // Copyright (C) 2004 Novell, Inc (http://www.novell.com)
  3. //
  4. // Permission is hereby granted, free of charge, to any person obtaining
  5. // a copy of this software and associated documentation files (the
  6. // "Software"), to deal in the Software without restriction, including
  7. // without limitation the rights to use, copy, modify, merge, publish,
  8. // distribute, sublicense, and/or sell copies of the Software, and to
  9. // permit persons to whom the Software is furnished to do so, subject to
  10. // the following conditions:
  11. //
  12. // The above copyright notice and this permission notice shall be
  13. // included in all copies or substantial portions of the Software.
  14. //
  15. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
  16. // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
  17. // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
  18. // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
  19. // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
  20. // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
  21. // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
  22. //
  23. //
  24. // System.Reflection.Emit/ModuleBuilder.cs
  25. //
  26. // Author:
  27. // Paolo Molaro ([email protected])
  28. //
  29. // (C) 2001 Ximian, Inc. http://www.ximian.com
  30. //
  31. using System;
  32. using System.Reflection;
  33. using System.Collections;
  34. using System.Runtime.CompilerServices;
  35. using System.Runtime.InteropServices;
  36. using System.Diagnostics.SymbolStore;
  37. using System.IO;
  38. using System.Resources;
  39. using System.Globalization;
  40. namespace System.Reflection.Emit {
  41. #if NET_2_0
  42. [ComVisible (true)]
  43. [ClassInterfaceAttribute (ClassInterfaceType.None)]
  44. [ComDefaultInterfaceAttribute (typeof (_ModuleBuilder))]
  45. #endif
  46. public class ModuleBuilder : Module {
  47. #region Sync with reflection.h
  48. private IntPtr dynamic_image;
  49. private int num_types;
  50. private TypeBuilder[] types;
  51. private CustomAttributeBuilder[] cattrs;
  52. private byte[] guid;
  53. private int table_idx;
  54. internal AssemblyBuilder assemblyb;
  55. private MethodBuilder[] global_methods;
  56. private FieldBuilder[] global_fields;
  57. bool is_main;
  58. private MonoResource[] resources;
  59. #endregion
  60. private TypeBuilder global_type;
  61. private Type global_type_created;
  62. Hashtable name_cache;
  63. Hashtable us_string_cache = new Hashtable ();
  64. private int[] table_indexes;
  65. bool transient;
  66. ModuleBuilderTokenGenerator token_gen;
  67. ArrayList resource_writers = null;
  68. ISymbolWriter symbolWriter;
  69. [MethodImplAttribute(MethodImplOptions.InternalCall)]
  70. private static extern void basic_init (ModuleBuilder ab);
  71. internal ModuleBuilder (AssemblyBuilder assb, string name, string fullyqname, bool emitSymbolInfo, bool transient) {
  72. this.name = this.scopename = name;
  73. this.fqname = fullyqname;
  74. this.assembly = this.assemblyb = assb;
  75. this.transient = transient;
  76. // to keep mcs fast we do not want CryptoConfig wo be involved to create the RNG
  77. guid = Guid.FastNewGuidArray ();
  78. // guid = Guid.NewGuid().ToByteArray ();
  79. table_idx = get_next_table_index (this, 0x00, true);
  80. name_cache = new Hashtable ();
  81. basic_init (this);
  82. CreateGlobalType ();
  83. if (emitSymbolInfo) {
  84. Assembly asm = Assembly.LoadWithPartialName ("Mono.CompilerServices.SymbolWriter");
  85. Type t = asm.GetType ("Mono.CompilerServices.SymbolWriter.SymbolWriterImpl");
  86. if (t != null) {
  87. symbolWriter = (ISymbolWriter) Activator.CreateInstance (t, new object[] { this });
  88. string fileName = fqname;
  89. if (assemblyb.AssemblyDir != null)
  90. fileName = Path.Combine (assemblyb.AssemblyDir, fileName);
  91. symbolWriter.Initialize (IntPtr.Zero, fileName, true);
  92. }
  93. }
  94. }
  95. public override string FullyQualifiedName {get { return fqname;}}
  96. public bool IsTransient () {
  97. return transient;
  98. }
  99. public void CreateGlobalFunctions ()
  100. {
  101. if (global_type_created != null)
  102. throw new InvalidOperationException ("global methods already created");
  103. if (global_type != null)
  104. global_type_created = global_type.CreateType ();
  105. }
  106. public FieldBuilder DefineInitializedData( string name, byte[] data, FieldAttributes attributes) {
  107. if (data == null)
  108. throw new ArgumentNullException ("data");
  109. FieldBuilder fb = DefineUninitializedData (name, data.Length,
  110. attributes | FieldAttributes.HasFieldRVA);
  111. fb.SetRVAData (data);
  112. return fb;
  113. }
  114. public FieldBuilder DefineUninitializedData( string name, int size, FieldAttributes attributes) {
  115. if (name == null)
  116. throw new ArgumentNullException ("name");
  117. if (global_type_created != null)
  118. throw new InvalidOperationException ("global fields already created");
  119. if (global_type == null)
  120. global_type = new TypeBuilder (this, 0);
  121. string typeName = "$ArrayType$" + size;
  122. Type datablobtype = GetType (typeName, false, false);
  123. if (datablobtype == null) {
  124. TypeBuilder tb = DefineType (typeName,
  125. TypeAttributes.Public|TypeAttributes.ExplicitLayout|TypeAttributes.Sealed,
  126. assemblyb.corlib_value_type, null, PackingSize.Size1, size);
  127. tb.CreateType ();
  128. datablobtype = tb;
  129. }
  130. FieldBuilder fb = global_type.DefineField (name, datablobtype, attributes|FieldAttributes.Static);
  131. if (global_fields != null) {
  132. FieldBuilder[] new_fields = new FieldBuilder [global_fields.Length+1];
  133. System.Array.Copy (global_fields, new_fields, global_fields.Length);
  134. new_fields [global_fields.Length] = fb;
  135. global_fields = new_fields;
  136. } else {
  137. global_fields = new FieldBuilder [1];
  138. global_fields [0] = fb;
  139. }
  140. return fb;
  141. }
  142. private void addGlobalMethod (MethodBuilder mb) {
  143. if (global_methods != null) {
  144. MethodBuilder[] new_methods = new MethodBuilder [global_methods.Length+1];
  145. System.Array.Copy (global_methods, new_methods, global_methods.Length);
  146. new_methods [global_methods.Length] = mb;
  147. global_methods = new_methods;
  148. } else {
  149. global_methods = new MethodBuilder [1];
  150. global_methods [0] = mb;
  151. }
  152. }
  153. public MethodBuilder DefineGlobalMethod (string name, MethodAttributes attributes, Type returnType, Type[] parameterTypes)
  154. {
  155. return DefineGlobalMethod (name, attributes, CallingConventions.Standard, returnType, parameterTypes);
  156. }
  157. public MethodBuilder DefineGlobalMethod (string name, MethodAttributes attributes, CallingConventions callingConvention, Type returnType, Type[] parameterTypes) {
  158. return DefineGlobalMethod (name, attributes, callingConvention, returnType, null, null, parameterTypes, null, null);
  159. }
  160. #if NET_2_0 || BOOTSTRAP_NET_2_0
  161. public
  162. #else
  163. internal
  164. #endif
  165. MethodBuilder DefineGlobalMethod (string name, MethodAttributes attributes, CallingConventions callingConvention, Type returnType, Type[] requiredReturnTypeCustomModifiers, Type[] optionalReturnTypeCustomModifiers, Type[] parameterTypes, Type[][] requiredParameterTypeCustomModifiers, Type[][] optionalParameterTypeCustomModifiers)
  166. {
  167. if (name == null)
  168. throw new ArgumentNullException ("name");
  169. if ((attributes & MethodAttributes.Static) == 0)
  170. throw new ArgumentException ("global methods must be static");
  171. if (global_type_created != null)
  172. throw new InvalidOperationException ("global methods already created");
  173. if (global_type == null)
  174. global_type = new TypeBuilder (this, 0);
  175. MethodBuilder mb = global_type.DefineMethod (name, attributes, callingConvention, returnType, requiredReturnTypeCustomModifiers, optionalReturnTypeCustomModifiers, parameterTypes, requiredParameterTypeCustomModifiers, optionalParameterTypeCustomModifiers);
  176. addGlobalMethod (mb);
  177. return mb;
  178. }
  179. public MethodBuilder DefinePInvokeMethod (string name, string dllName, MethodAttributes attributes, CallingConventions callingConvention, Type returnType, Type[] parameterTypes, CallingConvention nativeCallConv, CharSet nativeCharSet) {
  180. return DefinePInvokeMethod (name, dllName, name, attributes, callingConvention, returnType, parameterTypes, nativeCallConv, nativeCharSet);
  181. }
  182. public MethodBuilder DefinePInvokeMethod (string name, string dllName, string entryName, MethodAttributes attributes, CallingConventions callingConvention, Type returnType, Type[] parameterTypes, CallingConvention nativeCallConv, CharSet nativeCharSet) {
  183. if (name == null)
  184. throw new ArgumentNullException ("name");
  185. if ((attributes & MethodAttributes.Static) == 0)
  186. throw new ArgumentException ("global methods must be static");
  187. if (global_type_created != null)
  188. throw new InvalidOperationException ("global methods already created");
  189. if (global_type == null)
  190. global_type = new TypeBuilder (this, 0);
  191. MethodBuilder mb = global_type.DefinePInvokeMethod (name, dllName, entryName, attributes, callingConvention, returnType, parameterTypes, nativeCallConv, nativeCharSet);
  192. addGlobalMethod (mb);
  193. return mb;
  194. }
  195. public TypeBuilder DefineType (string name) {
  196. return DefineType (name, 0);
  197. }
  198. public TypeBuilder DefineType (string name, TypeAttributes attr) {
  199. if ((attr & TypeAttributes.Interface) != 0)
  200. return DefineType (name, attr, null, null);
  201. return DefineType (name, attr, typeof(object), null);
  202. }
  203. public TypeBuilder DefineType (string name, TypeAttributes attr, Type parent) {
  204. return DefineType (name, attr, parent, null);
  205. }
  206. private void AddType (TypeBuilder tb)
  207. {
  208. if (types != null) {
  209. if (types.Length == num_types) {
  210. TypeBuilder[] new_types = new TypeBuilder [types.Length * 2];
  211. System.Array.Copy (types, new_types, num_types);
  212. types = new_types;
  213. }
  214. } else {
  215. types = new TypeBuilder [1];
  216. }
  217. types [num_types] = tb;
  218. num_types ++;
  219. }
  220. private TypeBuilder DefineType (string name, TypeAttributes attr, Type parent, Type[] interfaces, PackingSize packsize, int typesize) {
  221. if (name_cache.Contains (name))
  222. throw new ArgumentException ("Duplicate type name within an assembly.");
  223. TypeBuilder res = new TypeBuilder (this, name, attr, parent, interfaces, packsize, typesize, null);
  224. AddType (res);
  225. name_cache.Add (name, res);
  226. return res;
  227. }
  228. internal void RegisterTypeName (TypeBuilder tb, string name) {
  229. name_cache.Add (name, tb);
  230. }
  231. #if NET_2_0
  232. [ComVisible (true)]
  233. #endif
  234. public TypeBuilder DefineType (string name, TypeAttributes attr, Type parent, Type[] interfaces) {
  235. return DefineType (name, attr, parent, interfaces, PackingSize.Unspecified, TypeBuilder.UnspecifiedTypeSize);
  236. }
  237. public TypeBuilder DefineType (string name, TypeAttributes attr, Type parent, int typesize) {
  238. return DefineType (name, attr, parent, null, PackingSize.Unspecified, TypeBuilder.UnspecifiedTypeSize);
  239. }
  240. public TypeBuilder DefineType (string name, TypeAttributes attr, Type parent, PackingSize packsize) {
  241. return DefineType (name, attr, parent, null, packsize, TypeBuilder.UnspecifiedTypeSize);
  242. }
  243. public TypeBuilder DefineType (string name, TypeAttributes attr, Type parent, PackingSize packsize, int typesize) {
  244. return DefineType (name, attr, parent, null, packsize, typesize);
  245. }
  246. public MethodInfo GetArrayMethod( Type arrayClass, string methodName, CallingConventions callingConvention, Type returnType, Type[] parameterTypes) {
  247. return new MonoArrayMethod (arrayClass, methodName, callingConvention, returnType, parameterTypes);
  248. }
  249. public EnumBuilder DefineEnum( string name, TypeAttributes visibility, Type underlyingType) {
  250. if (name_cache.Contains (name))
  251. throw new ArgumentException ("Duplicate type name within an assembly.");
  252. EnumBuilder eb = new EnumBuilder (this, name, visibility, underlyingType);
  253. TypeBuilder res = eb.GetTypeBuilder ();
  254. AddType (res);
  255. name_cache.Add (name, res);
  256. return eb;
  257. }
  258. #if NET_2_0
  259. [ComVisible (true)]
  260. #endif
  261. public override Type GetType( string className) {
  262. return GetType (className, false, false);
  263. }
  264. #if NET_2_0
  265. [ComVisible (true)]
  266. #endif
  267. public override Type GetType( string className, bool ignoreCase) {
  268. return GetType (className, false, ignoreCase);
  269. }
  270. private TypeBuilder search_in_array (TypeBuilder[] arr, int validElementsInArray, string className) {
  271. int i;
  272. for (i = 0; i < validElementsInArray; ++i) {
  273. if (String.Compare (className, arr [i].FullName, true, CultureInfo.InvariantCulture) == 0) {
  274. return arr [i];
  275. }
  276. }
  277. return null;
  278. }
  279. private TypeBuilder search_nested_in_array (TypeBuilder[] arr, int validElementsInArray, string className) {
  280. int i;
  281. for (i = 0; i < validElementsInArray; ++i) {
  282. if (String.Compare (className, arr [i].Name, true, CultureInfo.InvariantCulture) == 0)
  283. return arr [i];
  284. }
  285. return null;
  286. }
  287. [MethodImplAttribute(MethodImplOptions.InternalCall)]
  288. private static extern Type create_modified_type (TypeBuilder tb, string modifiers);
  289. static readonly char [] type_modifiers = {'&', '[', '*'};
  290. private TypeBuilder GetMaybeNested (TypeBuilder t, string className) {
  291. int subt;
  292. string pname, rname;
  293. subt = className.IndexOf ('+');
  294. if (subt < 0) {
  295. if (t.subtypes != null)
  296. return search_nested_in_array (t.subtypes, t.subtypes.Length, className);
  297. return null;
  298. }
  299. if (t.subtypes != null) {
  300. pname = className.Substring (0, subt);
  301. rname = className.Substring (subt + 1);
  302. TypeBuilder result = search_nested_in_array (t.subtypes, t.subtypes.Length, pname);
  303. if (result != null)
  304. return GetMaybeNested (result, rname);
  305. }
  306. return null;
  307. }
  308. #if NET_2_0
  309. [ComVisible (true)]
  310. #endif
  311. public override Type GetType (string className, bool throwOnError, bool ignoreCase) {
  312. int subt;
  313. string orig = className;
  314. string modifiers;
  315. TypeBuilder result = null;
  316. if (types == null && throwOnError)
  317. throw new TypeLoadException (className);
  318. subt = className.IndexOfAny (type_modifiers);
  319. if (subt >= 0) {
  320. modifiers = className.Substring (subt);
  321. className = className.Substring (0, subt);
  322. } else
  323. modifiers = null;
  324. if (!ignoreCase) {
  325. result = name_cache [className] as TypeBuilder;
  326. } else {
  327. subt = className.IndexOf ('+');
  328. if (subt < 0) {
  329. if (types != null)
  330. result = search_in_array (types, num_types, className);
  331. } else {
  332. string pname, rname;
  333. pname = className.Substring (0, subt);
  334. rname = className.Substring (subt + 1);
  335. result = search_in_array (types, num_types, pname);
  336. if (result != null)
  337. result = GetMaybeNested (result, rname);
  338. }
  339. }
  340. if ((result == null) && throwOnError)
  341. throw new TypeLoadException (orig);
  342. if (result != null && (modifiers != null))
  343. return create_modified_type (result, modifiers);
  344. return result;
  345. }
  346. internal int get_next_table_index (object obj, int table, bool inc) {
  347. if (table_indexes == null) {
  348. table_indexes = new int [64];
  349. for (int i=0; i < 64; ++i)
  350. table_indexes [i] = 1;
  351. /* allow room for .<Module> in TypeDef table */
  352. table_indexes [0x02] = 2;
  353. }
  354. // Console.WriteLine ("getindex for table "+table.ToString()+" got "+table_indexes [table].ToString());
  355. if (inc)
  356. return table_indexes [table]++;
  357. return table_indexes [table];
  358. }
  359. public void SetCustomAttribute( CustomAttributeBuilder customBuilder) {
  360. if (cattrs != null) {
  361. CustomAttributeBuilder[] new_array = new CustomAttributeBuilder [cattrs.Length + 1];
  362. cattrs.CopyTo (new_array, 0);
  363. new_array [cattrs.Length] = customBuilder;
  364. cattrs = new_array;
  365. } else {
  366. cattrs = new CustomAttributeBuilder [1];
  367. cattrs [0] = customBuilder;
  368. }
  369. }
  370. #if NET_2_0
  371. [ComVisible (true)]
  372. #endif
  373. public void SetCustomAttribute( ConstructorInfo con, byte[] binaryAttribute) {
  374. SetCustomAttribute (new CustomAttributeBuilder (con, binaryAttribute));
  375. }
  376. public ISymbolWriter GetSymWriter () {
  377. return symbolWriter;
  378. }
  379. public ISymbolDocumentWriter DefineDocument (string url, Guid language, Guid languageVendor, Guid documentType)
  380. {
  381. if (symbolWriter != null)
  382. return symbolWriter.DefineDocument (url, language, languageVendor, documentType);
  383. else
  384. return null;
  385. }
  386. public override Type [] GetTypes ()
  387. {
  388. if (types == null)
  389. return new TypeBuilder [0];
  390. int n = num_types;
  391. TypeBuilder [] copy = new TypeBuilder [n];
  392. Array.Copy (types, copy, n);
  393. return copy;
  394. }
  395. public IResourceWriter DefineResource (string name, string description, ResourceAttributes attribute)
  396. {
  397. if (name == null)
  398. throw new ArgumentNullException ("name");
  399. if (name == String.Empty)
  400. throw new ArgumentException ("name cannot be empty");
  401. if (transient)
  402. throw new InvalidOperationException ("The module is transient");
  403. if (!assemblyb.IsSave)
  404. throw new InvalidOperationException ("The assembly is transient");
  405. ResourceWriter writer = new ResourceWriter (new MemoryStream ());
  406. if (resource_writers == null)
  407. resource_writers = new ArrayList ();
  408. resource_writers.Add (writer);
  409. // The data is filled out later
  410. if (resources != null) {
  411. MonoResource[] new_r = new MonoResource [resources.Length + 1];
  412. System.Array.Copy(resources, new_r, resources.Length);
  413. resources = new_r;
  414. } else {
  415. resources = new MonoResource [1];
  416. }
  417. int p = resources.Length - 1;
  418. resources [p].name = name;
  419. resources [p].attrs = attribute;
  420. return writer;
  421. }
  422. public IResourceWriter DefineResource (string name, string description)
  423. {
  424. return DefineResource (name, description, ResourceAttributes.Public);
  425. }
  426. [MonoTODO]
  427. public void DefineUnmanagedResource (byte[] resource)
  428. {
  429. if (resource == null)
  430. throw new ArgumentNullException ("resource");
  431. throw new NotImplementedException ();
  432. }
  433. [MonoTODO]
  434. public void DefineUnmanagedResource (string resourceFileName)
  435. {
  436. if (resourceFileName == null)
  437. throw new ArgumentNullException ("resourceFileName");
  438. if (resourceFileName == String.Empty)
  439. throw new ArgumentException ("resourceFileName");
  440. if (!File.Exists (resourceFileName) || Directory.Exists (resourceFileName))
  441. throw new FileNotFoundException ("File '" + resourceFileName + "' does not exists or is a directory.");
  442. throw new NotImplementedException ();
  443. }
  444. [MonoTODO]
  445. public void SetSymCustomAttribute (string name, byte[] data)
  446. {
  447. throw new NotImplementedException ();
  448. }
  449. [MonoTODO]
  450. public void SetUserEntryPoint (MethodInfo entryPoint)
  451. {
  452. if (entryPoint == null)
  453. throw new ArgumentNullException ("entryPoint");
  454. if (entryPoint.DeclaringType.Module != this)
  455. throw new InvalidOperationException ("entryPoint is not contained in this module");
  456. throw new NotImplementedException ();
  457. }
  458. public MethodToken GetMethodToken (MethodInfo method)
  459. {
  460. if (method == null)
  461. throw new ArgumentNullException ("method");
  462. if (method.DeclaringType.Module != this)
  463. throw new InvalidOperationException ("The method is not in this module");
  464. return new MethodToken (GetToken (method));
  465. }
  466. public MethodToken GetArrayMethodToken (Type arrayClass, string methodName, CallingConventions callingConvention, Type returnType, Type[] parameterTypes)
  467. {
  468. return GetMethodToken (GetArrayMethod (arrayClass, methodName, callingConvention, returnType, parameterTypes));
  469. }
  470. #if NET_2_0
  471. [ComVisible (true)]
  472. #endif
  473. public MethodToken GetConstructorToken (ConstructorInfo con)
  474. {
  475. if (con == null)
  476. throw new ArgumentNullException ("con");
  477. return new MethodToken (GetToken (con));
  478. }
  479. public FieldToken GetFieldToken (FieldInfo field)
  480. {
  481. if (field == null)
  482. throw new ArgumentNullException ("field");
  483. if (field.DeclaringType.Module != this)
  484. throw new InvalidOperationException ("The method is not in this module");
  485. return new FieldToken (GetToken (field));
  486. }
  487. [MonoTODO]
  488. public SignatureToken GetSignatureToken (byte[] sigBytes, int sigLength)
  489. {
  490. throw new NotImplementedException ();
  491. }
  492. public SignatureToken GetSignatureToken (SignatureHelper sigHelper)
  493. {
  494. if (sigHelper == null)
  495. throw new ArgumentNullException ("sigHelper");
  496. return new SignatureToken (GetToken (sigHelper));
  497. }
  498. public StringToken GetStringConstant (string str)
  499. {
  500. if (str == null)
  501. throw new ArgumentNullException ("str");
  502. return new StringToken (GetToken (str));
  503. }
  504. public TypeToken GetTypeToken (Type type)
  505. {
  506. if (type == null)
  507. throw new ArgumentNullException ("type");
  508. if (type.IsByRef)
  509. throw new ArgumentException ("type can't be a byref type", "type");
  510. if (!IsTransient () && (type.Module is ModuleBuilder) && ((ModuleBuilder)type.Module).IsTransient ())
  511. throw new InvalidOperationException ("a non-transient module can't reference a transient module");
  512. return new TypeToken (GetToken (type));
  513. }
  514. public TypeToken GetTypeToken (string type)
  515. {
  516. return GetTypeToken (GetType (name));
  517. }
  518. [MethodImplAttribute(MethodImplOptions.InternalCall)]
  519. private static extern int getUSIndex (ModuleBuilder mb, string str);
  520. [MethodImplAttribute(MethodImplOptions.InternalCall)]
  521. private static extern int getToken (ModuleBuilder mb, object obj);
  522. [MethodImplAttribute(MethodImplOptions.InternalCall)]
  523. private static extern int getMethodToken (ModuleBuilder mb, MethodInfo method,
  524. Type[] opt_param_types);
  525. internal int GetToken (string str) {
  526. if (us_string_cache.Contains (str))
  527. return (int)us_string_cache [str];
  528. int result = getUSIndex (this, str);
  529. us_string_cache [str] = result;
  530. return result;
  531. }
  532. internal int GetToken (MemberInfo member) {
  533. return getToken (this, member);
  534. }
  535. internal int GetToken (MethodInfo method, Type[] opt_param_types) {
  536. return getMethodToken (this, method, opt_param_types);
  537. }
  538. internal int GetToken (SignatureHelper helper) {
  539. return getToken (this, helper);
  540. }
  541. internal TokenGenerator GetTokenGenerator () {
  542. if (token_gen == null)
  543. token_gen = new ModuleBuilderTokenGenerator (this);
  544. return token_gen;
  545. }
  546. [MethodImplAttribute(MethodImplOptions.InternalCall)]
  547. private static extern void build_metadata (ModuleBuilder mb);
  548. [MethodImplAttribute(MethodImplOptions.InternalCall)]
  549. private extern void WriteToFile (IntPtr handle);
  550. internal void Save ()
  551. {
  552. if (transient && !is_main)
  553. return;
  554. if (types != null) {
  555. for (int i = 0; i < num_types; ++i)
  556. if (!types [i].is_created)
  557. throw new NotSupportedException ("Type '" + types [i].FullName + "' was not completed.");
  558. }
  559. if ((global_type != null) && (global_type_created == null))
  560. global_type_created = global_type.CreateType ();
  561. if (resource_writers != null) {
  562. for (int i = 0; i < resource_writers.Count; ++i) {
  563. ResourceWriter writer = (ResourceWriter)resource_writers [i];
  564. writer.Generate ();
  565. MemoryStream stream = (MemoryStream)writer.Stream;
  566. resources [i].data = new byte [stream.Length];
  567. stream.Seek (0, SeekOrigin.Begin);
  568. stream.Read (resources [i].data, 0, (int)stream.Length);
  569. }
  570. }
  571. build_metadata (this);
  572. string fileName = fqname;
  573. if (assemblyb.AssemblyDir != null)
  574. fileName = Path.Combine (assemblyb.AssemblyDir, fileName);
  575. using (FileStream file = new FileStream (fileName, FileMode.Create, FileAccess.Write))
  576. WriteToFile (file.Handle);
  577. //
  578. // The constant 0x80000000 is internal to Mono, it means `make executable'
  579. //
  580. File.SetAttributes (fileName, (FileAttributes) (unchecked ((int) 0x80000000)));
  581. if (types != null && symbolWriter != null) {
  582. for (int i = 0; i < num_types; ++i)
  583. types [i].GenerateDebugInfo (symbolWriter);
  584. symbolWriter.Close ();
  585. }
  586. }
  587. internal string FileName {
  588. get {
  589. return fqname;
  590. }
  591. }
  592. internal bool IsMain {
  593. set {
  594. is_main = value;
  595. }
  596. }
  597. internal void CreateGlobalType () {
  598. if (global_type == null)
  599. global_type = new TypeBuilder (this, 0);
  600. }
  601. internal static Guid Mono_GetGuid (ModuleBuilder mb)
  602. {
  603. return new Guid (mb.guid);
  604. }
  605. }
  606. internal class ModuleBuilderTokenGenerator : TokenGenerator {
  607. private ModuleBuilder mb;
  608. public ModuleBuilderTokenGenerator (ModuleBuilder mb) {
  609. this.mb = mb;
  610. }
  611. public int GetToken (string str) {
  612. return mb.GetToken (str);
  613. }
  614. public int GetToken (MemberInfo member) {
  615. return mb.GetToken (member);
  616. }
  617. public int GetToken (MethodInfo method, Type[] opt_param_types) {
  618. return mb.GetToken (method, opt_param_types);
  619. }
  620. public int GetToken (SignatureHelper helper) {
  621. return mb.GetToken (helper);
  622. }
  623. }
  624. }