public override AssemblyDefinition Resolve (AssemblyNameReference name)
		{
			AssemblyDefinition assembly;
			if (assemblies.TryGetValue(name.Name, out assembly))
				return assembly;

			return base.Resolve (name);
		}
 public AssemblyDefinition Resolve(string fullName)
 {
     return(Resolve(AssemblyNameReference.Parse(fullName)));
 }
示例#3
0
 public virtual void VisitAssemblyReference(AssemblyNameReference assemblyRef, AssemblyDefinition current)
 {
 }
示例#4
0
        public bool ConvertAssemblyReferences(string dllPath)
        {
            VortexPatcher.Logger.Info($"Attempting to convert {Path.GetFileName(dllPath)}");
            if (!File.Exists(dllPath))
            {
                VortexPatcher.Logger.Error($"File is missing: { dllPath }");
                return(false);
            }

            string tempFile         = dllPath + Constants.VORTEX_TEMP_SUFFIX;
            string instructionsFile = null;

            try
            {
                string backUpFile = dllPath + Constants.VORTEX_BACKUP;
                if (!File.Exists(backUpFile))
                {
                    Util.Backup(dllPath);
                }

                // Create a temporary file for us to manipulate.
                File.Copy(dllPath, tempFile, true);

                // UMM mods need to have an assembly reference to the VortexUnity.dll file
                //  containing UI specific functionality.
                AssemblyDefinition    vigoDef  = AssemblyDefinition.ReadAssembly(Path.Combine(VortexPatcher.CurrentDataPath, Constants.VIGO_FILENAME));
                AssemblyNameReference vigoRef  = AssemblyNameReference.Parse(vigoDef.FullName);
                string             vigoName    = vigoDef.Name.Name;
                AssemblyDefinition modAssembly = AssemblyDefinition.ReadAssembly(tempFile);

                // Add the reference to VIGO.
                modAssembly.MainModule.ImportReference(vigoRef.GetType());
                modAssembly.MainModule.AssemblyReferences.Add(vigoRef);
                var references = modAssembly.MainModule.AssemblyReferences;

                // Find the UMM reference
                AssemblyNameReference ummRef = references.FirstOrDefault(res => res.Name == Constants.UMM_ASSEMBLY_REF_NAME);
                if (ummRef == null)
                {
                    m_ModAssembly = Assembly.LoadFile(dllPath);
                    throw new Exceptions.AssemblyIsInjectedException(dllPath);
                }

                AssemblyNameReference newRef = AssemblyNameReference.Parse(VortexPatcher.InstallerAssembly.FullName);
                int idx = modAssembly.MainModule.AssemblyReferences.IndexOf(ummRef);
                modAssembly.MainModule.AssemblyReferences.Insert(idx, newRef);
                modAssembly.MainModule.AssemblyReferences.Remove(ummRef);

                modAssembly.Write(dllPath);
                modAssembly.Dispose();
                vigoDef.Dispose();

                File.Copy(dllPath, tempFile, true);

                // We're going to re-assemble the mod file; to do this we need to find out which
                //  .NET assembler to use (version is important)
                Version assemblerVersion = Util.GetFrameworkVer(dllPath);

                // Disassemble and extract any embedded resource files we can find.
                string disassembled = VortexHarmonyInstaller.Util.Disassembler.DisassembleFile(tempFile, true);

                // Find the reference id for VIGO within the assembly, we're
                //  going to use this value to replace the existing UMM refId.
                string pattern = @"(.assembly extern )(\/.*\/)( VortexUnity)";
                string refId   = Regex.Match(disassembled, pattern).Groups[2].Value;

                // UMM distributes 2 nearly identical Harmony assemblies
                //  one which seems to reference GAC assemblies directly (Harmony12),
                //  and the normally distributed assembly which will look for assemlies
                //  locally before resorting to GAC (An optimization?)
                //  Either way, we're going to use the assembly we distribute instead and
                //  remove Harmony12 if we find it.
                disassembled = disassembled.Replace("Harmony12", "Harmony");

                // This is one UGLY pattern but will have to do in the meantime.
                //  We use regex to find all UI calls which will now point to VortexHarmonyInstaller
                //  as we replaced the UMM reference, and re-point the instruction to VortexUnity
                //  TODO: There must be a better way of doing this - more research is needed.
                pattern          = @"(VortexHarmonyInstaller)(\/\*.*?\*\/)(\]UnityModManagerNet\.UnityModManager\/\*.*?\*\/\/UI)";
                disassembled     = Regex.Replace(disassembled, pattern, m => vigoName + refId + m.Groups[3].Value);
                instructionsFile = tempFile + Constants.IL_EXT;

                // Write the data to an IL file and delete the current dll file
                //  as we want to replace it. We backed up this file earlier so we should be fine.
                File.WriteAllText(instructionsFile, disassembled);
                File.Delete(dllPath);

                // Generate the new Assembly!
                VortexHarmonyInstaller.Util.Assembler.AssembleFile(instructionsFile, dllPath, assemblerVersion);

                // Ensure that the mod is aware of its assembly.
                m_ModAssembly = Assembly.LoadFile(dllPath);
                VortexPatcher.Logger.Info($"Assembly {Path.GetFileName(dllPath)} converted successfully.");
                return(true);
            }
            catch (Exceptions.AssemblyIsInjectedException)
            {
                // We already dealt with this mod, no need to hijack its calls again.
                VortexPatcher.Logger.Info($"Assembly {Path.GetFileName(dllPath)} is already patched.");
                return(true);
            }
            catch (Exception exc)
            {
                Util.RestoreBackup(dllPath);
                VortexPatcher.Logger.Error("Assembly conversion failed", exc);
                return(false);
            }
            finally
            {
                // Cleanup
                AssemblyDefinition modAssembly = AssemblyDefinition.ReadAssembly(tempFile);
                if (modAssembly.MainModule.HasResources)
                {
                    Resource[] resources = modAssembly.MainModule.Resources.Where(res => res.ResourceType == ResourceType.Embedded).ToArray();
                    foreach (Resource res in resources)
                    {
                        string possiblePath = Path.Combine(Path.GetDirectoryName(dllPath), res.Name);
                        if (File.Exists(possiblePath))
                        {
                            File.Delete(possiblePath);
                        }
                    }
                }

                modAssembly.Dispose();
                modAssembly = null;

                // We have no guarantee that the file reference has been released yet
                //  but we can try to delete anyway.
                Util.TryDelete(tempFile);

                if ((instructionsFile != null) && (File.Exists(instructionsFile)))
                {
                    Util.TryDelete(instructionsFile);
                }
            }
        }
