public ExecuteReplCommand(
            string scriptName,
            string[] scriptArgs,
            IFileSystem fileSystem,
            IScriptPackResolver scriptPackResolver,
            IRepl repl,
            ILogProvider logProvider,
            IConsole console,
            IAssemblyResolver assemblyResolver,
            IFileSystemMigrator fileSystemMigrator,
            IScriptLibraryComposer composer)
        {
            Guard.AgainstNullArgument("fileSystem", fileSystem);
            Guard.AgainstNullArgument("scriptPackResolver", scriptPackResolver);
            Guard.AgainstNullArgument("repl", repl);
            Guard.AgainstNullArgument("logProvider", logProvider);
            Guard.AgainstNullArgument("console", console);
            Guard.AgainstNullArgument("assemblyResolver", assemblyResolver);
            Guard.AgainstNullArgument("fileSystemMigrator", fileSystemMigrator);
            Guard.AgainstNullArgument("composer", composer);

            _scriptName = scriptName;
            _scriptArgs = scriptArgs;
            _fileSystem = fileSystem;
            _scriptPackResolver = scriptPackResolver;
            _repl = repl;
            _logger = logProvider.ForCurrentType();
            _console = console;
            _assemblyResolver = assemblyResolver;
            _fileSystemMigrator = fileSystemMigrator;
            _composer = composer;
        }
Beispiel #2
0
        public static TypeDefinition Resolve(IAssemblyResolver resolver, TypeReference type)
        {
            type = type.GetElementType ();

            var scope = type.Scope;
            switch (scope.MetadataScopeType) {
            case MetadataScopeType.AssemblyNameReference:
                var assembly = resolver.Resolve ((AssemblyNameReference) scope);
                if (assembly == null)
                    return null;

                return GetType (assembly.MainModule, type);
            case MetadataScopeType.ModuleDefinition:
                return GetType ((ModuleDefinition) scope, type);
            case MetadataScopeType.ModuleReference:
                var modules = type.Module.Assembly.Modules;
                var module_ref = (ModuleReference) scope;
                for (int i = 0; i < modules.Count; i++) {
                    var netmodule = modules [i];
                    if (netmodule.Name == module_ref.Name)
                        return GetType (netmodule, type);
                }
                break;
            }

            throw new NotSupportedException ();
        }
Beispiel #3
0
        public ReferenceContainer(ModuleDefinition moduleDefinition, IAssemblyResolver assemblyResolver)
        {
            var systemDefinition = assemblyResolver.Resolve("mscorlib");
            var yalfDefinition = assemblyResolver.Resolve("Yalf");
            var yalfTypes = yalfDefinition.MainModule.Types;

            var logType = yalfTypes.Single(x => x.Name == "Log");
            var iContextType = yalfTypes.Single(x => x.Name == "IContext");

            var iDisposableType = systemDefinition.MainModule.Types.Single(x => x.Name == "IDisposable");
            var exceptionType = systemDefinition.MainModule.Types.Single(x => x.Name == "Exception");

            MethodContextMethod = moduleDefinition.Import(logType.Methods.Single(m => m.Name == "MethodContext"));
            TraceExceptionMethod = moduleDefinition.Import(logType.Methods.Single(m => m.Name == "TraceException"));
            CreateRecordReturnMethod = retType => {

                var recordReturn = moduleDefinition.Import(iContextType.Methods.Single(m => m.Name == "RecordReturn"));
                if (retType.IsGenericInstance)
                {
                    return recordReturn.MakeGeneric(retType);
                }
                else
                {
                    return recordReturn.MakeGeneric(retType);
                }
            };
            DisposeMethod = moduleDefinition.Import(iDisposableType.Methods.Single(m => m.Name == "Dispose"));
            LogType = moduleDefinition.Import(logType);
            IContextType = moduleDefinition.Import(iContextType);
            ExceptionType = moduleDefinition.Import(exceptionType);
            PreserveStackTraceMethod = moduleDefinition.Import(iContextType.Methods.Single(m => m.Name == "PreserveStackTrace"));
        }
Beispiel #4
0
 public ExecuteReplCommand(
     string scriptName,
     string[] scriptArgs,
     IFileSystem fileSystem,
     IScriptPackResolver scriptPackResolver,
     IScriptEngine scriptEngine,
     IFilePreProcessor filePreProcessor,
     IObjectSerializer serializer,
     ILog logger,
     IConsole console,
     IAssemblyResolver assemblyResolver,
     IEnumerable<IReplCommand> replCommands)
 {
     _scriptName = scriptName;
     _scriptArgs = scriptArgs;
     _fileSystem = fileSystem;
     _scriptPackResolver = scriptPackResolver;
     _scriptEngine = scriptEngine;
     _filePreProcessor = filePreProcessor;
     _serializer = serializer;
     _logger = logger;
     _console = console;
     _assemblyResolver = assemblyResolver;
     _replCommands = replCommands;
 }
Beispiel #5
0
		public MetadataResolver (IAssemblyResolver assemblyResolver)
		{
			if (assemblyResolver == null)
				throw new ArgumentNullException ("assemblyResolver");

			assembly_resolver = assemblyResolver;
		}
