ModuleBuilder.cs 27 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829
  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. [ComDefaultInterface (typeof (_ModuleBuilder))]
  44. #endif
  45. [ClassInterface (ClassInterfaceType.None)]
  46. public class ModuleBuilder : Module, _ModuleBuilder {
  47. #region Sync with object-internals.h
  48. private UIntPtr dynamic_image; /* GC-tracked */
  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. Hashtable resource_writers;
  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. {
  116. if (name == null)
  117. throw new ArgumentNullException ("name");
  118. if (global_type_created != null)
  119. throw new InvalidOperationException ("global fields already created");
  120. if ((size <= 0) || (size > 0x3f0000))
  121. throw new ArgumentException ("size", "Data size must be > 0 and < 0x3f0000");
  122. if (global_type == null)
  123. global_type = new TypeBuilder (this, 0);
  124. string typeName = "$ArrayType$" + size;
  125. Type datablobtype = GetType (typeName, false, false);
  126. if (datablobtype == null) {
  127. TypeBuilder tb = DefineType (typeName,
  128. TypeAttributes.Public|TypeAttributes.ExplicitLayout|TypeAttributes.Sealed,
  129. assemblyb.corlib_value_type, null, PackingSize.Size1, size);
  130. tb.CreateType ();
  131. datablobtype = tb;
  132. }
  133. FieldBuilder fb = global_type.DefineField (name, datablobtype, attributes|FieldAttributes.Static);
  134. if (global_fields != null) {
  135. FieldBuilder[] new_fields = new FieldBuilder [global_fields.Length+1];
  136. System.Array.Copy (global_fields, new_fields, global_fields.Length);
  137. new_fields [global_fields.Length] = fb;
  138. global_fields = new_fields;
  139. } else {
  140. global_fields = new FieldBuilder [1];
  141. global_fields [0] = fb;
  142. }
  143. return fb;
  144. }
  145. private void addGlobalMethod (MethodBuilder mb) {
  146. if (global_methods != null) {
  147. MethodBuilder[] new_methods = new MethodBuilder [global_methods.Length+1];
  148. System.Array.Copy (global_methods, new_methods, global_methods.Length);
  149. new_methods [global_methods.Length] = mb;
  150. global_methods = new_methods;
  151. } else {
  152. global_methods = new MethodBuilder [1];
  153. global_methods [0] = mb;
  154. }
  155. }
  156. public MethodBuilder DefineGlobalMethod (string name, MethodAttributes attributes, Type returnType, Type[] parameterTypes)
  157. {
  158. return DefineGlobalMethod (name, attributes, CallingConventions.Standard, returnType, parameterTypes);
  159. }
  160. public MethodBuilder DefineGlobalMethod (string name, MethodAttributes attributes, CallingConventions callingConvention, Type returnType, Type[] parameterTypes) {
  161. return DefineGlobalMethod (name, attributes, callingConvention, returnType, null, null, parameterTypes, null, null);
  162. }
  163. #if NET_2_0 || BOOTSTRAP_NET_2_0
  164. public
  165. #else
  166. internal
  167. #endif
  168. MethodBuilder DefineGlobalMethod (string name, MethodAttributes attributes, CallingConventions callingConvention, Type returnType, Type[] requiredReturnTypeCustomModifiers, Type[] optionalReturnTypeCustomModifiers, Type[] parameterTypes, Type[][] requiredParameterTypeCustomModifiers, Type[][] optionalParameterTypeCustomModifiers)
  169. {
  170. if (name == null)
  171. throw new ArgumentNullException ("name");
  172. if ((attributes & MethodAttributes.Static) == 0)
  173. throw new ArgumentException ("global methods must be static");
  174. if (global_type_created != null)
  175. throw new InvalidOperationException ("global methods already created");
  176. if (global_type == null)
  177. global_type = new TypeBuilder (this, 0);
  178. MethodBuilder mb = global_type.DefineMethod (name, attributes, callingConvention, returnType, requiredReturnTypeCustomModifiers, optionalReturnTypeCustomModifiers, parameterTypes, requiredParameterTypeCustomModifiers, optionalParameterTypeCustomModifiers);
  179. addGlobalMethod (mb);
  180. return mb;
  181. }
  182. public MethodBuilder DefinePInvokeMethod (string name, string dllName, MethodAttributes attributes, CallingConventions callingConvention, Type returnType, Type[] parameterTypes, CallingConvention nativeCallConv, CharSet nativeCharSet) {
  183. return DefinePInvokeMethod (name, dllName, name, attributes, callingConvention, returnType, parameterTypes, nativeCallConv, nativeCharSet);
  184. }
  185. public MethodBuilder DefinePInvokeMethod (string name, string dllName, string entryName, MethodAttributes attributes, CallingConventions callingConvention, Type returnType, Type[] parameterTypes, CallingConvention nativeCallConv, CharSet nativeCharSet) {
  186. if (name == null)
  187. throw new ArgumentNullException ("name");
  188. if ((attributes & MethodAttributes.Static) == 0)
  189. throw new ArgumentException ("global methods must be static");
  190. if (global_type_created != null)
  191. throw new InvalidOperationException ("global methods already created");
  192. if (global_type == null)
  193. global_type = new TypeBuilder (this, 0);
  194. MethodBuilder mb = global_type.DefinePInvokeMethod (name, dllName, entryName, attributes, callingConvention, returnType, parameterTypes, nativeCallConv, nativeCharSet);
  195. addGlobalMethod (mb);
  196. return mb;
  197. }
  198. public TypeBuilder DefineType (string name) {
  199. return DefineType (name, 0);
  200. }
  201. public TypeBuilder DefineType (string name, TypeAttributes attr) {
  202. if ((attr & TypeAttributes.Interface) != 0)
  203. return DefineType (name, attr, null, null);
  204. return DefineType (name, attr, typeof(object), null);
  205. }
  206. public TypeBuilder DefineType (string name, TypeAttributes attr, Type parent) {
  207. return DefineType (name, attr, parent, null);
  208. }
  209. private void AddType (TypeBuilder tb)
  210. {
  211. if (types != null) {
  212. if (types.Length == num_types) {
  213. TypeBuilder[] new_types = new TypeBuilder [types.Length * 2];
  214. System.Array.Copy (types, new_types, num_types);
  215. types = new_types;
  216. }
  217. } else {
  218. types = new TypeBuilder [1];
  219. }
  220. types [num_types] = tb;
  221. num_types ++;
  222. }
  223. private TypeBuilder DefineType (string name, TypeAttributes attr, Type parent, Type[] interfaces, PackingSize packsize, int typesize) {
  224. if (name_cache.Contains (name))
  225. throw new ArgumentException ("Duplicate type name within an assembly.");
  226. TypeBuilder res = new TypeBuilder (this, name, attr, parent, interfaces, packsize, typesize, null);
  227. AddType (res);
  228. name_cache.Add (name, res);
  229. return res;
  230. }
  231. internal void RegisterTypeName (TypeBuilder tb, string name)
  232. {
  233. name_cache.Add (name, tb);
  234. }
  235. internal TypeBuilder GetRegisteredType (string name)
  236. {
  237. if (name_cache == null)
  238. return null;
  239. return (TypeBuilder)name_cache [name];
  240. }
  241. #if NET_2_0
  242. [ComVisible (true)]
  243. #endif
  244. public TypeBuilder DefineType (string name, TypeAttributes attr, Type parent, Type[] interfaces) {
  245. return DefineType (name, attr, parent, interfaces, PackingSize.Unspecified, TypeBuilder.UnspecifiedTypeSize);
  246. }
  247. public TypeBuilder DefineType (string name, TypeAttributes attr, Type parent, int typesize) {
  248. return DefineType (name, attr, parent, null, PackingSize.Unspecified, TypeBuilder.UnspecifiedTypeSize);
  249. }
  250. public TypeBuilder DefineType (string name, TypeAttributes attr, Type parent, PackingSize packsize) {
  251. return DefineType (name, attr, parent, null, packsize, TypeBuilder.UnspecifiedTypeSize);
  252. }
  253. public TypeBuilder DefineType (string name, TypeAttributes attr, Type parent, PackingSize packsize, int typesize) {
  254. return DefineType (name, attr, parent, null, packsize, typesize);
  255. }
  256. public MethodInfo GetArrayMethod( Type arrayClass, string methodName, CallingConventions callingConvention, Type returnType, Type[] parameterTypes) {
  257. return new MonoArrayMethod (arrayClass, methodName, callingConvention, returnType, parameterTypes);
  258. }
  259. public EnumBuilder DefineEnum( string name, TypeAttributes visibility, Type underlyingType) {
  260. if (name_cache.Contains (name))
  261. throw new ArgumentException ("Duplicate type name within an assembly.");
  262. EnumBuilder eb = new EnumBuilder (this, name, visibility, underlyingType);
  263. TypeBuilder res = eb.GetTypeBuilder ();
  264. AddType (res);
  265. name_cache.Add (name, res);
  266. return eb;
  267. }
  268. #if NET_2_0
  269. [ComVisible (true)]
  270. #endif
  271. public override Type GetType( string className) {
  272. return GetType (className, false, false);
  273. }
  274. #if NET_2_0
  275. [ComVisible (true)]
  276. #endif
  277. public override Type GetType( string className, bool ignoreCase) {
  278. return GetType (className, false, ignoreCase);
  279. }
  280. private TypeBuilder search_in_array (TypeBuilder[] arr, int validElementsInArray, string className) {
  281. int i;
  282. for (i = 0; i < validElementsInArray; ++i) {
  283. if (String.Compare (className, arr [i].FullName, true, CultureInfo.InvariantCulture) == 0) {
  284. return arr [i];
  285. }
  286. }
  287. return null;
  288. }
  289. private TypeBuilder search_nested_in_array (TypeBuilder[] arr, int validElementsInArray, string className) {
  290. int i;
  291. for (i = 0; i < validElementsInArray; ++i) {
  292. if (String.Compare (className, arr [i].Name, true, CultureInfo.InvariantCulture) == 0)
  293. return arr [i];
  294. }
  295. return null;
  296. }
  297. [MethodImplAttribute(MethodImplOptions.InternalCall)]
  298. private static extern Type create_modified_type (TypeBuilder tb, string modifiers);
  299. static readonly char [] type_modifiers = {'&', '[', '*'};
  300. private TypeBuilder GetMaybeNested (TypeBuilder t, string className) {
  301. int subt;
  302. string pname, rname;
  303. subt = className.IndexOf ('+');
  304. if (subt < 0) {
  305. if (t.subtypes != null)
  306. return search_nested_in_array (t.subtypes, t.subtypes.Length, className);
  307. return null;
  308. }
  309. if (t.subtypes != null) {
  310. pname = className.Substring (0, subt);
  311. rname = className.Substring (subt + 1);
  312. TypeBuilder result = search_nested_in_array (t.subtypes, t.subtypes.Length, pname);
  313. if (result != null)
  314. return GetMaybeNested (result, rname);
  315. }
  316. return null;
  317. }
  318. #if NET_2_0
  319. [ComVisible (true)]
  320. #endif
  321. public override Type GetType (string className, bool throwOnError, bool ignoreCase) {
  322. int subt;
  323. string orig = className;
  324. string modifiers;
  325. TypeBuilder result = null;
  326. if (types == null && throwOnError)
  327. throw new TypeLoadException (className);
  328. subt = className.IndexOfAny (type_modifiers);
  329. if (subt >= 0) {
  330. modifiers = className.Substring (subt);
  331. className = className.Substring (0, subt);
  332. } else
  333. modifiers = null;
  334. if (!ignoreCase) {
  335. result = name_cache [className] as TypeBuilder;
  336. } else {
  337. subt = className.IndexOf ('+');
  338. if (subt < 0) {
  339. if (types != null)
  340. result = search_in_array (types, num_types, className);
  341. } else {
  342. string pname, rname;
  343. pname = className.Substring (0, subt);
  344. rname = className.Substring (subt + 1);
  345. result = search_in_array (types, num_types, pname);
  346. if (result != null)
  347. result = GetMaybeNested (result, rname);
  348. }
  349. }
  350. if ((result == null) && throwOnError)
  351. throw new TypeLoadException (orig);
  352. if (result != null && (modifiers != null)) {
  353. Type mt = create_modified_type (result, modifiers);
  354. if (mt is TypeBuilder)
  355. result = mt as TypeBuilder;
  356. else
  357. return mt;
  358. }
  359. if (result != null && result.is_created)
  360. return result.CreateType ();
  361. else
  362. return result;
  363. }
  364. internal int get_next_table_index (object obj, int table, bool inc) {
  365. if (table_indexes == null) {
  366. table_indexes = new int [64];
  367. for (int i=0; i < 64; ++i)
  368. table_indexes [i] = 1;
  369. /* allow room for .<Module> in TypeDef table */
  370. table_indexes [0x02] = 2;
  371. }
  372. // Console.WriteLine ("getindex for table "+table.ToString()+" got "+table_indexes [table].ToString());
  373. if (inc)
  374. return table_indexes [table]++;
  375. return table_indexes [table];
  376. }
  377. public void SetCustomAttribute( CustomAttributeBuilder customBuilder) {
  378. if (cattrs != null) {
  379. CustomAttributeBuilder[] new_array = new CustomAttributeBuilder [cattrs.Length + 1];
  380. cattrs.CopyTo (new_array, 0);
  381. new_array [cattrs.Length] = customBuilder;
  382. cattrs = new_array;
  383. } else {
  384. cattrs = new CustomAttributeBuilder [1];
  385. cattrs [0] = customBuilder;
  386. }
  387. }
  388. #if NET_2_0
  389. [ComVisible (true)]
  390. #endif
  391. public void SetCustomAttribute( ConstructorInfo con, byte[] binaryAttribute) {
  392. SetCustomAttribute (new CustomAttributeBuilder (con, binaryAttribute));
  393. }
  394. public ISymbolWriter GetSymWriter () {
  395. return symbolWriter;
  396. }
  397. public ISymbolDocumentWriter DefineDocument (string url, Guid language, Guid languageVendor, Guid documentType)
  398. {
  399. if (symbolWriter != null)
  400. return symbolWriter.DefineDocument (url, language, languageVendor, documentType);
  401. else
  402. return null;
  403. }
  404. public override Type [] GetTypes ()
  405. {
  406. if (types == null)
  407. return new TypeBuilder [0];
  408. int n = num_types;
  409. Type [] copy = new Type [n];
  410. Array.Copy (types, copy, n);
  411. // MS replaces the typebuilders with their created types
  412. for (int i = 0; i < copy.Length; ++i)
  413. if (types [i].is_created)
  414. copy [i] = types [i].CreateType ();
  415. return copy;
  416. }
  417. public IResourceWriter DefineResource (string name, string description, ResourceAttributes attribute)
  418. {
  419. if (name == null)
  420. throw new ArgumentNullException ("name");
  421. if (name == String.Empty)
  422. throw new ArgumentException ("name cannot be empty");
  423. if (transient)
  424. throw new InvalidOperationException ("The module is transient");
  425. if (!assemblyb.IsSave)
  426. throw new InvalidOperationException ("The assembly is transient");
  427. ResourceWriter writer = new ResourceWriter (new MemoryStream ());
  428. if (resource_writers == null)
  429. resource_writers = new Hashtable ();
  430. resource_writers [name] = writer;
  431. // The data is filled out later
  432. if (resources != null) {
  433. MonoResource[] new_r = new MonoResource [resources.Length + 1];
  434. System.Array.Copy(resources, new_r, resources.Length);
  435. resources = new_r;
  436. } else {
  437. resources = new MonoResource [1];
  438. }
  439. int p = resources.Length - 1;
  440. resources [p].name = name;
  441. resources [p].attrs = attribute;
  442. return writer;
  443. }
  444. public IResourceWriter DefineResource (string name, string description)
  445. {
  446. return DefineResource (name, description, ResourceAttributes.Public);
  447. }
  448. [MonoTODO]
  449. public void DefineUnmanagedResource (byte[] resource)
  450. {
  451. if (resource == null)
  452. throw new ArgumentNullException ("resource");
  453. throw new NotImplementedException ();
  454. }
  455. [MonoTODO]
  456. public void DefineUnmanagedResource (string resourceFileName)
  457. {
  458. if (resourceFileName == null)
  459. throw new ArgumentNullException ("resourceFileName");
  460. if (resourceFileName == String.Empty)
  461. throw new ArgumentException ("resourceFileName");
  462. if (!File.Exists (resourceFileName) || Directory.Exists (resourceFileName))
  463. throw new FileNotFoundException ("File '" + resourceFileName + "' does not exists or is a directory.");
  464. throw new NotImplementedException ();
  465. }
  466. #if NET_2_0
  467. public void DefineManifestResource (string name, Stream stream, ResourceAttributes attribute) {
  468. if (name == null)
  469. throw new ArgumentNullException ("name");
  470. if (name == String.Empty)
  471. throw new ArgumentException ("name cannot be empty");
  472. if (stream == null)
  473. throw new ArgumentNullException ("stream");
  474. if (transient)
  475. throw new InvalidOperationException ("The module is transient");
  476. if (!assemblyb.IsSave)
  477. throw new InvalidOperationException ("The assembly is transient");
  478. if (resources != null) {
  479. MonoResource[] new_r = new MonoResource [resources.Length + 1];
  480. System.Array.Copy(resources, new_r, resources.Length);
  481. resources = new_r;
  482. } else {
  483. resources = new MonoResource [1];
  484. }
  485. int p = resources.Length - 1;
  486. resources [p].name = name;
  487. resources [p].attrs = attribute;
  488. resources [p].stream = stream;
  489. }
  490. #endif
  491. [MonoTODO]
  492. public void SetSymCustomAttribute (string name, byte[] data)
  493. {
  494. throw new NotImplementedException ();
  495. }
  496. [MonoTODO]
  497. public void SetUserEntryPoint (MethodInfo entryPoint)
  498. {
  499. if (entryPoint == null)
  500. throw new ArgumentNullException ("entryPoint");
  501. if (entryPoint.DeclaringType.Module != this)
  502. throw new InvalidOperationException ("entryPoint is not contained in this module");
  503. throw new NotImplementedException ();
  504. }
  505. public MethodToken GetMethodToken (MethodInfo method)
  506. {
  507. if (method == null)
  508. throw new ArgumentNullException ("method");
  509. if (method.DeclaringType.Module != this)
  510. throw new InvalidOperationException ("The method is not in this module");
  511. return new MethodToken (GetToken (method));
  512. }
  513. public MethodToken GetArrayMethodToken (Type arrayClass, string methodName, CallingConventions callingConvention, Type returnType, Type[] parameterTypes)
  514. {
  515. return GetMethodToken (GetArrayMethod (arrayClass, methodName, callingConvention, returnType, parameterTypes));
  516. }
  517. #if NET_2_0
  518. [ComVisible (true)]
  519. #endif
  520. public MethodToken GetConstructorToken (ConstructorInfo con)
  521. {
  522. if (con == null)
  523. throw new ArgumentNullException ("con");
  524. return new MethodToken (GetToken (con));
  525. }
  526. public FieldToken GetFieldToken (FieldInfo field)
  527. {
  528. if (field == null)
  529. throw new ArgumentNullException ("field");
  530. if (field.DeclaringType.Module != this)
  531. throw new InvalidOperationException ("The method is not in this module");
  532. return new FieldToken (GetToken (field));
  533. }
  534. [MonoTODO]
  535. public SignatureToken GetSignatureToken (byte[] sigBytes, int sigLength)
  536. {
  537. throw new NotImplementedException ();
  538. }
  539. public SignatureToken GetSignatureToken (SignatureHelper sigHelper)
  540. {
  541. if (sigHelper == null)
  542. throw new ArgumentNullException ("sigHelper");
  543. return new SignatureToken (GetToken (sigHelper));
  544. }
  545. public StringToken GetStringConstant (string str)
  546. {
  547. if (str == null)
  548. throw new ArgumentNullException ("str");
  549. return new StringToken (GetToken (str));
  550. }
  551. public TypeToken GetTypeToken (Type type)
  552. {
  553. if (type == null)
  554. throw new ArgumentNullException ("type");
  555. if (type.IsByRef)
  556. throw new ArgumentException ("type can't be a byref type", "type");
  557. if (!IsTransient () && (type.Module is ModuleBuilder) && ((ModuleBuilder)type.Module).IsTransient ())
  558. throw new InvalidOperationException ("a non-transient module can't reference a transient module");
  559. return new TypeToken (GetToken (type));
  560. }
  561. public TypeToken GetTypeToken (string type)
  562. {
  563. return GetTypeToken (GetType (name));
  564. }
  565. [MethodImplAttribute(MethodImplOptions.InternalCall)]
  566. private static extern int getUSIndex (ModuleBuilder mb, string str);
  567. [MethodImplAttribute(MethodImplOptions.InternalCall)]
  568. private static extern int getToken (ModuleBuilder mb, object obj);
  569. [MethodImplAttribute(MethodImplOptions.InternalCall)]
  570. private static extern int getMethodToken (ModuleBuilder mb, MethodInfo method,
  571. Type[] opt_param_types);
  572. internal int GetToken (string str) {
  573. if (us_string_cache.Contains (str))
  574. return (int)us_string_cache [str];
  575. int result = getUSIndex (this, str);
  576. us_string_cache [str] = result;
  577. return result;
  578. }
  579. internal int GetToken (MemberInfo member) {
  580. return getToken (this, member);
  581. }
  582. internal int GetToken (MethodInfo method, Type[] opt_param_types) {
  583. return getMethodToken (this, method, opt_param_types);
  584. }
  585. internal int GetToken (SignatureHelper helper) {
  586. return getToken (this, helper);
  587. }
  588. internal TokenGenerator GetTokenGenerator () {
  589. if (token_gen == null)
  590. token_gen = new ModuleBuilderTokenGenerator (this);
  591. return token_gen;
  592. }
  593. [MethodImplAttribute(MethodImplOptions.InternalCall)]
  594. private static extern void build_metadata (ModuleBuilder mb);
  595. [MethodImplAttribute(MethodImplOptions.InternalCall)]
  596. private extern void WriteToFile (IntPtr handle);
  597. internal void Save ()
  598. {
  599. if (transient && !is_main)
  600. return;
  601. if (types != null) {
  602. for (int i = 0; i < num_types; ++i)
  603. if (!types [i].is_created)
  604. throw new NotSupportedException ("Type '" + types [i].FullName + "' was not completed.");
  605. }
  606. if ((global_type != null) && (global_type_created == null))
  607. global_type_created = global_type.CreateType ();
  608. if (resources != null) {
  609. for (int i = 0; i < resources.Length; ++i) {
  610. IResourceWriter rwriter;
  611. if (resource_writers != null && (rwriter = resource_writers [resources [i].name] as IResourceWriter) != null) {
  612. ResourceWriter writer = (ResourceWriter)rwriter;
  613. writer.Generate ();
  614. MemoryStream mstream = (MemoryStream)writer.Stream;
  615. resources [i].data = new byte [mstream.Length];
  616. mstream.Seek (0, SeekOrigin.Begin);
  617. mstream.Read (resources [i].data, 0, (int)mstream.Length);
  618. continue;
  619. }
  620. Stream stream = resources [i].stream;
  621. // According to MSDN docs, the stream is read during assembly save, not earlier
  622. if (stream != null) {
  623. try {
  624. long len = stream.Length;
  625. resources [i].data = new byte [len];
  626. stream.Seek (0, SeekOrigin.Begin);
  627. stream.Read (resources [i].data, 0, (int)len);
  628. } catch {
  629. /* do something */
  630. }
  631. }
  632. }
  633. }
  634. build_metadata (this);
  635. string fileName = fqname;
  636. if (assemblyb.AssemblyDir != null)
  637. fileName = Path.Combine (assemblyb.AssemblyDir, fileName);
  638. try {
  639. // We mmap the file, so unlink the previous version since it may be in use
  640. File.Delete (fileName);
  641. } catch {
  642. // We can safely ignore
  643. }
  644. using (FileStream file = new FileStream (fileName, FileMode.Create, FileAccess.Write))
  645. WriteToFile (file.Handle);
  646. //
  647. // The constant 0x80000000 is internal to Mono, it means `make executable'
  648. //
  649. File.SetAttributes (fileName, (FileAttributes) (unchecked ((int) 0x80000000)));
  650. if (types != null && symbolWriter != null) {
  651. for (int i = 0; i < num_types; ++i)
  652. types [i].GenerateDebugInfo (symbolWriter);
  653. symbolWriter.Close ();
  654. }
  655. }
  656. internal string FileName {
  657. get {
  658. return fqname;
  659. }
  660. }
  661. internal bool IsMain {
  662. set {
  663. is_main = value;
  664. }
  665. }
  666. internal void CreateGlobalType () {
  667. if (global_type == null)
  668. global_type = new TypeBuilder (this, 0);
  669. }
  670. internal static Guid Mono_GetGuid (ModuleBuilder mb)
  671. {
  672. return new Guid (mb.guid);
  673. }
  674. void _ModuleBuilder.GetIDsOfNames ([In] ref Guid riid, IntPtr rgszNames, uint cNames, uint lcid, IntPtr rgDispId)
  675. {
  676. throw new NotImplementedException ();
  677. }
  678. void _ModuleBuilder.GetTypeInfo (uint iTInfo, uint lcid, IntPtr ppTInfo)
  679. {
  680. throw new NotImplementedException ();
  681. }
  682. void _ModuleBuilder.GetTypeInfoCount (out uint pcTInfo)
  683. {
  684. throw new NotImplementedException ();
  685. }
  686. void _ModuleBuilder.Invoke (uint dispIdMember, [In] ref Guid riid, uint lcid, short wFlags, IntPtr pDispParams, IntPtr pVarResult, IntPtr pExcepInfo, IntPtr puArgErr)
  687. {
  688. throw new NotImplementedException ();
  689. }
  690. }
  691. internal class ModuleBuilderTokenGenerator : TokenGenerator {
  692. private ModuleBuilder mb;
  693. public ModuleBuilderTokenGenerator (ModuleBuilder mb) {
  694. this.mb = mb;
  695. }
  696. public int GetToken (string str) {
  697. return mb.GetToken (str);
  698. }
  699. public int GetToken (MemberInfo member) {
  700. return mb.GetToken (member);
  701. }
  702. public int GetToken (MethodInfo method, Type[] opt_param_types) {
  703. return mb.GetToken (method, opt_param_types);
  704. }
  705. public int GetToken (SignatureHelper helper) {
  706. return mb.GetToken (helper);
  707. }
  708. }
  709. }