Example #1
0
			public FieldSpec DefineInitializedData (byte[] data, Location loc)
			{
				Struct size_type;
				if (!size_types.TryGetValue (data.Length, out size_type)) {
					//
					// Build common type for this data length. We cannot use
					// DefineInitializedData because it creates public type,
					// and its name is not unique among modules
					//
					size_type = new Struct (null, this, new MemberName ("$ArrayType=" + data.Length, Location), Modifiers.PRIVATE | Modifiers.COMPILER_GENERATED, null);
					size_type.CreateType ();
					size_type.DefineType ();

					size_types.Add (data.Length, size_type);

					var pa = Module.PredefinedAttributes.StructLayout;
					if (pa.Constructor != null || pa.ResolveConstructor (Location, TypeManager.short_type)) {
						var argsEncoded = new AttributeEncoder (false);
						argsEncoded.Encode ((short) LayoutKind.Explicit);

						var field_size = pa.GetField ("Size", TypeManager.int32_type, Location);
						var pack = pa.GetField ("Pack", TypeManager.int32_type, Location);
						if (field_size != null) {
							argsEncoded.EncodeNamedArguments (
								new[] { field_size, pack },
								new[] { new IntConstant ((int) data.Length, Location), new IntConstant (1, Location) }
							);
						}

						pa.EmitAttribute (size_type.TypeBuilder, argsEncoded);
					}
				}

				var name = "$field-" + fields.ToString ("X");
				++fields;
				const Modifiers fmod = Modifiers.STATIC | Modifiers.INTERNAL;
				var fbuilder = TypeBuilder.DefineField (name, size_type.CurrentType.GetMetaInfo (), ModifiersExtensions.FieldAttr (fmod) | FieldAttributes.HasFieldRVA);
#if STATIC
				fbuilder.__SetDataAndRVA (data);
#else
				if (set_data == null)
					set_data = typeof (FieldBuilder).GetMethod ("SetRVAData", System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Instance);

				try {
					set_data.Invoke (fbuilder, new object[] { data });
				} catch {
					Report.RuntimeMissingSupport (loc, "SetRVAData");
				}
#endif

				return new FieldSpec (CurrentType, null, size_type.CurrentType, fbuilder, fmod);
			}
Example #2
0
			public FieldSpec DefineInitializedData (byte[] data, Location loc)
			{
				Struct size_type;
				if (!size_types.TryGetValue (data.Length, out size_type)) {
					//
					// Build common type for this data length. We cannot use
					// DefineInitializedData because it creates public type,
					// and its name is not unique among modules
					//
					size_type = new Struct (null, this, new MemberName ("$ArrayType=" + data.Length, Location), Modifiers.PRIVATE | Modifiers.COMPILER_GENERATED, null);
					size_type.CreateType ();
					size_type.DefineType ();

					size_types.Add (data.Length, size_type);

					var pa = Module.PredefinedAttributes.StructLayout;
					if (pa.Constructor != null || pa.ResolveConstructor (Location, Compiler.BuildinTypes.Short)) {
						var argsEncoded = new AttributeEncoder ();
						argsEncoded.Encode ((short) LayoutKind.Explicit);

						var field_size = pa.GetField ("Size", Compiler.BuildinTypes.Int, Location);
						var pack = pa.GetField ("Pack", Compiler.BuildinTypes.Int, Location);
						if (field_size != null) {
							argsEncoded.EncodeNamedArguments (
								new[] { field_size, pack },
								new[] { new IntConstant (Compiler.BuildinTypes, (int) data.Length, Location), new IntConstant (Compiler.BuildinTypes, 1, Location) }
							);
						}

						pa.EmitAttribute (size_type.TypeBuilder, argsEncoded);
					}
				}

				var name = "$field-" + fields.ToString ("X");
				++fields;
				const Modifiers fmod = Modifiers.STATIC | Modifiers.INTERNAL;
				var fbuilder = TypeBuilder.DefineField (name, size_type.CurrentType.GetMetaInfo (), ModifiersExtensions.FieldAttr (fmod) | FieldAttributes.HasFieldRVA);
				fbuilder.__SetDataAndRVA (data);

				return new FieldSpec (CurrentType, null, size_type.CurrentType, fbuilder, fmod);
			}
