d1b42da88e45de6fb8e60dc8248cfb901e626b1c
[mono.git] / mcs / mcs / codegen.cs
1 //
2 // codegen.cs: The code generator
3 //
4 // Author:
5 //   Miguel de Icaza (miguel@ximian.com)
6 //
7 // (C) 2001, 2002, 2003 Ximian, Inc.
8 // (C) 2004 Novell, Inc.
9 //
10
11 #if !DEBUG
12         #define PRODUCTION
13 #endif
14
15 using System;
16 using System.IO;
17 using System.Collections;
18 using System.Collections.Specialized;
19 using System.Reflection;
20 using System.Reflection.Emit;
21 using System.Runtime.InteropServices;
22 using System.Security;
23 using System.Security.Cryptography;
24 using System.Security.Permissions;
25
26 using Mono.Security.Cryptography;
27
28 namespace Mono.CSharp {
29
30         /// <summary>
31         ///    Code generator class.
32         /// </summary>
33         public class CodeGen {
34                 static AppDomain current_domain;
35                 static public SymbolWriter SymbolWriter;
36
37                 public static AssemblyClass Assembly;
38                 public static ModuleClass Module;
39
40                 static CodeGen ()
41                 {
42                         Reset ();
43                 }
44
45                 public static void Reset ()
46                 {
47                         Assembly = new AssemblyClass ();
48                         Module = new ModuleClass (RootContext.Unsafe);
49                 }
50
51                 public static string Basename (string name)
52                 {
53                         int pos = name.LastIndexOf ('/');
54
55                         if (pos != -1)
56                                 return name.Substring (pos + 1);
57
58                         pos = name.LastIndexOf ('\\');
59                         if (pos != -1)
60                                 return name.Substring (pos + 1);
61
62                         return name;
63                 }
64
65                 public static string Dirname (string name)
66                 {
67                         int pos = name.LastIndexOf ('/');
68
69                         if (pos != -1)
70                                 return name.Substring (0, pos);
71
72                         pos = name.LastIndexOf ('\\');
73                         if (pos != -1)
74                                 return name.Substring (0, pos);
75
76                         return ".";
77                 }
78
79                 static public string FileName;
80
81                 //
82                 // Initializes the symbol writer
83                 //
84                 static void InitializeSymbolWriter (string filename)
85                 {
86                         SymbolWriter = SymbolWriter.GetSymbolWriter (Module.Builder, filename);
87
88                         //
89                         // If we got an ISymbolWriter instance, initialize it.
90                         //
91                         if (SymbolWriter == null) {
92                                 Report.Warning (
93                                         -18, 1, "Could not find the symbol writer assembly (Mono.CompilerServices.SymbolWriter.dll). This is normally an installation problem. Please make sure to compile and install the mcs/class/Mono.CompilerServices.SymbolWriter directory.");
94                                 return;
95                         }
96                 }
97
98                 //
99                 // Initializes the code generator variables
100                 //
101                 static public bool Init (string name, string output, bool want_debugging_support)
102                 {
103                         FileName = output;
104                         AssemblyName an = Assembly.GetAssemblyName (name, output);
105                         if (an == null)
106                                 return false;
107
108                         if (an.KeyPair != null) {
109                                 // If we are going to strong name our assembly make
110                                 // sure all its refs are strong named
111                                 foreach (Assembly a in RootNamespace.Global.Assemblies) {
112                                         AssemblyName ref_name = a.GetName ();
113                                         byte [] b = ref_name.GetPublicKeyToken ();
114                                         if (b == null || b.Length == 0) {
115                                                 Report.Error (1577, "Assembly generation failed " +
116                                                                 "-- Referenced assembly '" +
117                                                                 ref_name.Name +
118                                                                 "' does not have a strong name.");
119                                                 //Environment.Exit (1);
120                                         }
121                                 }
122                         }
123                         
124                         current_domain = AppDomain.CurrentDomain;
125
126                         try {
127                                 Assembly.Builder = current_domain.DefineDynamicAssembly (an,
128                                         AssemblyBuilderAccess.Save, Dirname (name));
129                         }
130                         catch (ArgumentException) {
131                                 // specified key may not be exportable outside it's container
132                                 if (RootContext.StrongNameKeyContainer != null) {
133                                         Report.Error (1548, "Could not access the key inside the container `" +
134                                                 RootContext.StrongNameKeyContainer + "'.");
135                                         Environment.Exit (1);
136                                 }
137                                 return false;
138                         }
139                         catch (CryptographicException) {
140                                 if ((RootContext.StrongNameKeyContainer != null) || (RootContext.StrongNameKeyFile != null)) {
141                                         Report.Error (1548, "Could not use the specified key to strongname the assembly.");
142                                         Environment.Exit (1);
143                                 }
144                                 return false;
145                         }
146
147                         //
148                         // Pass a path-less name to DefineDynamicModule.  Wonder how
149                         // this copes with output in different directories then.
150                         // FIXME: figure out how this copes with --output /tmp/blah
151                         //
152                         // If the third argument is true, the ModuleBuilder will dynamically
153                         // load the default symbol writer.
154                         //
155                         Module.Builder = Assembly.Builder.DefineDynamicModule (
156                                 Basename (name), Basename (output), false);
157
158                         if (want_debugging_support)
159                                 InitializeSymbolWriter (output);
160
161                         return true;
162                 }
163
164                 static public void Save (string name)
165                 {
166                         try {
167                                 Assembly.Builder.Save (Basename (name));
168                         }
169                         catch (COMException) {
170                                 if ((RootContext.StrongNameKeyFile == null) || (!RootContext.StrongNameDelaySign))
171                                         throw;
172
173                                 // FIXME: it seems Microsoft AssemblyBuilder doesn't like to delay sign assemblies 
174                                 Report.Error (1548, "Couldn't delay-sign the assembly with the '" +
175                                         RootContext.StrongNameKeyFile +
176                                         "', Use MCS with the Mono runtime or CSC to compile this assembly.");
177                         }
178                         catch (System.IO.IOException io) {
179                                 Report.Error (16, "Could not write to file `"+name+"', cause: " + io.Message);
180                         }
181                         catch (System.UnauthorizedAccessException ua) {
182                                 Report.Error (16, "Could not write to file `"+name+"', cause: " + ua.Message);
183                         }
184
185                         if (SymbolWriter != null)
186                                 SymbolWriter.WriteSymbolFile ();
187                 }
188         }
189
190
191         public interface IResolveContext
192         {
193                 DeclSpace DeclContainer { get; }
194                 bool IsInObsoleteScope { get; }
195                 bool IsInUnsafeScope { get; }
196         }
197
198         /// <summary>
199         ///   An Emit Context is created for each body of code (from methods,
200         ///   properties bodies, indexer bodies or constructor bodies)
201         /// </summary>
202         public class EmitContext : IResolveContext {
203
204                 DeclSpace declSpace;
205                 public DeclSpace TypeContainer;
206                 public ILGenerator   ig;
207
208                 /// <summary>
209                 ///   This variable tracks the `checked' state of the compilation,
210                 ///   it controls whether we should generate code that does overflow
211                 ///   checking, or if we generate code that ignores overflows.
212                 ///
213                 ///   The default setting comes from the command line option to generate
214                 ///   checked or unchecked code plus any source code changes using the
215                 ///   checked/unchecked statements or expressions.   Contrast this with
216                 ///   the ConstantCheckState flag.
217                 /// </summary>
218                 
219                 public bool CheckState;
220
221                 /// <summary>
222                 ///   The constant check state is always set to `true' and cant be changed
223                 ///   from the command line.  The source code can change this setting with
224                 ///   the `checked' and `unchecked' statements and expressions. 
225                 /// </summary>
226                 public bool ConstantCheckState;
227
228                 /// <summary>
229                 ///   Whether we are emitting code inside a static or instance method
230                 /// </summary>
231                 public bool IsStatic;
232
233                 /// <summary>
234                 ///   Whether the actual created method is static or instance method.
235                 ///   Althoug the method might be declared as `static', if an anonymous
236                 ///   method is involved, we might turn this into an instance method.
237                 ///
238                 ///   So this reflects the low-level staticness of the method, while
239                 ///   IsStatic represents the semantic, high-level staticness.
240                 /// </summary>
241                 public bool MethodIsStatic;
242
243                 /// <summary>
244                 ///   Whether we are emitting a field initializer
245                 /// </summary>
246                 public bool IsFieldInitializer;
247
248                 /// <summary>
249                 ///   The value that is allowed to be returned or NULL if there is no
250                 ///   return type.
251                 /// </summary>
252                 public Type ReturnType;
253
254                 /// <summary>
255                 ///   Points to the Type (extracted from the TypeContainer) that
256                 ///   declares this body of code
257                 /// </summary>
258                 public Type ContainerType;
259                 
260                 /// <summary>
261                 ///   Whether this is generating code for a constructor
262                 /// </summary>
263                 public bool IsConstructor;
264
265                 /// <summary>
266                 ///   Whether we're control flow analysis enabled
267                 /// </summary>
268                 public bool DoFlowAnalysis;
269
270                 /// <summary>
271                 ///   Whether we're control flow analysis disabled on struct
272                 /// </summary>
273                 public bool OmitStructFlowAnalysis;
274
275                 /// <summary>
276                 ///   Keeps track of the Type to LocalBuilder temporary storage created
277                 ///   to store structures (used to compute the address of the structure
278                 ///   value on structure method invocations)
279                 /// </summary>
280                 public Hashtable temporary_storage;
281
282                 public Block CurrentBlock;
283
284                 public int CurrentFile;
285
286                 /// <summary>
287                 ///   The location where we store the return value.
288                 /// </summary>
289                 LocalBuilder return_value;
290
291                 /// <summary>
292                 ///   The location where return has to jump to return the
293                 ///   value
294                 /// </summary>
295                 public Label ReturnLabel;
296
297                 /// <summary>
298                 ///   If we already defined the ReturnLabel
299                 /// </summary>
300                 public bool HasReturnLabel;
301
302                 /// <summary>
303                 ///   Whether we are inside an iterator block.
304                 /// </summary>
305                 public bool InIterator;
306
307                 public bool IsLastStatement;
308
309                 /// <summary>
310                 ///  Whether we are inside an unsafe block
311                 /// </summary>
312                 public bool InUnsafe;
313
314                 /// <summary>
315                 ///  Whether we are in a `fixed' initialization
316                 /// </summary>
317                 public bool InFixedInitializer;
318
319                 public bool InRefOutArgumentResolving;
320
321                 public bool InCatch;
322                 public bool InFinally;
323
324                 /// <summary>
325                 ///  Whether we are inside an anonymous method.
326                 /// </summary>
327                 public AnonymousContainer CurrentAnonymousMethod;
328                 
329                 /// <summary>
330                 ///   Location for this EmitContext
331                 /// </summary>
332                 public Location loc;
333
334                 /// <summary>
335                 ///   Inside an enum definition, we do not resolve enumeration values
336                 ///   to their enumerations, but rather to the underlying type/value
337                 ///   This is so EnumVal + EnumValB can be evaluated.
338                 ///
339                 ///   There is no "E operator + (E x, E y)", so during an enum evaluation
340                 ///   we relax the rules
341                 /// </summary>
342                 public bool InEnumContext;
343
344                 /// <summary>
345                 ///   Anonymous methods can capture local variables and fields,
346                 ///   this object tracks it.  It is copied from the TopLevelBlock
347                 ///   field.
348                 /// </summary>
349                 public CaptureContext capture_context;
350
351                 public readonly IResolveContext ResolveContext;
352
353                 /// <summary>
354                 ///    The current iterator
355                 /// </summary>
356                 public Iterator CurrentIterator;
357
358                 /// <summary>
359                 ///    Whether we are in the resolving stage or not
360                 /// </summary>
361                 enum Phase {
362                         Created,
363                         Resolving,
364                         Emitting
365                 }
366                 
367                 Phase current_phase;
368                 FlowBranching current_flow_branching;
369
370                 static int next_id = 0;
371                 int id = ++next_id;
372
373                 public override string ToString ()
374                 {
375                         return String.Format ("EmitContext ({0}:{1}:{2})", id,
376                                               CurrentIterator, capture_context, loc);
377                 }
378                 
379                 public EmitContext (IResolveContext rc, DeclSpace parent, DeclSpace ds, Location l, ILGenerator ig,
380                                     Type return_type, int code_flags, bool is_constructor)
381                 {
382                         this.ResolveContext = rc;
383                         this.ig = ig;
384
385                         TypeContainer = parent;
386                         this.declSpace = ds;
387                         CheckState = RootContext.Checked;
388                         ConstantCheckState = true;
389
390                         IsStatic = (code_flags & Modifiers.STATIC) != 0;
391                         MethodIsStatic = IsStatic;
392                         InIterator = (code_flags & Modifiers.METHOD_YIELDS) != 0;
393                         ReturnType = return_type;
394                         IsConstructor = is_constructor;
395                         CurrentBlock = null;
396                         CurrentFile = 0;
397                         current_phase = Phase.Created;
398                         
399                         if (parent != null){
400                                 // Can only be null for the ResolveType contexts.
401                                 ContainerType = parent.TypeBuilder;
402                                 InUnsafe = rc.IsInUnsafeScope;
403                         }
404                         loc = l;
405
406                         if (ReturnType == TypeManager.void_type)
407                                 ReturnType = null;
408                 }
409
410                 public EmitContext (IResolveContext rc, DeclSpace ds, Location l, ILGenerator ig,
411                                     Type return_type, int code_flags, bool is_constructor)
412                         : this (rc, ds, ds, l, ig, return_type, code_flags, is_constructor)
413                 {
414                 }
415
416                 public EmitContext (IResolveContext rc, DeclSpace ds, Location l, ILGenerator ig,
417                                     Type return_type, int code_flags)
418                         : this (rc, ds, ds, l, ig, return_type, code_flags, false)
419                 {
420                 }
421
422                 public DeclSpace DeclContainer { 
423                         get { return declSpace; }
424                         set { declSpace = value; }
425                 }
426
427                 public bool IsInObsoleteScope {
428                         get { return ResolveContext.IsInObsoleteScope; }
429                 }
430
431                 public bool IsInUnsafeScope {
432                         get { return InUnsafe || ResolveContext.IsInUnsafeScope; }
433                 }
434
435
436                 public FlowBranching CurrentBranching {
437                         get { return current_flow_branching; }
438                 }
439
440                 public bool HaveCaptureInfo {
441                         get { return capture_context != null; }
442                 }
443
444                 public void EmitScopeInitFromBlock (Block b)
445                 {
446                         if (capture_context != null)
447                                 capture_context.EmitScopeInitFromBlock (this, b);
448                 }
449
450                 // <summary>
451                 //   Starts a new code branching.  This inherits the state of all local
452                 //   variables and parameters from the current branching.
453                 // </summary>
454                 public FlowBranching StartFlowBranching (FlowBranching.BranchingType type, Location loc)
455                 {
456                         current_flow_branching = FlowBranching.CreateBranching (CurrentBranching, type, null, loc);
457                         return current_flow_branching;
458                 }
459
460                 // <summary>
461                 //   Starts a new code branching for block `block'.
462                 // </summary>
463                 public FlowBranching StartFlowBranching (Block block)
464                 {
465                         FlowBranching.BranchingType type;
466
467                         if ((CurrentBranching != null) &&
468                             (CurrentBranching.Type == FlowBranching.BranchingType.Switch))
469                                 type = FlowBranching.BranchingType.SwitchSection;
470                         else
471                                 type = FlowBranching.BranchingType.Block;
472
473                         DoFlowAnalysis = true;
474
475                         current_flow_branching = FlowBranching.CreateBranching (
476                                 CurrentBranching, type, block, block.StartLocation);
477                         return current_flow_branching;
478                 }
479
480                 public FlowBranchingException StartFlowBranching (ExceptionStatement stmt)
481                 {
482                         FlowBranchingException branching = new FlowBranchingException (
483                                 CurrentBranching, stmt);
484                         current_flow_branching = branching;
485                         return branching;
486                 }
487
488                 // <summary>
489                 //   Ends a code branching.  Merges the state of locals and parameters
490                 //   from all the children of the ending branching.
491                 // </summary>
492                 public FlowBranching.UsageVector DoEndFlowBranching ()
493                 {
494                         FlowBranching old = current_flow_branching;
495                         current_flow_branching = current_flow_branching.Parent;
496
497                         return current_flow_branching.MergeChild (old);
498                 }
499
500                 // <summary>
501                 //   Ends a code branching.  Merges the state of locals and parameters
502                 //   from all the children of the ending branching.
503                 // </summary>
504                 public FlowBranching.Reachability EndFlowBranching ()
505                 {
506                         FlowBranching.UsageVector vector = DoEndFlowBranching ();
507
508                         return vector.Reachability;
509                 }
510
511                 // <summary>
512                 //   Kills the current code branching.  This throws away any changed state
513                 //   information and should only be used in case of an error.
514                 // </summary>
515                 public void KillFlowBranching ()
516                 {
517                         current_flow_branching = current_flow_branching.Parent;
518                 }
519
520                 public void CaptureVariable (LocalInfo li)
521                 {
522                         capture_context.AddLocal (CurrentAnonymousMethod, li);
523                         li.IsCaptured = true;
524                 }
525
526                 public void CaptureParameter (string name, Type t, int idx)
527                 {
528                         capture_context.AddParameter (this, CurrentAnonymousMethod, name, t, idx);
529                 }
530
531                 public void CaptureThis ()
532                 {
533                         capture_context.CaptureThis (CurrentAnonymousMethod);
534                 }
535                 
536                 
537                 //
538                 // Use to register a field as captured
539                 //
540                 public void CaptureField (FieldExpr fe)
541                 {
542                         capture_context.AddField (this, CurrentAnonymousMethod, fe);
543                 }
544
545                 //
546                 // Whether anonymous methods have captured variables
547                 //
548                 public bool HaveCapturedVariables ()
549                 {
550                         if (capture_context != null)
551                                 return capture_context.HaveCapturedVariables;
552                         return false;
553                 }
554
555                 //
556                 // Whether anonymous methods have captured fields or this.
557                 //
558                 public bool HaveCapturedFields ()
559                 {
560                         if (capture_context != null)
561                                 return capture_context.HaveCapturedFields;
562                         return false;
563                 }
564
565                 //
566                 // Emits the instance pointer for the host method
567                 //
568                 public void EmitMethodHostInstance (EmitContext target, AnonymousMethod am)
569                 {
570                         if (capture_context != null)
571                                 capture_context.EmitMethodHostInstance (target, am);
572                         else if (IsStatic)
573                                 target.ig.Emit (OpCodes.Ldnull);
574                         else
575                                 target.ig.Emit (OpCodes.Ldarg_0);
576                 }
577
578                 //
579                 // Returns whether the `local' variable has been captured by an anonymous
580                 // method
581                 //
582                 public bool IsCaptured (LocalInfo local)
583                 {
584                         return capture_context.IsCaptured (local);
585                 }
586
587                 public bool IsParameterCaptured (string name)
588                 {
589                         if (capture_context != null)
590                                 return capture_context.IsParameterCaptured (name);
591                         return false;
592                 }
593                 
594                 public void EmitMeta (ToplevelBlock b)
595                 {
596                         if (capture_context != null)
597                                 capture_context.EmitAnonymousHelperClasses (this);
598                         b.EmitMeta (this);
599
600                         if (HasReturnLabel)
601                                 ReturnLabel = ig.DefineLabel ();
602                 }
603
604                 //
605                 // Here until we can fix the problem with Mono.CSharp.Switch, which
606                 // currently can not cope with ig == null during resolve (which must
607                 // be fixed for switch statements to work on anonymous methods).
608                 //
609                 public void EmitTopBlock (IMethodData md, ToplevelBlock block)
610                 {
611                         if (block == null)
612                                 return;
613                         
614                         bool unreachable;
615                         
616                         if (ResolveTopBlock (null, block, md.ParameterInfo, md, out unreachable)){
617                                 EmitMeta (block);
618
619                                 current_phase = Phase.Emitting;
620                                 EmitResolvedTopBlock (block, unreachable);
621                         }
622                 }
623
624                 bool resolved;
625
626                 public bool ResolveTopBlock (EmitContext anonymous_method_host, ToplevelBlock block,
627                                              Parameters ip, IMethodData md, out bool unreachable)
628                 {
629                         current_phase = Phase.Resolving;
630                         
631                         unreachable = false;
632
633                         if (resolved)
634                                 return true;
635
636                         capture_context = block.CaptureContext;
637                         
638                         if (!loc.IsNull)
639                                 CurrentFile = loc.File;
640
641 #if PRODUCTION
642                         try {
643 #endif
644                                 if (!block.ResolveMeta (this, ip))
645                                         return false;
646
647                                 bool old_do_flow_analysis = DoFlowAnalysis;
648                                 DoFlowAnalysis = true;
649
650                                 if (anonymous_method_host != null)
651                                         current_flow_branching = FlowBranching.CreateBranching (
652                                                 anonymous_method_host.CurrentBranching,
653                                                 FlowBranching.BranchingType.Block, block, loc);
654                                 else 
655                                         current_flow_branching = block.TopLevelBranching;
656
657                                 if (!block.Resolve (this)) {
658                                         current_flow_branching = null;
659                                         DoFlowAnalysis = old_do_flow_analysis;
660                                         return false;
661                                 }
662
663                                 FlowBranching.Reachability reachability = current_flow_branching.MergeTopBlock ();
664                                 current_flow_branching = null;
665
666                                 DoFlowAnalysis = old_do_flow_analysis;
667
668                                 if (reachability.AlwaysReturns ||
669                                     reachability.AlwaysThrows ||
670                                     reachability.IsUnreachable)
671                                         unreachable = true;
672 #if PRODUCTION
673                         } catch (Exception e) {
674                                         Console.WriteLine ("Exception caught by the compiler while compiling:");
675                                         Console.WriteLine ("   Block that caused the problem begin at: " + loc);
676                                         
677                                         if (CurrentBlock != null){
678                                                 Console.WriteLine ("                     Block being compiled: [{0},{1}]",
679                                                                    CurrentBlock.StartLocation, CurrentBlock.EndLocation);
680                                         }
681                                         Console.WriteLine (e.GetType ().FullName + ": " + e.Message);
682                                         throw;
683                         }
684 #endif
685
686                         if (ReturnType != null && !unreachable) {
687                                 if (CurrentAnonymousMethod == null) {
688                                         Report.Error (161, md.Location, "`{0}': not all code paths return a value", md.GetSignatureForError ());
689                                         return false;
690                                 } else if (!CurrentAnonymousMethod.IsIterator) {
691                                         Report.Error (1643, CurrentAnonymousMethod.Location, "Not all code paths return a value in anonymous method of type `{0}'",
692                                                 CurrentAnonymousMethod.GetSignatureForError ());
693                                         return false;
694                                 }
695                         }
696
697                         block.CompleteContexts ();
698                         resolved = true;
699                         return true;
700                 }
701
702                 public void EmitResolvedTopBlock (ToplevelBlock block, bool unreachable)
703                 {
704                         if (block != null)
705                                 block.Emit (this);
706                         
707                         if (HasReturnLabel)
708                                 ig.MarkLabel (ReturnLabel);
709                         
710                         if (return_value != null){
711                                 ig.Emit (OpCodes.Ldloc, return_value);
712                                 ig.Emit (OpCodes.Ret);
713                         } else {
714                                 //
715                                 // If `HasReturnLabel' is set, then we already emitted a
716                                 // jump to the end of the method, so we must emit a `ret'
717                                 // there.
718                                 //
719                                 // Unfortunately, System.Reflection.Emit automatically emits
720                                 // a leave to the end of a finally block.  This is a problem
721                                 // if no code is following the try/finally block since we may
722                                 // jump to a point after the end of the method.
723                                 // As a workaround, we're always creating a return label in
724                                 // this case.
725                                 //
726
727                                 bool in_iterator = (CurrentAnonymousMethod != null) &&
728                                         CurrentAnonymousMethod.IsIterator && InIterator;
729
730                                 if ((block != null) && block.IsDestructor) {
731                                         // Nothing to do; S.R.E automatically emits a leave.
732                                 } else if (HasReturnLabel || (!unreachable && !in_iterator)) {
733                                         if (ReturnType != null)
734                                                 ig.Emit (OpCodes.Ldloc, TemporaryReturn ());
735                                         ig.Emit (OpCodes.Ret);
736                                 }
737                         }
738
739                         //
740                         // Close pending helper classes if we are the toplevel
741                         //
742                         if (capture_context != null && capture_context.ParentToplevel == null)
743                                 capture_context.CloseAnonymousHelperClasses ();
744                 }
745
746                 /// <summary>
747                 ///   This is called immediately before emitting an IL opcode to tell the symbol
748                 ///   writer to which source line this opcode belongs.
749                 /// </summary>
750                 public void Mark (Location loc, bool check_file)
751                 {
752                         if ((CodeGen.SymbolWriter == null) || loc.IsNull)
753                                 return;
754
755                         if (check_file && (CurrentFile != loc.File))
756                                 return;
757
758                         CodeGen.SymbolWriter.MarkSequencePoint (ig, loc.Row, loc.Column);
759                 }
760
761                 public void DefineLocalVariable (string name, LocalBuilder builder)
762                 {
763                         if (CodeGen.SymbolWriter == null)
764                                 return;
765
766                         CodeGen.SymbolWriter.DefineLocalVariable (name, builder);
767                 }
768
769                 public void BeginScope ()
770                 {
771                         ig.BeginScope();
772
773                         if (CodeGen.SymbolWriter != null)
774                                 CodeGen.SymbolWriter.OpenScope(ig);
775                 }
776
777                 public void EndScope ()
778                 {
779                         ig.EndScope();
780
781                         if (CodeGen.SymbolWriter != null)
782                                 CodeGen.SymbolWriter.CloseScope(ig);
783                 }
784
785                 /// <summary>
786                 ///   Returns a temporary storage for a variable of type t as 
787                 ///   a local variable in the current body.
788                 /// </summary>
789                 public LocalBuilder GetTemporaryLocal (Type t)
790                 {
791                         LocalBuilder location = null;
792                         
793                         if (temporary_storage != null){
794                                 object o = temporary_storage [t];
795                                 if (o != null){
796                                         if (o is ArrayList){
797                                                 ArrayList al = (ArrayList) o;
798                                                 
799                                                 for (int i = 0; i < al.Count; i++){
800                                                         if (al [i] != null){
801                                                                 location = (LocalBuilder) al [i];
802                                                                 al [i] = null;
803                                                                 break;
804                                                         }
805                                                 }
806                                         } else
807                                                 location = (LocalBuilder) o;
808                                         if (location != null)
809                                                 return location;
810                                 }
811                         }
812                         
813                         return ig.DeclareLocal (t);
814                 }
815
816                 public void FreeTemporaryLocal (LocalBuilder b, Type t)
817                 {
818                         if (temporary_storage == null){
819                                 temporary_storage = new Hashtable ();
820                                 temporary_storage [t] = b;
821                                 return;
822                         }
823                         object o = temporary_storage [t];
824                         if (o == null){
825                                 temporary_storage [t] = b;
826                                 return;
827                         }
828                         if (o is ArrayList){
829                                 ArrayList al = (ArrayList) o;
830                                 for (int i = 0; i < al.Count; i++){
831                                         if (al [i] == null){
832                                                 al [i] = b;
833                                                 return;
834                                         }
835                                 }
836                                 al.Add (b);
837                                 return;
838                         }
839                         ArrayList replacement = new ArrayList ();
840                         replacement.Add (o);
841                         temporary_storage.Remove (t);
842                         temporary_storage [t] = replacement;
843                 }
844
845                 /// <summary>
846                 ///   Current loop begin and end labels.
847                 /// </summary>
848                 public Label LoopBegin, LoopEnd;
849
850                 /// <summary>
851                 ///   Default target in a switch statement.   Only valid if
852                 ///   InSwitch is true
853                 /// </summary>
854                 public Label DefaultTarget;
855
856                 /// <summary>
857                 ///   If this is non-null, points to the current switch statement
858                 /// </summary>
859                 public Switch Switch;
860
861                 /// <summary>
862                 ///   ReturnValue creates on demand the LocalBuilder for the
863                 ///   return value from the function.  By default this is not
864                 ///   used.  This is only required when returns are found inside
865                 ///   Try or Catch statements.
866                 ///
867                 ///   This method is typically invoked from the Emit phase, so
868                 ///   we allow the creation of a return label if it was not
869                 ///   requested during the resolution phase.   Could be cleaned
870                 ///   up, but it would replicate a lot of logic in the Emit phase
871                 ///   of the code that uses it.
872                 /// </summary>
873                 public LocalBuilder TemporaryReturn ()
874                 {
875                         if (return_value == null){
876                                 return_value = ig.DeclareLocal (ReturnType);
877                                 if (!HasReturnLabel){
878                                         ReturnLabel = ig.DefineLabel ();
879                                         HasReturnLabel = true;
880                                 }
881                         }
882
883                         return return_value;
884                 }
885
886                 /// <summary>
887                 ///   This method is used during the Resolution phase to flag the
888                 ///   need to define the ReturnLabel
889                 /// </summary>
890                 public void NeedReturnLabel ()
891                 {
892                         if (current_phase != Phase.Resolving){
893                                 //
894                                 // The reason is that the `ReturnLabel' is declared between
895                                 // resolution and emission
896                                 // 
897                                 throw new Exception ("NeedReturnLabel called from Emit phase, should only be called during Resolve");
898                         }
899                         
900                         if (!InIterator && !HasReturnLabel) 
901                                 HasReturnLabel = true;
902                 }
903
904                 //
905                 // Emits the proper object to address fields on a remapped
906                 // variable/parameter to field in anonymous-method/iterator proxy classes.
907                 //
908                 public void EmitThis (bool need_address)
909                 {
910                         ig.Emit (OpCodes.Ldarg_0);
911                         if (capture_context != null && CurrentAnonymousMethod != null){
912                                 ScopeInfo si = CurrentAnonymousMethod.Scope;
913                                 while (si != null){
914                                         if (si.ParentLink != null)
915                                                 ig.Emit (OpCodes.Ldfld, si.ParentLink);
916                                         if (si.THIS != null){
917                                                 if (need_address && TypeManager.IsValueType (si.THIS.FieldType))
918                                                         ig.Emit (OpCodes.Ldflda, si.THIS);
919                                                 else
920                                                         ig.Emit (OpCodes.Ldfld, si.THIS);
921                                                 break;
922                                         }
923                                         si = si.ParentScope;
924                                 }
925                         } 
926                 }
927
928                 //
929                 // Emits the code necessary to load the instance required
930                 // to access the captured LocalInfo
931                 //
932                 public void EmitCapturedVariableInstance (LocalInfo li)
933                 {
934                         if (capture_context == null)
935                                 throw new Exception ("Calling EmitCapturedContext when there is no capture_context");
936                         
937                         capture_context.EmitCapturedVariableInstance (this, li, CurrentAnonymousMethod);
938                 }
939
940                 public void EmitParameter (string name, bool leave_copy, bool prepared, ref LocalTemporary temp)
941                 {
942                         capture_context.EmitParameter (this, name, leave_copy, prepared, ref temp);
943                 }
944
945                 public void EmitAssignParameter (string name, Expression source, bool leave_copy, bool prepare_for_load, ref LocalTemporary  temp)
946                 {
947                         capture_context.EmitAssignParameter (this, name, source, leave_copy, prepare_for_load, ref temp);
948                 }
949
950                 public void EmitAddressOfParameter (string name)
951                 {
952                         capture_context.EmitAddressOfParameter (this, name);
953                 }
954                 
955                 public Expression GetThis (Location loc)
956                 {
957                         This my_this;
958                         if (CurrentBlock != null)
959                                 my_this = new This (CurrentBlock, loc);
960                         else
961                                 my_this = new This (loc);
962
963                         if (!my_this.ResolveBase (this))
964                                 my_this = null;
965
966                         return my_this;
967                 }
968         }
969
970
971         public abstract class CommonAssemblyModulClass : Attributable, IResolveContext {
972
973                 protected CommonAssemblyModulClass ():
974                         base (null)
975                 {
976                 }
977
978                 public void AddAttributes (ArrayList attrs)
979                 {
980                         foreach (Attribute a in attrs)
981                                 a.AttachTo (this);
982
983                         if (attributes == null) {
984                                 attributes = new Attributes (attrs);
985                                 return;
986                         }
987                         attributes.AddAttributes (attrs);
988                 }
989
990                 public virtual void Emit (TypeContainer tc) 
991                 {
992                         if (OptAttributes == null)
993                                 return;
994
995                         OptAttributes.Emit ();
996                 }
997                 
998                 protected Attribute ResolveAttribute (Type a_type)
999                 {
1000                         if (OptAttributes == null)
1001                                 return null;
1002
1003                         // Ensure that we only have GlobalAttributes, since the Search below isn't safe with other types.
1004                         if (!OptAttributes.CheckTargets ())
1005                                 return null;
1006
1007                         Attribute a = OptAttributes.Search (a_type);
1008                         if (a != null) {
1009                                 a.Resolve ();
1010                         }
1011                         return a;
1012                 }
1013
1014                 public override IResolveContext ResolveContext {
1015                         get {
1016                                 return this;
1017                         }
1018                 }
1019
1020                 #region IResolveContext Members
1021
1022                 public DeclSpace DeclContainer {
1023                         get {
1024                                 return RootContext.Tree.Types;
1025                         }
1026                 }
1027
1028                 public bool IsInObsoleteScope {
1029                         get {
1030                                 return false;
1031                         }
1032                 }
1033
1034                 public bool IsInUnsafeScope {
1035                         get {
1036                                 return false;
1037                         }
1038                 }
1039
1040                 #endregion
1041         }
1042                 
1043         public class AssemblyClass : CommonAssemblyModulClass {
1044                 // TODO: make it private and move all builder based methods here
1045                 public AssemblyBuilder Builder;
1046                 bool is_cls_compliant;
1047                 bool wrap_non_exception_throws;
1048
1049                 public Attribute ClsCompliantAttribute;
1050
1051                 ListDictionary declarative_security;
1052
1053                 // Module is here just because of error messages
1054                 static string[] attribute_targets = new string [] { "assembly", "module" };
1055
1056                 public AssemblyClass (): base ()
1057                 {
1058                         wrap_non_exception_throws = true;
1059                 }
1060
1061                 public bool IsClsCompliant {
1062                         get {
1063                                 return is_cls_compliant;
1064                         }
1065                 }
1066
1067                 public bool WrapNonExceptionThrows {
1068                         get {
1069                                 return wrap_non_exception_throws;
1070                         }
1071                 }
1072
1073                 public override AttributeTargets AttributeTargets {
1074                         get {
1075                                 return AttributeTargets.Assembly;
1076                         }
1077                 }
1078
1079                 public override bool IsClsComplianceRequired ()
1080                 {
1081                         return is_cls_compliant;
1082                 }
1083
1084                 public void Resolve ()
1085                 {
1086                         ClsCompliantAttribute = ResolveAttribute (TypeManager.cls_compliant_attribute_type);
1087                         if (ClsCompliantAttribute != null) {
1088                                 is_cls_compliant = ClsCompliantAttribute.GetClsCompliantAttributeValue ();
1089                         }
1090
1091 #if NET_2_0
1092                         Attribute a = ResolveAttribute (TypeManager.runtime_compatibility_attr_type);
1093                         if (a != null) {
1094                                 object val = a.GetPropertyValue ("WrapNonExceptionThrows");
1095                                 if (val != null)
1096                                         wrap_non_exception_throws = (bool)val;
1097                         }
1098 #endif
1099                 }
1100
1101                 // fix bug #56621
1102                 private void SetPublicKey (AssemblyName an, byte[] strongNameBlob) 
1103                 {
1104                         try {
1105                                 // check for possible ECMA key
1106                                 if (strongNameBlob.Length == 16) {
1107                                         // will be rejected if not "the" ECMA key
1108                                         an.SetPublicKey (strongNameBlob);
1109                                 }
1110                                 else {
1111                                         // take it, with or without, a private key
1112                                         RSA rsa = CryptoConvert.FromCapiKeyBlob (strongNameBlob);
1113                                         // and make sure we only feed the public part to Sys.Ref
1114                                         byte[] publickey = CryptoConvert.ToCapiPublicKeyBlob (rsa);
1115                                         
1116                                         // AssemblyName.SetPublicKey requires an additional header
1117                                         byte[] publicKeyHeader = new byte [12] { 0x00, 0x24, 0x00, 0x00, 0x04, 0x80, 0x00, 0x00, 0x94, 0x00, 0x00, 0x00 };
1118
1119                                         byte[] encodedPublicKey = new byte [12 + publickey.Length];
1120                                         Buffer.BlockCopy (publicKeyHeader, 0, encodedPublicKey, 0, 12);
1121                                         Buffer.BlockCopy (publickey, 0, encodedPublicKey, 12, publickey.Length);
1122                                         an.SetPublicKey (encodedPublicKey);
1123                                 }
1124                         }
1125                         catch (Exception) {
1126                                 Error_AssemblySigning ("The specified file `" + RootContext.StrongNameKeyFile + "' is incorrectly encoded");
1127                                 Environment.Exit (1);
1128                         }
1129                 }
1130
1131                 // TODO: rewrite this code (to kill N bugs and make it faster) and use standard ApplyAttribute way.
1132                 public AssemblyName GetAssemblyName (string name, string output) 
1133                 {
1134                         if (OptAttributes != null) {
1135                                 foreach (Attribute a in OptAttributes.Attrs) {
1136                                         // cannot rely on any resolve-based members before you call Resolve
1137                                         if (a.ExplicitTarget == null || a.ExplicitTarget != "assembly")
1138                                                 continue;
1139
1140                                         // TODO: This code is buggy: comparing Attribute name without resolving is wrong.
1141                                         //       However, this is invoked by CodeGen.Init, when none of the namespaces
1142                                         //       are loaded yet.
1143                                         // TODO: Does not handle quoted attributes properly
1144                                         switch (a.Name) {
1145                                                 case "AssemblyKeyFile":
1146                                                 case "AssemblyKeyFileAttribute":
1147                                                 case "System.Reflection.AssemblyKeyFileAttribute":
1148                                                         if (RootContext.StrongNameKeyFile != null) {
1149                                                                 Report.SymbolRelatedToPreviousError (a.Location, a.Name);
1150                                                                 Report.Warning (1616, 1, "Option `{0}' overrides attribute `{1}' given in a source file or added module",
1151                                     "keyfile", "System.Reflection.AssemblyKeyFileAttribute");
1152                                                         }
1153                                                         else {
1154                                                                 string value = a.GetString ();
1155                                                                 if (value.Length != 0)
1156                                                                         RootContext.StrongNameKeyFile = value;
1157                                                         }
1158                                                         break;
1159                                                 case "AssemblyKeyName":
1160                                                 case "AssemblyKeyNameAttribute":
1161                                                 case "System.Reflection.AssemblyKeyNameAttribute":
1162                                                         if (RootContext.StrongNameKeyContainer != null) {
1163                                                                 Report.SymbolRelatedToPreviousError (a.Location, a.Name);
1164                                                                 Report.Warning (1616, 1, "Option `{0}' overrides attribute `{1}' given in a source file or added module",
1165                                                                         "keycontainer", "System.Reflection.AssemblyKeyNameAttribute");
1166                                                         }
1167                                                         else {
1168                                                                 string value = a.GetString ();
1169                                                                 if (value.Length != 0)
1170                                                                         RootContext.StrongNameKeyContainer = value;
1171                                                         }
1172                                                         break;
1173                                                 case "AssemblyDelaySign":
1174                                                 case "AssemblyDelaySignAttribute":
1175                                                 case "System.Reflection.AssemblyDelaySignAttribute":
1176                                                         RootContext.StrongNameDelaySign = a.GetBoolean ();
1177                                                         break;
1178                                         }
1179                                 }
1180                         }
1181
1182                         AssemblyName an = new AssemblyName ();
1183                         an.Name = Path.GetFileNameWithoutExtension (name);
1184
1185                         // note: delay doesn't apply when using a key container
1186                         if (RootContext.StrongNameKeyContainer != null) {
1187                                 an.KeyPair = new StrongNameKeyPair (RootContext.StrongNameKeyContainer);
1188                                 return an;
1189                         }
1190
1191                         // strongname is optional
1192                         if (RootContext.StrongNameKeyFile == null)
1193                                 return an;
1194
1195                         string AssemblyDir = Path.GetDirectoryName (output);
1196
1197                         // the StrongName key file may be relative to (a) the compiled
1198                         // file or (b) to the output assembly. See bugzilla #55320
1199                         // http://bugzilla.ximian.com/show_bug.cgi?id=55320
1200
1201                         // (a) relative to the compiled file
1202                         string filename = Path.GetFullPath (RootContext.StrongNameKeyFile);
1203                         bool exist = File.Exists (filename);
1204                         if ((!exist) && (AssemblyDir != null) && (AssemblyDir != String.Empty)) {
1205                                 // (b) relative to the outputed assembly
1206                                 filename = Path.GetFullPath (Path.Combine (AssemblyDir, RootContext.StrongNameKeyFile));
1207                                 exist = File.Exists (filename);
1208                         }
1209
1210                         if (exist) {
1211                                 using (FileStream fs = new FileStream (filename, FileMode.Open, FileAccess.Read)) {
1212                                         byte[] snkeypair = new byte [fs.Length];
1213                                         fs.Read (snkeypair, 0, snkeypair.Length);
1214
1215                                         if (RootContext.StrongNameDelaySign) {
1216                                                 // delayed signing - DO NOT include private key
1217                                                 SetPublicKey (an, snkeypair);
1218                                         }
1219                                         else {
1220                                                 // no delay so we make sure we have the private key
1221                                                 try {
1222                                                         CryptoConvert.FromCapiPrivateKeyBlob (snkeypair);
1223                                                         an.KeyPair = new StrongNameKeyPair (snkeypair);
1224                                                 }
1225                                                 catch (CryptographicException) {
1226                                                         if (snkeypair.Length == 16) {
1227                                                                 // error # is different for ECMA key
1228                                                                 Report.Error (1606, "Could not sign the assembly. " + 
1229                                                                         "ECMA key can only be used to delay-sign assemblies");
1230                                                         }
1231                                                         else {
1232                                                                 Error_AssemblySigning ("The specified file `" + RootContext.StrongNameKeyFile + "' does not have a private key");
1233                                                         }
1234                                                         return null;
1235                                                 }
1236                                         }
1237                                 }
1238                         }
1239                         else {
1240                                 Error_AssemblySigning ("The specified file `" + RootContext.StrongNameKeyFile + "' does not exist");
1241                                 return null;
1242                         }
1243                         return an;
1244                 }
1245
1246                 void Error_AssemblySigning (string text)
1247                 {
1248                         Report.Error (1548, "Error during assembly signing. " + text);
1249                 }
1250
1251                 public override void ApplyAttributeBuilder (Attribute a, CustomAttributeBuilder customBuilder)
1252                 {
1253                         if (a.Type.IsSubclassOf (TypeManager.security_attr_type) && a.CheckSecurityActionValidity (true)) {
1254                                 if (declarative_security == null)
1255                                         declarative_security = new ListDictionary ();
1256
1257                                 a.ExtractSecurityPermissionSet (declarative_security);
1258                                 return;
1259                         }
1260
1261                         if (a.Type == TypeManager.assembly_culture_attribute_type) {
1262                                 string value = a.GetString ();
1263                                 if (value == null || value.Length == 0)
1264                                         return;
1265
1266                                 if (RootContext.Target == Target.Exe) {
1267                                         a.Error_AttributeEmitError ("The executables cannot be satelite assemblies, remove the attribute or keep it empty");
1268                                         return;
1269                                 }
1270                         }
1271
1272                         Builder.SetCustomAttribute (customBuilder);
1273                 }
1274
1275                 public override void Emit (TypeContainer tc)
1276                 {
1277                         base.Emit (tc);
1278
1279                         if (declarative_security != null) {
1280
1281                                 MethodInfo add_permission = typeof (AssemblyBuilder).GetMethod ("AddPermissionRequests", BindingFlags.Instance | BindingFlags.NonPublic);
1282                                 object builder_instance = Builder;
1283
1284                                 try {
1285                                         // Microsoft runtime hacking
1286                                         if (add_permission == null) {
1287                                                 Type assembly_builder = typeof (AssemblyBuilder).Assembly.GetType ("System.Reflection.Emit.AssemblyBuilderData");
1288                                                 add_permission = assembly_builder.GetMethod ("AddPermissionRequests", BindingFlags.Instance | BindingFlags.NonPublic);
1289
1290                                                 FieldInfo fi = typeof (AssemblyBuilder).GetField ("m_assemblyData", BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.GetField);
1291                                                 builder_instance = fi.GetValue (Builder);
1292                                         }
1293
1294                                         object[] args = new object [] { declarative_security [SecurityAction.RequestMinimum],
1295                                                                                                   declarative_security [SecurityAction.RequestOptional],
1296                                                                                                   declarative_security [SecurityAction.RequestRefuse] };
1297                                         add_permission.Invoke (builder_instance, args);
1298                                 }
1299                                 catch {
1300                                         Report.RuntimeMissingSupport (Location.Null, "assembly permission setting");
1301                                 }
1302                         }
1303                 }
1304
1305                 public override string[] ValidAttributeTargets {
1306                         get {
1307                                 return attribute_targets;
1308                         }
1309                 }
1310         }
1311
1312         public class ModuleClass : CommonAssemblyModulClass {
1313                 // TODO: make it private and move all builder based methods here
1314                 public ModuleBuilder Builder;
1315                 bool m_module_is_unsafe;
1316
1317                 public CharSet DefaultCharSet = CharSet.Ansi;
1318                 public TypeAttributes DefaultCharSetType = TypeAttributes.AnsiClass;
1319
1320                 static string[] attribute_targets = new string [] { "module" };
1321
1322                 public ModuleClass (bool is_unsafe)
1323                 {
1324                         m_module_is_unsafe = is_unsafe;
1325                 }
1326
1327                 public override AttributeTargets AttributeTargets {
1328                         get {
1329                                 return AttributeTargets.Module;
1330                         }
1331                 }
1332
1333                 public override bool IsClsComplianceRequired ()
1334                 {
1335                         return CodeGen.Assembly.IsClsCompliant;
1336                 }
1337
1338                 public override void Emit (TypeContainer tc) 
1339                 {
1340                         base.Emit (tc);
1341
1342                         if (!m_module_is_unsafe)
1343                                 return;
1344
1345                         if (TypeManager.unverifiable_code_ctor == null) {
1346                                 Console.WriteLine ("Internal error ! Cannot set unverifiable code attribute.");
1347                                 return;
1348                         }
1349                                 
1350                         Builder.SetCustomAttribute (new CustomAttributeBuilder (TypeManager.unverifiable_code_ctor, new object [0]));
1351                 }
1352                 
1353                 public override void ApplyAttributeBuilder (Attribute a, CustomAttributeBuilder customBuilder)
1354                 {
1355                         if (a.Type == TypeManager.cls_compliant_attribute_type) {
1356                                 if (CodeGen.Assembly.ClsCompliantAttribute == null) {
1357                                         Report.Warning (3012, 1, a.Location, "You must specify the CLSCompliant attribute on the assembly, not the module, to enable CLS compliance checking");
1358                                 }
1359                                 else if (CodeGen.Assembly.IsClsCompliant != a.GetBoolean ()) {
1360                                         Report.SymbolRelatedToPreviousError (CodeGen.Assembly.ClsCompliantAttribute.Location, CodeGen.Assembly.ClsCompliantAttribute.GetSignatureForError ());
1361                                         Report.Error (3017, a.Location, "You cannot specify the CLSCompliant attribute on a module that differs from the CLSCompliant attribute on the assembly");
1362                                         return;
1363                                 }
1364                         }
1365
1366                         Builder.SetCustomAttribute (customBuilder);
1367                 }
1368
1369                 /// <summary>
1370                 /// It is called very early therefore can resolve only predefined attributes
1371                 /// </summary>
1372                 public void ResolveAttributes ()
1373                 {
1374 #if NET_2_0
1375                         Attribute a = ResolveAttribute (TypeManager.default_charset_type);
1376                         if (a != null) {
1377                                 DefaultCharSet = a.GetCharSetValue ();
1378                                 switch (DefaultCharSet) {
1379                                         case CharSet.Ansi:
1380                                         case CharSet.None:
1381                                                 break;
1382                                         case CharSet.Auto:
1383                                                 DefaultCharSetType = TypeAttributes.AutoClass;
1384                                                 break;
1385                                         case CharSet.Unicode:
1386                                                 DefaultCharSetType = TypeAttributes.UnicodeClass;
1387                                                 break;
1388                                         default:
1389                                                 Report.Error (1724, a.Location, "Value specified for the argument to 'System.Runtime.InteropServices.DefaultCharSetAttribute' is not valid");
1390                                                 break;
1391                                 }
1392                         }
1393 #endif
1394                 }
1395
1396                 public override string[] ValidAttributeTargets {
1397                         get {
1398                                 return attribute_targets;
1399                         }
1400                 }
1401         }
1402 }