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