Exemple #1
0
 public LoadedAssembly([NotNull] AssemblyContainer container, [NotNull] string path, [NotNull] Assembly assembly, Dictionary <string, string> dependencies)
 {
     Container    = container;
     Path         = path;
     Assembly     = assembly;
     Dependencies = dependencies;
 }
Exemple #2
0
        public Assembly LoadAssemblyFromPath([NotNull] string assemblyFullPath, ILogger outputLog = null, List <string> lookupDirectoryList = null)
        {
            if (assemblyFullPath == null)
            {
                throw new ArgumentNullException(nameof(assemblyFullPath));
            }

            log = new LoggerResult();

            lookupDirectoryList = lookupDirectoryList ?? new List <string>();
            assemblyFullPath    = Path.GetFullPath(Path.Combine(Environment.CurrentDirectory, assemblyFullPath));
            var assemblyDirectory = Path.GetDirectoryName(assemblyFullPath);

            if (assemblyDirectory == null || !Directory.Exists(assemblyDirectory))
            {
                throw new ArgumentException("Invalid assembly path. Doesn't contain directory information");
            }

            if (!lookupDirectoryList.Contains(assemblyDirectory, StringComparer.InvariantCultureIgnoreCase))
            {
                lookupDirectoryList.Add(assemblyDirectory);
            }

            var previousLookupList = searchDirectoryList;

            try
            {
                loadingInstance     = this;
                searchDirectoryList = lookupDirectoryList;

                return(LoadAssemblyFromPathInternal(assemblyFullPath));
            }
            finally
            {
                loadingInstance     = null;
                searchDirectoryList = previousLookupList;

                if (outputLog != null)
                {
                    log.CopyTo(outputLog);
                }
            }
        }