Example #3
0
		void EmitFieldSize (int buffer_size)
		{
			int type_size = BuiltinTypeSpec.GetSize (MemberType);

			if (buffer_size > int.MaxValue / type_size) {
				Report.Error (1664, Location, "Fixed size buffer `{0}' of length `{1}' and type `{2}' exceeded 2^31 limit",
					GetSignatureForError (), buffer_size.ToString (), TypeManager.CSharpName (MemberType));
				return;
			}

			AttributeEncoder encoder;

			var ctor = Module.PredefinedMembers.StructLayoutAttributeCtor.Resolve (Location);
			if (ctor == null)
				return;

			var field_size = Module.PredefinedMembers.StructLayoutSize.Resolve (Location);
			var field_charset = Module.PredefinedMembers.StructLayoutCharSet.Resolve (Location);
			if (field_size == null || field_charset == null)
				return;

			var char_set = CharSet ?? Module.DefaultCharSet ?? 0;

			encoder = new AttributeEncoder ();
			encoder.Encode ((short)LayoutKind.Sequential);
			encoder.EncodeNamedArguments (
				new [] { field_size, field_charset },
				new Constant [] { 
					new IntConstant (Compiler.BuiltinTypes, buffer_size * type_size, Location),
					new IntConstant (Compiler.BuiltinTypes, (int) char_set, Location)
				}
			);

			fixed_buffer_type.SetCustomAttribute ((ConstructorInfo) ctor.GetMetaInfo (), encoder.ToArray ());

			//
			// Don't emit FixedBufferAttribute attribute for private types
			//
			if ((ModFlags & Modifiers.PRIVATE) != 0)
				return;

			ctor = Module.PredefinedMembers.FixedBufferAttributeCtor.Resolve (Location);
			if (ctor == null)
				return;

			encoder = new AttributeEncoder ();
			encoder.EncodeTypeName (MemberType);
			encoder.Encode (buffer_size);
			encoder.EncodeEmptyNamedArguments ();

			FieldBuilder.SetCustomAttribute ((ConstructorInfo) ctor.GetMetaInfo (), encoder.ToArray ());
		}
Example #4
0
		public override void EncodeAttributeValue (IMemberContext rc, AttributeEncoder enc, TypeSpec targetType)
		{
			enc.Stream.Write ((ushort) Value);
		}
Example #5
0
		public override void EncodeAttributeValue (IMemberContext rc, AttributeEncoder enc, TypeSpec targetType)
		{
			// Type it as string cast
			if (targetType == TypeManager.object_type || targetType == InternalType.Null)
				enc.Encode (TypeManager.string_type);

			var ac = targetType as ArrayContainer;
			if (ac != null) {
				if (ac.Rank != 1 || ac.Element.IsArray)
					base.EncodeAttributeValue (rc, enc, targetType);
				else
					enc.Stream.Write (uint.MaxValue);
			} else {
				enc.Stream.Write (byte.MaxValue);
			}
		}
