ModuleBuilder.cs 31 KB

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