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