示例#5
0
        public TypeReference FixPlatformVersion(TypeReference reference)
        {
            if (targetPlatformDirectory == null)
            {
                return(reference);
            }

            AssemblyNameReference scopeAsm = reference.Scope as AssemblyNameReference;

            if (scopeAsm != null)
            {
                AssemblyDefinition platformAsm = TryGetPlatformAssembly(scopeAsm);
                if (platformAsm != null)
                {
                    TypeReference newTypeRef;
                    if (reference is TypeSpecification)
                    {
                        TypeSpecification refSpec = reference as TypeSpecification;
                        TypeReference     fet     = FixPlatformVersion(refSpec.ElementType);
                        if (reference is ArrayType)
                        {
                            var array          = (ArrayType)reference;
                            var imported_array = new ArrayType(fet);
                            if (array.IsVector)
                            {
                                return(imported_array);
                            }

                            var dimensions          = array.Dimensions;
                            var imported_dimensions = imported_array.Dimensions;

                            imported_dimensions.Clear();

                            for (int i = 0; i < dimensions.Count; i++)
                            {
                                var dimension = dimensions[i];

                                imported_dimensions.Add(new ArrayDimension(dimension.LowerBound, dimension.UpperBound));
                            }

                            return(imported_array);
                        }
                        else if (reference is PointerType)
                        {
                            return(new PointerType(fet));
                        }
                        else if (reference is ByReferenceType)
                        {
                            return(new ByReferenceType(fet));
                        }
                        else if (reference is PinnedType)
                        {
                            return(new PinnedType(fet));
                        }
                        else if (reference is SentinelType)
                        {
                            return(new SentinelType(fet));
                        }
                        else if (reference is OptionalModifierType)
                        {
                            return(new OptionalModifierType(FixPlatformVersion(((OptionalModifierType)reference).ModifierType), fet));
                        }
                        else if (reference is RequiredModifierType)
                        {
                            return(new RequiredModifierType(FixPlatformVersion(((RequiredModifierType)reference).ModifierType), fet));
                        }
                        else if (reference is GenericInstanceType)
                        {
                            var instance          = (GenericInstanceType)reference;
                            var element_type      = FixPlatformVersion(instance.ElementType);
                            var imported_instance = new GenericInstanceType(element_type);

                            var arguments          = instance.GenericArguments;
                            var imported_arguments = imported_instance.GenericArguments;

                            for (int i = 0; i < arguments.Count; i++)
                            {
                                imported_arguments.Add(FixPlatformVersion(arguments[i]));
                            }

                            return(imported_instance);
                        }
                        else if (reference is FunctionPointerType)
                        {
                            throw new NotImplementedException();
                        }
                        else
                        {
                            throw new InvalidOperationException();
                        }
                    }
                    else
                    {
                        newTypeRef = new TypeReference(reference.Namespace, reference.Name, reference.Module,
                                                       platformAsm.Name);
                    }
                    foreach (var gp in reference.GenericParameters)
                    {
                        newTypeRef.GenericParameters.Add(FixPlatformVersion(gp, newTypeRef));
                    }
                    newTypeRef.IsValueType = reference.IsValueType;
                    if (reference.DeclaringType != null)
                    {
                        newTypeRef.DeclaringType = FixPlatformVersion(reference.DeclaringType);
                    }
                    return(newTypeRef);
                }
            }
            return(reference);
        }
示例#6
0
        /*********
        ** Public methods
        *********/
        /// <summary>Construct an instance.</summary>
        /// <param name="targetPlatform">The target game platform.</param>
        /// <param name="removeAssemblyNames">The assembly short names to remove (like <c>Stardew Valley</c>).</param>
        /// <param name="targetAssemblies">The assemblies to target.</param>
        public PlatformAssemblyMap(Platform targetPlatform, string[] removeAssemblyNames, Assembly[] targetAssemblies)
        {
            // save data
            this.TargetPlatform = targetPlatform;
            this.RemoveNames    = removeAssemblyNames;

            // cache assembly metadata
            this.Targets          = targetAssemblies;
            this.TargetReferences = this.Targets.ToDictionary(assembly => assembly, assembly => AssemblyNameReference.Parse(assembly.FullName));
            this.TargetModules    = this.Targets.ToDictionary(assembly => assembly, assembly => ModuleDefinition.ReadModule(assembly.Modules.Single().FullyQualifiedName));
        }
示例#7
0
        /// <summary>
        /// Based on the closure, get a table of ideal remappings needed to 
        /// produce zero conflicts.
        /// </summary>
        internal void ResolveConflicts
        (
            out DependentAssembly[] idealRemappings,
            out AssemblyNameReference[] conflictingReferences
        )
        {
            idealRemappings = null;
            conflictingReferences = null;

            // First, resolve all conflicts between references.
            if (0 == ResolveConflictsBetweenReferences())
            {
                // If there were no basename conflicts then there can be no version-to-version conflicts.
                // In this case, short-circuit now rather than building up all the tables below.
                return;
            }

            // Build two tables, one with a count and one with the corresponding references.
            // Dependencies which differ only by version number need a suggested redirect.
            // The count tells us whether there are two or more.
            Hashtable counts = new Hashtable(StringComparer.OrdinalIgnoreCase);
            Hashtable references = new Hashtable(StringComparer.OrdinalIgnoreCase);

            foreach (AssemblyNameExtension assemblyName in References.Keys)
            {
                Reference reference = GetReference(assemblyName);

                // If the assembly has a parent which has specific version set to true then we need to see if it is framework assembly
                if (reference.CheckForSpecificVersionMetadataOnParentsReference(true))
                {
                    // Try and find an entry in the redist list by comparing everything except the version.
                    AssemblyEntry entry = null;

                    if (_installedAssemblies != null)
                    {
                        entry = _installedAssemblies.FindHighestVersionInRedistList(assemblyName);
                    }

                    if (entry != null)
                    {
                        // We have found an entry in the redist list that this assembly is a framework assembly of some version
                        // also one if its parent refernces has specific version set to true, therefore we need to make sure
                        // that we do not consider it for conflict resolution.
                        continue;
                    }
                }

                byte[] pkt = assemblyName.GetPublicKeyToken();
                if (pkt != null && pkt.Length > 0)
                {
                    AssemblyName baseKey = (AssemblyName)assemblyName.AssemblyName.Clone();
                    Version version = baseKey.Version;
                    baseKey.Version = null;
                    string key = baseKey.ToString();

                    if (counts.ContainsKey(key))
                    {
                        counts[key] = ((int)counts[key]) + 1;
                        Version lastVersion = ((AssemblyNameReference)references[key]).assemblyName.Version;

                        if (lastVersion == null || lastVersion < version)
                        {
                            references[key] = AssemblyNameReference.Create(assemblyName, reference);
                        }
                    }
                    else
                    {
                        counts[key] = 1;
                        references[key] = AssemblyNameReference.Create(assemblyName, reference);
                    }
                }
            }

            // Build the list of conflicted assemblies.
            List<AssemblyNameReference> assemblyNamesList = new List<AssemblyNameReference>();
            foreach (string versionLessAssemblyName in counts.Keys)
            {
                if (((int)counts[versionLessAssemblyName]) > 1)
                {
                    assemblyNamesList.Add((AssemblyNameReference)references[versionLessAssemblyName]);
                }
            }

            // Pass over the list of conflicting references and make a binding redirect for each.
            List<DependentAssembly> idealRemappingsList = new List<DependentAssembly>();

            foreach (AssemblyNameReference assemblyNameReference in assemblyNamesList)
            {
                DependentAssembly remapping = new DependentAssembly();
                remapping.PartialAssemblyName = assemblyNameReference.assemblyName.AssemblyName;
                BindingRedirect bindingRedirect = new BindingRedirect();
                bindingRedirect.OldVersionLow = new Version("0.0.0.0");
                bindingRedirect.OldVersionHigh = assemblyNameReference.assemblyName.AssemblyName.Version;
                bindingRedirect.NewVersion = assemblyNameReference.assemblyName.AssemblyName.Version;
                remapping.BindingRedirects = new BindingRedirect[] { bindingRedirect };

                idealRemappingsList.Add(remapping);
            }

            idealRemappings = idealRemappingsList.ToArray();
            conflictingReferences = assemblyNamesList.ToArray();
        }
