当前位置: 首页>>代码示例>>C#>>正文


C# ConfuserContext.CheckCancellation方法代码示例

本文整理汇总了C#中Confuser.Core.ConfuserContext.CheckCancellation方法的典型用法代码示例。如果您正苦于以下问题:C# ConfuserContext.CheckCancellation方法的具体用法?C# ConfuserContext.CheckCancellation怎么用?C# ConfuserContext.CheckCancellation使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在Confuser.Core.ConfuserContext的用法示例。


在下文中一共展示了ConfuserContext.CheckCancellation方法的14个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。

示例1: Execute

		protected override void Execute(ConfuserContext context, ProtectionParameters parameters) {
			var service = (NameService)context.Registry.GetService<INameService>();
			context.Logger.Debug("Building VTables & identifier list...");
			foreach (IDnlibDef def in parameters.Targets.WithProgress(context.Logger)) {
				ParseParameters(def, context, service, parameters);

				if (def is ModuleDef) {
					var module = (ModuleDef)def;
					foreach (Resource res in module.Resources)
						service.SetOriginalName(res, res.Name);
				}
				else
					service.SetOriginalName(def, def.Name);

				if (def is TypeDef) {
					service.GetVTables().GetVTable((TypeDef)def);
					service.SetOriginalNamespace(def, ((TypeDef)def).Namespace);
				}
				context.CheckCancellation();
			}

			context.Logger.Debug("Analyzing...");
			RegisterRenamers(context, service);
			IList<IRenamer> renamers = service.Renamers;
			foreach (IDnlibDef def in parameters.Targets.WithProgress(context.Logger)) {
				Analyze(service, context, parameters, def, true);
				context.CheckCancellation();
			}
		}
开发者ID:EmilZhou,项目名称:ConfuserEx,代码行数:29,代码来源:AnalyzePhase.cs

示例2: MarkProject

        protected override MarkerResult MarkProject(ConfuserProject proj, ConfuserContext context)
        {
            crossModuleAttrs = new Dictionary<string, Dictionary<Regex, List<ObfuscationAttributeInfo>>>();
            this.context = context;
            project = proj;
            extModules = new List<byte[]>();

            var modules = new List<Tuple<ProjectModule, ModuleDefMD>>();
            foreach (ProjectModule module in proj) {
                ModuleDefMD modDef = module.Resolve(proj.BaseDirectory, context.Resolver.DefaultModuleContext);
                context.CheckCancellation();

                context.Resolver.AddToCache(modDef);
                modules.Add(Tuple.Create(module, modDef));
            }
            foreach (var module in modules) {
                context.Logger.InfoFormat("Loading '{0}'...", module.Item1.Path);

                MarkModule(module.Item2, module == modules[0]);

                // Packer parameters are stored in modules
                if (packer != null)
                    ProtectionParameters.GetParameters(context, module.Item2)[packer] = packerParams;
            }
            return new MarkerResult(modules.Select(module => module.Item2).ToList(), packer, extModules);
        }
开发者ID:cybercircuits,项目名称:ConfuserEx,代码行数:26,代码来源:ObfAttrMarker.cs

示例3: Execute

		protected override void Execute(ConfuserContext context, ProtectionParameters parameters) {
			var service = (NameService)context.Registry.GetService<INameService>();

			foreach (IRenamer renamer in service.Renamers) {
				foreach (IDnlibDef def in parameters.Targets)
					renamer.PostRename(context, service, parameters, def);
				context.CheckCancellation();
			}
		}
开发者ID:EmilZhou,项目名称:ConfuserEx,代码行数:9,代码来源:PostRenamePhase.cs

