Example #1
0
        private MethodToken GetTokenNoLock()
        {
            Debug.Assert(m_tkMethod.Token == 0, "m_tkMethod should not have been initialized");

            int sigLength;

            byte[] sigBytes = GetMethodSignature().InternalGetSignature(out sigLength);

            int token = TypeBuilder.DefineMethod(m_module.GetNativeHandle(), m_containingType.MetadataTokenInternal, m_strName, sigBytes, sigLength, Attributes);

            m_tkMethod = new MethodToken(token);

            if (m_inst != null)
            {
                foreach (GenericTypeParameterBuilder tb in m_inst)
                {
                    if (!tb.m_type.IsCreated())
                    {
                        tb.m_type.CreateType();
                    }
                }
            }

            TypeBuilder.SetMethodImpl(m_module.GetNativeHandle(), token, m_dwMethodImplFlags);

            return(m_tkMethod);
        }
        private int GetMethodToken(MethodBase method, Type[] optionalParameterTypes, bool UseMethodDef)
        {
            int           tkParent = 0;
            ModuleBuilder module   = (ModuleBuilder)this.m_methodBuilder.Module;
            MethodInfo    info     = method as MethodInfo;

            if (method.IsGenericMethod)
            {
                int        num2;
                MethodInfo genericMethodDefinition   = info;
                bool       isGenericMethodDefinition = info.IsGenericMethodDefinition;
                if (!isGenericMethodDefinition)
                {
                    genericMethodDefinition = info.GetGenericMethodDefinition();
                }
                if (!this.m_methodBuilder.Module.Equals(genericMethodDefinition.Module) || ((genericMethodDefinition.DeclaringType != null) && genericMethodDefinition.DeclaringType.IsGenericType))
                {
                    tkParent = this.GetMemberRefToken(genericMethodDefinition, null);
                }
                else
                {
                    tkParent = module.GetMethodTokenInternal(genericMethodDefinition).Token;
                }
                if (isGenericMethodDefinition && UseMethodDef)
                {
                    return(tkParent);
                }
                byte[] signature = SignatureHelper.GetMethodSpecSigHelper(module, info.GetGenericArguments()).InternalGetSignature(out num2);
                return(TypeBuilder.DefineMethodSpec(module.GetNativeHandle(), tkParent, signature, num2));
            }
            if (((method.CallingConvention & CallingConventions.VarArgs) == 0) && ((method.DeclaringType == null) || !method.DeclaringType.IsGenericType))
            {
                if (info != null)
                {
                    return(module.GetMethodTokenInternal(info).Token);
                }
                return(module.GetConstructorToken(method as ConstructorInfo).Token);
            }
            return(this.GetMemberRefToken(method, optionalParameterTypes));
        }
