ModuleBuilder.cs 31 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951
  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. 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
  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. }