示例4: Execute

        protected override void Execute(ConfuserContext context, ProtectionParameters parameters)
        {
            var service = (NameService)context.Registry.GetService<INameService>();

            context.Logger.Debug("Renaming...");
            foreach (IRenamer renamer in service.Renamers) {
                foreach (IDnlibDef def in parameters.Targets)
                    renamer.PreRename(context, service, def);
                context.CheckCancellation();
            }

            foreach (IDnlibDef def in parameters.Targets.WithProgress(context.Logger)) {
                bool canRename = service.CanRename(def);
                if (def is MethodDef)
                    if (canRename && parameters.GetParameter(context, def, "renameArgs", true)) {
                        foreach (ParamDef param in ((MethodDef)def).ParamDefs)
                            param.Name = null;
                    }

                if (!canRename)
                    continue;

                RenameMode mode = service.GetRenameMode(def);

                IList<INameReference> references = service.GetReferences(def);
                bool cancel = false;
                foreach (INameReference refer in references) {
                    cancel |= refer.ShouldCancelRename();
                    if (cancel) break;
                }
                if (cancel)
                    continue;

                if (def is TypeDef) {
                    var typeDef = (TypeDef)def;
                    if (parameters.GetParameter(context, def, "flatten", true)) {
                        typeDef.Name = service.ObfuscateName(typeDef.FullName, mode);
                        typeDef.Namespace = "";
                    }
                    else {
                        typeDef.Namespace = service.ObfuscateName(typeDef.Namespace, mode);
                        typeDef.Name = service.ObfuscateName(typeDef.Name, mode);
                    }
                }
                else
                    def.Name = service.ObfuscateName(def.Name, mode);

                foreach (INameReference refer in references.ToList()) {
                    if (!refer.UpdateNameReference(context, service)) {
                        context.Logger.ErrorFormat("Failed to update name reference on '{0}'.", def);
                        throw new ConfuserException(null);
                    }
                }
                context.CheckCancellation();
            }
        }
开发者ID:89sos98,项目名称:ConfuserEx,代码行数:56,代码来源:RenamePhase.cs

示例5: Execute

		protected override void Execute(ConfuserContext context, ProtectionParameters parameters) {
			bool disabledOpti = DisabledOptimization(context.CurrentModule);
			RandomGenerator random = context.Registry.GetService<IRandomService>().GetRandomGenerator(ControlFlowProtection._FullId);

			foreach (MethodDef method in parameters.Targets.OfType<MethodDef>().WithProgress(context.Logger))
				if (method.HasBody && method.Body.Instructions.Count > 0) {
					ProcessMethod(method.Body, ParseParameters(method, context, parameters, random, disabledOpti));
					context.CheckCancellation();
				}
		}
开发者ID:EmilZhou,项目名称:ConfuserEx,代码行数:10,代码来源:ControlFlowPhase.cs

示例6: MarkProject

        /// <inheritdoc />
        protected internal override MarkerResult MarkProject(ConfuserProject proj, ConfuserContext context)
        {
            crossModuleAttrs = new Dictionary<string, Dictionary<Regex, List<ObfuscationAttributeInfo>>>();
            this.context = context;
            project = proj;
            extModules = new List<byte[]>();

            if (proj.Packer != null) {
                if (!packers.ContainsKey(proj.Packer.Id)) {
                    context.Logger.ErrorFormat("Cannot find packer with ID '{0}'.", proj.Packer.Id);
                    throw new ConfuserException(null);
                }

                packer = packers[proj.Packer.Id];
                packerParams = new Dictionary<string, string>(proj.Packer, StringComparer.OrdinalIgnoreCase);
            }

            var modules = new List<Tuple<ProjectModule, ModuleDefMD>>();
            foreach (ProjectModule module in proj) {
                if (module.IsExternal) {
                    extModules.Add(module.LoadRaw(proj.BaseDirectory));
                    continue;
                }

                ModuleDefMD modDef = module.Resolve(proj.BaseDirectory, context.Resolver.DefaultModuleContext);
                context.CheckCancellation();

                context.Resolver.AddToCache(modDef);
                modules.Add(Tuple.Create(module, modDef));
            }
            foreach (var module in modules) {
                context.Logger.InfoFormat("Loading '{0}'...", module.Item1.Path);

                Rules rules = ParseRules(proj, module.Item1, context);
                MarkModule(module.Item1, module.Item2, rules, module == modules[0]);

                context.Annotations.Set(module.Item2, RulesKey, rules);

                // Packer parameters are stored in modules
                if (packer != null)
                    ProtectionParameters.GetParameters(context, module.Item2)[packer] = packerParams;
            }

            if (proj.Debug && proj.Packer != null)
                context.Logger.Warn("Generated Debug symbols might not be usable with packers!");

            return new MarkerResult(modules.Select(module => module.Item2).ToList(), packer, extModules);
        }
开发者ID:JackWangCUMT,项目名称:ConfuserEx,代码行数:49,代码来源:ObfAttrMarker.cs

