2 // codegen.cs: The code generator
5 // Miguel de Icaza (miguel@ximian.com)
7 // Copyright 2001, 2002, 2003 Ximian, Inc.
8 // Copyright 2004 Novell, Inc.
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.
16 // Only remove it if you need to debug locally on your tree.
22 using System.Collections.Generic;
23 using System.Globalization;
24 using System.Reflection;
25 using System.Reflection.Emit;
26 using System.Runtime.InteropServices;
27 using System.Security;
28 using System.Security.Cryptography;
29 using System.Security.Permissions;
31 using Mono.Security.Cryptography;
33 namespace Mono.CSharp {
36 /// Code generator class.
38 public class CodeGen {
39 static AppDomain current_domain;
41 public static AssemblyClass Assembly;
48 public static void Reset ()
50 Assembly = new AssemblyClass ();
53 public static string Basename (string name)
55 int pos = name.LastIndexOf ('/');
58 return name.Substring (pos + 1);
60 pos = name.LastIndexOf ('\\');
62 return name.Substring (pos + 1);
67 public static string Dirname (string name)
69 int pos = name.LastIndexOf ('/');
72 return name.Substring (0, pos);
74 pos = name.LastIndexOf ('\\');
76 return name.Substring (0, pos);
81 static public string FileName;
84 const AssemblyBuilderAccess COMPILER_ACCESS = 0;
86 /* Keep this in sync with System.Reflection.Emit.AssemblyBuilder */
87 const AssemblyBuilderAccess COMPILER_ACCESS = (AssemblyBuilderAccess) 0x800;
91 // Initializes the code generator variables for interactive use (repl)
93 static public void InitDynamic (CompilerContext ctx, string name)
95 current_domain = AppDomain.CurrentDomain;
96 AssemblyName an = Assembly.GetAssemblyName (name, name);
98 Assembly.Builder = current_domain.DefineDynamicAssembly (an, AssemblyBuilderAccess.Run | COMPILER_ACCESS);
99 RootContext.ToplevelTypes = new ModuleCompiled (ctx, true);
100 RootContext.ToplevelTypes.Builder = Assembly.Builder.DefineDynamicModule (Basename (name), false);
101 Assembly.Name = Assembly.Builder.GetName ();
105 // Initializes the code generator variables
107 static public bool Init (string name, string output, bool want_debugging_support, CompilerContext ctx)
110 AssemblyName an = Assembly.GetAssemblyName (name, output);
114 if (an.KeyPair != null) {
115 // If we are going to strong name our assembly make
116 // sure all its refs are strong named
117 foreach (Assembly a in GlobalRootNamespace.Instance.Assemblies) {
118 AssemblyName ref_name = a.GetName ();
119 byte [] b = ref_name.GetPublicKeyToken ();
120 if (b == null || b.Length == 0) {
121 ctx.Report.Error (1577, "Assembly generation failed " +
122 "-- Referenced assembly '" +
124 "' does not have a strong name.");
125 //Environment.Exit (1);
130 current_domain = AppDomain.CurrentDomain;
133 Assembly.Builder = current_domain.DefineDynamicAssembly (an,
134 AssemblyBuilderAccess.RunAndSave | COMPILER_ACCESS, Dirname (name));
136 catch (ArgumentException) {
137 // specified key may not be exportable outside it's container
138 if (RootContext.StrongNameKeyContainer != null) {
139 ctx.Report.Error (1548, "Could not access the key inside the container `" +
140 RootContext.StrongNameKeyContainer + "'.");
141 Environment.Exit (1);
145 catch (CryptographicException) {
146 if ((RootContext.StrongNameKeyContainer != null) || (RootContext.StrongNameKeyFile != null)) {
147 ctx.Report.Error (1548, "Could not use the specified key to strongname the assembly.");
148 Environment.Exit (1);
153 // Get the complete AssemblyName from the builder
154 // (We need to get the public key and token)
155 Assembly.Name = Assembly.Builder.GetName ();
158 // Pass a path-less name to DefineDynamicModule. Wonder how
159 // this copes with output in different directories then.
160 // FIXME: figure out how this copes with --output /tmp/blah
162 // If the third argument is true, the ModuleBuilder will dynamically
163 // load the default symbol writer.
166 RootContext.ToplevelTypes.Builder = Assembly.Builder.DefineDynamicModule (
167 Basename (name), Basename (output), want_debugging_support);
170 // TODO: We should use SymbolWriter from DefineDynamicModule
171 if (want_debugging_support && !SymbolWriter.Initialize (RootContext.ToplevelTypes.Builder, output)) {
172 ctx.Report.Error (40, "Unexpected debug information initialization error `{0}'",
173 "Could not find the symbol writer assembly (Mono.CompilerServices.SymbolWriter.dll)");
177 } catch (ExecutionEngineException e) {
178 ctx.Report.Error (40, "Unexpected debug information initialization error `{0}'",
186 static public void Save (string name, bool saveDebugInfo, Report Report)
188 PortableExecutableKinds pekind;
189 ImageFileMachine machine;
191 switch (RootContext.Platform) {
193 pekind = PortableExecutableKinds.Required32Bit;
194 machine = ImageFileMachine.I386;
197 pekind = PortableExecutableKinds.PE32Plus;
198 machine = ImageFileMachine.AMD64;
201 pekind = PortableExecutableKinds.PE32Plus;
202 machine = ImageFileMachine.IA64;
204 case Platform.AnyCPU:
206 pekind = PortableExecutableKinds.ILOnly;
207 machine = ImageFileMachine.I386;
211 Assembly.Builder.Save (Basename (name), pekind, machine);
213 catch (COMException) {
214 if ((RootContext.StrongNameKeyFile == null) || (!RootContext.StrongNameDelaySign))
217 // FIXME: it seems Microsoft AssemblyBuilder doesn't like to delay sign assemblies
218 Report.Error (1548, "Couldn't delay-sign the assembly with the '" +
219 RootContext.StrongNameKeyFile +
220 "', Use MCS with the Mono runtime or CSC to compile this assembly.");
222 catch (System.IO.IOException io) {
223 Report.Error (16, "Could not write to file `"+name+"', cause: " + io.Message);
226 catch (System.UnauthorizedAccessException ua) {
227 Report.Error (16, "Could not write to file `"+name+"', cause: " + ua.Message);
230 catch (System.NotImplementedException nie) {
231 Report.RuntimeMissingSupport (Location.Null, nie.Message);
236 // Write debuger symbol file
239 SymbolWriter.WriteSymbolFile ();
244 /// An Emit Context is created for each body of code (from methods,
245 /// properties bodies, indexer bodies or constructor bodies)
247 public class EmitContext : BuilderContext
249 // TODO: Has to be private
250 public ILGenerator ig;
253 /// The value that is allowed to be returned or NULL if there is no
256 TypeSpec return_type;
259 /// Keeps track of the Type to LocalBuilder temporary storage created
260 /// to store structures (used to compute the address of the structure
261 /// value on structure method invocations)
263 Dictionary<TypeSpec, object> temporary_storage;
266 /// The location where we store the return value.
268 public LocalBuilder return_value;
271 /// The location where return has to jump to return the
274 public Label ReturnLabel;
277 /// If we already defined the ReturnLabel
279 public bool HasReturnLabel;
282 /// Current loop begin and end labels.
284 public Label LoopBegin, LoopEnd;
287 /// Default target in a switch statement. Only valid if
290 public Label DefaultTarget;
293 /// If this is non-null, points to the current switch statement
295 public Switch Switch;
298 /// Whether we are inside an anonymous method.
300 public AnonymousExpression CurrentAnonymousMethod;
302 public readonly IMemberContext MemberContext;
304 public EmitContext (IMemberContext rc, ILGenerator ig, TypeSpec return_type)
306 this.MemberContext = rc;
309 this.return_type = return_type;
314 public TypeSpec CurrentType {
315 get { return MemberContext.CurrentType; }
318 public TypeParameter[] CurrentTypeParameters {
319 get { return MemberContext.CurrentTypeParameters; }
322 public MemberCore CurrentTypeDefinition {
323 get { return MemberContext.CurrentMemberDefinition; }
326 public bool IsStatic {
327 get { return MemberContext.IsStatic; }
330 bool IsAnonymousStoreyMutateRequired {
332 return CurrentAnonymousMethod != null &&
333 CurrentAnonymousMethod.Storey != null &&
334 CurrentAnonymousMethod.Storey.Mutator != null;
338 // Has to be used for emitter errors only
339 public Report Report {
340 get { return MemberContext.Compiler.Report; }
343 public TypeSpec ReturnType {
351 /// This is called immediately before emitting an IL opcode to tell the symbol
352 /// writer to which source line this opcode belongs.
354 public void Mark (Location loc)
356 if (!SymbolWriter.HasSymbolWriter || HasSet (Options.OmitDebugInfo) || loc.IsNull)
359 SymbolWriter.MarkSequencePoint (ig, loc);
362 public void DefineLocalVariable (string name, LocalBuilder builder)
364 SymbolWriter.DefineLocalVariable (name, builder);
367 public void BeginCatchBlock (TypeSpec type)
369 ig.BeginCatchBlock (type.GetMetaInfo ());
372 public void BeginExceptionBlock ()
374 ig.BeginExceptionBlock ();
377 public void BeginFinallyBlock ()
379 ig.BeginFinallyBlock ();
382 public void BeginScope ()
385 SymbolWriter.OpenScope(ig);
388 public void EndExceptionBlock ()
390 ig.EndExceptionBlock ();
393 public void EndScope ()
396 SymbolWriter.CloseScope(ig);
399 public LocalBuilder DeclareLocal (TypeSpec type, bool pinned)
401 if (IsAnonymousStoreyMutateRequired)
402 type = CurrentAnonymousMethod.Storey.Mutator.Mutate (type);
404 return ig.DeclareLocal (type.GetMetaInfo (), pinned);
407 public Label DefineLabel ()
409 return ig.DefineLabel ();
412 public void MarkLabel (Label label)
414 ig.MarkLabel (label);
417 public void Emit (OpCode opcode)
422 public void Emit (OpCode opcode, LocalBuilder local)
424 ig.Emit (opcode, local);
427 public void Emit (OpCode opcode, string arg)
429 ig.Emit (opcode, arg);
432 public void Emit (OpCode opcode, double arg)
434 ig.Emit (opcode, arg);
437 public void Emit (OpCode opcode, float arg)
439 ig.Emit (opcode, arg);
442 public void Emit (OpCode opcode, int arg)
444 ig.Emit (opcode, arg);
447 public void Emit (OpCode opcode, byte arg)
449 ig.Emit (opcode, arg);
452 public void Emit (OpCode opcode, Label label)
454 ig.Emit (opcode, label);
457 public void Emit (OpCode opcode, Label[] labels)
459 ig.Emit (opcode, labels);
462 public void Emit (OpCode opcode, TypeSpec type)
464 if (IsAnonymousStoreyMutateRequired)
465 type = CurrentAnonymousMethod.Storey.Mutator.Mutate (type);
467 ig.Emit (opcode, type.GetMetaInfo ());
470 public void Emit (OpCode opcode, FieldSpec field)
472 if (IsAnonymousStoreyMutateRequired)
473 field = field.Mutate (CurrentAnonymousMethod.Storey.Mutator);
475 ig.Emit (opcode, field.GetMetaInfo ());
478 public void Emit (OpCode opcode, MethodSpec method)
480 if (IsAnonymousStoreyMutateRequired)
481 method = method.Mutate (CurrentAnonymousMethod.Storey.Mutator);
483 if (method.IsConstructor)
484 ig.Emit (opcode, (ConstructorInfo) method.GetMetaInfo ());
486 ig.Emit (opcode, (MethodInfo) method.GetMetaInfo ());
489 // TODO: REMOVE breaks mutator
490 public void Emit (OpCode opcode, MethodInfo method)
492 ig.Emit (opcode, method);
495 // TODO: REMOVE breaks mutator
496 public void Emit (OpCode opcode, FieldBuilder field)
498 ig.Emit (opcode, field);
501 public void Emit (OpCode opcode, MethodSpec method, Type[] vargs)
503 // TODO MemberCache: This should mutate too
504 ig.EmitCall (opcode, (MethodInfo) method.GetMetaInfo (), vargs);
507 public void EmitArrayNew (ArrayContainer ac)
510 Emit (OpCodes.Newarr, ac.Element);
512 if (IsAnonymousStoreyMutateRequired)
513 ac = (ArrayContainer) ac.Mutate (CurrentAnonymousMethod.Storey.Mutator);
515 ig.Emit (OpCodes.Newobj, ac.GetConstructor ());
520 // Emits the right opcode to load from an array
522 public void EmitArrayLoad (ArrayContainer ac)
525 if (IsAnonymousStoreyMutateRequired)
526 ac = (ArrayContainer) ac.Mutate (CurrentAnonymousMethod.Storey.Mutator);
528 ig.Emit (OpCodes.Call, ac.GetGetMethod ());
532 var type = ac.Element;
533 if (TypeManager.IsEnumType (type))
534 type = EnumSpec.GetUnderlyingType (type);
536 if (type == TypeManager.byte_type || type == TypeManager.bool_type)
537 Emit (OpCodes.Ldelem_U1);
538 else if (type == TypeManager.sbyte_type)
539 Emit (OpCodes.Ldelem_I1);
540 else if (type == TypeManager.short_type)
541 Emit (OpCodes.Ldelem_I2);
542 else if (type == TypeManager.ushort_type || type == TypeManager.char_type)
543 Emit (OpCodes.Ldelem_U2);
544 else if (type == TypeManager.int32_type)
545 Emit (OpCodes.Ldelem_I4);
546 else if (type == TypeManager.uint32_type)
547 Emit (OpCodes.Ldelem_U4);
548 else if (type == TypeManager.uint64_type)
549 Emit (OpCodes.Ldelem_I8);
550 else if (type == TypeManager.int64_type)
551 Emit (OpCodes.Ldelem_I8);
552 else if (type == TypeManager.float_type)
553 Emit (OpCodes.Ldelem_R4);
554 else if (type == TypeManager.double_type)
555 Emit (OpCodes.Ldelem_R8);
556 else if (type == TypeManager.intptr_type)
557 Emit (OpCodes.Ldelem_I);
558 else if (TypeManager.IsStruct (type)) {
559 Emit (OpCodes.Ldelema, type);
560 Emit (OpCodes.Ldobj, type);
561 } else if (type.IsGenericParameter) {
562 Emit (OpCodes.Ldelem, type);
563 } else if (type.IsPointer)
564 Emit (OpCodes.Ldelem_I);
566 Emit (OpCodes.Ldelem_Ref);
570 // Emits the right opcode to store to an array
572 public void EmitArrayStore (ArrayContainer ac)
575 if (IsAnonymousStoreyMutateRequired)
576 ac = (ArrayContainer) ac.Mutate (CurrentAnonymousMethod.Storey.Mutator);
578 ig.Emit (OpCodes.Call, ac.GetSetMethod ());
582 var type = ac.Element;
585 type = EnumSpec.GetUnderlyingType (type);
587 if (type == TypeManager.byte_type || type == TypeManager.sbyte_type || type == TypeManager.bool_type)
588 Emit (OpCodes.Stelem_I1);
589 else if (type == TypeManager.short_type || type == TypeManager.ushort_type || type == TypeManager.char_type)
590 Emit (OpCodes.Stelem_I2);
591 else if (type == TypeManager.int32_type || type == TypeManager.uint32_type)
592 Emit (OpCodes.Stelem_I4);
593 else if (type == TypeManager.int64_type || type == TypeManager.uint64_type)
594 Emit (OpCodes.Stelem_I8);
595 else if (type == TypeManager.float_type)
596 Emit (OpCodes.Stelem_R4);
597 else if (type == TypeManager.double_type)
598 Emit (OpCodes.Stelem_R8);
599 else if (type == TypeManager.intptr_type)
600 Emit (OpCodes.Stobj, type);
601 else if (TypeManager.IsStruct (type))
602 Emit (OpCodes.Stobj, type);
603 else if (type.IsGenericParameter)
604 Emit (OpCodes.Stelem, type);
605 else if (type.IsPointer)
606 Emit (OpCodes.Stelem_I);
608 Emit (OpCodes.Stelem_Ref);
611 public void EmitInt (int i)
615 ig.Emit (OpCodes.Ldc_I4_M1);
619 ig.Emit (OpCodes.Ldc_I4_0);
623 ig.Emit (OpCodes.Ldc_I4_1);
627 ig.Emit (OpCodes.Ldc_I4_2);
631 ig.Emit (OpCodes.Ldc_I4_3);
635 ig.Emit (OpCodes.Ldc_I4_4);
639 ig.Emit (OpCodes.Ldc_I4_5);
643 ig.Emit (OpCodes.Ldc_I4_6);
647 ig.Emit (OpCodes.Ldc_I4_7);
651 ig.Emit (OpCodes.Ldc_I4_8);
655 if (i >= -128 && i <= 127) {
656 ig.Emit (OpCodes.Ldc_I4_S, (sbyte) i);
658 ig.Emit (OpCodes.Ldc_I4, i);
663 public void EmitLong (long l)
665 if (l >= int.MinValue && l <= int.MaxValue) {
666 EmitInt (unchecked ((int) l));
667 ig.Emit (OpCodes.Conv_I8);
671 if (l >= 0 && l <= uint.MaxValue) {
672 EmitInt (unchecked ((int) l));
673 ig.Emit (OpCodes.Conv_U8);
677 ig.Emit (OpCodes.Ldc_I8, l);
681 // Load the object from the pointer.
683 public void EmitLoadFromPtr (TypeSpec t)
685 if (t == TypeManager.int32_type)
686 ig.Emit (OpCodes.Ldind_I4);
687 else if (t == TypeManager.uint32_type)
688 ig.Emit (OpCodes.Ldind_U4);
689 else if (t == TypeManager.short_type)
690 ig.Emit (OpCodes.Ldind_I2);
691 else if (t == TypeManager.ushort_type)
692 ig.Emit (OpCodes.Ldind_U2);
693 else if (t == TypeManager.char_type)
694 ig.Emit (OpCodes.Ldind_U2);
695 else if (t == TypeManager.byte_type)
696 ig.Emit (OpCodes.Ldind_U1);
697 else if (t == TypeManager.sbyte_type)
698 ig.Emit (OpCodes.Ldind_I1);
699 else if (t == TypeManager.uint64_type)
700 ig.Emit (OpCodes.Ldind_I8);
701 else if (t == TypeManager.int64_type)
702 ig.Emit (OpCodes.Ldind_I8);
703 else if (t == TypeManager.float_type)
704 ig.Emit (OpCodes.Ldind_R4);
705 else if (t == TypeManager.double_type)
706 ig.Emit (OpCodes.Ldind_R8);
707 else if (t == TypeManager.bool_type)
708 ig.Emit (OpCodes.Ldind_I1);
709 else if (t == TypeManager.intptr_type)
710 ig.Emit (OpCodes.Ldind_I);
712 if (t == TypeManager.enum_type)
713 ig.Emit (OpCodes.Ldind_Ref);
715 EmitLoadFromPtr (EnumSpec.GetUnderlyingType (t));
716 } else if (TypeManager.IsStruct (t) || TypeManager.IsGenericParameter (t))
717 Emit (OpCodes.Ldobj, t);
718 else if (t.IsPointer)
719 ig.Emit (OpCodes.Ldind_I);
721 ig.Emit (OpCodes.Ldind_Ref);
725 // The stack contains the pointer and the value of type `type'
727 public void EmitStoreFromPtr (TypeSpec type)
730 type = EnumSpec.GetUnderlyingType (type);
732 if (type == TypeManager.int32_type || type == TypeManager.uint32_type)
733 ig.Emit (OpCodes.Stind_I4);
734 else if (type == TypeManager.int64_type || type == TypeManager.uint64_type)
735 ig.Emit (OpCodes.Stind_I8);
736 else if (type == TypeManager.char_type || type == TypeManager.short_type ||
737 type == TypeManager.ushort_type)
738 ig.Emit (OpCodes.Stind_I2);
739 else if (type == TypeManager.float_type)
740 ig.Emit (OpCodes.Stind_R4);
741 else if (type == TypeManager.double_type)
742 ig.Emit (OpCodes.Stind_R8);
743 else if (type == TypeManager.byte_type || type == TypeManager.sbyte_type ||
744 type == TypeManager.bool_type)
745 ig.Emit (OpCodes.Stind_I1);
746 else if (type == TypeManager.intptr_type)
747 ig.Emit (OpCodes.Stind_I);
748 else if (TypeManager.IsStruct (type) || TypeManager.IsGenericParameter (type))
749 ig.Emit (OpCodes.Stobj, type.GetMetaInfo ());
751 ig.Emit (OpCodes.Stind_Ref);
755 /// Returns a temporary storage for a variable of type t as
756 /// a local variable in the current body.
758 public LocalBuilder GetTemporaryLocal (TypeSpec t)
760 if (temporary_storage != null) {
762 if (temporary_storage.TryGetValue (t, out o)) {
763 if (o is Stack<LocalBuilder>) {
764 var s = (Stack<LocalBuilder>) o;
765 o = s.Count == 0 ? null : s.Pop ();
767 temporary_storage.Remove (t);
771 return (LocalBuilder) o;
773 return DeclareLocal (t, false);
776 public void FreeTemporaryLocal (LocalBuilder b, TypeSpec t)
778 if (temporary_storage == null) {
779 temporary_storage = new Dictionary<TypeSpec, object> (ReferenceEquality<TypeSpec>.Default);
780 temporary_storage.Add (t, b);
785 if (!temporary_storage.TryGetValue (t, out o)) {
786 temporary_storage.Add (t, b);
789 var s = o as Stack<LocalBuilder>;
791 s = new Stack<LocalBuilder> ();
792 s.Push ((LocalBuilder)o);
793 temporary_storage [t] = s;
799 /// ReturnValue creates on demand the LocalBuilder for the
800 /// return value from the function. By default this is not
801 /// used. This is only required when returns are found inside
802 /// Try or Catch statements.
804 /// This method is typically invoked from the Emit phase, so
805 /// we allow the creation of a return label if it was not
806 /// requested during the resolution phase. Could be cleaned
807 /// up, but it would replicate a lot of logic in the Emit phase
808 /// of the code that uses it.
810 public LocalBuilder TemporaryReturn ()
812 if (return_value == null){
813 return_value = DeclareLocal (return_type, false);
814 if (!HasReturnLabel){
815 ReturnLabel = DefineLabel ();
816 HasReturnLabel = true;
824 public abstract class CommonAssemblyModulClass : Attributable, IMemberContext
826 public void AddAttributes (List<Attribute> attrs, IMemberContext context)
828 foreach (Attribute a in attrs)
829 a.AttachTo (this, context);
831 if (attributes == null) {
832 attributes = new Attributes (attrs);
835 attributes.AddAttributes (attrs);
838 public virtual void Emit (TypeContainer tc)
840 if (OptAttributes == null)
843 OptAttributes.Emit ();
846 protected Attribute ResolveAttribute (PredefinedAttribute a_type)
848 Attribute a = OptAttributes.Search (a_type);
855 #region IMemberContext Members
857 public CompilerContext Compiler {
858 get { return RootContext.ToplevelTypes.Compiler; }
861 public TypeSpec CurrentType {
865 public TypeParameter[] CurrentTypeParameters {
869 public MemberCore CurrentMemberDefinition {
870 get { return RootContext.ToplevelTypes; }
873 public string GetSignatureForError ()
878 public bool HasUnresolvedConstraints {
879 get { return false; }
882 public bool IsObsolete {
883 get { return false; }
886 public bool IsUnsafe {
887 get { return false; }
890 public bool IsStatic {
891 get { return false; }
894 public ExtensionMethodGroupExpr LookupExtensionMethod (TypeSpec extensionType, string name, int arity, Location loc)
896 throw new NotImplementedException ();
899 public FullNamedExpression LookupNamespaceOrType (string name, int arity, Location loc, bool ignore_cs0104)
901 return RootContext.ToplevelTypes.LookupNamespaceOrType (name, arity, loc, ignore_cs0104);
904 public FullNamedExpression LookupNamespaceAlias (string name)
912 public class AssemblyClass : CommonAssemblyModulClass {
913 // TODO: make it private and move all builder based methods here
914 public AssemblyBuilder Builder;
915 bool is_cls_compliant;
916 bool wrap_non_exception_throws;
918 public Attribute ClsCompliantAttribute;
920 Dictionary<SecurityAction, PermissionSet> declarative_security;
921 bool has_extension_method;
922 public AssemblyName Name;
923 MethodInfo add_type_forwarder;
924 Dictionary<ITypeDefinition, Attribute> emitted_forwarders;
926 // Module is here just because of error messages
927 static string[] attribute_targets = new string [] { "assembly", "module" };
929 public AssemblyClass ()
931 wrap_non_exception_throws = true;
934 public bool HasExtensionMethods {
936 has_extension_method = value;
940 public bool IsClsCompliant {
942 return is_cls_compliant;
946 public bool WrapNonExceptionThrows {
948 return wrap_non_exception_throws;
952 public override AttributeTargets AttributeTargets {
954 return AttributeTargets.Assembly;
958 public override bool IsClsComplianceRequired ()
960 return is_cls_compliant;
964 get { return Compiler.Report; }
967 public void Resolve ()
969 if (RootContext.Unsafe) {
971 // Emits [assembly: SecurityPermissionAttribute (SecurityAction.RequestMinimum, SkipVerification = true)]
972 // when -unsafe option was specified
975 Location loc = Location.Null;
977 MemberAccess system_security_permissions = new MemberAccess (new MemberAccess (
978 new QualifiedAliasMember (QualifiedAliasMember.GlobalAlias, "System", loc), "Security", loc), "Permissions", loc);
980 Arguments pos = new Arguments (1);
981 pos.Add (new Argument (new MemberAccess (new MemberAccess (system_security_permissions, "SecurityAction", loc), "RequestMinimum")));
983 Arguments named = new Arguments (1);
984 named.Add (new NamedArgument ("SkipVerification", loc, new BoolLiteral (true, loc)));
986 GlobalAttribute g = new GlobalAttribute (new NamespaceEntry (null, null, null), "assembly",
987 new MemberAccess (system_security_permissions, "SecurityPermissionAttribute"),
988 new Arguments[] { pos, named }, loc, false);
989 g.AttachTo (this, this);
991 if (g.Resolve () != null) {
992 declarative_security = new Dictionary<SecurityAction, PermissionSet> ();
993 g.ExtractSecurityPermissionSet (declarative_security);
997 if (OptAttributes == null)
1000 // Ensure that we only have GlobalAttributes, since the Search isn't safe with other types.
1001 if (!OptAttributes.CheckTargets())
1004 ClsCompliantAttribute = ResolveAttribute (PredefinedAttributes.Get.CLSCompliant);
1006 if (ClsCompliantAttribute != null) {
1007 is_cls_compliant = ClsCompliantAttribute.GetClsCompliantAttributeValue ();
1010 Attribute a = ResolveAttribute (PredefinedAttributes.Get.RuntimeCompatibility);
1012 var val = a.GetPropertyValue ("WrapNonExceptionThrows") as BoolConstant;
1014 wrap_non_exception_throws = val.Value;
1019 private void SetPublicKey (AssemblyName an, byte[] strongNameBlob)
1022 // check for possible ECMA key
1023 if (strongNameBlob.Length == 16) {
1024 // will be rejected if not "the" ECMA key
1025 an.SetPublicKey (strongNameBlob);
1028 // take it, with or without, a private key
1029 RSA rsa = CryptoConvert.FromCapiKeyBlob (strongNameBlob);
1030 // and make sure we only feed the public part to Sys.Ref
1031 byte[] publickey = CryptoConvert.ToCapiPublicKeyBlob (rsa);
1033 // AssemblyName.SetPublicKey requires an additional header
1034 byte[] publicKeyHeader = new byte [12] { 0x00, 0x24, 0x00, 0x00, 0x04, 0x80, 0x00, 0x00, 0x94, 0x00, 0x00, 0x00 };
1036 byte[] encodedPublicKey = new byte [12 + publickey.Length];
1037 Buffer.BlockCopy (publicKeyHeader, 0, encodedPublicKey, 0, 12);
1038 Buffer.BlockCopy (publickey, 0, encodedPublicKey, 12, publickey.Length);
1039 an.SetPublicKey (encodedPublicKey);
1043 Error_AssemblySigning ("The specified file `" + RootContext.StrongNameKeyFile + "' is incorrectly encoded");
1044 Environment.Exit (1);
1048 // TODO: rewrite this code (to kill N bugs and make it faster) and use standard ApplyAttribute way.
1049 public AssemblyName GetAssemblyName (string name, string output)
1051 if (OptAttributes != null) {
1052 foreach (Attribute a in OptAttributes.Attrs) {
1053 // cannot rely on any resolve-based members before you call Resolve
1054 if (a.ExplicitTarget == null || a.ExplicitTarget != "assembly")
1057 // TODO: This code is buggy: comparing Attribute name without resolving is wrong.
1058 // However, this is invoked by CodeGen.Init, when none of the namespaces
1060 // TODO: Does not handle quoted attributes properly
1062 case "AssemblyKeyFile":
1063 case "AssemblyKeyFileAttribute":
1064 case "System.Reflection.AssemblyKeyFileAttribute":
1065 if (RootContext.StrongNameKeyFile != null) {
1066 Report.SymbolRelatedToPreviousError (a.Location, a.GetSignatureForError ());
1067 Report.Warning (1616, 1, "Option `{0}' overrides attribute `{1}' given in a source file or added module",
1068 "keyfile", "System.Reflection.AssemblyKeyFileAttribute");
1070 string value = a.GetString ();
1071 if (value != null && value.Length != 0)
1072 RootContext.StrongNameKeyFile = value;
1075 case "AssemblyKeyName":
1076 case "AssemblyKeyNameAttribute":
1077 case "System.Reflection.AssemblyKeyNameAttribute":
1078 if (RootContext.StrongNameKeyContainer != null) {
1079 Report.SymbolRelatedToPreviousError (a.Location, a.GetSignatureForError ());
1080 Report.Warning (1616, 1, "Option `{0}' overrides attribute `{1}' given in a source file or added module",
1081 "keycontainer", "System.Reflection.AssemblyKeyNameAttribute");
1083 string value = a.GetString ();
1084 if (value != null && value.Length != 0)
1085 RootContext.StrongNameKeyContainer = value;
1088 case "AssemblyDelaySign":
1089 case "AssemblyDelaySignAttribute":
1090 case "System.Reflection.AssemblyDelaySignAttribute":
1091 RootContext.StrongNameDelaySign = a.GetBoolean ();
1097 AssemblyName an = new AssemblyName ();
1098 an.Name = Path.GetFileNameWithoutExtension (name);
1100 // note: delay doesn't apply when using a key container
1101 if (RootContext.StrongNameKeyContainer != null) {
1102 an.KeyPair = new StrongNameKeyPair (RootContext.StrongNameKeyContainer);
1106 // strongname is optional
1107 if (RootContext.StrongNameKeyFile == null)
1110 string AssemblyDir = Path.GetDirectoryName (output);
1112 // the StrongName key file may be relative to (a) the compiled
1113 // file or (b) to the output assembly. See bugzilla #55320
1114 // http://bugzilla.ximian.com/show_bug.cgi?id=55320
1116 // (a) relative to the compiled file
1117 string filename = Path.GetFullPath (RootContext.StrongNameKeyFile);
1118 bool exist = File.Exists (filename);
1119 if ((!exist) && (AssemblyDir != null) && (AssemblyDir != String.Empty)) {
1120 // (b) relative to the outputed assembly
1121 filename = Path.GetFullPath (Path.Combine (AssemblyDir, RootContext.StrongNameKeyFile));
1122 exist = File.Exists (filename);
1126 using (FileStream fs = new FileStream (filename, FileMode.Open, FileAccess.Read)) {
1127 byte[] snkeypair = new byte [fs.Length];
1128 fs.Read (snkeypair, 0, snkeypair.Length);
1130 if (RootContext.StrongNameDelaySign) {
1131 // delayed signing - DO NOT include private key
1132 SetPublicKey (an, snkeypair);
1135 // no delay so we make sure we have the private key
1137 CryptoConvert.FromCapiPrivateKeyBlob (snkeypair);
1138 an.KeyPair = new StrongNameKeyPair (snkeypair);
1140 catch (CryptographicException) {
1141 if (snkeypair.Length == 16) {
1142 // error # is different for ECMA key
1143 Report.Error (1606, "Could not sign the assembly. " +
1144 "ECMA key can only be used to delay-sign assemblies");
1147 Error_AssemblySigning ("The specified file `" + RootContext.StrongNameKeyFile + "' does not have a private key");
1155 Error_AssemblySigning ("The specified file `" + RootContext.StrongNameKeyFile + "' does not exist");
1161 void Error_AssemblySigning (string text)
1163 Report.Error (1548, "Error during assembly signing. " + text);
1166 bool CheckInternalsVisibleAttribute (Attribute a)
1168 string assembly_name = a.GetString ();
1169 if (assembly_name.Length == 0)
1172 AssemblyName aname = null;
1174 aname = new AssemblyName (assembly_name);
1175 } catch (FileLoadException) {
1176 } catch (ArgumentException) {
1179 // Bad assembly name format
1181 Report.Warning (1700, 3, a.Location, "Assembly reference `" + assembly_name + "' is invalid and cannot be resolved");
1182 // Report error if we have defined Version or Culture
1183 else if (aname.Version != null || aname.CultureInfo != null)
1184 throw new Exception ("Friend assembly `" + a.GetString () +
1185 "' is invalid. InternalsVisibleTo cannot have version or culture specified.");
1186 else if (aname.GetPublicKey () == null && Name.GetPublicKey () != null && Name.GetPublicKey ().Length != 0) {
1187 Report.Error (1726, a.Location, "Friend assembly reference `" + aname.FullName + "' is invalid." +
1188 " Strong named assemblies must specify a public key in their InternalsVisibleTo declarations");
1195 static bool IsValidAssemblyVersion (string version)
1199 v = new Version (version);
1202 int major = int.Parse (version, CultureInfo.InvariantCulture);
1203 v = new Version (major, 0);
1209 foreach (int candidate in new int [] { v.Major, v.Minor, v.Build, v.Revision }) {
1210 if (candidate > ushort.MaxValue)
1217 public override void ApplyAttributeBuilder (Attribute a, MethodSpec ctor, byte[] cdata, PredefinedAttributes pa)
1219 if (a.IsValidSecurityAttribute ()) {
1220 if (declarative_security == null)
1221 declarative_security = new Dictionary<SecurityAction, PermissionSet> ();
1223 a.ExtractSecurityPermissionSet (declarative_security);
1227 if (a.Type == pa.AssemblyCulture) {
1228 string value = a.GetString ();
1229 if (value == null || value.Length == 0)
1232 if (RootContext.Target == Target.Exe) {
1233 a.Error_AttributeEmitError ("The executables cannot be satelite assemblies, remove the attribute or keep it empty");
1238 if (a.Type == pa.AssemblyVersion) {
1239 string value = a.GetString ();
1240 if (value == null || value.Length == 0)
1243 value = value.Replace ('*', '0');
1245 if (!IsValidAssemblyVersion (value)) {
1246 a.Error_AttributeEmitError (string.Format ("Specified version `{0}' is not valid", value));
1251 if (a.Type == pa.InternalsVisibleTo && !CheckInternalsVisibleAttribute (a))
1254 if (a.Type == pa.TypeForwarder) {
1255 TypeSpec t = a.GetArgumentType ();
1256 if (t == null || TypeManager.HasElementType (t)) {
1257 Report.Error (735, a.Location, "Invalid type specified as an argument for TypeForwardedTo attribute");
1261 if (emitted_forwarders == null) {
1262 emitted_forwarders = new Dictionary<ITypeDefinition, Attribute> ();
1263 } else if (emitted_forwarders.ContainsKey (t.MemberDefinition)) {
1264 Report.SymbolRelatedToPreviousError(emitted_forwarders[t.MemberDefinition].Location, null);
1265 Report.Error(739, a.Location, "A duplicate type forward of type `{0}'",
1266 TypeManager.CSharpName(t));
1270 emitted_forwarders.Add(t.MemberDefinition, a);
1272 if (t.Assembly == Builder) {
1273 Report.SymbolRelatedToPreviousError (t);
1274 Report.Error (729, a.Location, "Cannot forward type `{0}' because it is defined in this assembly",
1275 TypeManager.CSharpName (t));
1280 Report.Error (730, a.Location, "Cannot forward type `{0}' because it is a nested type",
1281 TypeManager.CSharpName (t));
1285 if (add_type_forwarder == null) {
1286 add_type_forwarder = typeof (AssemblyBuilder).GetMethod ("AddTypeForwarder",
1287 BindingFlags.NonPublic | BindingFlags.Instance);
1289 if (add_type_forwarder == null) {
1290 Report.RuntimeMissingSupport (a.Location, "TypeForwardedTo attribute");
1295 add_type_forwarder.Invoke (Builder, new object[] { t.GetMetaInfo () });
1299 if (a.Type == pa.Extension) {
1300 a.Error_MisusedExtensionAttribute ();
1304 Builder.SetCustomAttribute ((ConstructorInfo) ctor.GetMetaInfo (), cdata);
1307 public override void Emit (TypeContainer tc)
1311 if (has_extension_method)
1312 PredefinedAttributes.Get.Extension.EmitAttribute (Builder);
1314 // FIXME: Does this belong inside SRE.AssemblyBuilder instead?
1315 PredefinedAttribute pa = PredefinedAttributes.Get.RuntimeCompatibility;
1316 if (pa.IsDefined && (OptAttributes == null || !OptAttributes.Contains (pa))) {
1317 var ci = TypeManager.GetPredefinedConstructor (pa.Type, Location.Null, TypeSpec.EmptyTypes);
1318 PropertyInfo [] pis = new PropertyInfo [1];
1319 pis [0] = TypeManager.GetPredefinedProperty (pa.Type,
1320 "WrapNonExceptionThrows", Location.Null, TypeManager.bool_type).MetaInfo;
1321 object [] pargs = new object [1];
1323 Builder.SetCustomAttribute (new CustomAttributeBuilder ((ConstructorInfo) ci.GetMetaInfo (), new object[0], pis, pargs));
1326 if (declarative_security != null) {
1328 MethodInfo add_permission = typeof (AssemblyBuilder).GetMethod ("AddPermissionRequests", BindingFlags.Instance | BindingFlags.NonPublic);
1329 object builder_instance = Builder;
1332 // Microsoft runtime hacking
1333 if (add_permission == null) {
1334 var assembly_builder = typeof (AssemblyBuilder).Assembly.GetType ("System.Reflection.Emit.AssemblyBuilderData");
1335 add_permission = assembly_builder.GetMethod ("AddPermissionRequests", BindingFlags.Instance | BindingFlags.NonPublic);
1337 FieldInfo fi = typeof (AssemblyBuilder).GetField ("m_assemblyData", BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.GetField);
1338 builder_instance = fi.GetValue (Builder);
1341 var args = new PermissionSet [3];
1342 declarative_security.TryGetValue (SecurityAction.RequestMinimum, out args [0]);
1343 declarative_security.TryGetValue (SecurityAction.RequestOptional, out args [1]);
1344 declarative_security.TryGetValue (SecurityAction.RequestRefuse, out args [2]);
1345 add_permission.Invoke (builder_instance, args);
1348 Report.RuntimeMissingSupport (Location.Null, "assembly permission setting");
1353 public override string[] ValidAttributeTargets {
1355 return attribute_targets;
1359 // Wrapper for AssemblyBuilder.AddModule
1360 static MethodInfo adder_method;
1361 static public MethodInfo AddModule_Method {
1363 if (adder_method == null)
1364 adder_method = typeof (AssemblyBuilder).GetMethod ("AddModule", BindingFlags.Instance|BindingFlags.NonPublic);
1365 return adder_method;
1368 public Module AddModule (string module)
1370 MethodInfo m = AddModule_Method;
1372 Report.RuntimeMissingSupport (Location.Null, "/addmodule");
1373 Environment.Exit (1);
1377 return (Module) m.Invoke (Builder, new object [] { module });
1378 } catch (TargetInvocationException ex) {
1379 throw ex.InnerException;