2 // codegen.cs: The code generator
5 // Miguel de Icaza (miguel@ximian.com)
7 // Copyright 2001, 2002, 2003 Ximian, Inc.
8 // Copyright 2004 Novell, Inc.
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.
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
{
37 /// Code generator class.
39 public class CodeGen
{
40 static AppDomain current_domain
;
42 public static AssemblyClass Assembly
;
49 public static void Reset ()
51 Assembly
= new AssemblyClass ();
54 public static string Basename (string name
)
56 int pos
= name
.LastIndexOf ('/');
59 return name
.Substring (pos
+ 1);
61 pos
= name
.LastIndexOf ('\\');
63 return name
.Substring (pos
+ 1);
68 public static string Dirname (string name
)
70 int pos
= name
.LastIndexOf ('/');
73 return name
.Substring (0, pos
);
75 pos
= name
.LastIndexOf ('\\');
77 return name
.Substring (0, pos
);
82 static public string FileName
;
85 const AssemblyBuilderAccess COMPILER_ACCESS
= 0;
87 /* Keep this in sync with System.Reflection.Emit.AssemblyBuilder */
88 const AssemblyBuilderAccess COMPILER_ACCESS
= (AssemblyBuilderAccess
) 0x800;
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
)
111 AssemblyName an
= Assembly
.GetAssemblyName (name
, output
);
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 '" +
125 "' does not have a strong name.");
126 //Environment.Exit (1);
131 current_domain
= AppDomain
.CurrentDomain
;
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);
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);
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.
167 RootContext
.ToplevelTypes
.Builder
= Assembly
.Builder
.DefineDynamicModule (
168 Basename (name
), Basename (output
), want_debugging_support
);
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)");
178 } catch (ExecutionEngineException e
) {
179 ctx
.Report
.Error (40, "Unexpected debug information initialization error `{0}'",
187 static public void Save (string name
, bool saveDebugInfo
, Report Report
)
190 PortableExecutableKinds pekind
;
191 ImageFileMachine machine
;
193 switch (RootContext
.Platform
) {
195 pekind
= PortableExecutableKinds
.Required32Bit
;
196 machine
= ImageFileMachine
.I386
;
199 pekind
= PortableExecutableKinds
.PE32Plus
;
200 machine
= ImageFileMachine
.AMD64
;
203 pekind
= PortableExecutableKinds
.PE32Plus
;
204 machine
= ImageFileMachine
.IA64
;
206 case Platform
.AnyCPU
:
208 pekind
= PortableExecutableKinds
.ILOnly
;
209 machine
= ImageFileMachine
.I386
;
215 Assembly
.Builder
.Save (Basename (name
), pekind
, machine
);
217 Assembly
.Builder
.Save (Basename (name
));
220 catch (COMException
) {
221 if ((RootContext
.StrongNameKeyFile
== null) || (!RootContext
.StrongNameDelaySign
))
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
);
233 catch (System
.UnauthorizedAccessException ua
) {
234 Report
.Error (16, "Could not write to file `"+name
+"', cause: " + ua
.Message
);
237 catch (System
.NotImplementedException nie
) {
238 Report
.RuntimeMissingSupport (Location
.Null
, nie
.Message
);
243 // Write debuger symbol file
246 SymbolWriter
.WriteSymbolFile ();
251 /// An Emit Context is created for each body of code (from methods,
252 /// properties bodies, indexer bodies or constructor bodies)
254 public class EmitContext
: BuilderContext
256 public ILGenerator ig
;
259 /// The value that is allowed to be returned or NULL if there is no
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)
269 Hashtable temporary_storage
;
272 /// The location where we store the return value.
274 public LocalBuilder return_value
;
277 /// The location where return has to jump to return the
280 public Label ReturnLabel
;
283 /// If we already defined the ReturnLabel
285 public bool HasReturnLabel
;
288 /// Whether we are inside an anonymous method.
290 public AnonymousExpression CurrentAnonymousMethod
;
292 public readonly IMemberContext MemberContext
;
294 public EmitContext (IMemberContext rc
, ILGenerator ig
, Type return_type
)
296 this.MemberContext
= rc
;
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
{
325 /// This is called immediately before emitting an IL opcode to tell the symbol
326 /// writer to which source line this opcode belongs.
328 public void Mark (Location loc
)
330 if (!SymbolWriter
.HasSymbolWriter
|| HasSet (Options
.OmitDebugInfo
) || loc
.IsNull
)
333 SymbolWriter
.MarkSequencePoint (ig
, loc
);
336 public void DefineLocalVariable (string name
, LocalBuilder builder
)
338 SymbolWriter
.DefineLocalVariable (name
, builder
);
341 public void BeginScope ()
344 SymbolWriter
.OpenScope(ig
);
347 public void EndScope ()
350 SymbolWriter
.CloseScope(ig
);
354 /// Returns a temporary storage for a variable of type t as
355 /// a local variable in the current body.
357 public LocalBuilder
GetTemporaryLocal (Type t
)
359 if (temporary_storage
!= null) {
360 object o
= temporary_storage
[t
];
364 o
= s
.Count
== 0 ? null : s
.Pop ();
366 temporary_storage
.Remove (t
);
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
;
382 object o
= temporary_storage
[t
];
384 temporary_storage
[t
] = b
;
387 Stack s
= o
as Stack
;
391 temporary_storage
[t
] = s
;
397 /// Current loop begin and end labels.
399 public Label LoopBegin
, LoopEnd
;
402 /// Default target in a switch statement. Only valid if
405 public Label DefaultTarget
;
408 /// If this is non-null, points to the current switch statement
410 public Switch Switch
;
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.
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;
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
);
449 attributes
.AddAttributes (attrs
);
452 public virtual void Emit (TypeContainer tc
)
454 if (OptAttributes
== null)
457 OptAttributes
.Emit ();
460 protected Attribute
ResolveAttribute (PredefinedAttribute a_type
)
462 Attribute a
= OptAttributes
.Search (a_type
);
469 #region IMemberContext Members
471 public CompilerContext Compiler
{
472 get { return RootContext.ToplevelTypes.Compiler; }
475 public Type CurrentType
{
479 public TypeParameter
[] CurrentTypeParameters
{
483 public TypeContainer CurrentTypeDefinition
{
484 get { return RootContext.ToplevelTypes; }
487 public string GetSignatureForError ()
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
)
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
{
546 has_extension_method
= value;
550 public bool IsClsCompliant
{
552 return is_cls_compliant
;
556 public bool WrapNonExceptionThrows
{
558 return wrap_non_exception_throws
;
562 public override AttributeTargets AttributeTargets
{
564 return AttributeTargets
.Assembly
;
568 public override bool IsClsComplianceRequired ()
570 return is_cls_compliant
;
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)
610 // Ensure that we only have GlobalAttributes, since the Search isn't safe with other types.
611 if (!OptAttributes
.CheckTargets())
614 ClsCompliantAttribute
= ResolveAttribute (PredefinedAttributes
.Get
.CLSCompliant
);
616 if (ClsCompliantAttribute
!= null) {
617 is_cls_compliant
= ClsCompliantAttribute
.GetClsCompliantAttributeValue ();
620 Attribute a
= ResolveAttribute (PredefinedAttributes
.Get
.RuntimeCompatibility
);
622 object val
= a
.GetPropertyValue ("WrapNonExceptionThrows");
624 wrap_non_exception_throws
= (bool) val
;
629 private void SetPublicKey (AssemblyName an
, byte[] strongNameBlob
)
632 // check for possible ECMA key
633 if (strongNameBlob
.Length
== 16) {
634 // will be rejected if not "the" ECMA key
635 an
.SetPublicKey (strongNameBlob
);
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
);
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")
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
670 // TODO: Does not handle quoted attributes properly
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");
680 string value = a
.GetString ();
681 if (value != null && value.Length
!= 0)
682 RootContext
.StrongNameKeyFile
= value;
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");
693 string value = a
.GetString ();
694 if (value != null && value.Length
!= 0)
695 RootContext
.StrongNameKeyContainer
= value;
698 case "AssemblyDelaySign":
699 case "AssemblyDelaySignAttribute":
700 case "System.Reflection.AssemblyDelaySignAttribute":
701 RootContext
.StrongNameDelaySign
= a
.GetBoolean ();
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
);
716 // strongname is optional
717 if (RootContext
.StrongNameKeyFile
== null)
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
);
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
);
745 // no delay so we make sure we have the private key
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");
757 Error_AssemblySigning ("The specified file `" + RootContext
.StrongNameKeyFile
+ "' does not have a private key");
765 Error_AssemblySigning ("The specified file `" + RootContext
.StrongNameKeyFile
+ "' does not exist");
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)
782 AssemblyName aname
= null;
785 aname
= new AssemblyName (assembly_name
);
787 throw new NotSupportedException ();
789 } catch (FileLoadException
) {
790 } catch (ArgumentException
) {
793 // Bad assembly name format
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");
809 static bool IsValidAssemblyVersion (string version
)
813 v
= new Version (version
);
816 int major
= int.Parse (version
, CultureInfo
.InvariantCulture
);
817 v
= new Version (major
, 0);
823 foreach (int candidate
in new int [] { v.Major, v.Minor, v.Build, v.Revision }
) {
824 if (candidate
> ushort.MaxValue
)
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
);
841 if (a
.Type
== pa
.AssemblyCulture
) {
842 string value = a
.GetString ();
843 if (value == null || value.Length
== 0)
846 if (RootContext
.Target
== Target
.Exe
) {
847 a
.Error_AttributeEmitError ("The executables cannot be satelite assemblies, remove the attribute or keep it empty");
852 if (a
.Type
== pa
.AssemblyVersion
) {
853 string value = a
.GetString ();
854 if (value == null || value.Length
== 0)
857 value = value.Replace ('*', '0');
859 if (!IsValidAssemblyVersion (value)) {
860 a
.Error_AttributeEmitError (string.Format ("Specified version `{0}' is not valid", value));
865 if (a
.Type
== pa
.InternalsVisibleTo
&& !CheckInternalsVisibleAttribute (a
))
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");
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
));
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
));
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
));
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");
910 add_type_forwarder
.Invoke (Builder
, new object[] { t }
);
914 if (a
.Type
== pa
.Extension
) {
915 a
.Error_MisusedExtensionAttribute ();
919 Builder
.SetCustomAttribute (cb
);
922 public override void Emit (TypeContainer 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];
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
;
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
);
963 Report
.RuntimeMissingSupport (Location
.Null
, "assembly permission setting");
968 public override string[] ValidAttributeTargets
{
970 return attribute_targets
;
974 // Wrapper for AssemblyBuilder.AddModule
975 static MethodInfo adder_method
;
976 static public MethodInfo AddModule_Method
{
978 if (adder_method
== null)
979 adder_method
= typeof (AssemblyBuilder
).GetMethod ("AddModule", BindingFlags
.Instance
|BindingFlags
.NonPublic
);
983 public Module
AddModule (string module
)
985 MethodInfo m
= AddModule_Method
;
987 Report
.RuntimeMissingSupport (Location
.Null
, "/addmodule");
988 Environment
.Exit (1);
992 return (Module
) m
.Invoke (Builder
, new object [] { module }
);
993 } catch (TargetInvocationException ex
) {
994 throw ex
.InnerException
;