示例#8
0
文件: Script.cs 项目: jthelin/Nake
        public void AddReference(AssemblyNameReference reference)
        {
            if (DefaultReferences.ContainsKey(reference.AssemblyName))
                return;

            string fullPath;
            if (!GAC.AssemblyExist(reference.AssemblyName, out fullPath))
                throw new NakeException(
                    "Assembly reference {0} defined in script {1} cannot be found",
                    reference.AssemblyName, reference.ScriptFile);

            AddReference(new MetadataFileReference(fullPath));
        }
 public AssemblyDefinition Resolve(AssemblyNameReference name, ReaderParameters parameters)
 {
     return(null);
 }
示例#10
0
 public AssemblyDefinition Resolve(AssemblyNameReference name)
 {
     return(null);
 }
示例#11
0
        public override AssemblyDefinition Resolve(AssemblyNameReference name, ReaderParameters parameters)
        {
            // Try list of references
            foreach (var reference in references)
            {
                if (string.Compare(Path.GetFileNameWithoutExtension(reference), name.Name, StringComparison.OrdinalIgnoreCase) == 0 && File.Exists(reference))
                {
                    return(GetAssembly(reference, parameters));
                }
            }

            if (WindowsKitsReferenceDirectory != null)
            {
                if (existingWindowsKitsReferenceAssemblies == null)
                {
                    // First time, make list of existing assemblies in windows kits directory
                    existingWindowsKitsReferenceAssemblies = new HashSet <string>();

                    try
                    {
                        foreach (var directory in Directory.EnumerateDirectories(WindowsKitsReferenceDirectory))
                        {
                            existingWindowsKitsReferenceAssemblies.Add(Path.GetFileName(directory));
                        }
                    }
                    catch (Exception)
                    {
                    }
                }

                // Look for this assembly in the windows kits directory
                if (existingWindowsKitsReferenceAssemblies.Contains(name.Name))
                {
                    var assemblyFile = Path.Combine(WindowsKitsReferenceDirectory, name.Name, name.Version.ToString(), name.Name + ".winmd");
                    if (File.Exists(assemblyFile))
                    {
                        if (parameters.AssemblyResolver == null)
                        {
                            parameters.AssemblyResolver = this;
                        }

                        return(ModuleDefinition.ReadModule(assemblyFile, parameters).Assembly);
                    }
                }
            }

            if (parameters == null)
            {
                parameters = new ReaderParameters();
            }

            try
            {
                // Check .winmd files as well
                var assembly = SearchDirectoryExtra(name, GetSearchDirectories(), parameters);
                if (assembly != null)
                {
                    return(assembly);
                }

                return(base.Resolve(name, parameters));
            }
            catch (AssemblyResolutionException)
            {
                // Check cache again, ignoring version numbers this time
                foreach (var assembly in cache)
                {
                    if (assembly.Value.Name.Name == name.Name)
                    {
                        return(assembly.Value);
                    }
                }
                throw;
            }
        }
示例#12
0
 /// <summary>
 /// Determines if two assembly name references matches
 /// </summary>
 /// <param name="anref1">an assembly name reference</param>
 /// <param name="anref2">an assembly name reference to compare</param>
 /// <returns>true if matches</returns>
 public static bool ReferenceMatches(AssemblyNameReference anref1, AssemblyNameReference anref2)
 {
     // Skip Key
     return((anref1.Name == anref2.Name) && (anref1.Version.ToString(2).CompareTo(anref2.Version.ToString(2)) == 0) && (anref1.Culture == anref2.Culture));
 }
示例#13
0
 public override AssemblyDefinition Resolve(AssemblyNameReference name)
 {
     throw new NotImplementedException();
 }
示例#14
0
        /// <summary>
        ///
        /// We try to manually load assembly.
        /// To work test project needs to use
        ///
        /// <PropertyGroup>
        ///     <PreserveCompilationContext>true</PreserveCompilationContext>
        /// </PropertyGroup>
        ///
        /// Runtime configuration file doc https://github.com/dotnet/cli/blob/master/Documentation/specs/runtime-configuration-file.md
        ///
        /// </summary>
        internal AssemblyDefinition TryWithCustomResolverOnDotNetCore(AssemblyNameReference name)
        {
            _logger.LogVerbose($"TryWithCustomResolverOnDotNetCore for {name}");

            if (!IsDotNetCore())
            {
                _logger.LogVerbose($"Not a dotnet core app");
                return(null);
            }

            if (string.IsNullOrEmpty(_modulePath))
            {
                throw new AssemblyResolutionException(name);
            }

            using DependencyContextJsonReader contextJsonReader = new DependencyContextJsonReader();
            Dictionary <string, Lazy <AssemblyDefinition> > libraries = new Dictionary <string, Lazy <AssemblyDefinition> >();

            foreach (string fileName in Directory.GetFiles(Path.GetDirectoryName(_modulePath), "*.deps.json"))
            {
                using FileStream depsFile = File.OpenRead(fileName);
                _logger.LogVerbose($"Loading {fileName}");
                DependencyContext dependencyContext = contextJsonReader.Read(depsFile);
                foreach (CompilationLibrary library in dependencyContext.CompileLibraries)
                {
                    // we're interested only on nuget package
                    if (library.Type == "project")
                    {
                        continue;
                    }

                    try
                    {
                        string path = library.ResolveReferencePaths(_compositeResolver.Value).FirstOrDefault();
                        if (string.IsNullOrEmpty(path))
                        {
                            continue;
                        }

                        // We could load more than one deps file, we need to check if lib is already found
                        if (!libraries.ContainsKey(library.Name))
                        {
                            libraries.Add(library.Name, new Lazy <AssemblyDefinition>(() => AssemblyDefinition.ReadAssembly(path, new ReaderParameters()
                            {
                                AssemblyResolver = this
                            })));
                        }
                    }
                    catch (Exception ex)
                    {
                        // if we don't find a lib go on
                        _logger.LogVerbose($"TryWithCustomResolverOnDotNetCore exception: {ex.ToString()}");
                    }
                }
            }

            if (libraries.TryGetValue(name.Name, out Lazy <AssemblyDefinition> asm))
            {
                return(asm.Value);
            }

            throw new CecilAssemblyResolutionException($"AssemblyResolutionException for '{name}'. Try to add <PreserveCompilationContext>true</PreserveCompilationContext> to test projects </PropertyGroup> or pass '/p:CopyLocalLockFileAssemblies=true' option to the 'dotnet test' command-line", new AssemblyResolutionException(name));
        }
