Exemplo n.º 1
0
 /// <summary>
 /// Returns a "live" System.Reflection.Assembly instance that provides reflective access to the referenced assembly. 
 /// If the assembly cannot be found or cannot be loaded, the result is null.
 /// </summary>
 public Assembly/*?*/ GetAssembly(IAssemblyReference/*?*/ assemblyReference) {
   if (assemblyReference == null) return null;
   var ident = assemblyReference.AssemblyIdentity;
   Assembly result = null;
   if (!this.assemblyMap.TryGetValue(ident, out result)) {
     var name = new System.Reflection.AssemblyName();
     if (!String.IsNullOrEmpty(ident.Location))
       name.CodeBase = new Uri(ident.Location).ToString();
     name.CultureInfo = new System.Globalization.CultureInfo(ident.Culture);
     name.Name = ident.Name.Value;
     name.SetPublicKeyToken(new List<byte>(ident.PublicKeyToken).ToArray());
     name.Version = ident.Version;
     var loadedAssemblies = AppDomain.CurrentDomain.GetAssemblies();
     foreach (var loadedAssem in loadedAssemblies) {
       if (System.Reflection.AssemblyName.ReferenceMatchesDefinition(name, loadedAssem.GetName())) {
         result = loadedAssem;
         break;
       }
     }
     if (result == null) {
       try {
         result = Assembly.Load(name);
       } catch (System.UriFormatException) {
       } catch (System.IO.FileNotFoundException) {
       } catch (System.IO.FileLoadException) {
       } catch (System.BadImageFormatException) {
       }
       this.assemblyMap.Add(ident, result);
     }
   }
   return result;
 }
        public IAssembly Resolve(IAssemblyReference value, string localPath)
        {
            foreach (IAssembly ia in _assemblyManager.Assemblies)
            {
                if (ia.CompareTo(value) == 0)
                    return ia;
            }

            string assemblyString = value.ToString();
            Assembly assembly = null;
            try
            {
                assembly = AssemblyUtils.ResolveAssemblyFile(assemblyString, localPath);
                if (assembly == null)
                {
                    assembly = AssemblyUtils.LoadAssembly(assemblyString);
                }
            }
            catch
            {
            }

            if (assembly != null)
            {
                IAssembly ia = _assemblyManager.LoadFile(assembly.Location);
                return ia;
            }
            
            return null;
        }
Exemplo n.º 3
0
        private static IEnumerable<IAssemblyResource> GetAssemblyResourceNames(IAssemblyReference assemblyReference)
        {
            Guard.NotNull(() => assemblyReference, assemblyReference);

            var resources = new List<IAssemblyResource>();

            if (!String.IsNullOrEmpty(assemblyReference.Path))
            {
                if (File.Exists(assemblyReference.Path))
                {
                    try
                    {
                        var assembly = Assembly.ReflectionOnlyLoadFrom(assemblyReference.Path);
                        if (assembly != null)
                        {
                            // .NET resources
                            resources.AddRange(LoadResources(assembly, @".resources").Select(r => new AssemblyResource(assemblyReference, r)));
                            // XAML resources
                            resources.AddRange(LoadResources(assembly, @".g.resources").Select(r => new AssemblyResource(assemblyReference, r)));
                        }
                    }
                    catch (Exception)
                    {
                        // Ignore the exception
                    }
                }
            }

            return resources;
        }
Exemplo n.º 4
0
        /// <summary>
        /// Computes the string representing the strong name of the given assembly reference.
        /// </summary>
        public static string StrongName(IAssemblyReference assemblyReference)
        {
            StringBuilder sb = new StringBuilder();
            sb.Append(assemblyReference.Name);
            sb.AppendFormat(CultureInfo.InvariantCulture, ", Version={0}.{1}.{2}.{3}", assemblyReference.Version.Major, assemblyReference.Version.Minor, assemblyReference.Version.Build, assemblyReference.Version.Revision);
            if (assemblyReference.Culture != null && assemblyReference.Culture.Length > 0)
            {
                sb.AppendFormat(CultureInfo.InvariantCulture, ", Culture={0}", assemblyReference.Culture);
            }
            else
            {
                sb.Append(", Culture=neutral");
            }

            sb.Append(", PublicKeyToken=");
            if (IteratorHelper.EnumerableIsNotEmpty(assemblyReference.PublicKeyToken))
            {
                foreach (byte b in assemblyReference.PublicKeyToken)
                {
                    sb.Append(b.ToString("x2"));
                }
            }
            else
            {
                sb.Append("null");
            }

            if (assemblyReference.IsRetargetable)
            {
                sb.Append(", Retargetable=Yes");
            }

            return sb.ToString();
        }
Exemplo n.º 5
0
 public override void Visit(IAssemblyReference assemblyReference)
 {
     if (assemblyReference != Context.Module.GetContainingAssembly(Context))
     {
         RecordAssemblyReference(assemblyReference);
     }
 }
 public override void TraverseChildren(IAssembly assembly) {
   foreach (IModule module in assembly.MemberModules) {
     assemblyBeingTranslated = module.ContainingAssembly;
     this.Traverse(module);
   }
   firstPassDone = true;
 }
Exemplo n.º 7
0
 public override void Visit(IAssemblyReference assemblyReference)
 {
     if (assemblyReference != this.module.AsAssembly)
     {
         RecordAssemblyReference(assemblyReference);
     }
 }
Exemplo n.º 8
0
        /// <summary>
        /// Creates a new instance of the <see cref="AssemblyResource"/> class.
        /// </summary>
        public AssemblyResource(IAssemblyReference assembly, string name)
        {
            Guard.NotNull(() => assembly, assembly);
            Guard.NotNullOrEmpty(() => name, name);

            this.assembly = assembly;
            this.name = name;
        }
Exemplo n.º 9
0
        internal AssemblyReferenceAlias(string name, IAssemblyReference assembly)
        {
            Debug.Assert(name != null);
            Debug.Assert(assembly != null);

            Name = name;
            Assembly = assembly;
        }
Exemplo n.º 10
0
 /// <summary>
 /// Creates a type reference anchored in the given assembly reference and whose names are relative to the given host.
 /// When the type name has periods in it, a structured reference with nested namespaces is created.
 /// </summary>
 private static INamespaceTypeReference CreateTypeReference(IMetadataHost host, IAssemblyReference assemblyReference, string typeName)
 {
     IUnitNamespaceReference ns = new Immutable.RootUnitNamespaceReference(assemblyReference);
     string[] names = typeName.Split('.');
     for (int i = 0, n = names.Length - 1; i < n; i++)
         ns = new Immutable.NestedUnitNamespaceReference(ns, host.NameTable.GetNameFor(names[i]));
     return new Immutable.NamespaceTypeReference(host, ns, host.NameTable.GetNameFor(names[names.Length - 1]), 0, false, false, true, PrimitiveTypeCode.NotPrimitive);
 }
 public bool Equals(IAssemblyReference assemblyReference1, IAssemblyReference assemblyReference2)
 {
     return assemblyReference1 != null && 
         assemblyReference2 != null && 
         assemblyReference1.Name != null &&
         assemblyReference1.Name == assemblyReference2.Name &&
         assemblyReference1.Culture == assemblyReference2.Culture;
 }
        protected void AddAssemblyReference(IAssemblyReference assembly)
        {
            if (assembly == null)
                return;

            AssemblyIdentity id = assembly.AssemblyIdentity;
            if (!UsedAssemblyReferences.Contains(id)) // Only checking for contains for so can easily see new additions with a breakpoint in the debugger.
                UsedAssemblyReferences.Add(id);
        }
