예제 #1
0
        /// <summary>
        ///     Runs the protection pipeline.
        /// </summary>
        /// <param name="pipeline">The protection pipeline.</param>
        /// <param name="context">The context.</param>
        static void RunPipeline(ProtectionPipeline pipeline, ConfuserContext context)
        {
            Func <IList <IDnlibDef> >            getAllDefs    = () => context.Modules.SelectMany(module => module.FindDefinitions()).ToList();
            Func <ModuleDef, IList <IDnlibDef> > getModuleDefs = module => module.FindDefinitions().ToList();

            context.CurrentModuleIndex = -1;

            pipeline.ExecuteStage(PipelineStage.Inspection, Inspection, () => getAllDefs(), context);

            var options   = new ModuleWriterOptionsBase[context.Modules.Count];
            var listeners = new ModuleWriterListener[context.Modules.Count];

            for (int i = 0; i < context.Modules.Count; i++)
            {
                context.CurrentModuleIndex          = i;
                context.CurrentModuleWriterOptions  = null;
                context.CurrentModuleWriterListener = null;

                pipeline.ExecuteStage(PipelineStage.BeginModule, BeginModule, () => getModuleDefs(context.CurrentModule), context);
                pipeline.ExecuteStage(PipelineStage.ProcessModule, ProcessModule, () => getModuleDefs(context.CurrentModule), context);
                pipeline.ExecuteStage(PipelineStage.OptimizeMethods, OptimizeMethods, () => getModuleDefs(context.CurrentModule), context);
                pipeline.ExecuteStage(PipelineStage.EndModule, EndModule, () => getModuleDefs(context.CurrentModule), context);

                options[i]   = context.CurrentModuleWriterOptions;
                listeners[i] = context.CurrentModuleWriterListener;
            }

            for (int i = 0; i < context.Modules.Count; i++)
            {
                context.CurrentModuleIndex          = i;
                context.CurrentModuleWriterOptions  = options[i];
                context.CurrentModuleWriterListener = listeners[i];

                pipeline.ExecuteStage(PipelineStage.WriteModule, WriteModule, () => getModuleDefs(context.CurrentModule), context);

                context.OutputModules[i]            = context.CurrentModuleOutput;
                context.OutputSymbols[i]            = context.CurrentModuleSymbol;
                context.CurrentModuleWriterOptions  = null;
                context.CurrentModuleWriterListener = null;
                context.CurrentModuleOutput         = null;
                context.CurrentModuleSymbol         = null;
            }

            context.CurrentModuleIndex = -1;

            pipeline.ExecuteStage(PipelineStage.Debug, Debug, () => getAllDefs(), context);
            pipeline.ExecuteStage(PipelineStage.Pack, Pack, () => getAllDefs(), context);
            pipeline.ExecuteStage(PipelineStage.SaveModules, SaveModules, () => getAllDefs(), context);

            if (!context.PackerInitiated)
            {
                context.Logger.Info("Done.");
            }
        }
        /// <summary>
        ///     Runs the protection pipeline.
        /// </summary>
        /// <param name="pipeline">The protection pipeline.</param>
        /// <param name="context">The context.</param>
        // Token: 0x0600010B RID: 267 RVA: 0x00009030 File Offset: 0x00007230
        private static void RunPipeline(ProtectionPipeline pipeline, ConfuserContext context)
        {
            Func <IList <IDnlibDef> >            getAllDefs    = () => context.Modules.SelectMany((ModuleDefMD module) => module.FindDefinitions()).ToList <IDnlibDef>();
            Func <ModuleDef, IList <IDnlibDef> > getModuleDefs = (ModuleDef module) => module.FindDefinitions().ToList <IDnlibDef>();

            context.CurrentModuleIndex = -1;
            pipeline.ExecuteStage(PipelineStage.Inspection, new Action <ConfuserContext>(ConfuserEngine.Inspection), () => getAllDefs(), context);
            ModuleWriterOptionsBase[] options   = new ModuleWriterOptionsBase[context.Modules.Count];
            ModuleWriterListener[]    listeners = new ModuleWriterListener[context.Modules.Count];
            for (int i = 0; i < context.Modules.Count; i++)
            {
                context.CurrentModuleIndex          = i;
                context.CurrentModuleWriterOptions  = null;
                context.CurrentModuleWriterListener = null;
                pipeline.ExecuteStage(PipelineStage.BeginModule, new Action <ConfuserContext>(ConfuserEngine.BeginModule), () => getModuleDefs(context.CurrentModule), context);
                pipeline.ExecuteStage(PipelineStage.ProcessModule, new Action <ConfuserContext>(ConfuserEngine.ProcessModule), () => getModuleDefs(context.CurrentModule), context);
                pipeline.ExecuteStage(PipelineStage.OptimizeMethods, new Action <ConfuserContext>(ConfuserEngine.OptimizeMethods), () => getModuleDefs(context.CurrentModule), context);
                pipeline.ExecuteStage(PipelineStage.EndModule, new Action <ConfuserContext>(ConfuserEngine.EndModule), () => getModuleDefs(context.CurrentModule), context);
                options[i]   = context.CurrentModuleWriterOptions;
                listeners[i] = context.CurrentModuleWriterListener;
            }
            for (int j = 0; j < context.Modules.Count; j++)
            {
                context.CurrentModuleIndex          = j;
                context.CurrentModuleWriterOptions  = options[j];
                context.CurrentModuleWriterListener = listeners[j];
                pipeline.ExecuteStage(PipelineStage.WriteModule, new Action <ConfuserContext>(ConfuserEngine.WriteModule), () => getModuleDefs(context.CurrentModule), context);
                context.OutputModules[j]            = context.CurrentModuleOutput;
                context.OutputSymbols[j]            = context.CurrentModuleSymbol;
                context.CurrentModuleWriterOptions  = null;
                context.CurrentModuleWriterListener = null;
                context.CurrentModuleOutput         = null;
                context.CurrentModuleSymbol         = null;
            }
            context.CurrentModuleIndex = -1;
            pipeline.ExecuteStage(PipelineStage.Debug, new Action <ConfuserContext>(ConfuserEngine.Debug), () => getAllDefs(), context);
            pipeline.ExecuteStage(PipelineStage.Pack, new Action <ConfuserContext>(ConfuserEngine.Pack), () => getAllDefs(), context);
            pipeline.ExecuteStage(PipelineStage.SaveModules, new Action <ConfuserContext>(ConfuserEngine.SaveModules), () => getAllDefs(), context);
            if (!context.PackerInitiated)
            {
                context.Logger.Info("Done.");
            }
        }