示例#15
0
 public AssemblyDefinition Resolve(AssemblyNameReference name, ReaderParameters parameters)
 {
     var node = parent.LookupReferencedAssembly(name);
     return node != null ? node.AssemblyDefinition : null;
 }
 public AssemblyDefinition Resolve(string fullName, ReaderParameters parameters)
 {
     return(Resolve(AssemblyNameReference.Parse(fullName), parameters));
 }
 internal void ResolveConflicts(out DependentAssembly[] idealRemappings, out AssemblyNameReference[] conflictingReferences)
 {
     idealRemappings = null;
     conflictingReferences = null;
     if (this.ResolveConflictsBetweenReferences() != 0)
     {
         Hashtable hashtable = new Hashtable(StringComparer.OrdinalIgnoreCase);
         Hashtable hashtable2 = new Hashtable(StringComparer.OrdinalIgnoreCase);
         foreach (AssemblyNameExtension extension in this.References.Keys)
         {
             Reference reference = this.GetReference(extension);
             if (reference.CheckForSpecificVersionMetadataOnParentsReference(true))
             {
                 AssemblyEntry entry = null;
                 if (this.installedAssemblies != null)
                 {
                     entry = this.installedAssemblies.FindHighestVersionInRedistList(extension);
                 }
                 if (entry != null)
                 {
                     continue;
                 }
             }
             byte[] publicKeyToken = extension.GetPublicKeyToken();
             if ((publicKeyToken != null) && (publicKeyToken.Length > 0))
             {
                 AssemblyName name = (AssemblyName) extension.AssemblyName.Clone();
                 Version version = name.Version;
                 name.Version = null;
                 string key = name.ToString();
                 if (hashtable.ContainsKey(key))
                 {
                     hashtable[key] = ((int) hashtable[key]) + 1;
                     Version version2 = ((AssemblyNameReference) hashtable2[key]).assemblyName.Version;
                     if ((version2 == null) || (version2 < version))
                     {
                         hashtable2[key] = AssemblyNameReference.Create(extension, reference);
                     }
                 }
                 else
                 {
                     hashtable[key] = 1;
                     hashtable2[key] = AssemblyNameReference.Create(extension, reference);
                 }
             }
         }
         List<AssemblyNameReference> list = new List<AssemblyNameReference>();
         foreach (string str2 in hashtable.Keys)
         {
             if (((int) hashtable[str2]) > 1)
             {
                 list.Add((AssemblyNameReference) hashtable2[str2]);
             }
         }
         List<DependentAssembly> list2 = new List<DependentAssembly>();
         foreach (AssemblyNameReference reference2 in list)
         {
             DependentAssembly item = new DependentAssembly {
                 PartialAssemblyName = reference2.assemblyName.AssemblyName
             };
             BindingRedirect redirect = new BindingRedirect {
                 OldVersionLow = new Version("0.0.0.0"),
                 OldVersionHigh = reference2.assemblyName.AssemblyName.Version,
                 NewVersion = reference2.assemblyName.AssemblyName.Version
             };
             item.BindingRedirects = new BindingRedirect[] { redirect };
             list2.Add(item);
         }
         idealRemappings = list2.ToArray();
         conflictingReferences = list.ToArray();
     }
 }
示例#18
0
        /// <summary>
        ///     A string extension method that queries if 'reference' is a Microsoft assembly.
        /// </summary>
        /// <param name="reference">
        ///     The reference.
        /// </param>
        /// <returns>
        ///     true if microsoft assembly, false if not.
        /// </returns>

        public static bool IsMicrosoftAssembly(this AssemblyNameReference
                                               reference)
        {
            return(reference.Name.IsMicrosoftAssembly());
        }
        /// <summary>
        /// Populates the suggested redirects output parameter.
        /// </summary>
        /// <param name="idealAssemblyRemappings">The list of ideal remappings.</param>
        /// <param name="idealAssemblyRemappedReferences">The list of of references to ideal assembly remappings.</param>
        private void PopulateSuggestedRedirects(DependentAssembly[] idealAssemblyRemappings, AssemblyNameReference[] idealAssemblyRemappedReferences)
        {
            ArrayList holdSuggestedRedirects = new ArrayList();
            if (idealAssemblyRemappings != null)
            {
                for (int i = 0; i < idealAssemblyRemappings.Length; i++)
                {
                    DependentAssembly idealRemapping = idealAssemblyRemappings[i];
                    string itemSpec = idealRemapping.PartialAssemblyName.ToString();

                    Reference reference = idealAssemblyRemappedReferences[i].reference;
                    AssemblyNameExtension[] conflictVictims = reference.GetConflictVictims();

                    // Skip any remapping that has no conflict victims since a redirect will not help.
                    if (null == conflictVictims || 0 == conflictVictims.Length)
                    {
                        continue;
                    }

                    for (int j = 0; j < idealRemapping.BindingRedirects.Length; j++)
                    {
                        ITaskItem suggestedRedirect = new TaskItem();
                        suggestedRedirect.ItemSpec = itemSpec;
                        suggestedRedirect.SetMetadata("MaxVersion", idealRemapping.BindingRedirects[j].NewVersion.ToString());
                        holdSuggestedRedirects.Add(suggestedRedirect);
                    }
                }
            }
            _suggestedRedirects = (ITaskItem[])holdSuggestedRedirects.ToArray(typeof(ITaskItem));
        }
示例#20
0
        AssemblyDefinition IAssemblyResolver.Resolve(AssemblyNameReference name, ReaderParameters parameters)
        {
            var loader = widget.AddReferenceByAssemblyName(name);

            return(loader != null ? loader.Assembly : null);
        }
示例#21
0
 public LoadedAssembly LookupReferencedAssembly(AssemblyNameReference name)
 {
     if (name == null)
         throw new ArgumentNullException("name");
     if (name.IsWindowsRuntime)
     {
         return assemblyList.winRTMetadataLookupCache.GetOrAdd(name.Name, LookupWinRTMetadata);
     }
     else
     {
         return assemblyList.assemblyLookupCache.GetOrAdd(name.FullName, LookupReferencedAssemblyInternal);
     }
 }
示例#22
0
            public AssemblyDefinition Resolve(AssemblyNameReference name, ReaderParameters parameters)
            {
                var node = parent.LookupReferencedAssembly(name);

                return(node != null?node.GetAssemblyDefinitionAsync().Result : null);
            }