Exemplo n.º 13
0
		/// <summary>
		/// Creates a new GetClassTypeReference that searches a top-level type in the specified assembly.
		/// </summary>
		/// <param name="assembly">A reference to the assembly containing this type.
		/// If this parameter is null, the GetClassTypeReference will search in all assemblies belonging to the ICompilation.</param>
		/// <param name="nameSpace">The namespace name containing the type, e.g. "System.Collections.Generic".</param>
		/// <param name="name">The name of the type, e.g. "List".</param>
		/// <param name="typeParameterCount">The number of type parameters, (e.g. 1 for List&lt;T&gt;).</param>
		public GetClassTypeReference(IAssemblyReference assembly, string nameSpace, string name, int typeParameterCount)
		{
			if (nameSpace == null)
				throw new ArgumentNullException("nameSpace");
			if (name == null)
				throw new ArgumentNullException("name");
			this.assembly = assembly;
			this.nameSpace = nameSpace;
			this.name = name;
			this.typeParameterCount = typeParameterCount;
		}
Exemplo n.º 14
0
            public void AddAssemblyReference(IAssemblyReference assembly)
            {
                if (null == assembly)
                    return;

                IAssembly assemblyDef = assembly.ResolvedAssembly;
                if (!AssembliesClosure.ContainsKey(assemblyDef.Name.Value))
                {
                    AssembliesClosure.Add(assemblyDef.Name.Value, assemblyDef);
                    _workList.Enqueue(assemblyDef);
                }
            }
Exemplo n.º 15
0
        public void Unregister(IAssemblyReference assemblyReference)
        {
            if (assemblyReference == null) throw new ArgumentNullException("assemblyReference");

            var assembly = assemblyReference.LoadAssembly();
            foreach (var type in assembly.GetTypes())
            {
                if (IsImporter(type))
                {
                    importerInfos.Remove(type.Name);
                    Tracer.TraceSource.TraceInformation("Unregistered ContentImporter '{0}'.", type.Name);
                }
            }
        }
Exemplo n.º 16
0
        public void Register(IAssemblyReference assemblyReference)
        {
            if (assemblyReference == null) throw new ArgumentNullException("assemblyReference");

            var assembly = assemblyReference.LoadAssembly();

            Tracer.TraceSource.TraceInformation("Parsing ContentImporters from assembly '{0}'.", assembly.FullName);

            foreach (var type in assembly.GetTypes())
            {
                if (IsImporter(type))
                {
                    var attribute = GetContentImporterAttribute(type);
                    importerInfos[type.Name] = new AssemblyReferenceImporterInfo(type.FullName, attribute, assemblyReference);
                    Tracer.TraceSource.TraceInformation("Registered ContentImporter '{0}'.", type.Name);
                }
            }
        }
Exemplo n.º 17
0
 /// <summary>
 /// Creates a type reference to a namespace type from the given assembly, where the last element of the names
 /// array is the name of the type and the other elements are the names of the namespaces.
 /// </summary>
 /// <param name="assemblyReference">A reference to the assembly that contains the type for which a reference is desired.</param>
 /// <param name="isValueType">True if the referenced type is known to be a value type.</param>
 /// <param name="genericParameterCount">The number of generic parameters, if any, that the type has must. Must be zero or more.</param>
 /// <param name="typeCode">A code that identifies what kind of type is being referenced.</param>
 /// <param name="names">The last entry of this array is the name of the type, the others are the names of the containing namespaces.</param>
 public INamespaceTypeReference CreateReference(IAssemblyReference assemblyReference, bool isValueType, ushort genericParameterCount, PrimitiveTypeCode typeCode, params string[] names)
 {
     IUnitNamespaceReference ns = new RootUnitNamespaceReference(assemblyReference);
       for (int i = 0, n = names.Length-1; i < n; i++)
     ns = new NestedUnitNamespaceReference(ns, this.host.NameTable.GetNameFor(names[i]));
       return new NamespaceTypeReference(this.host, ns, this.host.NameTable.GetNameFor(names[names.Length-1]), genericParameterCount, false, isValueType, typeCode);
 }
Exemplo n.º 18
0
 static bool IsSpecialVersionOrRetargetable(IAssemblyReference reference)
 {
     return(IsZeroOrAllOnes(reference.Version) || reference.IsRetargetable);
 }
Exemplo n.º 19
0
 public virtual void Visit(IAssemblyReference assemblyReference)
 {
 }
 public bool IsGacAssembly(IAssemblyReference reference) => false;
Exemplo n.º 21
0
 /// <summary>
 /// For GAC assembly references, the WholeProjectDecompiler will omit the HintPath in the
 /// generated .csproj file.
 /// </summary>
 public virtual bool IsGacAssembly(IAssemblyReference reference)
 {
     return(UniversalAssemblyResolver.GetAssemblyInGac(reference) != null);
 }
Exemplo n.º 22
0
            public Assembly GenerateFacade(IAssembly contractAssembly, IAssemblyReference seedCoreAssemblyReference, bool ignoreMissingTypes, IAssembly overrideContractAssembly = null)
            {
                Assembly assembly;
                if (overrideContractAssembly != null)
                {
                    MetadataDeepCopier copier = new MetadataDeepCopier(_seedHost);
                    assembly = copier.Copy(overrideContractAssembly); // Use non-empty partial facade if present
                }
                else
                {
                    MetadataDeepCopier copier = new MetadataDeepCopier(_contractHost);
                    assembly = copier.Copy(contractAssembly);
                    ReferenceAssemblyToFacadeRewriter rewriter = new ReferenceAssemblyToFacadeRewriter(_seedHost, _contractHost, seedCoreAssemblyReference, _assemblyFileVersion != null);
                    rewriter.Rewrite(assembly);
                }

                IEnumerable<string> docIds = _docIdTable[contractAssembly.AssemblyIdentity.Name.Value];

                // Add all the type forwards
                bool error = false;

                HashSet<string> existingDocIds = new HashSet<string>(assembly.AllTypes.Select(typeDef => typeDef.RefDocId()));
                IEnumerable<string> missingDocIds = docIds.Where(id => !existingDocIds.Contains(id));
                foreach (string docId in missingDocIds)
                {
                    IReadOnlyList<INamedTypeDefinition> seedTypes;
                    if (!_typeTable.TryGetValue(docId, out seedTypes))
                    {
                        if (!ignoreMissingTypes)
                        {
                            Trace.TraceError("Did not find type '{0}' in any of the seed assemblies.", docId);
                            error = true;
                        }
                        continue;
                    }

                    INamedTypeDefinition seedType = GetSeedType(docId, seedTypes);
                    if (seedType == null)
                    {
                        TraceDuplicateSeedTypeError(docId, seedTypes);
                        error = true;
                        continue;
                    }

                    AddTypeForward(assembly, seedType);
                }

                if (error)
                {
                    return null;
                }

                if (_assemblyFileVersion != null)
                {
                    assembly.AssemblyAttributes.Add(CreateAttribute("System.Reflection.AssemblyFileVersionAttribute", seedCoreAssemblyReference.ResolvedAssembly, _assemblyFileVersion.ToString()));
                    assembly.AssemblyAttributes.Add(CreateAttribute("System.Reflection.AssemblyInformationalVersionAttribute", seedCoreAssemblyReference.ResolvedAssembly, _assemblyFileVersion.ToString()));
                }

                if (_buildDesignTimeFacades)
                {
                    assembly.AssemblyAttributes.Add(CreateAttribute("System.Runtime.CompilerServices.ReferenceAssemblyAttribute", seedCoreAssemblyReference.ResolvedAssembly));
                    assembly.Flags |= ReferenceAssemblyFlag;
                }

                if (_clearBuildAndRevision)
                {
                    assembly.Version = new Version(assembly.Version.Major, assembly.Version.Minor, 0, 0);
                }

                AddWin32VersionResource(contractAssembly.Location, assembly);

                return assembly;
            }
