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 a.Error_AttributeEmitError ("The executables cannot be satelite 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 a.Error_AttributeEmitError (string.Format ("Specified version `{0}' is not valid", value));
238 if (Compiler.Settings.Target == Target.Module) {
239 SetCustomAttribute (ctor, cdata);
241 builder_extra.SetVersion (vinfo, a.Location);
247 if (a.Type == pa.AssemblyAlgorithmId) {
248 const int pos = 2; // skip CA header
249 uint alg = (uint) cdata [pos];
250 alg |= ((uint) cdata [pos + 1]) << 8;
251 alg |= ((uint) cdata [pos + 2]) << 16;
252 alg |= ((uint) cdata [pos + 3]) << 24;
254 if (Compiler.Settings.Target == Target.Module) {
255 SetCustomAttribute (ctor, cdata);
257 builder_extra.SetAlgorithmId (alg, a.Location);
263 if (a.Type == pa.AssemblyFlags) {
264 const int pos = 2; // skip CA header
265 uint flags = (uint) cdata[pos];
266 flags |= ((uint) cdata [pos + 1]) << 8;
267 flags |= ((uint) cdata [pos + 2]) << 16;
268 flags |= ((uint) cdata [pos + 3]) << 24;
270 // Ignore set PublicKey flag if assembly is not strongnamed
271 if ((flags & (uint) AssemblyNameFlags.PublicKey) != 0 && public_key == null)
272 flags &= ~(uint) AssemblyNameFlags.PublicKey;
274 if (Compiler.Settings.Target == Target.Module) {
275 SetCustomAttribute (ctor, cdata);
277 builder_extra.SetFlags (flags, a.Location);
283 if (a.Type == pa.TypeForwarder) {
284 TypeSpec t = a.GetArgumentType ();
285 if (t == null || TypeManager.HasElementType (t)) {
286 Report.Error (735, a.Location, "Invalid type specified as an argument for TypeForwardedTo attribute");
290 if (emitted_forwarders == null) {
291 emitted_forwarders = new Dictionary<ITypeDefinition, Attribute> ();
292 } else if (emitted_forwarders.ContainsKey (t.MemberDefinition)) {
293 Report.SymbolRelatedToPreviousError (emitted_forwarders[t.MemberDefinition].Location, null);
294 Report.Error (739, a.Location, "A duplicate type forward of type `{0}'",
295 t.GetSignatureForError ());
299 emitted_forwarders.Add (t.MemberDefinition, a);
301 if (t.MemberDefinition.DeclaringAssembly == this) {
302 Report.SymbolRelatedToPreviousError (t);
303 Report.Error (729, a.Location, "Cannot forward type `{0}' because it is defined in this assembly",
304 t.GetSignatureForError ());
309 Report.Error (730, a.Location, "Cannot forward type `{0}' because it is a nested type",
310 t.GetSignatureForError ());
314 builder_extra.AddTypeForwarder (t.GetDefinition (), a.Location);
318 if (a.Type == pa.Extension) {
319 a.Error_MisusedExtensionAttribute ();
323 if (a.Type == pa.InternalsVisibleTo) {
324 string assembly_name = a.GetString ();
325 if (assembly_name.Length == 0)
328 ParsedAssemblyName aname;
329 ParseAssemblyResult r = Fusion.ParseAssemblyName (assembly_name, out aname);
330 if (r != ParseAssemblyResult.OK) {
331 Report.Warning (1700, 3, a.Location, "Assembly reference `{0}' is invalid and cannot be resolved",
336 if (aname.Version != null || aname.Culture != null || aname.ProcessorArchitecture != ProcessorArchitecture.None) {
337 Report.Error (1725, a.Location,
338 "Friend assembly reference `{0}' is invalid. InternalsVisibleTo declarations cannot have a version, culture or processor architecture specified",
344 if (public_key != null && !aname.HasPublicKey) {
345 Report.Error (1726, a.Location,
346 "Friend assembly reference `{0}' is invalid. Strong named assemblies must specify a public key in their InternalsVisibleTo declarations",
351 } else if (a.Type == pa.RuntimeCompatibility) {
352 wrap_non_exception_throws_custom = true;
353 } else if (a.Type == pa.AssemblyFileVersion) {
354 vi_product_version = a.GetString ();
355 if (string.IsNullOrEmpty (vi_product_version) || IsValidAssemblyVersion (vi_product_version, false) == null) {
356 Report.Warning (1607, 1, a.Location, "The version number `{0}' specified for `{1}' is invalid",
357 vi_product_version, a.Name);
360 } else if (a.Type == pa.AssemblyProduct) {
361 vi_product = a.GetString ();
362 } else if (a.Type == pa.AssemblyCompany) {
363 vi_company = a.GetString ();
364 } else if (a.Type == pa.AssemblyDescription) {
365 // TODO: Needs extra api
366 } else if (a.Type == pa.AssemblyCopyright) {
367 vi_copyright = a.GetString ();
368 } else if (a.Type == pa.AssemblyTrademark) {
369 vi_trademark = a.GetString ();
370 } else if (a.Type == pa.Debuggable) {
371 has_user_debuggable = true;
374 SetCustomAttribute (ctor, cdata);
378 // When using assembly public key attributes InternalsVisibleTo key
379 // was not checked, we have to do it later when we actually know what
380 // our public key token is
382 void CheckReferencesPublicToken ()
384 // TODO: It should check only references assemblies but there is
385 // no working SRE API
386 foreach (var entry in Importer.Assemblies) {
387 var a = entry as ImportedAssemblyDefinition;
388 if (a == null || a.IsMissing)
391 if (public_key != null && !a.HasStrongName) {
392 Report.Error (1577, "Referenced assembly `{0}' does not have a strong name",
396 var ci = a.Assembly.GetName ().CultureInfo;
397 if (!ci.Equals (System.Globalization.CultureInfo.InvariantCulture)) {
398 Report.Warning (1607, 1, "Referenced assembly `{0}' has different culture setting of `{1}'",
402 if (!a.IsFriendAssemblyTo (this))
405 var attr = a.GetAssemblyVisibleToName (this);
406 var atoken = attr.GetPublicKeyToken ();
408 if (ArrayComparer.IsEqual (GetPublicKeyToken (), atoken))
411 Report.SymbolRelatedToPreviousError (a.Location);
413 "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",
414 attr.FullName, FullName);
418 protected AssemblyName CreateAssemblyName ()
420 var an = new AssemblyName (name);
422 if (public_key != null && Compiler.Settings.Target != Target.Module) {
424 an.SetPublicKey (public_key);
426 if (public_key.Length == 16) {
427 Report.Error (1606, "Could not sign the assembly. ECMA key can only be used to delay-sign assemblies");
428 } else if (private_key == null) {
429 Error_AssemblySigning ("The specified key file does not have a private key");
431 an.KeyPair = private_key;
439 public virtual ModuleBuilder CreateModuleBuilder ()
441 if (file_name == null)
442 throw new NotSupportedException ("transient module in static assembly");
444 var module_name = Path.GetFileName (file_name);
446 // Always initialize module without symbolInfo. We could be framework dependent
447 // but returned ISymbolWriter does not have all what we need therefore some
448 // adaptor will be needed for now we alwayas emit MDB format when generating
450 return Builder.DefineDynamicModule (module_name, module_name, false);
453 public virtual void Emit ()
455 if (Compiler.Settings.Target == Target.Module) {
456 module_target_attrs = new AssemblyAttributesPlaceholder (module, name);
457 module_target_attrs.CreateContainer ();
458 module_target_attrs.DefineContainer ();
459 module_target_attrs.Define ();
460 module.AddCompilerGeneratedClass (module_target_attrs);
461 } else if (added_modules != null) {
462 ReadModulesAssemblyAttributes ();
465 if (Compiler.Settings.GenerateDebugInfo) {
466 symbol_writer = new MonoSymbolFile ();
469 module.EmitContainer ();
471 if (module.HasExtensionMethod) {
472 var pa = module.PredefinedAttributes.Extension;
474 SetCustomAttribute (pa.Constructor, AttributeEncoder.Empty);
478 if (!IsSatelliteAssembly) {
479 if (!has_user_debuggable && Compiler.Settings.GenerateDebugInfo) {
480 var pa = module.PredefinedAttributes.Debuggable;
482 var modes = System.Diagnostics.DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints;
483 if (!Compiler.Settings.Optimize)
484 modes |= System.Diagnostics.DebuggableAttribute.DebuggingModes.DisableOptimizations;
486 pa.EmitAttribute (Builder, modes);
490 if (!wrap_non_exception_throws_custom) {
491 PredefinedAttribute pa = module.PredefinedAttributes.RuntimeCompatibility;
492 if (pa.IsDefined && pa.ResolveBuilder ()) {
493 var prop = module.PredefinedMembers.RuntimeCompatibilityWrapNonExceptionThrows.Get ();
495 AttributeEncoder encoder = new AttributeEncoder ();
496 encoder.EncodeNamedPropertyArgument (prop, new BoolLiteral (Compiler.BuiltinTypes, true, Location.Null));
497 SetCustomAttribute (pa.Constructor, encoder.ToArray ());
502 if (declarative_security != null) {
504 foreach (var entry in declarative_security) {
505 Builder.__AddDeclarativeSecurity (entry);
508 throw new NotSupportedException ("Assembly-level security");
513 CheckReferencesPublicToken ();
518 public byte[] GetPublicKeyToken ()
520 if (public_key == null || public_key_token != null)
521 return public_key_token;
523 HashAlgorithm ha = SHA1.Create ();
524 byte[] hash = ha.ComputeHash (public_key);
525 // we need the last 8 bytes in reverse order
526 public_key_token = new byte[8];
527 Buffer.BlockCopy (hash, hash.Length - 8, public_key_token, 0, 8);
528 Array.Reverse (public_key_token, 0, 8);
529 return public_key_token;
533 // Either keyFile or keyContainer has to be non-null
535 void LoadPublicKey (string keyFile, string keyContainer)
537 if (keyContainer != null) {
539 private_key = new StrongNameKeyPair (keyContainer);
540 public_key = private_key.PublicKey;
542 Error_AssemblySigning ("The specified key container `" + keyContainer + "' does not exist");
548 bool key_file_exists = File.Exists (keyFile);
551 // For attribute based KeyFile do additional lookup
552 // in output assembly path
554 if (!key_file_exists && Compiler.Settings.StrongNameKeyFile == null) {
556 // The key file can be relative to output assembly
558 string test_path = Path.Combine (Path.GetDirectoryName (file_name), keyFile);
559 key_file_exists = File.Exists (test_path);
564 if (!key_file_exists) {
565 Error_AssemblySigning ("The specified key file `" + keyFile + "' does not exist");
569 using (FileStream fs = new FileStream (keyFile, FileMode.Open, FileAccess.Read)) {
570 byte[] snkeypair = new byte[fs.Length];
571 fs.Read (snkeypair, 0, snkeypair.Length);
573 // check for ECMA key
574 if (snkeypair.Length == 16) {
575 public_key = snkeypair;
580 // take it, with or without, a private key
581 RSA rsa = CryptoConvert.FromCapiKeyBlob (snkeypair);
582 // and make sure we only feed the public part to Sys.Ref
583 byte[] publickey = CryptoConvert.ToCapiPublicKeyBlob (rsa);
585 // AssemblyName.SetPublicKey requires an additional header
586 byte[] publicKeyHeader = new byte[8] { 0x00, 0x24, 0x00, 0x00, 0x04, 0x80, 0x00, 0x00 };
589 public_key = new byte[12 + publickey.Length];
590 Buffer.BlockCopy (publicKeyHeader, 0, public_key, 0, publicKeyHeader.Length);
592 // Length of Public Key (in bytes)
593 int lastPart = public_key.Length - 12;
594 public_key[8] = (byte) (lastPart & 0xFF);
595 public_key[9] = (byte) ((lastPart >> 8) & 0xFF);
596 public_key[10] = (byte) ((lastPart >> 16) & 0xFF);
597 public_key[11] = (byte) ((lastPart >> 24) & 0xFF);
599 Buffer.BlockCopy (publickey, 0, public_key, 12, publickey.Length);
601 Error_AssemblySigning ("The specified key file `" + keyFile + "' has incorrect format");
609 // TODO: Is there better way to test for a private key presence ?
610 CryptoConvert.FromCapiPrivateKeyBlob (snkeypair);
611 private_key = new StrongNameKeyPair (snkeypair);
616 void ReadModulesAssemblyAttributes ()
618 foreach (var m in added_modules) {
619 var cattrs = m.ReadAssemblyAttributes ();
623 module.OptAttributes.AddAttributes (cattrs);
627 public void Resolve ()
629 if (Compiler.Settings.Unsafe && module.PredefinedTypes.SecurityAction.Define ()) {
631 // Emits [assembly: SecurityPermissionAttribute (SecurityAction.RequestMinimum, SkipVerification = true)]
632 // when -unsafe option was specified
634 Location loc = Location.Null;
636 MemberAccess system_security_permissions = new MemberAccess (new MemberAccess (
637 new QualifiedAliasMember (QualifiedAliasMember.GlobalAlias, "System", loc), "Security", loc), "Permissions", loc);
639 var req_min = module.PredefinedMembers.SecurityActionRequestMinimum.Resolve (loc);
641 Arguments pos = new Arguments (1);
642 pos.Add (new Argument (req_min.GetConstant (null)));
644 Arguments named = new Arguments (1);
645 named.Add (new NamedArgument ("SkipVerification", loc, new BoolLiteral (Compiler.BuiltinTypes, true, loc)));
647 Attribute g = new Attribute ("assembly",
648 new MemberAccess (system_security_permissions, "SecurityPermissionAttribute"),
649 new Arguments[] { pos, named }, loc, false);
650 g.AttachTo (module, module);
652 // Disable no-location warnings (e.g. obsolete) for compiler generated attribute
653 Compiler.Report.DisableReporting ();
655 var ctor = g.Resolve ();
657 g.ExtractSecurityPermissionSet (ctor, ref declarative_security);
660 Compiler.Report.EnableReporting ();
664 if (module.OptAttributes == null)
667 // Ensure that we only have GlobalAttributes, since the Search isn't safe with other types.
668 if (!module.OptAttributes.CheckTargets())
671 cls_attribute = module.ResolveAssemblyAttribute (module.PredefinedAttributes.CLSCompliant);
673 if (cls_attribute != null) {
674 is_cls_compliant = cls_attribute.GetClsCompliantAttributeValue ();
677 if (added_modules != null && Compiler.Settings.VerifyClsCompliance && is_cls_compliant) {
678 foreach (var m in added_modules) {
679 if (!m.IsCLSCompliant) {
681 "Added modules must be marked with the CLSCompliant attribute to match the assembly",
687 Attribute a = module.ResolveAssemblyAttribute (module.PredefinedAttributes.RuntimeCompatibility);
689 var val = a.GetNamedValue ("WrapNonExceptionThrows") as BoolConstant;
691 wrap_non_exception_throws = val.Value;
695 protected void ResolveAssemblySecurityAttributes ()
697 string key_file = null;
698 string key_container = null;
700 if (module.OptAttributes != null) {
701 foreach (Attribute a in module.OptAttributes.Attrs) {
702 // cannot rely on any resolve-based members before you call Resolve
703 if (a.ExplicitTarget != "assembly")
706 // TODO: This code is buggy: comparing Attribute name without resolving is wrong.
707 // However, this is invoked by CodeGen.Init, when none of the namespaces
709 // TODO: Does not handle quoted attributes properly
711 case "AssemblyKeyFile":
712 case "AssemblyKeyFileAttribute":
713 case "System.Reflection.AssemblyKeyFileAttribute":
714 if (Compiler.Settings.StrongNameKeyFile != null) {
715 Report.SymbolRelatedToPreviousError (a.Location, a.GetSignatureForError ());
716 Report.Warning (1616, 1, "Option `{0}' overrides attribute `{1}' given in a source file or added module",
717 "keyfile", "System.Reflection.AssemblyKeyFileAttribute");
719 string value = a.GetString ();
720 if (!string.IsNullOrEmpty (value)) {
721 Error_ObsoleteSecurityAttribute (a, "keyfile");
726 case "AssemblyKeyName":
727 case "AssemblyKeyNameAttribute":
728 case "System.Reflection.AssemblyKeyNameAttribute":
729 if (Compiler.Settings.StrongNameKeyContainer != 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 "keycontainer", "System.Reflection.AssemblyKeyNameAttribute");
734 string value = a.GetString ();
735 if (!string.IsNullOrEmpty (value)) {
736 Error_ObsoleteSecurityAttribute (a, "keycontainer");
737 key_container = value;
741 case "AssemblyDelaySign":
742 case "AssemblyDelaySignAttribute":
743 case "System.Reflection.AssemblyDelaySignAttribute":
744 bool b = a.GetBoolean ();
746 Error_ObsoleteSecurityAttribute (a, "delaysign");
755 // We came here only to report assembly attributes warnings
756 if (public_key != null)
760 // Load the strong key file found in attributes when no
761 // command line key was given
763 if (key_file != null || key_container != null) {
764 LoadPublicKey (key_file, key_container);
765 } else if (delay_sign) {
766 Report.Warning (1607, 1, "Delay signing was requested but no key file was given");
770 public void EmbedResources ()
773 // Add Win32 resources
775 if (Compiler.Settings.Win32ResourceFile != null) {
776 Builder.DefineUnmanagedResource (Compiler.Settings.Win32ResourceFile);
778 Builder.DefineVersionInfoResource (vi_product, vi_product_version, vi_company, vi_copyright, vi_trademark);
781 if (Compiler.Settings.Win32IconFile != null) {
782 builder_extra.DefineWin32IconResource (Compiler.Settings.Win32IconFile);
785 if (Compiler.Settings.Resources != null) {
786 if (Compiler.Settings.Target == Target.Module) {
787 Report.Error (1507, "Cannot link resource file when building a module");
790 foreach (var res in Compiler.Settings.Resources) {
791 if (!File.Exists (res.FileName)) {
792 Report.Error (1566, "Error reading resource file `{0}'", res.FileName);
798 if (counter++ < 10) {
799 stream = File.OpenRead (res.FileName);
801 // TODO: SRE API requires resource stream to be available during AssemblyBuilder::Save
802 // we workaround it by reading everything into memory to compile projects with
803 // many embedded resource (over 3500) references
804 stream = new MemoryStream (File.ReadAllBytes (res.FileName));
807 module.Builder.DefineManifestResource (res.Name, stream, res.Attributes);
809 Builder.AddResourceFile (res.Name, Path.GetFileName (res.FileName), res.Attributes);
818 PortableExecutableKinds pekind = PortableExecutableKinds.ILOnly;
819 ImageFileMachine machine;
821 switch (Compiler.Settings.Platform) {
823 pekind |= PortableExecutableKinds.Required32Bit;
824 machine = ImageFileMachine.I386;
827 pekind |= PortableExecutableKinds.PE32Plus;
828 machine = ImageFileMachine.AMD64;
831 machine = ImageFileMachine.IA64;
833 case Platform.AnyCPU32Preferred:
835 pekind |= PortableExecutableKinds.Preferred32Bit;
836 machine = ImageFileMachine.I386;
839 throw new NotSupportedException ();
843 machine = ImageFileMachine.ARM;
846 throw new NotSupportedException ();
848 case Platform.AnyCPU:
850 machine = ImageFileMachine.I386;
854 Compiler.TimeReporter.Start (TimeReporter.TimerType.OutputSave);
856 if (Compiler.Settings.Target == Target.Module) {
857 SaveModule (pekind, machine);
859 Builder.Save (module.Builder.ScopeName, pekind, machine);
861 } catch (Exception e) {
862 Report.Error (16, "Could not write to file `" + name + "', cause: " + e.Message);
864 Compiler.TimeReporter.Stop (TimeReporter.TimerType.OutputSave);
866 // Save debug symbols file
867 if (symbol_writer != null && Compiler.Report.Errors == 0) {
868 // TODO: it should run in parallel
869 Compiler.TimeReporter.Start (TimeReporter.TimerType.DebugSave);
871 var filename = file_name + ".mdb";
873 // We mmap the file, so unlink the previous version since it may be in use
874 File.Delete (filename);
876 // We can safely ignore
879 module.WriteDebugSymbol (symbol_writer);
881 using (FileStream fs = new FileStream (filename, FileMode.Create, FileAccess.Write)) {
882 symbol_writer.CreateSymbolFile (module.Builder.ModuleVersionId, fs);
885 Compiler.TimeReporter.Stop (TimeReporter.TimerType.DebugSave);
889 protected virtual void SaveModule (PortableExecutableKinds pekind, ImageFileMachine machine)
891 Report.RuntimeMissingSupport (Location.Null, "-target:module");
894 void SetCustomAttribute (MethodSpec ctor, byte[] data)
896 if (module_target_attrs != null)
897 module_target_attrs.AddAssemblyAttribute (ctor, data);
899 Builder.SetCustomAttribute ((ConstructorInfo) ctor.GetMetaInfo (), data);
902 void SetEntryPoint ()
904 if (!Compiler.Settings.NeedsEntryPoint) {
905 if (Compiler.Settings.MainClass != null)
906 Report.Error (2017, "Cannot specify -main if building a module or library");
911 PEFileKinds file_kind;
913 switch (Compiler.Settings.Target) {
916 file_kind = PEFileKinds.Dll;
919 file_kind = PEFileKinds.WindowApplication;
922 file_kind = PEFileKinds.ConsoleApplication;
926 if (entry_point == null) {
927 string main_class = Compiler.Settings.MainClass;
928 if (main_class != null) {
929 // TODO: Handle dotted names
930 var texpr = module.GlobalRootNamespace.LookupType (module, main_class, 0, LookupMode.Probing, Location.Null);
932 Report.Error (1555, "Could not find `{0}' specified for Main method", main_class);
936 var mtype = texpr.MemberDefinition as ClassOrStruct;
938 Report.Error (1556, "`{0}' specified for Main method must be a valid class or struct", main_class);
942 Report.Error (1558, mtype.Location, "`{0}' does not have a suitable static Main method", mtype.GetSignatureForError ());
944 string pname = file_name == null ? name : Path.GetFileName (file_name);
945 Report.Error (5001, "Program `{0}' does not contain a static `Main' method suitable for an entry point",
952 Builder.SetEntryPoint (entry_point.MethodBuilder, file_kind);
955 void Error_ObsoleteSecurityAttribute (Attribute a, string option)
957 Report.Warning (1699, 1, a.Location,
958 "Use compiler option `{0}' or appropriate project settings instead of `{1}' attribute",
962 void Error_AssemblySigning (string text)
964 Report.Error (1548, "Error during assembly signing. " + text);
967 public bool IsFriendAssemblyTo (IAssemblyDefinition assembly)
972 static Version IsValidAssemblyVersion (string version, bool allowGenerated)
974 string[] parts = version.Split ('.');
975 if (parts.Length < 1 || parts.Length > 4)
978 var values = new int[4];
979 for (int i = 0; i < parts.Length; ++i) {
980 if (!int.TryParse (parts[i], out values[i])) {
981 if (parts[i].Length == 1 && parts[i][0] == '*' && allowGenerated) {
983 // Nothing can follow *
984 if (parts.Length > 3)
987 // Generate Build value based on days since 1/1/2000
988 TimeSpan days = DateTime.Today - new DateTime (2000, 1, 1);
989 values[i] = System.Math.Max (days.Days, 0);
994 // Generate Revision value based on every other second today
995 var seconds = DateTime.Now - DateTime.Today;
996 values[i] = (int) seconds.TotalSeconds / 2;
1004 if (values[i] > ushort.MaxValue)
1008 return new Version (values[0], values[1], values[2], values[3]);
1012 public class AssemblyResource : IEquatable<AssemblyResource>
1014 public AssemblyResource (string fileName, string name)
1015 : this (fileName, name, false)
1019 public AssemblyResource (string fileName, string name, bool isPrivate)
1021 FileName = fileName;
1023 Attributes = isPrivate ? ResourceAttributes.Private : ResourceAttributes.Public;
1026 public ResourceAttributes Attributes { get; private set; }
1027 public string Name { get; private set; }
1028 public string FileName { get; private set; }
1029 public bool IsEmbeded { get; set; }
1031 #region IEquatable<AssemblyResource> Members
1033 public bool Equals (AssemblyResource other)
1035 return Name == other.Name;
1042 // A placeholder class for assembly attributes when emitting module
1044 class AssemblyAttributesPlaceholder : CompilerGeneratedContainer
1046 static readonly string TypeNamePrefix = "<$AssemblyAttributes${0}>";
1047 public static readonly string AssemblyFieldName = "attributes";
1051 public AssemblyAttributesPlaceholder (ModuleContainer parent, string outputName)
1052 : base (parent, new MemberName (GetGeneratedName (outputName)), Modifiers.STATIC | Modifiers.INTERNAL)
1054 assembly = new Field (this, new TypeExpression (parent.Compiler.BuiltinTypes.Object, Location), Modifiers.PUBLIC | Modifiers.STATIC,
1055 new MemberName (AssemblyFieldName), null);
1057 AddField (assembly);
1060 public void AddAssemblyAttribute (MethodSpec ctor, byte[] data)
1062 assembly.SetCustomAttribute (ctor, data);
1065 public static string GetGeneratedName (string outputName)
1067 return string.Format (TypeNamePrefix, outputName);
1072 // Extension to System.Reflection.Emit.AssemblyBuilder to have fully compatible
1073 // compiler. This is a default implementation for framework System.Reflection.Emit
1074 // which does not implement any of the methods
1076 public class AssemblyBuilderExtension
1078 readonly CompilerContext ctx;
1080 public AssemblyBuilderExtension (CompilerContext ctx)
1085 public virtual System.Reflection.Module AddModule (string module)
1087 ctx.Report.RuntimeMissingSupport (Location.Null, "-addmodule");
1091 public virtual void AddPermissionRequests (PermissionSet[] permissions)
1093 ctx.Report.RuntimeMissingSupport (Location.Null, "assembly declarative security");
1096 public virtual void AddTypeForwarder (TypeSpec type, Location loc)
1098 ctx.Report.RuntimeMissingSupport (loc, "TypeForwardedToAttribute");
1101 public virtual void DefineWin32IconResource (string fileName)
1103 ctx.Report.RuntimeMissingSupport (Location.Null, "-win32icon");
1106 public virtual void SetAlgorithmId (uint value, Location loc)
1108 ctx.Report.RuntimeMissingSupport (loc, "AssemblyAlgorithmIdAttribute");
1111 public virtual void SetCulture (string culture, Location loc)
1113 ctx.Report.RuntimeMissingSupport (loc, "AssemblyCultureAttribute");
1116 public virtual void SetFlags (uint flags, Location loc)
1118 ctx.Report.RuntimeMissingSupport (loc, "AssemblyFlagsAttribute");
1121 public virtual void SetVersion (Version version, Location loc)
1123 ctx.Report.RuntimeMissingSupport (loc, "AssemblyVersionAttribute");
1127 abstract class AssemblyReferencesLoader<T> where T : class
1129 protected readonly CompilerContext compiler;
1131 protected readonly List<string> paths;
1133 protected AssemblyReferencesLoader (CompilerContext compiler)
1135 this.compiler = compiler;
1137 paths = new List<string> ();
1138 paths.Add (Directory.GetCurrentDirectory ());
1139 paths.AddRange (compiler.Settings.ReferencesLookupPaths);
1142 public abstract bool HasObjectType (T assembly);
1143 protected abstract string[] GetDefaultReferences ();
1144 public abstract T LoadAssemblyFile (string fileName, bool isImplicitReference);
1145 public abstract void LoadReferences (ModuleContainer module);
1147 protected void Error_FileNotFound (string fileName)
1149 compiler.Report.Error (6, "Metadata file `{0}' could not be found", fileName);
1152 protected void Error_FileCorrupted (string fileName)
1154 compiler.Report.Error (9, "Metadata file `{0}' does not contain valid metadata", fileName);
1157 protected void Error_AssemblyIsModule (string fileName)
1159 compiler.Report.Error (1509,
1160 "Referenced assembly file `{0}' is a module. Consider using `-addmodule' option to add the module",
1164 protected void Error_ModuleIsAssembly (string fileName)
1166 compiler.Report.Error (1542,
1167 "Added module file `{0}' is an assembly. Consider using `-r' option to reference the file",
1171 protected void LoadReferencesCore (ModuleContainer module, out T corlib_assembly, out List<Tuple<RootNamespace, T>> loaded)
1173 compiler.TimeReporter.Start (TimeReporter.TimerType.ReferencesLoading);
1175 loaded = new List<Tuple<RootNamespace, T>> ();
1178 // Load mscorlib.dll as the first
1180 if (module.Compiler.Settings.StdLib) {
1181 corlib_assembly = LoadAssemblyFile ("mscorlib.dll", true);
1183 corlib_assembly = default (T);
1187 foreach (string r in module.Compiler.Settings.AssemblyReferences) {
1188 a = LoadAssemblyFile (r, false);
1189 if (a == null || EqualityComparer<T>.Default.Equals (a, corlib_assembly))
1192 var key = Tuple.Create (module.GlobalRootNamespace, a);
1193 if (loaded.Contains (key))
1199 if (corlib_assembly == null) {
1201 // Requires second pass because HasObjectType can trigger assembly load event
1203 for (int i = 0; i < loaded.Count; ++i) {
1204 var assembly = loaded [i];
1207 // corlib assembly is the first referenced assembly which contains System.Object
1209 if (HasObjectType (assembly.Item2)) {
1210 corlib_assembly = assembly.Item2;
1211 loaded.RemoveAt (i);
1217 foreach (var entry in module.Compiler.Settings.AssemblyReferencesAliases) {
1218 a = LoadAssemblyFile (entry.Item2, false);
1222 var key = Tuple.Create (module.CreateRootNamespace (entry.Item1), a);
1223 if (loaded.Contains (key))
1229 if (compiler.Settings.LoadDefaultReferences) {
1230 foreach (string r in GetDefaultReferences ()) {
1231 a = LoadAssemblyFile (r, true);
1235 var key = Tuple.Create (module.GlobalRootNamespace, a);
1236 if (loaded.Contains (key))
1243 compiler.TimeReporter.Stop (TimeReporter.TimerType.ReferencesLoading);