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