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.Reflection;
15 using System.Reflection.Emit;
16 using System.Runtime.InteropServices;
17 using System.Security.Cryptography;
19 using Mono.Security.Cryptography;
21 namespace Mono.CSharp {
24 /// Code generator class.
26 public class CodeGen {
27 static AppDomain current_domain;
28 static public SymbolWriter SymbolWriter;
30 public static AssemblyClass Assembly;
31 public static ModuleClass Module;
35 Assembly = new AssemblyClass ();
36 Module = new ModuleClass (RootContext.Unsafe);
39 public static string Basename (string name)
41 int pos = name.LastIndexOf ('/');
44 return name.Substring (pos + 1);
46 pos = name.LastIndexOf ('\\');
48 return name.Substring (pos + 1);
53 public static string Dirname (string name)
55 int pos = name.LastIndexOf ('/');
58 return name.Substring (0, pos);
60 pos = name.LastIndexOf ('\\');
62 return name.Substring (0, pos);
67 static string TrimExt (string name)
69 int pos = name.LastIndexOf ('.');
71 return name.Substring (0, pos);
74 static public string FileName;
77 // Initializes the symbol writer
79 static void InitializeSymbolWriter (string filename)
81 SymbolWriter = SymbolWriter.GetSymbolWriter (Module.Builder, filename);
84 // If we got an ISymbolWriter instance, initialize it.
86 if (SymbolWriter == null) {
88 -18, "Could not find the symbol writer assembly (Mono.CSharp.Debugger.dll). This is normally an installation problem. Please make sure to compile and install the mcs/class/Mono.CSharp.Debugger directory.");
94 // Initializes the code generator variables
96 static public void Init (string name, string output, bool want_debugging_support)
99 AssemblyName an = Assembly.GetAssemblyName (name, output);
101 if (an.KeyPair != null) {
102 // If we are going to strong name our assembly make
103 // sure all its refs are strong named
104 foreach (Assembly a in TypeManager.GetAssemblies ()) {
105 AssemblyName ref_name = a.GetName ();
106 byte [] b = ref_name.GetPublicKeyToken ();
107 if (b == null || b.Length == 0) {
108 Report.Warning (1577, "Assembly generation failed " +
109 "-- Referenced assembly '" +
111 "' does not have a strong name.");
112 //Environment.Exit (1);
117 current_domain = AppDomain.CurrentDomain;
120 Assembly.Builder = current_domain.DefineDynamicAssembly (an,
121 AssemblyBuilderAccess.Save, Dirname (name));
123 catch (ArgumentException) {
124 // specified key may not be exportable outside it's container
125 if (RootContext.StrongNameKeyContainer != null) {
126 Report.Error (1548, "Could not access the key inside the container `" +
127 RootContext.StrongNameKeyContainer + "'.");
128 Environment.Exit (1);
132 catch (CryptographicException) {
133 if ((RootContext.StrongNameKeyContainer != null) || (RootContext.StrongNameKeyFile != null)) {
134 Report.Error (1548, "Could not use the specified key to strongname the assembly.");
135 Environment.Exit (1);
141 // Pass a path-less name to DefineDynamicModule. Wonder how
142 // this copes with output in different directories then.
143 // FIXME: figure out how this copes with --output /tmp/blah
145 // If the third argument is true, the ModuleBuilder will dynamically
146 // load the default symbol writer.
148 Module.Builder = Assembly.Builder.DefineDynamicModule (
149 Basename (name), Basename (output), false);
151 if (want_debugging_support)
152 InitializeSymbolWriter (output);
155 static public void Save (string name)
158 Assembly.Builder.Save (Basename (name));
160 catch (COMException) {
161 if ((RootContext.StrongNameKeyFile == null) || (!RootContext.StrongNameDelaySign))
164 // FIXME: it seems Microsoft AssemblyBuilder doesn't like to delay sign assemblies
165 Report.Error (1548, "Couldn't delay-sign the assembly with the '" +
166 RootContext.StrongNameKeyFile +
167 "', Use MCS with the Mono runtime or CSC to compile this assembly.");
169 catch (System.IO.IOException io) {
170 Report.Error (16, "Could not write to file `"+name+"', cause: " + io.Message);
173 if (SymbolWriter != null)
174 SymbolWriter.WriteSymbolFile ();
179 // Provides "local" store across code that can yield: locals
180 // or fields, notice that this should not be used by anonymous
181 // methods to create local storage, those only require
184 public class VariableStorage {
190 public VariableStorage (EmitContext ec, Type t)
194 fb = ec.CurrentIterator.MapVariable ("s_", count.ToString (), t);
196 local = ec.ig.DeclareLocal (t);
199 public void EmitThis (ILGenerator ig)
202 ig.Emit (OpCodes.Ldarg_0);
205 public void EmitStore (ILGenerator ig)
208 ig.Emit (OpCodes.Stloc, local);
210 ig.Emit (OpCodes.Stfld, fb);
213 public void EmitLoad (ILGenerator ig)
216 ig.Emit (OpCodes.Ldloc, local);
218 ig.Emit (OpCodes.Ldfld, fb);
221 public void EmitLoadAddress (ILGenerator ig)
224 ig.Emit (OpCodes.Ldloca, local);
226 ig.Emit (OpCodes.Ldflda, fb);
229 public void EmitCall (ILGenerator ig, MethodInfo mi)
231 // FIXME : we should handle a call like tostring
232 // here, where boxing is needed. However, we will
233 // never encounter that with the current usage.
235 bool value_type_call;
238 value_type_call = local.LocalType.IsValueType;
241 ig.Emit (OpCodes.Ldloca, local);
243 ig.Emit (OpCodes.Ldloc, local);
245 value_type_call = fb.FieldType.IsValueType;
248 ig.Emit (OpCodes.Ldflda, fb);
250 ig.Emit (OpCodes.Ldfld, fb);
253 ig.Emit (value_type_call ? OpCodes.Call : OpCodes.Callvirt, mi);
258 /// An Emit Context is created for each body of code (from methods,
259 /// properties bodies, indexer bodies or constructor bodies)
261 public class EmitContext {
262 public DeclSpace DeclSpace;
263 public DeclSpace TypeContainer;
264 public ILGenerator ig;
267 /// This variable tracks the `checked' state of the compilation,
268 /// it controls whether we should generate code that does overflow
269 /// checking, or if we generate code that ignores overflows.
271 /// The default setting comes from the command line option to generate
272 /// checked or unchecked code plus any source code changes using the
273 /// checked/unchecked statements or expressions. Contrast this with
274 /// the ConstantCheckState flag.
277 public bool CheckState;
280 /// The constant check state is always set to `true' and cant be changed
281 /// from the command line. The source code can change this setting with
282 /// the `checked' and `unchecked' statements and expressions.
284 public bool ConstantCheckState;
287 /// Whether we are emitting code inside a static or instance method
289 public bool IsStatic;
292 /// Whether we are emitting a field initializer
294 public bool IsFieldInitializer;
297 /// The value that is allowed to be returned or NULL if there is no
300 public Type ReturnType;
303 /// Points to the Type (extracted from the TypeContainer) that
304 /// declares this body of code
306 public Type ContainerType;
309 /// Whether this is generating code for a constructor
311 public bool IsConstructor;
314 /// Whether we're control flow analysis enabled
316 public bool DoFlowAnalysis;
319 /// Keeps track of the Type to LocalBuilder temporary storage created
320 /// to store structures (used to compute the address of the structure
321 /// value on structure method invocations)
323 public Hashtable temporary_storage;
325 public Block CurrentBlock;
327 public int CurrentFile;
330 /// The location where we store the return value.
332 LocalBuilder return_value;
335 /// The location where return has to jump to return the
338 public Label ReturnLabel;
341 /// If we already defined the ReturnLabel
343 public bool HasReturnLabel;
346 /// Whether we are inside an iterator block.
348 public bool InIterator;
350 public bool IsLastStatement;
353 /// Whether remapping of locals, parameters and fields is turned on.
354 /// Used by iterators and anonymous methods.
356 public bool RemapToProxy;
359 /// Whether we are inside an unsafe block
361 public bool InUnsafe;
364 /// Whether we are in a `fixed' initialization
366 public bool InFixedInitializer;
369 /// Whether we are inside an anonymous method.
371 public AnonymousMethod CurrentAnonymousMethod;
374 /// Location for this EmitContext
379 /// Used to flag that it is ok to define types recursively, as the
380 /// expressions are being evaluated as part of the type lookup
381 /// during the type resolution process
383 public bool ResolvingTypeTree;
386 /// Inside an enum definition, we do not resolve enumeration values
387 /// to their enumerations, but rather to the underlying type/value
388 /// This is so EnumVal + EnumValB can be evaluated.
390 /// There is no "E operator + (E x, E y)", so during an enum evaluation
391 /// we relax the rules
393 public bool InEnumContext;
396 /// Anonymous methods can capture local variables and fields,
397 /// this object tracks it. It is copied from the TopLevelBlock
400 public CaptureContext capture_context;
403 /// Trace when method is called and is obsolete then this member suppress message
404 /// when call is inside next [Obsolete] method or type.
406 public bool TestObsoleteMethodUsage = true;
409 /// The current iterator
411 public Iterator CurrentIterator;
414 /// Whether we are in the resolving stage or not
424 FlowBranching current_flow_branching;
426 public EmitContext (DeclSpace parent, DeclSpace ds, Location l, ILGenerator ig,
427 Type return_type, int code_flags, bool is_constructor)
431 TypeContainer = parent;
433 CheckState = RootContext.Checked;
434 ConstantCheckState = true;
436 IsStatic = (code_flags & Modifiers.STATIC) != 0;
437 InIterator = (code_flags & Modifiers.METHOD_YIELDS) != 0;
438 RemapToProxy = InIterator;
439 ReturnType = return_type;
440 IsConstructor = is_constructor;
443 current_phase = Phase.Created;
446 // Can only be null for the ResolveType contexts.
447 ContainerType = parent.TypeBuilder;
448 if (parent.UnsafeContext)
451 InUnsafe = (code_flags & Modifiers.UNSAFE) != 0;
455 if (ReturnType == TypeManager.void_type)
459 public EmitContext (TypeContainer tc, Location l, ILGenerator ig,
460 Type return_type, int code_flags, bool is_constructor)
461 : this (tc, tc, l, ig, return_type, code_flags, is_constructor)
465 public EmitContext (TypeContainer tc, Location l, ILGenerator ig,
466 Type return_type, int code_flags)
467 : this (tc, tc, l, ig, return_type, code_flags, false)
471 public FlowBranching CurrentBranching {
473 return current_flow_branching;
477 public bool HaveCaptureInfo {
479 return capture_context != null;
484 // Starts a new code branching. This inherits the state of all local
485 // variables and parameters from the current branching.
487 public FlowBranching StartFlowBranching (FlowBranching.BranchingType type, Location loc)
489 current_flow_branching = FlowBranching.CreateBranching (CurrentBranching, type, null, loc);
490 return current_flow_branching;
494 // Starts a new code branching for block `block'.
496 public FlowBranching StartFlowBranching (Block block)
498 FlowBranching.BranchingType type;
500 if (CurrentBranching.Type == FlowBranching.BranchingType.Switch)
501 type = FlowBranching.BranchingType.SwitchSection;
503 type = FlowBranching.BranchingType.Block;
505 current_flow_branching = FlowBranching.CreateBranching (CurrentBranching, type, block, block.StartLocation);
506 return current_flow_branching;
509 public FlowBranchingException StartFlowBranching (ExceptionStatement stmt)
511 FlowBranchingException branching = new FlowBranchingException (
512 CurrentBranching, stmt);
513 current_flow_branching = branching;
518 // Ends a code branching. Merges the state of locals and parameters
519 // from all the children of the ending branching.
521 public FlowBranching.UsageVector DoEndFlowBranching ()
523 FlowBranching old = current_flow_branching;
524 current_flow_branching = current_flow_branching.Parent;
526 return current_flow_branching.MergeChild (old);
530 // Ends a code branching. Merges the state of locals and parameters
531 // from all the children of the ending branching.
533 public FlowBranching.Reachability EndFlowBranching ()
535 FlowBranching.UsageVector vector = DoEndFlowBranching ();
537 return vector.Reachability;
541 // Kills the current code branching. This throws away any changed state
542 // information and should only be used in case of an error.
544 public void KillFlowBranching ()
546 current_flow_branching = current_flow_branching.Parent;
549 public void CaptureVariable (LocalInfo li)
551 capture_context.AddLocal (CurrentAnonymousMethod, li);
552 li.IsCaptured = true;
555 public void CaptureParameter (string name, Type t, int idx)
558 capture_context.AddParameter (this, CurrentAnonymousMethod, name, t, idx);
562 // Use to register a field as captured
564 public void CaptureField (FieldExpr fe)
566 capture_context.AddField (fe);
570 // Whether anonymous methods have captured variables
572 public bool HaveCapturedVariables ()
574 if (capture_context != null)
575 return capture_context.HaveCapturedVariables;
580 // Whether anonymous methods have captured fields or this.
582 public bool HaveCapturedFields ()
584 if (capture_context != null)
585 return capture_context.HaveCapturedFields;
590 // Emits the instance pointer for the host method
592 public void EmitMethodHostInstance (EmitContext target, AnonymousMethod am)
594 if (capture_context != null)
595 capture_context.EmitMethodHostInstance (target, am);
597 target.ig.Emit (OpCodes.Ldnull);
599 target.ig.Emit (OpCodes.Ldarg_0);
603 // Returns whether the `local' variable has been captured by an anonymous
606 public bool IsCaptured (LocalInfo local)
608 return capture_context.IsCaptured (local);
611 public bool IsParameterCaptured (string name)
613 if (capture_context != null)
614 return capture_context.IsParameterCaptured (name);
618 public void EmitMeta (ToplevelBlock b, InternalParameters ip)
620 if (capture_context != null)
621 capture_context.EmitHelperClasses (this);
625 ReturnLabel = ig.DefineLabel ();
629 // Here until we can fix the problem with Mono.CSharp.Switch, which
630 // currently can not cope with ig == null during resolve (which must
631 // be fixed for switch statements to work on anonymous methods).
633 public void EmitTopBlock (ToplevelBlock block, InternalParameters ip, Location loc)
640 if (ResolveTopBlock (null, block, ip, loc, out unreachable)){
641 EmitMeta (block, ip);
643 current_phase = Phase.Emitting;
644 EmitResolvedTopBlock (block, unreachable);
648 public bool ResolveTopBlock (EmitContext anonymous_method_host, ToplevelBlock block,
649 InternalParameters ip, Location loc, out bool unreachable)
651 current_phase = Phase.Resolving;
655 capture_context = block.CaptureContext;
657 if (!Location.IsNull (loc))
658 CurrentFile = loc.File;
663 int errors = Report.Errors;
665 block.ResolveMeta (block, this, ip);
668 if (Report.Errors == errors){
669 bool old_do_flow_analysis = DoFlowAnalysis;
670 DoFlowAnalysis = true;
672 if (anonymous_method_host != null)
673 current_flow_branching = FlowBranching.CreateBranching (
674 anonymous_method_host.CurrentBranching, FlowBranching.BranchingType.Block,
677 current_flow_branching = FlowBranching.CreateBranching (
678 null, FlowBranching.BranchingType.Block, block, loc);
680 if (!block.Resolve (this)) {
681 current_flow_branching = null;
682 DoFlowAnalysis = old_do_flow_analysis;
686 FlowBranching.Reachability reachability = current_flow_branching.MergeTopBlock ();
687 current_flow_branching = null;
689 DoFlowAnalysis = old_do_flow_analysis;
691 if (reachability.AlwaysReturns ||
692 reachability.AlwaysThrows ||
693 reachability.IsUnreachable)
697 } catch (Exception e) {
698 Console.WriteLine ("Exception caught by the compiler while compiling:");
699 Console.WriteLine (" Block that caused the problem begin at: " + loc);
701 if (CurrentBlock != null){
702 Console.WriteLine (" Block being compiled: [{0},{1}]",
703 CurrentBlock.StartLocation, CurrentBlock.EndLocation);
705 Console.WriteLine (e.GetType ().FullName + ": " + e.Message);
710 if (ReturnType != null && !unreachable){
712 if (CurrentAnonymousMethod != null){
713 Report.Error (1643, loc, "Not all code paths return a value in anonymous method of type `{0}'",
714 CurrentAnonymousMethod.Type);
716 Report.Error (161, loc, "Not all code paths return a value");
722 block.CompleteContexts ();
727 public void EmitResolvedTopBlock (ToplevelBlock block, bool unreachable)
733 ig.MarkLabel (ReturnLabel);
735 if (return_value != null){
736 ig.Emit (OpCodes.Ldloc, return_value);
737 ig.Emit (OpCodes.Ret);
740 // If `HasReturnLabel' is set, then we already emitted a
741 // jump to the end of the method, so we must emit a `ret'
744 // Unfortunately, System.Reflection.Emit automatically emits
745 // a leave to the end of a finally block. This is a problem
746 // if no code is following the try/finally block since we may
747 // jump to a point after the end of the method.
748 // As a workaround, we're always creating a return label in
752 if ((block != null) && block.IsDestructor) {
753 // Nothing to do; S.R.E automatically emits a leave.
754 } else if (HasReturnLabel || (!unreachable && !InIterator)) {
755 if (ReturnType != null)
756 ig.Emit (OpCodes.Ldloc, TemporaryReturn ());
757 ig.Emit (OpCodes.Ret);
762 // Close pending helper classes if we are the toplevel
764 if (capture_context != null && capture_context.ParentToplevel == null)
765 capture_context.CloseHelperClasses ();
769 /// This is called immediately before emitting an IL opcode to tell the symbol
770 /// writer to which source line this opcode belongs.
772 public void Mark (Location loc, bool check_file)
774 if ((CodeGen.SymbolWriter == null) || Location.IsNull (loc))
777 if (check_file && (CurrentFile != loc.File))
780 CodeGen.SymbolWriter.MarkSequencePoint (ig, loc.Row, 0);
783 public void DefineLocalVariable (string name, LocalBuilder builder)
785 if (CodeGen.SymbolWriter == null)
788 CodeGen.SymbolWriter.DefineLocalVariable (name, builder);
792 /// Returns a temporary storage for a variable of type t as
793 /// a local variable in the current body.
795 public LocalBuilder GetTemporaryLocal (Type t)
797 LocalBuilder location = null;
799 if (temporary_storage != null){
800 object o = temporary_storage [t];
803 ArrayList al = (ArrayList) o;
805 for (int i = 0; i < al.Count; i++){
807 location = (LocalBuilder) al [i];
813 location = (LocalBuilder) o;
814 if (location != null)
819 return ig.DeclareLocal (t);
822 public void FreeTemporaryLocal (LocalBuilder b, Type t)
824 if (temporary_storage == null){
825 temporary_storage = new Hashtable ();
826 temporary_storage [t] = b;
829 object o = temporary_storage [t];
831 temporary_storage [t] = b;
835 ArrayList al = (ArrayList) o;
836 for (int i = 0; i < al.Count; i++){
845 ArrayList replacement = new ArrayList ();
847 temporary_storage.Remove (t);
848 temporary_storage [t] = replacement;
852 /// Current loop begin and end labels.
854 public Label LoopBegin, LoopEnd;
857 /// Default target in a switch statement. Only valid if
860 public Label DefaultTarget;
863 /// If this is non-null, points to the current switch statement
865 public Switch Switch;
868 /// ReturnValue creates on demand the LocalBuilder for the
869 /// return value from the function. By default this is not
870 /// used. This is only required when returns are found inside
871 /// Try or Catch statements.
873 /// This method is typically invoked from the Emit phase, so
874 /// we allow the creation of a return label if it was not
875 /// requested during the resolution phase. Could be cleaned
876 /// up, but it would replicate a lot of logic in the Emit phase
877 /// of the code that uses it.
879 public LocalBuilder TemporaryReturn ()
881 if (return_value == null){
882 return_value = ig.DeclareLocal (ReturnType);
883 if (!HasReturnLabel){
884 ReturnLabel = ig.DefineLabel ();
885 HasReturnLabel = true;
893 /// This method is used during the Resolution phase to flag the
894 /// need to define the ReturnLabel
896 public void NeedReturnLabel ()
898 if (current_phase != Phase.Resolving){
900 // The reason is that the `ReturnLabel' is declared between
901 // resolution and emission
903 throw new Exception ("NeedReturnLabel called from Emit phase, should only be called during Resolve");
906 if (!InIterator && !HasReturnLabel)
907 HasReturnLabel = true;
911 // Creates a field `name' with the type `t' on the proxy class
913 public FieldBuilder MapVariable (string name, Type t)
916 return CurrentIterator.MapVariable ("v_", name, t);
918 throw new Exception ("MapVariable for an unknown state");
921 public Expression RemapParameter (int idx)
923 FieldExpr fe = new FieldExprNoAddress (CurrentIterator.parameter_fields [idx].FieldBuilder, loc);
924 fe.InstanceExpression = new ProxyInstance ();
925 return fe.DoResolve (this);
928 public Expression RemapParameterLValue (int idx, Expression right_side)
930 FieldExpr fe = new FieldExprNoAddress (CurrentIterator.parameter_fields [idx].FieldBuilder, loc);
931 fe.InstanceExpression = new ProxyInstance ();
932 return fe.DoResolveLValue (this, right_side);
936 // Emits the proper object to address fields on a remapped
937 // variable/parameter to field in anonymous-method/iterator proxy classes.
939 public void EmitThis ()
941 ig.Emit (OpCodes.Ldarg_0);
944 FieldBuilder this_field = CurrentIterator.this_field.FieldBuilder;
945 if (TypeManager.IsValueType (this_field.FieldType))
946 ig.Emit (OpCodes.Ldflda, this_field);
948 ig.Emit (OpCodes.Ldfld, this_field);
950 } else if (capture_context != null && CurrentAnonymousMethod != null){
951 ScopeInfo si = CurrentAnonymousMethod.Scope;
953 if (si.ParentLink != null)
954 ig.Emit (OpCodes.Ldfld, si.ParentLink);
955 if (si.THIS != null){
956 ig.Emit (OpCodes.Ldfld, si.THIS);
965 // Emits the code necessary to load the instance required
966 // to access the captured LocalInfo
968 public void EmitCapturedVariableInstance (LocalInfo li)
971 ig.Emit (OpCodes.Ldarg_0);
975 if (capture_context == null)
976 throw new Exception ("Calling EmitCapturedContext when there is no capture_context");
978 capture_context.EmitCapturedVariableInstance (this, li, CurrentAnonymousMethod);
981 public void EmitParameter (string name)
983 capture_context.EmitParameter (this, name);
986 public void EmitAssignParameter (string name, Expression source, bool leave_copy, bool prepare_for_load)
988 capture_context.EmitAssignParameter (this, name, source, leave_copy, prepare_for_load);
991 public void EmitAddressOfParameter (string name)
993 capture_context.EmitAddressOfParameter (this, name);
996 public Expression GetThis (Location loc)
999 if (CurrentBlock != null)
1000 my_this = new This (CurrentBlock, loc);
1002 my_this = new This (loc);
1004 if (!my_this.ResolveBase (this))
1012 public abstract class CommonAssemblyModulClass: Attributable {
1013 protected CommonAssemblyModulClass ():
1018 public void AddAttributes (ArrayList attrs)
1020 if (OptAttributes == null) {
1021 OptAttributes = new Attributes (attrs);
1024 OptAttributes.AddAttributes (attrs);
1025 OptAttributes.CheckTargets (this);
1028 public virtual void Emit (TypeContainer tc)
1030 if (OptAttributes == null)
1033 EmitContext ec = new EmitContext (tc, Mono.CSharp.Location.Null, null, null, 0, false);
1034 OptAttributes.Emit (ec, this);
1037 protected Attribute GetClsCompliantAttribute ()
1039 if (OptAttributes == null)
1042 EmitContext temp_ec = new EmitContext (new RootTypes (), Mono.CSharp.Location.Null, null, null, 0, false);
1043 Attribute a = OptAttributes.Search (TypeManager.cls_compliant_attribute_type, temp_ec);
1045 a.Resolve (temp_ec);
1051 public class AssemblyClass: CommonAssemblyModulClass {
1052 // TODO: make it private and move all builder based methods here
1053 public AssemblyBuilder Builder;
1054 bool is_cls_compliant;
1056 static string[] attribute_targets = new string [] { "assembly" };
1058 public AssemblyClass (): base ()
1060 is_cls_compliant = false;
1063 public bool IsClsCompliant {
1065 return is_cls_compliant;
1069 public override AttributeTargets AttributeTargets {
1071 return AttributeTargets.Assembly;
1075 public override bool IsClsCompliaceRequired(DeclSpace ds)
1077 return is_cls_compliant;
1080 public void ResolveClsCompliance ()
1082 Attribute a = GetClsCompliantAttribute ();
1086 is_cls_compliant = a.GetClsCompliantAttributeValue (null);
1090 private void SetPublicKey (AssemblyName an, byte[] strongNameBlob)
1093 // check for possible ECMA key
1094 if (strongNameBlob.Length == 16) {
1095 // will be rejected if not "the" ECMA key
1096 an.SetPublicKey (strongNameBlob);
1099 // take it, with or without, a private key
1100 RSA rsa = CryptoConvert.FromCapiKeyBlob (strongNameBlob);
1101 // and make sure we only feed the public part to Sys.Ref
1102 byte[] publickey = CryptoConvert.ToCapiPublicKeyBlob (rsa);
1104 // AssemblyName.SetPublicKey requires an additional header
1105 byte[] publicKeyHeader = new byte [12] { 0x00, 0x24, 0x00, 0x00, 0x04, 0x80, 0x00, 0x00, 0x94, 0x00, 0x00, 0x00 };
1107 byte[] encodedPublicKey = new byte [12 + publickey.Length];
1108 Buffer.BlockCopy (publicKeyHeader, 0, encodedPublicKey, 0, 12);
1109 Buffer.BlockCopy (publickey, 0, encodedPublicKey, 12, publickey.Length);
1110 an.SetPublicKey (encodedPublicKey);
1114 Report.Error (1548, "Could not strongname the assembly. File `" +
1115 RootContext.StrongNameKeyFile + "' incorrectly encoded.");
1116 Environment.Exit (1);
1120 public AssemblyName GetAssemblyName (string name, string output)
1122 if (OptAttributes != null) {
1123 foreach (Attribute a in OptAttributes.Attrs) {
1124 if (a.Target != AttributeTargets.Assembly)
1126 // TODO: This code is buggy: comparing Attribute name without resolving it is wrong.
1127 // However, this is invoked by CodeGen.Init, at which time none of the namespaces
1130 case "AssemblyKeyFile":
1131 case "AssemblyKeyFileAttribute":
1132 case "System.Reflection.AssemblyKeyFileAttribute":
1133 if (RootContext.StrongNameKeyFile != null) {
1134 Report.SymbolRelatedToPreviousError (a.Location, a.Name);
1135 Report.Warning (1616, "Compiler option '{0}' overrides '{1}' given in source", "keyfile", "System.Reflection.AssemblyKeyFileAttribute");
1138 string value = a.GetString ();
1139 if (value != String.Empty)
1140 RootContext.StrongNameKeyFile = value;
1143 case "AssemblyKeyName":
1144 case "AssemblyKeyNameAttribute":
1145 case "System.Reflection.AssemblyKeyNameAttribute":
1146 if (RootContext.StrongNameKeyContainer != null) {
1147 Report.SymbolRelatedToPreviousError (a.Location, a.Name);
1148 Report.Warning (1616, "keycontainer", "Compiler option '{0}' overrides '{1}' given in source", "System.Reflection.AssemblyKeyNameAttribute");
1151 string value = a.GetString ();
1152 if (value != String.Empty)
1153 RootContext.StrongNameKeyContainer = value;
1156 case "AssemblyDelaySign":
1157 case "AssemblyDelaySignAttribute":
1158 case "System.Reflection.AssemblyDelaySignAttribute":
1159 RootContext.StrongNameDelaySign = a.GetBoolean ();
1165 AssemblyName an = new AssemblyName ();
1166 an.Name = Path.GetFileNameWithoutExtension (name);
1168 // note: delay doesn't apply when using a key container
1169 if (RootContext.StrongNameKeyContainer != null) {
1170 an.KeyPair = new StrongNameKeyPair (RootContext.StrongNameKeyContainer);
1174 // strongname is optional
1175 if (RootContext.StrongNameKeyFile == null)
1178 string AssemblyDir = Path.GetDirectoryName (output);
1180 // the StrongName key file may be relative to (a) the compiled
1181 // file or (b) to the output assembly. See bugzilla #55320
1182 // http://bugzilla.ximian.com/show_bug.cgi?id=55320
1184 // (a) relative to the compiled file
1185 string filename = Path.GetFullPath (RootContext.StrongNameKeyFile);
1186 bool exist = File.Exists (filename);
1187 if ((!exist) && (AssemblyDir != null) && (AssemblyDir != String.Empty)) {
1188 // (b) relative to the outputed assembly
1189 filename = Path.GetFullPath (Path.Combine (AssemblyDir, RootContext.StrongNameKeyFile));
1190 exist = File.Exists (filename);
1194 using (FileStream fs = new FileStream (filename, FileMode.Open, FileAccess.Read)) {
1195 byte[] snkeypair = new byte [fs.Length];
1196 fs.Read (snkeypair, 0, snkeypair.Length);
1198 if (RootContext.StrongNameDelaySign) {
1199 // delayed signing - DO NOT include private key
1200 SetPublicKey (an, snkeypair);
1203 // no delay so we make sure we have the private key
1205 CryptoConvert.FromCapiPrivateKeyBlob (snkeypair);
1206 an.KeyPair = new StrongNameKeyPair (snkeypair);
1208 catch (CryptographicException) {
1209 if (snkeypair.Length == 16) {
1210 // error # is different for ECMA key
1211 Report.Error (1606, "Could not strongname the assembly. " +
1212 "ECMA key can only be used to delay-sign assemblies");
1215 Report.Error (1548, "Could not strongname the assembly. File `" +
1216 RootContext.StrongNameKeyFile +
1217 "' doesn't have a private key.");
1219 Environment.Exit (1);
1225 Report.Error (1548, "Could not strongname the assembly. File `" +
1226 RootContext.StrongNameKeyFile + "' not found.");
1227 Environment.Exit (1);
1232 public override void ApplyAttributeBuilder (Attribute a, CustomAttributeBuilder customBuilder)
1234 Builder.SetCustomAttribute (customBuilder);
1237 public override string[] ValidAttributeTargets {
1239 return attribute_targets;
1244 public class ModuleClass: CommonAssemblyModulClass {
1245 // TODO: make it private and move all builder based methods here
1246 public ModuleBuilder Builder;
1247 bool m_module_is_unsafe;
1249 static string[] attribute_targets = new string [] { "module" };
1251 public ModuleClass (bool is_unsafe)
1253 m_module_is_unsafe = is_unsafe;
1256 public override AttributeTargets AttributeTargets {
1258 return AttributeTargets.Module;
1262 public override bool IsClsCompliaceRequired(DeclSpace ds)
1264 return CodeGen.Assembly.IsClsCompliant;
1267 public override void Emit (TypeContainer tc)
1271 if (!m_module_is_unsafe)
1274 if (TypeManager.unverifiable_code_ctor == null) {
1275 Console.WriteLine ("Internal error ! Cannot set unverifiable code attribute.");
1279 ApplyAttributeBuilder (null, new CustomAttributeBuilder (TypeManager.unverifiable_code_ctor, new object [0]));
1282 public override void ApplyAttributeBuilder (Attribute a, CustomAttributeBuilder customBuilder)
1284 if (a != null && a.Type == TypeManager.cls_compliant_attribute_type) {
1285 Report.Warning (3012, a.Location, "You must specify the CLSCompliant attribute on the assembly, not the module, to enable CLS compliance checking");
1289 Builder.SetCustomAttribute (customBuilder);
1292 public override string[] ValidAttributeTargets {
1294 return attribute_targets;