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;
26 using IKVM.Reflection;
27 using IKVM.Reflection.Emit;
28 using SecurityType = System.Collections.Generic.List<IKVM.Reflection.Emit.CustomAttributeBuilder>;
30 using SecurityType = System.Collections.Generic.Dictionary<System.Security.Permissions.SecurityAction, System.Security.PermissionSet>;
31 using System.Reflection;
32 using System.Reflection.Emit;
37 public interface IAssemblyDefinition
39 string FullName { get; }
40 bool IsCLSCompliant { get; }
41 bool IsMissing { get; }
44 byte[] GetPublicKeyToken ();
45 bool IsFriendAssemblyTo (IAssemblyDefinition assembly);
48 public class AssemblyReferenceErrorInfo
50 public AssemblyReferenceErrorInfo (AssemblyName dependencyName, string location, string message)
52 this.DependencyName = dependencyName;
53 this.RequestingAssemblyLocation = location;
54 this.Message = message;
57 public AssemblyName DependencyName { get; private set; }
58 public string RequestingAssemblyLocation { get; private set; }
59 public string Message { get; private set; }
62 public abstract class AssemblyDefinition : IAssemblyDefinition
64 // TODO: make it private and move all builder based methods here
65 public AssemblyBuilder Builder;
66 protected AssemblyBuilderExtension builder_extra;
67 MonoSymbolFile symbol_writer;
69 bool is_cls_compliant;
70 bool wrap_non_exception_throws;
71 bool wrap_non_exception_throws_custom;
72 bool has_user_debuggable;
74 protected ModuleContainer module;
76 protected readonly string file_name;
78 byte[] public_key, public_key_token;
81 // Holds private/public key pair when private key
83 StrongNameKeyPair private_key;
85 Attribute cls_attribute;
88 protected List<ImportedModuleDefinition> added_modules;
89 SecurityType declarative_security;
90 Dictionary<ITypeDefinition, Attribute> emitted_forwarders;
91 AssemblyAttributesPlaceholder module_target_attrs;
93 // Win32 version info values
94 string vi_product, vi_product_version, vi_company, vi_copyright, vi_trademark;
95 string pa_file_version, pa_assembly_version;
97 protected AssemblyDefinition (ModuleContainer module, string name)
100 this.name = Path.GetFileNameWithoutExtension (name);
102 wrap_non_exception_throws = true;
104 delay_sign = Compiler.Settings.StrongNameDelaySign;
107 // Load strong name key early enough for assembly importer to be able to
108 // use the keys for InternalsVisibleTo
109 // This should go somewhere close to ReferencesLoading but don't have the place yet
111 if (Compiler.Settings.HasKeyFileOrContainer) {
112 LoadPublicKey (Compiler.Settings.StrongNameKeyFile, Compiler.Settings.StrongNameKeyContainer);
116 protected AssemblyDefinition (ModuleContainer module, string name, string fileName)
117 : this (module, name)
119 this.file_name = fileName;
124 public Attribute CLSCompliantAttribute {
126 return cls_attribute;
130 public CompilerContext Compiler {
132 return module.Compiler;
137 // Assembly entry point, aka Main method
139 public Method EntryPoint {
148 public string FullName {
150 return Builder.FullName;
154 public bool HasCLSCompliantAttribute {
156 return cls_attribute != null;
160 // TODO: This should not exist here but will require more changes
161 public MetadataImporter Importer {
165 public bool IsCLSCompliant {
167 return is_cls_compliant;
171 bool IAssemblyDefinition.IsMissing {
177 public bool IsSatelliteAssembly { get; private set; }
185 public bool WrapNonExceptionThrows {
187 return wrap_non_exception_throws;
191 protected Report Report {
193 return Compiler.Report;
197 public MonoSymbolFile SymbolWriter {
199 return symbol_writer;
205 public void AddModule (ImportedModuleDefinition module)
207 if (added_modules == null) {
208 added_modules = new List<ImportedModuleDefinition> ();
209 added_modules.Add (module);
213 public void ApplyAttributeBuilder (Attribute a, MethodSpec ctor, byte[] cdata, PredefinedAttributes pa)
215 if (a.IsValidSecurityAttribute ()) {
216 a.ExtractSecurityPermissionSet (ctor, ref declarative_security);
220 if (a.Type == pa.AssemblyCulture) {
221 string value = a.GetString ();
222 if (value == null || value.Length == 0)
225 if (Compiler.Settings.Target == Target.Exe) {
226 Report.Error (7059, a.Location, "Executables cannot be satellite assemblies. Remove the attribute or keep it empty");
230 if (value == "neutral")
233 if (Compiler.Settings.Target == Target.Module) {
234 SetCustomAttribute (ctor, cdata);
236 builder_extra.SetCulture (value, a.Location);
239 IsSatelliteAssembly = true;
243 if (a.Type == pa.AssemblyVersion) {
244 string value = a.GetString ();
245 if (value == null || value.Length == 0)
248 var vinfo = IsValidAssemblyVersion (value, true);
250 Report.Error (7034, a.Location, "The specified version string `{0}' does not conform to the required format - major[.minor[.build[.revision]]]",
255 if (Compiler.Settings.Target == Target.Module) {
256 SetCustomAttribute (ctor, cdata);
258 builder_extra.SetVersion (vinfo, a.Location);
259 pa_assembly_version = vinfo.ToString ();
265 if (a.Type == pa.AssemblyAlgorithmId) {
266 const int pos = 2; // skip CA header
267 uint alg = (uint) cdata [pos];
268 alg |= ((uint) cdata [pos + 1]) << 8;
269 alg |= ((uint) cdata [pos + 2]) << 16;
270 alg |= ((uint) cdata [pos + 3]) << 24;
272 if (Compiler.Settings.Target == Target.Module) {
273 SetCustomAttribute (ctor, cdata);
275 builder_extra.SetAlgorithmId (alg, a.Location);
281 if (a.Type == pa.AssemblyFlags) {
282 const int pos = 2; // skip CA header
283 uint flags = (uint) cdata[pos];
284 flags |= ((uint) cdata [pos + 1]) << 8;
285 flags |= ((uint) cdata [pos + 2]) << 16;
286 flags |= ((uint) cdata [pos + 3]) << 24;
288 // Ignore set PublicKey flag if assembly is not strongnamed
289 if ((flags & (uint) AssemblyNameFlags.PublicKey) != 0 && public_key == null)
290 flags &= ~(uint) AssemblyNameFlags.PublicKey;
292 if (Compiler.Settings.Target == Target.Module) {
293 SetCustomAttribute (ctor, cdata);
295 builder_extra.SetFlags (flags, a.Location);
301 if (a.Type == pa.TypeForwarder) {
302 TypeSpec t = a.GetArgumentType ();
303 if (t == null || TypeManager.HasElementType (t)) {
304 Report.Error (735, a.Location, "Invalid type specified as an argument for TypeForwardedTo attribute");
308 if (emitted_forwarders == null) {
309 emitted_forwarders = new Dictionary<ITypeDefinition, Attribute> ();
310 } else if (emitted_forwarders.ContainsKey (t.MemberDefinition)) {
311 Report.SymbolRelatedToPreviousError (emitted_forwarders[t.MemberDefinition].Location, null);
312 Report.Error (739, a.Location, "A duplicate type forward of type `{0}'",
313 t.GetSignatureForError ());
317 emitted_forwarders.Add (t.MemberDefinition, a);
319 if (t.MemberDefinition.DeclaringAssembly == this) {
320 Report.SymbolRelatedToPreviousError (t);
321 Report.Error (729, a.Location, "Cannot forward type `{0}' because it is defined in this assembly",
322 t.GetSignatureForError ());
327 Report.Error (730, a.Location, "Cannot forward type `{0}' because it is a nested type",
328 t.GetSignatureForError ());
332 AddTypeForwarders (t, a.Location);
336 if (a.Type == pa.Extension) {
337 a.Error_MisusedExtensionAttribute ();
341 if (a.Type == pa.InternalsVisibleTo) {
342 string assembly_name = a.GetString ();
343 if (assembly_name == null) {
344 Report.Error (7030, a.Location, "Friend assembly reference cannot have `null' value");
348 if (assembly_name.Length == 0)
351 ParsedAssemblyName aname;
352 ParseAssemblyResult r = Fusion.ParseAssemblyName (assembly_name, out aname);
353 if (r != ParseAssemblyResult.OK) {
354 Report.Warning (1700, 3, a.Location, "Friend assembly reference `{0}' is invalid and cannot be resolved",
359 if (aname.Version != null || aname.Culture != null || aname.ProcessorArchitecture != ProcessorArchitecture.None) {
360 Report.Error (1725, a.Location,
361 "Friend assembly reference `{0}' is invalid. InternalsVisibleTo declarations cannot have a version, culture or processor architecture specified",
367 if (public_key != null && !aname.HasPublicKey) {
368 Report.Error (1726, a.Location,
369 "Friend assembly reference `{0}' is invalid. Strong named assemblies must specify a public key in their InternalsVisibleTo declarations",
374 } else if (a.Type == pa.RuntimeCompatibility) {
375 wrap_non_exception_throws_custom = true;
376 } else if (a.Type == pa.AssemblyFileVersion) {
377 pa_file_version = a.GetString ();
378 if (string.IsNullOrEmpty (pa_file_version) || IsValidAssemblyVersion (pa_file_version, false) == null) {
379 Report.Warning (7035, 1, a.Location, "The specified version string `{0}' does not conform to the recommended format major.minor.build.revision",
380 pa_file_version, a.Name);
384 // File version info decoding from blob is not supported
385 var cab = new CustomAttributeBuilder ((ConstructorInfo)ctor.GetMetaInfo (), new object [] { pa_file_version });
386 Builder.SetCustomAttribute (cab);
388 } else if (a.Type == pa.AssemblyProduct) {
389 vi_product = a.GetString ();
390 } else if (a.Type == pa.AssemblyCompany) {
391 vi_company = a.GetString ();
392 } else if (a.Type == pa.AssemblyCopyright) {
393 vi_copyright = a.GetString ();
394 } else if (a.Type == pa.AssemblyTrademark) {
395 vi_trademark = a.GetString ();
396 } else if (a.Type == pa.Debuggable) {
397 has_user_debuggable = true;
398 } else if (a.Type == pa.AssemblyInformationalVersion) {
399 vi_product_version = a.GetString ();
403 // Win32 version info attributes AssemblyDescription and AssemblyTitle cannot be
404 // set using public API and because we have blob like attributes we need to use
405 // special option DecodeVersionInfoAttributeBlobs to support values extraction
408 SetCustomAttribute (ctor, cdata);
411 void AddTypeForwarders (TypeSpec type, Location loc)
413 builder_extra.AddTypeForwarder (type.GetDefinition (), loc);
415 var ntypes = MemberCache.GetDeclaredNestedTypes (type);
419 foreach (var nested in ntypes) {
420 if (nested.IsPrivate)
423 AddTypeForwarders (nested, loc);
428 // When using assembly public key attributes InternalsVisibleTo key
429 // was not checked, we have to do it later when we actually know what
430 // our public key token is
432 void CheckReferencesPublicToken ()
434 var references = builder_extra.GetReferencedAssemblies ();
435 foreach (var an in references) {
436 if (public_key != null && an.GetPublicKey ().Length == 0) {
437 Report.Error (1577, "Referenced assembly `{0}' does not have a strong name",
441 var ci = an.CultureInfo;
442 if (!ci.Equals (CultureInfo.InvariantCulture)) {
443 Report.Warning (8009, 1, "Referenced assembly `{0}' has different culture setting of `{1}'",
447 var ia = Importer.GetImportedAssemblyDefinition (an);
451 var an_references = GetNotUnifiedReferences (an);
452 if (an_references != null) {
453 foreach (var r in an_references) {
455 // Secondary check when assembly references is resolved but not used. For example
456 // due to type-forwarding
458 if (references.Any (l => l.Name == r.DependencyName.Name)) {
459 Report.SymbolRelatedToPreviousError (r.RequestingAssemblyLocation);
460 Report.Error (1705, r.Message);
465 if (!ia.IsFriendAssemblyTo (this))
468 var attr = ia.GetAssemblyVisibleToName (this);
469 var atoken = attr.GetPublicKeyToken ();
471 if (ArrayComparer.IsEqual (GetPublicKeyToken (), atoken))
474 Report.SymbolRelatedToPreviousError (ia.Location);
476 "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",
477 attr.FullName, FullName);
481 protected AssemblyName CreateAssemblyName ()
483 var an = new AssemblyName (name);
485 if (public_key != null && Compiler.Settings.Target != Target.Module) {
487 an.SetPublicKey (public_key);
489 if (public_key.Length == 16) {
490 Report.Error (1606, "Could not sign the assembly. ECMA key can only be used to delay-sign assemblies");
491 } else if (private_key == null) {
492 Error_AssemblySigning ("The specified key file does not have a private key");
494 an.KeyPair = private_key;
502 public virtual ModuleBuilder CreateModuleBuilder ()
504 if (file_name == null)
505 throw new NotSupportedException ("transient module in static assembly");
507 var module_name = Path.GetFileName (file_name);
509 // Always initialize module without symbolInfo. We could be framework dependent
510 // but returned ISymbolWriter does not have all what we need therefore some
511 // adaptor will be needed for now we alwayas emit MDB format when generating
513 return Builder.DefineDynamicModule (module_name, module_name, false);
516 public virtual void Emit ()
518 if (Compiler.Settings.Target == Target.Module) {
519 module_target_attrs = new AssemblyAttributesPlaceholder (module, name);
520 module_target_attrs.CreateContainer ();
521 module_target_attrs.DefineContainer ();
522 module_target_attrs.Define ();
523 module.AddCompilerGeneratedClass (module_target_attrs);
524 } else if (added_modules != null) {
525 ReadModulesAssemblyAttributes ();
528 if (Compiler.Settings.GenerateDebugInfo) {
529 symbol_writer = new MonoSymbolFile ();
532 module.EmitContainer ();
534 if (module.HasExtensionMethod) {
535 var pa = module.PredefinedAttributes.Extension;
537 SetCustomAttribute (pa.Constructor, AttributeEncoder.Empty);
541 if (!IsSatelliteAssembly) {
542 if (!has_user_debuggable && Compiler.Settings.GenerateDebugInfo) {
543 var pa = module.PredefinedAttributes.Debuggable;
545 var modes = System.Diagnostics.DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints;
546 if (!Compiler.Settings.Optimize)
547 modes |= System.Diagnostics.DebuggableAttribute.DebuggingModes.DisableOptimizations;
549 pa.EmitAttribute (Builder, modes);
553 if (!wrap_non_exception_throws_custom) {
554 PredefinedAttribute pa = module.PredefinedAttributes.RuntimeCompatibility;
555 if (pa.IsDefined && pa.ResolveBuilder ()) {
556 var prop = module.PredefinedMembers.RuntimeCompatibilityWrapNonExceptionThrows.Get ();
558 AttributeEncoder encoder = new AttributeEncoder ();
559 encoder.EncodeNamedPropertyArgument (prop, new BoolLiteral (Compiler.BuiltinTypes, true, Location.Null));
560 SetCustomAttribute (pa.Constructor, encoder.ToArray ());
565 if (declarative_security != null) {
567 foreach (var entry in declarative_security) {
568 Builder.__AddDeclarativeSecurity (entry);
571 throw new NotSupportedException ("Assembly-level security");
576 CheckReferencesPublicToken ();
581 public byte[] GetPublicKeyToken ()
583 if (public_key == null || public_key_token != null)
584 return public_key_token;
586 HashAlgorithm ha = SHA1.Create ();
587 byte[] hash = ha.ComputeHash (public_key);
588 // we need the last 8 bytes in reverse order
589 public_key_token = new byte[8];
590 Buffer.BlockCopy (hash, hash.Length - 8, public_key_token, 0, 8);
591 Array.Reverse (public_key_token, 0, 8);
592 return public_key_token;
595 protected virtual List<AssemblyReferenceErrorInfo> GetNotUnifiedReferences (AssemblyName assemblyName)
601 // Either keyFile or keyContainer has to be non-null
603 void LoadPublicKey (string keyFile, string keyContainer)
605 if (keyContainer != null) {
607 private_key = new StrongNameKeyPair (keyContainer);
608 public_key = private_key.PublicKey;
610 Error_AssemblySigning ("The specified key container `" + keyContainer + "' does not exist");
616 bool key_file_exists = File.Exists (keyFile);
619 // For attribute based KeyFile do additional lookup
620 // in output assembly path
622 if (!key_file_exists && Compiler.Settings.StrongNameKeyFile == null) {
624 // The key file can be relative to output assembly
626 string test_path = Path.Combine (Path.GetDirectoryName (file_name), keyFile);
627 key_file_exists = File.Exists (test_path);
632 if (!key_file_exists) {
633 Error_AssemblySigning ("The specified key file `" + keyFile + "' does not exist");
637 using (FileStream fs = new FileStream (keyFile, FileMode.Open, FileAccess.Read)) {
638 byte[] snkeypair = new byte[fs.Length];
639 fs.Read (snkeypair, 0, snkeypair.Length);
641 // check for ECMA key
642 if (snkeypair.Length == 16) {
643 public_key = snkeypair;
648 // take it, with or without, a private key
649 RSA rsa = CryptoConvert.FromCapiKeyBlob (snkeypair);
650 // and make sure we only feed the public part to Sys.Ref
651 byte[] publickey = CryptoConvert.ToCapiPublicKeyBlob (rsa);
653 // AssemblyName.SetPublicKey requires an additional header
654 byte[] publicKeyHeader = new byte[8] { 0x00, 0x24, 0x00, 0x00, 0x04, 0x80, 0x00, 0x00 };
657 public_key = new byte[12 + publickey.Length];
658 Buffer.BlockCopy (publicKeyHeader, 0, public_key, 0, publicKeyHeader.Length);
660 // Length of Public Key (in bytes)
661 int lastPart = public_key.Length - 12;
662 public_key[8] = (byte) (lastPart & 0xFF);
663 public_key[9] = (byte) ((lastPart >> 8) & 0xFF);
664 public_key[10] = (byte) ((lastPart >> 16) & 0xFF);
665 public_key[11] = (byte) ((lastPart >> 24) & 0xFF);
667 Buffer.BlockCopy (publickey, 0, public_key, 12, publickey.Length);
669 Error_AssemblySigning ("The specified key file `" + keyFile + "' has incorrect format");
677 // TODO: Is there better way to test for a private key presence ?
678 CryptoConvert.FromCapiPrivateKeyBlob (snkeypair);
679 private_key = new StrongNameKeyPair (snkeypair);
684 void ReadModulesAssemblyAttributes ()
686 foreach (var m in added_modules) {
687 var cattrs = m.ReadAssemblyAttributes ();
691 module.OptAttributes.AddAttributes (cattrs);
695 public void Resolve ()
697 if (Compiler.Settings.Unsafe && module.PredefinedTypes.SecurityAction.Define ()) {
699 // Emits [assembly: SecurityPermissionAttribute (SecurityAction.RequestMinimum, SkipVerification = true)]
700 // when -unsafe option was specified
702 Location loc = Location.Null;
704 MemberAccess system_security_permissions = new MemberAccess (new MemberAccess (
705 new QualifiedAliasMember (QualifiedAliasMember.GlobalAlias, "System", loc), "Security", loc), "Permissions", loc);
707 var req_min = module.PredefinedMembers.SecurityActionRequestMinimum.Resolve (loc);
709 Arguments pos = new Arguments (1);
710 pos.Add (new Argument (req_min.GetConstant (null)));
712 Arguments named = new Arguments (1);
713 named.Add (new NamedArgument ("SkipVerification", loc, new BoolLiteral (Compiler.BuiltinTypes, true, loc)));
715 Attribute g = new Attribute ("assembly",
716 new MemberAccess (system_security_permissions, "SecurityPermissionAttribute"),
717 new Arguments[] { pos, named }, loc, false);
718 g.AttachTo (module, module);
720 // Disable no-location warnings (e.g. obsolete) for compiler generated attribute
721 Compiler.Report.DisableReporting ();
723 var ctor = g.Resolve ();
725 g.ExtractSecurityPermissionSet (ctor, ref declarative_security);
728 Compiler.Report.EnableReporting ();
732 if (module.OptAttributes == null)
735 // Ensure that we only have GlobalAttributes, since the Search isn't safe with other types.
736 if (!module.OptAttributes.CheckTargets())
739 cls_attribute = module.ResolveAssemblyAttribute (module.PredefinedAttributes.CLSCompliant);
741 if (cls_attribute != null) {
742 is_cls_compliant = cls_attribute.GetClsCompliantAttributeValue ();
745 if (added_modules != null && Compiler.Settings.VerifyClsCompliance && is_cls_compliant) {
746 foreach (var m in added_modules) {
747 if (!m.IsCLSCompliant) {
749 "Added modules must be marked with the CLSCompliant attribute to match the assembly",
755 Attribute a = module.ResolveAssemblyAttribute (module.PredefinedAttributes.RuntimeCompatibility);
757 var val = a.GetNamedValue ("WrapNonExceptionThrows") as BoolConstant;
759 wrap_non_exception_throws = val.Value;
763 protected void ResolveAssemblySecurityAttributes ()
765 string key_file = null;
766 string key_container = null;
768 if (module.OptAttributes != null) {
769 foreach (Attribute a in module.OptAttributes.Attrs) {
770 // cannot rely on any resolve-based members before you call Resolve
771 if (a.ExplicitTarget != "assembly")
774 // TODO: This code is buggy: comparing Attribute name without resolving is wrong.
775 // However, this is invoked by CodeGen.Init, when none of the namespaces
777 // TODO: Does not handle quoted attributes properly
779 case "AssemblyKeyFile":
780 case "AssemblyKeyFileAttribute":
781 case "System.Reflection.AssemblyKeyFileAttribute":
782 if (Compiler.Settings.StrongNameKeyFile != null) {
783 Report.SymbolRelatedToPreviousError (a.Location, a.GetSignatureForError ());
784 Report.Warning (1616, 1, "Option `{0}' overrides attribute `{1}' given in a source file or added module",
785 "keyfile", "System.Reflection.AssemblyKeyFileAttribute");
787 string value = a.GetString ();
788 if (!string.IsNullOrEmpty (value)) {
789 Error_ObsoleteSecurityAttribute (a, "keyfile");
794 case "AssemblyKeyName":
795 case "AssemblyKeyNameAttribute":
796 case "System.Reflection.AssemblyKeyNameAttribute":
797 if (Compiler.Settings.StrongNameKeyContainer != null) {
798 Report.SymbolRelatedToPreviousError (a.Location, a.GetSignatureForError ());
799 Report.Warning (1616, 1, "Option `{0}' overrides attribute `{1}' given in a source file or added module",
800 "keycontainer", "System.Reflection.AssemblyKeyNameAttribute");
802 string value = a.GetString ();
803 if (!string.IsNullOrEmpty (value)) {
804 Error_ObsoleteSecurityAttribute (a, "keycontainer");
805 key_container = value;
809 case "AssemblyDelaySign":
810 case "AssemblyDelaySignAttribute":
811 case "System.Reflection.AssemblyDelaySignAttribute":
812 bool b = a.GetBoolean ();
814 Error_ObsoleteSecurityAttribute (a, "delaysign");
823 // We came here only to report assembly attributes warnings
824 if (public_key != null)
828 // Load the strong key file found in attributes when no
829 // command line key was given
831 if (key_file != null || key_container != null) {
832 LoadPublicKey (key_file, key_container);
833 } else if (delay_sign) {
834 Report.Warning (1607, 1, "Delay signing was requested but no key file was given");
838 public void EmbedResources ()
841 // Add Win32 resources
843 if (Compiler.Settings.Win32ResourceFile != null) {
844 Builder.DefineUnmanagedResource (Compiler.Settings.Win32ResourceFile);
846 Builder.DefineVersionInfoResource (vi_product,
847 vi_product_version ?? pa_file_version ?? pa_assembly_version,
853 if (Compiler.Settings.Win32IconFile != null) {
854 builder_extra.DefineWin32IconResource (Compiler.Settings.Win32IconFile);
857 if (Compiler.Settings.Resources != null) {
858 if (Compiler.Settings.Target == Target.Module) {
859 Report.Error (1507, "Cannot link resource file when building a module");
862 foreach (var res in Compiler.Settings.Resources) {
863 if (!File.Exists (res.FileName)) {
864 Report.Error (1566, "Error reading resource file `{0}'", res.FileName);
870 if (counter++ < 10) {
871 stream = File.OpenRead (res.FileName);
873 // TODO: SRE API requires resource stream to be available during AssemblyBuilder::Save
874 // we workaround it by reading everything into memory to compile projects with
875 // many embedded resource (over 3500) references
876 stream = new MemoryStream (File.ReadAllBytes (res.FileName));
879 module.Builder.DefineManifestResource (res.Name, stream, res.Attributes);
881 Builder.AddResourceFile (res.Name, Path.GetFileName (res.FileName), res.Attributes);
890 PortableExecutableKinds pekind = PortableExecutableKinds.ILOnly;
891 ImageFileMachine machine;
893 switch (Compiler.Settings.Platform) {
895 pekind |= PortableExecutableKinds.Required32Bit;
896 machine = ImageFileMachine.I386;
899 pekind |= PortableExecutableKinds.PE32Plus;
900 machine = ImageFileMachine.AMD64;
903 machine = ImageFileMachine.IA64;
905 case Platform.AnyCPU32Preferred:
907 pekind |= PortableExecutableKinds.Preferred32Bit;
908 machine = ImageFileMachine.I386;
911 throw new NotSupportedException ();
915 machine = ImageFileMachine.ARM;
918 throw new NotSupportedException ();
920 case Platform.AnyCPU:
922 machine = ImageFileMachine.I386;
926 Compiler.TimeReporter.Start (TimeReporter.TimerType.OutputSave);
928 if (Compiler.Settings.Target == Target.Module) {
929 SaveModule (pekind, machine);
931 Builder.Save (module.Builder.ScopeName, pekind, machine);
933 } catch (ArgumentOutOfRangeException) {
934 Report.Error (16, "Output file `{0}' exceeds the 4GB limit", name);
935 } catch (Exception e) {
936 Report.Error (16, "Could not write to file `{0}'. {1}", name, e.Message);
938 Compiler.TimeReporter.Stop (TimeReporter.TimerType.OutputSave);
940 // Save debug symbols file
941 if (symbol_writer != null && Compiler.Report.Errors == 0) {
942 // TODO: it should run in parallel
943 Compiler.TimeReporter.Start (TimeReporter.TimerType.DebugSave);
945 var filename = file_name + ".mdb";
947 // We mmap the file, so unlink the previous version since it may be in use
948 File.Delete (filename);
950 // We can safely ignore
953 module.WriteDebugSymbol (symbol_writer);
955 using (FileStream fs = new FileStream (filename, FileMode.Create, FileAccess.Write)) {
956 symbol_writer.CreateSymbolFile (module.Builder.ModuleVersionId, fs);
959 Compiler.TimeReporter.Stop (TimeReporter.TimerType.DebugSave);
963 protected virtual void SaveModule (PortableExecutableKinds pekind, ImageFileMachine machine)
965 Report.RuntimeMissingSupport (Location.Null, "-target:module");
968 void SetCustomAttribute (MethodSpec ctor, byte[] data)
970 if (module_target_attrs != null)
971 module_target_attrs.AddAssemblyAttribute (ctor, data);
973 Builder.SetCustomAttribute ((ConstructorInfo) ctor.GetMetaInfo (), data);
976 void SetEntryPoint ()
978 if (!Compiler.Settings.NeedsEntryPoint) {
979 if (Compiler.Settings.MainClass != null)
980 Report.Error (2017, "Cannot specify -main if building a module or library");
985 PEFileKinds file_kind;
987 switch (Compiler.Settings.Target) {
990 file_kind = PEFileKinds.Dll;
993 file_kind = PEFileKinds.WindowApplication;
996 file_kind = PEFileKinds.ConsoleApplication;
1000 if (entry_point == null) {
1001 string main_class = Compiler.Settings.MainClass;
1002 if (main_class != null) {
1003 // TODO: Handle dotted names
1004 var texpr = module.GlobalRootNamespace.LookupType (module, main_class, 0, LookupMode.Probing, Location.Null);
1005 if (texpr == null) {
1006 Report.Error (1555, "Could not find `{0}' specified for Main method", main_class);
1010 var mtype = texpr.MemberDefinition as ClassOrStruct;
1011 if (mtype == null) {
1012 Report.Error (1556, "`{0}' specified for Main method must be a valid class or struct", main_class);
1016 Report.Error (1558, mtype.Location, "`{0}' does not have a suitable static Main method", mtype.GetSignatureForError ());
1018 string pname = file_name == null ? name : Path.GetFileName (file_name);
1019 Report.Error (5001, "Program `{0}' does not contain a static `Main' method suitable for an entry point",
1026 Builder.SetEntryPoint (entry_point.MethodBuilder, file_kind);
1029 void Error_ObsoleteSecurityAttribute (Attribute a, string option)
1031 Report.Warning (1699, 1, a.Location,
1032 "Use compiler option `{0}' or appropriate project settings instead of `{1}' attribute",
1036 void Error_AssemblySigning (string text)
1038 Report.Error (1548, "Error during assembly signing. " + text);
1041 public bool IsFriendAssemblyTo (IAssemblyDefinition assembly)
1046 static Version IsValidAssemblyVersion (string version, bool allowGenerated)
1048 string[] parts = version.Split ('.');
1049 if (parts.Length < 1 || parts.Length > 4)
1052 var values = new int[4];
1053 for (int i = 0; i < parts.Length; ++i) {
1054 if (!int.TryParse (parts[i], out values[i])) {
1055 if (parts[i].Length == 1 && parts[i][0] == '*' && allowGenerated) {
1057 // Nothing can follow *
1058 if (parts.Length > 3)
1061 // Generate Build value based on days since 1/1/2000
1062 TimeSpan days = DateTime.Today - new DateTime (2000, 1, 1);
1063 values[i] = System.Math.Max (days.Days, 0);
1068 // Generate Revision value based on every other second today
1069 var seconds = DateTime.Now - DateTime.Today;
1070 values[i] = (int) seconds.TotalSeconds / 2;
1078 if (values[i] > ushort.MaxValue)
1082 return new Version (values[0], values[1], values[2], values[3]);
1086 public class AssemblyResource : IEquatable<AssemblyResource>
1088 public AssemblyResource (string fileName, string name)
1089 : this (fileName, name, false)
1093 public AssemblyResource (string fileName, string name, bool isPrivate)
1095 FileName = fileName;
1097 Attributes = isPrivate ? ResourceAttributes.Private : ResourceAttributes.Public;
1100 public ResourceAttributes Attributes { get; private set; }
1101 public string Name { get; private set; }
1102 public string FileName { get; private set; }
1103 public bool IsEmbeded { get; set; }
1105 #region IEquatable<AssemblyResource> Members
1107 public bool Equals (AssemblyResource other)
1109 return Name == other.Name;
1116 // A placeholder class for assembly attributes when emitting module
1118 class AssemblyAttributesPlaceholder : CompilerGeneratedContainer
1120 static readonly string TypeNamePrefix = "<$AssemblyAttributes${0}>";
1121 public static readonly string AssemblyFieldName = "attributes";
1125 public AssemblyAttributesPlaceholder (ModuleContainer parent, string outputName)
1126 : base (parent, new MemberName (GetGeneratedName (outputName)), Modifiers.STATIC | Modifiers.INTERNAL)
1128 assembly = new Field (this, new TypeExpression (parent.Compiler.BuiltinTypes.Object, Location), Modifiers.PUBLIC | Modifiers.STATIC,
1129 new MemberName (AssemblyFieldName), null);
1131 AddField (assembly);
1134 public void AddAssemblyAttribute (MethodSpec ctor, byte[] data)
1136 assembly.SetCustomAttribute (ctor, data);
1139 public static string GetGeneratedName (string outputName)
1141 return string.Format (TypeNamePrefix, outputName);
1146 // Extension to System.Reflection.Emit.AssemblyBuilder to have fully compatible
1147 // compiler. This is a default implementation for framework System.Reflection.Emit
1148 // which does not implement any of the methods
1150 public class AssemblyBuilderExtension
1152 protected readonly CompilerContext ctx;
1154 public AssemblyBuilderExtension (CompilerContext ctx)
1159 public virtual System.Reflection.Module AddModule (string module)
1161 ctx.Report.RuntimeMissingSupport (Location.Null, "-addmodule");
1165 public virtual void AddPermissionRequests (PermissionSet[] permissions)
1167 ctx.Report.RuntimeMissingSupport (Location.Null, "assembly declarative security");
1170 public virtual void AddTypeForwarder (TypeSpec type, Location loc)
1172 ctx.Report.RuntimeMissingSupport (loc, "TypeForwardedToAttribute");
1175 public virtual void DefineWin32IconResource (string fileName)
1177 ctx.Report.RuntimeMissingSupport (Location.Null, "-win32icon");
1180 public virtual AssemblyName[] GetReferencedAssemblies ()
1185 public virtual void SetAlgorithmId (uint value, Location loc)
1187 ctx.Report.RuntimeMissingSupport (loc, "AssemblyAlgorithmIdAttribute");
1190 public virtual void SetCulture (string culture, Location loc)
1192 ctx.Report.RuntimeMissingSupport (loc, "AssemblyCultureAttribute");
1195 public virtual void SetFlags (uint flags, Location loc)
1197 ctx.Report.RuntimeMissingSupport (loc, "AssemblyFlagsAttribute");
1200 public virtual void SetVersion (Version version, Location loc)
1202 ctx.Report.RuntimeMissingSupport (loc, "AssemblyVersionAttribute");
1206 abstract class AssemblyReferencesLoader<T> where T : class
1208 protected readonly CompilerContext compiler;
1210 protected readonly List<string> paths;
1212 protected AssemblyReferencesLoader (CompilerContext compiler)
1214 this.compiler = compiler;
1216 paths = new List<string> ();
1217 paths.Add (Directory.GetCurrentDirectory ());
1218 paths.AddRange (compiler.Settings.ReferencesLookupPaths);
1221 public abstract T HasObjectType (T assembly);
1222 protected abstract string[] GetDefaultReferences ();
1223 public abstract T LoadAssemblyFile (string fileName, bool isImplicitReference);
1224 public abstract void LoadReferences (ModuleContainer module);
1226 protected void Error_FileNotFound (string fileName)
1228 compiler.Report.Error (6, "Metadata file `{0}' could not be found", fileName);
1231 protected void Error_FileCorrupted (string fileName)
1233 compiler.Report.Error (9, "Metadata file `{0}' does not contain valid metadata", fileName);
1236 protected void Error_AssemblyIsModule (string fileName)
1238 compiler.Report.Error (1509,
1239 "Referenced assembly file `{0}' is a module. Consider using `-addmodule' option to add the module",
1243 protected void Error_ModuleIsAssembly (string fileName)
1245 compiler.Report.Error (1542,
1246 "Added module file `{0}' is an assembly. Consider using `-r' option to reference the file",
1250 protected void LoadReferencesCore (ModuleContainer module, out T corlib_assembly, out List<Tuple<RootNamespace, T>> loaded)
1252 compiler.TimeReporter.Start (TimeReporter.TimerType.ReferencesLoading);
1254 loaded = new List<Tuple<RootNamespace, T>> ();
1257 // Load mscorlib.dll as the first
1259 if (module.Compiler.Settings.StdLib) {
1260 corlib_assembly = LoadAssemblyFile ("mscorlib.dll", true);
1262 corlib_assembly = default (T);
1266 foreach (string r in module.Compiler.Settings.AssemblyReferences) {
1267 a = LoadAssemblyFile (r, false);
1268 if (a == null || EqualityComparer<T>.Default.Equals (a, corlib_assembly))
1271 var key = Tuple.Create (module.GlobalRootNamespace, a);
1272 if (loaded.Contains (key))
1278 if (corlib_assembly == null) {
1280 // Requires second pass because HasObjectType can trigger assembly load event
1282 for (int i = 0; i < loaded.Count; ++i) {
1283 var assembly = loaded [i];
1286 // corlib assembly is the first referenced assembly which contains System.Object
1288 corlib_assembly = HasObjectType (assembly.Item2);
1289 if (corlib_assembly != null) {
1290 if (corlib_assembly != assembly.Item2) {
1291 var ca = corlib_assembly;
1292 i = loaded.FindIndex (l => l.Item2 == ca);
1295 loaded.RemoveAt (i);
1301 foreach (var entry in module.Compiler.Settings.AssemblyReferencesAliases) {
1302 a = LoadAssemblyFile (entry.Item2, false);
1306 var key = Tuple.Create (module.CreateRootNamespace (entry.Item1), a);
1307 if (loaded.Contains (key))
1313 if (compiler.Settings.LoadDefaultReferences) {
1314 foreach (string r in GetDefaultReferences ()) {
1315 a = LoadAssemblyFile (r, true);
1319 var key = Tuple.Create (module.GlobalRootNamespace, a);
1320 if (loaded.Contains (key))
1327 compiler.TimeReporter.Stop (TimeReporter.TimerType.ReferencesLoading);