2010-01-12 Zoltan Varga <vargaz@gmail.com>
[mcs.git] / mcs / codegen.cs
blob52341f168e8d249be608af772558c9ca89892f0c
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 ModuleContainer (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 #if GMCS_SOURCE
190 PortableExecutableKinds pekind;
191 ImageFileMachine machine;
193 switch (RootContext.Platform) {
194 case Platform.X86:
195 pekind = PortableExecutableKinds.Required32Bit;
196 machine = ImageFileMachine.I386;
197 break;
198 case Platform.X64:
199 pekind = PortableExecutableKinds.PE32Plus;
200 machine = ImageFileMachine.AMD64;
201 break;
202 case Platform.IA64:
203 pekind = PortableExecutableKinds.PE32Plus;
204 machine = ImageFileMachine.IA64;
205 break;
206 case Platform.AnyCPU:
207 default:
208 pekind = PortableExecutableKinds.ILOnly;
209 machine = ImageFileMachine.I386;
210 break;
212 #endif
213 try {
214 #if GMCS_SOURCE
215 Assembly.Builder.Save (Basename (name), pekind, machine);
216 #else
217 Assembly.Builder.Save (Basename (name));
218 #endif
220 catch (COMException) {
221 if ((RootContext.StrongNameKeyFile == null) || (!RootContext.StrongNameDelaySign))
222 throw;
224 // FIXME: it seems Microsoft AssemblyBuilder doesn't like to delay sign assemblies
225 Report.Error (1548, "Couldn't delay-sign the assembly with the '" +
226 RootContext.StrongNameKeyFile +
227 "', Use MCS with the Mono runtime or CSC to compile this assembly.");
229 catch (System.IO.IOException io) {
230 Report.Error (16, "Could not write to file `"+name+"', cause: " + io.Message);
231 return;
233 catch (System.UnauthorizedAccessException ua) {
234 Report.Error (16, "Could not write to file `"+name+"', cause: " + ua.Message);
235 return;
237 catch (System.NotImplementedException nie) {
238 Report.RuntimeMissingSupport (Location.Null, nie.Message);
239 return;
243 // Write debuger symbol file
245 if (saveDebugInfo)
246 SymbolWriter.WriteSymbolFile ();
250 /// <summary>
251 /// An Emit Context is created for each body of code (from methods,
252 /// properties bodies, indexer bodies or constructor bodies)
253 /// </summary>
254 public class EmitContext : BuilderContext
256 public ILGenerator ig;
258 /// <summary>
259 /// The value that is allowed to be returned or NULL if there is no
260 /// return type.
261 /// </summary>
262 Type return_type;
264 /// <summary>
265 /// Keeps track of the Type to LocalBuilder temporary storage created
266 /// to store structures (used to compute the address of the structure
267 /// value on structure method invocations)
268 /// </summary>
269 Hashtable temporary_storage;
271 /// <summary>
272 /// The location where we store the return value.
273 /// </summary>
274 public LocalBuilder return_value;
276 /// <summary>
277 /// The location where return has to jump to return the
278 /// value
279 /// </summary>
280 public Label ReturnLabel;
282 /// <summary>
283 /// If we already defined the ReturnLabel
284 /// </summary>
285 public bool HasReturnLabel;
287 /// <summary>
288 /// Whether we are inside an anonymous method.
289 /// </summary>
290 public AnonymousExpression CurrentAnonymousMethod;
292 public readonly IMemberContext MemberContext;
294 public EmitContext (IMemberContext rc, ILGenerator ig, Type return_type)
296 this.MemberContext = rc;
297 this.ig = ig;
299 this.return_type = return_type;
302 public Type CurrentType {
303 get { return MemberContext.CurrentType; }
306 public TypeParameter[] CurrentTypeParameters {
307 get { return MemberContext.CurrentTypeParameters; }
310 public TypeContainer CurrentTypeDefinition {
311 get { return MemberContext.CurrentTypeDefinition; }
314 public bool IsStatic {
315 get { return MemberContext.IsStatic; }
318 public Type ReturnType {
319 get {
320 return return_type;
324 /// <summary>
325 /// This is called immediately before emitting an IL opcode to tell the symbol
326 /// writer to which source line this opcode belongs.
327 /// </summary>
328 public void Mark (Location loc)
330 if (!SymbolWriter.HasSymbolWriter || HasSet (Options.OmitDebugInfo) || loc.IsNull)
331 return;
333 SymbolWriter.MarkSequencePoint (ig, loc);
336 public void DefineLocalVariable (string name, LocalBuilder builder)
338 SymbolWriter.DefineLocalVariable (name, builder);
341 public void BeginScope ()
343 ig.BeginScope();
344 SymbolWriter.OpenScope(ig);
347 public void EndScope ()
349 ig.EndScope();
350 SymbolWriter.CloseScope(ig);
353 /// <summary>
354 /// Returns a temporary storage for a variable of type t as
355 /// a local variable in the current body.
356 /// </summary>
357 public LocalBuilder GetTemporaryLocal (Type t)
359 if (temporary_storage != null) {
360 object o = temporary_storage [t];
361 if (o != null) {
362 if (o is Stack) {
363 Stack s = (Stack) o;
364 o = s.Count == 0 ? null : s.Pop ();
365 } else {
366 temporary_storage.Remove (t);
369 if (o != null)
370 return (LocalBuilder) o;
372 return ig.DeclareLocal (t);
375 public void FreeTemporaryLocal (LocalBuilder b, Type t)
377 if (temporary_storage == null) {
378 temporary_storage = new Hashtable ();
379 temporary_storage [t] = b;
380 return;
382 object o = temporary_storage [t];
383 if (o == null) {
384 temporary_storage [t] = b;
385 return;
387 Stack s = o as Stack;
388 if (s == null) {
389 s = new Stack ();
390 s.Push (o);
391 temporary_storage [t] = s;
393 s.Push (b);
396 /// <summary>
397 /// Current loop begin and end labels.
398 /// </summary>
399 public Label LoopBegin, LoopEnd;
401 /// <summary>
402 /// Default target in a switch statement. Only valid if
403 /// InSwitch is true
404 /// </summary>
405 public Label DefaultTarget;
407 /// <summary>
408 /// If this is non-null, points to the current switch statement
409 /// </summary>
410 public Switch Switch;
412 /// <summary>
413 /// ReturnValue creates on demand the LocalBuilder for the
414 /// return value from the function. By default this is not
415 /// used. This is only required when returns are found inside
416 /// Try or Catch statements.
418 /// This method is typically invoked from the Emit phase, so
419 /// we allow the creation of a return label if it was not
420 /// requested during the resolution phase. Could be cleaned
421 /// up, but it would replicate a lot of logic in the Emit phase
422 /// of the code that uses it.
423 /// </summary>
424 public LocalBuilder TemporaryReturn ()
426 if (return_value == null){
427 return_value = ig.DeclareLocal (return_type);
428 if (!HasReturnLabel){
429 ReturnLabel = ig.DefineLabel ();
430 HasReturnLabel = true;
434 return return_value;
438 public abstract class CommonAssemblyModulClass : Attributable, IMemberContext
440 public void AddAttributes (ArrayList attrs, IMemberContext context)
442 foreach (Attribute a in attrs)
443 a.AttachTo (this, context);
445 if (attributes == null) {
446 attributes = new Attributes (attrs);
447 return;
449 attributes.AddAttributes (attrs);
452 public virtual void Emit (TypeContainer tc)
454 if (OptAttributes == null)
455 return;
457 OptAttributes.Emit ();
460 protected Attribute ResolveAttribute (PredefinedAttribute a_type)
462 Attribute a = OptAttributes.Search (a_type);
463 if (a != null) {
464 a.Resolve ();
466 return a;
469 #region IMemberContext Members
471 public CompilerContext Compiler {
472 get { return RootContext.ToplevelTypes.Compiler; }
475 public Type CurrentType {
476 get { return null; }
479 public TypeParameter[] CurrentTypeParameters {
480 get { return null; }
483 public TypeContainer CurrentTypeDefinition {
484 get { return RootContext.ToplevelTypes; }
487 public string GetSignatureForError ()
489 return "<module>";
492 public bool IsObsolete {
493 get { return false; }
496 public bool IsUnsafe {
497 get { return false; }
500 public bool IsStatic {
501 get { return false; }
504 public ExtensionMethodGroupExpr LookupExtensionMethod (Type extensionType, string name, Location loc)
506 throw new NotImplementedException ();
509 public FullNamedExpression LookupNamespaceOrType (string name, Location loc, bool ignore_cs0104)
511 return RootContext.ToplevelTypes.LookupNamespaceOrType (name, loc, ignore_cs0104);
514 public FullNamedExpression LookupNamespaceAlias (string name)
516 return null;
519 #endregion
522 public class AssemblyClass : CommonAssemblyModulClass {
523 // TODO: make it private and move all builder based methods here
524 public AssemblyBuilder Builder;
525 bool is_cls_compliant;
526 bool wrap_non_exception_throws;
528 public Attribute ClsCompliantAttribute;
530 ListDictionary declarative_security;
531 bool has_extension_method;
532 public AssemblyName Name;
533 MethodInfo add_type_forwarder;
534 ListDictionary emitted_forwarders;
536 // Module is here just because of error messages
537 static string[] attribute_targets = new string [] { "assembly", "module" };
539 public AssemblyClass ()
541 wrap_non_exception_throws = true;
544 public bool HasExtensionMethods {
545 set {
546 has_extension_method = value;
550 public bool IsClsCompliant {
551 get {
552 return is_cls_compliant;
556 public bool WrapNonExceptionThrows {
557 get {
558 return wrap_non_exception_throws;
562 public override AttributeTargets AttributeTargets {
563 get {
564 return AttributeTargets.Assembly;
568 public override bool IsClsComplianceRequired ()
570 return is_cls_compliant;
573 Report Report {
574 get { return Compiler.Report; }
577 public void Resolve ()
579 if (RootContext.Unsafe) {
581 // Emits [assembly: SecurityPermissionAttribute (SecurityAction.RequestMinimum, SkipVerification = true)]
582 // when -unsafe option was specified
585 Location loc = Location.Null;
587 MemberAccess system_security_permissions = new MemberAccess (new MemberAccess (
588 new QualifiedAliasMember (QualifiedAliasMember.GlobalAlias, "System", loc), "Security", loc), "Permissions", loc);
590 Arguments pos = new Arguments (1);
591 pos.Add (new Argument (new MemberAccess (new MemberAccess (system_security_permissions, "SecurityAction", loc), "RequestMinimum")));
593 Arguments named = new Arguments (1);
594 named.Add (new NamedArgument (new LocatedToken (loc, "SkipVerification"), (new BoolLiteral (true, loc))));
596 GlobalAttribute g = new GlobalAttribute (new NamespaceEntry (null, null, null), "assembly",
597 new MemberAccess (system_security_permissions, "SecurityPermissionAttribute"),
598 new Arguments[] { pos, named }, loc, false);
599 g.AttachTo (this, this);
601 if (g.Resolve () != null) {
602 declarative_security = new ListDictionary ();
603 g.ExtractSecurityPermissionSet (declarative_security);
607 if (OptAttributes == null)
608 return;
610 // Ensure that we only have GlobalAttributes, since the Search isn't safe with other types.
611 if (!OptAttributes.CheckTargets())
612 return;
614 ClsCompliantAttribute = ResolveAttribute (PredefinedAttributes.Get.CLSCompliant);
616 if (ClsCompliantAttribute != null) {
617 is_cls_compliant = ClsCompliantAttribute.GetClsCompliantAttributeValue ();
620 Attribute a = ResolveAttribute (PredefinedAttributes.Get.RuntimeCompatibility);
621 if (a != null) {
622 object val = a.GetPropertyValue ("WrapNonExceptionThrows");
623 if (val != null)
624 wrap_non_exception_throws = (bool) val;
628 // fix bug #56621
629 private void SetPublicKey (AssemblyName an, byte[] strongNameBlob)
631 try {
632 // check for possible ECMA key
633 if (strongNameBlob.Length == 16) {
634 // will be rejected if not "the" ECMA key
635 an.SetPublicKey (strongNameBlob);
637 else {
638 // take it, with or without, a private key
639 RSA rsa = CryptoConvert.FromCapiKeyBlob (strongNameBlob);
640 // and make sure we only feed the public part to Sys.Ref
641 byte[] publickey = CryptoConvert.ToCapiPublicKeyBlob (rsa);
643 // AssemblyName.SetPublicKey requires an additional header
644 byte[] publicKeyHeader = new byte [12] { 0x00, 0x24, 0x00, 0x00, 0x04, 0x80, 0x00, 0x00, 0x94, 0x00, 0x00, 0x00 };
646 byte[] encodedPublicKey = new byte [12 + publickey.Length];
647 Buffer.BlockCopy (publicKeyHeader, 0, encodedPublicKey, 0, 12);
648 Buffer.BlockCopy (publickey, 0, encodedPublicKey, 12, publickey.Length);
649 an.SetPublicKey (encodedPublicKey);
652 catch (Exception) {
653 Error_AssemblySigning ("The specified file `" + RootContext.StrongNameKeyFile + "' is incorrectly encoded");
654 Environment.Exit (1);
658 // TODO: rewrite this code (to kill N bugs and make it faster) and use standard ApplyAttribute way.
659 public AssemblyName GetAssemblyName (string name, string output)
661 if (OptAttributes != null) {
662 foreach (Attribute a in OptAttributes.Attrs) {
663 // cannot rely on any resolve-based members before you call Resolve
664 if (a.ExplicitTarget == null || a.ExplicitTarget != "assembly")
665 continue;
667 // TODO: This code is buggy: comparing Attribute name without resolving is wrong.
668 // However, this is invoked by CodeGen.Init, when none of the namespaces
669 // are loaded yet.
670 // TODO: Does not handle quoted attributes properly
671 switch (a.Name) {
672 case "AssemblyKeyFile":
673 case "AssemblyKeyFileAttribute":
674 case "System.Reflection.AssemblyKeyFileAttribute":
675 if (RootContext.StrongNameKeyFile != null) {
676 Report.SymbolRelatedToPreviousError (a.Location, a.GetSignatureForError ());
677 Report.Warning (1616, 1, "Option `{0}' overrides attribute `{1}' given in a source file or added module",
678 "keyfile", "System.Reflection.AssemblyKeyFileAttribute");
679 } else {
680 string value = a.GetString ();
681 if (value != null && value.Length != 0)
682 RootContext.StrongNameKeyFile = value;
684 break;
685 case "AssemblyKeyName":
686 case "AssemblyKeyNameAttribute":
687 case "System.Reflection.AssemblyKeyNameAttribute":
688 if (RootContext.StrongNameKeyContainer != null) {
689 Report.SymbolRelatedToPreviousError (a.Location, a.GetSignatureForError ());
690 Report.Warning (1616, 1, "Option `{0}' overrides attribute `{1}' given in a source file or added module",
691 "keycontainer", "System.Reflection.AssemblyKeyNameAttribute");
692 } else {
693 string value = a.GetString ();
694 if (value != null && value.Length != 0)
695 RootContext.StrongNameKeyContainer = value;
697 break;
698 case "AssemblyDelaySign":
699 case "AssemblyDelaySignAttribute":
700 case "System.Reflection.AssemblyDelaySignAttribute":
701 RootContext.StrongNameDelaySign = a.GetBoolean ();
702 break;
707 AssemblyName an = new AssemblyName ();
708 an.Name = Path.GetFileNameWithoutExtension (name);
710 // note: delay doesn't apply when using a key container
711 if (RootContext.StrongNameKeyContainer != null) {
712 an.KeyPair = new StrongNameKeyPair (RootContext.StrongNameKeyContainer);
713 return an;
716 // strongname is optional
717 if (RootContext.StrongNameKeyFile == null)
718 return an;
720 string AssemblyDir = Path.GetDirectoryName (output);
722 // the StrongName key file may be relative to (a) the compiled
723 // file or (b) to the output assembly. See bugzilla #55320
724 // http://bugzilla.ximian.com/show_bug.cgi?id=55320
726 // (a) relative to the compiled file
727 string filename = Path.GetFullPath (RootContext.StrongNameKeyFile);
728 bool exist = File.Exists (filename);
729 if ((!exist) && (AssemblyDir != null) && (AssemblyDir != String.Empty)) {
730 // (b) relative to the outputed assembly
731 filename = Path.GetFullPath (Path.Combine (AssemblyDir, RootContext.StrongNameKeyFile));
732 exist = File.Exists (filename);
735 if (exist) {
736 using (FileStream fs = new FileStream (filename, FileMode.Open, FileAccess.Read)) {
737 byte[] snkeypair = new byte [fs.Length];
738 fs.Read (snkeypair, 0, snkeypair.Length);
740 if (RootContext.StrongNameDelaySign) {
741 // delayed signing - DO NOT include private key
742 SetPublicKey (an, snkeypair);
744 else {
745 // no delay so we make sure we have the private key
746 try {
747 CryptoConvert.FromCapiPrivateKeyBlob (snkeypair);
748 an.KeyPair = new StrongNameKeyPair (snkeypair);
750 catch (CryptographicException) {
751 if (snkeypair.Length == 16) {
752 // error # is different for ECMA key
753 Report.Error (1606, "Could not sign the assembly. " +
754 "ECMA key can only be used to delay-sign assemblies");
756 else {
757 Error_AssemblySigning ("The specified file `" + RootContext.StrongNameKeyFile + "' does not have a private key");
759 return null;
764 else {
765 Error_AssemblySigning ("The specified file `" + RootContext.StrongNameKeyFile + "' does not exist");
766 return null;
768 return an;
771 void Error_AssemblySigning (string text)
773 Report.Error (1548, "Error during assembly signing. " + text);
776 bool CheckInternalsVisibleAttribute (Attribute a)
778 string assembly_name = a.GetString ();
779 if (assembly_name.Length == 0)
780 return false;
782 AssemblyName aname = null;
783 try {
784 #if GMCS_SOURCE
785 aname = new AssemblyName (assembly_name);
786 #else
787 throw new NotSupportedException ();
788 #endif
789 } catch (FileLoadException) {
790 } catch (ArgumentException) {
793 // Bad assembly name format
794 if (aname == null)
795 Report.Warning (1700, 3, a.Location, "Assembly reference `" + assembly_name + "' is invalid and cannot be resolved");
796 // Report error if we have defined Version or Culture
797 else if (aname.Version != null || aname.CultureInfo != null)
798 throw new Exception ("Friend assembly `" + a.GetString () +
799 "' is invalid. InternalsVisibleTo cannot have version or culture specified.");
800 else if (aname.GetPublicKey () == null && Name.GetPublicKey () != null && Name.GetPublicKey ().Length != 0) {
801 Report.Error (1726, a.Location, "Friend assembly reference `" + aname.FullName + "' is invalid." +
802 " Strong named assemblies must specify a public key in their InternalsVisibleTo declarations");
803 return false;
806 return true;
809 static bool IsValidAssemblyVersion (string version)
811 Version v;
812 try {
813 v = new Version (version);
814 } catch {
815 try {
816 int major = int.Parse (version, CultureInfo.InvariantCulture);
817 v = new Version (major, 0);
818 } catch {
819 return false;
823 foreach (int candidate in new int [] { v.Major, v.Minor, v.Build, v.Revision }) {
824 if (candidate > ushort.MaxValue)
825 return false;
828 return true;
831 public override void ApplyAttributeBuilder (Attribute a, CustomAttributeBuilder cb, PredefinedAttributes pa)
833 if (a.IsValidSecurityAttribute ()) {
834 if (declarative_security == null)
835 declarative_security = new ListDictionary ();
837 a.ExtractSecurityPermissionSet (declarative_security);
838 return;
841 if (a.Type == pa.AssemblyCulture) {
842 string value = a.GetString ();
843 if (value == null || value.Length == 0)
844 return;
846 if (RootContext.Target == Target.Exe) {
847 a.Error_AttributeEmitError ("The executables cannot be satelite assemblies, remove the attribute or keep it empty");
848 return;
852 if (a.Type == pa.AssemblyVersion) {
853 string value = a.GetString ();
854 if (value == null || value.Length == 0)
855 return;
857 value = value.Replace ('*', '0');
859 if (!IsValidAssemblyVersion (value)) {
860 a.Error_AttributeEmitError (string.Format ("Specified version `{0}' is not valid", value));
861 return;
865 if (a.Type == pa.InternalsVisibleTo && !CheckInternalsVisibleAttribute (a))
866 return;
868 if (a.Type == pa.TypeForwarder) {
869 Type t = a.GetArgumentType ();
870 if (t == null || TypeManager.HasElementType (t)) {
871 Report.Error (735, a.Location, "Invalid type specified as an argument for TypeForwardedTo attribute");
872 return;
875 t = TypeManager.DropGenericTypeArguments (t);
876 if (emitted_forwarders == null) {
877 emitted_forwarders = new ListDictionary();
878 } else if (emitted_forwarders.Contains(t)) {
879 Report.SymbolRelatedToPreviousError(((Attribute)emitted_forwarders[t]).Location, null);
880 Report.Error(739, a.Location, "A duplicate type forward of type `{0}'",
881 TypeManager.CSharpName(t));
882 return;
885 emitted_forwarders.Add(t, a);
887 if (TypeManager.LookupDeclSpace (t) != null) {
888 Report.SymbolRelatedToPreviousError (t);
889 Report.Error (729, a.Location, "Cannot forward type `{0}' because it is defined in this assembly",
890 TypeManager.CSharpName (t));
891 return;
894 if (t.DeclaringType != null) {
895 Report.Error (730, a.Location, "Cannot forward type `{0}' because it is a nested type",
896 TypeManager.CSharpName (t));
897 return;
900 if (add_type_forwarder == null) {
901 add_type_forwarder = typeof (AssemblyBuilder).GetMethod ("AddTypeForwarder",
902 BindingFlags.NonPublic | BindingFlags.Instance);
904 if (add_type_forwarder == null) {
905 Report.RuntimeMissingSupport (a.Location, "TypeForwardedTo attribute");
906 return;
910 add_type_forwarder.Invoke (Builder, new object[] { t });
911 return;
914 if (a.Type == pa.Extension) {
915 a.Error_MisusedExtensionAttribute ();
916 return;
919 Builder.SetCustomAttribute (cb);
922 public override void Emit (TypeContainer tc)
924 base.Emit (tc);
926 if (has_extension_method)
927 PredefinedAttributes.Get.Extension.EmitAttribute (Builder);
929 // FIXME: Does this belong inside SRE.AssemblyBuilder instead?
930 PredefinedAttribute pa = PredefinedAttributes.Get.RuntimeCompatibility;
931 if (pa.IsDefined && (OptAttributes == null || !OptAttributes.Contains (pa))) {
932 ConstructorInfo ci = TypeManager.GetPredefinedConstructor (
933 pa.Type, Location.Null, Type.EmptyTypes);
934 PropertyInfo [] pis = new PropertyInfo [1];
935 pis [0] = TypeManager.GetPredefinedProperty (pa.Type,
936 "WrapNonExceptionThrows", Location.Null, TypeManager.bool_type);
937 object [] pargs = new object [1];
938 pargs [0] = true;
939 Builder.SetCustomAttribute (new CustomAttributeBuilder (ci, new object [0], pis, pargs));
942 if (declarative_security != null) {
944 MethodInfo add_permission = typeof (AssemblyBuilder).GetMethod ("AddPermissionRequests", BindingFlags.Instance | BindingFlags.NonPublic);
945 object builder_instance = Builder;
947 try {
948 // Microsoft runtime hacking
949 if (add_permission == null) {
950 Type assembly_builder = typeof (AssemblyBuilder).Assembly.GetType ("System.Reflection.Emit.AssemblyBuilderData");
951 add_permission = assembly_builder.GetMethod ("AddPermissionRequests", BindingFlags.Instance | BindingFlags.NonPublic);
953 FieldInfo fi = typeof (AssemblyBuilder).GetField ("m_assemblyData", BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.GetField);
954 builder_instance = fi.GetValue (Builder);
957 object[] args = new object [] { declarative_security [SecurityAction.RequestMinimum],
958 declarative_security [SecurityAction.RequestOptional],
959 declarative_security [SecurityAction.RequestRefuse] };
960 add_permission.Invoke (builder_instance, args);
962 catch {
963 Report.RuntimeMissingSupport (Location.Null, "assembly permission setting");
968 public override string[] ValidAttributeTargets {
969 get {
970 return attribute_targets;
974 // Wrapper for AssemblyBuilder.AddModule
975 static MethodInfo adder_method;
976 static public MethodInfo AddModule_Method {
977 get {
978 if (adder_method == null)
979 adder_method = typeof (AssemblyBuilder).GetMethod ("AddModule", BindingFlags.Instance|BindingFlags.NonPublic);
980 return adder_method;
983 public Module AddModule (string module)
985 MethodInfo m = AddModule_Method;
986 if (m == null) {
987 Report.RuntimeMissingSupport (Location.Null, "/addmodule");
988 Environment.Exit (1);
991 try {
992 return (Module) m.Invoke (Builder, new object [] { module });
993 } catch (TargetInvocationException ex) {
994 throw ex.InnerException;