ModuleBuilder.cs 28 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853
  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. [ComVisible (true)]
  42. [ComDefaultInterface (typeof (_ModuleBuilder))]
  43. [ClassInterface (ClassInterfaceType.None)]
  44. public class ModuleBuilder : Module, _ModuleBuilder {
  45. #pragma warning disable 169, 414
  46. #region Sync with object-internals.h
  47. private UIntPtr dynamic_image; /* GC-tracked */
  48. private int num_types;
  49. private TypeBuilder[] types;
  50. private CustomAttributeBuilder[] cattrs;
  51. private byte[] guid;
  52. private int table_idx;
  53. internal AssemblyBuilder assemblyb;
  54. private MethodBuilder[] global_methods;
  55. private FieldBuilder[] global_fields;
  56. bool is_main;
  57. private MonoResource[] resources;
  58. #endregion
  59. #pragma warning restore 169, 414
  60. private TypeBuilder global_type;
  61. private Type global_type_created;
  62. Hashtable name_cache;
  63. Hashtable us_string_cache = new Hashtable ();
  64. private int[] table_indexes;
  65. bool transient;
  66. ModuleBuilderTokenGenerator token_gen;
  67. Hashtable resource_writers;
  68. ISymbolWriter symbolWriter;
  69. [MethodImplAttribute(MethodImplOptions.InternalCall)]
  70. private static extern void basic_init (ModuleBuilder ab);
  71. [MethodImplAttribute(MethodImplOptions.InternalCall)]
  72. private static extern void set_wrappers_type (ModuleBuilder mb, Type ab);
  73. internal ModuleBuilder (AssemblyBuilder assb, string name, string fullyqname, bool emitSymbolInfo, bool transient) {
  74. this.name = this.scopename = name;
  75. this.fqname = fullyqname;
  76. this.assembly = this.assemblyb = assb;
  77. this.transient = transient;
  78. // to keep mcs fast we do not want CryptoConfig wo be involved to create the RNG
  79. guid = Guid.FastNewGuidArray ();
  80. // guid = Guid.NewGuid().ToByteArray ();
  81. table_idx = get_next_table_index (this, 0x00, true);
  82. name_cache = new Hashtable ();
  83. basic_init (this);
  84. CreateGlobalType ();
  85. if (assb.IsRun) {
  86. TypeBuilder tb = new TypeBuilder (this, TypeAttributes.Abstract, 0xFFFFFF); /*last valid token*/
  87. Type type = tb.CreateType ();
  88. set_wrappers_type (this, type);
  89. }
  90. if (emitSymbolInfo) {
  91. #if MOONLIGHT
  92. symbolWriter = new Mono.CompilerServices.SymbolWriter.SymbolWriterImpl (this);
  93. #else
  94. Assembly asm = Assembly.LoadWithPartialName ("Mono.CompilerServices.SymbolWriter");
  95. if (asm == null)
  96. throw new ExecutionEngineException ("The assembly for default symbol writer cannot be loaded");
  97. Type t = asm.GetType ("Mono.CompilerServices.SymbolWriter.SymbolWriterImpl");
  98. if (t == null)
  99. throw new ExecutionEngineException ("The type that implements the default symbol writer interface cannot be found");
  100. symbolWriter = (ISymbolWriter) Activator.CreateInstance (t, new object[] { this });
  101. #endif
  102. string fileName = fqname;
  103. if (assemblyb.AssemblyDir != null)
  104. fileName = Path.Combine (assemblyb.AssemblyDir, fileName);
  105. symbolWriter.Initialize (IntPtr.Zero, fileName, true);
  106. }
  107. }
  108. public override string FullyQualifiedName {get { return fqname;}}
  109. public bool IsTransient () {
  110. return transient;
  111. }
  112. public void CreateGlobalFunctions ()
  113. {
  114. if (global_type_created != null)
  115. throw new InvalidOperationException ("global methods already created");
  116. if (global_type != null)
  117. global_type_created = global_type.CreateType ();
  118. }
  119. public FieldBuilder DefineInitializedData( string name, byte[] data, FieldAttributes attributes) {
  120. if (data == null)
  121. throw new ArgumentNullException ("data");
  122. FieldBuilder fb = DefineUninitializedData (name, data.Length,
  123. attributes | FieldAttributes.HasFieldRVA);
  124. fb.SetRVAData (data);
  125. return fb;
  126. }
  127. public FieldBuilder DefineUninitializedData (string name, int size, FieldAttributes attributes)
  128. {
  129. if (name == null)
  130. throw new ArgumentNullException ("name");
  131. if (global_type_created != null)
  132. throw new InvalidOperationException ("global fields already created");
  133. if ((size <= 0) || (size > 0x3f0000))
  134. throw new ArgumentException ("size", "Data size must be > 0 and < 0x3f0000");
  135. CreateGlobalType ();
  136. string typeName = "$ArrayType$" + size;
  137. Type datablobtype = GetType (typeName, false, false);
  138. if (datablobtype == null) {
  139. TypeBuilder tb = DefineType (typeName,
  140. TypeAttributes.Public|TypeAttributes.ExplicitLayout|TypeAttributes.Sealed,
  141. assemblyb.corlib_value_type, null, PackingSize.Size1, size);
  142. tb.CreateType ();
  143. datablobtype = tb;
  144. }
  145. FieldBuilder fb = global_type.DefineField (name, datablobtype, attributes|FieldAttributes.Static);
  146. if (global_fields != null) {
  147. FieldBuilder[] new_fields = new FieldBuilder [global_fields.Length+1];
  148. System.Array.Copy (global_fields, new_fields, global_fields.Length);
  149. new_fields [global_fields.Length] = fb;
  150. global_fields = new_fields;
  151. } else {
  152. global_fields = new FieldBuilder [1];
  153. global_fields [0] = fb;
  154. }
  155. return fb;
  156. }
  157. private void addGlobalMethod (MethodBuilder mb) {
  158. if (global_methods != null) {
  159. MethodBuilder[] new_methods = new MethodBuilder [global_methods.Length+1];
  160. System.Array.Copy (global_methods, new_methods, global_methods.Length);
  161. new_methods [global_methods.Length] = mb;
  162. global_methods = new_methods;
  163. } else {
  164. global_methods = new MethodBuilder [1];
  165. global_methods [0] = mb;
  166. }
  167. }
  168. public MethodBuilder DefineGlobalMethod (string name, MethodAttributes attributes, Type returnType, Type[] parameterTypes)
  169. {
  170. return DefineGlobalMethod (name, attributes, CallingConventions.Standard, returnType, parameterTypes);
  171. }
  172. public MethodBuilder DefineGlobalMethod (string name, MethodAttributes attributes, CallingConventions callingConvention, Type returnType, Type[] parameterTypes) {
  173. return DefineGlobalMethod (name, attributes, callingConvention, returnType, null, null, parameterTypes, null, null);
  174. }
  175. public MethodBuilder DefineGlobalMethod (string name, MethodAttributes attributes, CallingConventions callingConvention, Type returnType, Type[] requiredReturnTypeCustomModifiers, Type[] optionalReturnTypeCustomModifiers, Type[] parameterTypes, Type[][] requiredParameterTypeCustomModifiers, Type[][] optionalParameterTypeCustomModifiers)
  176. {
  177. if (name == null)
  178. throw new ArgumentNullException ("name");
  179. if ((attributes & MethodAttributes.Static) == 0)
  180. throw new ArgumentException ("global methods must be static");
  181. if (global_type_created != null)
  182. throw new InvalidOperationException ("global methods already created");
  183. CreateGlobalType ();
  184. MethodBuilder mb = global_type.DefineMethod (name, attributes, callingConvention, returnType, requiredReturnTypeCustomModifiers, optionalReturnTypeCustomModifiers, parameterTypes, requiredParameterTypeCustomModifiers, optionalParameterTypeCustomModifiers);
  185. addGlobalMethod (mb);
  186. return mb;
  187. }
  188. public MethodBuilder DefinePInvokeMethod (string name, string dllName, MethodAttributes attributes, CallingConventions callingConvention, Type returnType, Type[] parameterTypes, CallingConvention nativeCallConv, CharSet nativeCharSet) {
  189. return DefinePInvokeMethod (name, dllName, name, attributes, callingConvention, returnType, parameterTypes, nativeCallConv, nativeCharSet);
  190. }
  191. public MethodBuilder DefinePInvokeMethod (string name, string dllName, string entryName, MethodAttributes attributes, CallingConventions callingConvention, Type returnType, Type[] parameterTypes, CallingConvention nativeCallConv, CharSet nativeCharSet) {
  192. if (name == null)
  193. throw new ArgumentNullException ("name");
  194. if ((attributes & MethodAttributes.Static) == 0)
  195. throw new ArgumentException ("global methods must be static");
  196. if (global_type_created != null)
  197. throw new InvalidOperationException ("global methods already created");
  198. CreateGlobalType ();
  199. MethodBuilder mb = global_type.DefinePInvokeMethod (name, dllName, entryName, attributes, callingConvention, returnType, parameterTypes, nativeCallConv, nativeCharSet);
  200. addGlobalMethod (mb);
  201. return mb;
  202. }
  203. public TypeBuilder DefineType (string name) {
  204. return DefineType (name, 0);
  205. }
  206. public TypeBuilder DefineType (string name, TypeAttributes attr) {
  207. if ((attr & TypeAttributes.Interface) != 0)
  208. return DefineType (name, attr, null, null);
  209. return DefineType (name, attr, typeof(object), null);
  210. }
  211. public TypeBuilder DefineType (string name, TypeAttributes attr, Type parent) {
  212. return DefineType (name, attr, parent, null);
  213. }
  214. private void AddType (TypeBuilder tb)
  215. {
  216. if (types != null) {
  217. if (types.Length == num_types) {
  218. TypeBuilder[] new_types = new TypeBuilder [types.Length * 2];
  219. System.Array.Copy (types, new_types, num_types);
  220. types = new_types;
  221. }
  222. } else {
  223. types = new TypeBuilder [1];
  224. }
  225. types [num_types] = tb;
  226. num_types ++;
  227. }
  228. private TypeBuilder DefineType (string name, TypeAttributes attr, Type parent, Type[] interfaces, PackingSize packingSize, int typesize) {
  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, TypeBuilder.UnspecifiedTypeSize);
  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 exists 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. if (method.DeclaringType.Module != this)
  505. throw new InvalidOperationException ("The method is not in this module");
  506. return new MethodToken (GetToken (method));
  507. }
  508. public MethodToken GetArrayMethodToken (Type arrayClass, string methodName, CallingConventions callingConvention, Type returnType, Type[] parameterTypes)
  509. {
  510. return GetMethodToken (GetArrayMethod (arrayClass, methodName, callingConvention, returnType, parameterTypes));
  511. }
  512. [ComVisible (true)]
  513. public MethodToken GetConstructorToken (ConstructorInfo con)
  514. {
  515. if (con == null)
  516. throw new ArgumentNullException ("con");
  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);
  562. [MethodImplAttribute(MethodImplOptions.InternalCall)]
  563. private static extern int getMethodToken (ModuleBuilder mb, MethodInfo method,
  564. Type[] opt_param_types);
  565. internal int GetToken (string str) {
  566. if (us_string_cache.Contains (str))
  567. return (int)us_string_cache [str];
  568. int result = getUSIndex (this, str);
  569. us_string_cache [str] = result;
  570. return result;
  571. }
  572. internal int GetToken (MemberInfo member) {
  573. return getToken (this, member);
  574. }
  575. internal int GetToken (MethodInfo method, Type[] opt_param_types) {
  576. return getMethodToken (this, method, opt_param_types);
  577. }
  578. internal int GetToken (SignatureHelper helper) {
  579. return getToken (this, helper);
  580. }
  581. /*
  582. * Register the token->obj mapping with the runtime so the Module.Resolve...
  583. * methods will work for obj.
  584. */
  585. [MethodImplAttribute(MethodImplOptions.InternalCall)]
  586. internal extern void RegisterToken (object obj, int token);
  587. internal TokenGenerator GetTokenGenerator () {
  588. if (token_gen == null)
  589. token_gen = new ModuleBuilderTokenGenerator (this);
  590. return token_gen;
  591. }
  592. [MethodImplAttribute(MethodImplOptions.InternalCall)]
  593. private static extern void build_metadata (ModuleBuilder mb);
  594. [MethodImplAttribute(MethodImplOptions.InternalCall)]
  595. private extern void WriteToFile (IntPtr handle);
  596. internal void Save ()
  597. {
  598. if (transient && !is_main)
  599. return;
  600. if (types != null) {
  601. for (int i = 0; i < num_types; ++i)
  602. if (!types [i].is_created)
  603. throw new NotSupportedException ("Type '" + types [i].FullName + "' was not completed.");
  604. }
  605. if ((global_type != null) && (global_type_created == null))
  606. global_type_created = global_type.CreateType ();
  607. if (resources != null) {
  608. for (int i = 0; i < resources.Length; ++i) {
  609. IResourceWriter rwriter;
  610. if (resource_writers != null && (rwriter = resource_writers [resources [i].name] as IResourceWriter) != null) {
  611. ResourceWriter writer = (ResourceWriter)rwriter;
  612. writer.Generate ();
  613. MemoryStream mstream = (MemoryStream)writer.Stream;
  614. resources [i].data = new byte [mstream.Length];
  615. mstream.Seek (0, SeekOrigin.Begin);
  616. mstream.Read (resources [i].data, 0, (int)mstream.Length);
  617. continue;
  618. }
  619. Stream stream = resources [i].stream;
  620. // According to MSDN docs, the stream is read during assembly save, not earlier
  621. if (stream != null) {
  622. try {
  623. long len = stream.Length;
  624. resources [i].data = new byte [len];
  625. stream.Seek (0, SeekOrigin.Begin);
  626. stream.Read (resources [i].data, 0, (int)len);
  627. } catch {
  628. /* do something */
  629. }
  630. }
  631. }
  632. }
  633. build_metadata (this);
  634. string fileName = fqname;
  635. if (assemblyb.AssemblyDir != null)
  636. fileName = Path.Combine (assemblyb.AssemblyDir, fileName);
  637. try {
  638. // We mmap the file, so unlink the previous version since it may be in use
  639. File.Delete (fileName);
  640. } catch {
  641. // We can safely ignore
  642. }
  643. using (FileStream file = new FileStream (fileName, FileMode.Create, FileAccess.Write))
  644. WriteToFile (file.Handle);
  645. //
  646. // The constant 0x80000000 is internal to Mono, it means `make executable'
  647. //
  648. File.SetAttributes (fileName, (FileAttributes) (unchecked ((int) 0x80000000)));
  649. if (types != null && symbolWriter != null) {
  650. for (int i = 0; i < num_types; ++i)
  651. types [i].GenerateDebugInfo (symbolWriter);
  652. symbolWriter.Close ();
  653. }
  654. }
  655. internal string FileName {
  656. get {
  657. return fqname;
  658. }
  659. }
  660. internal bool IsMain {
  661. set {
  662. is_main = value;
  663. }
  664. }
  665. internal void CreateGlobalType () {
  666. if (global_type == null)
  667. global_type = new TypeBuilder (this, 0, 1);
  668. }
  669. internal override Guid GetModuleVersionId ()
  670. {
  671. return new Guid (guid);
  672. }
  673. // Used by mcs, the symbol writer, and mdb through reflection
  674. internal static Guid Mono_GetGuid (ModuleBuilder mb)
  675. {
  676. return mb.GetModuleVersionId ();
  677. }
  678. void _ModuleBuilder.GetIDsOfNames ([In] ref Guid riid, IntPtr rgszNames, uint cNames, uint lcid, IntPtr rgDispId)
  679. {
  680. throw new NotImplementedException ();
  681. }
  682. void _ModuleBuilder.GetTypeInfo (uint iTInfo, uint lcid, IntPtr ppTInfo)
  683. {
  684. throw new NotImplementedException ();
  685. }
  686. void _ModuleBuilder.GetTypeInfoCount (out uint pcTInfo)
  687. {
  688. throw new NotImplementedException ();
  689. }
  690. void _ModuleBuilder.Invoke (uint dispIdMember, [In] ref Guid riid, uint lcid, short wFlags, IntPtr pDispParams, IntPtr pVarResult, IntPtr pExcepInfo, IntPtr puArgErr)
  691. {
  692. throw new NotImplementedException ();
  693. }
  694. #if NET_4_0
  695. public override Assembly Assembly {
  696. get { return assemblyb; }
  697. }
  698. public override string Name {
  699. get { return name; }
  700. }
  701. #endif
  702. }
  703. internal class ModuleBuilderTokenGenerator : TokenGenerator {
  704. private ModuleBuilder mb;
  705. public ModuleBuilderTokenGenerator (ModuleBuilder mb) {
  706. this.mb = mb;
  707. }
  708. public int GetToken (string str) {
  709. return mb.GetToken (str);
  710. }
  711. public int GetToken (MemberInfo member) {
  712. return mb.GetToken (member);
  713. }
  714. public int GetToken (MethodInfo method, Type[] opt_param_types) {
  715. return mb.GetToken (method, opt_param_types);
  716. }
  717. public int GetToken (SignatureHelper helper) {
  718. return mb.GetToken (helper);
  719. }
  720. }
  721. }