示例#23
0
        //Send solutionName ,domain name, eod creation date
        static void Main(String[] args)
        {
            String solutionName    = args[0];
            String eodCreationDate = args[1];
            String domainName      = args[2];


            Console.WriteLine("Solution Name:" + solutionName + " Domain Name:" + domainName + " EOD creation Date is:" + eodCreationDate);

            const string source_directory = @""; //add the directory path of dll to be injected
            const string backup           = @""; //add directory path location to create back up of dll
            const string senderfile       = @""; //add dll file that needs to be referenced.This can be a dll that runs your own code.
            const string log_file         = @""; //log file path

            string json;
            string sourcefile;
            string source;
            var    sender_method = (dynamic)null;

            Int32 count = 10;

            char[] pspearator = { ' ', '/', '.' };
            char[] spearator  = { ' ', ':', '(', ')' };

            Formatter format = new Formatter();

            //call the service and get the json with data of files to be injected
            using (TimeoutWebClient wc = new TimeoutWebClient())
            {
                json = wc.DownloadString(""); // This block just downloads a file containg method names which need to be injected.
            }
            RootObject r = JsonConvert.DeserializeObject <RootObject>(json);

            //load ATSsenderfile
            AssemblyDefinition Sender_assembly = AssemblyDefinition.ReadAssembly(senderfile, new ReaderParameters {
                ReadWrite = true
            });
            var Sender_module = Sender_assembly.MainModule;

            TypeDefinition[] sender_types = Sender_module.Types.ToArray();

            var resolver = new DefaultAssemblyResolver();

            resolver.AddSearchDirectory(source_directory);

            //load refrence to the send fucntion of sender dll
            foreach (var type in sender_types)
            {
                foreach (var method in type.Methods)
                {
                    if (method.Name == "send")
                    {
                        sender_method = method;
                    }
                }
            }


            foreach (Project projects in r.projects)
            {
                Console.WriteLine("Instrumentation Started......");
                sourcefile = source_directory + projects.endStateName;
                source     = projects.endStateName;


                if (File.Exists(sourcefile))
                {
                    //create backup of the source DLL
                    File.Copy(sourcefile, backup + Path.GetFileName(source)); // handle exception dude to this folder and files inside // after coping the dll is renamed with diffrent casing.

                    //load DLL reference
                    AssemblyDefinition assembly = AssemblyDefinition.ReadAssembly(sourcefile, new ReaderParameters {
                        ReadWrite = true, AssemblyResolver = resolver
                    });
                    var module             = assembly.MainModule;
                    TypeDefinition[] types = module.GetTypes().ToArray();

                    foreach (Files dll in projects.files) // this loop is used to inject the dll reference in the start of a method and pass the method name and the varible name and type used in the method.
                    {
                        foreach (class_name clas in dll.classes)
                        {
                            //gives class name
                            foreach (var type in types)
                            {
                                string[] splitClassName  = type.ToString().Split('.');
                                string   clsName         = splitClassName[splitClassName.Length - 1];
                                string   clsNameFromFile = "";

                                //This change is to support instrumentation both before or after separation of classname and namespace
                                if (clas.className != null)
                                {
                                    string[] splitClassNameFromFile = clas.className.Split('.');
                                    clsNameFromFile = splitClassNameFromFile[splitClassNameFromFile.Length - 1];
                                }


                                //check if if we require this class to be injected
                                if (clsName == clsNameFromFile)
                                {
                                    Console.WriteLine(type.ToString());

                                    foreach (var method in type.Methods)
                                    {
                                        try
                                        {
                                            string methodname = method.FullName.ToString();

                                            Console.WriteLine(methodname);
                                            //Ignore setters and getters
                                            if (!method.IsGetter && !method.IsSetter)
                                            {
                                                string variable = "";
                                                //find all arguments
                                                foreach (var Param in method.Parameters)
                                                {
                                                    string parameter_type = Param.ParameterType.ToString();
                                                    //In case of generic this garbage value gets appended
                                                    parameter_type = parameter_type.Replace("`1", "");

                                                    string variable_type = "";
                                                    //This implementation is specfic to Generic in variable type e.g Memlib<MainModule.usrdefMainOrder> nSourceTable
                                                    if (parameter_type.Contains("<") && parameter_type.Contains(">"))
                                                    {
                                                        String[] list    = parameter_type.Split('<');
                                                        string   pre     = list[0];
                                                        string   post    = list[1];
                                                        String[] preList = pre.Split(pspearator, count);
                                                        pre = preList[preList.Count() - 1];
                                                        String[] postList = post.Split(pspearator, count);
                                                        post          = postList[postList.Count() - 1];
                                                        variable_type = pre + " <" + post;
                                                    }
                                                    else
                                                    {
                                                        String[] parameter_list = parameter_type.Split(pspearator, count);
                                                        variable_type = parameter_list[parameter_list.Count() - 1];
                                                    }
                                                    variable_type = variable_parser(variable_type);
                                                    var param_name = Param.Name;
                                                    if (Param.HasConstant)
                                                    {
                                                        param_name = param_name + " = " + Param.Constant;
                                                    }
                                                    variable_type = variable_type + " " + param_name + ", ";
                                                    variable      = variable + variable_type;
                                                }

                                                // Removing comma and space
                                                if (variable.Length > 2)
                                                {
                                                    variable = variable.Remove(variable.Length - 1);
                                                    variable = variable.Remove(variable.Length - 1);
                                                }
                                                String[] strlist = methodname.Split(spearator, count);

                                                string final;
                                                string signature = format.Format("(" + variable + ")");
                                                //string signature = "(" + variable + ")";
                                                string[] nameSpaceAndClassName = type.ToString().Split('.');
                                                string   clazz      = nameSpaceAndClassName[nameSpaceAndClassName.Length - 1];
                                                string   nameSpace_ = type.ToString().Replace("." + clazz, "");
                                                final = strlist[3] + ';' + type.ToString() + ';' + dll.fileName + ';' + source + ";" + signature;
                                                string methodName = strlist[3];

                                                // for constructors
                                                final = methodName + ';' + clazz + ';' + nameSpace_ + ';' + dll.fileName + ';' + source + ";" + signature;


                                                //injection log
                                                File.AppendAllText(log_file, final + Environment.NewLine);

                                                //load IL processor
                                                var processor2 = method.Body.GetILProcessor();
                                                var call       = processor2.Create(OpCodes.Call, method.Module.Import(sender_method));
                                                var ldstr      = processor2.Create(OpCodes.Ldstr, final);

                                                //Inject the code
                                                processor2.InsertBefore(method.Body.Instructions[0], ldstr);
                                                processor2.InsertAfter(method.Body.Instructions[0], call);

                                                //Console.WriteLine("Successfully Injected:" + source);
                                                Console.WriteLine("-----------------------------------------------------------------------------------------------");
                                            }
                                        }
                                        catch (Exception e)
                                        {
                                            File.AppendAllText(log_file, e + Environment.NewLine);
                                        }
                                    } //before the try
                                }
                            }
                        }
                    }
                    //write back the new Injected source file
                    assembly.MainModule.AssemblyReferences.Add(AssemblyNameReference.Parse(Sender_assembly.FullName));
                    assembly.Write();
                    Console.WriteLine("--- Finished Injecting DLL ---");
                }
                else
                {
                    Console.WriteLine("");
                }
                //Console.WriteLine(sourcefile + " doesnt exsit in cerner directory");
            }
            Console.ReadLine();
        }
示例#24
0
        private string ResolveI18nAssembly(string name)
        {
            var assembly = resolver.Resolve(AssemblyNameReference.Parse(name));

            return(assembly.MainModule.FullyQualifiedName);
        }
示例#25
0
 static AssemblyNameReference GetAssemblyName(XPathNavigator nav)
 {
     return(AssemblyNameReference.Parse(GetAttribute(nav, "fullname")));
 }
示例#26
0
 protected virtual AssemblyNameReference GetAssemblyName(XPathNavigator nav)
 {
     return(AssemblyNameReference.Parse(GetFullName(nav)));
 }
示例#27
0
 public AssemblyDefinition Resolve(AssemblyNameReference reference)
 {
     return(Resolve(reference, new ReaderParameters {
         AssemblyResolver = this
     }));
 }
示例#28
0
 public static void RemoveStrongNameReference(AssemblyNameReference andef)
 {
     andef.PublicKeyToken = new byte[0];
 }
示例#29
0
 public AssemblyNameReference ImportReference(AssemblyNameReference reference)
 {
     return(this.defaultMetadataImporter.ImportReference(reference));
 }