Example #6
0
		void EmitIndexerName ()
		{
			if (!seen_normal_indexers)
				return;

			PredefinedAttribute pa = Module.PredefinedAttributes.DefaultMember;
			if (pa.Constructor == null &&
				!pa.ResolveConstructor (Location, TypeManager.string_type))
				return;

			var encoder = new AttributeEncoder ();
			encoder.Encode (GetAttributeDefaultMember ());
			encoder.EncodeEmptyNamedArguments ();

			pa.EmitAttribute (TypeBuilder, encoder);
		}
        void EmitFieldSize(int buffer_size)
        {
            PredefinedAttribute pa;
            AttributeEncoder encoder;

            pa = Module.PredefinedAttributes.StructLayout;
            if (pa.Constructor == null && !pa.ResolveConstructor (Location, TypeManager.short_type))
                return;

            var char_set_type = Module.PredefinedTypes.CharSet.Resolve (Location);
            if (char_set_type == null)
                return;

            var field_size = pa.GetField ("Size", TypeManager.int32_type, Location);
            var field_charset = pa.GetField ("CharSet", char_set_type, Location);
            if (field_size == null || field_charset == null)
                return;

            var char_set = CharSet ?? Module.DefaultCharSet ?? 0;

            encoder = new AttributeEncoder ();
            encoder.Encode ((short)LayoutKind.Sequential);
            encoder.EncodeNamedArguments (
                new [] { field_size, field_charset },
                new Constant [] { new IntConstant (buffer_size, Location), new IntConstant ((int) char_set, Location) }
            );

            pa.EmitAttribute (fixed_buffer_type, encoder);

            //
            // Don't emit FixedBufferAttribute attribute for private types
            //
            if ((ModFlags & Modifiers.PRIVATE) != 0)
                return;

            pa = Module.PredefinedAttributes.FixedBuffer;
            if (pa.Constructor == null && !pa.ResolveConstructor (Location, TypeManager.type_type, TypeManager.int32_type))
                return;

            encoder = new AttributeEncoder ();
            encoder.EncodeTypeName (MemberType);
            encoder.Encode (buffer_size);
            encoder.EncodeEmptyNamedArguments ();

            pa.EmitAttribute (FieldBuilder, encoder);
        }
Example #8
0
		public override void EncodeAttributeValue (IMemberContext rc, AttributeEncoder enc, TypeSpec targetType)
		{
			enc.Encode (Value);
		}
Example #9
0
		/// <summary>
		/// Emit attribute for Attributable symbol
		/// </summary>
		public void Emit (Dictionary<Attribute, List<Attribute>> allEmitted)
		{
			var ctor = Resolve ();
			if (ctor == null)
				return;

			var predefined = context.Compiler.PredefinedAttributes;

			AttributeUsageAttribute usage_attr = Type.GetAttributeUsage (predefined.AttributeUsage);
			if ((usage_attr.ValidOn & Target) == 0) {
				Report.Error (592, Location, "The attribute `{0}' is not valid on this declaration type. " +
					      "It is valid on `{1}' declarations only",
					GetSignatureForError (), GetValidTargets ());
				return;
			}

			AttributeEncoder encoder = new AttributeEncoder (false);

			if (PosArguments != null) {
				var param_types = ctor.Parameters.Types;
				for (int j = 0; j < PosArguments.Count; ++j) {
					var pt = param_types[j];
					var arg_expr = PosArguments[j].Expr;
					if (j == 0) {
						if (Type == predefined.IndexerName || Type == predefined.Conditional) {
							string v = ((StringConstant) arg_expr).Value;
							if (!Tokenizer.IsValidIdentifier (v) || Tokenizer.IsKeyword (v)) {
								context.Compiler.Report.Error (633, arg_expr.Location,
									"The argument to the `{0}' attribute must be a valid identifier", GetSignatureForError ());
							}
						} else if (Type == predefined.Guid) {
							try {
								string v = ((StringConstant) arg_expr).Value;
								new Guid (v);
							} catch (Exception e) {
								Error_AttributeEmitError (e.Message);
								return;
							}
						} else if (Type == predefined.AttributeUsage) {
							int v = ((IntConstant)((EnumConstant) arg_expr).Child).Value;
							if (v == 0) {
								context.Compiler.Report.Error (591, Location, "Invalid value for argument to `{0}' attribute",
									"System.AttributeUsage");
							}
						} else if (Type == predefined.MethodImpl && pt == TypeManager.short_type &&
							!System.Enum.IsDefined (typeof (MethodImplOptions), ((Constant) arg_expr).GetValue ().ToString ())) {
							Error_AttributeEmitError ("Incorrect argument value.");
							return;
						}
					}

					arg_expr.EncodeAttributeValue (context, encoder, pt);
				}
			}

			if (named_values != null) {
				encoder.Stream.Write ((ushort) named_values.Count);
				foreach (var na in named_values) {
					if (na.Key is FieldExpr)
						encoder.Stream.Write ((byte) 0x53);
					else
						encoder.Stream.Write ((byte) 0x54);

					encoder.Encode (na.Key.Type);
					encoder.Encode (na.Value.Name);
					na.Value.Expr.EncodeAttributeValue (context, encoder, na.Key.Type);
				}
			} else {
				encoder.Stream.Write ((ushort) 0);
			}

			byte[] cdata = encoder.ToArray ();

			try {
				foreach (Attributable target in targets)
					target.ApplyAttributeBuilder (this, ctor, cdata, predefined);
			} catch (Exception e) {
				Error_AttributeEmitError (e.Message);
				return;
			}

			if (!usage_attr.AllowMultiple && allEmitted != null) {
				if (allEmitted.ContainsKey (this)) {
					var a = allEmitted [this];
					if (a == null) {
						a = new List<Attribute> (2);
						allEmitted [this] = a;
					}
					a.Add (this);
				} else {
					allEmitted.Add (this, null);
				}
			}

			if (!RootContext.VerifyClsCompliance)
				return;

			// Here we are testing attribute arguments for array usage (error 3016)
			if (Owner.IsClsComplianceRequired ()) {
				if (PosArguments != null)
					PosArguments.CheckArrayAsAttribute (context.Compiler);
			
				if (NamedArguments == null)
					return;

				NamedArguments.CheckArrayAsAttribute (context.Compiler);
			}
		}