Exemplo n.º 23
0
 protected override uint GetOrAddAssemblyRefIndex(IAssemblyReference reference)
 {
     return(this.assemblyRefIndex.GetOrAdd(reference));
 }
        public string Decompile(int languageIndex, object o)
        {
            if (o == null)
            {
                return(String.Empty);
            }

            IFormatter      formatter  = CreateFormatter(this.LanguageManager.Languages[languageIndex].Name);
            ILanguageWriter writer     = this.LanguageManager.Languages[languageIndex].GetWriter(formatter, _langurageWriterConfiguration);
            ITranslator     translator = this.TranslatorManager.CreateDisassembler(null, null);

            if (o is IMethodDeclaration)
            {
                IMethodDeclaration m2;
                if (IsIL(languageIndex))
                {
                    m2 = (IMethodDeclaration)o;
                }
                else
                {
                    m2 = translator.TranslateMethodDeclaration((IMethodDeclaration)o);
                }
                writer.WriteMethodDeclaration(m2);
            }
            else if (o is IPropertyDeclaration)
            {
                IPropertyDeclaration p2 = translator.TranslatePropertyDeclaration((IPropertyDeclaration)o);
                writer.WritePropertyDeclaration(p2);
            }
            else if (o is IFieldDeclaration)
            {
                IFieldDeclaration f2 = translator.TranslateFieldDeclaration((IFieldDeclaration)o);
                writer.WriteFieldDeclaration(f2);
            }
            else if (o is ITypeDeclaration)
            {
                ITypeDeclaration t2 = translator.TranslateTypeDeclaration((ITypeDeclaration)o, true, false);
                writer.WriteTypeDeclaration(t2);
            }
            else if (o is IEventDeclaration)
            {
                IEventDeclaration e2 = translator.TranslateEventDeclaration((IEventDeclaration)o);
                writer.WriteEventDeclaration(e2);
            }
            else if (o is IModule)
            {
                IModule m2 = translator.TranslateModule((IModule)o, true);
                writer.WriteModule(m2);
            }
            else if (o is IModuleReference)
            {
                IModuleReference mr2 = translator.TranslateModuleReference((IModuleReference)o);
                writer.WriteModuleReference(mr2);
            }
            else if (o is IAssembly)
            {
                IAssembly a2 = translator.TranslateAssembly((IAssembly)o, true);
                writer.WriteAssembly(a2);
            }
            else if (o is IAssemblyReference)
            {
                IAssemblyReference ar2 = translator.TranslateAssemblyReference((IAssemblyReference)o);
                writer.WriteAssemblyReference(ar2);
            }
            else if (o is IResource)
            {
                writer.WriteResource((IResource)o);
            }
            else if (o is INamespace)
            {
                writer.WriteNamespace((INamespace)o);
            }

            return(formatter.ToString());
        }
Exemplo n.º 25
0
        public PEFile Resolve(IAssemblyReference name)
        {
            Log("------------------");
            Log(CSharpEditorResources.Resolve_0, name.FullName);

            // First, find the correct list of assemblies by name
            if (!_cache.TryGetValue(name.Name, out var assemblies))
            {
                Log(CSharpEditorResources.Could_not_find_by_name_0, name.FullName);
                return(null);
            }

            // If we have only one assembly available, just use it.
            // This is necessary, because in most cases there is only one assembly,
            // but still might have a version different from what the decompiler asks for.
            if (assemblies.Count == 1)
            {
                Log(CSharpEditorResources.Found_single_assembly_0, assemblies[0]);
                if (assemblies[0].Identity.Version != name.Version)
                {
                    Log(CSharpEditorResources.WARN_Version_mismatch_Expected_0_Got_1, name.Version, assemblies[0].Identity.Version);
                }
                return(MakePEFile(assemblies[0]));
            }

            // There are multiple assemblies
            Log(CSharpEditorResources.Found_0_assemblies_for_1, assemblies.Count, name.Name);

            // Get an exact match or highest version match from the list
            IAssemblySymbol highestVersion = null;
            IAssemblySymbol exactMatch     = null;

            var publicKeyTokenOfName = name.PublicKeyToken ?? Array.Empty <byte>();

            foreach (var assembly in assemblies)
            {
                Log(assembly.Identity.GetDisplayName());
                var version        = assembly.Identity.Version;
                var publicKeyToken = assembly.Identity.PublicKey;
                if (version == name.Version && publicKeyToken.SequenceEqual(publicKeyTokenOfName))
                {
                    exactMatch = assembly;
                    Log(CSharpEditorResources.Found_exact_match_0, assembly);
                }
                else if (highestVersion == null || highestVersion.Identity.Version < version)
                {
                    highestVersion = assembly;
                    Log(CSharpEditorResources.Found_higher_version_match_0, assembly);
                }
            }

            var chosen = exactMatch ?? highestVersion;

            Log(CSharpEditorResources.Chosen_version_0, chosen);
            return(MakePEFile(chosen));

            PEFile MakePEFile(IAssemblySymbol assembly)
            {
                // reference assemblies should be fine here, we only need the metadata of references.
                var reference = _parentCompilation.GetMetadataReference(assembly);

                Log(CSharpEditorResources.Load_from_0, reference.Display);
                return(new PEFile(reference.Display, PEStreamOptions.PrefetchMetadata));
            }
        }
Exemplo n.º 26
0
 bool IAssemblyResolver.IsGacAssembly(IAssemblyReference reference)
 {
     // This method is not called by the decompiler
     throw new NotSupportedException();
 }
Exemplo n.º 27
0
 void ISupportsInterning.PrepareForInterning(IInterningProvider provider)
 {
     assembly  = provider.Intern(assembly);
     nameSpace = provider.Intern(nameSpace);
     name      = provider.Intern(name);
 }
 public override void TraverseChildren(IAssemblyReference assemblyReference) {
   base.TraverseChildren(assemblyReference);
 }
Exemplo n.º 29
0
 protected override void RecordAssemblyReference(IAssemblyReference assemblyReference)
 {
 }
Exemplo n.º 30
0
 internal static INamespaceTypeReference CreateTypeReference(IMetadataHost host, IAssemblyReference assemblyReference, string typeName)
 {
     return(CreateTypeReference(host, assemblyReference, typeName, 0));
 }
Exemplo n.º 31
0
 public AssemblyResolutionException(IAssemblyReference reference, Exception innerException)
     : base($"Failed to resolve assembly: '{reference}'", innerException)
 {
     this.Reference = reference;
 }