示例7: BeginModule

        private static void BeginModule(ConfuserContext context)
        {
            context.Logger.InfoFormat("Processing module '{0}'...", context.CurrentModule.Name);

            context.CurrentModuleWriterListener = new ModuleWriterListener();
            context.CurrentModuleWriterListener.OnWriterEvent += (sender, e) => context.CheckCancellation();
            context.CurrentModuleWriterOptions = new ModuleWriterOptions(context.CurrentModule, context.CurrentModuleWriterListener);
            var snKey = context.Annotations.Get<StrongNameKey>(context.CurrentModule, Marker.SNKey);
            context.CurrentModuleWriterOptions.InitializeStrongNameSigning(context.CurrentModule, snKey);

            foreach (TypeDef type in context.CurrentModule.GetTypes())
                foreach (MethodDef method in type.Methods) {
                    if (method.Body != null) {
                        method.Body.Instructions.SimplifyMacros(method.Body.Variables, method.Parameters);
                    }
                }
        }
开发者ID:GavinHwa,项目名称:ConfuserEx,代码行数:17,代码来源:ConfuserEngine.cs

示例8: MarkProject

		/// <summary>
		///     Loads the assembly and marks the project.
		/// </summary>
		/// <param name="proj">The project.</param>
		/// <param name="context">The working context.</param>
		/// <returns><see cref="MarkerResult" /> storing the marked modules and packer information.</returns>
		protected internal virtual MarkerResult MarkProject(ConfuserProject proj, ConfuserContext context) {
			Packer packer = null;
			Dictionary<string, string> packerParams = null;

			if (proj.Packer != null) {
				if (!packers.ContainsKey(proj.Packer.Id)) {
					context.Logger.ErrorFormat("Cannot find packer with ID '{0}'.", proj.Packer.Id);
					throw new ConfuserException(null);
				}
				if (proj.Debug)
					context.Logger.Warn("Generated Debug symbols might not be usable with packers!");

				packer = packers[proj.Packer.Id];
				packerParams = new Dictionary<string, string>(proj.Packer, StringComparer.OrdinalIgnoreCase);
			}

			var modules = new List<Tuple<ProjectModule, ModuleDefMD>>();
			var extModules = new List<byte[]>();
			foreach (ProjectModule module in proj) {
				if (module.IsExternal) {
					extModules.Add(module.LoadRaw(proj.BaseDirectory));
					continue;
				}

				ModuleDefMD modDef = module.Resolve(proj.BaseDirectory, context.Resolver.DefaultModuleContext);
				context.CheckCancellation();

				if (proj.Debug)
					modDef.LoadPdb();

				context.Resolver.AddToCache(modDef);
				modules.Add(Tuple.Create(module, modDef));
			}

			foreach (var module in modules) {
				context.Logger.InfoFormat("Loading '{0}'...", module.Item1.Path);
				Rules rules = ParseRules(proj, module.Item1, context);

				context.Annotations.Set(module.Item2, SNKey, LoadSNKey(context, module.Item1.SNKeyPath == null ? null : Path.Combine(proj.BaseDirectory, module.Item1.SNKeyPath), module.Item1.SNKeyPassword));
				context.Annotations.Set(module.Item2, RulesKey, rules);

				foreach (IDnlibDef def in module.Item2.FindDefinitions()) {
					ApplyRules(context, def, rules);
					context.CheckCancellation();
				}

				// Packer parameters are stored in modules
				if (packerParams != null)
					ProtectionParameters.GetParameters(context, module.Item2)[packer] = packerParams;
			}
			return new MarkerResult(modules.Select(module => module.Item2).ToList(), packer, extModules);
		}
开发者ID:EmilZhou,项目名称:ConfuserEx,代码行数:58,代码来源:Marker.cs

示例9: RunInternal

        /// <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);
                }

//.........这里部分代码省略.........
开发者ID:MetSystem,项目名称:ConfuserEx,代码行数:101,代码来源:ConfuserEngine.cs

