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 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
)
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
)
189 PortableExecutableKinds pekind
;
190 ImageFileMachine machine
;
192 switch (RootContext
.Platform
) {
194 pekind
= PortableExecutableKinds
.Required32Bit
;
195 machine
= ImageFileMachine
.I386
;
198 pekind
= PortableExecutableKinds
.PE32Plus
;
199 machine
= ImageFileMachine
.AMD64
;
202 pekind
= PortableExecutableKinds
.PE32Plus
;
203 machine
= ImageFileMachine
.IA64
;
205 case Platform
.AnyCPU
:
207 pekind
= PortableExecutableKinds
.ILOnly
;
208 machine
= ImageFileMachine
.I386
;
212 Assembly
.Builder
.Save (Basename (name
), pekind
, machine
);
214 catch (COMException
) {
215 if ((RootContext
.StrongNameKeyFile
== null) || (!RootContext
.StrongNameDelaySign
))
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
);
227 catch (System
.UnauthorizedAccessException ua
) {
228 Report
.Error (16, "Could not write to file `"+name
+"', cause: " + ua
.Message
);
231 catch (System
.NotImplementedException nie
) {
232 Report
.RuntimeMissingSupport (Location
.Null
, nie
.Message
);
237 // Write debuger symbol file
240 SymbolWriter
.WriteSymbolFile ();
245 /// An Emit Context is created for each body of code (from methods,
246 /// properties bodies, indexer bodies or constructor bodies)
248 public class EmitContext
: BuilderContext
250 public ILGenerator ig
;
253 /// The value that is allowed to be returned or NULL if there is no
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)
263 Hashtable temporary_storage
;
266 /// The location where we store the return value.
268 public LocalBuilder return_value
;
271 /// The location where return has to jump to return the
274 public Label ReturnLabel
;
277 /// If we already defined the ReturnLabel
279 public bool HasReturnLabel
;
282 /// Whether we are inside an anonymous method.
284 public AnonymousExpression CurrentAnonymousMethod
;
286 public readonly IMemberContext MemberContext
;
288 public EmitContext (IMemberContext rc
, ILGenerator ig
, Type return_type
)
290 this.MemberContext
= rc
;
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
{
319 /// This is called immediately before emitting an IL opcode to tell the symbol
320 /// writer to which source line this opcode belongs.
322 public void Mark (Location loc
)
324 if (!SymbolWriter
.HasSymbolWriter
|| HasSet (Options
.OmitDebugInfo
) || loc
.IsNull
)
327 SymbolWriter
.MarkSequencePoint (ig
, loc
);
330 public void DefineLocalVariable (string name
, LocalBuilder builder
)
332 SymbolWriter
.DefineLocalVariable (name
, builder
);
335 public void BeginScope ()
338 SymbolWriter
.OpenScope(ig
);
341 public void EndScope ()
344 SymbolWriter
.CloseScope(ig
);
348 /// Returns a temporary storage for a variable of type t as
349 /// a local variable in the current body.
351 public LocalBuilder
GetTemporaryLocal (Type t
)
353 if (temporary_storage
!= null) {
354 object o
= temporary_storage
[t
];
358 o
= s
.Count
== 0 ? null : s
.Pop ();
360 temporary_storage
.Remove (t
);
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
;
376 object o
= temporary_storage
[t
];
378 temporary_storage
[t
] = b
;
381 Stack s
= o
as Stack
;
385 temporary_storage
[t
] = s
;
391 /// Current loop begin and end labels.
393 public Label LoopBegin
, LoopEnd
;
396 /// Default target in a switch statement. Only valid if
399 public Label DefaultTarget
;
402 /// If this is non-null, points to the current switch statement
404 public Switch Switch
;
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.
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;
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
);
443 attributes
.AddAttributes (attrs
);
446 public virtual void Emit (TypeContainer tc
)
448 if (OptAttributes
== null)
451 OptAttributes
.Emit ();
454 protected Attribute
ResolveAttribute (PredefinedAttribute a_type
)
456 Attribute a
= OptAttributes
.Search (a_type
);
463 #region IMemberContext Members
465 public CompilerContext Compiler
{
466 get { return RootContext.ToplevelTypes.Compiler; }
469 public Type CurrentType
{
473 public TypeParameter
[] CurrentTypeParameters
{
477 public TypeContainer CurrentTypeDefinition
{
478 get { return RootContext.ToplevelTypes; }
481 public string GetSignatureForError ()
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
)
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
{
540 has_extension_method
= value;
544 public bool IsClsCompliant
{
546 return is_cls_compliant
;
550 public bool WrapNonExceptionThrows
{
552 return wrap_non_exception_throws
;
556 public override AttributeTargets AttributeTargets
{
558 return AttributeTargets
.Assembly
;
562 public override bool IsClsComplianceRequired ()
564 return is_cls_compliant
;
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)
604 // Ensure that we only have GlobalAttributes, since the Search isn't safe with other types.
605 if (!OptAttributes
.CheckTargets())
608 ClsCompliantAttribute
= ResolveAttribute (PredefinedAttributes
.Get
.CLSCompliant
);
610 if (ClsCompliantAttribute
!= null) {
611 is_cls_compliant
= ClsCompliantAttribute
.GetClsCompliantAttributeValue ();
614 Attribute a
= ResolveAttribute (PredefinedAttributes
.Get
.RuntimeCompatibility
);
616 object val
= a
.GetPropertyValue ("WrapNonExceptionThrows");
618 wrap_non_exception_throws
= (bool) val
;
623 private void SetPublicKey (AssemblyName an
, byte[] strongNameBlob
)
626 // check for possible ECMA key
627 if (strongNameBlob
.Length
== 16) {
628 // will be rejected if not "the" ECMA key
629 an
.SetPublicKey (strongNameBlob
);
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
);
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")
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
664 // TODO: Does not handle quoted attributes properly
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");
674 string value = a
.GetString ();
675 if (value != null && value.Length
!= 0)
676 RootContext
.StrongNameKeyFile
= value;
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");
687 string value = a
.GetString ();
688 if (value != null && value.Length
!= 0)
689 RootContext
.StrongNameKeyContainer
= value;
692 case "AssemblyDelaySign":
693 case "AssemblyDelaySignAttribute":
694 case "System.Reflection.AssemblyDelaySignAttribute":
695 RootContext
.StrongNameDelaySign
= a
.GetBoolean ();
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
);
710 // strongname is optional
711 if (RootContext
.StrongNameKeyFile
== null)
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
);
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
);
739 // no delay so we make sure we have the private key
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");
751 Error_AssemblySigning ("The specified file `" + RootContext
.StrongNameKeyFile
+ "' does not have a private key");
759 Error_AssemblySigning ("The specified file `" + RootContext
.StrongNameKeyFile
+ "' does not exist");
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)
776 AssemblyName aname
= null;
778 aname
= new AssemblyName (assembly_name
);
779 } catch (FileLoadException
) {
780 } catch (ArgumentException
) {
783 // Bad assembly name format
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");
799 static bool IsValidAssemblyVersion (string version
)
803 v
= new Version (version
);
806 int major
= int.Parse (version
, CultureInfo
.InvariantCulture
);
807 v
= new Version (major
, 0);
813 foreach (int candidate
in new int [] { v.Major, v.Minor, v.Build, v.Revision }
) {
814 if (candidate
> ushort.MaxValue
)
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
);
831 if (a
.Type
== pa
.AssemblyCulture
) {
832 string value = a
.GetString ();
833 if (value == null || value.Length
== 0)
836 if (RootContext
.Target
== Target
.Exe
) {
837 a
.Error_AttributeEmitError ("The executables cannot be satelite assemblies, remove the attribute or keep it empty");
842 if (a
.Type
== pa
.AssemblyVersion
) {
843 string value = a
.GetString ();
844 if (value == null || value.Length
== 0)
847 value = value.Replace ('*', '0');
849 if (!IsValidAssemblyVersion (value)) {
850 a
.Error_AttributeEmitError (string.Format ("Specified version `{0}' is not valid", value));
855 if (a
.Type
== pa
.InternalsVisibleTo
&& !CheckInternalsVisibleAttribute (a
))
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");
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
));
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
));
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
));
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");
900 add_type_forwarder
.Invoke (Builder
, new object[] { t }
);
904 if (a
.Type
== pa
.Extension
) {
905 a
.Error_MisusedExtensionAttribute ();
909 Builder
.SetCustomAttribute (cb
);
912 public override void Emit (TypeContainer 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];
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
;
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
);
953 Report
.RuntimeMissingSupport (Location
.Null
, "assembly permission setting");
958 public override string[] ValidAttributeTargets
{
960 return attribute_targets
;
964 // Wrapper for AssemblyBuilder.AddModule
965 static MethodInfo adder_method
;
966 static public MethodInfo AddModule_Method
{
968 if (adder_method
== null)
969 adder_method
= typeof (AssemblyBuilder
).GetMethod ("AddModule", BindingFlags
.Instance
|BindingFlags
.NonPublic
);
973 public Module
AddModule (string module
)
975 MethodInfo m
= AddModule_Method
;
977 Report
.RuntimeMissingSupport (Location
.Null
, "/addmodule");
978 Environment
.Exit (1);
982 return (Module
) m
.Invoke (Builder
, new object [] { module }
);
983 } catch (TargetInvocationException ex
) {
984 throw ex
.InnerException
;