Exemplo n.º 32
0
 protected override AssemblyReferenceHandle GetOrAddAssemblyReferenceHandle(IAssemblyReference reference)
 {
     return(MetadataTokens.AssemblyReferenceHandle(_assemblyRefIndex.GetOrAdd(reference.Identity)));
 }
Exemplo n.º 33
0
 /// <summary>
 /// For .NET Core framework references, the WholeProjectDecompiler will omit the
 /// assembly reference if the runtimePack is already included as an SDK.
 /// </summary>
 public virtual bool IsSharedAssembly(IAssemblyReference reference, out string runtimePack)
 {
     runtimePack = null;
     return(false);
 }
Exemplo n.º 34
0
        public static void Main(string[] args)
        {
            string         seeds                          = null;
            string         contracts                      = null;
            string         facadePath                     = null;
            Version        assemblyFileVersion            = null;
            bool           clearBuildAndRevision          = false;
            bool           ignoreMissingTypes             = false;
            bool           ignoreBuildAndRevisionMismatch = false;
            bool           buildDesignTimeFacades         = false;
            string         inclusionContracts             = null;
            ErrorTreatment seedLoadErrorTreatment         = ErrorTreatment.Default;
            ErrorTreatment contractLoadErrorTreatment     = ErrorTreatment.Default;

            string[] seedTypePreferencesUnsplit = null;
            bool     forceZeroVersionSeeds      = false;
            bool     producePdb = true;
            string   partialFacadeAssemblyPath = null;

            bool parsingSucceeded = CommandLineParser.ParseForConsoleApplication((parser) =>
            {
                parser.DefineQualifier("facadePath", ref facadePath, "Path to output the facades.");
                parser.DefineQualifier("seeds", ref seeds, "Path to the seed assemblies. Can contain multiple assemblies or directories delimited by ',' or ';'.");
                parser.DefineQualifier("contracts", ref contracts, "Path to the contract assemblies. Can contain multiple assemblies or directories delimited by ',' or ';'.");
                parser.DefineOptionalQualifier("assemblyFileVersion", ref assemblyFileVersion, "Override the AssemblyFileVersion attribute from the contract with the given version for the generated facade.");
                parser.DefineOptionalQualifier("clearBuildAndRevision", ref clearBuildAndRevision, "Generate facade assembly version x.y.0.0 for contract version x.y.z.w");
                parser.DefineOptionalQualifier("ignoreBuildAndRevisionMismatch", ref ignoreBuildAndRevisionMismatch, "Ignore a mismatch in revision and build for partial facade.");
                parser.DefineOptionalQualifier("ignoreMissingTypes", ref ignoreMissingTypes, "Ignore types that cannot be found in the seed assemblies. This is not recommended but is sometimes helpful while hacking around or trying to produce partial facades.");
                parser.DefineOptionalQualifier("designTime", ref buildDesignTimeFacades, "Enable design-time facade generation (marks facades with reference assembly flag and attribute).");
                parser.DefineOptionalQualifier("include", ref inclusionContracts, "Add types from these contracts to the facades. Can contain multiple assemblies or directories delimited by ',' or ';'.");
                parser.DefineOptionalQualifier("seedError", ref seedLoadErrorTreatment, "Error handling for seed assembly load failure.");
                parser.DefineOptionalQualifier("contractError", ref seedLoadErrorTreatment, "Error handling for contract assembly load failure.");
                parser.DefineOptionalQualifier("preferSeedType", ref seedTypePreferencesUnsplit, "Set which seed assembly to choose for a given type when it is defined in more than one assembly. Format: FullTypeName=PreferredSeedAssemblyName");
                parser.DefineOptionalQualifier("forceZeroVersionSeeds", ref forceZeroVersionSeeds, "Forces all seed assembly versions to 0.0.0.0, regardless of their true version.");
                parser.DefineOptionalQualifier("partialFacadeAssemblyPath", ref partialFacadeAssemblyPath, "Specifies the path to a single partial facade assembly, into which appropriate type forwards will be added to satisfy the given contract. If this option is specified, only a single partial assembly and a single contract may be given.");
                parser.DefineOptionalQualifier("producePdb", ref producePdb, "Specifices if a PDB file should be produced for the resulting partial facade.");
            }, args);

            if (!parsingSucceeded)
            {
                return;
            }

            CommandLineTraceHandler.Enable();

            if (!Directory.Exists(facadePath))
            {
                Directory.CreateDirectory(facadePath);
            }

            var nameTable     = new NameTable();
            var internFactory = new InternFactory();

            try
            {
                Dictionary <string, string> seedTypePreferences = ParseSeedTypePreferences(seedTypePreferencesUnsplit);

                using (var contractHost = new HostEnvironment(nameTable, internFactory))
                    using (var seedHost = new HostEnvironment(nameTable, internFactory))
                    {
                        contractHost.LoadErrorTreatment = contractLoadErrorTreatment;
                        seedHost.LoadErrorTreatment     = seedLoadErrorTreatment;

                        var contractAssemblies = LoadAssemblies(contractHost, contracts);
                        IReadOnlyDictionary <string, IEnumerable <string> > docIdTable = GenerateDocIdTable(contractAssemblies, inclusionContracts);

                        IAssembly[] seedAssemblies = LoadAssemblies(seedHost, seeds).ToArray();

                        IAssemblyReference seedCoreAssemblyRef = ((Microsoft.Cci.Immutable.PlatformType)seedHost.PlatformType).CoreAssemblyRef;

                        if (forceZeroVersionSeeds)
                        {
                            // Create a deep copier, copy the seed assemblies, and zero out their versions.
                            var copier = new MetadataDeepCopier(seedHost);

                            for (int i = 0; i < seedAssemblies.Length; i++)
                            {
                                var mutableSeed = copier.Copy(seedAssemblies[i]);
                                mutableSeed.Version = new Version(0, 0, 0, 0);
                                // Copy the modified seed assembly back.
                                seedAssemblies[i] = mutableSeed;

                                if (mutableSeed.Name.UniqueKey == seedCoreAssemblyRef.Name.UniqueKey)
                                {
                                    seedCoreAssemblyRef = mutableSeed;
                                }
                            }
                        }

                        var typeTable       = GenerateTypeTable(seedAssemblies);
                        var facadeGenerator = new FacadeGenerator(seedHost, contractHost, docIdTable, typeTable, seedTypePreferences, clearBuildAndRevision, buildDesignTimeFacades, assemblyFileVersion);

                        if (partialFacadeAssemblyPath != null)
                        {
                            if (contractAssemblies.Count() != 1)
                            {
                                throw new FacadeGenerationException(
                                          "When partialFacadeAssemblyPath is specified, only exactly one corresponding contract assembly can be specified.");
                            }

                            IAssembly contractAssembly      = contractAssemblies.First();
                            IAssembly partialFacadeAssembly = seedHost.LoadAssembly(partialFacadeAssemblyPath);
                            if (contractAssembly.Name != partialFacadeAssembly.Name ||
                                contractAssembly.Version.Major != partialFacadeAssembly.Version.Major ||
                                contractAssembly.Version.Minor != partialFacadeAssembly.Version.Minor ||
                                (!ignoreBuildAndRevisionMismatch && contractAssembly.Version.Build != partialFacadeAssembly.Version.Build) ||
                                (!ignoreBuildAndRevisionMismatch && contractAssembly.Version.Revision != partialFacadeAssembly.Version.Revision) ||
                                contractAssembly.GetPublicKeyToken() != partialFacadeAssembly.GetPublicKeyToken())
                            {
                                throw new FacadeGenerationException(
                                          string.Format("The partial facade assembly's name, version, and public key token must exactly match the contract to be filled. Contract: {0}, Facade: {1}",
                                                        contractAssembly.AssemblyIdentity,
                                                        partialFacadeAssembly.AssemblyIdentity));
                            }

                            Assembly filledPartialFacade = facadeGenerator.GenerateFacade(contractAssembly, seedCoreAssemblyRef, ignoreMissingTypes, overrideContractAssembly: partialFacadeAssembly);

                            string pdbLocation = null;

                            if (producePdb)
                            {
                                string pdbFolder = Path.GetDirectoryName(partialFacadeAssemblyPath);
                                pdbLocation = Path.Combine(pdbFolder, contractAssembly.Name + ".pdb");
                                if (producePdb && !File.Exists(pdbLocation))
                                {
                                    pdbLocation = null;
                                    Trace.TraceWarning("No PDB file present for un-transformed partial facade. No PDB will be generated.");
                                }
                            }

                            OutputFacadeToFile(facadePath, seedHost, filledPartialFacade, contractAssembly, pdbLocation);
                        }
                        else
                        {
                            foreach (var contract in contractAssemblies)
                            {
                                Assembly facade = facadeGenerator.GenerateFacade(contract, seedCoreAssemblyRef, ignoreMissingTypes);
                                if (facade == null)
                                {
#if !COREFX
                                    Debug.Assert(Environment.ExitCode != 0);
#endif
                                    continue;
                                }

                                OutputFacadeToFile(facadePath, seedHost, facade, contract);
                            }
                        }
                    }
            }
            catch (FacadeGenerationException ex)
            {
                Trace.TraceError(ex.Message);
#if !COREFX
                Debug.Assert(Environment.ExitCode != 0);
#endif
            }
        }
