internal RuntimeType(RuntimeTypeHandle handle) { this.handle = handle; typeStruct = (MetadataTypeStruct*)((uint**)&handle)[0]; assemblyQualifiedName = Mosa.Runtime.Internal.InitializeMetadataString(typeStruct->Name); // TODO name = Mosa.Runtime.Internal.InitializeMetadataString(typeStruct->Name); // TODO @namespace = Mosa.Runtime.Internal.InitializeMetadataString(typeStruct->Name); // TODO fullname = Mosa.Runtime.Internal.InitializeMetadataString(typeStruct->Name); typeCode = (TypeCode)(typeStruct->Attributes >> 24); attributes = (TypeAttributes)(typeStruct->Attributes & 0x00FFFFFF); // Declaring Type if (typeStruct->DeclaringType != null) { RuntimeTypeHandle declaringHandle = new RuntimeTypeHandle(); ((uint**)&declaringHandle)[0] = (uint*)typeStruct->DeclaringType; declaringTypeHandle = declaringHandle; } // Element Type if ((*typeStruct).ElementType != null) { RuntimeTypeHandle elementHandle = new RuntimeTypeHandle(); ((uint**)&elementHandle)[0] = (uint*)typeStruct->ElementType; elementTypeHandle = elementHandle; } }
public void MakePointerType(TypeAttributes attributes) { TypeBuilder type = Helpers.DynamicType(attributes); Type arrayType = type.MakePointerType(); Assert.Equal(typeof(Array), arrayType.GetTypeInfo().BaseType); Assert.Equal("TestType*", arrayType.Name); }
public StructureBuilder (NamespaceBuilder ns, CodeLinePragma loc, TypeAttributes attr) : base (BundleManagerBase.DefaultStructureClass, ns, loc, attr) { BaseClass = new UserType (typeof (StructureTemplate)); ns.SetUserParams (this); }
public static CodeTypeDeclaration Class(string className, TypeAttributes attributes) { return new CodeTypeDeclaration(className) { TypeAttributes = attributes }; }
public void MakeArrayType_Int_Three(TypeAttributes attributes) { TypeBuilder type = Helpers.DynamicType(attributes); Type arrayType = type.MakeArrayType(3); Assert.Equal(typeof(Array), arrayType.GetTypeInfo().BaseType); Assert.Equal("TestType[,,]", arrayType.Name); }
private static Type Type( string name, Type[] interfaces, MemberDefinition[] memberDefinitions, TypeAttributes typeAttributes, Type baseType = null) { if (name == null) throw new ArgumentNullException("name"); if (interfaces == null) throw new ArgumentNullException("interfaces"); if (memberDefinitions == null) throw new ArgumentNullException("memberDefinitions"); var assemblyBuilder = AppDomain.CurrentDomain.DefineDynamicAssembly( new AssemblyName(name), AssemblyBuilderAccess.Run); var moduleBuilder = assemblyBuilder.DefineDynamicModule("MainModule"); var typeBuilder = moduleBuilder.DefineType(name, typeAttributes, baseType, interfaces); var fields = new List<FieldBuilder>(); foreach (var definition in memberDefinitions.OrderBy(d => d is ConstructorDefinition)) { definition.EmitTo(typeBuilder, fields); } if (baseType != typeof(ValueType) && !memberDefinitions.Any(d => d is ConstructorDefinition)) { Define.Constructor().EmitTo(typeBuilder, fields); } return typeBuilder.CreateType(); }
public static RTypeAttributes GetRTypeAttributes(TypeAttributes attrs, bool isValueType) { RTypeAttributes rAttrs = 0; TypeAttributes visibility = attrs & TypeAttributes.VisibilityMask; if (visibility == TypeAttributes.NotPublic) { rAttrs |= RTypeAttributes.Private; } else if (visibility == TypeAttributes.Public) { rAttrs |= RTypeAttributes.Public; } TypeAttributes classSemantics = attrs & TypeAttributes.ClassSemanticsMask; if (classSemantics == TypeAttributes.Class && !isValueType) { rAttrs |= RTypeAttributes.Class; } else if (classSemantics == TypeAttributes.Interface) { rAttrs |= RTypeAttributes.Interface; } if ((attrs & TypeAttributes.Sealed) != 0) { rAttrs |= RTypeAttributes.Sealed; } return rAttrs; }
public TypeDefinition(string @namespace, string name, TypeAttributes attributes, TypeReference baseType, uint fieldList, uint methodList) : base(new MetaDataRow((uint)attributes, 0U, 0U, 0U, fieldList, methodList)) { this._namespace = @namespace; this._name = name; this._baseType = baseType; }
private static TypeBuilder CreateTypeBuilder(AbstractTypeEmitter maintype, string name, TypeAttributes attributes, Type baseType, Type[] interfaces) { return maintype.TypeBuilder.DefineNestedType( name, attributes, baseType, interfaces); }
public void DefineNestedType(string name, TypeAttributes attributes, Type parent, PackingSize packingSize, int typesize, Type[] implementedInterfaces) { bool isDefaultImplementedInterfaces = implementedInterfaces?.Length == 0; bool isDefaultPackingSize = packingSize == PackingSize.Unspecified; bool isDefaultSize = typesize == 0; bool isDefaultParent = parent == null; bool isDefaultAttributes = attributes == TypeAttributes.NestedPrivate; Action<TypeBuilder, TypeBuilder> verify = (type, declaringType) => { bool allowsNullParent = attributes.HasFlag(TypeAttributes.Abstract) && attributes.HasFlag(TypeAttributes.ClassSemanticsMask); Type baseType = allowsNullParent ? parent : (parent ?? typeof(object)); Helpers.VerifyType(type, declaringType.Module, declaringType, name, attributes, baseType, typesize, packingSize, implementedInterfaces); }; if (isDefaultImplementedInterfaces) { if (isDefaultSize && isDefaultPackingSize) { if (isDefaultParent) { if (isDefaultAttributes) { // Use DefineNestedType(string) TypeBuilder type1 = Helpers.DynamicType(TypeAttributes.Public); verify(type1.DefineNestedType(name), type1); } // Use DefineNestedType(string, TypeAttributes) TypeBuilder type2 = Helpers.DynamicType(TypeAttributes.Public); verify(type2.DefineNestedType(name, attributes), type2); } // Use DefineNestedType(string, TypeAttributes, Type) TypeBuilder type3 = Helpers.DynamicType(TypeAttributes.Public); verify(type3.DefineNestedType(name, attributes, parent), type3); } else if (isDefaultSize) { // Use DefineNestedType(string, TypeAttributes, Type, PackingSize) TypeBuilder type4 = Helpers.DynamicType(TypeAttributes.Public); verify(type4.DefineNestedType(name, attributes, parent, packingSize), type4); } else if (isDefaultPackingSize) { // Use DefineNestedType(string, TypeAttributes, Type, int) TypeBuilder type5 = Helpers.DynamicType(TypeAttributes.Public); verify(type5.DefineNestedType(name, attributes, parent, typesize), type5); } // Use DefineNestedType(string, TypeAttributes, Type, PackingSize, int); TypeBuilder type6 = Helpers.DynamicType(TypeAttributes.Public); verify(type6.DefineNestedType(name, attributes, parent, packingSize, typesize), type6); } else { // Use DefineNestedType(string, TypeAttributes, Type, Type[]) Assert.True(isDefaultSize && isDefaultPackingSize); // Sanity check TypeBuilder type7 = Helpers.DynamicType(TypeAttributes.Public); verify(type7.DefineNestedType(name, attributes, parent, implementedInterfaces), type7); } }
public void CreateType(TypeAttributes attributes) { TypeBuilder type = Helpers.DynamicType(attributes); Type createdType = type.CreateTypeInfo().AsType(); Assert.Equal(type.Name, createdType.Name); Assert.Equal(type.CreateTypeInfo(), type.CreateTypeInfo()); }
public void Read(ClrModuleReader reader) { this.Flags = (TypeAttributes)reader.Binary.ReadUInt32(); this.TypeDefId = reader.Binary.ReadUInt32(); this.TypeName = reader.ReadString(); this.TypeNamespace = reader.ReadString(); this.Implementation = reader.ReadCodedIndex<Implementation>(); }
public void Initialize(string name, TypeAttributes attr, BlockStructure block = null, Type info = null) { Name = name; Attributes = attr; Block = block; AppendChild(Block); Info = info; }
private void InitializeType(XmlNode ruleInstance) { string modifierstring = ruleInstance.Attributes["modifiers"].Value; foreach (string s in modifierstring.Split(',')) this.typeAttributes = this.typeAttributes | (TypeAttributes)Enum.Parse(typeof(TypeAttributes), s.Trim(), true); }
public EnumResultBuilder (string name, NamespaceBuilder ns, CodeLinePragma loc, TypeAttributes attr) { if (name == null) throw new ArgumentNullException (); enumer = new TheEnum (name, ns, loc, attr); result = new TheResult (name + "Result", ns, name, loc, attr); }
public TheResult (string name, NamespaceBuilder ns, string ename, CodeLinePragma loc, TypeAttributes attr) : base (name, ns, loc, attr) { etype = new UserType (ename); BaseClass = new UserType (typeof (EnumResult<>)); BaseClass.AddTypeArgument (etype); }
internal void Initialize(string name, TypeAttributes attr, IReadOnlyList<GenericParameterStructure> gnr, TypeStructure bt, IReadOnlyList<TypeStructure> imp, BlockStructure block = null, Type info = null) { Generics = gnr; BaseType = bt; Implements = imp; AppendChild(Generics); base.Initialize(name, attr, block, info); }
public MetaRuleBuilder (string name, NamespaceBuilder ns, CodeLinePragma loc, TypeAttributes attr) { rb = new RuleBuilder (name, ns, loc, attr); tmpl = new RuleTemplateBuilder (name + "RTemplate", rb, ns, loc, attr); ns.AddMetaRule (this); BaseClass = RuleType; }
public void GetILGenerator_NoMethodBody_ThrowsInvalidOperationException(TypeAttributes typeAttributes, MethodAttributes methodAttributes) { TypeBuilder type = Helpers.DynamicType(typeAttributes); MethodBuilder method = type.DefineMethod("TestMethod", methodAttributes); Assert.Throws<InvalidOperationException>(() => method.GetILGenerator()); Assert.Throws<InvalidOperationException>(() => method.GetILGenerator(10)); }
public void DefineType(string name, TypeAttributes attributes, Type parent, PackingSize packingSize, int typesize, Type[] implementedInterfaces) { bool isDefaultImplementedInterfaces = implementedInterfaces?.Length == 0; bool isDefaultPackingSize = packingSize == PackingSize.Unspecified; bool isDefaultSize = typesize == 0; bool isDefaultParent = parent == null; bool isDefaultAttributes = attributes == TypeAttributes.NotPublic; Action<TypeBuilder, Module> verify = (type, module) => { Type baseType = attributes.HasFlag(TypeAttributes.Abstract) && parent == null ? null : (parent ?? typeof(object)); Helpers.VerifyType(type, module, null, name, attributes, baseType, typesize, packingSize, implementedInterfaces); }; if (isDefaultImplementedInterfaces) { if (isDefaultSize && isDefaultPackingSize) { if (isDefaultParent) { if (isDefaultAttributes) { // Use DefineType(string) ModuleBuilder module1 = Helpers.DynamicModule(); verify(module1.DefineType(name), module1); } // Use DefineType(string, TypeAttributes) ModuleBuilder module2 = Helpers.DynamicModule(); verify(module2.DefineType(name, attributes), module2); } // Use DefineType(string, TypeAttributes, Type) ModuleBuilder module3 = Helpers.DynamicModule(); verify(module3.DefineType(name, attributes, parent), module3); } else if (isDefaultSize) { // Use DefineType(string, TypeAttributes, Type, PackingSize) ModuleBuilder module4 = Helpers.DynamicModule(); verify(module4.DefineType(name, attributes, parent, packingSize), module4); } else if (isDefaultPackingSize) { // Use DefineType(string, TypeAttributes, Type, int) ModuleBuilder module5 = Helpers.DynamicModule(); verify(module5.DefineType(name, attributes, parent, typesize), module5); } // Use DefineType(string, TypeAttributes, Type, PackingSize, int) ModuleBuilder module6 = Helpers.DynamicModule(); verify(module6.DefineType(name, attributes, parent, packingSize, typesize), module6); } else { // Use DefineType(string, TypeAttributes, Type, Type[]) Assert.True(isDefaultSize && isDefaultPackingSize); // Sanity check ModuleBuilder module7 = Helpers.DynamicModule(); verify(module7.DefineType(name, attributes, parent, implementedInterfaces), module7); } }
public static void GetTypeDefProps(this IMetadataImport importer, int typeDefinition, out string qualifiedName, out TypeAttributes attributes, out int baseType) { int bufferLength; importer.GetTypeDefProps(typeDefinition, null, 0, out bufferLength, out attributes, out baseType); var buffer = new StringBuilder(bufferLength); importer.GetTypeDefProps(typeDefinition, buffer, buffer.Capacity, out bufferLength, out attributes, out baseType); qualifiedName = buffer.ToString(); }
public static CodeTypeDeclaration CreateClass (string name, MemberAttributes attribute, TypeAttributes typeAttr) { CodeTypeDeclaration ct = new CodeTypeDeclaration (name); ct.Attributes = attribute; ct.TypeAttributes = typeAttr; ct.IsClass = true; return ct; }
/// <summary> /// Initializes a new instance of the <see cref="ExportedTypeRow"/> struct. /// </summary> /// <param name="flags">The flags.</param> /// <param name="typeDefTableIdx">The type def table idx.</param> /// <param name="typeNameStringIdx">The type name string idx.</param> /// <param name="typeNamespaceStringIdx">The type namespace string idx.</param> /// <param name="implementationTableIdx">The implementation table idx.</param> public ExportedTypeRow(TypeAttributes flags, TokenTypes typeDefTableIdx, TokenTypes typeNameStringIdx, TokenTypes typeNamespaceStringIdx, TokenTypes implementationTableIdx) { _flags = flags; _typeDefTableIdx = typeDefTableIdx; _typeNameStringIdx = typeNameStringIdx; _typeNamespaceStringIdx = typeNamespaceStringIdx; _implementationTableIdx = implementationTableIdx; }
internal EnumBuilder (ModuleBuilder mb, string name, TypeAttributes visibility, Type underlyingType) { _tb = new TypeBuilder (mb, name, (visibility | TypeAttributes.Sealed), typeof(Enum), null, PackingSize.Unspecified, 0, null); _underlyingType = underlyingType; _underlyingField = _tb.DefineField ("value__", underlyingType, (FieldAttributes.SpecialName | FieldAttributes.Private | FieldAttributes.RTSpecialName)); setup_enum_type (_tb); }
/// <summary> /// Initializes a new instance of the <see cref="ExportedTypeRow"/> struct. /// </summary> /// <param name="flags">The flags.</param> /// <param name="typeDef">The type def.</param> /// <param name="typeName">Name of the type.</param> /// <param name="typeNamespace">The type namespace.</param> /// <param name="implementation">The implementation.</param> public ExportedTypeRow(TypeAttributes flags, HeapIndexToken typeDef, HeapIndexToken typeName, HeapIndexToken typeNamespace, Token implementation) { Flags = flags; TypeDef = typeDef; TypeName = typeName; TypeNamespace = typeNamespace; Implementation = implementation; }
public void DefineType_String_TypeAttributes(TypeAttributes attributes) { ModuleBuilder module = Helpers.DynamicModule(); TypeBuilder type = module.DefineType("TestType", attributes); Type createdType = type.CreateTypeInfo().AsType(); Assert.Equal("TestType", createdType.Name); Assert.Equal(attributes, createdType.GetTypeInfo().Attributes); }
internal static TypeBuilder DefineUniqueType(string strInitFullName, TypeAttributes attrs, Type BaseType, Type[] aInterfaceTypes, ModuleBuilder mb) { string className = strInitFullName; for (int i = 2; mb.GetType(className) != null; i++) { className = strInitFullName + "_" + i; } return mb.DefineType(className, attrs, BaseType, aInterfaceTypes); }
public TypeBuilder RetrieveTestTypeBuilder(TypeAttributes typeAtt) { AssemblyName asmName = new AssemblyName(); asmName.Name = DynamicAssemblyName; AssemblyBuilder asmBuilder = AssemblyBuilder.DefineDynamicAssembly(asmName, AssemblyBuilderAccess.Run); ModuleBuilder modBuilder = TestLibrary.Utilities.GetModuleBuilder(asmBuilder, DynamicModuleName); TypeBuilder typeBuilder = modBuilder.DefineType(DynamicTypeName, typeAtt); return typeBuilder; }
public static CodeTypeDeclaration AddClass(this CodeNamespace codeNamespace, string className, TypeAttributes ma) { var c = Define.Class(className, ma); codeNamespace.Types_Add(c); return c; }
public static TypeBuilder DefineType( string name, TypeAttributes attributes, Type baseType, Type[] interfaces) { name = name + "_" + Counter++; return ModuleBuilder.DefineType(name, attributes, baseType, interfaces); }
protected TypeEmitter(AssemblyEmitter assembly, string className, string @namespace, TypeAttributes typeAttributes, TypeReference baseType, bool addToAssembly) { if (assembly == null) { throw new ArgumentNullException("assembly"); } Assembly = assembly; if (baseType == null) { baseType = Assembly.TypeSystem.Object; } typeDefinition = new TypeDefinition(@namespace, className, typeAttributes, baseType); // Structs without fields must have specified class and packing size parameters if (typeDefinition.IsValueType) { typeDefinition.IsSequentialLayout = true; typeDefinition.ClassSize = 1; typeDefinition.PackingSize = 0; } if (addToAssembly) { Assembly.AddType(typeDefinition); } Assembly.AddTypeUsage(baseType); }
public TypeDefinition(string @namespace, string name, TypeAttributes attributes, TypeReference baseType) : this(@namespace, name, attributes) { this.BaseType = baseType; }
protected sealed override TypeAttributes GetAttributeFlagsImpl() { TypeAttributes attr = _typeDefinition.Flags; return(attr); }
public TypeBuilder DefineType(string name, TypeAttributes attr, Type parent, PackingSize packsize) { return(DefineType(name, attr, parent, null, packsize, TypeBuilder.UnspecifiedTypeSize)); }
internal MetadataTypeDefinition(MetadataModule module, TypeDefinitionHandle handle) { Debug.Assert(module != null); Debug.Assert(!handle.IsNil); this.module = module; this.handle = handle; var metadata = module.metadata; var td = metadata.GetTypeDefinition(handle); this.attributes = td.Attributes; this.fullTypeName = td.GetFullTypeName(metadata); // Find DeclaringType + KnownTypeCode: if (fullTypeName.IsNested) { this.DeclaringTypeDefinition = module.GetDefinition(td.GetDeclaringType()); // Create type parameters: this.TypeParameters = MetadataTypeParameter.Create(module, this.DeclaringTypeDefinition, this, td.GetGenericParameters()); this.NullableContext = td.GetCustomAttributes().GetNullableContext(metadata) ?? this.DeclaringTypeDefinition.NullableContext; } else { // Create type parameters: this.TypeParameters = MetadataTypeParameter.Create(module, this, td.GetGenericParameters()); this.NullableContext = td.GetCustomAttributes().GetNullableContext(metadata) ?? module.NullableContext; var topLevelTypeName = fullTypeName.TopLevelTypeName; for (int i = 0; i < KnownTypeReference.KnownTypeCodeCount; i++) { var ktr = KnownTypeReference.Get((KnownTypeCode)i); if (ktr != null && ktr.TypeName == topLevelTypeName) { this.KnownTypeCode = (KnownTypeCode)i; break; } } } // Find type kind: if ((attributes & TypeAttributes.ClassSemanticsMask) == TypeAttributes.Interface) { this.Kind = TypeKind.Interface; } else if (td.IsEnum(metadata, out var underlyingType)) { this.Kind = TypeKind.Enum; this.EnumUnderlyingType = module.Compilation.FindType(underlyingType.ToKnownTypeCode()); } else if (td.IsValueType(metadata)) { if (KnownTypeCode == KnownTypeCode.Void) { this.Kind = TypeKind.Void; } else { this.Kind = TypeKind.Struct; this.IsByRefLike = (module.TypeSystemOptions & TypeSystemOptions.RefStructs) == TypeSystemOptions.RefStructs && td.GetCustomAttributes().HasKnownAttribute(metadata, KnownAttribute.IsByRefLike); this.IsReadOnly = (module.TypeSystemOptions & TypeSystemOptions.ReadOnlyStructsAndParameters) == TypeSystemOptions.ReadOnlyStructsAndParameters && td.GetCustomAttributes().HasKnownAttribute(metadata, KnownAttribute.IsReadOnly); } } else if (td.IsDelegate(metadata)) { this.Kind = TypeKind.Delegate; } else { this.Kind = TypeKind.Class; this.HasExtensionMethods = this.IsStatic && (module.TypeSystemOptions & TypeSystemOptions.ExtensionMethods) == TypeSystemOptions.ExtensionMethods && td.GetCustomAttributes().HasKnownAttribute(metadata, KnownAttribute.Extension); } }
public bool TryGetTypeDefinitionInfo(int typeDefinitionToken, out string namespaceName, out string typeName, out TypeAttributes attributes) => throw new NotSupportedException(ConverterResources.MetadataNotAvailable);
public TypeBuilder DefineType(string typeName, TypeAttributes attrs, Type parentType) { return(m_ModuleBuilder.DefineType(typeName, attrs, parentType)); }
private Type CreateUncachedProxyType(Type[] baseInterfaces, Type baseType) { AppDomain currentDomain = AppDomain.CurrentDomain; string typeName = string.Format("{0}Proxy", baseType.Name); string assemblyName = string.Format("{0}Assembly", typeName); string moduleName = string.Format("{0}Module", typeName); AssemblyName name = new AssemblyName(assemblyName); #if DEBUG && !SILVERLIGHT AssemblyBuilderAccess access = AssemblyBuilderAccess.RunAndSave; #else AssemblyBuilderAccess access = AssemblyBuilderAccess.Run; #endif AssemblyBuilder assemblyBuilder = currentDomain.DefineDynamicAssembly(name, access); #if DEBUG && !SILVERLIGHT ModuleBuilder moduleBuilder = assemblyBuilder.DefineDynamicModule(moduleName, string.Format("{0}.mod", moduleName), true); #else ModuleBuilder moduleBuilder = assemblyBuilder.DefineDynamicModule(moduleName); #endif TypeAttributes typeAttributes = TypeAttributes.AutoClass | TypeAttributes.Class | TypeAttributes.Public | TypeAttributes.BeforeFieldInit; List <Type> interfaceList = new List <Type>(); if (baseInterfaces != null && baseInterfaces.Length > 0) { interfaceList.AddRange(baseInterfaces); } // Use the proxy dummy as the base type // since we're not inheriting from any class type Type parentType = baseType; if (baseType.IsInterface) { parentType = typeof(ProxyDummy); interfaceList.Add(baseType); } // Add any inherited interfaces Type[] interfaces = interfaceList.ToArray(); foreach (Type interfaceType in interfaces) { BuildInterfaceList(interfaceType, interfaceList); } #if !SILVERLIGHT // Add the ISerializable interface so that it can be implemented if (!interfaceList.Contains(typeof(ISerializable))) { interfaceList.Add(typeof(ISerializable)); } #endif TypeBuilder typeBuilder = moduleBuilder.DefineType(typeName, typeAttributes, parentType, interfaceList.ToArray()); ConstructorBuilder defaultConstructor = DefineConstructor(typeBuilder); // Implement IProxy ProxyImplementor implementor = new ProxyImplementor(); implementor.ImplementProxy(typeBuilder); MethodInfo[] methods = baseType.GetMethods(BindingFlags.Public | BindingFlags.Instance); List <MethodInfo> proxyList = new List <MethodInfo>(); BuildMethodList(interfaceList, methods, proxyList); Debug.Assert(_proxyMethodBuilder != null, "ProxyMethodBuilder cannot be null"); FieldInfo interceptorField = implementor.InterceptorField; foreach (MethodInfo method in proxyList) { #if !SILVERLIGHT // Provide a custom implementation of ISerializable // instead of redirecting it back to the interceptor if (method.DeclaringType == typeof(ISerializable)) { continue; } #endif _proxyMethodBuilder.CreateProxiedMethod(interceptorField, method, typeBuilder); } #if !SILVERLIGHT // Make the proxy serializable AddSerializationSupport(baseType, baseInterfaces, typeBuilder, interceptorField, defaultConstructor); #endif Type proxyType = typeBuilder.CreateType(); #if DEBUG_PROXY_OUTPUT assemblyBuilder.Save("generatedAssembly.dll"); #endif return(proxyType); }
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()); }
public void DefineParameter_NoParameters_NonZeroPosition_ThrowsArgumentOutOfRangeException(TypeAttributes typeAttributes, MethodAttributes methodAttributes, ParameterAttributes parameterAttributes) { TypeBuilder type = Helpers.DynamicType(typeAttributes); MethodBuilder method = type.DefineMethod("TestMethod", methodAttributes); Assert.Throws <ArgumentOutOfRangeException>(() => method.DefineParameter(1, parameterAttributes, "Param1")); Assert.Throws <ArgumentOutOfRangeException>(() => method.DefineParameter(-1, parameterAttributes, "Param1")); }
static public TypeBuilder CreateTypeBuilder(this ModuleBuilder item, string name, TypeAttributes type_attributes) { return(item.DefineType(name, type_attributes)); }
public TypeEmitter(AssemblyEmitter assembly, string className, string @namespace = "", TypeAttributes typeAttributes = DefaultTypeAttributes, TypeReference baseType = null) : this(assembly, className, @namespace, typeAttributes, baseType, true) { }
public void CreateType_InvalidTypeAttributes_Throws(TypeAttributes attributes, Type exceptionType) { Assert.Throws(exceptionType, () => Helpers.DynamicType(attributes)); }
//public virtual Structure generate() //{ // return new Structure(); //} public void build() { string moduleName = "test.exe"; string path = ""; try { AssemblyName name = new AssemblyName(System.IO.Path.GetFileNameWithoutExtension(moduleName)); // AssemblyBuilder asmb = AppDomain.CurrentDomain.DefineDynamicAssembly(name, AssemblyBuilderAccess.RunAndSave); AssemblyBuilder asmb = AssemblyBuilder.DefineDynamicAssembly(new AssemblyName(Guid.NewGuid().ToString()), AssemblyBuilderAccess.RunAndCollect); ModuleBuilder modb = asmb.DefineDynamicModule(moduleName); // AssemblyBuilder asmbincstance = asmb.CreateInstance("mymodule"); TypeBuilder typeBuilder = modb.DefineType("Foo"); MethodBuilder methb = typeBuilder.DefineMethod("Main", MethodAttributes.Static, typeof(void), Type.EmptyTypes); ILGenerator il = methb.GetILGenerator(); //LocalBuilder aObject = il.DeclareLocal(aType); //il.Emit(OpCodes.Newobj, aType.GetConstructor(new Type[0])); //il.Emit(OpCodes.Stloc, aObject); // Init of _base_L field attribute //il.Emit(OpCodes.Ldloc, aObject); //il.Emit(OpCodes.Newobj, lType); //il.Emit(OpCodes.Stfld, aTypeBaseL); // Call of foo function from base class L //il.Emit(OpCodes.Ldfld, aTypeBaseL); //il.Emit(OpCodes.Call, lTypeMethodFoo); Assembly slib = Assembly.LoadFrom("SLib.dll"); Type consoleType = slib.GetType("SLib.IO.Console"); //BindingFlags flags = BindingFlags.InvokeMethod | BindingFlags.Public | BindingFlags.Static; MethodInfo consolePut = consoleType.GetMethod("put", new [] { typeof(string) }); MethodInfo readKey = consoleType.GetMethod("read_key", new Type[0]); il.Emit(OpCodes.Ldstr, "HelloWorld!\n"); il.Emit(OpCodes.Call, consolePut); Type file = slib.GetType("SLib.IO.File"); ConstructorInfo fileConstructor = file.GetConstructor(new Type[] { typeof(string), typeof(bool) }); LocalBuilder fileBuilder = il.DeclareLocal(file); string fileName = @"test.txt"; il.Emit(OpCodes.Ldstr, "File will be created after key press\n"); il.Emit(OpCodes.Call, consolePut); il.Emit(OpCodes.Call, readKey); il.Emit(OpCodes.Ldstr, fileName); il.Emit(OpCodes.Ldc_I4_1); il.Emit(OpCodes.Newobj, fileConstructor); il.Emit(OpCodes.Stloc, fileBuilder); il.Emit(OpCodes.Ldloc, fileBuilder); il.Emit(OpCodes.Ldstr, "File will be removed after key press\n"); il.Emit(OpCodes.Call, consolePut); il.Emit(OpCodes.Call, readKey); MethodInfo remove = file.GetMethod("remove", new Type[0]); il.Emit(OpCodes.Callvirt, remove); il.Emit(OpCodes.Ldstr, "File removed\n"); il.Emit(OpCodes.Call, consolePut); il.Emit(OpCodes.Call, readKey); //TypeBuilder lBuilder = modb.DefineType("L"); //FieldBuilder iBuilder = lBuilder.DefineField("i", typeof(int), FieldAttributes.Public); //MethodBuilder newMethod = lBuilder.DefineMethod(); //If(4 + 5) > (9 - 4 / 2) then // StandartIO.Print(“True\n”) //Else // StandartIO.Print(“False\n”) //End //StandartIO.Print(“end if\n”) //il.Emit(OpCodes.Ldstr, "(4+5) > (9-4/2) ?\n"); //il.Emit(OpCodes.Call, consolePut); //il.Emit(OpCodes.Call, readKey); //Label @else = il.DefineLabel(); //il.Emit(OpCodes.Ldc_I4, 4); //il.Emit(OpCodes.Ldc_I4, 5); //il.Emit(OpCodes.Add); //il.Emit(OpCodes.Ldc_I4, 9); //il.Emit(OpCodes.Ldc_I4, 4); //il.Emit(OpCodes.Ldc_I4, 2); //il.Emit(OpCodes.Div); //il.Emit(OpCodes.Sub); //il.Emit(OpCodes.Ble, @else); //il.Emit(OpCodes.Ldstr, "True\n"); //il.Emit(OpCodes.Call, consolePut); //Label @end = il.DefineLabel(); //il.Emit(OpCodes.Br, @end); //il.MarkLabel(@else); //il.Emit(OpCodes.Ldstr, "False\n"); //il.Emit(OpCodes.Call, consolePut); //il.MarkLabel(@end); //il.Emit(OpCodes.Call, readKey); //il.Emit(OpCodes.Ldstr, "end if\n"); //il.Emit(OpCodes.Call, consolePut); //il.Emit(OpCodes.Call, readKey); // x is Integer(5) //LocalBuilder x = il.DeclareLocal(typeof(int)); //il.Emit(OpCodes.Ldc_I4_5); //il.Emit(OpCodes.Stloc, x); // while x > 1 //Label @loop = il.DefineLabel(); //Label @end = il.DefineLabel(); //il.MarkLabel(@loop); //il.Emit(OpCodes.Ldc_I4, x); //il.Emit(OpCodes.Ldc_I4_1); //il.Emit(OpCodes.Sub); //il.Emit(OpCodes.Stloc, x); //il.Emit(OpCodes.Ldc_I4_1); //il.Emit(OpCodes.Ble, @end); // loop //il.Emit(OpCodes.Ldstr, "loop \n"); //il.Emit(OpCodes.Call, consolePut); //il.Emit(OpCodes.Br, @loop); // end //il.MarkLabel(@end); //il.Emit(OpCodes.Ldstr, "end loop\n"); //il.Emit(OpCodes.Call, consolePut); //il.Emit(OpCodes.Call, readKey); //il.Emit(OpCodes.Pop); il.Emit(OpCodes.Ret); typeBuilder.CreateType(); // unit L TypeBuilder lType = modb.DefineType("L"); // define constructor ConstructorBuilder lTypeCtor = lType.DefineConstructor( MethodAttributes.Public | MethodAttributes.SpecialName | MethodAttributes.RTSpecialName, CallingConventions.Standard, new Type[0]); ILGenerator IllType = lTypeCtor.GetILGenerator(); IllType.Emit(OpCodes.Ldarg_0); ConstructorInfo ctor = typeof(Object).GetConstructor(new Type[0]); IllType.Emit(OpCodes.Call, ctor); IllType.Emit(OpCodes.Ret); // type creation lType.CreateType(); TypeBuilder aType = modb.DefineType("A"); FieldBuilder aTypeBaseField = aType.DefineField("__base_L", lType, FieldAttributes.Public); ConstructorBuilder aTypeCtor = aType.DefineConstructor( MethodAttributes.Public | MethodAttributes.SpecialName | MethodAttributes.RTSpecialName, CallingConventions.Standard, new Type[0]); ILGenerator IlaType = aTypeCtor.GetILGenerator(); IlaType.Emit(OpCodes.Ldarg_0); ConstructorInfo aCtor = typeof(Object).GetConstructor(new Type[0]); IlaType.Emit(OpCodes.Call, aCtor); IlaType.Emit(OpCodes.Newobj, lType); IlaType.Emit(OpCodes.Stloc, aTypeBaseField); IlaType.Emit(OpCodes.Ret); aType.CreateType(); TypeAttributes valueAttrTypes = TypeAttributes.AnsiClass | TypeAttributes.SequentialLayout | TypeAttributes.Sealed | TypeAttributes.Public | TypeAttributes.BeforeFieldInit; TypeBuilder valueType = modb.DefineType("ValueData", valueAttrTypes, typeof(ValueType)); //ConstructorInfo customGenCtor = typeof(System.Runtime.CompilerServices.CompilerGeneratedAttribute).GetConstructor(new Type[0]); //valueType.SetCustomAttribute(customGenCtor, new byte[] { 01, 00, 00, 00 }); FieldBuilder xValueType = valueType.DefineField("x", typeof(int), FieldAttributes.Public); valueType.CreateType(); modb.CreateGlobalFunctions(); // asmb.Save("my_assembly"); // asmb.EntryPoint = methb; } catch (Exception e) { Console.WriteLine(e.StackTrace); } //Loat(); }
public TypeBuilder DefineType(string name, TypeAttributes attr, Type parent, PackingSize packingSize, int typesize) { return(DefineType(name, attr, parent, null, packingSize, typesize)); }
public SourcefileRuleBuilder(string name, NamespaceBuilder ns, CodeLinePragma loc, TypeAttributes attr) : base(name, ns, loc, attr) { BaseClass = new UserType(typeof(SourcefileRule)); fp.Add(name); }
public TypeBuilder DefineType(string name, TypeAttributes attr, Type parent, Type[] interfaces) { return(DefineType(name, attr, parent, interfaces, PackingSize.Unspecified, TypeBuilder.UnspecifiedTypeSize)); }
public static RecordTypeDescriptor GenerateRecordTypeDescriptor(AssemblyGen ag, object name, object parent, object uid, object issealed, object isopaque, object fields, object fieldtypes) { string n = SymbolTable.IdToString(RequiresNotNull <SymbolId>(name)); string id = uid is SymbolId?SymbolTable.IdToString(RequiresNotNull <SymbolId>(uid)) : uid as string; if (id != null) { RecordTypeDescriptor ngrtd; if (nongenerative.TryGetValue(n + id, out ngrtd)) { return(ngrtd); } var type = ClrGenerator.GetTypeFast("record." + id + "." + n.Replace("&", "$").Replace("*", "$")); // TODO: Make me better if (type != null) { return(RecordTypeDescriptor.Create(type, n, id, parent as RecordTypeDescriptor)); } } bool @sealed = RequiresNotNull <bool>(issealed); bool opaque = RequiresNotNull <bool>(isopaque); RecordTypeDescriptor prtd = parent as RecordTypeDescriptor; // can be #f Type parenttype = typeof(object); if (prtd != null) { parenttype = prtd.type; } else if (n == "&condition") { parenttype = typeof(Condition); } TypeAttributes attrs = TypeAttributes.Public | TypeAttributes.Serializable; var rtd = new RecordTypeDescriptor { Name = n, @sealed = @sealed, opaque = opaque, ag = ag, Parent = prtd, uid = uid, generative = id == null || uid is string, }; if (@sealed) { attrs |= TypeAttributes.Sealed; } object gid = (object)id ?? Guid.NewGuid(); var ns = "record." + gid; var typename = ns + "." + n.Replace("&", "$").Replace("*", "$"); // TODO: Make me better TypeGen tg = ag.DefinePublicType(typename, parenttype, attrs); rtd.tg = tg; rtd.type = tg.TypeBuilder; if (id != null) { nongenerative[n + id] = rtd; } if (parenttype.IsSubclassOf(typeof(Condition))) { SetSymbolValueFast(SymbolTable.StringToObject(n + "-rtd"), rtd); } GeneratePredicate(n, rtd, tg); GenerateFields(fields, n, rtd, tg, fieldtypes); GenerateConstructor(rtd, tg, parenttype); return(rtd); }
public TypeBuilder DefineType(string name, TypeAttributes attr, Type parent) { return(DefineType(name, attr, parent, null)); }
public bool CreateCilTypeForClass(JavaClass jclass) { var name = jclass.Name; if (typeMap.TryGetValue(name, out _) || jclass.IsInnerClass() && (name.StartsWith("java.lang.Object$") || name.StartsWith("java.lang.String$"))) { Console.WriteLine($"skipping duplicate class '{name}'"); return(false); } string nsName, clsName; TypeAttributes attrs = 0; if (jclass.IsInnerClass()) { nsName = string.Empty; clsName = jclass.OuterAndInnerClasses[0].InnerShortName; if (!string.IsNullOrEmpty(clsName)) { int idx = name.LastIndexOf('$'); if (idx != -1 && idx + 1 < name.Length) { clsName = name.Substring(idx + 1); } } if (string.IsNullOrEmpty(clsName) || (!Char.IsLetter(clsName[0]))) { clsName = "autogenerated_" + jclass.GetHashCode().ToString("X8"); } if ((jclass.Flags & JavaAccessFlags.ACC_PUBLIC) != 0) { attrs = TypeAttributes.NestedPublic; } else if ((jclass.Flags & JavaAccessFlags.ACC_PRIVATE) != 0) { attrs = TypeAttributes.NestedPrivate; } else if ((jclass.Flags & JavaAccessFlags.ACC_PROTECTED) != 0) { attrs = TypeAttributes.NestedFamORAssem; } else { attrs = TypeAttributes.NestedAssembly; } } else { int n = jclass.PackageNameLength; nsName = name.Substring(0, n); if (name[n] == '.') { n++; } clsName = name.Substring(n); if ((jclass.Flags & JavaAccessFlags.ACC_PUBLIC) != 0) { attrs |= TypeAttributes.Public; } } if ((jclass.Flags & JavaAccessFlags.ACC_ABSTRACT) != 0) { attrs |= TypeAttributes.Abstract; } if ((jclass.Flags & JavaAccessFlags.ACC_INTERFACE) != 0) { attrs |= TypeAttributes.Interface; } if ((jclass.Flags & JavaAccessFlags.ACC_FINAL) != 0) { attrs |= TypeAttributes.Sealed; } var newType = new TypeDefinition(nsName, clsName, attrs); newType.CustomAttributes.Add(new CustomAttribute(retainNameAttributeConstructor)); typeMap[name] = newType; return(true); }
public TypeBuilder CreateBuilder(string name, TypeAttributes attr, int typeSize) { return(builder.DefineType(name, attr, null, typeSize)); }
public static bool HasFlag(this TypeDefinition typeDefinition, TypeAttributes attribute) => (typeDefinition.Attributes & attribute) == attribute;
private Type CreateType(IProxyInvocationHandler handler, Type[] interfaces, string dynamicTypeName) { Type retVal = null; if (handler != null && interfaces != null) { Type objType = typeof(System.Object); Type handlerType = typeof(IProxyInvocationHandler); AppDomain domain = Thread.GetDomain(); AssemblyName assemblyName = new AssemblyName(); assemblyName.Name = ASSEMBLY_NAME; assemblyName.Version = new Version(1, 0, 0, 0); // create a new assembly for this proxy, one that isn't presisted on the file system AssemblyBuilder assemblyBuilder = domain.DefineDynamicAssembly( assemblyName, AssemblyBuilderAccess.Run); // assemblyName, AssemblyBuilderAccess.RunAndSave,"."); // to save it to the disk // create a new module for this proxy ModuleBuilder moduleBuilder = assemblyBuilder.DefineDynamicModule(MODULE_NAME); // Set the class to be public and sealed TypeAttributes typeAttributes = TypeAttributes.Class | TypeAttributes.Public | TypeAttributes.Sealed; // Gather up the proxy information and create a new type builder. One that // inherits from Object and implements the interface passed in TypeBuilder typeBuilder = moduleBuilder.DefineType( dynamicTypeName, typeAttributes, objType, interfaces); // Define a member variable to hold the delegate FieldBuilder handlerField = typeBuilder.DefineField( HANDLER_NAME, handlerType, FieldAttributes.Private); // build a constructor that takes the delegate object as the only argument //ConstructorInfo defaultObjConstructor = objType.GetConstructor( new Type[0] ); ConstructorInfo superConstructor = objType.GetConstructor(new Type[0]); ConstructorBuilder delegateConstructor = typeBuilder.DefineConstructor( MethodAttributes.Public, CallingConventions.Standard, new Type[] { handlerType }); #region ( "Constructor IL Code" ) ILGenerator constructorIL = delegateConstructor.GetILGenerator(); // Load "this" constructorIL.Emit(OpCodes.Ldarg_0); // Load first constructor parameter constructorIL.Emit(OpCodes.Ldarg_1); // Set the first parameter into the handler field constructorIL.Emit(OpCodes.Stfld, handlerField); // Load "this" constructorIL.Emit(OpCodes.Ldarg_0); // Call the super constructor constructorIL.Emit(OpCodes.Call, superConstructor); // Constructor return constructorIL.Emit(OpCodes.Ret); #endregion // for every method that the interfaces define, build a corresponding // method in the dynamic type that calls the handlers invoke method. foreach (Type interfaceType in interfaces) { GenerateMethod(interfaceType, handlerField, typeBuilder); } retVal = typeBuilder.CreateType(); // assemblyBuilder.Save(dynamicTypeName + ".dll"); } return(retVal); }
private static bool IsNested(TypeAttributes flags) { return((flags & ((TypeAttributes)0x00000006)) != 0); }
private static bool IsPublic(TypeAttributes attributes) { var masked = attributes & TypeAttributes.VisibilityMask; return(masked == TypeAttributes.Public || masked == TypeAttributes.NestedPublic); }
public static bool IsNested(this TypeAttributes flags) { return((flags & NestedMask) != 0); }
public PersistentCollectionMemberInfo(Session session, PersistentAssociationAttribute persistentAssociationAttribute) : base(session) { TypeAttributes.Add(persistentAssociationAttribute); }
public static bool IsForwarder(this TypeAttributes flags) { return((flags & Forwarder) != 0); }
internal TypeBuilder DefineType(bool inSignedModulePreferably, string name, TypeAttributes flags) { var module = ObtainDynamicModule(disableSignedModule == false && inSignedModulePreferably); return(module.DefineType(name, flags)); }
public TypeDefinition(string @namespace, string name, TypeAttributes attributes) : base(@namespace, name) { this.attributes = (uint)attributes; this.token = new MetadataToken(TokenType.TypeDef); }