ModuleBuilder.cs 28 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862
  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. {
  331. if (className == null)
  332. throw new ArgumentNullException ("className");
  333. if (className.Length == 0)
  334. throw new ArgumentException ("className");
  335. int subt;
  336. string orig = className;
  337. string modifiers;
  338. TypeBuilder result = null;
  339. if (types == null && throwOnError)
  340. throw new TypeLoadException (className);
  341. subt = className.IndexOfAny (type_modifiers);
  342. if (subt >= 0) {
  343. modifiers = className.Substring (subt);
  344. className = className.Substring (0, subt);
  345. } else
  346. modifiers = null;
  347. if (!ignoreCase) {
  348. result = name_cache [className] as TypeBuilder;
  349. } else {
  350. subt = className.IndexOf ('+');
  351. if (subt < 0) {
  352. if (types != null)
  353. result = search_in_array (types, num_types, className);
  354. } else {
  355. string pname, rname;
  356. pname = className.Substring (0, subt);
  357. rname = className.Substring (subt + 1);
  358. result = search_in_array (types, num_types, pname);
  359. if (result != null)
  360. result = GetMaybeNested (result, rname);
  361. }
  362. }
  363. if ((result == null) && throwOnError)
  364. throw new TypeLoadException (orig);
  365. if (result != null && (modifiers != null)) {
  366. Type mt = create_modified_type (result, modifiers);
  367. result = mt as TypeBuilder;
  368. if (result == null)
  369. return mt;
  370. }
  371. if (result != null && result.is_created)
  372. return result.CreateType ();
  373. else
  374. return result;
  375. }
  376. internal int get_next_table_index (object obj, int table, bool inc) {
  377. if (table_indexes == null) {
  378. table_indexes = new int [64];
  379. for (int i=0; i < 64; ++i)
  380. table_indexes [i] = 1;
  381. /* allow room for .<Module> in TypeDef table */
  382. table_indexes [0x02] = 2;
  383. }
  384. // Console.WriteLine ("getindex for table "+table.ToString()+" got "+table_indexes [table].ToString());
  385. if (inc)
  386. return table_indexes [table]++;
  387. return table_indexes [table];
  388. }
  389. public void SetCustomAttribute( CustomAttributeBuilder customBuilder) {
  390. if (cattrs != null) {
  391. CustomAttributeBuilder[] new_array = new CustomAttributeBuilder [cattrs.Length + 1];
  392. cattrs.CopyTo (new_array, 0);
  393. new_array [cattrs.Length] = customBuilder;
  394. cattrs = new_array;
  395. } else {
  396. cattrs = new CustomAttributeBuilder [1];
  397. cattrs [0] = customBuilder;
  398. }
  399. }
  400. #if NET_2_0
  401. [ComVisible (true)]
  402. #endif
  403. public void SetCustomAttribute( ConstructorInfo con, byte[] binaryAttribute) {
  404. SetCustomAttribute (new CustomAttributeBuilder (con, binaryAttribute));
  405. }
  406. public ISymbolWriter GetSymWriter () {
  407. return symbolWriter;
  408. }
  409. public ISymbolDocumentWriter DefineDocument (string url, Guid language, Guid languageVendor, Guid documentType)
  410. {
  411. if (symbolWriter != null)
  412. return symbolWriter.DefineDocument (url, language, languageVendor, documentType);
  413. else
  414. return null;
  415. }
  416. public override Type [] GetTypes ()
  417. {
  418. if (types == null)
  419. return Type.EmptyTypes;
  420. int n = num_types;
  421. Type [] copy = new Type [n];
  422. Array.Copy (types, copy, n);
  423. // MS replaces the typebuilders with their created types
  424. for (int i = 0; i < copy.Length; ++i)
  425. if (types [i].is_created)
  426. copy [i] = types [i].CreateType ();
  427. return copy;
  428. }
  429. public IResourceWriter DefineResource (string name, string description, ResourceAttributes attribute)
  430. {
  431. if (name == null)
  432. throw new ArgumentNullException ("name");
  433. if (name == String.Empty)
  434. throw new ArgumentException ("name cannot be empty");
  435. if (transient)
  436. throw new InvalidOperationException ("The module is transient");
  437. if (!assemblyb.IsSave)
  438. throw new InvalidOperationException ("The assembly is transient");
  439. ResourceWriter writer = new ResourceWriter (new MemoryStream ());
  440. if (resource_writers == null)
  441. resource_writers = new Hashtable ();
  442. resource_writers [name] = writer;
  443. // The data is filled out later
  444. if (resources != null) {
  445. MonoResource[] new_r = new MonoResource [resources.Length + 1];
  446. System.Array.Copy(resources, new_r, resources.Length);
  447. resources = new_r;
  448. } else {
  449. resources = new MonoResource [1];
  450. }
  451. int p = resources.Length - 1;
  452. resources [p].name = name;
  453. resources [p].attrs = attribute;
  454. return writer;
  455. }
  456. public IResourceWriter DefineResource (string name, string description)
  457. {
  458. return DefineResource (name, description, ResourceAttributes.Public);
  459. }
  460. [MonoTODO]
  461. public void DefineUnmanagedResource (byte[] resource)
  462. {
  463. if (resource == null)
  464. throw new ArgumentNullException ("resource");
  465. throw new NotImplementedException ();
  466. }
  467. [MonoTODO]
  468. public void DefineUnmanagedResource (string resourceFileName)
  469. {
  470. if (resourceFileName == null)
  471. throw new ArgumentNullException ("resourceFileName");
  472. if (resourceFileName == String.Empty)
  473. throw new ArgumentException ("resourceFileName");
  474. if (!File.Exists (resourceFileName) || Directory.Exists (resourceFileName))
  475. throw new FileNotFoundException ("File '" + resourceFileName + "' does not exists or is a directory.");
  476. throw new NotImplementedException ();
  477. }
  478. #if NET_2_0 || BOOTSTRAP_NET_2_0
  479. public void DefineManifestResource (string name, Stream stream, ResourceAttributes attribute) {
  480. if (name == null)
  481. throw new ArgumentNullException ("name");
  482. if (name == String.Empty)
  483. throw new ArgumentException ("name cannot be empty");
  484. if (stream == null)
  485. throw new ArgumentNullException ("stream");
  486. if (transient)
  487. throw new InvalidOperationException ("The module is transient");
  488. if (!assemblyb.IsSave)
  489. throw new InvalidOperationException ("The assembly is transient");
  490. if (resources != null) {
  491. MonoResource[] new_r = new MonoResource [resources.Length + 1];
  492. System.Array.Copy(resources, new_r, resources.Length);
  493. resources = new_r;
  494. } else {
  495. resources = new MonoResource [1];
  496. }
  497. int p = resources.Length - 1;
  498. resources [p].name = name;
  499. resources [p].attrs = attribute;
  500. resources [p].stream = stream;
  501. }
  502. #endif
  503. [MonoTODO]
  504. public void SetSymCustomAttribute (string name, byte[] data)
  505. {
  506. throw new NotImplementedException ();
  507. }
  508. [MonoTODO]
  509. public void SetUserEntryPoint (MethodInfo entryPoint)
  510. {
  511. if (entryPoint == null)
  512. throw new ArgumentNullException ("entryPoint");
  513. if (entryPoint.DeclaringType.Module != this)
  514. throw new InvalidOperationException ("entryPoint is not contained in this module");
  515. throw new NotImplementedException ();
  516. }
  517. public MethodToken GetMethodToken (MethodInfo method)
  518. {
  519. if (method == null)
  520. throw new ArgumentNullException ("method");
  521. if (method.DeclaringType.Module != this)
  522. throw new InvalidOperationException ("The method is not in this module");
  523. return new MethodToken (GetToken (method));
  524. }
  525. public MethodToken GetArrayMethodToken (Type arrayClass, string methodName, CallingConventions callingConvention, Type returnType, Type[] parameterTypes)
  526. {
  527. return GetMethodToken (GetArrayMethod (arrayClass, methodName, callingConvention, returnType, parameterTypes));
  528. }
  529. #if NET_2_0
  530. [ComVisible (true)]
  531. #endif
  532. public MethodToken GetConstructorToken (ConstructorInfo con)
  533. {
  534. if (con == null)
  535. throw new ArgumentNullException ("con");
  536. return new MethodToken (GetToken (con));
  537. }
  538. public FieldToken GetFieldToken (FieldInfo field)
  539. {
  540. if (field == null)
  541. throw new ArgumentNullException ("field");
  542. if (field.DeclaringType.Module != this)
  543. throw new InvalidOperationException ("The method is not in this module");
  544. return new FieldToken (GetToken (field));
  545. }
  546. [MonoTODO]
  547. public SignatureToken GetSignatureToken (byte[] sigBytes, int sigLength)
  548. {
  549. throw new NotImplementedException ();
  550. }
  551. public SignatureToken GetSignatureToken (SignatureHelper sigHelper)
  552. {
  553. if (sigHelper == null)
  554. throw new ArgumentNullException ("sigHelper");
  555. return new SignatureToken (GetToken (sigHelper));
  556. }
  557. public StringToken GetStringConstant (string str)
  558. {
  559. if (str == null)
  560. throw new ArgumentNullException ("str");
  561. return new StringToken (GetToken (str));
  562. }
  563. public TypeToken GetTypeToken (Type type)
  564. {
  565. if (type == null)
  566. throw new ArgumentNullException ("type");
  567. if (type.IsByRef)
  568. throw new ArgumentException ("type can't be a byref type", "type");
  569. if (!IsTransient () && (type.Module is ModuleBuilder) && ((ModuleBuilder)type.Module).IsTransient ())
  570. throw new InvalidOperationException ("a non-transient module can't reference a transient module");
  571. return new TypeToken (GetToken (type));
  572. }
  573. public TypeToken GetTypeToken (string name)
  574. {
  575. return GetTypeToken (GetType (name));
  576. }
  577. [MethodImplAttribute(MethodImplOptions.InternalCall)]
  578. private static extern int getUSIndex (ModuleBuilder mb, string str);
  579. [MethodImplAttribute(MethodImplOptions.InternalCall)]
  580. private static extern int getToken (ModuleBuilder mb, object obj);
  581. [MethodImplAttribute(MethodImplOptions.InternalCall)]
  582. private static extern int getMethodToken (ModuleBuilder mb, MethodInfo method,
  583. Type[] opt_param_types);
  584. internal int GetToken (string str) {
  585. if (us_string_cache.Contains (str))
  586. return (int)us_string_cache [str];
  587. int result = getUSIndex (this, str);
  588. us_string_cache [str] = result;
  589. return result;
  590. }
  591. internal int GetToken (MemberInfo member) {
  592. return getToken (this, member);
  593. }
  594. internal int GetToken (MethodInfo method, Type[] opt_param_types) {
  595. return getMethodToken (this, method, opt_param_types);
  596. }
  597. internal int GetToken (SignatureHelper helper) {
  598. return getToken (this, helper);
  599. }
  600. /*
  601. * Register the token->obj mapping with the runtime so the Module.Resolve...
  602. * methods will work for obj.
  603. */
  604. [MethodImplAttribute(MethodImplOptions.InternalCall)]
  605. internal extern void RegisterToken (object obj, int token);
  606. internal TokenGenerator GetTokenGenerator () {
  607. if (token_gen == null)
  608. token_gen = new ModuleBuilderTokenGenerator (this);
  609. return token_gen;
  610. }
  611. [MethodImplAttribute(MethodImplOptions.InternalCall)]
  612. private static extern void build_metadata (ModuleBuilder mb);
  613. [MethodImplAttribute(MethodImplOptions.InternalCall)]
  614. private extern void WriteToFile (IntPtr handle);
  615. internal void Save ()
  616. {
  617. if (transient && !is_main)
  618. return;
  619. if (types != null) {
  620. for (int i = 0; i < num_types; ++i)
  621. if (!types [i].is_created)
  622. throw new NotSupportedException ("Type '" + types [i].FullName + "' was not completed.");
  623. }
  624. if ((global_type != null) && (global_type_created == null))
  625. global_type_created = global_type.CreateType ();
  626. if (resources != null) {
  627. for (int i = 0; i < resources.Length; ++i) {
  628. IResourceWriter rwriter;
  629. if (resource_writers != null && (rwriter = resource_writers [resources [i].name] as IResourceWriter) != null) {
  630. ResourceWriter writer = (ResourceWriter)rwriter;
  631. writer.Generate ();
  632. MemoryStream mstream = (MemoryStream)writer.Stream;
  633. resources [i].data = new byte [mstream.Length];
  634. mstream.Seek (0, SeekOrigin.Begin);
  635. mstream.Read (resources [i].data, 0, (int)mstream.Length);
  636. continue;
  637. }
  638. Stream stream = resources [i].stream;
  639. // According to MSDN docs, the stream is read during assembly save, not earlier
  640. if (stream != null) {
  641. try {
  642. long len = stream.Length;
  643. resources [i].data = new byte [len];
  644. stream.Seek (0, SeekOrigin.Begin);
  645. stream.Read (resources [i].data, 0, (int)len);
  646. } catch {
  647. /* do something */
  648. }
  649. }
  650. }
  651. }
  652. build_metadata (this);
  653. string fileName = fqname;
  654. if (assemblyb.AssemblyDir != null)
  655. fileName = Path.Combine (assemblyb.AssemblyDir, fileName);
  656. try {
  657. // We mmap the file, so unlink the previous version since it may be in use
  658. File.Delete (fileName);
  659. } catch {
  660. // We can safely ignore
  661. }
  662. using (FileStream file = new FileStream (fileName, FileMode.Create, FileAccess.Write))
  663. WriteToFile (file.Handle);
  664. //
  665. // The constant 0x80000000 is internal to Mono, it means `make executable'
  666. //
  667. File.SetAttributes (fileName, (FileAttributes) (unchecked ((int) 0x80000000)));
  668. if (types != null && symbolWriter != null) {
  669. for (int i = 0; i < num_types; ++i)
  670. types [i].GenerateDebugInfo (symbolWriter);
  671. symbolWriter.Close ();
  672. }
  673. }
  674. internal string FileName {
  675. get {
  676. return fqname;
  677. }
  678. }
  679. internal bool IsMain {
  680. set {
  681. is_main = value;
  682. }
  683. }
  684. internal void CreateGlobalType () {
  685. if (global_type == null)
  686. global_type = new TypeBuilder (this, 0, 1);
  687. }
  688. internal override Guid GetModuleVersionId ()
  689. {
  690. return new Guid (guid);
  691. }
  692. // Used by mcs, the symbol writer, and mdb through reflection
  693. internal static Guid Mono_GetGuid (ModuleBuilder mb)
  694. {
  695. return mb.GetModuleVersionId ();
  696. }
  697. void _ModuleBuilder.GetIDsOfNames ([In] ref Guid riid, IntPtr rgszNames, uint cNames, uint lcid, IntPtr rgDispId)
  698. {
  699. throw new NotImplementedException ();
  700. }
  701. void _ModuleBuilder.GetTypeInfo (uint iTInfo, uint lcid, IntPtr ppTInfo)
  702. {
  703. throw new NotImplementedException ();
  704. }
  705. void _ModuleBuilder.GetTypeInfoCount (out uint pcTInfo)
  706. {
  707. throw new NotImplementedException ();
  708. }
  709. void _ModuleBuilder.Invoke (uint dispIdMember, [In] ref Guid riid, uint lcid, short wFlags, IntPtr pDispParams, IntPtr pVarResult, IntPtr pExcepInfo, IntPtr puArgErr)
  710. {
  711. throw new NotImplementedException ();
  712. }
  713. }
  714. internal class ModuleBuilderTokenGenerator : TokenGenerator {
  715. private ModuleBuilder mb;
  716. public ModuleBuilderTokenGenerator (ModuleBuilder mb) {
  717. this.mb = mb;
  718. }
  719. public int GetToken (string str) {
  720. return mb.GetToken (str);
  721. }
  722. public int GetToken (MemberInfo member) {
  723. return mb.GetToken (member);
  724. }
  725. public int GetToken (MethodInfo method, Type[] opt_param_types) {
  726. return mb.GetToken (method, opt_param_types);
  727. }
  728. public int GetToken (SignatureHelper helper) {
  729. return mb.GetToken (helper);
  730. }
  731. }
  732. }