Example #10
0
 public virtual void EncodeAttributeValue(IMemberContext rc, AttributeEncoder enc, TypeSpec targetType)
 {
     Attribute.Error_AttributeArgumentNotValid (rc, loc);
 }
Example #11
0
		void EmitFieldSize (int buffer_size)
		{
			int type_size = BuiltinTypeSpec.GetSize (MemberType);

			if (buffer_size > int.MaxValue / type_size) {
				Report.Error (1664, Location, "Fixed size buffer `{0}' of length `{1}' and type `{2}' exceeded 2^31 limit",
					GetSignatureForError (), buffer_size.ToString (), MemberType.GetSignatureForError ());
				return;
			}

			AttributeEncoder encoder;
			MethodSpec ctor;

			var char_set = CharSetValue ?? Module.DefaultCharSet ?? 0;
#if STATIC
			//
			// Set struct layout without resolving StructLayoutAttribute which is not always available
			//

			TypeAttributes attribs = TypeAttributes.SequentialLayout;
			switch (char_set) {
			case CharSet.None:
			case CharSet.Ansi:
				attribs |= TypeAttributes.AnsiClass;
				break;
			case CharSet.Auto:
				attribs |= TypeAttributes.AutoClass;
				break;
			case CharSet.Unicode:
				attribs |= TypeAttributes.UnicodeClass;
				break;
			}

			fixed_buffer_type.__SetAttributes (fixed_buffer_type.Attributes | attribs);
			fixed_buffer_type.__SetLayout (0, buffer_size * type_size);
#else
			ctor = Module.PredefinedMembers.StructLayoutAttributeCtor.Resolve (Location);
			if (ctor == null)
				return;

			var field_size = Module.PredefinedMembers.StructLayoutSize.Resolve (Location);
			var field_charset = Module.PredefinedMembers.StructLayoutCharSet.Resolve (Location);
			if (field_size == null || field_charset == null)
				return;

			encoder = new AttributeEncoder ();
			encoder.Encode ((short)LayoutKind.Sequential);
			encoder.EncodeNamedArguments (
				new [] { field_size, field_charset },
				new Constant [] { 
					new IntConstant (Compiler.BuiltinTypes, buffer_size * type_size, Location),
					new IntConstant (Compiler.BuiltinTypes, (int) char_set, Location)
				}
			);

			fixed_buffer_type.SetCustomAttribute ((ConstructorInfo) ctor.GetMetaInfo (), encoder.ToArray ());
#endif
			//
			// Don't emit FixedBufferAttribute attribute for private types
			//
			if ((ModFlags & Modifiers.PRIVATE) != 0)
				return;

			ctor = Module.PredefinedMembers.FixedBufferAttributeCtor.Resolve (Location);
			if (ctor == null)
				return;

			encoder = new AttributeEncoder ();
			encoder.EncodeTypeName (MemberType);
			encoder.Encode (buffer_size);
			encoder.EncodeEmptyNamedArguments ();

			FieldBuilder.SetCustomAttribute ((ConstructorInfo) ctor.GetMetaInfo (), encoder.ToArray ());
		}
