Esempio n. 1
0
        public ConverterAssemblyInfo(ConverterInfo info, Assembly assembly, TypeLib typeLib)
        {
            m_assembly = assembly;
            m_typeLib  = typeLib;
            m_info     = info;

            m_classInterfaceMap = new ClassInterfaceMap(m_typeLib);

            // Try GUID_ManagedName
            m_tlbNamespace = m_info.GetCustomNamespaceForTypeLib(typeLib);
            if (m_tlbNamespace == null)
            {
                // Try to use the namespace of the first type
                Type[] types = assembly.GetTypes();
                if (types.Length > 0)
                {
                    m_tlbNamespace = types[0].Namespace;
                }
            }

            // Otherwise use the type library name
            if (m_tlbNamespace == null)
            {
                m_tlbNamespace = m_typeLib.GetDocumentation();
            }
        }
Esempio n. 2
0
        public ConvEnumExternal(ConverterInfo info, TypeInfo typeInfo, Type managedType)
        {
            m_typeInfo    = typeInfo;
            m_managedType = managedType;

            info.AddToSymbolTable(typeInfo, ConvType.Enum, this);
            info.RegisterType(managedType, this);
        }
Esempio n. 3
0
        public ConvCoClassExternal(ConverterInfo info, TypeInfo typeInfo, Type managedType, ConverterAssemblyInfo converterAssemblyInfo)
        {
            m_typeInfo    = typeInfo;
            m_managedType = managedType;

            info.RegisterType(managedType, this);

            TypeInfo defaultTypeInfo = ConvCommon.GetDefaultInterface(ConvCommon.GetAlias(typeInfo));

            if (defaultTypeInfo != null)
            {
                m_defaultInterface = info.GetTypeRef(ConvType.Interface, defaultTypeInfo) as IConvInterface;
            }
        }
Esempio n. 4
0
        public ConvClassInterfaceLocal(
            ConverterInfo info,
            TypeInfo coclassTypeInfo,
            TypeInfo defaultInterfaceTypeInfo,
            TypeInfo defaultSourceInterfaceTypeInfo,
            bool isExclusive)
        {
            m_info                           = info;
            m_coclassTypeInfo                = coclassTypeInfo;
            m_defaultInterfaceTypeInfo       = defaultInterfaceTypeInfo;
            m_defaultSourceInterfaceTypeInfo = defaultSourceInterfaceTypeInfo;
            m_isExclusive                    = isExclusive;

            DefineType(info, m_coclassTypeInfo, false);
        }
Esempio n. 5
0
        public ConvClassInterfaceExternal(ConverterInfo info, TypeInfo typeInfo, Type managedType, ConverterAssemblyInfo converterAssemblyInfo)
        {
            m_typeInfo    = typeInfo;
            m_managedType = managedType;

            info.RegisterType(managedType, this);

            //
            // Associate the default interface with the class interface
            //
            TypeInfo defaultInterfaceTypeInfo;

            if (converterAssemblyInfo.ClassInterfaceMap.GetExclusiveDefaultInterfaceForCoclass(typeInfo, out defaultInterfaceTypeInfo))
            {
                IConvInterface convInterface = info.GetTypeRef(ConvType.Interface, defaultInterfaceTypeInfo) as IConvInterface;
                convInterface.AssociateWithExclusiveClassInterface(this);
            }
        }
Esempio n. 6
0
        private void Init(ConverterInfo info, TypeBuilder typeBuilder, bool emitDispId, TypeInfo type, TypeAttr attr, bool bCoClass, bool bSource, TypeInfo implementingInterface)
        {
            m_typeStack = new Stack <TypeInfo>();

            m_attrStack = new Stack <TypeAttr>();
            PushType(type, attr);

            m_info                         = info;
            m_typeBuilder                  = typeBuilder;
            m_emitDispId                   = emitDispId;
            m_bCoClass                     = bCoClass;
            m_propertyInfo                 = new PropertyInfo(this);
            m_bSource                      = bSource;
            IsConversionLoss               = false;
            IsDefaultInterface             = false;
            m_currentSlot                  = 0;
            m_currentImplementingInterface = implementingInterface;
        }