Example #3
0
        [System.Security.SecurityCritical]  // auto-generated
        private void Init(String fullname, TypeAttributes attr, Type parent, Type[] interfaces, ModuleBuilder module,
            PackingSize iPackingSize, int iTypeSize, TypeBuilder enclosingType)
        {
            if (fullname == null)
                throw new ArgumentNullException("fullname");

            if (fullname.Length == 0)
                throw new ArgumentException(Environment.GetResourceString("Argument_EmptyName"), "fullname");

            if (fullname[0] == '\0')
                throw new ArgumentException(Environment.GetResourceString("Argument_IllegalName"), "fullname");


            if (fullname.Length > 1023)
                throw new ArgumentException(Environment.GetResourceString("Argument_TypeNameTooLong"), "fullname");
            Contract.EndContractBlock();

            int i;
            m_module = module;
            m_DeclaringType = enclosingType;
            AssemblyBuilder containingAssem = m_module.ContainingAssemblyBuilder;

            // cannot have two types within the same assembly of the same name
            containingAssem.m_assemblyData.CheckTypeNameConflict(fullname, enclosingType);

            if (enclosingType != null)
            {
                // Nested Type should have nested attribute set.
                // If we are renumbering TypeAttributes' bit, we need to change the logic here.
                if (((attr & TypeAttributes.VisibilityMask) == TypeAttributes.Public) ||((attr & TypeAttributes.VisibilityMask) == TypeAttributes.NotPublic))
                    throw new ArgumentException(Environment.GetResourceString("Argument_BadNestedTypeFlags"), "attr");
            }

            int[] interfaceTokens = null;
            if (interfaces != null)
            {
                for(i = 0; i < interfaces.Length; i++)
                {
                    if (interfaces[i] == null)
                    {
                        // cannot contain null in the interface list
                        throw new ArgumentNullException("interfaces");
                    }
                }
                interfaceTokens = new int[interfaces.Length + 1];
                for(i = 0; i < interfaces.Length; i++)
                {
                    interfaceTokens[i] = m_module.GetTypeTokenInternal(interfaces[i]).Token;
                }
            }

            int iLast = fullname.LastIndexOf('.');
            if (iLast == -1 || iLast == 0)
            {
                // no name space
                m_strNameSpace = String.Empty;
                m_strName = fullname;
            }
            else
            {
                // split the name space
                m_strNameSpace = fullname.Substring(0, iLast);
                m_strName = fullname.Substring(iLast + 1);
            }

            VerifyTypeAttributes(attr);

            m_iAttr = attr;

            SetParent(parent);

            m_listMethods = new List<MethodBuilder>();
            m_lastTokenizedMethod = -1;

            SetInterfaces(interfaces);

            int tkParent = 0;
            if (m_typeParent != null)
                tkParent = m_module.GetTypeTokenInternal(m_typeParent).Token;

            int tkEnclosingType = 0;
            if (enclosingType != null)
            {
                tkEnclosingType = enclosingType.m_tdType.Token;
            }

            m_tdType = new TypeToken(DefineType(m_module.GetNativeHandle(),
                fullname, tkParent, m_iAttr, tkEnclosingType, interfaceTokens));

            m_iPackingSize = iPackingSize;
            m_iTypeSize = iTypeSize;
            if ((m_iPackingSize != 0) ||(m_iTypeSize != 0))
                SetClassLayout(GetModuleBuilder().GetNativeHandle(), m_tdType.Token, m_iPackingSize, m_iTypeSize);

#if !FEATURE_CORECLR
            // If the type is public and it is contained in a assemblyBuilder,
            // update the public COMType list.
            if (IsPublicComType(this))
            {
                if (containingAssem.IsPersistable() && m_module.IsTransient() == false)
                {
                    // This will throw InvalidOperationException if the assembly has been saved
                    // Ideally we should reject all emit operations if the assembly has been saved,
                    // but that would be a breaking change for some. Currently you cannot define 
                    // modules and public types, but you can still define private types and global methods.
                    containingAssem.m_assemblyData.AddPublicComType(this);
                }

                // Now add the type to the ExportedType table
                if (!m_module.Equals(containingAssem.ManifestModule))
                    containingAssem.DefineExportedTypeInMemory(this, m_module.m_moduleData.FileToken, m_tdType.Token);
            }
#endif
            m_module.AddType(FullName, this);
        }