示例10: Pack

        protected override void Pack(ConfuserContext context, ProtectionParameters parameters)
        {
            var ctx = context.Annotations.Get<CompressorContext>(context, ContextKey);
            if (ctx == null) {
                context.Logger.Error("No executable module!");
                throw new ConfuserException(null);
            }

            ModuleDefMD originModule = context.Modules[ctx.ModuleIndex];
            ctx.OriginModuleDef = originModule;
            var stubModule = new ModuleDefUser(ctx.ModuleName, originModule.Mvid, originModule.CorLibTypes.AssemblyRef);
            ctx.Assembly.Modules.Insert(0, stubModule);
            stubModule.Characteristics = originModule.Characteristics;
            stubModule.Cor20HeaderFlags = originModule.Cor20HeaderFlags;
            stubModule.Cor20HeaderRuntimeVersion = originModule.Cor20HeaderRuntimeVersion;
            stubModule.DllCharacteristics = originModule.DllCharacteristics;
            stubModule.EncBaseId = originModule.EncBaseId;
            stubModule.EncId = originModule.EncId;
            stubModule.Generation = originModule.Generation;
            stubModule.Kind = ctx.Kind;
            stubModule.Machine = originModule.Machine;
            stubModule.RuntimeVersion = originModule.RuntimeVersion;
            stubModule.TablesHeaderVersion = originModule.TablesHeaderVersion;
            stubModule.Win32Resources = originModule.Win32Resources;
            ImportAssemblyTypeReferences(originModule, stubModule);

            InjectStub(context, ctx, parameters, stubModule);

            var snKey = context.Annotations.Get<StrongNameKey>(originModule, Marker.SNKey);
            using (var ms = new MemoryStream()) {
                stubModule.Write(ms, new ModuleWriterOptions(stubModule, new KeyInjector(ctx)) {
                    StrongNameKey = snKey
                });
                context.CheckCancellation();
                ProtectStub(context, context.OutputPaths[ctx.ModuleIndex], ms.ToArray(), snKey, new StubProtection(ctx, originModule));
            }
        }
开发者ID:cybercircuits,项目名称:ConfuserEx,代码行数:37,代码来源:Compressor.cs

示例11: PackModules

        void PackModules(ConfuserContext context, CompressorContext compCtx, ModuleDef stubModule, ICompressionService comp, RandomGenerator random)
        {
            int maxLen = 0;
            var modules = new Dictionary<string, byte[]>();
            for (int i = 0; i < context.OutputModules.Count; i++) {
                if (i == compCtx.ModuleIndex)
                    continue;

                string name = context.Modules[i].Assembly.Name.ToUpperInvariant();
                modules.Add(name, context.OutputModules[i]);

                int strLen = Encoding.UTF8.GetByteCount(name);
                if (strLen > maxLen)
                    maxLen = strLen;
            }
            foreach (var extModule in context.ExternalModules) {
                var name = GetName(extModule).ToUpperInvariant();
                modules.Add(name, extModule);

                int strLen = Encoding.UTF8.GetByteCount(name);
                if (strLen > maxLen)
                    maxLen = strLen;
            }

            byte[] key = random.NextBytes(4 + maxLen);
            key[0] = (byte)(compCtx.EntryPointToken >> 0);
            key[1] = (byte)(compCtx.EntryPointToken >> 8);
            key[2] = (byte)(compCtx.EntryPointToken >> 16);
            key[3] = (byte)(compCtx.EntryPointToken >> 24);
            for (int i = 4; i < key.Length; i++) // no zero bytes
                key[i] |= 1;
            compCtx.KeySig = key;

            int moduleIndex = 0;
            foreach (var entry in modules) {
                byte[] name = Encoding.UTF8.GetBytes(entry.Key);
                for (int i = 0; i < name.Length; i++)
                    name[i] *= key[i + 4];

                uint state = 0x6fff61;
                foreach (byte chr in name)
                    state = state * 0x5e3f1f + chr;
                byte[] encrypted = compCtx.Encrypt(comp, entry.Value, state, progress => {
                    progress = (progress + moduleIndex) / modules.Count;
                    context.Logger.Progress((int)(progress * 10000), 10000);
                });
                context.CheckCancellation();

                var resource = new EmbeddedResource(Convert.ToBase64String(name), encrypted, ManifestResourceAttributes.Private);
                stubModule.Resources.Add(resource);
                moduleIndex++;
            }
            context.Logger.EndProgress();
        }
开发者ID:cybercircuits,项目名称:ConfuserEx,代码行数:54,代码来源:Compressor.cs