Exemple #3
0
        private Assembly LoadAssemblyFromPathInternal([NotNull] string assemblyFullPath)
        {
            if (assemblyFullPath == null)
            {
                throw new ArgumentNullException(nameof(assemblyFullPath));
            }

            assemblyFullPath = Path.GetFullPath(assemblyFullPath);

            try
            {
                lock (loadedAssemblies)
                {
                    LoadedAssembly loadedAssembly;
                    if (loadedAssembliesByName.TryGetValue(assemblyFullPath, out loadedAssembly))
                    {
                        return(loadedAssembly.Assembly);
                    }

                    if (!File.Exists(assemblyFullPath))
                    {
                        return(null);
                    }

                    // Find pdb (if it exists)
                    var pdbFullPath = Path.ChangeExtension(assemblyFullPath, ".pdb");
                    if (!File.Exists(pdbFullPath))
                    {
                        pdbFullPath = null;
                    }

                    // PreLoad the assembly into memory without locking it
                    var assemblyBytes = File.ReadAllBytes(assemblyFullPath);
                    var pdbBytes      = pdbFullPath != null?File.ReadAllBytes(pdbFullPath) : null;

                    // Load the assembly into the current AppDomain
                    Assembly assembly;
                    if (new UDirectory(AppDomain.CurrentDomain.BaseDirectory) == new UFile(assemblyFullPath).GetFullDirectory())
                    {
                        // If loading from base directory, don't even try to load through byte array, as Assembly.Load will notice there is a "safer" version to load
                        // This happens usually when opening Xenko assemblies themselves
                        assembly = Assembly.LoadFrom(assemblyFullPath);
                    }
                    else
                    {
                        // Load .deps.json file (if any)
                        var depsFile = Path.ChangeExtension(assemblyFullPath, ".deps.json");
                        Dictionary <string, string> dependenciesMapping = null;
                        if (File.Exists(depsFile))
                        {
                            // Read file
                            var dependenciesReader         = new DependencyContextJsonReader();
                            DependencyContext dependencies = null;
                            using (var dependenciesStream = File.OpenRead(depsFile))
                            {
                                dependencies = dependenciesReader.Read(dependenciesStream);
                            }

                            // Locate NuGet package folder
                            var settings             = NuGet.Configuration.Settings.LoadDefaultSettings(Path.GetDirectoryName(assemblyFullPath));
                            var globalPackagesFolder = NuGet.Configuration.SettingsUtility.GetGlobalPackagesFolder(settings);

                            // Build list of assemblies listed in .deps.json file
                            dependenciesMapping = new Dictionary <string, string>();
                            foreach (var library in dependencies.RuntimeLibraries)
                            {
                                if (library.Path == null)
                                {
                                    continue;
                                }

                                foreach (var runtimeAssemblyGroup in library.RuntimeAssemblyGroups)
                                {
                                    foreach (var runtimeFile in runtimeAssemblyGroup.RuntimeFiles)
                                    {
                                        var fullPath = Path.Combine(globalPackagesFolder, library.Path, runtimeFile.Path);
                                        if (File.Exists(fullPath))
                                        {
                                            var assemblyName = Path.GetFileNameWithoutExtension(runtimeFile.Path);

                                            // TODO: Properly deal with file duplicates (same file in multiple package, or RID conflicts)
                                            if (!dependenciesMapping.ContainsKey(assemblyName))
                                            {
                                                dependenciesMapping.Add(assemblyName, fullPath);
                                            }
                                        }
                                    }
                                }

                                // It seems .deps.json files don't contain library info if referencer is non-RID specific and dependency is RID specific
                                // (i.e. compiling Game project without runtime identifier and a dependency needs runtime identifier)
                                // TODO: Look for a proper way to query that properly, maybe using NuGet API? however some constraints are:
                                // - limited info (only .deps.json available from path, no project info; we might need to reconstruct a proper NuGet restore request from .deps.json)
                                // - need to be fast (make sure to use NuGet caching mechanism)
                                if (library.RuntimeAssemblyGroups.Count == 0)
                                {
                                    var runtimeFolder = new[] { "win", "any" }
                                    .Select(runtime => Path.Combine(globalPackagesFolder, library.Path, "runtimes", runtime))
                                    .Where(Directory.Exists)
                                    .SelectMany(folder => Directory.EnumerateDirectories(Path.Combine(folder, "lib")))
                                    .FirstOrDefault(file => Path.GetFileName(file).StartsWith("net"));     // Only consider framework netXX and netstandardX.X
                                    if (runtimeFolder != null)
                                    {
                                        foreach (var runtimeFile in Directory.EnumerateFiles(runtimeFolder, "*.dll"))
                                        {
                                            var assemblyName = Path.GetFileNameWithoutExtension(runtimeFile);

                                            // TODO: Properly deal with file duplicates (same file in multiple package, or RID conflicts)
                                            if (!dependenciesMapping.ContainsKey(assemblyName))
                                            {
                                                dependenciesMapping.Add(assemblyName, runtimeFile);
                                            }
                                        }
                                    }
                                }
                            }
                        }

                        // TODO: Is using AppDomain would provide more opportunities for unloading?
                        assembly = pdbBytes != null?Assembly.Load(assemblyBytes, pdbBytes) : Assembly.Load(assemblyBytes);

                        loadedAssembly = new LoadedAssembly(this, assemblyFullPath, assembly, dependenciesMapping);
                        loadedAssemblies.Add(loadedAssembly);
                        loadedAssembliesByName.Add(assemblyFullPath, loadedAssembly);

                        // Force assembly resolve with proper name (with proper context)
                        var previousSearchDirectory = currentSearchDirectory;
                        var previousContainer       = currentContainer;
                        try
                        {
                            currentContainer       = this;
                            currentSearchDirectory = Path.GetDirectoryName(assemblyFullPath);

                            Assembly.Load(assembly.FullName);
                        }
                        finally
                        {
                            currentContainer       = previousContainer;
                            currentSearchDirectory = previousSearchDirectory;
                        }
                    }

                    // Make sure there is no duplicate
                    Debug.Assert(!assemblyToContainers.TryGetValue(assembly, out var _));
                    // Add to mapping
                    assemblyToContainers.GetValue(assembly, _ => loadedAssembly);

                    // Make sure that Module initializer are called
                    foreach (var module in assembly.Modules)
                    {
                        RuntimeHelpers.RunModuleConstructor(module.ModuleHandle);
                    }
                    return(assembly);
                }
            }
            catch (Exception exception)
            {
                log.Error($"Error while loading assembly reference [{assemblyFullPath}]", exception);
                var loaderException = exception as ReflectionTypeLoadException;
                if (loaderException != null)
                {
                    foreach (var exceptionForType in loaderException.LoaderExceptions)
                    {
                        log.Error("Unable to load type. See exception.", exceptionForType);
                    }
                }
            }
            return(null);
        }
