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; }
42 byte[] GetPublicKeyToken ();
45 public abstract class AssemblyDefinition : IAssemblyDefinition
47 // TODO: make it private and move all builder based methods here
48 public AssemblyBuilder Builder;
49 protected AssemblyBuilderExtension builder_extra;
50 MonoSymbolWriter symbol_writer;
52 bool is_cls_compliant;
53 bool wrap_non_exception_throws;
54 bool wrap_non_exception_throws_custom;
56 protected ModuleContainer module;
58 protected readonly string file_name;
60 byte[] public_key, public_key_token;
63 // Holds private/public key pair when private key
65 StrongNameKeyPair private_key;
67 Attribute cls_attribute;
70 protected List<ImportedModuleDefinition> added_modules;
71 SecurityType declarative_security;
72 Dictionary<ITypeDefinition, Attribute> emitted_forwarders;
73 AssemblyAttributesPlaceholder module_target_attrs;
75 protected AssemblyDefinition (ModuleContainer module, string name)
78 this.name = Path.GetFileNameWithoutExtension (name);
80 wrap_non_exception_throws = true;
82 delay_sign = RootContext.StrongNameDelaySign;
85 // Load strong name key early enough for assembly importer to be able to
86 // use the keys for InternalsVisibleTo
87 // This should go somewhere close to ReferencesLoading but don't have the place yet
89 if (RootContext.StrongNameKeyFile != null || RootContext.StrongNameKeyContainer != null) {
90 LoadPublicKey (RootContext.StrongNameKeyFile, RootContext.StrongNameKeyContainer);
94 protected AssemblyDefinition (ModuleContainer module, string name, string fileName)
97 this.file_name = fileName;
102 public Attribute CLSCompliantAttribute {
104 return cls_attribute;
108 public CompilerContext Compiler {
110 return module.Compiler;
115 // Assembly entry point, aka Main method
117 public Method EntryPoint {
126 public string FullName {
128 return Builder.FullName;
132 public bool HasExtensionMethod {
134 return module.HasExtensionMethod;
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;
161 public bool WrapNonExceptionThrows {
163 return wrap_non_exception_throws;
167 protected Report Report {
169 return Compiler.Report;
175 public void AddModule (ImportedModuleDefinition module)
177 if (added_modules == null) {
178 added_modules = new List<ImportedModuleDefinition> ();
179 added_modules.Add (module);
183 public void ApplyAttributeBuilder (Attribute a, MethodSpec ctor, byte[] cdata, PredefinedAttributes pa)
185 if (a.IsValidSecurityAttribute ()) {
186 a.ExtractSecurityPermissionSet (ctor, ref declarative_security);
190 if (a.Type == pa.AssemblyCulture) {
191 string value = a.GetString ();
192 if (value == null || value.Length == 0)
195 if (RootContext.Target == Target.Exe) {
196 a.Error_AttributeEmitError ("The executables cannot be satelite assemblies, remove the attribute or keep it empty");
200 if (value == "neutral")
203 if (RootContext.Target == Target.Module) {
204 SetCustomAttribute (ctor, cdata);
206 builder_extra.SetCulture (value, a.Location);
212 if (a.Type == pa.AssemblyVersion) {
213 string value = a.GetString ();
214 if (value == null || value.Length == 0)
217 var vinfo = IsValidAssemblyVersion (value, true);
219 a.Error_AttributeEmitError (string.Format ("Specified version `{0}' is not valid", value));
223 if (RootContext.Target == Target.Module) {
224 SetCustomAttribute (ctor, cdata);
226 builder_extra.SetVersion (vinfo, a.Location);
232 if (a.Type == pa.AssemblyAlgorithmId) {
233 const int pos = 2; // skip CA header
234 uint alg = (uint) cdata [pos];
235 alg |= ((uint) cdata [pos + 1]) << 8;
236 alg |= ((uint) cdata [pos + 2]) << 16;
237 alg |= ((uint) cdata [pos + 3]) << 24;
239 if (RootContext.Target == Target.Module) {
240 SetCustomAttribute (ctor, cdata);
242 builder_extra.SetAlgorithmId (alg, a.Location);
248 if (a.Type == pa.AssemblyFlags) {
249 const int pos = 2; // skip CA header
250 uint flags = (uint) cdata[pos];
251 flags |= ((uint) cdata [pos + 1]) << 8;
252 flags |= ((uint) cdata [pos + 2]) << 16;
253 flags |= ((uint) cdata [pos + 3]) << 24;
255 // Ignore set PublicKey flag if assembly is not strongnamed
256 if ((flags & (uint) AssemblyNameFlags.PublicKey) != 0 && public_key == null)
257 flags &= ~(uint) AssemblyNameFlags.PublicKey;
259 if (RootContext.Target == Target.Module) {
260 SetCustomAttribute (ctor, cdata);
262 builder_extra.SetFlags (flags, a.Location);
268 if (a.Type == pa.TypeForwarder) {
269 TypeSpec t = a.GetArgumentType ();
270 if (t == null || TypeManager.HasElementType (t)) {
271 Report.Error (735, a.Location, "Invalid type specified as an argument for TypeForwardedTo attribute");
275 if (emitted_forwarders == null) {
276 emitted_forwarders = new Dictionary<ITypeDefinition, Attribute> ();
277 } else if (emitted_forwarders.ContainsKey (t.MemberDefinition)) {
278 Report.SymbolRelatedToPreviousError (emitted_forwarders[t.MemberDefinition].Location, null);
279 Report.Error (739, a.Location, "A duplicate type forward of type `{0}'",
280 TypeManager.CSharpName (t));
284 emitted_forwarders.Add (t.MemberDefinition, a);
286 if (t.MemberDefinition.DeclaringAssembly == this) {
287 Report.SymbolRelatedToPreviousError (t);
288 Report.Error (729, a.Location, "Cannot forward type `{0}' because it is defined in this assembly",
289 TypeManager.CSharpName (t));
294 Report.Error (730, a.Location, "Cannot forward type `{0}' because it is a nested type",
295 TypeManager.CSharpName (t));
299 builder_extra.AddTypeForwarder (t.GetDefinition (), a.Location);
303 if (a.Type == pa.Extension) {
304 a.Error_MisusedExtensionAttribute ();
308 if (a.Type == pa.InternalsVisibleTo) {
309 string assembly_name = a.GetString ();
310 if (assembly_name.Length == 0)
313 AssemblyName aname = null;
315 aname = new AssemblyName (assembly_name);
316 } catch (Exception) {
317 Report.Warning (1700, 3, a.Location, "Assembly reference `{0}' is invalid and cannot be resolved",
322 if (aname.Version != null || aname.CultureInfo != null || aname.ProcessorArchitecture != ProcessorArchitecture.None) {
323 Report.Error (1725, a.Location,
324 "Friend assembly reference `{0}' is invalid. InternalsVisibleTo declarations cannot have a version, culture or processor architecture specified",
330 // TODO: GetPublicKey () does not work on .NET when AssemblyName is constructed from a string
331 if (public_key != null && aname.GetPublicKey () == null) {
332 Report.Error (1726, a.Location,
333 "Friend assembly reference `{0}' is invalid. Strong named assemblies must specify a public key in their InternalsVisibleTo declarations",
337 } else if (a.Type == pa.RuntimeCompatibility) {
338 wrap_non_exception_throws_custom = true;
339 } else if (a.Type == pa.AssemblyFileVersion) {
340 string value = a.GetString ();
341 if (string.IsNullOrEmpty (value) || IsValidAssemblyVersion (value, false) == null) {
342 Report.Warning (1607, 1, a.Location, "The version number `{0}' specified for `{1}' is invalid",
349 SetCustomAttribute (ctor, cdata);
353 // When using assembly public key attributes InternalsVisibleTo key
354 // was not checked, we have to do it later when we actually know what
355 // our public key token is
357 void CheckReferencesPublicToken ()
359 // TODO: It should check only references assemblies but there is
360 // no working SRE API
361 foreach (var a in Importer.Assemblies) {
362 if (public_key != null && !a.HasStrongName) {
363 Report.Error (1577, "Referenced assembly `{0}' does not have a strong name",
367 if (!a.IsFriendAssemblyTo (this))
370 var attr = a.GetAssemblyVisibleToName (this);
371 var atoken = attr.GetPublicKeyToken ();
373 if (ArrayComparer.IsEqual (GetPublicKeyToken (), atoken))
377 "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",
378 attr.FullName, FullName);
382 protected AssemblyName CreateAssemblyName ()
384 var an = new AssemblyName (name);
386 if (public_key != null && RootContext.Target != Target.Module) {
388 an.SetPublicKey (public_key);
390 if (public_key.Length == 16) {
391 Report.Error (1606, "Could not sign the assembly. ECMA key can only be used to delay-sign assemblies");
392 } else if (private_key == null) {
393 Error_AssemblySigning ("The specified key file does not have a private key");
395 an.KeyPair = private_key;
403 public virtual ModuleBuilder CreateModuleBuilder ()
405 if (file_name == null)
406 throw new NotSupportedException ("transient module in static assembly");
408 var module_name = Path.GetFileName (file_name);
410 // Always initialize module without symbolInfo. We could be framework dependent
411 // but returned ISymbolWriter does not have all what we need therefore some
412 // adaptor will be needed for now we alwayas emit MDB format when generating
414 return Builder.DefineDynamicModule (module_name, module_name, false);
419 if (RootContext.Target == Target.Module) {
420 module_target_attrs = new AssemblyAttributesPlaceholder (module, name);
421 module_target_attrs.CreateType ();
422 module_target_attrs.DefineType ();
423 module_target_attrs.Define ();
424 module.AddCompilerGeneratedClass (module_target_attrs);
425 } else if (added_modules != null) {
426 ReadModulesAssemblyAttributes ();
429 if (RootContext.GenerateDebugInfo) {
430 symbol_writer = new MonoSymbolWriter (file_name);
432 // TODO: global variables
433 Location.DefineSymbolDocuments (symbol_writer);
434 SymbolWriter.symwriter = symbol_writer;
439 if (module.HasExtensionMethod) {
440 var pa = module.PredefinedAttributes.Extension;
442 SetCustomAttribute (pa.Constructor, AttributeEncoder.Empty);
446 if (!wrap_non_exception_throws_custom) {
447 PredefinedAttribute pa = module.PredefinedAttributes.RuntimeCompatibility;
448 if (pa.IsDefined && pa.ResolveBuilder ()) {
449 var prop = pa.GetProperty ("WrapNonExceptionThrows", TypeManager.bool_type, Location.Null);
451 AttributeEncoder encoder = new AttributeEncoder (false);
452 encoder.EncodeNamedPropertyArgument (prop, new BoolLiteral (true, Location.Null));
453 SetCustomAttribute (pa.Constructor, encoder.ToArray ());
458 if (declarative_security != null) {
460 foreach (var entry in declarative_security) {
461 Builder.__AddDeclarativeSecurity (entry);
464 var args = new PermissionSet[3];
465 declarative_security.TryGetValue (SecurityAction.RequestMinimum, out args[0]);
466 declarative_security.TryGetValue (SecurityAction.RequestOptional, out args[1]);
467 declarative_security.TryGetValue (SecurityAction.RequestRefuse, out args[2]);
468 builder_extra.AddPermissionRequests (args);
472 CheckReferencesPublicToken ();
477 public byte[] GetPublicKeyToken ()
479 if (public_key == null || public_key_token != null)
480 return public_key_token;
482 HashAlgorithm ha = SHA1.Create ();
483 byte[] hash = ha.ComputeHash (public_key);
484 // we need the last 8 bytes in reverse order
485 public_key_token = new byte[8];
486 Buffer.BlockCopy (hash, hash.Length - 8, public_key_token, 0, 8);
487 Array.Reverse (public_key_token, 0, 8);
488 return public_key_token;
492 // Either keyFile or keyContainer has to be non-null
494 void LoadPublicKey (string keyFile, string keyContainer)
496 if (keyContainer != null) {
498 private_key = new StrongNameKeyPair (keyContainer);
499 public_key = private_key.PublicKey;
501 Error_AssemblySigning ("The specified key container `" + keyContainer + "' does not exist");
507 bool key_file_exists = File.Exists (keyFile);
510 // For attribute based KeyFile do additional lookup
511 // in output assembly path
513 if (!key_file_exists && RootContext.StrongNameKeyFile == null) {
515 // The key file can be relative to output assembly
517 string test_path = Path.Combine (Path.GetDirectoryName (file_name), keyFile);
518 key_file_exists = File.Exists (test_path);
523 if (!key_file_exists) {
524 Error_AssemblySigning ("The specified key file `" + keyFile + "' does not exist");
528 using (FileStream fs = new FileStream (keyFile, FileMode.Open, FileAccess.Read)) {
529 byte[] snkeypair = new byte[fs.Length];
530 fs.Read (snkeypair, 0, snkeypair.Length);
532 // check for ECMA key
533 if (snkeypair.Length == 16) {
534 public_key = snkeypair;
539 // take it, with or without, a private key
540 RSA rsa = CryptoConvert.FromCapiKeyBlob (snkeypair);
541 // and make sure we only feed the public part to Sys.Ref
542 byte[] publickey = CryptoConvert.ToCapiPublicKeyBlob (rsa);
544 // AssemblyName.SetPublicKey requires an additional header
545 byte[] publicKeyHeader = new byte[8] { 0x00, 0x24, 0x00, 0x00, 0x04, 0x80, 0x00, 0x00 };
548 public_key = new byte[12 + publickey.Length];
549 Buffer.BlockCopy (publicKeyHeader, 0, public_key, 0, publicKeyHeader.Length);
551 // Length of Public Key (in bytes)
552 byte[] lastPart = BitConverter.GetBytes (public_key.Length - 12);
553 public_key[8] = lastPart[0];
554 public_key[9] = lastPart[1];
555 public_key[10] = lastPart[2];
556 public_key[11] = lastPart[3];
558 Buffer.BlockCopy (publickey, 0, public_key, 12, publickey.Length);
560 Error_AssemblySigning ("The specified key file `" + keyFile + "' has incorrect format");
568 // TODO: Is there better way to test for a private key presence ?
569 CryptoConvert.FromCapiPrivateKeyBlob (snkeypair);
570 private_key = new StrongNameKeyPair (snkeypair);
575 void ReadModulesAssemblyAttributes ()
577 foreach (var m in added_modules) {
578 var cattrs = m.ReadAssemblyAttributes ();
582 module.OptAttributes.AddAttributes (cattrs);
586 public void Resolve ()
588 if (RootContext.Unsafe && module.PredefinedTypes.SecurityAction.Define ()) {
590 // Emits [assembly: SecurityPermissionAttribute (SecurityAction.RequestMinimum, SkipVerification = true)]
591 // when -unsafe option was specified
593 Location loc = Location.Null;
595 MemberAccess system_security_permissions = new MemberAccess (new MemberAccess (
596 new QualifiedAliasMember (QualifiedAliasMember.GlobalAlias, "System", loc), "Security", loc), "Permissions", loc);
598 var req_min = (ConstSpec) module.PredefinedTypes.SecurityAction.GetField ("RequestMinimum", module.PredefinedTypes.SecurityAction.TypeSpec, loc);
600 Arguments pos = new Arguments (1);
601 pos.Add (new Argument (req_min.GetConstant (null)));
603 Arguments named = new Arguments (1);
604 named.Add (new NamedArgument ("SkipVerification", loc, new BoolLiteral (true, loc)));
606 GlobalAttribute g = new GlobalAttribute (new NamespaceEntry (module, null, null, null), "assembly",
607 new MemberAccess (system_security_permissions, "SecurityPermissionAttribute"),
608 new Arguments[] { pos, named }, loc, false);
609 g.AttachTo (module, module);
610 var ctor = g.Resolve ();
612 g.ExtractSecurityPermissionSet (ctor, ref declarative_security);
616 if (module.OptAttributes == null)
619 // Ensure that we only have GlobalAttributes, since the Search isn't safe with other types.
620 if (!module.OptAttributes.CheckTargets())
623 cls_attribute = module.ResolveAssemblyAttribute (module.PredefinedAttributes.CLSCompliant);
625 if (cls_attribute != null) {
626 is_cls_compliant = cls_attribute.GetClsCompliantAttributeValue ();
629 if (added_modules != null && RootContext.VerifyClsCompliance && is_cls_compliant) {
630 foreach (var m in added_modules) {
631 if (!m.IsCLSCompliant) {
633 "Added modules must be marked with the CLSCompliant attribute to match the assembly",
639 Attribute a = module.ResolveAssemblyAttribute (module.PredefinedAttributes.RuntimeCompatibility);
641 var val = a.GetNamedValue ("WrapNonExceptionThrows") as BoolConstant;
643 wrap_non_exception_throws = val.Value;
647 protected void ResolveAssemblySecurityAttributes ()
649 string key_file = null;
650 string key_container = null;
652 if (module.OptAttributes != null) {
653 foreach (Attribute a in module.OptAttributes.Attrs) {
654 // cannot rely on any resolve-based members before you call Resolve
655 if (a.ExplicitTarget != "assembly")
658 // TODO: This code is buggy: comparing Attribute name without resolving is wrong.
659 // However, this is invoked by CodeGen.Init, when none of the namespaces
661 // TODO: Does not handle quoted attributes properly
663 case "AssemblyKeyFile":
664 case "AssemblyKeyFileAttribute":
665 case "System.Reflection.AssemblyKeyFileAttribute":
666 if (RootContext.StrongNameKeyFile != null) {
667 Report.SymbolRelatedToPreviousError (a.Location, a.GetSignatureForError ());
668 Report.Warning (1616, 1, "Option `{0}' overrides attribute `{1}' given in a source file or added module",
669 "keyfile", "System.Reflection.AssemblyKeyFileAttribute");
671 string value = a.GetString ();
672 if (!string.IsNullOrEmpty (value)) {
673 Error_ObsoleteSecurityAttribute (a, "keyfile");
678 case "AssemblyKeyName":
679 case "AssemblyKeyNameAttribute":
680 case "System.Reflection.AssemblyKeyNameAttribute":
681 if (RootContext.StrongNameKeyContainer != null) {
682 Report.SymbolRelatedToPreviousError (a.Location, a.GetSignatureForError ());
683 Report.Warning (1616, 1, "Option `{0}' overrides attribute `{1}' given in a source file or added module",
684 "keycontainer", "System.Reflection.AssemblyKeyNameAttribute");
686 string value = a.GetString ();
687 if (!string.IsNullOrEmpty (value)) {
688 Error_ObsoleteSecurityAttribute (a, "keycontainer");
689 key_container = value;
693 case "AssemblyDelaySign":
694 case "AssemblyDelaySignAttribute":
695 case "System.Reflection.AssemblyDelaySignAttribute":
696 bool b = a.GetBoolean ();
698 Error_ObsoleteSecurityAttribute (a, "delaysign");
707 // We came here only to report assembly attributes warnings
708 if (public_key != null)
712 // Load the strong key file found in attributes when no
713 // command line key was given
715 if (key_file != null || key_container != null) {
716 LoadPublicKey (key_file, key_container);
717 } else if (delay_sign) {
718 Report.Warning (1607, 1, "Delay signing was requested but no key file was given");
722 public void EmbedResources ()
725 // Add Win32 resources
727 if (RootContext.Win32ResourceFile != null) {
728 Builder.DefineUnmanagedResource (RootContext.Win32ResourceFile);
730 Builder.DefineVersionInfoResource ();
733 if (RootContext.Win32IconFile != null) {
734 builder_extra.DefineWin32IconResource (RootContext.Win32IconFile);
737 if (RootContext.Resources != null) {
738 if (RootContext.Target == Target.Module) {
739 Report.Error (1507, "Cannot link resource file when building a module");
742 foreach (var res in RootContext.Resources) {
743 if (!File.Exists (res.FileName)) {
744 Report.Error (1566, "Error reading resource file `{0}'", res.FileName);
750 if (counter++ < 10) {
751 stream = File.OpenRead (res.FileName);
753 // TODO: SRE API requires resource stream to be available during AssemblyBuilder::Save
754 // we workaround it by reading everything into memory to compile projects with
755 // many embedded resource (over 3500) references
756 stream = new MemoryStream (File.ReadAllBytes (res.FileName));
759 module.Builder.DefineManifestResource (res.Name, stream, res.Attributes);
761 Builder.AddResourceFile (res.Name, Path.GetFileName (res.FileName), res.Attributes);
770 PortableExecutableKinds pekind;
771 ImageFileMachine machine;
773 switch (RootContext.Platform) {
775 pekind = PortableExecutableKinds.Required32Bit | PortableExecutableKinds.ILOnly;
776 machine = ImageFileMachine.I386;
779 pekind = PortableExecutableKinds.ILOnly;
780 machine = ImageFileMachine.AMD64;
783 pekind = PortableExecutableKinds.ILOnly;
784 machine = ImageFileMachine.IA64;
786 case Platform.AnyCPU:
788 pekind = PortableExecutableKinds.ILOnly;
789 machine = ImageFileMachine.I386;
794 if (RootContext.Target == Target.Module) {
795 SaveModule (pekind, machine);
797 Builder.Save (module.Builder.ScopeName, pekind, machine);
799 } catch (Exception e) {
800 Report.Error (16, "Could not write to file `" + name + "', cause: " + e.Message);
803 // Save debug symbols file
804 if (symbol_writer != null) {
805 // TODO: it should run in parallel
806 symbol_writer.WriteSymbolFile (SymbolWriter.GetGuid (module.Builder));
810 protected virtual void SaveModule (PortableExecutableKinds pekind, ImageFileMachine machine)
812 Report.RuntimeMissingSupport (Location.Null, "-target:module");
815 void SetCustomAttribute (MethodSpec ctor, byte[] data)
817 if (module_target_attrs != null)
818 module_target_attrs.AddAssemblyAttribute (ctor, data);
820 Builder.SetCustomAttribute ((ConstructorInfo) ctor.GetMetaInfo (), data);
823 void SetEntryPoint ()
825 if (!RootContext.NeedsEntryPoint) {
826 if (RootContext.MainClass != null)
827 Report.Error (2017, "Cannot specify -main if building a module or library");
832 PEFileKinds file_kind;
834 switch (RootContext.Target) {
837 file_kind = PEFileKinds.Dll;
840 file_kind = PEFileKinds.WindowApplication;
843 file_kind = PEFileKinds.ConsoleApplication;
847 if (entry_point == null) {
848 if (RootContext.MainClass != null) {
849 // TODO: Should use MemberCache
850 DeclSpace main_cont = module.GetDefinition (RootContext.MainClass) as DeclSpace;
851 if (main_cont == null) {
852 Report.Error (1555, "Could not find `{0}' specified for Main method", RootContext.MainClass);
856 if (!(main_cont is ClassOrStruct)) {
857 Report.Error (1556, "`{0}' specified for Main method must be a valid class or struct", RootContext.MainClass);
861 Report.Error (1558, main_cont.Location, "`{0}' does not have a suitable static Main method", main_cont.GetSignatureForError ());
865 if (Report.Errors == 0) {
866 string pname = file_name == null ? name : Path.GetFileName (file_name);
868 Report.Error (5001, "Program `{0}' does not contain a static `Main' method suitable for an entry point",
875 Builder.SetEntryPoint (entry_point.MethodBuilder, file_kind);
878 void Error_ObsoleteSecurityAttribute (Attribute a, string option)
880 Report.Warning (1699, 1, a.Location,
881 "Use compiler option `{0}' or appropriate project settings instead of `{1}' attribute",
885 void Error_AssemblySigning (string text)
887 Report.Error (1548, "Error during assembly signing. " + text);
890 static Version IsValidAssemblyVersion (string version, bool allowGenerated)
892 string[] parts = version.Split ('.');
893 if (parts.Length < 1 || parts.Length > 4)
896 var values = new int[4];
897 for (int i = 0; i < parts.Length; ++i) {
898 if (!int.TryParse (parts[i], out values[i])) {
899 if (parts[i].Length == 1 && parts[i][0] == '*' && allowGenerated) {
901 // Nothing can follow *
902 if (parts.Length > 3)
905 // Generate Build value based on days since 1/1/2000
906 TimeSpan days = DateTime.Today - new DateTime (2000, 1, 1);
907 values[i] = System.Math.Max (days.Days, 0);
912 // Generate Revision value based on every other second today
913 var seconds = DateTime.Now - DateTime.Today;
914 values[i] = (int) seconds.TotalSeconds / 2;
922 if (values[i] > ushort.MaxValue)
926 return new Version (values[0], values[1], values[2], values[3]);
930 public class AssemblyResource : IEquatable<AssemblyResource>
932 public AssemblyResource (string fileName, string name)
933 : this (fileName, name, false)
937 public AssemblyResource (string fileName, string name, bool isPrivate)
941 Attributes = isPrivate ? ResourceAttributes.Private : ResourceAttributes.Public;
944 public ResourceAttributes Attributes { get; private set; }
945 public string Name { get; private set; }
946 public string FileName { get; private set; }
947 public bool IsEmbeded { get; set; }
949 #region IEquatable<AssemblyResource> Members
951 public bool Equals (AssemblyResource other)
953 return Name == other.Name;
960 // A placeholder class for assembly attributes when emitting module
962 class AssemblyAttributesPlaceholder : CompilerGeneratedClass
964 static readonly string TypeNamePrefix = "<$AssemblyAttributes${0}>";
965 public static readonly string AssemblyFieldName = "attributes";
969 public AssemblyAttributesPlaceholder (ModuleContainer parent, string outputName)
970 : base (parent, new MemberName (GetGeneratedName (outputName)), Modifiers.STATIC)
972 assembly = new Field (this, new TypeExpression (TypeManager.object_type, Location), Modifiers.PUBLIC | Modifiers.STATIC,
973 new MemberName (AssemblyFieldName), null);
978 public void AddAssemblyAttribute (MethodSpec ctor, byte[] data)
980 assembly.SetCustomAttribute (ctor, data);
983 public static string GetGeneratedName (string outputName)
985 return string.Format (TypeNamePrefix, outputName);
990 // Extension to System.Reflection.Emit.AssemblyBuilder to have fully compatible
991 // compiler. This is a default implementation for framework System.Reflection.Emit
992 // which does not implement any of the methods
994 public class AssemblyBuilderExtension
996 readonly CompilerContext ctx;
998 public AssemblyBuilderExtension (CompilerContext ctx)
1003 public virtual System.Reflection.Module AddModule (string module)
1005 ctx.Report.RuntimeMissingSupport (Location.Null, "-addmodule");
1009 public virtual void AddPermissionRequests (PermissionSet[] permissions)
1011 ctx.Report.RuntimeMissingSupport (Location.Null, "assembly declarative security");
1014 public virtual void AddTypeForwarder (TypeSpec type, Location loc)
1016 ctx.Report.RuntimeMissingSupport (loc, "TypeForwardedToAttribute");
1019 public virtual void DefineWin32IconResource (string fileName)
1021 ctx.Report.RuntimeMissingSupport (Location.Null, "-win32icon");
1024 public virtual void SetAlgorithmId (uint value, Location loc)
1026 ctx.Report.RuntimeMissingSupport (loc, "AssemblyAlgorithmIdAttribute");
1029 public virtual void SetCulture (string culture, Location loc)
1031 ctx.Report.RuntimeMissingSupport (loc, "AssemblyCultureAttribute");
1034 public virtual void SetFlags (uint flags, Location loc)
1036 ctx.Report.RuntimeMissingSupport (loc, "AssemblyFlagsAttribute");
1039 public virtual void SetVersion (Version version, Location loc)
1041 ctx.Report.RuntimeMissingSupport (loc, "AssemblyVersionAttribute");
1045 abstract class AssemblyReferencesLoader<T>
1047 protected readonly CompilerContext compiler;
1049 protected readonly List<string> paths;
1050 readonly string[] default_references;
1052 public AssemblyReferencesLoader (CompilerContext compiler)
1054 this.compiler = compiler;
1056 if (RootContext.LoadDefaultReferences)
1057 default_references = GetDefaultReferences ();
1059 default_references = new string[0];
1061 paths = new List<string> ();
1062 paths.AddRange (RootContext.ReferencesLookupPaths);
1063 paths.Add (Directory.GetCurrentDirectory ());
1066 public abstract bool HasObjectType (T assembly);
1067 protected abstract string[] GetDefaultReferences ();
1068 public abstract T LoadAssemblyFile (string fileName);
1069 public abstract T LoadAssemblyDefault (string assembly);
1070 public abstract void LoadReferences (ModuleContainer module);
1072 protected void Error_FileNotFound (string fileName)
1074 compiler.Report.Error (6, "Metadata file `{0}' could not be found", fileName);
1077 protected void Error_FileCorrupted (string fileName)
1079 compiler.Report.Error (9, "Metadata file `{0}' does not contain valid metadata", fileName);
1082 protected void Error_AssemblyIsModule (string fileName)
1084 compiler.Report.Error (1509,
1085 "Referenced assembly file `{0}' is a module. Consider using `-addmodule' option to add the module",
1089 protected void Error_ModuleIsAssembly (string fileName)
1091 compiler.Report.Error (1542,
1092 "Added module file `{0}' is an assembly. Consider using `-r' option to reference the file",
1096 protected void LoadReferencesCore (ModuleContainer module, out T corlib_assembly, out List<Tuple<RootNamespace, T>> loaded)
1098 loaded = new List<Tuple<RootNamespace, T>> ();
1101 // Load mscorlib.dll as the first
1103 if (RootContext.StdLib) {
1104 corlib_assembly = LoadAssemblyDefault ("mscorlib.dll");
1106 corlib_assembly = default (T);
1110 foreach (string r in default_references) {
1111 a = LoadAssemblyDefault (r);
1113 loaded.Add (Tuple.Create (module.GlobalRootNamespace, a));
1116 foreach (string r in RootContext.AssemblyReferences) {
1117 a = LoadAssemblyFile (r);
1118 if (a == null || EqualityComparer<T>.Default.Equals (a, corlib_assembly))
1121 var key = Tuple.Create (module.GlobalRootNamespace, a);
1122 if (loaded.Contains (key))
1125 // A corlib assembly is the first assembly which contains System.Object
1126 if (corlib_assembly == null && HasObjectType (a)) {
1127 corlib_assembly = a;
1134 foreach (var entry in RootContext.AssemblyReferencesAliases) {
1135 a = LoadAssemblyFile (entry.Item2);
1139 var key = Tuple.Create (module.CreateRootNamespace (entry.Item1), a);
1140 if (loaded.Contains (key))