2 // codegen.cs: The code generator
5 // Miguel de Icaza (miguel@ximian.com)
7 // (C) 2001, 2002, 2003 Ximian, Inc.
8 // (C) 2004 Novell, Inc.
13 using System.Collections;
14 using System.Collections.Specialized;
15 using System.Reflection;
16 using System.Reflection.Emit;
17 using System.Runtime.InteropServices;
18 using System.Security;
19 using System.Security.Cryptography;
20 using System.Security.Permissions;
22 using Mono.Security.Cryptography;
24 namespace Mono.CSharp {
27 /// Code generator class.
29 public class CodeGen {
30 static AppDomain current_domain;
31 static public SymbolWriter SymbolWriter;
33 public static AssemblyClass Assembly;
34 public static ModuleClass Module;
41 public static void Reset ()
43 Assembly = new AssemblyClass ();
44 Module = new ModuleClass (RootContext.Unsafe);
47 public static string Basename (string name)
49 int pos = name.LastIndexOf ('/');
52 return name.Substring (pos + 1);
54 pos = name.LastIndexOf ('\\');
56 return name.Substring (pos + 1);
61 public static string Dirname (string name)
63 int pos = name.LastIndexOf ('/');
66 return name.Substring (0, pos);
68 pos = name.LastIndexOf ('\\');
70 return name.Substring (0, pos);
75 static public string FileName;
78 // Initializes the symbol writer
80 static void InitializeSymbolWriter (string filename)
82 SymbolWriter = SymbolWriter.GetSymbolWriter (Module.Builder, filename);
85 // If we got an ISymbolWriter instance, initialize it.
87 if (SymbolWriter == null) {
89 -18, "Could not find the symbol writer assembly (Mono.CompilerServices.SymbolWriter.dll). This is normally an installation problem. Please make sure to compile and install the mcs/class/Mono.CompilerServices.SymbolWriter directory.");
95 // Initializes the code generator variables
97 static public bool Init (string name, string output, bool want_debugging_support)
100 AssemblyName an = Assembly.GetAssemblyName (name, output);
104 if (an.KeyPair != null) {
105 // If we are going to strong name our assembly make
106 // sure all its refs are strong named
107 foreach (Assembly a in TypeManager.GetAssemblies ()) {
108 AssemblyName ref_name = a.GetName ();
109 byte [] b = ref_name.GetPublicKeyToken ();
110 if (b == null || b.Length == 0) {
111 Report.Warning (1577, "Assembly generation failed " +
112 "-- Referenced assembly '" +
114 "' does not have a strong name.");
115 //Environment.Exit (1);
120 current_domain = AppDomain.CurrentDomain;
123 Assembly.Builder = current_domain.DefineDynamicAssembly (an,
124 AssemblyBuilderAccess.Save, Dirname (name));
126 catch (ArgumentException) {
127 // specified key may not be exportable outside it's container
128 if (RootContext.StrongNameKeyContainer != null) {
129 Report.Error (1548, "Could not access the key inside the container `" +
130 RootContext.StrongNameKeyContainer + "'.");
131 Environment.Exit (1);
135 catch (CryptographicException) {
136 if ((RootContext.StrongNameKeyContainer != null) || (RootContext.StrongNameKeyFile != null)) {
137 Report.Error (1548, "Could not use the specified key to strongname the assembly.");
138 Environment.Exit (1);
144 // Pass a path-less name to DefineDynamicModule. Wonder how
145 // this copes with output in different directories then.
146 // FIXME: figure out how this copes with --output /tmp/blah
148 // If the third argument is true, the ModuleBuilder will dynamically
149 // load the default symbol writer.
151 Module.Builder = Assembly.Builder.DefineDynamicModule (
152 Basename (name), Basename (output), false);
154 if (want_debugging_support)
155 InitializeSymbolWriter (output);
160 static public void Save (string name)
163 Assembly.Builder.Save (Basename (name));
165 catch (COMException) {
166 if ((RootContext.StrongNameKeyFile == null) || (!RootContext.StrongNameDelaySign))
169 // FIXME: it seems Microsoft AssemblyBuilder doesn't like to delay sign assemblies
170 Report.Error (1548, "Couldn't delay-sign the assembly with the '" +
171 RootContext.StrongNameKeyFile +
172 "', Use MCS with the Mono runtime or CSC to compile this assembly.");
174 catch (System.IO.IOException io) {
175 Report.Error (16, "Could not write to file `"+name+"', cause: " + io.Message);
177 catch (System.UnauthorizedAccessException ua) {
178 Report.Error (16, "Could not write to file `"+name+"', cause: " + ua.Message);
181 if (SymbolWriter != null)
182 SymbolWriter.WriteSymbolFile ();
187 /// An Emit Context is created for each body of code (from methods,
188 /// properties bodies, indexer bodies or constructor bodies)
190 public class EmitContext {
191 public DeclSpace DeclSpace;
192 public DeclSpace TypeContainer;
193 public ILGenerator ig;
196 /// This variable tracks the `checked' state of the compilation,
197 /// it controls whether we should generate code that does overflow
198 /// checking, or if we generate code that ignores overflows.
200 /// The default setting comes from the command line option to generate
201 /// checked or unchecked code plus any source code changes using the
202 /// checked/unchecked statements or expressions. Contrast this with
203 /// the ConstantCheckState flag.
206 public bool CheckState;
209 /// The constant check state is always set to `true' and cant be changed
210 /// from the command line. The source code can change this setting with
211 /// the `checked' and `unchecked' statements and expressions.
213 public bool ConstantCheckState;
216 /// Whether we are emitting code inside a static or instance method
218 public bool IsStatic;
221 /// Whether the actual created method is static or instance method.
222 /// Althoug the method might be declared as `static', if an anonymous
223 /// method is involved, we might turn this into an instance method.
225 /// So this reflects the low-level staticness of the method, while
226 /// IsStatic represents the semantic, high-level staticness.
228 public bool MethodIsStatic;
231 /// Whether we are emitting a field initializer
233 public bool IsFieldInitializer;
236 /// We are resolving a class'es base class and interfaces.
238 public bool ResolvingTypeTree;
241 /// The value that is allowed to be returned or NULL if there is no
244 public Type ReturnType;
247 /// Points to the Type (extracted from the TypeContainer) that
248 /// declares this body of code
250 public Type ContainerType;
253 /// Whether this is generating code for a constructor
255 public bool IsConstructor;
258 /// Whether we're control flow analysis enabled
260 public bool DoFlowAnalysis;
263 /// Keeps track of the Type to LocalBuilder temporary storage created
264 /// to store structures (used to compute the address of the structure
265 /// value on structure method invocations)
267 public Hashtable temporary_storage;
269 public Block CurrentBlock;
271 public int CurrentFile;
274 /// The location where we store the return value.
276 LocalBuilder return_value;
279 /// The location where return has to jump to return the
282 public Label ReturnLabel;
285 /// If we already defined the ReturnLabel
287 public bool HasReturnLabel;
290 /// Whether we are inside an iterator block.
292 public bool InIterator;
294 public bool IsLastStatement;
297 /// Whether we are inside an unsafe block
299 public bool InUnsafe;
302 /// Whether we are in a `fixed' initialization
304 public bool InFixedInitializer;
306 public bool InRefOutArgumentResolving;
309 public bool InFinally;
312 /// Whether we are inside an anonymous method.
314 public AnonymousContainer CurrentAnonymousMethod;
317 /// Location for this EmitContext
322 /// Inside an enum definition, we do not resolve enumeration values
323 /// to their enumerations, but rather to the underlying type/value
324 /// This is so EnumVal + EnumValB can be evaluated.
326 /// There is no "E operator + (E x, E y)", so during an enum evaluation
327 /// we relax the rules
329 public bool InEnumContext;
332 /// Anonymous methods can capture local variables and fields,
333 /// this object tracks it. It is copied from the TopLevelBlock
336 public CaptureContext capture_context;
339 /// Trace when method is called and is obsolete then this member suppress message
340 /// when call is inside next [Obsolete] method or type.
342 public bool TestObsoleteMethodUsage = true;
345 /// The current iterator
347 public Iterator CurrentIterator;
350 /// Whether we are in the resolving stage or not
359 FlowBranching current_flow_branching;
361 static int next_id = 0;
364 public override string ToString ()
366 return String.Format ("EmitContext ({0}:{1}:{2})", id,
367 CurrentIterator, capture_context, loc);
370 public EmitContext (DeclSpace parent, DeclSpace ds, Location l, ILGenerator ig,
371 Type return_type, int code_flags, bool is_constructor)
375 TypeContainer = parent;
377 CheckState = RootContext.Checked;
378 ConstantCheckState = true;
380 if ((return_type is TypeBuilder) && return_type.IsGenericTypeDefinition)
381 throw new InternalErrorException ();
383 IsStatic = (code_flags & Modifiers.STATIC) != 0;
384 MethodIsStatic = IsStatic;
385 InIterator = (code_flags & Modifiers.METHOD_YIELDS) != 0;
386 ReturnType = return_type;
387 IsConstructor = is_constructor;
390 current_phase = Phase.Created;
393 // Can only be null for the ResolveType contexts.
394 ContainerType = parent.TypeBuilder;
395 if (parent.UnsafeContext)
398 InUnsafe = (code_flags & Modifiers.UNSAFE) != 0;
402 if (ReturnType == TypeManager.void_type)
406 public EmitContext (TypeContainer tc, Location l, ILGenerator ig,
407 Type return_type, int code_flags, bool is_constructor)
408 : this (tc, tc, l, ig, return_type, code_flags, is_constructor)
412 public EmitContext (TypeContainer tc, Location l, ILGenerator ig,
413 Type return_type, int code_flags)
414 : this (tc, tc, l, ig, return_type, code_flags, false)
418 public FlowBranching CurrentBranching {
420 return current_flow_branching;
424 public bool HaveCaptureInfo {
426 return capture_context != null;
431 // Starts a new code branching. This inherits the state of all local
432 // variables and parameters from the current branching.
434 public FlowBranching StartFlowBranching (FlowBranching.BranchingType type, Location loc)
436 current_flow_branching = FlowBranching.CreateBranching (CurrentBranching, type, null, loc);
437 return current_flow_branching;
441 // Starts a new code branching for block `block'.
443 public FlowBranching StartFlowBranching (Block block)
445 FlowBranching.BranchingType type;
447 if ((CurrentBranching != null) &&
448 (CurrentBranching.Type == FlowBranching.BranchingType.Switch))
449 type = FlowBranching.BranchingType.SwitchSection;
451 type = FlowBranching.BranchingType.Block;
453 DoFlowAnalysis = true;
455 current_flow_branching = FlowBranching.CreateBranching (
456 CurrentBranching, type, block, block.StartLocation);
457 return current_flow_branching;
460 public FlowBranchingException StartFlowBranching (ExceptionStatement stmt)
462 FlowBranchingException branching = new FlowBranchingException (
463 CurrentBranching, stmt);
464 current_flow_branching = branching;
469 // Ends a code branching. Merges the state of locals and parameters
470 // from all the children of the ending branching.
472 public FlowBranching.UsageVector DoEndFlowBranching ()
474 FlowBranching old = current_flow_branching;
475 current_flow_branching = current_flow_branching.Parent;
477 return current_flow_branching.MergeChild (old);
481 // Ends a code branching. Merges the state of locals and parameters
482 // from all the children of the ending branching.
484 public FlowBranching.Reachability EndFlowBranching ()
486 FlowBranching.UsageVector vector = DoEndFlowBranching ();
488 return vector.Reachability;
492 // Kills the current code branching. This throws away any changed state
493 // information and should only be used in case of an error.
495 public void KillFlowBranching ()
497 current_flow_branching = current_flow_branching.Parent;
500 public void CaptureVariable (LocalInfo li)
502 capture_context.AddLocal (CurrentAnonymousMethod, li);
503 li.IsCaptured = true;
506 public void CaptureParameter (string name, Type t, int idx)
508 capture_context.AddParameter (this, CurrentAnonymousMethod, name, t, idx);
511 public void CaptureThis ()
513 capture_context.CaptureThis ();
518 // Use to register a field as captured
520 public void CaptureField (FieldExpr fe)
522 capture_context.AddField (fe);
526 // Whether anonymous methods have captured variables
528 public bool HaveCapturedVariables ()
530 if (capture_context != null)
531 return capture_context.HaveCapturedVariables;
536 // Whether anonymous methods have captured fields or this.
538 public bool HaveCapturedFields ()
540 if (capture_context != null)
541 return capture_context.HaveCapturedFields;
546 // Emits the instance pointer for the host method
548 public void EmitMethodHostInstance (EmitContext target, AnonymousMethod am)
550 if (capture_context != null)
551 capture_context.EmitMethodHostInstance (target, am);
553 target.ig.Emit (OpCodes.Ldnull);
555 target.ig.Emit (OpCodes.Ldarg_0);
559 // Returns whether the `local' variable has been captured by an anonymous
562 public bool IsCaptured (LocalInfo local)
564 return capture_context.IsCaptured (local);
567 public bool IsParameterCaptured (string name)
569 if (capture_context != null)
570 return capture_context.IsParameterCaptured (name);
574 public void EmitMeta (ToplevelBlock b, InternalParameters ip)
576 if (capture_context != null)
577 capture_context.EmitAnonymousHelperClasses (this);
581 ReturnLabel = ig.DefineLabel ();
585 // Here until we can fix the problem with Mono.CSharp.Switch, which
586 // currently can not cope with ig == null during resolve (which must
587 // be fixed for switch statements to work on anonymous methods).
589 public void EmitTopBlock (ToplevelBlock block, InternalParameters ip, Location loc)
596 if (ResolveTopBlock (null, block, ip, loc, out unreachable)){
597 EmitMeta (block, ip);
599 current_phase = Phase.Emitting;
600 EmitResolvedTopBlock (block, unreachable);
606 public bool ResolveTopBlock (EmitContext anonymous_method_host, ToplevelBlock block,
607 InternalParameters ip, Location loc, out bool unreachable)
609 current_phase = Phase.Resolving;
616 capture_context = block.CaptureContext;
618 if (!Location.IsNull (loc))
619 CurrentFile = loc.File;
624 if (!block.ResolveMeta (this, ip))
627 bool old_do_flow_analysis = DoFlowAnalysis;
628 DoFlowAnalysis = true;
630 if (anonymous_method_host != null)
631 current_flow_branching = FlowBranching.CreateBranching (
632 anonymous_method_host.CurrentBranching,
633 FlowBranching.BranchingType.Block, block, loc);
635 current_flow_branching = block.TopLevelBranching;
637 if (!block.Resolve (this)) {
638 current_flow_branching = null;
639 DoFlowAnalysis = old_do_flow_analysis;
643 FlowBranching.Reachability reachability = current_flow_branching.MergeTopBlock ();
644 current_flow_branching = null;
646 DoFlowAnalysis = old_do_flow_analysis;
648 if (reachability.AlwaysReturns ||
649 reachability.AlwaysThrows ||
650 reachability.IsUnreachable)
653 } catch (Exception e) {
654 Console.WriteLine ("Exception caught by the compiler while compiling:");
655 Console.WriteLine (" Block that caused the problem begin at: " + loc);
657 if (CurrentBlock != null){
658 Console.WriteLine (" Block being compiled: [{0},{1}]",
659 CurrentBlock.StartLocation, CurrentBlock.EndLocation);
661 Console.WriteLine (e.GetType ().FullName + ": " + e.Message);
666 if (ReturnType != null && !unreachable) {
667 if (CurrentAnonymousMethod == null) {
668 Report.Error (161, loc, "Not all code paths return a value");
670 } else if (!CurrentAnonymousMethod.IsIterator) {
672 1643, loc, "Not all code paths return a " +
673 "value in anonymous method of type `{0}'",
674 CurrentAnonymousMethod.Type);
679 block.CompleteContexts ();
684 public void EmitResolvedTopBlock (ToplevelBlock block, bool unreachable)
690 ig.MarkLabel (ReturnLabel);
692 if (return_value != null){
693 ig.Emit (OpCodes.Ldloc, return_value);
694 ig.Emit (OpCodes.Ret);
697 // If `HasReturnLabel' is set, then we already emitted a
698 // jump to the end of the method, so we must emit a `ret'
701 // Unfortunately, System.Reflection.Emit automatically emits
702 // a leave to the end of a finally block. This is a problem
703 // if no code is following the try/finally block since we may
704 // jump to a point after the end of the method.
705 // As a workaround, we're always creating a return label in
709 bool in_iterator = (CurrentAnonymousMethod != null) &&
710 CurrentAnonymousMethod.IsIterator && InIterator;
712 if ((block != null) && block.IsDestructor) {
713 // Nothing to do; S.R.E automatically emits a leave.
714 } else if (HasReturnLabel || (!unreachable && !in_iterator)) {
715 if (ReturnType != null)
716 ig.Emit (OpCodes.Ldloc, TemporaryReturn ());
717 ig.Emit (OpCodes.Ret);
722 // Close pending helper classes if we are the toplevel
724 if (capture_context != null && capture_context.ParentToplevel == null)
725 capture_context.CloseAnonymousHelperClasses ();
729 /// This is called immediately before emitting an IL opcode to tell the symbol
730 /// writer to which source line this opcode belongs.
732 public void Mark (Location loc, bool check_file)
734 if ((CodeGen.SymbolWriter == null) || Location.IsNull (loc))
737 if (check_file && (CurrentFile != loc.File))
740 CodeGen.SymbolWriter.MarkSequencePoint (ig, loc.Row, 0);
743 public void DefineLocalVariable (string name, LocalBuilder builder)
745 if (CodeGen.SymbolWriter == null)
748 CodeGen.SymbolWriter.DefineLocalVariable (name, builder);
751 public void BeginScope ()
755 if (CodeGen.SymbolWriter != null)
756 CodeGen.SymbolWriter.OpenScope(ig);
759 public void EndScope ()
763 if (CodeGen.SymbolWriter != null)
764 CodeGen.SymbolWriter.CloseScope(ig);
768 /// Returns a temporary storage for a variable of type t as
769 /// a local variable in the current body.
771 public LocalBuilder GetTemporaryLocal (Type t)
773 LocalBuilder location = null;
775 if (temporary_storage != null){
776 object o = temporary_storage [t];
779 ArrayList al = (ArrayList) o;
781 for (int i = 0; i < al.Count; i++){
783 location = (LocalBuilder) al [i];
789 location = (LocalBuilder) o;
790 if (location != null)
795 return ig.DeclareLocal (t);
798 public void FreeTemporaryLocal (LocalBuilder b, Type t)
800 if (temporary_storage == null){
801 temporary_storage = new Hashtable ();
802 temporary_storage [t] = b;
805 object o = temporary_storage [t];
807 temporary_storage [t] = b;
811 ArrayList al = (ArrayList) o;
812 for (int i = 0; i < al.Count; i++){
821 ArrayList replacement = new ArrayList ();
823 temporary_storage.Remove (t);
824 temporary_storage [t] = replacement;
828 /// Current loop begin and end labels.
830 public Label LoopBegin, LoopEnd;
833 /// Default target in a switch statement. Only valid if
836 public Label DefaultTarget;
839 /// If this is non-null, points to the current switch statement
841 public Switch Switch;
844 /// ReturnValue creates on demand the LocalBuilder for the
845 /// return value from the function. By default this is not
846 /// used. This is only required when returns are found inside
847 /// Try or Catch statements.
849 /// This method is typically invoked from the Emit phase, so
850 /// we allow the creation of a return label if it was not
851 /// requested during the resolution phase. Could be cleaned
852 /// up, but it would replicate a lot of logic in the Emit phase
853 /// of the code that uses it.
855 public LocalBuilder TemporaryReturn ()
857 if (return_value == null){
858 return_value = ig.DeclareLocal (ReturnType);
859 if (!HasReturnLabel){
860 ReturnLabel = ig.DefineLabel ();
861 HasReturnLabel = true;
869 /// This method is used during the Resolution phase to flag the
870 /// need to define the ReturnLabel
872 public void NeedReturnLabel ()
874 if (current_phase != Phase.Resolving){
876 // The reason is that the `ReturnLabel' is declared between
877 // resolution and emission
879 throw new Exception ("NeedReturnLabel called from Emit phase, should only be called during Resolve");
882 if (!InIterator && !HasReturnLabel)
883 HasReturnLabel = true;
887 // Emits the proper object to address fields on a remapped
888 // variable/parameter to field in anonymous-method/iterator proxy classes.
890 public void EmitThis ()
892 ig.Emit (OpCodes.Ldarg_0);
893 if (capture_context != null && CurrentAnonymousMethod != null){
894 ScopeInfo si = CurrentAnonymousMethod.Scope;
896 if (si.ParentLink != null)
897 ig.Emit (OpCodes.Ldfld, si.ParentLink);
898 if (si.THIS != null){
899 ig.Emit (OpCodes.Ldfld, si.THIS);
908 // Emits the code necessary to load the instance required
909 // to access the captured LocalInfo
911 public void EmitCapturedVariableInstance (LocalInfo li)
913 if (capture_context == null)
914 throw new Exception ("Calling EmitCapturedContext when there is no capture_context");
916 capture_context.EmitCapturedVariableInstance (this, li, CurrentAnonymousMethod);
919 public void EmitParameter (string name)
921 capture_context.EmitParameter (this, name);
924 public void EmitAssignParameter (string name, Expression source, bool leave_copy, bool prepare_for_load)
926 capture_context.EmitAssignParameter (this, name, source, leave_copy, prepare_for_load);
929 public void EmitAddressOfParameter (string name)
931 capture_context.EmitAddressOfParameter (this, name);
934 public Expression GetThis (Location loc)
937 if (CurrentBlock != null)
938 my_this = new This (CurrentBlock, loc);
940 my_this = new This (loc);
942 if (!my_this.ResolveBase (this))
950 public abstract class CommonAssemblyModulClass: Attributable {
951 protected CommonAssemblyModulClass ():
956 public void AddAttributes (ArrayList attrs)
958 if (OptAttributes == null) {
959 OptAttributes = new Attributes (attrs);
962 OptAttributes.AddAttributes (attrs);
965 public virtual void Emit (TypeContainer tc)
967 if (OptAttributes == null)
970 EmitContext ec = new EmitContext (tc, Mono.CSharp.Location.Null, null, null, 0, false);
971 OptAttributes.Emit (ec, this);
974 protected Attribute ResolveAttribute (Type a_type)
976 if (OptAttributes == null)
979 // Ensure that we only have GlobalAttributes, since the Search below isn't safe with other types.
980 if (!OptAttributes.CheckTargets (this))
983 EmitContext temp_ec = new EmitContext (RootContext.Tree.Types, Mono.CSharp.Location.Null, null, null, 0, false);
984 Attribute a = OptAttributes.Search (a_type, temp_ec);
992 public class AssemblyClass: CommonAssemblyModulClass {
993 // TODO: make it private and move all builder based methods here
994 public AssemblyBuilder Builder;
996 bool is_cls_compliant;
997 public Attribute ClsCompliantAttribute;
999 ListDictionary declarative_security;
1001 static string[] attribute_targets = new string [] { "assembly" };
1003 public AssemblyClass (): base ()
1005 is_cls_compliant = false;
1008 public bool IsClsCompliant {
1010 return is_cls_compliant;
1014 public override AttributeTargets AttributeTargets {
1016 return AttributeTargets.Assembly;
1020 public override bool IsClsComplianceRequired(DeclSpace ds)
1022 return is_cls_compliant;
1025 public void ResolveClsCompliance ()
1027 ClsCompliantAttribute = ResolveAttribute (TypeManager.cls_compliant_attribute_type);
1028 if (ClsCompliantAttribute == null)
1031 is_cls_compliant = ClsCompliantAttribute.GetClsCompliantAttributeValue (null);
1035 private void SetPublicKey (AssemblyName an, byte[] strongNameBlob)
1038 // check for possible ECMA key
1039 if (strongNameBlob.Length == 16) {
1040 // will be rejected if not "the" ECMA key
1041 an.SetPublicKey (strongNameBlob);
1044 // take it, with or without, a private key
1045 RSA rsa = CryptoConvert.FromCapiKeyBlob (strongNameBlob);
1046 // and make sure we only feed the public part to Sys.Ref
1047 byte[] publickey = CryptoConvert.ToCapiPublicKeyBlob (rsa);
1049 // AssemblyName.SetPublicKey requires an additional header
1050 byte[] publicKeyHeader = new byte [12] { 0x00, 0x24, 0x00, 0x00, 0x04, 0x80, 0x00, 0x00, 0x94, 0x00, 0x00, 0x00 };
1052 byte[] encodedPublicKey = new byte [12 + publickey.Length];
1053 Buffer.BlockCopy (publicKeyHeader, 0, encodedPublicKey, 0, 12);
1054 Buffer.BlockCopy (publickey, 0, encodedPublicKey, 12, publickey.Length);
1055 an.SetPublicKey (encodedPublicKey);
1059 Report.Error (1548, "Could not strongname the assembly. File `" +
1060 RootContext.StrongNameKeyFile + "' incorrectly encoded.");
1061 Environment.Exit (1);
1065 // TODO: rewrite this code (to kill N bugs and make it faster) and use standard ApplyAttribute way.
1066 public AssemblyName GetAssemblyName (string name, string output)
1068 if (OptAttributes != null) {
1069 foreach (Attribute a in OptAttributes.Attrs) {
1070 // cannot rely on any resolve-based members before you call Resolve
1071 if (a.ExplicitTarget == null || a.ExplicitTarget != "assembly")
1074 // TODO: This code is buggy: comparing Attribute name without resolving it is wrong.
1075 // However, this is invoked by CodeGen.Init, at which time none of the namespaces
1078 case "AssemblyKeyFile":
1079 case "AssemblyKeyFileAttribute":
1080 case "System.Reflection.AssemblyKeyFileAttribute":
1081 if (RootContext.StrongNameKeyFile != null) {
1082 Report.SymbolRelatedToPreviousError (a.Location, a.Name);
1083 Report.Warning (1616, "Compiler option '{0}' overrides '{1}' given in source", "keyfile", "System.Reflection.AssemblyKeyFileAttribute");
1086 string value = a.GetString ();
1087 if (value != String.Empty)
1088 RootContext.StrongNameKeyFile = value;
1091 case "AssemblyKeyName":
1092 case "AssemblyKeyNameAttribute":
1093 case "System.Reflection.AssemblyKeyNameAttribute":
1094 if (RootContext.StrongNameKeyContainer != null) {
1095 Report.SymbolRelatedToPreviousError (a.Location, a.Name);
1096 Report.Warning (1616, "keycontainer", "Compiler option '{0}' overrides '{1}' given in source", "System.Reflection.AssemblyKeyNameAttribute");
1099 string value = a.GetString ();
1100 if (value != String.Empty)
1101 RootContext.StrongNameKeyContainer = value;
1104 case "AssemblyDelaySign":
1105 case "AssemblyDelaySignAttribute":
1106 case "System.Reflection.AssemblyDelaySignAttribute":
1107 RootContext.StrongNameDelaySign = a.GetBoolean ();
1113 AssemblyName an = new AssemblyName ();
1114 an.Name = Path.GetFileNameWithoutExtension (name);
1116 // note: delay doesn't apply when using a key container
1117 if (RootContext.StrongNameKeyContainer != null) {
1118 an.KeyPair = new StrongNameKeyPair (RootContext.StrongNameKeyContainer);
1122 // strongname is optional
1123 if (RootContext.StrongNameKeyFile == null)
1126 string AssemblyDir = Path.GetDirectoryName (output);
1128 // the StrongName key file may be relative to (a) the compiled
1129 // file or (b) to the output assembly. See bugzilla #55320
1130 // http://bugzilla.ximian.com/show_bug.cgi?id=55320
1132 // (a) relative to the compiled file
1133 string filename = Path.GetFullPath (RootContext.StrongNameKeyFile);
1134 bool exist = File.Exists (filename);
1135 if ((!exist) && (AssemblyDir != null) && (AssemblyDir != String.Empty)) {
1136 // (b) relative to the outputed assembly
1137 filename = Path.GetFullPath (Path.Combine (AssemblyDir, RootContext.StrongNameKeyFile));
1138 exist = File.Exists (filename);
1142 using (FileStream fs = new FileStream (filename, FileMode.Open, FileAccess.Read)) {
1143 byte[] snkeypair = new byte [fs.Length];
1144 fs.Read (snkeypair, 0, snkeypair.Length);
1146 if (RootContext.StrongNameDelaySign) {
1147 // delayed signing - DO NOT include private key
1148 SetPublicKey (an, snkeypair);
1151 // no delay so we make sure we have the private key
1153 CryptoConvert.FromCapiPrivateKeyBlob (snkeypair);
1154 an.KeyPair = new StrongNameKeyPair (snkeypair);
1156 catch (CryptographicException) {
1157 if (snkeypair.Length == 16) {
1158 // error # is different for ECMA key
1159 Report.Error (1606, "Could not strongname the assembly. " +
1160 "ECMA key can only be used to delay-sign assemblies");
1163 Report.Error (1548, "Could not strongname the assembly. File `" +
1164 RootContext.StrongNameKeyFile +
1165 "' doesn't have a private key.");
1173 Report.Error (1548, "Could not strongname the assembly. File `" +
1174 RootContext.StrongNameKeyFile + "' not found.");
1180 public override void ApplyAttributeBuilder (Attribute a, CustomAttributeBuilder customBuilder)
1182 if (a.Type.IsSubclassOf (TypeManager.security_attr_type) && a.CheckSecurityActionValidity (true)) {
1183 if (declarative_security == null)
1184 declarative_security = new ListDictionary ();
1186 a.ExtractSecurityPermissionSet (declarative_security);
1190 Builder.SetCustomAttribute (customBuilder);
1193 public override void Emit (TypeContainer tc)
1197 if (declarative_security != null) {
1199 MethodInfo add_permission = typeof (AssemblyBuilder).GetMethod ("AddPermissionRequests", BindingFlags.Instance | BindingFlags.NonPublic);
1200 object builder_instance = Builder;
1203 // Microsoft runtime hacking
1204 if (add_permission == null) {
1205 Type assembly_builder = typeof (AssemblyBuilder).Assembly.GetType ("System.Reflection.Emit.AssemblyBuilderData");
1206 add_permission = assembly_builder.GetMethod ("AddPermissionRequests", BindingFlags.Instance | BindingFlags.NonPublic);
1208 FieldInfo fi = typeof (AssemblyBuilder).GetField ("m_assemblyData", BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.GetField);
1209 builder_instance = fi.GetValue (Builder);
1212 object[] args = new object [] { declarative_security [SecurityAction.RequestMinimum],
1213 declarative_security [SecurityAction.RequestOptional],
1214 declarative_security [SecurityAction.RequestRefuse] };
1215 add_permission.Invoke (builder_instance, args);
1218 Report.RuntimeMissingSupport (Location.Null, "assembly permission setting");
1223 public override string[] ValidAttributeTargets {
1225 return attribute_targets;
1230 public class ModuleClass: CommonAssemblyModulClass {
1231 // TODO: make it private and move all builder based methods here
1232 public ModuleBuilder Builder;
1233 bool m_module_is_unsafe;
1235 public CharSet DefaultCharSet = CharSet.Ansi;
1236 public TypeAttributes DefaultCharSetType = TypeAttributes.AnsiClass;
1238 static string[] attribute_targets = new string [] { "module" };
1240 public ModuleClass (bool is_unsafe)
1242 m_module_is_unsafe = is_unsafe;
1245 public override AttributeTargets AttributeTargets {
1247 return AttributeTargets.Module;
1251 public override bool IsClsComplianceRequired(DeclSpace ds)
1253 return CodeGen.Assembly.IsClsCompliant;
1256 public override void Emit (TypeContainer tc)
1260 if (!m_module_is_unsafe)
1263 if (TypeManager.unverifiable_code_ctor == null) {
1264 Console.WriteLine ("Internal error ! Cannot set unverifiable code attribute.");
1268 Builder.SetCustomAttribute (new CustomAttributeBuilder (TypeManager.unverifiable_code_ctor, new object [0]));
1271 public override void ApplyAttributeBuilder (Attribute a, CustomAttributeBuilder customBuilder)
1273 if (a.Type == TypeManager.cls_compliant_attribute_type) {
1274 if (CodeGen.Assembly.ClsCompliantAttribute == null) {
1275 Report.Warning (3012, a.Location, "You must specify the CLSCompliant attribute on the assembly, not the module, to enable CLS compliance checking");
1277 else if (CodeGen.Assembly.IsClsCompliant != a.GetBoolean ()) {
1278 Report.SymbolRelatedToPreviousError (CodeGen.Assembly.ClsCompliantAttribute.Location, CodeGen.Assembly.ClsCompliantAttribute.Name);
1279 Report.Error (3017, a.Location, "You cannot specify the CLSCompliant attribute on a module that differs from the CLSCompliant attribute on the assembly");
1284 Builder.SetCustomAttribute (customBuilder);
1288 /// It is called very early therefore can resolve only predefined attributes
1290 public void ResolveAttributes ()
1292 Attribute a = ResolveAttribute (TypeManager.default_charset_type);
1294 DefaultCharSet = a.GetCharSetValue ();
1295 switch (DefaultCharSet) {
1300 DefaultCharSetType = TypeAttributes.AutoClass;
1302 case CharSet.Unicode:
1303 DefaultCharSetType = TypeAttributes.UnicodeClass;
1306 Report.Error (1724, a.Location, "Value specified for the argument to 'System.Runtime.InteropServices.DefaultCharSetAttribute' is not valid");
1312 public override string[] ValidAttributeTargets {
1314 return attribute_targets;