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