ModuleBuilder.cs 27 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856
  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.Runtime.CompilerServices;
  35. using System.Runtime.InteropServices;
  36. using System.Diagnostics.SymbolStore;
  37. using System.IO;
  38. using System.Resources;
  39. using System.Globalization;
  40. namespace System.Reflection.Emit {
  41. #if NET_2_0
  42. [ComVisible (true)]
  43. [ComDefaultInterface (typeof (_ModuleBuilder))]
  44. #endif
  45. [ClassInterface (ClassInterfaceType.None)]
  46. public class ModuleBuilder : Module, _ModuleBuilder {
  47. #pragma warning disable 169, 414
  48. #region Sync with object-internals.h
  49. private UIntPtr dynamic_image; /* GC-tracked */
  50. private int num_types;
  51. private TypeBuilder[] types;
  52. private CustomAttributeBuilder[] cattrs;
  53. private byte[] guid;
  54. private int table_idx;
  55. internal AssemblyBuilder assemblyb;
  56. private MethodBuilder[] global_methods;
  57. private FieldBuilder[] global_fields;
  58. bool is_main;
  59. private MonoResource[] resources;
  60. #endregion
  61. #pragma warning restore 169, 414
  62. private TypeBuilder global_type;
  63. private Type global_type_created;
  64. Hashtable name_cache;
  65. Hashtable us_string_cache = new Hashtable ();
  66. private int[] table_indexes;
  67. bool transient;
  68. ModuleBuilderTokenGenerator token_gen;
  69. Hashtable resource_writers;
  70. ISymbolWriter symbolWriter;
  71. [MethodImplAttribute(MethodImplOptions.InternalCall)]
  72. private static extern void basic_init (ModuleBuilder ab);
  73. [MethodImplAttribute(MethodImplOptions.InternalCall)]
  74. private static extern void set_wrappers_type (ModuleBuilder mb, Type ab);
  75. internal ModuleBuilder (AssemblyBuilder assb, string name, string fullyqname, bool emitSymbolInfo, bool transient) {
  76. this.name = this.scopename = name;
  77. this.fqname = fullyqname;
  78. this.assembly = this.assemblyb = assb;
  79. this.transient = transient;
  80. // to keep mcs fast we do not want CryptoConfig wo be involved to create the RNG
  81. guid = Guid.FastNewGuidArray ();
  82. // guid = Guid.NewGuid().ToByteArray ();
  83. table_idx = get_next_table_index (this, 0x00, true);
  84. name_cache = new Hashtable ();
  85. 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. Assembly asm = Assembly.LoadWithPartialName ("Mono.CompilerServices.SymbolWriter");
  94. if (asm == null)
  95. throw new ExecutionEngineException ("The assembly for default symbol writer cannot be loaded");
  96. Type t = asm.GetType ("Mono.CompilerServices.SymbolWriter.SymbolWriterImpl");
  97. if (t == null)
  98. throw new ExecutionEngineException ("The type that implements the default symbol writer interface cannot be found");
  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. #if NET_2_0 || BOOTSTRAP_NET_2_0
  174. public
  175. #else
  176. internal
  177. #endif
  178. MethodBuilder DefineGlobalMethod (string name, MethodAttributes attributes, CallingConventions callingConvention, Type returnType, Type[] requiredReturnTypeCustomModifiers, Type[] optionalReturnTypeCustomModifiers, Type[] parameterTypes, Type[][] requiredParameterTypeCustomModifiers, Type[][] optionalParameterTypeCustomModifiers)
  179. {
  180. if (name == null)
  181. throw new ArgumentNullException ("name");
  182. if ((attributes & MethodAttributes.Static) == 0)
  183. throw new ArgumentException ("global methods must be static");
  184. if (global_type_created != null)
  185. throw new InvalidOperationException ("global methods already created");
  186. CreateGlobalType ();
  187. MethodBuilder mb = global_type.DefineMethod (name, attributes, callingConvention, returnType, requiredReturnTypeCustomModifiers, optionalReturnTypeCustomModifiers, parameterTypes, requiredParameterTypeCustomModifiers, optionalParameterTypeCustomModifiers);
  188. addGlobalMethod (mb);
  189. return mb;
  190. }
  191. public MethodBuilder DefinePInvokeMethod (string name, string dllName, MethodAttributes attributes, CallingConventions callingConvention, Type returnType, Type[] parameterTypes, CallingConvention nativeCallConv, CharSet nativeCharSet) {
  192. return DefinePInvokeMethod (name, dllName, name, attributes, callingConvention, returnType, parameterTypes, nativeCallConv, nativeCharSet);
  193. }
  194. public MethodBuilder DefinePInvokeMethod (string name, string dllName, string entryName, MethodAttributes attributes, CallingConventions callingConvention, Type returnType, Type[] parameterTypes, CallingConvention nativeCallConv, CharSet nativeCharSet) {
  195. if (name == null)
  196. throw new ArgumentNullException ("name");
  197. if ((attributes & MethodAttributes.Static) == 0)
  198. throw new ArgumentException ("global methods must be static");
  199. if (global_type_created != null)
  200. throw new InvalidOperationException ("global methods already created");
  201. CreateGlobalType ();
  202. MethodBuilder mb = global_type.DefinePInvokeMethod (name, dllName, entryName, attributes, callingConvention, returnType, parameterTypes, nativeCallConv, nativeCharSet);
  203. addGlobalMethod (mb);
  204. return mb;
  205. }
  206. public TypeBuilder DefineType (string name) {
  207. return DefineType (name, 0);
  208. }
  209. public TypeBuilder DefineType (string name, TypeAttributes attr) {
  210. if ((attr & TypeAttributes.Interface) != 0)
  211. return DefineType (name, attr, null, null);
  212. return DefineType (name, attr, typeof(object), null);
  213. }
  214. public TypeBuilder DefineType (string name, TypeAttributes attr, Type parent) {
  215. return DefineType (name, attr, parent, null);
  216. }
  217. private void AddType (TypeBuilder tb)
  218. {
  219. if (types != null) {
  220. if (types.Length == num_types) {
  221. TypeBuilder[] new_types = new TypeBuilder [types.Length * 2];
  222. System.Array.Copy (types, new_types, num_types);
  223. types = new_types;
  224. }
  225. } else {
  226. types = new TypeBuilder [1];
  227. }
  228. types [num_types] = tb;
  229. num_types ++;
  230. }
  231. private TypeBuilder DefineType (string name, TypeAttributes attr, Type parent, Type[] interfaces, PackingSize packingSize, int typesize) {
  232. TypeBuilder res = new TypeBuilder (this, name, attr, parent, interfaces, packingSize, typesize, null);
  233. AddType (res);
  234. try {
  235. name_cache.Add (name, res);
  236. } catch {
  237. throw new ArgumentException ("Duplicate type name within an assembly.");
  238. }
  239. return res;
  240. }
  241. internal void RegisterTypeName (TypeBuilder tb, string name)
  242. {
  243. name_cache.Add (name, tb);
  244. }
  245. internal TypeBuilder GetRegisteredType (string name)
  246. {
  247. return (TypeBuilder) name_cache [name];
  248. }
  249. #if NET_2_0
  250. [ComVisible (true)]
  251. #endif
  252. public TypeBuilder DefineType (string name, TypeAttributes attr, Type parent, Type[] interfaces) {
  253. return DefineType (name, attr, parent, interfaces, PackingSize.Unspecified, TypeBuilder.UnspecifiedTypeSize);
  254. }
  255. public TypeBuilder DefineType (string name, TypeAttributes attr, Type parent, int typesize) {
  256. return DefineType (name, attr, parent, null, PackingSize.Unspecified, TypeBuilder.UnspecifiedTypeSize);
  257. }
  258. public TypeBuilder DefineType (string name, TypeAttributes attr, Type parent, PackingSize packsize) {
  259. return DefineType (name, attr, parent, null, packsize, TypeBuilder.UnspecifiedTypeSize);
  260. }
  261. public TypeBuilder DefineType (string name, TypeAttributes attr, Type parent, PackingSize packingSize, int typesize) {
  262. return DefineType (name, attr, parent, null, packingSize, typesize);
  263. }
  264. public MethodInfo GetArrayMethod( Type arrayClass, string methodName, CallingConventions callingConvention, Type returnType, Type[] parameterTypes) {
  265. return new MonoArrayMethod (arrayClass, methodName, callingConvention, returnType, parameterTypes);
  266. }
  267. public EnumBuilder DefineEnum( string name, TypeAttributes visibility, Type underlyingType) {
  268. if (name_cache.Contains (name))
  269. throw new ArgumentException ("Duplicate type name within an assembly.");
  270. EnumBuilder eb = new EnumBuilder (this, name, visibility, underlyingType);
  271. TypeBuilder res = eb.GetTypeBuilder ();
  272. AddType (res);
  273. name_cache.Add (name, res);
  274. return eb;
  275. }
  276. #if NET_2_0
  277. [ComVisible (true)]
  278. #endif
  279. public override Type GetType( string className) {
  280. return GetType (className, false, false);
  281. }
  282. #if NET_2_0
  283. [ComVisible (true)]
  284. #endif
  285. public override Type GetType( string className, bool ignoreCase) {
  286. return GetType (className, false, ignoreCase);
  287. }
  288. private TypeBuilder search_in_array (TypeBuilder[] arr, int validElementsInArray, string className) {
  289. int i;
  290. for (i = 0; i < validElementsInArray; ++i) {
  291. if (String.Compare (className, arr [i].FullName, true, CultureInfo.InvariantCulture) == 0) {
  292. return arr [i];
  293. }
  294. }
  295. return null;
  296. }
  297. private TypeBuilder search_nested_in_array (TypeBuilder[] arr, int validElementsInArray, string className) {
  298. int i;
  299. for (i = 0; i < validElementsInArray; ++i) {
  300. if (String.Compare (className, arr [i].Name, true, CultureInfo.InvariantCulture) == 0)
  301. return arr [i];
  302. }
  303. return null;
  304. }
  305. [MethodImplAttribute(MethodImplOptions.InternalCall)]
  306. private static extern Type create_modified_type (TypeBuilder tb, string modifiers);
  307. static readonly char [] type_modifiers = {'&', '[', '*'};
  308. private TypeBuilder GetMaybeNested (TypeBuilder t, string className) {
  309. int subt;
  310. string pname, rname;
  311. subt = className.IndexOf ('+');
  312. if (subt < 0) {
  313. if (t.subtypes != null)
  314. return search_nested_in_array (t.subtypes, t.subtypes.Length, className);
  315. return null;
  316. }
  317. if (t.subtypes != null) {
  318. pname = className.Substring (0, subt);
  319. rname = className.Substring (subt + 1);
  320. TypeBuilder result = search_nested_in_array (t.subtypes, t.subtypes.Length, pname);
  321. if (result != null)
  322. return GetMaybeNested (result, rname);
  323. }
  324. return null;
  325. }
  326. #if NET_2_0
  327. [ComVisible (true)]
  328. #endif
  329. public override Type GetType (string className, bool throwOnError, bool ignoreCase) {
  330. int subt;
  331. string orig = className;
  332. string modifiers;
  333. TypeBuilder result = null;
  334. if (types == null && throwOnError)
  335. throw new TypeLoadException (className);
  336. subt = className.IndexOfAny (type_modifiers);
  337. if (subt >= 0) {
  338. modifiers = className.Substring (subt);
  339. className = className.Substring (0, subt);
  340. } else
  341. modifiers = null;
  342. if (!ignoreCase) {
  343. result = name_cache [className] as TypeBuilder;
  344. } else {
  345. subt = className.IndexOf ('+');
  346. if (subt < 0) {
  347. if (types != null)
  348. result = search_in_array (types, num_types, className);
  349. } else {
  350. string pname, rname;
  351. pname = className.Substring (0, subt);
  352. rname = className.Substring (subt + 1);
  353. result = search_in_array (types, num_types, pname);
  354. if (result != null)
  355. result = GetMaybeNested (result, rname);
  356. }
  357. }
  358. if ((result == null) && throwOnError)
  359. throw new TypeLoadException (orig);
  360. if (result != null && (modifiers != null)) {
  361. Type mt = create_modified_type (result, modifiers);
  362. result = mt as TypeBuilder;
  363. if (result == null)
  364. return mt;
  365. }
  366. if (result != null && result.is_created)
  367. return result.CreateType ();
  368. else
  369. return result;
  370. }
  371. internal int get_next_table_index (object obj, int table, bool inc) {
  372. if (table_indexes == null) {
  373. table_indexes = new int [64];
  374. for (int i=0; i < 64; ++i)
  375. table_indexes [i] = 1;
  376. /* allow room for .<Module> in TypeDef table */
  377. table_indexes [0x02] = 2;
  378. }
  379. // Console.WriteLine ("getindex for table "+table.ToString()+" got "+table_indexes [table].ToString());
  380. if (inc)
  381. return table_indexes [table]++;
  382. return table_indexes [table];
  383. }
  384. public void SetCustomAttribute( CustomAttributeBuilder customBuilder) {
  385. if (cattrs != null) {
  386. CustomAttributeBuilder[] new_array = new CustomAttributeBuilder [cattrs.Length + 1];
  387. cattrs.CopyTo (new_array, 0);
  388. new_array [cattrs.Length] = customBuilder;
  389. cattrs = new_array;
  390. } else {
  391. cattrs = new CustomAttributeBuilder [1];
  392. cattrs [0] = customBuilder;
  393. }
  394. }
  395. #if NET_2_0
  396. [ComVisible (true)]
  397. #endif
  398. public void SetCustomAttribute( ConstructorInfo con, byte[] binaryAttribute) {
  399. SetCustomAttribute (new CustomAttributeBuilder (con, binaryAttribute));
  400. }
  401. public ISymbolWriter GetSymWriter () {
  402. return symbolWriter;
  403. }
  404. public ISymbolDocumentWriter DefineDocument (string url, Guid language, Guid languageVendor, Guid documentType)
  405. {
  406. if (symbolWriter != null)
  407. return symbolWriter.DefineDocument (url, language, languageVendor, documentType);
  408. else
  409. return null;
  410. }
  411. public override Type [] GetTypes ()
  412. {
  413. if (types == null)
  414. return Type.EmptyTypes;
  415. int n = num_types;
  416. Type [] copy = new Type [n];
  417. Array.Copy (types, copy, n);
  418. // MS replaces the typebuilders with their created types
  419. for (int i = 0; i < copy.Length; ++i)
  420. if (types [i].is_created)
  421. copy [i] = types [i].CreateType ();
  422. return copy;
  423. }
  424. public IResourceWriter DefineResource (string name, string description, ResourceAttributes attribute)
  425. {
  426. if (name == null)
  427. throw new ArgumentNullException ("name");
  428. if (name == String.Empty)
  429. throw new ArgumentException ("name cannot be empty");
  430. if (transient)
  431. throw new InvalidOperationException ("The module is transient");
  432. if (!assemblyb.IsSave)
  433. throw new InvalidOperationException ("The assembly is transient");
  434. ResourceWriter writer = new ResourceWriter (new MemoryStream ());
  435. if (resource_writers == null)
  436. resource_writers = new Hashtable ();
  437. resource_writers [name] = writer;
  438. // The data is filled out later
  439. if (resources != null) {
  440. MonoResource[] new_r = new MonoResource [resources.Length + 1];
  441. System.Array.Copy(resources, new_r, resources.Length);
  442. resources = new_r;
  443. } else {
  444. resources = new MonoResource [1];
  445. }
  446. int p = resources.Length - 1;
  447. resources [p].name = name;
  448. resources [p].attrs = attribute;
  449. return writer;
  450. }
  451. public IResourceWriter DefineResource (string name, string description)
  452. {
  453. return DefineResource (name, description, ResourceAttributes.Public);
  454. }
  455. [MonoTODO]
  456. public void DefineUnmanagedResource (byte[] resource)
  457. {
  458. if (resource == null)
  459. throw new ArgumentNullException ("resource");
  460. throw new NotImplementedException ();
  461. }
  462. [MonoTODO]
  463. public void DefineUnmanagedResource (string resourceFileName)
  464. {
  465. if (resourceFileName == null)
  466. throw new ArgumentNullException ("resourceFileName");
  467. if (resourceFileName == String.Empty)
  468. throw new ArgumentException ("resourceFileName");
  469. if (!File.Exists (resourceFileName) || Directory.Exists (resourceFileName))
  470. throw new FileNotFoundException ("File '" + resourceFileName + "' does not exists or is a directory.");
  471. throw new NotImplementedException ();
  472. }
  473. #if NET_2_0 || BOOTSTRAP_NET_2_0
  474. public void DefineManifestResource (string name, Stream stream, ResourceAttributes attribute) {
  475. if (name == null)
  476. throw new ArgumentNullException ("name");
  477. if (name == String.Empty)
  478. throw new ArgumentException ("name cannot be empty");
  479. if (stream == null)
  480. throw new ArgumentNullException ("stream");
  481. if (transient)
  482. throw new InvalidOperationException ("The module is transient");
  483. if (!assemblyb.IsSave)
  484. throw new InvalidOperationException ("The assembly is transient");
  485. if (resources != null) {
  486. MonoResource[] new_r = new MonoResource [resources.Length + 1];
  487. System.Array.Copy(resources, new_r, resources.Length);
  488. resources = new_r;
  489. } else {
  490. resources = new MonoResource [1];
  491. }
  492. int p = resources.Length - 1;
  493. resources [p].name = name;
  494. resources [p].attrs = attribute;
  495. resources [p].stream = stream;
  496. }
  497. #endif
  498. [MonoTODO]
  499. public void SetSymCustomAttribute (string name, byte[] data)
  500. {
  501. throw new NotImplementedException ();
  502. }
  503. [MonoTODO]
  504. public void SetUserEntryPoint (MethodInfo entryPoint)
  505. {
  506. if (entryPoint == null)
  507. throw new ArgumentNullException ("entryPoint");
  508. if (entryPoint.DeclaringType.Module != this)
  509. throw new InvalidOperationException ("entryPoint is not contained in this module");
  510. throw new NotImplementedException ();
  511. }
  512. public MethodToken GetMethodToken (MethodInfo method)
  513. {
  514. if (method == null)
  515. throw new ArgumentNullException ("method");
  516. if (method.DeclaringType.Module != this)
  517. throw new InvalidOperationException ("The method is not in this module");
  518. return new MethodToken (GetToken (method));
  519. }
  520. public MethodToken GetArrayMethodToken (Type arrayClass, string methodName, CallingConventions callingConvention, Type returnType, Type[] parameterTypes)
  521. {
  522. return GetMethodToken (GetArrayMethod (arrayClass, methodName, callingConvention, returnType, parameterTypes));
  523. }
  524. #if NET_2_0
  525. [ComVisible (true)]
  526. #endif
  527. public MethodToken GetConstructorToken (ConstructorInfo con)
  528. {
  529. if (con == null)
  530. throw new ArgumentNullException ("con");
  531. return new MethodToken (GetToken (con));
  532. }
  533. public FieldToken GetFieldToken (FieldInfo field)
  534. {
  535. if (field == null)
  536. throw new ArgumentNullException ("field");
  537. if (field.DeclaringType.Module != this)
  538. throw new InvalidOperationException ("The method is not in this module");
  539. return new FieldToken (GetToken (field));
  540. }
  541. [MonoTODO]
  542. public SignatureToken GetSignatureToken (byte[] sigBytes, int sigLength)
  543. {
  544. throw new NotImplementedException ();
  545. }
  546. public SignatureToken GetSignatureToken (SignatureHelper sigHelper)
  547. {
  548. if (sigHelper == null)
  549. throw new ArgumentNullException ("sigHelper");
  550. return new SignatureToken (GetToken (sigHelper));
  551. }
  552. public StringToken GetStringConstant (string str)
  553. {
  554. if (str == null)
  555. throw new ArgumentNullException ("str");
  556. return new StringToken (GetToken (str));
  557. }
  558. public TypeToken GetTypeToken (Type type)
  559. {
  560. if (type == null)
  561. throw new ArgumentNullException ("type");
  562. if (type.IsByRef)
  563. throw new ArgumentException ("type can't be a byref type", "type");
  564. if (!IsTransient () && (type.Module is ModuleBuilder) && ((ModuleBuilder)type.Module).IsTransient ())
  565. throw new InvalidOperationException ("a non-transient module can't reference a transient module");
  566. return new TypeToken (GetToken (type));
  567. }
  568. public TypeToken GetTypeToken (string name)
  569. {
  570. return GetTypeToken (GetType (name));
  571. }
  572. [MethodImplAttribute(MethodImplOptions.InternalCall)]
  573. private static extern int getUSIndex (ModuleBuilder mb, string str);
  574. [MethodImplAttribute(MethodImplOptions.InternalCall)]
  575. private static extern int getToken (ModuleBuilder mb, object obj);
  576. [MethodImplAttribute(MethodImplOptions.InternalCall)]
  577. private static extern int getMethodToken (ModuleBuilder mb, MethodInfo method,
  578. Type[] opt_param_types);
  579. internal int GetToken (string str) {
  580. if (us_string_cache.Contains (str))
  581. return (int)us_string_cache [str];
  582. int result = getUSIndex (this, str);
  583. us_string_cache [str] = result;
  584. return result;
  585. }
  586. internal int GetToken (MemberInfo member) {
  587. return getToken (this, member);
  588. }
  589. internal int GetToken (MethodInfo method, Type[] opt_param_types) {
  590. return getMethodToken (this, method, opt_param_types);
  591. }
  592. internal int GetToken (SignatureHelper helper) {
  593. return getToken (this, helper);
  594. }
  595. /*
  596. * Register the token->obj mapping with the runtime so the Module.Resolve...
  597. * methods will work for obj.
  598. */
  599. [MethodImplAttribute(MethodImplOptions.InternalCall)]
  600. internal extern void RegisterToken (object obj, int token);
  601. internal TokenGenerator GetTokenGenerator () {
  602. if (token_gen == null)
  603. token_gen = new ModuleBuilderTokenGenerator (this);
  604. return token_gen;
  605. }
  606. [MethodImplAttribute(MethodImplOptions.InternalCall)]
  607. private static extern void build_metadata (ModuleBuilder mb);
  608. [MethodImplAttribute(MethodImplOptions.InternalCall)]
  609. private extern void WriteToFile (IntPtr handle);
  610. internal void Save ()
  611. {
  612. if (transient && !is_main)
  613. return;
  614. if (types != null) {
  615. for (int i = 0; i < num_types; ++i)
  616. if (!types [i].is_created)
  617. throw new NotSupportedException ("Type '" + types [i].FullName + "' was not completed.");
  618. }
  619. if ((global_type != null) && (global_type_created == null))
  620. global_type_created = global_type.CreateType ();
  621. if (resources != null) {
  622. for (int i = 0; i < resources.Length; ++i) {
  623. IResourceWriter rwriter;
  624. if (resource_writers != null && (rwriter = resource_writers [resources [i].name] as IResourceWriter) != null) {
  625. ResourceWriter writer = (ResourceWriter)rwriter;
  626. writer.Generate ();
  627. MemoryStream mstream = (MemoryStream)writer.Stream;
  628. resources [i].data = new byte [mstream.Length];
  629. mstream.Seek (0, SeekOrigin.Begin);
  630. mstream.Read (resources [i].data, 0, (int)mstream.Length);
  631. continue;
  632. }
  633. Stream stream = resources [i].stream;
  634. // According to MSDN docs, the stream is read during assembly save, not earlier
  635. if (stream != null) {
  636. try {
  637. long len = stream.Length;
  638. resources [i].data = new byte [len];
  639. stream.Seek (0, SeekOrigin.Begin);
  640. stream.Read (resources [i].data, 0, (int)len);
  641. } catch {
  642. /* do something */
  643. }
  644. }
  645. }
  646. }
  647. build_metadata (this);
  648. string fileName = fqname;
  649. if (assemblyb.AssemblyDir != null)
  650. fileName = Path.Combine (assemblyb.AssemblyDir, fileName);
  651. try {
  652. // We mmap the file, so unlink the previous version since it may be in use
  653. File.Delete (fileName);
  654. } catch {
  655. // We can safely ignore
  656. }
  657. using (FileStream file = new FileStream (fileName, FileMode.Create, FileAccess.Write))
  658. WriteToFile (file.Handle);
  659. //
  660. // The constant 0x80000000 is internal to Mono, it means `make executable'
  661. //
  662. File.SetAttributes (fileName, (FileAttributes) (unchecked ((int) 0x80000000)));
  663. if (types != null && symbolWriter != null) {
  664. for (int i = 0; i < num_types; ++i)
  665. types [i].GenerateDebugInfo (symbolWriter);
  666. symbolWriter.Close ();
  667. }
  668. }
  669. internal string FileName {
  670. get {
  671. return fqname;
  672. }
  673. }
  674. internal bool IsMain {
  675. set {
  676. is_main = value;
  677. }
  678. }
  679. internal void CreateGlobalType () {
  680. if (global_type == null)
  681. global_type = new TypeBuilder (this, 0, 1);
  682. }
  683. internal override Guid GetModuleVersionId ()
  684. {
  685. return new Guid (guid);
  686. }
  687. // Used by mcs, the symbol writer, and mdb through reflection
  688. internal static Guid Mono_GetGuid (ModuleBuilder mb)
  689. {
  690. return mb.GetModuleVersionId ();
  691. }
  692. void _ModuleBuilder.GetIDsOfNames ([In] ref Guid riid, IntPtr rgszNames, uint cNames, uint lcid, IntPtr rgDispId)
  693. {
  694. throw new NotImplementedException ();
  695. }
  696. void _ModuleBuilder.GetTypeInfo (uint iTInfo, uint lcid, IntPtr ppTInfo)
  697. {
  698. throw new NotImplementedException ();
  699. }
  700. void _ModuleBuilder.GetTypeInfoCount (out uint pcTInfo)
  701. {
  702. throw new NotImplementedException ();
  703. }
  704. void _ModuleBuilder.Invoke (uint dispIdMember, [In] ref Guid riid, uint lcid, short wFlags, IntPtr pDispParams, IntPtr pVarResult, IntPtr pExcepInfo, IntPtr puArgErr)
  705. {
  706. throw new NotImplementedException ();
  707. }
  708. }
  709. internal class ModuleBuilderTokenGenerator : TokenGenerator {
  710. private ModuleBuilder mb;
  711. public ModuleBuilderTokenGenerator (ModuleBuilder mb) {
  712. this.mb = mb;
  713. }
  714. public int GetToken (string str) {
  715. return mb.GetToken (str);
  716. }
  717. public int GetToken (MemberInfo member) {
  718. return mb.GetToken (member);
  719. }
  720. public int GetToken (MethodInfo method, Type[] opt_param_types) {
  721. return mb.GetToken (method, opt_param_types);
  722. }
  723. public int GetToken (SignatureHelper helper) {
  724. return mb.GetToken (helper);
  725. }
  726. }
  727. }