Example #12
0
 public override void EncodeAttributeValue(IMemberContext rc, AttributeEncoder enc, TypeSpec targetType)
 {
     Child.EncodeAttributeValue (rc, enc, Child.Type);
 }
Example #13
0
		public override void EncodeAttributeValue (IMemberContext rc, AttributeEncoder enc, TypeSpec targetType)
		{
			throw new NotSupportedException ();
		}
Example #14
0
		void EmitFieldSize (int buffer_size)
		{
			int type_size = Expression.GetTypeSize (MemberType);

			if (buffer_size > int.MaxValue / type_size) {
				Report.Error (1664, Location, "Fixed size buffer `{0}' of length `{1}' and type `{2}' exceeded 2^31 limit",
					GetSignatureForError (), buffer_size.ToString (), TypeManager.CSharpName (MemberType));
				return;
			}
			
			PredefinedAttribute pa;
			AttributeEncoder encoder;

			pa = Module.PredefinedAttributes.StructLayout;
			if (pa.Constructor == null && !pa.ResolveConstructor (Location, TypeManager.short_type))
				return;

			var char_set_type = Module.PredefinedTypes.CharSet.Resolve (Location);
			if (char_set_type == null)
				return;

			var field_size = pa.GetField ("Size", TypeManager.int32_type, Location);
			var field_charset = pa.GetField ("CharSet", char_set_type, Location);
			if (field_size == null || field_charset == null)
				return;

			var char_set = CharSet ?? Module.DefaultCharSet;

			encoder = new AttributeEncoder ();
			encoder.Encode ((short)LayoutKind.Sequential);
			encoder.EncodeNamedArguments (
				new [] { field_size, field_charset },
				new Constant [] { new IntConstant (buffer_size * type_size, Location), new IntConstant ((int) char_set, Location) }
			);

			pa.EmitAttribute (fixed_buffer_type, encoder);

			//
			// Don't emit FixedBufferAttribute attribute for private types
			//
			if ((ModFlags & Modifiers.PRIVATE) != 0)
				return;

			pa = Module.PredefinedAttributes.FixedBuffer;
			if (pa.Constructor == null && !pa.ResolveConstructor (Location, TypeManager.type_type, TypeManager.int32_type))
				return;

			encoder = new AttributeEncoder ();
			encoder.EncodeTypeName (MemberType);
			encoder.Encode (buffer_size);
			encoder.EncodeEmptyNamedArguments ();

			pa.EmitAttribute (FieldBuilder, encoder);
		}
Example #15
0
		public override void EncodeAttributeValue (IMemberContext rc, AttributeEncoder enc, TypeSpec targetType)
		{
			// cast to object
			if (type != targetType)
				enc.Encode (type);

			enc.Encode (Value);
		}
Example #16
0
		public override void EncodeAttributeValue (IMemberContext rc, AttributeEncoder enc, TypeSpec targetType, TypeSpec parameterType)
		{
			enc.Encode ((ushort) Value);
		}
Example #17
0
		public override void EncodeAttributeValue (IMemberContext rc, AttributeEncoder enc, TypeSpec targetType)
		{
			switch (targetType.BuiltinType) {
			case BuiltinTypeSpec.Type.Object:
				// Type it as string cast
				enc.Encode (rc.Module.Compiler.BuiltinTypes.String);
				goto case BuiltinTypeSpec.Type.String;
			case BuiltinTypeSpec.Type.String:
			case BuiltinTypeSpec.Type.Type:
				enc.Encode (byte.MaxValue);
				return;
			default:
				var ac = targetType as ArrayContainer;
				if (ac != null && ac.Rank == 1 && !ac.Element.IsArray) {
					enc.Encode (uint.MaxValue);
					return;
				}

				break;
			}

			base.EncodeAttributeValue (rc, enc, targetType);
		}