Example #4
0
        [System.Security.SecurityCritical]  // auto-generated
        internal static unsafe void SetConstantValue(ModuleBuilder module, int tk, Type destType, Object value)
        {
            // This is a helper function that is used by ParameterBuilder, PropertyBuilder,
            // and FieldBuilder to validate a default value and save it in the meta-data.

            if (value != null)
            {
                Type type = value.GetType();

                // We should allow setting a constant value on a ByRef parameter
                if (destType.IsByRef)
                    destType = destType.GetElementType();

                if (destType.IsEnum)
                {
                    //                                   |  UnderlyingSystemType     |  Enum.GetUnderlyingType() |  IsEnum
                    // ----------------------------------|---------------------------|---------------------------|---------
                    // runtime Enum Type                 |  self                     |  underlying type of enum  |  TRUE
                    // EnumBuilder                       |  underlying type of enum  |  underlying type of enum* |  TRUE
                    // TypeBuilder of enum types**       |  underlying type of enum  |  Exception                |  TRUE
                    // TypeBuilder of enum types (baked) |  runtime enum type        |  Exception                |  TRUE

                    //  *: the behavior of Enum.GetUnderlyingType(EnumBuilder) might change in the future
                    //     so let's not depend on it.
                    // **: created with System.Enum as the parent type.

                    // The above behaviors might not be the most consistent but we have to live with them.

                    Type underlyingType;
                    EnumBuilder enumBldr;
                    TypeBuilder typeBldr;
                    if ((enumBldr = destType as EnumBuilder) != null)
                    {
                        underlyingType = enumBldr.GetEnumUnderlyingType();

                        // The constant value supplied should match either the baked enum type or its underlying type
                        // we don't need to compare it with the EnumBuilder itself because you can never have an object of that type
                        if (type != enumBldr.m_typeBuilder.m_bakedRuntimeType && type != underlyingType)
                            throw new ArgumentException(Environment.GetResourceString("Argument_ConstantDoesntMatch"));
                    }
                    else if ((typeBldr = destType as TypeBuilder) != null)
                    {
                        underlyingType = typeBldr.m_enumUnderlyingType;

                        // The constant value supplied should match either the baked enum type or its underlying type
                        // typeBldr.m_enumUnderlyingType is null if the user hasn't created a "value__" field on the enum
                        if (underlyingType == null || (type != typeBldr.UnderlyingSystemType && type != underlyingType))
                            throw new ArgumentException(Environment.GetResourceString("Argument_ConstantDoesntMatch"));
                    }
                    else // must be a runtime Enum Type
                    {
                        Contract.Assert(destType is RuntimeType, "destType is not a runtime type, an EnumBuilder, or a TypeBuilder.");

                        underlyingType = Enum.GetUnderlyingType(destType);

                        // The constant value supplied should match either the enum itself or its underlying type
                        if (type != destType && type != underlyingType)
                            throw new ArgumentException(Environment.GetResourceString("Argument_ConstantDoesntMatch"));
                    }

                    type = underlyingType;
                }
                else
                {
                    // Note that it is non CLS compliant if destType != type. But RefEmit never guarantees CLS-Compliance.
                    if (!destType.IsAssignableFrom(type))
                        throw new ArgumentException(Environment.GetResourceString("Argument_ConstantDoesntMatch"));
                }
                        
                CorElementType corType = RuntimeTypeHandle.GetCorElementType((RuntimeType)type);

                switch (corType)
                {
                    case CorElementType.I1:
                    case CorElementType.U1:
                    case CorElementType.Boolean:
                    case CorElementType.I2:
                    case CorElementType.U2:
                    case CorElementType.Char:
                    case CorElementType.I4:
                    case CorElementType.U4:
                    case CorElementType.R4:
                    case CorElementType.I8:
                    case CorElementType.U8:
                    case CorElementType.R8:
                        fixed (byte* pData = &JitHelpers.GetPinningHelper(value).m_data)
                            SetConstantValue(module.GetNativeHandle(), tk, (int)corType, pData);
                        break;

                    default:
                        if (type == typeof(String))
                        {
                            fixed (char* pString = (string)value)
                                SetConstantValue(module.GetNativeHandle(), tk, (int)CorElementType.String, pString);
                        }
                        else if (type == typeof(DateTime))
                        {
                            //date is a I8 representation
                            long ticks = ((DateTime)value).Ticks;
                            SetConstantValue(module.GetNativeHandle(), tk, (int)CorElementType.I8, &ticks);
                        }
                        else
                        {
                            throw new ArgumentException(Environment.GetResourceString("Argument_ConstantNotSupported", type.ToString()));
                        }
                        break;
                }
            }
            else
            {
                if (destType.IsValueType)
                {
                    // nullable types can hold null value.
                    if (!(destType.IsGenericType && destType.GetGenericTypeDefinition() == typeof(Nullable<>)))
                        throw new ArgumentException(Environment.GetResourceString("Argument_ConstantNull"));
                }

                SetConstantValue(module.GetNativeHandle(), tk, (int)CorElementType.Class, null);
            }
        }