Esempio n. 7
0
        public TypeConverter(ConverterInfo info, TypeInfo type, TypeDesc desc, ParamDesc paramDesc, bool convertingNewEnumMember, ConversionType conversionType)
        {
            m_info           = info;
            m_typeInfo       = type;
            m_typeDesc       = desc;
            m_paramDesc      = paramDesc;
            m_conversionType = conversionType;

            m_attribute               = null;
            m_conversionLoss          = false;
            m_convertedType           = null;
            m_nativeIndirections      = 0;
            m_convertingNewEnumMember = convertingNewEnumMember;

            ResetUnmanagedType();

            // Do the conversion
            _Convert();
        }
Esempio n. 8
0
        protected void DefineType(ConverterInfo info, TypeInfo typeInfo, bool dealWithAlias)
        {
            m_info     = info;
            m_typeInfo = typeInfo;

            if (dealWithAlias)
            {
                m_nonAliasedTypeInfo = ConvCommon.GetAlias(typeInfo);
            }
            else
            {
                m_nonAliasedTypeInfo = typeInfo;
            }

            try
            {
                OnDefineType();

                //
                // Emit SuppressUnmanagedCodeSecurityAttribute for /unsafe switch
                //
                if ((m_info.Settings.m_flags & TypeLibImporterFlags.UnsafeInterfaces) != 0)
                {
                    if (ConvType != ConvType.ClassInterface && ConvType != ConvType.EventInterface)
                    {
                        m_typeBuilder.SetCustomAttribute(CustomAttributeHelper.GetBuilderForSuppressUnmanagedCodeSecurity());
                    }
                }
            }
            catch (ReflectionTypeLoadException)
            {
                throw; // Fatal failure. Throw
            }
            catch (TlbImpResolveRefFailWrapperException)
            {
                throw; // Fatal failure. Throw
            }
            catch (TlbImpGeneralException)
            {
                throw; // Fatal failure. Throw
            }
            catch (Exception)
            {
                string name = String.Empty;
                if (m_typeInfo != null)
                {
                    try
                    {
                        name = m_typeInfo.GetDocumentation();
                    }
                    catch (Exception)
                    {
                    }
                }

                if (name != String.Empty)
                {
                    string msg = Resource.FormatString("Wrn_InvalidTypeInfo", name);
                    m_info.ReportEvent(WarningCode.Wrn_InvalidTypeInfo, msg);
                }
                else
                {
                    string msg = Resource.FormatString("Wrn_InvalidTypeInfo_Unnamed");
                    m_info.ReportEvent(WarningCode.Wrn_InvalidTypeInfo_Unnamed, msg);
                }

                // When failure, try to create the type anyway
                if (m_typeBuilder != null)
                {
                    m_type = m_typeBuilder.CreateType();
                }
            }
        }