Exemplo n.º 35
0
    /// <summary>
    /// Creates a type reference anchored in the given assembly reference and whose names are relative to the given host.
    /// When the type name has periods in it, a structured reference with nested namespaces is created.
    /// </summary>
    protected static INamespaceTypeReference CreateTypeReference(IMetadataHost host, IAssemblyReference assemblyReference, string typeName) {
      Contract.Requires(host != null);
      Contract.Requires(assemblyReference != null);
      Contract.Requires(assemblyReference != Dummy.AssemblyReference);
      Contract.Requires(typeName != null);
      Contract.Requires(typeName != string.Empty);

      Contract.Ensures(Contract.Result<INamespaceTypeReference>() != null);
      Contract.Ensures(Contract.Result<INamespaceTypeReference>() != Dummy.NamespaceTypeReference);

      IUnitNamespaceReference ns = new Microsoft.Cci.Immutable.RootUnitNamespaceReference(assemblyReference);
      string[] names = typeName.Split('.');
      for (int i = 0, n = names.Length - 1; i < n; i++)
        ns = new Microsoft.Cci.Immutable.NestedUnitNamespaceReference(ns, host.NameTable.GetNameFor(names[i]));
      return new Microsoft.Cci.Immutable.NamespaceTypeReference(host, ns, host.NameTable.GetNameFor(names[names.Length - 1]), 0, false, false, true, PrimitiveTypeCode.NotPrimitive);
    }
Exemplo n.º 36
0
        /// <summary>
        /// Resolves the specified full assembly name.
        /// </summary>
        /// <param name="reference">A reference with details about the assembly.</param>
        /// <param name="parent">The parent of the reference.</param>
        /// <param name="input">The directories potentially containing the assemblies.</param>
        /// <param name="framework">The framework we are processing for.</param>
        /// <param name="parameters">Parameters to provide to the reflection system..</param>
        /// <returns>The assembly definitions.</returns>
        public static PEFile?Resolve(this IAssemblyReference reference, IModule parent, InputAssembliesGroup input, NuGetFramework framework, PEStreamOptions parameters = PEStreamOptions.PrefetchMetadata)
        {
            var fileName = GetFileName(reference, parent, input, framework);

            return(string.IsNullOrWhiteSpace(fileName) ? null : new PEFile(fileName, parameters));
        }
Exemplo n.º 37
0
 public virtual bool IsGacAssembly(IAssemblyReference reference)
 {
     return(GetAssemblyInGac(reference) != null);
 }
Exemplo n.º 38
0
 private static string?SearchDirectories(IAssemblyReference name, InputAssembliesGroup input, IEnumerable <string> extensions)
 {
     return(extensions.Select(extension => input.SupportGroup.GetFullFilePath(name.Name + extension)).Where(testName => !string.IsNullOrWhiteSpace(testName)).FirstOrDefault(File.Exists));
 }
Exemplo n.º 39
0
 public ReferenceAssemblyToFacadeRewriter(
     IMetadataHost seedHost,
     IMetadataHost contractHost,
     IAssemblyReference seedCoreAssemblyReference,
     bool stripFileVersionAttributes)
     : base(seedHost)
 {
     _seedHost = seedHost;
     _contractHost = contractHost;
     _stripFileVersionAttributes = stripFileVersionAttributes;
     _seedCoreAssemblyReference = seedCoreAssemblyReference;
 }