예제 #3
0
 /// <summary>
 ///     Execute the specified pipeline stage with pre-processing and post-processing.
 /// </summary>
 /// <param name="stage">The pipeline stage.</param>
 /// <param name="func">The stage function.</param>
 /// <param name="targets">The target list of the stage.</param>
 /// <param name="context">The working context.</param>
 // Token: 0x060002FD RID: 765 RVA: 0x0001298C File Offset: 0x00010B8C
 internal void ExecuteStage(PipelineStage stage, Action <ConfuserContext> func, Func <IList <IDnlibDef> > targets, ConfuserContext context)
 {
     foreach (ProtectionPhase pre in this.preStage[stage])
     {
         context.CheckCancellation();
         context.Logger.DebugFormat("Executing '{0}' phase...", new object[]
         {
             pre.Name
         });
         pre.Execute(context, new ProtectionParameters(pre.Parent, ProtectionPipeline.Filter(context, targets(), pre)));
     }
     context.CheckCancellation();
     func(context);
     context.CheckCancellation();
     foreach (ProtectionPhase post in this.postStage[stage])
     {
         context.Logger.DebugFormat("Executing '{0}' phase...", new object[]
         {
             post.Name
         });
         post.Execute(context, new ProtectionParameters(post.Parent, ProtectionPipeline.Filter(context, targets(), post)));
         context.CheckCancellation();
     }
 }
예제 #4
0
        /// <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);
            }
        }
예제 #5
0
 /// <inheritdoc />
 protected internal override void PopulatePipeline(ProtectionPipeline pipeline)
 {
     //
 }
        /// <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);
            }
        }
예제 #7
0
 /// <inheritdoc />
 protected internal override void PopulatePipeline(ProtectionPipeline pipeline) =>
 pipeline.InsertPostStage(PipelineStage.EndModule, new WatermarkingPhase(this));
예제 #8
0
 /// <summary>
 ///     Inserts protection stages into processing pipeline.
 /// </summary>
 /// <param name="pipeline">The processing pipeline.</param>
 // Token: 0x0600012F RID: 303
 protected internal abstract void PopulatePipeline(ProtectionPipeline pipeline);
예제 #9
0
        /// <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);
            }
        }