AssemblyBuilder.cs 31 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011
  1. //
  2. // System.Reflection.Emit/AssemblyBuilder.cs
  3. //
  4. // Author:
  5. // Paolo Molaro ([email protected])
  6. //
  7. // (C) 2001 Ximian, Inc. http://www.ximian.com
  8. //
  9. //
  10. // Copyright (C) 2004 Novell, Inc (http://www.novell.com)
  11. //
  12. // Permission is hereby granted, free of charge, to any person obtaining
  13. // a copy of this software and associated documentation files (the
  14. // "Software"), to deal in the Software without restriction, including
  15. // without limitation the rights to use, copy, modify, merge, publish,
  16. // distribute, sublicense, and/or sell copies of the Software, and to
  17. // permit persons to whom the Software is furnished to do so, subject to
  18. // the following conditions:
  19. //
  20. // The above copyright notice and this permission notice shall be
  21. // included in all copies or substantial portions of the Software.
  22. //
  23. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
  24. // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
  25. // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
  26. // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
  27. // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
  28. // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
  29. // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
  30. //
  31. using System;
  32. using System.Reflection;
  33. using System.Resources;
  34. using System.IO;
  35. using System.Security.Policy;
  36. using System.Runtime.Serialization;
  37. using System.Globalization;
  38. using System.Runtime.CompilerServices;
  39. using System.Collections;
  40. using System.Runtime.InteropServices;
  41. using System.Security;
  42. using System.Security.Cryptography;
  43. using System.Security.Permissions;
  44. using Mono.Security;
  45. using Mono.Security.Cryptography;
  46. namespace System.Reflection.Emit {
  47. internal struct RefEmitPermissionSet {
  48. public SecurityAction action;
  49. public string pset;
  50. public RefEmitPermissionSet (SecurityAction action, string pset) {
  51. this.action = action;
  52. this.pset = pset;
  53. }
  54. }
  55. internal struct MonoResource {
  56. public byte[] data;
  57. public string name;
  58. public string filename;
  59. public ResourceAttributes attrs;
  60. public int offset;
  61. public Stream stream;
  62. }
  63. internal struct MonoWin32Resource {
  64. public int res_type;
  65. public int res_id;
  66. public int lang_id;
  67. public byte[] data;
  68. public MonoWin32Resource (int res_type, int res_id, int lang_id, byte[] data) {
  69. this.res_type = res_type;
  70. this.res_id = res_id;
  71. this.lang_id = lang_id;
  72. this.data = data;
  73. }
  74. }
  75. #if NET_2_0
  76. [ComVisible (true)]
  77. [ComDefaultInterface (typeof (_AssemblyBuilder))]
  78. #endif
  79. [ClassInterface (ClassInterfaceType.None)]
  80. public sealed class AssemblyBuilder : Assembly, _AssemblyBuilder {
  81. #region Sync with object-internals.h
  82. private UIntPtr dynamic_assembly; /* GC-tracked */
  83. private MethodInfo entry_point;
  84. private ModuleBuilder[] modules;
  85. private string name;
  86. private string dir;
  87. private CustomAttributeBuilder[] cattrs;
  88. private MonoResource[] resources;
  89. byte[] public_key;
  90. string version;
  91. string culture;
  92. uint algid;
  93. uint flags;
  94. PEFileKinds pekind = PEFileKinds.Dll;
  95. bool delay_sign;
  96. uint access;
  97. Module[] loaded_modules;
  98. MonoWin32Resource[] win32_resources;
  99. private RefEmitPermissionSet[] permissions_minimum;
  100. private RefEmitPermissionSet[] permissions_optional;
  101. private RefEmitPermissionSet[] permissions_refused;
  102. PortableExecutableKinds peKind;
  103. ImageFileMachine machine;
  104. bool corlib_internal;
  105. Type[] type_forwarders;
  106. #endregion
  107. internal Type corlib_object_type = typeof (System.Object);
  108. internal Type corlib_value_type = typeof (System.ValueType);
  109. internal Type corlib_enum_type = typeof (System.Enum);
  110. internal Type corlib_void_type = typeof (void);
  111. ArrayList resource_writers = null;
  112. Win32VersionResource version_res;
  113. bool created;
  114. bool is_module_only;
  115. private Mono.Security.StrongName sn;
  116. readonly bool is_compiler_context;
  117. [MethodImplAttribute(MethodImplOptions.InternalCall)]
  118. private static extern void basic_init (AssemblyBuilder ab);
  119. /* Keep this in sync with codegen.cs in mcs */
  120. private const AssemblyBuilderAccess COMPILER_ACCESS = (AssemblyBuilderAccess) 0x800;
  121. internal AssemblyBuilder (AssemblyName n, string directory, AssemblyBuilderAccess access, bool corlib_internal)
  122. {
  123. #if BOOTSTRAP_WITH_OLDLIB
  124. is_compiler_context = true;
  125. #else
  126. is_compiler_context = (access & COMPILER_ACCESS) != 0;
  127. #endif
  128. // remove Mono specific flag to allow enum check to pass
  129. access &= ~COMPILER_ACCESS;
  130. #if NET_2_0
  131. if (!Enum.IsDefined (typeof (AssemblyBuilderAccess), access))
  132. throw new ArgumentException (string.Format (CultureInfo.InvariantCulture,
  133. "Argument value {0} is not valid.", (int) access),
  134. "access");
  135. #endif
  136. name = n.Name;
  137. this.access = (uint)access;
  138. flags = (uint) n.Flags;
  139. // don't call GetCurrentDirectory for Run-only builders (CAS may not like that)
  140. if (IsSave && (directory == null || directory.Length == 0)) {
  141. dir = Directory.GetCurrentDirectory ();
  142. } else {
  143. dir = directory;
  144. }
  145. /* Set defaults from n */
  146. if (n.CultureInfo != null) {
  147. culture = n.CultureInfo.Name;
  148. }
  149. Version v = n.Version;
  150. if (v != null) {
  151. version = v.ToString ();
  152. }
  153. if (n.KeyPair != null) {
  154. // full keypair is available (for signing)
  155. sn = n.KeyPair.StrongName ();
  156. }
  157. else {
  158. // public key is available (for delay-signing)
  159. byte[] pk = n.GetPublicKey ();
  160. if ((pk != null) && (pk.Length > 0)) {
  161. sn = new Mono.Security.StrongName (pk);
  162. }
  163. }
  164. this.corlib_internal = corlib_internal;
  165. basic_init (this);
  166. }
  167. public override string CodeBase {
  168. get {
  169. throw not_supported ();
  170. }
  171. }
  172. public override MethodInfo EntryPoint {
  173. get {
  174. return entry_point;
  175. }
  176. }
  177. public override string Location {
  178. get {
  179. throw not_supported ();
  180. }
  181. }
  182. #if NET_1_1
  183. /* This is to keep signature compatibility with MS.NET */
  184. public override string ImageRuntimeVersion {
  185. get {
  186. return base.ImageRuntimeVersion;
  187. }
  188. }
  189. #endif
  190. #if NET_2_0
  191. [MonoTODO]
  192. public override bool ReflectionOnly {
  193. get { return base.ReflectionOnly; }
  194. }
  195. #endif
  196. public void AddResourceFile (string name, string fileName)
  197. {
  198. AddResourceFile (name, fileName, ResourceAttributes.Public);
  199. }
  200. public void AddResourceFile (string name, string fileName, ResourceAttributes attribute)
  201. {
  202. AddResourceFile (name, fileName, attribute, true);
  203. }
  204. private void AddResourceFile (string name, string fileName, ResourceAttributes attribute, bool fileNeedsToExists)
  205. {
  206. check_name_and_filename (name, fileName, fileNeedsToExists);
  207. // Resource files are created/searched under the assembly storage
  208. // directory
  209. if (dir != null)
  210. fileName = Path.Combine (dir, fileName);
  211. if (resources != null) {
  212. MonoResource[] new_r = new MonoResource [resources.Length + 1];
  213. System.Array.Copy(resources, new_r, resources.Length);
  214. resources = new_r;
  215. } else {
  216. resources = new MonoResource [1];
  217. }
  218. int p = resources.Length - 1;
  219. resources [p].name = name;
  220. resources [p].filename = fileName;
  221. resources [p].attrs = attribute;
  222. }
  223. /// <summary>
  224. /// Don't change the method name and parameters order. It is used by mcs
  225. /// </summary>
  226. internal void AddPermissionRequests (PermissionSet required, PermissionSet optional, PermissionSet refused)
  227. {
  228. if (created)
  229. throw new InvalidOperationException ("Assembly was already saved.");
  230. // required for base Assembly class (so the permissions
  231. // can be used even if the assembly isn't saved to disk)
  232. _minimum = required;
  233. _optional = optional;
  234. _refuse = refused;
  235. // required to reuse AddDeclarativeSecurity support
  236. // already present in the runtime
  237. if (required != null) {
  238. permissions_minimum = new RefEmitPermissionSet [1];
  239. permissions_minimum [0] = new RefEmitPermissionSet (
  240. SecurityAction.RequestMinimum, required.ToXml ().ToString ());
  241. }
  242. if (optional != null) {
  243. permissions_optional = new RefEmitPermissionSet [1];
  244. permissions_optional [0] = new RefEmitPermissionSet (
  245. SecurityAction.RequestOptional, optional.ToXml ().ToString ());
  246. }
  247. if (refused != null) {
  248. permissions_refused = new RefEmitPermissionSet [1];
  249. permissions_refused [0] = new RefEmitPermissionSet (
  250. SecurityAction.RequestRefuse, refused.ToXml ().ToString ());
  251. }
  252. }
  253. internal void EmbedResourceFile (string name, string fileName)
  254. {
  255. EmbedResourceFile (name, fileName, ResourceAttributes.Public);
  256. }
  257. internal void EmbedResourceFile (string name, string fileName, ResourceAttributes attribute)
  258. {
  259. if (resources != null) {
  260. MonoResource[] new_r = new MonoResource [resources.Length + 1];
  261. System.Array.Copy(resources, new_r, resources.Length);
  262. resources = new_r;
  263. } else {
  264. resources = new MonoResource [1];
  265. }
  266. int p = resources.Length - 1;
  267. resources [p].name = name;
  268. resources [p].attrs = attribute;
  269. try {
  270. FileStream s = new FileStream (fileName, FileMode.Open, FileAccess.Read);
  271. long len = s.Length;
  272. resources [p].data = new byte [len];
  273. s.Read (resources [p].data, 0, (int)len);
  274. s.Close ();
  275. } catch {
  276. /* do something */
  277. }
  278. }
  279. internal void EmbedResource (string name, byte[] blob, ResourceAttributes attribute)
  280. {
  281. if (resources != null) {
  282. MonoResource[] new_r = new MonoResource [resources.Length + 1];
  283. System.Array.Copy(resources, new_r, resources.Length);
  284. resources = new_r;
  285. } else {
  286. resources = new MonoResource [1];
  287. }
  288. int p = resources.Length - 1;
  289. resources [p].name = name;
  290. resources [p].attrs = attribute;
  291. resources [p].data = blob;
  292. }
  293. #if NET_2_0
  294. internal void AddTypeForwarder (Type t) {
  295. if (t == null)
  296. throw new ArgumentNullException ("t");
  297. if (type_forwarders == null) {
  298. type_forwarders = new Type [1] { t };
  299. } else {
  300. Type[] arr = new Type [type_forwarders.Length + 1];
  301. Array.Copy (type_forwarders, arr, type_forwarders.Length);
  302. type_forwarders = arr;
  303. }
  304. }
  305. #endif
  306. public ModuleBuilder DefineDynamicModule (string name)
  307. {
  308. return DefineDynamicModule (name, name, false, true);
  309. }
  310. public ModuleBuilder DefineDynamicModule (string name, bool emitSymbolInfo)
  311. {
  312. return DefineDynamicModule (name, name, emitSymbolInfo, true);
  313. }
  314. public ModuleBuilder DefineDynamicModule(string name, string fileName)
  315. {
  316. return DefineDynamicModule (name, fileName, false, false);
  317. }
  318. public ModuleBuilder DefineDynamicModule (string name, string fileName,
  319. bool emitSymbolInfo)
  320. {
  321. return DefineDynamicModule (name, fileName, emitSymbolInfo, false);
  322. }
  323. private ModuleBuilder DefineDynamicModule (string name, string fileName,
  324. bool emitSymbolInfo, bool transient)
  325. {
  326. check_name_and_filename (name, fileName, false);
  327. if (!transient) {
  328. if (Path.GetExtension (fileName) == String.Empty)
  329. throw new ArgumentException ("Module file name '" + fileName + "' must have file extension.");
  330. if (!IsSave)
  331. throw new NotSupportedException ("Persistable modules are not supported in a dynamic assembly created with AssemblyBuilderAccess.Run");
  332. if (created)
  333. throw new InvalidOperationException ("Assembly was already saved.");
  334. }
  335. ModuleBuilder r = new ModuleBuilder (this, name, fileName, emitSymbolInfo, transient);
  336. if ((modules != null) && is_module_only)
  337. throw new InvalidOperationException ("A module-only assembly can only contain one module.");
  338. if (modules != null) {
  339. ModuleBuilder[] new_modules = new ModuleBuilder [modules.Length + 1];
  340. System.Array.Copy(modules, new_modules, modules.Length);
  341. modules = new_modules;
  342. } else {
  343. modules = new ModuleBuilder [1];
  344. }
  345. modules [modules.Length - 1] = r;
  346. return r;
  347. }
  348. [MethodImplAttribute(MethodImplOptions.InternalCall)]
  349. private extern Module InternalAddModule (string fileName);
  350. /*
  351. * Mono extension to support /addmodule in mcs.
  352. */
  353. internal Module AddModule (string fileName)
  354. {
  355. if (fileName == null)
  356. throw new ArgumentNullException (fileName);
  357. Module m = InternalAddModule (fileName);
  358. if (loaded_modules != null) {
  359. Module[] new_modules = new Module [loaded_modules.Length + 1];
  360. System.Array.Copy (loaded_modules, new_modules, loaded_modules.Length);
  361. loaded_modules = new_modules;
  362. } else {
  363. loaded_modules = new Module [1];
  364. }
  365. loaded_modules [loaded_modules.Length - 1] = m;
  366. return m;
  367. }
  368. public IResourceWriter DefineResource (string name, string description, string fileName)
  369. {
  370. return DefineResource (name, description, fileName, ResourceAttributes.Public);
  371. }
  372. public IResourceWriter DefineResource (string name, string description,
  373. string fileName, ResourceAttributes attribute)
  374. {
  375. IResourceWriter writer;
  376. // description seems to be ignored
  377. AddResourceFile (name, fileName, attribute, false);
  378. writer = new ResourceWriter (fileName);
  379. if (resource_writers == null)
  380. resource_writers = new ArrayList ();
  381. resource_writers.Add (writer);
  382. return writer;
  383. }
  384. private void AddUnmanagedResource (Win32Resource res) {
  385. MemoryStream ms = new MemoryStream ();
  386. res.WriteTo (ms);
  387. if (win32_resources != null) {
  388. MonoWin32Resource[] new_res = new MonoWin32Resource [win32_resources.Length + 1];
  389. System.Array.Copy (win32_resources, new_res, win32_resources.Length);
  390. win32_resources = new_res;
  391. }
  392. else
  393. win32_resources = new MonoWin32Resource [1];
  394. win32_resources [win32_resources.Length - 1] = new MonoWin32Resource (res.Type.Id, res.Name.Id, res.Language, ms.ToArray ());
  395. }
  396. [MonoTODO ("Not currently implemenented")]
  397. public void DefineUnmanagedResource (byte[] resource)
  398. {
  399. if (resource == null)
  400. throw new ArgumentNullException ("resource");
  401. /*
  402. * The format of the argument byte array is not documented
  403. * so this method is impossible to implement.
  404. */
  405. throw new NotImplementedException ();
  406. }
  407. public void DefineUnmanagedResource (string resourceFileName)
  408. {
  409. if (resourceFileName == null)
  410. throw new ArgumentNullException ("resourceFileName");
  411. if (resourceFileName.Length == 0)
  412. throw new ArgumentException ("resourceFileName");
  413. if (!File.Exists (resourceFileName) || Directory.Exists (resourceFileName))
  414. throw new FileNotFoundException ("File '" + resourceFileName + "' does not exists or is a directory.");
  415. using (FileStream fs = new FileStream (resourceFileName, FileMode.Open, FileAccess.Read)) {
  416. Win32ResFileReader reader = new Win32ResFileReader (fs);
  417. foreach (Win32EncodedResource res in reader.ReadResources ()) {
  418. if (res.Name.IsName || res.Type.IsName)
  419. throw new InvalidOperationException ("resource files with named resources or non-default resource types are not supported.");
  420. AddUnmanagedResource (res);
  421. }
  422. }
  423. }
  424. public void DefineVersionInfoResource ()
  425. {
  426. if (version_res != null)
  427. throw new ArgumentException ("Native resource has already been defined.");
  428. version_res = new Win32VersionResource (1, 0);
  429. if (cattrs != null) {
  430. foreach (CustomAttributeBuilder cb in cattrs) {
  431. string attrname = cb.Ctor.ReflectedType.FullName;
  432. if (attrname == "System.Reflection.AssemblyProductAttribute")
  433. version_res.ProductName = cb.string_arg ();
  434. else if (attrname == "System.Reflection.AssemblyCompanyAttribute")
  435. version_res.CompanyName = cb.string_arg ();
  436. else if (attrname == "System.Reflection.AssemblyCopyrightAttribute")
  437. version_res.LegalCopyright = cb.string_arg ();
  438. else if (attrname == "System.Reflection.AssemblyTrademarkAttribute")
  439. version_res.LegalTrademarks = cb.string_arg ();
  440. else if (attrname == "System.Reflection.AssemblyCultureAttribute"){
  441. int lcid;
  442. try {
  443. lcid = new CultureInfo (GetCultureString (cb.string_arg ())).LCID;
  444. } catch (ArgumentException){
  445. //
  446. // This means that the resource is set to the invariant, but
  447. // the locale encoded will come from the AssemblyName anyways.
  448. //
  449. // In fact, my exploration of MS.NEt shows that this is always
  450. // set to zero, so I wonder if we should completely drop this
  451. // code from here.
  452. //
  453. lcid = CultureInfo.InvariantCulture.LCID;
  454. }
  455. version_res.FileLanguage = lcid;
  456. }
  457. else if (attrname == "System.Reflection.AssemblyFileVersionAttribute")
  458. version_res.FileVersion = cb.string_arg ();
  459. else if (attrname == "System.Reflection.AssemblyInformationalVersionAttribute")
  460. version_res.ProductVersion = cb.string_arg ();
  461. else if (attrname == "System.Reflection.AssemblyTitleAttribute")
  462. version_res.FileDescription = cb.string_arg ();
  463. else if (attrname == "System.Reflection.AssemblyDescriptionAttribute")
  464. version_res.Comments = cb.string_arg ();
  465. }
  466. }
  467. }
  468. public void DefineVersionInfoResource (string product, string productVersion,
  469. string company, string copyright, string trademark)
  470. {
  471. if (version_res != null)
  472. throw new ArgumentException ("Native resource has already been defined.");
  473. /*
  474. * We can only create the resource later, when the file name and
  475. * the binary version is known.
  476. */
  477. version_res = new Win32VersionResource (1, 0);
  478. version_res.ProductName = product != null ? product : " ";
  479. version_res.ProductVersion = productVersion != null ? productVersion : " ";
  480. version_res.CompanyName = company != null ? company : " ";
  481. version_res.LegalCopyright = copyright != null ? copyright : " ";
  482. version_res.LegalTrademarks = trademark != null ? trademark : " ";
  483. }
  484. /*
  485. * Mono extension to support /win32icon in mcs
  486. */
  487. internal void DefineIconResource (string iconFileName)
  488. {
  489. if (iconFileName == null)
  490. throw new ArgumentNullException ("iconFileName");
  491. if (iconFileName.Length == 0)
  492. throw new ArgumentException ("iconFileName");
  493. if (!File.Exists (iconFileName) || Directory.Exists (iconFileName))
  494. throw new FileNotFoundException ("File '" + iconFileName + "' does not exists or is a directory.");
  495. using (FileStream fs = new FileStream (iconFileName, FileMode.Open, FileAccess.Read)) {
  496. Win32IconFileReader reader = new Win32IconFileReader (fs);
  497. ICONDIRENTRY[] entries = reader.ReadIcons ();
  498. Win32IconResource[] icons = new Win32IconResource [entries.Length];
  499. for (int i = 0; i < entries.Length; ++i) {
  500. icons [i] = new Win32IconResource (i + 1, 0, entries [i]);
  501. AddUnmanagedResource (icons [i]);
  502. }
  503. Win32GroupIconResource group = new Win32GroupIconResource (1, 0, icons);
  504. AddUnmanagedResource (group);
  505. }
  506. }
  507. private void DefineVersionInfoResourceImpl (string fileName) {
  508. // Add missing info
  509. if (version_res.Version == "0.0.0.0")
  510. version_res.Version = version;
  511. if (version_res.FileVersion.Trim ().Length == 0 && version != null)
  512. version_res.FileVersion = version;
  513. version_res.InternalName = Path.GetFileNameWithoutExtension (fileName);
  514. version_res.OriginalFilename = fileName;
  515. AddUnmanagedResource (version_res);
  516. }
  517. public ModuleBuilder GetDynamicModule (string name)
  518. {
  519. if (name == null)
  520. throw new ArgumentNullException ("name");
  521. if (name.Length == 0)
  522. throw new ArgumentException ("Empty name is not legal.", "name");
  523. if (modules != null)
  524. for (int i = 0; i < modules.Length; ++i)
  525. if (modules [i].name == name)
  526. return modules [i];
  527. return null;
  528. }
  529. public override Type[] GetExportedTypes ()
  530. {
  531. throw not_supported ();
  532. }
  533. public override FileStream GetFile (string name)
  534. {
  535. throw not_supported ();
  536. }
  537. public override FileStream[] GetFiles(bool getResourceModules) {
  538. throw not_supported ();
  539. }
  540. internal override Module[] GetModulesInternal () {
  541. if (modules == null)
  542. return new Module [0];
  543. else
  544. return (Module[])modules.Clone ();
  545. }
  546. internal override Type[] GetTypes (bool exportedOnly) {
  547. Type[] res = null;
  548. if (modules != null) {
  549. for (int i = 0; i < modules.Length; ++i) {
  550. Type[] types = modules [i].GetTypes ();
  551. if (res == null)
  552. res = types;
  553. else {
  554. Type[] tmp = new Type [res.Length + types.Length];
  555. Array.Copy (res, 0, tmp, 0, res.Length);
  556. Array.Copy (types, 0, tmp, res.Length, types.Length);
  557. }
  558. }
  559. }
  560. if (loaded_modules != null) {
  561. for (int i = 0; i < loaded_modules.Length; ++i) {
  562. Type[] types = loaded_modules [i].GetTypes ();
  563. if (res == null)
  564. res = types;
  565. else {
  566. Type[] tmp = new Type [res.Length + types.Length];
  567. Array.Copy (res, 0, tmp, 0, res.Length);
  568. Array.Copy (types, 0, tmp, res.Length, types.Length);
  569. }
  570. }
  571. }
  572. if (res == null)
  573. return new Type [0];
  574. else
  575. return res;
  576. }
  577. public override ManifestResourceInfo GetManifestResourceInfo(string resourceName) {
  578. throw not_supported ();
  579. }
  580. public override string[] GetManifestResourceNames() {
  581. throw not_supported ();
  582. }
  583. public override Stream GetManifestResourceStream(string name) {
  584. throw not_supported ();
  585. }
  586. public override Stream GetManifestResourceStream(Type type, string name) {
  587. throw not_supported ();
  588. }
  589. /*
  590. * This is set when the the AssemblyBuilder is created by (g)mcs
  591. * or vbnc.
  592. */
  593. internal bool IsCompilerContext
  594. {
  595. get { return is_compiler_context; }
  596. }
  597. internal bool IsSave {
  598. get {
  599. return access != (uint)AssemblyBuilderAccess.Run;
  600. }
  601. }
  602. internal string AssemblyDir {
  603. get {
  604. return dir;
  605. }
  606. }
  607. /*
  608. * Mono extension. If this is set, the assembly can only contain one
  609. * module, access should be Save, and the saved image will not contain an
  610. * assembly manifest.
  611. */
  612. internal bool IsModuleOnly {
  613. get {
  614. return is_module_only;
  615. }
  616. set {
  617. is_module_only = value;
  618. }
  619. }
  620. #if NET_2_0
  621. ModuleBuilder manifest_module;
  622. //
  623. // MS.NET seems to return a ModuleBuilder when GetManifestModule () is called
  624. // on an assemblybuilder.
  625. //
  626. internal override Module GetManifestModule () {
  627. if (manifest_module == null)
  628. manifest_module = DefineDynamicModule ("Default Dynamic Module");
  629. return manifest_module;
  630. }
  631. #endif
  632. #if NET_2_0
  633. public
  634. #else
  635. internal
  636. #endif
  637. void Save (string assemblyFileName, PortableExecutableKinds portableExecutableKind, ImageFileMachine imageFileMachine)
  638. {
  639. this.peKind = portableExecutableKind;
  640. this.machine = imageFileMachine;
  641. if (resource_writers != null) {
  642. foreach (IResourceWriter writer in resource_writers) {
  643. writer.Generate ();
  644. writer.Close ();
  645. }
  646. }
  647. // Create a main module if not already created
  648. ModuleBuilder mainModule = null;
  649. if (modules != null) {
  650. foreach (ModuleBuilder module in modules)
  651. if (module.FullyQualifiedName == assemblyFileName)
  652. mainModule = module;
  653. }
  654. if (mainModule == null)
  655. mainModule = DefineDynamicModule ("RefEmit_OnDiskManifestModule", assemblyFileName);
  656. if (!is_module_only)
  657. mainModule.IsMain = true;
  658. /*
  659. * Create a new entry point if the one specified
  660. * by the user is in another module.
  661. */
  662. if ((entry_point != null) && entry_point.DeclaringType.Module != mainModule) {
  663. Type[] paramTypes;
  664. if (entry_point.GetParameters ().Length == 1)
  665. paramTypes = new Type [] { typeof (string) };
  666. else
  667. paramTypes = new Type [0];
  668. MethodBuilder mb = mainModule.DefineGlobalMethod ("__EntryPoint$", MethodAttributes.Static|MethodAttributes.PrivateScope, entry_point.ReturnType, paramTypes);
  669. ILGenerator ilgen = mb.GetILGenerator ();
  670. if (paramTypes.Length == 1)
  671. ilgen.Emit (OpCodes.Ldarg_0);
  672. ilgen.Emit (OpCodes.Tailcall);
  673. ilgen.Emit (OpCodes.Call, entry_point);
  674. ilgen.Emit (OpCodes.Ret);
  675. entry_point = mb;
  676. }
  677. if (version_res != null)
  678. DefineVersionInfoResourceImpl (assemblyFileName);
  679. if (sn != null) {
  680. // runtime needs to value to embed it into the assembly
  681. public_key = sn.PublicKey;
  682. }
  683. foreach (ModuleBuilder module in modules)
  684. if (module != mainModule)
  685. module.Save ();
  686. // Write out the main module at the end, because it needs to
  687. // contain the hash of the other modules
  688. mainModule.Save ();
  689. if ((sn != null) && (sn.CanSign)) {
  690. sn.Sign (System.IO.Path.Combine (this.AssemblyDir, assemblyFileName));
  691. }
  692. created = true;
  693. }
  694. public void Save (string assemblyFileName)
  695. {
  696. Save (assemblyFileName, PortableExecutableKinds.ILOnly, ImageFileMachine.I386);
  697. }
  698. public void SetEntryPoint (MethodInfo entryMethod)
  699. {
  700. SetEntryPoint (entryMethod, PEFileKinds.ConsoleApplication);
  701. }
  702. public void SetEntryPoint (MethodInfo entryMethod, PEFileKinds fileKind)
  703. {
  704. if (entryMethod == null)
  705. throw new ArgumentNullException ("entryMethod");
  706. if (entryMethod.DeclaringType.Assembly != this)
  707. throw new InvalidOperationException ("Entry method is not defined in the same assembly.");
  708. entry_point = entryMethod;
  709. pekind = fileKind;
  710. }
  711. public void SetCustomAttribute( CustomAttributeBuilder customBuilder)
  712. {
  713. if (customBuilder == null)
  714. throw new ArgumentNullException ("customBuilder");
  715. if (IsCompilerContext) {
  716. string attrname = customBuilder.Ctor.ReflectedType.FullName;
  717. byte [] data;
  718. int pos;
  719. if (attrname == "System.Reflection.AssemblyVersionAttribute") {
  720. version = create_assembly_version (customBuilder.string_arg ());
  721. return;
  722. } else if (attrname == "System.Reflection.AssemblyCultureAttribute") {
  723. culture = GetCultureString (customBuilder.string_arg ());
  724. } else if (attrname == "System.Reflection.AssemblyAlgorithmIdAttribute") {
  725. data = customBuilder.Data;
  726. pos = 2;
  727. algid = (uint) data [pos];
  728. algid |= ((uint) data [pos + 1]) << 8;
  729. algid |= ((uint) data [pos + 2]) << 16;
  730. algid |= ((uint) data [pos + 3]) << 24;
  731. } else if (attrname == "System.Reflection.AssemblyFlagsAttribute") {
  732. data = customBuilder.Data;
  733. pos = 2;
  734. flags = (uint) data [pos];
  735. flags |= ((uint) data [pos + 1]) << 8;
  736. flags |= ((uint) data [pos + 2]) << 16;
  737. flags |= ((uint) data [pos + 3]) << 24;
  738. }
  739. }
  740. if (cattrs != null) {
  741. CustomAttributeBuilder[] new_array = new CustomAttributeBuilder [cattrs.Length + 1];
  742. cattrs.CopyTo (new_array, 0);
  743. new_array [cattrs.Length] = customBuilder;
  744. cattrs = new_array;
  745. } else {
  746. cattrs = new CustomAttributeBuilder [1];
  747. cattrs [0] = customBuilder;
  748. }
  749. }
  750. #if NET_2_0
  751. [ComVisible (true)]
  752. #endif
  753. public void SetCustomAttribute ( ConstructorInfo con, byte[] binaryAttribute) {
  754. if (con == null)
  755. throw new ArgumentNullException ("con");
  756. if (binaryAttribute == null)
  757. throw new ArgumentNullException ("binaryAttribute");
  758. SetCustomAttribute (new CustomAttributeBuilder (con, binaryAttribute));
  759. }
  760. internal void SetCorlibTypeBuilders (Type corlib_object_type, Type corlib_value_type, Type corlib_enum_type) {
  761. this.corlib_object_type = corlib_object_type;
  762. this.corlib_value_type = corlib_value_type;
  763. this.corlib_enum_type = corlib_enum_type;
  764. }
  765. internal void SetCorlibTypeBuilders (Type corlib_object_type, Type corlib_value_type, Type corlib_enum_type, Type corlib_void_type)
  766. {
  767. SetCorlibTypeBuilders (corlib_object_type, corlib_value_type, corlib_enum_type);
  768. this.corlib_void_type = corlib_void_type;
  769. }
  770. private Exception not_supported () {
  771. // Strange message but this is what MS.NET prints...
  772. return new NotSupportedException ("The invoked member is not supported in a dynamic module.");
  773. }
  774. private void check_name_and_filename (string name, string fileName,
  775. bool fileNeedsToExists) {
  776. if (name == null)
  777. throw new ArgumentNullException ("name");
  778. if (fileName == null)
  779. throw new ArgumentNullException ("fileName");
  780. if (name.Length == 0)
  781. throw new ArgumentException ("Empty name is not legal.", "name");
  782. if (fileName.Length == 0)
  783. throw new ArgumentException ("Empty file name is not legal.", "fileName");
  784. if (Path.GetFileName (fileName) != fileName)
  785. throw new ArgumentException ("fileName '" + fileName + "' must not include a path.", "fileName");
  786. // Resource files are created/searched under the assembly storage
  787. // directory
  788. string fullFileName = fileName;
  789. if (dir != null)
  790. fullFileName = Path.Combine (dir, fileName);
  791. if (fileNeedsToExists && !File.Exists (fullFileName))
  792. throw new FileNotFoundException ("Could not find file '" + fileName + "'");
  793. if (resources != null) {
  794. for (int i = 0; i < resources.Length; ++i) {
  795. if (resources [i].filename == fullFileName)
  796. throw new ArgumentException ("Duplicate file name '" + fileName + "'");
  797. if (resources [i].name == name)
  798. throw new ArgumentException ("Duplicate name '" + name + "'");
  799. }
  800. }
  801. if (modules != null) {
  802. for (int i = 0; i < modules.Length; ++i) {
  803. // Use fileName instead of fullFileName here
  804. if (!modules [i].IsTransient () && (modules [i].FileName == fileName))
  805. throw new ArgumentException ("Duplicate file name '" + fileName + "'");
  806. if (modules [i].Name == name)
  807. throw new ArgumentException ("Duplicate name '" + name + "'");
  808. }
  809. }
  810. }
  811. private String create_assembly_version (String version) {
  812. String[] parts = version.Split ('.');
  813. int[] ver = new int [4] { 0, 0, 0, 0 };
  814. if ((parts.Length < 0) || (parts.Length > 4))
  815. throw new ArgumentException ("The version specified '" + version + "' is invalid");
  816. for (int i = 0; i < parts.Length; ++i) {
  817. if (parts [i] == "*") {
  818. DateTime now = DateTime.Now;
  819. if (i == 2) {
  820. ver [2] = (now - new DateTime (2000, 1, 1)).Days;
  821. if (parts.Length == 3)
  822. ver [3] = (now.Second + (now.Minute * 60) + (now.Hour * 3600)) / 2;
  823. }
  824. else
  825. if (i == 3)
  826. ver [3] = (now.Second + (now.Minute * 60) + (now.Hour * 3600)) / 2;
  827. else
  828. throw new ArgumentException ("The version specified '" + version + "' is invalid");
  829. }
  830. else {
  831. try {
  832. ver [i] = Int32.Parse (parts [i]);
  833. }
  834. catch (FormatException) {
  835. throw new ArgumentException ("The version specified '" + version + "' is invalid");
  836. }
  837. }
  838. }
  839. return ver [0] + "." + ver [1] + "." + ver [2] + "." + ver [3];
  840. }
  841. private string GetCultureString (string str)
  842. {
  843. return (str == "neutral" ? String.Empty : str);
  844. }
  845. internal override AssemblyName UnprotectedGetName ()
  846. {
  847. AssemblyName an = base.UnprotectedGetName ();
  848. if (sn != null) {
  849. an.SetPublicKey (sn.PublicKey);
  850. an.SetPublicKeyToken (sn.PublicKeyToken);
  851. }
  852. return an;
  853. }
  854. void _AssemblyBuilder.GetIDsOfNames([In] ref Guid riid, IntPtr rgszNames, uint cNames, uint lcid, IntPtr rgDispId)
  855. {
  856. throw new NotImplementedException ();
  857. }
  858. void _AssemblyBuilder.GetTypeInfo (uint iTInfo, uint lcid, IntPtr ppTInfo)
  859. {
  860. throw new NotImplementedException ();
  861. }
  862. void _AssemblyBuilder.GetTypeInfoCount (out uint pcTInfo)
  863. {
  864. throw new NotImplementedException ();
  865. }
  866. void _AssemblyBuilder.Invoke (uint dispIdMember, [In] ref Guid riid, uint lcid, short wFlags, IntPtr pDispParams, IntPtr pVarResult, IntPtr pExcepInfo, IntPtr puArgErr)
  867. {
  868. throw new NotImplementedException ();
  869. }
  870. }
  871. }