示例#30
0
 private TypeDefinition FindTypeInUnknownWinmd(AssemblyNameReference assemblyNameReference, TypeReference type)
 {
     if (< > f__am$cache0 == null)
     {
 public AssemblyDefinition Resolve(AssemblyNameReference name)
 {
     return(Resolve(name, parameters));
 }
示例#32
0
 private NetAssembly CreateAssemblyModel(AssemblyNameReference assemblyReference)
 {
     return(Factory.CreateAssemblyModel(assemblyReference));
 }
 private static int ResolveAssemblyNameConflict(AssemblyNameReference assemblyReference0, AssemblyNameReference assemblyReference1)
 {
     int index = 0;
     Microsoft.Build.Shared.ErrorUtilities.VerifyThrow(assemblyReference0.assemblyName.FullName != null, "Got a null assembly name fullname. (0)");
     Microsoft.Build.Shared.ErrorUtilities.VerifyThrow(assemblyReference1.assemblyName.FullName != null, "Got a null assembly name fullname. (1)");
     string[] strArray = new string[] { assemblyReference0.assemblyName.FullName, assemblyReference1.assemblyName.FullName };
     Reference[] referenceArray = new Reference[] { assemblyReference0.reference, assemblyReference1.reference };
     AssemblyNameExtension[] extensionArray = new AssemblyNameExtension[] { assemblyReference0.assemblyName, assemblyReference1.assemblyName };
     bool[] flagArray = new bool[] { assemblyReference0.reference.IsPrimary, assemblyReference1.reference.IsPrimary };
     if (referenceArray[0].IsPrimary && referenceArray[1].IsPrimary)
     {
         flagArray[0] = false;
         flagArray[1] = false;
     }
     bool pfEquivalent = false;
     Microsoft.Build.Tasks.NativeMethods.AssemblyComparisonResult pResult = Microsoft.Build.Tasks.NativeMethods.AssemblyComparisonResult.ACR_Unknown;
     Microsoft.Build.Tasks.NativeMethods.CompareAssemblyIdentity(strArray[0], flagArray[0], strArray[1], flagArray[1], out pfEquivalent, out pResult);
     index = 0;
     ConflictLossReason insolubleConflict = ConflictLossReason.InsolubleConflict;
     if (referenceArray[0].IsPrimary && !referenceArray[1].IsPrimary)
     {
         index = 1;
         insolubleConflict = ConflictLossReason.WasNotPrimary;
     }
     else if (!referenceArray[0].IsPrimary && referenceArray[1].IsPrimary)
     {
         index = 0;
         insolubleConflict = ConflictLossReason.WasNotPrimary;
     }
     else if (!referenceArray[0].IsPrimary && !referenceArray[1].IsPrimary)
     {
         if (((extensionArray[0].Version != null) && (extensionArray[1].Version != null)) && (extensionArray[0].Version > extensionArray[1].Version))
         {
             index = 1;
             if (pfEquivalent)
             {
                 insolubleConflict = ConflictLossReason.HadLowerVersion;
             }
         }
         else if (((extensionArray[0].Version != null) && (extensionArray[1].Version != null)) && (extensionArray[0].Version < extensionArray[1].Version))
         {
             index = 0;
             if (pfEquivalent)
             {
                 insolubleConflict = ConflictLossReason.HadLowerVersion;
             }
         }
         else
         {
             index = 0;
             if (pfEquivalent)
             {
                 insolubleConflict = ConflictLossReason.FusionEquivalentWithSameVersion;
             }
         }
     }
     int num2 = 1 - index;
     referenceArray[index].ConflictVictorName = extensionArray[num2];
     referenceArray[index].ConflictLossExplanation = insolubleConflict;
     referenceArray[num2].AddConflictVictim(extensionArray[index]);
     return index;
 }
示例#34
0
 public GacEntry(AssemblyNameReference r, string fileName)
 {
     this.r        = r;
     this.fileName = fileName;
 }
 public AssemblyLinkedResource(string name, ManifestResourceAttributes flags,
     AssemblyNameReference asmRef)
     : base(name, flags)
 {
     m_asmRef = asmRef;
 }
示例#36
0
 public AssemblyDefinition Resolve(AssemblyNameReference name, ReaderParameters parameters)
 {
     throw new NotImplementedException();
 }
 private bool LogResults(ReferenceTable dependencyTable, DependentAssembly[] idealAssemblyRemappings, AssemblyNameReference[] idealAssemblyRemappingsIdentities, ArrayList generalResolutionExceptions)
 {
     bool flag = true;
     using (new CodeMarkerStartEnd(CodeMarkerEvent.perfMSBuildRARLogResultsBegin, CodeMarkerEvent.perfMSBuildRARLogResultsEnd))
     {
         if (this.Silent)
         {
             return flag;
         }
         foreach (AssemblyNameExtension extension in dependencyTable.References.Keys)
         {
             string fullName = extension.FullName;
             Reference reference = dependencyTable.GetReference(extension);
             if (reference.IsPrimary && (!reference.IsConflictVictim || !reference.IsCopyLocal))
             {
                 this.LogReference(reference, fullName);
             }
         }
         foreach (AssemblyNameExtension extension2 in dependencyTable.References.Keys)
         {
             string fusionName = extension2.FullName;
             Reference reference2 = dependencyTable.GetReference(extension2);
             if (!reference2.IsPrimary && (!reference2.IsConflictVictim || !reference2.IsCopyLocal))
             {
                 this.LogReference(reference2, fusionName);
             }
         }
         foreach (AssemblyNameExtension extension3 in dependencyTable.References.Keys)
         {
             string str3 = extension3.FullName;
             Reference reference3 = dependencyTable.GetReference(extension3);
             if (reference3.IsConflictVictim)
             {
                 this.LogConflict(reference3, str3);
                 Reference conflictCandidate = dependencyTable.GetReference(reference3.ConflictVictorName);
                 this.LogReferenceDependenciesAndSourceItems(reference3.ConflictVictorName.FullName, conflictCandidate);
                 this.LogReferenceDependenciesAndSourceItems(str3, reference3);
             }
         }
         if (this.suggestedRedirects.Length > 0)
         {
             for (int i = 0; i < idealAssemblyRemappings.Length; i++)
             {
                 DependentAssembly assembly = idealAssemblyRemappings[i];
                 AssemblyName partialAssemblyName = assembly.PartialAssemblyName;
                 Reference reference5 = idealAssemblyRemappingsIdentities[i].reference;
                 for (int j = 0; j < assembly.BindingRedirects.Length; j++)
                 {
                     foreach (AssemblyNameExtension extension4 in reference5.GetConflictVictims())
                     {
                         Reference reference6 = dependencyTable.GetReference(extension4);
                         base.Log.LogMessageFromResources(MessageImportance.High, "ResolveAssemblyReference.ConflictRedirectSuggestion", new object[] { partialAssemblyName, extension4.Version, reference6.FullPath, assembly.BindingRedirects[j].NewVersion, reference5.FullPath });
                     }
                 }
             }
             base.Log.LogWarningWithCodeFromResources("ResolveAssemblyReference.SuggestedRedirects", new object[0]);
         }
         foreach (Exception exception in generalResolutionExceptions)
         {
             if (!(exception is InvalidReferenceAssemblyNameException))
             {
                 throw exception;
             }
             InvalidReferenceAssemblyNameException exception2 = (InvalidReferenceAssemblyNameException) exception;
             base.Log.LogWarningWithCodeFromResources("General.MalformedAssemblyName", new object[] { exception2.SourceItemSpec });
         }
     }
     return flag;
 }
示例#38
0
 public AssemblyDefinition Resolve(AssemblyNameReference name)
 {
     return(Resolve(name.Name));
 }
        /// <summary>
        /// Log the results.
        /// </summary>
        /// <param name="dependencyTable">Reference table.</param>
        /// <param name="idealAssemblyRemappings">Array of ideal assembly remappings.</param>
        /// <param name="idealAssemblyRemappingsIdentities">Array of identities of ideal assembly remappings.</param>
        /// <param name="generalResolutionExceptions">List of exceptions that were not attributable to a particular fusion name.</param>
        /// <returns></returns>
        private bool LogResults
        (
            ReferenceTable dependencyTable,
            DependentAssembly[] idealAssemblyRemappings,
            AssemblyNameReference[] idealAssemblyRemappingsIdentities,
            ArrayList generalResolutionExceptions
        )
        {
            bool success = true;
#if (!STANDALONEBUILD)
            using (new CodeMarkerStartEnd(CodeMarkerEvent.perfMSBuildRARLogResultsBegin, CodeMarkerEvent.perfMSBuildRARLogResultsEnd))
#endif
            {
                /*
                PERF NOTE: The Silent flag turns off logging completely from the task side. This means
                we avoid the String.Formats that would normally occur even if the verbosity was set to 
                quiet at the engine level.
                */
                if (!Silent)
                {
                    // First, loop over primaries and display information.
                    foreach (AssemblyNameExtension assemblyName in dependencyTable.References.Keys)
                    {
                        string fusionName = assemblyName.FullName;
                        Reference primaryCandidate = dependencyTable.GetReference(assemblyName);

                        if (primaryCandidate.IsPrimary && !(primaryCandidate.IsConflictVictim && primaryCandidate.IsCopyLocal))
                        {
                            LogReference(primaryCandidate, fusionName);
                        }
                    }

                    // Second, loop over dependencies and display information.
                    foreach (AssemblyNameExtension assemblyName in dependencyTable.References.Keys)
                    {
                        string fusionName = assemblyName.FullName;
                        Reference dependencyCandidate = dependencyTable.GetReference(assemblyName);

                        if (!dependencyCandidate.IsPrimary && !(dependencyCandidate.IsConflictVictim && dependencyCandidate.IsCopyLocal))
                        {
                            LogReference(dependencyCandidate, fusionName);
                        }
                    }

                    // Third, show conflicts and their resolution.
                    foreach (AssemblyNameExtension assemblyName in dependencyTable.References.Keys)
                    {
                        string fusionName = assemblyName.FullName;
                        Reference conflictCandidate = dependencyTable.GetReference(assemblyName);

                        if (conflictCandidate.IsConflictVictim)
                        {
                            LogConflict(conflictCandidate, fusionName);

                            // Log the assemblies and primary source items which are related to the conflict which was just logged.
                            Reference victor = dependencyTable.GetReference(conflictCandidate.ConflictVictorName);

                            // Log the winner of the conflict resolution, the source items and dependencies which caused it
                            LogReferenceDependenciesAndSourceItems(conflictCandidate.ConflictVictorName.FullName, victor);

                            // Log the reference which lost the conflict and the dependencies and source items which caused it.
                            LogReferenceDependenciesAndSourceItems(fusionName, conflictCandidate);
                        }
                    }

                    // Fourth, if there were any suggested redirects. Show one message per redirect and a single warning.
                    if (idealAssemblyRemappings != null)
                    {
                        bool foundAtLeastOneValidBindingRedirect = false;
                        bool foundAtLeastOneUnresolvableConflict = false;

                        var buffer = new StringBuilder();
                        var ns = XNamespace.Get("urn:schemas-microsoft-com:asm.v1");

                        // A high-priority message for each individual redirect.
                        for (int i = 0; i < idealAssemblyRemappings.Length; i++)
                        {
                            DependentAssembly idealRemapping = idealAssemblyRemappings[i];
                            AssemblyName idealRemappingPartialAssemblyName = idealRemapping.PartialAssemblyName;
                            Reference reference = idealAssemblyRemappingsIdentities[i].reference;

                            for (int j = 0; j < idealRemapping.BindingRedirects.Length; j++)
                            {
                                AssemblyNameExtension[] conflictVictims = reference.GetConflictVictims();
                                foreach (AssemblyNameExtension conflictVictim in conflictVictims)
                                {
                                    // Make note we only output a conflict suggestion if the reference has at 
                                    // least one conflict victim - that way we don't suggest redirects to 
                                    // assemblies that don't exist at runtime. For example, this avoids us suggesting
                                    // a redirect from Foo 1.0.0.0 -> 2.0.0.0 in the following:
                                    //
                                    //      Project -> Foo, 1.0.0.0
                                    //      Project -> Bar -> Foo, 2.0.0.0
                                    //
                                    // Above, Foo, 1.0.0.0 wins out and is copied to the output directory because 
                                    // it is a primary reference.
                                    foundAtLeastOneValidBindingRedirect = true;

                                    Reference victimReference = dependencyTable.GetReference(conflictVictim);
                                    var newVerStr = idealRemapping.BindingRedirects[j].NewVersion.ToString();
                                    Log.LogMessageFromResources
                                    (
                                        MessageImportance.High,
                                        "ResolveAssemblyReference.ConflictRedirectSuggestion",
                                        idealRemappingPartialAssemblyName,
                                        conflictVictim.Version,
                                        victimReference.FullPath,
                                        newVerStr,
                                        reference.FullPath
                                    );

                                    if (!SupportsBindingRedirectGeneration && !AutoUnify)
                                    {
                                        // When running against projects types (such as Web Projects) where we can't auto-generate
                                        // binding redirects during the build, populate a buffer (to be output below) with the
                                        // binding redirect syntax that users need to add manually to the App.Config.

                                        var assemblyIdentityAttributes = new List<XAttribute>(4);

                                        assemblyIdentityAttributes.Add(new XAttribute("name", idealRemappingPartialAssemblyName.Name));

                                        // We use "neutral" for "Invariant Language (Invariant Country)" in assembly names.
                                        var cultureString = idealRemappingPartialAssemblyName.CultureName;
                                        assemblyIdentityAttributes.Add(new XAttribute("culture", String.IsNullOrEmpty(idealRemappingPartialAssemblyName.CultureName) ? "neutral" : idealRemappingPartialAssemblyName.CultureName));

                                        var publicKeyToken = idealRemappingPartialAssemblyName.GetPublicKeyToken();
                                        assemblyIdentityAttributes.Add(new XAttribute("publicKeyToken", ResolveAssemblyReference.ByteArrayToString(publicKeyToken)));

                                        var node = new XElement(
                                            ns + "assemblyBinding",
                                            new XElement(
                                                ns + "dependentAssembly",
                                                new XElement(
                                                    ns + "assemblyIdentity",
                                                    assemblyIdentityAttributes),
                                                new XElement(
                                                    ns + "bindingRedirect",
                                                    new XAttribute("oldVersion", "0.0.0.0-" + newVerStr),
                                                    new XAttribute("newVersion", newVerStr))));

                                        buffer.Append(node.ToString(SaveOptions.DisableFormatting));
                                    }
                                }

                                if (conflictVictims.Length == 0)
                                {
                                    foundAtLeastOneUnresolvableConflict = true;
                                }
                            }
                        }

                        // Log the warning
                        if (idealAssemblyRemappings.Length > 0 && foundAtLeastOneValidBindingRedirect)
                        {
                            if (SupportsBindingRedirectGeneration)
                            {
                                if (!AutoUnify)
                                {
                                    Log.LogWarningWithCodeFromResources("ResolveAssemblyReference.TurnOnAutoGenerateBindingRedirects");
                                }
                                // else we'll generate bindingRedirects to address the remappings
                            }
                            else if (!AutoUnify)
                            {
                                Log.LogWarningWithCodeFromResources("ResolveAssemblyReference.SuggestedRedirects", buffer.ToString());
                            }
                            // else AutoUnify is on and bindingRedirect generation is not supported
                            // we don't warn in this case since the binder will automatically unify these remappings
                        }

                        if (foundAtLeastOneUnresolvableConflict)
                        {
                            // This warning is logged regardless of AutoUnify since it means a conflict existed where the reference
                            // chosen was not the conflict victor in a version comparison, in other words it was older.
                            Log.LogWarningWithCodeFromResources("ResolveAssemblyReference.FoundConflicts");
                        }
                    }

                    // Fifth, log general resolution problems.

                    // Log general resolution exceptions.
                    foreach (Exception error in generalResolutionExceptions)
                    {
                        if (error is InvalidReferenceAssemblyNameException)
                        {
                            InvalidReferenceAssemblyNameException e = (InvalidReferenceAssemblyNameException)error;
                            Log.LogWarningWithCodeFromResources("General.MalformedAssemblyName", e.SourceItemSpec);
                        }
                        else
                        {
                            // An unknown Exception type was returned. Just throw.
                            throw error;
                        }
                    }
                }
            }

            if (dependencyTable.Resolvers != null)
            {
                foreach (Resolver r in dependencyTable.Resolvers)
                {
                    if (r is AssemblyFoldersExResolver)
                    {
                        AssemblyFoldersEx assemblyFoldersEx = ((AssemblyFoldersExResolver)r).AssemblyFoldersExLocations;

                        MessageImportance messageImportance = MessageImportance.Low;
                        if (assemblyFoldersEx != null && _showAssemblyFoldersExLocations.TryGetValue(r.SearchPath, out messageImportance))
                        {
                            Log.LogMessageFromResources(messageImportance, "ResolveAssemblyReference.AssemblyFoldersExSearchLocations", r.SearchPath);
                            foreach (AssemblyFoldersExInfo info in assemblyFoldersEx)
                            {
                                Log.LogMessageFromResources(messageImportance, "ResolveAssemblyReference.EightSpaceIndent", info.DirectoryPath);
                            }
                        }
                    }
                }
            }

            return success;
        }
示例#40
0
 private static AssemblyDefinition OnResolveAssemblyFailure(object sender, AssemblyNameReference reference)
 {
     Console.WriteLine("Error resolving assembly: " + reference.FullName);
     return(null);
 }
示例#41
0
        /// <summary>
        /// Given two references along with their fusion names, resolve the filename conflict that they
        /// would have if both assemblies need to be copied to the same directory.
        /// </summary>
        private static int ResolveAssemblyNameConflict(AssemblyNameReference assemblyReference0, AssemblyNameReference assemblyReference1)
        {
            int victim = 0;

            // Extra checks for PInvoke-destined data.
            ErrorUtilities.VerifyThrow(assemblyReference0.assemblyName.FullName != null, "Got a null assembly name fullname. (0)");
            ErrorUtilities.VerifyThrow(assemblyReference1.assemblyName.FullName != null, "Got a null assembly name fullname. (1)");

            string[] conflictFusionNames = new string[] { assemblyReference0.assemblyName.FullName, assemblyReference1.assemblyName.FullName };
            Reference[] conflictReferences = new Reference[] { assemblyReference0.reference, assemblyReference1.reference };
            AssemblyNameExtension[] conflictAssemblyNames = new AssemblyNameExtension[] { assemblyReference0.assemblyName, assemblyReference1.assemblyName };
            bool[] conflictLegacyUnified = new bool[] { assemblyReference0.reference.IsPrimary, assemblyReference1.reference.IsPrimary };

            //  If both assemblies being compared are primary references, the caller should pass in a zero-flag 
            // (non-unified) for both. (This conforms to the C# assumption that two direct references are meant to be 
            // SxS.)
            if (conflictReferences[0].IsPrimary && conflictReferences[1].IsPrimary)
            {
                conflictLegacyUnified[0] = false;
                conflictLegacyUnified[1] = false;
            }

            // This is ok here because even if the method says two versions are equivilant the algorithm below will still pick the highest version.
            bool equivalent = false;
            NativeMethods.AssemblyComparisonResult result = 0;
            NativeMethods.CompareAssemblyIdentity
            (
                conflictFusionNames[0],
                conflictLegacyUnified[0],
                conflictFusionNames[1],
                conflictLegacyUnified[1],
                out equivalent,
                out result
            );

            // Remove one and provide some information about why.
            victim = 0;
            ConflictLossReason reason = ConflictLossReason.InsolubleConflict;

            // Pick the one with the highest version number.
            if (conflictReferences[0].IsPrimary && !conflictReferences[1].IsPrimary)
            {
                // Choose the primary version.
                victim = 1;
                reason = ConflictLossReason.WasNotPrimary;
            }
            else if (!conflictReferences[0].IsPrimary && conflictReferences[1].IsPrimary)
            {
                // Choose the primary version.
                victim = 0;
                reason = ConflictLossReason.WasNotPrimary;
            }
            else if (!conflictReferences[0].IsPrimary && !conflictReferences[1].IsPrimary)
            {
                if
                (
                    // Version comparison only if there are two versions to compare.
                    // Null versions can occur when simply-named assemblies are unresolved.
                    conflictAssemblyNames[0].Version != null && conflictAssemblyNames[1].Version != null
                    && conflictAssemblyNames[0].Version > conflictAssemblyNames[1].Version
                )
                {
                    // Choose the higher version
                    victim = 1;
                    if (equivalent)
                    {
                        reason = ConflictLossReason.HadLowerVersion;
                    }
                }
                else if
                (
                    // Version comparison only if there are two versions to compare.
                    // Null versions can occur when simply-named assemblies are unresolved.
                    conflictAssemblyNames[0].Version != null && conflictAssemblyNames[1].Version != null
                    && conflictAssemblyNames[0].Version < conflictAssemblyNames[1].Version
                )
                {
                    // Choose the higher version
                    victim = 0;
                    if (equivalent)
                    {
                        reason = ConflictLossReason.HadLowerVersion;
                    }
                }
                else
                {
                    victim = 0;

                    if (equivalent)
                    {
                        // Fusion thinks they're interchangeable.
                        reason = ConflictLossReason.FusionEquivalentWithSameVersion;
                    }
                }
            }


            // Remove the one chosen.
            int victor = 1 - victim;
            conflictReferences[victim].ConflictVictorName = conflictAssemblyNames[victor];
            conflictReferences[victim].ConflictLossExplanation = reason;
            conflictReferences[victor].AddConflictVictim(conflictAssemblyNames[victim]);

            return victim;
        }
示例#42
0
 public override AssemblyDefinition Resolve(AssemblyNameReference name)
 {
     return(Resolve(name, new ReaderParameters()));
 }