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 (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 (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
)
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 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 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 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 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 Report
.Error (40, "Unexpected debug information initialization error `{0}'",
187 static public void Save (string name
, bool saveDebugInfo
)
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 ();
252 /// An interface to hold all the information needed in the resolving phase.
254 public interface IResolveContext
256 DeclSpace DeclContainer { get; }
257 bool IsInObsoleteScope { get; }
258 bool IsInUnsafeScope { get; }
260 // the declcontainer to lookup for type-parameters. Should only use LookupGeneric on it.
262 // FIXME: This is somewhat of a hack. We don't need a full DeclSpace for this. We just need the
263 // current type parameters in scope. IUIC, that will require us to rewrite GenericMethod.
264 // Maybe we can replace this with a 'LookupGeneric (string)' instead, but we'll have to
265 // handle generic method overrides differently
266 DeclSpace GenericDeclContainer { get; }
270 /// An Emit Context is created for each body of code (from methods,
271 /// properties bodies, indexer bodies or constructor bodies)
273 public class EmitContext
: IResolveContext
{
276 // Holds a varible used during collection or object initialization.
278 public Expression CurrentInitializerVariable
;
280 DeclSpace decl_space
;
282 public DeclSpace TypeContainer
;
283 public ILGenerator ig
;
286 public enum Flags
: int {
288 /// This flag tracks the `checked' state of the compilation,
289 /// it controls whether we should generate code that does overflow
290 /// checking, or if we generate code that ignores overflows.
292 /// The default setting comes from the command line option to generate
293 /// checked or unchecked code plus any source code changes using the
294 /// checked/unchecked statements or expressions. Contrast this with
295 /// the ConstantCheckState flag.
300 /// The constant check state is always set to `true' and cant be changed
301 /// from the command line. The source code can change this setting with
302 /// the `checked' and `unchecked' statements and expressions.
304 ConstantCheckState
= 1 << 1,
306 AllCheckStateFlags
= CheckState
| ConstantCheckState
,
309 /// Whether we are inside an unsafe block
317 /// Whether control flow analysis is enabled
319 DoFlowAnalysis
= 1 << 5,
322 /// Whether control flow analysis is disabled on structs
323 /// (only meaningful when DoFlowAnalysis is set)
325 OmitStructFlowAnalysis
= 1 << 6,
328 /// Indicates the current context is in probing mode, no errors are reported.
330 ProbingMode
= 1 << 7,
333 // Inside field intializer expression
335 InFieldInitializer
= 1 << 8,
337 InferReturnType
= 1 << 9,
339 InCompoundAssignment
= 1 << 10,
341 OmitDebuggingInfo
= 1 << 11
347 /// Whether we are emitting code inside a static or instance method
349 public bool IsStatic
;
352 /// Whether the actual created method is static or instance method.
353 /// Althoug the method might be declared as `static', if an anonymous
354 /// method is involved, we might turn this into an instance method.
356 /// So this reflects the low-level staticness of the method, while
357 /// IsStatic represents the semantic, high-level staticness.
359 //public bool MethodIsStatic;
362 /// The value that is allowed to be returned or NULL if there is no
368 /// Points to the Type (extracted from the TypeContainer) that
369 /// declares this body of code
371 public readonly Type ContainerType
;
374 /// Whether this is generating code for a constructor
376 public bool IsConstructor
;
379 /// Keeps track of the Type to LocalBuilder temporary storage created
380 /// to store structures (used to compute the address of the structure
381 /// value on structure method invocations)
383 public Hashtable temporary_storage
;
385 public Block CurrentBlock
;
387 public int CurrentFile
;
390 /// The location where we store the return value.
392 LocalBuilder return_value
;
395 /// The location where return has to jump to return the
398 public Label ReturnLabel
;
401 /// If we already defined the ReturnLabel
403 public bool HasReturnLabel
;
406 /// Whether we are in a `fixed' initialization
408 public bool InFixedInitializer
;
411 /// Whether we are inside an anonymous method.
413 public AnonymousExpression CurrentAnonymousMethod
;
416 /// Location for this EmitContext
421 /// Inside an enum definition, we do not resolve enumeration values
422 /// to their enumerations, but rather to the underlying type/value
423 /// This is so EnumVal + EnumValB can be evaluated.
425 /// There is no "E operator + (E x, E y)", so during an enum evaluation
426 /// we relax the rules
428 public bool InEnumContext
;
430 public readonly IResolveContext ResolveContext
;
433 /// The current iterator
435 public Iterator CurrentIterator
{
436 get { return CurrentAnonymousMethod as Iterator; }
440 /// Whether we are in the resolving stage or not
448 bool isAnonymousMethodAllowed
= true;
451 FlowBranching current_flow_branching
;
453 static int next_id
= 0;
456 public override string ToString ()
458 return String
.Format ("EmitContext ({0}:{1})", id
,
459 CurrentAnonymousMethod
, loc
);
462 public EmitContext (IResolveContext rc
, DeclSpace parent
, DeclSpace ds
, Location l
, ILGenerator ig
,
463 Type return_type
, int code_flags
, bool is_constructor
)
465 this.ResolveContext
= rc
;
468 TypeContainer
= parent
;
469 this.decl_space
= ds
;
470 if (RootContext
.Checked
)
471 flags
|= Flags
.CheckState
;
472 flags
|= Flags
.ConstantCheckState
;
474 if (return_type
== null)
475 throw new ArgumentNullException ("return_type");
477 IsStatic
= (code_flags
& Modifiers
.STATIC
) != 0;
478 ReturnType
= return_type
;
479 IsConstructor
= is_constructor
;
482 current_phase
= Phase
.Created
;
485 // Can only be null for the ResolveType contexts.
486 ContainerType
= parent
.TypeBuilder
;
487 if (rc
.IsInUnsafeScope
)
488 flags
|= Flags
.InUnsafe
;
493 public EmitContext (IResolveContext rc
, DeclSpace ds
, Location l
, ILGenerator ig
,
494 Type return_type
, int code_flags
, bool is_constructor
)
495 : this (rc
, ds
, ds
, l
, ig
, return_type
, code_flags
, is_constructor
)
499 public EmitContext (IResolveContext rc
, DeclSpace ds
, Location l
, ILGenerator ig
,
500 Type return_type
, int code_flags
)
501 : this (rc
, ds
, ds
, l
, ig
, return_type
, code_flags
, false)
505 // IResolveContext.DeclContainer
506 public DeclSpace DeclContainer
{
507 get { return decl_space; }
508 set { decl_space = value; }
511 // IResolveContext.GenericDeclContainer
512 public DeclSpace GenericDeclContainer
{
513 get { return DeclContainer; }
516 public bool CheckState
{
517 get { return (flags & Flags.CheckState) != 0; }
520 public bool ConstantCheckState
{
521 get { return (flags & Flags.ConstantCheckState) != 0; }
524 public bool InUnsafe
{
525 get { return (flags & Flags.InUnsafe) != 0; }
528 public bool InCatch
{
529 get { return (flags & Flags.InCatch) != 0; }
532 public bool InFinally
{
533 get { return (flags & Flags.InFinally) != 0; }
536 public bool DoFlowAnalysis
{
537 get { return (flags & Flags.DoFlowAnalysis) != 0; }
540 public bool OmitStructFlowAnalysis
{
541 get { return (flags & Flags.OmitStructFlowAnalysis) != 0; }
544 // utility helper for CheckExpr, UnCheckExpr, Checked and Unchecked statements
545 // it's public so that we can use a struct at the callsite
546 public struct FlagsHandle
: IDisposable
549 readonly Flags invmask
, oldval
;
551 public FlagsHandle (EmitContext ec
, Flags flagsToSet
)
552 : this (ec
, flagsToSet
, flagsToSet
)
556 internal FlagsHandle (EmitContext ec
, Flags mask
, Flags val
)
560 oldval
= ec
.flags
& mask
;
561 ec
.flags
= (ec
.flags
& invmask
) | (val
& mask
);
563 if ((mask
& Flags
.ProbingMode
) != 0)
564 Report
.DisableReporting ();
567 public void Dispose ()
569 if ((invmask
& Flags
.ProbingMode
) == 0)
570 Report
.EnableReporting ();
572 ec
.flags
= (ec
.flags
& invmask
) | oldval
;
576 // Temporarily set all the given flags to the given value. Should be used in an 'using' statement
577 public FlagsHandle
Set (Flags flagsToSet
)
579 return new FlagsHandle (this, flagsToSet
);
582 public FlagsHandle
With (Flags bits
, bool enable
)
584 return new FlagsHandle (this, bits
, enable
? bits
: 0);
587 public FlagsHandle
WithFlowAnalysis (bool do_flow_analysis
, bool omit_struct_analysis
)
590 (do_flow_analysis
? Flags
.DoFlowAnalysis
: 0) |
591 (omit_struct_analysis
? Flags
.OmitStructFlowAnalysis
: 0);
592 return new FlagsHandle (this, Flags
.DoFlowAnalysis
| Flags
.OmitStructFlowAnalysis
, newflags
);
596 /// If this is true, then Return and ContextualReturn statements
597 /// will set the ReturnType value based on the expression types
598 /// of each return statement instead of the method return type
599 /// (which is initially null).
601 public bool InferReturnType
{
602 get { return (flags & Flags.InferReturnType) != 0; }
605 // IResolveContext.IsInObsoleteScope
606 public bool IsInObsoleteScope
{
608 // Disables obsolete checks when probing is on
609 return IsInProbingMode
|| ResolveContext
.IsInObsoleteScope
;
613 public bool IsInProbingMode
{
614 get { return (flags & Flags.ProbingMode) != 0; }
617 // IResolveContext.IsInUnsafeScope
618 public bool IsInUnsafeScope
{
619 get { return InUnsafe || ResolveContext.IsInUnsafeScope; }
622 public bool IsAnonymousMethodAllowed
{
623 get { return isAnonymousMethodAllowed; }
624 set { isAnonymousMethodAllowed = value; }
627 public bool IsInFieldInitializer
{
628 get { return (flags & Flags.InFieldInitializer) != 0; }
631 public bool IsInCompoundAssignment
{
632 get { return (flags & Flags.InCompoundAssignment) != 0; }
635 public bool IsVariableCapturingRequired
{
637 return !IsInProbingMode
&& (CurrentBranching
== null || !CurrentBranching
.CurrentUsageVector
.IsUnreachable
);
641 public FlowBranching CurrentBranching
{
642 get { return current_flow_branching; }
645 public bool OmitDebuggingInfo
{
646 get { return (flags & Flags.OmitDebuggingInfo) != 0; }
649 flags
|= Flags
.OmitDebuggingInfo
;
651 flags
&= ~Flags
.OmitDebuggingInfo
;
656 // Starts a new code branching. This inherits the state of all local
657 // variables and parameters from the current branching.
659 public FlowBranching
StartFlowBranching (FlowBranching
.BranchingType type
, Location loc
)
661 current_flow_branching
= FlowBranching
.CreateBranching (CurrentBranching
, type
, null, loc
);
662 return current_flow_branching
;
666 // Starts a new code branching for block `block'.
668 public FlowBranching
StartFlowBranching (Block block
)
670 flags
|= Flags
.DoFlowAnalysis
;
672 current_flow_branching
= FlowBranching
.CreateBranching (
673 CurrentBranching
, FlowBranching
.BranchingType
.Block
, block
, block
.StartLocation
);
674 return current_flow_branching
;
677 public FlowBranchingTryCatch
StartFlowBranching (TryCatch stmt
)
679 FlowBranchingTryCatch branching
= new FlowBranchingTryCatch (CurrentBranching
, stmt
);
680 current_flow_branching
= branching
;
684 public FlowBranchingException
StartFlowBranching (ExceptionStatement stmt
)
686 FlowBranchingException branching
= new FlowBranchingException (CurrentBranching
, stmt
);
687 current_flow_branching
= branching
;
691 public FlowBranchingLabeled
StartFlowBranching (LabeledStatement stmt
)
693 FlowBranchingLabeled branching
= new FlowBranchingLabeled (CurrentBranching
, stmt
);
694 current_flow_branching
= branching
;
698 public FlowBranchingIterator
StartFlowBranching (Iterator iterator
)
700 FlowBranchingIterator branching
= new FlowBranchingIterator (CurrentBranching
, iterator
);
701 current_flow_branching
= branching
;
705 public FlowBranchingToplevel
StartFlowBranching (ToplevelBlock stmt
)
707 FlowBranchingToplevel branching
= new FlowBranchingToplevel (CurrentBranching
, stmt
);
708 current_flow_branching
= branching
;
713 // Ends a code branching. Merges the state of locals and parameters
714 // from all the children of the ending branching.
716 public bool EndFlowBranching ()
718 FlowBranching old
= current_flow_branching
;
719 current_flow_branching
= current_flow_branching
.Parent
;
721 FlowBranching
.UsageVector vector
= current_flow_branching
.MergeChild (old
);
722 return vector
.IsUnreachable
;
726 // Kills the current code branching. This throws away any changed state
727 // information and should only be used in case of an error.
729 // FIXME: this is evil
730 public void KillFlowBranching ()
732 current_flow_branching
= current_flow_branching
.Parent
;
735 public bool MustCaptureVariable (LocalInfo local
)
737 if (CurrentAnonymousMethod
== null)
740 // FIXME: IsIterator is too aggressive, we should capture only if child
741 // block contains yield
742 if (CurrentAnonymousMethod
.IsIterator
)
745 return local
.Block
.Toplevel
!= CurrentBlock
.Toplevel
;
748 public void EmitMeta (ToplevelBlock b
)
753 ReturnLabel
= ig
.DefineLabel ();
757 // Here until we can fix the problem with Mono.CSharp.Switch, which
758 // currently can not cope with ig == null during resolve (which must
759 // be fixed for switch statements to work on anonymous methods).
761 public void EmitTopBlock (IMethodData md
, ToplevelBlock block
)
768 if (ResolveTopBlock (null, block
, md
.ParameterInfo
, md
, out unreachable
)){
769 if (Report
.Errors
> 0)
774 current_phase
= Phase
.Emitting
;
778 EmitResolvedTopBlock (block
, unreachable
);
780 } catch (Exception e
){
781 Console
.WriteLine ("Exception caught by the compiler while emitting:");
782 Console
.WriteLine (" Block that caused the problem begin at: " + block
.loc
);
784 Console
.WriteLine (e
.GetType ().FullName
+ ": " + e
.Message
);
794 public bool ResolveTopBlock (EmitContext anonymous_method_host
, ToplevelBlock block
,
795 ParametersCompiled ip
, IMethodData md
, out bool unreachable
)
798 unreachable
= this.unreachable
;
802 current_phase
= Phase
.Resolving
;
806 CurrentFile
= loc
.File
;
811 if (!block
.ResolveMeta (this, ip
))
814 using (this.With (EmitContext
.Flags
.DoFlowAnalysis
, true)) {
815 FlowBranchingToplevel top_level
;
816 if (anonymous_method_host
!= null)
817 top_level
= new FlowBranchingToplevel (anonymous_method_host
.CurrentBranching
, block
);
819 top_level
= block
.TopLevelBranching
;
821 current_flow_branching
= top_level
;
822 bool ok
= block
.Resolve (this);
823 current_flow_branching
= null;
828 bool flow_unreachable
= top_level
.End ();
829 if (flow_unreachable
)
830 this.unreachable
= unreachable
= true;
833 } catch (Exception e
) {
834 Console
.WriteLine ("Exception caught by the compiler while compiling:");
835 Console
.WriteLine (" Block that caused the problem begin at: " + loc
);
837 if (CurrentBlock
!= null){
838 Console
.WriteLine (" Block being compiled: [{0},{1}]",
839 CurrentBlock
.StartLocation
, CurrentBlock
.EndLocation
);
841 Console
.WriteLine (e
.GetType ().FullName
+ ": " + e
.Message
);
846 if (return_type
!= TypeManager
.void_type
&& !unreachable
) {
847 if (CurrentAnonymousMethod
== null) {
848 Report
.Error (161, md
.Location
, "`{0}': not all code paths return a value", md
.GetSignatureForError ());
850 } else if (!CurrentAnonymousMethod
.IsIterator
) {
851 Report
.Error (1643, CurrentAnonymousMethod
.Location
, "Not all code paths return a value in anonymous method of type `{0}'",
852 CurrentAnonymousMethod
.GetSignatureForError ());
861 public Type ReturnType
{
870 public void EmitResolvedTopBlock (ToplevelBlock block
, bool unreachable
)
876 ig
.MarkLabel (ReturnLabel
);
878 if (return_value
!= null){
879 ig
.Emit (OpCodes
.Ldloc
, return_value
);
880 ig
.Emit (OpCodes
.Ret
);
883 // If `HasReturnLabel' is set, then we already emitted a
884 // jump to the end of the method, so we must emit a `ret'
887 // Unfortunately, System.Reflection.Emit automatically emits
888 // a leave to the end of a finally block. This is a problem
889 // if no code is following the try/finally block since we may
890 // jump to a point after the end of the method.
891 // As a workaround, we're always creating a return label in
895 if (HasReturnLabel
|| !unreachable
) {
896 if (return_type
!= TypeManager
.void_type
)
897 ig
.Emit (OpCodes
.Ldloc
, TemporaryReturn ());
898 ig
.Emit (OpCodes
.Ret
);
904 /// This is called immediately before emitting an IL opcode to tell the symbol
905 /// writer to which source line this opcode belongs.
907 public void Mark (Location loc
)
909 if (!SymbolWriter
.HasSymbolWriter
|| OmitDebuggingInfo
|| loc
.IsNull
)
912 SymbolWriter
.MarkSequencePoint (ig
, loc
);
915 public void DefineLocalVariable (string name
, LocalBuilder builder
)
917 SymbolWriter
.DefineLocalVariable (name
, builder
);
920 public void BeginScope ()
923 SymbolWriter
.OpenScope(ig
);
926 public void EndScope ()
929 SymbolWriter
.CloseScope(ig
);
933 /// Returns a temporary storage for a variable of type t as
934 /// a local variable in the current body.
936 public LocalBuilder
GetTemporaryLocal (Type t
)
938 if (temporary_storage
!= null) {
939 object o
= temporary_storage
[t
];
943 o
= s
.Count
== 0 ? null : s
.Pop ();
945 temporary_storage
.Remove (t
);
949 return (LocalBuilder
) o
;
951 return ig
.DeclareLocal (t
);
954 public void FreeTemporaryLocal (LocalBuilder b
, Type t
)
956 if (temporary_storage
== null) {
957 temporary_storage
= new Hashtable ();
958 temporary_storage
[t
] = b
;
961 object o
= temporary_storage
[t
];
963 temporary_storage
[t
] = b
;
966 Stack s
= o
as Stack
;
970 temporary_storage
[t
] = s
;
976 /// Current loop begin and end labels.
978 public Label LoopBegin
, LoopEnd
;
981 /// Default target in a switch statement. Only valid if
984 public Label DefaultTarget
;
987 /// If this is non-null, points to the current switch statement
989 public Switch Switch
;
992 /// ReturnValue creates on demand the LocalBuilder for the
993 /// return value from the function. By default this is not
994 /// used. This is only required when returns are found inside
995 /// Try or Catch statements.
997 /// This method is typically invoked from the Emit phase, so
998 /// we allow the creation of a return label if it was not
999 /// requested during the resolution phase. Could be cleaned
1000 /// up, but it would replicate a lot of logic in the Emit phase
1001 /// of the code that uses it.
1003 public LocalBuilder
TemporaryReturn ()
1005 if (return_value
== null){
1006 return_value
= ig
.DeclareLocal (return_type
);
1007 if (!HasReturnLabel
){
1008 ReturnLabel
= ig
.DefineLabel ();
1009 HasReturnLabel
= true;
1013 return return_value
;
1017 /// This method is used during the Resolution phase to flag the
1018 /// need to define the ReturnLabel
1020 public void NeedReturnLabel ()
1022 if (current_phase
!= Phase
.Resolving
){
1024 // The reason is that the `ReturnLabel' is declared between
1025 // resolution and emission
1027 throw new Exception ("NeedReturnLabel called from Emit phase, should only be called during Resolve");
1030 if (!HasReturnLabel
)
1031 HasReturnLabel
= true;
1035 public Expression
GetThis (Location loc
)
1038 if (CurrentBlock
!= null)
1039 my_this
= new This (CurrentBlock
, loc
);
1041 my_this
= new This (loc
);
1043 if (!my_this
.ResolveBase (this))
1051 public abstract class CommonAssemblyModulClass
: Attributable
, IResolveContext
{
1053 protected CommonAssemblyModulClass ():
1058 public void AddAttributes (ArrayList attrs
)
1060 foreach (Attribute a
in attrs
)
1063 if (attributes
== null) {
1064 attributes
= new Attributes (attrs
);
1067 attributes
.AddAttributes (attrs
);
1070 public virtual void Emit (TypeContainer tc
)
1072 if (OptAttributes
== null)
1075 OptAttributes
.Emit ();
1078 protected Attribute
ResolveAttribute (PredefinedAttribute a_type
)
1080 Attribute a
= OptAttributes
.Search (a_type
);
1087 public override IResolveContext ResolveContext
{
1088 get { return this; }
1091 #region IResolveContext Members
1093 public DeclSpace DeclContainer
{
1094 get { return RootContext.ToplevelTypes; }
1097 public DeclSpace GenericDeclContainer
{
1098 get { return DeclContainer; }
1101 public bool IsInObsoleteScope
{
1102 get { return false; }
1105 public bool IsInUnsafeScope
{
1106 get { return false; }
1112 public class AssemblyClass
: CommonAssemblyModulClass
{
1113 // TODO: make it private and move all builder based methods here
1114 public AssemblyBuilder Builder
;
1115 bool is_cls_compliant
;
1116 bool wrap_non_exception_throws
;
1118 public Attribute ClsCompliantAttribute
;
1120 ListDictionary declarative_security
;
1121 bool has_extension_method
;
1122 public AssemblyName Name
;
1123 MethodInfo add_type_forwarder
;
1124 ListDictionary emitted_forwarders
;
1126 // Module is here just because of error messages
1127 static string[] attribute_targets
= new string [] { "assembly", "module" }
;
1129 public AssemblyClass (): base ()
1131 wrap_non_exception_throws
= true;
1134 public bool HasExtensionMethods
{
1136 has_extension_method
= value;
1140 public bool IsClsCompliant
{
1142 return is_cls_compliant
;
1146 public bool WrapNonExceptionThrows
{
1148 return wrap_non_exception_throws
;
1152 public override AttributeTargets AttributeTargets
{
1154 return AttributeTargets
.Assembly
;
1158 public override bool IsClsComplianceRequired ()
1160 return is_cls_compliant
;
1163 public void Resolve ()
1165 if (RootContext
.Unsafe
) {
1167 // Emits [assembly: SecurityPermissionAttribute (SecurityAction.RequestMinimum, SkipVerification = true)]
1168 // when -unsafe option was specified
1171 Location loc
= Location
.Null
;
1173 MemberAccess system_security_permissions
= new MemberAccess (new MemberAccess (
1174 new QualifiedAliasMember (QualifiedAliasMember
.GlobalAlias
, "System", loc
), "Security", loc
), "Permissions", loc
);
1176 Arguments pos
= new Arguments (1);
1177 pos
.Add (new Argument (new MemberAccess (new MemberAccess (system_security_permissions
, "SecurityAction", loc
), "RequestMinimum")));
1179 Arguments named
= new Arguments (1);
1180 named
.Add (new NamedArgument (new LocatedToken (loc
, "SkipVerification"), (new BoolLiteral (true, loc
))));
1182 GlobalAttribute g
= new GlobalAttribute (new NamespaceEntry (null, null, null), "assembly", system_security_permissions
,
1183 "SecurityPermissionAttribute", new Arguments
[] { pos, named }
, loc
, false);
1186 if (g
.Resolve () != null) {
1187 declarative_security
= new ListDictionary ();
1188 g
.ExtractSecurityPermissionSet (declarative_security
);
1192 if (OptAttributes
== null)
1195 // Ensure that we only have GlobalAttributes, since the Search isn't safe with other types.
1196 if (!OptAttributes
.CheckTargets())
1199 ClsCompliantAttribute
= ResolveAttribute (PredefinedAttributes
.Get
.CLSCompliant
);
1201 if (ClsCompliantAttribute
!= null) {
1202 is_cls_compliant
= ClsCompliantAttribute
.GetClsCompliantAttributeValue ();
1205 Attribute a
= ResolveAttribute (PredefinedAttributes
.Get
.RuntimeCompatibility
);
1207 object val
= a
.GetPropertyValue ("WrapNonExceptionThrows");
1209 wrap_non_exception_throws
= (bool) val
;
1214 private void SetPublicKey (AssemblyName an
, byte[] strongNameBlob
)
1217 // check for possible ECMA key
1218 if (strongNameBlob
.Length
== 16) {
1219 // will be rejected if not "the" ECMA key
1220 an
.SetPublicKey (strongNameBlob
);
1223 // take it, with or without, a private key
1224 RSA rsa
= CryptoConvert
.FromCapiKeyBlob (strongNameBlob
);
1225 // and make sure we only feed the public part to Sys.Ref
1226 byte[] publickey
= CryptoConvert
.ToCapiPublicKeyBlob (rsa
);
1228 // AssemblyName.SetPublicKey requires an additional header
1229 byte[] publicKeyHeader
= new byte [12] { 0x00, 0x24, 0x00, 0x00, 0x04, 0x80, 0x00, 0x00, 0x94, 0x00, 0x00, 0x00 }
;
1231 byte[] encodedPublicKey
= new byte [12 + publickey
.Length
];
1232 Buffer
.BlockCopy (publicKeyHeader
, 0, encodedPublicKey
, 0, 12);
1233 Buffer
.BlockCopy (publickey
, 0, encodedPublicKey
, 12, publickey
.Length
);
1234 an
.SetPublicKey (encodedPublicKey
);
1238 Error_AssemblySigning ("The specified file `" + RootContext
.StrongNameKeyFile
+ "' is incorrectly encoded");
1239 Environment
.Exit (1);
1243 // TODO: rewrite this code (to kill N bugs and make it faster) and use standard ApplyAttribute way.
1244 public AssemblyName
GetAssemblyName (string name
, string output
)
1246 if (OptAttributes
!= null) {
1247 foreach (Attribute a
in OptAttributes
.Attrs
) {
1248 // cannot rely on any resolve-based members before you call Resolve
1249 if (a
.ExplicitTarget
== null || a
.ExplicitTarget
!= "assembly")
1252 // TODO: This code is buggy: comparing Attribute name without resolving is wrong.
1253 // However, this is invoked by CodeGen.Init, when none of the namespaces
1255 // TODO: Does not handle quoted attributes properly
1257 case "AssemblyKeyFile":
1258 case "AssemblyKeyFileAttribute":
1259 case "System.Reflection.AssemblyKeyFileAttribute":
1260 if (RootContext
.StrongNameKeyFile
!= null) {
1261 Report
.SymbolRelatedToPreviousError (a
.Location
, a
.Name
);
1262 Report
.Warning (1616, 1, "Option `{0}' overrides attribute `{1}' given in a source file or added module",
1263 "keyfile", "System.Reflection.AssemblyKeyFileAttribute");
1265 string value = a
.GetString ();
1266 if (value != null && value.Length
!= 0)
1267 RootContext
.StrongNameKeyFile
= value;
1270 case "AssemblyKeyName":
1271 case "AssemblyKeyNameAttribute":
1272 case "System.Reflection.AssemblyKeyNameAttribute":
1273 if (RootContext
.StrongNameKeyContainer
!= null) {
1274 Report
.SymbolRelatedToPreviousError (a
.Location
, a
.Name
);
1275 Report
.Warning (1616, 1, "Option `{0}' overrides attribute `{1}' given in a source file or added module",
1276 "keycontainer", "System.Reflection.AssemblyKeyNameAttribute");
1278 string value = a
.GetString ();
1279 if (value != null && value.Length
!= 0)
1280 RootContext
.StrongNameKeyContainer
= value;
1283 case "AssemblyDelaySign":
1284 case "AssemblyDelaySignAttribute":
1285 case "System.Reflection.AssemblyDelaySignAttribute":
1286 RootContext
.StrongNameDelaySign
= a
.GetBoolean ();
1292 AssemblyName an
= new AssemblyName ();
1293 an
.Name
= Path
.GetFileNameWithoutExtension (name
);
1295 // note: delay doesn't apply when using a key container
1296 if (RootContext
.StrongNameKeyContainer
!= null) {
1297 an
.KeyPair
= new StrongNameKeyPair (RootContext
.StrongNameKeyContainer
);
1301 // strongname is optional
1302 if (RootContext
.StrongNameKeyFile
== null)
1305 string AssemblyDir
= Path
.GetDirectoryName (output
);
1307 // the StrongName key file may be relative to (a) the compiled
1308 // file or (b) to the output assembly. See bugzilla #55320
1309 // http://bugzilla.ximian.com/show_bug.cgi?id=55320
1311 // (a) relative to the compiled file
1312 string filename
= Path
.GetFullPath (RootContext
.StrongNameKeyFile
);
1313 bool exist
= File
.Exists (filename
);
1314 if ((!exist
) && (AssemblyDir
!= null) && (AssemblyDir
!= String
.Empty
)) {
1315 // (b) relative to the outputed assembly
1316 filename
= Path
.GetFullPath (Path
.Combine (AssemblyDir
, RootContext
.StrongNameKeyFile
));
1317 exist
= File
.Exists (filename
);
1321 using (FileStream fs
= new FileStream (filename
, FileMode
.Open
, FileAccess
.Read
)) {
1322 byte[] snkeypair
= new byte [fs
.Length
];
1323 fs
.Read (snkeypair
, 0, snkeypair
.Length
);
1325 if (RootContext
.StrongNameDelaySign
) {
1326 // delayed signing - DO NOT include private key
1327 SetPublicKey (an
, snkeypair
);
1330 // no delay so we make sure we have the private key
1332 CryptoConvert
.FromCapiPrivateKeyBlob (snkeypair
);
1333 an
.KeyPair
= new StrongNameKeyPair (snkeypair
);
1335 catch (CryptographicException
) {
1336 if (snkeypair
.Length
== 16) {
1337 // error # is different for ECMA key
1338 Report
.Error (1606, "Could not sign the assembly. " +
1339 "ECMA key can only be used to delay-sign assemblies");
1342 Error_AssemblySigning ("The specified file `" + RootContext
.StrongNameKeyFile
+ "' does not have a private key");
1350 Error_AssemblySigning ("The specified file `" + RootContext
.StrongNameKeyFile
+ "' does not exist");
1356 void Error_AssemblySigning (string text
)
1358 Report
.Error (1548, "Error during assembly signing. " + text
);
1361 bool CheckInternalsVisibleAttribute (Attribute a
)
1363 string assembly_name
= a
.GetString ();
1364 if (assembly_name
.Length
== 0)
1367 AssemblyName aname
= null;
1370 aname
= new AssemblyName (assembly_name
);
1372 throw new NotSupportedException ();
1374 } catch (FileLoadException
) {
1375 } catch (ArgumentException
) {
1378 // Bad assembly name format
1380 Report
.Warning (1700, 3, a
.Location
, "Assembly reference `" + assembly_name
+ "' is invalid and cannot be resolved");
1381 // Report error if we have defined Version or Culture
1382 else if (aname
.Version
!= null || aname
.CultureInfo
!= null)
1383 throw new Exception ("Friend assembly `" + a
.GetString () +
1384 "' is invalid. InternalsVisibleTo cannot have version or culture specified.");
1385 else if (aname
.GetPublicKey () == null && Name
.GetPublicKey () != null && Name
.GetPublicKey ().Length
!= 0) {
1386 Report
.Error (1726, a
.Location
, "Friend assembly reference `" + aname
.FullName
+ "' is invalid." +
1387 " Strong named assemblies must specify a public key in their InternalsVisibleTo declarations");
1394 static bool IsValidAssemblyVersion (string version
)
1398 v
= new Version (version
);
1401 int major
= int.Parse (version
, CultureInfo
.InvariantCulture
);
1402 v
= new Version (major
, 0);
1408 foreach (int candidate
in new int [] { v.Major, v.Minor, v.Build, v.Revision }
) {
1409 if (candidate
> ushort.MaxValue
)
1416 public override void ApplyAttributeBuilder (Attribute a
, CustomAttributeBuilder cb
, PredefinedAttributes pa
)
1418 if (a
.IsValidSecurityAttribute ()) {
1419 if (declarative_security
== null)
1420 declarative_security
= new ListDictionary ();
1422 a
.ExtractSecurityPermissionSet (declarative_security
);
1426 if (a
.Type
== pa
.AssemblyCulture
) {
1427 string value = a
.GetString ();
1428 if (value == null || value.Length
== 0)
1431 if (RootContext
.Target
== Target
.Exe
) {
1432 a
.Error_AttributeEmitError ("The executables cannot be satelite assemblies, remove the attribute or keep it empty");
1437 if (a
.Type
== pa
.AssemblyVersion
) {
1438 string value = a
.GetString ();
1439 if (value == null || value.Length
== 0)
1442 value = value.Replace ('*', '0');
1444 if (!IsValidAssemblyVersion (value)) {
1445 a
.Error_AttributeEmitError (string.Format ("Specified version `{0}' is not valid", value));
1450 if (a
.Type
== pa
.InternalsVisibleTo
&& !CheckInternalsVisibleAttribute (a
))
1453 if (a
.Type
== pa
.TypeForwarder
) {
1454 Type t
= a
.GetArgumentType ();
1455 if (t
== null || TypeManager
.HasElementType (t
)) {
1456 Report
.Error (735, a
.Location
, "Invalid type specified as an argument for TypeForwardedTo attribute");
1460 t
= TypeManager
.DropGenericTypeArguments (t
);
1461 if (emitted_forwarders
== null) {
1462 emitted_forwarders
= new ListDictionary();
1463 } else if (emitted_forwarders
.Contains(t
)) {
1464 Report
.SymbolRelatedToPreviousError(((Attribute
)emitted_forwarders
[t
]).Location
, null);
1465 Report
.Error(739, a
.Location
, "A duplicate type forward of type `{0}'",
1466 TypeManager
.CSharpName(t
));
1470 emitted_forwarders
.Add(t
, a
);
1472 if (TypeManager
.LookupDeclSpace (t
) != null) {
1473 Report
.SymbolRelatedToPreviousError (t
);
1474 Report
.Error (729, a
.Location
, "Cannot forward type `{0}' because it is defined in this assembly",
1475 TypeManager
.CSharpName (t
));
1479 if (t
.DeclaringType
!= null) {
1480 Report
.Error (730, a
.Location
, "Cannot forward type `{0}' because it is a nested type",
1481 TypeManager
.CSharpName (t
));
1485 if (add_type_forwarder
== null) {
1486 add_type_forwarder
= typeof (AssemblyBuilder
).GetMethod ("AddTypeForwarder",
1487 BindingFlags
.NonPublic
| BindingFlags
.Instance
);
1489 if (add_type_forwarder
== null) {
1490 Report
.RuntimeMissingSupport (a
.Location
, "TypeForwardedTo attribute");
1495 add_type_forwarder
.Invoke (Builder
, new object[] { t }
);
1499 if (a
.Type
== pa
.Extension
) {
1500 a
.Error_MisusedExtensionAttribute ();
1504 Builder
.SetCustomAttribute (cb
);
1507 public override void Emit (TypeContainer tc
)
1511 if (has_extension_method
)
1512 PredefinedAttributes
.Get
.Extension
.EmitAttribute (Builder
);
1514 // FIXME: Does this belong inside SRE.AssemblyBuilder instead?
1515 PredefinedAttribute pa
= PredefinedAttributes
.Get
.RuntimeCompatibility
;
1516 if (pa
.IsDefined
&& (OptAttributes
== null || !OptAttributes
.Contains (pa
))) {
1517 ConstructorInfo ci
= TypeManager
.GetPredefinedConstructor (
1518 pa
.Type
, Location
.Null
, Type
.EmptyTypes
);
1519 PropertyInfo
[] pis
= new PropertyInfo
[1];
1520 pis
[0] = TypeManager
.GetPredefinedProperty (pa
.Type
,
1521 "WrapNonExceptionThrows", Location
.Null
, TypeManager
.bool_type
);
1522 object [] pargs
= new object [1];
1524 Builder
.SetCustomAttribute (new CustomAttributeBuilder (ci
, new object [0], pis
, pargs
));
1527 if (declarative_security
!= null) {
1529 MethodInfo add_permission
= typeof (AssemblyBuilder
).GetMethod ("AddPermissionRequests", BindingFlags
.Instance
| BindingFlags
.NonPublic
);
1530 object builder_instance
= Builder
;
1533 // Microsoft runtime hacking
1534 if (add_permission
== null) {
1535 Type assembly_builder
= typeof (AssemblyBuilder
).Assembly
.GetType ("System.Reflection.Emit.AssemblyBuilderData");
1536 add_permission
= assembly_builder
.GetMethod ("AddPermissionRequests", BindingFlags
.Instance
| BindingFlags
.NonPublic
);
1538 FieldInfo fi
= typeof (AssemblyBuilder
).GetField ("m_assemblyData", BindingFlags
.Instance
| BindingFlags
.NonPublic
| BindingFlags
.GetField
);
1539 builder_instance
= fi
.GetValue (Builder
);
1542 object[] args
= new object [] { declarative_security
[SecurityAction
.RequestMinimum
],
1543 declarative_security
[SecurityAction
.RequestOptional
],
1544 declarative_security
[SecurityAction
.RequestRefuse
] };
1545 add_permission
.Invoke (builder_instance
, args
);
1548 Report
.RuntimeMissingSupport (Location
.Null
, "assembly permission setting");
1553 public override string[] ValidAttributeTargets
{
1555 return attribute_targets
;
1559 // Wrapper for AssemblyBuilder.AddModule
1560 static MethodInfo adder_method
;
1561 static public MethodInfo AddModule_Method
{
1563 if (adder_method
== null)
1564 adder_method
= typeof (AssemblyBuilder
).GetMethod ("AddModule", BindingFlags
.Instance
|BindingFlags
.NonPublic
);
1565 return adder_method
;
1568 public Module
AddModule (string module
)
1570 MethodInfo m
= AddModule_Method
;
1572 Report
.RuntimeMissingSupport (Location
.Null
, "/addmodule");
1573 Environment
.Exit (1);
1577 return (Module
) m
.Invoke (Builder
, new object [] { module }
);
1578 } catch (TargetInvocationException ex
) {
1579 throw ex
.InnerException
;