/// <summary> /// Rewrites the assemblies specified in the configuration. /// </summary> private static void RewriteAssemblies() { try { if (string.IsNullOrEmpty(Configuration.RewritingConfigurationFile)) { // We are rewriting a dll directly, so we fake up a default configuration for doing this. var fullPath = Path.GetFullPath(Configuration.AssemblyToBeAnalyzed); var assemblyDir = Path.GetDirectoryName(fullPath); Console.WriteLine($". Rewriting {fullPath}"); var config = Rewriting.Configuration.Create(assemblyDir, assemblyDir, new HashSet <string>(new string[] { fullPath })); config.PlatformVersion = Configuration.PlatformVersion; AssemblyRewriter.Rewrite(config); } else { Console.WriteLine($". Rewriting the assemblies specified in {Configuration.RewritingConfigurationFile}"); var config = Rewriting.Configuration.ParseFromJSON(Configuration.RewritingConfigurationFile); config.PlatformVersion = Configuration.PlatformVersion; AssemblyRewriter.Rewrite(config); } Console.WriteLine($". Done rewriting"); } catch (Exception ex) { Debug.WriteLine(ex.StackTrace); Error.ReportAndExit(ex.Message); } }
public override bool Execute() { List <string> assemblySearchPaths = this.References.Select(Path.GetDirectoryName).Distinct(StringComparer.OrdinalIgnoreCase).ToList(); AssemblyRewriter rewriter = new AssemblyRewriter(new TaskOutputWriter(this.Log)); return(rewriter.TryRewriteAssembly(this.AssemblyPath, this.AssemblyPath, assemblySearchPaths)); }
public static int Main(string[] args) { if (args.Length < 1 || args.Length > 2) { Console.WriteLine("Usage:"); Console.WriteLine(" LogSpectRewriter <inputAssemblyPath>"); Console.WriteLine(" LogSpectRewriter <inputAssemblyPath> <outputAssemblyPath>"); Console.WriteLine(); Console.WriteLine("Possible exit codes:"); Console.WriteLine(" 0 - Rewrite was successful"); Console.WriteLine(" 1 - Invalid arguments"); Console.WriteLine(" 2 - Input file doesn't exist"); Console.WriteLine(" 3 - Unexpected exception"); return(1); } string inputAssemblyPath = args[0]; string outputAssemblyPath = args.Length > 1 ? args[1] : inputAssemblyPath; if (!File.Exists(inputAssemblyPath)) { Console.WriteLine("Input file doesn't exist: {0}", inputAssemblyPath); return(2); } AssemblyRewriter rewriter = new AssemblyRewriter(new ConsoleOutputWriter()); bool success = rewriter.TryRewriteAssembly(inputAssemblyPath, outputAssemblyPath, null); return(success ? 0 : 3); }
private IAssemblyRewriter CreateAssemblyRewriter(Delegate @delegate, Configuration configuration) { var dependencyGraph = _dependencyGraphBuilder.BuildGraphForMethod(@delegate.Method); var setups = _setupExtractor.GetSetups(@delegate.Method, @delegate.Target).ToList(); var eventSetups = _eventTargetExtractor.GetTargets(@delegate.Method, @delegate.Target).ToList(); var moduleFilter = _moduleFilterFactory.GetFilter(configuration.Scope, dependencyGraph); var rewriter = new AssemblyRewriter(configuration, setups.Concat(eventSetups), _serviceLocator.Resolve <IMethodRewriter>(), moduleFilter); return(rewriter); }
public bool Execute(string outputPath, ILogger logger = null) { if (logger == null) { logger = new DummyLogger(); } try { if (string.IsNullOrEmpty(AssemblyPath)) { throw new InvalidOperationException($"You have to specify {nameof(AssemblyPath)} for {nameof(AssemblyRewrite)} task."); } if (!File.Exists(AssemblyPath)) { throw new FileNotFoundException($"Unable to find assembly '{AssemblyPath}'."); } filePathResolver.AddSearchPath(Path.GetDirectoryName(Path.GetFullPath(AssemblyPath))); logger.Progress($"Loading configuration '{ConfigurationPath ?? string.Empty}'."); var configuration = LoadConfiguration(); configuration.Check(); logger.Progress("Loading configuration done."); var rewriter = new AssemblyRewriter(AssemblyPath, logger); AppDomain.CurrentDomain.AssemblyResolve += CurrentDomain_AssemblyResolve; logger.Progress("Loading processors."); LoadProcessors(rewriter, configuration, logger); logger.Progress("Loading processors done."); rewriter.ProcessAssemblyAndSave(outputPath); } catch (Exception e) { logger.Error(e.ToString()); return(false); } return(true); }
private void LoadProcessors(AssemblyRewriter assemblyRewriter, AssemblyRewriteConfiguration configuration, [NotNull] ILogger logger) { var assembliesDict = new Dictionary <string, LazyAssembly>(); foreach (var assemblyCfg in configuration.Assemblies) { var lazyAssemblyDefinition = new Lazy <AssemblyDefinition>(() => LoadProcessorsAssemblyDefinition(assemblyCfg.Path)); var lazyAssembly = new Lazy <Assembly>(() => LoadProcessorsAssembly(assemblyCfg.Path, lazyAssemblyDefinition.Value)); assembliesDict.Add(assemblyCfg.Alias, new LazyAssembly(lazyAssembly, lazyAssemblyDefinition)); } var typeAliasResolver = new TypeAliasResolver( assembliesDict.ToDictionary(kv => kv.Key, kv => kv.Value.AssemblyDefinition), assembliesDict.ToDictionary(kv => kv.Key, kv => kv.Value.Assembly), configuration.Types.ToDictionary(t => t.Alias, t => new TypeAliasResolver.TypeAliasDefinition(t.AssemblyAlias, t.Name))); var processors = LoadProcessors(configuration.Processors, logger, assembliesDict, typeAliasResolver); foreach (var processor in processors) { if (processor.SupportedComponents.Count == 0) { throw new InvalidOperationException($"Processor '{processor.GetType().FullName}' contains no supported components."); } foreach (var supportedComponent in processor.SupportedComponents) { switch (supportedComponent) { case ProcessableComponentType.Assembly: assemblyRewriter.AssemblyProcessors.Add(processor); break; case ProcessableComponentType.Module: assemblyRewriter.ModuleProcessors.Add(processor); break; case ProcessableComponentType.Type: assemblyRewriter.TypeProcessors.Add(processor); break; case ProcessableComponentType.Field: assemblyRewriter.FieldProcessors.Add(processor); break; case ProcessableComponentType.Property: assemblyRewriter.PropertyProcessors.Add(processor); break; case ProcessableComponentType.Method: assemblyRewriter.MethodProcessors.Add(processor); break; case ProcessableComponentType.MethodParameter: assemblyRewriter.ParameterProcessors.Add(processor); break; default: throw new InvalidOperationException($"Unknown {nameof(ProcessableComponentType)}: '{supportedComponent}'."); } } } }
public static int Main(string[] _args) { try { var options = new RewriteOptions(); foreach (var arg in _args) { ParseArgument(arg, options); } var argv = _args.Where(arg => !arg.StartsWith("-")).ToArray(); var step = (options.Overwrite || options.Audit) ? 1 : 2; if (argv.Length < step) { Usage(); return(1); } int exitCode = 0; for (int i = 0; i < argv.Length; i += step) { var src = argv[i]; var dst = options.Overwrite || options.Audit ? src : argv[i + 1]; if (options.Audit) { Console.WriteLine($"// {src}{Environment.NewLine}===="); } else if (options.Verbose) { Console.WriteLine($"// {Path.GetFileName (src)} -> {Path.GetFullPath (dst)}...{Environment.NewLine}===="); } else if (argv.Length > step) { Console.WriteLine($"// {Path.GetFileName (src)} -> {Path.GetFullPath (dst)}"); } var wroteOk = false; try { var assemblyResolver = new DefaultAssemblyResolver(); assemblyResolver.AddSearchDirectory(Path.GetDirectoryName(src)); using (var def = AssemblyDefinition.ReadAssembly(src, new ReaderParameters { ReadWrite = options.Overwrite, ReadingMode = ReadingMode.Deferred, AssemblyResolver = assemblyResolver, ReadSymbols = options.EnableSymbols, SymbolReaderProvider = new DefaultSymbolReaderProvider(throwIfNoSymbol: false) })) { var arw = new AssemblyRewriter(def, options); int errorCount = arw.Rewrite(); if (options.Mark) { def.Name.Name = Path.GetFileNameWithoutExtension(dst); } if (!options.Audit) { if (errorCount > 0 && false) { Console.Error.WriteLine($"// Not saving due to error(s): {dst}"); exitCode += 1; } else { var shouldWriteSymbols = options.EnableSymbols && def.MainModule.SymbolReader != null; if (options.Overwrite) { def.Write(); } else { def.Write(dst + ".tmp", new WriterParameters { WriteSymbols = shouldWriteSymbols, DeterministicMvid = true }); } wroteOk = true; } } } } catch (Exception exc) { Console.Error.WriteLine("Unhandled exception while rewriting {0}. Continuing...", src); Console.Error.WriteLine(exc); exitCode += 1; } if (wroteOk && !options.Overwrite) { File.Copy(dst + ".tmp", dst, true); if (File.Exists(dst + ".pdb")) { File.Copy(dst + ".pdb", dst.Replace(".exe", ".pdb"), true); File.Delete(dst + ".pdb"); } File.Delete(dst + ".tmp"); } } return(exitCode); } finally { if (Debugger.IsAttached) { Console.WriteLine("Press enter to exit"); Console.ReadLine(); } } }