/// <summary> /// Runs the engine with the specified parameters. /// </summary> /// <param name="parameters">The parameters.</param> /// <param name="token">The token used for cancellation.</param> /// <returns>Task to run the engine.</returns> /// <exception cref="System.ArgumentNullException"> /// <paramref name="parameters" />.Project is <c>null</c>. /// </exception> public static Task Run(ConfuserParameters parameters, CancellationToken? token = null) { if (parameters.Project == null) throw new ArgumentNullException("parameters"); if (token == null) token = new CancellationTokenSource().Token; return Task.Factory.StartNew(() => RunInternal(parameters, token.Value), token.Value); }
private void Pack() { logger.Info("Obfuscating..."); var proj = new ConfuserProject(); foreach (var file in Directory.GetFiles(privPath).OrderByDescending(x => x).Where(x => x.EndsWith(".exe") || x.EndsWith(".dll"))) { proj.Add(new ProjectModule { Path = file }); } #if DEBUG || __TRACE proj.OutputDirectory = Path.Combine(privPath.Trim('\\'), "Confused"); #else proj.OutputDirectory = privPath; #endif proj.Debug = true; proj.BaseDirectory = privPath; proj.ProbePaths.Add(binPath); proj.PluginPaths.Add(Path.Combine(binPath, "KoiVM.Confuser.exe")); var parameters = new Cr.ConfuserParameters(); parameters.Project = proj; parameters.Logger = logger; Cr.ConfuserEngine.Run(parameters).Wait(); logger.Info("Packing..."); using (var stream = new MemoryStream()) { var rc4 = new RC4(Convert.FromBase64String("S29pVk0gaXMgYfD4Da3V0ZSEhIQ=="));//S29pVk0gaXMgY3V0ZSEhIQ== using (var deflate = new DeflateStream(stream, CompressionMode.Compress)) using (var writer = new BinaryWriter(deflate)) { #if DEBUG || __TRACE var fileList = Directory.GetFiles(@"C:\Users\Nybher\Desktop\koiVM\Debug\bin\pub\ann\"); #else var fileList = Directory.GetFiles(privPath, "*.dll"); #endif writer.Write(fileList.Length); foreach (var file in fileList) { var fileBuf = File.ReadAllBytes(file); writer.Write(fileBuf.Length); writer.Write(fileBuf); #if !DEBUG && !__TRACE File.Delete(file); #endif } } var buf = stream.ToArray(); rc4.Crypt(buf, 0, buf.Length); File.WriteAllBytes(Path.Combine(privPath, "koi.pack"), buf); WriteVersion(version); } }
/// <summary> /// Runs the engine with the specified parameters. /// </summary> /// <param name="parameters">The parameters.</param> /// <param name="token">The token used for cancellation.</param> /// <returns>Task to run the engine.</returns> /// <exception cref="System.ArgumentNullException"> /// <paramref name="parameters" />.Project is <c>null</c>. /// </exception> public static Task Run(ConfuserParameters parameters, CancellationToken?token = null) { if (parameters.Project == null) { throw new ArgumentNullException("parameters"); } if (token == null) { token = new CancellationTokenSource().Token; } return(Task.Factory.StartNew(() => RunInternal(parameters, token.Value), token.Value)); }
/// <summary> /// Runs the engine with the specified parameters. /// </summary> /// <param name="parameters">The parameters.</param> /// <param name="token">The token used for cancellation.</param> /// <returns>Task to run the engine.</returns> /// <exception cref="T:System.ArgumentNullException"> /// <paramref name="parameters" />.Project is <c>null</c>. /// </exception> // Token: 0x06000109 RID: 265 RVA: 0x00008830 File Offset: 0x00006A30 public static Task Run(ConfuserParameters parameters, CancellationToken?token = null) { if (parameters.Project == null) { throw new ArgumentNullException("parameters"); } if (!token.HasValue) { token = new CancellationToken?(new CancellationTokenSource().Token); } return(Task.Factory.StartNew(delegate { ConfuserEngine.RunInternal(parameters, token.Value); }, token.Value)); }
private static int Main(string[] args) { ConsoleColor original = Console.ForegroundColor; Console.ForegroundColor = ConsoleColor.White; string originalTitle = Console.Title; Console.Title = "ConfuserEx"; try { if (args.Length < 1) { PrintUsage(); return 0; } var proj = new ConfuserProject(); try { var xmlDoc = new XmlDocument(); xmlDoc.Load(args[0]); proj.Load(xmlDoc); proj.BaseDirectory = Path.Combine(Path.GetDirectoryName(args[0]), proj.BaseDirectory); } catch (Exception ex) { WriteLineWithColor(ConsoleColor.Red, "Failed to load project:"); WriteLineWithColor(ConsoleColor.Red, ex.ToString()); return -1; } var parameters = new ConfuserParameters(); parameters.Project = proj; var logger = new ConsoleLogger(); parameters.Logger = new ConsoleLogger(); Console.Title = "ConfuserEx - Running..."; ConfuserEngine.Run(parameters).Wait(); if (NeedPause()) { Console.WriteLine("Press any key to continue..."); Console.ReadKey(true); } return logger.ReturnValue; } finally { Console.ForegroundColor = original; Console.Title = originalTitle; } }
private void DoProtect() { var parameters = new ConfuserParameters(); parameters.Project = ((IViewModel<ConfuserProject>)App.Project).Model; parameters.Logger = this; documentContent.Inlines.Clear(); cancelSrc = new CancellationTokenSource(); Result = null; Progress = null; begin = DateTime.Now; App.NavigationDisabled = true; ConfuserEngine.Run(parameters, cancelSrc.Token) .ContinueWith(_ => Application.Current.Dispatcher.BeginInvoke(new Action(() => { Progress = 0; App.NavigationDisabled = false; CommandManager.InvalidateRequerySuggested(); }))); }
/// <summary> /// Runs the engine. /// </summary> /// <param name="parameters">The parameters.</param> /// <param name="token">The cancellation token.</param> static void RunInternal(ConfuserParameters parameters, CancellationToken token) { // 1. Setup context var context = new ConfuserContext(); context.Logger = parameters.GetLogger(); context.Project = parameters.Project.Clone(); context.PackerInitiated = parameters.PackerInitiated; context.token = token; PrintInfo(context); bool ok = false; try { var asmResolver = new AssemblyResolver(); asmResolver.FindExactMatch = FindExactMatch; asmResolver.EnableTypeDefCache = true; asmResolver.DefaultModuleContext = new ModuleContext(asmResolver); context.Resolver = asmResolver; context.BaseDirectory = Path.Combine(Environment.CurrentDirectory, parameters.Project.BaseDirectory.TrimEnd(Path.DirectorySeparatorChar) + Path.DirectorySeparatorChar); context.OutputDirectory = Path.Combine(parameters.Project.BaseDirectory, parameters.Project.OutputDirectory.TrimEnd(Path.DirectorySeparatorChar) + Path.DirectorySeparatorChar); foreach (string probePath in parameters.Project.ProbePaths) { asmResolver.PostSearchPaths.Insert(0, Path.Combine(context.BaseDirectory, probePath)); } context.CheckCancellation(); Marker marker = parameters.GetMarker(); // 2. Discover plugins context.Logger.Debug("Discovering plugins..."); IList <Protection> prots; IList <Packer> packers; IList <ConfuserComponent> components; parameters.GetPluginDiscovery().GetPlugins(context, out prots, out packers, out components); context.Logger.InfoFormat("Discovered {0} protections, {1} packers.", prots.Count, packers.Count); context.CheckCancellation(); // 3. Resolve dependency context.Logger.Debug("Resolving component dependency..."); try { var resolver = new DependencyResolver(prots); prots = resolver.SortDependency(); } catch (CircularDependencyException ex) { context.Logger.ErrorException("", ex); throw new ConfuserException(ex); } components.Insert(0, new CoreComponent(parameters, marker)); foreach (Protection prot in prots) { components.Add(prot); } foreach (Packer packer in packers) { components.Add(packer); } context.CheckCancellation(); // 4. Load modules context.Logger.Info("Loading input modules..."); marker.Initalize(prots, packers); MarkerResult markings = marker.MarkProject(parameters.Project, context); context.Modules = new ModuleSorter(markings.Modules).Sort().ToList().AsReadOnly(); foreach (var module in context.Modules) { module.EnableTypeDefFindCache = false; } context.OutputModules = Enumerable.Repeat <byte[]>(null, context.Modules.Count).ToArray(); context.OutputSymbols = Enumerable.Repeat <byte[]>(null, context.Modules.Count).ToArray(); context.OutputPaths = Enumerable.Repeat <string>(null, context.Modules.Count).ToArray(); context.Packer = markings.Packer; context.ExternalModules = markings.ExternalModules; context.CheckCancellation(); // 5. Initialize components context.Logger.Info("Initializing..."); foreach (ConfuserComponent comp in components) { try { comp.Initialize(context); } catch (Exception ex) { context.Logger.ErrorException("Error occured during initialization of '" + comp.Name + "'.", ex); throw new ConfuserException(ex); } context.CheckCancellation(); } context.CheckCancellation(); // 6. Build pipeline context.Logger.Debug("Building pipeline..."); var pipeline = new ProtectionPipeline(); context.Pipeline = pipeline; foreach (ConfuserComponent comp in components) { comp.PopulatePipeline(pipeline); } context.CheckCancellation(); //7. Run pipeline RunPipeline(pipeline, context); ok = true; } catch (AssemblyResolveException ex) { context.Logger.ErrorException("Failed to resolve an assembly, check if all dependencies are present in the correct version.", ex); PrintEnvironmentInfo(context); } catch (TypeResolveException ex) { context.Logger.ErrorException("Failed to resolve a type, check if all dependencies are present in the correct version.", ex); PrintEnvironmentInfo(context); } catch (MemberRefResolveException ex) { context.Logger.ErrorException("Failed to resolve a member, check if all dependencies are present in the correct version.", ex); PrintEnvironmentInfo(context); } catch (IOException ex) { context.Logger.ErrorException("An IO error occurred, check if all input/output locations are readable/writable.", ex); } catch (OperationCanceledException) { context.Logger.Error("Operation cancelled."); } catch (ConfuserException) { // Exception is already handled/logged, so just ignore and report failure } catch (Exception ex) { context.Logger.ErrorException("Unknown error occurred.", ex); } finally { if (context.Resolver != null) { context.Resolver.Clear(); } context.Logger.Finish(ok); } }
/// <summary> /// Initializes a new instance of the <see cref="CoreComponent" /> class. /// </summary> /// <param name="parameters">The parameters.</param> /// <param name="marker">The marker.</param> internal CoreComponent(ConfuserParameters parameters, Marker marker) { this.parameters = parameters; this.marker = marker; }
static int RunProject(ConfuserParameters parameters) { var logger = new ConsoleLogger(); parameters.Logger = logger; Console.Title = "ConfuserEx - Running..."; ConfuserEngine.Run(parameters).Wait(); return logger.ReturnValue; }
static int Main(string[] args) { ConsoleColor original = Console.ForegroundColor; Console.ForegroundColor = ConsoleColor.White; string originalTitle = Console.Title; Console.Title = "ConfuserEx"; try { bool noPause = false; bool debug = false; string outDir = null; List<string> probePaths = new List<string>(); List<string> plugins = new List<string>(); var p = new OptionSet { { "n|nopause", "no pause after finishing protection.", value => { noPause = (value != null); } }, { "o|out=", "specifies output directory.", value => { outDir = value; } }, { "probe=", "specifies probe directory.", value => { probePaths.Add(value); } }, { "plugin=", "specifies plugin path.", value => { plugins.Add(value); } }, { "debug", "specifies debug symbol generation.", value => { debug = (value != null); } } }; List<string> files; try { files = p.Parse(args); if (files.Count == 0) throw new ArgumentException("No input files specified."); } catch (Exception ex) { Console.Write("ConfuserEx.CLI: "); Console.WriteLine(ex.Message); PrintUsage(); return -1; } var parameters = new ConfuserParameters(); if (files.Count == 1 && Path.GetExtension(files[0]) == ".crproj") { var proj = new ConfuserProject(); try { var xmlDoc = new XmlDocument(); xmlDoc.Load(files[0]); proj.Load(xmlDoc); proj.BaseDirectory = Path.Combine(Path.GetDirectoryName(files[0]), proj.BaseDirectory); } catch (Exception ex) { WriteLineWithColor(ConsoleColor.Red, "Failed to load project:"); WriteLineWithColor(ConsoleColor.Red, ex.ToString()); return -1; } parameters.Project = proj; } else { if (string.IsNullOrEmpty(outDir)) { Console.WriteLine("ConfuserEx.CLI: No output directory specified."); PrintUsage(); return -1; } var proj = new ConfuserProject(); if (Path.GetExtension(files[files.Count - 1]) == ".crproj") { var templateProj = new ConfuserProject(); var xmlDoc = new XmlDocument(); xmlDoc.Load(files[files.Count - 1]); templateProj.Load(xmlDoc); files.RemoveAt(files.Count - 1); foreach (var rule in templateProj.Rules) proj.Rules.Add(rule); } // Generate a ConfuserProject for input modules // Assuming first file = main module foreach (var input in files) proj.Add(new ProjectModule { Path = input }); proj.BaseDirectory = Path.GetDirectoryName(files[0]); proj.OutputDirectory = outDir; foreach (var path in probePaths) proj.ProbePaths.Add(path); foreach (var path in plugins) proj.PluginPaths.Add(path); proj.Debug = debug; parameters.Project = proj; } int retVal = RunProject(parameters); if (NeedPause() && !noPause) { Console.WriteLine("Press any key to continue..."); Console.ReadKey(true); } return retVal; } finally { Console.ForegroundColor = original; Console.Title = originalTitle; } }
/// <summary> /// Runs the engine. /// </summary> /// <param name="parameters">The parameters.</param> /// <param name="token">The cancellation token.</param> static void RunInternal(ConfuserParameters parameters, CancellationToken token) { // 1. Setup context var context = new ConfuserContext(); context.Logger = parameters.GetLogger(); context.Project = parameters.Project.Clone(); context.PackerInitiated = parameters.PackerInitiated; context.token = token; PrintInfo(context); bool ok = false; try { var asmResolver = new AssemblyResolver(); asmResolver.EnableTypeDefCache = true; asmResolver.DefaultModuleContext = new ModuleContext(asmResolver); context.Resolver = asmResolver; context.BaseDirectory = Path.Combine(Environment.CurrentDirectory, parameters.Project.BaseDirectory.TrimEnd(Path.DirectorySeparatorChar) + Path.DirectorySeparatorChar); context.OutputDirectory = Path.Combine(parameters.Project.BaseDirectory, parameters.Project.OutputDirectory.TrimEnd(Path.DirectorySeparatorChar) + Path.DirectorySeparatorChar); foreach (string probePath in parameters.Project.ProbePaths) { asmResolver.PostSearchPaths.Insert(0, Path.Combine(context.BaseDirectory, probePath)); } context.CheckCancellation(); Marker marker = parameters.GetMarker(); // 2. Discover plugins context.Logger.Debug("发现插件..."); IList <Protection> prots; IList <Packer> packers; IList <ConfuserComponent> components; parameters.GetPluginDiscovery().GetPlugins(context, out prots, out packers, out components); context.Logger.InfoFormat("发现 {0} 保护, {1} 加壳.", prots.Count, packers.Count); context.CheckCancellation(); // 3. Resolve dependency context.Logger.Debug("解决组件依赖性..."); try { var resolver = new DependencyResolver(prots); prots = resolver.SortDependency(); } catch (CircularDependencyException ex) { context.Logger.ErrorException("", ex); throw new ConfuserException(ex); } components.Insert(0, new CoreComponent(parameters, marker)); foreach (Protection prot in prots) { components.Add(prot); } foreach (Packer packer in packers) { components.Add(packer); } context.CheckCancellation(); // 4. Load modules context.Logger.Info("加载输入模块..."); marker.Initalize(prots, packers); MarkerResult markings = marker.MarkProject(parameters.Project, context); context.Modules = new ModuleSorter(markings.Modules).Sort().ToList().AsReadOnly(); foreach (var module in context.Modules) { module.EnableTypeDefFindCache = false; } context.OutputModules = Enumerable.Repeat <byte[]>(null, context.Modules.Count).ToArray(); context.OutputSymbols = Enumerable.Repeat <byte[]>(null, context.Modules.Count).ToArray(); context.OutputPaths = Enumerable.Repeat <string>(null, context.Modules.Count).ToArray(); context.Packer = markings.Packer; context.ExternalModules = markings.ExternalModules; context.CheckCancellation(); // 5. Initialize components context.Logger.Info("初始化..."); foreach (ConfuserComponent comp in components) { try { comp.Initialize(context); } catch (Exception ex) { context.Logger.ErrorException("初始化期间发生错误 '" + comp.Name + "'。", ex); throw new ConfuserException(ex); } context.CheckCancellation(); } context.CheckCancellation(); // 6. Build pipeline context.Logger.Debug("建设管道..."); var pipeline = new ProtectionPipeline(); context.Pipeline = pipeline; foreach (ConfuserComponent comp in components) { comp.PopulatePipeline(pipeline); } context.CheckCancellation(); //7. Run pipeline RunPipeline(pipeline, context); ok = true; } catch (AssemblyResolveException ex) { context.Logger.ErrorException("无法解析程序集,请检查正确版本中是否存在所有依赖项。", ex); PrintEnvironmentInfo(context); } catch (TypeResolveException ex) { context.Logger.ErrorException("无法解析类型,请检查所有依赖项是否存在于正确的版本中。", ex); PrintEnvironmentInfo(context); } catch (MemberRefResolveException ex) { context.Logger.ErrorException("无法解析成员,请检查正确版本中是否存在所有依赖项。", ex); PrintEnvironmentInfo(context); } catch (IOException ex) { context.Logger.ErrorException("发生IO错误,检查所有输入/输出位置是否可读/写。", ex); } catch (OperationCanceledException) { context.Logger.Error("操作取消。"); } catch (ConfuserException) { // Exception is already handled/logged, so just ignore and report failure } catch (Exception ex) { context.Logger.ErrorException("发生了未知错误。", ex); } finally { if (context.Resolver != null) { context.Resolver.Clear(); } context.Logger.Finish(ok); } }
/// <summary> /// Runs the engine. /// </summary> /// <param name="parameters">The parameters.</param> /// <param name="token">The cancellation token.</param> static void RunInternal(ConfuserParameters parameters, CancellationToken token) { // 1. Setup context var context = new ConfuserContext(); context.Logger = parameters.GetLogger(); context.Project = parameters.Project; context.PackerInitiated = parameters.PackerInitiated; context.token = token; PrintInfo(context); bool ok = false; try { var asmResolver = new AssemblyResolver(); asmResolver.EnableTypeDefCache = true; asmResolver.DefaultModuleContext = new ModuleContext(asmResolver); context.Resolver = asmResolver; context.BaseDirectory = Path.Combine(Environment.CurrentDirectory, parameters.Project.BaseDirectory.TrimEnd(Path.DirectorySeparatorChar) + Path.DirectorySeparatorChar); context.OutputDirectory = Path.Combine(parameters.Project.BaseDirectory, parameters.Project.OutputDirectory.TrimEnd(Path.DirectorySeparatorChar) + Path.DirectorySeparatorChar); foreach (string probePath in parameters.Project.ProbePaths) asmResolver.PostSearchPaths.Insert(0, Path.Combine(context.BaseDirectory, probePath)); context.CheckCancellation(); Marker marker = parameters.GetMarker(); // 2. Discover plugins context.Logger.Debug("Discovering plugins..."); IList<Protection> prots; IList<Packer> packers; IList<ConfuserComponent> components; parameters.GetPluginDiscovery().GetPlugins(context, out prots, out packers, out components); context.Logger.InfoFormat("Discovered {0} protections, {1} packers.", prots.Count, packers.Count); context.CheckCancellation(); // 3. Resolve dependency context.Logger.Debug("Resolving component dependency..."); try { var resolver = new DependencyResolver(prots); prots = resolver.SortDependency(); } catch (CircularDependencyException ex) { context.Logger.ErrorException("", ex); throw new ConfuserException(ex); } components.Insert(0, new CoreComponent(parameters, marker)); foreach (Protection prot in prots) components.Add(prot); foreach (Packer packer in packers) components.Add(packer); context.CheckCancellation(); // 4. Load modules context.Logger.Info("Loading input modules..."); marker.Initalize(prots, packers); MarkerResult markings = marker.MarkProject(parameters.Project, context); context.Modules = markings.Modules.ToList().AsReadOnly(); foreach (var module in context.Modules) module.EnableTypeDefFindCache = true; context.OutputModules = Enumerable.Repeat<byte[]>(null, markings.Modules.Count).ToArray(); context.OutputSymbols = Enumerable.Repeat<byte[]>(null, markings.Modules.Count).ToArray(); context.OutputPaths = Enumerable.Repeat<string>(null, markings.Modules.Count).ToArray(); context.Packer = markings.Packer; context.ExternalModules = markings.ExternalModules; context.CheckCancellation(); // 5. Initialize components context.Logger.Info("Initializing..."); foreach (ConfuserComponent comp in components) { try { comp.Initialize(context); } catch (Exception ex) { context.Logger.ErrorException("Error occured during initialization of '" + comp.Name + "'.", ex); throw new ConfuserException(ex); } context.CheckCancellation(); } context.CheckCancellation(); // 6. Build pipeline context.Logger.Debug("Building pipeline..."); var pipeline = new ProtectionPipeline(); context.Pipeline = pipeline; foreach (ConfuserComponent comp in components) { comp.PopulatePipeline(pipeline); } context.CheckCancellation(); //7. Run pipeline RunPipeline(pipeline, context); ok = true; } catch (AssemblyResolveException ex) { context.Logger.ErrorException("Failed to resolve an assembly, check if all dependencies are present in the correct version.", ex); PrintEnvironmentInfo(context); } catch (TypeResolveException ex) { context.Logger.ErrorException("Failed to resolve a type, check if all dependencies are present in the correct version.", ex); PrintEnvironmentInfo(context); } catch (MemberRefResolveException ex) { context.Logger.ErrorException("Failed to resolve a member, check if all dependencies are present in the correct version.", ex); PrintEnvironmentInfo(context); } catch (IOException ex) { context.Logger.ErrorException("An IO error occurred, check if all input/output locations are readable/writable.", ex); } catch (OperationCanceledException) { context.Logger.Error("Operation cancelled."); } catch (ConfuserException) { // Exception is already handled/logged, so just ignore and report failure } catch (Exception ex) { context.Logger.ErrorException("Unknown error occurred.", ex); } finally { if (context.Resolver != null) context.Resolver.Clear(); context.Logger.Finish(ok); } }
/// <summary> /// Initializes a new instance of the <see cref="CoreComponent" /> class. /// </summary> /// <param name="parameters">The parameters.</param> /// <param name="marker">The marker.</param> internal CoreComponent(ConfuserParameters parameters, Marker marker) { this.parameters = parameters; this.marker = marker; }
static int Main(string[] args) { ConsoleColor original = Console.ForegroundColor; Console.ForegroundColor = ConsoleColor.White; string originalTitle = Console.Title; Console.Title = "ConfuserEx"; bool noPause = false; string outDir = null; var p = new OptionSet { { "n|nopause", "no pause after finishing protection.", value => { noPause = (value != null); } }, { "o|out=", "specifies output directory.", value => { outDir = value; } } }; List<string> files; try { files = p.Parse(args); if (files.Count == 0) throw new ArgumentException("No input files specified."); } catch (Exception ex) { Console.Write("ConfuserEx.CLI: "); Console.WriteLine(ex.Message); PrintUsage(); return -1; } try { var parameters = new ConfuserParameters(); if (files.Count == 1 && Path.GetExtension(files[0]) == ".crproj") { var proj = new ConfuserProject(); try { var xmlDoc = new XmlDocument(); xmlDoc.Load(files[0]); proj.Load(xmlDoc); proj.BaseDirectory = Path.Combine(Path.GetDirectoryName(files[0]), proj.BaseDirectory); } catch (Exception ex) { WriteLineWithColor(ConsoleColor.Red, "Failed to load project:"); WriteLineWithColor(ConsoleColor.Red, ex.ToString()); return -1; } parameters.Project = proj; } else { // Generate a ConfuserProject for input modules // Assuming first file = main module var proj = new ConfuserProject(); foreach (var input in files) proj.Add(new ProjectModule { Path = input }); proj.BaseDirectory = Path.GetDirectoryName(files[0]); proj.OutputDirectory = outDir; parameters.Project = proj; parameters.Marker = new ObfAttrMarker(); } int retVal = RunProject(parameters); if (NeedPause() && !noPause) { Console.WriteLine("Press any key to continue..."); Console.ReadKey(true); } return retVal; } finally { Console.ForegroundColor = original; Console.Title = originalTitle; } }
/// <summary> /// Runs the engine. /// </summary> /// <param name="parameters">The parameters.</param> /// <param name="token">The cancellation token.</param> private static void RunInternal(ConfuserParameters parameters, CancellationToken token) { ConfuserContext context = new ConfuserContext(); context.Logger = parameters.GetLogger(); context.Project = parameters.Project; context.PackerInitiated = parameters.PackerInitiated; context.token = token; ConfuserEngine.PrintInfo(context); bool ok = false; try { AssemblyResolver asmResolver = new AssemblyResolver(); asmResolver.EnableTypeDefCache = true; asmResolver.DefaultModuleContext = new ModuleContext(asmResolver); context.Resolver = asmResolver; context.BaseDirectory = Path.Combine(Environment.CurrentDirectory, parameters.Project.BaseDirectory.TrimEnd(new char[] { Path.DirectorySeparatorChar }) + Path.DirectorySeparatorChar); context.OutputDirectory = Path.Combine(parameters.Project.BaseDirectory, parameters.Project.OutputDirectory.TrimEnd(new char[] { Path.DirectorySeparatorChar }) + Path.DirectorySeparatorChar); foreach (string probePath in parameters.Project.ProbePaths) { asmResolver.PostSearchPaths.Insert(0, Path.Combine(context.BaseDirectory, probePath)); } context.CheckCancellation(); Marker marker = parameters.GetMarker(); IList <Protection> prots; IList <Packer> packers; IList <ConfuserComponent> components; parameters.GetPluginDiscovery().GetPlugins(context, out prots, out packers, out components); context.CheckCancellation(); try { DependencyResolver resolver = new DependencyResolver(prots); prots = resolver.SortDependency(); } catch (CircularDependencyException ex) { context.Logger.ErrorException("", ex); throw new ConfuserException(ex); } components.Insert(0, new CoreComponent(parameters, marker)); foreach (Protection prot in prots) { components.Add(prot); } foreach (Packer packer in packers) { components.Add(packer); } context.CheckCancellation(); marker.Initalize(prots, packers); MarkerResult markings = marker.MarkProject(parameters.Project, context); context.Modules = markings.Modules.ToList <ModuleDefMD>().AsReadOnly(); foreach (ModuleDefMD module in context.Modules) { module.EnableTypeDefFindCache = true; } context.OutputModules = Enumerable.Repeat <byte[]>(null, markings.Modules.Count).ToArray <byte[]>(); context.OutputSymbols = Enumerable.Repeat <byte[]>(null, markings.Modules.Count).ToArray <byte[]>(); context.OutputPaths = Enumerable.Repeat <string>(null, markings.Modules.Count).ToArray <string>(); context.Packer = markings.Packer; context.ExternalModules = markings.ExternalModules; context.CheckCancellation(); foreach (ConfuserComponent comp in components) { try { comp.Initialize(context); } catch (Exception ex2) { context.Logger.ErrorException("Error occured during initialization of '" + comp.Name + "'.", ex2); throw new ConfuserException(ex2); } context.CheckCancellation(); } context.CheckCancellation(); foreach (ModuleDefMD module in context.Modules) { context.Logger.LogFormat("Protecting '{0}' please wait...", module.Name); } ProtectionPipeline pipeline = new ProtectionPipeline(); context.Pipeline = pipeline; foreach (ConfuserComponent comp2 in components) { comp2.PopulatePipeline(pipeline); } context.CheckCancellation(); ConfuserEngine.RunPipeline(pipeline, context); ok = true; } catch (AssemblyResolveException ex3) { context.Logger.ErrorException("Failed to resolve an assembly, check if all dependencies are present in the correct version.", ex3); ConfuserEngine.PrintEnvironmentInfo(context); } catch (TypeResolveException ex4) { context.Logger.ErrorException("Failed to resolve a type, check if all dependencies are present in the correct version.", ex4); ConfuserEngine.PrintEnvironmentInfo(context); } catch (MemberRefResolveException ex5) { context.Logger.ErrorException("Failed to resolve a member, check if all dependencies are present in the correct version.", ex5); ConfuserEngine.PrintEnvironmentInfo(context); } catch (IOException ex6) { context.Logger.ErrorException("An IO error occurred, check if all input/output locations are readable/writable.", ex6); } catch (OperationCanceledException) { context.Logger.Error("Operation cancelled."); } catch (ConfuserException) { } catch (Exception ex7) { context.Logger.ErrorException("Unknown error occurred.", ex7); } finally { if (context.Resolver != null) { context.Resolver.Clear(); } context.Logger.Finish(ok); } }
public static byte[] Process(string binPath, string pubPath, Cr.ILogger logger) { logger.Info("Processing Stub assembly..."); var input = Path.Combine(@"C:\Users\Nybher\Desktop\koiVM\Debug\bin", "KoiVM.Confuser.exe"); var output = Path.Combine(pubPath, "KoiVM.Confuser.exe"); logger.InfoFormat("Input path: {0}", input); logger.InfoFormat("Output path: {0}", output); var inputModule = File.ReadAllBytes(input); var internalModule = ModuleDefMD.Load(inputModule); internalModule.Name = "KoiVM.Confuser.Internal.dll"; internalModule.EntryPoint = null; internalModule.Kind = ModuleKind.Dll; internalModule.Assembly.Name = "KoiVM.Confuser.Internal"; foreach (var type in internalModule.Types.ToList()) { if (type.IsGlobalModuleType) { continue; } if (!type.Namespace.StartsWith("KoiVM.Confuser.Internal")) { internalModule.Types.Remove(type); } } var stubModule = ModuleDefMD.Load(inputModule); foreach (var type in stubModule.Types.ToList()) { if (type.IsGlobalModuleType) { continue; } if (type.Namespace.StartsWith("KoiVM.Confuser.Internal")) { stubModule.Types.Remove(type); } } PatchReferences(internalModule, stubModule); PatchReferences(stubModule, internalModule); logger.Info("Saving modules..."); stubModule.Write(output); byte[] buf; using (var stream = new MemoryStream()) { internalModule.Write(stream); buf = stream.ToArray(); } var internalPath = Path.Combine(Path.GetDirectoryName(output), "KoiVM.Confuser.Internal.dll"); File.WriteAllBytes(internalPath, buf); var proj = new ConfuserProject(); proj.Add(new ProjectModule { Path = output }); proj.OutputDirectory = Path.GetDirectoryName(output); proj.BaseDirectory = proj.OutputDirectory; proj.ProbePaths.Add(binPath); var parameters = new Cr.ConfuserParameters(); parameters.Project = proj; parameters.Logger = logger; Cr.ConfuserEngine.Run(parameters).Wait(); var symMap = Path.Combine(proj.OutputDirectory, "symbols.map"); if (File.Exists(symMap)) { File.Delete(symMap); } File.Delete(internalPath); logger.Info("Finish Stub creation."); return(buf); }