/// <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(); var targetList = Filter(context, targets(), pre); if (targetList.Any()) { context.Logger.DebugFormat("Executing '{0}' phase...", pre.Name); } pre.Execute(context, new ProtectionParameters(pre.Parent, targetList)); } context.CheckCancellation(); func(context); context.CheckCancellation(); foreach (ProtectionPhase post in this.postStage[stage]) { var targetList = Filter(context, targets(), post); if (targetList.Any()) { context.Logger.DebugFormat("Executing '{0}' phase...", post.Name); } post.Execute(context, new ProtectionParameters(post.Parent, targetList)); context.CheckCancellation(); } }
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(); } }
/// <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 <ModuleDefMD>(); foreach (ProjectModule module in proj) { context.Logger.InfoFormat("Loading '{0}'...", module.Path); ModuleDefMD modDef = module.Resolve(proj.BaseDirectory, context.Resolver.DefaultModuleContext); context.CheckCancellation(); if (proj.Debug) { modDef.LoadPdb(); } Rules rules = ParseRules(proj, module, context); context.Annotations.Set(modDef, SNKey, LoadSNKey(context, module.SNKeyPath == null ? null : Path.Combine(proj.BaseDirectory, module.SNKeyPath), module.SNKeyPassword)); context.Annotations.Set(modDef, RulesKey, rules); foreach (IDnlibDef def in modDef.FindDefinitions()) { ApplyRules(context, def, rules); context.CheckCancellation(); } // Packer parameters are stored in modules if (packerParams != null) { ProtectionParameters.GetParameters(context, modDef)[packer] = packerParams; } modules.Add(modDef); } return(new MarkerResult(modules, packer)); }
/// <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> internal void ExecuteStage(PipelineStage stage, Action <ConfuserContext> func, Func <IList <IDnlibDef> > targets, ConfuserContext context) { foreach (ProtectionPhase pre in preStage[stage]) { context.CheckCancellation(); pre.Execute(context, new ProtectionParameters(pre.Parent, Filter(context, targets(), pre))); } context.CheckCancellation(); func(context); context.CheckCancellation(); foreach (ProtectionPhase post in postStage[stage]) { post.Execute(context, new ProtectionParameters(post.Parent, Filter(context, targets(), post))); context.CheckCancellation(); } }
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); }
// Token: 0x0600010D RID: 269 RVA: 0x000098A4 File Offset: 0x00007AA4 private static void BeginModule(ConfuserContext context) { context.Logger.InfoFormat("Processing module '{0}'...", new object[] { context.CurrentModule.Name }); context.CurrentModuleWriterListener = new ModuleWriterListener(); context.CurrentModuleWriterListener.OnWriterEvent += delegate(object sender, ModuleWriterListenerEventArgs e) { context.CheckCancellation(); }; context.CurrentModuleWriterOptions = new ModuleWriterOptions(context.CurrentModule, context.CurrentModuleWriterListener); if (!context.CurrentModule.IsILOnly) { context.RequestNative(); } StrongNameKey snKey = context.Annotations.Get <StrongNameKey>(context.CurrentModule, Marker.SNKey, null); 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); } } } }
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); CopyPEHeaders(context.CurrentModuleWriterOptions.PEHeadersOptions, context.CurrentModule); if (!context.CurrentModule.IsILOnly || context.CurrentModule.VTableFixups != null) { context.RequestNative(); } 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); } } } }
/// <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)); }
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(); } }
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(); } }
/// <inheritdoc /> // Token: 0x060001B6 RID: 438 RVA: 0x0000E14C File Offset: 0x0000C34C protected internal override MarkerResult MarkProject(ConfuserProject proj, ConfuserContext context) { this.crossModuleAttrs = new Dictionary <string, Dictionary <Regex, List <ObfAttrMarker.ObfuscationAttributeInfo> > >(); this.context = context; this.project = proj; this.extModules = new List <byte[]>(); if (proj.Packer != null) { if (!this.packers.ContainsKey(proj.Packer.Id)) { context.Logger.ErrorFormat("Cannot find packer with ID '{0}'.", new object[] { proj.Packer.Id }); throw new ConfuserException(null); } this.packer = this.packers[proj.Packer.Id]; this.packerParams = new Dictionary <string, string>(proj.Packer, StringComparer.OrdinalIgnoreCase); } List <Tuple <ProjectModule, ModuleDefMD> > modules = new List <Tuple <ProjectModule, ModuleDefMD> >(); foreach (ProjectModule module3 in proj) { if (module3.IsExternal) { this.extModules.Add(module3.LoadRaw(proj.BaseDirectory)); } else { ModuleDefMD modDef = module3.Resolve(proj.BaseDirectory, context.Resolver.DefaultModuleContext); context.CheckCancellation(); context.Resolver.AddToCache(modDef); modules.Add(Tuple.Create <ProjectModule, ModuleDefMD>(module3, modDef)); } } foreach (Tuple <ProjectModule, ModuleDefMD> module2 in modules) { context.Logger.InfoFormat("Loading '{0}'...", new object[] { module2.Item1.Path }); Dictionary <Rule, PatternExpression> rules = base.ParseRules(proj, module2.Item1, context); this.MarkModule(module2.Item1, module2.Item2, rules, module2 == modules[0]); context.Annotations.Set <Dictionary <Rule, PatternExpression> >(module2.Item2, Marker.RulesKey, rules); if (this.packer != null) { ProtectionParameters.GetParameters(context, module2.Item2)[this.packer] = this.packerParams; } } if (proj.Debug && proj.Packer != null) { context.Logger.Warn("Generated Debug symbols might not be usable with packers!"); } return(new MarkerResult((from module in modules select module.Item2).ToList <ModuleDefMD>(), this.packer, this.extModules)); }
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(); } }
/// <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> // Token: 0x060001D3 RID: 467 RVA: 0x0000F594 File Offset: 0x0000D794 protected static void AddPlugins(ConfuserContext context, IList <Protection> protections, IList <Packer> packers, IList <ConfuserComponent> components, Assembly asm) { Module[] loadedModules = asm.GetLoadedModules(); for (int j = 0; j < loadedModules.Length; j++) { Module module = loadedModules[j]; Type[] types = module.GetTypes(); for (int k = 0; k < types.Length; k++) { Type i = types[k]; if (!i.IsAbstract && PluginDiscovery.HasAccessibleDefConstructor(i)) { if (typeof(Protection).IsAssignableFrom(i)) { try { protections.Add((Protection)Activator.CreateInstance(i)); goto IL_126; } catch (Exception ex) { context.Logger.ErrorException("Failed to instantiate protection '" + i.Name + "'.", ex); goto IL_126; } } if (typeof(Packer).IsAssignableFrom(i)) { try { packers.Add((Packer)Activator.CreateInstance(i)); goto IL_126; } catch (Exception ex2) { context.Logger.ErrorException("Failed to instantiate packer '" + i.Name + "'.", ex2); goto IL_126; } } if (typeof(ConfuserComponent).IsAssignableFrom(i)) { try { components.Add((ConfuserComponent)Activator.CreateInstance(i)); } catch (Exception ex3) { context.Logger.ErrorException("Failed to instantiate component '" + i.Name + "'.", ex3); } } } IL_126 :; } } context.CheckCancellation(); }
static void BeginModule(ConfuserContext context) { context.Logger.InfoFormat("Processing module '{0}'...", context.CurrentModule.Name); context.CurrentModuleWriterOptions = new ModuleWriterOptions(context.CurrentModule); context.CurrentModuleWriterOptions.WriterEvent += (sender, e) => context.CheckCancellation(); CopyPEHeaders(context.CurrentModuleWriterOptions.PEHeadersOptions, context.CurrentModule); if (!context.CurrentModule.IsILOnly || context.CurrentModule.VTableFixups != null) { context.RequestNative(); } var snKey = context.Annotations.Get <StrongNameKey>(context.CurrentModule, Marker.SNKey); var snPubKey = context.Annotations.Get <StrongNamePublicKey>(context.CurrentModule, Marker.SNPubKey); var snSigKey = context.Annotations.Get <StrongNameKey>(context.CurrentModule, Marker.SNSigKey); var snSigPubKey = context.Annotations.Get <StrongNamePublicKey>(context.CurrentModule, Marker.SNSigPubKey); var snDelaySig = context.Annotations.Get <bool>(context.CurrentModule, Marker.SNDelaySig, false); context.CurrentModuleWriterOptions.DelaySign = snDelaySig; if (snKey != null && snPubKey != null && snSigKey != null && snSigPubKey != null) { context.CurrentModuleWriterOptions.InitializeEnhancedStrongNameSigning(context.CurrentModule, snSigKey, snSigPubKey, snKey, snPubKey); } else if (snSigPubKey != null && snSigKey != null) { context.CurrentModuleWriterOptions.InitializeEnhancedStrongNameSigning(context.CurrentModule, snSigKey, snSigPubKey); } else { context.CurrentModuleWriterOptions.InitializeStrongNameSigning(context.CurrentModule, snKey); } if (snDelaySig) { context.CurrentModuleWriterOptions.StrongNamePublicKey = snPubKey; context.CurrentModuleWriterOptions.StrongNameKey = null; } 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); } } } }
/// <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(); }
/// <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); }
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); } } }
/// <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(); }
/// <inheritdoc /> protected internal override MarkerResult MarkProject(ConfuserProject proj, ConfuserContext context) { 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) { var rawModule = module.LoadRaw(proj.BaseDirectory); extModules.Add(rawModule); context.InternalResolver.AddToCache(ModuleDefMD.Load(rawModule, context.InternalResolver.DefaultModuleContext)); continue; } try { ModuleDefMD modDef = module.Resolve(proj.BaseDirectory, context.InternalResolver.DefaultModuleContext); context.CheckCancellation(); context.InternalResolver.AddToCache(modDef); modules.Add(Tuple.Create(module, modDef)); } catch (BadImageFormatException ex) { context.Logger.ErrorFormat("Failed to load \"{0}\" - Assembly does not appear to be a .NET assembly: \"{1}\".", module.Path, ex.Message); throw new ConfuserException(ex); } } 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)); }
/// <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); }
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(); } }
/// <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> 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); } }
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); }
/// <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("找不到带ID的打包器 '{0}'.", proj.Packer.Id); throw new ConfuserException(null); } if (proj.Debug) { context.Logger.Warn("生成的调试符号可能无法与打包程序一起使用!"); } 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("加载 '{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)); }
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(); }
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)); } }
/// <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) { var rawModule = module.LoadRaw(proj.BaseDirectory); extModules.Add(rawModule); var extModule = ModuleDefMD.Load(rawModule, context.InternalResolver.DefaultModuleContext); extModule.EnableTypeDefFindCache = true; context.InternalResolver.AddToCache(extModule); continue; } ModuleDefMD modDef = module.Resolve(proj.BaseDirectory, context.InternalResolver.DefaultModuleContext); context.CheckCancellation(); if (proj.Debug) { modDef.LoadPdb(); } context.InternalResolver.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, SNSigKey, LoadSNKey(context, module.Item1.SNSigKeyPath == null ? null : Path.Combine(proj.BaseDirectory, module.Item1.SNSigKeyPath), module.Item1.SNSigKeyPassword)); context.Annotations.Set(module.Item2, SNPubKey, LoadSNPubKey(context, module.Item1.SNPubKeyPath == null ? null : Path.Combine(proj.BaseDirectory, module.Item1.SNPubKeyPath))); context.Annotations.Set(module.Item2, SNSigPubKey, LoadSNPubKey(context, module.Item1.SNPubSigKeyPath == null ? null : Path.Combine(proj.BaseDirectory, module.Item1.SNPubSigKeyPath))); context.Annotations.Set(module.Item2, SNDelaySig, module.Item1.SNDelaySig); 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)); }
/// <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); } }
static void ProcessModule(ConfuserContext context) => context.CurrentModuleWriterOptions.WriterEvent += (sender, e) => context.CheckCancellation();
/// <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> /// Loads the assembly and marks the project. /// </summary> /// <param name="proj">The project.</param> /// <param name="context">The working context.</param> /// <returns><see cref="T:Confuser.Core.MarkerResult" /> storing the marked modules and packer information.</returns> // Token: 0x06000193 RID: 403 RVA: 0x0000CFF0 File Offset: 0x0000B1F0 protected internal virtual MarkerResult MarkProject(ConfuserProject proj, ConfuserContext context) { Packer packer = null; Dictionary <string, string> packerParams = null; if (proj.Packer != null) { if (!this.packers.ContainsKey(proj.Packer.Id)) { context.Logger.ErrorFormat("Cannot find packer with ID '{0}'.", new object[] { proj.Packer.Id }); throw new ConfuserException(null); } if (proj.Debug) { context.Logger.Warn("Generated Debug symbols might not be usable with packers!"); } packer = this.packers[proj.Packer.Id]; packerParams = new Dictionary <string, string>(proj.Packer, StringComparer.OrdinalIgnoreCase); } List <Tuple <ProjectModule, ModuleDefMD> > modules = new List <Tuple <ProjectModule, ModuleDefMD> >(); List <byte[]> extModules = new List <byte[]>(); foreach (ProjectModule module3 in proj) { if (module3.IsExternal) { extModules.Add(module3.LoadRaw(proj.BaseDirectory)); } else { ModuleDefMD modDef = module3.Resolve(proj.BaseDirectory, context.Resolver.DefaultModuleContext); context.CheckCancellation(); if (proj.Debug) { modDef.LoadPdb(); } context.Resolver.AddToCache(modDef); modules.Add(Tuple.Create <ProjectModule, ModuleDefMD>(module3, modDef)); } } foreach (Tuple <ProjectModule, ModuleDefMD> module2 in modules) { context.Logger.InfoFormat("Loading '{0}'...", new object[] { module2.Item1.Path }); Dictionary <Rule, PatternExpression> rules = this.ParseRules(proj, module2.Item1, context); context.Annotations.Set <StrongNameKey>(module2.Item2, Marker.SNKey, Marker.LoadSNKey(context, (module2.Item1.SNKeyPath == null) ? null : Path.Combine(proj.BaseDirectory, module2.Item1.SNKeyPath), module2.Item1.SNKeyPassword)); context.Annotations.Set <Dictionary <Rule, PatternExpression> >(module2.Item2, Marker.RulesKey, rules); foreach (IDnlibDef def in module2.Item2.FindDefinitions()) { this.ApplyRules(context, def, rules, null); context.CheckCancellation(); } if (packerParams != null) { ProtectionParameters.GetParameters(context, module2.Item2)[packer] = packerParams; } } return(new MarkerResult((from module in modules select module.Item2).ToList <ModuleDefMD>(), packer, extModules)); }