Esempio n. 9
0
        public AssemblyBuilder DoProcess(
            Object typeLib,
            string asmFilename,
            TypeLibImporterFlags flags,
            ITypeLibImporterNotifySink notifySink,
            byte[] publicKey,
            StrongNameKeyPair keyPair,
            string asmNamespace,
            Version asmVersion,
            bool isVersion2,
            bool isPreserveSig,
            bool isRemoveEnumPrefix)
        {
            m_resolver = notifySink;

            TypeLib tlb = new TypeLib((ITypeLib)typeLib);

            if (asmNamespace == null)
            {
                asmNamespace = tlb.GetDocumentation();

                string fileName = System.IO.Path.GetFileNameWithoutExtension(asmFilename);
                if (fileName != asmNamespace)
                {
                    asmNamespace = fileName;
                }

                //
                // Support for GUID_ManagedName (for namespace)
                //
                string customManagedNamespace = tlb.GetCustData(CustomAttributeGuids.GUID_ManagedName) as string;
                if (customManagedNamespace != null)
                {
                    customManagedNamespace = customManagedNamespace.Trim();
                    if (customManagedNamespace.ToUpper().EndsWith(".DLL"))
                    {
                        customManagedNamespace = customManagedNamespace.Substring(0, customManagedNamespace.Length - 4);
                    }
                    else if (customManagedNamespace.ToUpper().EndsWith(".EXE"))
                    {
                        customManagedNamespace = customManagedNamespace.Substring(0, customManagedNamespace.Length - 4);
                    }

                    asmNamespace = customManagedNamespace;
                }
            }

            //
            // Check for GUID_ExportedFromComPlus
            //
            object value = tlb.GetCustData(CustomAttributeGuids.GUID_ExportedFromComPlus);

            if (value != null)
            {
                // Make this a critical failure, instead of returning null which will be ignored.
                throw new TlbImpGeneralException(Resource.FormatString("Err_CircularImport", asmNamespace), ErrorCode.Err_CircularImport);
            }

            string strModuleName = asmFilename;

            if (asmFilename.Contains("\\"))
            {
                int nIndex;
                for (nIndex = strModuleName.Length; strModuleName[nIndex - 1] != '\\'; --nIndex)
                {
                    ;
                }
                strModuleName = strModuleName.Substring(nIndex);
            }

            // If the version information was not specified, then retrieve it from the typelib.
            if (asmVersion == null)
            {
                using (TypeLibAttr attr = tlb.GetLibAttr())
                {
                    asmVersion = new Version(attr.wMajorVerNum, attr.wMinorVerNum, 0, 0);
                }
            }

            // Assembly name should not have .DLL
            // while module name must contain the .DLL
            string strAsmName = String.Copy(strModuleName);

            if (strAsmName.EndsWith(".DLL", StringComparison.InvariantCultureIgnoreCase))
            {
                strAsmName = strAsmName.Substring(0, strAsmName.Length - 4);
            }

            AssemblyName assemblyName = new AssemblyName();

            assemblyName.Name = strAsmName;
            assemblyName.SetPublicKey(publicKey);
            assemblyName.Version = asmVersion;
            assemblyName.KeyPair = keyPair;

            m_assemblyBuilder = CreateAssemblyBuilder(assemblyName, tlb, flags);

            m_moduleBuilder = CreateModuleBuilder(m_assemblyBuilder, strModuleName);

            // Add a listener for the reflection load only resolve events.
            AppDomain           currentDomain     = Thread.GetDomain();
            ResolveEventHandler asmResolveHandler = new ResolveEventHandler(ReflectionOnlyResolveAsmEvent);

            currentDomain.ReflectionOnlyAssemblyResolve += asmResolveHandler;

            ConverterSettings settings;

            settings.m_isGenerateClassInterfaces = true;
            settings.m_namespace          = asmNamespace;
            settings.m_flags              = flags;
            settings.m_isVersion2         = isVersion2;
            settings.m_isPreserveSig      = isPreserveSig;
            settings.m_isRemoveEnumPrefix = isRemoveEnumPrefix;

            m_converterInfo = new ConverterInfo(m_moduleBuilder, tlb, m_resolver, settings);

            //
            // Generate class interfaces
            // NOTE:
            // We have to create class interface ahead of time because of the need to convert default interfaces to
            // class interfafces. However, this creates another problem that the event interface is always named first
            // before the other interfaces, because we need to create the type builder for the event interface first
            // so that we can create a class interface that implement it. But in the previous version of TlbImp,
            // it doesn't have to do that because it can directly create a typeref with the class interface name,
            // without actually creating anything like the TypeBuilder. The result is that the name would be different
            // with interop assemblies generated by old tlbimp in this case.
            // Given the nature of reflection API, this cannot be easily workarounded unless we switch to metadata APIs.
            // I believe this is acceptable because this only happens when:
            // 1. People decide to migrate newer .NET framework
            // 2. The event interface name conflicts with a normal interface
            //
            // In this case the problem can be easily fixed with a global refactoring, so I wouldn't worry about that
            //
            if (m_converterInfo.GenerateClassInterfaces)
            {
                CreateClassInterfaces();
            }

            //
            // Generate the remaining types except coclass
            // Because during creating coclass, we require every type, including all the referenced type to be created
            // This is a restriction of reflection API that when you override a method in parent interface, the method info
            // is needed so the type must be already created and loaded
            //
            List <TypeInfo> coclassList = new List <TypeInfo>();
            int             nCount      = tlb.GetTypeInfoCount();

            for (int n = 0; n < nCount; ++n)
            {
                TypeInfo type = null;
                try
                {
                    type = tlb.GetTypeInfo(n);
                    string strType = type.GetDocumentation();

                    TypeInfo typeToProcess;
                    TypeAttr attrToProcess;

                    using (TypeAttr attr = type.GetTypeAttr())
                    {
                        TYPEKIND kind = attr.typekind;
                        if (kind == TYPEKIND.TKIND_ALIAS)
                        {
                            ConvCommon.ResolveAlias(type, attr.tdescAlias, out typeToProcess, out attrToProcess);
                            if (attrToProcess.typekind == TYPEKIND.TKIND_ALIAS)
                            {
                                continue;
                            }
                            else
                            {
                                // We need to duplicate the definition of the user defined type in the name of the alias
                                kind          = attrToProcess.typekind;
                                typeToProcess = type;
                                attrToProcess = attr;
                            }
                        }
                        else
                        {
                            typeToProcess = type;
                            attrToProcess = attr;
                        }

                        switch (kind)
                        {
                        // Process coclass later because of reflection API requirements
                        case TYPEKIND.TKIND_COCLASS:
                            coclassList.Add(typeToProcess);
                            break;

                        case TYPEKIND.TKIND_ENUM:
                            m_converterInfo.GetEnum(typeToProcess, attrToProcess);
                            break;

                        case TYPEKIND.TKIND_DISPATCH:
                        case TYPEKIND.TKIND_INTERFACE:
                            m_converterInfo.GetInterface(typeToProcess, attrToProcess);
                            break;

                        case TYPEKIND.TKIND_MODULE:
                            m_converterInfo.GetModule(typeToProcess, attrToProcess);
                            break;

                        case TYPEKIND.TKIND_RECORD:
                            m_converterInfo.GetStruct(typeToProcess, attrToProcess);
                            break;

                        case TYPEKIND.TKIND_UNION:
                            m_converterInfo.GetUnion(typeToProcess, attrToProcess);
                            break;
                        }

                        m_converterInfo.ReportEvent(
                            MessageCode.Msg_TypeInfoImported,
                            Resource.FormatString("Msg_TypeInfoImported", typeToProcess.GetDocumentation()));
                    }
                }
                catch (ReflectionTypeLoadException)
                {
                    throw; // Fatal failure. Throw
                }
                catch (TlbImpResolveRefFailWrapperException)
                {
                    throw; // Fatal failure. Throw
                }
                catch (TlbImpGeneralException)
                {
                    throw; // Fatal failure. Throw
                }
                catch (TypeLoadException)
                {
                    throw; // TypeLoadException is critical. Throw.
                }
                catch (Exception)
                {
                }
            }

            // Process coclass after processing all the other types
            foreach (TypeInfo type in coclassList)
            {
                using (TypeAttr attr = type.GetTypeAttr())
                {
                    try
                    {
                        m_converterInfo.GetCoClass(type, attr);
                    }
                    catch (ReflectionTypeLoadException)
                    {
                        throw; // Fatal failure. Throw
                    }
                    catch (TlbImpResolveRefFailWrapperException)
                    {
                        throw; // Fatal failure. Throw
                    }
                    catch (TlbImpGeneralException)
                    {
                        throw; // Fatal failure. Throw
                    }
                    catch (TypeLoadException)
                    {
                        throw; // TypeLoadException is critical. Throw.
                    }
                    catch (Exception)
                    {
                    }
                }
            }

            //
            // Build an array of EventItfInfo & generate event provider / event sink helpers
            //

            Event.TCEAdapterGenerator eventAdapterGenerator = new Event.TCEAdapterGenerator();
            List <Event.EventItfInfo> eventItfList          = new List <Event.EventItfInfo>();

            foreach (IConvBase symbol in m_converterInfo.GetAllConvBase)
            {
                IConvInterface convInterface = symbol as IConvInterface;
                if (convInterface != null)
                {
                    if (convInterface.EventInterface != null)
                    {
                        Debug.Assert(convInterface.EventInterface is ConvEventInterfaceLocal);
                        ConvEventInterfaceLocal local = convInterface.EventInterface as ConvEventInterfaceLocal;

                        Type eventInterfaceType = convInterface.EventInterface.ManagedType;

                        // Build EventItfInfo and add to the list
                        Type               sourceInterfaceType = convInterface.ManagedType;
                        string             sourceInterfaceName = sourceInterfaceType.FullName;
                        Event.EventItfInfo eventItfInfo        = new Event.EventItfInfo(
                            eventInterfaceType.FullName,
                            sourceInterfaceName,
                            local.EventProviderName,
                            eventInterfaceType,
                            convInterface.ManagedType);
                        eventItfList.Add(eventItfInfo);
                    }
                }
            }

            eventAdapterGenerator.Process(m_moduleBuilder, eventItfList);

            return(m_assemblyBuilder);
        }