示例12: InjectStub

        void InjectStub(ConfuserContext context, CompressorContext compCtx, ProtectionParameters parameters, ModuleDef stubModule)
        {
            var rt = context.Registry.GetService<IRuntimeService>();
            RandomGenerator random = context.Registry.GetService<IRandomService>().GetRandomGenerator(Id);
            var comp = context.Registry.GetService<ICompressionService>();
            IEnumerable<IDnlibDef> defs = InjectHelper.Inject(rt.GetRuntimeType("Confuser.Runtime.Compressor"), stubModule.GlobalType, stubModule);

            switch (parameters.GetParameter(context, context.CurrentModule, "key", Mode.Normal)) {
                case Mode.Normal:
                    compCtx.Deriver = new NormalDeriver();
                    break;
                case Mode.Dynamic:
                    compCtx.Deriver = new DynamicDeriver();
                    break;
                default:
                    throw new UnreachableException();
            }
            compCtx.Deriver.Init(context, random);

            context.Logger.Debug("Encrypting modules...");

            // Main
            MethodDef entryPoint = defs.OfType<MethodDef>().Single(method => method.Name == "Main");
            stubModule.EntryPoint = entryPoint;

            if (compCtx.EntryPoint.HasAttribute("System.STAThreadAttribute")) {
                var attrType = stubModule.CorLibTypes.GetTypeRef("System", "STAThreadAttribute");
                var ctorSig = MethodSig.CreateInstance(stubModule.CorLibTypes.Void);
                entryPoint.CustomAttributes.Add(new CustomAttribute(
                    new MemberRefUser(stubModule, ".ctor", ctorSig, attrType)));
            }
            else if (compCtx.EntryPoint.HasAttribute("System.MTAThreadAttribute")) {
                var attrType = stubModule.CorLibTypes.GetTypeRef("System", "MTAThreadAttribute");
                var ctorSig = MethodSig.CreateInstance(stubModule.CorLibTypes.Void);
                entryPoint.CustomAttributes.Add(new CustomAttribute(
                    new MemberRefUser(stubModule, ".ctor", ctorSig, attrType)));
            }

            uint seed = random.NextUInt32();
            compCtx.OriginModule = context.OutputModules[compCtx.ModuleIndex];

            byte[] encryptedModule = compCtx.Encrypt(comp, compCtx.OriginModule, seed,
                                                     progress => context.Logger.Progress((int)(progress * 10000), 10000));
            context.Logger.EndProgress();
            context.CheckCancellation();

            compCtx.EncryptedModule = encryptedModule;

            MutationHelper.InjectKeys(entryPoint,
                                      new[] { 0, 1 },
                                      new[] { encryptedModule.Length >> 2, (int)seed });
            InjectData(stubModule, entryPoint, encryptedModule);

            // Decrypt
            MethodDef decrypter = defs.OfType<MethodDef>().Single(method => method.Name == "Decrypt");
            decrypter.Body.SimplifyMacros(decrypter.Parameters);
            List<Instruction> instrs = decrypter.Body.Instructions.ToList();
            for (int i = 0; i < instrs.Count; i++) {
                Instruction instr = instrs[i];
                if (instr.OpCode == OpCodes.Call) {
                    var method = (IMethod)instr.Operand;
                    if (method.DeclaringType.Name == "Mutation" &&
                        method.Name == "Crypt") {
                        Instruction ldDst = instrs[i - 2];
                        Instruction ldSrc = instrs[i - 1];
                        Debug.Assert(ldDst.OpCode == OpCodes.Ldloc && ldSrc.OpCode == OpCodes.Ldloc);
                        instrs.RemoveAt(i);
                        instrs.RemoveAt(i - 1);
                        instrs.RemoveAt(i - 2);
                        instrs.InsertRange(i - 2, compCtx.Deriver.EmitDerivation(decrypter, context, (Local)ldDst.Operand, (Local)ldSrc.Operand));
                    }
                    else if (method.DeclaringType.Name == "Lzma" &&
                             method.Name == "Decompress") {
                        MethodDef decomp = comp.GetRuntimeDecompressor(stubModule, member => { });
                        instr.Operand = decomp;
                    }
                }
            }
            decrypter.Body.Instructions.Clear();
            foreach (Instruction instr in instrs)
                decrypter.Body.Instructions.Add(instr);

            // Pack modules
            PackModules(context, compCtx, stubModule, comp, random);
        }
开发者ID:cybercircuits,项目名称:ConfuserEx,代码行数:85,代码来源:Compressor.cs