Exemplo n.º 40
0
            public Assembly GenerateFacade(IAssembly contractAssembly, IAssemblyReference seedCoreAssemblyReference, bool ignoreMissingTypes, IAssembly overrideContractAssembly = null, bool buildPartialReferenceFacade = false)
            {
                Assembly assembly;

                if (overrideContractAssembly != null)
                {
                    MetadataDeepCopier copier = new MetadataDeepCopier(_seedHost);
                    assembly = copier.Copy(overrideContractAssembly); // Use non-empty partial facade if present
                }
                else
                {
                    MetadataDeepCopier copier = new MetadataDeepCopier(_contractHost);
                    assembly = copier.Copy(contractAssembly);

                    // if building a reference facade don't strip the contract
                    if (!buildPartialReferenceFacade)
                    {
                        ReferenceAssemblyToFacadeRewriter rewriter = new ReferenceAssemblyToFacadeRewriter(_seedHost, _contractHost, seedCoreAssemblyReference, _assemblyFileVersion != null);
                        rewriter.Rewrite(assembly);
                    }
                }

                string contractAssemblyName = contractAssembly.AssemblyIdentity.Name.Value;
                IEnumerable <string> docIds = _docIdTable[contractAssemblyName];

                // Add all the type forwards
                bool error = false;

                Dictionary <string, INamedTypeDefinition> existingDocIds = assembly.AllTypes.ToDictionary(typeDef => typeDef.RefDocId(), typeDef => typeDef);
                IEnumerable <string> docIdsToForward = buildPartialReferenceFacade ? existingDocIds.Keys : docIds.Where(id => !existingDocIds.ContainsKey(id));
                Dictionary <string, INamedTypeReference> forwardedTypes = new Dictionary <string, INamedTypeReference>();

                foreach (string docId in docIdsToForward)
                {
                    IReadOnlyList <INamedTypeDefinition> seedTypes;
                    if (!_typeTable.TryGetValue(docId, out seedTypes))
                    {
                        if (!ignoreMissingTypes && !buildPartialReferenceFacade)
                        {
                            Trace.TraceError("Did not find type '{0}' in any of the seed assemblies.", docId);
                            error = true;
                        }
                        continue;
                    }

                    INamedTypeDefinition seedType = GetSeedType(docId, seedTypes);
                    if (seedType == null)
                    {
                        TraceDuplicateSeedTypeError(docId, seedTypes);
                        error = true;
                        continue;
                    }

                    if (buildPartialReferenceFacade)
                    {
                        // honor preferSeedType for keeping contract type
                        string preferredSeedAssembly;
                        bool   keepType = _seedTypePreferences.TryGetValue(docId, out preferredSeedAssembly) &&
                                          contractAssemblyName.Equals(preferredSeedAssembly, StringComparison.OrdinalIgnoreCase);

                        if (keepType)
                        {
                            continue;
                        }

                        assembly.AllTypes.Remove(existingDocIds[docId]);
                        forwardedTypes.Add(docId, seedType);
                    }

                    AddTypeForward(assembly, seedType);
                }

                if (buildPartialReferenceFacade)
                {
                    if (forwardedTypes.Count == 0)
                    {
                        Trace.TraceError("Did not find any types in any of the seed assemblies.");
                        return(null);
                    }
                    else
                    {
                        // for any thing that's now a typeforward, make sure typerefs point to that rather than
                        // the type previously inside the assembly.
                        TypeReferenceRewriter typeRefRewriter = new TypeReferenceRewriter(_seedHost, oldType =>
                        {
                            INamedTypeReference newType = null;
                            return(forwardedTypes.TryGetValue(oldType.DocId(), out newType) ? newType : oldType);
                        });

                        typeRefRewriter.Rewrite(assembly);
                    }
                }

                if (error)
                {
                    return(null);
                }

                if (_assemblyFileVersion != null)
                {
                    assembly.AssemblyAttributes.Add(CreateAttribute("System.Reflection.AssemblyFileVersionAttribute", seedCoreAssemblyReference.ResolvedAssembly, _assemblyFileVersion.ToString()));
                    assembly.AssemblyAttributes.Add(CreateAttribute("System.Reflection.AssemblyInformationalVersionAttribute", seedCoreAssemblyReference.ResolvedAssembly, _assemblyFileVersion.ToString()));
                }

                if (_buildDesignTimeFacades)
                {
                    assembly.AssemblyAttributes.Add(CreateAttribute("System.Runtime.CompilerServices.ReferenceAssemblyAttribute", seedCoreAssemblyReference.ResolvedAssembly));
                    assembly.Flags |= ReferenceAssemblyFlag;
                }

                if (_clearBuildAndRevision)
                {
                    assembly.Version = new Version(assembly.Version.Major, assembly.Version.Minor, 0, 0);
                }

                AddWin32VersionResource(contractAssembly.Location, assembly);

                return(assembly);
            }
Exemplo n.º 41
0
        public static bool Execute(
            string seeds,
            string contracts,
            string facadePath,
            Version assemblyFileVersion               = null,
            bool clearBuildAndRevision                = false,
            bool ignoreMissingTypes                   = false,
            bool ignoreBuildAndRevisionMismatch       = false,
            bool buildDesignTimeFacades               = false,
            string inclusionContracts                 = null,
            ErrorTreatment seedLoadErrorTreatment     = ErrorTreatment.Default,
            ErrorTreatment contractLoadErrorTreatment = ErrorTreatment.Default,
            string[] seedTypePreferencesUnsplit       = null,
            bool forceZeroVersionSeeds                = false,
            bool producePdb = true,
            string partialFacadeAssemblyPath = null)
        {
            if (!Directory.Exists(facadePath))
            {
                Directory.CreateDirectory(facadePath);
            }

            var nameTable     = new NameTable();
            var internFactory = new InternFactory();

            try
            {
                Dictionary <string, string> seedTypePreferences = ParseSeedTypePreferences(seedTypePreferencesUnsplit);

                using (var contractHost = new HostEnvironment(nameTable, internFactory))
                    using (var seedHost = new HostEnvironment(nameTable, internFactory))
                    {
                        contractHost.LoadErrorTreatment = contractLoadErrorTreatment;
                        seedHost.LoadErrorTreatment     = seedLoadErrorTreatment;

                        var contractAssemblies = LoadAssemblies(contractHost, contracts);
                        IReadOnlyDictionary <string, IEnumerable <string> > docIdTable = GenerateDocIdTable(contractAssemblies, inclusionContracts);

                        IAssembly[] seedAssemblies = LoadAssemblies(seedHost, seeds).ToArray();

                        IAssemblyReference seedCoreAssemblyRef = ((Microsoft.Cci.Immutable.PlatformType)seedHost.PlatformType).CoreAssemblyRef;

                        if (forceZeroVersionSeeds)
                        {
                            // Create a deep copier, copy the seed assemblies, and zero out their versions.
                            var copier = new MetadataDeepCopier(seedHost);

                            for (int i = 0; i < seedAssemblies.Length; i++)
                            {
                                var mutableSeed = copier.Copy(seedAssemblies[i]);
                                mutableSeed.Version = new Version(0, 0, 0, 0);
                                // Copy the modified seed assembly back.
                                seedAssemblies[i] = mutableSeed;

                                if (mutableSeed.Name.UniqueKey == seedCoreAssemblyRef.Name.UniqueKey)
                                {
                                    seedCoreAssemblyRef = mutableSeed;
                                }
                            }
                        }

                        var typeTable       = GenerateTypeTable(seedAssemblies);
                        var facadeGenerator = new FacadeGenerator(seedHost, contractHost, docIdTable, typeTable, seedTypePreferences, clearBuildAndRevision, buildDesignTimeFacades, assemblyFileVersion);

                        if (partialFacadeAssemblyPath != null)
                        {
                            if (contractAssemblies.Count() != 1)
                            {
                                throw new FacadeGenerationException(
                                          "When partialFacadeAssemblyPath is specified, only exactly one corresponding contract assembly can be specified.");
                            }

                            IAssembly contractAssembly      = contractAssemblies.First();
                            IAssembly partialFacadeAssembly = seedHost.LoadAssembly(partialFacadeAssemblyPath);
                            if (contractAssembly.Name != partialFacadeAssembly.Name ||
                                contractAssembly.Version.Major != partialFacadeAssembly.Version.Major ||
                                contractAssembly.Version.Minor != partialFacadeAssembly.Version.Minor ||
                                (!ignoreBuildAndRevisionMismatch && contractAssembly.Version.Build != partialFacadeAssembly.Version.Build) ||
                                (!ignoreBuildAndRevisionMismatch && contractAssembly.Version.Revision != partialFacadeAssembly.Version.Revision) ||
                                contractAssembly.GetPublicKeyToken() != partialFacadeAssembly.GetPublicKeyToken())
                            {
                                throw new FacadeGenerationException(
                                          string.Format("The partial facade assembly's name, version, and public key token must exactly match the contract to be filled. Contract: {0}, Facade: {1}",
                                                        contractAssembly.AssemblyIdentity,
                                                        partialFacadeAssembly.AssemblyIdentity));
                            }

                            Assembly filledPartialFacade = facadeGenerator.GenerateFacade(contractAssembly, seedCoreAssemblyRef, ignoreMissingTypes, overrideContractAssembly: partialFacadeAssembly);

                            if (filledPartialFacade == null)
                            {
                                Trace.TraceError("Errors were encountered while generating the facade.");
                                return(false);
                            }

                            string pdbLocation = null;

                            if (producePdb)
                            {
                                string pdbFolder = Path.GetDirectoryName(partialFacadeAssemblyPath);
                                pdbLocation = Path.Combine(pdbFolder, contractAssembly.Name + ".pdb");
                                if (producePdb && !File.Exists(pdbLocation))
                                {
                                    pdbLocation = null;
                                    Trace.TraceWarning("No PDB file present for un-transformed partial facade. No PDB will be generated.");
                                }
                            }

                            OutputFacadeToFile(facadePath, seedHost, filledPartialFacade, contractAssembly, pdbLocation);
                        }
                        else
                        {
                            foreach (var contract in contractAssemblies)
                            {
                                Assembly facade = facadeGenerator.GenerateFacade(contract, seedCoreAssemblyRef, ignoreMissingTypes);
                                if (facade == null)
                                {
#if !COREFX
                                    Debug.Assert(Environment.ExitCode != 0);
#endif
                                    return(false);
                                }

                                OutputFacadeToFile(facadePath, seedHost, facade, contract);
                            }
                        }
                    }

                return(true);
            }
            catch (FacadeGenerationException ex)
            {
                Trace.TraceError(ex.Message);
#if !COREFX
                Debug.Assert(Environment.ExitCode != 0);
#endif
                return(false);
            }
        }