Example #5
0
        [System.Security.SecurityCritical]  // auto-generated
        internal static void DefineCustomAttribute(ModuleBuilder module, int tkAssociate, int tkConstructor,
            byte[] attr, bool toDisk, bool updateCompilerFlags)
        {
            byte[] localAttr = null;

            if (attr != null)
            {
                localAttr = new byte[attr.Length];
                Array.Copy(attr, localAttr, attr.Length);
            }

            DefineCustomAttribute(module.GetNativeHandle(), tkAssociate, tkConstructor, 
                localAttr, (localAttr != null) ? localAttr.Length : 0, toDisk, updateCompilerFlags);
        }
Example #6
0
 internal QCallModule(ref System.Reflection.Emit.ModuleBuilder module)
 {
     _ptr    = Unsafe.AsPointer(ref module);
     _module = module.GetNativeHandle().GetUnderlyingNativeHandle();
 }
 internal static unsafe void SetConstantValue(ModuleBuilder module, int tk, Type destType, object value)
 {
     if (value != null)
     {
         Type c = value.GetType();
         if (destType.IsByRef)
         {
             destType = destType.GetElementType();
         }
         if (destType.IsEnum)
         {
             Type underlyingSystemType;
             EnumBuilder builder = destType as EnumBuilder;
             if (builder != null)
             {
                 underlyingSystemType = builder.UnderlyingSystemType;
                 if ((c != builder.RuntimeEnumType) && (c != underlyingSystemType))
                 {
                     throw new ArgumentException(Environment.GetResourceString("Argument_ConstantDoesntMatch"));
                 }
             }
             else
             {
                 TypeBuilder builder2 = destType as TypeBuilder;
                 if (builder2 != null)
                 {
                     underlyingSystemType = builder2.m_underlyingSystemType;
                     if ((underlyingSystemType == null) || ((c != builder2.UnderlyingSystemType) && (c != underlyingSystemType)))
                     {
                         throw new ArgumentException(Environment.GetResourceString("Argument_ConstantDoesntMatch"));
                     }
                 }
                 else
                 {
                     underlyingSystemType = Enum.GetUnderlyingType(destType);
                     if ((c != destType) && (c != underlyingSystemType))
                     {
                         throw new ArgumentException(Environment.GetResourceString("Argument_ConstantDoesntMatch"));
                     }
                 }
             }
             c = underlyingSystemType;
         }
         else if (!destType.IsAssignableFrom(c))
         {
             throw new ArgumentException(Environment.GetResourceString("Argument_ConstantDoesntMatch"));
         }
         CorElementType corElementType = RuntimeTypeHandle.GetCorElementType(c.GetTypeHandleInternal().GetRuntimeType());
         switch (corElementType)
         {
             case CorElementType.Boolean:
             case CorElementType.Char:
             case CorElementType.I1:
             case CorElementType.U1:
             case CorElementType.I2:
             case CorElementType.U2:
             case CorElementType.I4:
             case CorElementType.U4:
             case CorElementType.I8:
             case CorElementType.U8:
             case CorElementType.R4:
             case CorElementType.R8:
                 fixed (byte* numRef = &JitHelpers.GetPinningHelper(value).m_data)
                 {
                     SetConstantValue(module.GetNativeHandle(), tk, (int) corElementType, (void*) numRef);
                 }
                 return;
         }
         if (c == typeof(string))
         {
             fixed (char* str = ((char*) ((string) value)))
             {
                 char* chPtr = str;
                 SetConstantValue(module.GetNativeHandle(), tk, 14, (void*) chPtr);
             }
         }
         else
         {
             if (c != typeof(DateTime))
             {
                 throw new ArgumentException(Environment.GetResourceString("Argument_ConstantNotSupported", new object[] { c.ToString() }));
             }
             DateTime time = (DateTime) value;
             long ticks = time.Ticks;
             SetConstantValue(module.GetNativeHandle(), tk, 10, (void*) &ticks);
         }
     }
     else
     {
         if (destType.IsValueType)
         {
             throw new ArgumentException(Environment.GetResourceString("Argument_ConstantNull"));
         }
         SetConstantValue(module.GetNativeHandle(), tk, 0x12, null);
     }
 }
