ModuleBuilder.cs 32 KB

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