Exemplo n.º 42
0
            public override IAssemblyReference Rewrite(IAssemblyReference assemblyReference)
            {
                if (assemblyReference == null)
                    return assemblyReference;

                if (assemblyReference.UnifiedAssemblyIdentity.Equals(_contractHost.CoreAssemblySymbolicIdentity) &&
                    !assemblyReference.ModuleIdentity.Equals(host.CoreAssemblySymbolicIdentity))
                {
                    assemblyReference = _seedCoreAssemblyReference;
                }

                return base.Rewrite(assemblyReference);
            }
Exemplo n.º 43
0
        internal static INamespaceTypeReference CreateTypeReference(IMetadataHost host, IAssemblyReference assemblyReference, string typeName, ushort genericParameterCount)
        {
            IUnitNamespaceReference ns = new Microsoft.Cci.Immutable.RootUnitNamespaceReference(assemblyReference);

            string[] names = typeName.Split('.');
            for (int i = 0, n = names.Length - 1; i < n; i++)
            {
                ns = new Microsoft.Cci.Immutable.NestedUnitNamespaceReference(ns, host.NameTable.GetNameFor(names[i]));
            }
            return(new Microsoft.Cci.Immutable.NamespaceTypeReference(host, ns, host.NameTable.GetNameFor(names[names.Length - 1]), genericParameterCount, false, false, true, PrimitiveTypeCode.NotPrimitive));
        }
Exemplo n.º 44
0
 internal static UsedNamespaceOrType CreateNamespace(INamespace @namespace, IAssemblyReference assemblyOpt = null, string aliasOpt = null)
 {
     Debug.Assert(@namespace != null);
     return(new UsedNamespaceOrType(alias: aliasOpt, targetAssembly: assemblyOpt, targetNamespace: @namespace));
 }
Exemplo n.º 45
0
 public static AssemblyNameReference FindMatchingAssemblyReference(AssemblyDefinition adef, IAssemblyReference anref)
 {
     return(adef.MainModule.AssemblyReferences.FirstOrDefault(item => item.ToString() == anref.ToString()));
 }
Exemplo n.º 46
0
 protected override void RecordAssemblyReference(IAssemblyReference assemblyReference)
 {
     this.metadataWriter.GetAssemblyRefIndex(assemblyReference);
 }
Exemplo n.º 47
0
            public Assembly GenerateFacade(IAssembly contractAssembly, IAssemblyReference seedCoreAssemblyReference, bool ignoreMissingTypes, IAssembly overrideContractAssembly = null)
            {
                Assembly assembly;

                if (overrideContractAssembly != null)
                {
                    MetadataDeepCopier copier = new MetadataDeepCopier(_seedHost);
                    assembly = copier.Copy(overrideContractAssembly); // Use non-empty partial facade if present
                }
                else
                {
                    MetadataDeepCopier copier = new MetadataDeepCopier(_contractHost);
                    assembly = copier.Copy(contractAssembly);
                    ReferenceAssemblyToFacadeRewriter rewriter = new ReferenceAssemblyToFacadeRewriter(_seedHost, _contractHost, seedCoreAssemblyReference, _assemblyFileVersion != null);
                    rewriter.Rewrite(assembly);
                }

                IEnumerable <string> docIds = _docIdTable[contractAssembly.AssemblyIdentity.Name.Value];

                // Add all the type forwards
                bool error = false;

                HashSet <string>     existingDocIds = new HashSet <string>(assembly.AllTypes.Select(typeDef => typeDef.RefDocId()));
                IEnumerable <string> missingDocIds  = docIds.Where(id => !existingDocIds.Contains(id));

                foreach (string docId in missingDocIds)
                {
                    IReadOnlyList <INamedTypeDefinition> seedTypes;
                    if (!_typeTable.TryGetValue(docId, out seedTypes))
                    {
                        if (!ignoreMissingTypes)
                        {
                            Trace.TraceError("Did not find type '{0}' in any of the seed assemblies.", docId);
                            error = true;
                        }
                        continue;
                    }

                    INamedTypeDefinition seedType = GetSeedType(docId, seedTypes);
                    if (seedType == null)
                    {
                        TraceDuplicateSeedTypeError(docId, seedTypes);
                        error = true;
                        continue;
                    }

                    AddTypeForward(assembly, seedType);
                }

                if (error)
                {
                    return(null);
                }

                if (_assemblyFileVersion != null)
                {
                    assembly.AssemblyAttributes.Add(CreateAttribute("System.Reflection.AssemblyFileVersionAttribute", seedCoreAssemblyReference.ResolvedAssembly, _assemblyFileVersion.ToString()));
                    assembly.AssemblyAttributes.Add(CreateAttribute("System.Reflection.AssemblyInformationalVersionAttribute", seedCoreAssemblyReference.ResolvedAssembly, _assemblyFileVersion.ToString()));
                }

                if (_buildDesignTimeFacades)
                {
                    assembly.AssemblyAttributes.Add(CreateAttribute("System.Runtime.CompilerServices.ReferenceAssemblyAttribute", seedCoreAssemblyReference.ResolvedAssembly));
                    assembly.Flags |= ReferenceAssemblyFlag;
                }

                if (_clearBuildAndRevision)
                {
                    assembly.Version = new Version(assembly.Version.Major, assembly.Version.Minor, 0, 0);
                }

                AddWin32VersionResource(contractAssembly.Location, assembly);

                return(assembly);
            }
            public IAssembly Resolve(IAssemblyReference assemblyName, string localPath)
            {
                if (_assemblyTable.Contains(assemblyName))
                {
                    return (IAssembly)_assemblyTable[assemblyName];
                }

                IAssembly assembly = _assemblyResolver.Resolve(assemblyName, localPath);

                _assemblyTable.Add(assemblyName, assembly);

                return assembly;
            }