Beispiel #6
0
        public ModuleLoader(IAssemblyResolver resolver, ILog logger, Action<Assembly, AggregateCatalog> addToCatalog, Func<CompositionContainer, IEnumerable<Lazy<IModule, IModuleMetadata>>> getLazyModules, IFileSystem fileSystem, IAssemblyUtility assemblyUtility)
        {
            _resolver = resolver;
            _logger = logger;

            if (addToCatalog == null)
            {
                addToCatalog = (assembly, catalog) =>
                {
                    try
                    {
                        var assemblyCatalog = new AssemblyCatalog(assembly);
                        catalog.Catalogs.Add(assemblyCatalog);
                    }
                    catch (Exception exception)
                    {
                        logger.DebugFormat("Module Loader exception: {0}", exception.Message);
                    }
                };
            }

            _addToCatalog = addToCatalog;

            if (getLazyModules == null)
            {
                getLazyModules = container => container.GetExports<IModule, IModuleMetadata>();
            }

            _getLazyModules = getLazyModules;
            _fileSystem = fileSystem;
            _assemblyUtility = assemblyUtility;
        }
        public ExecuteScriptCommand(
            string script,
            string[] scriptArgs,
            IFileSystem fileSystem,
            IScriptExecutor scriptExecutor,
            IScriptPackResolver scriptPackResolver,
            ILog logger,
            IAssemblyResolver assemblyResolver,
            IFileSystemMigrator fileSystemMigrator,
            IScriptLibraryComposer composer
            )
        {
            Guard.AgainstNullArgument("fileSystem", fileSystem);
            Guard.AgainstNullArgument("scriptExecutor", scriptExecutor);
            Guard.AgainstNullArgument("scriptPackResolver", scriptPackResolver);
            Guard.AgainstNullArgument("logger", logger);
            Guard.AgainstNullArgument("assemblyResolver", assemblyResolver);
            Guard.AgainstNullArgument("fileSystemMigrator", fileSystemMigrator);
            Guard.AgainstNullArgument("composer", composer);

            _script = script;
            ScriptArgs = scriptArgs;
            _fileSystem = fileSystem;
            _scriptExecutor = scriptExecutor;
            _scriptPackResolver = scriptPackResolver;
            _logger = logger;
            _assemblyResolver = assemblyResolver;
            _fileSystemMigrator = fileSystemMigrator;
            _composer = composer;
        }
        public static IEnumerable<AssemblyDefinition> Dependencies(this AssemblyDefinition asm)
        {
            if (_resolver == null)
                _resolver = asm.MainModule.AssemblyResolver;

            return asm.MainModule.AssemblyReferences.Select(Resolve);
        }
Beispiel #9
0
 public ScriptServices(
     IFileSystem fileSystem,
     IPackageAssemblyResolver packageAssemblyResolver,
     IScriptExecutor executor,
     IRepl repl,
     IScriptEngine engine,
     IFilePreProcessor filePreProcessor,
     IScriptPackResolver scriptPackResolver,
     IPackageInstaller packageInstaller,
     IObjectSerializer objectSerializer,
     ILog logger,
     IAssemblyResolver assemblyResolver,
     IEnumerable<IReplCommand> replCommands,
     IConsole console = null,
     IInstallationProvider installationProvider = null)
 {
     FileSystem = fileSystem;
     PackageAssemblyResolver = packageAssemblyResolver;
     Executor = executor;
     Repl = repl;
     Engine = engine;
     FilePreProcessor = filePreProcessor;
     ScriptPackResolver = scriptPackResolver;
     PackageInstaller = packageInstaller;
     ObjectSerializer = objectSerializer;
     Logger = logger;
     Console = console;
     AssemblyResolver = assemblyResolver;
     InstallationProvider = installationProvider;
     ReplCommands = replCommands;
 }
        public static TypeDefinition ResolveType(string type, ICustomAttributeProvider provider, IAssemblyResolver resolver)
        {
            if (provider == null)
                throw new ArgumentException ("Type resolution support requires an AssemblyDefinition or TypeDefinition.", "provider");
            if (resolver == null)
                throw new ArgumentException ("Type resolution support requires a IAssemblyResolver.", "resolver");

            // `type` is either a "bare" type "Foo.Bar", or an
            // assembly-qualified type "Foo.Bar, AssemblyName [Version=...]?".
            //
            // Bare types are looked up via `provider`; assembly-qualified types are
            // looked up via `resolver`

            int c = type.IndexOf (',');
            string typeName = c < 0 ? type  : type.Substring (0, c);
            string assmName = c < 0 ? null  : type.Substring (c+1);

            AssemblyDefinition assembly = assmName == null ? null : resolver.Resolve (assmName);
            if (assembly == null) {
                assembly = provider as AssemblyDefinition;
                if (assembly == null) {
                    TypeDefinition decl = (TypeDefinition) provider;
                    assembly = decl.Module.Assembly;
                }
            }
            var ret = assembly.Modules.Cast<ModuleDefinition> ()
                .Select (md => md.Types.FirstOrDefault (t => t.FullName == typeName))
                .FirstOrDefault (td => td != null);
            if (ret == null)
                throw new ArgumentException ("Type not found: " + type, "type");

            return ret;
        }
        /// <inheritdoc />
        public void AddAssemblyResolver(IAssemblyResolver assemblyResolver)
        {
            if (assemblyResolver == null)
                throw new ArgumentNullException(@"assemblyResolver");

            assemblyResolvers.Add(assemblyResolver);
        }
 public void SetUp()
 {
     this.log = MockRepository.GenerateMock<ILog>();
     this.assemblyResolver = new AssemblyResolver(new DirectoryImpl(), log);
     this.config = new SqlToGraphiteConfig(this.assemblyResolver, log);
     this.template = new Template();
 }
 public void SetUp()
 {
     encryption = new Encryption();
     log = MockRepository.GenerateMock<ILog>();
     assemblyResolver = MockRepository.GenerateMock<IAssemblyResolver>();
     this.dataClientFactory = new DataClientFactory(log, assemblyResolver, encryption);
 }
        public AppDomainAssemblyResolver(
            ILogProvider logProvider,
            IFileSystem fileSystem,
            IAssemblyResolver resolver,
            IAssemblyUtility assemblyUtility,
            IDictionary<string, AssemblyInfo> assemblyInfoMap = null,
            Func<object, ResolveEventArgs, Assembly> resolveHandler = null)
        {
            Guard.AgainstNullArgument("logProvider", logProvider);
            Guard.AgainstNullArgument("fileSystem", fileSystem);
            Guard.AgainstNullArgument("resolver", resolver);
            Guard.AgainstNullArgument("assemblyUtility", assemblyUtility);

            _assemblyInfoMap = assemblyInfoMap ?? new Dictionary<string, AssemblyInfo>();
            _assemblyUtility = assemblyUtility;
            _logger = logProvider.ForCurrentType();
            _fileSystem = fileSystem;
            _resolver = resolver;

            if (resolveHandler == null)
            {
                resolveHandler = AssemblyResolve;
            }

            AppDomain.CurrentDomain.AssemblyResolve += new ResolveEventHandler(resolveHandler);
        }
 public ScriptServices(
     IFileSystem fileSystem,
     IPackageAssemblyResolver packageAssemblyResolver, 
     IScriptExecutor executor,
     IScriptEngine engine,
     IFilePreProcessor filePreProcessor,
     IReplCommandService replCommandService,
     IScriptPackResolver scriptPackResolver, 
     IPackageInstaller packageInstaller,
     ILog logger,
     IAssemblyResolver assemblyResolver,
     IConsole console = null,
     IInstallationProvider installationProvider = null 
     )
 {
     FileSystem = fileSystem;
     PackageAssemblyResolver = packageAssemblyResolver;
     Executor = executor;
     Engine = engine;
     FilePreProcessor = filePreProcessor;
     ReplCommandService = replCommandService;
     ScriptPackResolver = scriptPackResolver;
     PackageInstaller = packageInstaller;
     Logger = logger;
     Console = console;
     AssemblyResolver = assemblyResolver;
     InstallationProvider = installationProvider;
 }
		public MemberReference GetMemberReference(IAssemblyResolver resolver)
		{
			if (resolver == null)
				throw new ArgumentNullException("resolver");
			
			if (memberReference != null)
				return memberReference;
			
			// reload from filename
			ReaderParameters readerParameters = new ReaderParameters();
			// Use new assembly resolver instance so that the AssemblyDefinitions can be garbage-collected
			// once the code is decompiled.
			readerParameters.AssemblyResolver = resolver;
			
			string typeName;
			if (GetAssemblyAndType(FileName.ToString(), out assemblyFile, out typeName)) {
				ModuleDefinition module = ModuleDefinition.ReadModule(assemblyFile, readerParameters);
				TypeDefinition typeDefinition = module.GetType(typeName);
				if (typeDefinition == null)
					throw new InvalidOperationException("Could not find type");
				memberReference = typeDefinition;
			}
			
			return memberReference;
		}
