2009-07-20 Jb Evain <jbevain@novell.com>
[mcs.git] / mcs / codegen.cs
blob39adbb4fa8c9ad12fb75bb7c4265b14fdf6921d6
1 //
2 // codegen.cs: The code generator
3 //
4 // Author:
5 // Miguel de Icaza (miguel@ximian.com)
6 //
7 // Copyright 2001, 2002, 2003 Ximian, Inc.
8 // Copyright 2004 Novell, Inc.
9 //
12 // Please leave this defined on SVN: The idea is that when we ship the
13 // compiler to end users, if the compiler crashes, they have a chance
14 // to narrow down the problem.
16 // Only remove it if you need to debug locally on your tree.
18 //#define PRODUCTION
20 using System;
21 using System.IO;
22 using System.Collections;
23 using System.Collections.Specialized;
24 using System.Globalization;
25 using System.Reflection;
26 using System.Reflection.Emit;
27 using System.Runtime.InteropServices;
28 using System.Security;
29 using System.Security.Cryptography;
30 using System.Security.Permissions;
32 using Mono.Security.Cryptography;
34 namespace Mono.CSharp {
36 /// <summary>
37 /// Code generator class.
38 /// </summary>
39 public class CodeGen {
40 static AppDomain current_domain;
42 public static AssemblyClass Assembly;
44 static CodeGen ()
46 Reset ();
49 public static void Reset ()
51 Assembly = new AssemblyClass ();
54 public static string Basename (string name)
56 int pos = name.LastIndexOf ('/');
58 if (pos != -1)
59 return name.Substring (pos + 1);
61 pos = name.LastIndexOf ('\\');
62 if (pos != -1)
63 return name.Substring (pos + 1);
65 return name;
68 public static string Dirname (string name)
70 int pos = name.LastIndexOf ('/');
72 if (pos != -1)
73 return name.Substring (0, pos);
75 pos = name.LastIndexOf ('\\');
76 if (pos != -1)
77 return name.Substring (0, pos);
79 return ".";
82 static public string FileName;
84 #if MS_COMPATIBLE
85 const AssemblyBuilderAccess COMPILER_ACCESS = 0;
86 #else
87 /* Keep this in sync with System.Reflection.Emit.AssemblyBuilder */
88 const AssemblyBuilderAccess COMPILER_ACCESS = (AssemblyBuilderAccess) 0x800;
89 #endif
92 // Initializes the code generator variables for interactive use (repl)
94 static public void InitDynamic (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)
110 FileName = output;
111 AssemblyName an = Assembly.GetAssemblyName (name, output);
112 if (an == null)
113 return false;
115 if (an.KeyPair != null) {
116 // If we are going to strong name our assembly make
117 // sure all its refs are strong named
118 foreach (Assembly a in GlobalRootNamespace.Instance.Assemblies) {
119 AssemblyName ref_name = a.GetName ();
120 byte [] b = ref_name.GetPublicKeyToken ();
121 if (b == null || b.Length == 0) {
122 Report.Error (1577, "Assembly generation failed " +
123 "-- Referenced assembly '" +
124 ref_name.Name +
125 "' does not have a strong name.");
126 //Environment.Exit (1);
131 current_domain = AppDomain.CurrentDomain;
133 try {
134 Assembly.Builder = current_domain.DefineDynamicAssembly (an,
135 AssemblyBuilderAccess.RunAndSave | COMPILER_ACCESS, Dirname (name));
137 catch (ArgumentException) {
138 // specified key may not be exportable outside it's container
139 if (RootContext.StrongNameKeyContainer != null) {
140 Report.Error (1548, "Could not access the key inside the container `" +
141 RootContext.StrongNameKeyContainer + "'.");
142 Environment.Exit (1);
144 throw;
146 catch (CryptographicException) {
147 if ((RootContext.StrongNameKeyContainer != null) || (RootContext.StrongNameKeyFile != null)) {
148 Report.Error (1548, "Could not use the specified key to strongname the assembly.");
149 Environment.Exit (1);
151 return false;
154 // Get the complete AssemblyName from the builder
155 // (We need to get the public key and token)
156 Assembly.Name = Assembly.Builder.GetName ();
159 // Pass a path-less name to DefineDynamicModule. Wonder how
160 // this copes with output in different directories then.
161 // FIXME: figure out how this copes with --output /tmp/blah
163 // If the third argument is true, the ModuleBuilder will dynamically
164 // load the default symbol writer.
166 try {
167 RootContext.ToplevelTypes.Builder = Assembly.Builder.DefineDynamicModule (
168 Basename (name), Basename (output), want_debugging_support);
170 #if !MS_COMPATIBLE
171 // TODO: We should use SymbolWriter from DefineDynamicModule
172 if (want_debugging_support && !SymbolWriter.Initialize (RootContext.ToplevelTypes.Builder, output)) {
173 Report.Error (40, "Unexpected debug information initialization error `{0}'",
174 "Could not find the symbol writer assembly (Mono.CompilerServices.SymbolWriter.dll)");
175 return false;
177 #endif
178 } catch (ExecutionEngineException e) {
179 Report.Error (40, "Unexpected debug information initialization error `{0}'",
180 e.Message);
181 return false;
184 return true;
187 static public void Save (string name, bool saveDebugInfo)
189 #if GMCS_SOURCE
190 PortableExecutableKinds pekind;
191 ImageFileMachine machine;
193 switch (RootContext.Platform) {
194 case Platform.X86:
195 pekind = PortableExecutableKinds.Required32Bit;
196 machine = ImageFileMachine.I386;
197 break;
198 case Platform.X64:
199 pekind = PortableExecutableKinds.PE32Plus;
200 machine = ImageFileMachine.AMD64;
201 break;
202 case Platform.IA64:
203 pekind = PortableExecutableKinds.PE32Plus;
204 machine = ImageFileMachine.IA64;
205 break;
206 case Platform.AnyCPU:
207 default:
208 pekind = PortableExecutableKinds.ILOnly;
209 machine = ImageFileMachine.I386;
210 break;
212 #endif
213 try {
214 #if GMCS_SOURCE
215 Assembly.Builder.Save (Basename (name), pekind, machine);
216 #else
217 Assembly.Builder.Save (Basename (name));
218 #endif
220 catch (COMException) {
221 if ((RootContext.StrongNameKeyFile == null) || (!RootContext.StrongNameDelaySign))
222 throw;
224 // FIXME: it seems Microsoft AssemblyBuilder doesn't like to delay sign assemblies
225 Report.Error (1548, "Couldn't delay-sign the assembly with the '" +
226 RootContext.StrongNameKeyFile +
227 "', Use MCS with the Mono runtime or CSC to compile this assembly.");
229 catch (System.IO.IOException io) {
230 Report.Error (16, "Could not write to file `"+name+"', cause: " + io.Message);
231 return;
233 catch (System.UnauthorizedAccessException ua) {
234 Report.Error (16, "Could not write to file `"+name+"', cause: " + ua.Message);
235 return;
237 catch (System.NotImplementedException nie) {
238 Report.RuntimeMissingSupport (Location.Null, nie.Message);
239 return;
243 // Write debuger symbol file
245 if (saveDebugInfo)
246 SymbolWriter.WriteSymbolFile ();
251 /// <summary>
252 /// An interface to hold all the information needed in the resolving phase.
253 /// </summary>
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; }
269 /// <summary>
270 /// An Emit Context is created for each body of code (from methods,
271 /// properties bodies, indexer bodies or constructor bodies)
272 /// </summary>
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;
285 [Flags]
286 public enum Flags : int {
287 /// <summary>
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.
296 /// </summary>
297 CheckState = 1 << 0,
299 /// <summary>
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.
303 /// </summary>
304 ConstantCheckState = 1 << 1,
306 AllCheckStateFlags = CheckState | ConstantCheckState,
308 /// <summary>
309 /// Whether we are inside an unsafe block
310 /// </summary>
311 InUnsafe = 1 << 2,
313 InCatch = 1 << 3,
314 InFinally = 1 << 4,
316 /// <summary>
317 /// Whether control flow analysis is enabled
318 /// </summary>
319 DoFlowAnalysis = 1 << 5,
321 /// <summary>
322 /// Whether control flow analysis is disabled on structs
323 /// (only meaningful when DoFlowAnalysis is set)
324 /// </summary>
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
344 Flags flags;
346 /// <summary>
347 /// Whether we are emitting code inside a static or instance method
348 /// </summary>
349 public bool IsStatic;
351 /// <summary>
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.
358 /// </summary>
359 //public bool MethodIsStatic;
361 /// <summary>
362 /// The value that is allowed to be returned or NULL if there is no
363 /// return type.
364 /// </summary>
365 Type return_type;
367 /// <summary>
368 /// Points to the Type (extracted from the TypeContainer) that
369 /// declares this body of code
370 /// </summary>
371 public readonly Type ContainerType;
373 /// <summary>
374 /// Whether this is generating code for a constructor
375 /// </summary>
376 public bool IsConstructor;
378 /// <summary>
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)
382 /// </summary>
383 public Hashtable temporary_storage;
385 public Block CurrentBlock;
387 public int CurrentFile;
389 /// <summary>
390 /// The location where we store the return value.
391 /// </summary>
392 LocalBuilder return_value;
394 /// <summary>
395 /// The location where return has to jump to return the
396 /// value
397 /// </summary>
398 public Label ReturnLabel;
400 /// <summary>
401 /// If we already defined the ReturnLabel
402 /// </summary>
403 public bool HasReturnLabel;
405 /// <summary>
406 /// Whether we are in a `fixed' initialization
407 /// </summary>
408 public bool InFixedInitializer;
410 /// <summary>
411 /// Whether we are inside an anonymous method.
412 /// </summary>
413 public AnonymousExpression CurrentAnonymousMethod;
415 /// <summary>
416 /// Location for this EmitContext
417 /// </summary>
418 public Location loc;
420 /// <summary>
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
427 /// </summary>
428 public bool InEnumContext;
430 public readonly IResolveContext ResolveContext;
432 /// <summary>
433 /// The current iterator
434 /// </summary>
435 public Iterator CurrentIterator {
436 get { return CurrentAnonymousMethod as Iterator; }
439 /// <summary>
440 /// Whether we are in the resolving stage or not
441 /// </summary>
442 enum Phase {
443 Created,
444 Resolving,
445 Emitting
448 bool isAnonymousMethodAllowed = true;
450 Phase current_phase;
451 FlowBranching current_flow_branching;
453 static int next_id = 0;
454 int id = ++next_id;
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;
466 this.ig = ig;
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;
480 CurrentBlock = null;
481 CurrentFile = 0;
482 current_phase = Phase.Created;
484 if (parent != null){
485 // Can only be null for the ResolveType contexts.
486 ContainerType = parent.TypeBuilder;
487 if (rc.IsInUnsafeScope)
488 flags |= Flags.InUnsafe;
490 loc = l;
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
548 EmitContext ec;
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)
558 this.ec = ec;
559 invmask = ~mask;
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)
589 Flags newflags =
590 (do_flow_analysis ? Flags.DoFlowAnalysis : 0) |
591 (omit_struct_analysis ? Flags.OmitStructFlowAnalysis : 0);
592 return new FlagsHandle (this, Flags.DoFlowAnalysis | Flags.OmitStructFlowAnalysis, newflags);
595 /// <summary>
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).
600 /// </summary>
601 public bool InferReturnType {
602 get { return (flags & Flags.InferReturnType) != 0; }
605 // IResolveContext.IsInObsoleteScope
606 public bool IsInObsoleteScope {
607 get {
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 {
636 get {
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; }
647 set {
648 if (value)
649 flags |= Flags.OmitDebuggingInfo;
650 else
651 flags &= ~Flags.OmitDebuggingInfo;
655 // <summary>
656 // Starts a new code branching. This inherits the state of all local
657 // variables and parameters from the current branching.
658 // </summary>
659 public FlowBranching StartFlowBranching (FlowBranching.BranchingType type, Location loc)
661 current_flow_branching = FlowBranching.CreateBranching (CurrentBranching, type, null, loc);
662 return current_flow_branching;
665 // <summary>
666 // Starts a new code branching for block `block'.
667 // </summary>
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;
681 return branching;
684 public FlowBranchingException StartFlowBranching (ExceptionStatement stmt)
686 FlowBranchingException branching = new FlowBranchingException (CurrentBranching, stmt);
687 current_flow_branching = branching;
688 return branching;
691 public FlowBranchingLabeled StartFlowBranching (LabeledStatement stmt)
693 FlowBranchingLabeled branching = new FlowBranchingLabeled (CurrentBranching, stmt);
694 current_flow_branching = branching;
695 return branching;
698 public FlowBranchingIterator StartFlowBranching (Iterator iterator)
700 FlowBranchingIterator branching = new FlowBranchingIterator (CurrentBranching, iterator);
701 current_flow_branching = branching;
702 return branching;
705 public FlowBranchingToplevel StartFlowBranching (ToplevelBlock stmt)
707 FlowBranchingToplevel branching = new FlowBranchingToplevel (CurrentBranching, stmt);
708 current_flow_branching = branching;
709 return branching;
712 // <summary>
713 // Ends a code branching. Merges the state of locals and parameters
714 // from all the children of the ending branching.
715 // </summary>
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;
725 // <summary>
726 // Kills the current code branching. This throws away any changed state
727 // information and should only be used in case of an error.
728 // </summary>
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)
738 return false;
740 // FIXME: IsIterator is too aggressive, we should capture only if child
741 // block contains yield
742 if (CurrentAnonymousMethod.IsIterator)
743 return true;
745 return local.Block.Toplevel != CurrentBlock.Toplevel;
748 public void EmitMeta (ToplevelBlock b)
750 b.EmitMeta (this);
752 if (HasReturnLabel)
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)
763 if (block == null)
764 return;
766 bool unreachable;
768 if (ResolveTopBlock (null, block, md.ParameterInfo, md, out unreachable)){
769 if (Report.Errors > 0)
770 return;
772 EmitMeta (block);
774 current_phase = Phase.Emitting;
775 #if PRODUCTION
776 try {
777 #endif
778 EmitResolvedTopBlock (block, unreachable);
779 #if PRODUCTION
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);
785 throw;
787 #endif
791 bool resolved;
792 bool unreachable;
794 public bool ResolveTopBlock (EmitContext anonymous_method_host, ToplevelBlock block,
795 ParametersCompiled ip, IMethodData md, out bool unreachable)
797 if (resolved) {
798 unreachable = this.unreachable;
799 return true;
802 current_phase = Phase.Resolving;
803 unreachable = false;
805 if (!loc.IsNull)
806 CurrentFile = loc.File;
808 #if PRODUCTION
809 try {
810 #endif
811 if (!block.ResolveMeta (this, ip))
812 return false;
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);
818 else
819 top_level = block.TopLevelBranching;
821 current_flow_branching = top_level;
822 bool ok = block.Resolve (this);
823 current_flow_branching = null;
825 if (!ok)
826 return false;
828 bool flow_unreachable = top_level.End ();
829 if (flow_unreachable)
830 this.unreachable = unreachable = true;
832 #if PRODUCTION
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);
842 throw;
844 #endif
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 ());
849 return false;
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 ());
853 return false;
857 resolved = true;
858 return true;
861 public Type ReturnType {
862 set {
863 return_type = value;
865 get {
866 return return_type;
870 public void EmitResolvedTopBlock (ToplevelBlock block, bool unreachable)
872 if (block != null)
873 block.Emit (this);
875 if (HasReturnLabel)
876 ig.MarkLabel (ReturnLabel);
878 if (return_value != null){
879 ig.Emit (OpCodes.Ldloc, return_value);
880 ig.Emit (OpCodes.Ret);
881 } else {
883 // If `HasReturnLabel' is set, then we already emitted a
884 // jump to the end of the method, so we must emit a `ret'
885 // there.
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
892 // this case.
895 if (HasReturnLabel || !unreachable) {
896 if (return_type != TypeManager.void_type)
897 ig.Emit (OpCodes.Ldloc, TemporaryReturn ());
898 ig.Emit (OpCodes.Ret);
903 /// <summary>
904 /// This is called immediately before emitting an IL opcode to tell the symbol
905 /// writer to which source line this opcode belongs.
906 /// </summary>
907 public void Mark (Location loc)
909 if (!SymbolWriter.HasSymbolWriter || OmitDebuggingInfo || loc.IsNull)
910 return;
912 SymbolWriter.MarkSequencePoint (ig, loc);
915 public void DefineLocalVariable (string name, LocalBuilder builder)
917 SymbolWriter.DefineLocalVariable (name, builder);
920 public void BeginScope ()
922 ig.BeginScope();
923 SymbolWriter.OpenScope(ig);
926 public void EndScope ()
928 ig.EndScope();
929 SymbolWriter.CloseScope(ig);
932 /// <summary>
933 /// Returns a temporary storage for a variable of type t as
934 /// a local variable in the current body.
935 /// </summary>
936 public LocalBuilder GetTemporaryLocal (Type t)
938 if (temporary_storage != null) {
939 object o = temporary_storage [t];
940 if (o != null) {
941 if (o is Stack) {
942 Stack s = (Stack) o;
943 o = s.Count == 0 ? null : s.Pop ();
944 } else {
945 temporary_storage.Remove (t);
948 if (o != null)
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;
959 return;
961 object o = temporary_storage [t];
962 if (o == null) {
963 temporary_storage [t] = b;
964 return;
966 Stack s = o as Stack;
967 if (s == null) {
968 s = new Stack ();
969 s.Push (o);
970 temporary_storage [t] = s;
972 s.Push (b);
975 /// <summary>
976 /// Current loop begin and end labels.
977 /// </summary>
978 public Label LoopBegin, LoopEnd;
980 /// <summary>
981 /// Default target in a switch statement. Only valid if
982 /// InSwitch is true
983 /// </summary>
984 public Label DefaultTarget;
986 /// <summary>
987 /// If this is non-null, points to the current switch statement
988 /// </summary>
989 public Switch Switch;
991 /// <summary>
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.
1002 /// </summary>
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;
1016 /// <summary>
1017 /// This method is used during the Resolution phase to flag the
1018 /// need to define the ReturnLabel
1019 /// </summary>
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)
1037 This my_this;
1038 if (CurrentBlock != null)
1039 my_this = new This (CurrentBlock, loc);
1040 else
1041 my_this = new This (loc);
1043 if (!my_this.ResolveBase (this))
1044 my_this = null;
1046 return my_this;
1051 public abstract class CommonAssemblyModulClass : Attributable, IResolveContext {
1053 protected CommonAssemblyModulClass ():
1054 base (null)
1058 public void AddAttributes (ArrayList attrs)
1060 foreach (Attribute a in attrs)
1061 a.AttachTo (this);
1063 if (attributes == null) {
1064 attributes = new Attributes (attrs);
1065 return;
1067 attributes.AddAttributes (attrs);
1070 public virtual void Emit (TypeContainer tc)
1072 if (OptAttributes == null)
1073 return;
1075 OptAttributes.Emit ();
1078 protected Attribute ResolveAttribute (PredefinedAttribute a_type)
1080 Attribute a = OptAttributes.Search (a_type);
1081 if (a != null) {
1082 a.Resolve ();
1084 return a;
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; }
1109 #endregion
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 {
1135 set {
1136 has_extension_method = value;
1140 public bool IsClsCompliant {
1141 get {
1142 return is_cls_compliant;
1146 public bool WrapNonExceptionThrows {
1147 get {
1148 return wrap_non_exception_throws;
1152 public override AttributeTargets AttributeTargets {
1153 get {
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);
1184 g.AttachTo (this);
1186 if (g.Resolve () != null) {
1187 declarative_security = new ListDictionary ();
1188 g.ExtractSecurityPermissionSet (declarative_security);
1192 if (OptAttributes == null)
1193 return;
1195 // Ensure that we only have GlobalAttributes, since the Search isn't safe with other types.
1196 if (!OptAttributes.CheckTargets())
1197 return;
1199 ClsCompliantAttribute = ResolveAttribute (PredefinedAttributes.Get.CLSCompliant);
1201 if (ClsCompliantAttribute != null) {
1202 is_cls_compliant = ClsCompliantAttribute.GetClsCompliantAttributeValue ();
1205 Attribute a = ResolveAttribute (PredefinedAttributes.Get.RuntimeCompatibility);
1206 if (a != null) {
1207 object val = a.GetPropertyValue ("WrapNonExceptionThrows");
1208 if (val != null)
1209 wrap_non_exception_throws = (bool) val;
1213 // fix bug #56621
1214 private void SetPublicKey (AssemblyName an, byte[] strongNameBlob)
1216 try {
1217 // check for possible ECMA key
1218 if (strongNameBlob.Length == 16) {
1219 // will be rejected if not "the" ECMA key
1220 an.SetPublicKey (strongNameBlob);
1222 else {
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);
1237 catch (Exception) {
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")
1250 continue;
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
1254 // are loaded yet.
1255 // TODO: Does not handle quoted attributes properly
1256 switch (a.Name) {
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");
1264 } else {
1265 string value = a.GetString ();
1266 if (value != null && value.Length != 0)
1267 RootContext.StrongNameKeyFile = value;
1269 break;
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");
1277 } else {
1278 string value = a.GetString ();
1279 if (value != null && value.Length != 0)
1280 RootContext.StrongNameKeyContainer = value;
1282 break;
1283 case "AssemblyDelaySign":
1284 case "AssemblyDelaySignAttribute":
1285 case "System.Reflection.AssemblyDelaySignAttribute":
1286 RootContext.StrongNameDelaySign = a.GetBoolean ();
1287 break;
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);
1298 return an;
1301 // strongname is optional
1302 if (RootContext.StrongNameKeyFile == null)
1303 return an;
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);
1320 if (exist) {
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);
1329 else {
1330 // no delay so we make sure we have the private key
1331 try {
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");
1341 else {
1342 Error_AssemblySigning ("The specified file `" + RootContext.StrongNameKeyFile + "' does not have a private key");
1344 return null;
1349 else {
1350 Error_AssemblySigning ("The specified file `" + RootContext.StrongNameKeyFile + "' does not exist");
1351 return null;
1353 return an;
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)
1365 return false;
1367 AssemblyName aname = null;
1368 try {
1369 #if GMCS_SOURCE
1370 aname = new AssemblyName (assembly_name);
1371 #else
1372 throw new NotSupportedException ();
1373 #endif
1374 } catch (FileLoadException) {
1375 } catch (ArgumentException) {
1378 // Bad assembly name format
1379 if (aname == null)
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");
1388 return false;
1391 return true;
1394 static bool IsValidAssemblyVersion (string version)
1396 Version v;
1397 try {
1398 v = new Version (version);
1399 } catch {
1400 try {
1401 int major = int.Parse (version, CultureInfo.InvariantCulture);
1402 v = new Version (major, 0);
1403 } catch {
1404 return false;
1408 foreach (int candidate in new int [] { v.Major, v.Minor, v.Build, v.Revision }) {
1409 if (candidate > ushort.MaxValue)
1410 return false;
1413 return true;
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);
1423 return;
1426 if (a.Type == pa.AssemblyCulture) {
1427 string value = a.GetString ();
1428 if (value == null || value.Length == 0)
1429 return;
1431 if (RootContext.Target == Target.Exe) {
1432 a.Error_AttributeEmitError ("The executables cannot be satelite assemblies, remove the attribute or keep it empty");
1433 return;
1437 if (a.Type == pa.AssemblyVersion) {
1438 string value = a.GetString ();
1439 if (value == null || value.Length == 0)
1440 return;
1442 value = value.Replace ('*', '0');
1444 if (!IsValidAssemblyVersion (value)) {
1445 a.Error_AttributeEmitError (string.Format ("Specified version `{0}' is not valid", value));
1446 return;
1450 if (a.Type == pa.InternalsVisibleTo && !CheckInternalsVisibleAttribute (a))
1451 return;
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");
1457 return;
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));
1467 return;
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));
1476 return;
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));
1482 return;
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");
1491 return;
1495 add_type_forwarder.Invoke (Builder, new object[] { t });
1496 return;
1499 if (a.Type == pa.Extension) {
1500 a.Error_MisusedExtensionAttribute ();
1501 return;
1504 Builder.SetCustomAttribute (cb);
1507 public override void Emit (TypeContainer tc)
1509 base.Emit (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];
1523 pargs [0] = true;
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;
1532 try {
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);
1547 catch {
1548 Report.RuntimeMissingSupport (Location.Null, "assembly permission setting");
1553 public override string[] ValidAttributeTargets {
1554 get {
1555 return attribute_targets;
1559 // Wrapper for AssemblyBuilder.AddModule
1560 static MethodInfo adder_method;
1561 static public MethodInfo AddModule_Method {
1562 get {
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;
1571 if (m == null) {
1572 Report.RuntimeMissingSupport (Location.Null, "/addmodule");
1573 Environment.Exit (1);
1576 try {
1577 return (Module) m.Invoke (Builder, new object [] { module });
1578 } catch (TargetInvocationException ex) {
1579 throw ex.InnerException;