2009-08-17 Marek Safar <marek.safar@gmail.com>
[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 // Copyright 2001, 2002, 2003 Ximian, Inc.
8 // Copyright 2004 Novell, Inc.
9 //
10
11 //
12 // Please leave this defined on SVN: The idea is that when we ship the
13 // compiler to end users, if the compiler crashes, they have a chance
14 // to narrow down the problem.   
15 //
16 // Only remove it if you need to debug locally on your tree.
17 //
18 //#define PRODUCTION
19
20 using System;
21 using System.IO;
22 using System.Collections;
23 using System.Collections.Specialized;
24 using System.Globalization;
25 using System.Reflection;
26 using System.Reflection.Emit;
27 using System.Runtime.InteropServices;
28 using System.Security;
29 using System.Security.Cryptography;
30 using System.Security.Permissions;
31
32 using Mono.Security.Cryptography;
33
34 namespace Mono.CSharp {
35
36         /// <summary>
37         ///    Code generator class.
38         /// </summary>
39         public class CodeGen {
40                 static AppDomain current_domain;
41
42                 public static AssemblyClass Assembly;
43
44                 static CodeGen ()
45                 {
46                         Reset ();
47                 }
48
49                 public static void Reset ()
50                 {
51                         Assembly = new AssemblyClass ();
52                 }
53
54                 public static string Basename (string name)
55                 {
56                         int pos = name.LastIndexOf ('/');
57
58                         if (pos != -1)
59                                 return name.Substring (pos + 1);
60
61                         pos = name.LastIndexOf ('\\');
62                         if (pos != -1)
63                                 return name.Substring (pos + 1);
64
65                         return name;
66                 }
67
68                 public static string Dirname (string name)
69                 {
70                         int pos = name.LastIndexOf ('/');
71
72                         if (pos != -1)
73                                 return name.Substring (0, pos);
74
75                         pos = name.LastIndexOf ('\\');
76                         if (pos != -1)
77                                 return name.Substring (0, pos);
78
79                         return ".";
80                 }
81
82                 static public string FileName;
83
84 #if MS_COMPATIBLE
85                 const AssemblyBuilderAccess COMPILER_ACCESS = 0;
86 #else
87                 /* Keep this in sync with System.Reflection.Emit.AssemblyBuilder */
88                 const AssemblyBuilderAccess COMPILER_ACCESS = (AssemblyBuilderAccess) 0x800;
89 #endif
90                                 
91                 //
92                 // Initializes the code generator variables for interactive use (repl)
93                 //
94                 static public void InitDynamic (string name)
95                 {
96                         current_domain = AppDomain.CurrentDomain;
97                         AssemblyName an = Assembly.GetAssemblyName (name, name);
98                         
99                         Assembly.Builder = current_domain.DefineDynamicAssembly (an, AssemblyBuilderAccess.Run | COMPILER_ACCESS);
100                         RootContext.ToplevelTypes = new ModuleContainer (true);
101                         RootContext.ToplevelTypes.Builder = Assembly.Builder.DefineDynamicModule (Basename (name), false);
102                         Assembly.Name = Assembly.Builder.GetName ();
103                 }
104                 
105                 //
106                 // Initializes the code generator variables
107                 //
108                 static public bool Init (string name, string output, bool want_debugging_support)
109                 {
110                         FileName = output;
111                         AssemblyName an = Assembly.GetAssemblyName (name, output);
112                         if (an == null)
113                                 return false;
114
115                         if (an.KeyPair != null) {
116                                 // If we are going to strong name our assembly make
117                                 // sure all its refs are strong named
118                                 foreach (Assembly a in GlobalRootNamespace.Instance.Assemblies) {
119                                         AssemblyName ref_name = a.GetName ();
120                                         byte [] b = ref_name.GetPublicKeyToken ();
121                                         if (b == null || b.Length == 0) {
122                                                 Report.Error (1577, "Assembly generation failed " +
123                                                                 "-- Referenced assembly '" +
124                                                                 ref_name.Name +
125                                                                 "' does not have a strong name.");
126                                                 //Environment.Exit (1);
127                                         }
128                                 }
129                         }
130                         
131                         current_domain = AppDomain.CurrentDomain;
132
133                         try {
134                                 Assembly.Builder = current_domain.DefineDynamicAssembly (an,
135                                         AssemblyBuilderAccess.RunAndSave | COMPILER_ACCESS, Dirname (name));
136                         }
137                         catch (ArgumentException) {
138                                 // specified key may not be exportable outside it's container
139                                 if (RootContext.StrongNameKeyContainer != null) {
140                                         Report.Error (1548, "Could not access the key inside the container `" +
141                                                 RootContext.StrongNameKeyContainer + "'.");
142                                         Environment.Exit (1);
143                                 }
144                                 throw;
145                         }
146                         catch (CryptographicException) {
147                                 if ((RootContext.StrongNameKeyContainer != null) || (RootContext.StrongNameKeyFile != null)) {
148                                         Report.Error (1548, "Could not use the specified key to strongname the assembly.");
149                                         Environment.Exit (1);
150                                 }
151                                 return false;
152                         }
153
154                         // Get the complete AssemblyName from the builder
155                         // (We need to get the public key and token)
156                         Assembly.Name = Assembly.Builder.GetName ();
157
158                         //
159                         // Pass a path-less name to DefineDynamicModule.  Wonder how
160                         // this copes with output in different directories then.
161                         // FIXME: figure out how this copes with --output /tmp/blah
162                         //
163                         // If the third argument is true, the ModuleBuilder will dynamically
164                         // load the default symbol writer.
165                         //
166                         try {
167                                 RootContext.ToplevelTypes.Builder = Assembly.Builder.DefineDynamicModule (
168                                         Basename (name), Basename (output), want_debugging_support);
169
170 #if !MS_COMPATIBLE
171                                 // TODO: We should use SymbolWriter from DefineDynamicModule
172                                 if (want_debugging_support && !SymbolWriter.Initialize (RootContext.ToplevelTypes.Builder, output)) {
173                                         Report.Error (40, "Unexpected debug information initialization error `{0}'",
174                                                 "Could not find the symbol writer assembly (Mono.CompilerServices.SymbolWriter.dll)");
175                                         return false;
176                                 }
177 #endif
178                         } catch (ExecutionEngineException e) {
179                                 Report.Error (40, "Unexpected debug information initialization error `{0}'",
180                                         e.Message);
181                                 return false;
182                         }
183
184                         return true;
185                 }
186
187                 static public void Save (string name, bool saveDebugInfo)
188                 {
189 #if GMCS_SOURCE
190                         PortableExecutableKinds pekind;
191                         ImageFileMachine machine;
192
193                         switch (RootContext.Platform) {
194                         case Platform.X86:
195                                 pekind = PortableExecutableKinds.Required32Bit;
196                                 machine = ImageFileMachine.I386;
197                                 break;
198                         case Platform.X64:
199                                 pekind = PortableExecutableKinds.PE32Plus;
200                                 machine = ImageFileMachine.AMD64;
201                                 break;
202                         case Platform.IA64:
203                                 pekind = PortableExecutableKinds.PE32Plus;
204                                 machine = ImageFileMachine.IA64;
205                                 break;
206                         case Platform.AnyCPU:
207                         default:
208                                 pekind = PortableExecutableKinds.ILOnly;
209                                 machine = ImageFileMachine.I386;
210                                 break;
211                         }
212 #endif
213                         try {
214 #if GMCS_SOURCE
215                                 Assembly.Builder.Save (Basename (name), pekind, machine);
216 #else
217                                 Assembly.Builder.Save (Basename (name));
218 #endif
219                         }
220                         catch (COMException) {
221                                 if ((RootContext.StrongNameKeyFile == null) || (!RootContext.StrongNameDelaySign))
222                                         throw;
223
224                                 // FIXME: it seems Microsoft AssemblyBuilder doesn't like to delay sign assemblies 
225                                 Report.Error (1548, "Couldn't delay-sign the assembly with the '" +
226                                         RootContext.StrongNameKeyFile +
227                                         "', Use MCS with the Mono runtime or CSC to compile this assembly.");
228                         }
229                         catch (System.IO.IOException io) {
230                                 Report.Error (16, "Could not write to file `"+name+"', cause: " + io.Message);
231                                 return;
232                         }
233                         catch (System.UnauthorizedAccessException ua) {
234                                 Report.Error (16, "Could not write to file `"+name+"', cause: " + ua.Message);
235                                 return;
236                         }
237                         catch (System.NotImplementedException nie) {
238                                 Report.RuntimeMissingSupport (Location.Null, nie.Message);
239                                 return;
240                         }
241
242                         //
243                         // Write debuger symbol file
244                         //
245                         if (saveDebugInfo)
246                                 SymbolWriter.WriteSymbolFile ();
247                         }
248         }
249
250
251         /// <summary>
252         /// An interface to hold all the information needed in the resolving phase.
253         /// </summary>
254         public interface IResolveContext
255         {
256                 //
257                 // A scope type context, it can be inflated for generic types
258                 //
259                 Type CurrentType { get; }
260
261                 //
262                 // A scope type parameters either VAR or MVAR
263                 //
264                 TypeParameter[] CurrentTypeParameters { get; }
265
266                 //
267                 // A type definition of the type context. For partial types definition use
268                 // CurrentTypeDefinition.PartialContainer otherwise the context is local
269                 //
270                 // TODO: CurrentType.Definition
271                 //
272                 TypeContainer CurrentTypeDefinition { get; }
273
274                 bool IsInObsoleteScope { get; }
275                 bool IsInUnsafeScope { get; }
276
277                 ExtensionMethodGroupExpr LookupExtensionMethod (Type extensionType, string name, Location loc);
278                 FullNamedExpression LookupNamespaceOrType (string name, Location loc, bool ignore_cs0104);
279                 FullNamedExpression LookupNamespaceAlias (string name);
280
281                 // the declcontainer to lookup for type-parameters.  Should only use LookupGeneric on it.
282                 //
283                 // FIXME: This is somewhat of a hack.  We don't need a full DeclSpace for this.  We just need the
284                 //        current type parameters in scope. IUIC, that will require us to rewrite GenericMethod.
285                 //        Maybe we can replace this with a 'LookupGeneric (string)' instead, but we'll have to 
286                 //        handle generic method overrides differently
287                 DeclSpace GenericDeclContainer { get; }
288         }
289
290         /// <summary>
291         ///   An Emit Context is created for each body of code (from methods,
292         ///   properties bodies, indexer bodies or constructor bodies)
293         /// </summary>
294         public class EmitContext : IResolveContext {
295
296                 //
297                 // Holds a varible used during collection or object initialization.
298                 //
299                 public Expression CurrentInitializerVariable;
300
301                 DeclSpace decl_space;
302                 
303                 public ILGenerator ig;
304
305                 [Flags]
306                 public enum Flags : int {
307                         /// <summary>
308                         ///   This flag tracks the `checked' state of the compilation,
309                         ///   it controls whether we should generate code that does overflow
310                         ///   checking, or if we generate code that ignores overflows.
311                         ///
312                         ///   The default setting comes from the command line option to generate
313                         ///   checked or unchecked code plus any source code changes using the
314                         ///   checked/unchecked statements or expressions.   Contrast this with
315                         ///   the ConstantCheckState flag.
316                         /// </summary>
317                         CheckState = 1 << 0,
318
319                         /// <summary>
320                         ///   The constant check state is always set to `true' and cant be changed
321                         ///   from the command line.  The source code can change this setting with
322                         ///   the `checked' and `unchecked' statements and expressions. 
323                         /// </summary>
324                         ConstantCheckState = 1 << 1,
325
326                         AllCheckStateFlags = CheckState | ConstantCheckState,
327
328                         /// <summary>
329                         ///  Whether we are inside an unsafe block
330                         /// </summary>
331                         InUnsafe = 1 << 2,
332
333                         InCatch = 1 << 3,
334                         InFinally = 1 << 4,
335
336                         /// <summary>
337                         ///   Whether control flow analysis is enabled
338                         /// </summary>
339                         DoFlowAnalysis = 1 << 5,
340
341                         /// <summary>
342                         ///   Whether control flow analysis is disabled on structs
343                         ///   (only meaningful when DoFlowAnalysis is set)
344                         /// </summary>
345                         OmitStructFlowAnalysis = 1 << 6,
346
347                         ///
348                         /// Indicates the current context is in probing mode, no errors are reported. 
349                         ///
350                         ProbingMode = 1 <<      7,
351
352                         //
353                         // Inside field intializer expression
354                         //
355                         InFieldInitializer = 1 << 8,
356                         
357                         InferReturnType = 1 << 9,
358                         
359                         InCompoundAssignment = 1 << 10,
360
361                         OmitDebuggingInfo = 1 << 11
362                 }
363
364                 Flags flags;
365
366                 /// <summary>
367                 ///   Whether we are emitting code inside a static or instance method
368                 /// </summary>
369                 public bool IsStatic;
370
371                 /// <summary>
372                 ///   Whether the actual created method is static or instance method.
373                 ///   Althoug the method might be declared as `static', if an anonymous
374                 ///   method is involved, we might turn this into an instance method.
375                 ///
376                 ///   So this reflects the low-level staticness of the method, while
377                 ///   IsStatic represents the semantic, high-level staticness.
378                 /// </summary>
379                 //public bool MethodIsStatic;
380
381                 /// <summary>
382                 ///   The value that is allowed to be returned or NULL if there is no
383                 ///   return type.
384                 /// </summary>
385                 Type return_type;
386
387                 /// <summary>
388                 ///   Whether this is generating code for a constructor
389                 /// </summary>
390                 public bool IsConstructor;
391
392                 /// <summary>
393                 ///   Keeps track of the Type to LocalBuilder temporary storage created
394                 ///   to store structures (used to compute the address of the structure
395                 ///   value on structure method invocations)
396                 /// </summary>
397                 public Hashtable temporary_storage;
398
399                 public Block CurrentBlock;
400
401                 public int CurrentFile;
402
403                 /// <summary>
404                 ///   The location where we store the return value.
405                 /// </summary>
406                 LocalBuilder return_value;
407
408                 /// <summary>
409                 ///   The location where return has to jump to return the
410                 ///   value
411                 /// </summary>
412                 public Label ReturnLabel;
413
414                 /// <summary>
415                 ///   If we already defined the ReturnLabel
416                 /// </summary>
417                 public bool HasReturnLabel;
418
419                 /// <summary>
420                 ///  Whether we are in a `fixed' initialization
421                 /// </summary>
422                 public bool InFixedInitializer;
423
424                 /// <summary>
425                 ///  Whether we are inside an anonymous method.
426                 /// </summary>
427                 public AnonymousExpression CurrentAnonymousMethod;
428                 
429                 /// <summary>
430                 ///   Location for this EmitContext
431                 /// </summary>
432                 public Location loc;
433
434                 /// <summary>
435                 ///   Inside an enum definition, we do not resolve enumeration values
436                 ///   to their enumerations, but rather to the underlying type/value
437                 ///   This is so EnumVal + EnumValB can be evaluated.
438                 ///
439                 ///   There is no "E operator + (E x, E y)", so during an enum evaluation
440                 ///   we relax the rules
441                 /// </summary>
442                 public bool InEnumContext;
443
444                 public readonly IResolveContext ResolveContext;
445
446                 /// <summary>
447                 ///    The current iterator
448                 /// </summary>
449                 public Iterator CurrentIterator {
450                         get { return CurrentAnonymousMethod as Iterator; }
451                 }
452
453                 /// <summary>
454                 ///    Whether we are in the resolving stage or not
455                 /// </summary>
456                 enum Phase {
457                         Created,
458                         Resolving,
459                         Emitting
460                 }
461
462                 bool isAnonymousMethodAllowed = true;
463
464                 Phase current_phase;
465                 FlowBranching current_flow_branching;
466
467                 static int next_id = 0;
468                 int id = ++next_id;
469
470                 public override string ToString ()
471                 {
472                         return String.Format ("EmitContext ({0}:{1})", id,
473                                               CurrentAnonymousMethod, loc);
474                 }
475                 
476                 public EmitContext (IResolveContext rc, DeclSpace ds, Location l, ILGenerator ig,
477                                     Type return_type, int code_flags, bool is_constructor)
478                 {
479                         this.ResolveContext = rc;
480                         this.ig = ig;
481
482                         this.decl_space = ds;
483                         if (RootContext.Checked)
484                                 flags |= Flags.CheckState;
485                         flags |= Flags.ConstantCheckState;
486
487                         if (return_type == null)
488                                 throw new ArgumentNullException ("return_type");
489
490                         IsStatic = (code_flags & Modifiers.STATIC) != 0;
491                         ReturnType = return_type;
492                         IsConstructor = is_constructor;
493                         CurrentBlock = null;
494                         CurrentFile = 0;
495                         current_phase = Phase.Created;
496
497                         loc = l;
498                 }
499
500                 public EmitContext (IResolveContext rc, DeclSpace ds, Location l, ILGenerator ig,
501                                     Type return_type, int code_flags)
502                         : this (rc, ds, l, ig, return_type, code_flags, false)
503                 {
504                 }
505
506                 public Type CurrentType {
507                         get { return ResolveContext.CurrentType; }
508                 }
509
510                 public TypeParameter[] CurrentTypeParameters {
511                         get { return ResolveContext.CurrentTypeParameters; }
512                 }
513
514                 public TypeContainer CurrentTypeDefinition {
515                         get { return ResolveContext.CurrentTypeDefinition; }
516                 }
517
518                 // IResolveContext.GenericDeclContainer
519                 public DeclSpace GenericDeclContainer {
520                         get { return decl_space; }
521                 }
522
523                 public bool CheckState {
524                         get { return (flags & Flags.CheckState) != 0; }
525                 }
526
527                 public bool ConstantCheckState {
528                         get { return (flags & Flags.ConstantCheckState) != 0; }
529                 }
530
531                 public bool InUnsafe {
532                         get { return IsInUnsafeScope; }
533                 }
534
535                 public bool InCatch {
536                         get { return (flags & Flags.InCatch) != 0; }
537                 }
538
539                 public bool InFinally {
540                         get { return (flags & Flags.InFinally) != 0; }
541                 }
542
543                 public bool DoFlowAnalysis {
544                         get { return (flags & Flags.DoFlowAnalysis) != 0; }
545                 }
546
547                 public bool OmitStructFlowAnalysis {
548                         get { return (flags & Flags.OmitStructFlowAnalysis) != 0; }
549                 }
550
551                 // utility helper for CheckExpr, UnCheckExpr, Checked and Unchecked statements
552                 // it's public so that we can use a struct at the callsite
553                 public struct FlagsHandle : IDisposable
554                 {
555                         EmitContext ec;
556                         readonly Flags invmask, oldval;
557
558                         public FlagsHandle (EmitContext ec, Flags flagsToSet)
559                                 : this (ec, flagsToSet, flagsToSet)
560                         {
561                         }
562
563                         internal FlagsHandle (EmitContext ec, Flags mask, Flags val)
564                         {
565                                 this.ec = ec;
566                                 invmask = ~mask;
567                                 oldval = ec.flags & mask;
568                                 ec.flags = (ec.flags & invmask) | (val & mask);
569
570                                 if ((mask & Flags.ProbingMode) != 0)
571                                         Report.DisableReporting ();
572                         }
573
574                         public void Dispose ()
575                         {
576                                 if ((invmask & Flags.ProbingMode) == 0)
577                                         Report.EnableReporting ();
578
579                                 ec.flags = (ec.flags & invmask) | oldval;
580                         }
581                 }
582
583                 // Temporarily set all the given flags to the given value.  Should be used in an 'using' statement
584                 public FlagsHandle Set (Flags flagsToSet)
585                 {
586                         return new FlagsHandle (this, flagsToSet);
587                 }
588
589                 public FlagsHandle With (Flags bits, bool enable)
590                 {
591                         return new FlagsHandle (this, bits, enable ? bits : 0);
592                 }
593
594                 public FlagsHandle WithFlowAnalysis (bool do_flow_analysis, bool omit_struct_analysis)
595                 {
596                         Flags newflags = 
597                                 (do_flow_analysis ? Flags.DoFlowAnalysis : 0) |
598                                 (omit_struct_analysis ? Flags.OmitStructFlowAnalysis : 0);
599                         return new FlagsHandle (this, Flags.DoFlowAnalysis | Flags.OmitStructFlowAnalysis, newflags);
600                 }
601                 
602                 /// <summary>
603                 ///   If this is true, then Return and ContextualReturn statements
604                 ///   will set the ReturnType value based on the expression types
605                 ///   of each return statement instead of the method return type
606                 ///   (which is initially null).
607                 /// </summary>
608                 public bool InferReturnType {
609                         get { return (flags & Flags.InferReturnType) != 0; }
610                 }
611
612                 public TypeInferenceContext ReturnTypeInference;
613
614                 // IResolveContext.IsInObsoleteScope
615                 public bool IsInObsoleteScope {
616                         get {
617                                 // Disables obsolete checks when probing is on
618                                 return IsInProbingMode || ResolveContext.IsInObsoleteScope;
619                         }
620                 }
621
622                 public bool IsInProbingMode {
623                         get { return (flags & Flags.ProbingMode) != 0; }
624                 }
625
626                 // IResolveContext.IsInUnsafeScope
627                 public bool IsInUnsafeScope {
628                         get { return (flags & Flags.InUnsafe) != 0 || ResolveContext.IsInUnsafeScope; }
629                 }
630
631                 public bool IsAnonymousMethodAllowed {
632                         get { return isAnonymousMethodAllowed; }
633                         set { isAnonymousMethodAllowed = value; }
634                 }
635
636                 public bool IsInFieldInitializer {
637                         get { return (flags & Flags.InFieldInitializer) != 0; }
638                 }
639                 
640                 public bool IsInCompoundAssignment {
641                         get { return (flags & Flags.InCompoundAssignment) != 0; }
642                 }
643
644                 public bool IsVariableCapturingRequired {
645                         get {
646                                 return !IsInProbingMode && (CurrentBranching == null || !CurrentBranching.CurrentUsageVector.IsUnreachable);
647                         }
648                 }
649
650                 public FlowBranching CurrentBranching {
651                         get { return current_flow_branching; }
652                 }
653
654                 public bool OmitDebuggingInfo {
655                         get { return (flags & Flags.OmitDebuggingInfo) != 0; }
656                         set {
657                                 if (value)
658                                         flags |= Flags.OmitDebuggingInfo;
659                                 else
660                                         flags &= ~Flags.OmitDebuggingInfo;
661                         }
662                 }
663
664                 // <summary>
665                 //   Starts a new code branching.  This inherits the state of all local
666                 //   variables and parameters from the current branching.
667                 // </summary>
668                 public FlowBranching StartFlowBranching (FlowBranching.BranchingType type, Location loc)
669                 {
670                         current_flow_branching = FlowBranching.CreateBranching (CurrentBranching, type, null, loc);
671                         return current_flow_branching;
672                 }
673
674                 // <summary>
675                 //   Starts a new code branching for block `block'.
676                 // </summary>
677                 public FlowBranching StartFlowBranching (Block block)
678                 {
679                         flags |= Flags.DoFlowAnalysis;
680
681                         current_flow_branching = FlowBranching.CreateBranching (
682                                 CurrentBranching, FlowBranching.BranchingType.Block, block, block.StartLocation);
683                         return current_flow_branching;
684                 }
685
686                 public FlowBranchingTryCatch StartFlowBranching (TryCatch stmt)
687                 {
688                         FlowBranchingTryCatch branching = new FlowBranchingTryCatch (CurrentBranching, stmt);
689                         current_flow_branching = branching;
690                         return branching;
691                 }
692
693                 public FlowBranchingException StartFlowBranching (ExceptionStatement stmt)
694                 {
695                         FlowBranchingException branching = new FlowBranchingException (CurrentBranching, stmt);
696                         current_flow_branching = branching;
697                         return branching;
698                 }
699
700                 public FlowBranchingLabeled StartFlowBranching (LabeledStatement stmt)
701                 {
702                         FlowBranchingLabeled branching = new FlowBranchingLabeled (CurrentBranching, stmt);
703                         current_flow_branching = branching;
704                         return branching;
705                 }
706
707                 public FlowBranchingIterator StartFlowBranching (Iterator iterator)
708                 {
709                         FlowBranchingIterator branching = new FlowBranchingIterator (CurrentBranching, iterator);
710                         current_flow_branching = branching;
711                         return branching;
712                 }
713
714                 public FlowBranchingToplevel StartFlowBranching (ToplevelBlock stmt)
715                 {
716                         FlowBranchingToplevel branching = new FlowBranchingToplevel (CurrentBranching, stmt);
717                         current_flow_branching = branching;
718                         return branching;
719                 }
720
721                 // <summary>
722                 //   Ends a code branching.  Merges the state of locals and parameters
723                 //   from all the children of the ending branching.
724                 // </summary>
725                 public bool EndFlowBranching ()
726                 {
727                         FlowBranching old = current_flow_branching;
728                         current_flow_branching = current_flow_branching.Parent;
729
730                         FlowBranching.UsageVector vector = current_flow_branching.MergeChild (old);
731                         return vector.IsUnreachable;
732                 }
733
734                 // <summary>
735                 //   Kills the current code branching.  This throws away any changed state
736                 //   information and should only be used in case of an error.
737                 // </summary>
738                 // FIXME: this is evil
739                 public void KillFlowBranching ()
740                 {
741                         current_flow_branching = current_flow_branching.Parent;
742                 }
743
744                 public bool MustCaptureVariable (LocalInfo local)
745                 {
746                         if (CurrentAnonymousMethod == null)
747                                 return false;
748
749                         // FIXME: IsIterator is too aggressive, we should capture only if child
750                         // block contains yield
751                         if (CurrentAnonymousMethod.IsIterator)
752                                 return true;
753
754                         return local.Block.Toplevel != CurrentBlock.Toplevel;
755                 }
756                 
757                 public void EmitMeta (ToplevelBlock b)
758                 {
759                         b.EmitMeta (this);
760
761                         if (HasReturnLabel)
762                                 ReturnLabel = ig.DefineLabel ();
763                 }
764
765                 //
766                 // Here until we can fix the problem with Mono.CSharp.Switch, which
767                 // currently can not cope with ig == null during resolve (which must
768                 // be fixed for switch statements to work on anonymous methods).
769                 //
770                 public void EmitTopBlock (IMethodData md, ToplevelBlock block)
771                 {
772                         if (block == null)
773                                 return;
774                         
775                         bool unreachable;
776                         
777                         if (ResolveTopBlock (null, block, md.ParameterInfo, md, out unreachable)){
778                                 if (Report.Errors > 0)
779                                         return;
780
781                                 EmitMeta (block);
782
783                                 current_phase = Phase.Emitting;
784 #if PRODUCTION
785                                 try {
786 #endif
787                                 EmitResolvedTopBlock (block, unreachable);
788 #if PRODUCTION
789                                 } catch (Exception e){
790                                         Console.WriteLine ("Exception caught by the compiler while emitting:");
791                                         Console.WriteLine ("   Block that caused the problem begin at: " + block.loc);
792                                         
793                                         Console.WriteLine (e.GetType ().FullName + ": " + e.Message);
794                                         throw;
795                                 }
796 #endif
797                         }
798                 }
799
800                 bool resolved;
801                 bool unreachable;
802                 
803                 public bool ResolveTopBlock (EmitContext anonymous_method_host, ToplevelBlock block,
804                                              ParametersCompiled ip, IMethodData md, out bool unreachable)
805                 {
806                         if (resolved) {
807                                 unreachable = this.unreachable;
808                                 return true;
809                         }
810
811                         current_phase = Phase.Resolving;
812                         unreachable = false;
813
814                         if (!loc.IsNull)
815                                 CurrentFile = loc.File;
816
817 #if PRODUCTION
818                         try {
819 #endif
820                                 if (!block.ResolveMeta (this, ip))
821                                         return false;
822
823                                 using (this.With (EmitContext.Flags.DoFlowAnalysis, true)) {
824                                         FlowBranchingToplevel top_level;
825                                         if (anonymous_method_host != null)
826                                                 top_level = new FlowBranchingToplevel (anonymous_method_host.CurrentBranching, block);
827                                         else 
828                                                 top_level = block.TopLevelBranching;
829
830                                         current_flow_branching = top_level;
831                                         bool ok = block.Resolve (this);
832                                         current_flow_branching = null;
833
834                                         if (!ok)
835                                                 return false;
836
837                                         bool flow_unreachable = top_level.End ();
838                                         if (flow_unreachable)
839                                                 this.unreachable = unreachable = true;
840                                 }
841 #if PRODUCTION
842                         } catch (Exception e) {
843                                 Console.WriteLine ("Exception caught by the compiler while compiling:");
844                                 Console.WriteLine ("   Block that caused the problem begin at: " + loc);
845
846                                 if (CurrentBlock != null){
847                                         Console.WriteLine ("                     Block being compiled: [{0},{1}]",
848                                                            CurrentBlock.StartLocation, CurrentBlock.EndLocation);
849                                 }
850                                 Console.WriteLine (e.GetType ().FullName + ": " + e.Message);
851                                 throw;
852                         }
853 #endif
854
855                         if (return_type != TypeManager.void_type && !unreachable) {
856                                 if (CurrentAnonymousMethod == null) {
857                                         Report.Error (161, md.Location, "`{0}': not all code paths return a value", md.GetSignatureForError ());
858                                         return false;
859                                 } else if (!CurrentAnonymousMethod.IsIterator) {
860                                         Report.Error (1643, CurrentAnonymousMethod.Location, "Not all code paths return a value in anonymous method of type `{0}'",
861                                                       CurrentAnonymousMethod.GetSignatureForError ());
862                                         return false;
863                                 }
864                         }
865
866                         resolved = true;
867                         return true;
868                 }
869
870                 public Type ReturnType {
871                         set {
872                                 return_type = value;
873                         }
874                         get {
875                                 return return_type;
876                         }
877                 }
878
879                 public void EmitResolvedTopBlock (ToplevelBlock block, bool unreachable)
880                 {
881                         if (block != null)
882                                 block.Emit (this);
883
884                         if (HasReturnLabel)
885                                 ig.MarkLabel (ReturnLabel);
886
887                         if (return_value != null){
888                                 ig.Emit (OpCodes.Ldloc, return_value);
889                                 ig.Emit (OpCodes.Ret);
890                         } else {
891                                 //
892                                 // If `HasReturnLabel' is set, then we already emitted a
893                                 // jump to the end of the method, so we must emit a `ret'
894                                 // there.
895                                 //
896                                 // Unfortunately, System.Reflection.Emit automatically emits
897                                 // a leave to the end of a finally block.  This is a problem
898                                 // if no code is following the try/finally block since we may
899                                 // jump to a point after the end of the method.
900                                 // As a workaround, we're always creating a return label in
901                                 // this case.
902                                 //
903
904                                 if (HasReturnLabel || !unreachable) {
905                                         if (return_type != TypeManager.void_type)
906                                                 ig.Emit (OpCodes.Ldloc, TemporaryReturn ());
907                                         ig.Emit (OpCodes.Ret);
908                                 }
909                         }
910                 }
911
912                 /// <summary>
913                 ///   This is called immediately before emitting an IL opcode to tell the symbol
914                 ///   writer to which source line this opcode belongs.
915                 /// </summary>
916                 public void Mark (Location loc)
917                 {
918                         if (!SymbolWriter.HasSymbolWriter || OmitDebuggingInfo || loc.IsNull)
919                                 return;
920
921                         SymbolWriter.MarkSequencePoint (ig, loc);
922                 }
923
924                 public void DefineLocalVariable (string name, LocalBuilder builder)
925                 {
926                         SymbolWriter.DefineLocalVariable (name, builder);
927                 }
928
929                 public void BeginScope ()
930                 {
931                         ig.BeginScope();
932                         SymbolWriter.OpenScope(ig);
933                 }
934
935                 public void EndScope ()
936                 {
937                         ig.EndScope();
938                         SymbolWriter.CloseScope(ig);
939                 }
940
941                 /// <summary>
942                 ///   Returns a temporary storage for a variable of type t as 
943                 ///   a local variable in the current body.
944                 /// </summary>
945                 public LocalBuilder GetTemporaryLocal (Type t)
946                 {
947                         if (temporary_storage != null) {
948                                 object o = temporary_storage [t];
949                                 if (o != null) {
950                                         if (o is Stack) {
951                                                 Stack s = (Stack) o;
952                                                 o = s.Count == 0 ? null : s.Pop ();
953                                         } else {
954                                                 temporary_storage.Remove (t);
955                                         }
956                                 }
957                                 if (o != null)
958                                         return (LocalBuilder) o;
959                         }
960                         return ig.DeclareLocal (t);
961                 }
962
963                 public void FreeTemporaryLocal (LocalBuilder b, Type t)
964                 {
965                         if (temporary_storage == null) {
966                                 temporary_storage = new Hashtable ();
967                                 temporary_storage [t] = b;
968                                 return;
969                         }
970                         object o = temporary_storage [t];
971                         if (o == null) {
972                                 temporary_storage [t] = b;
973                                 return;
974                         }
975                         Stack s = o as Stack;
976                         if (s == null) {
977                                 s = new Stack ();
978                                 s.Push (o);
979                                 temporary_storage [t] = s;
980                         }
981                         s.Push (b);
982                 }
983
984                 /// <summary>
985                 ///   Current loop begin and end labels.
986                 /// </summary>
987                 public Label LoopBegin, LoopEnd;
988
989                 /// <summary>
990                 ///   Default target in a switch statement.   Only valid if
991                 ///   InSwitch is true
992                 /// </summary>
993                 public Label DefaultTarget;
994
995                 /// <summary>
996                 ///   If this is non-null, points to the current switch statement
997                 /// </summary>
998                 public Switch Switch;
999
1000                 /// <summary>
1001                 ///   ReturnValue creates on demand the LocalBuilder for the
1002                 ///   return value from the function.  By default this is not
1003                 ///   used.  This is only required when returns are found inside
1004                 ///   Try or Catch statements.
1005                 ///
1006                 ///   This method is typically invoked from the Emit phase, so
1007                 ///   we allow the creation of a return label if it was not
1008                 ///   requested during the resolution phase.   Could be cleaned
1009                 ///   up, but it would replicate a lot of logic in the Emit phase
1010                 ///   of the code that uses it.
1011                 /// </summary>
1012                 public LocalBuilder TemporaryReturn ()
1013                 {
1014                         if (return_value == null){
1015                                 return_value = ig.DeclareLocal (return_type);
1016                                 if (!HasReturnLabel){
1017                                         ReturnLabel = ig.DefineLabel ();
1018                                         HasReturnLabel = true;
1019                                 }
1020                         }
1021
1022                         return return_value;
1023                 }
1024
1025                 /// <summary>
1026                 ///   This method is used during the Resolution phase to flag the
1027                 ///   need to define the ReturnLabel
1028                 /// </summary>
1029                 public void NeedReturnLabel ()
1030                 {
1031                         if (current_phase != Phase.Resolving){
1032                                 //
1033                                 // The reason is that the `ReturnLabel' is declared between
1034                                 // resolution and emission
1035                                 // 
1036                                 throw new Exception ("NeedReturnLabel called from Emit phase, should only be called during Resolve");
1037                         }
1038                         
1039                         if (!HasReturnLabel)
1040                                 HasReturnLabel = true;
1041                 }
1042
1043
1044                 public Expression GetThis (Location loc)
1045                 {
1046                         This my_this;
1047                         if (CurrentBlock != null)
1048                                 my_this = new This (CurrentBlock, loc);
1049                         else
1050                                 my_this = new This (loc);
1051
1052                         if (!my_this.ResolveBase (this))
1053                                 my_this = null;
1054
1055                         return my_this;
1056                 }
1057
1058                 #region IResolveContext Members
1059
1060                 public ExtensionMethodGroupExpr LookupExtensionMethod (Type extensionType, string name, Location loc)
1061                 {
1062                         return ResolveContext.LookupExtensionMethod (extensionType, name, loc);
1063                 }
1064
1065                 public FullNamedExpression LookupNamespaceOrType (string name, Location loc, bool ignore_cs0104)
1066                 {
1067                         return ResolveContext.LookupNamespaceOrType (name, loc, ignore_cs0104);
1068                 }
1069
1070                 public FullNamedExpression LookupNamespaceAlias (string name)
1071                 {
1072                         return ResolveContext.LookupNamespaceAlias (name);
1073                 }
1074
1075                 #endregion
1076         }
1077
1078
1079         public abstract class CommonAssemblyModulClass : Attributable, IResolveContext
1080         {
1081                 public void AddAttributes (ArrayList attrs)
1082                 {
1083                         foreach (Attribute a in attrs)
1084                                 a.AttachTo (this, this);
1085
1086                         if (attributes == null) {
1087                                 attributes = new Attributes (attrs);
1088                                 return;
1089                         }
1090                         attributes.AddAttributes (attrs);
1091                 }
1092
1093                 public virtual void Emit (TypeContainer tc) 
1094                 {
1095                         if (OptAttributes == null)
1096                                 return;
1097
1098                         OptAttributes.Emit ();
1099                 }
1100
1101                 protected Attribute ResolveAttribute (PredefinedAttribute a_type)
1102                 {
1103                         Attribute a = OptAttributes.Search (a_type);
1104                         if (a != null) {
1105                                 a.Resolve ();
1106                         }
1107                         return a;
1108                 }
1109
1110                 #region IResolveContext Members
1111
1112                 public Type CurrentType {
1113                         get { return null; }
1114                 }
1115
1116                 public TypeParameter[] CurrentTypeParameters {
1117                         get { return null; }
1118                 }
1119
1120                 public TypeContainer CurrentTypeDefinition {
1121                         get { throw new InternalErrorException ("No TypeContainer in module context"); }
1122                 }
1123
1124                 public DeclSpace DeclContainer {
1125                         get { return RootContext.ToplevelTypes; }
1126                 }
1127
1128                 public DeclSpace GenericDeclContainer {
1129                         get { return DeclContainer; }
1130                 }
1131
1132                 public bool IsInObsoleteScope {
1133                         get { return false; }
1134                 }
1135
1136                 public bool IsInUnsafeScope {
1137                         get { return false; }
1138                 }
1139
1140                 public ExtensionMethodGroupExpr LookupExtensionMethod (Type extensionType, string name, Location loc)
1141                 {
1142                         throw new NotImplementedException ();
1143                 }
1144
1145                 public FullNamedExpression LookupNamespaceOrType (string name, Location loc, bool ignore_cs0104)
1146                 {
1147                         return RootContext.ToplevelTypes.LookupNamespaceOrType (name, loc, ignore_cs0104);
1148                 }
1149
1150                 public FullNamedExpression LookupNamespaceAlias (string name)
1151                 {
1152                         throw new NotImplementedException ();
1153                 }
1154
1155                 #endregion
1156         }
1157                 
1158         public class AssemblyClass : CommonAssemblyModulClass {
1159                 // TODO: make it private and move all builder based methods here
1160                 public AssemblyBuilder Builder;
1161                 bool is_cls_compliant;
1162                 bool wrap_non_exception_throws;
1163
1164                 public Attribute ClsCompliantAttribute;
1165
1166                 ListDictionary declarative_security;
1167                 bool has_extension_method;              
1168                 public AssemblyName Name;
1169                 MethodInfo add_type_forwarder;
1170                 ListDictionary emitted_forwarders;
1171
1172                 // Module is here just because of error messages
1173                 static string[] attribute_targets = new string [] { "assembly", "module" };
1174
1175                 public AssemblyClass (): base ()
1176                 {
1177                         wrap_non_exception_throws = true;
1178                 }
1179
1180                 public bool HasExtensionMethods {
1181                         set {
1182                                 has_extension_method = value;
1183                         }
1184                 }
1185
1186                 public bool IsClsCompliant {
1187                         get {
1188                                 return is_cls_compliant;
1189                         }
1190                 }
1191
1192                 public bool WrapNonExceptionThrows {
1193                         get {
1194                                 return wrap_non_exception_throws;
1195                         }
1196                 }
1197
1198                 public override AttributeTargets AttributeTargets {
1199                         get {
1200                                 return AttributeTargets.Assembly;
1201                         }
1202                 }
1203
1204                 public override bool IsClsComplianceRequired ()
1205                 {
1206                         return is_cls_compliant;
1207                 }
1208
1209                 public void Resolve ()
1210                 {
1211                         if (RootContext.Unsafe) {
1212                                 //
1213                                 // Emits [assembly: SecurityPermissionAttribute (SecurityAction.RequestMinimum, SkipVerification = true)]
1214                                 // when -unsafe option was specified
1215                                 //
1216                                 
1217                                 Location loc = Location.Null;
1218
1219                                 MemberAccess system_security_permissions = new MemberAccess (new MemberAccess (
1220                                         new QualifiedAliasMember (QualifiedAliasMember.GlobalAlias, "System", loc), "Security", loc), "Permissions", loc);
1221
1222                                 Arguments pos = new Arguments (1);
1223                                 pos.Add (new Argument (new MemberAccess (new MemberAccess (system_security_permissions, "SecurityAction", loc), "RequestMinimum")));
1224
1225                                 Arguments named = new Arguments (1);
1226                                 named.Add (new NamedArgument (new LocatedToken (loc, "SkipVerification"), (new BoolLiteral (true, loc))));
1227
1228                                 GlobalAttribute g = new GlobalAttribute (new NamespaceEntry (null, null, null), "assembly", system_security_permissions,
1229                                         "SecurityPermissionAttribute", new Arguments[] { pos, named }, loc, false);
1230                                 g.AttachTo (this, this);
1231
1232                                 if (g.Resolve () != null) {
1233                                         declarative_security = new ListDictionary ();
1234                                         g.ExtractSecurityPermissionSet (declarative_security);
1235                                 }
1236                         }
1237
1238                         if (OptAttributes == null)
1239                                 return;
1240
1241                         // Ensure that we only have GlobalAttributes, since the Search isn't safe with other types.
1242                         if (!OptAttributes.CheckTargets())
1243                                 return;
1244
1245                         ClsCompliantAttribute = ResolveAttribute (PredefinedAttributes.Get.CLSCompliant);
1246
1247                         if (ClsCompliantAttribute != null) {
1248                                 is_cls_compliant = ClsCompliantAttribute.GetClsCompliantAttributeValue ();
1249                         }
1250
1251                         Attribute a = ResolveAttribute (PredefinedAttributes.Get.RuntimeCompatibility);
1252                         if (a != null) {
1253                                 object val = a.GetPropertyValue ("WrapNonExceptionThrows");
1254                                 if (val != null)
1255                                         wrap_non_exception_throws = (bool) val;
1256                         }
1257                 }
1258
1259                 // fix bug #56621
1260                 private void SetPublicKey (AssemblyName an, byte[] strongNameBlob) 
1261                 {
1262                         try {
1263                                 // check for possible ECMA key
1264                                 if (strongNameBlob.Length == 16) {
1265                                         // will be rejected if not "the" ECMA key
1266                                         an.SetPublicKey (strongNameBlob);
1267                                 }
1268                                 else {
1269                                         // take it, with or without, a private key
1270                                         RSA rsa = CryptoConvert.FromCapiKeyBlob (strongNameBlob);
1271                                         // and make sure we only feed the public part to Sys.Ref
1272                                         byte[] publickey = CryptoConvert.ToCapiPublicKeyBlob (rsa);
1273                                         
1274                                         // AssemblyName.SetPublicKey requires an additional header
1275                                         byte[] publicKeyHeader = new byte [12] { 0x00, 0x24, 0x00, 0x00, 0x04, 0x80, 0x00, 0x00, 0x94, 0x00, 0x00, 0x00 };
1276
1277                                         byte[] encodedPublicKey = new byte [12 + publickey.Length];
1278                                         Buffer.BlockCopy (publicKeyHeader, 0, encodedPublicKey, 0, 12);
1279                                         Buffer.BlockCopy (publickey, 0, encodedPublicKey, 12, publickey.Length);
1280                                         an.SetPublicKey (encodedPublicKey);
1281                                 }
1282                         }
1283                         catch (Exception) {
1284                                 Error_AssemblySigning ("The specified file `" + RootContext.StrongNameKeyFile + "' is incorrectly encoded");
1285                                 Environment.Exit (1);
1286                         }
1287                 }
1288
1289                 // TODO: rewrite this code (to kill N bugs and make it faster) and use standard ApplyAttribute way.
1290                 public AssemblyName GetAssemblyName (string name, string output) 
1291                 {
1292                         if (OptAttributes != null) {
1293                                 foreach (Attribute a in OptAttributes.Attrs) {
1294                                         // cannot rely on any resolve-based members before you call Resolve
1295                                         if (a.ExplicitTarget == null || a.ExplicitTarget != "assembly")
1296                                                 continue;
1297
1298                                         // TODO: This code is buggy: comparing Attribute name without resolving is wrong.
1299                                         //       However, this is invoked by CodeGen.Init, when none of the namespaces
1300                                         //       are loaded yet.
1301                                         // TODO: Does not handle quoted attributes properly
1302                                         switch (a.Name) {
1303                                         case "AssemblyKeyFile":
1304                                         case "AssemblyKeyFileAttribute":
1305                                         case "System.Reflection.AssemblyKeyFileAttribute":
1306                                                 if (RootContext.StrongNameKeyFile != null) {
1307                                                         Report.SymbolRelatedToPreviousError (a.Location, a.Name);
1308                                                         Report.Warning (1616, 1, "Option `{0}' overrides attribute `{1}' given in a source file or added module",
1309                                                                         "keyfile", "System.Reflection.AssemblyKeyFileAttribute");
1310                                                 } else {
1311                                                         string value = a.GetString ();
1312                                                         if (value != null && value.Length != 0)
1313                                                                 RootContext.StrongNameKeyFile = value;
1314                                                 }
1315                                                 break;
1316                                         case "AssemblyKeyName":
1317                                         case "AssemblyKeyNameAttribute":
1318                                         case "System.Reflection.AssemblyKeyNameAttribute":
1319                                                 if (RootContext.StrongNameKeyContainer != null) {
1320                                                         Report.SymbolRelatedToPreviousError (a.Location, a.Name);
1321                                                         Report.Warning (1616, 1, "Option `{0}' overrides attribute `{1}' given in a source file or added module",
1322                                                                         "keycontainer", "System.Reflection.AssemblyKeyNameAttribute");
1323                                                 } else {
1324                                                         string value = a.GetString ();
1325                                                         if (value != null && value.Length != 0)
1326                                                                 RootContext.StrongNameKeyContainer = value;
1327                                                 }
1328                                                 break;
1329                                         case "AssemblyDelaySign":
1330                                         case "AssemblyDelaySignAttribute":
1331                                         case "System.Reflection.AssemblyDelaySignAttribute":
1332                                                 RootContext.StrongNameDelaySign = a.GetBoolean ();
1333                                                 break;
1334                                         }
1335                                 }
1336                         }
1337                         
1338                         AssemblyName an = new AssemblyName ();
1339                         an.Name = Path.GetFileNameWithoutExtension (name);
1340
1341                         // note: delay doesn't apply when using a key container
1342                         if (RootContext.StrongNameKeyContainer != null) {
1343                                 an.KeyPair = new StrongNameKeyPair (RootContext.StrongNameKeyContainer);
1344                                 return an;
1345                         }
1346
1347                         // strongname is optional
1348                         if (RootContext.StrongNameKeyFile == null)
1349                                 return an;
1350
1351                         string AssemblyDir = Path.GetDirectoryName (output);
1352
1353                         // the StrongName key file may be relative to (a) the compiled
1354                         // file or (b) to the output assembly. See bugzilla #55320
1355                         // http://bugzilla.ximian.com/show_bug.cgi?id=55320
1356
1357                         // (a) relative to the compiled file
1358                         string filename = Path.GetFullPath (RootContext.StrongNameKeyFile);
1359                         bool exist = File.Exists (filename);
1360                         if ((!exist) && (AssemblyDir != null) && (AssemblyDir != String.Empty)) {
1361                                 // (b) relative to the outputed assembly
1362                                 filename = Path.GetFullPath (Path.Combine (AssemblyDir, RootContext.StrongNameKeyFile));
1363                                 exist = File.Exists (filename);
1364                         }
1365
1366                         if (exist) {
1367                                 using (FileStream fs = new FileStream (filename, FileMode.Open, FileAccess.Read)) {
1368                                         byte[] snkeypair = new byte [fs.Length];
1369                                         fs.Read (snkeypair, 0, snkeypair.Length);
1370
1371                                         if (RootContext.StrongNameDelaySign) {
1372                                                 // delayed signing - DO NOT include private key
1373                                                 SetPublicKey (an, snkeypair);
1374                                         }
1375                                         else {
1376                                                 // no delay so we make sure we have the private key
1377                                                 try {
1378                                                         CryptoConvert.FromCapiPrivateKeyBlob (snkeypair);
1379                                                         an.KeyPair = new StrongNameKeyPair (snkeypair);
1380                                                 }
1381                                                 catch (CryptographicException) {
1382                                                         if (snkeypair.Length == 16) {
1383                                                                 // error # is different for ECMA key
1384                                                                 Report.Error (1606, "Could not sign the assembly. " + 
1385                                                                         "ECMA key can only be used to delay-sign assemblies");
1386                                                         }
1387                                                         else {
1388                                                                 Error_AssemblySigning ("The specified file `" + RootContext.StrongNameKeyFile + "' does not have a private key");
1389                                                         }
1390                                                         return null;
1391                                                 }
1392                                         }
1393                                 }
1394                         }
1395                         else {
1396                                 Error_AssemblySigning ("The specified file `" + RootContext.StrongNameKeyFile + "' does not exist");
1397                                 return null;
1398                         }
1399                         return an;
1400                 }
1401
1402                 void Error_AssemblySigning (string text)
1403                 {
1404                         Report.Error (1548, "Error during assembly signing. " + text);
1405                 }
1406
1407                 bool CheckInternalsVisibleAttribute (Attribute a)
1408                 {
1409                         string assembly_name = a.GetString ();
1410                         if (assembly_name.Length == 0)
1411                                 return false;
1412                                 
1413                         AssemblyName aname = null;
1414                         try {
1415 #if GMCS_SOURCE
1416                                 aname = new AssemblyName (assembly_name);
1417 #else
1418                                 throw new NotSupportedException ();
1419 #endif
1420                         } catch (FileLoadException) {
1421                         } catch (ArgumentException) {
1422                         }
1423                                 
1424                         // Bad assembly name format
1425                         if (aname == null)
1426                                 Report.Warning (1700, 3, a.Location, "Assembly reference `" + assembly_name + "' is invalid and cannot be resolved");
1427                         // Report error if we have defined Version or Culture
1428                         else if (aname.Version != null || aname.CultureInfo != null)
1429                                 throw new Exception ("Friend assembly `" + a.GetString () + 
1430                                                 "' is invalid. InternalsVisibleTo cannot have version or culture specified.");
1431                         else if (aname.GetPublicKey () == null && Name.GetPublicKey () != null && Name.GetPublicKey ().Length != 0) {
1432                                 Report.Error (1726, a.Location, "Friend assembly reference `" + aname.FullName + "' is invalid." +
1433                                                 " Strong named assemblies must specify a public key in their InternalsVisibleTo declarations");
1434                                 return false;
1435                         }
1436
1437                         return true;
1438                 }
1439
1440                 static bool IsValidAssemblyVersion (string version)
1441                 {
1442                         Version v;
1443                         try {
1444                                 v = new Version (version);
1445                         } catch {
1446                                 try {
1447                                         int major = int.Parse (version, CultureInfo.InvariantCulture);
1448                                         v = new Version (major, 0);
1449                                 } catch {
1450                                         return false;
1451                                 }
1452                         }
1453
1454                         foreach (int candidate in new int [] { v.Major, v.Minor, v.Build, v.Revision }) {
1455                                 if (candidate > ushort.MaxValue)
1456                                         return false;
1457                         }
1458
1459                         return true;
1460                 }
1461
1462                 public override void ApplyAttributeBuilder (Attribute a, CustomAttributeBuilder cb, PredefinedAttributes pa)
1463                 {
1464                         if (a.IsValidSecurityAttribute ()) {
1465                                 if (declarative_security == null)
1466                                         declarative_security = new ListDictionary ();
1467
1468                                 a.ExtractSecurityPermissionSet (declarative_security);
1469                                 return;
1470                         }
1471
1472                         if (a.Type == pa.AssemblyCulture) {
1473                                 string value = a.GetString ();
1474                                 if (value == null || value.Length == 0)
1475                                         return;
1476
1477                                 if (RootContext.Target == Target.Exe) {
1478                                         a.Error_AttributeEmitError ("The executables cannot be satelite assemblies, remove the attribute or keep it empty");
1479                                         return;
1480                                 }
1481                         }
1482
1483                         if (a.Type == pa.AssemblyVersion) {
1484                                 string value = a.GetString ();
1485                                 if (value == null || value.Length == 0)
1486                                         return;
1487
1488                                 value = value.Replace ('*', '0');
1489
1490                                 if (!IsValidAssemblyVersion (value)) {
1491                                         a.Error_AttributeEmitError (string.Format ("Specified version `{0}' is not valid", value));
1492                                         return;
1493                                 }
1494                         }
1495
1496                         if (a.Type == pa.InternalsVisibleTo && !CheckInternalsVisibleAttribute (a))
1497                                 return;
1498
1499                         if (a.Type == pa.TypeForwarder) {
1500                                 Type t = a.GetArgumentType ();
1501                                 if (t == null || TypeManager.HasElementType (t)) {
1502                                         Report.Error (735, a.Location, "Invalid type specified as an argument for TypeForwardedTo attribute");
1503                                         return;
1504                                 }
1505
1506                                 t = TypeManager.DropGenericTypeArguments (t);
1507                                 if (emitted_forwarders == null) {
1508                                         emitted_forwarders = new ListDictionary();
1509                                 } else if (emitted_forwarders.Contains(t)) {
1510                                         Report.SymbolRelatedToPreviousError(((Attribute)emitted_forwarders[t]).Location, null);
1511                                         Report.Error(739, a.Location, "A duplicate type forward of type `{0}'",
1512                                                 TypeManager.CSharpName(t));
1513                                         return;
1514                                 }
1515
1516                                 emitted_forwarders.Add(t, a);
1517
1518                                 if (TypeManager.LookupDeclSpace (t) != null) {
1519                                         Report.SymbolRelatedToPreviousError (t);
1520                                         Report.Error (729, a.Location, "Cannot forward type `{0}' because it is defined in this assembly",
1521                                                 TypeManager.CSharpName (t));
1522                                         return;
1523                                 }
1524
1525                                 if (t.DeclaringType != null) {
1526                                         Report.Error (730, a.Location, "Cannot forward type `{0}' because it is a nested type",
1527                                                 TypeManager.CSharpName (t));
1528                                         return;
1529                                 }
1530
1531                                 if (add_type_forwarder == null) {
1532                                         add_type_forwarder = typeof (AssemblyBuilder).GetMethod ("AddTypeForwarder",
1533                                                 BindingFlags.NonPublic | BindingFlags.Instance);
1534
1535                                         if (add_type_forwarder == null) {
1536                                                 Report.RuntimeMissingSupport (a.Location, "TypeForwardedTo attribute");
1537                                                 return;
1538                                         }
1539                                 }
1540
1541                                 add_type_forwarder.Invoke (Builder, new object[] { t });
1542                                 return;
1543                         }
1544                         
1545                         if (a.Type == pa.Extension) {
1546                                 a.Error_MisusedExtensionAttribute ();
1547                                 return;
1548                         }
1549
1550                         Builder.SetCustomAttribute (cb);
1551                 }
1552
1553                 public override void Emit (TypeContainer tc)
1554                 {
1555                         base.Emit (tc);
1556
1557                         if (has_extension_method)
1558                                 PredefinedAttributes.Get.Extension.EmitAttribute (Builder);
1559
1560                         // FIXME: Does this belong inside SRE.AssemblyBuilder instead?
1561                         PredefinedAttribute pa = PredefinedAttributes.Get.RuntimeCompatibility;
1562                         if (pa.IsDefined && (OptAttributes == null || !OptAttributes.Contains (pa))) {
1563                                 ConstructorInfo ci = TypeManager.GetPredefinedConstructor (
1564                                         pa.Type, Location.Null, Type.EmptyTypes);
1565                                 PropertyInfo [] pis = new PropertyInfo [1];
1566                                 pis [0] = TypeManager.GetPredefinedProperty (pa.Type,
1567                                         "WrapNonExceptionThrows", Location.Null, TypeManager.bool_type);
1568                                 object [] pargs = new object [1];
1569                                 pargs [0] = true;
1570                                 Builder.SetCustomAttribute (new CustomAttributeBuilder (ci, new object [0], pis, pargs));
1571                         }
1572
1573                         if (declarative_security != null) {
1574
1575                                 MethodInfo add_permission = typeof (AssemblyBuilder).GetMethod ("AddPermissionRequests", BindingFlags.Instance | BindingFlags.NonPublic);
1576                                 object builder_instance = Builder;
1577
1578                                 try {
1579                                         // Microsoft runtime hacking
1580                                         if (add_permission == null) {
1581                                                 Type assembly_builder = typeof (AssemblyBuilder).Assembly.GetType ("System.Reflection.Emit.AssemblyBuilderData");
1582                                                 add_permission = assembly_builder.GetMethod ("AddPermissionRequests", BindingFlags.Instance | BindingFlags.NonPublic);
1583
1584                                                 FieldInfo fi = typeof (AssemblyBuilder).GetField ("m_assemblyData", BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.GetField);
1585                                                 builder_instance = fi.GetValue (Builder);
1586                                         }
1587
1588                                         object[] args = new object [] { declarative_security [SecurityAction.RequestMinimum],
1589                                                                                                   declarative_security [SecurityAction.RequestOptional],
1590                                                                                                   declarative_security [SecurityAction.RequestRefuse] };
1591                                         add_permission.Invoke (builder_instance, args);
1592                                 }
1593                                 catch {
1594                                         Report.RuntimeMissingSupport (Location.Null, "assembly permission setting");
1595                                 }
1596                         }
1597                 }
1598
1599                 public override string[] ValidAttributeTargets {
1600                         get {
1601                                 return attribute_targets;
1602                         }
1603                 }
1604
1605                 // Wrapper for AssemblyBuilder.AddModule
1606                 static MethodInfo adder_method;
1607                 static public MethodInfo AddModule_Method {
1608                         get {
1609                                 if (adder_method == null)
1610                                         adder_method = typeof (AssemblyBuilder).GetMethod ("AddModule", BindingFlags.Instance|BindingFlags.NonPublic);
1611                                 return adder_method;
1612                         }
1613                 }
1614                 public Module AddModule (string module)
1615                 {
1616                         MethodInfo m = AddModule_Method;
1617                         if (m == null) {
1618                                 Report.RuntimeMissingSupport (Location.Null, "/addmodule");
1619                                 Environment.Exit (1);
1620                         }
1621
1622                         try {
1623                                 return (Module) m.Invoke (Builder, new object [] { module });
1624                         } catch (TargetInvocationException ex) {
1625                                 throw ex.InnerException;
1626                         }
1627                 }               
1628         }
1629 }