ModuleBuilder.cs 32 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996
  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. [StructLayout (LayoutKind.Sequential)]
  46. public class ModuleBuilder : Module, _ModuleBuilder {
  47. #pragma warning disable 169, 414
  48. #region Sync with object-internals.h
  49. private UIntPtr dynamic_image; /* GC-tracked */
  50. private int num_types;
  51. private TypeBuilder[] types;
  52. private CustomAttributeBuilder[] cattrs;
  53. private byte[] guid;
  54. private int table_idx;
  55. internal AssemblyBuilder assemblyb;
  56. private MethodBuilder[] global_methods;
  57. private FieldBuilder[] global_fields;
  58. bool is_main;
  59. private MonoResource[] resources;
  60. #endregion
  61. #pragma warning restore 169, 414
  62. private TypeBuilder global_type;
  63. private Type global_type_created;
  64. Hashtable name_cache;
  65. Dictionary<string, int> us_string_cache;
  66. private int[] table_indexes;
  67. bool transient;
  68. ModuleBuilderTokenGenerator token_gen;
  69. Hashtable resource_writers;
  70. ISymbolWriter symbolWriter;
  71. [MethodImplAttribute(MethodImplOptions.InternalCall)]
  72. private static extern void basic_init (ModuleBuilder ab);
  73. [MethodImplAttribute(MethodImplOptions.InternalCall)]
  74. private static extern void set_wrappers_type (ModuleBuilder mb, Type ab);
  75. internal ModuleBuilder (AssemblyBuilder assb, string name, string fullyqname, bool emitSymbolInfo, bool transient) {
  76. this.name = this.scopename = name;
  77. this.fqname = fullyqname;
  78. this.assembly = this.assemblyb = assb;
  79. this.transient = transient;
  80. // to keep mcs fast we do not want CryptoConfig wo be involved to create the RNG
  81. guid = Guid.FastNewGuidArray ();
  82. // guid = Guid.NewGuid().ToByteArray ();
  83. table_idx = get_next_table_index (this, 0x00, true);
  84. name_cache = new Hashtable ();
  85. us_string_cache = new Dictionary<string, int> (512);
  86. basic_init (this);
  87. CreateGlobalType ();
  88. if (assb.IsRun) {
  89. TypeBuilder tb = new TypeBuilder (this, TypeAttributes.Abstract, 0xFFFFFF); /*last valid token*/
  90. Type type = tb.CreateType ();
  91. set_wrappers_type (this, type);
  92. }
  93. if (emitSymbolInfo) {
  94. #if MOONLIGHT
  95. symbolWriter = new Mono.CompilerServices.SymbolWriter.SymbolWriterImpl (this);
  96. #else
  97. Assembly asm = Assembly.LoadWithPartialName ("Mono.CompilerServices.SymbolWriter");
  98. if (asm == null)
  99. throw new TypeLoadException ("The assembly for default symbol writer cannot be loaded");
  100. Type t = asm.GetType ("Mono.CompilerServices.SymbolWriter.SymbolWriterImpl", true);
  101. symbolWriter = (ISymbolWriter) Activator.CreateInstance (t, new object[] { this });
  102. #endif
  103. string fileName = fqname;
  104. if (assemblyb.AssemblyDir != null)
  105. fileName = Path.Combine (assemblyb.AssemblyDir, fileName);
  106. symbolWriter.Initialize (IntPtr.Zero, fileName, true);
  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. {
  130. if (name == null)
  131. throw new ArgumentNullException ("name");
  132. if (global_type_created != null)
  133. throw new InvalidOperationException ("global fields already created");
  134. if ((size <= 0) || (size > 0x3f0000))
  135. throw new ArgumentException ("size", "Data size must be > 0 and < 0x3f0000");
  136. CreateGlobalType ();
  137. string typeName = "$ArrayType$" + size;
  138. Type datablobtype = GetType (typeName, false, false);
  139. if (datablobtype == null) {
  140. TypeBuilder tb = DefineType (typeName,
  141. TypeAttributes.Public|TypeAttributes.ExplicitLayout|TypeAttributes.Sealed,
  142. assemblyb.corlib_value_type, null, PackingSize.Size1, size);
  143. tb.CreateType ();
  144. datablobtype = tb;
  145. }
  146. FieldBuilder fb = global_type.DefineField (name, datablobtype, attributes|FieldAttributes.Static);
  147. if (global_fields != null) {
  148. FieldBuilder[] new_fields = new FieldBuilder [global_fields.Length+1];
  149. System.Array.Copy (global_fields, new_fields, global_fields.Length);
  150. new_fields [global_fields.Length] = fb;
  151. global_fields = new_fields;
  152. } else {
  153. global_fields = new FieldBuilder [1];
  154. global_fields [0] = fb;
  155. }
  156. return fb;
  157. }
  158. private void addGlobalMethod (MethodBuilder mb) {
  159. if (global_methods != null) {
  160. MethodBuilder[] new_methods = new MethodBuilder [global_methods.Length+1];
  161. System.Array.Copy (global_methods, new_methods, global_methods.Length);
  162. new_methods [global_methods.Length] = mb;
  163. global_methods = new_methods;
  164. } else {
  165. global_methods = new MethodBuilder [1];
  166. global_methods [0] = mb;
  167. }
  168. }
  169. public MethodBuilder DefineGlobalMethod (string name, MethodAttributes attributes, Type returnType, Type[] parameterTypes)
  170. {
  171. return DefineGlobalMethod (name, attributes, CallingConventions.Standard, returnType, parameterTypes);
  172. }
  173. public MethodBuilder DefineGlobalMethod (string name, MethodAttributes attributes, CallingConventions callingConvention, Type returnType, Type[] parameterTypes) {
  174. return DefineGlobalMethod (name, attributes, callingConvention, returnType, null, null, parameterTypes, null, null);
  175. }
  176. public MethodBuilder DefineGlobalMethod (string name, MethodAttributes attributes, CallingConventions callingConvention, Type returnType, Type[] requiredReturnTypeCustomModifiers, Type[] optionalReturnTypeCustomModifiers, Type[] parameterTypes, Type[][] requiredParameterTypeCustomModifiers, Type[][] optionalParameterTypeCustomModifiers)
  177. {
  178. if (name == null)
  179. throw new ArgumentNullException ("name");
  180. if ((attributes & MethodAttributes.Static) == 0)
  181. throw new ArgumentException ("global methods must be static");
  182. if (global_type_created != null)
  183. throw new InvalidOperationException ("global methods already created");
  184. CreateGlobalType ();
  185. MethodBuilder mb = global_type.DefineMethod (name, attributes, callingConvention, returnType, requiredReturnTypeCustomModifiers, optionalReturnTypeCustomModifiers, parameterTypes, requiredParameterTypeCustomModifiers, optionalParameterTypeCustomModifiers);
  186. addGlobalMethod (mb);
  187. return mb;
  188. }
  189. public MethodBuilder DefinePInvokeMethod (string name, string dllName, MethodAttributes attributes, CallingConventions callingConvention, Type returnType, Type[] parameterTypes, CallingConvention nativeCallConv, CharSet nativeCharSet) {
  190. return DefinePInvokeMethod (name, dllName, name, attributes, callingConvention, returnType, parameterTypes, nativeCallConv, nativeCharSet);
  191. }
  192. public MethodBuilder DefinePInvokeMethod (string name, string dllName, string entryName, MethodAttributes attributes, CallingConventions callingConvention, Type returnType, Type[] parameterTypes, CallingConvention nativeCallConv, CharSet nativeCharSet) {
  193. if (name == null)
  194. throw new ArgumentNullException ("name");
  195. if ((attributes & MethodAttributes.Static) == 0)
  196. throw new ArgumentException ("global methods must be static");
  197. if (global_type_created != null)
  198. throw new InvalidOperationException ("global methods already created");
  199. CreateGlobalType ();
  200. MethodBuilder mb = global_type.DefinePInvokeMethod (name, dllName, entryName, attributes, callingConvention, returnType, parameterTypes, nativeCallConv, nativeCharSet);
  201. addGlobalMethod (mb);
  202. return mb;
  203. }
  204. public TypeBuilder DefineType (string name) {
  205. return DefineType (name, 0);
  206. }
  207. public TypeBuilder DefineType (string name, TypeAttributes attr) {
  208. if ((attr & TypeAttributes.Interface) != 0)
  209. return DefineType (name, attr, null, null);
  210. return DefineType (name, attr, typeof(object), null);
  211. }
  212. public TypeBuilder DefineType (string name, TypeAttributes attr, Type parent) {
  213. return DefineType (name, attr, parent, null);
  214. }
  215. private void AddType (TypeBuilder tb)
  216. {
  217. if (types != null) {
  218. if (types.Length == num_types) {
  219. TypeBuilder[] new_types = new TypeBuilder [types.Length * 2];
  220. System.Array.Copy (types, new_types, num_types);
  221. types = new_types;
  222. }
  223. } else {
  224. types = new TypeBuilder [1];
  225. }
  226. types [num_types] = tb;
  227. num_types ++;
  228. }
  229. private TypeBuilder DefineType (string name, TypeAttributes attr, Type parent, Type[] interfaces, PackingSize packingSize, int typesize) {
  230. if (name == null)
  231. throw new ArgumentNullException ("fullname");
  232. if (name_cache.ContainsKey (name))
  233. throw new ArgumentException ("Duplicate type name within an assembly.");
  234. TypeBuilder res = new TypeBuilder (this, name, attr, parent, interfaces, packingSize, typesize, null);
  235. AddType (res);
  236. name_cache.Add (name, res);
  237. return res;
  238. }
  239. internal void RegisterTypeName (TypeBuilder tb, string name)
  240. {
  241. name_cache.Add (name, tb);
  242. }
  243. internal TypeBuilder GetRegisteredType (string name)
  244. {
  245. return (TypeBuilder) name_cache [name];
  246. }
  247. [ComVisible (true)]
  248. public TypeBuilder DefineType (string name, TypeAttributes attr, Type parent, Type[] interfaces) {
  249. return DefineType (name, attr, parent, interfaces, PackingSize.Unspecified, TypeBuilder.UnspecifiedTypeSize);
  250. }
  251. public TypeBuilder DefineType (string name, TypeAttributes attr, Type parent, int typesize) {
  252. return DefineType (name, attr, parent, null, PackingSize.Unspecified, TypeBuilder.UnspecifiedTypeSize);
  253. }
  254. public TypeBuilder DefineType (string name, TypeAttributes attr, Type parent, PackingSize packsize) {
  255. return DefineType (name, attr, parent, null, packsize, TypeBuilder.UnspecifiedTypeSize);
  256. }
  257. public TypeBuilder DefineType (string name, TypeAttributes attr, Type parent, PackingSize packingSize, int typesize) {
  258. return DefineType (name, attr, parent, null, packingSize, typesize);
  259. }
  260. public MethodInfo GetArrayMethod( Type arrayClass, string methodName, CallingConventions callingConvention, Type returnType, Type[] parameterTypes) {
  261. return new MonoArrayMethod (arrayClass, methodName, callingConvention, returnType, parameterTypes);
  262. }
  263. public EnumBuilder DefineEnum( string name, TypeAttributes visibility, Type underlyingType) {
  264. if (name_cache.Contains (name))
  265. throw new ArgumentException ("Duplicate type name within an assembly.");
  266. EnumBuilder eb = new EnumBuilder (this, name, visibility, underlyingType);
  267. TypeBuilder res = eb.GetTypeBuilder ();
  268. AddType (res);
  269. name_cache.Add (name, res);
  270. return eb;
  271. }
  272. [ComVisible (true)]
  273. public override Type GetType( string className) {
  274. return GetType (className, false, false);
  275. }
  276. [ComVisible (true)]
  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. [ComVisible (true)]
  319. public override Type GetType (string className, bool throwOnError, bool ignoreCase)
  320. {
  321. if (className == null)
  322. throw new ArgumentNullException ("className");
  323. if (className.Length == 0)
  324. throw new ArgumentException ("className");
  325. int subt;
  326. string orig = className;
  327. string modifiers;
  328. TypeBuilder result = null;
  329. if (types == null && throwOnError)
  330. throw new TypeLoadException (className);
  331. subt = className.IndexOfAny (type_modifiers);
  332. if (subt >= 0) {
  333. modifiers = className.Substring (subt);
  334. className = className.Substring (0, subt);
  335. } else
  336. modifiers = null;
  337. if (!ignoreCase) {
  338. result = name_cache [className] as TypeBuilder;
  339. } else {
  340. subt = className.IndexOf ('+');
  341. if (subt < 0) {
  342. if (types != null)
  343. result = search_in_array (types, num_types, className);
  344. } else {
  345. string pname, rname;
  346. pname = className.Substring (0, subt);
  347. rname = className.Substring (subt + 1);
  348. result = search_in_array (types, num_types, pname);
  349. if (result != null)
  350. result = GetMaybeNested (result, rname);
  351. }
  352. }
  353. if ((result == null) && throwOnError)
  354. throw new TypeLoadException (orig);
  355. if (result != null && (modifiers != null)) {
  356. Type mt = create_modified_type (result, modifiers);
  357. result = mt as TypeBuilder;
  358. if (result == null)
  359. return mt;
  360. }
  361. if (result != null && result.is_created)
  362. return result.CreateType ();
  363. else
  364. return result;
  365. }
  366. internal int get_next_table_index (object obj, int table, bool inc) {
  367. if (table_indexes == null) {
  368. table_indexes = new int [64];
  369. for (int i=0; i < 64; ++i)
  370. table_indexes [i] = 1;
  371. /* allow room for .<Module> in TypeDef table */
  372. table_indexes [0x02] = 2;
  373. }
  374. // Console.WriteLine ("getindex for table "+table.ToString()+" got "+table_indexes [table].ToString());
  375. if (inc)
  376. return table_indexes [table]++;
  377. return table_indexes [table];
  378. }
  379. public void SetCustomAttribute( CustomAttributeBuilder customBuilder) {
  380. if (cattrs != null) {
  381. CustomAttributeBuilder[] new_array = new CustomAttributeBuilder [cattrs.Length + 1];
  382. cattrs.CopyTo (new_array, 0);
  383. new_array [cattrs.Length] = customBuilder;
  384. cattrs = new_array;
  385. } else {
  386. cattrs = new CustomAttributeBuilder [1];
  387. cattrs [0] = customBuilder;
  388. }
  389. }
  390. [ComVisible (true)]
  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 Type.EmptyTypes;
  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. public void DefineManifestResource (string name, Stream stream, ResourceAttributes attribute) {
  467. if (name == null)
  468. throw new ArgumentNullException ("name");
  469. if (name == String.Empty)
  470. throw new ArgumentException ("name cannot be empty");
  471. if (stream == null)
  472. throw new ArgumentNullException ("stream");
  473. if (transient)
  474. throw new InvalidOperationException ("The module is transient");
  475. if (!assemblyb.IsSave)
  476. throw new InvalidOperationException ("The assembly is transient");
  477. if (resources != null) {
  478. MonoResource[] new_r = new MonoResource [resources.Length + 1];
  479. System.Array.Copy(resources, new_r, resources.Length);
  480. resources = new_r;
  481. } else {
  482. resources = new MonoResource [1];
  483. }
  484. int p = resources.Length - 1;
  485. resources [p].name = name;
  486. resources [p].attrs = attribute;
  487. resources [p].stream = stream;
  488. }
  489. [MonoTODO]
  490. public void SetSymCustomAttribute (string name, byte[] data)
  491. {
  492. throw new NotImplementedException ();
  493. }
  494. [MonoTODO]
  495. public void SetUserEntryPoint (MethodInfo entryPoint)
  496. {
  497. if (entryPoint == null)
  498. throw new ArgumentNullException ("entryPoint");
  499. if (entryPoint.DeclaringType.Module != this)
  500. throw new InvalidOperationException ("entryPoint is not contained in this module");
  501. throw new NotImplementedException ();
  502. }
  503. public MethodToken GetMethodToken (MethodInfo method)
  504. {
  505. if (method == null)
  506. throw new ArgumentNullException ("method");
  507. if (method.DeclaringType.Module != this)
  508. throw new InvalidOperationException ("The method is not in this module");
  509. return new MethodToken (GetToken (method));
  510. }
  511. public MethodToken GetArrayMethodToken (Type arrayClass, string methodName, CallingConventions callingConvention, Type returnType, Type[] parameterTypes)
  512. {
  513. return GetMethodToken (GetArrayMethod (arrayClass, methodName, callingConvention, returnType, parameterTypes));
  514. }
  515. [ComVisible (true)]
  516. public MethodToken GetConstructorToken (ConstructorInfo con)
  517. {
  518. if (con == null)
  519. throw new ArgumentNullException ("con");
  520. if (con.DeclaringType.Module != this)
  521. throw new InvalidOperationException ("The constructor is not in this module");
  522. return new MethodToken (GetToken (con));
  523. }
  524. public FieldToken GetFieldToken (FieldInfo field)
  525. {
  526. if (field == null)
  527. throw new ArgumentNullException ("field");
  528. if (field.DeclaringType.Module != this)
  529. throw new InvalidOperationException ("The method is not in this module");
  530. return new FieldToken (GetToken (field));
  531. }
  532. [MonoTODO]
  533. public SignatureToken GetSignatureToken (byte[] sigBytes, int sigLength)
  534. {
  535. throw new NotImplementedException ();
  536. }
  537. public SignatureToken GetSignatureToken (SignatureHelper sigHelper)
  538. {
  539. if (sigHelper == null)
  540. throw new ArgumentNullException ("sigHelper");
  541. return new SignatureToken (GetToken (sigHelper));
  542. }
  543. public StringToken GetStringConstant (string str)
  544. {
  545. if (str == null)
  546. throw new ArgumentNullException ("str");
  547. return new StringToken (GetToken (str));
  548. }
  549. public TypeToken GetTypeToken (Type type)
  550. {
  551. if (type == null)
  552. throw new ArgumentNullException ("type");
  553. if (type.IsByRef)
  554. throw new ArgumentException ("type can't be a byref type", "type");
  555. if (!IsTransient () && (type.Module is ModuleBuilder) && ((ModuleBuilder)type.Module).IsTransient ())
  556. throw new InvalidOperationException ("a non-transient module can't reference a transient module");
  557. return new TypeToken (GetToken (type));
  558. }
  559. public TypeToken GetTypeToken (string name)
  560. {
  561. return GetTypeToken (GetType (name));
  562. }
  563. [MethodImplAttribute(MethodImplOptions.InternalCall)]
  564. private static extern int getUSIndex (ModuleBuilder mb, string str);
  565. [MethodImplAttribute(MethodImplOptions.InternalCall)]
  566. private static extern int getToken (ModuleBuilder mb, object obj, bool create_open_instance);
  567. [MethodImplAttribute(MethodImplOptions.InternalCall)]
  568. private static extern int getMethodToken (ModuleBuilder mb, MethodInfo method,
  569. Type[] opt_param_types);
  570. internal int GetToken (string str)
  571. {
  572. int result;
  573. if (!us_string_cache.TryGetValue (str, out result)) {
  574. result = getUSIndex (this, str);
  575. us_string_cache [str] = result;
  576. }
  577. return result;
  578. }
  579. internal int GetToken (MemberInfo member) {
  580. return getToken (this, member, true);
  581. }
  582. internal int GetToken (MemberInfo member, bool create_open_instance) {
  583. return getToken (this, member, create_open_instance);
  584. }
  585. internal int GetToken (MethodInfo method, Type[] opt_param_types) {
  586. return getMethodToken (this, method, opt_param_types);
  587. }
  588. internal int GetToken (SignatureHelper helper) {
  589. return getToken (this, helper, true);
  590. }
  591. /*
  592. * Register the token->obj mapping with the runtime so the Module.Resolve...
  593. * methods will work for obj.
  594. */
  595. [MethodImplAttribute(MethodImplOptions.InternalCall)]
  596. internal extern void RegisterToken (object obj, int token);
  597. internal TokenGenerator GetTokenGenerator () {
  598. if (token_gen == null)
  599. token_gen = new ModuleBuilderTokenGenerator (this);
  600. return token_gen;
  601. }
  602. [MethodImplAttribute(MethodImplOptions.InternalCall)]
  603. private static extern void build_metadata (ModuleBuilder mb);
  604. [MethodImplAttribute(MethodImplOptions.InternalCall)]
  605. private extern void WriteToFile (IntPtr handle);
  606. internal void Save ()
  607. {
  608. if (transient && !is_main)
  609. return;
  610. if (types != null) {
  611. for (int i = 0; i < num_types; ++i)
  612. if (!types [i].is_created)
  613. throw new NotSupportedException ("Type '" + types [i].FullName + "' was not completed.");
  614. }
  615. if ((global_type != null) && (global_type_created == null))
  616. global_type_created = global_type.CreateType ();
  617. if (resources != null) {
  618. for (int i = 0; i < resources.Length; ++i) {
  619. IResourceWriter rwriter;
  620. if (resource_writers != null && (rwriter = resource_writers [resources [i].name] as IResourceWriter) != null) {
  621. ResourceWriter writer = (ResourceWriter)rwriter;
  622. writer.Generate ();
  623. MemoryStream mstream = (MemoryStream)writer.Stream;
  624. resources [i].data = new byte [mstream.Length];
  625. mstream.Seek (0, SeekOrigin.Begin);
  626. mstream.Read (resources [i].data, 0, (int)mstream.Length);
  627. continue;
  628. }
  629. Stream stream = resources [i].stream;
  630. // According to MSDN docs, the stream is read during assembly save, not earlier
  631. if (stream != null) {
  632. try {
  633. long len = stream.Length;
  634. resources [i].data = new byte [len];
  635. stream.Seek (0, SeekOrigin.Begin);
  636. stream.Read (resources [i].data, 0, (int)len);
  637. } catch {
  638. /* do something */
  639. }
  640. }
  641. }
  642. }
  643. build_metadata (this);
  644. string fileName = fqname;
  645. if (assemblyb.AssemblyDir != null)
  646. fileName = Path.Combine (assemblyb.AssemblyDir, fileName);
  647. try {
  648. // We mmap the file, so unlink the previous version since it may be in use
  649. File.Delete (fileName);
  650. } catch {
  651. // We can safely ignore
  652. }
  653. using (FileStream file = new FileStream (fileName, FileMode.Create, FileAccess.Write))
  654. WriteToFile (file.Handle);
  655. //
  656. // The constant 0x80000000 is internal to Mono, it means `make executable'
  657. //
  658. File.SetAttributes (fileName, (FileAttributes) (unchecked ((int) 0x80000000)));
  659. if (types != null && symbolWriter != null) {
  660. for (int i = 0; i < num_types; ++i)
  661. types [i].GenerateDebugInfo (symbolWriter);
  662. symbolWriter.Close ();
  663. }
  664. }
  665. internal string FileName {
  666. get {
  667. return fqname;
  668. }
  669. }
  670. internal bool IsMain {
  671. set {
  672. is_main = value;
  673. }
  674. }
  675. internal void CreateGlobalType () {
  676. if (global_type == null)
  677. global_type = new TypeBuilder (this, 0, 1);
  678. }
  679. internal override Guid GetModuleVersionId ()
  680. {
  681. return new Guid (guid);
  682. }
  683. // Used by mcs, the symbol writer, and mdb through reflection
  684. internal static Guid Mono_GetGuid (ModuleBuilder mb)
  685. {
  686. return mb.GetModuleVersionId ();
  687. }
  688. void _ModuleBuilder.GetIDsOfNames ([In] ref Guid riid, IntPtr rgszNames, uint cNames, uint lcid, IntPtr rgDispId)
  689. {
  690. throw new NotImplementedException ();
  691. }
  692. void _ModuleBuilder.GetTypeInfo (uint iTInfo, uint lcid, IntPtr ppTInfo)
  693. {
  694. throw new NotImplementedException ();
  695. }
  696. void _ModuleBuilder.GetTypeInfoCount (out uint pcTInfo)
  697. {
  698. throw new NotImplementedException ();
  699. }
  700. void _ModuleBuilder.Invoke (uint dispIdMember, [In] ref Guid riid, uint lcid, short wFlags, IntPtr pDispParams, IntPtr pVarResult, IntPtr pExcepInfo, IntPtr puArgErr)
  701. {
  702. throw new NotImplementedException ();
  703. }
  704. #if NET_4_0 || MOONLIGHT || MOBILE
  705. public override Assembly Assembly {
  706. get { return assemblyb; }
  707. }
  708. public override string Name {
  709. get { return name; }
  710. }
  711. public override string ScopeName {
  712. get { return name; }
  713. }
  714. public override Guid ModuleVersionId {
  715. get {
  716. return GetModuleVersionId ();
  717. }
  718. }
  719. //XXX resource modules can't be defined with ModuleBuilder
  720. public override bool IsResource ()
  721. {
  722. return false;
  723. }
  724. protected override MethodInfo GetMethodImpl (string name, BindingFlags bindingAttr, Binder binder, CallingConventions callConvention, Type[] types, ParameterModifier[] modifiers)
  725. {
  726. if (global_type_created == null)
  727. return null;
  728. if (types == null)
  729. return global_type_created.GetMethod (name);
  730. return global_type_created.GetMethod (name, bindingAttr, binder, callConvention, types, modifiers);
  731. }
  732. public override FieldInfo ResolveField (int metadataToken, Type [] genericTypeArguments, Type [] genericMethodArguments) {
  733. ResolveTokenError error;
  734. IntPtr handle = ResolveFieldToken (_impl, metadataToken, ptrs_from_types (genericTypeArguments), ptrs_from_types (genericMethodArguments), out error);
  735. if (handle == IntPtr.Zero)
  736. throw resolve_token_exception (metadataToken, error, "Field");
  737. else
  738. return FieldInfo.GetFieldFromHandle (new RuntimeFieldHandle (handle));
  739. }
  740. public override MemberInfo ResolveMember (int metadataToken, Type [] genericTypeArguments, Type [] genericMethodArguments) {
  741. ResolveTokenError error;
  742. MemberInfo m = ResolveMemberToken (_impl, metadataToken, ptrs_from_types (genericTypeArguments), ptrs_from_types (genericMethodArguments), out error);
  743. if (m == null)
  744. throw resolve_token_exception (metadataToken, error, "MemberInfo");
  745. else
  746. return m;
  747. }
  748. public override MethodBase ResolveMethod (int metadataToken, Type [] genericTypeArguments, Type [] genericMethodArguments) {
  749. ResolveTokenError error;
  750. IntPtr handle = ResolveMethodToken (_impl, metadataToken, ptrs_from_types (genericTypeArguments), ptrs_from_types (genericMethodArguments), out error);
  751. if (handle == IntPtr.Zero)
  752. throw resolve_token_exception (metadataToken, error, "MethodBase");
  753. else
  754. return MethodBase.GetMethodFromHandleNoGenericCheck (new RuntimeMethodHandle (handle));
  755. }
  756. public override string ResolveString (int metadataToken) {
  757. ResolveTokenError error;
  758. string s = ResolveStringToken (_impl, metadataToken, out error);
  759. if (s == null)
  760. throw resolve_token_exception (metadataToken, error, "string");
  761. else
  762. return s;
  763. }
  764. public override byte[] ResolveSignature (int metadataToken) {
  765. ResolveTokenError error;
  766. byte[] res = ResolveSignature (_impl, metadataToken, out error);
  767. if (res == null)
  768. throw resolve_token_exception (metadataToken, error, "signature");
  769. else
  770. return res;
  771. }
  772. public override Type ResolveType (int metadataToken, Type [] genericTypeArguments, Type [] genericMethodArguments) {
  773. ResolveTokenError error;
  774. IntPtr handle = ResolveTypeToken (_impl, metadataToken, ptrs_from_types (genericTypeArguments), ptrs_from_types (genericMethodArguments), out error);
  775. if (handle == IntPtr.Zero)
  776. throw resolve_token_exception (metadataToken, error, "Type");
  777. else
  778. return Type.GetTypeFromHandle (new RuntimeTypeHandle (handle));
  779. }
  780. public override bool Equals (object obj)
  781. {
  782. return base.Equals (obj);
  783. }
  784. public override int GetHashCode ()
  785. {
  786. return base.GetHashCode ();
  787. }
  788. public override bool IsDefined (Type attributeType, bool inherit)
  789. {
  790. return base.IsDefined (attributeType, inherit);
  791. }
  792. public override object[] GetCustomAttributes (bool inherit)
  793. {
  794. return base.GetCustomAttributes (inherit);
  795. }
  796. public override object[] GetCustomAttributes (Type attributeType, bool inherit)
  797. {
  798. return base.GetCustomAttributes (attributeType, inherit);
  799. }
  800. public override FieldInfo GetField (string name, BindingFlags bindingAttr)
  801. {
  802. return base.GetField (name, bindingAttr);
  803. }
  804. public override FieldInfo[] GetFields (BindingFlags bindingFlags)
  805. {
  806. return base.GetFields (bindingFlags);
  807. }
  808. public override MethodInfo[] GetMethods (BindingFlags bindingFlags)
  809. {
  810. return base.GetMethods (bindingFlags);
  811. }
  812. public override int MetadataToken {
  813. get {
  814. return base.MetadataToken;
  815. }
  816. }
  817. #endif
  818. }
  819. internal class ModuleBuilderTokenGenerator : TokenGenerator {
  820. private ModuleBuilder mb;
  821. public ModuleBuilderTokenGenerator (ModuleBuilder mb) {
  822. this.mb = mb;
  823. }
  824. public int GetToken (string str) {
  825. return mb.GetToken (str);
  826. }
  827. public int GetToken (MemberInfo member, bool create_open_instance) {
  828. return mb.GetToken (member, create_open_instance);
  829. }
  830. public int GetToken (MethodInfo method, Type[] opt_param_types) {
  831. return mb.GetToken (method, opt_param_types);
  832. }
  833. public int GetToken (SignatureHelper helper) {
  834. return mb.GetToken (helper);
  835. }
  836. }
  837. }