Beispiel #17
0
		public FileManager(IFileManagerSettings fileManagerSettings, [ImportMany] IDnSpyFileCreator[] mefCreators) {
			this.lockObj = new object();
			this.files = new List<IDnSpyFile>();
			this.tempCache = new List<IDnSpyFile>();
			this.asmResolver = new AssemblyResolver(this);
			this.dnSpyFileCreators = mefCreators.OrderBy(a => a.Order).ToArray();
			this.fileManagerSettings = fileManagerSettings;
		}
 public AssemblyTypeInfoGenerator(string assembly, IAssemblyResolver resolver)
 {
   string str = assembly;
   ReaderParameters readerParameters1 = new ReaderParameters();
   readerParameters1.set_AssemblyResolver(resolver);
   ReaderParameters readerParameters2 = readerParameters1;
   this.assembly_ = AssemblyDefinition.ReadAssembly(str, readerParameters2);
 }
Beispiel #19
0
        internal AssemblyDefinition(AssemblyNameDefinition name)
        {
            if (name == null)
                throw new ArgumentNullException ("name");

            m_asmName = name;
            m_modules = new ModuleDefinitionCollection (this);
            m_resolver = new DefaultAssemblyResolver ();
        }
 public IAssemblyResolver GetAssemblyResolver()
 {
     if (_assemblyResolver == null)
     {
         _logger.Debug("Resolving AssemblyResolver");
         _assemblyResolver = Container.Resolve<IAssemblyResolver>();
     }
     return _assemblyResolver;
 }
		internal static XDocument LoadIntoDocument(IAssemblyResolver resolver, AssemblyDefinition asm, Stream stream)
		{
			XDocument xamlDocument;
			using (XmlBamlReader reader = new XmlBamlReader(stream, new CecilTypeResolver(resolver, asm)))
				xamlDocument = XDocument.Load(reader);
			ConvertToEmptyElements(xamlDocument.Root);
			MoveNamespacesToRoot(xamlDocument);
			return xamlDocument;
		}
