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;
57 bool has_user_debuggable;
59 protected ModuleContainer module;
61 protected readonly string file_name;
63 byte[] public_key, public_key_token;
66 // Holds private/public key pair when private key
68 StrongNameKeyPair private_key;
70 Attribute cls_attribute;
73 protected List<ImportedModuleDefinition> added_modules;
74 SecurityType declarative_security;
75 Dictionary<ITypeDefinition, Attribute> emitted_forwarders;
76 AssemblyAttributesPlaceholder module_target_attrs;
78 // Win32 version info values
79 string vi_product, vi_product_version, vi_company, vi_copyright, vi_trademark;
81 protected AssemblyDefinition (ModuleContainer module, string name)
84 this.name = Path.GetFileNameWithoutExtension (name);
86 wrap_non_exception_throws = true;
88 delay_sign = Compiler.Settings.StrongNameDelaySign;
91 // Load strong name key early enough for assembly importer to be able to
92 // use the keys for InternalsVisibleTo
93 // This should go somewhere close to ReferencesLoading but don't have the place yet
95 if (Compiler.Settings.HasKeyFileOrContainer) {
96 LoadPublicKey (Compiler.Settings.StrongNameKeyFile, Compiler.Settings.StrongNameKeyContainer);
100 protected AssemblyDefinition (ModuleContainer module, string name, string fileName)
101 : this (module, name)
103 this.file_name = fileName;
108 public Attribute CLSCompliantAttribute {
110 return cls_attribute;
114 public CompilerContext Compiler {
116 return module.Compiler;
121 // Assembly entry point, aka Main method
123 public Method EntryPoint {
132 public string FullName {
134 return Builder.FullName;
138 public bool HasCLSCompliantAttribute {
140 return cls_attribute != null;
144 // TODO: This should not exist here but will require more changes
145 public MetadataImporter Importer {
149 public bool IsCLSCompliant {
151 return is_cls_compliant;
155 bool IAssemblyDefinition.IsMissing {
161 public bool IsSatelliteAssembly { get; private set; }
169 public bool WrapNonExceptionThrows {
171 return wrap_non_exception_throws;
175 protected Report Report {
177 return Compiler.Report;
181 public MonoSymbolFile SymbolWriter {
183 return symbol_writer;
189 public void AddModule (ImportedModuleDefinition module)
191 if (added_modules == null) {
192 added_modules = new List<ImportedModuleDefinition> ();
193 added_modules.Add (module);
197 public void ApplyAttributeBuilder (Attribute a, MethodSpec ctor, byte[] cdata, PredefinedAttributes pa)
199 if (a.IsValidSecurityAttribute ()) {
200 a.ExtractSecurityPermissionSet (ctor, ref declarative_security);
204 if (a.Type == pa.AssemblyCulture) {
205 string value = a.GetString ();
206 if (value == null || value.Length == 0)
209 if (Compiler.Settings.Target == Target.Exe) {
210 Report.Error (7059, a.Location, "Executables cannot be satellite assemblies. Remove the attribute or keep it empty");
214 if (value == "neutral")
217 if (Compiler.Settings.Target == Target.Module) {
218 SetCustomAttribute (ctor, cdata);
220 builder_extra.SetCulture (value, a.Location);
223 IsSatelliteAssembly = true;
227 if (a.Type == pa.AssemblyVersion) {
228 string value = a.GetString ();
229 if (value == null || value.Length == 0)
232 var vinfo = IsValidAssemblyVersion (value, true);
234 Report.Error (7034, a.Location, "The specified version string `{0}' does not conform to the required format - major[.minor[.build[.revision]]]",
239 if (Compiler.Settings.Target == Target.Module) {
240 SetCustomAttribute (ctor, cdata);
242 builder_extra.SetVersion (vinfo, a.Location);
248 if (a.Type == pa.AssemblyAlgorithmId) {
249 const int pos = 2; // skip CA header
250 uint alg = (uint) cdata [pos];
251 alg |= ((uint) cdata [pos + 1]) << 8;
252 alg |= ((uint) cdata [pos + 2]) << 16;
253 alg |= ((uint) cdata [pos + 3]) << 24;
255 if (Compiler.Settings.Target == Target.Module) {
256 SetCustomAttribute (ctor, cdata);
258 builder_extra.SetAlgorithmId (alg, a.Location);
264 if (a.Type == pa.AssemblyFlags) {
265 const int pos = 2; // skip CA header
266 uint flags = (uint) cdata[pos];
267 flags |= ((uint) cdata [pos + 1]) << 8;
268 flags |= ((uint) cdata [pos + 2]) << 16;
269 flags |= ((uint) cdata [pos + 3]) << 24;
271 // Ignore set PublicKey flag if assembly is not strongnamed
272 if ((flags & (uint) AssemblyNameFlags.PublicKey) != 0 && public_key == null)
273 flags &= ~(uint) AssemblyNameFlags.PublicKey;
275 if (Compiler.Settings.Target == Target.Module) {
276 SetCustomAttribute (ctor, cdata);
278 builder_extra.SetFlags (flags, a.Location);
284 if (a.Type == pa.TypeForwarder) {
285 TypeSpec t = a.GetArgumentType ();
286 if (t == null || TypeManager.HasElementType (t)) {
287 Report.Error (735, a.Location, "Invalid type specified as an argument for TypeForwardedTo attribute");
291 if (emitted_forwarders == null) {
292 emitted_forwarders = new Dictionary<ITypeDefinition, Attribute> ();
293 } else if (emitted_forwarders.ContainsKey (t.MemberDefinition)) {
294 Report.SymbolRelatedToPreviousError (emitted_forwarders[t.MemberDefinition].Location, null);
295 Report.Error (739, a.Location, "A duplicate type forward of type `{0}'",
296 t.GetSignatureForError ());
300 emitted_forwarders.Add (t.MemberDefinition, a);
302 if (t.MemberDefinition.DeclaringAssembly == this) {
303 Report.SymbolRelatedToPreviousError (t);
304 Report.Error (729, a.Location, "Cannot forward type `{0}' because it is defined in this assembly",
305 t.GetSignatureForError ());
310 Report.Error (730, a.Location, "Cannot forward type `{0}' because it is a nested type",
311 t.GetSignatureForError ());
315 builder_extra.AddTypeForwarder (t.GetDefinition (), a.Location);
319 if (a.Type == pa.Extension) {
320 a.Error_MisusedExtensionAttribute ();
324 if (a.Type == pa.InternalsVisibleTo) {
325 string assembly_name = a.GetString ();
326 if (assembly_name == null) {
327 Report.Error (7030, a.Location, "Friend assembly reference cannot have `null' value");
331 if (assembly_name.Length == 0)
334 ParsedAssemblyName aname;
335 ParseAssemblyResult r = Fusion.ParseAssemblyName (assembly_name, out aname);
336 if (r != ParseAssemblyResult.OK) {
337 Report.Warning (1700, 3, a.Location, "Friend assembly reference `{0}' is invalid and cannot be resolved",
342 if (aname.Version != null || aname.Culture != null || aname.ProcessorArchitecture != ProcessorArchitecture.None) {
343 Report.Error (1725, a.Location,
344 "Friend assembly reference `{0}' is invalid. InternalsVisibleTo declarations cannot have a version, culture or processor architecture specified",
350 if (public_key != null && !aname.HasPublicKey) {
351 Report.Error (1726, a.Location,
352 "Friend assembly reference `{0}' is invalid. Strong named assemblies must specify a public key in their InternalsVisibleTo declarations",
357 } else if (a.Type == pa.RuntimeCompatibility) {
358 wrap_non_exception_throws_custom = true;
359 } else if (a.Type == pa.AssemblyFileVersion) {
360 vi_product_version = a.GetString ();
361 if (string.IsNullOrEmpty (vi_product_version) || IsValidAssemblyVersion (vi_product_version, false) == null) {
362 Report.Warning (7035, 1, a.Location, "The specified version string `{0}' does not conform to the recommended format major.minor.build.revision",
363 vi_product_version, a.Name);
367 // File version info decoding from blob is not supported
368 var cab = new CustomAttributeBuilder ((ConstructorInfo) ctor.GetMetaInfo (), new object[] { vi_product_version });
369 Builder.SetCustomAttribute (cab);
371 } else if (a.Type == pa.AssemblyProduct) {
372 vi_product = a.GetString ();
373 } else if (a.Type == pa.AssemblyCompany) {
374 vi_company = a.GetString ();
375 } else if (a.Type == pa.AssemblyCopyright) {
376 vi_copyright = a.GetString ();
377 } else if (a.Type == pa.AssemblyTrademark) {
378 vi_trademark = a.GetString ();
379 } else if (a.Type == pa.Debuggable) {
380 has_user_debuggable = true;
384 // Win32 version info attributes AssemblyDescription and AssemblyTitle cannot be
385 // set using public API and because we have blob like attributes we need to use
386 // special option DecodeVersionInfoAttributeBlobs to support values extraction
389 SetCustomAttribute (ctor, cdata);
393 // When using assembly public key attributes InternalsVisibleTo key
394 // was not checked, we have to do it later when we actually know what
395 // our public key token is
397 void CheckReferencesPublicToken ()
399 // TODO: It should check only references assemblies but there is
400 // no working SRE API
401 foreach (var entry in Importer.Assemblies) {
402 var a = entry as ImportedAssemblyDefinition;
403 if (a == null || a.IsMissing)
406 if (public_key != null && !a.HasStrongName) {
407 Report.Error (1577, "Referenced assembly `{0}' does not have a strong name",
411 var ci = a.Assembly.GetName ().CultureInfo;
412 if (!ci.Equals (CultureInfo.InvariantCulture)) {
413 Report.Warning (8009, 1, "Referenced assembly `{0}' has different culture setting of `{1}'",
417 if (!a.IsFriendAssemblyTo (this))
420 var attr = a.GetAssemblyVisibleToName (this);
421 var atoken = attr.GetPublicKeyToken ();
423 if (ArrayComparer.IsEqual (GetPublicKeyToken (), atoken))
426 Report.SymbolRelatedToPreviousError (a.Location);
428 "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",
429 attr.FullName, FullName);
433 protected AssemblyName CreateAssemblyName ()
435 var an = new AssemblyName (name);
437 if (public_key != null && Compiler.Settings.Target != Target.Module) {
439 an.SetPublicKey (public_key);
441 if (public_key.Length == 16) {
442 Report.Error (1606, "Could not sign the assembly. ECMA key can only be used to delay-sign assemblies");
443 } else if (private_key == null) {
444 Error_AssemblySigning ("The specified key file does not have a private key");
446 an.KeyPair = private_key;
454 public virtual ModuleBuilder CreateModuleBuilder ()
456 if (file_name == null)
457 throw new NotSupportedException ("transient module in static assembly");
459 var module_name = Path.GetFileName (file_name);
461 // Always initialize module without symbolInfo. We could be framework dependent
462 // but returned ISymbolWriter does not have all what we need therefore some
463 // adaptor will be needed for now we alwayas emit MDB format when generating
465 return Builder.DefineDynamicModule (module_name, module_name, false);
468 public virtual void Emit ()
470 if (Compiler.Settings.Target == Target.Module) {
471 module_target_attrs = new AssemblyAttributesPlaceholder (module, name);
472 module_target_attrs.CreateContainer ();
473 module_target_attrs.DefineContainer ();
474 module_target_attrs.Define ();
475 module.AddCompilerGeneratedClass (module_target_attrs);
476 } else if (added_modules != null) {
477 ReadModulesAssemblyAttributes ();
480 if (Compiler.Settings.GenerateDebugInfo) {
481 symbol_writer = new MonoSymbolFile ();
484 module.EmitContainer ();
486 if (module.HasExtensionMethod) {
487 var pa = module.PredefinedAttributes.Extension;
489 SetCustomAttribute (pa.Constructor, AttributeEncoder.Empty);
493 if (!IsSatelliteAssembly) {
494 if (!has_user_debuggable && Compiler.Settings.GenerateDebugInfo) {
495 var pa = module.PredefinedAttributes.Debuggable;
497 var modes = System.Diagnostics.DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints;
498 if (!Compiler.Settings.Optimize)
499 modes |= System.Diagnostics.DebuggableAttribute.DebuggingModes.DisableOptimizations;
501 pa.EmitAttribute (Builder, modes);
505 if (!wrap_non_exception_throws_custom) {
506 PredefinedAttribute pa = module.PredefinedAttributes.RuntimeCompatibility;
507 if (pa.IsDefined && pa.ResolveBuilder ()) {
508 var prop = module.PredefinedMembers.RuntimeCompatibilityWrapNonExceptionThrows.Get ();
510 AttributeEncoder encoder = new AttributeEncoder ();
511 encoder.EncodeNamedPropertyArgument (prop, new BoolLiteral (Compiler.BuiltinTypes, true, Location.Null));
512 SetCustomAttribute (pa.Constructor, encoder.ToArray ());
517 if (declarative_security != null) {
519 foreach (var entry in declarative_security) {
520 Builder.__AddDeclarativeSecurity (entry);
523 throw new NotSupportedException ("Assembly-level security");
528 CheckReferencesPublicToken ();
533 public byte[] GetPublicKeyToken ()
535 if (public_key == null || public_key_token != null)
536 return public_key_token;
538 HashAlgorithm ha = SHA1.Create ();
539 byte[] hash = ha.ComputeHash (public_key);
540 // we need the last 8 bytes in reverse order
541 public_key_token = new byte[8];
542 Buffer.BlockCopy (hash, hash.Length - 8, public_key_token, 0, 8);
543 Array.Reverse (public_key_token, 0, 8);
544 return public_key_token;
548 // Either keyFile or keyContainer has to be non-null
550 void LoadPublicKey (string keyFile, string keyContainer)
552 if (keyContainer != null) {
554 private_key = new StrongNameKeyPair (keyContainer);
555 public_key = private_key.PublicKey;
557 Error_AssemblySigning ("The specified key container `" + keyContainer + "' does not exist");
563 bool key_file_exists = File.Exists (keyFile);
566 // For attribute based KeyFile do additional lookup
567 // in output assembly path
569 if (!key_file_exists && Compiler.Settings.StrongNameKeyFile == null) {
571 // The key file can be relative to output assembly
573 string test_path = Path.Combine (Path.GetDirectoryName (file_name), keyFile);
574 key_file_exists = File.Exists (test_path);
579 if (!key_file_exists) {
580 Error_AssemblySigning ("The specified key file `" + keyFile + "' does not exist");
584 using (FileStream fs = new FileStream (keyFile, FileMode.Open, FileAccess.Read)) {
585 byte[] snkeypair = new byte[fs.Length];
586 fs.Read (snkeypair, 0, snkeypair.Length);
588 // check for ECMA key
589 if (snkeypair.Length == 16) {
590 public_key = snkeypair;
595 // take it, with or without, a private key
596 RSA rsa = CryptoConvert.FromCapiKeyBlob (snkeypair);
597 // and make sure we only feed the public part to Sys.Ref
598 byte[] publickey = CryptoConvert.ToCapiPublicKeyBlob (rsa);
600 // AssemblyName.SetPublicKey requires an additional header
601 byte[] publicKeyHeader = new byte[8] { 0x00, 0x24, 0x00, 0x00, 0x04, 0x80, 0x00, 0x00 };
604 public_key = new byte[12 + publickey.Length];
605 Buffer.BlockCopy (publicKeyHeader, 0, public_key, 0, publicKeyHeader.Length);
607 // Length of Public Key (in bytes)
608 int lastPart = public_key.Length - 12;
609 public_key[8] = (byte) (lastPart & 0xFF);
610 public_key[9] = (byte) ((lastPart >> 8) & 0xFF);
611 public_key[10] = (byte) ((lastPart >> 16) & 0xFF);
612 public_key[11] = (byte) ((lastPart >> 24) & 0xFF);
614 Buffer.BlockCopy (publickey, 0, public_key, 12, publickey.Length);
616 Error_AssemblySigning ("The specified key file `" + keyFile + "' has incorrect format");
624 // TODO: Is there better way to test for a private key presence ?
625 CryptoConvert.FromCapiPrivateKeyBlob (snkeypair);
626 private_key = new StrongNameKeyPair (snkeypair);
631 void ReadModulesAssemblyAttributes ()
633 foreach (var m in added_modules) {
634 var cattrs = m.ReadAssemblyAttributes ();
638 module.OptAttributes.AddAttributes (cattrs);
642 public void Resolve ()
644 if (Compiler.Settings.Unsafe && module.PredefinedTypes.SecurityAction.Define ()) {
646 // Emits [assembly: SecurityPermissionAttribute (SecurityAction.RequestMinimum, SkipVerification = true)]
647 // when -unsafe option was specified
649 Location loc = Location.Null;
651 MemberAccess system_security_permissions = new MemberAccess (new MemberAccess (
652 new QualifiedAliasMember (QualifiedAliasMember.GlobalAlias, "System", loc), "Security", loc), "Permissions", loc);
654 var req_min = module.PredefinedMembers.SecurityActionRequestMinimum.Resolve (loc);
656 Arguments pos = new Arguments (1);
657 pos.Add (new Argument (req_min.GetConstant (null)));
659 Arguments named = new Arguments (1);
660 named.Add (new NamedArgument ("SkipVerification", loc, new BoolLiteral (Compiler.BuiltinTypes, true, loc)));
662 Attribute g = new Attribute ("assembly",
663 new MemberAccess (system_security_permissions, "SecurityPermissionAttribute"),
664 new Arguments[] { pos, named }, loc, false);
665 g.AttachTo (module, module);
667 // Disable no-location warnings (e.g. obsolete) for compiler generated attribute
668 Compiler.Report.DisableReporting ();
670 var ctor = g.Resolve ();
672 g.ExtractSecurityPermissionSet (ctor, ref declarative_security);
675 Compiler.Report.EnableReporting ();
679 if (module.OptAttributes == null)
682 // Ensure that we only have GlobalAttributes, since the Search isn't safe with other types.
683 if (!module.OptAttributes.CheckTargets())
686 cls_attribute = module.ResolveAssemblyAttribute (module.PredefinedAttributes.CLSCompliant);
688 if (cls_attribute != null) {
689 is_cls_compliant = cls_attribute.GetClsCompliantAttributeValue ();
692 if (added_modules != null && Compiler.Settings.VerifyClsCompliance && is_cls_compliant) {
693 foreach (var m in added_modules) {
694 if (!m.IsCLSCompliant) {
696 "Added modules must be marked with the CLSCompliant attribute to match the assembly",
702 Attribute a = module.ResolveAssemblyAttribute (module.PredefinedAttributes.RuntimeCompatibility);
704 var val = a.GetNamedValue ("WrapNonExceptionThrows") as BoolConstant;
706 wrap_non_exception_throws = val.Value;
710 protected void ResolveAssemblySecurityAttributes ()
712 string key_file = null;
713 string key_container = null;
715 if (module.OptAttributes != null) {
716 foreach (Attribute a in module.OptAttributes.Attrs) {
717 // cannot rely on any resolve-based members before you call Resolve
718 if (a.ExplicitTarget != "assembly")
721 // TODO: This code is buggy: comparing Attribute name without resolving is wrong.
722 // However, this is invoked by CodeGen.Init, when none of the namespaces
724 // TODO: Does not handle quoted attributes properly
726 case "AssemblyKeyFile":
727 case "AssemblyKeyFileAttribute":
728 case "System.Reflection.AssemblyKeyFileAttribute":
729 if (Compiler.Settings.StrongNameKeyFile != null) {
730 Report.SymbolRelatedToPreviousError (a.Location, a.GetSignatureForError ());
731 Report.Warning (1616, 1, "Option `{0}' overrides attribute `{1}' given in a source file or added module",
732 "keyfile", "System.Reflection.AssemblyKeyFileAttribute");
734 string value = a.GetString ();
735 if (!string.IsNullOrEmpty (value)) {
736 Error_ObsoleteSecurityAttribute (a, "keyfile");
741 case "AssemblyKeyName":
742 case "AssemblyKeyNameAttribute":
743 case "System.Reflection.AssemblyKeyNameAttribute":
744 if (Compiler.Settings.StrongNameKeyContainer != null) {
745 Report.SymbolRelatedToPreviousError (a.Location, a.GetSignatureForError ());
746 Report.Warning (1616, 1, "Option `{0}' overrides attribute `{1}' given in a source file or added module",
747 "keycontainer", "System.Reflection.AssemblyKeyNameAttribute");
749 string value = a.GetString ();
750 if (!string.IsNullOrEmpty (value)) {
751 Error_ObsoleteSecurityAttribute (a, "keycontainer");
752 key_container = value;
756 case "AssemblyDelaySign":
757 case "AssemblyDelaySignAttribute":
758 case "System.Reflection.AssemblyDelaySignAttribute":
759 bool b = a.GetBoolean ();
761 Error_ObsoleteSecurityAttribute (a, "delaysign");
770 // We came here only to report assembly attributes warnings
771 if (public_key != null)
775 // Load the strong key file found in attributes when no
776 // command line key was given
778 if (key_file != null || key_container != null) {
779 LoadPublicKey (key_file, key_container);
780 } else if (delay_sign) {
781 Report.Warning (1607, 1, "Delay signing was requested but no key file was given");
785 public void EmbedResources ()
788 // Add Win32 resources
790 if (Compiler.Settings.Win32ResourceFile != null) {
791 Builder.DefineUnmanagedResource (Compiler.Settings.Win32ResourceFile);
793 Builder.DefineVersionInfoResource (vi_product, vi_product_version, vi_company, vi_copyright, vi_trademark);
796 if (Compiler.Settings.Win32IconFile != null) {
797 builder_extra.DefineWin32IconResource (Compiler.Settings.Win32IconFile);
800 if (Compiler.Settings.Resources != null) {
801 if (Compiler.Settings.Target == Target.Module) {
802 Report.Error (1507, "Cannot link resource file when building a module");
805 foreach (var res in Compiler.Settings.Resources) {
806 if (!File.Exists (res.FileName)) {
807 Report.Error (1566, "Error reading resource file `{0}'", res.FileName);
813 if (counter++ < 10) {
814 stream = File.OpenRead (res.FileName);
816 // TODO: SRE API requires resource stream to be available during AssemblyBuilder::Save
817 // we workaround it by reading everything into memory to compile projects with
818 // many embedded resource (over 3500) references
819 stream = new MemoryStream (File.ReadAllBytes (res.FileName));
822 module.Builder.DefineManifestResource (res.Name, stream, res.Attributes);
824 Builder.AddResourceFile (res.Name, Path.GetFileName (res.FileName), res.Attributes);
833 PortableExecutableKinds pekind = PortableExecutableKinds.ILOnly;
834 ImageFileMachine machine;
836 switch (Compiler.Settings.Platform) {
838 pekind |= PortableExecutableKinds.Required32Bit;
839 machine = ImageFileMachine.I386;
842 pekind |= PortableExecutableKinds.PE32Plus;
843 machine = ImageFileMachine.AMD64;
846 machine = ImageFileMachine.IA64;
848 case Platform.AnyCPU32Preferred:
850 pekind |= PortableExecutableKinds.Preferred32Bit;
851 machine = ImageFileMachine.I386;
854 throw new NotSupportedException ();
858 machine = ImageFileMachine.ARM;
861 throw new NotSupportedException ();
863 case Platform.AnyCPU:
865 machine = ImageFileMachine.I386;
869 Compiler.TimeReporter.Start (TimeReporter.TimerType.OutputSave);
871 if (Compiler.Settings.Target == Target.Module) {
872 SaveModule (pekind, machine);
874 Builder.Save (module.Builder.ScopeName, pekind, machine);
876 } catch (Exception e) {
877 Report.Error (16, "Could not write to file `" + name + "', cause: " + e.Message);
879 Compiler.TimeReporter.Stop (TimeReporter.TimerType.OutputSave);
881 // Save debug symbols file
882 if (symbol_writer != null && Compiler.Report.Errors == 0) {
883 // TODO: it should run in parallel
884 Compiler.TimeReporter.Start (TimeReporter.TimerType.DebugSave);
886 var filename = file_name + ".mdb";
888 // We mmap the file, so unlink the previous version since it may be in use
889 File.Delete (filename);
891 // We can safely ignore
894 module.WriteDebugSymbol (symbol_writer);
896 using (FileStream fs = new FileStream (filename, FileMode.Create, FileAccess.Write)) {
897 symbol_writer.CreateSymbolFile (module.Builder.ModuleVersionId, fs);
900 Compiler.TimeReporter.Stop (TimeReporter.TimerType.DebugSave);
904 protected virtual void SaveModule (PortableExecutableKinds pekind, ImageFileMachine machine)
906 Report.RuntimeMissingSupport (Location.Null, "-target:module");
909 void SetCustomAttribute (MethodSpec ctor, byte[] data)
911 if (module_target_attrs != null)
912 module_target_attrs.AddAssemblyAttribute (ctor, data);
914 Builder.SetCustomAttribute ((ConstructorInfo) ctor.GetMetaInfo (), data);
917 void SetEntryPoint ()
919 if (!Compiler.Settings.NeedsEntryPoint) {
920 if (Compiler.Settings.MainClass != null)
921 Report.Error (2017, "Cannot specify -main if building a module or library");
926 PEFileKinds file_kind;
928 switch (Compiler.Settings.Target) {
931 file_kind = PEFileKinds.Dll;
934 file_kind = PEFileKinds.WindowApplication;
937 file_kind = PEFileKinds.ConsoleApplication;
941 if (entry_point == null) {
942 string main_class = Compiler.Settings.MainClass;
943 if (main_class != null) {
944 // TODO: Handle dotted names
945 var texpr = module.GlobalRootNamespace.LookupType (module, main_class, 0, LookupMode.Probing, Location.Null);
947 Report.Error (1555, "Could not find `{0}' specified for Main method", main_class);
951 var mtype = texpr.MemberDefinition as ClassOrStruct;
953 Report.Error (1556, "`{0}' specified for Main method must be a valid class or struct", main_class);
957 Report.Error (1558, mtype.Location, "`{0}' does not have a suitable static Main method", mtype.GetSignatureForError ());
959 string pname = file_name == null ? name : Path.GetFileName (file_name);
960 Report.Error (5001, "Program `{0}' does not contain a static `Main' method suitable for an entry point",
967 Builder.SetEntryPoint (entry_point.MethodBuilder, file_kind);
970 void Error_ObsoleteSecurityAttribute (Attribute a, string option)
972 Report.Warning (1699, 1, a.Location,
973 "Use compiler option `{0}' or appropriate project settings instead of `{1}' attribute",
977 void Error_AssemblySigning (string text)
979 Report.Error (1548, "Error during assembly signing. " + text);
982 public bool IsFriendAssemblyTo (IAssemblyDefinition assembly)
987 static Version IsValidAssemblyVersion (string version, bool allowGenerated)
989 string[] parts = version.Split ('.');
990 if (parts.Length < 1 || parts.Length > 4)
993 var values = new int[4];
994 for (int i = 0; i < parts.Length; ++i) {
995 if (!int.TryParse (parts[i], out values[i])) {
996 if (parts[i].Length == 1 && parts[i][0] == '*' && allowGenerated) {
998 // Nothing can follow *
999 if (parts.Length > 3)
1002 // Generate Build value based on days since 1/1/2000
1003 TimeSpan days = DateTime.Today - new DateTime (2000, 1, 1);
1004 values[i] = System.Math.Max (days.Days, 0);
1009 // Generate Revision value based on every other second today
1010 var seconds = DateTime.Now - DateTime.Today;
1011 values[i] = (int) seconds.TotalSeconds / 2;
1019 if (values[i] > ushort.MaxValue)
1023 return new Version (values[0], values[1], values[2], values[3]);
1027 public class AssemblyResource : IEquatable<AssemblyResource>
1029 public AssemblyResource (string fileName, string name)
1030 : this (fileName, name, false)
1034 public AssemblyResource (string fileName, string name, bool isPrivate)
1036 FileName = fileName;
1038 Attributes = isPrivate ? ResourceAttributes.Private : ResourceAttributes.Public;
1041 public ResourceAttributes Attributes { get; private set; }
1042 public string Name { get; private set; }
1043 public string FileName { get; private set; }
1044 public bool IsEmbeded { get; set; }
1046 #region IEquatable<AssemblyResource> Members
1048 public bool Equals (AssemblyResource other)
1050 return Name == other.Name;
1057 // A placeholder class for assembly attributes when emitting module
1059 class AssemblyAttributesPlaceholder : CompilerGeneratedContainer
1061 static readonly string TypeNamePrefix = "<$AssemblyAttributes${0}>";
1062 public static readonly string AssemblyFieldName = "attributes";
1066 public AssemblyAttributesPlaceholder (ModuleContainer parent, string outputName)
1067 : base (parent, new MemberName (GetGeneratedName (outputName)), Modifiers.STATIC | Modifiers.INTERNAL)
1069 assembly = new Field (this, new TypeExpression (parent.Compiler.BuiltinTypes.Object, Location), Modifiers.PUBLIC | Modifiers.STATIC,
1070 new MemberName (AssemblyFieldName), null);
1072 AddField (assembly);
1075 public void AddAssemblyAttribute (MethodSpec ctor, byte[] data)
1077 assembly.SetCustomAttribute (ctor, data);
1080 public static string GetGeneratedName (string outputName)
1082 return string.Format (TypeNamePrefix, outputName);
1087 // Extension to System.Reflection.Emit.AssemblyBuilder to have fully compatible
1088 // compiler. This is a default implementation for framework System.Reflection.Emit
1089 // which does not implement any of the methods
1091 public class AssemblyBuilderExtension
1093 readonly CompilerContext ctx;
1095 public AssemblyBuilderExtension (CompilerContext ctx)
1100 public virtual System.Reflection.Module AddModule (string module)
1102 ctx.Report.RuntimeMissingSupport (Location.Null, "-addmodule");
1106 public virtual void AddPermissionRequests (PermissionSet[] permissions)
1108 ctx.Report.RuntimeMissingSupport (Location.Null, "assembly declarative security");
1111 public virtual void AddTypeForwarder (TypeSpec type, Location loc)
1113 ctx.Report.RuntimeMissingSupport (loc, "TypeForwardedToAttribute");
1116 public virtual void DefineWin32IconResource (string fileName)
1118 ctx.Report.RuntimeMissingSupport (Location.Null, "-win32icon");
1121 public virtual void SetAlgorithmId (uint value, Location loc)
1123 ctx.Report.RuntimeMissingSupport (loc, "AssemblyAlgorithmIdAttribute");
1126 public virtual void SetCulture (string culture, Location loc)
1128 ctx.Report.RuntimeMissingSupport (loc, "AssemblyCultureAttribute");
1131 public virtual void SetFlags (uint flags, Location loc)
1133 ctx.Report.RuntimeMissingSupport (loc, "AssemblyFlagsAttribute");
1136 public virtual void SetVersion (Version version, Location loc)
1138 ctx.Report.RuntimeMissingSupport (loc, "AssemblyVersionAttribute");
1142 abstract class AssemblyReferencesLoader<T> where T : class
1144 protected readonly CompilerContext compiler;
1146 protected readonly List<string> paths;
1148 protected AssemblyReferencesLoader (CompilerContext compiler)
1150 this.compiler = compiler;
1152 paths = new List<string> ();
1153 paths.Add (Directory.GetCurrentDirectory ());
1154 paths.AddRange (compiler.Settings.ReferencesLookupPaths);
1157 public abstract bool HasObjectType (T assembly);
1158 protected abstract string[] GetDefaultReferences ();
1159 public abstract T LoadAssemblyFile (string fileName, bool isImplicitReference);
1160 public abstract void LoadReferences (ModuleContainer module);
1162 protected void Error_FileNotFound (string fileName)
1164 compiler.Report.Error (6, "Metadata file `{0}' could not be found", fileName);
1167 protected void Error_FileCorrupted (string fileName)
1169 compiler.Report.Error (9, "Metadata file `{0}' does not contain valid metadata", fileName);
1172 protected void Error_AssemblyIsModule (string fileName)
1174 compiler.Report.Error (1509,
1175 "Referenced assembly file `{0}' is a module. Consider using `-addmodule' option to add the module",
1179 protected void Error_ModuleIsAssembly (string fileName)
1181 compiler.Report.Error (1542,
1182 "Added module file `{0}' is an assembly. Consider using `-r' option to reference the file",
1186 protected void LoadReferencesCore (ModuleContainer module, out T corlib_assembly, out List<Tuple<RootNamespace, T>> loaded)
1188 compiler.TimeReporter.Start (TimeReporter.TimerType.ReferencesLoading);
1190 loaded = new List<Tuple<RootNamespace, T>> ();
1193 // Load mscorlib.dll as the first
1195 if (module.Compiler.Settings.StdLib) {
1196 corlib_assembly = LoadAssemblyFile ("mscorlib.dll", true);
1198 corlib_assembly = default (T);
1202 foreach (string r in module.Compiler.Settings.AssemblyReferences) {
1203 a = LoadAssemblyFile (r, false);
1204 if (a == null || EqualityComparer<T>.Default.Equals (a, corlib_assembly))
1207 var key = Tuple.Create (module.GlobalRootNamespace, a);
1208 if (loaded.Contains (key))
1214 if (corlib_assembly == null) {
1216 // Requires second pass because HasObjectType can trigger assembly load event
1218 for (int i = 0; i < loaded.Count; ++i) {
1219 var assembly = loaded [i];
1222 // corlib assembly is the first referenced assembly which contains System.Object
1224 if (HasObjectType (assembly.Item2)) {
1225 corlib_assembly = assembly.Item2;
1226 loaded.RemoveAt (i);
1232 foreach (var entry in module.Compiler.Settings.AssemblyReferencesAliases) {
1233 a = LoadAssemblyFile (entry.Item2, false);
1237 var key = Tuple.Create (module.CreateRootNamespace (entry.Item1), a);
1238 if (loaded.Contains (key))
1244 if (compiler.Settings.LoadDefaultReferences) {
1245 foreach (string r in GetDefaultReferences ()) {
1246 a = LoadAssemblyFile (r, true);
1250 var key = Tuple.Create (module.GlobalRootNamespace, a);
1251 if (loaded.Contains (key))
1258 compiler.TimeReporter.Stop (TimeReporter.TimerType.ReferencesLoading);