Exemplo n.º 49
0
        private static string?SearchNugetFrameworkDirectories(IAssemblyReference reference, IReadOnlyCollection <string> extensions, NuGetFramework framework)
        {
            var folders = framework.GetNuGetFrameworkFolders();

            return(folders.SelectMany(_ => extensions, (folder, extension) => Path.Combine(folder, reference.Name + extension)).Where(testName => !string.IsNullOrWhiteSpace(testName)).FirstOrDefault(File.Exists));
        }
Exemplo n.º 50
0
 public PEFile?Resolve(IAssemblyReference reference)
 {
     return(ResolveAsync(reference).GetAwaiter().GetResult());
 }
Exemplo n.º 51
0
 public virtual void AddAssemblyReference(IAssemblyReference assembly)
 {
     Debug.Assert(CanIncludeAssembly(assembly.AssemblyIdentity));
     _depot.AddAssemblyReference(assembly);
 }
Exemplo n.º 52
0
            public async Task <PEFile?> ResolveAsync(IAssemblyReference reference)
            {
                PEFile?module;

                // 0) if we're inside a package, look for filename.dll in parent directories
                if (providedAssemblyResolver != null)
                {
                    module = await providedAssemblyResolver.ResolveAsync(reference).ConfigureAwait(false);

                    if (module != null)
                    {
                        return(module);
                    }
                }

                string tfm = await tfmTask.ConfigureAwait(false);

                bool   isWinRT = reference.IsWindowsRuntime;
                string key     = tfm + ";" + (isWinRT ? reference.Name : reference.FullName);

                // 1) try to find exact match by tfm + full asm name in loaded assemblies
                var lookup = LazyInit.VolatileRead(ref isWinRT ? ref asmLookupByShortName : ref asmLookupByFullName);

                if (lookup == null)
                {
                    lookup = await CreateLoadedAssemblyLookupAsync(shortNames : isWinRT).ConfigureAwait(false);

                    lookup = LazyInit.GetOrSet(ref isWinRT ? ref asmLookupByShortName : ref asmLookupByFullName, lookup);
                }
                if (lookup.TryGetValue(key, out module))
                {
                    referenceLoadInfo.AddMessageOnce(reference.FullName, MessageKind.Info, "Success - Found in Assembly List");
                    return(module);
                }

                string?file = parent.GetUniversalResolver().FindAssemblyFile(reference);

                if (file != null)
                {
                    // Load assembly from disk
                    LoadedAssembly?asm;
                    if (loadOnDemand)
                    {
                        asm = assemblyList.OpenAssembly(file, isAutoLoaded: true);
                    }
                    else
                    {
                        asm = assemblyList.FindAssembly(file);
                    }
                    if (asm != null)
                    {
                        referenceLoadInfo.AddMessage(reference.ToString(), MessageKind.Info, "Success - Loading from: " + file);
                        return(await asm.GetPEFileOrNullAsync().ConfigureAwait(false));
                    }
                    return(null);
                }
                else
                {
                    // Assembly not found; try to find a similar-enough already-loaded assembly
                    var candidates = new List <(LoadedAssembly assembly, Version version)>();

                    foreach (LoadedAssembly loaded in alreadyLoadedAssemblies)
                    {
                        module = await loaded.GetPEFileOrNullAsync().ConfigureAwait(false);

                        var reader = module?.Metadata;
                        if (reader == null || !reader.IsAssembly)
                        {
                            continue;
                        }
                        var asmDef     = reader.GetAssemblyDefinition();
                        var asmDefName = reader.GetString(asmDef.Name);
                        if (reference.Name.Equals(asmDefName, StringComparison.OrdinalIgnoreCase))
                        {
                            candidates.Add((loaded, asmDef.Version));
                        }
                    }

                    if (candidates.Count == 0)
                    {
                        referenceLoadInfo.AddMessageOnce(reference.ToString(), MessageKind.Error, "Could not find reference: " + reference);
                        return(null);
                    }

                    candidates.SortBy(c => c.version);

                    var bestCandidate = candidates.FirstOrDefault(c => c.version >= reference.Version).assembly ?? candidates.Last().assembly;
                    referenceLoadInfo.AddMessageOnce(reference.ToString(), MessageKind.Info, "Success - Found in Assembly List with different TFM or version: " + bestCandidate.fileName);
                    return(await bestCandidate.GetPEFileOrNullAsync().ConfigureAwait(false));
                }
            }
Exemplo n.º 53
0
 public virtual void onMetadataElement(IAssemblyReference assemblyReference) { }
Exemplo n.º 54
0
 public AssemblyIdentity UnifyAssembly(IAssemblyReference assemblyReference) {
   throw new NotImplementedException();
 }
Exemplo n.º 55
0
 /// <summary>
 /// Returns true if the given two assembly references are to be considered equivalent.
 /// </summary>
 public static bool AssembliesAreEquivalent(IAssemblyReference /*?*/ assembly1, IAssemblyReference /*?*/ assembly2)
 {
     if (assembly1 == null || assembly2 == null)
     {
         return(false);
     }
     if (assembly1 == assembly2)
     {
         return(true);
     }
     if (assembly1.Name.UniqueKeyIgnoringCase != assembly2.Name.UniqueKeyIgnoringCase)
     {
         return(false);
     }
     if (!assembly1.Version.Equals(assembly2.Version))
     {
         return(false);
     }
     if (!assembly1.Culture.Equals(assembly2.Culture))
     {
         return(false);
     }
     return(IteratorHelper.EnumerablesAreEqual <byte>(assembly1.PublicKeyToken, assembly2.PublicKeyToken));
 }
Exemplo n.º 56
0
 public override void TraverseChildren(IAssemblyReference assemblyReference)
 {
     MethodEnter(assemblyReference);
     base.TraverseChildren(assemblyReference);
     MethodExit();
 }
Exemplo n.º 57
0
 /// <summary>
 /// Default implementation of UnifyAssembly. Override this method to change the behavior.
 /// </summary>
 public virtual AssemblyIdentity UnifyAssembly(IAssemblyReference assemblyReference) {
   return this.UnifyAssembly(assemblyReference.AssemblyIdentity);
 }
Exemplo n.º 58
0
 /// <summary>
 /// Performs some computation with the given assembly reference.
 /// </summary>
 public void Visit(IAssemblyReference assemblyReference)
 {
     this.Visit((IModuleReference)assemblyReference);
     //if (assemblyReference.Name.Value.IndexOfAny(badAssemblyNameChars) > 0)
     if (assemblyReference.Name.Value.IndexOfAny(badPosixNameChars) > 0)
       this.ReportError(MetadataError.NotPosixAssemblyName, assemblyReference, assemblyReference.Name.Value);
     if (assemblyReference.Culture != string.Empty && validCultureNames.Find(x => string.Compare(assemblyReference.Culture, x, StringComparison.OrdinalIgnoreCase) == 0) == null)
       this.ReportError(MetadataError.InvalidCulture, assemblyReference, assemblyReference.Culture);
 }
Exemplo n.º 59
0
		public static AssemblyNameReference FindMatchingAssemblyReference(AssemblyDefinition adef, IAssemblyReference anref)
		{
			return adef.MainModule.AssemblyReferences.FirstOrDefault(item => item.ToString() == anref.ToString());
		}
Exemplo n.º 60
0
 public AssemblyResolutionException(IAssemblyReference reference)
     : this(reference, null)
 {
 }