Beispiel #22
0
 public static bool Process(string unityEngine, string unetDLL, string outputDirectory, string[] assemblies, string[] extraAssemblyPaths, IAssemblyResolver assemblyResolver, Action<string> printWarning, Action<string> printError)
 {
     CheckDLLPath(unityEngine);
     CheckDLLPath(unetDLL);
     CheckOutputDirectory(outputDirectory);
     CheckAssemblies(assemblies);
     Log.WarningMethod = printWarning;
     Log.ErrorMethod = printError;
     return Weaver.WeaveAssemblies(assemblies, extraAssemblyPaths, assemblyResolver, outputDirectory, unityEngine, unetDLL);
 }
        public ScopedAssemblyResolver(string location)
        {
            if (!string.IsNullOrEmpty(location) && Directory.Exists(location))
                AddSearchDirectory(location);

            // also search the directory that the runner is within
            AddSearchDirectory(typeof(ScopedAssemblyResolver).Assembly.Location);

            defaultResolver = new DefaultAssemblyResolver();
        }
 public AppDomainAssemblyResolver(
     Common.Logging.ILog logger,
     IFileSystem fileSystem,
     IAssemblyResolver resolver,
     IAssemblyUtility assemblyUtility,
     IDictionary<string, AssemblyInfo> assemblyInfoMap = null,
     Func<object, ResolveEventArgs, Assembly> resolveHandler = null)
     : this(new CommonLoggingLogProvider(logger), fileSystem, resolver, assemblyUtility, assemblyInfoMap, resolveHandler)
 {
 }
        public ComplexSerializerCodeGenerator(IAssemblyResolver assemblyResolver, AssemblyDefinition assembly, ILogger log)
        {
            this.assembly = assembly;
            this.assemblySerializerFactoryClassName = assembly.Name.Name.Replace(" ", string.Empty).Replace(".", string.Empty) + "SerializerFactory";

            // Register referenced assemblies serializer factory, so that we can call them recursively
            foreach (var referencedAssemblyName in assembly.MainModule.AssemblyReferences)
            {
                try
                {
                    var referencedAssembly = assembly.MainModule.AssemblyResolver.Resolve(referencedAssemblyName);

                    var assemblySerializerFactoryType = GetSerializerFactoryType(referencedAssembly);
                    if (assemblySerializerFactoryType != null)
                        referencedAssemblySerializerFactoryTypes.Add(assemblySerializerFactoryType);
                }
                catch (AssemblyResolutionException)
                {
                    continue;
                }
            }

            // Find target framework and replicate it for serializer assembly.
            var targetFrameworkAttribute = assembly.CustomAttributes
                .FirstOrDefault(x => x.AttributeType.FullName == typeof(TargetFrameworkAttribute).FullName);
            if (targetFrameworkAttribute != null)
            {
                targetFramework = "\"" + (string)targetFrameworkAttribute.ConstructorArguments[0].Value + "\"";
                var frameworkDisplayNameField = targetFrameworkAttribute.Properties.FirstOrDefault(x => x.Name == "FrameworkDisplayName");
                if (frameworkDisplayNameField.Name != null)
                {
                    targetFramework += ", FrameworkDisplayName=\"" + (string)frameworkDisplayNameField.Argument.Value + "\"";
                }
            }

            // Prepare serializer processors
            cecilSerializerContext = new CecilSerializerContext(assembly, log);
            var processors = new List<ICecilSerializerProcessor>();

            // Import list of serializer registered by referenced assemblies
            processors.Add(new ReferencedAssemblySerializerProcessor());

            // Generate serializers for types tagged as serializable
            processors.Add(new CecilComplexClassSerializerProcessor());

            // Generate serializers for PropertyKey and ParameterKey
            processors.Add(new PropertyKeySerializerProcessor());

            // Profile serializers
            processors.Add(new ProfileSerializerProcessor());

            // Apply each processor
            foreach (var processor in processors)
                processor.ProcessSerializers(cecilSerializerContext);
        }
		public static FieldDefinition Resolve (IAssemblyResolver resolver, FieldReference field)
		{
			var type = Resolve (resolver, field.DeclaringType);
			if (type == null)
				return null;

			if (!type.HasFields)
				return null;

			return GetField (resolver, type, field);
		}
Beispiel #27
0
        public CecilReflector(InstrumentationContext context)
        {
            _context = context;
            _resolver = new RelativeAssemblyResolver(_context);

            if (_context.AlternateAssemblyLocation != null)
            {
                _resolver = new CompositeAssemblyResolver(
                    new RelativeAssemblyResolver(_context.AlternateAssemblyLocation),
                    _resolver);
            }
        }
 public void SetUp()
 {
     sleepTime = 1000;
     assemblyResolver = MockRepository.GenerateMock<IAssemblyResolver>();
     config = new SqlToGraphiteConfig(assemblyResolver, log);
     reader = MockRepository.GenerateMock<IConfigReader>();
     cache = MockRepository.GenerateMock<ICache>();
     sleep = MockRepository.GenerateMock<ISleep>();
     log = MockRepository.GenerateMock<ILog>();
     configPersister = MockRepository.GenerateMock<IConfigPersister>();
     genericSerializer = MockRepository.GenerateMock<IGenericSerializer>();
     repository = new ConfigRepository(this.reader, this.cache, this.sleep, this.log, this.sleepTime, this.configPersister, this.genericSerializer);
 }
        public SqlToGraphiteConfig(IAssemblyResolver assemblyResolver, ILog log)
        {
            this.log = log;
            var job = new JobImpl();
            jobTypes = assemblyResolver.ResolveTypes(job);
            //JobTypes = GetJobTypes().ToArray();
            clientTypes = GetClientTypes().ToArray();

            this.Jobs = new List<Job>();
            this.Clients = new ListOfUniqueType<Client>();
            this.Hosts = new List<Host>();
            this.Templates = new List<Template>();
            this.genericSerializer = new GenericSerializer(Global.GetNameSpace());
        }
Beispiel #30
0
        public ModuleLoader(IAssemblyResolver resolver, ILog logger, Action<string, AggregateCatalog> addToCatalog, Func<CompositionContainer, IEnumerable<Lazy<IModule, IModuleMetadata>>> getModules)
        {
            _resolver = resolver;
            _logger = logger;
            if (addToCatalog == null)
                addToCatalog = (p, catalog) => catalog.Catalogs.Add(new AssemblyCatalog(p));

            _addToCatalog = addToCatalog;

            if (getModules == null)
                getModules = (container) => container.GetExports<IModule, IModuleMetadata>();

            _getModules = getModules;
        }
Beispiel #31
0
 public static DnSpyFile Create(ModuleDef module, bool loadSyms, IAssemblyResolver asmResolver)
 {
     module.Context = CreateModuleContext(asmResolver);
     return(new DotNetFile(module, loadSyms));
 }
Beispiel #32
0
 public Processor(IAssemblyResolver resolver, ModuleDefinition module)
 {
     _resolver = resolver;
     _module   = module;
 }
