2 // assembly.cs: Assembly declaration and specifications
5 // Miguel de Icaza (miguel@ximian.com)
6 // Marek Safar (marek.safar@gmail.com)
8 // Copyright 2001, 2002, 2003 Ximian, Inc.
9 // Copyright 2004-2011 Novell, Inc.
10 // Copyright 2011-2013 Xamarin Inc
16 using System.Collections.Generic;
17 using System.Globalization;
18 using System.Security;
19 using System.Security.Cryptography;
20 using System.Security.Permissions;
21 using Mono.Security.Cryptography;
22 using Mono.CompilerServices.SymbolWriter;
25 using IKVM.Reflection;
26 using IKVM.Reflection.Emit;
27 using SecurityType = System.Collections.Generic.List<IKVM.Reflection.Emit.CustomAttributeBuilder>;
29 using SecurityType = System.Collections.Generic.Dictionary<System.Security.Permissions.SecurityAction, System.Security.PermissionSet>;
30 using System.Reflection;
31 using System.Reflection.Emit;
36 public interface IAssemblyDefinition
38 string FullName { get; }
39 bool IsCLSCompliant { get; }
40 bool IsMissing { get; }
43 byte[] GetPublicKeyToken ();
44 bool IsFriendAssemblyTo (IAssemblyDefinition assembly);
47 public abstract class AssemblyDefinition : IAssemblyDefinition
49 // TODO: make it private and move all builder based methods here
50 public AssemblyBuilder Builder;
51 protected AssemblyBuilderExtension builder_extra;
52 MonoSymbolFile symbol_writer;
54 bool is_cls_compliant;
55 bool wrap_non_exception_throws;
56 bool wrap_non_exception_throws_custom;
58 protected ModuleContainer module;
60 protected readonly string file_name;
62 byte[] public_key, public_key_token;
65 // Holds private/public key pair when private key
67 StrongNameKeyPair private_key;
69 Attribute cls_attribute;
72 protected List<ImportedModuleDefinition> added_modules;
73 SecurityType declarative_security;
74 Dictionary<ITypeDefinition, Attribute> emitted_forwarders;
75 AssemblyAttributesPlaceholder module_target_attrs;
77 // Win32 version info values
78 string vi_product, vi_product_version, vi_company, vi_copyright, vi_trademark;
80 protected AssemblyDefinition (ModuleContainer module, string name)
83 this.name = Path.GetFileNameWithoutExtension (name);
85 wrap_non_exception_throws = true;
87 delay_sign = Compiler.Settings.StrongNameDelaySign;
90 // Load strong name key early enough for assembly importer to be able to
91 // use the keys for InternalsVisibleTo
92 // This should go somewhere close to ReferencesLoading but don't have the place yet
94 if (Compiler.Settings.HasKeyFileOrContainer) {
95 LoadPublicKey (Compiler.Settings.StrongNameKeyFile, Compiler.Settings.StrongNameKeyContainer);
99 protected AssemblyDefinition (ModuleContainer module, string name, string fileName)
100 : this (module, name)
102 this.file_name = fileName;
107 public Attribute CLSCompliantAttribute {
109 return cls_attribute;
113 public CompilerContext Compiler {
115 return module.Compiler;
120 // Assembly entry point, aka Main method
122 public Method EntryPoint {
131 public string FullName {
133 return Builder.FullName;
137 public bool HasCLSCompliantAttribute {
139 return cls_attribute != null;
143 // TODO: This should not exist here but will require more changes
144 public MetadataImporter Importer {
148 public bool IsCLSCompliant {
150 return is_cls_compliant;
154 bool IAssemblyDefinition.IsMissing {
160 public bool IsSatelliteAssembly { get; private set; }
168 public bool WrapNonExceptionThrows {
170 return wrap_non_exception_throws;
174 protected Report Report {
176 return Compiler.Report;
180 public MonoSymbolFile SymbolWriter {
182 return symbol_writer;
188 public void AddModule (ImportedModuleDefinition module)
190 if (added_modules == null) {
191 added_modules = new List<ImportedModuleDefinition> ();
192 added_modules.Add (module);
196 public void ApplyAttributeBuilder (Attribute a, MethodSpec ctor, byte[] cdata, PredefinedAttributes pa)
198 if (a.IsValidSecurityAttribute ()) {
199 a.ExtractSecurityPermissionSet (ctor, ref declarative_security);
203 if (a.Type == pa.AssemblyCulture) {
204 string value = a.GetString ();
205 if (value == null || value.Length == 0)
208 if (Compiler.Settings.Target == Target.Exe) {
209 a.Error_AttributeEmitError ("The executables cannot be satelite assemblies, remove the attribute or keep it empty");
213 if (value == "neutral")
216 if (Compiler.Settings.Target == Target.Module) {
217 SetCustomAttribute (ctor, cdata);
219 builder_extra.SetCulture (value, a.Location);
222 IsSatelliteAssembly = true;
226 if (a.Type == pa.AssemblyVersion) {
227 string value = a.GetString ();
228 if (value == null || value.Length == 0)
231 var vinfo = IsValidAssemblyVersion (value, true);
233 a.Error_AttributeEmitError (string.Format ("Specified version `{0}' is not valid", value));
237 if (Compiler.Settings.Target == Target.Module) {
238 SetCustomAttribute (ctor, cdata);
240 builder_extra.SetVersion (vinfo, a.Location);
246 if (a.Type == pa.AssemblyAlgorithmId) {
247 const int pos = 2; // skip CA header
248 uint alg = (uint) cdata [pos];
249 alg |= ((uint) cdata [pos + 1]) << 8;
250 alg |= ((uint) cdata [pos + 2]) << 16;
251 alg |= ((uint) cdata [pos + 3]) << 24;
253 if (Compiler.Settings.Target == Target.Module) {
254 SetCustomAttribute (ctor, cdata);
256 builder_extra.SetAlgorithmId (alg, a.Location);
262 if (a.Type == pa.AssemblyFlags) {
263 const int pos = 2; // skip CA header
264 uint flags = (uint) cdata[pos];
265 flags |= ((uint) cdata [pos + 1]) << 8;
266 flags |= ((uint) cdata [pos + 2]) << 16;
267 flags |= ((uint) cdata [pos + 3]) << 24;
269 // Ignore set PublicKey flag if assembly is not strongnamed
270 if ((flags & (uint) AssemblyNameFlags.PublicKey) != 0 && public_key == null)
271 flags &= ~(uint) AssemblyNameFlags.PublicKey;
273 if (Compiler.Settings.Target == Target.Module) {
274 SetCustomAttribute (ctor, cdata);
276 builder_extra.SetFlags (flags, a.Location);
282 if (a.Type == pa.TypeForwarder) {
283 TypeSpec t = a.GetArgumentType ();
284 if (t == null || TypeManager.HasElementType (t)) {
285 Report.Error (735, a.Location, "Invalid type specified as an argument for TypeForwardedTo attribute");
289 if (emitted_forwarders == null) {
290 emitted_forwarders = new Dictionary<ITypeDefinition, Attribute> ();
291 } else if (emitted_forwarders.ContainsKey (t.MemberDefinition)) {
292 Report.SymbolRelatedToPreviousError (emitted_forwarders[t.MemberDefinition].Location, null);
293 Report.Error (739, a.Location, "A duplicate type forward of type `{0}'",
294 t.GetSignatureForError ());
298 emitted_forwarders.Add (t.MemberDefinition, a);
300 if (t.MemberDefinition.DeclaringAssembly == this) {
301 Report.SymbolRelatedToPreviousError (t);
302 Report.Error (729, a.Location, "Cannot forward type `{0}' because it is defined in this assembly",
303 t.GetSignatureForError ());
308 Report.Error (730, a.Location, "Cannot forward type `{0}' because it is a nested type",
309 t.GetSignatureForError ());
313 builder_extra.AddTypeForwarder (t.GetDefinition (), a.Location);
317 if (a.Type == pa.Extension) {
318 a.Error_MisusedExtensionAttribute ();
322 if (a.Type == pa.InternalsVisibleTo) {
323 string assembly_name = a.GetString ();
324 if (assembly_name.Length == 0)
327 ParsedAssemblyName aname;
328 ParseAssemblyResult r = Fusion.ParseAssemblyName (assembly_name, out aname);
329 if (r != ParseAssemblyResult.OK) {
330 Report.Warning (1700, 3, a.Location, "Assembly reference `{0}' is invalid and cannot be resolved",
335 if (aname.Version != null || aname.Culture != null || aname.ProcessorArchitecture != ProcessorArchitecture.None) {
336 Report.Error (1725, a.Location,
337 "Friend assembly reference `{0}' is invalid. InternalsVisibleTo declarations cannot have a version, culture or processor architecture specified",
343 if (public_key != null && !aname.HasPublicKey) {
344 Report.Error (1726, a.Location,
345 "Friend assembly reference `{0}' is invalid. Strong named assemblies must specify a public key in their InternalsVisibleTo declarations",
350 } else if (a.Type == pa.RuntimeCompatibility) {
351 wrap_non_exception_throws_custom = true;
352 } else if (a.Type == pa.AssemblyFileVersion) {
353 vi_product_version = a.GetString ();
354 if (string.IsNullOrEmpty (vi_product_version) || IsValidAssemblyVersion (vi_product_version, false) == null) {
355 Report.Warning (1607, 1, a.Location, "The version number `{0}' specified for `{1}' is invalid",
356 vi_product_version, a.Name);
359 } else if (a.Type == pa.AssemblyProduct) {
360 vi_product = a.GetString ();
361 } else if (a.Type == pa.AssemblyCompany) {
362 vi_company = a.GetString ();
363 } else if (a.Type == pa.AssemblyDescription) {
364 // TODO: Needs extra api
365 } else if (a.Type == pa.AssemblyCopyright) {
366 vi_copyright = a.GetString ();
367 } else if (a.Type == pa.AssemblyTrademark) {
368 vi_trademark = a.GetString ();
371 SetCustomAttribute (ctor, cdata);
375 // When using assembly public key attributes InternalsVisibleTo key
376 // was not checked, we have to do it later when we actually know what
377 // our public key token is
379 void CheckReferencesPublicToken ()
381 // TODO: It should check only references assemblies but there is
382 // no working SRE API
383 foreach (var entry in Importer.Assemblies) {
384 var a = entry as ImportedAssemblyDefinition;
385 if (a == null || a.IsMissing)
388 if (public_key != null && !a.HasStrongName) {
389 Report.Error (1577, "Referenced assembly `{0}' does not have a strong name",
393 var ci = a.Assembly.GetName ().CultureInfo;
394 if (!ci.Equals (System.Globalization.CultureInfo.InvariantCulture)) {
395 Report.Warning (1607, 1, "Referenced assembly `{0}' has different culture setting of `{1}'",
399 if (!a.IsFriendAssemblyTo (this))
402 var attr = a.GetAssemblyVisibleToName (this);
403 var atoken = attr.GetPublicKeyToken ();
405 if (ArrayComparer.IsEqual (GetPublicKeyToken (), atoken))
408 Report.SymbolRelatedToPreviousError (a.Location);
410 "Friend access was granted to `{0}', but the output assembly is named `{1}'. Try adding a reference to `{0}' or change the output assembly name to match it",
411 attr.FullName, FullName);
415 protected AssemblyName CreateAssemblyName ()
417 var an = new AssemblyName (name);
419 if (public_key != null && Compiler.Settings.Target != Target.Module) {
421 an.SetPublicKey (public_key);
423 if (public_key.Length == 16) {
424 Report.Error (1606, "Could not sign the assembly. ECMA key can only be used to delay-sign assemblies");
425 } else if (private_key == null) {
426 Error_AssemblySigning ("The specified key file does not have a private key");
428 an.KeyPair = private_key;
436 public virtual ModuleBuilder CreateModuleBuilder ()
438 if (file_name == null)
439 throw new NotSupportedException ("transient module in static assembly");
441 var module_name = Path.GetFileName (file_name);
443 // Always initialize module without symbolInfo. We could be framework dependent
444 // but returned ISymbolWriter does not have all what we need therefore some
445 // adaptor will be needed for now we alwayas emit MDB format when generating
447 return Builder.DefineDynamicModule (module_name, module_name, false);
450 public virtual void Emit ()
452 if (Compiler.Settings.Target == Target.Module) {
453 module_target_attrs = new AssemblyAttributesPlaceholder (module, name);
454 module_target_attrs.CreateContainer ();
455 module_target_attrs.DefineContainer ();
456 module_target_attrs.Define ();
457 module.AddCompilerGeneratedClass (module_target_attrs);
458 } else if (added_modules != null) {
459 ReadModulesAssemblyAttributes ();
462 if (Compiler.Settings.GenerateDebugInfo) {
463 symbol_writer = new MonoSymbolFile ();
466 module.EmitContainer ();
468 if (module.HasExtensionMethod) {
469 var pa = module.PredefinedAttributes.Extension;
471 SetCustomAttribute (pa.Constructor, AttributeEncoder.Empty);
475 if (!IsSatelliteAssembly) {
476 if (!wrap_non_exception_throws_custom) {
477 PredefinedAttribute pa = module.PredefinedAttributes.RuntimeCompatibility;
478 if (pa.IsDefined && pa.ResolveBuilder ()) {
479 var prop = module.PredefinedMembers.RuntimeCompatibilityWrapNonExceptionThrows.Get ();
481 AttributeEncoder encoder = new AttributeEncoder ();
482 encoder.EncodeNamedPropertyArgument (prop, new BoolLiteral (Compiler.BuiltinTypes, true, Location.Null));
483 SetCustomAttribute (pa.Constructor, encoder.ToArray ());
488 if (declarative_security != null) {
490 foreach (var entry in declarative_security) {
491 Builder.__AddDeclarativeSecurity (entry);
494 throw new NotSupportedException ("Assembly-level security");
499 CheckReferencesPublicToken ();
504 public byte[] GetPublicKeyToken ()
506 if (public_key == null || public_key_token != null)
507 return public_key_token;
509 HashAlgorithm ha = SHA1.Create ();
510 byte[] hash = ha.ComputeHash (public_key);
511 // we need the last 8 bytes in reverse order
512 public_key_token = new byte[8];
513 Buffer.BlockCopy (hash, hash.Length - 8, public_key_token, 0, 8);
514 Array.Reverse (public_key_token, 0, 8);
515 return public_key_token;
519 // Either keyFile or keyContainer has to be non-null
521 void LoadPublicKey (string keyFile, string keyContainer)
523 if (keyContainer != null) {
525 private_key = new StrongNameKeyPair (keyContainer);
526 public_key = private_key.PublicKey;
528 Error_AssemblySigning ("The specified key container `" + keyContainer + "' does not exist");
534 bool key_file_exists = File.Exists (keyFile);
537 // For attribute based KeyFile do additional lookup
538 // in output assembly path
540 if (!key_file_exists && Compiler.Settings.StrongNameKeyFile == null) {
542 // The key file can be relative to output assembly
544 string test_path = Path.Combine (Path.GetDirectoryName (file_name), keyFile);
545 key_file_exists = File.Exists (test_path);
550 if (!key_file_exists) {
551 Error_AssemblySigning ("The specified key file `" + keyFile + "' does not exist");
555 using (FileStream fs = new FileStream (keyFile, FileMode.Open, FileAccess.Read)) {
556 byte[] snkeypair = new byte[fs.Length];
557 fs.Read (snkeypair, 0, snkeypair.Length);
559 // check for ECMA key
560 if (snkeypair.Length == 16) {
561 public_key = snkeypair;
566 // take it, with or without, a private key
567 RSA rsa = CryptoConvert.FromCapiKeyBlob (snkeypair);
568 // and make sure we only feed the public part to Sys.Ref
569 byte[] publickey = CryptoConvert.ToCapiPublicKeyBlob (rsa);
571 // AssemblyName.SetPublicKey requires an additional header
572 byte[] publicKeyHeader = new byte[8] { 0x00, 0x24, 0x00, 0x00, 0x04, 0x80, 0x00, 0x00 };
575 public_key = new byte[12 + publickey.Length];
576 Buffer.BlockCopy (publicKeyHeader, 0, public_key, 0, publicKeyHeader.Length);
578 // Length of Public Key (in bytes)
579 int lastPart = public_key.Length - 12;
580 public_key[8] = (byte) (lastPart & 0xFF);
581 public_key[9] = (byte) ((lastPart >> 8) & 0xFF);
582 public_key[10] = (byte) ((lastPart >> 16) & 0xFF);
583 public_key[11] = (byte) ((lastPart >> 24) & 0xFF);
585 Buffer.BlockCopy (publickey, 0, public_key, 12, publickey.Length);
587 Error_AssemblySigning ("The specified key file `" + keyFile + "' has incorrect format");
595 // TODO: Is there better way to test for a private key presence ?
596 CryptoConvert.FromCapiPrivateKeyBlob (snkeypair);
597 private_key = new StrongNameKeyPair (snkeypair);
602 void ReadModulesAssemblyAttributes ()
604 foreach (var m in added_modules) {
605 var cattrs = m.ReadAssemblyAttributes ();
609 module.OptAttributes.AddAttributes (cattrs);
613 public void Resolve ()
615 if (Compiler.Settings.Unsafe && module.PredefinedTypes.SecurityAction.Define ()) {
617 // Emits [assembly: SecurityPermissionAttribute (SecurityAction.RequestMinimum, SkipVerification = true)]
618 // when -unsafe option was specified
620 Location loc = Location.Null;
622 MemberAccess system_security_permissions = new MemberAccess (new MemberAccess (
623 new QualifiedAliasMember (QualifiedAliasMember.GlobalAlias, "System", loc), "Security", loc), "Permissions", loc);
625 var req_min = module.PredefinedMembers.SecurityActionRequestMinimum.Resolve (loc);
627 Arguments pos = new Arguments (1);
628 pos.Add (new Argument (req_min.GetConstant (null)));
630 Arguments named = new Arguments (1);
631 named.Add (new NamedArgument ("SkipVerification", loc, new BoolLiteral (Compiler.BuiltinTypes, true, loc)));
633 Attribute g = new Attribute ("assembly",
634 new MemberAccess (system_security_permissions, "SecurityPermissionAttribute"),
635 new Arguments[] { pos, named }, loc, false);
636 g.AttachTo (module, module);
638 // Disable no-location warnings (e.g. obsolete) for compiler generated attribute
639 Compiler.Report.DisableReporting ();
641 var ctor = g.Resolve ();
643 g.ExtractSecurityPermissionSet (ctor, ref declarative_security);
646 Compiler.Report.EnableReporting ();
650 if (module.OptAttributes == null)
653 // Ensure that we only have GlobalAttributes, since the Search isn't safe with other types.
654 if (!module.OptAttributes.CheckTargets())
657 cls_attribute = module.ResolveAssemblyAttribute (module.PredefinedAttributes.CLSCompliant);
659 if (cls_attribute != null) {
660 is_cls_compliant = cls_attribute.GetClsCompliantAttributeValue ();
663 if (added_modules != null && Compiler.Settings.VerifyClsCompliance && is_cls_compliant) {
664 foreach (var m in added_modules) {
665 if (!m.IsCLSCompliant) {
667 "Added modules must be marked with the CLSCompliant attribute to match the assembly",
673 Attribute a = module.ResolveAssemblyAttribute (module.PredefinedAttributes.RuntimeCompatibility);
675 var val = a.GetNamedValue ("WrapNonExceptionThrows") as BoolConstant;
677 wrap_non_exception_throws = val.Value;
681 protected void ResolveAssemblySecurityAttributes ()
683 string key_file = null;
684 string key_container = null;
686 if (module.OptAttributes != null) {
687 foreach (Attribute a in module.OptAttributes.Attrs) {
688 // cannot rely on any resolve-based members before you call Resolve
689 if (a.ExplicitTarget != "assembly")
692 // TODO: This code is buggy: comparing Attribute name without resolving is wrong.
693 // However, this is invoked by CodeGen.Init, when none of the namespaces
695 // TODO: Does not handle quoted attributes properly
697 case "AssemblyKeyFile":
698 case "AssemblyKeyFileAttribute":
699 case "System.Reflection.AssemblyKeyFileAttribute":
700 if (Compiler.Settings.StrongNameKeyFile != null) {
701 Report.SymbolRelatedToPreviousError (a.Location, a.GetSignatureForError ());
702 Report.Warning (1616, 1, "Option `{0}' overrides attribute `{1}' given in a source file or added module",
703 "keyfile", "System.Reflection.AssemblyKeyFileAttribute");
705 string value = a.GetString ();
706 if (!string.IsNullOrEmpty (value)) {
707 Error_ObsoleteSecurityAttribute (a, "keyfile");
712 case "AssemblyKeyName":
713 case "AssemblyKeyNameAttribute":
714 case "System.Reflection.AssemblyKeyNameAttribute":
715 if (Compiler.Settings.StrongNameKeyContainer != null) {
716 Report.SymbolRelatedToPreviousError (a.Location, a.GetSignatureForError ());
717 Report.Warning (1616, 1, "Option `{0}' overrides attribute `{1}' given in a source file or added module",
718 "keycontainer", "System.Reflection.AssemblyKeyNameAttribute");
720 string value = a.GetString ();
721 if (!string.IsNullOrEmpty (value)) {
722 Error_ObsoleteSecurityAttribute (a, "keycontainer");
723 key_container = value;
727 case "AssemblyDelaySign":
728 case "AssemblyDelaySignAttribute":
729 case "System.Reflection.AssemblyDelaySignAttribute":
730 bool b = a.GetBoolean ();
732 Error_ObsoleteSecurityAttribute (a, "delaysign");
741 // We came here only to report assembly attributes warnings
742 if (public_key != null)
746 // Load the strong key file found in attributes when no
747 // command line key was given
749 if (key_file != null || key_container != null) {
750 LoadPublicKey (key_file, key_container);
751 } else if (delay_sign) {
752 Report.Warning (1607, 1, "Delay signing was requested but no key file was given");
756 public void EmbedResources ()
759 // Add Win32 resources
761 if (Compiler.Settings.Win32ResourceFile != null) {
762 Builder.DefineUnmanagedResource (Compiler.Settings.Win32ResourceFile);
764 Builder.DefineVersionInfoResource (vi_product, vi_product_version, vi_company, vi_copyright, vi_trademark);
767 if (Compiler.Settings.Win32IconFile != null) {
768 builder_extra.DefineWin32IconResource (Compiler.Settings.Win32IconFile);
771 if (Compiler.Settings.Resources != null) {
772 if (Compiler.Settings.Target == Target.Module) {
773 Report.Error (1507, "Cannot link resource file when building a module");
776 foreach (var res in Compiler.Settings.Resources) {
777 if (!File.Exists (res.FileName)) {
778 Report.Error (1566, "Error reading resource file `{0}'", res.FileName);
784 if (counter++ < 10) {
785 stream = File.OpenRead (res.FileName);
787 // TODO: SRE API requires resource stream to be available during AssemblyBuilder::Save
788 // we workaround it by reading everything into memory to compile projects with
789 // many embedded resource (over 3500) references
790 stream = new MemoryStream (File.ReadAllBytes (res.FileName));
793 module.Builder.DefineManifestResource (res.Name, stream, res.Attributes);
795 Builder.AddResourceFile (res.Name, Path.GetFileName (res.FileName), res.Attributes);
804 PortableExecutableKinds pekind = PortableExecutableKinds.ILOnly;
805 ImageFileMachine machine;
807 switch (Compiler.Settings.Platform) {
809 pekind |= PortableExecutableKinds.Required32Bit;
810 machine = ImageFileMachine.I386;
813 pekind |= PortableExecutableKinds.PE32Plus;
814 machine = ImageFileMachine.AMD64;
817 machine = ImageFileMachine.IA64;
819 case Platform.AnyCPU32Preferred:
821 pekind |= PortableExecutableKinds.Preferred32Bit;
822 machine = ImageFileMachine.I386;
825 throw new NotSupportedException ();
829 machine = ImageFileMachine.ARM;
832 throw new NotSupportedException ();
834 case Platform.AnyCPU:
836 machine = ImageFileMachine.I386;
840 Compiler.TimeReporter.Start (TimeReporter.TimerType.OutputSave);
842 if (Compiler.Settings.Target == Target.Module) {
843 SaveModule (pekind, machine);
845 Builder.Save (module.Builder.ScopeName, pekind, machine);
847 } catch (Exception e) {
848 Report.Error (16, "Could not write to file `" + name + "', cause: " + e.Message);
850 Compiler.TimeReporter.Stop (TimeReporter.TimerType.OutputSave);
852 // Save debug symbols file
853 if (symbol_writer != null && Compiler.Report.Errors == 0) {
854 // TODO: it should run in parallel
855 Compiler.TimeReporter.Start (TimeReporter.TimerType.DebugSave);
857 var filename = file_name + ".mdb";
859 // We mmap the file, so unlink the previous version since it may be in use
860 File.Delete (filename);
862 // We can safely ignore
865 module.WriteDebugSymbol (symbol_writer);
867 using (FileStream fs = new FileStream (filename, FileMode.Create, FileAccess.Write)) {
868 symbol_writer.CreateSymbolFile (module.Builder.ModuleVersionId, fs);
871 Compiler.TimeReporter.Stop (TimeReporter.TimerType.DebugSave);
875 protected virtual void SaveModule (PortableExecutableKinds pekind, ImageFileMachine machine)
877 Report.RuntimeMissingSupport (Location.Null, "-target:module");
880 void SetCustomAttribute (MethodSpec ctor, byte[] data)
882 if (module_target_attrs != null)
883 module_target_attrs.AddAssemblyAttribute (ctor, data);
885 Builder.SetCustomAttribute ((ConstructorInfo) ctor.GetMetaInfo (), data);
888 void SetEntryPoint ()
890 if (!Compiler.Settings.NeedsEntryPoint) {
891 if (Compiler.Settings.MainClass != null)
892 Report.Error (2017, "Cannot specify -main if building a module or library");
897 PEFileKinds file_kind;
899 switch (Compiler.Settings.Target) {
902 file_kind = PEFileKinds.Dll;
905 file_kind = PEFileKinds.WindowApplication;
908 file_kind = PEFileKinds.ConsoleApplication;
912 if (entry_point == null) {
913 string main_class = Compiler.Settings.MainClass;
914 if (main_class != null) {
915 // TODO: Handle dotted names
916 var texpr = module.GlobalRootNamespace.LookupType (module, main_class, 0, LookupMode.Probing, Location.Null);
918 Report.Error (1555, "Could not find `{0}' specified for Main method", main_class);
922 var mtype = texpr.MemberDefinition as ClassOrStruct;
924 Report.Error (1556, "`{0}' specified for Main method must be a valid class or struct", main_class);
928 Report.Error (1558, mtype.Location, "`{0}' does not have a suitable static Main method", mtype.GetSignatureForError ());
930 string pname = file_name == null ? name : Path.GetFileName (file_name);
931 Report.Error (5001, "Program `{0}' does not contain a static `Main' method suitable for an entry point",
938 Builder.SetEntryPoint (entry_point.MethodBuilder, file_kind);
941 void Error_ObsoleteSecurityAttribute (Attribute a, string option)
943 Report.Warning (1699, 1, a.Location,
944 "Use compiler option `{0}' or appropriate project settings instead of `{1}' attribute",
948 void Error_AssemblySigning (string text)
950 Report.Error (1548, "Error during assembly signing. " + text);
953 public bool IsFriendAssemblyTo (IAssemblyDefinition assembly)
958 static Version IsValidAssemblyVersion (string version, bool allowGenerated)
960 string[] parts = version.Split ('.');
961 if (parts.Length < 1 || parts.Length > 4)
964 var values = new int[4];
965 for (int i = 0; i < parts.Length; ++i) {
966 if (!int.TryParse (parts[i], out values[i])) {
967 if (parts[i].Length == 1 && parts[i][0] == '*' && allowGenerated) {
969 // Nothing can follow *
970 if (parts.Length > 3)
973 // Generate Build value based on days since 1/1/2000
974 TimeSpan days = DateTime.Today - new DateTime (2000, 1, 1);
975 values[i] = System.Math.Max (days.Days, 0);
980 // Generate Revision value based on every other second today
981 var seconds = DateTime.Now - DateTime.Today;
982 values[i] = (int) seconds.TotalSeconds / 2;
990 if (values[i] > ushort.MaxValue)
994 return new Version (values[0], values[1], values[2], values[3]);
998 public class AssemblyResource : IEquatable<AssemblyResource>
1000 public AssemblyResource (string fileName, string name)
1001 : this (fileName, name, false)
1005 public AssemblyResource (string fileName, string name, bool isPrivate)
1007 FileName = fileName;
1009 Attributes = isPrivate ? ResourceAttributes.Private : ResourceAttributes.Public;
1012 public ResourceAttributes Attributes { get; private set; }
1013 public string Name { get; private set; }
1014 public string FileName { get; private set; }
1015 public bool IsEmbeded { get; set; }
1017 #region IEquatable<AssemblyResource> Members
1019 public bool Equals (AssemblyResource other)
1021 return Name == other.Name;
1028 // A placeholder class for assembly attributes when emitting module
1030 class AssemblyAttributesPlaceholder : CompilerGeneratedContainer
1032 static readonly string TypeNamePrefix = "<$AssemblyAttributes${0}>";
1033 public static readonly string AssemblyFieldName = "attributes";
1037 public AssemblyAttributesPlaceholder (ModuleContainer parent, string outputName)
1038 : base (parent, new MemberName (GetGeneratedName (outputName)), Modifiers.STATIC | Modifiers.INTERNAL)
1040 assembly = new Field (this, new TypeExpression (parent.Compiler.BuiltinTypes.Object, Location), Modifiers.PUBLIC | Modifiers.STATIC,
1041 new MemberName (AssemblyFieldName), null);
1043 AddField (assembly);
1046 public void AddAssemblyAttribute (MethodSpec ctor, byte[] data)
1048 assembly.SetCustomAttribute (ctor, data);
1051 public static string GetGeneratedName (string outputName)
1053 return string.Format (TypeNamePrefix, outputName);
1058 // Extension to System.Reflection.Emit.AssemblyBuilder to have fully compatible
1059 // compiler. This is a default implementation for framework System.Reflection.Emit
1060 // which does not implement any of the methods
1062 public class AssemblyBuilderExtension
1064 readonly CompilerContext ctx;
1066 public AssemblyBuilderExtension (CompilerContext ctx)
1071 public virtual System.Reflection.Module AddModule (string module)
1073 ctx.Report.RuntimeMissingSupport (Location.Null, "-addmodule");
1077 public virtual void AddPermissionRequests (PermissionSet[] permissions)
1079 ctx.Report.RuntimeMissingSupport (Location.Null, "assembly declarative security");
1082 public virtual void AddTypeForwarder (TypeSpec type, Location loc)
1084 ctx.Report.RuntimeMissingSupport (loc, "TypeForwardedToAttribute");
1087 public virtual void DefineWin32IconResource (string fileName)
1089 ctx.Report.RuntimeMissingSupport (Location.Null, "-win32icon");
1092 public virtual void SetAlgorithmId (uint value, Location loc)
1094 ctx.Report.RuntimeMissingSupport (loc, "AssemblyAlgorithmIdAttribute");
1097 public virtual void SetCulture (string culture, Location loc)
1099 ctx.Report.RuntimeMissingSupport (loc, "AssemblyCultureAttribute");
1102 public virtual void SetFlags (uint flags, Location loc)
1104 ctx.Report.RuntimeMissingSupport (loc, "AssemblyFlagsAttribute");
1107 public virtual void SetVersion (Version version, Location loc)
1109 ctx.Report.RuntimeMissingSupport (loc, "AssemblyVersionAttribute");
1113 abstract class AssemblyReferencesLoader<T> where T : class
1115 protected readonly CompilerContext compiler;
1117 protected readonly List<string> paths;
1119 protected AssemblyReferencesLoader (CompilerContext compiler)
1121 this.compiler = compiler;
1123 paths = new List<string> ();
1124 paths.Add (Directory.GetCurrentDirectory ());
1125 paths.AddRange (compiler.Settings.ReferencesLookupPaths);
1128 public abstract bool HasObjectType (T assembly);
1129 protected abstract string[] GetDefaultReferences ();
1130 public abstract T LoadAssemblyFile (string fileName, bool isImplicitReference);
1131 public abstract void LoadReferences (ModuleContainer module);
1133 protected void Error_FileNotFound (string fileName)
1135 compiler.Report.Error (6, "Metadata file `{0}' could not be found", fileName);
1138 protected void Error_FileCorrupted (string fileName)
1140 compiler.Report.Error (9, "Metadata file `{0}' does not contain valid metadata", fileName);
1143 protected void Error_AssemblyIsModule (string fileName)
1145 compiler.Report.Error (1509,
1146 "Referenced assembly file `{0}' is a module. Consider using `-addmodule' option to add the module",
1150 protected void Error_ModuleIsAssembly (string fileName)
1152 compiler.Report.Error (1542,
1153 "Added module file `{0}' is an assembly. Consider using `-r' option to reference the file",
1157 protected void LoadReferencesCore (ModuleContainer module, out T corlib_assembly, out List<Tuple<RootNamespace, T>> loaded)
1159 compiler.TimeReporter.Start (TimeReporter.TimerType.ReferencesLoading);
1161 loaded = new List<Tuple<RootNamespace, T>> ();
1164 // Load mscorlib.dll as the first
1166 if (module.Compiler.Settings.StdLib) {
1167 corlib_assembly = LoadAssemblyFile ("mscorlib.dll", true);
1169 corlib_assembly = default (T);
1173 foreach (string r in module.Compiler.Settings.AssemblyReferences) {
1174 a = LoadAssemblyFile (r, false);
1175 if (a == null || EqualityComparer<T>.Default.Equals (a, corlib_assembly))
1178 var key = Tuple.Create (module.GlobalRootNamespace, a);
1179 if (loaded.Contains (key))
1185 if (corlib_assembly == null) {
1187 // Requires second pass because HasObjectType can trigger assembly load event
1189 for (int i = 0; i < loaded.Count; ++i) {
1190 var assembly = loaded [i];
1193 // corlib assembly is the first referenced assembly which contains System.Object
1195 if (HasObjectType (assembly.Item2)) {
1196 corlib_assembly = assembly.Item2;
1197 loaded.RemoveAt (i);
1203 foreach (var entry in module.Compiler.Settings.AssemblyReferencesAliases) {
1204 a = LoadAssemblyFile (entry.Item2, false);
1208 var key = Tuple.Create (module.CreateRootNamespace (entry.Item1), a);
1209 if (loaded.Contains (key))
1215 if (compiler.Settings.LoadDefaultReferences) {
1216 foreach (string r in GetDefaultReferences ()) {
1217 a = LoadAssemblyFile (r, true);
1221 var key = Tuple.Create (module.GlobalRootNamespace, a);
1222 if (loaded.Contains (key))
1229 compiler.TimeReporter.Stop (TimeReporter.TimerType.ReferencesLoading);