AssemblyBuilder.cs 39 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288
  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. #if MONO_FEATURE_SRE
  32. using System;
  33. using System.Reflection;
  34. using System.Resources;
  35. using System.IO;
  36. using System.Security.Policy;
  37. using System.Runtime.Serialization;
  38. using System.Globalization;
  39. using System.Runtime.CompilerServices;
  40. using System.Collections;
  41. using System.Collections.Generic;
  42. using System.Runtime.InteropServices;
  43. using System.Security;
  44. using System.Security.Cryptography;
  45. using System.Security.Permissions;
  46. using System.Threading;
  47. using Mono.Security;
  48. using Mono.Security.Cryptography;
  49. namespace System.Reflection.Emit
  50. {
  51. internal enum NativeResourceType
  52. {
  53. None,
  54. Unmanaged,
  55. Assembly,
  56. Explicit
  57. }
  58. internal struct RefEmitPermissionSet {
  59. public SecurityAction action;
  60. public string pset;
  61. public RefEmitPermissionSet (SecurityAction action, string pset) {
  62. this.action = action;
  63. this.pset = pset;
  64. }
  65. }
  66. internal struct MonoResource {
  67. #pragma warning disable 649
  68. public byte[] data;
  69. public string name;
  70. public string filename;
  71. public ResourceAttributes attrs;
  72. public int offset;
  73. public Stream stream;
  74. #pragma warning restore 649
  75. }
  76. internal struct MonoWin32Resource {
  77. public int res_type;
  78. public int res_id;
  79. public int lang_id;
  80. public byte[] data;
  81. public MonoWin32Resource (int res_type, int res_id, int lang_id, byte[] data) {
  82. this.res_type = res_type;
  83. this.res_id = res_id;
  84. this.lang_id = lang_id;
  85. this.data = data;
  86. }
  87. }
  88. internal class GenericInstanceKey {
  89. Type gtd;
  90. internal Type[] args;
  91. int hash_code;
  92. internal GenericInstanceKey (Type gtd, Type[] args)
  93. {
  94. this.gtd = gtd;
  95. this.args = args;
  96. hash_code = gtd.GetHashCode ();
  97. for (int i = 0; i < args.Length; ++i)
  98. hash_code ^= args [i].GetHashCode ();
  99. }
  100. static bool IsBoundedVector (Type type) {
  101. ArrayType at = type as ArrayType;
  102. if (at != null)
  103. return at.GetEffectiveRank () == 1;
  104. return type.ToString ().EndsWith ("[*]", StringComparison.Ordinal); /*Super uggly hack, SR doesn't allow one to query for it */
  105. }
  106. static bool TypeEquals (Type a, Type b) {
  107. if (a == b)
  108. return true;
  109. if (a.HasElementType) {
  110. if (!b.HasElementType)
  111. return false;
  112. if (!TypeEquals (a.GetElementType (), b.GetElementType ()))
  113. return false;
  114. if (a.IsArray) {
  115. if (!b.IsArray)
  116. return false;
  117. int rank = a.GetArrayRank ();
  118. if (rank != b.GetArrayRank ())
  119. return false;
  120. if (rank == 1 && IsBoundedVector (a) != IsBoundedVector (b))
  121. return false;
  122. } else if (a.IsByRef) {
  123. if (!b.IsByRef)
  124. return false;
  125. } else if (a.IsPointer) {
  126. if (!b.IsPointer)
  127. return false;
  128. }
  129. return true;
  130. }
  131. if (a.IsGenericType) {
  132. if (!b.IsGenericType)
  133. return false;
  134. if (a.IsGenericParameter)
  135. return a == b;
  136. if (a.IsGenericParameter) //previous test should have caught it
  137. return false;
  138. if (a.IsGenericTypeDefinition) {
  139. if (!b.IsGenericTypeDefinition)
  140. return false;
  141. } else {
  142. if (b.IsGenericTypeDefinition)
  143. return false;
  144. if (!TypeEquals (a.GetGenericTypeDefinition (), b.GetGenericTypeDefinition ()))
  145. return false;
  146. Type[] argsA = a.GetGenericArguments ();
  147. Type[] argsB = b.GetGenericArguments ();
  148. for (int i = 0; i < argsA.Length; ++i) {
  149. if (!TypeEquals (argsA [i], argsB [i]))
  150. return false;
  151. }
  152. }
  153. }
  154. /*
  155. Now only non-generic, non compound types are left. To properly deal with user
  156. types we would have to call UnderlyingSystemType, but we let them have their
  157. own instantiation as this is MS behavior and mcs (pre C# 4.0, at least) doesn't
  158. depend on proper UT canonicalization.
  159. */
  160. return a == b;
  161. }
  162. public override bool Equals (object obj)
  163. {
  164. GenericInstanceKey other = obj as GenericInstanceKey;
  165. if (other == null)
  166. return false;
  167. if (gtd != other.gtd)
  168. return false;
  169. for (int i = 0; i < args.Length; ++i) {
  170. Type a = args [i];
  171. Type b = other.args [i];
  172. /*
  173. We must cannonicalize as much as we can. Using equals means that some resulting types
  174. won't have the exact same types as the argument ones.
  175. For example, flyweight types used array, pointer and byref will should this behavior.
  176. MCS seens to be resilient to this problem so hopefully this won't show up.
  177. */
  178. if (a != b && !a.Equals (b))
  179. return false;
  180. }
  181. return true;
  182. }
  183. public override int GetHashCode ()
  184. {
  185. return hash_code;
  186. }
  187. }
  188. #if !MOBILE
  189. [ComVisible (true)]
  190. [ComDefaultInterface (typeof (_AssemblyBuilder))]
  191. [ClassInterface (ClassInterfaceType.None)]
  192. partial class AssemblyBuilder : _AssemblyBuilder
  193. {
  194. void _AssemblyBuilder.GetIDsOfNames([In] ref Guid riid, IntPtr rgszNames, uint cNames, uint lcid, IntPtr rgDispId)
  195. {
  196. throw new NotImplementedException ();
  197. }
  198. void _AssemblyBuilder.GetTypeInfo (uint iTInfo, uint lcid, IntPtr ppTInfo)
  199. {
  200. throw new NotImplementedException ();
  201. }
  202. void _AssemblyBuilder.GetTypeInfoCount (out uint pcTInfo)
  203. {
  204. throw new NotImplementedException ();
  205. }
  206. void _AssemblyBuilder.Invoke (uint dispIdMember, [In] ref Guid riid, uint lcid, short wFlags, IntPtr pDispParams, IntPtr pVarResult, IntPtr pExcepInfo, IntPtr puArgErr)
  207. {
  208. throw new NotImplementedException ();
  209. }
  210. }
  211. #endif
  212. [StructLayout (LayoutKind.Sequential)]
  213. public sealed partial class AssemblyBuilder : Assembly
  214. {
  215. //
  216. // AssemblyBuilder inherits from Assembly, but the runtime thinks its layout inherits from RuntimeAssembly
  217. //
  218. #region Sync with RuntimeAssembly.cs and ReflectionAssembly in object-internals.h
  219. #pragma warning disable 649
  220. internal IntPtr _mono_assembly;
  221. #pragma warning restore 649
  222. #if !MOBILE
  223. internal Evidence _evidence;
  224. #else
  225. object _evidence;
  226. #endif
  227. #endregion
  228. #pragma warning disable 169, 414, 649
  229. #region Sync with object-internals.h
  230. private UIntPtr dynamic_assembly; /* GC-tracked */
  231. private MethodInfo entry_point;
  232. private ModuleBuilder[] modules;
  233. private string name;
  234. private string dir;
  235. private CustomAttributeBuilder[] cattrs;
  236. private MonoResource[] resources;
  237. byte[] public_key;
  238. string version;
  239. string culture;
  240. uint algid;
  241. uint flags;
  242. PEFileKinds pekind = PEFileKinds.Dll;
  243. bool delay_sign;
  244. uint access;
  245. Module[] loaded_modules;
  246. MonoWin32Resource[] win32_resources;
  247. private RefEmitPermissionSet[] permissions_minimum;
  248. private RefEmitPermissionSet[] permissions_optional;
  249. private RefEmitPermissionSet[] permissions_refused;
  250. PortableExecutableKinds peKind;
  251. ImageFileMachine machine;
  252. bool corlib_internal;
  253. Type[] type_forwarders;
  254. byte[] pktoken;
  255. #endregion
  256. #pragma warning restore 169, 414, 649
  257. #if !MOBILE
  258. internal PermissionSet _minimum; // for SecurityAction.RequestMinimum
  259. internal PermissionSet _optional; // for SecurityAction.RequestOptional
  260. internal PermissionSet _refuse; // for SecurityAction.RequestRefuse
  261. internal PermissionSet _granted; // for the resolved assembly granted permissions
  262. internal PermissionSet _denied; // for the resolved assembly denied permissions
  263. #else
  264. object _minimum, _optional, _refuse, _granted, _denied;
  265. #endif
  266. string assemblyName;
  267. internal Type corlib_object_type = typeof (System.Object);
  268. internal Type corlib_value_type = typeof (System.ValueType);
  269. internal Type corlib_enum_type = typeof (System.Enum);
  270. internal Type corlib_void_type = typeof (void);
  271. ArrayList resource_writers = null;
  272. Win32VersionResource version_res;
  273. bool created;
  274. bool is_module_only;
  275. private Mono.Security.StrongName sn;
  276. NativeResourceType native_resource;
  277. string versioninfo_culture;
  278. [MethodImplAttribute(MethodImplOptions.InternalCall)]
  279. private static extern void basic_init (AssemblyBuilder ab);
  280. [MethodImplAttribute(MethodImplOptions.InternalCall)]
  281. static extern void UpdateNativeCustomAttributes (AssemblyBuilder ab);
  282. /* Keep this in sync with codegen.cs in mcs */
  283. private const AssemblyBuilderAccess COMPILER_ACCESS = (AssemblyBuilderAccess) 0x800;
  284. [PreserveDependency ("RuntimeResolve", "System.Reflection.Emit.ModuleBuilder")]
  285. internal AssemblyBuilder (AssemblyName n, string directory, AssemblyBuilderAccess access, bool corlib_internal)
  286. {
  287. /* This is obsolete now, as mcs doesn't use SRE any more */
  288. if ((access & COMPILER_ACCESS) != 0)
  289. throw new NotImplementedException ("COMPILER_ACCESS is no longer supperted, use a newer mcs.");
  290. if (!Enum.IsDefined (typeof (AssemblyBuilderAccess), access))
  291. throw new ArgumentException (string.Format (CultureInfo.InvariantCulture,
  292. "Argument value {0} is not valid.", (int) access),
  293. "access");
  294. name = n.Name;
  295. this.access = (uint)access;
  296. flags = (uint) n.Flags;
  297. // don't call GetCurrentDirectory for Run-only builders (CAS may not like that)
  298. if (IsSave && (directory == null || directory.Length == 0)) {
  299. dir = Directory.GetCurrentDirectory ();
  300. } else {
  301. dir = directory;
  302. }
  303. /* Set defaults from n */
  304. if (n.CultureInfo != null) {
  305. culture = n.CultureInfo.Name;
  306. versioninfo_culture = n.CultureInfo.Name;
  307. }
  308. Version v = n.Version;
  309. if (v != null) {
  310. version = v.ToString ();
  311. }
  312. if (n.KeyPair != null) {
  313. // full keypair is available (for signing)
  314. sn = n.KeyPair.StrongName ();
  315. } else {
  316. // public key is available (for delay-signing)
  317. byte[] pk = n.GetPublicKey ();
  318. if ((pk != null) && (pk.Length > 0)) {
  319. sn = new Mono.Security.StrongName (pk);
  320. }
  321. }
  322. if (sn != null)
  323. flags |= (uint) AssemblyNameFlags.PublicKey;
  324. this.corlib_internal = corlib_internal;
  325. if (sn != null) {
  326. this.pktoken = new byte[sn.PublicKeyToken.Length * 2];
  327. int pkti = 0;
  328. foreach (byte pkb in sn.PublicKeyToken) {
  329. string part = pkb.ToString("x2");
  330. this.pktoken[pkti++] = (byte)part[0];
  331. this.pktoken[pkti++] = (byte)part[1];
  332. }
  333. }
  334. basic_init (this);
  335. }
  336. public override string CodeBase {
  337. get { throw not_supported (); }
  338. }
  339. public override string EscapedCodeBase {
  340. get { return RuntimeAssembly.GetCodeBase (this, true); }
  341. }
  342. public override MethodInfo EntryPoint {
  343. get {
  344. return entry_point;
  345. }
  346. }
  347. public override string Location {
  348. get {
  349. throw not_supported ();
  350. }
  351. }
  352. /* This is to keep signature compatibility with MS.NET */
  353. public override string ImageRuntimeVersion {
  354. get {
  355. return RuntimeAssembly.InternalImageRuntimeVersion (this);
  356. }
  357. }
  358. [MonoTODO]
  359. public override bool ReflectionOnly {
  360. get { return base.ReflectionOnly; }
  361. }
  362. public void AddResourceFile (string name, string fileName)
  363. {
  364. AddResourceFile (name, fileName, ResourceAttributes.Public);
  365. }
  366. public void AddResourceFile (string name, string fileName, ResourceAttributes attribute)
  367. {
  368. AddResourceFile (name, fileName, attribute, true);
  369. }
  370. private void AddResourceFile (string name, string fileName, ResourceAttributes attribute, bool fileNeedsToExists)
  371. {
  372. check_name_and_filename (name, fileName, fileNeedsToExists);
  373. // Resource files are created/searched under the assembly storage
  374. // directory
  375. if (dir != null)
  376. fileName = Path.Combine (dir, fileName);
  377. if (resources != null) {
  378. MonoResource[] new_r = new MonoResource [resources.Length + 1];
  379. System.Array.Copy(resources, new_r, resources.Length);
  380. resources = new_r;
  381. } else {
  382. resources = new MonoResource [1];
  383. }
  384. int p = resources.Length - 1;
  385. resources [p].name = name;
  386. resources [p].filename = fileName;
  387. resources [p].attrs = attribute;
  388. }
  389. internal void AddPermissionRequests (PermissionSet required, PermissionSet optional, PermissionSet refused)
  390. {
  391. #if !MOBILE
  392. if (created)
  393. throw new InvalidOperationException ("Assembly was already saved.");
  394. // required for base Assembly class (so the permissions
  395. // can be used even if the assembly isn't saved to disk)
  396. _minimum = required;
  397. _optional = optional;
  398. _refuse = refused;
  399. // required to reuse AddDeclarativeSecurity support
  400. // already present in the runtime
  401. if (required != null) {
  402. permissions_minimum = new RefEmitPermissionSet [1];
  403. permissions_minimum [0] = new RefEmitPermissionSet (
  404. SecurityAction.RequestMinimum, required.ToXml ().ToString ());
  405. }
  406. if (optional != null) {
  407. permissions_optional = new RefEmitPermissionSet [1];
  408. permissions_optional [0] = new RefEmitPermissionSet (
  409. SecurityAction.RequestOptional, optional.ToXml ().ToString ());
  410. }
  411. if (refused != null) {
  412. permissions_refused = new RefEmitPermissionSet [1];
  413. permissions_refused [0] = new RefEmitPermissionSet (
  414. SecurityAction.RequestRefuse, refused.ToXml ().ToString ());
  415. }
  416. #endif
  417. }
  418. // Still in use by al.exe
  419. internal void EmbedResourceFile (string name, string fileName)
  420. {
  421. EmbedResourceFile (name, fileName, ResourceAttributes.Public);
  422. }
  423. void EmbedResourceFile (string name, string fileName, ResourceAttributes attribute)
  424. {
  425. if (resources != null) {
  426. MonoResource[] new_r = new MonoResource [resources.Length + 1];
  427. System.Array.Copy(resources, new_r, resources.Length);
  428. resources = new_r;
  429. } else {
  430. resources = new MonoResource [1];
  431. }
  432. int p = resources.Length - 1;
  433. resources [p].name = name;
  434. resources [p].attrs = attribute;
  435. try {
  436. FileStream s = new FileStream (fileName, FileMode.Open, FileAccess.Read);
  437. long len = s.Length;
  438. resources [p].data = new byte [len];
  439. s.Read (resources [p].data, 0, (int)len);
  440. s.Close ();
  441. } catch {
  442. }
  443. }
  444. /*
  445. internal void EmbedResource (string name, byte[] blob, ResourceAttributes attribute)
  446. {
  447. if (resources != null) {
  448. MonoResource[] new_r = new MonoResource [resources.Length + 1];
  449. System.Array.Copy(resources, new_r, resources.Length);
  450. resources = new_r;
  451. } else {
  452. resources = new MonoResource [1];
  453. }
  454. int p = resources.Length - 1;
  455. resources [p].name = name;
  456. resources [p].attrs = attribute;
  457. resources [p].data = blob;
  458. }
  459. */
  460. public static AssemblyBuilder DefineDynamicAssembly (AssemblyName name, AssemblyBuilderAccess access)
  461. {
  462. if (name == null)
  463. throw new ArgumentNullException ("name");
  464. return new AssemblyBuilder (name, null, access, false);
  465. }
  466. public static AssemblyBuilder DefineDynamicAssembly (AssemblyName name, AssemblyBuilderAccess access, IEnumerable<CustomAttributeBuilder> assemblyAttributes)
  467. {
  468. var ab = DefineDynamicAssembly (name, access);
  469. foreach (var attr in assemblyAttributes) {
  470. ab.SetCustomAttribute (attr);
  471. }
  472. return ab;
  473. }
  474. public ModuleBuilder DefineDynamicModule (string name)
  475. {
  476. return DefineDynamicModule (name, name, false, true);
  477. }
  478. public ModuleBuilder DefineDynamicModule (string name, bool emitSymbolInfo)
  479. {
  480. return DefineDynamicModule (name, name, emitSymbolInfo, true);
  481. }
  482. public ModuleBuilder DefineDynamicModule(string name, string fileName)
  483. {
  484. return DefineDynamicModule (name, fileName, false, false);
  485. }
  486. public ModuleBuilder DefineDynamicModule (string name, string fileName,
  487. bool emitSymbolInfo)
  488. {
  489. return DefineDynamicModule (name, fileName, emitSymbolInfo, false);
  490. }
  491. private ModuleBuilder DefineDynamicModule (string name, string fileName, bool emitSymbolInfo, bool transient)
  492. {
  493. check_name_and_filename (name, fileName, false);
  494. if (!transient) {
  495. if (Path.GetExtension (fileName) == String.Empty)
  496. throw new ArgumentException ("Module file name '" + fileName + "' must have file extension.");
  497. if (!IsSave)
  498. throw new NotSupportedException ("Persistable modules are not supported in a dynamic assembly created with AssemblyBuilderAccess.Run");
  499. if (created)
  500. throw new InvalidOperationException ("Assembly was already saved.");
  501. }
  502. ModuleBuilder r = new ModuleBuilder (this, name, fileName, emitSymbolInfo, transient);
  503. if ((modules != null) && is_module_only)
  504. throw new InvalidOperationException ("A module-only assembly can only contain one module.");
  505. if (modules != null) {
  506. ModuleBuilder[] new_modules = new ModuleBuilder [modules.Length + 1];
  507. System.Array.Copy(modules, new_modules, modules.Length);
  508. modules = new_modules;
  509. } else {
  510. modules = new ModuleBuilder [1];
  511. }
  512. modules [modules.Length - 1] = r;
  513. return r;
  514. }
  515. public IResourceWriter DefineResource (string name, string description, string fileName)
  516. {
  517. return DefineResource (name, description, fileName, ResourceAttributes.Public);
  518. }
  519. public IResourceWriter DefineResource (string name, string description,
  520. string fileName, ResourceAttributes attribute)
  521. {
  522. IResourceWriter writer;
  523. // description seems to be ignored
  524. AddResourceFile (name, fileName, attribute, false);
  525. writer = new ResourceWriter (fileName);
  526. if (resource_writers == null)
  527. resource_writers = new ArrayList ();
  528. resource_writers.Add (writer);
  529. return writer;
  530. }
  531. private void AddUnmanagedResource (Win32Resource res) {
  532. MemoryStream ms = new MemoryStream ();
  533. res.WriteTo (ms);
  534. if (win32_resources != null) {
  535. MonoWin32Resource[] new_res = new MonoWin32Resource [win32_resources.Length + 1];
  536. System.Array.Copy (win32_resources, new_res, win32_resources.Length);
  537. win32_resources = new_res;
  538. }
  539. else
  540. win32_resources = new MonoWin32Resource [1];
  541. win32_resources [win32_resources.Length - 1] = new MonoWin32Resource (res.Type.Id, res.Name.Id, res.Language, ms.ToArray ());
  542. }
  543. [MonoTODO ("Not currently implemenented")]
  544. public void DefineUnmanagedResource (byte[] resource)
  545. {
  546. if (resource == null)
  547. throw new ArgumentNullException ("resource");
  548. if (native_resource != NativeResourceType.None)
  549. throw new ArgumentException ("Native resource has already been defined.");
  550. // avoid definition of more than one unmanaged resource
  551. native_resource = NativeResourceType.Unmanaged;
  552. /*
  553. * The format of the argument byte array is not documented
  554. * so this method is impossible to implement.
  555. *
  556. * https://connect.microsoft.com/VisualStudio/feedback/details/95784/fatal-assemblybuilder-defineunmanagedresource-byte-and-modulebuilder-defineunmanagedresource-byte-bugs-renders-them-useless
  557. */
  558. throw new NotImplementedException ();
  559. }
  560. public void DefineUnmanagedResource (string resourceFileName)
  561. {
  562. if (resourceFileName == null)
  563. throw new ArgumentNullException ("resourceFileName");
  564. if (resourceFileName.Length == 0)
  565. throw new ArgumentException ("resourceFileName");
  566. if (!File.Exists (resourceFileName) || Directory.Exists (resourceFileName))
  567. throw new FileNotFoundException ("File '" + resourceFileName + "' does not exist or is a directory.");
  568. if (native_resource != NativeResourceType.None)
  569. throw new ArgumentException ("Native resource has already been defined.");
  570. // avoid definition of more than one unmanaged resource
  571. native_resource = NativeResourceType.Unmanaged;
  572. using (FileStream fs = new FileStream (resourceFileName, FileMode.Open, FileAccess.Read)) {
  573. Win32ResFileReader reader = new Win32ResFileReader (fs);
  574. foreach (Win32EncodedResource res in reader.ReadResources ()) {
  575. if (res.Name.IsName || res.Type.IsName)
  576. throw new InvalidOperationException ("resource files with named resources or non-default resource types are not supported.");
  577. AddUnmanagedResource (res);
  578. }
  579. }
  580. }
  581. public void DefineVersionInfoResource ()
  582. {
  583. if (native_resource != NativeResourceType.None)
  584. throw new ArgumentException ("Native resource has already been defined.");
  585. // avoid definition of more than one unmanaged resource
  586. native_resource = NativeResourceType.Assembly;
  587. version_res = new Win32VersionResource (1, 0, false);
  588. }
  589. public void DefineVersionInfoResource (string product, string productVersion,
  590. string company, string copyright, string trademark)
  591. {
  592. if (native_resource != NativeResourceType.None)
  593. throw new ArgumentException ("Native resource has already been defined.");
  594. // avoid definition of more than one unmanaged resource
  595. native_resource = NativeResourceType.Explicit;
  596. /*
  597. * We can only create the resource later, when the file name and
  598. * the binary version is known.
  599. */
  600. version_res = new Win32VersionResource (1, 0, false);
  601. version_res.ProductName = product != null ? product : " ";
  602. version_res.ProductVersion = productVersion != null ? productVersion : " ";
  603. version_res.CompanyName = company != null ? company : " ";
  604. version_res.LegalCopyright = copyright != null ? copyright : " ";
  605. version_res.LegalTrademarks = trademark != null ? trademark : " ";
  606. }
  607. private void DefineVersionInfoResourceImpl (string fileName)
  608. {
  609. if (versioninfo_culture != null)
  610. version_res.FileLanguage = new CultureInfo (versioninfo_culture).LCID;
  611. version_res.Version = version == null ? "0.0.0.0" : version;
  612. if (cattrs != null) {
  613. switch (native_resource) {
  614. case NativeResourceType.Assembly:
  615. foreach (CustomAttributeBuilder cb in cattrs) {
  616. string attrname = cb.Ctor.ReflectedType.FullName;
  617. if (attrname == "System.Reflection.AssemblyProductAttribute")
  618. version_res.ProductName = cb.string_arg ();
  619. else if (attrname == "System.Reflection.AssemblyCompanyAttribute")
  620. version_res.CompanyName = cb.string_arg ();
  621. else if (attrname == "System.Reflection.AssemblyCopyrightAttribute")
  622. version_res.LegalCopyright = cb.string_arg ();
  623. else if (attrname == "System.Reflection.AssemblyTrademarkAttribute")
  624. version_res.LegalTrademarks = cb.string_arg ();
  625. else if (attrname == "System.Reflection.AssemblyCultureAttribute") {
  626. version_res.FileLanguage = new CultureInfo (cb.string_arg ()).LCID;
  627. } else if (attrname == "System.Reflection.AssemblyFileVersionAttribute") {
  628. version_res.FileVersion = cb.string_arg ();
  629. } else if (attrname == "System.Reflection.AssemblyInformationalVersionAttribute")
  630. version_res.ProductVersion = cb.string_arg ();
  631. else if (attrname == "System.Reflection.AssemblyTitleAttribute")
  632. version_res.FileDescription = cb.string_arg ();
  633. else if (attrname == "System.Reflection.AssemblyDescriptionAttribute")
  634. version_res.Comments = cb.string_arg ();
  635. }
  636. break;
  637. case NativeResourceType.Explicit:
  638. foreach (CustomAttributeBuilder cb in cattrs) {
  639. string attrname = cb.Ctor.ReflectedType.FullName;
  640. if (attrname == "System.Reflection.AssemblyCultureAttribute") {
  641. version_res.FileLanguage = new CultureInfo (cb.string_arg ()).LCID;
  642. } else if (attrname == "System.Reflection.AssemblyDescriptionAttribute")
  643. version_res.Comments = cb.string_arg ();
  644. }
  645. break;
  646. }
  647. }
  648. version_res.OriginalFilename = fileName;
  649. version_res.InternalName = Path.GetFileNameWithoutExtension (fileName);
  650. AddUnmanagedResource (version_res);
  651. }
  652. public ModuleBuilder GetDynamicModule (string name)
  653. {
  654. if (name == null)
  655. throw new ArgumentNullException ("name");
  656. if (name.Length == 0)
  657. throw new ArgumentException ("Empty name is not legal.", "name");
  658. if (modules != null)
  659. for (int i = 0; i < modules.Length; ++i)
  660. if (modules [i].name == name)
  661. return modules [i];
  662. return null;
  663. }
  664. public override Type[] GetExportedTypes ()
  665. {
  666. throw not_supported ();
  667. }
  668. public override FileStream GetFile (string name)
  669. {
  670. throw not_supported ();
  671. }
  672. public override FileStream[] GetFiles(bool getResourceModules) {
  673. throw not_supported ();
  674. }
  675. internal override Module[] GetModulesInternal () {
  676. if (modules == null)
  677. return new Module [0];
  678. else
  679. return (Module[])modules.Clone ();
  680. }
  681. internal override Type[] GetTypes (bool exportedOnly) {
  682. Type[] res = null;
  683. if (modules != null) {
  684. for (int i = 0; i < modules.Length; ++i) {
  685. Type[] types = modules [i].GetTypes ();
  686. if (res == null)
  687. res = types;
  688. else {
  689. Type[] tmp = new Type [res.Length + types.Length];
  690. Array.Copy (res, 0, tmp, 0, res.Length);
  691. Array.Copy (types, 0, tmp, res.Length, types.Length);
  692. }
  693. }
  694. }
  695. if (loaded_modules != null) {
  696. for (int i = 0; i < loaded_modules.Length; ++i) {
  697. Type[] types = loaded_modules [i].GetTypes ();
  698. if (res == null)
  699. res = types;
  700. else {
  701. Type[] tmp = new Type [res.Length + types.Length];
  702. Array.Copy (res, 0, tmp, 0, res.Length);
  703. Array.Copy (types, 0, tmp, res.Length, types.Length);
  704. }
  705. }
  706. }
  707. if (res != null) {
  708. List<Exception> exceptions = null;
  709. foreach (var type in res) {
  710. if (type is TypeBuilder) {
  711. if (exceptions == null)
  712. exceptions = new List <Exception> ();
  713. exceptions.Add (new TypeLoadException (string.Format ("Type '{0}' is not finished", type.FullName)));
  714. }
  715. }
  716. if (exceptions != null)
  717. throw new ReflectionTypeLoadException (new Type [exceptions.Count], exceptions.ToArray ());
  718. }
  719. return res == null ? Type.EmptyTypes : res;
  720. }
  721. public override ManifestResourceInfo GetManifestResourceInfo(string resourceName) {
  722. throw not_supported ();
  723. }
  724. public override string[] GetManifestResourceNames() {
  725. throw not_supported ();
  726. }
  727. public override Stream GetManifestResourceStream(string name) {
  728. throw not_supported ();
  729. }
  730. public override Stream GetManifestResourceStream(Type type, string name) {
  731. throw not_supported ();
  732. }
  733. internal bool IsSave {
  734. get {
  735. return access != (uint)AssemblyBuilderAccess.Run;
  736. }
  737. }
  738. internal bool IsRun {
  739. get {
  740. return access == (uint)AssemblyBuilderAccess.Run || access == (uint)AssemblyBuilderAccess.RunAndSave
  741. || access == (uint)AssemblyBuilderAccess.RunAndCollect
  742. ;
  743. }
  744. }
  745. /*
  746. internal bool IsCollectible {
  747. get {
  748. return access == (uint)AssemblyBuilderAccess.RunAndCollect;
  749. }
  750. }
  751. */
  752. internal string AssemblyDir {
  753. get {
  754. return dir;
  755. }
  756. }
  757. /*
  758. * Mono extension. If this is set, the assembly can only contain one
  759. * module, access should be Save, and the saved image will not contain an
  760. * assembly manifest.
  761. */
  762. internal bool IsModuleOnly {
  763. get {
  764. return is_module_only;
  765. }
  766. set {
  767. is_module_only = value;
  768. }
  769. }
  770. ModuleBuilder manifest_module;
  771. //
  772. // MS.NET seems to return a ModuleBuilder when GetManifestModule () is called
  773. // on an assemblybuilder.
  774. //
  775. internal override Module GetManifestModule () {
  776. if (manifest_module == null)
  777. manifest_module = DefineDynamicModule ("Default Dynamic Module");
  778. return manifest_module;
  779. }
  780. [MonoLimitation ("No support for PE32+ assemblies for AMD64 and IA64")]
  781. public
  782. void Save (string assemblyFileName, PortableExecutableKinds portableExecutableKind, ImageFileMachine imageFileMachine)
  783. {
  784. this.peKind = portableExecutableKind;
  785. this.machine = imageFileMachine;
  786. if ((peKind & PortableExecutableKinds.PE32Plus) != 0 || (peKind & PortableExecutableKinds.Unmanaged32Bit) != 0)
  787. throw new NotImplementedException (peKind.ToString ());
  788. if (machine == ImageFileMachine.IA64 || machine == ImageFileMachine.AMD64)
  789. throw new NotImplementedException (machine.ToString ());
  790. if (resource_writers != null) {
  791. foreach (IResourceWriter writer in resource_writers) {
  792. writer.Generate ();
  793. writer.Close ();
  794. }
  795. }
  796. // Create a main module if not already created
  797. ModuleBuilder mainModule = null;
  798. if (modules != null) {
  799. foreach (ModuleBuilder module in modules)
  800. if (module.FullyQualifiedName == assemblyFileName)
  801. mainModule = module;
  802. }
  803. if (mainModule == null)
  804. mainModule = DefineDynamicModule ("RefEmit_OnDiskManifestModule", assemblyFileName);
  805. if (!is_module_only)
  806. mainModule.IsMain = true;
  807. /*
  808. * Create a new entry point if the one specified
  809. * by the user is in another module.
  810. */
  811. if ((entry_point != null) && entry_point.DeclaringType.Module != mainModule) {
  812. Type[] paramTypes;
  813. if (entry_point.GetParametersCount () == 1)
  814. paramTypes = new Type [] { typeof (string) };
  815. else
  816. paramTypes = Type.EmptyTypes;
  817. MethodBuilder mb = mainModule.DefineGlobalMethod ("__EntryPoint$", MethodAttributes.Static|MethodAttributes.PrivateScope, entry_point.ReturnType, paramTypes);
  818. ILGenerator ilgen = mb.GetILGenerator ();
  819. if (paramTypes.Length == 1)
  820. ilgen.Emit (OpCodes.Ldarg_0);
  821. ilgen.Emit (OpCodes.Tailcall);
  822. ilgen.Emit (OpCodes.Call, entry_point);
  823. ilgen.Emit (OpCodes.Ret);
  824. entry_point = mb;
  825. }
  826. if (version_res != null)
  827. DefineVersionInfoResourceImpl (assemblyFileName);
  828. if (sn != null) {
  829. // runtime needs to value to embed it into the assembly
  830. public_key = sn.PublicKey;
  831. }
  832. foreach (ModuleBuilder module in modules)
  833. if (module != mainModule)
  834. module.Save ();
  835. // Write out the main module at the end, because it needs to
  836. // contain the hash of the other modules
  837. mainModule.Save ();
  838. if ((sn != null) && (sn.CanSign)) {
  839. sn.Sign (System.IO.Path.Combine (this.AssemblyDir, assemblyFileName));
  840. }
  841. created = true;
  842. }
  843. public void Save (string assemblyFileName)
  844. {
  845. Save (assemblyFileName, PortableExecutableKinds.ILOnly, ImageFileMachine.I386);
  846. }
  847. public void SetEntryPoint (MethodInfo entryMethod)
  848. {
  849. SetEntryPoint (entryMethod, PEFileKinds.ConsoleApplication);
  850. }
  851. public void SetEntryPoint (MethodInfo entryMethod, PEFileKinds fileKind)
  852. {
  853. if (entryMethod == null)
  854. throw new ArgumentNullException ("entryMethod");
  855. if (entryMethod.DeclaringType.Assembly != this)
  856. throw new InvalidOperationException ("Entry method is not defined in the same assembly.");
  857. entry_point = entryMethod;
  858. pekind = fileKind;
  859. }
  860. public void SetCustomAttribute( CustomAttributeBuilder customBuilder)
  861. {
  862. if (customBuilder == null)
  863. throw new ArgumentNullException ("customBuilder");
  864. if (cattrs != null) {
  865. CustomAttributeBuilder[] new_array = new CustomAttributeBuilder [cattrs.Length + 1];
  866. cattrs.CopyTo (new_array, 0);
  867. new_array [cattrs.Length] = customBuilder;
  868. cattrs = new_array;
  869. } else {
  870. cattrs = new CustomAttributeBuilder [1];
  871. cattrs [0] = customBuilder;
  872. }
  873. /*
  874. Only update the native list of custom attributes if we're adding one that is known to change dynamic execution behavior.
  875. */
  876. if (customBuilder.Ctor != null && customBuilder.Ctor.DeclaringType == typeof (System.Runtime.CompilerServices.RuntimeCompatibilityAttribute))
  877. UpdateNativeCustomAttributes (this);
  878. }
  879. [ComVisible (true)]
  880. public void SetCustomAttribute ( ConstructorInfo con, byte[] binaryAttribute) {
  881. if (con == null)
  882. throw new ArgumentNullException ("con");
  883. if (binaryAttribute == null)
  884. throw new ArgumentNullException ("binaryAttribute");
  885. SetCustomAttribute (new CustomAttributeBuilder (con, binaryAttribute));
  886. }
  887. private Exception not_supported () {
  888. // Strange message but this is what MS.NET prints...
  889. return new NotSupportedException ("The invoked member is not supported in a dynamic module.");
  890. }
  891. private void check_name_and_filename (string name, string fileName,
  892. bool fileNeedsToExists) {
  893. if (name == null)
  894. throw new ArgumentNullException ("name");
  895. if (fileName == null)
  896. throw new ArgumentNullException ("fileName");
  897. if (name.Length == 0)
  898. throw new ArgumentException ("Empty name is not legal.", "name");
  899. if (fileName.Length == 0)
  900. throw new ArgumentException ("Empty file name is not legal.", "fileName");
  901. if (Path.GetFileName (fileName) != fileName)
  902. throw new ArgumentException ("fileName '" + fileName + "' must not include a path.", "fileName");
  903. // Resource files are created/searched under the assembly storage
  904. // directory
  905. string fullFileName = fileName;
  906. if (dir != null)
  907. fullFileName = Path.Combine (dir, fileName);
  908. if (fileNeedsToExists && !File.Exists (fullFileName))
  909. throw new FileNotFoundException ("Could not find file '" + fileName + "'");
  910. if (resources != null) {
  911. for (int i = 0; i < resources.Length; ++i) {
  912. if (resources [i].filename == fullFileName)
  913. throw new ArgumentException ("Duplicate file name '" + fileName + "'");
  914. if (resources [i].name == name)
  915. throw new ArgumentException ("Duplicate name '" + name + "'");
  916. }
  917. }
  918. if (modules != null) {
  919. for (int i = 0; i < modules.Length; ++i) {
  920. // Use fileName instead of fullFileName here
  921. if (!modules [i].IsTransient () && (modules [i].FileName == fileName))
  922. throw new ArgumentException ("Duplicate file name '" + fileName + "'");
  923. if (modules [i].Name == name)
  924. throw new ArgumentException ("Duplicate name '" + name + "'");
  925. }
  926. }
  927. }
  928. private String create_assembly_version (String version) {
  929. String[] parts = version.Split ('.');
  930. int[] ver = new int [4] { 0, 0, 0, 0 };
  931. if ((parts.Length < 0) || (parts.Length > 4))
  932. throw new ArgumentException ("The version specified '" + version + "' is invalid");
  933. for (int i = 0; i < parts.Length; ++i) {
  934. if (parts [i] == "*") {
  935. DateTime now = DateTime.Now;
  936. if (i == 2) {
  937. ver [2] = (now - new DateTime (2000, 1, 1)).Days;
  938. if (parts.Length == 3)
  939. ver [3] = (now.Second + (now.Minute * 60) + (now.Hour * 3600)) / 2;
  940. }
  941. else
  942. if (i == 3)
  943. ver [3] = (now.Second + (now.Minute * 60) + (now.Hour * 3600)) / 2;
  944. else
  945. throw new ArgumentException ("The version specified '" + version + "' is invalid");
  946. }
  947. else {
  948. try {
  949. ver [i] = Int32.Parse (parts [i]);
  950. }
  951. catch (FormatException) {
  952. throw new ArgumentException ("The version specified '" + version + "' is invalid");
  953. }
  954. }
  955. }
  956. return ver [0] + "." + ver [1] + "." + ver [2] + "." + ver [3];
  957. }
  958. private string GetCultureString (string str)
  959. {
  960. return (str == "neutral" ? String.Empty : str);
  961. }
  962. /*Warning, @typeArguments must be a mscorlib internal array. So make a copy before passing it in*/
  963. internal Type MakeGenericType (Type gtd, Type[] typeArguments)
  964. {
  965. return new TypeBuilderInstantiation (gtd, typeArguments);
  966. }
  967. public override Type GetType (string name, bool throwOnError, bool ignoreCase)
  968. {
  969. if (name == null)
  970. throw new ArgumentNullException (name);
  971. if (name.Length == 0)
  972. throw new ArgumentException ("name", "Name cannot be empty");
  973. var res = InternalGetType (null, name, throwOnError, ignoreCase);
  974. if (res is TypeBuilder) {
  975. if (throwOnError)
  976. throw new TypeLoadException (string.Format ("Could not load type '{0}' from assembly '{1}'", name, this.name));
  977. return null;
  978. }
  979. return res;
  980. }
  981. public override Module GetModule (String name)
  982. {
  983. if (name == null)
  984. throw new ArgumentNullException ("name");
  985. if (name.Length == 0)
  986. throw new ArgumentException ("Name can't be empty");
  987. if (modules == null)
  988. return null;
  989. foreach (Module module in modules) {
  990. if (module.ScopeName == name)
  991. return module;
  992. }
  993. return null;
  994. }
  995. public override Module[] GetModules (bool getResourceModules)
  996. {
  997. Module[] modules = GetModulesInternal ();
  998. if (!getResourceModules) {
  999. var result = new List<Module> (modules.Length);
  1000. foreach (Module m in modules)
  1001. if (!m.IsResource ())
  1002. result.Add (m);
  1003. return result.ToArray ();
  1004. }
  1005. return modules;
  1006. }
  1007. public override AssemblyName GetName (bool copiedName)
  1008. {
  1009. var aname = AssemblyName.Create (this, false);
  1010. if (sn != null) {
  1011. aname.SetPublicKey (sn.PublicKey);
  1012. aname.SetPublicKeyToken (sn.PublicKeyToken);
  1013. }
  1014. return aname;
  1015. }
  1016. [MonoTODO ("This always returns an empty array")]
  1017. public override AssemblyName[] GetReferencedAssemblies () {
  1018. return GetReferencedAssemblies (this);
  1019. }
  1020. public override Module[] GetLoadedModules (bool getResourceModules)
  1021. {
  1022. return GetModules (getResourceModules);
  1023. }
  1024. //FIXME MS has issues loading satelite assemblies from SRE
  1025. [MethodImplAttribute(MethodImplOptions.NoInlining)] // Methods containing StackCrawlMark local var has to be marked non-inlineable
  1026. public override Assembly GetSatelliteAssembly (CultureInfo culture)
  1027. {
  1028. StackCrawlMark stackMark = StackCrawlMark.LookForMyCaller;
  1029. return GetSatelliteAssembly (culture, null, true, ref stackMark);
  1030. }
  1031. //FIXME MS has issues loading satelite assemblies from SRE
  1032. [MethodImplAttribute(MethodImplOptions.NoInlining)] // Methods containing StackCrawlMark local var has to be marked non-inlineable
  1033. public override Assembly GetSatelliteAssembly (CultureInfo culture, Version version)
  1034. {
  1035. StackCrawlMark stackMark = StackCrawlMark.LookForMyCaller;
  1036. return GetSatelliteAssembly (culture, version, true, ref stackMark);
  1037. }
  1038. public override Module ManifestModule {
  1039. get {
  1040. return GetManifestModule ();
  1041. }
  1042. }
  1043. public override bool GlobalAssemblyCache {
  1044. get {
  1045. return false;
  1046. }
  1047. }
  1048. public override bool IsDynamic {
  1049. get { return true; }
  1050. }
  1051. public override bool Equals (object obj)
  1052. {
  1053. return base.Equals (obj);
  1054. }
  1055. public override int GetHashCode ()
  1056. {
  1057. return base.GetHashCode ();
  1058. }
  1059. public override string ToString ()
  1060. {
  1061. if (assemblyName != null)
  1062. return assemblyName;
  1063. assemblyName = FullName;
  1064. return assemblyName;
  1065. }
  1066. public override bool IsDefined (Type attributeType, bool inherit)
  1067. {
  1068. return MonoCustomAttrs.IsDefined (this, attributeType, inherit);
  1069. }
  1070. public override object[] GetCustomAttributes (bool inherit)
  1071. {
  1072. return MonoCustomAttrs.GetCustomAttributes (this, inherit);
  1073. }
  1074. public override object[] GetCustomAttributes (Type attributeType, bool inherit)
  1075. {
  1076. return MonoCustomAttrs.GetCustomAttributes (this, attributeType, inherit);
  1077. }
  1078. public override string FullName {
  1079. get { return RuntimeAssembly.get_fullname (this); }
  1080. }
  1081. internal override IntPtr MonoAssembly {
  1082. get {
  1083. return _mono_assembly;
  1084. }
  1085. }
  1086. public override Evidence Evidence {
  1087. [SecurityPermission (SecurityAction.Demand, ControlEvidence = true)]
  1088. get { return UnprotectedGetEvidence (); }
  1089. }
  1090. internal override Evidence UnprotectedGetEvidence ()
  1091. {
  1092. #if MOBILE
  1093. return null;
  1094. #else
  1095. // if the host (runtime) hasn't provided it's own evidence...
  1096. if (_evidence == null) {
  1097. // ... we will provide our own
  1098. lock (this) {
  1099. _evidence = Evidence.GetDefaultHostEvidence (this);
  1100. }
  1101. }
  1102. return _evidence;
  1103. #endif
  1104. }
  1105. }
  1106. }
  1107. #endif