Example #18
0
		public void Emit ()
		{
			if (RootContext.Target == Target.Module) {
				module_target_attrs = new AssemblyAttributesPlaceholder (module, name);
				module_target_attrs.CreateType ();
				module_target_attrs.DefineType ();
				module_target_attrs.Define ();
				module.AddCompilerGeneratedClass (module_target_attrs);
			} else if (added_modules != null) {
				ReadModulesAssemblyAttributes ();
			}

			module.Emit ();

			if (module.HasExtensionMethod) {
				var pa = Compiler.PredefinedAttributes.Extension;
				if (pa.IsDefined) {
					SetCustomAttribute (pa.Constructor, AttributeEncoder.Empty);
				}
			}

			if (!wrap_non_exception_throws_custom) {
				PredefinedAttribute pa = Compiler.PredefinedAttributes.RuntimeCompatibility;
				if (pa.IsDefined && pa.ResolveBuilder ()) {
					var prop = pa.GetProperty ("WrapNonExceptionThrows", TypeManager.bool_type, Location.Null);
					if (prop != null) {
						AttributeEncoder encoder = new AttributeEncoder (false);
						encoder.EncodeNamedPropertyArgument (prop, new BoolLiteral (true, Location.Null));
						SetCustomAttribute (pa.Constructor, encoder.ToArray ());
					}
				}
			}

			if (declarative_security != null) {

				MethodInfo add_permission = typeof (AssemblyBuilder).GetMethod ("AddPermissionRequests", BindingFlags.Instance | BindingFlags.NonPublic);
				object builder_instance = Builder;

				try {
					// Microsoft runtime hacking
					if (add_permission == null) {
						var assembly_builder = typeof (AssemblyBuilder).Assembly.GetType ("System.Reflection.Emit.AssemblyBuilderData");
						add_permission = assembly_builder.GetMethod ("AddPermissionRequests", BindingFlags.Instance | BindingFlags.NonPublic);

						FieldInfo fi = typeof (AssemblyBuilder).GetField ("m_assemblyData", BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.GetField);
						builder_instance = fi.GetValue (Builder);
					}

					var args = new PermissionSet [3];
					declarative_security.TryGetValue (SecurityAction.RequestMinimum, out args [0]);
					declarative_security.TryGetValue (SecurityAction.RequestOptional, out args [1]);
					declarative_security.TryGetValue (SecurityAction.RequestRefuse, out args [2]);
					add_permission.Invoke (builder_instance, args);
				} catch {
					Report.RuntimeMissingSupport (Location.Null, "assembly permission setting");
				}
			}

			CheckReferencesPublicToken ();

			SetEntryPoint ();
		}
Example #19
0
		void EmitIndexerName ()
		{
			if (!has_normal_indexers)
				return;

			var ctor = Module.PredefinedMembers.DefaultMemberAttributeCtor.Get ();
			if (ctor == null)
				return;

			var encoder = new AttributeEncoder ();
			encoder.Encode (GetAttributeDefaultMember ());
			encoder.EncodeEmptyNamedArguments ();

			TypeBuilder.SetCustomAttribute ((ConstructorInfo) ctor.GetMetaInfo (), encoder.ToArray ());
		}
Example #20
0
		public override void EncodeAttributeValue (IMemberContext rc, AttributeEncoder enc, TypeSpec targetType)
		{
			// Type it as string cast
			if (targetType.BuiltinType == BuiltinTypeSpec.Type.Object)
				enc.Encode (rc.Module.Compiler.BuiltinTypes.String);

			var ac = targetType as ArrayContainer;
			if (ac != null) {
				if (ac.Rank != 1 || ac.Element.IsArray)
					base.EncodeAttributeValue (rc, enc, targetType);
				else
					enc.Encode (uint.MaxValue);
			} else {
				enc.Encode (byte.MaxValue);
			}
		}