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 Novell, Inc.
15 using System.Collections.Generic;
16 using System.Globalization;
17 using System.Security;
18 using System.Security.Cryptography;
19 using System.Security.Permissions;
20 using Mono.Security.Cryptography;
21 using Mono.CompilerServices.SymbolWriter;
24 using IKVM.Reflection;
25 using IKVM.Reflection.Emit;
26 using SecurityType = System.Collections.Generic.List<IKVM.Reflection.Emit.CustomAttributeBuilder>;
28 using SecurityType = System.Collections.Generic.Dictionary<System.Security.Permissions.SecurityAction, System.Security.PermissionSet>;
29 using System.Reflection;
30 using System.Reflection.Emit;
35 public interface IAssemblyDefinition
37 string FullName { get; }
38 bool HasExtensionMethod { 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 MonoSymbolWriter symbol_writer;
54 bool is_cls_compliant;
55 bool wrap_non_exception_throws;
56 bool wrap_non_exception_throws_custom;
58 protected ModuleContainer module;
60 protected readonly string file_name;
62 byte[] public_key, public_key_token;
65 // Holds private/public key pair when private key
67 StrongNameKeyPair private_key;
69 Attribute cls_attribute;
72 protected List<ImportedModuleDefinition> added_modules;
73 SecurityType declarative_security;
74 Dictionary<ITypeDefinition, Attribute> emitted_forwarders;
75 AssemblyAttributesPlaceholder module_target_attrs;
77 protected AssemblyDefinition (ModuleContainer module, string name)
80 this.name = Path.GetFileNameWithoutExtension (name);
82 wrap_non_exception_throws = true;
84 delay_sign = RootContext.StrongNameDelaySign;
87 // Load strong name key early enough for assembly importer to be able to
88 // use the keys for InternalsVisibleTo
89 // This should go somewhere close to ReferencesLoading but don't have the place yet
91 if (RootContext.StrongNameKeyFile != null || RootContext.StrongNameKeyContainer != null) {
92 LoadPublicKey (RootContext.StrongNameKeyFile, RootContext.StrongNameKeyContainer);
96 protected AssemblyDefinition (ModuleContainer module, string name, string fileName)
99 this.file_name = fileName;
104 public Attribute CLSCompliantAttribute {
106 return cls_attribute;
110 public CompilerContext Compiler {
112 return module.Compiler;
117 // Assembly entry point, aka Main method
119 public Method EntryPoint {
128 public string FullName {
130 return Builder.FullName;
134 public bool HasExtensionMethod {
136 return module.HasExtensionMethod;
140 public bool HasCLSCompliantAttribute {
142 return cls_attribute != null;
146 // TODO: This should not exist here but will require more changes
147 public MetadataImporter Importer {
151 public bool IsCLSCompliant {
153 return is_cls_compliant;
157 bool IAssemblyDefinition.IsMissing {
169 public bool WrapNonExceptionThrows {
171 return wrap_non_exception_throws;
175 protected Report Report {
177 return Compiler.Report;
183 public void AddModule (ImportedModuleDefinition module)
185 if (added_modules == null) {
186 added_modules = new List<ImportedModuleDefinition> ();
187 added_modules.Add (module);
191 public void ApplyAttributeBuilder (Attribute a, MethodSpec ctor, byte[] cdata, PredefinedAttributes pa)
193 if (a.IsValidSecurityAttribute ()) {
194 a.ExtractSecurityPermissionSet (ctor, ref declarative_security);
198 if (a.Type == pa.AssemblyCulture) {
199 string value = a.GetString ();
200 if (value == null || value.Length == 0)
203 if (RootContext.Target == Target.Exe) {
204 a.Error_AttributeEmitError ("The executables cannot be satelite assemblies, remove the attribute or keep it empty");
208 if (value == "neutral")
211 if (RootContext.Target == Target.Module) {
212 SetCustomAttribute (ctor, cdata);
214 builder_extra.SetCulture (value, a.Location);
220 if (a.Type == pa.AssemblyVersion) {
221 string value = a.GetString ();
222 if (value == null || value.Length == 0)
225 var vinfo = IsValidAssemblyVersion (value, true);
227 a.Error_AttributeEmitError (string.Format ("Specified version `{0}' is not valid", value));
231 if (RootContext.Target == Target.Module) {
232 SetCustomAttribute (ctor, cdata);
234 builder_extra.SetVersion (vinfo, a.Location);
240 if (a.Type == pa.AssemblyAlgorithmId) {
241 const int pos = 2; // skip CA header
242 uint alg = (uint) cdata [pos];
243 alg |= ((uint) cdata [pos + 1]) << 8;
244 alg |= ((uint) cdata [pos + 2]) << 16;
245 alg |= ((uint) cdata [pos + 3]) << 24;
247 if (RootContext.Target == Target.Module) {
248 SetCustomAttribute (ctor, cdata);
250 builder_extra.SetAlgorithmId (alg, a.Location);
256 if (a.Type == pa.AssemblyFlags) {
257 const int pos = 2; // skip CA header
258 uint flags = (uint) cdata[pos];
259 flags |= ((uint) cdata [pos + 1]) << 8;
260 flags |= ((uint) cdata [pos + 2]) << 16;
261 flags |= ((uint) cdata [pos + 3]) << 24;
263 // Ignore set PublicKey flag if assembly is not strongnamed
264 if ((flags & (uint) AssemblyNameFlags.PublicKey) != 0 && public_key == null)
265 flags &= ~(uint) AssemblyNameFlags.PublicKey;
267 if (RootContext.Target == Target.Module) {
268 SetCustomAttribute (ctor, cdata);
270 builder_extra.SetFlags (flags, a.Location);
276 if (a.Type == pa.TypeForwarder) {
277 TypeSpec t = a.GetArgumentType ();
278 if (t == null || TypeManager.HasElementType (t)) {
279 Report.Error (735, a.Location, "Invalid type specified as an argument for TypeForwardedTo attribute");
283 if (emitted_forwarders == null) {
284 emitted_forwarders = new Dictionary<ITypeDefinition, Attribute> ();
285 } else if (emitted_forwarders.ContainsKey (t.MemberDefinition)) {
286 Report.SymbolRelatedToPreviousError (emitted_forwarders[t.MemberDefinition].Location, null);
287 Report.Error (739, a.Location, "A duplicate type forward of type `{0}'",
288 TypeManager.CSharpName (t));
292 emitted_forwarders.Add (t.MemberDefinition, a);
294 if (t.MemberDefinition.DeclaringAssembly == this) {
295 Report.SymbolRelatedToPreviousError (t);
296 Report.Error (729, a.Location, "Cannot forward type `{0}' because it is defined in this assembly",
297 TypeManager.CSharpName (t));
302 Report.Error (730, a.Location, "Cannot forward type `{0}' because it is a nested type",
303 TypeManager.CSharpName (t));
307 builder_extra.AddTypeForwarder (t.GetDefinition (), a.Location);
311 if (a.Type == pa.Extension) {
312 a.Error_MisusedExtensionAttribute ();
316 if (a.Type == pa.InternalsVisibleTo) {
317 string assembly_name = a.GetString ();
318 if (assembly_name.Length == 0)
321 AssemblyName aname = null;
323 aname = new AssemblyName (assembly_name);
324 } catch (Exception) {
325 Report.Warning (1700, 3, a.Location, "Assembly reference `{0}' is invalid and cannot be resolved",
330 if (aname.Version != null || aname.CultureInfo != 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 // TODO: GetPublicKey () does not work on .NET when AssemblyName is constructed from a string
339 if (public_key != null && aname.GetPublicKey () == null) {
340 Report.Error (1726, a.Location,
341 "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 if (!a.IsFriendAssemblyTo (this))
382 var attr = a.GetAssemblyVisibleToName (this);
383 var atoken = attr.GetPublicKeyToken ();
385 if (ArrayComparer.IsEqual (GetPublicKeyToken (), atoken))
389 "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",
390 attr.FullName, FullName);
394 protected AssemblyName CreateAssemblyName ()
396 var an = new AssemblyName (name);
398 if (public_key != null && RootContext.Target != Target.Module) {
400 an.SetPublicKey (public_key);
402 if (public_key.Length == 16) {
403 Report.Error (1606, "Could not sign the assembly. ECMA key can only be used to delay-sign assemblies");
404 } else if (private_key == null) {
405 Error_AssemblySigning ("The specified key file does not have a private key");
407 an.KeyPair = private_key;
415 public virtual ModuleBuilder CreateModuleBuilder ()
417 if (file_name == null)
418 throw new NotSupportedException ("transient module in static assembly");
420 var module_name = Path.GetFileName (file_name);
422 // Always initialize module without symbolInfo. We could be framework dependent
423 // but returned ISymbolWriter does not have all what we need therefore some
424 // adaptor will be needed for now we alwayas emit MDB format when generating
426 return Builder.DefineDynamicModule (module_name, module_name, false);
429 public virtual void Emit ()
431 if (RootContext.Target == Target.Module) {
432 module_target_attrs = new AssemblyAttributesPlaceholder (module, name);
433 module_target_attrs.CreateType ();
434 module_target_attrs.DefineType ();
435 module_target_attrs.Define ();
436 module.AddCompilerGeneratedClass (module_target_attrs);
437 } else if (added_modules != null) {
438 ReadModulesAssemblyAttributes ();
441 if (RootContext.GenerateDebugInfo) {
442 symbol_writer = new MonoSymbolWriter (file_name);
444 // TODO: global variables
445 Location.DefineSymbolDocuments (symbol_writer);
446 SymbolWriter.symwriter = symbol_writer;
451 if (module.HasExtensionMethod) {
452 var pa = module.PredefinedAttributes.Extension;
454 SetCustomAttribute (pa.Constructor, AttributeEncoder.Empty);
458 if (!wrap_non_exception_throws_custom) {
459 PredefinedAttribute pa = module.PredefinedAttributes.RuntimeCompatibility;
460 if (pa.IsDefined && pa.ResolveBuilder ()) {
461 var prop = pa.GetProperty ("WrapNonExceptionThrows", TypeManager.bool_type, Location.Null);
463 AttributeEncoder encoder = new AttributeEncoder ();
464 encoder.EncodeNamedPropertyArgument (prop, new BoolLiteral (true, Location.Null));
465 SetCustomAttribute (pa.Constructor, encoder.ToArray ());
470 if (declarative_security != null) {
472 foreach (var entry in declarative_security) {
473 Builder.__AddDeclarativeSecurity (entry);
476 var args = new PermissionSet[3];
477 declarative_security.TryGetValue (SecurityAction.RequestMinimum, out args[0]);
478 declarative_security.TryGetValue (SecurityAction.RequestOptional, out args[1]);
479 declarative_security.TryGetValue (SecurityAction.RequestRefuse, out args[2]);
480 builder_extra.AddPermissionRequests (args);
484 CheckReferencesPublicToken ();
489 public byte[] GetPublicKeyToken ()
491 if (public_key == null || public_key_token != null)
492 return public_key_token;
494 HashAlgorithm ha = SHA1.Create ();
495 byte[] hash = ha.ComputeHash (public_key);
496 // we need the last 8 bytes in reverse order
497 public_key_token = new byte[8];
498 Buffer.BlockCopy (hash, hash.Length - 8, public_key_token, 0, 8);
499 Array.Reverse (public_key_token, 0, 8);
500 return public_key_token;
504 // Either keyFile or keyContainer has to be non-null
506 void LoadPublicKey (string keyFile, string keyContainer)
508 if (keyContainer != null) {
510 private_key = new StrongNameKeyPair (keyContainer);
511 public_key = private_key.PublicKey;
513 Error_AssemblySigning ("The specified key container `" + keyContainer + "' does not exist");
519 bool key_file_exists = File.Exists (keyFile);
522 // For attribute based KeyFile do additional lookup
523 // in output assembly path
525 if (!key_file_exists && RootContext.StrongNameKeyFile == null) {
527 // The key file can be relative to output assembly
529 string test_path = Path.Combine (Path.GetDirectoryName (file_name), keyFile);
530 key_file_exists = File.Exists (test_path);
535 if (!key_file_exists) {
536 Error_AssemblySigning ("The specified key file `" + keyFile + "' does not exist");
540 using (FileStream fs = new FileStream (keyFile, FileMode.Open, FileAccess.Read)) {
541 byte[] snkeypair = new byte[fs.Length];
542 fs.Read (snkeypair, 0, snkeypair.Length);
544 // check for ECMA key
545 if (snkeypair.Length == 16) {
546 public_key = snkeypair;
551 // take it, with or without, a private key
552 RSA rsa = CryptoConvert.FromCapiKeyBlob (snkeypair);
553 // and make sure we only feed the public part to Sys.Ref
554 byte[] publickey = CryptoConvert.ToCapiPublicKeyBlob (rsa);
556 // AssemblyName.SetPublicKey requires an additional header
557 byte[] publicKeyHeader = new byte[8] { 0x00, 0x24, 0x00, 0x00, 0x04, 0x80, 0x00, 0x00 };
560 public_key = new byte[12 + publickey.Length];
561 Buffer.BlockCopy (publicKeyHeader, 0, public_key, 0, publicKeyHeader.Length);
563 // Length of Public Key (in bytes)
564 int lastPart = public_key.Length - 12;
565 public_key[8] = (byte) (lastPart & 0xFF);
566 public_key[9] = (byte) ((lastPart >> 8) & 0xFF);
567 public_key[10] = (byte) ((lastPart >> 16) & 0xFF);
568 public_key[11] = (byte) ((lastPart >> 24) & 0xFF);
570 Buffer.BlockCopy (publickey, 0, public_key, 12, publickey.Length);
572 Error_AssemblySigning ("The specified key file `" + keyFile + "' has incorrect format");
580 // TODO: Is there better way to test for a private key presence ?
581 CryptoConvert.FromCapiPrivateKeyBlob (snkeypair);
582 private_key = new StrongNameKeyPair (snkeypair);
587 void ReadModulesAssemblyAttributes ()
589 foreach (var m in added_modules) {
590 var cattrs = m.ReadAssemblyAttributes ();
594 module.OptAttributes.AddAttributes (cattrs);
598 public void Resolve ()
600 if (RootContext.Unsafe && module.PredefinedTypes.SecurityAction.Define ()) {
602 // Emits [assembly: SecurityPermissionAttribute (SecurityAction.RequestMinimum, SkipVerification = true)]
603 // when -unsafe option was specified
605 Location loc = Location.Null;
607 MemberAccess system_security_permissions = new MemberAccess (new MemberAccess (
608 new QualifiedAliasMember (QualifiedAliasMember.GlobalAlias, "System", loc), "Security", loc), "Permissions", loc);
610 var req_min = (ConstSpec) module.PredefinedTypes.SecurityAction.GetField ("RequestMinimum", module.PredefinedTypes.SecurityAction.TypeSpec, loc);
612 Arguments pos = new Arguments (1);
613 pos.Add (new Argument (req_min.GetConstant (null)));
615 Arguments named = new Arguments (1);
616 named.Add (new NamedArgument ("SkipVerification", loc, new BoolLiteral (true, loc)));
618 GlobalAttribute g = new GlobalAttribute (new NamespaceEntry (module, null, null, null), "assembly",
619 new MemberAccess (system_security_permissions, "SecurityPermissionAttribute"),
620 new Arguments[] { pos, named }, loc, false);
621 g.AttachTo (module, module);
622 var ctor = g.Resolve ();
624 g.ExtractSecurityPermissionSet (ctor, ref declarative_security);
628 if (module.OptAttributes == null)
631 // Ensure that we only have GlobalAttributes, since the Search isn't safe with other types.
632 if (!module.OptAttributes.CheckTargets())
635 cls_attribute = module.ResolveAssemblyAttribute (module.PredefinedAttributes.CLSCompliant);
637 if (cls_attribute != null) {
638 is_cls_compliant = cls_attribute.GetClsCompliantAttributeValue ();
641 if (added_modules != null && RootContext.VerifyClsCompliance && is_cls_compliant) {
642 foreach (var m in added_modules) {
643 if (!m.IsCLSCompliant) {
645 "Added modules must be marked with the CLSCompliant attribute to match the assembly",
651 Attribute a = module.ResolveAssemblyAttribute (module.PredefinedAttributes.RuntimeCompatibility);
653 var val = a.GetNamedValue ("WrapNonExceptionThrows") as BoolConstant;
655 wrap_non_exception_throws = val.Value;
659 protected void ResolveAssemblySecurityAttributes ()
661 string key_file = null;
662 string key_container = null;
664 if (module.OptAttributes != null) {
665 foreach (Attribute a in module.OptAttributes.Attrs) {
666 // cannot rely on any resolve-based members before you call Resolve
667 if (a.ExplicitTarget != "assembly")
670 // TODO: This code is buggy: comparing Attribute name without resolving is wrong.
671 // However, this is invoked by CodeGen.Init, when none of the namespaces
673 // TODO: Does not handle quoted attributes properly
675 case "AssemblyKeyFile":
676 case "AssemblyKeyFileAttribute":
677 case "System.Reflection.AssemblyKeyFileAttribute":
678 if (RootContext.StrongNameKeyFile != null) {
679 Report.SymbolRelatedToPreviousError (a.Location, a.GetSignatureForError ());
680 Report.Warning (1616, 1, "Option `{0}' overrides attribute `{1}' given in a source file or added module",
681 "keyfile", "System.Reflection.AssemblyKeyFileAttribute");
683 string value = a.GetString ();
684 if (!string.IsNullOrEmpty (value)) {
685 Error_ObsoleteSecurityAttribute (a, "keyfile");
690 case "AssemblyKeyName":
691 case "AssemblyKeyNameAttribute":
692 case "System.Reflection.AssemblyKeyNameAttribute":
693 if (RootContext.StrongNameKeyContainer != null) {
694 Report.SymbolRelatedToPreviousError (a.Location, a.GetSignatureForError ());
695 Report.Warning (1616, 1, "Option `{0}' overrides attribute `{1}' given in a source file or added module",
696 "keycontainer", "System.Reflection.AssemblyKeyNameAttribute");
698 string value = a.GetString ();
699 if (!string.IsNullOrEmpty (value)) {
700 Error_ObsoleteSecurityAttribute (a, "keycontainer");
701 key_container = value;
705 case "AssemblyDelaySign":
706 case "AssemblyDelaySignAttribute":
707 case "System.Reflection.AssemblyDelaySignAttribute":
708 bool b = a.GetBoolean ();
710 Error_ObsoleteSecurityAttribute (a, "delaysign");
719 // We came here only to report assembly attributes warnings
720 if (public_key != null)
724 // Load the strong key file found in attributes when no
725 // command line key was given
727 if (key_file != null || key_container != null) {
728 LoadPublicKey (key_file, key_container);
729 } else if (delay_sign) {
730 Report.Warning (1607, 1, "Delay signing was requested but no key file was given");
734 public void EmbedResources ()
737 // Add Win32 resources
739 if (RootContext.Win32ResourceFile != null) {
740 Builder.DefineUnmanagedResource (RootContext.Win32ResourceFile);
742 Builder.DefineVersionInfoResource ();
745 if (RootContext.Win32IconFile != null) {
746 builder_extra.DefineWin32IconResource (RootContext.Win32IconFile);
749 if (RootContext.Resources != null) {
750 if (RootContext.Target == Target.Module) {
751 Report.Error (1507, "Cannot link resource file when building a module");
754 foreach (var res in RootContext.Resources) {
755 if (!File.Exists (res.FileName)) {
756 Report.Error (1566, "Error reading resource file `{0}'", res.FileName);
762 if (counter++ < 10) {
763 stream = File.OpenRead (res.FileName);
765 // TODO: SRE API requires resource stream to be available during AssemblyBuilder::Save
766 // we workaround it by reading everything into memory to compile projects with
767 // many embedded resource (over 3500) references
768 stream = new MemoryStream (File.ReadAllBytes (res.FileName));
771 module.Builder.DefineManifestResource (res.Name, stream, res.Attributes);
773 Builder.AddResourceFile (res.Name, Path.GetFileName (res.FileName), res.Attributes);
782 PortableExecutableKinds pekind;
783 ImageFileMachine machine;
785 switch (RootContext.Platform) {
787 pekind = PortableExecutableKinds.Required32Bit | PortableExecutableKinds.ILOnly;
788 machine = ImageFileMachine.I386;
791 pekind = PortableExecutableKinds.ILOnly;
792 machine = ImageFileMachine.AMD64;
795 pekind = PortableExecutableKinds.ILOnly;
796 machine = ImageFileMachine.IA64;
798 case Platform.AnyCPU:
800 pekind = PortableExecutableKinds.ILOnly;
801 machine = ImageFileMachine.I386;
805 Compiler.TimeReporter.Start (TimeReporter.TimerType.OutputSave);
807 if (RootContext.Target == Target.Module) {
808 SaveModule (pekind, machine);
810 Builder.Save (module.Builder.ScopeName, pekind, machine);
812 } catch (Exception e) {
813 Report.Error (16, "Could not write to file `" + name + "', cause: " + e.Message);
815 Compiler.TimeReporter.Stop (TimeReporter.TimerType.OutputSave);
817 // Save debug symbols file
818 if (symbol_writer != null) {
819 // TODO: it should run in parallel
820 Compiler.TimeReporter.Start (TimeReporter.TimerType.DebugSave);
821 symbol_writer.WriteSymbolFile (SymbolWriter.GetGuid (module.Builder));
822 Compiler.TimeReporter.Stop (TimeReporter.TimerType.DebugSave);
826 protected virtual void SaveModule (PortableExecutableKinds pekind, ImageFileMachine machine)
828 Report.RuntimeMissingSupport (Location.Null, "-target:module");
831 void SetCustomAttribute (MethodSpec ctor, byte[] data)
833 if (module_target_attrs != null)
834 module_target_attrs.AddAssemblyAttribute (ctor, data);
836 Builder.SetCustomAttribute ((ConstructorInfo) ctor.GetMetaInfo (), data);
839 void SetEntryPoint ()
841 if (!RootContext.NeedsEntryPoint) {
842 if (RootContext.MainClass != null)
843 Report.Error (2017, "Cannot specify -main if building a module or library");
848 PEFileKinds file_kind;
850 switch (RootContext.Target) {
853 file_kind = PEFileKinds.Dll;
856 file_kind = PEFileKinds.WindowApplication;
859 file_kind = PEFileKinds.ConsoleApplication;
863 if (entry_point == null) {
864 if (RootContext.MainClass != null) {
865 // TODO: Should use MemberCache
866 DeclSpace main_cont = module.GetDefinition (RootContext.MainClass) as DeclSpace;
867 if (main_cont == null) {
868 Report.Error (1555, "Could not find `{0}' specified for Main method", RootContext.MainClass);
872 if (!(main_cont is ClassOrStruct)) {
873 Report.Error (1556, "`{0}' specified for Main method must be a valid class or struct", RootContext.MainClass);
877 Report.Error (1558, main_cont.Location, "`{0}' does not have a suitable static Main method", main_cont.GetSignatureForError ());
881 if (Report.Errors == 0) {
882 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 (TypeManager.object_type, 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;
1071 readonly string[] default_references;
1073 public AssemblyReferencesLoader (CompilerContext compiler)
1075 this.compiler = compiler;
1077 if (RootContext.LoadDefaultReferences)
1078 default_references = GetDefaultReferences ();
1080 default_references = new string[0];
1082 paths = new List<string> ();
1083 paths.AddRange (RootContext.ReferencesLookupPaths);
1084 paths.Add (Directory.GetCurrentDirectory ());
1087 public abstract bool HasObjectType (T assembly);
1088 protected abstract string[] GetDefaultReferences ();
1089 public abstract T LoadAssemblyFile (string fileName);
1090 public abstract T LoadAssemblyDefault (string assembly);
1091 public abstract void LoadReferences (ModuleContainer module);
1093 protected void Error_FileNotFound (string fileName)
1095 compiler.Report.Error (6, "Metadata file `{0}' could not be found", fileName);
1098 protected void Error_FileCorrupted (string fileName)
1100 compiler.Report.Error (9, "Metadata file `{0}' does not contain valid metadata", fileName);
1103 protected void Error_AssemblyIsModule (string fileName)
1105 compiler.Report.Error (1509,
1106 "Referenced assembly file `{0}' is a module. Consider using `-addmodule' option to add the module",
1110 protected void Error_ModuleIsAssembly (string fileName)
1112 compiler.Report.Error (1542,
1113 "Added module file `{0}' is an assembly. Consider using `-r' option to reference the file",
1117 protected void LoadReferencesCore (ModuleContainer module, out T corlib_assembly, out List<Tuple<RootNamespace, T>> loaded)
1119 compiler.TimeReporter.Start (TimeReporter.TimerType.ReferencesLoading);
1121 loaded = new List<Tuple<RootNamespace, T>> ();
1124 // Load mscorlib.dll as the first
1126 if (RootContext.StdLib) {
1127 corlib_assembly = LoadAssemblyDefault ("mscorlib.dll");
1129 corlib_assembly = default (T);
1133 foreach (string r in default_references) {
1134 a = LoadAssemblyDefault (r);
1136 loaded.Add (Tuple.Create (module.GlobalRootNamespace, a));
1139 foreach (string r in RootContext.AssemblyReferences) {
1140 a = LoadAssemblyFile (r);
1141 if (a == null || EqualityComparer<T>.Default.Equals (a, corlib_assembly))
1144 var key = Tuple.Create (module.GlobalRootNamespace, a);
1145 if (loaded.Contains (key))
1148 // A corlib assembly is the first assembly which contains System.Object
1149 if (corlib_assembly == null && HasObjectType (a)) {
1150 corlib_assembly = a;
1157 foreach (var entry in RootContext.AssemblyReferencesAliases) {
1158 a = LoadAssemblyFile (entry.Item2);
1162 var key = Tuple.Create (module.CreateRootNamespace (entry.Item1), a);
1163 if (loaded.Contains (key))
1169 compiler.TimeReporter.Stop (TimeReporter.TimerType.ReferencesLoading);