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 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 HasExtensionMethod { get; }
40 bool IsCLSCompliant { get; }
41 bool IsMissing { get; }
44 byte[] GetPublicKeyToken ();
45 bool IsFriendAssemblyTo (IAssemblyDefinition assembly);
48 public abstract class AssemblyDefinition : IAssemblyDefinition
50 // TODO: make it private and move all builder based methods here
51 public AssemblyBuilder Builder;
52 protected AssemblyBuilderExtension builder_extra;
53 MonoSymbolWriter symbol_writer;
55 bool is_cls_compliant;
56 bool wrap_non_exception_throws;
57 bool wrap_non_exception_throws_custom;
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 protected AssemblyDefinition (ModuleContainer module, string name)
81 this.name = Path.GetFileNameWithoutExtension (name);
83 wrap_non_exception_throws = true;
85 delay_sign = Compiler.Settings.StrongNameDelaySign;
88 // Load strong name key early enough for assembly importer to be able to
89 // use the keys for InternalsVisibleTo
90 // This should go somewhere close to ReferencesLoading but don't have the place yet
92 if (Compiler.Settings.HasKeyFileOrContainer) {
93 LoadPublicKey (Compiler.Settings.StrongNameKeyFile, Compiler.Settings.StrongNameKeyContainer);
97 protected AssemblyDefinition (ModuleContainer module, string name, string fileName)
100 this.file_name = fileName;
105 public Attribute CLSCompliantAttribute {
107 return cls_attribute;
111 public CompilerContext Compiler {
113 return module.Compiler;
118 // Assembly entry point, aka Main method
120 public Method EntryPoint {
129 public string FullName {
131 return Builder.FullName;
135 public bool HasExtensionMethod {
137 return module.HasExtensionMethod;
141 public bool HasCLSCompliantAttribute {
143 return cls_attribute != null;
147 // TODO: This should not exist here but will require more changes
148 public MetadataImporter Importer {
152 public bool IsCLSCompliant {
154 return is_cls_compliant;
158 bool IAssemblyDefinition.IsMissing {
170 public bool WrapNonExceptionThrows {
172 return wrap_non_exception_throws;
176 protected Report Report {
178 return Compiler.Report;
184 public void AddModule (ImportedModuleDefinition module)
186 if (added_modules == null) {
187 added_modules = new List<ImportedModuleDefinition> ();
188 added_modules.Add (module);
192 public void ApplyAttributeBuilder (Attribute a, MethodSpec ctor, byte[] cdata, PredefinedAttributes pa)
194 if (a.IsValidSecurityAttribute ()) {
195 a.ExtractSecurityPermissionSet (ctor, ref declarative_security);
199 if (a.Type == pa.AssemblyCulture) {
200 string value = a.GetString ();
201 if (value == null || value.Length == 0)
204 if (Compiler.Settings.Target == Target.Exe) {
205 a.Error_AttributeEmitError ("The executables cannot be satelite assemblies, remove the attribute or keep it empty");
209 if (value == "neutral")
212 if (Compiler.Settings.Target == Target.Module) {
213 SetCustomAttribute (ctor, cdata);
215 builder_extra.SetCulture (value, a.Location);
221 if (a.Type == pa.AssemblyVersion) {
222 string value = a.GetString ();
223 if (value == null || value.Length == 0)
226 var vinfo = IsValidAssemblyVersion (value, true);
228 a.Error_AttributeEmitError (string.Format ("Specified version `{0}' is not valid", value));
232 if (Compiler.Settings.Target == Target.Module) {
233 SetCustomAttribute (ctor, cdata);
235 builder_extra.SetVersion (vinfo, a.Location);
241 if (a.Type == pa.AssemblyAlgorithmId) {
242 const int pos = 2; // skip CA header
243 uint alg = (uint) cdata [pos];
244 alg |= ((uint) cdata [pos + 1]) << 8;
245 alg |= ((uint) cdata [pos + 2]) << 16;
246 alg |= ((uint) cdata [pos + 3]) << 24;
248 if (Compiler.Settings.Target == Target.Module) {
249 SetCustomAttribute (ctor, cdata);
251 builder_extra.SetAlgorithmId (alg, a.Location);
257 if (a.Type == pa.AssemblyFlags) {
258 const int pos = 2; // skip CA header
259 uint flags = (uint) cdata[pos];
260 flags |= ((uint) cdata [pos + 1]) << 8;
261 flags |= ((uint) cdata [pos + 2]) << 16;
262 flags |= ((uint) cdata [pos + 3]) << 24;
264 // Ignore set PublicKey flag if assembly is not strongnamed
265 if ((flags & (uint) AssemblyNameFlags.PublicKey) != 0 && public_key == null)
266 flags &= ~(uint) AssemblyNameFlags.PublicKey;
268 if (Compiler.Settings.Target == Target.Module) {
269 SetCustomAttribute (ctor, cdata);
271 builder_extra.SetFlags (flags, a.Location);
277 if (a.Type == pa.TypeForwarder) {
278 TypeSpec t = a.GetArgumentType ();
279 if (t == null || TypeManager.HasElementType (t)) {
280 Report.Error (735, a.Location, "Invalid type specified as an argument for TypeForwardedTo attribute");
284 if (emitted_forwarders == null) {
285 emitted_forwarders = new Dictionary<ITypeDefinition, Attribute> ();
286 } else if (emitted_forwarders.ContainsKey (t.MemberDefinition)) {
287 Report.SymbolRelatedToPreviousError (emitted_forwarders[t.MemberDefinition].Location, null);
288 Report.Error (739, a.Location, "A duplicate type forward of type `{0}'",
289 TypeManager.CSharpName (t));
293 emitted_forwarders.Add (t.MemberDefinition, a);
295 if (t.MemberDefinition.DeclaringAssembly == this) {
296 Report.SymbolRelatedToPreviousError (t);
297 Report.Error (729, a.Location, "Cannot forward type `{0}' because it is defined in this assembly",
298 TypeManager.CSharpName (t));
303 Report.Error (730, a.Location, "Cannot forward type `{0}' because it is a nested type",
304 TypeManager.CSharpName (t));
308 builder_extra.AddTypeForwarder (t.GetDefinition (), a.Location);
312 if (a.Type == pa.Extension) {
313 a.Error_MisusedExtensionAttribute ();
317 if (a.Type == pa.InternalsVisibleTo) {
318 string assembly_name = a.GetString ();
319 if (assembly_name.Length == 0)
322 ParsedAssemblyName aname;
323 ParseAssemblyResult r = Fusion.ParseAssemblyName (assembly_name, out aname);
324 if (r != ParseAssemblyResult.OK) {
325 Report.Warning (1700, 3, a.Location, "Assembly reference `{0}' is invalid and cannot be resolved",
330 if (aname.Version != null || aname.Culture != null || aname.ProcessorArchitecture != ProcessorArchitecture.None) {
331 Report.Error (1725, a.Location,
332 "Friend assembly reference `{0}' is invalid. InternalsVisibleTo declarations cannot have a version, culture or processor architecture specified",
338 if (public_key != null && !aname.HasPublicKey) {
339 Report.Error (1726, a.Location,
340 "Friend assembly reference `{0}' is invalid. Strong named assemblies must specify a public key in their InternalsVisibleTo declarations",
345 } else if (a.Type == pa.RuntimeCompatibility) {
346 wrap_non_exception_throws_custom = true;
347 } else if (a.Type == pa.AssemblyFileVersion) {
348 string value = a.GetString ();
349 if (string.IsNullOrEmpty (value) || IsValidAssemblyVersion (value, false) == null) {
350 Report.Warning (1607, 1, a.Location, "The version number `{0}' specified for `{1}' is invalid",
357 SetCustomAttribute (ctor, cdata);
361 // When using assembly public key attributes InternalsVisibleTo key
362 // was not checked, we have to do it later when we actually know what
363 // our public key token is
365 void CheckReferencesPublicToken ()
367 // TODO: It should check only references assemblies but there is
368 // no working SRE API
369 foreach (var entry in Importer.Assemblies) {
370 var a = entry as ImportedAssemblyDefinition;
374 if (public_key != null && !a.HasStrongName) {
375 Report.Error (1577, "Referenced assembly `{0}' does not have a strong name",
379 var ci = a.Assembly.GetName ().CultureInfo;
380 if (!ci.Equals (System.Globalization.CultureInfo.InvariantCulture)) {
381 Report.Warning (1607, 1, "Referenced assembly `{0}' has different culture setting of `{1}'",
385 if (!a.IsFriendAssemblyTo (this))
388 var attr = a.GetAssemblyVisibleToName (this);
389 var atoken = attr.GetPublicKeyToken ();
391 if (ArrayComparer.IsEqual (GetPublicKeyToken (), atoken))
394 Report.SymbolRelatedToPreviousError (a.Location);
396 "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",
397 attr.FullName, FullName);
401 protected AssemblyName CreateAssemblyName ()
403 var an = new AssemblyName (name);
405 if (public_key != null && Compiler.Settings.Target != Target.Module) {
407 an.SetPublicKey (public_key);
409 if (public_key.Length == 16) {
410 Report.Error (1606, "Could not sign the assembly. ECMA key can only be used to delay-sign assemblies");
411 } else if (private_key == null) {
412 Error_AssemblySigning ("The specified key file does not have a private key");
414 an.KeyPair = private_key;
422 public virtual ModuleBuilder CreateModuleBuilder ()
424 if (file_name == null)
425 throw new NotSupportedException ("transient module in static assembly");
427 var module_name = Path.GetFileName (file_name);
429 // Always initialize module without symbolInfo. We could be framework dependent
430 // but returned ISymbolWriter does not have all what we need therefore some
431 // adaptor will be needed for now we alwayas emit MDB format when generating
433 return Builder.DefineDynamicModule (module_name, module_name, false);
436 public virtual void Emit ()
438 if (Compiler.Settings.Target == Target.Module) {
439 module_target_attrs = new AssemblyAttributesPlaceholder (module, name);
440 module_target_attrs.CreateContainer ();
441 module_target_attrs.DefineContainer ();
442 module_target_attrs.Define ();
443 module.AddCompilerGeneratedClass (module_target_attrs);
444 } else if (added_modules != null) {
445 ReadModulesAssemblyAttributes ();
448 if (Compiler.Settings.GenerateDebugInfo) {
449 symbol_writer = new MonoSymbolWriter (file_name);
451 // TODO: global variables
452 SymbolWriter.symwriter = symbol_writer;
455 module.EmitContainer ();
457 if (module.HasExtensionMethod) {
458 var pa = module.PredefinedAttributes.Extension;
460 SetCustomAttribute (pa.Constructor, AttributeEncoder.Empty);
464 if (!wrap_non_exception_throws_custom) {
465 PredefinedAttribute pa = module.PredefinedAttributes.RuntimeCompatibility;
466 if (pa.IsDefined && pa.ResolveBuilder ()) {
467 var prop = module.PredefinedMembers.RuntimeCompatibilityWrapNonExceptionThrows.Get ();
469 AttributeEncoder encoder = new AttributeEncoder ();
470 encoder.EncodeNamedPropertyArgument (prop, new BoolLiteral (Compiler.BuiltinTypes, true, Location.Null));
471 SetCustomAttribute (pa.Constructor, encoder.ToArray ());
476 if (declarative_security != null) {
478 foreach (var entry in declarative_security) {
479 Builder.__AddDeclarativeSecurity (entry);
482 throw new NotSupportedException ("Assembly-level security");
486 CheckReferencesPublicToken ();
491 public byte[] GetPublicKeyToken ()
493 if (public_key == null || public_key_token != null)
494 return public_key_token;
496 HashAlgorithm ha = SHA1.Create ();
497 byte[] hash = ha.ComputeHash (public_key);
498 // we need the last 8 bytes in reverse order
499 public_key_token = new byte[8];
500 Buffer.BlockCopy (hash, hash.Length - 8, public_key_token, 0, 8);
501 Array.Reverse (public_key_token, 0, 8);
502 return public_key_token;
506 // Either keyFile or keyContainer has to be non-null
508 void LoadPublicKey (string keyFile, string keyContainer)
510 if (keyContainer != null) {
512 private_key = new StrongNameKeyPair (keyContainer);
513 public_key = private_key.PublicKey;
515 Error_AssemblySigning ("The specified key container `" + keyContainer + "' does not exist");
521 bool key_file_exists = File.Exists (keyFile);
524 // For attribute based KeyFile do additional lookup
525 // in output assembly path
527 if (!key_file_exists && Compiler.Settings.StrongNameKeyFile == null) {
529 // The key file can be relative to output assembly
531 string test_path = Path.Combine (Path.GetDirectoryName (file_name), keyFile);
532 key_file_exists = File.Exists (test_path);
537 if (!key_file_exists) {
538 Error_AssemblySigning ("The specified key file `" + keyFile + "' does not exist");
542 using (FileStream fs = new FileStream (keyFile, FileMode.Open, FileAccess.Read)) {
543 byte[] snkeypair = new byte[fs.Length];
544 fs.Read (snkeypair, 0, snkeypair.Length);
546 // check for ECMA key
547 if (snkeypair.Length == 16) {
548 public_key = snkeypair;
553 // take it, with or without, a private key
554 RSA rsa = CryptoConvert.FromCapiKeyBlob (snkeypair);
555 // and make sure we only feed the public part to Sys.Ref
556 byte[] publickey = CryptoConvert.ToCapiPublicKeyBlob (rsa);
558 // AssemblyName.SetPublicKey requires an additional header
559 byte[] publicKeyHeader = new byte[8] { 0x00, 0x24, 0x00, 0x00, 0x04, 0x80, 0x00, 0x00 };
562 public_key = new byte[12 + publickey.Length];
563 Buffer.BlockCopy (publicKeyHeader, 0, public_key, 0, publicKeyHeader.Length);
565 // Length of Public Key (in bytes)
566 int lastPart = public_key.Length - 12;
567 public_key[8] = (byte) (lastPart & 0xFF);
568 public_key[9] = (byte) ((lastPart >> 8) & 0xFF);
569 public_key[10] = (byte) ((lastPart >> 16) & 0xFF);
570 public_key[11] = (byte) ((lastPart >> 24) & 0xFF);
572 Buffer.BlockCopy (publickey, 0, public_key, 12, publickey.Length);
574 Error_AssemblySigning ("The specified key file `" + keyFile + "' has incorrect format");
582 // TODO: Is there better way to test for a private key presence ?
583 CryptoConvert.FromCapiPrivateKeyBlob (snkeypair);
584 private_key = new StrongNameKeyPair (snkeypair);
589 void ReadModulesAssemblyAttributes ()
591 foreach (var m in added_modules) {
592 var cattrs = m.ReadAssemblyAttributes ();
596 module.OptAttributes.AddAttributes (cattrs);
600 public void Resolve ()
602 if (Compiler.Settings.Unsafe && module.PredefinedTypes.SecurityAction.Define ()) {
604 // Emits [assembly: SecurityPermissionAttribute (SecurityAction.RequestMinimum, SkipVerification = true)]
605 // when -unsafe option was specified
607 Location loc = Location.Null;
609 MemberAccess system_security_permissions = new MemberAccess (new MemberAccess (
610 new QualifiedAliasMember (QualifiedAliasMember.GlobalAlias, "System", loc), "Security", loc), "Permissions", loc);
612 var req_min = module.PredefinedMembers.SecurityActionRequestMinimum.Resolve (loc);
614 Arguments pos = new Arguments (1);
615 pos.Add (new Argument (req_min.GetConstant (null)));
617 Arguments named = new Arguments (1);
618 named.Add (new NamedArgument ("SkipVerification", loc, new BoolLiteral (Compiler.BuiltinTypes, true, loc)));
620 Attribute g = new Attribute ("assembly",
621 new MemberAccess (system_security_permissions, "SecurityPermissionAttribute"),
622 new Arguments[] { pos, named }, loc, false);
623 g.AttachTo (module, module);
624 var ctor = g.Resolve ();
626 g.ExtractSecurityPermissionSet (ctor, ref declarative_security);
630 if (module.OptAttributes == null)
633 // Ensure that we only have GlobalAttributes, since the Search isn't safe with other types.
634 if (!module.OptAttributes.CheckTargets())
637 cls_attribute = module.ResolveAssemblyAttribute (module.PredefinedAttributes.CLSCompliant);
639 if (cls_attribute != null) {
640 is_cls_compliant = cls_attribute.GetClsCompliantAttributeValue ();
643 if (added_modules != null && Compiler.Settings.VerifyClsCompliance && is_cls_compliant) {
644 foreach (var m in added_modules) {
645 if (!m.IsCLSCompliant) {
647 "Added modules must be marked with the CLSCompliant attribute to match the assembly",
653 Attribute a = module.ResolveAssemblyAttribute (module.PredefinedAttributes.RuntimeCompatibility);
655 var val = a.GetNamedValue ("WrapNonExceptionThrows") as BoolConstant;
657 wrap_non_exception_throws = val.Value;
661 protected void ResolveAssemblySecurityAttributes ()
663 string key_file = null;
664 string key_container = null;
666 if (module.OptAttributes != null) {
667 foreach (Attribute a in module.OptAttributes.Attrs) {
668 // cannot rely on any resolve-based members before you call Resolve
669 if (a.ExplicitTarget != "assembly")
672 // TODO: This code is buggy: comparing Attribute name without resolving is wrong.
673 // However, this is invoked by CodeGen.Init, when none of the namespaces
675 // TODO: Does not handle quoted attributes properly
677 case "AssemblyKeyFile":
678 case "AssemblyKeyFileAttribute":
679 case "System.Reflection.AssemblyKeyFileAttribute":
680 if (Compiler.Settings.StrongNameKeyFile != null) {
681 Report.SymbolRelatedToPreviousError (a.Location, a.GetSignatureForError ());
682 Report.Warning (1616, 1, "Option `{0}' overrides attribute `{1}' given in a source file or added module",
683 "keyfile", "System.Reflection.AssemblyKeyFileAttribute");
685 string value = a.GetString ();
686 if (!string.IsNullOrEmpty (value)) {
687 Error_ObsoleteSecurityAttribute (a, "keyfile");
692 case "AssemblyKeyName":
693 case "AssemblyKeyNameAttribute":
694 case "System.Reflection.AssemblyKeyNameAttribute":
695 if (Compiler.Settings.StrongNameKeyContainer != null) {
696 Report.SymbolRelatedToPreviousError (a.Location, a.GetSignatureForError ());
697 Report.Warning (1616, 1, "Option `{0}' overrides attribute `{1}' given in a source file or added module",
698 "keycontainer", "System.Reflection.AssemblyKeyNameAttribute");
700 string value = a.GetString ();
701 if (!string.IsNullOrEmpty (value)) {
702 Error_ObsoleteSecurityAttribute (a, "keycontainer");
703 key_container = value;
707 case "AssemblyDelaySign":
708 case "AssemblyDelaySignAttribute":
709 case "System.Reflection.AssemblyDelaySignAttribute":
710 bool b = a.GetBoolean ();
712 Error_ObsoleteSecurityAttribute (a, "delaysign");
721 // We came here only to report assembly attributes warnings
722 if (public_key != null)
726 // Load the strong key file found in attributes when no
727 // command line key was given
729 if (key_file != null || key_container != null) {
730 LoadPublicKey (key_file, key_container);
731 } else if (delay_sign) {
732 Report.Warning (1607, 1, "Delay signing was requested but no key file was given");
736 public void EmbedResources ()
739 // Add Win32 resources
741 if (Compiler.Settings.Win32ResourceFile != null) {
742 Builder.DefineUnmanagedResource (Compiler.Settings.Win32ResourceFile);
744 Builder.DefineVersionInfoResource ();
747 if (Compiler.Settings.Win32IconFile != null) {
748 builder_extra.DefineWin32IconResource (Compiler.Settings.Win32IconFile);
751 if (Compiler.Settings.Resources != null) {
752 if (Compiler.Settings.Target == Target.Module) {
753 Report.Error (1507, "Cannot link resource file when building a module");
756 foreach (var res in Compiler.Settings.Resources) {
757 if (!File.Exists (res.FileName)) {
758 Report.Error (1566, "Error reading resource file `{0}'", res.FileName);
764 if (counter++ < 10) {
765 stream = File.OpenRead (res.FileName);
767 // TODO: SRE API requires resource stream to be available during AssemblyBuilder::Save
768 // we workaround it by reading everything into memory to compile projects with
769 // many embedded resource (over 3500) references
770 stream = new MemoryStream (File.ReadAllBytes (res.FileName));
773 module.Builder.DefineManifestResource (res.Name, stream, res.Attributes);
775 Builder.AddResourceFile (res.Name, Path.GetFileName (res.FileName), res.Attributes);
784 PortableExecutableKinds pekind;
785 ImageFileMachine machine;
787 switch (Compiler.Settings.Platform) {
789 pekind = PortableExecutableKinds.Required32Bit | PortableExecutableKinds.ILOnly;
790 machine = ImageFileMachine.I386;
793 pekind = PortableExecutableKinds.ILOnly;
794 machine = ImageFileMachine.AMD64;
797 pekind = PortableExecutableKinds.ILOnly;
798 machine = ImageFileMachine.IA64;
800 case Platform.AnyCPU:
802 pekind = PortableExecutableKinds.ILOnly;
803 machine = ImageFileMachine.I386;
807 Compiler.TimeReporter.Start (TimeReporter.TimerType.OutputSave);
809 if (Compiler.Settings.Target == Target.Module) {
810 SaveModule (pekind, machine);
812 Builder.Save (module.Builder.ScopeName, pekind, machine);
814 } catch (Exception e) {
815 Report.Error (16, "Could not write to file `" + name + "', cause: " + e.Message);
817 Compiler.TimeReporter.Stop (TimeReporter.TimerType.OutputSave);
819 // Save debug symbols file
820 if (symbol_writer != null && Compiler.Report.Errors == 0) {
821 // TODO: it should run in parallel
822 Compiler.TimeReporter.Start (TimeReporter.TimerType.DebugSave);
823 symbol_writer.WriteSymbolFile (SymbolWriter.GetGuid (module.Builder));
824 Compiler.TimeReporter.Stop (TimeReporter.TimerType.DebugSave);
828 protected virtual void SaveModule (PortableExecutableKinds pekind, ImageFileMachine machine)
830 Report.RuntimeMissingSupport (Location.Null, "-target:module");
833 void SetCustomAttribute (MethodSpec ctor, byte[] data)
835 if (module_target_attrs != null)
836 module_target_attrs.AddAssemblyAttribute (ctor, data);
838 Builder.SetCustomAttribute ((ConstructorInfo) ctor.GetMetaInfo (), data);
841 void SetEntryPoint ()
843 if (!Compiler.Settings.NeedsEntryPoint) {
844 if (Compiler.Settings.MainClass != null)
845 Report.Error (2017, "Cannot specify -main if building a module or library");
850 PEFileKinds file_kind;
852 switch (Compiler.Settings.Target) {
855 file_kind = PEFileKinds.Dll;
858 file_kind = PEFileKinds.WindowApplication;
861 file_kind = PEFileKinds.ConsoleApplication;
865 if (entry_point == null) {
866 string main_class = Compiler.Settings.MainClass;
867 if (main_class != null) {
868 // TODO: Handle dotted names
869 var texpr = module.GlobalRootNamespace.LookupType (module, main_class, 0, LookupMode.Probing, Location.Null);
871 Report.Error (1555, "Could not find `{0}' specified for Main method", main_class);
875 var mtype = texpr.Type.MemberDefinition as ClassOrStruct;
877 Report.Error (1556, "`{0}' specified for Main method must be a valid class or struct", main_class);
881 Report.Error (1558, mtype.Location, "`{0}' does not have a suitable static Main method", mtype.GetSignatureForError ());
883 string pname = file_name == null ? name : Path.GetFileName (file_name);
884 Report.Error (5001, "Program `{0}' does not contain a static `Main' method suitable for an entry point",
891 Builder.SetEntryPoint (entry_point.MethodBuilder, file_kind);
894 void Error_ObsoleteSecurityAttribute (Attribute a, string option)
896 Report.Warning (1699, 1, a.Location,
897 "Use compiler option `{0}' or appropriate project settings instead of `{1}' attribute",
901 void Error_AssemblySigning (string text)
903 Report.Error (1548, "Error during assembly signing. " + text);
906 public bool IsFriendAssemblyTo (IAssemblyDefinition assembly)
911 static Version IsValidAssemblyVersion (string version, bool allowGenerated)
913 string[] parts = version.Split ('.');
914 if (parts.Length < 1 || parts.Length > 4)
917 var values = new int[4];
918 for (int i = 0; i < parts.Length; ++i) {
919 if (!int.TryParse (parts[i], out values[i])) {
920 if (parts[i].Length == 1 && parts[i][0] == '*' && allowGenerated) {
922 // Nothing can follow *
923 if (parts.Length > 3)
926 // Generate Build value based on days since 1/1/2000
927 TimeSpan days = DateTime.Today - new DateTime (2000, 1, 1);
928 values[i] = System.Math.Max (days.Days, 0);
933 // Generate Revision value based on every other second today
934 var seconds = DateTime.Now - DateTime.Today;
935 values[i] = (int) seconds.TotalSeconds / 2;
943 if (values[i] > ushort.MaxValue)
947 return new Version (values[0], values[1], values[2], values[3]);
951 public class AssemblyResource : IEquatable<AssemblyResource>
953 public AssemblyResource (string fileName, string name)
954 : this (fileName, name, false)
958 public AssemblyResource (string fileName, string name, bool isPrivate)
962 Attributes = isPrivate ? ResourceAttributes.Private : ResourceAttributes.Public;
965 public ResourceAttributes Attributes { get; private set; }
966 public string Name { get; private set; }
967 public string FileName { get; private set; }
968 public bool IsEmbeded { get; set; }
970 #region IEquatable<AssemblyResource> Members
972 public bool Equals (AssemblyResource other)
974 return Name == other.Name;
981 // A placeholder class for assembly attributes when emitting module
983 class AssemblyAttributesPlaceholder : CompilerGeneratedClass
985 static readonly string TypeNamePrefix = "<$AssemblyAttributes${0}>";
986 public static readonly string AssemblyFieldName = "attributes";
990 public AssemblyAttributesPlaceholder (ModuleContainer parent, string outputName)
991 : base (parent, new MemberName (GetGeneratedName (outputName)), Modifiers.STATIC)
993 assembly = new Field (this, new TypeExpression (parent.Compiler.BuiltinTypes.Object, Location), Modifiers.PUBLIC | Modifiers.STATIC,
994 new MemberName (AssemblyFieldName), null);
999 public void AddAssemblyAttribute (MethodSpec ctor, byte[] data)
1001 assembly.SetCustomAttribute (ctor, data);
1004 public static string GetGeneratedName (string outputName)
1006 return string.Format (TypeNamePrefix, outputName);
1011 // Extension to System.Reflection.Emit.AssemblyBuilder to have fully compatible
1012 // compiler. This is a default implementation for framework System.Reflection.Emit
1013 // which does not implement any of the methods
1015 public class AssemblyBuilderExtension
1017 readonly CompilerContext ctx;
1019 public AssemblyBuilderExtension (CompilerContext ctx)
1024 public virtual System.Reflection.Module AddModule (string module)
1026 ctx.Report.RuntimeMissingSupport (Location.Null, "-addmodule");
1030 public virtual void AddPermissionRequests (PermissionSet[] permissions)
1032 ctx.Report.RuntimeMissingSupport (Location.Null, "assembly declarative security");
1035 public virtual void AddTypeForwarder (TypeSpec type, Location loc)
1037 ctx.Report.RuntimeMissingSupport (loc, "TypeForwardedToAttribute");
1040 public virtual void DefineWin32IconResource (string fileName)
1042 ctx.Report.RuntimeMissingSupport (Location.Null, "-win32icon");
1045 public virtual void SetAlgorithmId (uint value, Location loc)
1047 ctx.Report.RuntimeMissingSupport (loc, "AssemblyAlgorithmIdAttribute");
1050 public virtual void SetCulture (string culture, Location loc)
1052 ctx.Report.RuntimeMissingSupport (loc, "AssemblyCultureAttribute");
1055 public virtual void SetFlags (uint flags, Location loc)
1057 ctx.Report.RuntimeMissingSupport (loc, "AssemblyFlagsAttribute");
1060 public virtual void SetVersion (Version version, Location loc)
1062 ctx.Report.RuntimeMissingSupport (loc, "AssemblyVersionAttribute");
1066 abstract class AssemblyReferencesLoader<T>
1068 protected readonly CompilerContext compiler;
1070 protected readonly List<string> paths;
1072 public AssemblyReferencesLoader (CompilerContext compiler)
1074 this.compiler = compiler;
1076 paths = new List<string> ();
1077 paths.AddRange (compiler.Settings.ReferencesLookupPaths);
1078 paths.Add (Directory.GetCurrentDirectory ());
1081 public abstract bool HasObjectType (T assembly);
1082 protected abstract string[] GetDefaultReferences ();
1083 public abstract T LoadAssemblyFile (string fileName, bool isImplicitReference);
1084 public abstract void LoadReferences (ModuleContainer module);
1086 protected void Error_FileNotFound (string fileName)
1088 compiler.Report.Error (6, "Metadata file `{0}' could not be found", fileName);
1091 protected void Error_FileCorrupted (string fileName)
1093 compiler.Report.Error (9, "Metadata file `{0}' does not contain valid metadata", fileName);
1096 protected void Error_AssemblyIsModule (string fileName)
1098 compiler.Report.Error (1509,
1099 "Referenced assembly file `{0}' is a module. Consider using `-addmodule' option to add the module",
1103 protected void Error_ModuleIsAssembly (string fileName)
1105 compiler.Report.Error (1542,
1106 "Added module file `{0}' is an assembly. Consider using `-r' option to reference the file",
1110 protected void LoadReferencesCore (ModuleContainer module, out T corlib_assembly, out List<Tuple<RootNamespace, T>> loaded)
1112 compiler.TimeReporter.Start (TimeReporter.TimerType.ReferencesLoading);
1114 loaded = new List<Tuple<RootNamespace, T>> ();
1117 // Load mscorlib.dll as the first
1119 if (module.Compiler.Settings.StdLib) {
1120 corlib_assembly = LoadAssemblyFile ("mscorlib.dll", true);
1122 corlib_assembly = default (T);
1126 foreach (string r in module.Compiler.Settings.AssemblyReferences) {
1127 a = LoadAssemblyFile (r, false);
1128 if (a == null || EqualityComparer<T>.Default.Equals (a, corlib_assembly))
1131 var key = Tuple.Create (module.GlobalRootNamespace, a);
1132 if (loaded.Contains (key))
1135 // A corlib assembly is the first assembly which contains System.Object
1136 if (corlib_assembly == null && HasObjectType (a)) {
1137 corlib_assembly = a;
1144 foreach (var entry in module.Compiler.Settings.AssemblyReferencesAliases) {
1145 a = LoadAssemblyFile (entry.Item2, false);
1149 var key = Tuple.Create (module.CreateRootNamespace (entry.Item1), a);
1150 if (loaded.Contains (key))
1156 if (compiler.Settings.LoadDefaultReferences) {
1157 foreach (string r in GetDefaultReferences ()) {
1158 a = LoadAssemblyFile (r, true);
1162 var key = Tuple.Create (module.GlobalRootNamespace, a);
1163 if (loaded.Contains (key))
1170 compiler.TimeReporter.Stop (TimeReporter.TimerType.ReferencesLoading);