ModuleBuilder.cs 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486
  1. //
  2. // System.Reflection.Emit/ModuleBuilder.cs
  3. //
  4. // Author:
  5. // Paolo Molaro ([email protected])
  6. //
  7. // (C) 2001 Ximian, Inc. http://www.ximian.com
  8. //
  9. using System;
  10. using System.Reflection;
  11. using System.Collections;
  12. using System.Runtime.CompilerServices;
  13. using System.Runtime.InteropServices;
  14. using System.Diagnostics.SymbolStore;
  15. using System.IO;
  16. using Mono.CSharp.Debugger;
  17. namespace System.Reflection.Emit {
  18. public class ModuleBuilder : Module {
  19. private IntPtr dynamic_image;
  20. private TypeBuilder[] types;
  21. private CustomAttributeBuilder[] cattrs;
  22. private byte[] guid;
  23. private int table_idx;
  24. internal AssemblyBuilder assemblyb;
  25. private MethodBuilder[] global_methods;
  26. private FieldBuilder[] global_fields;
  27. bool is_main;
  28. private TypeBuilder global_type;
  29. private Type global_type_created;
  30. internal IMonoSymbolWriter symbol_writer;
  31. Hashtable name_cache;
  32. Hashtable us_string_cache = new Hashtable ();
  33. private int[] table_indexes;
  34. bool transient;
  35. ModuleBuilderTokenGenerator token_gen;
  36. [MethodImplAttribute(MethodImplOptions.InternalCall)]
  37. private static extern void basic_init (ModuleBuilder ab);
  38. internal ModuleBuilder (AssemblyBuilder assb, string name, string fullyqname, bool emitSymbolInfo, bool transient) {
  39. this.name = this.scopename = name;
  40. this.fqname = fullyqname;
  41. this.assembly = this.assemblyb = assb;
  42. this.transient = transient;
  43. guid = Guid.NewGuid().ToByteArray ();
  44. table_idx = get_next_table_index (this, 0x00, true);
  45. name_cache = new Hashtable ();
  46. if (emitSymbolInfo)
  47. GetSymbolWriter (fullyqname);
  48. basic_init (this);
  49. }
  50. internal void GetSymbolWriter (string filename)
  51. {
  52. Assembly assembly;
  53. try {
  54. assembly = Assembly.Load ("Mono.CSharp.Debugger");
  55. } catch (FileNotFoundException) {
  56. return;
  57. }
  58. Type type = assembly.GetType ("Mono.CSharp.Debugger.MonoSymbolWriter");
  59. if (type == null)
  60. return;
  61. // First get the constructor.
  62. {
  63. Type[] arg_types = new Type [1];
  64. arg_types [0] = typeof (ModuleBuilder);
  65. ConstructorInfo constructor = type.GetConstructor (arg_types);
  66. object[] args = new object [1];
  67. args [0] = this;
  68. if (constructor == null)
  69. return;
  70. Object instance = constructor.Invoke (args);
  71. if (instance == null)
  72. return;
  73. if (!(instance is IMonoSymbolWriter))
  74. return;
  75. symbol_writer = (IMonoSymbolWriter) instance;
  76. }
  77. }
  78. public override string FullyQualifiedName {get { return fqname;}}
  79. public bool IsTransient () {
  80. return transient;
  81. }
  82. public void CreateGlobalFunctions ()
  83. {
  84. if (global_type_created != null)
  85. throw new InvalidOperationException ("global methods already created");
  86. if (global_type != null)
  87. global_type_created = global_type.CreateType ();
  88. }
  89. public FieldBuilder DefineInitializedData( string name, byte[] data, FieldAttributes attributes) {
  90. if (data == null)
  91. throw new ArgumentNullException ("data");
  92. FieldBuilder fb = DefineUninitializedData (name, data.Length,
  93. attributes | FieldAttributes.HasFieldRVA);
  94. fb.SetRVAData (data);
  95. return fb;
  96. }
  97. public FieldBuilder DefineUninitializedData( string name, int size, FieldAttributes attributes) {
  98. if (name == null)
  99. throw new ArgumentNullException ("name");
  100. if (global_type_created != null)
  101. throw new InvalidOperationException ("global fields already created");
  102. if (global_type == null)
  103. global_type = new TypeBuilder (this, 0);
  104. string typeName = "$ArrayType$" + size;
  105. Type datablobtype = GetType (typeName, false, false);
  106. if (datablobtype == null) {
  107. TypeBuilder tb = DefineType (typeName,
  108. TypeAttributes.Public|TypeAttributes.ExplicitLayout|TypeAttributes.Sealed,
  109. assemblyb.corlib_value_type, null, PackingSize.Size1, size);
  110. tb.CreateType ();
  111. datablobtype = tb;
  112. }
  113. FieldBuilder fb = global_type.DefineField (name, datablobtype, attributes|FieldAttributes.Static);
  114. if (global_fields != null) {
  115. FieldBuilder[] new_fields = new FieldBuilder [global_fields.Length+1];
  116. System.Array.Copy (global_fields, new_fields, global_fields.Length);
  117. new_fields [global_fields.Length] = fb;
  118. global_fields = new_fields;
  119. } else {
  120. global_fields = new FieldBuilder [1];
  121. global_fields [0] = fb;
  122. }
  123. return fb;
  124. }
  125. public MethodBuilder DefineGlobalMethod (string name, MethodAttributes attributes, Type returnType, Type[] parameterTypes)
  126. {
  127. return DefineGlobalMethod (name, attributes, CallingConventions.Standard, returnType, parameterTypes);
  128. }
  129. public MethodBuilder DefineGlobalMethod (string name, MethodAttributes attributes, CallingConventions callingConvention, Type returnType, Type[] parameterTypes)
  130. {
  131. if (name == null)
  132. throw new ArgumentNullException ("name");
  133. if ((attributes & MethodAttributes.Static) == 0)
  134. throw new ArgumentException ("global methods must be static");
  135. if (global_type_created != null)
  136. throw new InvalidOperationException ("global methods already created");
  137. if (global_type == null)
  138. global_type = new TypeBuilder (this, 0);
  139. MethodBuilder mb = global_type.DefineMethod (name, attributes, callingConvention, returnType, parameterTypes);
  140. if (global_methods != null) {
  141. MethodBuilder[] new_methods = new MethodBuilder [global_methods.Length+1];
  142. System.Array.Copy (global_methods, new_methods, global_methods.Length);
  143. new_methods [global_methods.Length] = mb;
  144. global_methods = new_methods;
  145. } else {
  146. global_methods = new MethodBuilder [1];
  147. global_methods [0] = mb;
  148. }
  149. return mb;
  150. }
  151. [MonoTODO]
  152. public TypeBuilder DefineType (string name) {
  153. // FIXME: LAMESPEC: what other attributes should we use here as default?
  154. return DefineType (name, TypeAttributes.Public, typeof(object), null);
  155. }
  156. public TypeBuilder DefineType (string name, TypeAttributes attr) {
  157. return DefineType (name, attr, typeof(object), null);
  158. }
  159. public TypeBuilder DefineType (string name, TypeAttributes attr, Type parent) {
  160. return DefineType (name, attr, parent, null);
  161. }
  162. private TypeBuilder DefineType (string name, TypeAttributes attr, Type parent, Type[] interfaces, PackingSize packsize, int typesize) {
  163. TypeBuilder res = new TypeBuilder (this, name, attr, parent, interfaces, packsize, typesize, null);
  164. if (types != null) {
  165. TypeBuilder[] new_types = new TypeBuilder [types.Length + 1];
  166. System.Array.Copy (types, new_types, types.Length);
  167. new_types [types.Length] = res;
  168. types = new_types;
  169. } else {
  170. types = new TypeBuilder [1];
  171. types [0] = res;
  172. }
  173. name_cache.Add (name, res);
  174. return res;
  175. }
  176. internal void RegisterTypeName (TypeBuilder tb, string name) {
  177. name_cache.Add (name, tb);
  178. }
  179. public TypeBuilder DefineType (string name, TypeAttributes attr, Type parent, Type[] interfaces) {
  180. return DefineType (name, attr, parent, interfaces, PackingSize.Unspecified, TypeBuilder.UnspecifiedTypeSize);
  181. }
  182. public TypeBuilder DefineType (string name, TypeAttributes attr, Type parent, int typesize) {
  183. return DefineType (name, attr, parent, null, PackingSize.Unspecified, TypeBuilder.UnspecifiedTypeSize);
  184. }
  185. public TypeBuilder DefineType (string name, TypeAttributes attr, Type parent, PackingSize packsize) {
  186. return DefineType (name, attr, parent, null, packsize, TypeBuilder.UnspecifiedTypeSize);
  187. }
  188. public TypeBuilder DefineType (string name, TypeAttributes attr, Type parent, PackingSize packsize, int typesize) {
  189. return DefineType (name, attr, parent, null, packsize, typesize);
  190. }
  191. public MethodInfo GetArrayMethod( Type arrayClass, string methodName, CallingConventions callingConvention, Type returnType, Type[] parameterTypes) {
  192. return new MonoArrayMethod (arrayClass, methodName, callingConvention, returnType, parameterTypes);
  193. }
  194. public EnumBuilder DefineEnum( string name, TypeAttributes visibility, Type underlyingType) {
  195. EnumBuilder eb = new EnumBuilder (this, name, visibility, underlyingType);
  196. return eb;
  197. }
  198. public override Type GetType( string className) {
  199. return GetType (className, false, false);
  200. }
  201. public override Type GetType( string className, bool ignoreCase) {
  202. return GetType (className, false, ignoreCase);
  203. }
  204. private TypeBuilder search_in_array (TypeBuilder[] arr, string className) {
  205. int i;
  206. for (i = 0; i < arr.Length; ++i) {
  207. if (String.Compare (className, arr [i].FullName, true) == 0) {
  208. return arr [i];
  209. }
  210. }
  211. return null;
  212. }
  213. private TypeBuilder search_nested_in_array (TypeBuilder[] arr, string className) {
  214. int i;
  215. for (i = 0; i < arr.Length; ++i) {
  216. if (String.Compare (className, arr [i].Name, true) == 0)
  217. return arr [i];
  218. }
  219. return null;
  220. }
  221. [MethodImplAttribute(MethodImplOptions.InternalCall)]
  222. private static extern Type create_modified_type (TypeBuilder tb, string modifiers);
  223. static char[] type_modifiers = {'&', '[', '*'};
  224. private TypeBuilder GetMaybeNested (TypeBuilder t, string className) {
  225. int subt;
  226. string pname, rname;
  227. subt = className.IndexOf ('+');
  228. if (subt < 0) {
  229. if (t.subtypes != null)
  230. return search_nested_in_array (t.subtypes, className);
  231. return null;
  232. }
  233. if (t.subtypes != null) {
  234. pname = className.Substring (0, subt);
  235. rname = className.Substring (subt + 1);
  236. TypeBuilder result = search_nested_in_array (t.subtypes, pname);
  237. if (result != null)
  238. return GetMaybeNested (result, rname);
  239. }
  240. return null;
  241. }
  242. public override Type GetType (string className, bool throwOnError, bool ignoreCase) {
  243. int subt;
  244. string orig = className;
  245. string modifiers;
  246. TypeBuilder result = null;
  247. if (types == null && throwOnError)
  248. throw new TypeLoadException (className);
  249. subt = className.IndexOfAny (type_modifiers);
  250. if (subt >= 0) {
  251. modifiers = className.Substring (subt);
  252. className = className.Substring (0, subt);
  253. } else
  254. modifiers = null;
  255. if (!ignoreCase) {
  256. result = name_cache [className] as TypeBuilder;
  257. } else {
  258. subt = className.IndexOf ('+');
  259. if (subt < 0) {
  260. if (types != null)
  261. result = search_in_array (types, className);
  262. } else {
  263. string pname, rname;
  264. pname = className.Substring (0, subt);
  265. rname = className.Substring (subt + 1);
  266. result = search_in_array (types, pname);
  267. if (result != null)
  268. result = GetMaybeNested (result, rname);
  269. }
  270. }
  271. if ((result == null) && throwOnError)
  272. throw new TypeLoadException (orig);
  273. if (result != null && (modifiers != null))
  274. return create_modified_type (result, modifiers);
  275. return result;
  276. }
  277. internal int get_next_table_index (object obj, int table, bool inc) {
  278. if (table_indexes == null) {
  279. table_indexes = new int [64];
  280. for (int i=0; i < 64; ++i)
  281. table_indexes [i] = 1;
  282. /* allow room for .<Module> in TypeDef table */
  283. table_indexes [0x02] = 2;
  284. }
  285. // Console.WriteLine ("getindex for table "+table.ToString()+" got "+table_indexes [table].ToString());
  286. if (inc)
  287. return table_indexes [table]++;
  288. return table_indexes [table];
  289. }
  290. public void SetCustomAttribute( CustomAttributeBuilder customBuilder) {
  291. if (cattrs != null) {
  292. CustomAttributeBuilder[] new_array = new CustomAttributeBuilder [cattrs.Length + 1];
  293. cattrs.CopyTo (new_array, 0);
  294. new_array [cattrs.Length] = customBuilder;
  295. cattrs = new_array;
  296. } else {
  297. cattrs = new CustomAttributeBuilder [1];
  298. cattrs [0] = customBuilder;
  299. }
  300. }
  301. public void SetCustomAttribute( ConstructorInfo con, byte[] binaryAttribute) {
  302. SetCustomAttribute (new CustomAttributeBuilder (con, binaryAttribute));
  303. }
  304. public ISymbolWriter GetSymWriter () {
  305. return symbol_writer;
  306. }
  307. public ISymbolDocumentWriter DefineDocument (string url, Guid language, Guid languageVendor, Guid documentType) {
  308. if (symbol_writer == null)
  309. throw new InvalidOperationException ();
  310. return symbol_writer.DefineDocument (url, language, languageVendor, documentType);
  311. }
  312. public override Type [] GetTypes ()
  313. {
  314. if (types == null)
  315. return new TypeBuilder [0];
  316. int n = types.Length;
  317. TypeBuilder [] copy = new TypeBuilder [n];
  318. Array.Copy (types, copy, n);
  319. return copy;
  320. }
  321. [MethodImplAttribute(MethodImplOptions.InternalCall)]
  322. private static extern int getUSIndex (ModuleBuilder mb, string str);
  323. [MethodImplAttribute(MethodImplOptions.InternalCall)]
  324. private static extern int getToken (ModuleBuilder mb, object obj);
  325. internal int GetToken (string str) {
  326. if (us_string_cache.Contains (str))
  327. return (int)us_string_cache [str];
  328. int result = getUSIndex (this, str);
  329. us_string_cache [str] = result;
  330. return result;
  331. }
  332. internal int GetToken (MemberInfo member) {
  333. return getToken (this, member);
  334. }
  335. internal int GetToken (SignatureHelper helper) {
  336. return getToken (this, helper);
  337. }
  338. internal TokenGenerator GetTokenGenerator () {
  339. if (token_gen == null)
  340. token_gen = new ModuleBuilderTokenGenerator (this);
  341. return token_gen;
  342. }
  343. [MethodImplAttribute(MethodImplOptions.InternalCall)]
  344. private static extern void build_metadata (ModuleBuilder mb);
  345. [MethodImplAttribute(MethodImplOptions.InternalCall)]
  346. private static extern int getDataChunk (ModuleBuilder mb, byte[] buf, int offset);
  347. internal void Save ()
  348. {
  349. if (transient)
  350. return;
  351. build_metadata (this);
  352. if (symbol_writer != null) {
  353. string res_name;
  354. if (is_main)
  355. res_name = "MonoSymbolFile";
  356. else
  357. res_name = "MonoSymbolFile:" + fqname;
  358. byte[] data = symbol_writer.CreateSymbolFile (assemblyb);
  359. assemblyb.EmbedResource (res_name, data, ResourceAttributes.Public);
  360. }
  361. string fileName = fqname;
  362. if (assemblyb.AssemblyDir != null)
  363. fileName = System.IO.Path.Combine (assemblyb.AssemblyDir, fileName);
  364. byte[] buf = new byte [65536];
  365. FileStream file;
  366. int count, offset;
  367. file = new FileStream (fileName, FileMode.Create, FileAccess.Write);
  368. offset = 0;
  369. while ((count = getDataChunk (this, buf, offset)) != 0) {
  370. file.Write (buf, 0, count);
  371. offset += count;
  372. }
  373. file.Close ();
  374. //
  375. // The constant 0x80000000 is internal to Mono, it means `make executable'
  376. //
  377. File.SetAttributes (fileName, (FileAttributes) (unchecked ((int) 0x80000000)));
  378. }
  379. internal string FileName {
  380. get {
  381. return fqname;
  382. }
  383. }
  384. internal bool IsMain {
  385. set {
  386. is_main = value;
  387. }
  388. }
  389. }
  390. internal class ModuleBuilderTokenGenerator : TokenGenerator {
  391. private ModuleBuilder mb;
  392. public ModuleBuilderTokenGenerator (ModuleBuilder mb) {
  393. this.mb = mb;
  394. }
  395. public int GetToken (string str) {
  396. return mb.GetToken (str);
  397. }
  398. public int GetToken (MemberInfo member) {
  399. return mb.GetToken (member);
  400. }
  401. public int GetToken (SignatureHelper helper) {
  402. return mb.GetToken (helper);
  403. }
  404. }
  405. }