示例13: Execute

        protected override void Execute(ConfuserContext context, ProtectionParameters parameters)
        {
            var service = (NameService)context.Registry.GetService<INameService>();

            context.Logger.Debug("Renaming...");
            foreach (IRenamer renamer in service.Renamers) {
                foreach (IDnlibDef def in parameters.Targets)
                    renamer.PreRename(context, service, parameters, def);
                context.CheckCancellation();
            }

            var pdbDocs = new HashSet<string>();
            foreach (IDnlibDef def in parameters.Targets.WithProgress(context.Logger)) {
                if (def is ModuleDef && parameters.GetParameter(context, def, "rickroll", false))
                    RickRoller.CommenceRickroll(context, (ModuleDef)def);

                bool canRename = service.CanRename(def);
                RenameMode mode = service.GetRenameMode(def);

                if (def is MethodDef) {
                    var method = (MethodDef)def;
                    if ((canRename || method.IsConstructor) && parameters.GetParameter(context, def, "renameArgs", true)) {
                        foreach (ParamDef param in ((MethodDef)def).ParamDefs)
                            param.Name = null;
                    }

                    if (parameters.GetParameter(context, def, "renPdb", false) && method.HasBody) {
                        foreach (var instr in method.Body.Instructions) {
                            if (instr.SequencePoint != null && !pdbDocs.Contains(instr.SequencePoint.Document.Url)) {
                                instr.SequencePoint.Document.Url = service.ObfuscateName(instr.SequencePoint.Document.Url, mode);
                                pdbDocs.Add(instr.SequencePoint.Document.Url);
                            }
                        }
                        foreach (var local in method.Body.Variables) {
                            if (!string.IsNullOrEmpty(local.Name))
                                local.Name = service.ObfuscateName(local.Name, mode);
                        }
                        method.Body.Scope = null;
                    }
                }

                if (!canRename)
                    continue;

                IList<INameReference> references = service.GetReferences(def);
                bool cancel = false;
                foreach (INameReference refer in references) {
                    cancel |= refer.ShouldCancelRename();
                    if (cancel) break;
                }
                if (cancel)
                    continue;

                if (def is TypeDef) {
                    var typeDef = (TypeDef)def;
                    if (parameters.GetParameter(context, def, "flatten", true)) {
                        typeDef.Name = service.ObfuscateName(typeDef.FullName, mode);
                        typeDef.Namespace = "";
                    }
                    else {
                        typeDef.Namespace = service.ObfuscateName(typeDef.Namespace, mode);
                        typeDef.Name = service.ObfuscateName(typeDef.Name, mode);
                    }
                    foreach (var param in typeDef.GenericParameters)
                        param.Name = ((char)(param.Number + 1)).ToString();
                }
                else if (def is MethodDef) {
                    foreach (var param in ((MethodDef)def).GenericParameters)
                        param.Name = ((char)(param.Number + 1)).ToString();

                    def.Name = service.ObfuscateName(def.Name, mode);
                }
                else
                    def.Name = service.ObfuscateName(def.Name, mode);

                foreach (INameReference refer in references.ToList()) {
                    if (!refer.UpdateNameReference(context, service)) {
                        context.Logger.ErrorFormat("Failed to update name reference on '{0}'.", def);
                        throw new ConfuserException(null);
                    }
                }
                context.CheckCancellation();
            }
        }
开发者ID:n017,项目名称:ConfuserEx,代码行数:84,代码来源:RenamePhase.cs

示例14: AddPlugins

		/// <summary>
		///     Adds plugins in the assembly to the protection list.
		/// </summary>
		/// <param name="context">The working context.</param>
		/// <param name="protections">The working list of protections.</param>
		/// <param name="packers">The working list of packers.</param>
		/// <param name="components">The working list of components.</param>
		/// <param name="asm">The assembly.</param>
		protected static void AddPlugins(
			ConfuserContext context, IList<Protection> protections, IList<Packer> packers,
			IList<ConfuserComponent> components, Assembly asm) {
			foreach(var module in asm.GetLoadedModules())
				foreach (var i in module.GetTypes()) {
					if (i.IsAbstract || !HasAccessibleDefConstructor(i))
						continue;

					if (typeof(Protection).IsAssignableFrom(i)) {
						try {
							protections.Add((Protection)Activator.CreateInstance(i));
						}
						catch (Exception ex) {
							context.Logger.ErrorException("Failed to instantiate protection '" + i.Name + "'.", ex);
						}
					}
					else if (typeof(Packer).IsAssignableFrom(i)) {
						try {
							packers.Add((Packer)Activator.CreateInstance(i));
						}
						catch (Exception ex) {
							context.Logger.ErrorException("Failed to instantiate packer '" + i.Name + "'.", ex);
						}
					}
					else if (typeof(ConfuserComponent).IsAssignableFrom(i)) {
						try {
							components.Add((ConfuserComponent)Activator.CreateInstance(i));
						}
						catch (Exception ex) {
							context.Logger.ErrorException("Failed to instantiate component '" + i.Name + "'.", ex);
						}
					}
				}
			context.CheckCancellation();
		}
开发者ID:EmilZhou,项目名称:ConfuserEx,代码行数:43,代码来源:PluginDiscovery.cs


注:本文中的Confuser.Core.ConfuserContext.CheckCancellation方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。