public AssemblyBuilder CreateAssemblyBuilder(AssemblyName name, TypeLib tlb, TypeLibImporterFlags flags) { using (TypeLibAttr attr = tlb.GetLibAttr()) { // New assembly as well as loaded assembly should be all in a ReflectionOnly context as we don't need to run the code AssemblyBuilder assemblyBuilder = Thread.GetDomain().DefineDynamicAssembly(name, AssemblyBuilderAccess.ReflectionOnly); // Handle the type library name assemblyBuilder.SetCustomAttribute(CustomAttributeHelper.GetBuilderForImportedFromTypeLib(tlb.GetDocumentation())); // Handle the type library version assemblyBuilder.SetCustomAttribute(CustomAttributeHelper.GetBuilderForTypeLibVersion(attr.wMajorVerNum, attr.wMinorVerNum)); // Handle the LIBID assemblyBuilder.SetCustomAttribute(CustomAttributeHelper.GetBuilderForGuid(attr.guid)); // If we are generating a PIA, then set the PIA custom attribute. if ((flags & TypeLibImporterFlags.PrimaryInteropAssembly) != 0) { assemblyBuilder.SetCustomAttribute(CustomAttributeHelper.GetBuilderForPrimaryInteropAssembly(attr.wMajorVerNum, attr.wMinorVerNum)); } return(assemblyBuilder); } }
public System.Reflection.Emit.AssemblyBuilder ConvertTypeLibToAssembly (object! typeLib, string! asmFileName, TypeLibImporterFlags flags, ITypeLibImporterNotifySink! notifySink, Byte[]! publicKey, System.Reflection.StrongNameKeyPair! keyPair, string asmNamespace, Version asmVersion) { CodeContract.Requires(typeLib != null); CodeContract.Requires(asmFileName != null); CodeContract.Requires(notifySink != null); CodeContract.Requires(asmFileName.Length <= 260); return default(System.Reflection.Emit.AssemblyBuilder); }
public AssemblyBuilder ConvertTypeLibToAssembly (Object typeLib, String asmFileName, TypeLibImporterFlags flags, ITypeLibImporterNotifySink notifySink, byte[] publicKey, StrongNameKeyPair keyPair, String asmNamespace, Version asmVersion) { throw new NotImplementedException(); }
public int Run(String strTypeLibName, String strAssemblyName, String strAssemblyNamespace, String strOutputDir, byte[] aPublicKey, StrongNameKeyPair sKeyPair, String strAssemblyRefList, String strTypeLibRefList, Version AssemblyVersion, TypeLibImporterFlags flags, bool bNoLogo, bool bSilentMode, System.Collections.Generic.List <int> silenceList, bool bVerboseMode, bool bStrictRef, bool bStrictRefNoPia, bool bSearchPathSucceeded, String strProduct, String strProductVersion, String strCompany, String strCopyright, String strTrademark, bool isVersion2, bool isPreserveSig, String ruleSetFileName) { TlbImpOptions options = new TlbImpOptions(); options.m_strTypeLibName = strTypeLibName; options.m_strAssemblyName = strAssemblyName; options.m_strAssemblyNamespace = strAssemblyNamespace; options.m_strOutputDir = strOutputDir; options.m_aPublicKey = aPublicKey; options.m_sKeyPair = sKeyPair; options.m_strAssemblyRefList = strAssemblyRefList; options.m_strTypeLibRefList = strTypeLibRefList; options.m_AssemblyVersion = AssemblyVersion; options.m_flags = flags; options.m_bNoLogo = bNoLogo; options.m_bSilentMode = bSilentMode; options.m_silenceList = silenceList; options.m_bVerboseMode = bVerboseMode; options.m_bStrictRef = bStrictRef; options.m_bStrictRefNoPia = bStrictRefNoPia; options.m_bSearchPathSucceeded = bSearchPathSucceeded; options.m_strProduct = strProduct; options.m_strProductVersion = strProductVersion; options.m_strCompany = strCompany; options.m_strCopyright = strCopyright; options.m_strTrademark = strTrademark; options.m_isVersion2 = isVersion2; options.m_isPreserveSig = isPreserveSig; options.m_ruleSetFileName = ruleSetFileName; return(TlbImpCode.Run(options)); }
public AssemblyBuilder ConvertTypeLibToAssembly([MarshalAs(UnmanagedType.Interface)] object typeLib, string asmFileName, TypeLibImporterFlags flags, ITypeLibImporterNotifySink notifySink, byte[] publicKey, StrongNameKeyPair keyPair, string asmNamespace, Version asmVersion) { if (typeLib == null) { throw new ArgumentNullException("typeLib"); } if (asmFileName == null) { throw new ArgumentNullException("asmFileName"); } if (notifySink == null) { throw new ArgumentNullException("notifySink"); } if (string.Empty.Equals(asmFileName)) { throw new ArgumentException(Environment.GetResourceString("Arg_InvalidFileName"), "asmFileName"); } if (asmFileName.Length > 260) { throw new ArgumentException(Environment.GetResourceString("IO.PathTooLong"), asmFileName); } if ((((flags & TypeLibImporterFlags.PrimaryInteropAssembly) != TypeLibImporterFlags.None) && (publicKey == null)) && (keyPair == null)) { throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_PIAMustBeStrongNamed")); } ArrayList eventItfInfoList = null; AssemblyNameFlags none = AssemblyNameFlags.None; AssemblyName asmName = GetAssemblyNameFromTypelib(typeLib, asmFileName, publicKey, keyPair, asmVersion, none); AssemblyBuilder asmBldr = CreateAssemblyForTypeLib(typeLib, asmFileName, asmName, (flags & TypeLibImporterFlags.PrimaryInteropAssembly) != TypeLibImporterFlags.None, (flags & TypeLibImporterFlags.ReflectionOnlyLoading) != TypeLibImporterFlags.None, (flags & TypeLibImporterFlags.NoDefineVersionResource) != TypeLibImporterFlags.None); string fileName = Path.GetFileName(asmFileName); ModuleBuilder mod = asmBldr.DefineDynamicModule(fileName, fileName); if (asmNamespace == null) { asmNamespace = asmName.Name; } TypeResolveHandler handler = new TypeResolveHandler(mod, notifySink); AppDomain domain = Thread.GetDomain(); ResolveEventHandler handler2 = new ResolveEventHandler(handler.ResolveEvent); ResolveEventHandler handler3 = new ResolveEventHandler(handler.ResolveAsmEvent); ResolveEventHandler handler4 = new ResolveEventHandler(handler.ResolveROAsmEvent); domain.TypeResolve += handler2; domain.AssemblyResolve += handler3; domain.ReflectionOnlyAssemblyResolve += handler4; nConvertTypeLibToMetadata(typeLib, asmBldr.InternalAssembly, mod.InternalModule, asmNamespace, flags, handler, out eventItfInfoList); UpdateComTypesInAssembly(asmBldr, mod); if (eventItfInfoList.Count > 0) { new TCEAdapterGenerator().Process(mod, eventItfInfoList); } domain.TypeResolve -= handler2; domain.AssemblyResolve -= handler3; domain.ReflectionOnlyAssemblyResolve -= handler4; return asmBldr; }
public int Run(String strTypeLibName, String strAssemblyName, String strAssemblyNamespace, String strOutputDir, byte[] aPublicKey, StrongNameKeyPair sKeyPair, String strAssemblyRefList, String strTypeLibRefList, Version AssemblyVersion, TypeLibImporterFlags flags, bool bNoLogo, bool bSilentMode, System.Collections.Generic.List<int> silenceList, bool bVerboseMode, bool bStrictRef, bool bStrictRefNoPia, bool bSearchPathSucceeded, String strProduct, String strProductVersion, String strCompany, String strCopyright, String strTrademark, bool isVersion2, bool isPreserveSig, String ruleSetFileName) { TlbImpOptions options = new TlbImpOptions(); options.m_strTypeLibName = strTypeLibName; options.m_strAssemblyName = strAssemblyName; options.m_strAssemblyNamespace = strAssemblyNamespace; options.m_strOutputDir = strOutputDir; options.m_aPublicKey = aPublicKey; options.m_sKeyPair = sKeyPair; options.m_strAssemblyRefList = strAssemblyRefList; options.m_strTypeLibRefList = strTypeLibRefList; options.m_AssemblyVersion = AssemblyVersion; options.m_flags = flags; options.m_bNoLogo = bNoLogo; options.m_bSilentMode = bSilentMode; options.m_silenceList = silenceList; options.m_bVerboseMode = bVerboseMode; options.m_bStrictRef = bStrictRef; options.m_bStrictRefNoPia = bStrictRefNoPia; options.m_bSearchPathSucceeded = bSearchPathSucceeded; options.m_strProduct = strProduct; options.m_strProductVersion = strProductVersion; options.m_strCompany = strCompany; options.m_strCopyright = strCopyright; options.m_strTrademark = strTrademark; options.m_isVersion2 = isVersion2; options.m_isPreserveSig = isPreserveSig; options.m_ruleSetFileName = ruleSetFileName; return TlbImpCode.Run(options); }
//************************************************************************** // Static importer function used by main and the callback. //************************************************************************** public static AssemblyBuilder DoImport(UCOMITypeLib TypeLib, String strAssemblyFileName, String strAssemblyNamespace, Version asmVersion, byte[] publicKey, StrongNameKeyPair keyPair, TypeLibImporterFlags flags) { // Detemine the assembly file name. String asmFileName = Path.GetFileName(strAssemblyFileName); // Add this typelib to list of importing typelibs. Guid guid = Marshal.GetTypeLibGuid(TypeLib); s_ImportingLibraries.Add(guid.ToString(), guid); // Convert the typelib. ImporterCallback callback = new ImporterCallback(); AssemblyBuilder AsmBldr = s_TypeLibConverter.ConvertTypeLibToAssembly(TypeLib, strAssemblyFileName, flags, callback, publicKey, keyPair, strAssemblyNamespace, asmVersion); // Remove this typelib from list of importing typelibs. s_ImportingLibraries.Remove(guid.ToString()); // Delete the output assembly. File.Delete(asmFileName); // Save the assembly to disk. AsmBldr.Save(asmFileName); return(AsmBldr); }
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); }
private static extern void nConvertTypeLibToMetadata(Object typeLib, AssemblyBuilder asmBldr, ModuleBuilder modBldr, String nameSpace, TypeLibImporterFlags flags, ITypeLibImporterNotifySink notifySink, out ArrayList eventItfInfoList);
internal bool GenerateWrapper(out ComReferenceWrapperInfo wrapperInfo) { wrapperInfo = null; string typeLibName = this.ReferenceInfo.typeLibName; string wrapperPath = base.GetWrapperPath(); StrongNameKeyPair keyPair = null; byte[] publicKey = null; StrongNameUtils.GetStrongNameKey(base.Log, base.KeyFile, base.KeyContainer, out keyPair, out publicKey); if (base.DelaySign) { keyPair = null; if (publicKey == null) { base.Log.LogErrorWithCodeFromResources(null, this.ReferenceInfo.SourceItemSpec, 0, 0, 0, 0, "StrongNameUtils.NoPublicKeySpecified", new object[0]); throw new StrongNameException(); } } else { publicKey = null; if (keyPair == null) { if ((base.KeyContainer != null) && (base.KeyContainer.Length > 0)) { base.Log.LogErrorWithCodeFromResources(null, this.ReferenceInfo.SourceItemSpec, 0, 0, 0, 0, "ResolveComReference.StrongNameUtils.NoKeyPairInContainer", new object[] { base.KeyContainer }); throw new StrongNameException(); } if ((base.KeyFile != null) && (base.KeyFile.Length > 0)) { base.Log.LogErrorWithCodeFromResources(null, this.ReferenceInfo.SourceItemSpec, 0, 0, 0, 0, "ResolveComReference.StrongNameUtils.NoKeyPairInFile", new object[] { base.KeyFile }); throw new StrongNameException(); } } } bool flag = true; if (!base.ExecuteAsTool) { TypeLibConverter converter = new TypeLibConverter(); AssemblyBuilder assemblyBuilder = null; try { TypeLibImporterFlags flags = TypeLibImporterFlags.TransformDispRetVals | TypeLibImporterFlags.SafeArrayAsSystemArray; if (this.noClassMembers) { flags |= TypeLibImporterFlags.PreventClassMembers; } string str4 = this.targetProcessorArchitecture; if (str4 != null) { if (!(str4 == "MSIL")) { if (str4 == "AMD64") { goto Label_0323; } if (str4 == "IA64") { goto Label_032F; } if (str4 == "x86") { goto Label_033B; } } else { flags |= TypeLibImporterFlags.ImportAsAgnostic; } } goto Label_0345; Label_0323: flags |= TypeLibImporterFlags.ImportAsX64; goto Label_0345; Label_032F: flags |= TypeLibImporterFlags.ImportAsItanium; goto Label_0345; Label_033B: flags |= TypeLibImporterFlags.ImportAsX86; Label_0345: assemblyBuilder = converter.ConvertTypeLibToAssembly(this.ReferenceInfo.typeLibPointer, wrapperPath, flags, this, publicKey, keyPair, typeLibName, null); } catch (COMException exception) { base.Log.LogWarningWithCodeFromResources("ResolveComReference.ErrorCreatingWrapperAssembly", new object[] { this.ItemName, exception.Message }); throw new ComReferenceResolutionException(exception); } if (!this.HasTemporaryWrapper) { this.WriteWrapperToDisk(assemblyBuilder, wrapperPath); } wrapperInfo = new ComReferenceWrapperInfo(); wrapperInfo.path = this.HasTemporaryWrapper ? null : wrapperPath; wrapperInfo.assembly = assemblyBuilder; return(flag); } ResolveComReference.TlbImp imp = new ResolveComReference.TlbImp { BuildEngine = base.BuildEngine, EnvironmentVariables = base.EnvironmentVariables, DelaySign = base.DelaySign, KeyContainer = base.KeyContainer, KeyFile = base.KeyFile, OutputAssembly = wrapperPath, ToolPath = base.ToolPath, TypeLibName = this.ReferenceInfo.typeLibPath, AssemblyNamespace = typeLibName, AssemblyVersion = null, PreventClassMembers = this.noClassMembers, SafeArrayAsSystemArray = true, Transform = ResolveComReference.TlbImpTransformFlags.TransformDispRetVals }; if (this.referenceFiles != null) { string fullPathToOutput = Path.GetFullPath(wrapperPath); imp.ReferenceFiles = (from rf in this.referenceFiles where string.Compare(fullPathToOutput, rf, StringComparison.OrdinalIgnoreCase) != 0 select rf).ToArray <string>(); } string targetProcessorArchitecture = this.targetProcessorArchitecture; if (targetProcessorArchitecture != null) { if (!(targetProcessorArchitecture == "MSIL")) { if (targetProcessorArchitecture == "AMD64") { imp.Machine = "X64"; } else if (targetProcessorArchitecture == "IA64") { imp.Machine = "Itanium"; } else if (targetProcessorArchitecture == "x86") { imp.Machine = "X86"; } else { imp.Machine = this.targetProcessorArchitecture; } } else { imp.Machine = "Agnostic"; } } flag = imp.Execute(); wrapperInfo = new ComReferenceWrapperInfo(); wrapperInfo.path = this.HasTemporaryWrapper ? null : wrapperPath; return(flag); }
//************************************************************************** // Static importer function used by main and the callback. //************************************************************************** public static AssemblyBuilder DoImport(System.Runtime.InteropServices.ComTypes.ITypeLib TypeLib, String strAssemblyFileName, String strAssemblyNamespace, Version asmVersion, byte[] publicKey, StrongNameKeyPair keyPair, String strProduct, String strProductVersion, String strCompany, String strCopyright, String strTrademark, TypeLibImporterFlags flags, bool isVersion2, bool isPreserveSig, String ruleSetFileName) { if (TypeLib == null) throw new ArgumentNullException(nameof(TypeLib)); // Detemine the assembly file name. String asmFileName = Path.GetFileName(strAssemblyFileName); // Add this typelib to list of importing typelibs. Guid guid = Marshal.GetTypeLibGuid(TypeLib); s_ImportingLibraries.Add(guid.ToString(), guid); // If the type library is 64-bit, make sure the user specified a platform type. IntPtr pTLibAttr = IntPtr.Zero; TypeLib.GetLibAttr(out pTLibAttr); _TYPELIBATTR TLibAttr = (_TYPELIBATTR)Marshal.PtrToStructure(pTLibAttr, typeof(_TYPELIBATTR)); TypeLib.ReleaseTLibAttr(pTLibAttr); // Validate the machine options if (!ValidateMachineType(flags, TLibAttr.syskind)) return null; // Convert the typelib. ImporterCallback callback = new ImporterCallback(); tlbimp2.Process process = new Process(); AssemblyBuilder AsmBldr = process.DoProcess( TypeLib, strAssemblyFileName, flags, callback, publicKey, keyPair, strAssemblyNamespace, asmVersion, isVersion2, isPreserveSig, ruleSetFileName); if (AsmBldr == null) return null; // Remove this typelib from list of importing typelibs. s_ImportingLibraries.Remove(guid.ToString()); // Delete the output assembly. File.Delete(asmFileName); AsmBldr.DefineVersionInfoResource(strProduct, strProductVersion, strCompany, strCopyright, strTrademark); if (IsImportingToX64(flags)) { AsmBldr.Save(asmFileName, PortableExecutableKinds.ILOnly | PortableExecutableKinds.PE32Plus, ImageFileMachine.AMD64); } else if (IsImportingToItanium(flags)) { AsmBldr.Save(asmFileName, PortableExecutableKinds.ILOnly | PortableExecutableKinds.PE32Plus, ImageFileMachine.IA64); } else if (IsImportingToX86(flags)) { AsmBldr.Save(asmFileName, PortableExecutableKinds.ILOnly | PortableExecutableKinds.Required32Bit, ImageFileMachine.I386); } else { // Default is agnostic AsmBldr.Save(asmFileName); } return AsmBldr; }
public virtual System.Reflection.Emit.AssemblyBuilder ConvertTypeLibToAssembly(object typeLib, string asmFileName, TypeLibImporterFlags flags, ITypeLibImporterNotifySink notifySink, byte[] publicKey, System.Reflection.StrongNameKeyPair keyPair, string asmNamespace, System.Version asmVersion) { }
private Assembly ConvertTypeLib(NativeMethods.ITypeLib typeLib, string assemblyPath, string assemblyFile, string assemblyNamespace, Version assemblyVersion, TypeLibImporterFlags flags, byte[] publicKey, StrongNameKeyPair keyPair) { try { this.RaiseMessage(string.Format("Converting '{0}'.", GetTypeLibName(typeLib))); TypeLibConverter converter = new TypeLibConverter(); AssemblyBuilder assemblyBuilder = converter.ConvertTypeLibToAssembly(typeLib, Path.Combine(assemblyPath, assemblyFile), flags, this, publicKey, keyPair, assemblyNamespace, assemblyVersion); this.RaiseMessage(string.Format("Saving '{0}'.", assemblyFile)); string currentDirectory = Environment.CurrentDirectory; Environment.CurrentDirectory = assemblyPath; assemblyBuilder.Save(assemblyFile); Environment.CurrentDirectory = currentDirectory; return(assemblyBuilder); } catch (COMException exception) { this.RaiseError(exception.Message); } return(null); }
public AssemblyBuilder DoProcess( Object typeLib, string asmFilename, TypeLibImporterFlags flags, ITypeLibImporterNotifySink notifySink, byte[] publicKey, StrongNameKeyPair keyPair, string asmNamespace, Version asmVersion, bool isVersion2, bool isPreserveSig, string ruleSetFileName) { m_resolver = notifySink; TypeLib tlb = new TypeLib((TypeLibTypes.Interop.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 = 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; RuleEngine.InitRuleEngine(new TlbImpActionManager(), new TlbImpCategoryManager(), new TlbImpConditionManager(), new TlbImpOperatorManager()); if (ruleSetFileName != null) { try { RuleFileParser parser = new RuleFileParser(ruleSetFileName); settings.m_ruleSet = parser.Parse(); } catch (Exception ex) { Output.WriteWarning(Resource.FormatString("Wrn_LoadRuleFileFailed", ruleSetFileName, ex.Message), WarningCode.Wrn_LoadRuleFileFailed); settings.m_ruleSet = null; } } else { settings.m_ruleSet = null; } 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 // var coclassList = new List<TypeInfo>(); int nCount = tlb.GetTypeInfoCount(); for (int n = 0; n < nCount; ++n) { try { TypeInfo type = tlb.GetTypeInfo(n); string strType = type.GetDocumentation(); using (TypeAttr attr = type.GetTypeAttr()) { TypeLibTypes.Interop.TYPEKIND kind = attr.typekind; TypeInfo typeToProcess; TypeAttr attrToProcess; if (kind == TypeLibTypes.Interop.TYPEKIND.TKIND_ALIAS) { ConvCommon.ResolveAlias(type, attr.tdescAlias, out typeToProcess, out attrToProcess); if (attrToProcess.typekind == TypeLibTypes.Interop.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 TypeLibTypes.Interop.TYPEKIND.TKIND_COCLASS: coclassList.Add(typeToProcess); break; case TypeLibTypes.Interop.TYPEKIND.TKIND_ENUM: m_converterInfo.GetEnum(typeToProcess, attrToProcess); break; case TypeLibTypes.Interop.TYPEKIND.TKIND_DISPATCH: case TypeLibTypes.Interop.TYPEKIND.TKIND_INTERFACE: m_converterInfo.GetInterface(typeToProcess, attrToProcess); break; case TypeLibTypes.Interop.TYPEKIND.TKIND_MODULE: m_converterInfo.GetModule(typeToProcess, attrToProcess); break; case TypeLibTypes.Interop.TYPEKIND.TKIND_RECORD: m_converterInfo.GetStruct(typeToProcess, attrToProcess); break; case TypeLibTypes.Interop.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 // var eventAdapterGenerator = new Event.TCEAdapterGenerator(); var eventItfList = new List<Event.EventItfInfo>(); foreach (IConvBase symbol in m_converterInfo.GetAllConvBase) { var convInterface = symbol as IConvInterface; if (convInterface != null) { if (convInterface.EventInterface != null) { Debug.Assert(convInterface.EventInterface is ConvEventInterfaceLocal); var 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; }
public AssemblyBuilder ConvertTypeLibToAssembly([MarshalAs(UnmanagedType.Interface)] Object typeLib, String asmFileName, TypeLibImporterFlags flags, ITypeLibImporterNotifySink notifySink, byte[] publicKey, StrongNameKeyPair keyPair, String asmNamespace, Version asmVersion) { // Validate the arguments. if (typeLib == null) { throw new ArgumentNullException("typeLib"); } if (asmFileName == null) { throw new ArgumentNullException("asmFileName"); } if (notifySink == null) { throw new ArgumentNullException("notifySink"); } if (String.Empty.Equals(asmFileName)) { throw new ArgumentException(Environment.GetResourceString("Arg_InvalidFileName"), "asmFileName"); } if (asmFileName.Length > Path.MAX_PATH) { throw new ArgumentException(Environment.GetResourceString("IO.PathTooLong"), asmFileName); } if ((flags & TypeLibImporterFlags.PrimaryInteropAssembly) != 0 && publicKey == null && keyPair == null) { throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_PIAMustBeStrongNamed")); } Contract.EndContractBlock(); ArrayList eventItfInfoList = null; // Determine the AssemblyNameFlags AssemblyNameFlags asmNameFlags = AssemblyNameFlags.None; // Retrieve the assembly name from the typelib. AssemblyName asmName = GetAssemblyNameFromTypelib(typeLib, asmFileName, publicKey, keyPair, asmVersion, asmNameFlags); // Create the dynamic assembly that will contain the converted typelib types. AssemblyBuilder asmBldr = CreateAssemblyForTypeLib(typeLib, asmFileName, asmName, (flags & TypeLibImporterFlags.PrimaryInteropAssembly) != 0, (flags & TypeLibImporterFlags.ReflectionOnlyLoading) != 0, (flags & TypeLibImporterFlags.NoDefineVersionResource) != 0); // Define a dynamic module that will contain the contain the imported types. String strNonQualifiedAsmFileName = Path.GetFileName(asmFileName); ModuleBuilder modBldr = asmBldr.DefineDynamicModule(strNonQualifiedAsmFileName, strNonQualifiedAsmFileName); // If the namespace hasn't been specified, then use the assembly name. if (asmNamespace == null) { asmNamespace = asmName.Name; } // Create a type resolve handler that will also intercept resolve ref messages // on the sink interface to build up a list of referenced assemblies. TypeResolveHandler typeResolveHandler = new TypeResolveHandler(modBldr, notifySink); // Add a listener for the type resolve events. AppDomain currentDomain = Thread.GetDomain(); ResolveEventHandler resolveHandler = new ResolveEventHandler(typeResolveHandler.ResolveEvent); ResolveEventHandler asmResolveHandler = new ResolveEventHandler(typeResolveHandler.ResolveAsmEvent); ResolveEventHandler ROAsmResolveHandler = new ResolveEventHandler(typeResolveHandler.ResolveROAsmEvent); currentDomain.TypeResolve += resolveHandler; currentDomain.AssemblyResolve += asmResolveHandler; currentDomain.ReflectionOnlyAssemblyResolve += ROAsmResolveHandler; // Convert the types contained in the typelib into metadata and add them to the assembly. nConvertTypeLibToMetadata(typeLib, asmBldr.InternalAssembly, modBldr.InternalModule, asmNamespace, flags, typeResolveHandler, out eventItfInfoList); // Update the COM types in the assembly. UpdateComTypesInAssembly(asmBldr, modBldr); // If there are any event sources then generate the TCE adapters. if (eventItfInfoList.Count > 0) { new TCEAdapterGenerator().Process(modBldr, eventItfInfoList); } // Remove the listener for the type resolve events. currentDomain.TypeResolve -= resolveHandler; currentDomain.AssemblyResolve -= asmResolveHandler; currentDomain.ReflectionOnlyAssemblyResolve -= ROAsmResolveHandler; // We have finished converting the typelib and now have a fully formed assembly. return(asmBldr); }
internal static bool ValidateMachineType(TypeLibImporterFlags flags, _SYSKIND syskind) { int count = 0; if (IsImportingToX86(flags)) count++; if (IsImportingToX64(flags)) count++; if (IsImportingToItanium(flags)) count++; if (IsImportingToAgnostic(flags)) count++; if (count > 1) { Output.WriteError(Resource.FormatString("Err_BadMachineSwitch"), ErrorCode.Err_BadMachineSwitch); return false; } // Check the import type against the type of the type library. if (syskind == _SYSKIND.SYS_WIN64) { // If x86 was chosen, throw an error. if (IsImportingToX86(flags)) { Output.WriteError(Resource.FormatString("Err_BadMachineSwitch"), ErrorCode.Err_BadMachineSwitch); return false; } // If nothing is chosen, output a warning on all platforms. if (IsImportingToDefault(flags)) { Output.WriteWarning(Resource.FormatString("Wrn_AgnosticAssembly"), WarningCode.Wrn_AgnosticAssembly); } } else if (syskind == _SYSKIND.SYS_WIN32) { // If a 64-bit option was chosen, throw an error. if (IsImportingToItanium(flags) || IsImportingToX64(flags)) { Output.WriteError(Resource.FormatString("Err_BadMachineSwitch"), ErrorCode.Err_BadMachineSwitch); return false; } #if WIN64 // If nothing is chosen, and we're on a 64-bit machine, output a warning if (IsImportingToDefault(flags)) { Output.WriteWarning(Resource.FormatString("Wrn_AgnosticAssembly"), WarningCode.Wrn_AgnosticAssembly); } #endif } return true; }
internal static bool IsImportingToX86(TypeLibImporterFlags flags) { return ((flags & TypeLibImporterFlags.ImportAsX86) != 0); }
internal static bool IsImportingToItanium(TypeLibImporterFlags flags) { return ((flags & TypeLibImporterFlags.ImportAsItanium) != 0); }
internal static bool IsImportingToDefault(TypeLibImporterFlags flags) { return !(IsImportingToItanium(flags) || IsImportingToX64(flags) || IsImportingToX86(flags) || IsImportingToAgnostic(flags)); }
internal static bool IsImportingToAgnostic(TypeLibImporterFlags flags) { return ((flags & TypeLibImporterFlags.ImportAsAgnostic) != 0); }
public AssemblyBuilder CreateAssemblyBuilder(AssemblyName name, TypeLib tlb, TypeLibImporterFlags flags) { using (TypeLibAttr attr = tlb.GetLibAttr()) { // New assembly as well as loaded assembly should be all in a ReflectionOnly context as we don't need to run the code AssemblyBuilder assemblyBuilder = Thread.GetDomain().DefineDynamicAssembly(name, AssemblyBuilderAccess.ReflectionOnly); // Handle the type library name assemblyBuilder.SetCustomAttribute(CustomAttributeHelper.GetBuilderForImportedFromTypeLib(tlb.GetDocumentation())); // Handle the type library version assemblyBuilder.SetCustomAttribute(CustomAttributeHelper.GetBuilderForTypeLibVersion(attr.wMajorVerNum, attr.wMinorVerNum)); // Handle the LIBID assemblyBuilder.SetCustomAttribute(CustomAttributeHelper.GetBuilderForGuid(attr.guid)); // If we are generating a PIA, then set the PIA custom attribute. if ((flags & TypeLibImporterFlags.PrimaryInteropAssembly) != 0) assemblyBuilder.SetCustomAttribute(CustomAttributeHelper.GetBuilderForPrimaryInteropAssembly(attr.wMajorVerNum, attr.wMinorVerNum)); return assemblyBuilder; } }
public AssemblyBuilder ConvertTypeLibToAssembly([MarshalAs(UnmanagedType.Interface)] Object typeLib, String asmFileName, TypeLibImporterFlags flags, ITypeLibImporterNotifySink notifySink, byte[] publicKey, StrongNameKeyPair keyPair, String asmNamespace, Version asmVersion) { // Validate the arguments. if (typeLib == null) throw new ArgumentNullException("typeLib"); if (asmFileName == null) throw new ArgumentNullException("asmFileName"); if (notifySink == null) throw new ArgumentNullException("notifySink"); if (String.Empty.Equals(asmFileName)) throw new ArgumentException(Environment.GetResourceString("Arg_InvalidFileName"), "asmFileName"); if (asmFileName.Length > Path.MaxPath) throw new ArgumentException(Environment.GetResourceString("IO.PathTooLong"), asmFileName); if ((flags & TypeLibImporterFlags.PrimaryInteropAssembly) != 0 && publicKey == null && keyPair == null) throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_PIAMustBeStrongNamed")); Contract.EndContractBlock(); ArrayList eventItfInfoList = null; // Determine the AssemblyNameFlags AssemblyNameFlags asmNameFlags = AssemblyNameFlags.None; // Retrieve the assembly name from the typelib. AssemblyName asmName = GetAssemblyNameFromTypelib(typeLib, asmFileName, publicKey, keyPair, asmVersion, asmNameFlags); // Create the dynamic assembly that will contain the converted typelib types. AssemblyBuilder asmBldr = CreateAssemblyForTypeLib(typeLib, asmFileName, asmName, (flags & TypeLibImporterFlags.PrimaryInteropAssembly) != 0, (flags & TypeLibImporterFlags.ReflectionOnlyLoading) != 0, (flags & TypeLibImporterFlags.NoDefineVersionResource) != 0); // Define a dynamic module that will contain the contain the imported types. String strNonQualifiedAsmFileName = Path.GetFileName(asmFileName); ModuleBuilder modBldr = asmBldr.DefineDynamicModule(strNonQualifiedAsmFileName, strNonQualifiedAsmFileName); // If the namespace hasn't been specified, then use the assembly name. if (asmNamespace == null) asmNamespace = asmName.Name; // Create a type resolve handler that will also intercept resolve ref messages // on the sink interface to build up a list of referenced assemblies. TypeResolveHandler typeResolveHandler = new TypeResolveHandler(modBldr, notifySink); // Add a listener for the type resolve events. AppDomain currentDomain = Thread.GetDomain(); ResolveEventHandler resolveHandler = new ResolveEventHandler(typeResolveHandler.ResolveEvent); ResolveEventHandler asmResolveHandler = new ResolveEventHandler(typeResolveHandler.ResolveAsmEvent); ResolveEventHandler ROAsmResolveHandler = new ResolveEventHandler(typeResolveHandler.ResolveROAsmEvent); currentDomain.TypeResolve += resolveHandler; currentDomain.AssemblyResolve += asmResolveHandler; currentDomain.ReflectionOnlyAssemblyResolve += ROAsmResolveHandler; // Convert the types contained in the typelib into metadata and add them to the assembly. nConvertTypeLibToMetadata(typeLib, asmBldr.InternalAssembly, modBldr.InternalModule, asmNamespace, flags, typeResolveHandler, out eventItfInfoList); // Update the COM types in the assembly. UpdateComTypesInAssembly(asmBldr, modBldr); // If there are any event sources then generate the TCE adapters. if (eventItfInfoList.Count > 0) new TCEAdapterGenerator().Process(modBldr, eventItfInfoList); // Remove the listener for the type resolve events. currentDomain.TypeResolve -= resolveHandler; currentDomain.AssemblyResolve -= asmResolveHandler; currentDomain.ReflectionOnlyAssemblyResolve -= ROAsmResolveHandler; // We have finished converting the typelib and now have a fully formed assembly. return asmBldr; }
private static extern void nConvertTypeLibToMetadata(object typeLib, RuntimeAssembly asmBldr, RuntimeModule modBldr, string nameSpace, TypeLibImporterFlags flags, ITypeLibImporterNotifySink notifySink, out ArrayList eventItfInfoList);
public void Convert(string typeLibraryLocation, string assemblyLocation, string assemblyNamespace, Version assemblyVersion, TypeLibImporterFlags flags, byte[] publicKey, StrongNameKeyPair keyPair) { string assemblyFile = Path.GetFileName(assemblyLocation); this.assemblyPath = Path.GetDirectoryName(assemblyLocation); NativeMethods.ITypeLib typeLib = null; try { if (!Directory.Exists(assemblyPath)) { Directory.CreateDirectory(assemblyPath); } this.RaiseMessage(string.Format("Loading '{0}'.", typeLibraryLocation)); NativeMethods.LoadTypeLibEx(typeLibraryLocation, NativeMethods.RegKind.RegKind_None, out typeLib); if (typeLib != null) { this.ConvertTypeLib(typeLib, assemblyPath, assemblyFile, assemblyNamespace, assemblyVersion, flags, publicKey, keyPair); } } catch (Exception exception) { this.RaiseError(exception.Message); } finally { if (typeLib != null) { Marshal.ReleaseComObject(typeLib); } } this.RaiseMessage("Done."); }
private static extern void nConvertTypeLibToMetadata(Object typeLib, RuntimeAssembly asmBldr, RuntimeModule modBldr, String nameSpace, TypeLibImporterFlags flags, ITypeLibImporterNotifySink notifySink, out ArrayList eventItfInfoList);
public System.Reflection.Emit.AssemblyBuilder ConvertTypeLibToAssembly(Object typeLib, string asmFileName, TypeLibImporterFlags flags, ITypeLibImporterNotifySink notifySink, byte[] publicKey, System.Reflection.StrongNameKeyPair keyPair, string asmNamespace, Version asmVersion) { return default(System.Reflection.Emit.AssemblyBuilder); }
/* * Method: GenerateWrapper * * Generates a wrapper for this reference. */ internal bool GenerateWrapper(out ComReferenceWrapperInfo wrapperInfo) { wrapperInfo = null; string rootNamespace = ReferenceInfo.typeLibName; string wrapperPath = GetWrapperPath(); bool generateWrapperSucceeded = true; if (ExecuteAsTool) { // delegate generation of the assembly to an instance of the TlbImp ToolTask. MUST // HAVE SET SDKTOOLSPATH TO THE TARGET SDK TO WORK var tlbImp = new ResolveComReference.TlbImp(); tlbImp.BuildEngine = BuildEngine; tlbImp.EnvironmentVariables = EnvironmentVariables; tlbImp.DelaySign = DelaySign; tlbImp.KeyContainer = KeyContainer; tlbImp.KeyFile = KeyFile; tlbImp.OutputAssembly = wrapperPath; tlbImp.ToolPath = ToolPath; tlbImp.TypeLibName = ReferenceInfo.fullTypeLibPath; tlbImp.AssemblyNamespace = rootNamespace; tlbImp.AssemblyVersion = null; tlbImp.PreventClassMembers = _noClassMembers; tlbImp.SafeArrayAsSystemArray = true; tlbImp.Silent = Silent; tlbImp.Transform = ResolveComReference.TlbImpTransformFlags.TransformDispRetVals; if (_referenceFiles != null) { // Issue is that there may be reference dependencies that need to be passed in. It is possible // that the set of references will also contain the file that is meant to be written here (when reference resolution // found the file in the output folder). We need to filter out this case. var fullPathToOutput = Path.GetFullPath(wrapperPath); // Current directory is the directory of the project file. tlbImp.ReferenceFiles = _referenceFiles.Where(rf => String.Compare(fullPathToOutput, rf, StringComparison.OrdinalIgnoreCase) != 0).ToArray(); } switch (_targetProcessorArchitecture) { case UtilitiesProcessorArchitecture.MSIL: tlbImp.Machine = "Agnostic"; break; case UtilitiesProcessorArchitecture.AMD64: tlbImp.Machine = "X64"; break; case UtilitiesProcessorArchitecture.IA64: tlbImp.Machine = "Itanium"; break; case UtilitiesProcessorArchitecture.X86: tlbImp.Machine = "X86"; break; case UtilitiesProcessorArchitecture.ARM: tlbImp.Machine = "ARM"; break; case null: break; default: // Transmit the flag directly from the .targets files and rely on tlbimp.exe to produce a good error message. tlbImp.Machine = _targetProcessorArchitecture; break; } generateWrapperSucceeded = tlbImp.Execute(); // store the wrapper info... wrapperInfo = new ComReferenceWrapperInfo(); wrapperInfo.path = (HasTemporaryWrapper) ? null : wrapperPath; // Changed to ReflectionOnlyLoadFrom, related to bug: // RCR: Bad COM-interop assemblies being generated when using 64-bit MSBuild to build a project that is targeting 32-bit platform // The original call to UnsafeLoadFrom loads the assembly in preparation for execution. If the assembly is x86 and this is x64 msbuild.exe then we // have problems (UnsafeLoadFrom will fail). We only use this assembly for reference resolution so we don't need to be ready to execute the code. // // Its actually not clear to me that we even need to load the assembly at all. Reference resoluton is only used in the !ExecuteAsTool which is not // where we are right now. // // If we really do need to load it then: // // wrapperInfo.assembly = Assembly.ReflectionOnlyLoadFrom(wrapperPath); } else { // use framework classes in-proc to generate the assembly TypeLibConverter converter = new TypeLibConverter(); AssemblyBuilder assemblyBuilder = null; StrongNameKeyPair keyPair; byte[] publicKey; GetAndValidateStrongNameKey(out keyPair, out publicKey); try { TypeLibImporterFlags flags = TypeLibImporterFlags.SafeArrayAsSystemArray | TypeLibImporterFlags.TransformDispRetVals; if (_noClassMembers) { flags |= TypeLibImporterFlags.PreventClassMembers; } switch (_targetProcessorArchitecture) { case UtilitiesProcessorArchitecture.MSIL: flags |= TypeLibImporterFlags.ImportAsAgnostic; break; case UtilitiesProcessorArchitecture.AMD64: flags |= TypeLibImporterFlags.ImportAsX64; break; case UtilitiesProcessorArchitecture.IA64: flags |= TypeLibImporterFlags.ImportAsItanium; break; case UtilitiesProcessorArchitecture.X86: flags |= TypeLibImporterFlags.ImportAsX86; break; case UtilitiesProcessorArchitecture.ARM: flags |= TypeLibImporterFlags.ImportAsArm; break; default: // Let the type importer decide. break; } // Start the conversion process. We'll get callbacks on ITypeLibImporterNotifySink to resolve dependent refs. assemblyBuilder = converter.ConvertTypeLibToAssembly(ReferenceInfo.typeLibPointer, wrapperPath, flags, this, publicKey, keyPair, rootNamespace, null); } catch (COMException ex) { if (!Silent) { Log.LogWarningWithCodeFromResources("ResolveComReference.ErrorCreatingWrapperAssembly", ItemName, ex.Message); } throw new ComReferenceResolutionException(ex); } // if we're done, and this is not a temporary wrapper, write it out to disk if (!HasTemporaryWrapper) { WriteWrapperToDisk(assemblyBuilder, wrapperPath); } // store the wrapper info... wrapperInfo = new ComReferenceWrapperInfo(); wrapperInfo.path = (HasTemporaryWrapper) ? null : wrapperPath; wrapperInfo.assembly = assemblyBuilder; } // ...and we're done! return(generateWrapperSucceeded); }
public System.Reflection.Emit.AssemblyBuilder ConvertTypeLibToAssembly(Object typeLib, string asmFileName, TypeLibImporterFlags flags, ITypeLibImporterNotifySink notifySink, byte[] publicKey, System.Reflection.StrongNameKeyPair keyPair, string asmNamespace, Version asmVersion) { return(default(System.Reflection.Emit.AssemblyBuilder)); }
public AssemblyBuilder ConvertTypeLibToAssembly([MarshalAs(UnmanagedType.Interface)] object typeLib, string asmFileName, TypeLibImporterFlags flags, ITypeLibImporterNotifySink notifySink, byte[] publicKey, StrongNameKeyPair keyPair, string asmNamespace, Version asmVersion) { if (typeLib == null) { throw new ArgumentNullException("typeLib"); } if (asmFileName == null) { throw new ArgumentNullException("asmFileName"); } if (notifySink == null) { throw new ArgumentNullException("notifySink"); } if (string.Empty.Equals(asmFileName)) { throw new ArgumentException(Environment.GetResourceString("Arg_InvalidFileName"), "asmFileName"); } if (asmFileName.Length > 260) { throw new ArgumentException(Environment.GetResourceString("IO.PathTooLong"), asmFileName); } if ((flags & TypeLibImporterFlags.PrimaryInteropAssembly) != TypeLibImporterFlags.None && publicKey == null && keyPair == null) { throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_PIAMustBeStrongNamed")); } ArrayList arrayList = null; AssemblyNameFlags asmNameFlags = AssemblyNameFlags.None; AssemblyName assemblyNameFromTypelib = TypeLibConverter.GetAssemblyNameFromTypelib(typeLib, asmFileName, publicKey, keyPair, asmVersion, asmNameFlags); AssemblyBuilder assemblyBuilder = TypeLibConverter.CreateAssemblyForTypeLib(typeLib, asmFileName, assemblyNameFromTypelib, (flags & TypeLibImporterFlags.PrimaryInteropAssembly) > TypeLibImporterFlags.None, (flags & TypeLibImporterFlags.ReflectionOnlyLoading) > TypeLibImporterFlags.None, (flags & TypeLibImporterFlags.NoDefineVersionResource) > TypeLibImporterFlags.None); string fileName = Path.GetFileName(asmFileName); ModuleBuilder moduleBuilder = assemblyBuilder.DefineDynamicModule(fileName, fileName); if (asmNamespace == null) { asmNamespace = assemblyNameFromTypelib.Name; } TypeLibConverter.TypeResolveHandler typeResolveHandler = new TypeLibConverter.TypeResolveHandler(moduleBuilder, notifySink); AppDomain domain = Thread.GetDomain(); ResolveEventHandler value = new ResolveEventHandler(typeResolveHandler.ResolveEvent); ResolveEventHandler value2 = new ResolveEventHandler(typeResolveHandler.ResolveAsmEvent); ResolveEventHandler value3 = new ResolveEventHandler(typeResolveHandler.ResolveROAsmEvent); domain.TypeResolve += value; domain.AssemblyResolve += value2; domain.ReflectionOnlyAssemblyResolve += value3; TypeLibConverter.nConvertTypeLibToMetadata(typeLib, assemblyBuilder.InternalAssembly, moduleBuilder.InternalModule, asmNamespace, flags, typeResolveHandler, out arrayList); TypeLibConverter.UpdateComTypesInAssembly(assemblyBuilder, moduleBuilder); if (arrayList.Count > 0) { new TCEAdapterGenerator().Process(moduleBuilder, arrayList); } domain.TypeResolve -= value; domain.AssemblyResolve -= value2; domain.ReflectionOnlyAssemblyResolve -= value3; return(assemblyBuilder); }
public System.Reflection.Emit.AssemblyBuilder ConvertTypeLibToAssembly(object typeLib, string asmFileName, TypeLibImporterFlags flags, ITypeLibImporterNotifySink notifySink, Byte[] publicKey, System.Reflection.StrongNameKeyPair keyPair, string asmNamespace, Version asmVersion) { Contract.Requires(typeLib != null); Contract.Requires(asmFileName != null); Contract.Requires(notifySink != null); Contract.Requires(asmFileName.Length <= 260); Contract.Requires((int)((int)flags & 1) == 0 || publicKey != null || keyPair != null); return(default(System.Reflection.Emit.AssemblyBuilder)); }