ModuleBuilder.cs 31 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950
  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.Collections.Generic;
  35. using System.Runtime.CompilerServices;
  36. using System.Runtime.InteropServices;
  37. using System.Diagnostics.SymbolStore;
  38. using System.IO;
  39. using System.Resources;
  40. using System.Globalization;
  41. namespace System.Reflection.Emit {
  42. [ComVisible (true)]
  43. [ComDefaultInterface (typeof (_ModuleBuilder))]
  44. [ClassInterface (ClassInterfaceType.None)]
  45. public class ModuleBuilder : Module, _ModuleBuilder {
  46. #pragma warning disable 169, 414
  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. #pragma warning restore 169, 414
  61. private TypeBuilder global_type;
  62. private Type global_type_created;
  63. Hashtable name_cache;
  64. Dictionary<string, int> us_string_cache;
  65. private int[] table_indexes;
  66. bool transient;
  67. ModuleBuilderTokenGenerator token_gen;
  68. Hashtable resource_writers;
  69. ISymbolWriter symbolWriter;
  70. [MethodImplAttribute(MethodImplOptions.InternalCall)]
  71. private static extern void basic_init (ModuleBuilder ab);
  72. [MethodImplAttribute(MethodImplOptions.InternalCall)]
  73. private static extern void set_wrappers_type (ModuleBuilder mb, Type ab);
  74. internal ModuleBuilder (AssemblyBuilder assb, string name, string fullyqname, bool emitSymbolInfo, bool transient) {
  75. this.name = this.scopename = name;
  76. this.fqname = fullyqname;
  77. this.assembly = this.assemblyb = assb;
  78. this.transient = transient;
  79. // to keep mcs fast we do not want CryptoConfig wo be involved to create the RNG
  80. guid = Guid.FastNewGuidArray ();
  81. // guid = Guid.NewGuid().ToByteArray ();
  82. table_idx = get_next_table_index (this, 0x00, true);
  83. name_cache = new Hashtable ();
  84. us_string_cache = new Dictionary<string, int> (512);
  85. basic_init (this);
  86. CreateGlobalType ();
  87. if (assb.IsRun) {
  88. TypeBuilder tb = new TypeBuilder (this, TypeAttributes.Abstract, 0xFFFFFF); /*last valid token*/
  89. Type type = tb.CreateType ();
  90. set_wrappers_type (this, type);
  91. }
  92. if (emitSymbolInfo) {
  93. #if MOONLIGHT
  94. symbolWriter = new Mono.CompilerServices.SymbolWriter.SymbolWriterImpl (this);
  95. #else
  96. Assembly asm = Assembly.LoadWithPartialName ("Mono.CompilerServices.SymbolWriter");
  97. if (asm == null)
  98. throw new TypeLoadException ("The assembly for default symbol writer cannot be loaded");
  99. Type t = asm.GetType ("Mono.CompilerServices.SymbolWriter.SymbolWriterImpl", true);
  100. symbolWriter = (ISymbolWriter) Activator.CreateInstance (t, new object[] { this });
  101. #endif
  102. string fileName = fqname;
  103. if (assemblyb.AssemblyDir != null)
  104. fileName = Path.Combine (assemblyb.AssemblyDir, fileName);
  105. symbolWriter.Initialize (IntPtr.Zero, fileName, true);
  106. }
  107. }
  108. public override string FullyQualifiedName {get { return fqname;}}
  109. public bool IsTransient () {
  110. return transient;
  111. }
  112. public void CreateGlobalFunctions ()
  113. {
  114. if (global_type_created != null)
  115. throw new InvalidOperationException ("global methods already created");
  116. if (global_type != null)
  117. global_type_created = global_type.CreateType ();
  118. }
  119. public FieldBuilder DefineInitializedData( string name, byte[] data, FieldAttributes attributes) {
  120. if (data == null)
  121. throw new ArgumentNullException ("data");
  122. FieldBuilder fb = DefineUninitializedData (name, data.Length,
  123. attributes | FieldAttributes.HasFieldRVA);
  124. fb.SetRVAData (data);
  125. return fb;
  126. }
  127. public FieldBuilder DefineUninitializedData (string name, int size, FieldAttributes attributes)
  128. {
  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 ((size <= 0) || (size > 0x3f0000))
  134. throw new ArgumentException ("size", "Data size must be > 0 and < 0x3f0000");
  135. CreateGlobalType ();
  136. string typeName = "$ArrayType$" + size;
  137. Type datablobtype = GetType (typeName, false, false);
  138. if (datablobtype == null) {
  139. TypeBuilder tb = DefineType (typeName,
  140. TypeAttributes.Public|TypeAttributes.ExplicitLayout|TypeAttributes.Sealed,
  141. assemblyb.corlib_value_type, null, PackingSize.Size1, size);
  142. tb.CreateType ();
  143. datablobtype = tb;
  144. }
  145. FieldBuilder fb = global_type.DefineField (name, datablobtype, attributes|FieldAttributes.Static);
  146. if (global_fields != null) {
  147. FieldBuilder[] new_fields = new FieldBuilder [global_fields.Length+1];
  148. System.Array.Copy (global_fields, new_fields, global_fields.Length);
  149. new_fields [global_fields.Length] = fb;
  150. global_fields = new_fields;
  151. } else {
  152. global_fields = new FieldBuilder [1];
  153. global_fields [0] = fb;
  154. }
  155. return fb;
  156. }
  157. private void addGlobalMethod (MethodBuilder mb) {
  158. if (global_methods != null) {
  159. MethodBuilder[] new_methods = new MethodBuilder [global_methods.Length+1];
  160. System.Array.Copy (global_methods, new_methods, global_methods.Length);
  161. new_methods [global_methods.Length] = mb;
  162. global_methods = new_methods;
  163. } else {
  164. global_methods = new MethodBuilder [1];
  165. global_methods [0] = mb;
  166. }
  167. }
  168. public MethodBuilder DefineGlobalMethod (string name, MethodAttributes attributes, Type returnType, Type[] parameterTypes)
  169. {
  170. return DefineGlobalMethod (name, attributes, CallingConventions.Standard, returnType, parameterTypes);
  171. }
  172. public MethodBuilder DefineGlobalMethod (string name, MethodAttributes attributes, CallingConventions callingConvention, Type returnType, Type[] parameterTypes) {
  173. return DefineGlobalMethod (name, attributes, callingConvention, returnType, null, null, parameterTypes, null, null);
  174. }
  175. public MethodBuilder DefineGlobalMethod (string name, MethodAttributes attributes, CallingConventions callingConvention, Type returnType, Type[] requiredReturnTypeCustomModifiers, Type[] optionalReturnTypeCustomModifiers, Type[] parameterTypes, Type[][] requiredParameterTypeCustomModifiers, Type[][] optionalParameterTypeCustomModifiers)
  176. {
  177. if (name == null)
  178. throw new ArgumentNullException ("name");
  179. if ((attributes & MethodAttributes.Static) == 0)
  180. throw new ArgumentException ("global methods must be static");
  181. if (global_type_created != null)
  182. throw new InvalidOperationException ("global methods already created");
  183. CreateGlobalType ();
  184. MethodBuilder mb = global_type.DefineMethod (name, attributes, callingConvention, returnType, requiredReturnTypeCustomModifiers, optionalReturnTypeCustomModifiers, parameterTypes, requiredParameterTypeCustomModifiers, optionalParameterTypeCustomModifiers);
  185. addGlobalMethod (mb);
  186. return mb;
  187. }
  188. public MethodBuilder DefinePInvokeMethod (string name, string dllName, MethodAttributes attributes, CallingConventions callingConvention, Type returnType, Type[] parameterTypes, CallingConvention nativeCallConv, CharSet nativeCharSet) {
  189. return DefinePInvokeMethod (name, dllName, name, attributes, callingConvention, returnType, parameterTypes, nativeCallConv, nativeCharSet);
  190. }
  191. public MethodBuilder DefinePInvokeMethod (string name, string dllName, string entryName, MethodAttributes attributes, CallingConventions callingConvention, Type returnType, Type[] parameterTypes, CallingConvention nativeCallConv, CharSet nativeCharSet) {
  192. if (name == null)
  193. throw new ArgumentNullException ("name");
  194. if ((attributes & MethodAttributes.Static) == 0)
  195. throw new ArgumentException ("global methods must be static");
  196. if (global_type_created != null)
  197. throw new InvalidOperationException ("global methods already created");
  198. CreateGlobalType ();
  199. MethodBuilder mb = global_type.DefinePInvokeMethod (name, dllName, entryName, attributes, callingConvention, returnType, parameterTypes, nativeCallConv, nativeCharSet);
  200. addGlobalMethod (mb);
  201. return mb;
  202. }
  203. public TypeBuilder DefineType (string name) {
  204. return DefineType (name, 0);
  205. }
  206. public TypeBuilder DefineType (string name, TypeAttributes attr) {
  207. if ((attr & TypeAttributes.Interface) != 0)
  208. return DefineType (name, attr, null, null);
  209. return DefineType (name, attr, typeof(object), null);
  210. }
  211. public TypeBuilder DefineType (string name, TypeAttributes attr, Type parent) {
  212. return DefineType (name, attr, parent, null);
  213. }
  214. private void AddType (TypeBuilder tb)
  215. {
  216. if (types != null) {
  217. if (types.Length == num_types) {
  218. TypeBuilder[] new_types = new TypeBuilder [types.Length * 2];
  219. System.Array.Copy (types, new_types, num_types);
  220. types = new_types;
  221. }
  222. } else {
  223. types = new TypeBuilder [1];
  224. }
  225. types [num_types] = tb;
  226. num_types ++;
  227. }
  228. private TypeBuilder DefineType (string name, TypeAttributes attr, Type parent, Type[] interfaces, PackingSize packingSize, int typesize) {
  229. if (name == null)
  230. throw new ArgumentNullException ("fullname");
  231. if (name_cache.ContainsKey (name))
  232. throw new ArgumentException ("Duplicate type name within an assembly.");
  233. TypeBuilder res = new TypeBuilder (this, name, attr, parent, interfaces, packingSize, typesize, null);
  234. AddType (res);
  235. name_cache.Add (name, res);
  236. return res;
  237. }
  238. internal void RegisterTypeName (TypeBuilder tb, string name)
  239. {
  240. name_cache.Add (name, tb);
  241. }
  242. internal TypeBuilder GetRegisteredType (string name)
  243. {
  244. return (TypeBuilder) name_cache [name];
  245. }
  246. [ComVisible (true)]
  247. public TypeBuilder DefineType (string name, TypeAttributes attr, Type parent, Type[] interfaces) {
  248. return DefineType (name, attr, parent, interfaces, PackingSize.Unspecified, TypeBuilder.UnspecifiedTypeSize);
  249. }
  250. public TypeBuilder DefineType (string name, TypeAttributes attr, Type parent, int typesize) {
  251. return DefineType (name, attr, parent, null, PackingSize.Unspecified, TypeBuilder.UnspecifiedTypeSize);
  252. }
  253. public TypeBuilder DefineType (string name, TypeAttributes attr, Type parent, PackingSize packsize) {
  254. return DefineType (name, attr, parent, null, packsize, TypeBuilder.UnspecifiedTypeSize);
  255. }
  256. public TypeBuilder DefineType (string name, TypeAttributes attr, Type parent, PackingSize packingSize, int typesize) {
  257. return DefineType (name, attr, parent, null, packingSize, typesize);
  258. }
  259. public MethodInfo GetArrayMethod( Type arrayClass, string methodName, CallingConventions callingConvention, Type returnType, Type[] parameterTypes) {
  260. return new MonoArrayMethod (arrayClass, methodName, callingConvention, returnType, parameterTypes);
  261. }
  262. public EnumBuilder DefineEnum( string name, TypeAttributes visibility, Type underlyingType) {
  263. if (name_cache.Contains (name))
  264. throw new ArgumentException ("Duplicate type name within an assembly.");
  265. EnumBuilder eb = new EnumBuilder (this, name, visibility, underlyingType);
  266. TypeBuilder res = eb.GetTypeBuilder ();
  267. AddType (res);
  268. name_cache.Add (name, res);
  269. return eb;
  270. }
  271. [ComVisible (true)]
  272. public override Type GetType( string className) {
  273. return GetType (className, false, false);
  274. }
  275. [ComVisible (true)]
  276. public override Type GetType( string className, bool ignoreCase) {
  277. return GetType (className, false, ignoreCase);
  278. }
  279. private TypeBuilder search_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].FullName, true, CultureInfo.InvariantCulture) == 0) {
  283. return arr [i];
  284. }
  285. }
  286. return null;
  287. }
  288. private TypeBuilder search_nested_in_array (TypeBuilder[] arr, int validElementsInArray, string className) {
  289. int i;
  290. for (i = 0; i < validElementsInArray; ++i) {
  291. if (String.Compare (className, arr [i].Name, true, CultureInfo.InvariantCulture) == 0)
  292. return arr [i];
  293. }
  294. return null;
  295. }
  296. [MethodImplAttribute(MethodImplOptions.InternalCall)]
  297. private static extern Type create_modified_type (TypeBuilder tb, string modifiers);
  298. static readonly char [] type_modifiers = {'&', '[', '*'};
  299. private TypeBuilder GetMaybeNested (TypeBuilder t, string className) {
  300. int subt;
  301. string pname, rname;
  302. subt = className.IndexOf ('+');
  303. if (subt < 0) {
  304. if (t.subtypes != null)
  305. return search_nested_in_array (t.subtypes, t.subtypes.Length, className);
  306. return null;
  307. }
  308. if (t.subtypes != null) {
  309. pname = className.Substring (0, subt);
  310. rname = className.Substring (subt + 1);
  311. TypeBuilder result = search_nested_in_array (t.subtypes, t.subtypes.Length, pname);
  312. if (result != null)
  313. return GetMaybeNested (result, rname);
  314. }
  315. return null;
  316. }
  317. [ComVisible (true)]
  318. public override Type GetType (string className, bool throwOnError, bool ignoreCase)
  319. {
  320. if (className == null)
  321. throw new ArgumentNullException ("className");
  322. if (className.Length == 0)
  323. throw new ArgumentException ("className");
  324. int subt;
  325. string orig = className;
  326. string modifiers;
  327. TypeBuilder result = null;
  328. if (types == null && throwOnError)
  329. throw new TypeLoadException (className);
  330. subt = className.IndexOfAny (type_modifiers);
  331. if (subt >= 0) {
  332. modifiers = className.Substring (subt);
  333. className = className.Substring (0, subt);
  334. } else
  335. modifiers = null;
  336. if (!ignoreCase) {
  337. result = name_cache [className] as TypeBuilder;
  338. } else {
  339. subt = className.IndexOf ('+');
  340. if (subt < 0) {
  341. if (types != null)
  342. result = search_in_array (types, num_types, className);
  343. } else {
  344. string pname, rname;
  345. pname = className.Substring (0, subt);
  346. rname = className.Substring (subt + 1);
  347. result = search_in_array (types, num_types, pname);
  348. if (result != null)
  349. result = GetMaybeNested (result, rname);
  350. }
  351. }
  352. if ((result == null) && throwOnError)
  353. throw new TypeLoadException (orig);
  354. if (result != null && (modifiers != null)) {
  355. Type mt = create_modified_type (result, modifiers);
  356. result = mt as TypeBuilder;
  357. if (result == null)
  358. return mt;
  359. }
  360. if (result != null && result.is_created)
  361. return result.CreateType ();
  362. else
  363. return result;
  364. }
  365. internal int get_next_table_index (object obj, int table, bool inc) {
  366. if (table_indexes == null) {
  367. table_indexes = new int [64];
  368. for (int i=0; i < 64; ++i)
  369. table_indexes [i] = 1;
  370. /* allow room for .<Module> in TypeDef table */
  371. table_indexes [0x02] = 2;
  372. }
  373. // Console.WriteLine ("getindex for table "+table.ToString()+" got "+table_indexes [table].ToString());
  374. if (inc)
  375. return table_indexes [table]++;
  376. return table_indexes [table];
  377. }
  378. public void SetCustomAttribute( CustomAttributeBuilder customBuilder) {
  379. if (cattrs != null) {
  380. CustomAttributeBuilder[] new_array = new CustomAttributeBuilder [cattrs.Length + 1];
  381. cattrs.CopyTo (new_array, 0);
  382. new_array [cattrs.Length] = customBuilder;
  383. cattrs = new_array;
  384. } else {
  385. cattrs = new CustomAttributeBuilder [1];
  386. cattrs [0] = customBuilder;
  387. }
  388. }
  389. [ComVisible (true)]
  390. public void SetCustomAttribute( ConstructorInfo con, byte[] binaryAttribute) {
  391. SetCustomAttribute (new CustomAttributeBuilder (con, binaryAttribute));
  392. }
  393. public ISymbolWriter GetSymWriter () {
  394. return symbolWriter;
  395. }
  396. public ISymbolDocumentWriter DefineDocument (string url, Guid language, Guid languageVendor, Guid documentType)
  397. {
  398. if (symbolWriter != null)
  399. return symbolWriter.DefineDocument (url, language, languageVendor, documentType);
  400. else
  401. return null;
  402. }
  403. public override Type [] GetTypes ()
  404. {
  405. if (types == null)
  406. return Type.EmptyTypes;
  407. int n = num_types;
  408. Type [] copy = new Type [n];
  409. Array.Copy (types, copy, n);
  410. // MS replaces the typebuilders with their created types
  411. for (int i = 0; i < copy.Length; ++i)
  412. if (types [i].is_created)
  413. copy [i] = types [i].CreateType ();
  414. return copy;
  415. }
  416. public IResourceWriter DefineResource (string name, string description, ResourceAttributes attribute)
  417. {
  418. if (name == null)
  419. throw new ArgumentNullException ("name");
  420. if (name == String.Empty)
  421. throw new ArgumentException ("name cannot be empty");
  422. if (transient)
  423. throw new InvalidOperationException ("The module is transient");
  424. if (!assemblyb.IsSave)
  425. throw new InvalidOperationException ("The assembly is transient");
  426. ResourceWriter writer = new ResourceWriter (new MemoryStream ());
  427. if (resource_writers == null)
  428. resource_writers = new Hashtable ();
  429. resource_writers [name] = writer;
  430. // The data is filled out later
  431. if (resources != null) {
  432. MonoResource[] new_r = new MonoResource [resources.Length + 1];
  433. System.Array.Copy(resources, new_r, resources.Length);
  434. resources = new_r;
  435. } else {
  436. resources = new MonoResource [1];
  437. }
  438. int p = resources.Length - 1;
  439. resources [p].name = name;
  440. resources [p].attrs = attribute;
  441. return writer;
  442. }
  443. public IResourceWriter DefineResource (string name, string description)
  444. {
  445. return DefineResource (name, description, ResourceAttributes.Public);
  446. }
  447. [MonoTODO]
  448. public void DefineUnmanagedResource (byte[] resource)
  449. {
  450. if (resource == null)
  451. throw new ArgumentNullException ("resource");
  452. throw new NotImplementedException ();
  453. }
  454. [MonoTODO]
  455. public void DefineUnmanagedResource (string resourceFileName)
  456. {
  457. if (resourceFileName == null)
  458. throw new ArgumentNullException ("resourceFileName");
  459. if (resourceFileName == String.Empty)
  460. throw new ArgumentException ("resourceFileName");
  461. if (!File.Exists (resourceFileName) || Directory.Exists (resourceFileName))
  462. throw new FileNotFoundException ("File '" + resourceFileName + "' does not exists or is a directory.");
  463. throw new NotImplementedException ();
  464. }
  465. public void DefineManifestResource (string name, Stream stream, ResourceAttributes attribute) {
  466. if (name == null)
  467. throw new ArgumentNullException ("name");
  468. if (name == String.Empty)
  469. throw new ArgumentException ("name cannot be empty");
  470. if (stream == null)
  471. throw new ArgumentNullException ("stream");
  472. if (transient)
  473. throw new InvalidOperationException ("The module is transient");
  474. if (!assemblyb.IsSave)
  475. throw new InvalidOperationException ("The assembly is transient");
  476. if (resources != null) {
  477. MonoResource[] new_r = new MonoResource [resources.Length + 1];
  478. System.Array.Copy(resources, new_r, resources.Length);
  479. resources = new_r;
  480. } else {
  481. resources = new MonoResource [1];
  482. }
  483. int p = resources.Length - 1;
  484. resources [p].name = name;
  485. resources [p].attrs = attribute;
  486. resources [p].stream = stream;
  487. }
  488. [MonoTODO]
  489. public void SetSymCustomAttribute (string name, byte[] data)
  490. {
  491. throw new NotImplementedException ();
  492. }
  493. [MonoTODO]
  494. public void SetUserEntryPoint (MethodInfo entryPoint)
  495. {
  496. if (entryPoint == null)
  497. throw new ArgumentNullException ("entryPoint");
  498. if (entryPoint.DeclaringType.Module != this)
  499. throw new InvalidOperationException ("entryPoint is not contained in this module");
  500. throw new NotImplementedException ();
  501. }
  502. public MethodToken GetMethodToken (MethodInfo method)
  503. {
  504. if (method == null)
  505. throw new ArgumentNullException ("method");
  506. if (method.DeclaringType.Module != this)
  507. throw new InvalidOperationException ("The method is not in this module");
  508. return new MethodToken (GetToken (method));
  509. }
  510. public MethodToken GetArrayMethodToken (Type arrayClass, string methodName, CallingConventions callingConvention, Type returnType, Type[] parameterTypes)
  511. {
  512. return GetMethodToken (GetArrayMethod (arrayClass, methodName, callingConvention, returnType, parameterTypes));
  513. }
  514. [ComVisible (true)]
  515. public MethodToken GetConstructorToken (ConstructorInfo con)
  516. {
  517. if (con == null)
  518. throw new ArgumentNullException ("con");
  519. if (con.DeclaringType.Module != this)
  520. throw new InvalidOperationException ("The constructor is not in this module");
  521. return new MethodToken (GetToken (con));
  522. }
  523. public FieldToken GetFieldToken (FieldInfo field)
  524. {
  525. if (field == null)
  526. throw new ArgumentNullException ("field");
  527. if (field.DeclaringType.Module != this)
  528. throw new InvalidOperationException ("The method is not in this module");
  529. return new FieldToken (GetToken (field));
  530. }
  531. [MonoTODO]
  532. public SignatureToken GetSignatureToken (byte[] sigBytes, int sigLength)
  533. {
  534. throw new NotImplementedException ();
  535. }
  536. public SignatureToken GetSignatureToken (SignatureHelper sigHelper)
  537. {
  538. if (sigHelper == null)
  539. throw new ArgumentNullException ("sigHelper");
  540. return new SignatureToken (GetToken (sigHelper));
  541. }
  542. public StringToken GetStringConstant (string str)
  543. {
  544. if (str == null)
  545. throw new ArgumentNullException ("str");
  546. return new StringToken (GetToken (str));
  547. }
  548. public TypeToken GetTypeToken (Type type)
  549. {
  550. if (type == null)
  551. throw new ArgumentNullException ("type");
  552. if (type.IsByRef)
  553. throw new ArgumentException ("type can't be a byref type", "type");
  554. if (!IsTransient () && (type.Module is ModuleBuilder) && ((ModuleBuilder)type.Module).IsTransient ())
  555. throw new InvalidOperationException ("a non-transient module can't reference a transient module");
  556. return new TypeToken (GetToken (type));
  557. }
  558. public TypeToken GetTypeToken (string name)
  559. {
  560. return GetTypeToken (GetType (name));
  561. }
  562. [MethodImplAttribute(MethodImplOptions.InternalCall)]
  563. private static extern int getUSIndex (ModuleBuilder mb, string str);
  564. [MethodImplAttribute(MethodImplOptions.InternalCall)]
  565. private static extern int getToken (ModuleBuilder mb, object obj, bool create_open_instance);
  566. [MethodImplAttribute(MethodImplOptions.InternalCall)]
  567. private static extern int getMethodToken (ModuleBuilder mb, MethodInfo method,
  568. Type[] opt_param_types);
  569. internal int GetToken (string str)
  570. {
  571. int result;
  572. if (!us_string_cache.TryGetValue (str, out result)) {
  573. result = getUSIndex (this, str);
  574. us_string_cache [str] = result;
  575. }
  576. return result;
  577. }
  578. internal int GetToken (MemberInfo member) {
  579. return getToken (this, member, true);
  580. }
  581. internal int GetToken (MemberInfo member, bool create_open_instance) {
  582. return getToken (this, member, create_open_instance);
  583. }
  584. internal int GetToken (MethodInfo method, Type[] opt_param_types) {
  585. return getMethodToken (this, method, opt_param_types);
  586. }
  587. internal int GetToken (SignatureHelper helper) {
  588. return getToken (this, helper, true);
  589. }
  590. /*
  591. * Register the token->obj mapping with the runtime so the Module.Resolve...
  592. * methods will work for obj.
  593. */
  594. [MethodImplAttribute(MethodImplOptions.InternalCall)]
  595. internal extern void RegisterToken (object obj, int token);
  596. internal TokenGenerator GetTokenGenerator () {
  597. if (token_gen == null)
  598. token_gen = new ModuleBuilderTokenGenerator (this);
  599. return token_gen;
  600. }
  601. [MethodImplAttribute(MethodImplOptions.InternalCall)]
  602. private static extern void build_metadata (ModuleBuilder mb);
  603. [MethodImplAttribute(MethodImplOptions.InternalCall)]
  604. private extern void WriteToFile (IntPtr handle);
  605. internal void Save ()
  606. {
  607. if (transient && !is_main)
  608. return;
  609. if (types != null) {
  610. for (int i = 0; i < num_types; ++i)
  611. if (!types [i].is_created)
  612. throw new NotSupportedException ("Type '" + types [i].FullName + "' was not completed.");
  613. }
  614. if ((global_type != null) && (global_type_created == null))
  615. global_type_created = global_type.CreateType ();
  616. if (resources != null) {
  617. for (int i = 0; i < resources.Length; ++i) {
  618. IResourceWriter rwriter;
  619. if (resource_writers != null && (rwriter = resource_writers [resources [i].name] as IResourceWriter) != null) {
  620. ResourceWriter writer = (ResourceWriter)rwriter;
  621. writer.Generate ();
  622. MemoryStream mstream = (MemoryStream)writer.Stream;
  623. resources [i].data = new byte [mstream.Length];
  624. mstream.Seek (0, SeekOrigin.Begin);
  625. mstream.Read (resources [i].data, 0, (int)mstream.Length);
  626. continue;
  627. }
  628. Stream stream = resources [i].stream;
  629. // According to MSDN docs, the stream is read during assembly save, not earlier
  630. if (stream != null) {
  631. try {
  632. long len = stream.Length;
  633. resources [i].data = new byte [len];
  634. stream.Seek (0, SeekOrigin.Begin);
  635. stream.Read (resources [i].data, 0, (int)len);
  636. } catch {
  637. /* do something */
  638. }
  639. }
  640. }
  641. }
  642. build_metadata (this);
  643. string fileName = fqname;
  644. if (assemblyb.AssemblyDir != null)
  645. fileName = Path.Combine (assemblyb.AssemblyDir, fileName);
  646. try {
  647. // We mmap the file, so unlink the previous version since it may be in use
  648. File.Delete (fileName);
  649. } catch {
  650. // We can safely ignore
  651. }
  652. using (FileStream file = new FileStream (fileName, FileMode.Create, FileAccess.Write))
  653. WriteToFile (file.Handle);
  654. //
  655. // The constant 0x80000000 is internal to Mono, it means `make executable'
  656. //
  657. File.SetAttributes (fileName, (FileAttributes) (unchecked ((int) 0x80000000)));
  658. if (types != null && symbolWriter != null) {
  659. for (int i = 0; i < num_types; ++i)
  660. types [i].GenerateDebugInfo (symbolWriter);
  661. symbolWriter.Close ();
  662. }
  663. }
  664. internal string FileName {
  665. get {
  666. return fqname;
  667. }
  668. }
  669. internal bool IsMain {
  670. set {
  671. is_main = value;
  672. }
  673. }
  674. internal void CreateGlobalType () {
  675. if (global_type == null)
  676. global_type = new TypeBuilder (this, 0, 1);
  677. }
  678. internal override Guid GetModuleVersionId ()
  679. {
  680. return new Guid (guid);
  681. }
  682. // Used by mcs, the symbol writer, and mdb through reflection
  683. internal static Guid Mono_GetGuid (ModuleBuilder mb)
  684. {
  685. return mb.GetModuleVersionId ();
  686. }
  687. void _ModuleBuilder.GetIDsOfNames ([In] ref Guid riid, IntPtr rgszNames, uint cNames, uint lcid, IntPtr rgDispId)
  688. {
  689. throw new NotImplementedException ();
  690. }
  691. void _ModuleBuilder.GetTypeInfo (uint iTInfo, uint lcid, IntPtr ppTInfo)
  692. {
  693. throw new NotImplementedException ();
  694. }
  695. void _ModuleBuilder.GetTypeInfoCount (out uint pcTInfo)
  696. {
  697. throw new NotImplementedException ();
  698. }
  699. void _ModuleBuilder.Invoke (uint dispIdMember, [In] ref Guid riid, uint lcid, short wFlags, IntPtr pDispParams, IntPtr pVarResult, IntPtr pExcepInfo, IntPtr puArgErr)
  700. {
  701. throw new NotImplementedException ();
  702. }
  703. #if NET_4_0 || MOONLIGHT || MOBILE
  704. public override Assembly Assembly {
  705. get { return assemblyb; }
  706. }
  707. public override string Name {
  708. get { return name; }
  709. }
  710. public override string ScopeName {
  711. get { return name; }
  712. }
  713. public override Guid ModuleVersionId {
  714. get {
  715. return GetModuleVersionId ();
  716. }
  717. }
  718. //XXX resource modules can't be defined with ModuleBuilder
  719. public override bool IsResource ()
  720. {
  721. return false;
  722. }
  723. protected override MethodInfo GetMethodImpl (string name, BindingFlags bindingAttr, Binder binder, CallingConventions callConvention, Type[] types, ParameterModifier[] modifiers)
  724. {
  725. if (global_type_created == null)
  726. return null;
  727. if (types == null)
  728. return global_type_created.GetMethod (name);
  729. return global_type_created.GetMethod (name, bindingAttr, binder, callConvention, types, modifiers);
  730. }
  731. public override FieldInfo ResolveField (int metadataToken, Type [] genericTypeArguments, Type [] genericMethodArguments) {
  732. ResolveTokenError error;
  733. IntPtr handle = ResolveFieldToken (_impl, metadataToken, ptrs_from_types (genericTypeArguments), ptrs_from_types (genericMethodArguments), out error);
  734. if (handle == IntPtr.Zero)
  735. throw resolve_token_exception (metadataToken, error, "Field");
  736. else
  737. return FieldInfo.GetFieldFromHandle (new RuntimeFieldHandle (handle));
  738. }
  739. public override MemberInfo ResolveMember (int metadataToken, Type [] genericTypeArguments, Type [] genericMethodArguments) {
  740. ResolveTokenError error;
  741. MemberInfo m = ResolveMemberToken (_impl, metadataToken, ptrs_from_types (genericTypeArguments), ptrs_from_types (genericMethodArguments), out error);
  742. if (m == null)
  743. throw resolve_token_exception (metadataToken, error, "MemberInfo");
  744. else
  745. return m;
  746. }
  747. public override MethodBase ResolveMethod (int metadataToken, Type [] genericTypeArguments, Type [] genericMethodArguments) {
  748. ResolveTokenError error;
  749. IntPtr handle = ResolveMethodToken (_impl, metadataToken, ptrs_from_types (genericTypeArguments), ptrs_from_types (genericMethodArguments), out error);
  750. if (handle == IntPtr.Zero)
  751. throw resolve_token_exception (metadataToken, error, "MethodBase");
  752. else
  753. return MethodBase.GetMethodFromHandleNoGenericCheck (new RuntimeMethodHandle (handle));
  754. }
  755. public override string ResolveString (int metadataToken) {
  756. ResolveTokenError error;
  757. string s = ResolveStringToken (_impl, metadataToken, out error);
  758. if (s == null)
  759. throw resolve_token_exception (metadataToken, error, "string");
  760. else
  761. return s;
  762. }
  763. public override byte[] ResolveSignature (int metadataToken) {
  764. ResolveTokenError error;
  765. byte[] res = ResolveSignature (_impl, metadataToken, out error);
  766. if (res == null)
  767. throw resolve_token_exception (metadataToken, error, "signature");
  768. else
  769. return res;
  770. }
  771. public override Type ResolveType (int metadataToken, Type [] genericTypeArguments, Type [] genericMethodArguments) {
  772. ResolveTokenError error;
  773. IntPtr handle = ResolveTypeToken (_impl, metadataToken, ptrs_from_types (genericTypeArguments), ptrs_from_types (genericMethodArguments), out error);
  774. if (handle == IntPtr.Zero)
  775. throw resolve_token_exception (metadataToken, error, "Type");
  776. else
  777. return Type.GetTypeFromHandle (new RuntimeTypeHandle (handle));
  778. }
  779. #endif
  780. }
  781. internal class ModuleBuilderTokenGenerator : TokenGenerator {
  782. private ModuleBuilder mb;
  783. public ModuleBuilderTokenGenerator (ModuleBuilder mb) {
  784. this.mb = mb;
  785. }
  786. public int GetToken (string str) {
  787. return mb.GetToken (str);
  788. }
  789. public int GetToken (MemberInfo member, bool create_open_instance) {
  790. return mb.GetToken (member, create_open_instance);
  791. }
  792. public int GetToken (MethodInfo method, Type[] opt_param_types) {
  793. return mb.GetToken (method, opt_param_types);
  794. }
  795. public int GetToken (SignatureHelper helper) {
  796. return mb.GetToken (helper);
  797. }
  798. }
  799. }