2009-11-02 Jb Evain <jbevain@novell.com>
[mcs.git] / mcs / codegen.cs
blobdad7fd412f106314a1eb668d176110c6c91f014f
1 //
2 // codegen.cs: The code generator
3 //
4 // Author:
5 // Miguel de Icaza (miguel@ximian.com)
6 //
7 // Copyright 2001, 2002, 2003 Ximian, Inc.
8 // Copyright 2004 Novell, Inc.
9 //
12 // Please leave this defined on SVN: The idea is that when we ship the
13 // compiler to end users, if the compiler crashes, they have a chance
14 // to narrow down the problem.
16 // Only remove it if you need to debug locally on your tree.
18 //#define PRODUCTION
20 using System;
21 using System.IO;
22 using System.Collections;
23 using System.Collections.Specialized;
24 using System.Globalization;
25 using System.Reflection;
26 using System.Reflection.Emit;
27 using System.Runtime.InteropServices;
28 using System.Security;
29 using System.Security.Cryptography;
30 using System.Security.Permissions;
32 using Mono.Security.Cryptography;
34 namespace Mono.CSharp {
36 /// <summary>
37 /// Code generator class.
38 /// </summary>
39 public class CodeGen {
40 static AppDomain current_domain;
42 public static AssemblyClass Assembly;
44 static CodeGen ()
46 Reset ();
49 public static void Reset ()
51 Assembly = new AssemblyClass ();
54 public static string Basename (string name)
56 int pos = name.LastIndexOf ('/');
58 if (pos != -1)
59 return name.Substring (pos + 1);
61 pos = name.LastIndexOf ('\\');
62 if (pos != -1)
63 return name.Substring (pos + 1);
65 return name;
68 public static string Dirname (string name)
70 int pos = name.LastIndexOf ('/');
72 if (pos != -1)
73 return name.Substring (0, pos);
75 pos = name.LastIndexOf ('\\');
76 if (pos != -1)
77 return name.Substring (0, pos);
79 return ".";
82 static public string FileName;
84 #if MS_COMPATIBLE
85 const AssemblyBuilderAccess COMPILER_ACCESS = 0;
86 #else
87 /* Keep this in sync with System.Reflection.Emit.AssemblyBuilder */
88 const AssemblyBuilderAccess COMPILER_ACCESS = (AssemblyBuilderAccess) 0x800;
89 #endif
92 // Initializes the code generator variables for interactive use (repl)
94 static public void InitDynamic (CompilerContext ctx, string name)
96 current_domain = AppDomain.CurrentDomain;
97 AssemblyName an = Assembly.GetAssemblyName (name, name);
99 Assembly.Builder = current_domain.DefineDynamicAssembly (an, AssemblyBuilderAccess.Run | COMPILER_ACCESS);
100 RootContext.ToplevelTypes = new ModuleCompiled (ctx, true);
101 RootContext.ToplevelTypes.Builder = Assembly.Builder.DefineDynamicModule (Basename (name), false);
102 Assembly.Name = Assembly.Builder.GetName ();
106 // Initializes the code generator variables
108 static public bool Init (string name, string output, bool want_debugging_support, CompilerContext ctx)
110 FileName = output;
111 AssemblyName an = Assembly.GetAssemblyName (name, output);
112 if (an == null)
113 return false;
115 if (an.KeyPair != null) {
116 // If we are going to strong name our assembly make
117 // sure all its refs are strong named
118 foreach (Assembly a in GlobalRootNamespace.Instance.Assemblies) {
119 AssemblyName ref_name = a.GetName ();
120 byte [] b = ref_name.GetPublicKeyToken ();
121 if (b == null || b.Length == 0) {
122 ctx.Report.Error (1577, "Assembly generation failed " +
123 "-- Referenced assembly '" +
124 ref_name.Name +
125 "' does not have a strong name.");
126 //Environment.Exit (1);
131 current_domain = AppDomain.CurrentDomain;
133 try {
134 Assembly.Builder = current_domain.DefineDynamicAssembly (an,
135 AssemblyBuilderAccess.RunAndSave | COMPILER_ACCESS, Dirname (name));
137 catch (ArgumentException) {
138 // specified key may not be exportable outside it's container
139 if (RootContext.StrongNameKeyContainer != null) {
140 ctx.Report.Error (1548, "Could not access the key inside the container `" +
141 RootContext.StrongNameKeyContainer + "'.");
142 Environment.Exit (1);
144 throw;
146 catch (CryptographicException) {
147 if ((RootContext.StrongNameKeyContainer != null) || (RootContext.StrongNameKeyFile != null)) {
148 ctx.Report.Error (1548, "Could not use the specified key to strongname the assembly.");
149 Environment.Exit (1);
151 return false;
154 // Get the complete AssemblyName from the builder
155 // (We need to get the public key and token)
156 Assembly.Name = Assembly.Builder.GetName ();
159 // Pass a path-less name to DefineDynamicModule. Wonder how
160 // this copes with output in different directories then.
161 // FIXME: figure out how this copes with --output /tmp/blah
163 // If the third argument is true, the ModuleBuilder will dynamically
164 // load the default symbol writer.
166 try {
167 RootContext.ToplevelTypes.Builder = Assembly.Builder.DefineDynamicModule (
168 Basename (name), Basename (output), want_debugging_support);
170 #if !MS_COMPATIBLE
171 // TODO: We should use SymbolWriter from DefineDynamicModule
172 if (want_debugging_support && !SymbolWriter.Initialize (RootContext.ToplevelTypes.Builder, output)) {
173 ctx.Report.Error (40, "Unexpected debug information initialization error `{0}'",
174 "Could not find the symbol writer assembly (Mono.CompilerServices.SymbolWriter.dll)");
175 return false;
177 #endif
178 } catch (ExecutionEngineException e) {
179 ctx.Report.Error (40, "Unexpected debug information initialization error `{0}'",
180 e.Message);
181 return false;
184 return true;
187 static public void Save (string name, bool saveDebugInfo, Report Report)
189 PortableExecutableKinds pekind;
190 ImageFileMachine machine;
192 switch (RootContext.Platform) {
193 case Platform.X86:
194 pekind = PortableExecutableKinds.Required32Bit;
195 machine = ImageFileMachine.I386;
196 break;
197 case Platform.X64:
198 pekind = PortableExecutableKinds.PE32Plus;
199 machine = ImageFileMachine.AMD64;
200 break;
201 case Platform.IA64:
202 pekind = PortableExecutableKinds.PE32Plus;
203 machine = ImageFileMachine.IA64;
204 break;
205 case Platform.AnyCPU:
206 default:
207 pekind = PortableExecutableKinds.ILOnly;
208 machine = ImageFileMachine.I386;
209 break;
211 try {
212 Assembly.Builder.Save (Basename (name), pekind, machine);
214 catch (COMException) {
215 if ((RootContext.StrongNameKeyFile == null) || (!RootContext.StrongNameDelaySign))
216 throw;
218 // FIXME: it seems Microsoft AssemblyBuilder doesn't like to delay sign assemblies
219 Report.Error (1548, "Couldn't delay-sign the assembly with the '" +
220 RootContext.StrongNameKeyFile +
221 "', Use MCS with the Mono runtime or CSC to compile this assembly.");
223 catch (System.IO.IOException io) {
224 Report.Error (16, "Could not write to file `"+name+"', cause: " + io.Message);
225 return;
227 catch (System.UnauthorizedAccessException ua) {
228 Report.Error (16, "Could not write to file `"+name+"', cause: " + ua.Message);
229 return;
231 catch (System.NotImplementedException nie) {
232 Report.RuntimeMissingSupport (Location.Null, nie.Message);
233 return;
237 // Write debuger symbol file
239 if (saveDebugInfo)
240 SymbolWriter.WriteSymbolFile ();
244 /// <summary>
245 /// An Emit Context is created for each body of code (from methods,
246 /// properties bodies, indexer bodies or constructor bodies)
247 /// </summary>
248 public class EmitContext : BuilderContext
250 public ILGenerator ig;
252 /// <summary>
253 /// The value that is allowed to be returned or NULL if there is no
254 /// return type.
255 /// </summary>
256 Type return_type;
258 /// <summary>
259 /// Keeps track of the Type to LocalBuilder temporary storage created
260 /// to store structures (used to compute the address of the structure
261 /// value on structure method invocations)
262 /// </summary>
263 Hashtable temporary_storage;
265 /// <summary>
266 /// The location where we store the return value.
267 /// </summary>
268 public LocalBuilder return_value;
270 /// <summary>
271 /// The location where return has to jump to return the
272 /// value
273 /// </summary>
274 public Label ReturnLabel;
276 /// <summary>
277 /// If we already defined the ReturnLabel
278 /// </summary>
279 public bool HasReturnLabel;
281 /// <summary>
282 /// Whether we are inside an anonymous method.
283 /// </summary>
284 public AnonymousExpression CurrentAnonymousMethod;
286 public readonly IMemberContext MemberContext;
288 public EmitContext (IMemberContext rc, ILGenerator ig, Type return_type)
290 this.MemberContext = rc;
291 this.ig = ig;
293 this.return_type = return_type;
296 public Type CurrentType {
297 get { return MemberContext.CurrentType; }
300 public TypeParameter[] CurrentTypeParameters {
301 get { return MemberContext.CurrentTypeParameters; }
304 public TypeContainer CurrentTypeDefinition {
305 get { return MemberContext.CurrentTypeDefinition; }
308 public bool IsStatic {
309 get { return MemberContext.IsStatic; }
312 public Type ReturnType {
313 get {
314 return return_type;
318 /// <summary>
319 /// This is called immediately before emitting an IL opcode to tell the symbol
320 /// writer to which source line this opcode belongs.
321 /// </summary>
322 public void Mark (Location loc)
324 if (!SymbolWriter.HasSymbolWriter || HasSet (Options.OmitDebugInfo) || loc.IsNull)
325 return;
327 SymbolWriter.MarkSequencePoint (ig, loc);
330 public void DefineLocalVariable (string name, LocalBuilder builder)
332 SymbolWriter.DefineLocalVariable (name, builder);
335 public void BeginScope ()
337 ig.BeginScope();
338 SymbolWriter.OpenScope(ig);
341 public void EndScope ()
343 ig.EndScope();
344 SymbolWriter.CloseScope(ig);
347 /// <summary>
348 /// Returns a temporary storage for a variable of type t as
349 /// a local variable in the current body.
350 /// </summary>
351 public LocalBuilder GetTemporaryLocal (Type t)
353 if (temporary_storage != null) {
354 object o = temporary_storage [t];
355 if (o != null) {
356 if (o is Stack) {
357 Stack s = (Stack) o;
358 o = s.Count == 0 ? null : s.Pop ();
359 } else {
360 temporary_storage.Remove (t);
363 if (o != null)
364 return (LocalBuilder) o;
366 return ig.DeclareLocal (TypeManager.TypeToReflectionType (t));
369 public void FreeTemporaryLocal (LocalBuilder b, Type t)
371 if (temporary_storage == null) {
372 temporary_storage = new Hashtable ();
373 temporary_storage [t] = b;
374 return;
376 object o = temporary_storage [t];
377 if (o == null) {
378 temporary_storage [t] = b;
379 return;
381 Stack s = o as Stack;
382 if (s == null) {
383 s = new Stack ();
384 s.Push (o);
385 temporary_storage [t] = s;
387 s.Push (b);
390 /// <summary>
391 /// Current loop begin and end labels.
392 /// </summary>
393 public Label LoopBegin, LoopEnd;
395 /// <summary>
396 /// Default target in a switch statement. Only valid if
397 /// InSwitch is true
398 /// </summary>
399 public Label DefaultTarget;
401 /// <summary>
402 /// If this is non-null, points to the current switch statement
403 /// </summary>
404 public Switch Switch;
406 /// <summary>
407 /// ReturnValue creates on demand the LocalBuilder for the
408 /// return value from the function. By default this is not
409 /// used. This is only required when returns are found inside
410 /// Try or Catch statements.
412 /// This method is typically invoked from the Emit phase, so
413 /// we allow the creation of a return label if it was not
414 /// requested during the resolution phase. Could be cleaned
415 /// up, but it would replicate a lot of logic in the Emit phase
416 /// of the code that uses it.
417 /// </summary>
418 public LocalBuilder TemporaryReturn ()
420 if (return_value == null){
421 return_value = ig.DeclareLocal (return_type);
422 if (!HasReturnLabel){
423 ReturnLabel = ig.DefineLabel ();
424 HasReturnLabel = true;
428 return return_value;
432 public abstract class CommonAssemblyModulClass : Attributable, IMemberContext
434 public void AddAttributes (ArrayList attrs, IMemberContext context)
436 foreach (Attribute a in attrs)
437 a.AttachTo (this, context);
439 if (attributes == null) {
440 attributes = new Attributes (attrs);
441 return;
443 attributes.AddAttributes (attrs);
446 public virtual void Emit (TypeContainer tc)
448 if (OptAttributes == null)
449 return;
451 OptAttributes.Emit ();
454 protected Attribute ResolveAttribute (PredefinedAttribute a_type)
456 Attribute a = OptAttributes.Search (a_type);
457 if (a != null) {
458 a.Resolve ();
460 return a;
463 #region IMemberContext Members
465 public CompilerContext Compiler {
466 get { return RootContext.ToplevelTypes.Compiler; }
469 public Type CurrentType {
470 get { return null; }
473 public TypeParameter[] CurrentTypeParameters {
474 get { return null; }
477 public TypeContainer CurrentTypeDefinition {
478 get { return RootContext.ToplevelTypes; }
481 public string GetSignatureForError ()
483 return "<module>";
486 public bool IsObsolete {
487 get { return false; }
490 public bool IsUnsafe {
491 get { return false; }
494 public bool IsStatic {
495 get { return false; }
498 public ExtensionMethodGroupExpr LookupExtensionMethod (Type extensionType, string name, Location loc)
500 throw new NotImplementedException ();
503 public FullNamedExpression LookupNamespaceOrType (string name, Location loc, bool ignore_cs0104)
505 return RootContext.ToplevelTypes.LookupNamespaceOrType (name, loc, ignore_cs0104);
508 public FullNamedExpression LookupNamespaceAlias (string name)
510 return null;
513 #endregion
516 public class AssemblyClass : CommonAssemblyModulClass {
517 // TODO: make it private and move all builder based methods here
518 public AssemblyBuilder Builder;
519 bool is_cls_compliant;
520 bool wrap_non_exception_throws;
522 public Attribute ClsCompliantAttribute;
524 ListDictionary declarative_security;
525 bool has_extension_method;
526 public AssemblyName Name;
527 MethodInfo add_type_forwarder;
528 ListDictionary emitted_forwarders;
530 // Module is here just because of error messages
531 static string[] attribute_targets = new string [] { "assembly", "module" };
533 public AssemblyClass ()
535 wrap_non_exception_throws = true;
538 public bool HasExtensionMethods {
539 set {
540 has_extension_method = value;
544 public bool IsClsCompliant {
545 get {
546 return is_cls_compliant;
550 public bool WrapNonExceptionThrows {
551 get {
552 return wrap_non_exception_throws;
556 public override AttributeTargets AttributeTargets {
557 get {
558 return AttributeTargets.Assembly;
562 public override bool IsClsComplianceRequired ()
564 return is_cls_compliant;
567 Report Report {
568 get { return Compiler.Report; }
571 public void Resolve ()
573 if (RootContext.Unsafe) {
575 // Emits [assembly: SecurityPermissionAttribute (SecurityAction.RequestMinimum, SkipVerification = true)]
576 // when -unsafe option was specified
579 Location loc = Location.Null;
581 MemberAccess system_security_permissions = new MemberAccess (new MemberAccess (
582 new QualifiedAliasMember (QualifiedAliasMember.GlobalAlias, "System", loc), "Security", loc), "Permissions", loc);
584 Arguments pos = new Arguments (1);
585 pos.Add (new Argument (new MemberAccess (new MemberAccess (system_security_permissions, "SecurityAction", loc), "RequestMinimum")));
587 Arguments named = new Arguments (1);
588 named.Add (new NamedArgument (new LocatedToken (loc, "SkipVerification"), (new BoolLiteral (true, loc))));
590 GlobalAttribute g = new GlobalAttribute (new NamespaceEntry (null, null, null), "assembly",
591 new MemberAccess (system_security_permissions, "SecurityPermissionAttribute"),
592 new Arguments[] { pos, named }, loc, false);
593 g.AttachTo (this, this);
595 if (g.Resolve () != null) {
596 declarative_security = new ListDictionary ();
597 g.ExtractSecurityPermissionSet (declarative_security);
601 if (OptAttributes == null)
602 return;
604 // Ensure that we only have GlobalAttributes, since the Search isn't safe with other types.
605 if (!OptAttributes.CheckTargets())
606 return;
608 ClsCompliantAttribute = ResolveAttribute (PredefinedAttributes.Get.CLSCompliant);
610 if (ClsCompliantAttribute != null) {
611 is_cls_compliant = ClsCompliantAttribute.GetClsCompliantAttributeValue ();
614 Attribute a = ResolveAttribute (PredefinedAttributes.Get.RuntimeCompatibility);
615 if (a != null) {
616 object val = a.GetPropertyValue ("WrapNonExceptionThrows");
617 if (val != null)
618 wrap_non_exception_throws = (bool) val;
622 // fix bug #56621
623 private void SetPublicKey (AssemblyName an, byte[] strongNameBlob)
625 try {
626 // check for possible ECMA key
627 if (strongNameBlob.Length == 16) {
628 // will be rejected if not "the" ECMA key
629 an.SetPublicKey (strongNameBlob);
631 else {
632 // take it, with or without, a private key
633 RSA rsa = CryptoConvert.FromCapiKeyBlob (strongNameBlob);
634 // and make sure we only feed the public part to Sys.Ref
635 byte[] publickey = CryptoConvert.ToCapiPublicKeyBlob (rsa);
637 // AssemblyName.SetPublicKey requires an additional header
638 byte[] publicKeyHeader = new byte [12] { 0x00, 0x24, 0x00, 0x00, 0x04, 0x80, 0x00, 0x00, 0x94, 0x00, 0x00, 0x00 };
640 byte[] encodedPublicKey = new byte [12 + publickey.Length];
641 Buffer.BlockCopy (publicKeyHeader, 0, encodedPublicKey, 0, 12);
642 Buffer.BlockCopy (publickey, 0, encodedPublicKey, 12, publickey.Length);
643 an.SetPublicKey (encodedPublicKey);
646 catch (Exception) {
647 Error_AssemblySigning ("The specified file `" + RootContext.StrongNameKeyFile + "' is incorrectly encoded");
648 Environment.Exit (1);
652 // TODO: rewrite this code (to kill N bugs and make it faster) and use standard ApplyAttribute way.
653 public AssemblyName GetAssemblyName (string name, string output)
655 if (OptAttributes != null) {
656 foreach (Attribute a in OptAttributes.Attrs) {
657 // cannot rely on any resolve-based members before you call Resolve
658 if (a.ExplicitTarget == null || a.ExplicitTarget != "assembly")
659 continue;
661 // TODO: This code is buggy: comparing Attribute name without resolving is wrong.
662 // However, this is invoked by CodeGen.Init, when none of the namespaces
663 // are loaded yet.
664 // TODO: Does not handle quoted attributes properly
665 switch (a.Name) {
666 case "AssemblyKeyFile":
667 case "AssemblyKeyFileAttribute":
668 case "System.Reflection.AssemblyKeyFileAttribute":
669 if (RootContext.StrongNameKeyFile != null) {
670 Report.SymbolRelatedToPreviousError (a.Location, a.GetSignatureForError ());
671 Report.Warning (1616, 1, "Option `{0}' overrides attribute `{1}' given in a source file or added module",
672 "keyfile", "System.Reflection.AssemblyKeyFileAttribute");
673 } else {
674 string value = a.GetString ();
675 if (value != null && value.Length != 0)
676 RootContext.StrongNameKeyFile = value;
678 break;
679 case "AssemblyKeyName":
680 case "AssemblyKeyNameAttribute":
681 case "System.Reflection.AssemblyKeyNameAttribute":
682 if (RootContext.StrongNameKeyContainer != null) {
683 Report.SymbolRelatedToPreviousError (a.Location, a.GetSignatureForError ());
684 Report.Warning (1616, 1, "Option `{0}' overrides attribute `{1}' given in a source file or added module",
685 "keycontainer", "System.Reflection.AssemblyKeyNameAttribute");
686 } else {
687 string value = a.GetString ();
688 if (value != null && value.Length != 0)
689 RootContext.StrongNameKeyContainer = value;
691 break;
692 case "AssemblyDelaySign":
693 case "AssemblyDelaySignAttribute":
694 case "System.Reflection.AssemblyDelaySignAttribute":
695 RootContext.StrongNameDelaySign = a.GetBoolean ();
696 break;
701 AssemblyName an = new AssemblyName ();
702 an.Name = Path.GetFileNameWithoutExtension (name);
704 // note: delay doesn't apply when using a key container
705 if (RootContext.StrongNameKeyContainer != null) {
706 an.KeyPair = new StrongNameKeyPair (RootContext.StrongNameKeyContainer);
707 return an;
710 // strongname is optional
711 if (RootContext.StrongNameKeyFile == null)
712 return an;
714 string AssemblyDir = Path.GetDirectoryName (output);
716 // the StrongName key file may be relative to (a) the compiled
717 // file or (b) to the output assembly. See bugzilla #55320
718 // http://bugzilla.ximian.com/show_bug.cgi?id=55320
720 // (a) relative to the compiled file
721 string filename = Path.GetFullPath (RootContext.StrongNameKeyFile);
722 bool exist = File.Exists (filename);
723 if ((!exist) && (AssemblyDir != null) && (AssemblyDir != String.Empty)) {
724 // (b) relative to the outputed assembly
725 filename = Path.GetFullPath (Path.Combine (AssemblyDir, RootContext.StrongNameKeyFile));
726 exist = File.Exists (filename);
729 if (exist) {
730 using (FileStream fs = new FileStream (filename, FileMode.Open, FileAccess.Read)) {
731 byte[] snkeypair = new byte [fs.Length];
732 fs.Read (snkeypair, 0, snkeypair.Length);
734 if (RootContext.StrongNameDelaySign) {
735 // delayed signing - DO NOT include private key
736 SetPublicKey (an, snkeypair);
738 else {
739 // no delay so we make sure we have the private key
740 try {
741 CryptoConvert.FromCapiPrivateKeyBlob (snkeypair);
742 an.KeyPair = new StrongNameKeyPair (snkeypair);
744 catch (CryptographicException) {
745 if (snkeypair.Length == 16) {
746 // error # is different for ECMA key
747 Report.Error (1606, "Could not sign the assembly. " +
748 "ECMA key can only be used to delay-sign assemblies");
750 else {
751 Error_AssemblySigning ("The specified file `" + RootContext.StrongNameKeyFile + "' does not have a private key");
753 return null;
758 else {
759 Error_AssemblySigning ("The specified file `" + RootContext.StrongNameKeyFile + "' does not exist");
760 return null;
762 return an;
765 void Error_AssemblySigning (string text)
767 Report.Error (1548, "Error during assembly signing. " + text);
770 bool CheckInternalsVisibleAttribute (Attribute a)
772 string assembly_name = a.GetString ();
773 if (assembly_name.Length == 0)
774 return false;
776 AssemblyName aname = null;
777 try {
778 aname = new AssemblyName (assembly_name);
779 } catch (FileLoadException) {
780 } catch (ArgumentException) {
783 // Bad assembly name format
784 if (aname == null)
785 Report.Warning (1700, 3, a.Location, "Assembly reference `" + assembly_name + "' is invalid and cannot be resolved");
786 // Report error if we have defined Version or Culture
787 else if (aname.Version != null || aname.CultureInfo != null)
788 throw new Exception ("Friend assembly `" + a.GetString () +
789 "' is invalid. InternalsVisibleTo cannot have version or culture specified.");
790 else if (aname.GetPublicKey () == null && Name.GetPublicKey () != null && Name.GetPublicKey ().Length != 0) {
791 Report.Error (1726, a.Location, "Friend assembly reference `" + aname.FullName + "' is invalid." +
792 " Strong named assemblies must specify a public key in their InternalsVisibleTo declarations");
793 return false;
796 return true;
799 static bool IsValidAssemblyVersion (string version)
801 Version v;
802 try {
803 v = new Version (version);
804 } catch {
805 try {
806 int major = int.Parse (version, CultureInfo.InvariantCulture);
807 v = new Version (major, 0);
808 } catch {
809 return false;
813 foreach (int candidate in new int [] { v.Major, v.Minor, v.Build, v.Revision }) {
814 if (candidate > ushort.MaxValue)
815 return false;
818 return true;
821 public override void ApplyAttributeBuilder (Attribute a, CustomAttributeBuilder cb, PredefinedAttributes pa)
823 if (a.IsValidSecurityAttribute ()) {
824 if (declarative_security == null)
825 declarative_security = new ListDictionary ();
827 a.ExtractSecurityPermissionSet (declarative_security);
828 return;
831 if (a.Type == pa.AssemblyCulture) {
832 string value = a.GetString ();
833 if (value == null || value.Length == 0)
834 return;
836 if (RootContext.Target == Target.Exe) {
837 a.Error_AttributeEmitError ("The executables cannot be satelite assemblies, remove the attribute or keep it empty");
838 return;
842 if (a.Type == pa.AssemblyVersion) {
843 string value = a.GetString ();
844 if (value == null || value.Length == 0)
845 return;
847 value = value.Replace ('*', '0');
849 if (!IsValidAssemblyVersion (value)) {
850 a.Error_AttributeEmitError (string.Format ("Specified version `{0}' is not valid", value));
851 return;
855 if (a.Type == pa.InternalsVisibleTo && !CheckInternalsVisibleAttribute (a))
856 return;
858 if (a.Type == pa.TypeForwarder) {
859 Type t = a.GetArgumentType ();
860 if (t == null || TypeManager.HasElementType (t)) {
861 Report.Error (735, a.Location, "Invalid type specified as an argument for TypeForwardedTo attribute");
862 return;
865 t = TypeManager.DropGenericTypeArguments (t);
866 if (emitted_forwarders == null) {
867 emitted_forwarders = new ListDictionary();
868 } else if (emitted_forwarders.Contains(t)) {
869 Report.SymbolRelatedToPreviousError(((Attribute)emitted_forwarders[t]).Location, null);
870 Report.Error(739, a.Location, "A duplicate type forward of type `{0}'",
871 TypeManager.CSharpName(t));
872 return;
875 emitted_forwarders.Add(t, a);
877 if (TypeManager.LookupDeclSpace (t) != null) {
878 Report.SymbolRelatedToPreviousError (t);
879 Report.Error (729, a.Location, "Cannot forward type `{0}' because it is defined in this assembly",
880 TypeManager.CSharpName (t));
881 return;
884 if (t.DeclaringType != null) {
885 Report.Error (730, a.Location, "Cannot forward type `{0}' because it is a nested type",
886 TypeManager.CSharpName (t));
887 return;
890 if (add_type_forwarder == null) {
891 add_type_forwarder = typeof (AssemblyBuilder).GetMethod ("AddTypeForwarder",
892 BindingFlags.NonPublic | BindingFlags.Instance);
894 if (add_type_forwarder == null) {
895 Report.RuntimeMissingSupport (a.Location, "TypeForwardedTo attribute");
896 return;
900 add_type_forwarder.Invoke (Builder, new object[] { t });
901 return;
904 if (a.Type == pa.Extension) {
905 a.Error_MisusedExtensionAttribute ();
906 return;
909 Builder.SetCustomAttribute (cb);
912 public override void Emit (TypeContainer tc)
914 base.Emit (tc);
916 if (has_extension_method)
917 PredefinedAttributes.Get.Extension.EmitAttribute (Builder);
919 // FIXME: Does this belong inside SRE.AssemblyBuilder instead?
920 PredefinedAttribute pa = PredefinedAttributes.Get.RuntimeCompatibility;
921 if (pa.IsDefined && (OptAttributes == null || !OptAttributes.Contains (pa))) {
922 ConstructorInfo ci = TypeManager.GetPredefinedConstructor (
923 pa.Type, Location.Null, Type.EmptyTypes);
924 PropertyInfo [] pis = new PropertyInfo [1];
925 pis [0] = TypeManager.GetPredefinedProperty (pa.Type,
926 "WrapNonExceptionThrows", Location.Null, TypeManager.bool_type);
927 object [] pargs = new object [1];
928 pargs [0] = true;
929 Builder.SetCustomAttribute (new CustomAttributeBuilder (ci, new object [0], pis, pargs));
932 if (declarative_security != null) {
934 MethodInfo add_permission = typeof (AssemblyBuilder).GetMethod ("AddPermissionRequests", BindingFlags.Instance | BindingFlags.NonPublic);
935 object builder_instance = Builder;
937 try {
938 // Microsoft runtime hacking
939 if (add_permission == null) {
940 Type assembly_builder = typeof (AssemblyBuilder).Assembly.GetType ("System.Reflection.Emit.AssemblyBuilderData");
941 add_permission = assembly_builder.GetMethod ("AddPermissionRequests", BindingFlags.Instance | BindingFlags.NonPublic);
943 FieldInfo fi = typeof (AssemblyBuilder).GetField ("m_assemblyData", BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.GetField);
944 builder_instance = fi.GetValue (Builder);
947 object[] args = new object [] { declarative_security [SecurityAction.RequestMinimum],
948 declarative_security [SecurityAction.RequestOptional],
949 declarative_security [SecurityAction.RequestRefuse] };
950 add_permission.Invoke (builder_instance, args);
952 catch {
953 Report.RuntimeMissingSupport (Location.Null, "assembly permission setting");
958 public override string[] ValidAttributeTargets {
959 get {
960 return attribute_targets;
964 // Wrapper for AssemblyBuilder.AddModule
965 static MethodInfo adder_method;
966 static public MethodInfo AddModule_Method {
967 get {
968 if (adder_method == null)
969 adder_method = typeof (AssemblyBuilder).GetMethod ("AddModule", BindingFlags.Instance|BindingFlags.NonPublic);
970 return adder_method;
973 public Module AddModule (string module)
975 MethodInfo m = AddModule_Method;
976 if (m == null) {
977 Report.RuntimeMissingSupport (Location.Null, "/addmodule");
978 Environment.Exit (1);
981 try {
982 return (Module) m.Invoke (Builder, new object [] { module });
983 } catch (TargetInvocationException ex) {
984 throw ex.InnerException;