Beispiel #33
0
 /// <summary>
 /// Initializes the fields of the R2RHeader and R2RMethods
 /// </summary>
 /// <param name="filename">PE image</param>
 /// <exception cref="BadImageFormatException">The Cor header flag must be ILLibrary</exception>
 public unsafe ReadyToRunReader(IAssemblyResolver assemblyResolver, string filename)
 {
     _assemblyResolver = assemblyResolver;
     Filename          = filename;
     Initialize(metadata: null);
 }
 /// <summary>
 /// Removes a module's assembly from the cache
 /// </summary>
 /// <param name="self">this</param>
 /// <param name="module">The module</param>
 /// <returns><c>true</c> if its assembly was removed, <c>false</c> if it wasn't removed
 /// since it wasn't in the cache, it has no assembly, or <paramref name="module"/> was
 /// <c>null</c></returns>
 public static bool Remove(this IAssemblyResolver self, ModuleDef module)
 {
     return(module != null && self.Remove(module.Assembly));
 }
 /// <summary>
 /// Add a module's assembly to the assembly cache
 /// </summary>
 /// <param name="self">this</param>
 /// <param name="module">The module whose assembly should be cached</param>
 /// <returns><c>true</c> if <paramref name="module"/>'s assembly is cached, <c>false</c>
 /// if it's not cached because some other assembly with the exact same full name has
 /// already been cached or if <paramref name="module"/> or its assembly is <c>null</c>.</returns>
 public static bool AddToCache(this IAssemblyResolver self, ModuleDef module)
 {
     return(module != null && self.AddToCache(module.Assembly));
 }
Beispiel #36
0
 public static Task <DecompilerTypeSystem> CreateAsync(PEFile mainModule, IAssemblyResolver assemblyResolver, DecompilerSettings settings)
 {
     return(CreateAsync(mainModule, assemblyResolver, GetOptions(settings ?? throw new ArgumentNullException(nameof(settings)))));
 }
        public override bool Execute()
        {
            var outputDir = MergeOutputDir;

            Directory.CreateDirectory(outputDir);

            var restoreMap = BuildRestoreMap(RestoreAssemblyResources);

            if (restoreMap == null)
            {
                return(false);
            }

            var changedReferencePaths = new List <ITaskItem> ();
            var removedReferencePaths = new List <ITaskItem> ();

            IAssemblyResolver resolver = null;

            foreach (var asm in restoreMap)
            {
                var       asmName = new AssemblyName(asm.Key);
                ITaskItem item    = FindMatchingAssembly(InputReferencePaths, asmName);
                if (item == null)
                {
                    if (ThrowOnMissingAssembly)
                    {
                        return(false);
                    }
                    else
                    {
                        continue;
                    }
                }

                var originalAsmPath = item.GetMetadata("FullPath");

                //TODO: collision avoidance. AssemblyName MD5? NuGet package ID?
                var mergedAsmPath = Path.Combine(outputDir, asmName.Name + ".dll");

                var mergedFileInfo = new FileInfo(mergedAsmPath);
                if (!mergedFileInfo.Exists || mergedFileInfo.LastWriteTime < File.GetLastWriteTime(originalAsmPath))
                {
                    if (resolver == null)
                    {
                        resolver = CreateAssemblyResolver();
                    }
                    if (!MergeResources(resolver, originalAsmPath, mergedAsmPath, asm.Key, asm.Value))
                    {
                        return(false);
                    }
                }

                removedReferencePaths.Add(item);
                var newItem = new TaskItem(mergedAsmPath);
                item.CopyMetadataTo(newItem);
                changedReferencePaths.Add(newItem);
            }

            ChangedReferencePaths = changedReferencePaths.ToArray();
            RemovedReferencePaths = removedReferencePaths.ToArray();

            return(true);
        }
 public static AssemblyDefinition Resolve(this IAssemblyResolver assemblyResolver, string name)
 {
     return(assemblyResolver.Resolve(new AssemblyNameReference(name, null)));
 }
Beispiel #39
0
 public static Task <DecompilerTypeSystem> CreateAsync(PEFile mainModule, IAssemblyResolver assemblyResolver)
 {
     return(CreateAsync(mainModule, assemblyResolver, TypeSystemOptions.Default));
 }
Beispiel #40
0
 public Checker()
 {
     resolver = new CustomAssemblyResolver(this);
 }
 public MsCoreReferenceFinder(ModuleWeaver moduleWeaver, IAssemblyResolver assemblyResolver)
 {
     _moduleWeaver     = moduleWeaver;
     _assemblyResolver = assemblyResolver;
 }
Beispiel #42
0
        /// <summary>
        /// Enumerates from self to references, recursively, by layers, with a maximum depth (good luck otherwise).
        /// </summary>
        /// <param name="moduleDefinition">The module definition.</param>
        /// <param name="assemblyResolver">The assembly resolver.</param>
        /// <param name="ignoreSystem">if set to <c>true</c> [ignore system].</param>
        /// <param name="maximumDepth">The maximum depth (or -1 to search all).</param>
        /// <returns></returns>
        public static IEnumerable <ModuleDefinition> GetSelfAndReferences(this ModuleDefinition moduleDefinition, IAssemblyResolver assemblyResolver,
                                                                          bool ignoreSystem, int maximumDepth)
        {
            var remainingModules = new List <Tuple <ModuleDefinition, int> > {
                Tuple.Create(moduleDefinition, maximumDepth)
            };
            var discoveredNames = new HashSet <string> {
                moduleDefinition.FullyQualifiedName
            };

            while (remainingModules.Count > 0)
            {
                var thisModule = remainingModules[0].Item1;
                var depth      = remainingModules[0].Item2;
                remainingModules.RemoveAt(0);

                yield return(thisModule);

                // now, recurse
                if (depth != 0)
                {
                    foreach (var referencedModule in thisModule.GetReferencedModules(assemblyResolver, ignoreSystem))
                    {
                        var fullyQualifiedName = referencedModule.FullyQualifiedName;
                        if (!discoveredNames.Contains(fullyQualifiedName))
                        {
                            remainingModules.Add(Tuple.Create(referencedModule, depth - 1));
                            discoveredNames.Add(fullyQualifiedName);
                        }
                    }
                }
            }
        }
 /// <summary>
 /// Initializes a new instance of the <see cref="FileModuleTypeLoader"/> class.
 /// </summary>
 /// <param name="assemblyResolver">The assembly resolver.</param>
 public FileModuleTypeLoader(IAssemblyResolver assemblyResolver)
 {
     this.assemblyResolver = assemblyResolver;
 }
