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