Example #8
0
        private void Init(String fullname, TypeAttributes attr, Type parent, Type[] interfaces, ModuleBuilder module,
            PackingSize iPackingSize, int iTypeSize, TypeBuilder enclosingType)
        {
            if (fullname == null)
                throw new ArgumentNullException(nameof(fullname));

            if (fullname.Length == 0)
                throw new ArgumentException(Environment.GetResourceString("Argument_EmptyName"), nameof(fullname));

            if (fullname[0] == '\0')
                throw new ArgumentException(Environment.GetResourceString("Argument_IllegalName"), nameof(fullname));


            if (fullname.Length > 1023)
                throw new ArgumentException(Environment.GetResourceString("Argument_TypeNameTooLong"), nameof(fullname));
            Contract.EndContractBlock();

            int i;
            m_module = module;
            m_DeclaringType = enclosingType;
            AssemblyBuilder containingAssem = m_module.ContainingAssemblyBuilder;

            // cannot have two types within the same assembly of the same name
            containingAssem.m_assemblyData.CheckTypeNameConflict(fullname, enclosingType);

            if (enclosingType != null)
            {
                // Nested Type should have nested attribute set.
                // If we are renumbering TypeAttributes' bit, we need to change the logic here.
                if (((attr & TypeAttributes.VisibilityMask) == TypeAttributes.Public) ||((attr & TypeAttributes.VisibilityMask) == TypeAttributes.NotPublic))
                    throw new ArgumentException(Environment.GetResourceString("Argument_BadNestedTypeFlags"), nameof(attr));
            }

            int[] interfaceTokens = null;
            if (interfaces != null)
            {
                for(i = 0; i < interfaces.Length; i++)
                {
                    if (interfaces[i] == null)
                    {
                        // cannot contain null in the interface list
                        throw new ArgumentNullException(nameof(interfaces));
                    }
                }
                interfaceTokens = new int[interfaces.Length + 1];
                for(i = 0; i < interfaces.Length; i++)
                {
                    interfaceTokens[i] = m_module.GetTypeTokenInternal(interfaces[i]).Token;
                }
            }

            int iLast = fullname.LastIndexOf('.');
            if (iLast == -1 || iLast == 0)
            {
                // no name space
                m_strNameSpace = String.Empty;
                m_strName = fullname;
            }
            else
            {
                // split the name space
                m_strNameSpace = fullname.Substring(0, iLast);
                m_strName = fullname.Substring(iLast + 1);
            }

            VerifyTypeAttributes(attr);

            m_iAttr = attr;

            SetParent(parent);

            m_listMethods = new List<MethodBuilder>();
            m_lastTokenizedMethod = -1;

            SetInterfaces(interfaces);

            int tkParent = 0;
            if (m_typeParent != null)
                tkParent = m_module.GetTypeTokenInternal(m_typeParent).Token;

            int tkEnclosingType = 0;
            if (enclosingType != null)
            {
                tkEnclosingType = enclosingType.m_tdType.Token;
            }

            m_tdType = new TypeToken(DefineType(m_module.GetNativeHandle(),
                fullname, tkParent, m_iAttr, tkEnclosingType, interfaceTokens));

            m_iPackingSize = iPackingSize;
            m_iTypeSize = iTypeSize;
            if ((m_iPackingSize != 0) ||(m_iTypeSize != 0))
                SetClassLayout(GetModuleBuilder().GetNativeHandle(), m_tdType.Token, m_iPackingSize, m_iTypeSize);

            m_module.AddType(FullName, this);
        }