Beispiel #44
0
 public GraphQlTypePool(IAssemblyResolver assemblyResolver)
 {
     _assemblyResolver = assemblyResolver;
 }
Beispiel #45
0
 public WholeProjectDecompiler(IAssemblyResolver assemblyResolver)
     : this(new DecompilerSettings(), assemblyResolver, assemblyReferenceClassifier : null, debugInfoProvider : null)
 {
 }
Beispiel #46
0
 /// <summary>
 /// Constructor
 /// </summary>
 /// <param name="assemblyResolver">Assembly resolver or <c>null</c></param>
 public ModuleContext(IAssemblyResolver assemblyResolver)
     : this(assemblyResolver, new Resolver(assemblyResolver))
 {
 }
Beispiel #47
0
        /****
        ** Assembly parsing
        ****/
        /// <summary>Get a list of referenced local assemblies starting from the mod assembly, ordered from leaf to root.</summary>
        /// <param name="file">The assembly file to load.</param>
        /// <param name="visitedAssemblyNames">The assembly names that should be skipped.</param>
        /// <param name="assemblyResolver">A resolver which resolves references to known assemblies.</param>
        /// <returns>Returns the rewrite metadata for the preprocessed assembly.</returns>
        private IEnumerable <AssemblyParseResult> GetReferencedLocalAssemblies(FileInfo file, HashSet <string> visitedAssemblyNames, IAssemblyResolver assemblyResolver)
        {
            // validate
            if (file.Directory == null)
            {
                throw new InvalidOperationException($"Could not get directory from file path '{file.FullName}'.");
            }
            if (!file.Exists)
            {
                yield break; // not a local assembly
            }
            // read assembly
            byte[]             assemblyBytes = File.ReadAllBytes(file.FullName);
            Stream             readStream    = this.TrackForDisposal(new MemoryStream(assemblyBytes));
            AssemblyDefinition assembly      = this.TrackForDisposal(AssemblyDefinition.ReadAssembly(readStream, new ReaderParameters(ReadingMode.Immediate)
            {
                AssemblyResolver = assemblyResolver, InMemory = true
            }));

            // skip if already visited
            if (visitedAssemblyNames.Contains(assembly.Name.Name))
            {
                yield return(new AssemblyParseResult(file, null, AssemblyLoadStatus.AlreadyLoaded));

                yield break;
            }
            visitedAssemblyNames.Add(assembly.Name.Name);

            // yield referenced assemblies
            foreach (AssemblyNameReference dependency in assembly.MainModule.AssemblyReferences)
            {
                FileInfo dependencyFile = new FileInfo(Path.Combine(file.Directory.FullName, $"{dependency.Name}.dll"));
                foreach (AssemblyParseResult result in this.GetReferencedLocalAssemblies(dependencyFile, visitedAssemblyNames, assemblyResolver))
                {
                    yield return(result);
                }
            }

            // yield assembly
            yield return(new AssemblyParseResult(file, assembly, AssemblyLoadStatus.Okay));
        }
Beispiel #48
0
 public DecompilerTypeSystem(PEFile mainModule, IAssemblyResolver assemblyResolver, DecompilerSettings settings)
     : this(mainModule, assemblyResolver, GetOptions(settings ?? throw new ArgumentNullException(nameof(settings))))
 internal AggregationBinderEFFake(ODataQuerySettings settings, IAssemblyResolver assembliesResolver, Type elementType, IEdmModel model, TransformationNode transformation)
     : base(settings, assembliesResolver, elementType, model, transformation)
 {
 }
 public static AssemblyDefinition GetAssembly(this IAssemblyResolver resolver, string fileName)
 {
     return(resolver.Resolve(AssemblyNameReference.Parse(Path.GetFileNameWithoutExtension(fileName))));
 }
 void ITestModelBuilder.AddAssemblyResolver(IAssemblyResolver resolver)
 {
     throw new NotSupportedException();
 }
Beispiel #52
0
 public CachedResolver(IAssemblyResolver resolver)
 {
     Resolver = resolver;
     cache    = new Dictionary <string, AssemblyDefinition> (StringComparer.Ordinal);
 }