Esempio n. 10
0
        /// <summary>
        /// Create local class interfaces
        /// </summary>
        public void CreateLocalClassInterfaces(ConverterInfo converterInfo)
        {
            // Walk the candidate list and generate class interfaces
            // Note: We need to create the class interface in two phases because
            // during creation of class interface, we'll need to create interface & event interface, which
            // could have parameters resolve back to coclass which requires certain class interface
            // So split into two stages so that when we are doing creation all necessary information are inplace
            List <ConvClassInterfaceLocal> convClassInterfaceLocals = new List <ConvClassInterfaceLocal>();

            //
            // Phase 1 : Create ConvClassInterfaceLocal instances and associate interface with class interfaces
            //
            foreach (DefaultInterfaceInfo info in m_defaultInterfaceInfoList)
            {
                try
                {
                    ConvClassInterfaceLocal local = new ConvClassInterfaceLocal(
                        converterInfo,
                        info.coclass,
                        info.defaultInterface,
                        info.defaultSourceInterface,
                        info.isExclusive);
                    convClassInterfaceLocals.Add(local);
                }
                catch (ReflectionTypeLoadException)
                {
                    throw; // Fatal failure. Throw
                }
                catch (TlbImpResolveRefFailWrapperException)
                {
                    throw; // Fatal failure. Throw
                }
                catch (TlbImpGeneralException)
                {
                    throw; // Fatal failure. Throw
                }
                catch (TypeLoadException)
                {
                    throw; // TypeLoadException is critical. Throw.
                }
                catch (Exception)
                {
                }
            }

            //
            // Phase 2 : Create the class interface
            //
            foreach (ConvClassInterfaceLocal local in convClassInterfaceLocals)
            {
                try
                {
                    local.Create();
                }
                catch (ReflectionTypeLoadException)
                {
                    throw; // Fatal failure. Throw
                }
                catch (TlbImpResolveRefFailWrapperException)
                {
                    throw; // Fatal failure. Throw
                }
                catch (TlbImpGeneralException)
                {
                    throw; // Fatal failure. Throw
                }
                catch (TypeLoadException)
                {
                    throw; // TypeLoadException is critical. Throw.
                }
                catch (Exception)
                {
                }
            }
        }