Exemple #4
0
        private Assembly LoadAssemblyFromPathInternal([NotNull] string assemblyFullPath)
        {
            if (assemblyFullPath == null)
            {
                throw new ArgumentNullException(nameof(assemblyFullPath));
            }

            assemblyFullPath = Path.GetFullPath(assemblyFullPath);

            try
            {
                lock (loadedAssemblies)
                {
                    LoadedAssembly loadedAssembly;
                    if (loadedAssembliesByName.TryGetValue(assemblyFullPath, out loadedAssembly))
                    {
                        return(loadedAssembly.Assembly);
                    }

                    if (!File.Exists(assemblyFullPath))
                    {
                        return(null);
                    }

                    // Find pdb (if it exists)
                    var pdbFullPath = Path.ChangeExtension(assemblyFullPath, ".pdb");
                    if (!File.Exists(pdbFullPath))
                    {
                        pdbFullPath = null;
                    }

                    // PreLoad the assembly into memory without locking it
                    var assemblyBytes = File.ReadAllBytes(assemblyFullPath);
                    var pdbBytes      = pdbFullPath != null?File.ReadAllBytes(pdbFullPath) : null;

                    // Load the assembly into the current AppDomain
                    Assembly assembly;
                    if (new UDirectory(AppDomain.CurrentDomain.BaseDirectory) == new UFile(assemblyFullPath).GetFullDirectory())
                    {
                        // If loading from base directory, don't even try to load through byte array, as Assembly.Load will notice there is a "safer" version to load
                        // This happens usually when opening Xenko assemblies themselves
                        assembly = Assembly.LoadFrom(assemblyFullPath);
                    }
                    else
                    {
                        // Load .deps.json file (if any)
                        var depsFile = Path.ChangeExtension(assemblyFullPath, ".deps.json");
                        Dictionary <string, string> dependenciesMapping = null;
                        if (File.Exists(depsFile))
                        {
                            // Read file
                            var dependenciesReader         = new DependencyContextJsonReader();
                            DependencyContext dependencies = null;
                            using (var dependenciesStream = File.OpenRead(depsFile))
                            {
                                dependencies = dependenciesReader.Read(dependenciesStream);
                            }

                            // Locate NuGet package folder
                            var settings             = NuGet.Configuration.Settings.LoadDefaultSettings(Path.GetDirectoryName(assemblyFullPath));
                            var globalPackagesFolder = NuGet.Configuration.SettingsUtility.GetGlobalPackagesFolder(settings);

                            // Build list of assemblies listed in .deps.json file
                            dependenciesMapping = new Dictionary <string, string>();
                            foreach (var library in dependencies.RuntimeLibraries)
                            {
                                if (library.Path == null)
                                {
                                    continue;
                                }

                                foreach (var runtimeAssemblyGroup in library.RuntimeAssemblyGroups)
                                {
                                    foreach (var runtimeFile in runtimeAssemblyGroup.RuntimeFiles)
                                    {
                                        var fullPath = Path.Combine(globalPackagesFolder, library.Path, runtimeFile.Path);
                                        if (File.Exists(fullPath))
                                        {
                                            var assemblyName = Path.GetFileNameWithoutExtension(runtimeFile.Path);

                                            // TODO: Properly deal with file duplicates (same file in multiple package, or RID conflicts)
                                            if (!dependenciesMapping.ContainsKey(assemblyName))
                                            {
                                                dependenciesMapping.Add(assemblyName, fullPath);
                                            }
                                        }
                                    }
                                }
                            }
                        }

                        // TODO: Is using AppDomain would provide more opportunities for unloading?
                        assembly = pdbBytes != null?Assembly.Load(assemblyBytes, pdbBytes) : Assembly.Load(assemblyBytes);

                        loadedAssembly = new LoadedAssembly(this, assemblyFullPath, assembly, dependenciesMapping);
                        loadedAssemblies.Add(loadedAssembly);
                        loadedAssembliesByName.Add(assemblyFullPath, loadedAssembly);

                        // Force assembly resolve with proper name (with proper context)
                        var previousSearchDirectory = currentSearchDirectory;
                        var previousContainer       = currentContainer;
                        try
                        {
                            currentContainer       = this;
                            currentSearchDirectory = Path.GetDirectoryName(assemblyFullPath);

                            Assembly.Load(assembly.FullName);
                        }
                        finally
                        {
                            currentContainer       = previousContainer;
                            currentSearchDirectory = previousSearchDirectory;
                        }
                    }

                    // Make sure there is no duplicate
                    Debug.Assert(!assemblyToContainers.TryGetValue(assembly, out var _));
                    // Add to mapping
                    assemblyToContainers.GetValue(assembly, _ => loadedAssembly);

                    // Make sure that Module initializer are called
                    foreach (var module in assembly.Modules)
                    {
                        RuntimeHelpers.RunModuleConstructor(module.ModuleHandle);
                    }
                    return(assembly);
                }
            }
            catch (Exception exception)
            {
                log.Error($"Error while loading assembly reference [{assemblyFullPath}]", exception);
                var loaderException = exception as ReflectionTypeLoadException;
                if (loaderException != null)
                {
                    foreach (var exceptionForType in loaderException.LoaderExceptions)
                    {
                        log.Error("Unable to load type. See exception.", exceptionForType);
                    }
                }
            }
            return(null);
        }
 public LoadedAssembly([NotNull] AssemblyContainer container, [NotNull] string path, [NotNull] Assembly assembly)
 {
     Container = container;
     Path      = path;
     Assembly  = assembly;
 }
        private Assembly LoadAssemblyFromPathInternal([NotNull] string assemblyFullPath)
        {
            if (assemblyFullPath == null)
            {
                throw new ArgumentNullException(nameof(assemblyFullPath));
            }

            assemblyFullPath = Path.GetFullPath(assemblyFullPath);

            try
            {
                lock (loadedAssemblies)
                {
                    LoadedAssembly loadedAssembly;
                    if (loadedAssembliesByName.TryGetValue(assemblyFullPath, out loadedAssembly))
                    {
                        return(loadedAssembly.Assembly);
                    }

                    if (!File.Exists(assemblyFullPath))
                    {
                        return(null);
                    }

                    // Find pdb (if it exists)
                    var pdbFullPath = Path.ChangeExtension(assemblyFullPath, ".pdb");
                    if (!File.Exists(pdbFullPath))
                    {
                        pdbFullPath = null;
                    }

                    // PreLoad the assembly into memory without locking it
                    var assemblyBytes = File.ReadAllBytes(assemblyFullPath);
                    var pdbBytes      = pdbFullPath != null?File.ReadAllBytes(pdbFullPath) : null;

                    // Load the assembly into the current AppDomain
                    Assembly assembly;
                    if (new UDirectory(AppDomain.CurrentDomain.BaseDirectory) == new UFile(assemblyFullPath).GetFullDirectory())
                    {
                        // If loading from base directory, don't even try to load through byte array, as Assembly.Load will notice there is a "safer" version to load
                        // This happens usually when opening Xenko assemblies themselves
                        assembly = Assembly.LoadFrom(assemblyFullPath);
                    }
                    else
                    {
                        // TODO: Is using AppDomain would provide more opportunities for unloading?
                        assembly = pdbBytes != null?Assembly.Load(assemblyBytes, pdbBytes) : Assembly.Load(assemblyBytes);

                        loadedAssembly = new LoadedAssembly(this, assemblyFullPath, assembly);
                        loadedAssemblies.Add(loadedAssembly);
                        loadedAssembliesByName.Add(assemblyFullPath, loadedAssembly);

                        // Force assembly resolve with proper name (with proper context)
                        var previousSearchDirectory = currentSearchDirectory;
                        var previousContainer       = currentContainer;
                        try
                        {
                            currentContainer       = this;
                            currentSearchDirectory = Path.GetDirectoryName(assemblyFullPath);

                            Assembly.Load(assembly.FullName);
                        }
                        finally
                        {
                            currentContainer       = previousContainer;
                            currentSearchDirectory = previousSearchDirectory;
                        }
                    }

                    // Make sure there is no duplicate
                    Debug.Assert(!assemblyToContainers.TryGetValue(assembly, out var _));
                    // Add to mapping
                    assemblyToContainers.GetValue(assembly, _ => loadedAssembly);

                    // Make sure that Module initializer are called
                    foreach (var module in assembly.Modules)
                    {
                        RuntimeHelpers.RunModuleConstructor(module.ModuleHandle);
                    }
                    return(assembly);
                }
            }
            catch (Exception exception)
            {
                log.Error($"Error while loading assembly reference [{assemblyFullPath}]", exception);
                var loaderException = exception as ReflectionTypeLoadException;
                if (loaderException != null)
                {
                    foreach (var exceptionForType in loaderException.LoaderExceptions)
                    {
                        log.Error("Unable to load type. See exception.", exceptionForType);
                    }
                }
            }
            return(null);
        }