Beispiel #53
0
        /// <summary>
        /// Resolves the common Stiletto assembly, loads it into memory, and
        /// extracts types and methods so they can be imported into woven
        /// modules.
        /// </summary>
        /// <param name="assemblyResolver">
        /// The <see cref="IAssemblyResolver"/> instance provided by Fody.
        /// </param>
        /// <returns>
        /// Returns a selection of relevant types and methods from Stiletto.
        /// </returns>
        public static StilettoReferences Create(IAssemblyResolver assemblyResolver)
        {
            var stiletto = assemblyResolver.Resolve("Stiletto").MainModule;
            var types    = stiletto
                           .GetAllTypes()
                           .Where(t => t.IsPublic)
                           .ToDictionary(t => t.FullName, t => t, StringComparer.Ordinal);

            var tBinding                   = types["Stiletto.Internal.Binding"];
            var tBinding_ctor              = tBinding.GetMethod(".ctor");
            var tBinding_GetDependencies   = tBinding.GetMethod("GetDependencies");
            var tBinding_Resolve           = tBinding.GetMethod("Resolve");
            var tBinding_Get               = tBinding.GetMethod("Get");
            var tBinding_InjectProperties  = tBinding.GetMethod("InjectProperties");
            var tBinding_RequiredBy_Getter = tBinding.GetProperty("RequiredBy").GetMethod;
            var tBinding_IsLibrary_Setter  = tBinding.GetProperty("IsLibrary").SetMethod;

            var tProviderMethodBindingBase      = types["Stiletto.Internal.ProviderMethodBindingBase"];
            var tProviderMethodBingingBase_ctor = tProviderMethodBindingBase.GetMethod(".ctor");

            var tRuntimeModule               = types["Stiletto.Internal.RuntimeModule"];
            var tRuntimeModule_ctor          = tRuntimeModule.GetMethod(".ctor");
            var tRuntimeModule_module_getter = tRuntimeModule.GetProperty("Module").GetMethod;

            var tContainer                   = types["Stiletto.Container"];
            var tContainer_Create            = tContainer.GetMethod("Create");
            var tContainer_CreateWithPlugins = tContainer.GetMethod("CreateWithPlugins");

            var tPlugin = types["Stiletto.Internal.IPlugin"];
            var tPlugin_GetInjectBinding         = tPlugin.GetMethod("GetInjectBinding");
            var tPlugin_GetLazyInjectBinding     = tPlugin.GetMethod("GetLazyInjectBinding");
            var tPlugin_GetProviderInjectBinding = tPlugin.GetMethod("GetIProviderInjectBinding");
            var tPlugin_GetRuntimeModule         = tPlugin.GetMethod("GetRuntimeModule");

            var tResolver = types["Stiletto.Internal.Resolver"];
            var tResolver_RequestBinding = tResolver.GetMethod("RequestBinding");

            var tProviderOfT     = types["Stiletto.IProvider`1"];
            var tProviderOfT_Get = tProviderOfT.GetMethod("Get");

            var tInjectAttribute    = types["Stiletto.InjectAttribute"];
            var tModuleAttribute    = types["Stiletto.ModuleAttribute"];
            var tProvidesAttribute  = types["Stiletto.ProvidesAttribute"];
            var tNamedAttribute     = types["Stiletto.NamedAttribute"];
            var tSingletonAttribute = types["Stiletto.SingletonAttribute"];

            var tProcessedAssemblyAttribute      = types["Stiletto.Internal.Plugins.Codegen.ProcessedAssemblyAttribute"];
            var tProcessedAssemblyAttribute_Ctor = tProcessedAssemblyAttribute.GetDefaultConstructor();

            return(new StilettoReferences
            {
                Binding = tBinding,
                Binding_Ctor = tBinding_ctor,
                Binding_GetDependencies = tBinding_GetDependencies,
                Binding_Resolve = tBinding_Resolve,
                Binding_Get = tBinding_Get,
                Binding_InjectProperties = tBinding_InjectProperties,
                Binding_RequiredBy_Getter = tBinding_RequiredBy_Getter,
                Binding_IsLibrary_Setter = tBinding_IsLibrary_Setter,

                ProviderMethodBindingBase = tProviderMethodBindingBase,
                ProviderMethodBindingBase_Ctor = tProviderMethodBingingBase_ctor,

                RuntimeModule = tRuntimeModule,
                RuntimeModule_Ctor = tRuntimeModule_ctor,
                RuntimeModule_Module_Getter = tRuntimeModule_module_getter,

                Container = tContainer,
                Container_Create = tContainer_Create,
                Container_CreateWithPlugins = tContainer_CreateWithPlugins,

                IPlugin = tPlugin,
                IPlugin_GetInjectBinding = tPlugin_GetInjectBinding,
                IPlugin_GetLazyInjectBinding = tPlugin_GetLazyInjectBinding,
                IPlugin_GetIProviderInjectBinding = tPlugin_GetProviderInjectBinding,
                IPlugin_GetRuntimeModue = tPlugin_GetRuntimeModule,

                Resolver = tResolver,
                Resolver_RequestBinding = tResolver_RequestBinding,

                IProviderOfT = tProviderOfT,
                IProviderOfT_Get = tProviderOfT_Get,

                InjectAttribute = tInjectAttribute,
                ModuleAttribute = tModuleAttribute,
                ProvidesAttribute = tProvidesAttribute,
                NamedAttribute = tNamedAttribute,
                SingletonAttribute = tSingletonAttribute,

                ProcessedAssemblyAttribute = tProcessedAssemblyAttribute,
                ProcessedAssemblyAttribute_Ctor = tProcessedAssemblyAttribute_Ctor
            });
        }
        public static ReaderParameters ReaderParameters(string assemblyPath, IEnumerable <string> extraPaths, IAssemblyResolver assemblyResolver, string unityEngineDLLPath, string unityUNetDLLPath)
        {
            var parameters = new ReaderParameters();

            if (assemblyResolver == null)
            {
                assemblyResolver = new DefaultAssemblyResolver();
            }
            var helper = new AddSearchDirectoryHelper(assemblyResolver);

            helper.AddSearchDirectory(Path.GetDirectoryName(assemblyPath));
            helper.AddSearchDirectory(Helpers.UnityEngineDLLDirectoryName());
            helper.AddSearchDirectory(Path.GetDirectoryName(unityEngineDLLPath));
            helper.AddSearchDirectory(Path.GetDirectoryName(unityUNetDLLPath));
            if (extraPaths != null)
            {
                foreach (var path in extraPaths)
                {
                    helper.AddSearchDirectory(path);
                }
            }
            parameters.AssemblyResolver     = assemblyResolver;
            parameters.SymbolReaderProvider = GetSymbolReaderProvider(assemblyPath);
            return(parameters);
        }
Beispiel #55
0
        public static async Task <DecompilerTypeSystem> CreateAsync(PEFile mainModule, IAssemblyResolver assemblyResolver, TypeSystemOptions typeSystemOptions)
        {
            if (mainModule == null)
            {
                throw new ArgumentNullException(nameof(mainModule));
            }
            if (assemblyResolver == null)
            {
                throw new ArgumentNullException(nameof(assemblyResolver));
            }
            var ts = new DecompilerTypeSystem();
            await ts.InitializeAsync(mainModule, assemblyResolver, typeSystemOptions)
            .ConfigureAwait(false);

            return(ts);
        }