Esempio n. 11
0
        public ConvEventInterfaceLocal(IConvInterface convInterface, ConverterInfo info)
        {
            m_convInterface = convInterface;

            DefineType(info, convInterface.RefTypeInfo, false);
        }
Esempio n. 12
0
 public InterfaceInfo(ConverterInfo info, TypeBuilder typeBuilder, bool supportsDispatch, TypeInfo type, TypeAttr attr, bool bCoClass, bool bSource, TypeInfo implementingInterface)
 {
     Init(info, typeBuilder, supportsDispatch, type, attr, bCoClass, bSource, implementingInterface);
 }
Esempio n. 13
0
 public InterfaceInfo(ConverterInfo info, TypeBuilder typeBuilder, bool supportsDispatch, TypeInfo type, TypeAttr attr, bool bCoClass)
 {
     Init(info, typeBuilder, supportsDispatch, type, attr, bCoClass, false, null);
 }
Esempio n. 14
0
 public ConvUnionLocal(ConverterInfo info, TypeInfo type)
 {
     DefineType(info, type, true);
 }
Esempio n. 15
0
 public ConvCoClassLocal(ConverterInfo info, TypeInfo type)
 {
     DefineType(info, type, true);
 }
Esempio n. 16
0
 public ConvModuleLocal(ConverterInfo info, TypeInfo type)
 {
     DefineType(info, type, true);
 }
