ModuleBuilder.cs 23 KB

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