Beispiel #56
0
        /// <summary>
        /// Gets the references for the given module.
        /// </summary>
        /// <param name="moduleDefinition">The module definition.</param>
        /// <param name="assemblyResolver">The assembly resolver.</param>
        /// <param name="ignoreSystem">if set to <c>true</c> [ignore system].</param>
        /// <returns></returns>
        private static IEnumerable <ModuleDefinition> GetReferencedModules(this ModuleDefinition moduleDefinition, IAssemblyResolver assemblyResolver, bool ignoreSystem)
        {
            var assemblyDefinitions = moduleDefinition.AssemblyReferences
                                      .Where(ar => !ignoreSystem || !IsSystem(ar))
                                      .Select(r => TryResolve(assemblyResolver, r)).Where(a => a != null);

            return(assemblyDefinitions.Select(a => a.MainModule));
        }
Beispiel #57
0
 public DecompilerTypeSystem(PEFile mainModule, IAssemblyResolver assemblyResolver)
     : this(mainModule, assemblyResolver, TypeSystemOptions.Default)
 {
 }
        /// <summary>
        /// Gets the references for the given module.
        /// </summary>
        /// <param name="moduleDefinition">The module definition.</param>
        /// <param name="assemblyResolver">The assembly resolver.</param>
        /// <param name="ignoreSystem">if set to <c>true</c> [ignore system].</param>
        /// <param name="logging">The logging.</param>
        /// <param name="isMainModule">if set to <c>true</c> [is main module].</param>
        /// <returns></returns>
        private static IEnumerable <ModuleDef> GetReferencedModules(this ModuleDef moduleDefinition, IAssemblyResolver assemblyResolver, bool ignoreSystem, ILogging logging, bool isMainModule)
        {
            var assemblyDefinitions = moduleDefinition.GetAssemblyRefs()
                                      .Where(ar => !ignoreSystem || !IsSystem(ar))
                                      .Select(r => TryResolve(assemblyResolver, r, moduleDefinition, logging, isMainModule)).Where(a => a != null);

            return(assemblyDefinitions.Select(a => a.GetMainModule()));
        }
Beispiel #59
0
        static bool Weave(string assName, IEnumerable <string> dependencies, IAssemblyResolver assemblyResolver, string unityEngineDLLPath, string mirrorNetDLLPath, string outputDir)
        {
            using (DefaultAssemblyResolver asmResolver = new DefaultAssemblyResolver())
                using (CurrentAssembly = AssemblyDefinition.ReadAssembly(assName, new ReaderParameters {
                    ReadWrite = true, AssemblyResolver = asmResolver
                }))
                {
                    asmResolver.AddSearchDirectory(Path.GetDirectoryName(assName));
                    asmResolver.AddSearchDirectory(Helpers.UnityEngineDLLDirectoryName());
                    asmResolver.AddSearchDirectory(Path.GetDirectoryName(unityEngineDLLPath));
                    asmResolver.AddSearchDirectory(Path.GetDirectoryName(mirrorNetDLLPath));
                    if (dependencies != null)
                    {
                        foreach (string path in dependencies)
                        {
                            asmResolver.AddSearchDirectory(path);
                        }
                    }

                    SetupTargetTypes();
                    Readers.Init(CurrentAssembly);
                    Writers.Init(CurrentAssembly);

                    ModuleDefinition moduleDefinition = CurrentAssembly.MainModule;
                    Console.WriteLine("Script Module: {0}", moduleDefinition.Name);

                    // Process each NetworkBehaviour
                    bool didWork = false;

                    // We need to do 2 passes, because SyncListStructs might be referenced from other modules, so we must make sure we generate them first.
                    for (int pass = 0; pass < 2; pass++)
                    {
                        System.Diagnostics.Stopwatch watch = System.Diagnostics.Stopwatch.StartNew();
                        foreach (TypeDefinition td in moduleDefinition.Types)
                        {
                            if (td.IsClass && td.BaseType.CanBeResolved())
                            {
                                try
                                {
                                    if (pass == 0)
                                    {
                                        didWork |= CheckSyncList(td);
                                    }
                                    else
                                    {
                                        didWork |= CheckNetworkBehaviour(td);
                                        didWork |= CheckMessageBase(td);
                                    }
                                }
                                catch (Exception ex)
                                {
                                    Weaver.Error(ex.Message);
                                    throw ex;
                                }
                            }

                            if (WeavingFailed)
                            {
                                return(false);
                            }
                        }
                        watch.Stop();
                        Console.WriteLine("Pass: "******" took " + watch.ElapsedMilliseconds + " milliseconds");
                    }

                    if (didWork)
                    {
                        // this must be done for ALL code, not just NetworkBehaviours
                        try
                        {
                            PropertySiteProcessor.ProcessSitesModule(CurrentAssembly.MainModule);
                        }
                        catch (Exception e)
                        {
                            Log.Error("ProcessPropertySites exception: " + e);
                            return(false);
                        }

                        if (WeavingFailed)
                        {
                            //Log.Error("Failed phase II.");
                            return(false);
                        }

                        // write to outputDir if specified, otherwise perform in-place write
                        if (outputDir != null)
                        {
                            CurrentAssembly.Write(Helpers.DestinationFileFor(outputDir, assName));
                        }
                        else
                        {
                            CurrentAssembly.Write();
                        }
                    }
                }

            return(true);
        }
Beispiel #60
0
        public static bool WeaveAssemblies(IEnumerable <string> assemblies, IEnumerable <string> dependencies, IAssemblyResolver assemblyResolver, string outputDir, string unityEngineDLLPath, string mirrorNetDLLPath)
        {
            WeavingFailed = false;
            WeaveLists    = new WeaverLists();

            using (UnityAssembly = AssemblyDefinition.ReadAssembly(unityEngineDLLPath))
                using (NetAssembly = AssemblyDefinition.ReadAssembly(mirrorNetDLLPath))
                {
                    SetupUnityTypes();

                    try
                    {
                        foreach (string ass in assemblies)
                        {
                            if (!Weave(ass, dependencies, assemblyResolver, unityEngineDLLPath, mirrorNetDLLPath, outputDir))
                            {
                                return(false);
                            }
                        }
                    }
                    catch (Exception e)
                    {
                        Log.Error("Exception :" + e);
                        return(false);
                    }
                }
            return(true);
        }