Esempio n. 17
0
        protected void DefineType(ConverterInfo info, TypeInfo typeInfo, bool dealWithAlias)
        {
            m_info     = info;
            m_typeInfo = typeInfo;

            if (dealWithAlias)
            {
                m_nonAliasedTypeInfo = ConvCommon.GetAlias(typeInfo);
            }
            else
            {
                m_nonAliasedTypeInfo = typeInfo;
            }

            try
            {
                OnDefineType();

                //
                // Emit SuppressUnmanagedCodeSecurityAttribute for /unsafe switch
                //
                if ((m_info.Settings.m_flags & TypeLibImporterFlags.UnsafeInterfaces) != 0)
                {
                    if (ConvType != ConvType.ClassInterface && ConvType != ConvType.EventInterface)
                    {
                        m_typeBuilder.SetCustomAttribute(CustomAttributeHelper.GetBuilderForSuppressUnmanagedCodeSecurity());
                    }
                }

                // Rule Engine AddAttributeAction
                if (m_info.Settings.m_ruleSet != null)
                {
                    ICategory           category = TypeCategory.GetInstance();
                    TypeInfoMatchTarget target   = null;
                    using (TypeAttr attr = m_typeInfo.GetTypeAttr())
                    {
                        TypeLibTypes.Interop.TYPEKIND kind = attr.typekind;
                        target = new TypeInfoMatchTarget(m_typeInfo.GetContainingTypeLib(), m_typeInfo, kind);
                    }
                    AbstractActionManager actionManager     = RuleEngine.GetActionManager();
                    List <Rule>           addAttributeRules = m_info.Settings.m_ruleSet.GetRule(
                        category, AddAttributeActionDef.GetInstance(), target);
                    foreach (Rule rule in addAttributeRules)
                    {
                        AddAttributeAction addAttributeAction = rule.Action as AddAttributeAction;
                        ConstructorInfo    attributeCtor;
                        byte[]             blob;
                        bool success = true;
                        if (addAttributeAction.GetCustomAttribute(out attributeCtor, out blob))
                        {
                            try
                            {
                                m_typeBuilder.SetCustomAttribute(attributeCtor, blob);
                            }
                            catch (Exception)
                            {
                                success = false;
                            }
                        }
                        else
                        {
                            success = false;
                        }
                        if (!success)
                        {
                            string name = m_typeInfo.GetDocumentation();
                            string msg  = Resource.FormatString("Wrn_AddCustomAttributeFailed",
                                                                addAttributeAction.TypeName, name);
                            m_info.ReportEvent(WarningCode.Wrn_AddCustomAttributeFailed, msg);
                        }
                    }
                }
            }
            catch (ReflectionTypeLoadException)
            {
                throw; // Fatal failure. Throw
            }
            catch (TlbImpResolveRefFailWrapperException)
            {
                throw; // Fatal failure. Throw
            }
            catch (TlbImpGeneralException)
            {
                throw; // Fatal failure. Throw
            }
            catch (Exception)
            {
                string name = String.Empty;
                if (m_typeInfo != null)
                {
                    try
                    {
                        name = m_typeInfo.GetDocumentation();
                    }
                    catch (Exception)
                    {
                    }
                }

                if (name != String.Empty)
                {
                    string msg = Resource.FormatString("Wrn_InvalidTypeInfo", name);
                    m_info.ReportEvent(WarningCode.Wrn_InvalidTypeInfo, msg);
                }
                else
                {
                    string msg = Resource.FormatString("Wrn_InvalidTypeInfo_Unnamed");
                    m_info.ReportEvent(WarningCode.Wrn_InvalidTypeInfo_Unnamed, msg);
                }

                // When failure, try to create the type anyway
                if (m_typeBuilder != null)
                {
                    m_type = m_typeBuilder.CreateType();
                }
            }
        }