From 24a7fd80c431403c0dc5025538fea6ea64dfe936 Mon Sep 17 00:00:00 2001 From: yck1509 Date: Wed, 24 Dec 2014 03:28:51 +0800 Subject: [PATCH] Change code styles --- Confuser.CLI/ObfAttrParser.cs | 32 ++-- Confuser.CLI/Program.cs | 37 ++-- Confuser.Core/Annotations.cs | 14 +- Confuser.Core/ConfuserComponent.cs | 2 - Confuser.Core/ConfuserContext.cs | 6 +- Confuser.Core/ConfuserEngine.cs | 32 ++-- Confuser.Core/ConfuserException.cs | 2 - Confuser.Core/ConfuserParameters.cs | 2 - Confuser.Core/CoreComponent.cs | 6 +- Confuser.Core/DependencyResolver.cs | 12 +- Confuser.Core/DnlibUtils.cs | 5 +- Confuser.Core/Helpers/ControlFlowGraph.cs | 24 +-- Confuser.Core/Helpers/InjectHelper.cs | 24 ++- Confuser.Core/Helpers/KeySequence.cs | 16 +- Confuser.Core/Helpers/MutationHelper.cs | 6 +- Confuser.Core/ILogger.cs | 2 - Confuser.Core/Marker.cs | 7 +- Confuser.Core/MarkerResult.cs | 2 - Confuser.Core/ModuleWriterListener.cs | 4 - Confuser.Core/NullLogger.cs | 4 +- Confuser.Core/Packer.cs | 14 +- Confuser.Core/PluginDiscovery.cs | 2 - Confuser.Core/Project/ConfuserProject.cs | 19 +-- .../Project/InvalidPatternException.cs | 2 - Confuser.Core/Project/PatternParser.cs | 32 ++-- Confuser.Core/Project/PatternToken.cs | 6 +- Confuser.Core/Project/PatternTokenizer.cs | 16 +- Confuser.Core/Project/Patterns/AndOperator.cs | 2 - .../Project/Patterns/DeclTypeFunction.cs | 2 - .../Project/Patterns/FullNameFunction.cs | 2 - .../Project/Patterns/InheritsFunction.cs | 2 - .../Project/Patterns/IsPublicFunction.cs | 2 - .../Project/Patterns/IsTypeFunction.cs | 2 - .../Project/Patterns/LiteralExpression.cs | 2 - .../Project/Patterns/MatchFunction.cs | 6 - .../Project/Patterns/MemberTypeFunction.cs | 2 - .../Project/Patterns/ModuleFunction.cs | 2 - .../Project/Patterns/NameFunction.cs | 2 - .../Project/Patterns/NamespaceFunction.cs | 2 - Confuser.Core/Project/Patterns/NotOperator.cs | 2 - Confuser.Core/Project/Patterns/OrOperator.cs | 2 - .../Project/Patterns/PatternExpression.cs | 2 - .../Project/Patterns/PatternFunction.cs | 2 - .../Project/Patterns/PatternOperator.cs | 2 - Confuser.Core/Protection.cs | 2 - .../ProtectionDependencyAttributes.cs | 8 +- Confuser.Core/ProtectionParameters.cs | 6 +- Confuser.Core/ProtectionPhase.cs | 2 - Confuser.Core/ProtectionPipeline.cs | 10 +- Confuser.Core/ProtectionPreset.cs | 4 +- Confuser.Core/ProtectionSettings.cs | 2 - Confuser.Core/ProtectionTargets.cs | 4 +- Confuser.Core/ServiceRegistry.cs | 6 +- Confuser.Core/Services/CompressionService.cs | 20 +-- Confuser.Core/Services/MarkerService.cs | 8 +- Confuser.Core/Services/RandomService.cs | 20 +-- Confuser.Core/Services/RuntimeService.cs | 6 +- Confuser.Core/Services/TraceService.cs | 16 +- Confuser.Core/UnreachableException.cs | 2 - Confuser.Core/Utils.cs | 17 +- .../AST/ArrayIndexExpression.cs | 2 - Confuser.DynCipher/AST/AssignmentStatement.cs | 2 - Confuser.DynCipher/AST/BinOpExpression.cs | 6 +- Confuser.DynCipher/AST/Expression.cs | 2 - Confuser.DynCipher/AST/LiteralExpression.cs | 2 - Confuser.DynCipher/AST/LoopStatement.cs | 2 - Confuser.DynCipher/AST/Statement.cs | 2 - Confuser.DynCipher/AST/StatementBlock.cs | 2 - Confuser.DynCipher/AST/UnaryOpExpression.cs | 4 - Confuser.DynCipher/AST/Variable.cs | 2 - Confuser.DynCipher/AST/VariableExpression.cs | 2 - Confuser.DynCipher/DynCipherComponent.cs | 2 - Confuser.DynCipher/DynCipherService.cs | 4 - Confuser.DynCipher/Elements/AddKey.cs | 4 +- Confuser.DynCipher/Elements/BinOp.cs | 4 - Confuser.DynCipher/Elements/CryptoElement.cs | 2 - Confuser.DynCipher/Elements/Matrix.cs | 14 +- Confuser.DynCipher/Elements/NumOp.cs | 4 - Confuser.DynCipher/Elements/RotateBit.cs | 2 - Confuser.DynCipher/Elements/Swap.cs | 4 +- Confuser.DynCipher/Generation/CILCodeGen.cs | 10 +- .../Generation/CipherGenContext.cs | 20 +-- .../Generation/CipherGenerator.cs | 20 +-- Confuser.DynCipher/Generation/DMCodeGen.cs | 17 +- .../Generation/ExpressionGenerator.cs | 16 +- Confuser.DynCipher/Generation/x86CodeGen.cs | 30 +--- .../Transforms/ConvertVariables.cs | 6 +- .../Transforms/ExpansionTransform.cs | 4 +- .../Transforms/MulToShiftTransform.cs | 8 +- .../Transforms/NormalizeBinOpTransform.cs | 6 +- .../Transforms/ShuffleTransform.cs | 20 +-- Confuser.DynCipher/Utils.cs | 6 +- Confuser.Protections/AntiDebugProtection.cs | 10 +- Confuser.Protections/AntiDumpProtection.cs | 6 +- Confuser.Protections/AntiILDasmProtection.cs | 6 +- .../AntiTamper/AntiTamperProtection.cs | 18 +- .../AntiTamper/DynamicDeriver.cs | 14 +- .../AntiTamper/IKeyDeriver.cs | 4 - .../AntiTamper/IModeHandler.cs | 2 - Confuser.Protections/AntiTamper/JITBody.cs | 48 ++---- Confuser.Protections/AntiTamper/JITMode.cs | 44 +++-- .../AntiTamper/NormalDeriver.cs | 2 - Confuser.Protections/AntiTamper/NormalMode.cs | 28 ++-- Confuser.Protections/Compress/Compressor.cs | 23 ++- .../Compress/CompressorContext.cs | 3 - .../Compress/DynamicDeriver.cs | 14 +- Confuser.Protections/Compress/ExtractPhase.cs | 10 +- Confuser.Protections/Compress/IKeyDeriver.cs | 4 - .../Compress/NormalDeriver.cs | 10 +- .../Compress/StubProtection.cs | 14 +- Confuser.Protections/Constants/CEContext.cs | 4 - .../Constants/ConstantProtection.cs | 4 - Confuser.Protections/Constants/DynamicMode.cs | 13 +- .../Constants/EncodeElements.cs | 2 - Confuser.Protections/Constants/EncodePhase.cs | 24 +-- Confuser.Protections/Constants/IEncodeMode.cs | 2 - Confuser.Protections/Constants/InjectPhase.cs | 6 +- Confuser.Protections/Constants/Mode.cs | 2 - Confuser.Protections/Constants/NormalMode.cs | 3 - .../Constants/ReferenceReplacer.cs | 15 +- Confuser.Protections/Constants/x86Mode.cs | 26 ++- .../ControlFlow/BlockParser.cs | 3 - Confuser.Protections/ControlFlow/Blocks.cs | 8 - Confuser.Protections/ControlFlow/CFContext.cs | 10 +- .../ControlFlow/ControlFlowPhase.cs | 14 +- .../ControlFlow/ControlFlowProtection.cs | 4 - .../ControlFlow/ExpressionPredicate.cs | 25 ++- .../ControlFlow/IPredicate.cs | 2 - .../ControlFlow/JumpMangler.cs | 4 +- .../ControlFlow/ManglerBase.cs | 2 - .../ControlFlow/NormalPredicate.cs | 8 +- .../ControlFlow/SwitchMangler.cs | 6 +- .../ControlFlow/x86Predicate.cs | 24 ++- .../InvalidMetadataProtection.cs | 20 +-- .../ReferenceProxy/ExpressionEncoding.cs | 17 +- .../ReferenceProxy/IRPEncoding.cs | 2 - .../ReferenceProxy/MildMode.cs | 4 +- .../ReferenceProxy/NormalEncoding.cs | 7 +- .../ReferenceProxy/RPContext.cs | 6 - Confuser.Protections/ReferenceProxy/RPMode.cs | 4 +- .../ReferenceProxy/ReferenceProxyPhase.cs | 16 +- .../ReferenceProxyProtection.cs | 4 - .../ReferenceProxy/StrongMode.cs | 44 ++--- .../ReferenceProxy/x86Encoding.cs | 22 +-- Confuser.Protections/Resources/DynamicMode.cs | 13 +- Confuser.Protections/Resources/IEncodeMode.cs | 2 - Confuser.Protections/Resources/InjectPhase.cs | 8 +- Confuser.Protections/Resources/MDPhase.cs | 8 +- Confuser.Protections/Resources/Mode.cs | 2 - Confuser.Protections/Resources/NormalMode.cs | 2 - Confuser.Protections/Resources/REContext.cs | 2 - .../Resources/ResourceProtection.cs | 2 - Confuser.Renamer/AnalyzePhase.cs | 18 +- .../Analyzers/CaliburnAnalyzer.cs | 14 +- .../Analyzers/InterReferenceAnalyzer.cs | 2 - .../Analyzers/LdtokenEnumAnalyzer.cs | 8 +- .../Analyzers/ResourceAnalyzer.cs | 4 +- .../Analyzers/TypeBlobAnalyzer.cs | 8 +- Confuser.Renamer/Analyzers/VTableAnalyzer.cs | 11 +- Confuser.Renamer/Analyzers/WPFAnalyzer.cs | 12 +- Confuser.Renamer/BAML/BAMLAnalyzer.cs | 114 ++++++------- Confuser.Renamer/BAML/BamlDocument.cs | 4 - Confuser.Renamer/BAML/BamlElement.cs | 8 +- Confuser.Renamer/BAML/BamlRW.cs | 12 +- Confuser.Renamer/BAML/BamlRecords.cs | 120 +------------ Confuser.Renamer/BAML/IKnownThings.cs | 7 - Confuser.Renamer/BAML/KnownThingsv3.cs | 18 +- Confuser.Renamer/BAML/KnownThingsv4.cs | 18 +- Confuser.Renamer/BAML/PropertyPath.cs | 16 +- Confuser.Renamer/GenericArgumentResolver.cs | 14 +- Confuser.Renamer/INameReference.cs | 6 +- Confuser.Renamer/IRenamer.cs | 2 - Confuser.Renamer/NameProtection.cs | 6 +- Confuser.Renamer/NameService.cs | 56 +++---- Confuser.Renamer/PostRenamePhase.cs | 2 - .../References/BAMLAttributeReference.cs | 8 +- .../BAMLConverterMemberReference.cs | 10 +- .../References/BAMLConverterTypeReference.cs | 10 +- .../References/BAMLEnumReference.cs | 6 +- .../References/BAMLPathTypeReference.cs | 10 +- .../References/BAMLTypeReference.cs | 6 +- .../References/CAMemberReference.cs | 6 +- .../References/MemberRefReference.cs | 6 +- .../References/OverrideDirectiveReference.cs | 6 +- .../References/ResourceReference.cs | 8 +- .../References/StringTypeReference.cs | 6 +- .../References/TypeRefReference.cs | 6 +- Confuser.Renamer/RenameMode.cs | 4 +- Confuser.Renamer/RenamePhase.cs | 2 - Confuser.Renamer/VTable.cs | 58 +++---- Confuser.Runtime/AntiDebug.Antinet.cs | 4 +- Confuser.Runtime/AntiDebug.Safe.cs | 6 +- Confuser.Runtime/AntiDebug.Win32.cs | 12 +- Confuser.Runtime/AntiDump.cs | 6 +- Confuser.Runtime/AntiTamper.JIT.cs | 110 +++++------- Confuser.Runtime/AntiTamper.Normal.cs | 6 +- Confuser.Runtime/Compressor.cs | 10 +- Confuser.Runtime/Constant.cs | 10 +- Confuser.Runtime/Lzma.cs | 158 ++++++++---------- Confuser.Runtime/Mutation.cs | 2 - Confuser.Runtime/RefProxy.Strong.cs | 6 +- Confuser.Runtime/Resource.cs | 16 +- ConfuserEx/App.xaml.cs | 4 +- ConfuserEx/BrushToColorConverter.cs | 4 +- ConfuserEx/CompComboBox.xaml.cs | 2 - ConfuserEx/ComponentConverter.cs | 2 - ConfuserEx/ComponentDiscovery.cs | 22 +-- ConfuserEx/EnumValuesExtension.cs | 4 +- ConfuserEx/FileDragDrop.cs | 12 +- ConfuserEx/InvertBoolConverter.cs | 4 +- ConfuserEx/MainWindow.xaml.cs | 4 +- ConfuserEx/Skin.cs | 2 - ConfuserEx/StackTraceDecoder.xaml.cs | 16 +- ConfuserEx/ViewModel/IViewModel.cs | 2 - .../ViewModel/Project/ProjectModuleVM.cs | 12 +- ConfuserEx/ViewModel/Project/ProjectRuleVM.cs | 14 +- .../ViewModel/Project/ProjectSettingVM.cs | 6 +- ConfuserEx/ViewModel/Project/ProjectVM.cs | 8 +- ConfuserEx/ViewModel/StringItem.cs | 2 - ConfuserEx/ViewModel/UI/AboutTabVM.cs | 2 - ConfuserEx/ViewModel/UI/AppVM.cs | 23 ++- ConfuserEx/ViewModel/UI/ProjectTabVM.cs | 6 +- ConfuserEx/ViewModel/UI/ProtectTabVM.cs | 19 +-- ConfuserEx/ViewModel/UI/SettingsTabVM.cs | 10 +- ConfuserEx/ViewModel/UI/TabViewModel.cs | 2 - ConfuserEx/ViewModel/Utils.cs | 2 - ConfuserEx/ViewModel/ViewModelBase.cs | 2 - ConfuserEx/Views/ProjectModuleView.xaml.cs | 10 +- ConfuserEx/Views/ProjectRuleView.xaml.cs | 12 +- .../Views/ProjectTabAdvancedView.xaml.cs | 4 +- 230 files changed, 858 insertions(+), 1720 deletions(-) diff --git a/Confuser.CLI/ObfAttrParser.cs b/Confuser.CLI/ObfAttrParser.cs index b753035f7..978b677af 100644 --- a/Confuser.CLI/ObfAttrParser.cs +++ b/Confuser.CLI/ObfAttrParser.cs @@ -1,4 +1,5 @@ using System; +using System.Collections; using System.Collections.Generic; using System.Linq; using System.Text; @@ -6,18 +7,18 @@ namespace Confuser.CLI { internal struct ObfAttrParser { - private System.Collections.IDictionary items; + IDictionary items; - private string str; - private int index; + string str; + int index; - public ObfAttrParser(System.Collections.IDictionary items) { + public ObfAttrParser(IDictionary items) { this.items = items; - this.str = null; - this.index = -1; + str = null; + index = -1; } - private enum ParseState { + enum ParseState { Init, ReadPreset, ReadItemName, @@ -27,7 +28,7 @@ private enum ParseState { End } - private bool ReadId(StringBuilder sb) { + bool ReadId(StringBuilder sb) { while (index < str.Length) { switch (str[index]) { case '(': @@ -46,21 +47,21 @@ private bool ReadId(StringBuilder sb) { return false; } - private void Expect(char chr) { + void Expect(char chr) { if (str[index] != chr) throw new ArgumentException("Expect '" + chr + "' at position " + (index + 1) + "."); index++; } - private char Peek() { + char Peek() { return str[index]; } - private void Next() { + void Next() { index++; } - private bool IsEnd() { + bool IsEnd() { return index == str.Length; } @@ -69,7 +70,7 @@ public void ParseProtectionString(ProtectionSettings settings, string str) { return; this.str = str; - this.index = 0; + index = 0; var state = ParseState.Init; var buffer = new StringBuilder(); @@ -80,7 +81,6 @@ public void ParseProtectionString(ProtectionSettings settings, string str) { while (state != ParseState.End) { switch (state) { - case ParseState.Init: ReadId(buffer); if (buffer.ToString().Equals("preset", StringComparison.OrdinalIgnoreCase)) { @@ -211,7 +211,7 @@ public void ParsePackerString(string str, out Packer packer, out Dictionary { noPause = (value != null); } }, - { "o|out=", "specifies output directory.", - value => { outDir = value; } }, + var p = new OptionSet { + { + "n|nopause", "no pause after finishing protection.", + value => { noPause = (value != null); } + }, { + "o|out=", "specifies output directory.", + value => { outDir = value; } + } }; List files; @@ -62,7 +64,7 @@ private static int Main(string[] args) { // Assuming first file = main module var proj = new ConfuserProject(); foreach (var input in files) - proj.Add(new ProjectModule() { Path = input }); + proj.Add(new ProjectModule { Path = input }); proj.BaseDirectory = Path.GetDirectoryName(files[0]); proj.OutputDirectory = outDir; parameters.Project = proj; @@ -84,7 +86,7 @@ private static int Main(string[] args) { } } - private static int RunProject(ConfuserParameters parameters) { + static int RunProject(ConfuserParameters parameters) { var logger = new ConsoleLogger(); parameters.Logger = new ConsoleLogger(); @@ -94,11 +96,11 @@ private static int RunProject(ConfuserParameters parameters) { return logger.ReturnValue; } - private static bool NeedPause() { + static bool NeedPause() { return Debugger.IsAttached || string.IsNullOrEmpty(Environment.GetEnvironmentVariable("PROMPT")); } - private static void PrintUsage() { + static void PrintUsage() { WriteLine("Usage:"); WriteLine("Confuser.CLI -n|noPause "); WriteLine("Confuser.CLI -n|noPause -o|out= "); @@ -106,24 +108,23 @@ private static void PrintUsage() { WriteLine(" -o|out : specifies output directory."); } - private static void WriteLineWithColor(ConsoleColor color, string txt) { + static void WriteLineWithColor(ConsoleColor color, string txt) { ConsoleColor original = Console.ForegroundColor; Console.ForegroundColor = color; Console.WriteLine(txt); Console.ForegroundColor = original; } - private static void WriteLine(string txt) { + static void WriteLine(string txt) { Console.WriteLine(txt); } - private static void WriteLine() { + static void WriteLine() { Console.WriteLine(); } - private class ConsoleLogger : ILogger { - - private readonly DateTime begin; + class ConsoleLogger : ILogger { + readonly DateTime begin; public ConsoleLogger() { begin = DateTime.Now; @@ -195,8 +196,6 @@ public void Finish(bool successful) { ReturnValue = 1; } } - } - } } \ No newline at end of file diff --git a/Confuser.Core/Annotations.cs b/Confuser.Core/Annotations.cs index 899554434..5e2056d30 100644 --- a/Confuser.Core/Annotations.cs +++ b/Confuser.Core/Annotations.cs @@ -11,8 +11,7 @@ namespace Confuser.Core { /// The annotations are stored using /// public class Annotations { - - private readonly Dictionary annotations = new Dictionary(WeakReferenceComparer.Instance); + readonly Dictionary annotations = new Dictionary(WeakReferenceComparer.Instance); /// /// Retrieves the annotation on the specified object associated with the specified key. @@ -136,8 +135,7 @@ public void Trim() { /// /// Equality comparer of weak references. /// - private class WeakReferenceComparer : IEqualityComparer { - + class WeakReferenceComparer : IEqualityComparer { /// /// The singleton instance of this comparer. /// @@ -146,7 +144,7 @@ private class WeakReferenceComparer : IEqualityComparer { /// /// Prevents a default instance of the class from being created. /// - private WeakReferenceComparer() { } + WeakReferenceComparer() { } /// public new bool Equals(object x, object y) { @@ -172,14 +170,12 @@ public int GetHashCode(object obj) { return ((WeakReferenceKey)obj).HashCode; return obj.GetHashCode(); } - } /// /// Represent a key using . /// - private class WeakReferenceKey : WeakReference { - + class WeakReferenceKey : WeakReference { /// public WeakReferenceKey(object target) : base(target) { @@ -191,8 +187,6 @@ public WeakReferenceKey(object target) /// /// The hash code. public int HashCode { get; private set; } - } - } } \ No newline at end of file diff --git a/Confuser.Core/ConfuserComponent.cs b/Confuser.Core/ConfuserComponent.cs index 8f3b2f7ee..105211392 100644 --- a/Confuser.Core/ConfuserComponent.cs +++ b/Confuser.Core/ConfuserComponent.cs @@ -5,7 +5,6 @@ namespace Confuser.Core { /// Represent a component in Confuser /// public abstract class ConfuserComponent { - /// /// Gets the name of component. /// @@ -41,6 +40,5 @@ public abstract class ConfuserComponent { /// /// The processing pipeline. protected internal abstract void PopulatePipeline(ProtectionPipeline pipeline); - } } \ No newline at end of file diff --git a/Confuser.Core/ConfuserContext.cs b/Confuser.Core/ConfuserContext.cs index 9e25635c2..c0e527b26 100644 --- a/Confuser.Core/ConfuserContext.cs +++ b/Confuser.Core/ConfuserContext.cs @@ -10,9 +10,8 @@ namespace Confuser.Core { /// Context providing information on the current protection process. /// public class ConfuserContext { - - private readonly Annotations annotations = new Annotations(); - private readonly ServiceRegistry registry = new ServiceRegistry(); + readonly Annotations annotations = new Annotations(); + readonly ServiceRegistry registry = new ServiceRegistry(); internal CancellationToken token; /// @@ -181,6 +180,5 @@ public NativeModuleWriterOptions RequestNative() { CurrentModuleWriterOptions = newOptions; return newOptions; } - } } \ No newline at end of file diff --git a/Confuser.Core/ConfuserEngine.cs b/Confuser.Core/ConfuserEngine.cs index 9f8b9f058..33da1a906 100644 --- a/Confuser.Core/ConfuserEngine.cs +++ b/Confuser.Core/ConfuserEngine.cs @@ -22,13 +22,12 @@ namespace Confuser.Core { /// The processing engine of ConfuserEx. /// public static class ConfuserEngine { - /// /// The version of ConfuserEx. /// public static readonly string Version; - private static readonly string Copyright; + static readonly string Copyright; static ConfuserEngine() { Assembly assembly = typeof(ConfuserEngine).Assembly; @@ -61,7 +60,7 @@ public static Task Run(ConfuserParameters parameters, CancellationToken? token = /// /// The parameters. /// The cancellation token. - private static void RunInternal(ConfuserParameters parameters, CancellationToken token) { + static void RunInternal(ConfuserParameters parameters, CancellationToken token) { // 1. Setup context var context = new ConfuserContext(); context.Logger = parameters.GetLogger(); @@ -198,7 +197,7 @@ private static void RunInternal(ConfuserParameters parameters, CancellationToken /// /// The protection pipeline. /// The context. - private static void RunPipeline(ProtectionPipeline pipeline, ConfuserContext context) { + static void RunPipeline(ProtectionPipeline pipeline, ConfuserContext context) { Func> getAllDefs = () => context.Modules.SelectMany(module => module.FindDefinitions()).ToList(); Func> getModuleDefs = module => module.FindDefinitions().ToList(); @@ -247,7 +246,7 @@ private static void RunPipeline(ProtectionPipeline pipeline, ConfuserContext con context.Logger.Info("Done."); } - private static void Inspection(ConfuserContext context) { + static void Inspection(ConfuserContext context) { context.Logger.Info("Resolving dependencies..."); foreach (var dependency in context.Modules .SelectMany(module => module.GetAssemblyRefs().Select(asmRef => Tuple.Create(asmRef, module)))) { @@ -315,7 +314,7 @@ private static void Inspection(ConfuserContext context) { } } - private static void BeginModule(ConfuserContext context) { + static void BeginModule(ConfuserContext context) { context.Logger.InfoFormat("Processing module '{0}'...", context.CurrentModule.Name); context.CurrentModuleWriterListener = new ModuleWriterListener(); @@ -332,9 +331,9 @@ private static void BeginModule(ConfuserContext context) { } } - private static void ProcessModule(ConfuserContext context) { } + static void ProcessModule(ConfuserContext context) { } - private static void OptimizeMethods(ConfuserContext context) { + static void OptimizeMethods(ConfuserContext context) { foreach (TypeDef type in context.CurrentModule.GetTypes()) foreach (MethodDef method in type.Methods) { if (method.Body != null) @@ -342,7 +341,7 @@ private static void OptimizeMethods(ConfuserContext context) { } } - private static void EndModule(ConfuserContext context) { + static void EndModule(ConfuserContext context) { string output = context.Modules[context.CurrentModuleIndex].Location; if (output != null) { if (!Path.IsPathRooted(output)) @@ -355,7 +354,7 @@ private static void EndModule(ConfuserContext context) { context.OutputPaths[context.CurrentModuleIndex] = output; } - private static void WriteModule(ConfuserContext context) { + static void WriteModule(ConfuserContext context) { context.Logger.InfoFormat("Writing module '{0}'...", context.CurrentModule.Name); MemoryStream pdb = null, output = new MemoryStream(); @@ -377,7 +376,7 @@ private static void WriteModule(ConfuserContext context) { context.CurrentModuleSymbol = pdb.ToArray(); } - private static void Debug(ConfuserContext context) { + static void Debug(ConfuserContext context) { context.Logger.Info("Finalizing..."); for (int i = 0; i < context.OutputModules.Count; i++) { if (context.OutputSymbols[i] == null) @@ -390,14 +389,14 @@ private static void Debug(ConfuserContext context) { } } - private static void Pack(ConfuserContext context) { + static void Pack(ConfuserContext context) { if (context.Packer != null) { context.Logger.Info("Packing..."); context.Packer.Pack(context, new ProtectionParameters(context.Packer, context.Modules.OfType().ToList())); } } - private static void SaveModules(ConfuserContext context) { + static void SaveModules(ConfuserContext context) { context.Resolver.Clear(); for (int i = 0; i < context.OutputModules.Count; i++) { string path = Path.GetFullPath(Path.Combine(context.OutputDirectory, context.OutputPaths[i])); @@ -413,7 +412,7 @@ private static void SaveModules(ConfuserContext context) { /// Prints the copyright stuff and environment information. /// /// The working context. - private static void PrintInfo(ConfuserContext context) { + static void PrintInfo(ConfuserContext context) { if (context.PackerInitiated) { context.Logger.Info("Protecting packer stub..."); } @@ -430,7 +429,7 @@ private static void PrintInfo(ConfuserContext context) { } } - private static IEnumerable GetFrameworkVersions() { + static IEnumerable GetFrameworkVersions() { // http://msdn.microsoft.com/en-us/library/hh925568.aspx using (RegistryKey ndpKey = @@ -479,7 +478,7 @@ private static IEnumerable GetFrameworkVersions() { /// Prints the environment information when error occurred. /// /// The working context. - private static void PrintEnvironmentInfo(ConfuserContext context) { + static void PrintEnvironmentInfo(ConfuserContext context) { if (context.PackerInitiated) return; @@ -505,6 +504,5 @@ private static void PrintEnvironmentInfo(ConfuserContext context) { context.Logger.Error("---END DEBUG INFO---"); } - } } \ No newline at end of file diff --git a/Confuser.Core/ConfuserException.cs b/Confuser.Core/ConfuserException.cs index dc3c7fd34..df9928763 100644 --- a/Confuser.Core/ConfuserException.cs +++ b/Confuser.Core/ConfuserException.cs @@ -5,13 +5,11 @@ namespace Confuser.Core { /// The exception that is thrown when a handled error occurred during the protection process. /// public class ConfuserException : Exception { - /// /// Initializes a new instance of the class. /// /// The inner exception, or null if no exception is associated with the error. public ConfuserException(Exception innerException) : base("Exception occurred during the protection process.", innerException) { } - } } \ No newline at end of file diff --git a/Confuser.Core/ConfuserParameters.cs b/Confuser.Core/ConfuserParameters.cs index acfdb5551..f1e9b8549 100644 --- a/Confuser.Core/ConfuserParameters.cs +++ b/Confuser.Core/ConfuserParameters.cs @@ -6,7 +6,6 @@ namespace Confuser.Core { /// Parameters that passed to . /// public class ConfuserParameters { - /// /// Gets or sets the project that would be processed. /// @@ -56,6 +55,5 @@ internal PluginDiscovery GetPluginDiscovery() { internal Marker GetMarker() { return Marker ?? new Marker(); } - } } \ No newline at end of file diff --git a/Confuser.Core/CoreComponent.cs b/Confuser.Core/CoreComponent.cs index 7bb7d12a8..7ce689039 100644 --- a/Confuser.Core/CoreComponent.cs +++ b/Confuser.Core/CoreComponent.cs @@ -6,7 +6,6 @@ namespace Confuser.Core { /// Core component of Confuser. /// public class CoreComponent : ConfuserComponent { - /// /// The service ID of RNG /// @@ -32,8 +31,8 @@ public class CoreComponent : ConfuserComponent { /// public const string _CompressionServiceId = "Confuser.Compression"; - private readonly Marker marker; - private readonly ConfuserParameters parameters; + readonly Marker marker; + readonly ConfuserParameters parameters; /// /// Initializes a new instance of the class. @@ -78,6 +77,5 @@ protected internal override void Initialize(ConfuserContext context) { protected internal override void PopulatePipeline(ProtectionPipeline pipeline) { // } - } } \ No newline at end of file diff --git a/Confuser.Core/DependencyResolver.cs b/Confuser.Core/DependencyResolver.cs index d04e52728..c7c694525 100644 --- a/Confuser.Core/DependencyResolver.cs +++ b/Confuser.Core/DependencyResolver.cs @@ -8,8 +8,7 @@ namespace Confuser.Core { /// Resolves dependency between protections. /// internal class DependencyResolver { - - private readonly List protections; + readonly List protections; /// /// Initializes a new instance of the class. @@ -77,7 +76,7 @@ public IList SortDependency() { /// The root protections. /// The dependency graph edges. /// Topological sorted protections. - private IEnumerable SortGraph(IEnumerable roots, IList edges) { + IEnumerable SortGraph(IEnumerable roots, IList edges) { var queue = new Queue(roots.OrderBy(prot => prot.FullId)); while (queue.Count > 0) { Protection root = queue.Dequeue(); // Find a node with no incoming edges @@ -97,8 +96,7 @@ private IEnumerable SortGraph(IEnumerable roots, IList /// An edge of dependency graph. /// - private class DependencyGraphEdge { - + class DependencyGraphEdge { /// /// Initializes a new instance of the class. /// @@ -118,16 +116,13 @@ public DependencyGraphEdge(Protection from, Protection to) { /// The destination protection node. /// public Protection To { get; private set; } - } - } /// /// The exception that is thrown when there exists circular dependency between protections. /// internal class CircularDependencyException : Exception { - /// /// Initializes a new instance of the class. /// @@ -150,6 +145,5 @@ internal CircularDependencyException(Protection a, Protection b) /// Second protection that involved in circular dependency. /// public Protection ProtectionB { get; private set; } - } } \ No newline at end of file diff --git a/Confuser.Core/DnlibUtils.cs b/Confuser.Core/DnlibUtils.cs index 819008719..25aa11769 100644 --- a/Confuser.Core/DnlibUtils.cs +++ b/Confuser.Core/DnlibUtils.cs @@ -11,7 +11,6 @@ namespace Confuser.Core { /// Provides a set of utility methods about dnlib /// public static class DnlibUtils { - /// /// Finds all definitions of interest in a module. /// @@ -214,7 +213,7 @@ public static IList FindTypeRefs(this TypeSig typeSig) { return ret; } - private static void FindTypeRefsInternal(TypeSig typeSig, IList ret) { + static void FindTypeRefsInternal(TypeSig typeSig, IList ret) { while (typeSig.Next != null) { if (typeSig is ModifierSig) ret.Add(((ModifierSig)typeSig).Modifier); @@ -348,7 +347,6 @@ public static bool IsArrayAccessors(this IMethod method) { /// wrapper of . /// public class ImageStream : Stream { - /// /// Initializes a new instance of the class. /// @@ -422,6 +420,5 @@ public override void SetLength(long value) { public override void Write(byte[] buffer, int offset, int count) { throw new NotSupportedException(); } - } } \ No newline at end of file diff --git a/Confuser.Core/Helpers/ControlFlowGraph.cs b/Confuser.Core/Helpers/ControlFlowGraph.cs index b6dca6128..54127be3b 100644 --- a/Confuser.Core/Helpers/ControlFlowGraph.cs +++ b/Confuser.Core/Helpers/ControlFlowGraph.cs @@ -9,13 +9,12 @@ namespace Confuser.Core.Helpers { /// A Control Flow Graph (CFG) of a method /// public class ControlFlowGraph : IEnumerable { + readonly List blocks; + readonly CilBody body; + readonly int[] instrBlocks; + readonly Dictionary indexMap; - private readonly List blocks; - private readonly CilBody body; - private readonly int[] instrBlocks; - private readonly Dictionary indexMap; - - private ControlFlowGraph(CilBody body) { + ControlFlowGraph(CilBody body) { this.body = body; instrBlocks = new int[body.Instructions.Count]; blocks = new List(); @@ -76,7 +75,7 @@ public int IndexOf(Instruction instr) { return indexMap[instr]; } - private void PopulateBlockHeaders(HashSet blockHeaders, HashSet entryHeaders) { + void PopulateBlockHeaders(HashSet blockHeaders, HashSet entryHeaders) { for (int i = 0; i < body.Instructions.Count; i++) { Instruction instr = body.Instructions[i]; @@ -106,7 +105,7 @@ private void PopulateBlockHeaders(HashSet blockHeaders, HashSet blockHeaders, HashSet entryHeaders) { + void SplitBlocks(HashSet blockHeaders, HashSet entryHeaders) { int nextBlockId = 0; int currentBlockId = -1; Instruction currentBlockHdr = null; @@ -145,7 +144,7 @@ private void SplitBlocks(HashSet blockHeaders, HashSet } } - private void LinkBlocks() { + void LinkBlocks() { for (int i = 0; i < body.Instructions.Count; i++) { Instruction instr = body.Instructions[i]; if (instr.Operand is Instruction) { @@ -196,7 +195,6 @@ public static ControlFlowGraph Construct(CilBody body) { return graph; } - } /// @@ -204,7 +202,6 @@ public static ControlFlowGraph Construct(CilBody body) { /// [Flags] public enum ControlFlowBlockType { - /// /// The block is a normal block /// @@ -218,15 +215,13 @@ public enum ControlFlowBlockType { /// /// There are unknown edges from this block. Usually used at filter blocks / throw / method exit. /// - Exit = 2, - + Exit = 2 } /// /// A block in Control Flow Graph (CFG). /// public class ControlFlowBlock { - /// /// The footer instruction /// @@ -276,6 +271,5 @@ internal ControlFlowBlock(int id, ControlFlowBlockType type, Instruction header, public override string ToString() { return string.Format("Block {0} => {1} {2}", Id, Type, string.Join(", ", Targets.Select(block => block.Id.ToString()).ToArray())); } - } } \ No newline at end of file diff --git a/Confuser.Core/Helpers/InjectHelper.cs b/Confuser.Core/Helpers/InjectHelper.cs index 2ff532904..d3348fd1d 100644 --- a/Confuser.Core/Helpers/InjectHelper.cs +++ b/Confuser.Core/Helpers/InjectHelper.cs @@ -9,13 +9,12 @@ namespace Confuser.Core.Helpers { /// Provides methods to inject a into another module. /// public static class InjectHelper { - /// /// Clones the specified origin TypeDef. /// /// The origin TypeDef. /// The cloned TypeDef. - private static TypeDefUser Clone(TypeDef origin) { + static TypeDefUser Clone(TypeDef origin) { var ret = new TypeDefUser(origin.Namespace, origin.Name); ret.Attributes = origin.Attributes; @@ -33,7 +32,7 @@ private static TypeDefUser Clone(TypeDef origin) { /// /// The origin MethodDef. /// The cloned MethodDef. - private static MethodDefUser Clone(MethodDef origin) { + static MethodDefUser Clone(MethodDef origin) { var ret = new MethodDefUser(origin.Name, null, origin.ImplAttributes, origin.Attributes); foreach (GenericParam genericParam in origin.GenericParameters) @@ -47,7 +46,7 @@ private static MethodDefUser Clone(MethodDef origin) { /// /// The origin FieldDef. /// The cloned FieldDef. - private static FieldDefUser Clone(FieldDef origin) { + static FieldDefUser Clone(FieldDef origin) { var ret = new FieldDefUser(origin.Name, null, origin.Attributes); return ret; } @@ -58,7 +57,7 @@ private static FieldDefUser Clone(FieldDef origin) { /// The origin TypeDef. /// The injection context. /// The new TypeDef. - private static TypeDef PopulateContext(TypeDef typeDef, InjectContext ctx) { + static TypeDef PopulateContext(TypeDef typeDef, InjectContext ctx) { TypeDef ret; IDnlibDef existing; if (!ctx.Map.TryGetValue(typeDef, out existing)) { @@ -85,7 +84,7 @@ private static TypeDef PopulateContext(TypeDef typeDef, InjectContext ctx) { /// /// The origin TypeDef. /// The injection context. - private static void CopyTypeDef(TypeDef typeDef, InjectContext ctx) { + static void CopyTypeDef(TypeDef typeDef, InjectContext ctx) { var newTypeDef = (TypeDef)ctx.Map[typeDef]; newTypeDef.BaseType = (ITypeDefOrRef)ctx.Importer.Import(typeDef.BaseType); @@ -99,7 +98,7 @@ private static void CopyTypeDef(TypeDef typeDef, InjectContext ctx) { /// /// The origin MethodDef. /// The injection context. - private static void CopyMethodDef(MethodDef methodDef, InjectContext ctx) { + static void CopyMethodDef(MethodDef methodDef, InjectContext ctx) { var newMethodDef = (MethodDef)ctx.Map[methodDef]; newMethodDef.Signature = ctx.Importer.Import(methodDef.Signature); @@ -165,7 +164,7 @@ private static void CopyMethodDef(MethodDef methodDef, InjectContext ctx) { /// /// The origin FieldDef. /// The injection context. - private static void CopyFieldDef(FieldDef fieldDef, InjectContext ctx) { + static void CopyFieldDef(FieldDef fieldDef, InjectContext ctx) { var newFieldDef = (FieldDef)ctx.Map[fieldDef]; newFieldDef.Signature = ctx.Importer.Import(fieldDef.Signature); @@ -177,7 +176,7 @@ private static void CopyFieldDef(FieldDef fieldDef, InjectContext ctx) { /// The origin TypeDef. /// The injection context. /// if set to true, copy information of . - private static void Copy(TypeDef typeDef, InjectContext ctx, bool copySelf) { + static void Copy(TypeDef typeDef, InjectContext ctx, bool copySelf) { if (copySelf) CopyTypeDef(typeDef, ctx); @@ -235,8 +234,7 @@ public static IEnumerable Inject(TypeDef typeDef, TypeDef newType, Mo /// /// Context of the injection process. /// - private class InjectContext : ImportResolver { - + class InjectContext : ImportResolver { /// /// The mapping of origin definitions to injected definitions. /// @@ -255,7 +253,7 @@ private class InjectContext : ImportResolver { /// /// The importer. /// - private readonly Importer importer; + readonly Importer importer; /// /// Initializes a new instance of the class. @@ -297,8 +295,6 @@ public override FieldDef Resolve(FieldDef fieldDef) { return (FieldDef)Map[fieldDef]; return null; } - } - } } \ No newline at end of file diff --git a/Confuser.Core/Helpers/KeySequence.cs b/Confuser.Core/Helpers/KeySequence.cs index fbf93a6d2..7f956cdfa 100644 --- a/Confuser.Core/Helpers/KeySequence.cs +++ b/Confuser.Core/Helpers/KeySequence.cs @@ -9,7 +9,6 @@ namespace Confuser.Core.Helpers { /// The type of block in the key sequence /// public enum BlockKeyType { - /// /// The state key should be explicitly set in the block /// @@ -19,14 +18,12 @@ public enum BlockKeyType { /// The state key could be assumed to be same as at the beginning of block. /// Incremental - } /// /// The information of the block in the key sequence /// public struct BlockKey { - /// /// The state key at the beginning of the block /// @@ -41,7 +38,6 @@ public struct BlockKey { /// The type of block /// public BlockKeyType Type; - } /// @@ -63,7 +59,6 @@ public struct BlockKey { /// /// public static class KeySequence { - /// /// Computes a key sequence of the given CFG. /// @@ -85,7 +80,7 @@ public static BlockKey[] ComputeKeys(ControlFlowGraph graph, RandomGenerator ran return keys; } - private static void ProcessBlocks(BlockKey[] keys, ControlFlowGraph graph, RandomGenerator random) { + static void ProcessBlocks(BlockKey[] keys, ControlFlowGraph graph, RandomGenerator random) { uint id = 0; for (int i = 0; i < keys.Length; i++) { keys[i].EntryState = id++; @@ -125,13 +120,13 @@ private static void ProcessBlocks(BlockKey[] keys, ControlFlowGraph graph, Rando foreach (var eh in graph.Body.ExceptionHandlers) { if (eh.FilterStart != null && block.Footer.OpCode.Code == Code.Endfilter) { if (footerIndex >= graph.IndexOf(eh.FilterStart) && - footerIndex < graph.IndexOf(eh.HandlerStart)) + footerIndex < graph.IndexOf(eh.HandlerStart)) ehs.Add(eh); } else if (eh.HandlerType == ExceptionHandlerType.Finally || - eh.HandlerType == ExceptionHandlerType.Fault) { + eh.HandlerType == ExceptionHandlerType.Fault) { if (footerIndex >= graph.IndexOf(eh.HandlerStart) && - (eh.HandlerEnd == null || footerIndex < graph.IndexOf(eh.HandlerEnd))) + (eh.HandlerEnd == null || footerIndex < graph.IndexOf(eh.HandlerEnd))) ehs.Add(eh); } } @@ -163,7 +158,7 @@ private static void ProcessBlocks(BlockKey[] keys, ControlFlowGraph graph, Rando int footerIndex = graph.IndexOf(block.Footer); foreach (var eh in graph.Body.ExceptionHandlers) { if (footerIndex >= graph.IndexOf(eh.TryStart) && - (eh.TryEnd == null || footerIndex < graph.IndexOf(eh.TryEnd))) + (eh.TryEnd == null || footerIndex < graph.IndexOf(eh.TryEnd))) ehs.Add(eh); } ehMap[block] = ehs; @@ -211,6 +206,5 @@ private static void ProcessBlocks(BlockKey[] keys, ControlFlowGraph graph, Rando keys[i] = key; } } - } } \ No newline at end of file diff --git a/Confuser.Core/Helpers/MutationHelper.cs b/Confuser.Core/Helpers/MutationHelper.cs index 117129aee..e7b02a4ea 100644 --- a/Confuser.Core/Helpers/MutationHelper.cs +++ b/Confuser.Core/Helpers/MutationHelper.cs @@ -10,10 +10,9 @@ namespace Confuser.Core.Helpers { /// Provides methods to mutated injected methods. /// public static class MutationHelper { + const string mutationType = "Mutation"; - private const string mutationType = "Mutation"; - - private static readonly Dictionary field2index = new Dictionary { + static readonly Dictionary field2index = new Dictionary { { "KeyI0", 0 }, { "KeyI1", 1 }, { "KeyI2", 2 }, @@ -104,6 +103,5 @@ public static void ReplacePlaceholder(MethodDef method, Func public interface ILogger { - /// /// Logs a message at DEBUG level. /// @@ -101,6 +100,5 @@ public interface ILogger { /// /// Indicated whether the protection process is successful. void Finish(bool successful); - } } \ No newline at end of file diff --git a/Confuser.Core/Marker.cs b/Confuser.Core/Marker.cs index f635af962..1c6904d95 100644 --- a/Confuser.Core/Marker.cs +++ b/Confuser.Core/Marker.cs @@ -15,7 +15,6 @@ namespace Confuser.Core { /// Resolves and marks the modules with protection settings according to the rules. /// public class Marker { - /// /// Annotation key of Strong Name Key. /// @@ -30,6 +29,7 @@ public class Marker { /// The packers available to use. /// protected Dictionary packers; + /// /// The protections available to use. /// @@ -50,7 +50,7 @@ public virtual void Initalize(IList protections, IList packe /// /// The preset. /// The settings. - private void FillPreset(ProtectionPreset preset, ProtectionSettings settings) { + void FillPreset(ProtectionPreset preset, ProtectionSettings settings) { foreach (Protection prot in protections.Values) if (prot.Preset <= preset && !settings.ContainsKey(prot)) settings.Add(prot, new Dictionary()); @@ -119,7 +119,7 @@ protected internal virtual MarkerResult MarkProject(ConfuserProject proj, Confus extModules.Add(module.LoadRaw(proj.BaseDirectory)); continue; } - + ModuleDefMD modDef = module.Resolve(proj.BaseDirectory, context.Resolver.DefaultModuleContext); context.CheckCancellation(); @@ -216,6 +216,5 @@ protected void ApplyRules(ConfuserContext context, IDnlibDef target, Rules rules ProtectionParameters.SetParameters(context, target, ret); } - } } \ No newline at end of file diff --git a/Confuser.Core/MarkerResult.cs b/Confuser.Core/MarkerResult.cs index 5412e7399..ef7e14d82 100644 --- a/Confuser.Core/MarkerResult.cs +++ b/Confuser.Core/MarkerResult.cs @@ -7,7 +7,6 @@ namespace Confuser.Core { /// Result of the marker. /// public class MarkerResult { - /// /// Initializes a new instance of the class. /// @@ -37,6 +36,5 @@ public MarkerResult(IList modules, Packer packer, IList ext /// /// The packer, or null if no packer exists. public Packer Packer { get; private set; } - } } \ No newline at end of file diff --git a/Confuser.Core/ModuleWriterListener.cs b/Confuser.Core/ModuleWriterListener.cs index a7cfecb25..c8f127324 100644 --- a/Confuser.Core/ModuleWriterListener.cs +++ b/Confuser.Core/ModuleWriterListener.cs @@ -6,7 +6,6 @@ namespace Confuser.Core { /// The listener of module writer event. /// public class ModuleWriterListener : IModuleWriterListener { - /// void IModuleWriterListener.OnWriterEvent(ModuleWriterBase writer, ModuleWriterEvent evt) { if (OnWriterEvent != null) { @@ -18,14 +17,12 @@ void IModuleWriterListener.OnWriterEvent(ModuleWriterBase writer, ModuleWriterEv /// Occurs when a module writer event is triggered. /// public event EventHandler OnWriterEvent; - } /// /// Indicates the triggered writer event. /// public class ModuleWriterListenerEventArgs : EventArgs { - /// /// Initializes a new instance of the class. /// @@ -39,6 +36,5 @@ public ModuleWriterListenerEventArgs(ModuleWriterEvent evt) { /// /// The triggered writer event. public ModuleWriterEvent WriterEvent { get; private set; } - } } \ No newline at end of file diff --git a/Confuser.Core/NullLogger.cs b/Confuser.Core/NullLogger.cs index 87cf88fc2..9d629a0ce 100644 --- a/Confuser.Core/NullLogger.cs +++ b/Confuser.Core/NullLogger.cs @@ -6,7 +6,6 @@ namespace Confuser.Core { /// An implementation that doesn't actually do any logging. /// internal class NullLogger : ILogger { - /// /// The singleton instance of . /// @@ -15,7 +14,7 @@ internal class NullLogger : ILogger { /// /// Prevents a default instance of the class from being created. /// - private NullLogger() { } + NullLogger() { } /// public void Debug(string msg) { } @@ -61,6 +60,5 @@ public void BeginModule(ModuleDef module) { } /// public void EndModule(ModuleDef module) { } - } } \ No newline at end of file diff --git a/Confuser.Core/Packer.cs b/Confuser.Core/Packer.cs index cc661590c..005be2f0f 100644 --- a/Confuser.Core/Packer.cs +++ b/Confuser.Core/Packer.cs @@ -12,7 +12,6 @@ namespace Confuser.Core { /// A parameterless constructor must exists in derived classes to enable plugin discovery. /// public abstract class Packer : ConfuserComponent { - /// /// Executes the packer. /// @@ -76,12 +75,10 @@ protected void ProtectStub(ConfuserContext context, string fileName, byte[] modu context.OutputModules = new[] { File.ReadAllBytes(Path.Combine(outDir, fileName)) }; context.OutputPaths = new[] { fileName }; } - } internal class PackerLogger : ILogger { - - private readonly ILogger baseLogger; + readonly ILogger baseLogger; public PackerLogger(ILogger baseLogger) { this.baseLogger = baseLogger; @@ -140,12 +137,10 @@ public void Finish(bool successful) { throw new ConfuserException(null); baseLogger.Info("Finish protecting packer stub."); } - } internal class PackerMarker : Marker { - - private readonly StrongNameKey snKey; + readonly StrongNameKey snKey; public PackerMarker(StrongNameKey snKey) { this.snKey = snKey; @@ -157,12 +152,10 @@ protected internal override MarkerResult MarkProject(ConfuserProject proj, Confu context.Annotations.Set(module, SNKey, snKey); return result; } - } internal class PackerDiscovery : PluginDiscovery { - - private readonly Protection prot; + readonly Protection prot; public PackerDiscovery(Protection prot) { this.prot = prot; @@ -172,6 +165,5 @@ protected override void GetPluginsInternal(ConfuserContext context, IList public class PluginDiscovery { - /// /// The default plugin discovery service. /// @@ -132,6 +131,5 @@ protected virtual void GetPluginsInternal( } } } - } } \ No newline at end of file diff --git a/Confuser.Core/Project/ConfuserProject.cs b/Confuser.Core/Project/ConfuserProject.cs index 5f18945ba..0969b6f0a 100644 --- a/Confuser.Core/Project/ConfuserProject.cs +++ b/Confuser.Core/Project/ConfuserProject.cs @@ -1,5 +1,6 @@ using System; using System.Collections.Generic; +using System.IO; using System.Linq; using System.Xml; using System.Xml.Schema; @@ -10,7 +11,6 @@ namespace Confuser.Core.Project { /// A module description in a Confuser project. /// public class ProjectModule { - /// /// Initializes a new instance of the class. /// @@ -71,8 +71,8 @@ public ModuleDefMD Resolve(string basePath, ModuleContext context = null) { /// The loaded module. public byte[] LoadRaw(string basePath) { if (basePath == null) - return System.IO.File.ReadAllBytes(Path); - return System.IO.File.ReadAllBytes(System.IO.Path.Combine(basePath, Path)); + return File.ReadAllBytes(Path); + return File.ReadAllBytes(System.IO.Path.Combine(basePath, Path)); } /// @@ -87,7 +87,7 @@ internal XmlElement Save(XmlDocument xmlDoc) { nameAttr.Value = Path; elem.Attributes.Append(nameAttr); - if (IsExternal != false) { + if (IsExternal) { XmlAttribute extAttr = xmlDoc.CreateAttribute("external"); extAttr.Value = IsExternal.ToString(); elem.Attributes.Append(extAttr); @@ -147,14 +147,12 @@ internal void Load(XmlElement elem) { public override string ToString() { return Path; } - } /// /// Indicates add or remove the protection from the active protections /// public enum SettingItemAction { - /// /// Add the protection to the active protections /// @@ -164,7 +162,6 @@ public enum SettingItemAction { /// Remove the protection from the active protections /// Remove - } /// @@ -172,7 +169,6 @@ public enum SettingItemAction { /// /// or public class SettingItem : Dictionary { - /// /// The identifier of component /// @@ -236,7 +232,6 @@ internal void Load(XmlElement elem) { foreach (XmlElement i in elem.ChildNodes.OfType()) Add(i.Attributes["name"].Value, i.Attributes["value"].Value); } - } @@ -244,7 +239,6 @@ internal void Load(XmlElement elem) { /// A rule that control how s are applied to module /// public class Rule : List> { - /// /// Gets or sets the pattern that determine the target components of the rule. /// @@ -338,14 +332,12 @@ public Rule Clone() { } return ret; } - } /// /// The exception that is thrown when there exists schema errors in the project XML. /// public class ProjectValidationException : Exception { - /// /// Initializes a new instance of the class. /// @@ -360,14 +352,12 @@ internal ProjectValidationException(List exceptions) /// /// A list of schema exceptions. public IList Errors { get; private set; } - } /// /// Represent a project of Confuser. /// public class ConfuserProject : List { - /// /// The namespace of Confuser project schema /// @@ -551,6 +541,5 @@ public void Load(XmlDocument doc) { } } } - } } \ No newline at end of file diff --git a/Confuser.Core/Project/InvalidPatternException.cs b/Confuser.Core/Project/InvalidPatternException.cs index 3baaaf29e..e3236454b 100644 --- a/Confuser.Core/Project/InvalidPatternException.cs +++ b/Confuser.Core/Project/InvalidPatternException.cs @@ -5,7 +5,6 @@ namespace Confuser.Core.Project { /// The exception that is thrown when attempted to parse an invalid pattern. /// public class InvalidPatternException : Exception { - /// /// Initializes a new instance of the class. /// @@ -23,6 +22,5 @@ public InvalidPatternException(string message) /// public InvalidPatternException(string message, Exception innerException) : base(message, innerException) { } - } } \ No newline at end of file diff --git a/Confuser.Core/Project/PatternParser.cs b/Confuser.Core/Project/PatternParser.cs index b3e8ee97b..f839aaa70 100644 --- a/Confuser.Core/Project/PatternParser.cs +++ b/Confuser.Core/Project/PatternParser.cs @@ -7,11 +7,10 @@ namespace Confuser.Core.Project { /// Parser of pattern expressions. /// public class PatternParser { - - private static readonly Dictionary> fns; - private static readonly Dictionary> ops; - private readonly PatternTokenizer tokenizer = new PatternTokenizer(); - private PatternToken? lookAhead; + static readonly Dictionary> fns; + static readonly Dictionary> ops; + readonly PatternTokenizer tokenizer = new PatternTokenizer(); + PatternToken? lookAhead; static PatternParser() { fns = new Dictionary>(StringComparer.OrdinalIgnoreCase); @@ -61,43 +60,43 @@ public PatternExpression Parse(string pattern) { } } - private static bool IsFunction(PatternToken token) { + static bool IsFunction(PatternToken token) { if (token.Type != TokenType.Identifier) return false; return fns.ContainsKey(token.Value); } - private static bool IsOperator(PatternToken token) { + static bool IsOperator(PatternToken token) { if (token.Type != TokenType.Identifier) return false; return ops.ContainsKey(token.Value); } - private Exception UnexpectedEnd() { + Exception UnexpectedEnd() { throw new InvalidPatternException("Unexpected end of pattern."); } - private Exception MismatchParens(int position) { + Exception MismatchParens(int position) { throw new InvalidPatternException(string.Format("Mismatched parentheses at position {0}.", position)); } - private Exception UnknownToken(PatternToken token) { + Exception UnknownToken(PatternToken token) { throw new InvalidPatternException(string.Format("Unknown token '{0}' at position {1}.", token.Value, token.Position)); } - private Exception UnexpectedToken(PatternToken token) { + Exception UnexpectedToken(PatternToken token) { throw new InvalidPatternException(string.Format("Unexpected token '{0}' at position {1}.", token.Value, token.Position)); } - private Exception UnexpectedToken(PatternToken token, char expect) { + Exception UnexpectedToken(PatternToken token, char expect) { throw new InvalidPatternException(string.Format("Unexpected token '{0}' at position {1}. Expected '{2}'.", token.Value, token.Position, expect)); } - private Exception BadArgCount(PatternToken token, int expected) { + Exception BadArgCount(PatternToken token, int expected) { throw new InvalidPatternException(string.Format("Invalid argument count for '{0}' at position {1}. Expected {2}", token.Value, token.Position, expected)); } - private PatternToken ReadToken() { + PatternToken ReadToken() { if (lookAhead == null) throw UnexpectedEnd(); PatternToken ret = lookAhead.Value; @@ -105,11 +104,11 @@ private PatternToken ReadToken() { return ret; } - private PatternToken? PeekToken() { + PatternToken? PeekToken() { return lookAhead; } - private PatternExpression ParseExpression(bool readBinOp = false) { + PatternExpression ParseExpression(bool readBinOp = false) { PatternExpression ret; PatternToken token = ReadToken(); switch (token.Type) { @@ -199,6 +198,5 @@ private PatternExpression ParseExpression(bool readBinOp = false) { return ret; } - } } \ No newline at end of file diff --git a/Confuser.Core/Project/PatternToken.cs b/Confuser.Core/Project/PatternToken.cs index f99ed0140..39d98e91b 100644 --- a/Confuser.Core/Project/PatternToken.cs +++ b/Confuser.Core/Project/PatternToken.cs @@ -5,7 +5,6 @@ namespace Confuser.Core.Project { /// The type of pattern tokens /// public enum TokenType { - /// /// An identifier, could be functions/operators. /// @@ -29,8 +28,7 @@ public enum TokenType { /// /// A comma. /// - Comma, - + Comma } @@ -38,7 +36,6 @@ public enum TokenType { /// Represent a token in pattern /// public struct PatternToken { - /// /// The position of this token in the pattern, or null if position not available. /// @@ -109,6 +106,5 @@ public override string ToString() { return string.Format("[{0}] {1}", Type, Value); return string.Format("[{0}]", Type); } - } } \ No newline at end of file diff --git a/Confuser.Core/Project/PatternTokenizer.cs b/Confuser.Core/Project/PatternTokenizer.cs index 49192714e..b2c64b7d5 100644 --- a/Confuser.Core/Project/PatternTokenizer.cs +++ b/Confuser.Core/Project/PatternTokenizer.cs @@ -4,33 +4,32 @@ namespace Confuser.Core.Project { internal class PatternTokenizer { - - private int index; - private string rulePattern; + int index; + string rulePattern; public void Initialize(string pattern) { rulePattern = pattern; index = 0; } - private void SkipWhitespace() { + void SkipWhitespace() { while (index < rulePattern.Length && char.IsWhiteSpace(rulePattern[index])) index++; } - private char? PeekChar() { + char? PeekChar() { if (index >= rulePattern.Length) return null; return rulePattern[index]; } - private char NextChar() { + char NextChar() { if (index >= rulePattern.Length) throw new InvalidPatternException("Unexpected end of pattern."); return rulePattern[index++]; } - private string ReadLiteral() { + string ReadLiteral() { var ret = new StringBuilder(); char delim = NextChar(); Debug.Assert(delim == '"' || delim == '\''); @@ -47,7 +46,7 @@ private string ReadLiteral() { return ret.ToString(); } - private string ReadIdentifier() { + string ReadIdentifier() { var ret = new StringBuilder(); char? chr = PeekChar(); @@ -91,6 +90,5 @@ private string ReadIdentifier() { return new PatternToken(pos, TokenType.Identifier, ReadIdentifier()); } } - } } \ No newline at end of file diff --git a/Confuser.Core/Project/Patterns/AndOperator.cs b/Confuser.Core/Project/Patterns/AndOperator.cs index 08a325511..e55f27a90 100644 --- a/Confuser.Core/Project/Patterns/AndOperator.cs +++ b/Confuser.Core/Project/Patterns/AndOperator.cs @@ -6,7 +6,6 @@ namespace Confuser.Core.Project.Patterns { /// The AND operator. /// public class AndOperator : PatternOperator { - internal const string OpName = "and"; /// @@ -25,6 +24,5 @@ public override object Evaluate(IDnlibDef definition) { if (!a) return false; return (bool)OperandB.Evaluate(definition); } - } } \ No newline at end of file diff --git a/Confuser.Core/Project/Patterns/DeclTypeFunction.cs b/Confuser.Core/Project/Patterns/DeclTypeFunction.cs index 1d333ae70..40af325f0 100644 --- a/Confuser.Core/Project/Patterns/DeclTypeFunction.cs +++ b/Confuser.Core/Project/Patterns/DeclTypeFunction.cs @@ -6,7 +6,6 @@ namespace Confuser.Core.Project.Patterns { /// A function that compare the full name of declaring type. /// public class DeclTypeFunction : PatternFunction { - internal const string FnName = "decl-type"; /// @@ -26,6 +25,5 @@ public override object Evaluate(IDnlibDef definition) { object fullName = Arguments[0].Evaluate(definition); return ((IMemberDef)definition).DeclaringType.FullName == fullName.ToString(); } - } } \ No newline at end of file diff --git a/Confuser.Core/Project/Patterns/FullNameFunction.cs b/Confuser.Core/Project/Patterns/FullNameFunction.cs index eb9ec6b16..4fbd7b9d6 100644 --- a/Confuser.Core/Project/Patterns/FullNameFunction.cs +++ b/Confuser.Core/Project/Patterns/FullNameFunction.cs @@ -6,7 +6,6 @@ namespace Confuser.Core.Project.Patterns { /// A function that compare the full name of definition. /// public class FullNameFunction : PatternFunction { - internal const string FnName = "full-name"; /// @@ -24,6 +23,5 @@ public override object Evaluate(IDnlibDef definition) { object name = Arguments[0].Evaluate(definition); return definition.FullName == name.ToString(); } - } } \ No newline at end of file diff --git a/Confuser.Core/Project/Patterns/InheritsFunction.cs b/Confuser.Core/Project/Patterns/InheritsFunction.cs index cac492bce..3a6f4bfc3 100644 --- a/Confuser.Core/Project/Patterns/InheritsFunction.cs +++ b/Confuser.Core/Project/Patterns/InheritsFunction.cs @@ -6,7 +6,6 @@ namespace Confuser.Core.Project.Patterns { /// A function that indicate whether the type inherits from the specified type. /// public class InheritsFunction : PatternFunction { - internal const string FnName = "inherits"; /// @@ -32,6 +31,5 @@ public override object Evaluate(IDnlibDef definition) { } return false; } - } } \ No newline at end of file diff --git a/Confuser.Core/Project/Patterns/IsPublicFunction.cs b/Confuser.Core/Project/Patterns/IsPublicFunction.cs index df9f2df09..9fe96f1b0 100644 --- a/Confuser.Core/Project/Patterns/IsPublicFunction.cs +++ b/Confuser.Core/Project/Patterns/IsPublicFunction.cs @@ -6,7 +6,6 @@ namespace Confuser.Core.Project.Patterns { /// A function that indicate the visibility of members. /// public class IsPublicFunction : PatternFunction { - internal const string FnName = "is-public"; /// @@ -45,6 +44,5 @@ public override object Evaluate(IDnlibDef definition) { throw new NotSupportedException(); } - } } \ No newline at end of file diff --git a/Confuser.Core/Project/Patterns/IsTypeFunction.cs b/Confuser.Core/Project/Patterns/IsTypeFunction.cs index 2b5914ff2..49b305d75 100644 --- a/Confuser.Core/Project/Patterns/IsTypeFunction.cs +++ b/Confuser.Core/Project/Patterns/IsTypeFunction.cs @@ -6,7 +6,6 @@ namespace Confuser.Core.Project.Patterns { /// A function that indicate the type of type(?). /// public class IsTypeFunction : PatternFunction { - internal const string FnName = "is-type"; /// @@ -44,6 +43,5 @@ public override object Evaluate(IDnlibDef definition) { return false; } - } } \ No newline at end of file diff --git a/Confuser.Core/Project/Patterns/LiteralExpression.cs b/Confuser.Core/Project/Patterns/LiteralExpression.cs index 50a02f895..e796aaaee 100644 --- a/Confuser.Core/Project/Patterns/LiteralExpression.cs +++ b/Confuser.Core/Project/Patterns/LiteralExpression.cs @@ -7,7 +7,6 @@ namespace Confuser.Core.Project.Patterns { /// A literal expression. /// public class LiteralExpression : PatternExpression { - /// /// Initializes a new instance of the class. /// @@ -36,6 +35,5 @@ public override void Serialize(IList tokens) { else tokens.Add(new PatternToken(TokenType.Literal, Literal.ToString())); } - } } \ No newline at end of file diff --git a/Confuser.Core/Project/Patterns/MatchFunction.cs b/Confuser.Core/Project/Patterns/MatchFunction.cs index b9ba2bac0..94ff40e38 100644 --- a/Confuser.Core/Project/Patterns/MatchFunction.cs +++ b/Confuser.Core/Project/Patterns/MatchFunction.cs @@ -7,7 +7,6 @@ namespace Confuser.Core.Project.Patterns { /// A function that match the full name of the definition with specified RegEx. /// public class MatchFunction : PatternFunction { - internal const string FnName = "match"; /// @@ -25,14 +24,12 @@ public override object Evaluate(IDnlibDef definition) { string regex = Arguments[0].Evaluate(definition).ToString(); return Regex.IsMatch(definition.FullName, regex); } - } /// /// A function that match the name of the definition with specified RegEx. /// public class MatchNameFunction : PatternFunction { - internal const string FnName = "match-name"; /// @@ -50,14 +47,12 @@ public override object Evaluate(IDnlibDef definition) { string regex = Arguments[0].Evaluate(definition).ToString(); return Regex.IsMatch(definition.Name, regex); } - } /// /// A function that match the name of declaring type with specified RegEx. /// public class MatchTypeNameFunction : PatternFunction { - internal const string FnName = "match-type-name"; /// @@ -82,6 +77,5 @@ public override object Evaluate(IDnlibDef definition) { } return false; } - } } \ No newline at end of file diff --git a/Confuser.Core/Project/Patterns/MemberTypeFunction.cs b/Confuser.Core/Project/Patterns/MemberTypeFunction.cs index 7093affbb..0557bfe74 100644 --- a/Confuser.Core/Project/Patterns/MemberTypeFunction.cs +++ b/Confuser.Core/Project/Patterns/MemberTypeFunction.cs @@ -6,7 +6,6 @@ namespace Confuser.Core.Project.Patterns { /// A function that compare the type of definition. /// public class MemberTypeFunction : PatternFunction { - internal const string FnName = "member-type"; /// @@ -43,6 +42,5 @@ public override object Evaluate(IDnlibDef definition) { return false; } - } } \ No newline at end of file diff --git a/Confuser.Core/Project/Patterns/ModuleFunction.cs b/Confuser.Core/Project/Patterns/ModuleFunction.cs index 278d4ce0c..4c123462e 100644 --- a/Confuser.Core/Project/Patterns/ModuleFunction.cs +++ b/Confuser.Core/Project/Patterns/ModuleFunction.cs @@ -6,7 +6,6 @@ namespace Confuser.Core.Project.Patterns { /// A function that compare the module of definition. /// public class ModuleFunction : PatternFunction { - internal const string FnName = "module"; /// @@ -26,6 +25,5 @@ public override object Evaluate(IDnlibDef definition) { object name = Arguments[0].Evaluate(definition); return ((IOwnerModule)definition).Module.Name == name.ToString(); } - } } \ No newline at end of file diff --git a/Confuser.Core/Project/Patterns/NameFunction.cs b/Confuser.Core/Project/Patterns/NameFunction.cs index e69ec9031..c6d8d49a5 100644 --- a/Confuser.Core/Project/Patterns/NameFunction.cs +++ b/Confuser.Core/Project/Patterns/NameFunction.cs @@ -6,7 +6,6 @@ namespace Confuser.Core.Project.Patterns { /// A function that compare the name of definition. /// public class NameFunction : PatternFunction { - internal const string FnName = "name"; /// @@ -24,6 +23,5 @@ public override object Evaluate(IDnlibDef definition) { object name = Arguments[0].Evaluate(definition); return definition.Name == name.ToString(); } - } } \ No newline at end of file diff --git a/Confuser.Core/Project/Patterns/NamespaceFunction.cs b/Confuser.Core/Project/Patterns/NamespaceFunction.cs index 05a44ad73..d005ace03 100644 --- a/Confuser.Core/Project/Patterns/NamespaceFunction.cs +++ b/Confuser.Core/Project/Patterns/NamespaceFunction.cs @@ -6,7 +6,6 @@ namespace Confuser.Core.Project.Patterns { /// A function that compare the namespace of definition. /// public class NamespaceFunction : PatternFunction { - internal const string FnName = "namespace"; /// @@ -34,6 +33,5 @@ public override object Evaluate(IDnlibDef definition) { return type != null && type.Namespace == ns.ToString(); } - } } \ No newline at end of file diff --git a/Confuser.Core/Project/Patterns/NotOperator.cs b/Confuser.Core/Project/Patterns/NotOperator.cs index cc5da0d91..65dd31f78 100644 --- a/Confuser.Core/Project/Patterns/NotOperator.cs +++ b/Confuser.Core/Project/Patterns/NotOperator.cs @@ -6,7 +6,6 @@ namespace Confuser.Core.Project.Patterns { /// The NOT operator. /// public class NotOperator : PatternOperator { - internal const string OpName = "not"; /// @@ -23,6 +22,5 @@ public override bool IsUnary { public override object Evaluate(IDnlibDef definition) { return !(bool)OperandA.Evaluate(definition); } - } } \ No newline at end of file diff --git a/Confuser.Core/Project/Patterns/OrOperator.cs b/Confuser.Core/Project/Patterns/OrOperator.cs index 87c1d3272..112150e91 100644 --- a/Confuser.Core/Project/Patterns/OrOperator.cs +++ b/Confuser.Core/Project/Patterns/OrOperator.cs @@ -6,7 +6,6 @@ namespace Confuser.Core.Project.Patterns { /// The OR operator. /// public class OrOperator : PatternOperator { - internal const string OpName = "or"; /// @@ -25,6 +24,5 @@ public override object Evaluate(IDnlibDef definition) { if (a) return true; return (bool)OperandB.Evaluate(definition); } - } } \ No newline at end of file diff --git a/Confuser.Core/Project/Patterns/PatternExpression.cs b/Confuser.Core/Project/Patterns/PatternExpression.cs index 34068d008..e0700ef7d 100644 --- a/Confuser.Core/Project/Patterns/PatternExpression.cs +++ b/Confuser.Core/Project/Patterns/PatternExpression.cs @@ -7,7 +7,6 @@ namespace Confuser.Core.Project.Patterns { /// A pattern expression. /// public abstract class PatternExpression { - /// /// Evaluates the expression on the specified definition. /// @@ -20,6 +19,5 @@ public abstract class PatternExpression { /// /// The output list of tokens. public abstract void Serialize(IList tokens); - } } \ No newline at end of file diff --git a/Confuser.Core/Project/Patterns/PatternFunction.cs b/Confuser.Core/Project/Patterns/PatternFunction.cs index 81250183c..29aeae9d3 100644 --- a/Confuser.Core/Project/Patterns/PatternFunction.cs +++ b/Confuser.Core/Project/Patterns/PatternFunction.cs @@ -6,7 +6,6 @@ namespace Confuser.Core.Project.Patterns { /// A pattern function. /// public abstract class PatternFunction : PatternExpression { - /// /// Gets the name of function. /// @@ -36,6 +35,5 @@ public override void Serialize(IList tokens) { } tokens.Add(new PatternToken(TokenType.RParens)); } - } } \ No newline at end of file diff --git a/Confuser.Core/Project/Patterns/PatternOperator.cs b/Confuser.Core/Project/Patterns/PatternOperator.cs index e2bd8ec48..96c9bd652 100644 --- a/Confuser.Core/Project/Patterns/PatternOperator.cs +++ b/Confuser.Core/Project/Patterns/PatternOperator.cs @@ -6,7 +6,6 @@ namespace Confuser.Core.Project.Patterns { /// A pattern operator. /// public abstract class PatternOperator : PatternExpression { - /// /// Gets the name of operator. /// @@ -43,6 +42,5 @@ public override void Serialize(IList tokens) { OperandB.Serialize(tokens); } } - } } \ No newline at end of file diff --git a/Confuser.Core/Protection.cs b/Confuser.Core/Protection.cs index 989c7f05a..f7bb08075 100644 --- a/Confuser.Core/Protection.cs +++ b/Confuser.Core/Protection.cs @@ -8,12 +8,10 @@ namespace Confuser.Core { /// A parameterless constructor must exists in derived classes to enable plugin discovery. /// public abstract class Protection : ConfuserComponent { - /// /// Gets the preset this protection is in. /// /// The protection's preset. public abstract ProtectionPreset Preset { get; } - } } \ No newline at end of file diff --git a/Confuser.Core/ProtectionDependencyAttributes.cs b/Confuser.Core/ProtectionDependencyAttributes.cs index ac69b77ec..dabdcaaa9 100644 --- a/Confuser.Core/ProtectionDependencyAttributes.cs +++ b/Confuser.Core/ProtectionDependencyAttributes.cs @@ -4,9 +4,8 @@ namespace Confuser.Core { /// /// Indicates the must initialize before the specified protections. /// - [AttributeUsage(AttributeTargets.Class, AllowMultiple = false)] + [AttributeUsage(AttributeTargets.Class)] public class BeforeProtectionAttribute : Attribute { - /// /// Initializes a new instance of the class. /// @@ -20,15 +19,13 @@ public BeforeProtectionAttribute(params string[] ids) { /// /// The IDs of protections. public string[] Ids { get; private set; } - } /// /// Indicates the must initialize after the specified protections. /// - [AttributeUsage(AttributeTargets.Class, AllowMultiple = false)] + [AttributeUsage(AttributeTargets.Class)] public class AfterProtectionAttribute : Attribute { - /// /// Initializes a new instance of the class. /// @@ -42,6 +39,5 @@ public AfterProtectionAttribute(params string[] ids) { /// /// The IDs of protections. public string[] Ids { get; private set; } - } } \ No newline at end of file diff --git a/Confuser.Core/ProtectionParameters.cs b/Confuser.Core/ProtectionParameters.cs index 2af5858c7..470d6d560 100644 --- a/Confuser.Core/ProtectionParameters.cs +++ b/Confuser.Core/ProtectionParameters.cs @@ -9,15 +9,14 @@ namespace Confuser.Core { /// Parameters of . /// public class ProtectionParameters { - - private static readonly object ParametersKey = new object(); + static readonly object ParametersKey = new object(); /// /// A empty instance of . /// public static readonly ProtectionParameters Empty = new ProtectionParameters(null, new IDnlibDef[0]); - private readonly ConfuserComponent comp; + readonly ConfuserComponent comp; /// /// Initializes a new instance of the class. @@ -99,6 +98,5 @@ public static ProtectionSettings GetParameters( ConfuserContext context, IDnlibDef target) { return context.Annotations.Get(target, ParametersKey); } - } } \ No newline at end of file diff --git a/Confuser.Core/ProtectionPhase.cs b/Confuser.Core/ProtectionPhase.cs index 2dc28ff17..69c762410 100644 --- a/Confuser.Core/ProtectionPhase.cs +++ b/Confuser.Core/ProtectionPhase.cs @@ -5,7 +5,6 @@ namespace Confuser.Core { /// Base class of protection phases. /// public abstract class ProtectionPhase { - /// /// Initializes a new instance of the class. /// @@ -46,6 +45,5 @@ public virtual bool ProcessAll { /// The working context. /// The parameters of protection. protected internal abstract void Execute(ConfuserContext context, ProtectionParameters parameters); - } } \ No newline at end of file diff --git a/Confuser.Core/ProtectionPipeline.cs b/Confuser.Core/ProtectionPipeline.cs index 90afd2134..406ed3ebc 100644 --- a/Confuser.Core/ProtectionPipeline.cs +++ b/Confuser.Core/ProtectionPipeline.cs @@ -9,7 +9,6 @@ namespace Confuser.Core { /// Various stages in . /// public enum PipelineStage { - /// /// Confuser engine inspects the loaded modules and makes necessary changes. /// This stage occurs only once per pipeline run. @@ -63,16 +62,14 @@ public enum PipelineStage { /// This stage occurs only once per pipeline run. /// SaveModules - } /// /// Protection processing pipeline. /// public class ProtectionPipeline { - - private readonly Dictionary> postStage; - private readonly Dictionary> preStage; + readonly Dictionary> postStage; + readonly Dictionary> preStage; /// /// Initializes a new instance of the class. @@ -150,7 +147,7 @@ internal void ExecuteStage(PipelineStage stage, Action func, Fu /// List of targets. /// The component phase. /// Filtered targets. - private static IList Filter(ConfuserContext context, IList targets, ProtectionPhase phase) { + static IList Filter(ConfuserContext context, IList targets, ProtectionPhase phase) { ProtectionTargets targetType = phase.Targets; IEnumerable filter = targets; @@ -179,6 +176,5 @@ private static IList Filter(ConfuserContext context, IList return parameters.ContainsKey(phase.Parent); }).ToList(); } - } } \ No newline at end of file diff --git a/Confuser.Core/ProtectionPreset.cs b/Confuser.Core/ProtectionPreset.cs index 142e9de53..9a686ba2c 100644 --- a/Confuser.Core/ProtectionPreset.cs +++ b/Confuser.Core/ProtectionPreset.cs @@ -5,7 +5,6 @@ namespace Confuser.Core { /// Various presets of protections. /// public enum ProtectionPreset { - /// The protection does not belong to any preset. None = 0, @@ -19,7 +18,6 @@ public enum ProtectionPreset { Aggressive = 3, /// The protection provides strongest security with possible incompatibility. - Maximum = 4, - + Maximum = 4 } } \ No newline at end of file diff --git a/Confuser.Core/ProtectionSettings.cs b/Confuser.Core/ProtectionSettings.cs index 84a6cdb74..0c4d74bab 100644 --- a/Confuser.Core/ProtectionSettings.cs +++ b/Confuser.Core/ProtectionSettings.cs @@ -6,7 +6,6 @@ namespace Confuser.Core { /// Protection settings for a certain component /// public class ProtectionSettings : Dictionary> { - /// /// Initializes a new instance of the class. /// @@ -29,6 +28,5 @@ public ProtectionSettings(ProtectionSettings settings) { public bool IsEmpty() { return Count == 0; } - } } \ No newline at end of file diff --git a/Confuser.Core/ProtectionTargets.cs b/Confuser.Core/ProtectionTargets.cs index b4a7650c5..7b7f3c762 100644 --- a/Confuser.Core/ProtectionTargets.cs +++ b/Confuser.Core/ProtectionTargets.cs @@ -6,7 +6,6 @@ namespace Confuser.Core { /// [Flags] public enum ProtectionTargets { - /// Type definitions. Types = 1, @@ -29,7 +28,6 @@ public enum ProtectionTargets { Modules = 32, /// All definitions (i.e. All member definitions and modules). - AllDefinitions = AllMembers | Modules, - + AllDefinitions = AllMembers | Modules } } \ No newline at end of file diff --git a/Confuser.Core/ServiceRegistry.cs b/Confuser.Core/ServiceRegistry.cs index 59c276e9f..f3be8a06d 100644 --- a/Confuser.Core/ServiceRegistry.cs +++ b/Confuser.Core/ServiceRegistry.cs @@ -6,9 +6,8 @@ namespace Confuser.Core { /// A registry of different services provided by protections /// public class ServiceRegistry : IServiceProvider { - - private readonly HashSet serviceIds = new HashSet(); - private readonly Dictionary services = new Dictionary(); + readonly HashSet serviceIds = new HashSet(); + readonly Dictionary services = new Dictionary(); /// object IServiceProvider.GetService(Type serviceType) { @@ -47,6 +46,5 @@ public void RegisterService(string serviceId, Type serviceType, object service) public bool Contains(string serviceId) { return serviceIds.Contains(serviceId); } - } } \ No newline at end of file diff --git a/Confuser.Core/Services/CompressionService.cs b/Confuser.Core/Services/CompressionService.cs index f3dcba40d..fa12f05f2 100644 --- a/Confuser.Core/Services/CompressionService.cs +++ b/Confuser.Core/Services/CompressionService.cs @@ -10,9 +10,8 @@ namespace Confuser.Core.Services { internal class CompressionService : ICompressionService { - - private static readonly object Decompressor = new object(); - private readonly ConfuserContext context; + static readonly object Decompressor = new object(); + readonly ConfuserContext context; /// /// Initializes a new instance of the class. @@ -110,10 +109,9 @@ public byte[] Compress(byte[] data, Action progressFunc = null) { return x.ToArray(); } - private class CompressionLogger : ICodeProgress { - - private readonly Action progressFunc; - private readonly int size; + class CompressionLogger : ICodeProgress { + readonly Action progressFunc; + readonly int size; public CompressionLogger(Action progressFunc, int size) { this.progressFunc = progressFunc; @@ -124,24 +122,21 @@ public void SetProgress(long inSize, long outSize) { double precentage = (double)inSize / size; progressFunc(precentage); } - } - } /// /// Provides methods to do compression and inject decompression algorithm. /// public interface ICompressionService { - /// /// Gets the runtime decompression method in the module, or null if it's not yet injected. /// /// The module which the decompression method resides in. /// The initializing method for compression helper definitions. /// - /// The requested decompression method with signature 'static Byte[] (Byte[])', - /// or null if it hasn't been injected yet. + /// The requested decompression method with signature 'static Byte[] (Byte[])', + /// or null if it hasn't been injected yet. /// MethodDef TryGetRuntimeDecompressor(ModuleDef module, Action init); @@ -160,6 +155,5 @@ public interface ICompressionService { /// The function that receive the progress of compression. /// The compressed data. byte[] Compress(byte[] data, Action progressFunc = null); - } } \ No newline at end of file diff --git a/Confuser.Core/Services/MarkerService.cs b/Confuser.Core/Services/MarkerService.cs index 10e569f8f..ef1cd58b2 100644 --- a/Confuser.Core/Services/MarkerService.cs +++ b/Confuser.Core/Services/MarkerService.cs @@ -3,9 +3,8 @@ namespace Confuser.Core.Services { internal class MarkerService : IMarkerService { - - private readonly ConfuserContext context; - private readonly Marker marker; + readonly ConfuserContext context; + readonly Marker marker; /// /// Initializes a new instance of the class. @@ -33,14 +32,12 @@ public void Mark(IDnlibDef member) { public bool IsMarked(IDnlibDef def) { return ProtectionParameters.GetParameters(context, def) != null; } - } /// /// Provides methods to access the obfuscation marker. /// public interface IMarkerService { - /// /// Marks the helper member. /// @@ -55,6 +52,5 @@ public interface IMarkerService { /// The definition. /// true if the specified definition is marked; otherwise, false. bool IsMarked(IDnlibDef def); - } } \ No newline at end of file diff --git a/Confuser.Core/Services/RandomService.cs b/Confuser.Core/Services/RandomService.cs index 9596f8b70..2c1b4834e 100644 --- a/Confuser.Core/Services/RandomService.cs +++ b/Confuser.Core/Services/RandomService.cs @@ -8,16 +8,15 @@ namespace Confuser.Core.Services { /// A seeded SHA256 PRNG. /// public class RandomGenerator { - /// /// The prime numbers used for generation /// - private static readonly byte[] primes = { 7, 11, 23, 37, 43, 59, 71 }; + static readonly byte[] primes = { 7, 11, 23, 37, 43, 59, 71 }; - private readonly SHA256Managed sha256 = new SHA256Managed(); - private int mixIndex; - private byte[] state; //32 bytes - private int stateFilled; + readonly SHA256Managed sha256 = new SHA256Managed(); + int mixIndex; + byte[] state; //32 bytes + int stateFilled; /// /// Initializes a new instance of the class. @@ -51,7 +50,7 @@ internal static byte[] Seed(string seed) { /// /// Refills the state buffer. /// - private void NextState() { + void NextState() { for (int i = 0; i < 32; i++) state[i] ^= primes[mixIndex = (mixIndex + 1) % primes.Length]; state = sha256.ComputeHash(state); @@ -188,15 +187,13 @@ public void Shuffle(IList list) { list[i] = tmp; } } - } /// /// Implementation of . /// internal class RandomService : IRandomService { - - private readonly byte[] seed; //32 bytes + readonly byte[] seed; //32 bytes /// /// Initializes a new instance of the class. @@ -216,14 +213,12 @@ public RandomGenerator GetRandomGenerator(string id) { newSeed[i] ^= idHash[i]; return new RandomGenerator(Utils.SHA256(newSeed)); } - } /// /// Provides methods to obtain a unique stable PRNG for any given ID. /// public interface IRandomService { - /// /// Gets a RNG with the specified identifier. /// @@ -231,6 +226,5 @@ public interface IRandomService { /// The requested RNG. /// is null. RandomGenerator GetRandomGenerator(string id); - } } \ No newline at end of file diff --git a/Confuser.Core/Services/RuntimeService.cs b/Confuser.Core/Services/RuntimeService.cs index 3619674ca..d5ec0d1fd 100644 --- a/Confuser.Core/Services/RuntimeService.cs +++ b/Confuser.Core/Services/RuntimeService.cs @@ -5,8 +5,7 @@ namespace Confuser.Core.Services { internal class RuntimeService : IRuntimeService { - - private ModuleDef rtModule; + ModuleDef rtModule; /// public TypeDef GetRuntimeType(string fullName) { @@ -20,20 +19,17 @@ public TypeDef GetRuntimeType(string fullName) { } return rtModule.Find(fullName, true); } - } /// /// Provides methods to obtain runtime library injection type. /// public interface IRuntimeService { - /// /// Gets the specified runtime type for injection. /// /// The full name of the runtime type. /// The requested runtime type. TypeDef GetRuntimeType(string fullName); - } } \ No newline at end of file diff --git a/Confuser.Core/Services/TraceService.cs b/Confuser.Core/Services/TraceService.cs index 94ef8e255..9c2e4e383 100644 --- a/Confuser.Core/Services/TraceService.cs +++ b/Confuser.Core/Services/TraceService.cs @@ -7,9 +7,8 @@ namespace Confuser.Core.Services { internal class TraceService : ITraceService { - - private readonly Dictionary cache = new Dictionary(); - private ConfuserContext context; + readonly Dictionary cache = new Dictionary(); + ConfuserContext context; /// /// Initializes a new instance of the class. @@ -26,14 +25,12 @@ public MethodTrace Trace(MethodDef method) { throw new ArgumentNullException("method"); return cache.GetValueOrDefaultLazy(method, m => cache[m] = new MethodTrace(m)).Trace(); } - } /// /// Provides methods to trace stack of method body. /// public interface ITraceService { - /// /// Trace the stack of the specified method. /// @@ -41,7 +38,6 @@ public interface ITraceService { /// has invalid body. /// is null. MethodTrace Trace(MethodDef method); - } @@ -49,10 +45,9 @@ public interface ITraceService { /// The trace result of a method. /// public class MethodTrace { - - private readonly MethodDef method; - private Dictionary> fromInstrs; - private Dictionary offset2index; + readonly MethodDef method; + Dictionary> fromInstrs; + Dictionary offset2index; /// /// Initializes a new instance of the class. @@ -310,6 +305,5 @@ public int[] TraceArguments(Instruction instr) { Array.Reverse(ret); return ret; } - } } \ No newline at end of file diff --git a/Confuser.Core/UnreachableException.cs b/Confuser.Core/UnreachableException.cs index a59e6f988..a42d0585f 100644 --- a/Confuser.Core/UnreachableException.cs +++ b/Confuser.Core/UnreachableException.cs @@ -5,12 +5,10 @@ namespace Confuser.Core { /// The exception that is thrown when supposedly unreachable code is executed. /// public class UnreachableException : SystemException { - /// /// Initializes a new instance of the class. /// public UnreachableException() : base("Unreachable code reached.") { } - } } \ No newline at end of file diff --git a/Confuser.Core/Utils.cs b/Confuser.Core/Utils.cs index 712f49f5e..104e7a29b 100644 --- a/Confuser.Core/Utils.cs +++ b/Confuser.Core/Utils.cs @@ -9,8 +9,7 @@ namespace Confuser.Core { /// Provides a set of utility methods /// public static class Utils { - - private static readonly char[] hexCharset = "0123456789abcdef".ToCharArray(); + static readonly char[] hexCharset = "0123456789abcdef".ToCharArray(); /// /// Gets the value associated with the specified key, or default value if the key does not exists. @@ -153,17 +152,18 @@ public static string EncodeString(byte[] buff, char[] charset) { } /// - /// Returns a new string in which all occurrences of a specified string in - /// are replaced with another specified string. + /// Returns a new string in which all occurrences of a specified string in + /// are replaced with another specified string. /// /// - /// A equivalent to but with all instances of - /// replaced with . + /// A equivalent to but with all instances of + /// + /// replaced with . /// /// A string to do the replace in. /// A string to be replaced. - /// A string to replace all occurrences of . - /// One of the values. + /// A string to replace all occurrences of . + /// One of the values. /// Adopted from http://stackoverflow.com/a/244933 public static string Replace(this string str, string oldValue, string newValue, StringComparison comparison) { StringBuilder sb = new StringBuilder(); @@ -230,6 +230,5 @@ public static IEnumerable WithProgress(this IEnumerable enumerable, ILo logger.Progress(i, list.Count); logger.EndProgress(); } - } } \ No newline at end of file diff --git a/Confuser.DynCipher/AST/ArrayIndexExpression.cs b/Confuser.DynCipher/AST/ArrayIndexExpression.cs index 5d43a27d5..f08453645 100644 --- a/Confuser.DynCipher/AST/ArrayIndexExpression.cs +++ b/Confuser.DynCipher/AST/ArrayIndexExpression.cs @@ -2,13 +2,11 @@ namespace Confuser.DynCipher.AST { public class ArrayIndexExpression : Expression { - public Expression Array { get; set; } public int Index { get; set; } public override string ToString() { return string.Format("{0}[{1}]", Array, Index); } - } } \ No newline at end of file diff --git a/Confuser.DynCipher/AST/AssignmentStatement.cs b/Confuser.DynCipher/AST/AssignmentStatement.cs index 5020533cc..b02d5c3c2 100644 --- a/Confuser.DynCipher/AST/AssignmentStatement.cs +++ b/Confuser.DynCipher/AST/AssignmentStatement.cs @@ -2,13 +2,11 @@ namespace Confuser.DynCipher.AST { public class AssignmentStatement : Statement { - public Expression Target { get; set; } public Expression Value { get; set; } public override string ToString() { return string.Format("{0} = {1};", Target, Value); } - } } \ No newline at end of file diff --git a/Confuser.DynCipher/AST/BinOpExpression.cs b/Confuser.DynCipher/AST/BinOpExpression.cs index 44e6a783e..10191d5a3 100644 --- a/Confuser.DynCipher/AST/BinOpExpression.cs +++ b/Confuser.DynCipher/AST/BinOpExpression.cs @@ -2,7 +2,6 @@ namespace Confuser.DynCipher.AST { public enum BinOps { - Add, Sub, Div, @@ -11,12 +10,10 @@ public enum BinOps { And, Xor, Lsh, - Rsh, - + Rsh } public class BinOpExpression : Expression { - public Expression Left { get; set; } public Expression Right { get; set; } public BinOps Operation { get; set; } @@ -56,6 +53,5 @@ public override string ToString() { } return string.Format("({0} {1} {2})", Left, op, Right); } - } } \ No newline at end of file diff --git a/Confuser.DynCipher/AST/Expression.cs b/Confuser.DynCipher/AST/Expression.cs index 0cec3f25c..144e36799 100644 --- a/Confuser.DynCipher/AST/Expression.cs +++ b/Confuser.DynCipher/AST/Expression.cs @@ -2,7 +2,6 @@ namespace Confuser.DynCipher.AST { public abstract class Expression { - public object Tag { get; set; } public abstract override string ToString(); @@ -83,6 +82,5 @@ public abstract class Expression { Operation = UnaryOps.Negate }; } - } } \ No newline at end of file diff --git a/Confuser.DynCipher/AST/LiteralExpression.cs b/Confuser.DynCipher/AST/LiteralExpression.cs index 7c1cb5377..fa6257cde 100644 --- a/Confuser.DynCipher/AST/LiteralExpression.cs +++ b/Confuser.DynCipher/AST/LiteralExpression.cs @@ -2,7 +2,6 @@ namespace Confuser.DynCipher.AST { public class LiteralExpression : Expression { - public uint Value { get; set; } public static implicit operator LiteralExpression(uint val) { @@ -12,6 +11,5 @@ public static implicit operator LiteralExpression(uint val) { public override string ToString() { return Value.ToString("x8") + "h"; } - } } \ No newline at end of file diff --git a/Confuser.DynCipher/AST/LoopStatement.cs b/Confuser.DynCipher/AST/LoopStatement.cs index d81aba833..b3fee191c 100644 --- a/Confuser.DynCipher/AST/LoopStatement.cs +++ b/Confuser.DynCipher/AST/LoopStatement.cs @@ -4,7 +4,6 @@ namespace Confuser.DynCipher.AST { // i.e. for loop public class LoopStatement : StatementBlock { - public int Begin { get; set; } public int Limit { get; set; } @@ -15,6 +14,5 @@ public override string ToString() { ret.Append(base.ToString()); return ret.ToString(); } - } } \ No newline at end of file diff --git a/Confuser.DynCipher/AST/Statement.cs b/Confuser.DynCipher/AST/Statement.cs index 1fb0194d9..24f5c5366 100644 --- a/Confuser.DynCipher/AST/Statement.cs +++ b/Confuser.DynCipher/AST/Statement.cs @@ -2,9 +2,7 @@ namespace Confuser.DynCipher.AST { public abstract class Statement { - public object Tag { get; set; } public abstract override string ToString(); - } } \ No newline at end of file diff --git a/Confuser.DynCipher/AST/StatementBlock.cs b/Confuser.DynCipher/AST/StatementBlock.cs index d7fa1af08..b209fc317 100644 --- a/Confuser.DynCipher/AST/StatementBlock.cs +++ b/Confuser.DynCipher/AST/StatementBlock.cs @@ -4,7 +4,6 @@ namespace Confuser.DynCipher.AST { public class StatementBlock : Statement { - public StatementBlock() { Statements = new List(); } @@ -19,6 +18,5 @@ public override string ToString() { sb.AppendLine("}"); return sb.ToString(); } - } } \ No newline at end of file diff --git a/Confuser.DynCipher/AST/UnaryOpExpression.cs b/Confuser.DynCipher/AST/UnaryOpExpression.cs index 2c7d1cc0e..627625a2e 100644 --- a/Confuser.DynCipher/AST/UnaryOpExpression.cs +++ b/Confuser.DynCipher/AST/UnaryOpExpression.cs @@ -2,14 +2,11 @@ namespace Confuser.DynCipher.AST { public enum UnaryOps { - Not, Negate - } public class UnaryOpExpression : Expression { - public Expression Value { get; set; } public UnaryOps Operation { get; set; } @@ -27,6 +24,5 @@ public override string ToString() { } return op + Value; } - } } \ No newline at end of file diff --git a/Confuser.DynCipher/AST/Variable.cs b/Confuser.DynCipher/AST/Variable.cs index a8a902249..856f9b081 100644 --- a/Confuser.DynCipher/AST/Variable.cs +++ b/Confuser.DynCipher/AST/Variable.cs @@ -2,7 +2,6 @@ namespace Confuser.DynCipher.AST { public class Variable { - public Variable(string name) { Name = name; } @@ -13,6 +12,5 @@ public Variable(string name) { public override string ToString() { return Name; } - } } \ No newline at end of file diff --git a/Confuser.DynCipher/AST/VariableExpression.cs b/Confuser.DynCipher/AST/VariableExpression.cs index 7efe5d578..1e6836de9 100644 --- a/Confuser.DynCipher/AST/VariableExpression.cs +++ b/Confuser.DynCipher/AST/VariableExpression.cs @@ -2,12 +2,10 @@ namespace Confuser.DynCipher.AST { public class VariableExpression : Expression { - public Variable Variable { get; set; } public override string ToString() { return Variable.Name; } - } } \ No newline at end of file diff --git a/Confuser.DynCipher/DynCipherComponent.cs b/Confuser.DynCipher/DynCipherComponent.cs index 951d21df9..497f4d316 100644 --- a/Confuser.DynCipher/DynCipherComponent.cs +++ b/Confuser.DynCipher/DynCipherComponent.cs @@ -3,7 +3,6 @@ namespace Confuser.DynCipher { internal class DynCipherComponent : ConfuserComponent { - public const string _ServiceId = "Confuser.DynCipher"; public override string Name { @@ -29,6 +28,5 @@ protected override void Initialize(ConfuserContext context) { protected override void PopulatePipeline(ProtectionPipeline pipeline) { // } - } } \ No newline at end of file diff --git a/Confuser.DynCipher/DynCipherService.cs b/Confuser.DynCipher/DynCipherService.cs index 227abbb0d..bba7c4cc7 100644 --- a/Confuser.DynCipher/DynCipherService.cs +++ b/Confuser.DynCipher/DynCipherService.cs @@ -5,14 +5,11 @@ namespace Confuser.DynCipher { public interface IDynCipherService { - void GenerateCipherPair(RandomGenerator random, out StatementBlock encrypt, out StatementBlock decrypt); void GenerateExpressionPair(RandomGenerator random, Expression var, Expression result, int depth, out Expression expression, out Expression inverse); - } internal class DynCipherService : IDynCipherService { - public void GenerateCipherPair(RandomGenerator random, out StatementBlock encrypt, out StatementBlock decrypt) { CipherGenerator.GeneratePair(random, out encrypt, out decrypt); } @@ -20,6 +17,5 @@ public void GenerateCipherPair(RandomGenerator random, out StatementBlock encryp public void GenerateExpressionPair(RandomGenerator random, Expression var, Expression result, int depth, out Expression expression, out Expression inverse) { ExpressionGenerator.GeneratePair(random, var, result, depth, out expression, out inverse); } - } } \ No newline at end of file diff --git a/Confuser.DynCipher/Elements/AddKey.cs b/Confuser.DynCipher/Elements/AddKey.cs index 864ceeec8..782d3a2cb 100644 --- a/Confuser.DynCipher/Elements/AddKey.cs +++ b/Confuser.DynCipher/Elements/AddKey.cs @@ -5,7 +5,6 @@ namespace Confuser.DynCipher.Elements { internal class AddKey : CryptoElement { - public AddKey(int index) : base(0) { Index = index; @@ -15,7 +14,7 @@ public AddKey(int index) public override void Initialize(RandomGenerator random) { } - private void EmitCore(CipherGenContext context) { + void EmitCore(CipherGenContext context) { Expression val = context.GetDataExpression(Index); context.Emit(new AssignmentStatement { @@ -31,6 +30,5 @@ public override void Emit(CipherGenContext context) { public override void EmitInverse(CipherGenContext context) { EmitCore(context); } - } } \ No newline at end of file diff --git a/Confuser.DynCipher/Elements/BinOp.cs b/Confuser.DynCipher/Elements/BinOp.cs index 77603b178..24fe75dd3 100644 --- a/Confuser.DynCipher/Elements/BinOp.cs +++ b/Confuser.DynCipher/Elements/BinOp.cs @@ -5,15 +5,12 @@ namespace Confuser.DynCipher.Elements { internal enum CryptoBinOps { - Add, Xor, Xnor - } internal class BinOp : CryptoElement { - public BinOp() : base(2) { } @@ -72,6 +69,5 @@ public override void EmitInverse(CipherGenContext context) { break; } } - } } \ No newline at end of file diff --git a/Confuser.DynCipher/Elements/CryptoElement.cs b/Confuser.DynCipher/Elements/CryptoElement.cs index 7878cceb0..6f68c89da 100644 --- a/Confuser.DynCipher/Elements/CryptoElement.cs +++ b/Confuser.DynCipher/Elements/CryptoElement.cs @@ -4,7 +4,6 @@ namespace Confuser.DynCipher.Elements { internal abstract class CryptoElement { - public CryptoElement(int count) { DataCount = count; DataIndexes = new int[count]; @@ -16,6 +15,5 @@ public CryptoElement(int count) { public abstract void Initialize(RandomGenerator random); public abstract void Emit(CipherGenContext context); public abstract void EmitInverse(CipherGenContext context); - } } \ No newline at end of file diff --git a/Confuser.DynCipher/Elements/Matrix.cs b/Confuser.DynCipher/Elements/Matrix.cs index 932c05136..ac2268a83 100644 --- a/Confuser.DynCipher/Elements/Matrix.cs +++ b/Confuser.DynCipher/Elements/Matrix.cs @@ -5,14 +5,13 @@ namespace Confuser.DynCipher.Elements { internal class Matrix : CryptoElement { - public Matrix() : base(4) { } public uint[,] Key { get; private set; } public uint[,] InverseKey { get; private set; } - private static uint[,] GenerateUnimodularMatrix(RandomGenerator random) { + static uint[,] GenerateUnimodularMatrix(RandomGenerator random) { Func next = () => (uint)random.NextInt32(4); uint[,] l = { @@ -31,7 +30,7 @@ public Matrix() return mul(l, u); } - private static uint[,] mul(uint[,] a, uint[,] b) { + static uint[,] mul(uint[,] a, uint[,] b) { int n = a.GetLength(0), p = b.GetLength(1); int m = a.GetLength(1); if (b.GetLength(0) != m) return null; @@ -46,7 +45,7 @@ public Matrix() return ret; } - private static uint cofactor4(uint[,] mat, int i, int j) { + static uint cofactor4(uint[,] mat, int i, int j) { var sub = new uint[3, 3]; for (int ci = 0, si = 0; ci < 4; ci++, si++) { if (ci == i) { @@ -66,7 +65,7 @@ private static uint cofactor4(uint[,] mat, int i, int j) { return (uint)(-ret); } - private static uint det3(uint[,] mat) { + static uint det3(uint[,] mat) { return mat[0, 0] * mat[1, 1] * mat[2, 2] + mat[0, 1] * mat[1, 2] * mat[2, 0] + mat[0, 2] * mat[1, 0] * mat[2, 1] - @@ -75,7 +74,7 @@ private static uint det3(uint[,] mat) { mat[0, 0] * mat[1, 2] * mat[2, 1]; } - private static uint[,] transpose4(uint[,] mat) { + static uint[,] transpose4(uint[,] mat) { var ret = new uint[4, 4]; for (int i = 0; i < 4; i++) for (int j = 0; j < 4; j++) @@ -93,7 +92,7 @@ public override void Initialize(RandomGenerator random) { Key = transpose4(cof); } - private void EmitCore(CipherGenContext context, uint[,] k) { + void EmitCore(CipherGenContext context, uint[,] k) { Expression a = context.GetDataExpression(DataIndexes[0]); Expression b = context.GetDataExpression(DataIndexes[1]); Expression c = context.GetDataExpression(DataIndexes[2]); @@ -133,6 +132,5 @@ public override void Emit(CipherGenContext context) { public override void EmitInverse(CipherGenContext context) { EmitCore(context, InverseKey); } - } } \ No newline at end of file diff --git a/Confuser.DynCipher/Elements/NumOp.cs b/Confuser.DynCipher/Elements/NumOp.cs index 400b1c11d..edf3d26d6 100644 --- a/Confuser.DynCipher/Elements/NumOp.cs +++ b/Confuser.DynCipher/Elements/NumOp.cs @@ -5,16 +5,13 @@ namespace Confuser.DynCipher.Elements { internal enum CryptoNumOps { - Add, Mul, Xor, Xnor - } internal class NumOp : CryptoElement { - public NumOp() : base(1) { } @@ -99,6 +96,5 @@ public override void EmitInverse(CipherGenContext context) { break; } } - } } \ No newline at end of file diff --git a/Confuser.DynCipher/Elements/RotateBit.cs b/Confuser.DynCipher/Elements/RotateBit.cs index 5e3c13c18..c71dbb34f 100644 --- a/Confuser.DynCipher/Elements/RotateBit.cs +++ b/Confuser.DynCipher/Elements/RotateBit.cs @@ -5,7 +5,6 @@ namespace Confuser.DynCipher.Elements { internal class RotateBit : CryptoElement { - public RotateBit() : base(1) { } @@ -62,6 +61,5 @@ public override void EmitInverse(CipherGenContext context) { }); } } - } } \ No newline at end of file diff --git a/Confuser.DynCipher/Elements/Swap.cs b/Confuser.DynCipher/Elements/Swap.cs index 764d685ce..d65000c18 100644 --- a/Confuser.DynCipher/Elements/Swap.cs +++ b/Confuser.DynCipher/Elements/Swap.cs @@ -5,7 +5,6 @@ namespace Confuser.DynCipher.Elements { internal class Swap : CryptoElement { - public Swap() : base(2) { } @@ -20,7 +19,7 @@ public override void Initialize(RandomGenerator random) { Key = random.NextUInt32() | 1; } - private void EmitCore(CipherGenContext context) { + void EmitCore(CipherGenContext context) { Expression a = context.GetDataExpression(DataIndexes[0]); Expression b = context.GetDataExpression(DataIndexes[1]); VariableExpression tmp; @@ -72,6 +71,5 @@ public override void Emit(CipherGenContext context) { public override void EmitInverse(CipherGenContext context) { EmitCore(context); } - } } \ No newline at end of file diff --git a/Confuser.DynCipher/Generation/CILCodeGen.cs b/Confuser.DynCipher/Generation/CILCodeGen.cs index a439d8354..fbd9a6ad3 100644 --- a/Confuser.DynCipher/Generation/CILCodeGen.cs +++ b/Confuser.DynCipher/Generation/CILCodeGen.cs @@ -6,8 +6,7 @@ namespace Confuser.DynCipher.Generation { public class CILCodeGen { - - private readonly Dictionary localMap = new Dictionary(); + readonly Dictionary localMap = new Dictionary(); public CILCodeGen(MethodDef method, IList instrs) { Method = method; @@ -55,7 +54,7 @@ public void GenerateCIL(Statement statement) { EmitStatement(statement); } - private void EmitLoad(Expression exp) { + void EmitLoad(Expression exp) { if (exp is ArrayIndexExpression) { var arrIndex = (ArrayIndexExpression)exp; EmitLoad(arrIndex.Array); @@ -128,7 +127,7 @@ private void EmitLoad(Expression exp) { throw new NotSupportedException(); } - private void EmitStore(Expression exp, Expression value) { + void EmitStore(Expression exp, Expression value) { if (exp is ArrayIndexExpression) { var arrIndex = (ArrayIndexExpression)exp; EmitLoad(arrIndex.Array); @@ -145,7 +144,7 @@ private void EmitStore(Expression exp, Expression value) { throw new NotSupportedException(); } - private void EmitStatement(Statement statement) { + void EmitStatement(Statement statement) { if (statement is AssignmentStatement) { var assignment = (AssignmentStatement)statement; EmitStore(assignment.Target, assignment.Value); @@ -190,6 +189,5 @@ private void EmitStatement(Statement statement) { else throw new NotSupportedException(); } - } } \ No newline at end of file diff --git a/Confuser.DynCipher/Generation/CipherGenContext.cs b/Confuser.DynCipher/Generation/CipherGenContext.cs index 37f85a9a7..59221655c 100644 --- a/Confuser.DynCipher/Generation/CipherGenContext.cs +++ b/Confuser.DynCipher/Generation/CipherGenContext.cs @@ -5,12 +5,11 @@ namespace Confuser.DynCipher.Generation { internal class CipherGenContext { - - private readonly Variable[] dataVars; - private readonly Variable keyVar = new Variable("{KEY}"); - private readonly RandomGenerator random; - private readonly List tempVars = new List(); - private int tempVarCounter; + readonly Variable[] dataVars; + readonly Variable keyVar = new Variable("{KEY}"); + readonly RandomGenerator random; + readonly List tempVars = new List(); + int tempVarCounter; public CipherGenContext(RandomGenerator random, int dataVarCount) { this.random = random; @@ -50,10 +49,9 @@ public IDisposable AcquireTempVar(out VariableExpression exp) { return new TempVarHolder(this, var); } - private struct TempVarHolder : IDisposable { - - private readonly CipherGenContext parent; - private readonly Variable tempVar; + struct TempVarHolder : IDisposable { + readonly CipherGenContext parent; + readonly Variable tempVar; public TempVarHolder(CipherGenContext p, Variable v) { parent = p; @@ -63,8 +61,6 @@ public TempVarHolder(CipherGenContext p, Variable v) { public void Dispose() { parent.tempVars.Add(tempVar); } - } - } } \ No newline at end of file diff --git a/Confuser.DynCipher/Generation/CipherGenerator.cs b/Confuser.DynCipher/Generation/CipherGenerator.cs index aea47169a..29fb741f3 100644 --- a/Confuser.DynCipher/Generation/CipherGenerator.cs +++ b/Confuser.DynCipher/Generation/CipherGenerator.cs @@ -8,17 +8,16 @@ namespace Confuser.DynCipher.Generation { internal class CipherGenerator { + const int MAT_RATIO = 4; + const int NUMOP_RATIO = 10; + const int SWAP_RATIO = 6; + const int BINOP_RATIO = 9; + const int ROTATE_RATIO = 6; + const int RATIO_SUM = MAT_RATIO + NUMOP_RATIO + SWAP_RATIO + BINOP_RATIO + ROTATE_RATIO; + const double VARIANCE = 0.2; - private const int MAT_RATIO = 4; - private const int NUMOP_RATIO = 10; - private const int SWAP_RATIO = 6; - private const int BINOP_RATIO = 9; - private const int ROTATE_RATIO = 6; - private const int RATIO_SUM = MAT_RATIO + NUMOP_RATIO + SWAP_RATIO + BINOP_RATIO + ROTATE_RATIO; - private const double VARIANCE = 0.2; - - private static void Shuffle(RandomGenerator random, IList arr) { + static void Shuffle(RandomGenerator random, IList arr) { for (int i = 1; i < arr.Count; i++) { int j = random.NextInt32(i + 1); T tmp = arr[i]; @@ -27,7 +26,7 @@ private static void Shuffle(RandomGenerator random, IList arr) { } } - private static void PostProcessStatements(StatementBlock block, RandomGenerator random) { + static void PostProcessStatements(StatementBlock block, RandomGenerator random) { MulToShiftTransform.Run(block); NormalizeBinOpTransform.Run(block); ExpansionTransform.Run(block); @@ -87,6 +86,5 @@ public static void GeneratePair(RandomGenerator random, out StatementBlock encry decrypt = decryptContext.Block; PostProcessStatements(decrypt, random); } - } } \ No newline at end of file diff --git a/Confuser.DynCipher/Generation/DMCodeGen.cs b/Confuser.DynCipher/Generation/DMCodeGen.cs index 4bab0ec8b..8d1918cff 100644 --- a/Confuser.DynCipher/Generation/DMCodeGen.cs +++ b/Confuser.DynCipher/Generation/DMCodeGen.cs @@ -2,17 +2,15 @@ using System.Collections.Generic; using System.Linq; using System.Reflection.Emit; -using Confuser.Core; using Confuser.DynCipher.AST; namespace Confuser.DynCipher.Generation { public class DMCodeGen { + readonly DynamicMethod dm; + readonly ILGenerator ilGen; - private readonly DynamicMethod dm; - private readonly ILGenerator ilGen; - - private readonly Dictionary localMap = new Dictionary(); - private readonly Dictionary paramMap; + readonly Dictionary localMap = new Dictionary(); + readonly Dictionary paramMap; public DMCodeGen(Type returnType, Tuple[] parameters) { dm = new DynamicMethod("", returnType, parameters.Select(param => param.Item2).ToArray(), true); @@ -61,7 +59,7 @@ public DMCodeGen GenerateCIL(Statement statement) { return this; } - private void EmitLoad(Expression exp) { + void EmitLoad(Expression exp) { if (exp is ArrayIndexExpression) { var arrIndex = (ArrayIndexExpression)exp; EmitLoad(arrIndex.Array); @@ -134,7 +132,7 @@ private void EmitLoad(Expression exp) { throw new NotSupportedException(); } - private void EmitStore(Expression exp, Expression value) { + void EmitStore(Expression exp, Expression value) { if (exp is ArrayIndexExpression) { var arrIndex = (ArrayIndexExpression)exp; EmitLoad(arrIndex.Array); @@ -151,7 +149,7 @@ private void EmitStore(Expression exp, Expression value) { throw new NotSupportedException(); } - private void EmitStatement(Statement statement) { + void EmitStatement(Statement statement) { if (statement is AssignmentStatement) { var assignment = (AssignmentStatement)statement; EmitStore(assignment.Target, assignment.Value); @@ -197,6 +195,5 @@ private void EmitStatement(Statement statement) { else throw new NotSupportedException(); } - } } \ No newline at end of file diff --git a/Confuser.DynCipher/Generation/ExpressionGenerator.cs b/Confuser.DynCipher/Generation/ExpressionGenerator.cs index 5d0b581a4..4a01dac81 100644 --- a/Confuser.DynCipher/Generation/ExpressionGenerator.cs +++ b/Confuser.DynCipher/Generation/ExpressionGenerator.cs @@ -7,8 +7,7 @@ namespace Confuser.DynCipher.Generation { internal class ExpressionGenerator { - - private static Expression GenerateExpression(RandomGenerator random, Expression current, int currentDepth, int targetDepth) { + static Expression GenerateExpression(RandomGenerator random, Expression current, int currentDepth, int targetDepth) { if (currentDepth == targetDepth || (currentDepth > targetDepth / 3 && random.NextInt32(100) > 85)) return current; @@ -37,7 +36,7 @@ private static Expression GenerateExpression(RandomGenerator random, Expression throw new UnreachableException(); } - private static void SwapOperands(RandomGenerator random, Expression exp) { + static void SwapOperands(RandomGenerator random, Expression exp) { if (exp is BinOpExpression) { var binExp = (BinOpExpression)exp; if (random.NextBoolean()) { @@ -56,7 +55,7 @@ private static void SwapOperands(RandomGenerator random, Expression exp) { throw new UnreachableException(); } - private static bool HasVariable(Expression exp, Dictionary hasVar) { + static bool HasVariable(Expression exp, Dictionary hasVar) { bool ret; if (!hasVar.TryGetValue(exp, out ret)) { if (exp is VariableExpression) @@ -77,7 +76,7 @@ private static bool HasVariable(Expression exp, Dictionary has return ret; } - private static Expression GenerateInverse(Expression exp, Expression var, Dictionary hasVar) { + static Expression GenerateInverse(Expression exp, Expression var, Dictionary hasVar) { Expression result = var; while (!(exp is VariableExpression)) { Debug.Assert(hasVar[exp]); @@ -153,16 +152,13 @@ public static void GeneratePair(RandomGenerator random, Expression var, Expressi inverse = GenerateInverse(expression, result, hasVar); } - private enum ExpressionOps { - + enum ExpressionOps { Add, Sub, Mul, Xor, Not, - Neg, - + Neg } - } } \ No newline at end of file diff --git a/Confuser.DynCipher/Generation/x86CodeGen.cs b/Confuser.DynCipher/Generation/x86CodeGen.cs index de5b50eef..363853acd 100644 --- a/Confuser.DynCipher/Generation/x86CodeGen.cs +++ b/Confuser.DynCipher/Generation/x86CodeGen.cs @@ -7,9 +7,8 @@ namespace Confuser.DynCipher.Generation { public class x86CodeGen { - - private List instrs; - private bool[] usedRegs; + List instrs; + bool[] usedRegs; public IList Instructions { get { return instrs; } @@ -36,7 +35,7 @@ public IList Instructions { } } - private x86Register GetFreeRegister() { + x86Register GetFreeRegister() { for (int i = 0; i < 8; i++) if (!usedRegs[i]) return (x86Register)i; @@ -44,17 +43,17 @@ private x86Register GetFreeRegister() { throw new Exception("Register overflowed."); } - private void TakeRegister(x86Register reg) { + void TakeRegister(x86Register reg) { usedRegs[(int)reg] = true; if ((int)reg > MaxUsedRegister) MaxUsedRegister = (int)reg; } - private void ReleaseRegister(x86Register reg) { + void ReleaseRegister(x86Register reg) { usedRegs[(int)reg] = false; } - private x86Register Normalize(x86Instruction instr) { + x86Register Normalize(x86Instruction instr) { if (instr.Operands.Length == 2 && instr.Operands[0] is x86ImmediateOperand && instr.Operands[1] is x86ImmediateOperand) { @@ -135,7 +134,7 @@ instr.Operands[0] is x86ImmediateOperand && return ((x86RegisterOperand)instr.Operands[0]).Register; } - private Ix86Operand Emit(Expression exp, Func> loadArg) { + Ix86Operand Emit(Expression exp, Func> loadArg) { if (exp is BinOpExpression) { var binOp = (BinOpExpression)exp; x86Register reg; @@ -198,11 +197,9 @@ private Ix86Operand Emit(Expression exp, Func instr.ToString()).ToArray()); } - } public enum x86OpCode { - MOV, ADD, SUB, @@ -212,11 +209,9 @@ public enum x86OpCode { NOT, XOR, POP - } public enum x86Register { - EAX, ECX, EDX, @@ -225,15 +220,11 @@ public enum x86Register { EBP, ESI, EDI - } - public interface Ix86Operand { - - } + public interface Ix86Operand { } public class x86RegisterOperand : Ix86Operand { - public x86RegisterOperand(x86Register reg) { Register = reg; } @@ -243,11 +234,9 @@ public x86RegisterOperand(x86Register reg) { public override string ToString() { return Register.ToString(); } - } public class x86ImmediateOperand : Ix86Operand { - public x86ImmediateOperand(int imm) { Immediate = imm; } @@ -257,11 +246,9 @@ public x86ImmediateOperand(int imm) { public override string ToString() { return Immediate.ToString("X") + "h"; } - } public class x86Instruction { - public x86OpCode OpCode { get; set; } public Ix86Operand[] Operands { get; set; } @@ -438,6 +425,5 @@ public override string ToString() { } return ret.ToString(); } - } } \ No newline at end of file diff --git a/Confuser.DynCipher/Transforms/ConvertVariables.cs b/Confuser.DynCipher/Transforms/ConvertVariables.cs index 7057785b2..3e7252611 100644 --- a/Confuser.DynCipher/Transforms/ConvertVariables.cs +++ b/Confuser.DynCipher/Transforms/ConvertVariables.cs @@ -3,8 +3,7 @@ namespace Confuser.DynCipher.Transforms { internal class ConvertVariables { - - private static Expression ReplaceVar(Expression exp, Variable buff) { + static Expression ReplaceVar(Expression exp, Variable buff) { if (exp is VariableExpression) { if (((VariableExpression)exp).Variable.Name[0] != 'v') return exp; return new ArrayIndexExpression { @@ -25,7 +24,7 @@ private static Expression ReplaceVar(Expression exp, Variable buff) { return exp; } - private static Statement ReplaceVar(Statement st, Variable buff) { + static Statement ReplaceVar(Statement st, Variable buff) { if (st is AssignmentStatement) { ((AssignmentStatement)st).Value = ReplaceVar(((AssignmentStatement)st).Value, buff); ((AssignmentStatement)st).Target = ReplaceVar(((AssignmentStatement)st).Target, buff); @@ -38,6 +37,5 @@ public static void Run(StatementBlock block) { for (int i = 0; i < block.Statements.Count; i++) block.Statements[i] = ReplaceVar(block.Statements[i], mainBuff); } - } } \ No newline at end of file diff --git a/Confuser.DynCipher/Transforms/ExpansionTransform.cs b/Confuser.DynCipher/Transforms/ExpansionTransform.cs index d37256ace..f295c2b4b 100644 --- a/Confuser.DynCipher/Transforms/ExpansionTransform.cs +++ b/Confuser.DynCipher/Transforms/ExpansionTransform.cs @@ -4,8 +4,7 @@ namespace Confuser.DynCipher.Transforms { internal class ExpansionTransform { - - private static bool ProcessStatement(Statement st, StatementBlock block) { + static bool ProcessStatement(Statement st, StatementBlock block) { if (st is AssignmentStatement) { var assign = (AssignmentStatement)st; if (assign.Value is BinOpExpression) { @@ -42,6 +41,5 @@ public static void Run(StatementBlock block) { workDone |= ProcessStatement(st, block); } while (workDone); } - } } \ No newline at end of file diff --git a/Confuser.DynCipher/Transforms/MulToShiftTransform.cs b/Confuser.DynCipher/Transforms/MulToShiftTransform.cs index e7982f640..577000a4d 100644 --- a/Confuser.DynCipher/Transforms/MulToShiftTransform.cs +++ b/Confuser.DynCipher/Transforms/MulToShiftTransform.cs @@ -5,14 +5,13 @@ namespace Confuser.DynCipher.Transforms { internal class MulToShiftTransform { - - private static uint NumberOfSetBits(uint i) { + static uint NumberOfSetBits(uint i) { i = i - ((i >> 1) & 0x55555555); i = (i & 0x33333333) + ((i >> 2) & 0x33333333); return (((i + (i >> 4)) & 0x0F0F0F0F) * 0x01010101) >> 24; } - private static Expression ProcessExpression(Expression exp) { + static Expression ProcessExpression(Expression exp) { if (exp is BinOpExpression) { var binOp = (BinOpExpression)exp; if (binOp.Operation == BinOps.Mul && binOp.Right is LiteralExpression) { @@ -55,7 +54,7 @@ private static Expression ProcessExpression(Expression exp) { return exp; } - private static void ProcessStatement(Statement st) { + static void ProcessStatement(Statement st) { if (st is AssignmentStatement) { var assign = (AssignmentStatement)st; assign.Target = ProcessExpression(assign.Target); @@ -67,6 +66,5 @@ public static void Run(StatementBlock block) { foreach (Statement st in block.Statements) ProcessStatement(st); } - } } \ No newline at end of file diff --git a/Confuser.DynCipher/Transforms/NormalizeBinOpTransform.cs b/Confuser.DynCipher/Transforms/NormalizeBinOpTransform.cs index 365774050..d565a2e0d 100644 --- a/Confuser.DynCipher/Transforms/NormalizeBinOpTransform.cs +++ b/Confuser.DynCipher/Transforms/NormalizeBinOpTransform.cs @@ -3,8 +3,7 @@ namespace Confuser.DynCipher.Transforms { internal class NormalizeBinOpTransform { - - private static Expression ProcessExpression(Expression exp) { + static Expression ProcessExpression(Expression exp) { if (exp is BinOpExpression) { var binOp = (BinOpExpression)exp; var binOpRight = binOp.Right as BinOpExpression; @@ -37,7 +36,7 @@ private static Expression ProcessExpression(Expression exp) { return exp; } - private static void ProcessStatement(Statement st) { + static void ProcessStatement(Statement st) { if (st is AssignmentStatement) { var assign = (AssignmentStatement)st; assign.Target = ProcessExpression(assign.Target); @@ -49,6 +48,5 @@ public static void Run(StatementBlock block) { foreach (Statement st in block.Statements) ProcessStatement(st); } - } } \ No newline at end of file diff --git a/Confuser.DynCipher/Transforms/ShuffleTransform.cs b/Confuser.DynCipher/Transforms/ShuffleTransform.cs index 5db05bfc8..bd64eef12 100644 --- a/Confuser.DynCipher/Transforms/ShuffleTransform.cs +++ b/Confuser.DynCipher/Transforms/ShuffleTransform.cs @@ -6,10 +6,9 @@ namespace Confuser.DynCipher.Transforms { internal class ShuffleTransform { + const int ITERATION = 20; - private const int ITERATION = 20; - - private static IEnumerable GetVariableUsage(Expression exp) { + static IEnumerable GetVariableUsage(Expression exp) { if (exp is VariableExpression) yield return ((VariableExpression)exp).Variable; else if (exp is ArrayIndexExpression) { @@ -27,19 +26,19 @@ private static IEnumerable GetVariableUsage(Expression exp) { } } - private static IEnumerable GetVariableUsage(Statement st) { + static IEnumerable GetVariableUsage(Statement st) { if (st is AssignmentStatement) { foreach (Variable i in GetVariableUsage(((AssignmentStatement)st).Value)) yield return i; } } - private static IEnumerable GetVariableDefinition(Expression exp) { + static IEnumerable GetVariableDefinition(Expression exp) { if (exp is VariableExpression) yield return ((VariableExpression)exp).Variable; } - private static IEnumerable GetVariableDefinition(Statement st) { + static IEnumerable GetVariableDefinition(Statement st) { if (st is AssignmentStatement) { foreach (Variable i in GetVariableDefinition(((AssignmentStatement)st).Target)) yield return i; @@ -49,7 +48,7 @@ private static IEnumerable GetVariableDefinition(Statement st) { // Cannot go before the statements that use the variable defined at the statement // Cannot go further than the statements that override the variable used at the statement - private static int SearchUpwardKill(TransformContext context, Statement st, StatementBlock block, int startIndex) { + static int SearchUpwardKill(TransformContext context, Statement st, StatementBlock block, int startIndex) { Variable[] usage = context.Usages[st]; Variable[] definition = context.Definitions[st]; for (int i = startIndex - 1; i >= 0; i--) { @@ -60,7 +59,7 @@ private static int SearchUpwardKill(TransformContext context, Statement st, Stat return 0; } - private static int SearchDownwardKill(TransformContext context, Statement st, StatementBlock block, int startIndex) { + static int SearchDownwardKill(TransformContext context, Statement st, StatementBlock block, int startIndex) { Variable[] usage = context.Usages[st]; Variable[] definition = context.Definitions[st]; for (int i = startIndex + 1; i < block.Statements.Count; i++) { @@ -96,13 +95,10 @@ public static void Run(StatementBlock block, RandomGenerator random) { } } - private class TransformContext { - + class TransformContext { public Dictionary Definitions; public Statement[] Statements; public Dictionary Usages; - } - } } \ No newline at end of file diff --git a/Confuser.DynCipher/Utils.cs b/Confuser.DynCipher/Utils.cs index a1e985229..ad22524d5 100644 --- a/Confuser.DynCipher/Utils.cs +++ b/Confuser.DynCipher/Utils.cs @@ -4,8 +4,7 @@ namespace Confuser.DynCipher { public static class MathsUtils { - - private const ulong MODULO32 = 0x100000000; + const ulong MODULO32 = 0x100000000; public static ulong modInv(ulong num, ulong mod) { ulong a = mod, b = num % mod; @@ -31,11 +30,9 @@ public static uint modInv(uint num) { public static byte modInv(byte num) { return (byte)modInv(num, 0x100); } - } public static class CodeGenUtils { - public static byte[] AssembleCode(x86CodeGen codeGen, x86Register reg) { var stream = new MemoryStream(); using (var writer = new BinaryWriter(stream)) { @@ -83,6 +80,5 @@ public static byte[] AssembleCode(x86CodeGen codeGen, x86Register reg) { } return stream.ToArray(); } - } } \ No newline at end of file diff --git a/Confuser.Protections/AntiDebugProtection.cs b/Confuser.Protections/AntiDebugProtection.cs index 94cf20bc5..36cde3358 100644 --- a/Confuser.Protections/AntiDebugProtection.cs +++ b/Confuser.Protections/AntiDebugProtection.cs @@ -11,7 +11,6 @@ namespace Confuser.Protections { [BeforeProtection("Ki.ControlFlow")] internal class AntiDebugProtection : Protection { - public const string _Id = "anti debug"; public const string _FullId = "Ki.AntiDebug"; @@ -43,8 +42,7 @@ protected override void PopulatePipeline(ProtectionPipeline pipeline) { pipeline.InsertPreStage(PipelineStage.ProcessModule, new AntiDebugPhase(this)); } - private class AntiDebugPhase : ProtectionPhase { - + class AntiDebugPhase : ProtectionPhase { public AntiDebugPhase(AntiDebugProtection parent) : base(parent) { } @@ -130,15 +128,11 @@ protected override void Execute(ConfuserContext context, ProtectionParameters pa } } - private enum AntiMode { - + enum AntiMode { Safe, Win32, Antinet - } - } - } } \ No newline at end of file diff --git a/Confuser.Protections/AntiDumpProtection.cs b/Confuser.Protections/AntiDumpProtection.cs index 638e6fd8b..217a1d84d 100644 --- a/Confuser.Protections/AntiDumpProtection.cs +++ b/Confuser.Protections/AntiDumpProtection.cs @@ -11,7 +11,6 @@ namespace Confuser.Protections { [BeforeProtection("Ki.ControlFlow")] internal class AntiDumpProtection : Protection { - public const string _Id = "anti dump"; public const string _FullId = "Ki.AntiDump"; @@ -43,8 +42,7 @@ protected override void PopulatePipeline(ProtectionPipeline pipeline) { pipeline.InsertPreStage(PipelineStage.ProcessModule, new AntiDumpPhase(this)); } - private class AntiDumpPhase : ProtectionPhase { - + class AntiDumpPhase : ProtectionPhase { public AntiDumpPhase(AntiDumpProtection parent) : base(parent) { } @@ -73,8 +71,6 @@ protected override void Execute(ConfuserContext context, ProtectionParameters pa name.MarkHelper(member, marker); } } - } - } } \ No newline at end of file diff --git a/Confuser.Protections/AntiILDasmProtection.cs b/Confuser.Protections/AntiILDasmProtection.cs index 1a750a523..43241c96e 100644 --- a/Confuser.Protections/AntiILDasmProtection.cs +++ b/Confuser.Protections/AntiILDasmProtection.cs @@ -5,7 +5,6 @@ namespace Confuser.Protections { internal class AntiILDasmProtection : Protection { - public const string _Id = "anti ildasm"; public const string _FullId = "Ki.AntiILDasm"; @@ -37,8 +36,7 @@ protected override void PopulatePipeline(ProtectionPipeline pipeline) { pipeline.InsertPreStage(PipelineStage.ProcessModule, new AntiILDasmPhase(this)); } - private class AntiILDasmPhase : ProtectionPhase { - + class AntiILDasmPhase : ProtectionPhase { public AntiILDasmPhase(AntiILDasmProtection parent) : base(parent) { } @@ -59,8 +57,6 @@ protected override void Execute(ConfuserContext context, ProtectionParameters pa module.CustomAttributes.Add(attr); } } - } - } } \ No newline at end of file diff --git a/Confuser.Protections/AntiTamper/AntiTamperProtection.cs b/Confuser.Protections/AntiTamper/AntiTamperProtection.cs index abc861ffa..1269fc56a 100644 --- a/Confuser.Protections/AntiTamper/AntiTamperProtection.cs +++ b/Confuser.Protections/AntiTamper/AntiTamperProtection.cs @@ -6,18 +6,15 @@ namespace Confuser.Protections { public interface IAntiTamperService { - void ExcludeMethod(ConfuserContext context, MethodDef method); - } [BeforeProtection("Ki.ControlFlow"), AfterProtection("Ki.Constants")] internal class AntiTamperProtection : Protection, IAntiTamperService { - public const string _Id = "anti tamper"; public const string _FullId = "Ki.AntiTamper"; public const string _ServiceId = "Ki.AntiTamper"; - private static readonly object HandlerKey = new object(); + static readonly object HandlerKey = new object(); public override string Name { get { return "Anti Tamper Protection"; } @@ -52,8 +49,7 @@ public void ExcludeMethod(ConfuserContext context, MethodDef method) { ProtectionParameters.GetParameters(context, method).Remove(this); } - private class InjectPhase : ProtectionPhase { - + class InjectPhase : ProtectionPhase { public InjectPhase(AntiTamperProtection parent) : base(parent) { } @@ -84,11 +80,9 @@ protected override void Execute(ConfuserContext context, ProtectionParameters pa modeHandler.HandleInject((AntiTamperProtection)Parent, context, parameters); context.Annotations.Set(context.CurrentModule, HandlerKey, modeHandler); } - } - private class MDPhase : ProtectionPhase { - + class MDPhase : ProtectionPhase { public MDPhase(AntiTamperProtection parent) : base(parent) { } @@ -107,15 +101,11 @@ protected override void Execute(ConfuserContext context, ProtectionParameters pa var modeHandler = context.Annotations.Get(context.CurrentModule, HandlerKey); modeHandler.HandleMD((AntiTamperProtection)Parent, context, parameters); } - } - private enum Mode { - + enum Mode { Normal, JIT - } - } } \ No newline at end of file diff --git a/Confuser.Protections/AntiTamper/DynamicDeriver.cs b/Confuser.Protections/AntiTamper/DynamicDeriver.cs index fec7205a2..0409f9f55 100644 --- a/Confuser.Protections/AntiTamper/DynamicDeriver.cs +++ b/Confuser.Protections/AntiTamper/DynamicDeriver.cs @@ -10,9 +10,8 @@ namespace Confuser.Protections.AntiTamper { internal class DynamicDeriver : IKeyDeriver { - - private StatementBlock derivation; - private Action encryptFunc; + StatementBlock derivation; + Action encryptFunc; public void Init(ConfuserContext ctx, RandomGenerator random) { StatementBlock dummy; @@ -41,10 +40,9 @@ public IEnumerable EmitDerivation(MethodDef method, ConfuserContext return ret; } - private class CodeGen : CILCodeGen { - - private readonly Local block; - private readonly Local key; + class CodeGen : CILCodeGen { + readonly Local block; + readonly Local key; public CodeGen(Local block, Local key, MethodDef method, IList instrs) : base(method, instrs) { @@ -59,8 +57,6 @@ protected override Local Var(Variable var) { return key; return base.Var(var); } - } - } } \ No newline at end of file diff --git a/Confuser.Protections/AntiTamper/IKeyDeriver.cs b/Confuser.Protections/AntiTamper/IKeyDeriver.cs index d76533e56..a89fb9592 100644 --- a/Confuser.Protections/AntiTamper/IKeyDeriver.cs +++ b/Confuser.Protections/AntiTamper/IKeyDeriver.cs @@ -7,17 +7,13 @@ namespace Confuser.Protections.AntiTamper { internal enum Mode { - Normal, Dynamic - } internal interface IKeyDeriver { - void Init(ConfuserContext ctx, RandomGenerator random); uint[] DeriveKey(uint[] a, uint[] b); IEnumerable EmitDerivation(MethodDef method, ConfuserContext ctx, Local dst, Local src); - } } \ No newline at end of file diff --git a/Confuser.Protections/AntiTamper/IModeHandler.cs b/Confuser.Protections/AntiTamper/IModeHandler.cs index a775614ea..c7ccc660d 100644 --- a/Confuser.Protections/AntiTamper/IModeHandler.cs +++ b/Confuser.Protections/AntiTamper/IModeHandler.cs @@ -3,9 +3,7 @@ namespace Confuser.Protections.AntiTamper { internal interface IModeHandler { - void HandleInject(AntiTamperProtection parent, ConfuserContext context, ProtectionParameters parameters); void HandleMD(AntiTamperProtection parent, ConfuserContext context, ProtectionParameters parameters); - } } \ No newline at end of file diff --git a/Confuser.Protections/AntiTamper/JITBody.cs b/Confuser.Protections/AntiTamper/JITBody.cs index 33836d623..25de3774a 100644 --- a/Confuser.Protections/AntiTamper/JITBody.cs +++ b/Confuser.Protections/AntiTamper/JITBody.cs @@ -11,18 +11,15 @@ namespace Confuser.Protections.AntiTamper { internal struct JITEHClause { - public uint ClassTokenOrFilterOffset; public uint Flags; public uint HandlerLength; public uint HandlerOffset; public uint TryLength; public uint TryOffset; - } internal class JITMethodBody : IChunk { - public byte[] Body; public JITEHClause[] EHs; public byte[] ILCode; @@ -33,20 +30,13 @@ internal class JITMethodBody : IChunk { public uint Offset; public uint Options; - private FileOffset offset; - private RVA rva; + public FileOffset FileOffset { get; set; } - public FileOffset FileOffset { - get { return offset; } - } - - public RVA RVA { - get { return rva; } - } + public RVA RVA { get; set; } public void SetOffset(FileOffset offset, RVA rva) { - this.offset = offset; - this.rva = rva; + this.FileOffset = offset; + this.RVA = rva; } public uint GetFileLength() { @@ -114,15 +104,13 @@ public void Serialize(uint token, uint key, byte[] fieldLayout) { counter ^= (state >> 5) | (state << 27); } } - } internal class JITMethodBodyWriter : MethodBodyWriterBase { - - private readonly CilBody body; - private readonly JITMethodBody jitBody; - private readonly bool keepMaxStack; - private readonly MetaData metadata; + readonly CilBody body; + readonly JITMethodBody jitBody; + readonly bool keepMaxStack; + readonly MetaData metadata; public JITMethodBodyWriter(MetaData md, CilBody body, JITMethodBody jitBody, uint mulSeed, bool keepMaxStack) : base(body.Instructions, body.ExceptionHandlers) { @@ -208,31 +196,22 @@ protected override void WriteInlineTok(BinaryWriter writer, Instruction instr) { protected override void WriteInlineType(BinaryWriter writer, Instruction instr) { writer.Write(metadata.GetToken(instr.Operand).Raw); } - } internal class JITBodyIndex : IChunk { - - private readonly Dictionary bodies; - - private FileOffset offset; - private RVA rva; + readonly Dictionary bodies; public JITBodyIndex(IEnumerable tokens) { bodies = tokens.ToDictionary(token => token, token => (JITMethodBody)null); } - public FileOffset FileOffset { - get { return offset; } - } + public FileOffset FileOffset { get; set; } - public RVA RVA { - get { return rva; } - } + public RVA RVA { get; set; } public void SetOffset(FileOffset offset, RVA rva) { - this.offset = offset; - this.rva = rva; + this.FileOffset = offset; + this.RVA = rva; } public uint GetFileLength() { @@ -270,6 +249,5 @@ public void PopulateSection(PESection section) { offset += entry.Value.GetFileLength(); } } - } } \ No newline at end of file diff --git a/Confuser.Protections/AntiTamper/JITMode.cs b/Confuser.Protections/AntiTamper/JITMode.cs index d03ae88f0..68e14fab0 100644 --- a/Confuser.Protections/AntiTamper/JITMode.cs +++ b/Confuser.Protections/AntiTamper/JITMode.cs @@ -14,29 +14,28 @@ namespace Confuser.Protections.AntiTamper { internal class JITMode : IModeHandler { - - private static readonly CilBody NopBody = new CilBody { + static readonly CilBody NopBody = new CilBody { Instructions = { Instruction.Create(OpCodes.Ldnull), Instruction.Create(OpCodes.Throw) } }; - private uint c; - private MethodDef cctor; - private MethodDef cctorRepl; - private ConfuserContext context; - private IKeyDeriver deriver; - private byte[] fieldLayout; - - private MethodDef initMethod; - private uint key; - private List methods; - private uint name1, name2; - private RandomGenerator random; - private uint v; - private uint x; - private uint z; + uint c; + MethodDef cctor; + MethodDef cctorRepl; + ConfuserContext context; + IKeyDeriver deriver; + byte[] fieldLayout; + + MethodDef initMethod; + uint key; + List methods; + uint name1, name2; + RandomGenerator random; + uint v; + uint x; + uint z; public void HandleInject(AntiTamperProtection parent, ConfuserContext context, ProtectionParameters parameters) { this.context = context; @@ -151,7 +150,7 @@ public void HandleMD(AntiTamperProtection parent, ConfuserContext context, Prote context.CurrentModuleWriterListener.OnWriterEvent += OnWriterEvent; } - private void OnWriterEvent(object sender, ModuleWriterListenerEventArgs e) { + void OnWriterEvent(object sender, ModuleWriterListenerEventArgs e) { var writer = (ModuleWriter)sender; if (e.WriterEvent == ModuleWriterEvent.MDBeginWriteMethodBodies) { context.Logger.Debug("Extracting method bodies..."); @@ -163,7 +162,7 @@ private void OnWriterEvent(object sender, ModuleWriterListenerEventArgs e) { } } - private void CreateSection(ModuleWriter writer) { + void CreateSection(ModuleWriter writer) { // move some PE parts to separate section to prevent it from being hashed var peSection = new PESection("", 0x60000020); bool moved = false; @@ -229,7 +228,7 @@ private void CreateSection(ModuleWriter writer) { newSection.Add(new ByteArrayChunk(new byte[4]), 4); } - private void EncryptSection(ModuleWriter writer) { + void EncryptSection(ModuleWriter writer) { Stream stream = writer.DestinationStream; var reader = new BinaryReader(writer.DestinationStream); stream.Position = 0x3C; @@ -272,7 +271,7 @@ private void EncryptSection(ModuleWriter writer) { stream.Write(byteResult, 0, byteResult.Length); } - private void Hash(Stream stream, BinaryReader reader, uint offset, uint size) { + void Hash(Stream stream, BinaryReader reader, uint offset, uint size) { long original = stream.Position; stream.Position = offset; size >>= 2; @@ -287,7 +286,7 @@ private void Hash(Stream stream, BinaryReader reader, uint offset, uint size) { stream.Position = original; } - private uint[] DeriveKey() { + uint[] DeriveKey() { uint[] dst = new uint[0x10], src = new uint[0x10]; for (int i = 0; i < 0x10; i++) { dst[i] = v; @@ -299,6 +298,5 @@ private uint[] DeriveKey() { } return deriver.DeriveKey(dst, src); } - } } \ No newline at end of file diff --git a/Confuser.Protections/AntiTamper/NormalDeriver.cs b/Confuser.Protections/AntiTamper/NormalDeriver.cs index 6f77bf7ea..52ac6629f 100644 --- a/Confuser.Protections/AntiTamper/NormalDeriver.cs +++ b/Confuser.Protections/AntiTamper/NormalDeriver.cs @@ -7,7 +7,6 @@ namespace Confuser.Protections.AntiTamper { internal class NormalDeriver : IKeyDeriver { - public void Init(ConfuserContext ctx, RandomGenerator random) { // } @@ -54,6 +53,5 @@ public IEnumerable EmitDerivation(MethodDef method, ConfuserContext yield return Instruction.Create(OpCodes.Stelem_I4); } } - } } \ No newline at end of file diff --git a/Confuser.Protections/AntiTamper/NormalMode.cs b/Confuser.Protections/AntiTamper/NormalMode.cs index f160b191d..b72975537 100644 --- a/Confuser.Protections/AntiTamper/NormalMode.cs +++ b/Confuser.Protections/AntiTamper/NormalMode.cs @@ -15,16 +15,15 @@ namespace Confuser.Protections.AntiTamper { internal class NormalMode : IModeHandler { + uint c; + IKeyDeriver deriver; - private uint c; - private IKeyDeriver deriver; - - private List methods; - private uint name1, name2; - private RandomGenerator random; - private uint v; - private uint x; - private uint z; + List methods; + uint name1, name2; + RandomGenerator random; + uint v; + uint x; + uint z; public void HandleInject(AntiTamperProtection parent, ConfuserContext context, ProtectionParameters parameters) { random = context.Registry.GetService().GetRandomGenerator(parent.FullId); @@ -100,7 +99,7 @@ public void HandleMD(AntiTamperProtection parent, ConfuserContext context, Prote context.CurrentModuleWriterListener.OnWriterEvent += OnWriterEvent; } - private void OnWriterEvent(object sender, ModuleWriterListenerEventArgs e) { + void OnWriterEvent(object sender, ModuleWriterListenerEventArgs e) { var writer = (ModuleWriter)sender; if (e.WriterEvent == ModuleWriterEvent.MDEndCreateTables) { CreateSections(writer); @@ -110,7 +109,7 @@ private void OnWriterEvent(object sender, ModuleWriterListenerEventArgs e) { } } - private void CreateSections(ModuleWriter writer) { + void CreateSections(ModuleWriter writer) { var nameBuffer = new byte[8]; nameBuffer[0] = (byte)(name1 >> 0); nameBuffer[1] = (byte)(name1 >> 8); @@ -170,7 +169,7 @@ private void CreateSections(ModuleWriter writer) { newSection.Add(new ByteArrayChunk(new byte[4]), 4); } - private void EncryptSection(ModuleWriter writer) { + void EncryptSection(ModuleWriter writer) { Stream stream = writer.DestinationStream; var reader = new BinaryReader(writer.DestinationStream); stream.Position = 0x3C; @@ -213,7 +212,7 @@ private void EncryptSection(ModuleWriter writer) { stream.Write(byteResult, 0, byteResult.Length); } - private void Hash(Stream stream, BinaryReader reader, uint offset, uint size) { + void Hash(Stream stream, BinaryReader reader, uint offset, uint size) { long original = stream.Position; stream.Position = offset; size >>= 2; @@ -228,7 +227,7 @@ private void Hash(Stream stream, BinaryReader reader, uint offset, uint size) { stream.Position = original; } - private uint[] DeriveKey() { + uint[] DeriveKey() { uint[] dst = new uint[0x10], src = new uint[0x10]; for (int i = 0; i < 0x10; i++) { dst[i] = v; @@ -240,6 +239,5 @@ private uint[] DeriveKey() { } return deriver.DeriveKey(dst, src); } - } } \ No newline at end of file diff --git a/Confuser.Protections/Compress/Compressor.cs b/Confuser.Protections/Compress/Compressor.cs index c572a51c4..781bd353c 100644 --- a/Confuser.Protections/Compress/Compressor.cs +++ b/Confuser.Protections/Compress/Compressor.cs @@ -14,11 +14,11 @@ using dnlib.DotNet.Emit; using dnlib.DotNet.MD; using dnlib.DotNet.Writer; +using dnlib.PE; using FileAttributes = dnlib.DotNet.FileAttributes; namespace Confuser.Protections { internal class Compressor : Packer { - public const string _Id = "compressor"; public const string _FullId = "Ki.Compressor"; public const string _ServiceId = "Ki.Compressor"; @@ -78,12 +78,12 @@ protected override void Pack(ConfuserContext context, ProtectionParameters param StrongNameKey = snKey }); context.CheckCancellation(); - base.ProtectStub(context, context.OutputPaths[ctx.ModuleIndex], ms.ToArray(), snKey, new StubProtection(ctx, originModule)); + ProtectStub(context, context.OutputPaths[ctx.ModuleIndex], ms.ToArray(), snKey, new StubProtection(ctx, originModule)); } } - private static string GetFullName(byte[] module) { - var md = MetaDataCreator.CreateMetaData(new dnlib.PE.PEImage(module)); + static string GetFullName(byte[] module) { + var md = MetaDataCreator.CreateMetaData(new PEImage(module)); var assemblyRow = md.TablesStream.ReadAssemblyRow(1); var assembly = new AssemblyNameInfo(); assembly.Name = md.StringsStream.ReadNoNull(assemblyRow.Name); @@ -95,7 +95,7 @@ private static string GetFullName(byte[] module) { return assembly.FullName; } - private void PackModules(ConfuserContext context, CompressorContext compCtx, ModuleDef stubModule, ICompressionService comp, RandomGenerator random) { + void PackModules(ConfuserContext context, CompressorContext compCtx, ModuleDef stubModule, ICompressionService comp, RandomGenerator random) { int maxLen = 0; var modules = new Dictionary(); for (int i = 0; i < context.OutputModules.Count; i++) { @@ -149,7 +149,7 @@ private void PackModules(ConfuserContext context, CompressorContext compCtx, Mod context.Logger.EndProgress(); } - private void InjectData(ModuleDef stubModule, MethodDef method, byte[] data) { + void InjectData(ModuleDef stubModule, MethodDef method, byte[] data) { var dataType = new TypeDefUser("", "DataType", stubModule.CorLibTypes.GetTypeRef("System", "ValueType")); dataType.Layout = TypeAttributes.ExplicitLayout; dataType.Visibility = TypeAttributes.NestedPrivate; @@ -176,7 +176,7 @@ private void InjectData(ModuleDef stubModule, MethodDef method, byte[] data) { }); } - private void InjectStub(ConfuserContext context, CompressorContext compCtx, ProtectionParameters parameters, ModuleDef stubModule) { + void InjectStub(ConfuserContext context, CompressorContext compCtx, ProtectionParameters parameters, ModuleDef stubModule) { var rt = context.Registry.GetService(); RandomGenerator random = context.Registry.GetService().GetRandomGenerator(Id); var comp = context.Registry.GetService(); @@ -248,7 +248,7 @@ private void InjectStub(ConfuserContext context, CompressorContext compCtx, Prot PackModules(context, compCtx, stubModule, comp, random); } - private void ImportAssemblyTypeReferences(ModuleDef originModule, ModuleDef stubModule) { + void ImportAssemblyTypeReferences(ModuleDef originModule, ModuleDef stubModule) { var assembly = stubModule.Assembly; foreach (var ca in assembly.CustomAttributes) { if (ca.AttributeType.Scope == originModule) @@ -260,9 +260,8 @@ private void ImportAssemblyTypeReferences(ModuleDef originModule, ModuleDef stub } } - private class KeyInjector : IModuleWriterListener { - - private readonly CompressorContext ctx; + class KeyInjector : IModuleWriterListener { + readonly CompressorContext ctx; public KeyInjector(CompressorContext ctx) { this.ctx = ctx; @@ -296,8 +295,6 @@ public void OnWriterEvent(ModuleWriterBase writer, ModuleWriterEvent evt) { resTbl.Add(new RawManifestResourceRow(resource.Item1, resource.Item2, writer.MetaData.StringsHeap.Add(resource.Item3), impl)); } } - } - } } \ No newline at end of file diff --git a/Confuser.Protections/Compress/CompressorContext.cs b/Confuser.Protections/Compress/CompressorContext.cs index 3a4926132..97d7bb29b 100644 --- a/Confuser.Protections/Compress/CompressorContext.cs +++ b/Confuser.Protections/Compress/CompressorContext.cs @@ -1,12 +1,10 @@ using System; using System.Collections.Generic; -using Confuser.Core; using Confuser.Core.Services; using dnlib.DotNet; namespace Confuser.Protections.Compress { internal class CompressorContext { - public AssemblyDef Assembly; public IKeyDeriver Deriver; public byte[] EncryptedModule; @@ -56,6 +54,5 @@ public byte[] Encrypt(ICompressionService compress, byte[] data, uint seed, Acti return encryptedData; } - } } \ No newline at end of file diff --git a/Confuser.Protections/Compress/DynamicDeriver.cs b/Confuser.Protections/Compress/DynamicDeriver.cs index 412158aaa..fb983ecae 100644 --- a/Confuser.Protections/Compress/DynamicDeriver.cs +++ b/Confuser.Protections/Compress/DynamicDeriver.cs @@ -10,9 +10,8 @@ namespace Confuser.Protections.Compress { internal class DynamicDeriver : IKeyDeriver { - - private StatementBlock derivation; - private Action encryptFunc; + StatementBlock derivation; + Action encryptFunc; public void Init(ConfuserContext ctx, RandomGenerator random) { StatementBlock dummy; @@ -41,10 +40,9 @@ public IEnumerable EmitDerivation(MethodDef method, ConfuserContext return ret; } - private class CodeGen : CILCodeGen { - - private readonly Local block; - private readonly Local key; + class CodeGen : CILCodeGen { + readonly Local block; + readonly Local key; public CodeGen(Local block, Local key, MethodDef method, IList instrs) : base(method, instrs) { @@ -59,8 +57,6 @@ protected override Local Var(Variable var) { return key; return base.Var(var); } - } - } } \ No newline at end of file diff --git a/Confuser.Protections/Compress/ExtractPhase.cs b/Confuser.Protections/Compress/ExtractPhase.cs index 03f452e56..de97d3ecd 100644 --- a/Confuser.Protections/Compress/ExtractPhase.cs +++ b/Confuser.Protections/Compress/ExtractPhase.cs @@ -9,7 +9,6 @@ namespace Confuser.Protections.Compress { internal class ExtractPhase : ProtectionPhase { - public ExtractPhase(Compressor parent) : base(parent) { } public override ProtectionTargets Targets { @@ -55,10 +54,9 @@ protected override void Execute(ConfuserContext context, ProtectionParameters pa } } - private class ResourceRecorder { - - private readonly CompressorContext ctx; - private ModuleDef targetModule; + class ResourceRecorder { + readonly CompressorContext ctx; + ModuleDef targetModule; public ResourceRecorder(CompressorContext ctx, ModuleDef module) { this.ctx = ctx; @@ -75,8 +73,6 @@ public void OnWriterEvent(object sender, ModuleWriterListenerEventArgs e) { ctx.EntryPointToken = writer.MetaData.GetToken(ctx.EntryPoint).Raw; } } - } - } } \ No newline at end of file diff --git a/Confuser.Protections/Compress/IKeyDeriver.cs b/Confuser.Protections/Compress/IKeyDeriver.cs index e5d9802f4..5284205ce 100644 --- a/Confuser.Protections/Compress/IKeyDeriver.cs +++ b/Confuser.Protections/Compress/IKeyDeriver.cs @@ -7,17 +7,13 @@ namespace Confuser.Protections.Compress { internal enum Mode { - Normal, Dynamic - } internal interface IKeyDeriver { - void Init(ConfuserContext ctx, RandomGenerator random); uint[] DeriveKey(uint[] a, uint[] b); IEnumerable EmitDerivation(MethodDef method, ConfuserContext ctx, Local dst, Local src); - } } \ No newline at end of file diff --git a/Confuser.Protections/Compress/NormalDeriver.cs b/Confuser.Protections/Compress/NormalDeriver.cs index 64305e458..27465d7eb 100644 --- a/Confuser.Protections/Compress/NormalDeriver.cs +++ b/Confuser.Protections/Compress/NormalDeriver.cs @@ -7,11 +7,10 @@ namespace Confuser.Protections.Compress { internal class NormalDeriver : IKeyDeriver { - - private uint k1; - private uint k2; - private uint k3; - private uint seed; + uint k1; + uint k2; + uint k3; + uint seed; public void Init(ConfuserContext ctx, RandomGenerator random) { k1 = random.NextUInt32() | 1; @@ -93,6 +92,5 @@ public IEnumerable EmitDerivation(MethodDef method, ConfuserContext yield return Instruction.Create(OpCodes.Stelem_I4); } } - } } \ No newline at end of file diff --git a/Confuser.Protections/Compress/StubProtection.cs b/Confuser.Protections/Compress/StubProtection.cs index 3a369497a..5c682604f 100644 --- a/Confuser.Protections/Compress/StubProtection.cs +++ b/Confuser.Protections/Compress/StubProtection.cs @@ -9,9 +9,8 @@ namespace Confuser.Protections.Compress { internal class StubProtection : Protection { - - private readonly CompressorContext ctx; - private readonly ModuleDef originModule; + readonly CompressorContext ctx; + readonly ModuleDef originModule; internal StubProtection(CompressorContext ctx, ModuleDef originModule) { this.ctx = ctx; @@ -47,8 +46,7 @@ protected override void PopulatePipeline(ProtectionPipeline pipeline) { pipeline.InsertPostStage(PipelineStage.BeginModule, new SigPhase(this)); } - private class InjPhase : ProtectionPhase { - + class InjPhase : ProtectionPhase { public InjPhase(StubProtection parent) : base(parent) { } @@ -70,11 +68,9 @@ protected override void Execute(ConfuserContext context, ProtectionParameters pa originModule.Assembly.Modules.Remove(originModule); context.Modules[0].Assembly.Modules.Add(((StubProtection)Parent).originModule); } - } - private class SigPhase : ProtectionPhase { - + class SigPhase : ProtectionPhase { public SigPhase(StubProtection parent) : base(parent) { } @@ -112,8 +108,6 @@ protected override void Execute(ConfuserContext context, ProtectionParameters pa } }; } - } - } } \ No newline at end of file diff --git a/Confuser.Protections/Constants/CEContext.cs b/Confuser.Protections/Constants/CEContext.cs index 086a0b0c3..d3aef725e 100644 --- a/Confuser.Protections/Constants/CEContext.cs +++ b/Confuser.Protections/Constants/CEContext.cs @@ -9,7 +9,6 @@ namespace Confuser.Protections.Constants { internal class CEContext { - public ConfuserContext Context; public ModuleDef Module; @@ -33,15 +32,12 @@ internal class CEContext { public RandomGenerator Random; public Dictionary>> ReferenceRepl; - } internal class DecoderDesc { - public object Data; public byte InitializerID; public byte NumberID; public byte StringID; - } } \ No newline at end of file diff --git a/Confuser.Protections/Constants/ConstantProtection.cs b/Confuser.Protections/Constants/ConstantProtection.cs index 4804e00ff..bfa304746 100644 --- a/Confuser.Protections/Constants/ConstantProtection.cs +++ b/Confuser.Protections/Constants/ConstantProtection.cs @@ -5,14 +5,11 @@ namespace Confuser.Protections { public interface IConstantService { - void ExcludeMethod(ConfuserContext context, MethodDef method); - } [BeforeProtection("Ki.ControlFlow"), AfterProtection("Ki.RefProxy")] internal class ConstantProtection : Protection, IConstantService { - public const string _Id = "constants"; public const string _FullId = "Ki.Constants"; public const string _ServiceId = "Ki.Constants"; @@ -50,6 +47,5 @@ protected override void PopulatePipeline(ProtectionPipeline pipeline) { pipeline.InsertPreStage(PipelineStage.ProcessModule, new InjectPhase(this)); pipeline.InsertPostStage(PipelineStage.ProcessModule, new EncodePhase(this)); } - } } \ No newline at end of file diff --git a/Confuser.Protections/Constants/DynamicMode.cs b/Confuser.Protections/Constants/DynamicMode.cs index bb46bb896..5567904c2 100644 --- a/Confuser.Protections/Constants/DynamicMode.cs +++ b/Confuser.Protections/Constants/DynamicMode.cs @@ -1,7 +1,6 @@ using System; using System.Collections.Generic; using System.Diagnostics; -using Confuser.Core; using Confuser.Core.Helpers; using Confuser.DynCipher; using Confuser.DynCipher.AST; @@ -11,8 +10,7 @@ namespace Confuser.Protections.Constants { internal class DynamicMode : IEncodeMode { - - private Action encryptFunc; + Action encryptFunc; public IEnumerable EmitDecrypt(MethodDef init, CEContext ctx, Local block, Local key) { StatementBlock encrypt, decrypt; @@ -62,10 +60,9 @@ public uint Encode(object data, CEContext ctx, uint id) { return ret; } - private class CodeGen : CILCodeGen { - - private readonly Local block; - private readonly Local key; + class CodeGen : CILCodeGen { + readonly Local block; + readonly Local key; public CodeGen(Local block, Local key, MethodDef init, IList instrs) : base(init, instrs) { @@ -80,8 +77,6 @@ protected override Local Var(Variable var) { return key; return base.Var(var); } - } - } } \ No newline at end of file diff --git a/Confuser.Protections/Constants/EncodeElements.cs b/Confuser.Protections/Constants/EncodeElements.cs index 6f1806dce..4adc622ef 100644 --- a/Confuser.Protections/Constants/EncodeElements.cs +++ b/Confuser.Protections/Constants/EncodeElements.cs @@ -3,11 +3,9 @@ namespace Confuser.Protections.Constants { [Flags] internal enum EncodeElements { - Strings = 1, Numbers = 2, Primitive = 4, Initializers = 8 - } } \ No newline at end of file diff --git a/Confuser.Protections/Constants/EncodePhase.cs b/Confuser.Protections/Constants/EncodePhase.cs index d0a46ea07..680507a5e 100644 --- a/Confuser.Protections/Constants/EncodePhase.cs +++ b/Confuser.Protections/Constants/EncodePhase.cs @@ -13,7 +13,6 @@ namespace Confuser.Protections.Constants { internal class EncodePhase : ProtectionPhase { - public EncodePhase(ConstantProtection parent) : base(parent) { } @@ -128,13 +127,13 @@ protected override void Execute(ConfuserContext context, ProtectionParameters pa }); } - private void EncodeString(CEContext moduleCtx, string value, List> references) { + void EncodeString(CEContext moduleCtx, string value, List> references) { int buffIndex = EncodeByteArray(moduleCtx, Encoding.UTF8.GetBytes(value)); UpdateReference(moduleCtx, moduleCtx.Module.CorLibTypes.String, references, buffIndex, desc => desc.StringID); } - private void EncodeConstant32(CEContext moduleCtx, uint value, TypeSig valueType, List> references) { + void EncodeConstant32(CEContext moduleCtx, uint value, TypeSig valueType, List> references) { int buffIndex = moduleCtx.EncodedBuffer.IndexOf(value); if (buffIndex == -1) { buffIndex = moduleCtx.EncodedBuffer.Count; @@ -144,7 +143,7 @@ private void EncodeConstant32(CEContext moduleCtx, uint value, TypeSig valueType UpdateReference(moduleCtx, valueType, references, buffIndex, desc => desc.NumberID); } - private void EncodeConstant64(CEContext moduleCtx, uint hi, uint lo, TypeSig valueType, List> references) { + void EncodeConstant64(CEContext moduleCtx, uint hi, uint lo, TypeSig valueType, List> references) { int buffIndex = moduleCtx.EncodedBuffer.IndexOf(hi); while (buffIndex != -1) { if (moduleCtx.EncodedBuffer[buffIndex + 1] == lo) @@ -162,7 +161,7 @@ private void EncodeConstant64(CEContext moduleCtx, uint hi, uint lo, TypeSig val UpdateReference(moduleCtx, valueType, references, buffIndex, desc => desc.NumberID); } - private void EncodeInitializer(CEContext moduleCtx, byte[] init, List> references) { + void EncodeInitializer(CEContext moduleCtx, byte[] init, List> references) { int buffIndex = -1; foreach (var instr in references) { @@ -186,7 +185,7 @@ private void EncodeInitializer(CEContext moduleCtx, byte[] init, List> references, int buffIndex, Func typeID) { + void UpdateReference(CEContext moduleCtx, TypeSig valueType, List> references, int buffIndex, Func typeID) { foreach (var instr in references) { Tuple decoder = moduleCtx.Decoders[moduleCtx.Random.NextInt32(moduleCtx.Decoders.Count)]; uint id = (uint)buffIndex | (uint)(typeID(decoder.Item2) << 30); @@ -217,7 +216,7 @@ private void UpdateReference(CEContext moduleCtx, TypeSig valueType, List>> ldc, Dictionary>> ldInit) { @@ -331,8 +330,7 @@ private void ExtractConstants( } } - private class ByteArrayComparer : IEqualityComparer { - + class ByteArrayComparer : IEqualityComparer { public bool Equals(byte[] x, byte[] y) { return x.SequenceEqual(y); } @@ -343,19 +341,15 @@ public int GetHashCode(byte[] obj) { ret = ret * 17 + v; return ret; } - } [StructLayout(LayoutKind.Explicit)] - private struct RTransform { - + struct RTransform { [FieldOffset(0)] public float R4; [FieldOffset(0)] public double R8; [FieldOffset(0)] public readonly uint Hi; [FieldOffset(4)] public readonly uint Lo; - } - } } \ No newline at end of file diff --git a/Confuser.Protections/Constants/IEncodeMode.cs b/Confuser.Protections/Constants/IEncodeMode.cs index bdc2ce7b4..9df0aa6e7 100644 --- a/Confuser.Protections/Constants/IEncodeMode.cs +++ b/Confuser.Protections/Constants/IEncodeMode.cs @@ -5,12 +5,10 @@ namespace Confuser.Protections.Constants { internal interface IEncodeMode { - IEnumerable EmitDecrypt(MethodDef init, CEContext ctx, Local block, Local key); uint[] Encrypt(uint[] data, int offset, uint[] key); object CreateDecoder(MethodDef decoder, CEContext ctx); uint Encode(object data, CEContext ctx, uint id); - } } \ No newline at end of file diff --git a/Confuser.Protections/Constants/InjectPhase.cs b/Confuser.Protections/Constants/InjectPhase.cs index 6449522f6..15a1d059c 100644 --- a/Confuser.Protections/Constants/InjectPhase.cs +++ b/Confuser.Protections/Constants/InjectPhase.cs @@ -13,7 +13,6 @@ namespace Confuser.Protections.Constants { internal class InjectPhase : ProtectionPhase { - public InjectPhase(ConstantProtection parent) : base(parent) { } @@ -78,7 +77,7 @@ protected override void Execute(ConfuserContext context, ProtectionParameters pa } } - private void InjectHelpers(ConfuserContext context, ICompressionService compression, IRuntimeService rt, CEContext moduleCtx) { + void InjectHelpers(ConfuserContext context, ICompressionService compression, IRuntimeService rt, CEContext moduleCtx) { IEnumerable members = InjectHelper.Inject(rt.GetRuntimeType("Confuser.Runtime.Constant"), context.CurrentModule.GlobalType, context.CurrentModule); foreach (IDnlibDef member in members) { if (member.Name == "Get") { @@ -147,7 +146,7 @@ private void InjectHelpers(ConfuserContext context, ICompressionService compress } } - private void MutateInitializer(CEContext moduleCtx, MethodDef decomp) { + void MutateInitializer(CEContext moduleCtx, MethodDef decomp) { moduleCtx.InitMethod.Body.SimplifyMacros(moduleCtx.InitMethod.Parameters); List instrs = moduleCtx.InitMethod.Body.Instructions.ToList(); for (int i = 0; i < instrs.Count; i++) { @@ -174,6 +173,5 @@ private void MutateInitializer(CEContext moduleCtx, MethodDef decomp) { foreach (Instruction instr in instrs) moduleCtx.InitMethod.Body.Instructions.Add(instr); } - } } \ No newline at end of file diff --git a/Confuser.Protections/Constants/Mode.cs b/Confuser.Protections/Constants/Mode.cs index fcdba69d5..29cacb71f 100644 --- a/Confuser.Protections/Constants/Mode.cs +++ b/Confuser.Protections/Constants/Mode.cs @@ -2,10 +2,8 @@ namespace Confuser.Protections.Constants { internal enum Mode { - Normal, Dynamic, x86 - } } \ No newline at end of file diff --git a/Confuser.Protections/Constants/NormalMode.cs b/Confuser.Protections/Constants/NormalMode.cs index 6a3e131e8..473673568 100644 --- a/Confuser.Protections/Constants/NormalMode.cs +++ b/Confuser.Protections/Constants/NormalMode.cs @@ -1,7 +1,6 @@ using System; using System.Collections.Generic; using System.Diagnostics; -using Confuser.Core; using Confuser.Core.Helpers; using Confuser.DynCipher; using dnlib.DotNet; @@ -9,7 +8,6 @@ namespace Confuser.Protections.Constants { internal class NormalMode : IEncodeMode { - public IEnumerable EmitDecrypt(MethodDef init, CEContext ctx, Local block, Local key) { for (int i = 0; i < 0x10; i++) { yield return Instruction.Create(OpCodes.Ldloc, block); @@ -53,6 +51,5 @@ public uint Encode(object data, CEContext ctx, uint id) { Debug.Assert(((ret * MathsUtils.modInv(key.Item1)) ^ key.Item2) == id); return ret; } - } } \ No newline at end of file diff --git a/Confuser.Protections/Constants/ReferenceReplacer.cs b/Confuser.Protections/Constants/ReferenceReplacer.cs index f6c0fc930..351e6e46e 100644 --- a/Confuser.Protections/Constants/ReferenceReplacer.cs +++ b/Confuser.Protections/Constants/ReferenceReplacer.cs @@ -1,6 +1,5 @@ using System; using System.Collections.Generic; -using System.Diagnostics; using Confuser.Core; using Confuser.Core.Helpers; using Confuser.Core.Services; @@ -9,7 +8,6 @@ namespace Confuser.Protections.Constants { internal class ReferenceReplacer { - public static void ReplaceReference(CEContext ctx, ProtectionParameters parameters) { foreach (var entry in ctx.ReferenceRepl) { if (parameters.GetParameter(ctx.Context, entry.Key, "cfg")) @@ -19,7 +17,7 @@ public static void ReplaceReference(CEContext ctx, ProtectionParameters paramete } } - private static void ReplaceNormal(MethodDef method, List> instrs) { + static void ReplaceNormal(MethodDef method, List> instrs) { foreach (var instr in instrs) { int i = method.Body.Instructions.IndexOf(instr.Item1); instr.Item1.OpCode = OpCodes.Ldc_I4; @@ -28,16 +26,14 @@ private static void ReplaceNormal(MethodDef method, List> instrs, CEContext ctx) { + static void ReplaceCFG(MethodDef method, List> instrs, CEContext ctx) { var graph = ControlFlowGraph.Construct(method.Body); var sequence = KeySequence.ComputeKeys(graph, ctx.Random); @@ -157,6 +153,5 @@ private static void ReplaceCFG(MethodDef method, List encryptFunc; + Action encryptFunc; public IEnumerable EmitDecrypt(MethodDef init, CEContext ctx, Local block, Local key) { StatementBlock encrypt, decrypt; @@ -58,10 +57,9 @@ public uint Encode(object data, CEContext ctx, uint id) { return (uint)encoding.expCompiled((int)id); } - private class CipherCodeGen : CILCodeGen { - - private readonly Local block; - private readonly Local key; + class CipherCodeGen : CILCodeGen { + readonly Local block; + readonly Local key; public CipherCodeGen(Local block, Local key, MethodDef init, IList instrs) : base(init, instrs) { @@ -76,17 +74,15 @@ protected override Local Var(Variable var) { return key; return base.Var(var); } - } - private class x86Encoding { - - private byte[] code; - private MethodBody codeChunk; + class x86Encoding { + byte[] code; + MethodBody codeChunk; public Func expCompiled; - private Expression expression; - private Expression inverse; + Expression expression; + Expression inverse; public MethodDef native; public void Compile(CEContext ctx) { @@ -125,7 +121,7 @@ public void Compile(CEContext ctx) { ctx.Context.CurrentModuleWriterListener.OnWriterEvent += InjectNativeCode; } - private void InjectNativeCode(object sender, ModuleWriterListenerEventArgs e) { + void InjectNativeCode(object sender, ModuleWriterListenerEventArgs e) { var writer = (ModuleWriter)sender; if (e.WriterEvent == ModuleWriterEvent.MDEndWriteMethodBodies) { codeChunk = writer.MethodBodies.Add(new MethodBody(code)); @@ -135,8 +131,6 @@ private void InjectNativeCode(object sender, ModuleWriterListenerEventArgs e) { writer.MetaData.TablesHeap.MethodTable[rid].RVA = (uint)codeChunk.RVA; } } - } - } } \ No newline at end of file diff --git a/Confuser.Protections/ControlFlow/BlockParser.cs b/Confuser.Protections/ControlFlow/BlockParser.cs index 445f6f125..6a4dafd63 100644 --- a/Confuser.Protections/ControlFlow/BlockParser.cs +++ b/Confuser.Protections/ControlFlow/BlockParser.cs @@ -2,12 +2,10 @@ using System.Collections.Generic; using System.Diagnostics; using System.Linq; -using Confuser.Core; using dnlib.DotNet.Emit; namespace Confuser.Protections.ControlFlow { internal static class BlockParser { - public static ScopeBlock ParseBody(CilBody body) { var ehScopes = new Dictionary>(); foreach (ExceptionHandler eh in body.ExceptionHandlers) { @@ -88,6 +86,5 @@ public static ScopeBlock ParseBody(CilBody body) { Debug.Assert(scopeStack.Count == 1); return root; } - } } \ No newline at end of file diff --git a/Confuser.Protections/ControlFlow/Blocks.cs b/Confuser.Protections/ControlFlow/Blocks.cs index c2401aa4c..38a35dea9 100644 --- a/Confuser.Protections/ControlFlow/Blocks.cs +++ b/Confuser.Protections/ControlFlow/Blocks.cs @@ -6,7 +6,6 @@ namespace Confuser.Protections.ControlFlow { internal abstract class BlockBase { - public BlockBase(BlockType type) { Type = type; } @@ -15,22 +14,18 @@ public BlockBase(BlockType type) { public BlockType Type { get; private set; } public abstract void ToBody(CilBody body); - } internal enum BlockType { - Normal, Try, Handler, Finally, Filter, Fault - } internal class ScopeBlock : BlockBase { - public ScopeBlock(BlockType type, ExceptionHandler handler) : base(type) { Handler = handler; @@ -90,11 +85,9 @@ public override void ToBody(CilBody body) { foreach (BlockBase block in Children) block.ToBody(body); } - } internal class InstrBlock : BlockBase { - public InstrBlock() : base(BlockType.Normal) { Instructions = new List(); @@ -113,6 +106,5 @@ public override void ToBody(CilBody body) { foreach (Instruction instr in Instructions) body.Instructions.Add(instr); } - } } \ No newline at end of file diff --git a/Confuser.Protections/ControlFlow/CFContext.cs b/Confuser.Protections/ControlFlow/CFContext.cs index 218f64ebe..f9961efb6 100644 --- a/Confuser.Protections/ControlFlow/CFContext.cs +++ b/Confuser.Protections/ControlFlow/CFContext.cs @@ -8,22 +8,17 @@ namespace Confuser.Protections.ControlFlow { internal enum CFType { - Switch, - Jump, - + Jump } internal enum PredicateType { - Normal, Expression, - x86, - + x86 } internal class CFContext { - public ConfuserContext Context; public int Depth; public IDynCipherService DynCipher; @@ -103,6 +98,5 @@ public void AddJunk(IList instrs) { break; } } - } } \ No newline at end of file diff --git a/Confuser.Protections/ControlFlow/ControlFlowPhase.cs b/Confuser.Protections/ControlFlow/ControlFlowPhase.cs index 939e5028a..41a37362e 100644 --- a/Confuser.Protections/ControlFlow/ControlFlowPhase.cs +++ b/Confuser.Protections/ControlFlow/ControlFlowPhase.cs @@ -11,9 +11,8 @@ namespace Confuser.Protections.ControlFlow { internal class ControlFlowPhase : ProtectionPhase { - - private static readonly JumpMangler Jump = new JumpMangler(); - private static readonly SwitchMangler Switch = new SwitchMangler(); + static readonly JumpMangler Jump = new JumpMangler(); + static readonly SwitchMangler Switch = new SwitchMangler(); public ControlFlowPhase(ControlFlowProtection parent) : base(parent) { } @@ -26,7 +25,7 @@ public override string Name { get { return "Control flow mangling"; } } - private static CFContext ParseParameters(MethodDef method, ConfuserContext context, ProtectionParameters parameters, RandomGenerator random, bool disableOpti) { + static CFContext ParseParameters(MethodDef method, ConfuserContext context, ProtectionParameters parameters, RandomGenerator random, bool disableOpti) { var ret = new CFContext(); ret.Type = parameters.GetParameter(context, method, "type", CFType.Switch); ret.Predicate = parameters.GetParameter(context, method, "predicate", PredicateType.Normal); @@ -50,7 +49,7 @@ private static CFContext ParseParameters(MethodDef method, ConfuserContext conte return ret; } - private static bool DisabledOptimization(ModuleDef module) { + static bool DisabledOptimization(ModuleDef module) { bool disableOpti = false; CustomAttribute debugAttr = module.Assembly.CustomAttributes.Find("System.Diagnostics.DebuggableAttribute"); if (debugAttr != null) { @@ -80,13 +79,13 @@ protected override void Execute(ConfuserContext context, ProtectionParameters pa } } - private static ManglerBase GetMangler(CFType type) { + static ManglerBase GetMangler(CFType type) { if (type == CFType.Switch) return Switch; return Jump; } - private void ProcessMethod(CilBody body, CFContext ctx) { + void ProcessMethod(CilBody body, CFContext ctx) { uint maxStack; if (!MaxStackCalculator.GetMaxStack(body.Instructions, body.ExceptionHandlers, out maxStack)) { ctx.Context.Logger.Error("Failed to calcuate maxstack."); @@ -107,6 +106,5 @@ private void ProcessMethod(CilBody body, CFContext ctx) { } body.KeepOldMaxStack = true; } - } } \ No newline at end of file diff --git a/Confuser.Protections/ControlFlow/ControlFlowProtection.cs b/Confuser.Protections/ControlFlow/ControlFlowProtection.cs index 71289c87c..8a58222a1 100644 --- a/Confuser.Protections/ControlFlow/ControlFlowProtection.cs +++ b/Confuser.Protections/ControlFlow/ControlFlowProtection.cs @@ -5,13 +5,10 @@ namespace Confuser.Protections { public interface IControlFlowService { - void ExcludeMethod(ConfuserContext context, MethodDef method); - } internal class ControlFlowProtection : Protection, IControlFlowService { - public const string _Id = "ctrl flow"; public const string _FullId = "Ki.ControlFlow"; public const string _ServiceId = "Ki.ControlFlow"; @@ -47,6 +44,5 @@ protected override void Initialize(ConfuserContext context) { protected override void PopulatePipeline(ProtectionPipeline pipeline) { pipeline.InsertPreStage(PipelineStage.OptimizeMethods, new ControlFlowPhase(this)); } - } } \ No newline at end of file diff --git a/Confuser.Protections/ControlFlow/ExpressionPredicate.cs b/Confuser.Protections/ControlFlow/ExpressionPredicate.cs index 191c5bd7a..d9c7d68c5 100644 --- a/Confuser.Protections/ControlFlow/ExpressionPredicate.cs +++ b/Confuser.Protections/ControlFlow/ExpressionPredicate.cs @@ -1,21 +1,19 @@ using System; using System.Collections.Generic; -using Confuser.Core; using Confuser.DynCipher.AST; using Confuser.DynCipher.Generation; using dnlib.DotNet.Emit; namespace Confuser.Protections.ControlFlow { internal class ExpressionPredicate : IPredicate { + readonly CFContext ctx; + Func expCompiled; + Expression expression; - private readonly CFContext ctx; - private Func expCompiled; - private Expression expression; - - private bool inited; - private List invCompiled; - private Expression inverse; - private Local stateVar; + bool inited; + List invCompiled; + Expression inverse; + Local stateVar; public ExpressionPredicate(CFContext ctx) { this.ctx = ctx; @@ -41,7 +39,7 @@ public int GetSwitchKey(int key) { return expCompiled(key); } - private void Compile(CilBody body) { + void Compile(CilBody body) { var var = new Variable("{VAR}"); var result = new Variable("{RESULT}"); @@ -59,9 +57,8 @@ private void Compile(CilBody body) { body.MaxStack += (ushort)ctx.Depth; } - private class CodeGen : CILCodeGen { - - private readonly Local state; + class CodeGen : CILCodeGen { + readonly Local state; public CodeGen(Local state, CFContext ctx, IList instrs) : base(ctx.Method, instrs) { @@ -73,8 +70,6 @@ protected override Local Var(Variable var) { return state; return base.Var(var); } - } - } } \ No newline at end of file diff --git a/Confuser.Protections/ControlFlow/IPredicate.cs b/Confuser.Protections/ControlFlow/IPredicate.cs index ea9166911..4dc1152fe 100644 --- a/Confuser.Protections/ControlFlow/IPredicate.cs +++ b/Confuser.Protections/ControlFlow/IPredicate.cs @@ -4,10 +4,8 @@ namespace Confuser.Protections.ControlFlow { internal interface IPredicate { - void Init(CilBody body); void EmitSwitchLoad(IList instrs); int GetSwitchKey(int key); - } } \ No newline at end of file diff --git a/Confuser.Protections/ControlFlow/JumpMangler.cs b/Confuser.Protections/ControlFlow/JumpMangler.cs index 67f36b8c1..dbb72112a 100644 --- a/Confuser.Protections/ControlFlow/JumpMangler.cs +++ b/Confuser.Protections/ControlFlow/JumpMangler.cs @@ -5,8 +5,7 @@ namespace Confuser.Protections.ControlFlow { internal class JumpMangler : ManglerBase { - - private LinkedList SpiltFragments(InstrBlock block, CFContext ctx) { + LinkedList SpiltFragments(InstrBlock block, CFContext ctx) { var fragments = new LinkedList(); var currentFragment = new List(); @@ -92,6 +91,5 @@ public override void Mangle(CilBody body, ScopeBlock root, CFContext ctx) { .Concat(last).ToList(); } } - } } \ No newline at end of file diff --git a/Confuser.Protections/ControlFlow/ManglerBase.cs b/Confuser.Protections/ControlFlow/ManglerBase.cs index 7802ba1ab..8e42e29f3 100644 --- a/Confuser.Protections/ControlFlow/ManglerBase.cs +++ b/Confuser.Protections/ControlFlow/ManglerBase.cs @@ -4,7 +4,6 @@ namespace Confuser.Protections.ControlFlow { internal abstract class ManglerBase { - protected static IEnumerable GetAllBlocks(ScopeBlock scope) { foreach (BlockBase child in scope.Children) { if (child is InstrBlock) @@ -17,6 +16,5 @@ protected static IEnumerable GetAllBlocks(ScopeBlock scope) { } public abstract void Mangle(CilBody body, ScopeBlock root, CFContext ctx); - } } \ No newline at end of file diff --git a/Confuser.Protections/ControlFlow/NormalPredicate.cs b/Confuser.Protections/ControlFlow/NormalPredicate.cs index b0da20bb1..84b808e62 100644 --- a/Confuser.Protections/ControlFlow/NormalPredicate.cs +++ b/Confuser.Protections/ControlFlow/NormalPredicate.cs @@ -4,10 +4,9 @@ namespace Confuser.Protections.ControlFlow { internal class NormalPredicate : IPredicate { - - private readonly CFContext ctx; - private bool inited; - private int xorKey; + readonly CFContext ctx; + bool inited; + int xorKey; public NormalPredicate(CFContext ctx) { this.ctx = ctx; @@ -29,6 +28,5 @@ public void EmitSwitchLoad(IList instrs) { public int GetSwitchKey(int key) { return key ^ xorKey; } - } } \ No newline at end of file diff --git a/Confuser.Protections/ControlFlow/SwitchMangler.cs b/Confuser.Protections/ControlFlow/SwitchMangler.cs index 5a1ffe791..175224586 100644 --- a/Confuser.Protections/ControlFlow/SwitchMangler.cs +++ b/Confuser.Protections/ControlFlow/SwitchMangler.cs @@ -7,8 +7,7 @@ namespace Confuser.Protections.ControlFlow { internal class SwitchMangler : ManglerBase { - - private LinkedList SpiltStatements(InstrBlock block, MethodTrace trace, CFContext ctx) { + LinkedList SpiltStatements(InstrBlock block, MethodTrace trace, CFContext ctx) { var statements = new LinkedList(); var currentStatement = new List(); @@ -31,7 +30,7 @@ private LinkedList SpiltStatements(InstrBlock block, MethodTrace return statements; } - private static OpCode InverseBranch(OpCode opCode) { + static OpCode InverseBranch(OpCode opCode) { switch (opCode.Code) { case Code.Bge: return OpCodes.Blt; @@ -221,6 +220,5 @@ public override void Mangle(CilBody body, ScopeBlock root, CFContext ctx) { block.Instructions.AddRange(last); } } - } } \ No newline at end of file diff --git a/Confuser.Protections/ControlFlow/x86Predicate.cs b/Confuser.Protections/ControlFlow/x86Predicate.cs index b74631305..ed55790ff 100644 --- a/Confuser.Protections/ControlFlow/x86Predicate.cs +++ b/Confuser.Protections/ControlFlow/x86Predicate.cs @@ -13,12 +13,11 @@ namespace Confuser.Protections.ControlFlow { internal class x86Predicate : IPredicate { + static readonly object Encoding = new object(); + readonly CFContext ctx; + x86Encoding encoding; - private static readonly object Encoding = new object(); - private readonly CFContext ctx; - private x86Encoding encoding; - - private bool inited; + bool inited; public x86Predicate(CFContext ctx) { this.ctx = ctx; @@ -46,14 +45,13 @@ public int GetSwitchKey(int key) { return encoding.expCompiled(key); } - private class x86Encoding { - - private byte[] code; - private MethodBody codeChunk; + class x86Encoding { + byte[] code; + MethodBody codeChunk; public Func expCompiled; - private Expression expression; - private Expression inverse; + Expression expression; + Expression inverse; public MethodDef native; public void Compile(CFContext ctx) { @@ -93,7 +91,7 @@ public void Compile(CFContext ctx) { ctx.Context.CurrentModuleWriterListener.OnWriterEvent += InjectNativeCode; } - private void InjectNativeCode(object sender, ModuleWriterListenerEventArgs e) { + void InjectNativeCode(object sender, ModuleWriterListenerEventArgs e) { var writer = (ModuleWriter)sender; if (e.WriterEvent == ModuleWriterEvent.MDEndWriteMethodBodies) { codeChunk = writer.MethodBodies.Add(new MethodBody(code)); @@ -103,8 +101,6 @@ private void InjectNativeCode(object sender, ModuleWriterListenerEventArgs e) { writer.MetaData.TablesHeap.MethodTable[rid].RVA = (uint)codeChunk.RVA; } } - } - } } \ No newline at end of file diff --git a/Confuser.Protections/InvalidMetadataProtection.cs b/Confuser.Protections/InvalidMetadataProtection.cs index aadc35fce..df55d47ca 100644 --- a/Confuser.Protections/InvalidMetadataProtection.cs +++ b/Confuser.Protections/InvalidMetadataProtection.cs @@ -9,7 +9,6 @@ namespace Confuser.Protections { internal class InvalidMetadataProtection : Protection { - public const string _Id = "invalid metadata"; public const string _FullId = "Ki.InvalidMD"; @@ -41,9 +40,8 @@ protected override void PopulatePipeline(ProtectionPipeline pipeline) { pipeline.InsertPostStage(PipelineStage.BeginModule, new InvalidMDPhase(this)); } - private class InvalidMDPhase : ProtectionPhase { - - private RandomGenerator random; + class InvalidMDPhase : ProtectionPhase { + RandomGenerator random; public InvalidMDPhase(InvalidMetadataProtection parent) : base(parent) { } @@ -63,7 +61,7 @@ protected override void Execute(ConfuserContext context, ProtectionParameters pa } } - private void Randomize(MDTable table) where T : IRawRow { + void Randomize(MDTable table) where T : IRawRow { List rows = table.ToList(); random.Shuffle(rows); table.Reset(); @@ -71,7 +69,7 @@ private void Randomize(MDTable table) where T : IRawRow { table.Add(row); } - private void OnWriterEvent(object sender, ModuleWriterListenerEventArgs e) { + void OnWriterEvent(object sender, ModuleWriterListenerEventArgs e) { var writer = (ModuleWriter)sender; if (e.WriterEvent == ModuleWriterEvent.MDEndCreateTables) { // These hurts reflection @@ -131,13 +129,11 @@ private void OnWriterEvent(object sender, ModuleWriterListenerEventArgs e) { */ } } - } - private class RawHeap : HeapBase { - - private readonly byte[] content; - private readonly string name; + class RawHeap : HeapBase { + readonly byte[] content; + readonly string name; public RawHeap(string name, byte[] content) { this.name = name; @@ -155,8 +151,6 @@ public override uint GetRawLength() { protected override void WriteToImpl(BinaryWriter writer) { writer.Write(content); } - } - } } \ No newline at end of file diff --git a/Confuser.Protections/ReferenceProxy/ExpressionEncoding.cs b/Confuser.Protections/ReferenceProxy/ExpressionEncoding.cs index 53ca5cb6a..07a0719a7 100644 --- a/Confuser.Protections/ReferenceProxy/ExpressionEncoding.cs +++ b/Confuser.Protections/ReferenceProxy/ExpressionEncoding.cs @@ -1,6 +1,5 @@ using System; using System.Collections.Generic; -using Confuser.Core; using Confuser.DynCipher.AST; using Confuser.DynCipher.Generation; using dnlib.DotNet; @@ -8,8 +7,7 @@ namespace Confuser.Protections.ReferenceProxy { internal class ExpressionEncoding : IRPEncoding { - - private readonly Dictionary>> keys = new Dictionary>>(); + readonly Dictionary>> keys = new Dictionary>>(); public Instruction[] EmitDecode(MethodDef init, RPContext ctx, Instruction[] arg) { Tuple> key = GetKey(ctx, init); @@ -25,7 +23,7 @@ public int Encode(MethodDef init, RPContext ctx, int value) { return key.Item2(value); } - private void Compile(RPContext ctx, CilBody body, out Func expCompiled, out Expression inverse) { + void Compile(RPContext ctx, CilBody body, out Func expCompiled, out Expression inverse) { var var = new Variable("{VAR}"); var result = new Variable("{RESULT}"); @@ -40,7 +38,7 @@ private void Compile(RPContext ctx, CilBody body, out Func expCompiled .Compile>(); } - private Tuple> GetKey(RPContext ctx, MethodDef init) { + Tuple> GetKey(RPContext ctx, MethodDef init) { Tuple> ret; if (!keys.TryGetValue(init, out ret)) { Func keyFunc; @@ -51,9 +49,8 @@ private Tuple> GetKey(RPContext ctx, MethodDef init) return ret; } - private class CodeGen : CILCodeGen { - - private readonly Instruction[] arg; + class CodeGen : CILCodeGen { + readonly Instruction[] arg; public CodeGen(Instruction[] arg, MethodDef method, IList instrs) : base(method, instrs) { @@ -63,13 +60,11 @@ public CodeGen(Instruction[] arg, MethodDef method, IList instrs) protected override void LoadVar(Variable var) { if (var.Name == "{RESULT}") { foreach (Instruction instr in arg) - base.Emit(instr); + Emit(instr); } else base.LoadVar(var); } - } - } } \ No newline at end of file diff --git a/Confuser.Protections/ReferenceProxy/IRPEncoding.cs b/Confuser.Protections/ReferenceProxy/IRPEncoding.cs index 4f7f79178..0c16e6270 100644 --- a/Confuser.Protections/ReferenceProxy/IRPEncoding.cs +++ b/Confuser.Protections/ReferenceProxy/IRPEncoding.cs @@ -4,9 +4,7 @@ namespace Confuser.Protections.ReferenceProxy { internal interface IRPEncoding { - Instruction[] EmitDecode(MethodDef init, RPContext ctx, Instruction[] arg); int Encode(MethodDef init, RPContext ctx, int value); - } } \ No newline at end of file diff --git a/Confuser.Protections/ReferenceProxy/MildMode.cs b/Confuser.Protections/ReferenceProxy/MildMode.cs index 8cc6fddf7..ef5944f48 100644 --- a/Confuser.Protections/ReferenceProxy/MildMode.cs +++ b/Confuser.Protections/ReferenceProxy/MildMode.cs @@ -6,9 +6,8 @@ namespace Confuser.Protections.ReferenceProxy { internal class MildMode : RPMode { - // proxy method, { opCode, calling type, target method} - private readonly Dictionary, MethodDef> proxies = new Dictionary, MethodDef>(); + readonly Dictionary, MethodDef> proxies = new Dictionary, MethodDef>(); public override void ProcessCall(RPContext ctx, int instrIndex) { Instruction invoke = ctx.Body.Instructions[instrIndex]; @@ -68,6 +67,5 @@ public override void ProcessCall(RPContext ctx, int instrIndex) { } public override void Finalize(RPContext ctx) { } - } } \ No newline at end of file diff --git a/Confuser.Protections/ReferenceProxy/NormalEncoding.cs b/Confuser.Protections/ReferenceProxy/NormalEncoding.cs index c7b44ee6f..addf48a80 100644 --- a/Confuser.Protections/ReferenceProxy/NormalEncoding.cs +++ b/Confuser.Protections/ReferenceProxy/NormalEncoding.cs @@ -1,6 +1,5 @@ using System; using System.Collections.Generic; -using Confuser.Core; using Confuser.Core.Services; using Confuser.DynCipher; using dnlib.DotNet; @@ -8,8 +7,7 @@ namespace Confuser.Protections.ReferenceProxy { internal class NormalEncoding : IRPEncoding { - - private readonly Dictionary> keys = new Dictionary>(); + readonly Dictionary> keys = new Dictionary>(); public Instruction[] EmitDecode(MethodDef init, RPContext ctx, Instruction[] arg) { Tuple key = GetKey(ctx.Random, init); @@ -31,7 +29,7 @@ public int Encode(MethodDef init, RPContext ctx, int value) { return value * key.Item2; } - private Tuple GetKey(RandomGenerator random, MethodDef init) { + Tuple GetKey(RandomGenerator random, MethodDef init) { Tuple ret; if (!keys.TryGetValue(init, out ret)) { int key = random.NextInt32() | 1; @@ -39,6 +37,5 @@ private Tuple GetKey(RandomGenerator random, MethodDef init) { } return ret; } - } } \ No newline at end of file diff --git a/Confuser.Protections/ReferenceProxy/RPContext.cs b/Confuser.Protections/ReferenceProxy/RPContext.cs index 82358289b..a7f88d45a 100644 --- a/Confuser.Protections/ReferenceProxy/RPContext.cs +++ b/Confuser.Protections/ReferenceProxy/RPContext.cs @@ -9,23 +9,18 @@ namespace Confuser.Protections.ReferenceProxy { internal enum Mode { - Mild, Strong, Ftn - } internal enum EncodingType { - Normal, Expression, x86 - } internal class RPContext { - public CilBody Body; public HashSet BranchTargets; public ConfuserContext Context; @@ -45,6 +40,5 @@ internal class RPContext { public INameService Name; public RandomGenerator Random; public bool TypeErasure; - } } \ No newline at end of file diff --git a/Confuser.Protections/ReferenceProxy/RPMode.cs b/Confuser.Protections/ReferenceProxy/RPMode.cs index f31bbf5c7..ab34ebe67 100644 --- a/Confuser.Protections/ReferenceProxy/RPMode.cs +++ b/Confuser.Protections/ReferenceProxy/RPMode.cs @@ -9,11 +9,10 @@ namespace Confuser.Protections.ReferenceProxy { internal abstract class RPMode { - public abstract void ProcessCall(RPContext ctx, int instrIndex); public abstract void Finalize(RPContext ctx); - private static ITypeDefOrRef Import(RPContext ctx, TypeDef typeDef) { + static ITypeDefOrRef Import(RPContext ctx, TypeDef typeDef) { ITypeDefOrRef retTypeRef = new Importer(ctx.Module, ImporterOptions.TryToUseTypeDefs).Import(typeDef); if (typeDef.Module != ctx.Module && ctx.Context.Modules.Contains((ModuleDefMD)typeDef.Module)) ctx.Name.AddReference(typeDef, new TypeRefReference((TypeRef)retTypeRef, typeDef)); @@ -89,6 +88,5 @@ protected static TypeDef GetDelegateType(RPContext ctx, MethodSig sig) { ctx.Delegates[sig] = ret; return ret; } - } } \ No newline at end of file diff --git a/Confuser.Protections/ReferenceProxy/ReferenceProxyPhase.cs b/Confuser.Protections/ReferenceProxy/ReferenceProxyPhase.cs index 5bd18d5e9..efbd4bf85 100644 --- a/Confuser.Protections/ReferenceProxy/ReferenceProxyPhase.cs +++ b/Confuser.Protections/ReferenceProxy/ReferenceProxyPhase.cs @@ -11,7 +11,6 @@ namespace Confuser.Protections.ReferenceProxy { internal class ReferenceProxyPhase : ProtectionPhase { - public ReferenceProxyPhase(ReferenceProxyProtection parent) : base(parent) { } @@ -23,7 +22,7 @@ public override string Name { get { return "Encoding reference proxies"; } } - private static RPContext ParseParameters(MethodDef method, ConfuserContext context, ProtectionParameters parameters, RPStore store) { + static RPContext ParseParameters(MethodDef method, ConfuserContext context, ProtectionParameters parameters, RPStore store) { var ret = new RPContext(); ret.Mode = parameters.GetParameter(context, method, "mode", Mode.Mild); ret.Encoding = parameters.GetParameter(context, method, "encoding", EncodingType.Normal); @@ -81,7 +80,7 @@ private static RPContext ParseParameters(MethodDef method, ConfuserContext conte return ret; } - private static RPContext ParseParameters(ModuleDef module, ConfuserContext context, ProtectionParameters parameters, RPStore store) { + static RPContext ParseParameters(ModuleDef module, ConfuserContext context, ProtectionParameters parameters, RPStore store) { var ret = new RPContext(); ret.Depth = parameters.GetParameter(context, module, "depth", 3); ret.InitCount = parameters.GetParameter(context, module, "initCount", 0x10); @@ -118,7 +117,7 @@ protected override void Execute(ConfuserContext context, ProtectionParameters pa store.strong.Finalize(ctx); } - private void ProcessMethod(RPContext ctx) { + void ProcessMethod(RPContext ctx) { for (int i = 0; i < ctx.Body.Instructions.Count; i++) { Instruction instr = ctx.Body.Instructions[i]; if (instr.OpCode.Code == Code.Call || instr.OpCode.Code == Code.Callvirt || instr.OpCode.Code == Code.Newobj) { @@ -151,8 +150,7 @@ private void ProcessMethod(RPContext ctx) { } } - private class RPStore { - + class RPStore { public readonly Dictionary delegates = new Dictionary(new MethodSigComparer()); public ExpressionEncoding expression; public MildMode mild; @@ -162,8 +160,7 @@ private class RPStore { public StrongMode strong; public x86Encoding x86; - private class MethodSigComparer : IEqualityComparer { - + class MethodSigComparer : IEqualityComparer { public bool Equals(MethodSig x, MethodSig y) { return new SigComparer().Equals(x, y); } @@ -171,10 +168,7 @@ public bool Equals(MethodSig x, MethodSig y) { public int GetHashCode(MethodSig obj) { return new SigComparer().GetHashCode(obj); } - } - } - } } \ No newline at end of file diff --git a/Confuser.Protections/ReferenceProxy/ReferenceProxyProtection.cs b/Confuser.Protections/ReferenceProxy/ReferenceProxyProtection.cs index fb31e9813..37ebc2695 100644 --- a/Confuser.Protections/ReferenceProxy/ReferenceProxyProtection.cs +++ b/Confuser.Protections/ReferenceProxy/ReferenceProxyProtection.cs @@ -5,15 +5,12 @@ namespace Confuser.Protections { public interface IReferenceProxyService { - void ExcludeMethod(ConfuserContext context, MethodDef method); - } [AfterProtection("Ki.AntiDebug", "Ki.AntiDump")] [BeforeProtection("Ki.ControlFlow")] internal class ReferenceProxyProtection : Protection, IReferenceProxyService { - public const string _Id = "ref proxy"; public const string _FullId = "Ki.RefProxy"; public const string _ServiceId = "Ki.RefProxy"; @@ -49,6 +46,5 @@ protected override void Initialize(ConfuserContext context) { protected override void PopulatePipeline(ProtectionPipeline pipeline) { pipeline.InsertPreStage(PipelineStage.ProcessModule, new ReferenceProxyPhase(this)); } - } } \ No newline at end of file diff --git a/Confuser.Protections/ReferenceProxy/StrongMode.cs b/Confuser.Protections/ReferenceProxy/StrongMode.cs index 846fa1623..affd55b9b 100644 --- a/Confuser.Protections/ReferenceProxy/StrongMode.cs +++ b/Confuser.Protections/ReferenceProxy/StrongMode.cs @@ -14,16 +14,15 @@ namespace Confuser.Protections.ReferenceProxy { internal class StrongMode : RPMode { - // { invoke opCode, invoke target, encoding}, { proxy field, bridge method } - private readonly List fieldDescs = new List(); - private readonly Dictionary, Tuple> fields = new Dictionary, Tuple>(); + readonly List fieldDescs = new List(); + readonly Dictionary, Tuple> fields = new Dictionary, Tuple>(); - private readonly Dictionary inits = new Dictionary(); - private RPContext encodeCtx; - private Tuple>[] keyAttrs; + readonly Dictionary inits = new Dictionary(); + RPContext encodeCtx; + Tuple>[] keyAttrs; - private static int? TraceBeginning(RPContext ctx, int index, int argCount) { + static int? TraceBeginning(RPContext ctx, int index, int argCount) { if (ctx.BranchTargets.Contains(ctx.Body.Instructions[index])) return null; @@ -85,7 +84,7 @@ public override void ProcessCall(RPContext ctx, int instrIndex) { } } - private void ProcessBridge(RPContext ctx, int instrIndex) { + void ProcessBridge(RPContext ctx, int instrIndex) { Instruction instr = ctx.Body.Instructions[instrIndex]; var target = (IMethod)instr.Operand; @@ -130,7 +129,7 @@ private void ProcessBridge(RPContext ctx, int instrIndex) { instr.Operand = proxy.Item2; } - private void ProcessInvoke(RPContext ctx, int instrIndex, int argBeginIndex) { + void ProcessInvoke(RPContext ctx, int instrIndex, int argBeginIndex) { Instruction instr = ctx.Body.Instructions[instrIndex]; var target = (IMethod)instr.Operand; @@ -164,7 +163,7 @@ private void ProcessInvoke(RPContext ctx, int instrIndex, int argBeginIndex) { } } - private MethodDef CreateBridge(RPContext ctx, TypeDef delegateType, FieldDef field, MethodSig sig) { + MethodDef CreateBridge(RPContext ctx, TypeDef delegateType, FieldDef field, MethodSig sig) { var method = new MethodDefUser(ctx.Name.RandomName(), sig); method.Attributes = MethodAttributes.PrivateScope | MethodAttributes.Static; method.ImplAttributes = MethodImplAttributes.Managed | MethodImplAttributes.IL; @@ -184,7 +183,7 @@ private MethodDef CreateBridge(RPContext ctx, TypeDef delegateType, FieldDef fie return method; } - private FieldDef CreateField(RPContext ctx, TypeDef delegateType) { + FieldDef CreateField(RPContext ctx, TypeDef delegateType) { // Details will be filled in during metadata writing TypeDef randomType; do { @@ -203,7 +202,7 @@ private FieldDef CreateField(RPContext ctx, TypeDef delegateType) { return field; } - private TypeDef GetKeyAttr(RPContext ctx) { + TypeDef GetKeyAttr(RPContext ctx) { if (keyAttrs == null) keyAttrs = new Tuple>[0x10]; @@ -249,7 +248,7 @@ private TypeDef GetKeyAttr(RPContext ctx) { return keyAttrs[index].Item1; } - private InitMethodDesc GetInitMethod(RPContext ctx, IRPEncoding encoding) { + InitMethodDesc GetInitMethod(RPContext ctx, IRPEncoding encoding) { InitMethodDesc[] initDescs; if (!inits.TryGetValue(encoding, out initDescs)) inits[encoding] = initDescs = new InitMethodDesc[ctx.InitCount]; @@ -328,7 +327,7 @@ public override void Finalize(RPContext ctx) { encodeCtx = ctx; } - private void EncodeField(object sender, ModuleWriterListenerEventArgs e) { + void EncodeField(object sender, ModuleWriterListenerEventArgs e) { var writer = (ModuleWriter)sender; if (e.WriterEvent == ModuleWriterEvent.MDMemberDefRidsAllocated) { Dictionary> keyFuncs = keyAttrs @@ -379,9 +378,8 @@ private void EncodeField(object sender, ModuleWriterListenerEventArgs e) { } } - private class CodeGen : CILCodeGen { - - private readonly Instruction[] arg; + class CodeGen : CILCodeGen { + readonly Instruction[] arg; public CodeGen(Instruction[] arg, MethodDef method, IList instrs) : base(method, instrs) { @@ -391,33 +389,27 @@ public CodeGen(Instruction[] arg, MethodDef method, IList instrs) protected override void LoadVar(Variable var) { if (var.Name == "{RESULT}") { foreach (Instruction instr in arg) - base.Emit(instr); + Emit(instr); } else base.LoadVar(var); } - } - private class FieldDesc { - + class FieldDesc { public FieldDef Field; public InitMethodDesc InitDesc; public IMethod Method; public Code OpCode; public byte OpKey; - } - private class InitMethodDesc { - + class InitMethodDesc { public IRPEncoding Encoding; public MethodDef Method; public int OpCodeIndex; public int[] TokenByteOrder; public int[] TokenNameOrder; - } - } } \ No newline at end of file diff --git a/Confuser.Protections/ReferenceProxy/x86Encoding.cs b/Confuser.Protections/ReferenceProxy/x86Encoding.cs index 5a3396a49..0a84b4e19 100644 --- a/Confuser.Protections/ReferenceProxy/x86Encoding.cs +++ b/Confuser.Protections/ReferenceProxy/x86Encoding.cs @@ -13,10 +13,9 @@ namespace Confuser.Protections.ReferenceProxy { internal class x86Encoding : IRPEncoding { - - private readonly Dictionary>> keys = new Dictionary>>(); - private readonly List> nativeCodes = new List>(); - private bool addedHandler; + readonly Dictionary>> keys = new Dictionary>>(); + readonly List> nativeCodes = new List>(); + bool addedHandler; public Instruction[] EmitDecode(MethodDef init, RPContext ctx, Instruction[] arg) { Tuple> key = GetKey(ctx, init); @@ -32,7 +31,7 @@ public int Encode(MethodDef init, RPContext ctx, int value) { return key.Item2(value); } - private void Compile(RPContext ctx, out Func expCompiled, out MethodDef native) { + void Compile(RPContext ctx, out Func expCompiled, out MethodDef native) { var var = new Variable("{VAR}"); var result = new Variable("{RESULT}"); @@ -69,7 +68,7 @@ private void Compile(RPContext ctx, out Func expCompiled, out MethodDe } } - private void InjectNativeCode(object sender, ModuleWriterListenerEventArgs e) { + void InjectNativeCode(object sender, ModuleWriterListenerEventArgs e) { var writer = (ModuleWriter)sender; if (e.WriterEvent == ModuleWriterEvent.MDEndWriteMethodBodies) { for (int n = 0; n < nativeCodes.Count; n++) @@ -86,7 +85,7 @@ private void InjectNativeCode(object sender, ModuleWriterListenerEventArgs e) { } } - private Tuple> GetKey(RPContext ctx, MethodDef init) { + Tuple> GetKey(RPContext ctx, MethodDef init) { Tuple> ret; if (!keys.TryGetValue(init, out ret)) { Func keyFunc; @@ -97,9 +96,8 @@ private Tuple> GetKey(RPContext ctx, MethodDef init) { return ret; } - private class CodeGen : CILCodeGen { - - private readonly Instruction[] arg; + class CodeGen : CILCodeGen { + readonly Instruction[] arg; public CodeGen(Instruction[] arg, MethodDef method, IList instrs) : base(method, instrs) { @@ -109,13 +107,11 @@ public CodeGen(Instruction[] arg, MethodDef method, IList instrs) protected override void LoadVar(Variable var) { if (var.Name == "{RESULT}") { foreach (Instruction instr in arg) - base.Emit(instr); + Emit(instr); } else base.LoadVar(var); } - } - } } \ No newline at end of file diff --git a/Confuser.Protections/Resources/DynamicMode.cs b/Confuser.Protections/Resources/DynamicMode.cs index 927cdbb97..69522b6cd 100644 --- a/Confuser.Protections/Resources/DynamicMode.cs +++ b/Confuser.Protections/Resources/DynamicMode.cs @@ -1,6 +1,5 @@ using System; using System.Collections.Generic; -using Confuser.Core; using Confuser.DynCipher.AST; using Confuser.DynCipher.Generation; using dnlib.DotNet; @@ -8,8 +7,7 @@ namespace Confuser.Protections.Resources { internal class DynamicMode : IEncodeMode { - - private Action encryptFunc; + Action encryptFunc; public IEnumerable EmitDecrypt(MethodDef init, REContext ctx, Local block, Local key) { StatementBlock encrypt, decrypt; @@ -37,10 +35,9 @@ public uint[] Encrypt(uint[] data, int offset, uint[] key) { return ret; } - private class CodeGen : CILCodeGen { - - private readonly Local block; - private readonly Local key; + class CodeGen : CILCodeGen { + readonly Local block; + readonly Local key; public CodeGen(Local block, Local key, MethodDef init, IList instrs) : base(init, instrs) { @@ -55,8 +52,6 @@ protected override Local Var(Variable var) { return key; return base.Var(var); } - } - } } \ No newline at end of file diff --git a/Confuser.Protections/Resources/IEncodeMode.cs b/Confuser.Protections/Resources/IEncodeMode.cs index 26c4cb2be..5fd04c23f 100644 --- a/Confuser.Protections/Resources/IEncodeMode.cs +++ b/Confuser.Protections/Resources/IEncodeMode.cs @@ -5,9 +5,7 @@ namespace Confuser.Protections.Resources { internal interface IEncodeMode { - IEnumerable EmitDecrypt(MethodDef init, REContext ctx, Local block, Local key); uint[] Encrypt(uint[] data, int offset, uint[] key); - } } \ No newline at end of file diff --git a/Confuser.Protections/Resources/InjectPhase.cs b/Confuser.Protections/Resources/InjectPhase.cs index 45ce88d45..3446030b2 100644 --- a/Confuser.Protections/Resources/InjectPhase.cs +++ b/Confuser.Protections/Resources/InjectPhase.cs @@ -13,7 +13,6 @@ namespace Confuser.Protections.Resources { internal class InjectPhase : ProtectionPhase { - public InjectPhase(ResourceProtection parent) : base(parent) { } @@ -29,7 +28,7 @@ protected override void Execute(ConfuserContext context, ProtectionParameters pa if (parameters.Targets.Any()) { if (!UTF8String.IsNullOrEmpty(context.CurrentModule.Assembly.Culture)) { context.Logger.DebugFormat("Skipping resource encryption for satellite assembly '{0}'.", - context.CurrentModule.Assembly.FullName); + context.CurrentModule.Assembly.FullName); return; } var compression = context.Registry.GetService(); @@ -77,7 +76,7 @@ protected override void Execute(ConfuserContext context, ProtectionParameters pa } } - private void InjectHelpers(ConfuserContext context, ICompressionService compression, IRuntimeService rt, REContext moduleCtx) { + void InjectHelpers(ConfuserContext context, ICompressionService compression, IRuntimeService rt, REContext moduleCtx) { var rtName = context.Packer != null ? "Confuser.Runtime.Resource_Packer" : "Confuser.Runtime.Resource"; IEnumerable members = InjectHelper.Inject(rt.GetRuntimeType(rtName), context.CurrentModule.GlobalType, context.CurrentModule); foreach (IDnlibDef member in members) { @@ -105,7 +104,7 @@ private void InjectHelpers(ConfuserContext context, ICompressionService compress moduleCtx.Name.MarkHelper(moduleCtx.DataField, moduleCtx.Marker); } - private void MutateInitializer(REContext moduleCtx, MethodDef decomp) { + void MutateInitializer(REContext moduleCtx, MethodDef decomp) { moduleCtx.InitMethod.Body.SimplifyMacros(moduleCtx.InitMethod.Parameters); List instrs = moduleCtx.InitMethod.Body.Instructions.ToList(); for (int i = 0; i < instrs.Count; i++) { @@ -143,6 +142,5 @@ private void MutateInitializer(REContext moduleCtx, MethodDef decomp) { }); moduleCtx.Context.Registry.GetService().ExcludeMethod(moduleCtx.Context, moduleCtx.InitMethod); } - } } \ No newline at end of file diff --git a/Confuser.Protections/Resources/MDPhase.cs b/Confuser.Protections/Resources/MDPhase.cs index 9e4526de5..1bcf9c51a 100644 --- a/Confuser.Protections/Resources/MDPhase.cs +++ b/Confuser.Protections/Resources/MDPhase.cs @@ -12,9 +12,8 @@ namespace Confuser.Protections.Resources { internal class MDPhase { - - private readonly REContext ctx; - private ByteArrayChunk encryptedResource; + readonly REContext ctx; + ByteArrayChunk encryptedResource; public MDPhase(REContext ctx) { this.ctx = ctx; @@ -24,7 +23,7 @@ public void Hook() { ctx.Context.CurrentModuleWriterListener.OnWriterEvent += OnWriterEvent; } - private void OnWriterEvent(object sender, ModuleWriterListenerEventArgs e) { + void OnWriterEvent(object sender, ModuleWriterListenerEventArgs e) { var writer = (ModuleWriter)sender; if (e.WriterEvent == ModuleWriterEvent.MDBeginAddResources) { ctx.Context.CheckCancellation(); @@ -109,6 +108,5 @@ private void OnWriterEvent(object sender, ModuleWriterListenerEventArgs e) { tblHeap.FieldRVATable[writer.MetaData.GetFieldRVARid(ctx.DataField)].RVA = (uint)encryptedResource.RVA; } } - } } \ No newline at end of file diff --git a/Confuser.Protections/Resources/Mode.cs b/Confuser.Protections/Resources/Mode.cs index d8ec7cac9..f32d31386 100644 --- a/Confuser.Protections/Resources/Mode.cs +++ b/Confuser.Protections/Resources/Mode.cs @@ -2,9 +2,7 @@ namespace Confuser.Protections.Resources { internal enum Mode { - Normal, Dynamic - } } \ No newline at end of file diff --git a/Confuser.Protections/Resources/NormalMode.cs b/Confuser.Protections/Resources/NormalMode.cs index 4e37fd10f..bd37689d3 100644 --- a/Confuser.Protections/Resources/NormalMode.cs +++ b/Confuser.Protections/Resources/NormalMode.cs @@ -5,7 +5,6 @@ namespace Confuser.Protections.Resources { internal class NormalMode : IEncodeMode { - public IEnumerable EmitDecrypt(MethodDef init, REContext ctx, Local block, Local key) { for (int i = 0; i < 0x10; i++) { yield return Instruction.Create(OpCodes.Ldloc, block); @@ -27,6 +26,5 @@ public uint[] Encrypt(uint[] data, int offset, uint[] key) { ret[i] = data[i + offset] ^ key[i]; return ret; } - } } \ No newline at end of file diff --git a/Confuser.Protections/Resources/REContext.cs b/Confuser.Protections/Resources/REContext.cs index d0031a251..0166c8b38 100644 --- a/Confuser.Protections/Resources/REContext.cs +++ b/Confuser.Protections/Resources/REContext.cs @@ -7,7 +7,6 @@ namespace Confuser.Protections.Resources { internal class REContext { - public ConfuserContext Context; public FieldDef DataField; @@ -22,6 +21,5 @@ internal class REContext { public ModuleDef Module; public INameService Name; public RandomGenerator Random; - } } \ No newline at end of file diff --git a/Confuser.Protections/Resources/ResourceProtection.cs b/Confuser.Protections/Resources/ResourceProtection.cs index 53ee02604..a572bf079 100644 --- a/Confuser.Protections/Resources/ResourceProtection.cs +++ b/Confuser.Protections/Resources/ResourceProtection.cs @@ -5,7 +5,6 @@ namespace Confuser.Protections { [BeforeProtection("Ki.ControlFlow"), AfterProtection("Ki.Constants")] internal class ResourceProtection : Protection { - public const string _Id = "resources"; public const string _FullId = "Ki.Resources"; public const string _ServiceId = "Ki.Resources"; @@ -35,6 +34,5 @@ protected override void Initialize(ConfuserContext context) { } protected override void PopulatePipeline(ProtectionPipeline pipeline) { pipeline.InsertPreStage(PipelineStage.ProcessModule, new InjectPhase(this)); } - } } \ No newline at end of file diff --git a/Confuser.Renamer/AnalyzePhase.cs b/Confuser.Renamer/AnalyzePhase.cs index 038f5382b..a1549e745 100644 --- a/Confuser.Renamer/AnalyzePhase.cs +++ b/Confuser.Renamer/AnalyzePhase.cs @@ -6,7 +6,6 @@ namespace Confuser.Renamer { internal class AnalyzePhase : ProtectionPhase { - public AnalyzePhase(NameProtection parent) : base(parent) { } @@ -22,7 +21,7 @@ public override string Name { get { return "Name analysis"; } } - private void ParseParameters(IDnlibDef def, ConfuserContext context, NameService service, ProtectionParameters parameters) { + void ParseParameters(IDnlibDef def, ConfuserContext context, NameService service, ProtectionParameters parameters) { var mode = parameters.GetParameter(context, def, "mode", null); if (mode != null) service.SetRenameMode(def, mode.Value); @@ -58,14 +57,14 @@ protected override void Execute(ConfuserContext context, ProtectionParameters pa } } - private void RegisterRenamers(ConfuserContext context, NameService service) { + void RegisterRenamers(ConfuserContext context, NameService service) { bool wpf = false, caliburn = false; foreach (var module in context.Modules) foreach (var asmRef in module.GetAssemblyRefs()) { if (asmRef.Name == "WindowsBase" || asmRef.Name == "PresentationCore" || - asmRef.Name == "PresentationFramework" || asmRef.Name == "System.Xaml") { + asmRef.Name == "PresentationFramework" || asmRef.Name == "System.Xaml") { wpf = true; } else if (asmRef.Name == "Caliburn.Micro") { @@ -105,7 +104,7 @@ internal void Analyze(NameService service, ConfuserContext context, ProtectionPa renamer.Analyze(context, service, def); } - private void Analyze(NameService service, ConfuserContext context, ProtectionParameters parameters, TypeDef type) { + void Analyze(NameService service, ConfuserContext context, ProtectionParameters parameters, TypeDef type) { if (type.IsVisibleOutside() && !parameters.GetParameter(context, type, "renPublic", false)) { service.SetCanRename(type, false); } @@ -125,7 +124,7 @@ private void Analyze(NameService service, ConfuserContext context, ProtectionPar } } - private void Analyze(NameService service, ConfuserContext context, ProtectionParameters parameters, MethodDef method) { + void Analyze(NameService service, ConfuserContext context, ProtectionParameters parameters, MethodDef method) { if (method.DeclaringType.IsVisibleOutside() && (method.IsFamily || method.IsFamilyOrAssembly || method.IsPublic) && !parameters.GetParameter(context, method, "renPublic", false)) @@ -144,7 +143,7 @@ private void Analyze(NameService service, ConfuserContext context, ProtectionPar service.SetCanRename(method, false); } - private void Analyze(NameService service, ConfuserContext context, ProtectionParameters parameters, FieldDef field) { + void Analyze(NameService service, ConfuserContext context, ProtectionParameters parameters, FieldDef field) { if (field.DeclaringType.IsVisibleOutside() && (field.IsFamily || field.IsFamilyOrAssembly || field.IsPublic) && !parameters.GetParameter(context, field, "renPublic", false)) @@ -160,7 +159,7 @@ private void Analyze(NameService service, ConfuserContext context, ProtectionPar service.SetCanRename(field, false); } - private void Analyze(NameService service, ConfuserContext context, ProtectionParameters parameters, PropertyDef property) { + void Analyze(NameService service, ConfuserContext context, ProtectionParameters parameters, PropertyDef property) { if (property.DeclaringType.IsVisibleOutside() && !parameters.GetParameter(context, property, "renPublic", false)) service.SetCanRename(property, false); @@ -178,7 +177,7 @@ private void Analyze(NameService service, ConfuserContext context, ProtectionPar service.SetCanRename(property, false); } - private void Analyze(NameService service, ConfuserContext context, ProtectionParameters parameters, EventDef evt) { + void Analyze(NameService service, ConfuserContext context, ProtectionParameters parameters, EventDef evt) { if (evt.DeclaringType.IsVisibleOutside() && !parameters.GetParameter(context, evt, "renPublic", false)) service.SetCanRename(evt, false); @@ -186,6 +185,5 @@ private void Analyze(NameService service, ConfuserContext context, ProtectionPar else if (evt.IsRuntimeSpecialName || evt.IsSpecialName) service.SetCanRename(evt, false); } - } } \ No newline at end of file diff --git a/Confuser.Renamer/Analyzers/CaliburnAnalyzer.cs b/Confuser.Renamer/Analyzers/CaliburnAnalyzer.cs index acf53ebdd..527fe71c0 100644 --- a/Confuser.Renamer/Analyzers/CaliburnAnalyzer.cs +++ b/Confuser.Renamer/Analyzers/CaliburnAnalyzer.cs @@ -1,12 +1,10 @@ using System; -using System.Text.RegularExpressions; using Confuser.Core; using Confuser.Renamer.BAML; using dnlib.DotNet; namespace Confuser.Renamer.Analyzers { internal class CaliburnAnalyzer : IRenamer { - public CaliburnAnalyzer(WPFAnalyzer wpfAnalyzer) { wpfAnalyzer.AnalyzeBAMLElement += AnalyzeBAMLElement; } @@ -34,7 +32,7 @@ public void Analyze(ConfuserContext context, INameService service, IDnlibDef def } } - private void AnalyzeBAMLElement(BAMLAnalyzer analyzer, BamlElement elem) { + void AnalyzeBAMLElement(BAMLAnalyzer analyzer, BamlElement elem) { foreach (var rec in elem.Body) { var prop = rec as PropertyWithConverterRecord; if (prop == null) @@ -58,7 +56,7 @@ private void AnalyzeBAMLElement(BAMLAnalyzer analyzer, BamlElement elem) { } } - private void AnalyzeMessageAttach(BAMLAnalyzer analyzer, Tuple attr, string value) { + void AnalyzeMessageAttach(BAMLAnalyzer analyzer, Tuple attr, string value) { if (attr.Item2 == null) return; var attrDeclType = analyzer.ResolveType(attr.Item2.OwnerTypeId); @@ -85,7 +83,7 @@ private void AnalyzeMessageAttach(BAMLAnalyzer analyzer, Tuple attr, string value) { + void AnalyzeAutoBind(BAMLAnalyzer analyzer, Tuple attr, string value) { if (!(attr.Item1 is PropertyDef) || ((PropertyDef)attr.Item1).DeclaringType.FullName != "System.Windows.FrameworkElement") return; @@ -95,9 +93,9 @@ private void AnalyzeAutoBind(BAMLAnalyzer analyzer, Tuple attr, string value) { + void AnalyzeActionMessage(BAMLAnalyzer analyzer, Tuple attr, string value) { if (attr.Item2 == null) - return; + return; var attrDeclType = analyzer.ResolveType(attr.Item2.OwnerTypeId); if (attrDeclType.FullName != "Caliburn.Micro.ActionMessage") return; @@ -115,4 +113,4 @@ public void PostRename(ConfuserContext context, INameService service, IDnlibDef // } } -} +} \ No newline at end of file diff --git a/Confuser.Renamer/Analyzers/InterReferenceAnalyzer.cs b/Confuser.Renamer/Analyzers/InterReferenceAnalyzer.cs index 06b5b9033..5d2a0f179 100644 --- a/Confuser.Renamer/Analyzers/InterReferenceAnalyzer.cs +++ b/Confuser.Renamer/Analyzers/InterReferenceAnalyzer.cs @@ -6,7 +6,6 @@ namespace Confuser.Renamer.Analyzers { internal class InterReferenceAnalyzer : IRenamer { - // i.e. Inter-Assembly References, e.g. InternalVisibleToAttributes public void Analyze(ConfuserContext context, INameService service, IDnlibDef def) { @@ -52,6 +51,5 @@ public void PreRename(ConfuserContext context, INameService service, IDnlibDef d public void PostRename(ConfuserContext context, INameService service, IDnlibDef def) { // } - } } \ No newline at end of file diff --git a/Confuser.Renamer/Analyzers/LdtokenEnumAnalyzer.cs b/Confuser.Renamer/Analyzers/LdtokenEnumAnalyzer.cs index 5042766d8..f2c7a10d7 100644 --- a/Confuser.Renamer/Analyzers/LdtokenEnumAnalyzer.cs +++ b/Confuser.Renamer/Analyzers/LdtokenEnumAnalyzer.cs @@ -6,7 +6,6 @@ namespace Confuser.Renamer.Analyzers { internal class LdtokenEnumAnalyzer : IRenamer { - public void Analyze(ConfuserContext context, INameService service, IDnlibDef def) { var method = def as MethodDef; if (method == null || !method.HasBody) @@ -68,7 +67,7 @@ public void PostRename(ConfuserContext context, INameService service, IDnlibDef // } - private void HandleEnum(ConfuserContext context, INameService service, MethodDef method, int index) { + void HandleEnum(ConfuserContext context, INameService service, MethodDef method, int index) { var target = (IMethod)method.Body.Instructions[index].Operand; if (target.FullName == "System.String System.Object::ToString()" || target.FullName == "System.String System.Enum::ToString(System.String)") { @@ -114,7 +113,7 @@ private void HandleEnum(ConfuserContext context, INameService service, MethodDef } } - private bool HandleTypeOf(ConfuserContext context, INameService service, MethodDef method, int index) { + bool HandleTypeOf(ConfuserContext context, INameService service, MethodDef method, int index) { if (index + 1 >= method.Body.Instructions.Count) return true; @@ -160,7 +159,7 @@ private bool HandleTypeOf(ConfuserContext context, INameService service, MethodD return true; } - private void DisableRename(INameService service, TypeDef typeDef, bool memberOnly = true) { + void DisableRename(INameService service, TypeDef typeDef, bool memberOnly = true) { service.SetCanRename(typeDef, false); foreach (MethodDef m in typeDef.Methods) @@ -178,6 +177,5 @@ private void DisableRename(INameService service, TypeDef typeDef, bool memberOnl foreach (TypeDef nested in typeDef.NestedTypes) DisableRename(service, nested, false); } - } } \ No newline at end of file diff --git a/Confuser.Renamer/Analyzers/ResourceAnalyzer.cs b/Confuser.Renamer/Analyzers/ResourceAnalyzer.cs index c364d4a8b..0374d47ed 100644 --- a/Confuser.Renamer/Analyzers/ResourceAnalyzer.cs +++ b/Confuser.Renamer/Analyzers/ResourceAnalyzer.cs @@ -7,8 +7,7 @@ namespace Confuser.Renamer.Analyzers { internal class ResourceAnalyzer : IRenamer { - - private static readonly Regex ResourceNamePattern = new Regex("^(.*)\\.resources$"); + static readonly Regex ResourceNamePattern = new Regex("^(.*)\\.resources$"); public void Analyze(ConfuserContext context, INameService service, IDnlibDef def) { var module = def as ModuleDef; @@ -68,6 +67,5 @@ public void PreRename(ConfuserContext context, INameService service, IDnlibDef d public void PostRename(ConfuserContext context, INameService service, IDnlibDef def) { // } - } } \ No newline at end of file diff --git a/Confuser.Renamer/Analyzers/TypeBlobAnalyzer.cs b/Confuser.Renamer/Analyzers/TypeBlobAnalyzer.cs index c0e48fc60..f7891fd8f 100644 --- a/Confuser.Renamer/Analyzers/TypeBlobAnalyzer.cs +++ b/Confuser.Renamer/Analyzers/TypeBlobAnalyzer.cs @@ -10,7 +10,6 @@ namespace Confuser.Renamer.Analyzers { internal class TypeBlobAnalyzer : IRenamer { - public void Analyze(ConfuserContext context, INameService service, IDnlibDef def) { var module = def as ModuleDefMD; if (module == null) return; @@ -93,7 +92,7 @@ public void PostRename(ConfuserContext context, INameService service, IDnlibDef // } - private void AnalyzeCAArgument(ConfuserContext context, INameService service, CAArgument arg) { + void AnalyzeCAArgument(ConfuserContext context, INameService service, CAArgument arg) { if (arg.Type.DefinitionAssembly.IsCorLib() && arg.Type.FullName == "System.Type") { var typeSig = (TypeSig)arg.Value; foreach (ITypeDefOrRef typeRef in typeSig.FindTypeRefs()) { @@ -111,7 +110,7 @@ private void AnalyzeCAArgument(ConfuserContext context, INameService service, CA } } - private void AnalyzeMemberRef(ConfuserContext context, INameService service, MemberRef memberRef) { + void AnalyzeMemberRef(ConfuserContext context, INameService service, MemberRef memberRef) { ITypeDefOrRef declType = memberRef.DeclaringType; var typeSpec = declType as TypeSpec; if (typeSpec == null) @@ -128,7 +127,7 @@ private void AnalyzeMemberRef(ConfuserContext context, INameService service, Mem Debug.Assert(!(inst.GenericType.TypeDefOrRef is TypeSpec)); TypeDef openType = inst.GenericType.TypeDefOrRef.ResolveTypeDefThrow(); if (!context.Modules.Contains((ModuleDefMD)openType.Module) || - memberRef.IsArrayAccessors()) + memberRef.IsArrayAccessors()) return; IDnlibDef member; @@ -139,6 +138,5 @@ private void AnalyzeMemberRef(ConfuserContext context, INameService service, Mem service.AddReference(member, new MemberRefReference(memberRef, member)); } } - } } \ No newline at end of file diff --git a/Confuser.Renamer/Analyzers/VTableAnalyzer.cs b/Confuser.Renamer/Analyzers/VTableAnalyzer.cs index dc36e5056..6d8b9e50d 100644 --- a/Confuser.Renamer/Analyzers/VTableAnalyzer.cs +++ b/Confuser.Renamer/Analyzers/VTableAnalyzer.cs @@ -1,14 +1,12 @@ using System; using System.Collections.Generic; using System.Diagnostics; -using System.Linq; using Confuser.Core; using Confuser.Renamer.References; using dnlib.DotNet; namespace Confuser.Renamer.Analyzers { internal class VTableAnalyzer : IRenamer { - public void Analyze(ConfuserContext context, INameService service, IDnlibDef def) { VTable vTbl; @@ -69,13 +67,12 @@ public void PostRename(ConfuserContext context, INameService service, IDnlibDef var methods = new HashSet(MethodDefOrRefComparer.Instance); method.Overrides - .RemoveWhere(impl => MethodDefOrRefComparer.Instance.Equals(impl.MethodDeclaration, method)); + .RemoveWhere(impl => MethodDefOrRefComparer.Instance.Equals(impl.MethodDeclaration, method)); } - private class MethodDefOrRefComparer : IEqualityComparer { - + class MethodDefOrRefComparer : IEqualityComparer { public static readonly MethodDefOrRefComparer Instance = new MethodDefOrRefComparer(); - private MethodDefOrRefComparer() { } + MethodDefOrRefComparer() { } public bool Equals(IMethodDefOrRef x, IMethodDefOrRef y) { return new SigComparer().Equals(x, y) && new SigComparer().Equals(x.DeclaringType, y.DeclaringType); @@ -84,8 +81,6 @@ public bool Equals(IMethodDefOrRef x, IMethodDefOrRef y) { public int GetHashCode(IMethodDefOrRef obj) { return new SigComparer().GetHashCode(obj) * 5 + new SigComparer().GetHashCode(obj.DeclaringType); } - } - } } \ No newline at end of file diff --git a/Confuser.Renamer/Analyzers/WPFAnalyzer.cs b/Confuser.Renamer/Analyzers/WPFAnalyzer.cs index 6999028e5..3d4122f76 100644 --- a/Confuser.Renamer/Analyzers/WPFAnalyzer.cs +++ b/Confuser.Renamer/Analyzers/WPFAnalyzer.cs @@ -14,12 +14,11 @@ namespace Confuser.Renamer.Analyzers { internal class WPFAnalyzer : IRenamer { + static readonly object BAMLKey = new object(); - private static readonly object BAMLKey = new object(); - - private static readonly Regex ResourceNamePattern = new Regex("^.*\\.g\\.resources$"); + static readonly Regex ResourceNamePattern = new Regex("^.*\\.g\\.resources$"); internal static readonly Regex UriPattern = new Regex(";COMPONENT/(.+\\.[BX]AML)$"); - private BAMLAnalyzer analyzer; + BAMLAnalyzer analyzer; internal Dictionary> bamlRefs = new Dictionary>(StringComparer.OrdinalIgnoreCase); public event Action AnalyzeBAMLElement; @@ -109,7 +108,7 @@ public void PostRename(ConfuserContext context, INameService service, IDnlibDef } } - private void AnalyzeMethod(ConfuserContext context, INameService service, MethodDef method) { + void AnalyzeMethod(ConfuserContext context, INameService service, MethodDef method) { var dpRegInstrs = new List>(); var routedEvtRegInstrs = new List(); foreach (Instruction instr in method.Body.Instructions) { @@ -249,7 +248,7 @@ private void AnalyzeMethod(ConfuserContext context, INameService service, Method } } - private void AnalyzeResources(ConfuserContext context, INameService service, ModuleDefMD module) { + void AnalyzeResources(ConfuserContext context, INameService service, ModuleDefMD module) { if (analyzer == null) { analyzer = new BAMLAnalyzer(context, service); analyzer.AnalyzeElement += AnalyzeBAMLElement; @@ -286,6 +285,5 @@ private void AnalyzeResources(ConfuserContext context, INameService service, Mod if (wpfResInfo.Count > 0) context.Annotations.Set(module, BAMLKey, wpfResInfo); } - } } \ No newline at end of file diff --git a/Confuser.Renamer/BAML/BAMLAnalyzer.cs b/Confuser.Renamer/BAML/BAMLAnalyzer.cs index 877416137..5ad976328 100644 --- a/Confuser.Renamer/BAML/BAMLAnalyzer.cs +++ b/Confuser.Renamer/BAML/BAMLAnalyzer.cs @@ -4,40 +4,44 @@ using System.IO; using System.Linq; using Confuser.Core; +using Confuser.Renamer.Analyzers; using Confuser.Renamer.References; using dnlib.DotNet; namespace Confuser.Renamer.BAML { internal class BAMLAnalyzer { + readonly ConfuserContext context; + readonly INameService service; - private readonly ConfuserContext context; - private readonly INameService service; + readonly Dictionary> methods = new Dictionary>(); + readonly Dictionary> events = new Dictionary>(); + readonly Dictionary> properties = new Dictionary>(); - private readonly Dictionary> methods = new Dictionary>(); - private readonly Dictionary> events = new Dictionary>(); - private readonly Dictionary> properties = new Dictionary>(); + readonly Dictionary assemblyRefs = new Dictionary(); + readonly Dictionary> attrRefs = new Dictionary>(); - private readonly Dictionary assemblyRefs = new Dictionary(); - private readonly Dictionary> attrRefs = new Dictionary>(); - - private readonly Dictionary strings = new Dictionary(); - private readonly Dictionary typeRefs = new Dictionary(); - private readonly Dictionary>> xmlns = new Dictionary>>(); - - private string bamlName; - private ModuleDefMD module; - private IKnownThings things; + readonly Dictionary strings = new Dictionary(); + readonly Dictionary typeRefs = new Dictionary(); + readonly Dictionary>> xmlns = new Dictionary>>(); - private KnownThingsv3 thingsv3; - private KnownThingsv4 thingsv4; - private XmlNsContext xmlnsCtx; + IKnownThings things; + + KnownThingsv3 thingsv3; + KnownThingsv4 thingsv4; + XmlNsContext xmlnsCtx; public event Action AnalyzeElement; - public ConfuserContext Context { get { return context; } } - public INameService NameService { get { return service; } } - public string CurrentBAMLName { get { return bamlName; } } - public ModuleDefMD Module { get { return module; } } + public ConfuserContext Context { + get { return context; } + } + + public INameService NameService { + get { return service; } + } + + public string CurrentBAMLName { get; set; } + public ModuleDefMD Module { get; set; } public BAMLAnalyzer(ConfuserContext context, INameService service) { this.context = context; @@ -45,7 +49,7 @@ public BAMLAnalyzer(ConfuserContext context, INameService service) { PreInit(); } - private void PreInit() { + void PreInit() { // WPF will only look for public instance members foreach (TypeDef type in context.Modules.SelectMany(m => m.GetTypes())) { foreach (PropertyDef property in type.Properties) { @@ -87,8 +91,8 @@ public IEnumerable LookupMethod(string name) { } public BamlDocument Analyze(ModuleDefMD module, string bamlName, byte[] data) { - this.module = module; - this.bamlName = bamlName; + this.Module = module; + this.CurrentBAMLName = bamlName; if (module.IsClr40) { things = thingsv4 ?? (thingsv4 = new KnownThingsv4(context, module)); } @@ -121,12 +125,12 @@ public BamlDocument Analyze(ModuleDefMD module, string bamlName, byte[] data) { return document; } - private void PopulateReferences(BamlDocument document) { + void PopulateReferences(BamlDocument document) { var clrNs = new Dictionary>>(); assemblyRefs.Clear(); foreach (AssemblyInfoRecord rec in document.OfType()) { - AssemblyDef assembly = context.Resolver.ResolveThrow(rec.AssemblyFullName, module); + AssemblyDef assembly = context.Resolver.ResolveThrow(rec.AssemblyFullName, Module); assemblyRefs.Add(rec.AssemblyId, assembly); if (!context.Modules.Any(m => m.Assembly == assembly)) @@ -150,9 +154,9 @@ private void PopulateReferences(BamlDocument document) { else assembly = assemblyRefs[(ushort)asmId]; - AssemblyDef assemblyRef = module.Assembly == assembly ? null : assembly; + AssemblyDef assemblyRef = Module.Assembly == assembly ? null : assembly; - TypeSig typeSig = TypeNameParser.ParseAsTypeSigReflectionThrow(module, rec.TypeFullName, new DummyAssemblyRefFinder(assemblyRef)); + TypeSig typeSig = TypeNameParser.ParseAsTypeSigReflectionThrow(Module, rec.TypeFullName, new DummyAssemblyRefFinder(assemblyRef)); typeRefs[rec.TypeId] = typeSig; AddTypeSigReference(typeSig, new BAMLTypeReference(typeSig, rec)); @@ -206,7 +210,7 @@ public TypeDef ResolveType(ushort typeId) { return typeRefs[typeId].ToBasicTypeDefOrRef().ResolveTypeDefThrow(); } - private TypeSig ResolveType(string typeName, out string prefix) { + TypeSig ResolveType(string typeName, out string prefix) { List> clrNs; int index = typeName.IndexOf(':'); @@ -224,7 +228,7 @@ private TypeSig ResolveType(string typeName, out string prefix) { } foreach (var ns in clrNs) { - TypeSig sig = TypeNameParser.ParseAsTypeSigReflectionThrow(module, ns.Item2 + "." + typeName, new DummyAssemblyRefFinder(ns.Item1)); + TypeSig sig = TypeNameParser.ParseAsTypeSigReflectionThrow(Module, ns.Item2 + "." + typeName, new DummyAssemblyRefFinder(ns.Item1)); if (sig.ToBasicTypeDefOrRef().ResolveTypeDef() != null) return sig; } @@ -239,7 +243,7 @@ public Tuple ResolveAttribute(ushort at return attrRefs[attrId]; } - private void AddTypeSigReference(TypeSig typeSig, INameReference reference) { + void AddTypeSigReference(TypeSig typeSig, INameReference reference) { foreach (ITypeDefOrRef type in typeSig.FindTypeRefs()) { TypeDef typeDef = type.ResolveTypeDefThrow(); if (context.Modules.Contains((ModuleDefMD)typeDef.Module)) { @@ -249,7 +253,7 @@ private void AddTypeSigReference(TypeSig typeSig, INameReference refe } } - private void ProcessBAMLElement(BamlElement root, BamlElement elem) { + void ProcessBAMLElement(BamlElement root, BamlElement elem) { ProcessElementHeader(elem); ProcessElementBody(root, elem); @@ -257,7 +261,7 @@ private void ProcessBAMLElement(BamlElement root, BamlElement elem) { AnalyzeElement(this, elem); } - private void ProcessElementHeader(BamlElement elem) { + void ProcessElementHeader(BamlElement elem) { // Resolve type & properties of the element. switch (elem.Header.Type) { case BamlRecordType.ConstructorParametersStart: @@ -320,13 +324,13 @@ private void ProcessElementHeader(BamlElement elem) { case BamlRecordType.KeyElementStart: case BamlRecordType.StaticResourceStart: // i.e. - elem.Type = module.CorLibTypes.Object.TypeDefOrRef.ResolveTypeDef(); + elem.Type = Module.CorLibTypes.Object.TypeDefOrRef.ResolveTypeDef(); elem.Attribute = null; break; } } - private TypeDef GetAttributeType(IDnlibDef attr) { + TypeDef GetAttributeType(IDnlibDef attr) { ITypeDefOrRef retType = null; if (attr is PropertyDef) retType = ((PropertyDef)attr).PropertySig.RetType.ToBasicTypeDefOrRef(); @@ -336,7 +340,7 @@ private TypeDef GetAttributeType(IDnlibDef attr) { throw new UnreachableException(); } - private void ProcessElementBody(BamlElement root, BamlElement elem) { + void ProcessElementBody(BamlElement root, BamlElement elem) { foreach (BamlRecord rec in elem.Body) { // Resolve the type & property for simple property record too. TypeDef type = null; @@ -402,7 +406,8 @@ private void ProcessElementBody(BamlElement root, BamlElement elem) { if (elem.Attribute != null && attr != null) type = GetAttributeType(attr); - if (extRec.Flags == 602) { // Static Extension + if (extRec.Flags == 602) { + // Static Extension // We only care about the references in user-defined assemblies, so skip built-in attributes // Also, ValueId is a resource ID, which is not implemented, so just skip it. if ((short)extRec.ValueId >= 0) { @@ -429,7 +434,7 @@ private void ProcessElementBody(BamlElement root, BamlElement elem) { } } - private void ProcessConverter(PropertyWithConverterRecord rec, TypeDef type) { + void ProcessConverter(PropertyWithConverterRecord rec, TypeDef type) { TypeDef converter = ResolveType(rec.ConverterTypeId); if (converter.FullName == "System.ComponentModel.EnumConverter") { @@ -466,7 +471,7 @@ private void ProcessConverter(PropertyWithConverterRecord rec, TypeDef type) { service.AddReference(field, reference); } if (property == null && field == null) - context.Logger.WarnFormat("Could not resolve command '{0}' in '{1}'.", cmd, bamlName); + context.Logger.WarnFormat("Could not resolve command '{0}' in '{1}'.", cmd, CurrentBAMLName); } } } @@ -508,19 +513,19 @@ private void ProcessConverter(PropertyWithConverterRecord rec, TypeDef type) { if (declType == "System.Windows.ResourceDictionary") { var src = rec.Value.ToUpperInvariant(); if (src.EndsWith(".BAML") || src.EndsWith(".XAML")) { - var match = Analyzers.WPFAnalyzer.UriPattern.Match(src); + var match = WPFAnalyzer.UriPattern.Match(src); if (match.Success) src = match.Groups[1].Value; if (src.StartsWith("./") || src.StartsWith("../")) { - var rel = new Uri(new Uri("pack://application:,,,/" + bamlName), src); + var rel = new Uri(new Uri("pack://application:,,,/" + CurrentBAMLName), src); src = rel.LocalPath; } var reference = new BAMLPropertyReference(rec); src = src.TrimStart('/'); var baml = src.Substring(0, src.Length - 5) + ".BAML"; var xaml = src.Substring(0, src.Length - 5) + ".XAML"; - var bamlRefs = service.FindRenamer().bamlRefs; + var bamlRefs = service.FindRenamer().bamlRefs; bamlRefs.AddListEntry(baml, reference); bamlRefs.AddListEntry(xaml, reference); } @@ -528,7 +533,7 @@ private void ProcessConverter(PropertyWithConverterRecord rec, TypeDef type) { } } - private Tuple AnalyzeAttributeReference(TypeDef declType, AttributeInfoRecord rec) { + Tuple AnalyzeAttributeReference(TypeDef declType, AttributeInfoRecord rec) { IDnlibDef retDef = null; ITypeDefOrRef retType = null; while (declType != null) { @@ -557,7 +562,7 @@ private Tuple AnalyzeAttributeReference return Tuple.Create(retDef, rec, retType == null ? null : retType.ResolveTypeDefThrow()); } - private void AnalyzePropertyPath(string path) { + void AnalyzePropertyPath(string path) { var propertyPath = new PropertyPath(path); foreach (PropertyPathPart part in propertyPath.Parts) { if (part.IsAttachedDP()) { @@ -594,9 +599,8 @@ private void AnalyzePropertyPath(string path) { } } - private class DummyAssemblyRefFinder : IAssemblyRefFinder { - - private readonly AssemblyDef assemblyDef; + class DummyAssemblyRefFinder : IAssemblyRefFinder { + readonly AssemblyDef assemblyDef; public DummyAssemblyRefFinder(AssemblyDef assemblyDef) { this.assemblyDef = assemblyDef; @@ -605,16 +609,14 @@ public DummyAssemblyRefFinder(AssemblyDef assemblyDef) { public AssemblyRef FindAssemblyRef(TypeRef nonNestedTypeRef) { return assemblyDef.ToAssemblyRef(); } - } internal class XmlNsContext { - - private readonly Dictionary assemblyRefs; - private readonly BamlDocument doc; - private readonly Dictionary, string> xmlNsMap = new Dictionary, string>(); - private int rootIndex = -1; - private int x; + readonly Dictionary assemblyRefs; + readonly BamlDocument doc; + readonly Dictionary, string> xmlNsMap = new Dictionary, string>(); + int rootIndex = -1; + int x; public XmlNsContext(BamlDocument doc, Dictionary assemblyRefs) { this.doc = doc; @@ -654,8 +656,6 @@ public string GetPrefix(string clrNs, AssemblyDef assembly) { } return prefix; } - } - } } \ No newline at end of file diff --git a/Confuser.Renamer/BAML/BamlDocument.cs b/Confuser.Renamer/BAML/BamlDocument.cs index 89fed15a2..b2df1d581 100644 --- a/Confuser.Renamer/BAML/BamlDocument.cs +++ b/Confuser.Renamer/BAML/BamlDocument.cs @@ -3,7 +3,6 @@ namespace Confuser.Renamer.BAML { internal class BamlDocument : List { - public string DocumentName { get; set; } public string Signature { get; set; } @@ -12,11 +11,8 @@ internal class BamlDocument : List { public BamlVersion WriterVersion { get; set; } public struct BamlVersion { - public ushort Major; public ushort Minor; - } - } } \ No newline at end of file diff --git a/Confuser.Renamer/BAML/BamlElement.cs b/Confuser.Renamer/BAML/BamlElement.cs index 268a0ac88..dccc65ee5 100644 --- a/Confuser.Renamer/BAML/BamlElement.cs +++ b/Confuser.Renamer/BAML/BamlElement.cs @@ -5,7 +5,6 @@ namespace Confuser.Renamer.BAML { internal class BamlElement { - public BamlElement Parent { get; private set; } public BamlRecord Header { get; private set; } public IList Body { get; private set; } @@ -17,7 +16,7 @@ internal class BamlElement { // Attribute this element will be assigned to. public IDnlibDef Attribute { get; set; } - private static bool IsHeader(BamlRecord rec) { + static bool IsHeader(BamlRecord rec) { switch (rec.Type) { case BamlRecordType.ConstructorParametersStart: case BamlRecordType.DocumentStart: @@ -34,7 +33,7 @@ private static bool IsHeader(BamlRecord rec) { return false; } - private static bool IsFooter(BamlRecord rec) { + static bool IsFooter(BamlRecord rec) { switch (rec.Type) { case BamlRecordType.ConstructorParametersEnd: case BamlRecordType.DocumentEnd: @@ -50,7 +49,7 @@ private static bool IsFooter(BamlRecord rec) { return false; } - private static bool IsMatch(BamlRecord header, BamlRecord footer) { + static bool IsMatch(BamlRecord header, BamlRecord footer) { switch (header.Type) { case BamlRecordType.ConstructorParametersStart: return footer.Type == BamlRecordType.ConstructorParametersEnd; @@ -123,6 +122,5 @@ public static BamlElement Read(BamlDocument document) { Debug.Assert(stack.Count == 0); return current; } - } } \ No newline at end of file diff --git a/Confuser.Renamer/BAML/BamlRW.cs b/Confuser.Renamer/BAML/BamlRW.cs index 7f23acda7..24243d5d8 100644 --- a/Confuser.Renamer/BAML/BamlRW.cs +++ b/Confuser.Renamer/BAML/BamlRW.cs @@ -5,29 +5,24 @@ namespace Confuser.Renamer.BAML { internal class BamlBinaryReader : BinaryReader { - public BamlBinaryReader(Stream stream) : base(stream) { } public int ReadEncodedInt() { - return base.Read7BitEncodedInt(); + return Read7BitEncodedInt(); } - } internal class BamlBinaryWriter : BinaryWriter { - public BamlBinaryWriter(Stream stream) : base(stream) { } public void WriteEncodedInt(int val) { - base.Write7BitEncodedInt(val); + Write7BitEncodedInt(val); } - } internal class BamlReader { - public static BamlDocument ReadDocument(Stream str) { var ret = new BamlDocument(); var reader = new BamlBinaryReader(str); @@ -226,11 +221,9 @@ public static BamlDocument ReadDocument(Stream str) { return ret; } - } internal class BamlWriter { - public static void WriteDocument(BamlDocument doc, Stream str) { var writer = new BamlBinaryWriter(str); { @@ -258,6 +251,5 @@ public static void WriteDocument(BamlDocument doc, Stream str) { foreach (int i in defers) (doc[i] as IBamlDeferRecord).WriteDefer(doc, i, writer); } - } } \ No newline at end of file diff --git a/Confuser.Renamer/BAML/BamlRecords.cs b/Confuser.Renamer/BAML/BamlRecords.cs index 68813ddca..f51012899 100644 --- a/Confuser.Renamer/BAML/BamlRecords.cs +++ b/Confuser.Renamer/BAML/BamlRecords.cs @@ -4,7 +4,6 @@ namespace Confuser.Renamer.BAML { internal enum BamlRecordType : byte { - ClrEvent = 0x13, Comment = 0x17, AssemblyInfo = 0x1c, @@ -62,20 +61,16 @@ internal enum BamlRecordType : byte { TypeSerializerInfo = 0x1e, XmlAttribute = 0x15, XmlnsProperty = 0x14 - } internal abstract class BamlRecord { - public abstract BamlRecordType Type { get; } public long Position { get; internal set; } public abstract void Read(BamlBinaryReader reader); public abstract void Write(BamlBinaryWriter writer); - } internal abstract class SizedBamlRecord : BamlRecord { - public override void Read(BamlBinaryReader reader) { long pos = reader.BaseStream.Position; int size = reader.ReadEncodedInt(); @@ -84,7 +79,7 @@ public override void Read(BamlBinaryReader reader) { Debug.Assert(reader.BaseStream.Position - pos == size); } - private int SizeofEncodedInt(int val) { + int SizeofEncodedInt(int val) { if ((val & ~0x7F) == 0) { return 1; } @@ -112,19 +107,15 @@ public override void Write(BamlBinaryWriter writer) { protected abstract void ReadData(BamlBinaryReader reader, int size); protected abstract void WriteData(BamlBinaryWriter writer); - } internal interface IBamlDeferRecord { - BamlRecord Record { get; set; } void ReadDefer(BamlDocument doc, int index, Func resolve); void WriteDefer(BamlDocument doc, int index, BinaryWriter wtr); - } internal class XmlnsPropertyRecord : SizedBamlRecord { - public override BamlRecordType Type { get { return BamlRecordType.XmlnsProperty; } } @@ -148,11 +139,9 @@ protected override void WriteData(BamlBinaryWriter writer) { foreach (ushort i in AssemblyIds) writer.Write(i); } - } internal class PresentationOptionsAttributeRecord : SizedBamlRecord { - public override BamlRecordType Type { get { return BamlRecordType.PresentationOptionsAttribute; } } @@ -169,11 +158,9 @@ protected override void WriteData(BamlBinaryWriter writer) { writer.Write(Value); writer.Write(NameId); } - } internal class PIMappingRecord : SizedBamlRecord { - public override BamlRecordType Type { get { return BamlRecordType.PIMapping; } } @@ -193,11 +180,9 @@ protected override void WriteData(BamlBinaryWriter writer) { writer.Write(ClrNamespace); writer.Write(AssemblyId); } - } internal class AssemblyInfoRecord : SizedBamlRecord { - public override BamlRecordType Type { get { return BamlRecordType.AssemblyInfo; } } @@ -214,11 +199,9 @@ protected override void WriteData(BamlBinaryWriter writer) { writer.Write(AssemblyId); writer.Write(AssemblyFullName); } - } internal class PropertyRecord : SizedBamlRecord { - public override BamlRecordType Type { get { return BamlRecordType.Property; } } @@ -235,11 +218,9 @@ protected override void WriteData(BamlBinaryWriter writer) { writer.Write(AttributeId); writer.Write(Value); } - } internal class PropertyWithConverterRecord : PropertyRecord { - public override BamlRecordType Type { get { return BamlRecordType.PropertyWithConverter; } } @@ -255,11 +236,9 @@ protected override void WriteData(BamlBinaryWriter writer) { base.WriteData(writer); writer.Write(ConverterTypeId); } - } internal class PropertyCustomRecord : SizedBamlRecord { - public override BamlRecordType Type { get { return BamlRecordType.PropertyCustom; } } @@ -280,11 +259,9 @@ protected override void WriteData(BamlBinaryWriter writer) { writer.Write(SerializerTypeId); writer.Write(Data); } - } internal class DefAttributeRecord : SizedBamlRecord { - public override BamlRecordType Type { get { return BamlRecordType.DefAttribute; } } @@ -301,11 +278,9 @@ protected override void WriteData(BamlBinaryWriter writer) { writer.Write(Value); writer.Write(NameId); } - } internal class DefAttributeKeyStringRecord : SizedBamlRecord, IBamlDeferRecord { - internal uint pos = 0xffffffff; public override BamlRecordType Type { @@ -388,7 +363,7 @@ protected override void WriteData(BamlBinaryWriter writer) { writer.Write(SharedSet); } - private static void NavigateTree(BamlDocument doc, BamlRecordType start, BamlRecordType end, ref int index) { + static void NavigateTree(BamlDocument doc, BamlRecordType start, BamlRecordType end, ref int index) { index++; while (true) //Assume there alway is a end { @@ -399,11 +374,9 @@ private static void NavigateTree(BamlDocument doc, BamlRecordType start, BamlRec index++; } } - } internal class TypeInfoRecord : SizedBamlRecord { - public override BamlRecordType Type { get { return BamlRecordType.TypeInfo; } } @@ -423,11 +396,9 @@ protected override void WriteData(BamlBinaryWriter writer) { writer.Write(AssemblyId); writer.Write(TypeFullName); } - } internal class TypeSerializerInfoRecord : TypeInfoRecord { - public override BamlRecordType Type { get { return BamlRecordType.TypeSerializerInfo; } } @@ -443,11 +414,9 @@ protected override void WriteData(BamlBinaryWriter writer) { base.WriteData(writer); writer.Write(SerializerTypeId); } - } internal class AttributeInfoRecord : SizedBamlRecord { - public override BamlRecordType Type { get { return BamlRecordType.AttributeInfo; } } @@ -470,11 +439,9 @@ protected override void WriteData(BamlBinaryWriter writer) { writer.Write(AttributeUsage); writer.Write(Name); } - } internal class StringInfoRecord : SizedBamlRecord { - public override BamlRecordType Type { get { return BamlRecordType.StringInfo; } } @@ -491,11 +458,9 @@ protected override void WriteData(BamlBinaryWriter writer) { writer.Write(StringId); writer.Write(Value); } - } internal class TextRecord : SizedBamlRecord { - public override BamlRecordType Type { get { return BamlRecordType.Text; } } @@ -509,11 +474,9 @@ protected override void ReadData(BamlBinaryReader reader, int size) { protected override void WriteData(BamlBinaryWriter writer) { writer.Write(Value); } - } internal class TextWithConverterRecord : TextRecord { - public override BamlRecordType Type { get { return BamlRecordType.TextWithConverter; } } @@ -529,11 +492,9 @@ protected override void WriteData(BamlBinaryWriter writer) { base.WriteData(writer); writer.Write(ConverterTypeId); } - } internal class TextWithIdRecord : TextRecord { - public override BamlRecordType Type { get { return BamlRecordType.TextWithId; } } @@ -547,11 +508,9 @@ protected override void ReadData(BamlBinaryReader reader, int size) { protected override void WriteData(BamlBinaryWriter writer) { writer.Write(ValueId); } - } internal class LiteralContentRecord : SizedBamlRecord { - public override BamlRecordType Type { get { return BamlRecordType.LiteralContent; } } @@ -571,11 +530,9 @@ protected override void WriteData(BamlBinaryWriter writer) { writer.Write(Reserved0); writer.Write(Reserved1); } - } internal class RoutedEventRecord : SizedBamlRecord { - public override BamlRecordType Type { get { return BamlRecordType.RoutedEvent; } } @@ -593,11 +550,9 @@ protected override void WriteData(BamlBinaryWriter writer) { writer.Write(Value); writer.Write(AttributeId); } - } internal class DocumentStartRecord : BamlRecord { - public override BamlRecordType Type { get { return BamlRecordType.DocumentStart; } } @@ -617,22 +572,18 @@ public override void Write(BamlBinaryWriter writer) { writer.Write(MaxAsyncRecords); writer.Write(DebugBaml); } - } internal class DocumentEndRecord : BamlRecord { - public override BamlRecordType Type { get { return BamlRecordType.DocumentEnd; } } public override void Read(BamlBinaryReader reader) { } public override void Write(BamlBinaryWriter writer) { } - } internal class ElementStartRecord : BamlRecord { - public override BamlRecordType Type { get { return BamlRecordType.ElementStart; } } @@ -649,41 +600,33 @@ public override void Write(BamlBinaryWriter writer) { writer.Write(TypeId); writer.Write(Flags); } - } internal class ElementEndRecord : BamlRecord { - public override BamlRecordType Type { get { return BamlRecordType.ElementEnd; } } public override void Read(BamlBinaryReader reader) { } public override void Write(BamlBinaryWriter writer) { } - } internal class KeyElementStartRecord : DefAttributeKeyTypeRecord { - public override BamlRecordType Type { get { return BamlRecordType.KeyElementStart; } } - } internal class KeyElementEndRecord : BamlRecord { - public override BamlRecordType Type { get { return BamlRecordType.KeyElementEnd; } } public override void Read(BamlBinaryReader reader) { } public override void Write(BamlBinaryWriter writer) { } - } internal class ConnectionIdRecord : BamlRecord { - public override BamlRecordType Type { get { return BamlRecordType.ConnectionId; } } @@ -697,11 +640,9 @@ public override void Read(BamlBinaryReader reader) { public override void Write(BamlBinaryWriter writer) { writer.Write(ConnectionId); } - } internal class PropertyWithExtensionRecord : BamlRecord { - public override BamlRecordType Type { get { return BamlRecordType.PropertyWithExtension; } } @@ -721,11 +662,9 @@ public override void Write(BamlBinaryWriter writer) { writer.Write(Flags); writer.Write(ValueId); } - } internal class PropertyTypeReferenceRecord : PropertyComplexStartRecord { - public override BamlRecordType Type { get { return BamlRecordType.PropertyTypeReference; } } @@ -741,11 +680,9 @@ public override void Write(BamlBinaryWriter writer) { base.Write(writer); writer.Write(TypeId); } - } internal class PropertyStringReferenceRecord : PropertyComplexStartRecord { - public override BamlRecordType Type { get { return BamlRecordType.PropertyStringReference; } } @@ -761,11 +698,9 @@ public override void Write(BamlBinaryWriter writer) { base.Write(writer); writer.Write(StringId); } - } internal class PropertyWithStaticResourceIdRecord : StaticResourceIdRecord { - public override BamlRecordType Type { get { return BamlRecordType.PropertyWithStaticResourceId; } } @@ -781,11 +716,9 @@ public override void Write(BamlBinaryWriter writer) { writer.Write(AttributeId); base.Write(writer); } - } internal class ContentPropertyRecord : BamlRecord { - public override BamlRecordType Type { get { return BamlRecordType.ContentProperty; } } @@ -799,11 +732,9 @@ public override void Read(BamlBinaryReader reader) { public override void Write(BamlBinaryWriter writer) { writer.Write(AttributeId); } - } internal class DefAttributeKeyTypeRecord : ElementStartRecord, IBamlDeferRecord { - internal uint pos = 0xffffffff; public override BamlRecordType Type { @@ -885,7 +816,7 @@ public override void Write(BamlBinaryWriter writer) { writer.Write(SharedSet); } - private static void NavigateTree(BamlDocument doc, BamlRecordType start, BamlRecordType end, ref int index) { + static void NavigateTree(BamlDocument doc, BamlRecordType start, BamlRecordType end, ref int index) { index++; while (true) { if (doc[index].Type == start) @@ -895,68 +826,54 @@ private static void NavigateTree(BamlDocument doc, BamlRecordType start, BamlRec index++; } } - } internal class PropertyListStartRecord : PropertyComplexStartRecord { - public override BamlRecordType Type { get { return BamlRecordType.PropertyListStart; } } - } internal class PropertyListEndRecord : BamlRecord { - public override BamlRecordType Type { get { return BamlRecordType.PropertyListEnd; } } public override void Read(BamlBinaryReader reader) { } public override void Write(BamlBinaryWriter writer) { } - } internal class PropertyDictionaryStartRecord : PropertyComplexStartRecord { - public override BamlRecordType Type { get { return BamlRecordType.PropertyDictionaryStart; } } - } internal class PropertyDictionaryEndRecord : BamlRecord { - public override BamlRecordType Type { get { return BamlRecordType.PropertyDictionaryEnd; } } public override void Read(BamlBinaryReader reader) { } public override void Write(BamlBinaryWriter writer) { } - } internal class PropertyArrayStartRecord : PropertyComplexStartRecord { - public override BamlRecordType Type { get { return BamlRecordType.PropertyArrayStart; } } - } internal class PropertyArrayEndRecord : BamlRecord { - public override BamlRecordType Type { get { return BamlRecordType.PropertyArrayEnd; } } public override void Read(BamlBinaryReader reader) { } public override void Write(BamlBinaryWriter writer) { } - } internal class PropertyComplexStartRecord : BamlRecord { - public override BamlRecordType Type { get { return BamlRecordType.PropertyComplexStart; } } @@ -970,44 +887,36 @@ public override void Read(BamlBinaryReader reader) { public override void Write(BamlBinaryWriter writer) { writer.Write(AttributeId); } - } internal class PropertyComplexEndRecord : BamlRecord { - public override BamlRecordType Type { get { return BamlRecordType.PropertyComplexEnd; } } public override void Read(BamlBinaryReader reader) { } public override void Write(BamlBinaryWriter writer) { } - } internal class ConstructorParametersStartRecord : BamlRecord { - public override BamlRecordType Type { get { return BamlRecordType.ConstructorParametersStart; } } public override void Read(BamlBinaryReader reader) { } public override void Write(BamlBinaryWriter writer) { } - } internal class ConstructorParametersEndRecord : BamlRecord { - public override BamlRecordType Type { get { return BamlRecordType.ConstructorParametersEnd; } } public override void Read(BamlBinaryReader reader) { } public override void Write(BamlBinaryWriter writer) { } - } internal class ConstructorParameterTypeRecord : BamlRecord { - public override BamlRecordType Type { get { return BamlRecordType.ConstructorParameterType; } } @@ -1021,12 +930,10 @@ public override void Read(BamlBinaryReader reader) { public override void Write(BamlBinaryWriter writer) { writer.Write(TypeId); } - } internal class DeferableContentStartRecord : BamlRecord, IBamlDeferRecord { - - private long pos; + long pos; internal uint size = 0xffffffff; public override BamlRecordType Type { @@ -1053,30 +960,24 @@ public override void Write(BamlBinaryWriter writer) { pos = writer.BaseStream.Position; writer.Write((uint)0); } - } internal class StaticResourceStartRecord : ElementStartRecord { - public override BamlRecordType Type { get { return BamlRecordType.StaticResourceStart; } } - } internal class StaticResourceEndRecord : BamlRecord { - public override BamlRecordType Type { get { return BamlRecordType.StaticResourceEnd; } } public override void Read(BamlBinaryReader reader) { } public override void Write(BamlBinaryWriter writer) { } - } internal class StaticResourceIdRecord : BamlRecord { - public override BamlRecordType Type { get { return BamlRecordType.StaticResourceId; } } @@ -1090,11 +991,9 @@ public override void Read(BamlBinaryReader reader) { public override void Write(BamlBinaryWriter writer) { writer.Write(StaticResourceId); } - } internal class OptimizedStaticResourceRecord : BamlRecord { - public override BamlRecordType Type { get { return BamlRecordType.OptimizedStaticResource; } } @@ -1111,11 +1010,9 @@ public override void Write(BamlBinaryWriter writer) { writer.Write(Flags); writer.Write(ValueId); } - } internal class LineNumberAndPositionRecord : BamlRecord { - public override BamlRecordType Type { get { return BamlRecordType.LineNumberAndPosition; } } @@ -1132,11 +1029,9 @@ public override void Write(BamlBinaryWriter writer) { writer.Write(LineNumber); writer.Write(LinePosition); } - } internal class LinePositionRecord : BamlRecord { - public override BamlRecordType Type { get { return BamlRecordType.LinePosition; } } @@ -1150,11 +1045,9 @@ public override void Read(BamlBinaryReader reader) { public override void Write(BamlBinaryWriter writer) { writer.Write(LinePosition); } - } internal class NamedElementStartRecord : ElementStartRecord { - public override BamlRecordType Type { get { return BamlRecordType.NamedElementStart; } } @@ -1162,16 +1055,15 @@ public override BamlRecordType Type { public string RuntimeName { get; set; } public override void Read(BamlBinaryReader reader) { - base.TypeId = reader.ReadUInt16(); + TypeId = reader.ReadUInt16(); RuntimeName = reader.ReadString(); } public override void Write(BamlBinaryWriter writer) { - writer.Write(base.TypeId); + writer.Write(TypeId); if (RuntimeName != null) { writer.Write(RuntimeName); } } - } } \ No newline at end of file diff --git a/Confuser.Renamer/BAML/IKnownThings.cs b/Confuser.Renamer/BAML/IKnownThings.cs index 0f825efbd..e27bb0078 100644 --- a/Confuser.Renamer/BAML/IKnownThings.cs +++ b/Confuser.Renamer/BAML/IKnownThings.cs @@ -1,10 +1,8 @@ using System; -using Confuser.Core; using dnlib.DotNet; namespace Confuser.Renamer.BAML { internal enum KnownTypes : short { - Unknown = 0, AccessText, AdornedElementPlaceholder, @@ -765,11 +763,9 @@ internal enum KnownTypes : short { XmlLanguageConverter, XmlNamespaceMapping, ZoomPercentageConverter - } internal enum KnownProperties : short { - Unknown = 0, AccessText_Text, BeginStoryboard_Storyboard, @@ -1039,14 +1035,11 @@ internal enum KnownProperties : short { Window_Content, WrapPanel_Children, XmlDataProvider_XmlSerializer - } internal interface IKnownThings { - Func Types { get; } Func> Properties { get; } AssemblyDef FrameworkAssembly { get; } - } } \ No newline at end of file diff --git a/Confuser.Renamer/BAML/KnownThingsv3.cs b/Confuser.Renamer/BAML/KnownThingsv3.cs index 113247268..d5a65e351 100644 --- a/Confuser.Renamer/BAML/KnownThingsv3.cs +++ b/Confuser.Renamer/BAML/KnownThingsv3.cs @@ -5,11 +5,10 @@ namespace Confuser.Renamer.BAML { internal class KnownThingsv3 : IKnownThings { - - private readonly Dictionary assemblies; - private readonly ConfuserContext context; - private readonly Dictionary> properties; - private readonly Dictionary types; + readonly Dictionary assemblies; + readonly ConfuserContext context; + readonly Dictionary> properties; + readonly Dictionary types; public KnownThingsv3(ConfuserContext context, ModuleDefMD initMod) { this.context = context; @@ -35,7 +34,7 @@ public AssemblyDef FrameworkAssembly { get { return assemblies[0]; } } - private Tuple InitProperty(KnownTypes parent, string propertyName, TypeDef propertyType) { + Tuple InitProperty(KnownTypes parent, string propertyName, TypeDef propertyType) { if (propertyName != null) return Tuple.Create(parent, types[parent].FindProperty(propertyName), propertyType); return Tuple.Create(parent, (PropertyDef)null, propertyType); @@ -43,7 +42,7 @@ private Tuple InitProperty(KnownTypes parent, // Following codes are auto-generated, do not modify. - private void InitAssemblies(ModuleDefMD initMod) { + void InitAssemblies(ModuleDefMD initMod) { assemblies[0] = context.Resolver.ResolveThrow("PresentationFramework, Version=3.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35", initMod); assemblies[1] = context.Resolver.ResolveThrow("PresentationCore, Version=3.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35", initMod); assemblies[2] = context.Resolver.ResolveThrow("mscorlib, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089", initMod); @@ -52,7 +51,7 @@ private void InitAssemblies(ModuleDefMD initMod) { assemblies[5] = context.Resolver.ResolveThrow("System.Xml, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089", initMod); } - private void InitTypes() { + void InitTypes() { types[KnownTypes.AccessText] = assemblies[0].Find("System.Windows.Controls.AccessText", true); types[KnownTypes.AdornedElementPlaceholder] = assemblies[0].Find("System.Windows.Controls.AdornedElementPlaceholder", true); types[KnownTypes.Adorner] = assemblies[0].Find("System.Windows.Documents.Adorner", true); @@ -814,7 +813,7 @@ private void InitTypes() { types[KnownTypes.ZoomPercentageConverter] = assemblies[0].Find("System.Windows.Documents.ZoomPercentageConverter", true); } - private void InitProperties() { + void InitProperties() { properties[KnownProperties.AccessText_Text] = InitProperty(KnownTypes.AccessText, "Text", assemblies[2].Find("System.Char", true)); properties[KnownProperties.BeginStoryboard_Storyboard] = InitProperty(KnownTypes.BeginStoryboard, "Storyboard", assemblies[0].Find("System.Windows.Media.Animation.Storyboard", true)); properties[KnownProperties.BitmapEffectGroup_Children] = InitProperty(KnownTypes.BitmapEffectGroup, "Children", assemblies[1].Find("System.Windows.Media.Effects.BitmapEffect", true)); @@ -1083,6 +1082,5 @@ private void InitProperties() { properties[KnownProperties.WrapPanel_Children] = InitProperty(KnownTypes.WrapPanel, "Children", assemblies[1].Find("System.Windows.UIElement", true)); properties[KnownProperties.XmlDataProvider_XmlSerializer] = InitProperty(KnownTypes.XmlDataProvider, "XmlSerializer", assemblies[5].Find("System.Xml.Serialization.IXmlSerializable", true)); } - } } \ No newline at end of file diff --git a/Confuser.Renamer/BAML/KnownThingsv4.cs b/Confuser.Renamer/BAML/KnownThingsv4.cs index 7ac7f8dda..d1fbb530b 100644 --- a/Confuser.Renamer/BAML/KnownThingsv4.cs +++ b/Confuser.Renamer/BAML/KnownThingsv4.cs @@ -5,11 +5,10 @@ namespace Confuser.Renamer.BAML { internal class KnownThingsv4 : IKnownThings { - - private readonly Dictionary assemblies; - private readonly ConfuserContext context; - private readonly Dictionary> properties; - private readonly Dictionary types; + readonly Dictionary assemblies; + readonly ConfuserContext context; + readonly Dictionary> properties; + readonly Dictionary types; public KnownThingsv4(ConfuserContext context, ModuleDefMD initMod) { this.context = context; @@ -35,7 +34,7 @@ public AssemblyDef FrameworkAssembly { get { return assemblies[0]; } } - private Tuple InitProperty(KnownTypes parent, string propertyName, TypeDef propertyType) { + Tuple InitProperty(KnownTypes parent, string propertyName, TypeDef propertyType) { if (propertyName != null) return Tuple.Create(parent, types[parent].FindProperty(propertyName), propertyType); return Tuple.Create(parent, (PropertyDef)null, propertyType); @@ -43,7 +42,7 @@ private Tuple InitProperty(KnownTypes parent, // Following codes are auto-generated, do not modify. - private void InitAssemblies(ModuleDefMD initMod) { + void InitAssemblies(ModuleDefMD initMod) { assemblies[0] = context.Resolver.ResolveThrow("PresentationFramework, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35", initMod); assemblies[1] = context.Resolver.ResolveThrow("PresentationCore, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35", initMod); assemblies[2] = context.Resolver.ResolveThrow("System.Xaml, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089", initMod); @@ -53,7 +52,7 @@ private void InitAssemblies(ModuleDefMD initMod) { assemblies[6] = context.Resolver.ResolveThrow("System.Xml, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089", initMod); } - private void InitTypes() { + void InitTypes() { types[KnownTypes.AccessText] = assemblies[0].Find("System.Windows.Controls.AccessText", true); types[KnownTypes.AdornedElementPlaceholder] = assemblies[0].Find("System.Windows.Controls.AdornedElementPlaceholder", true); types[KnownTypes.Adorner] = assemblies[0].Find("System.Windows.Documents.Adorner", true); @@ -815,7 +814,7 @@ private void InitTypes() { types[KnownTypes.ZoomPercentageConverter] = assemblies[0].Find("System.Windows.Documents.ZoomPercentageConverter", true); } - private void InitProperties() { + void InitProperties() { properties[KnownProperties.AccessText_Text] = InitProperty(KnownTypes.AccessText, "Text", assemblies[3].Find("System.Char", true)); properties[KnownProperties.BeginStoryboard_Storyboard] = InitProperty(KnownTypes.BeginStoryboard, "Storyboard", assemblies[0].Find("System.Windows.Media.Animation.Storyboard", true)); properties[KnownProperties.BitmapEffectGroup_Children] = InitProperty(KnownTypes.BitmapEffectGroup, "Children", assemblies[1].Find("System.Windows.Media.Effects.BitmapEffect", true)); @@ -1084,6 +1083,5 @@ private void InitProperties() { properties[KnownProperties.WrapPanel_Children] = InitProperty(KnownTypes.WrapPanel, "Children", assemblies[1].Find("System.Windows.UIElement", true)); properties[KnownProperties.XmlDataProvider_XmlSerializer] = InitProperty(KnownTypes.XmlDataProvider, "XmlSerializer", assemblies[6].Find("System.Xml.Serialization.IXmlSerializable", true)); } - } } \ No newline at end of file diff --git a/Confuser.Renamer/BAML/PropertyPath.cs b/Confuser.Renamer/BAML/PropertyPath.cs index b036f7146..07f6da151 100644 --- a/Confuser.Renamer/BAML/PropertyPath.cs +++ b/Confuser.Renamer/BAML/PropertyPath.cs @@ -5,14 +5,11 @@ namespace Confuser.Renamer.BAML { internal class PropertyPathIndexer { - public string Type { get; set; } public string Value { get; set; } - } internal class PropertyPathPart { - public PropertyPathPart(bool isIndexer, bool? isHiera, string name) { IsIndexer = isIndexer; IsHierarchical = isHiera; @@ -43,21 +40,19 @@ public void ExtractAttachedDP(out string type, out string property) { property = name.Substring(dot + 1).Trim(); } } - } internal class PropertyPath { - // See: MS.Internal.Data.PathParser - private static readonly char[] SpecialChars = { + static readonly char[] SpecialChars = { '.', '/', '[', ']' }; - private readonly PropertyPathPart[] parts; + readonly PropertyPathPart[] parts; public PropertyPath(string path) { parts = Parse(path); @@ -67,7 +62,7 @@ public PropertyPathPart[] Parts { get { return parts; } } - private static PropertyPathPart ReadIndexer(string path, ref int index, bool? isHiera) { + static PropertyPathPart ReadIndexer(string path, ref int index, bool? isHiera) { index++; var args = new List(); @@ -169,7 +164,7 @@ private static PropertyPathPart ReadIndexer(string path, ref int index, bool? is }; } - private static PropertyPathPart ReadProperty(string path, ref int index, bool? isHiera) { + static PropertyPathPart ReadProperty(string path, ref int index, bool? isHiera) { int begin = index; while (index < path.Length && path[index] == '.') index++; @@ -190,7 +185,7 @@ private static PropertyPathPart ReadProperty(string path, ref int index, bool? i return new PropertyPathPart(false, isHiera, name); } - private static PropertyPathPart[] Parse(string path) { + static PropertyPathPart[] Parse(string path) { if (string.IsNullOrEmpty(path)) return new[] { new PropertyPathPart(true, null, "") }; @@ -262,6 +257,5 @@ public override string ToString() { } return ret.ToString(); } - } } \ No newline at end of file diff --git a/Confuser.Renamer/GenericArgumentResolver.cs b/Confuser.Renamer/GenericArgumentResolver.cs index 4a7e8271b..396bacc49 100644 --- a/Confuser.Renamer/GenericArgumentResolver.cs +++ b/Confuser.Renamer/GenericArgumentResolver.cs @@ -7,9 +7,8 @@ namespace Confuser.Renamer { /// Resolves generic arguments /// public struct GenericArgumentResolver { - - private GenericArguments genericArguments; - private RecursionCounter recursionCounter; + GenericArguments genericArguments; + RecursionCounter recursionCounter; /// /// Resolves the type signature with the specified generic arguments. @@ -53,7 +52,7 @@ public static MethodSig Resolve(MethodSig methodSig, IList typeGenArgs) return resolver.ResolveGenericArgs(methodSig); } - private bool ReplaceGenericArg(ref TypeSig typeSig) { + bool ReplaceGenericArg(ref TypeSig typeSig) { if (genericArguments == null) return false; TypeSig newTypeSig = genericArguments.Resolve(typeSig); @@ -64,7 +63,7 @@ private bool ReplaceGenericArg(ref TypeSig typeSig) { return false; } - private MethodSig ResolveGenericArgs(MethodSig sig) { + MethodSig ResolveGenericArgs(MethodSig sig) { if (sig == null) return null; if (!recursionCounter.Increment()) @@ -76,7 +75,7 @@ private MethodSig ResolveGenericArgs(MethodSig sig) { return result; } - private MethodSig ResolveGenericArgs(MethodSig sig, MethodSig old) { + MethodSig ResolveGenericArgs(MethodSig sig, MethodSig old) { sig.RetType = ResolveGenericArgs(old.RetType); foreach (TypeSig p in old.Params) sig.Params.Add(ResolveGenericArgs(p)); @@ -88,7 +87,7 @@ private MethodSig ResolveGenericArgs(MethodSig sig, MethodSig old) { return sig; } - private TypeSig ResolveGenericArgs(TypeSig typeSig) { + TypeSig ResolveGenericArgs(TypeSig typeSig) { if (!recursionCounter.Increment()) return null; @@ -156,6 +155,5 @@ private TypeSig ResolveGenericArgs(TypeSig typeSig) { return result; } - } } \ No newline at end of file diff --git a/Confuser.Renamer/INameReference.cs b/Confuser.Renamer/INameReference.cs index 5680e7094..47d28d9e5 100644 --- a/Confuser.Renamer/INameReference.cs +++ b/Confuser.Renamer/INameReference.cs @@ -3,14 +3,10 @@ namespace Confuser.Renamer { public interface INameReference { - bool UpdateNameReference(ConfuserContext context, INameService service); bool ShouldCancelRename(); - } - public interface INameReference : INameReference { - - } + public interface INameReference : INameReference { } } \ No newline at end of file diff --git a/Confuser.Renamer/IRenamer.cs b/Confuser.Renamer/IRenamer.cs index dea39da83..10cd7cf1e 100644 --- a/Confuser.Renamer/IRenamer.cs +++ b/Confuser.Renamer/IRenamer.cs @@ -4,10 +4,8 @@ namespace Confuser.Renamer { public interface IRenamer { - void Analyze(ConfuserContext context, INameService service, IDnlibDef def); void PreRename(ConfuserContext context, INameService service, IDnlibDef def); void PostRename(ConfuserContext context, INameService service, IDnlibDef def); - } } \ No newline at end of file diff --git a/Confuser.Renamer/NameProtection.cs b/Confuser.Renamer/NameProtection.cs index d50f3492b..63d83fe5d 100644 --- a/Confuser.Renamer/NameProtection.cs +++ b/Confuser.Renamer/NameProtection.cs @@ -4,7 +4,6 @@ namespace Confuser.Renamer { internal class NameProtection : Protection { - public const string _Id = "rename"; public const string _FullId = "Ki.Rename"; public const string _ServiceId = "Ki.Rename"; @@ -40,8 +39,7 @@ protected override void PopulatePipeline(ProtectionPipeline pipeline) { pipeline.InsertPostStage(PipelineStage.SaveModules, new ExportMapPhase(this)); } - private class ExportMapPhase : ProtectionPhase { - + class ExportMapPhase : ProtectionPhase { public ExportMapPhase(NameProtection parent) : base(parent) { } @@ -73,8 +71,6 @@ protected override void Execute(ConfuserContext context, ProtectionParameters pa writer.WriteLine("{0}\t{1}", entry.Key, entry.Value); } } - } - } } \ No newline at end of file diff --git a/Confuser.Renamer/NameService.cs b/Confuser.Renamer/NameService.cs index 19e061d4c..1774f1554 100644 --- a/Confuser.Renamer/NameService.cs +++ b/Confuser.Renamer/NameService.cs @@ -9,7 +9,6 @@ namespace Confuser.Renamer { public interface INameService { - VTableStorage GetVTables(); void Analyze(IDnlibDef def); @@ -33,27 +32,25 @@ public interface INameService { void SetOriginalNamespace(object obj, string ns); void MarkHelper(IDnlibDef def, IMarkerService marker); - } internal class NameService : INameService { - - private static readonly object CanRenameKey = new object(); - private static readonly object RenameModeKey = new object(); - private static readonly object ReferencesKey = new object(); - private static readonly object OriginalNameKey = new object(); - private static readonly object OriginalNamespaceKey = new object(); - - private readonly ConfuserContext context; - private readonly byte[] nameSeed; - private readonly RandomGenerator random; - private readonly VTableStorage storage; - private AnalyzePhase analyze; - private readonly Dictionary nameDict = new Dictionary(); + static readonly object CanRenameKey = new object(); + static readonly object RenameModeKey = new object(); + static readonly object ReferencesKey = new object(); + static readonly object OriginalNameKey = new object(); + static readonly object OriginalNamespaceKey = new object(); + + readonly ConfuserContext context; + readonly byte[] nameSeed; + readonly RandomGenerator random; + readonly VTableStorage storage; + AnalyzePhase analyze; + readonly Dictionary nameDict = new Dictionary(); public NameService(ConfuserContext context) { this.context = context; - this.storage = new VTableStorage(context.Logger); + storage = new VTableStorage(context.Logger); random = context.Registry.GetService().GetRandomGenerator(NameProtection._FullId); nameSeed = random.NextBytes(20); @@ -62,7 +59,7 @@ public NameService(ConfuserContext context) { new VTableAnalyzer(), new TypeBlobAnalyzer(), new ResourceAnalyzer(), - new LdtokenEnumAnalyzer(), + new LdtokenEnumAnalyzer() }; } @@ -202,23 +199,23 @@ public void MarkHelper(IDnlibDef def, IMarkerService marker) { #region Charsets - private static readonly char[] asciiCharset = Enumerable.Range(32, 95) - .Select(ord => (char)ord) - .Except(new[] { '.' }) - .ToArray(); + static readonly char[] asciiCharset = Enumerable.Range(32, 95) + .Select(ord => (char)ord) + .Except(new[] { '.' }) + .ToArray(); - private static readonly char[] letterCharset = Enumerable.Range(0, 26) - .SelectMany(ord => new[] { (char)('a' + ord), (char)('A' + ord) }) - .ToArray(); + static readonly char[] letterCharset = Enumerable.Range(0, 26) + .SelectMany(ord => new[] { (char)('a' + ord), (char)('A' + ord) }) + .ToArray(); - private static readonly char[] alphaNumCharset = Enumerable.Range(0, 26) - .SelectMany(ord => new[] { (char)('a' + ord), (char)('A' + ord) }) - .Concat(Enumerable.Range(0, 10).Select(ord => (char)('0' + ord))) - .ToArray(); + static readonly char[] alphaNumCharset = Enumerable.Range(0, 26) + .SelectMany(ord => new[] { (char)('a' + ord), (char)('A' + ord) }) + .Concat(Enumerable.Range(0, 10).Select(ord => (char)('0' + ord))) + .ToArray(); // Especially chosen, just to mess with people. // Inspired by: http://xkcd.com/1137/ :D - private static readonly char[] unicodeCharset = new char[] { } + static readonly char[] unicodeCharset = new char[] { } .Concat(Enumerable.Range(0x200b, 5).Select(ord => (char)ord)) .Concat(Enumerable.Range(0x2029, 6).Select(ord => (char)ord)) .Concat(Enumerable.Range(0x206a, 6).Select(ord => (char)ord)) @@ -246,6 +243,5 @@ public string GetOriginalNamespace(object obj) { public ICollection> GetNameMap() { return nameDict; } - } } \ No newline at end of file diff --git a/Confuser.Renamer/PostRenamePhase.cs b/Confuser.Renamer/PostRenamePhase.cs index cbadeb609..6de13b5d4 100644 --- a/Confuser.Renamer/PostRenamePhase.cs +++ b/Confuser.Renamer/PostRenamePhase.cs @@ -4,7 +4,6 @@ namespace Confuser.Renamer { internal class PostRenamePhase : ProtectionPhase { - public PostRenamePhase(NameProtection parent) : base(parent) { } @@ -29,6 +28,5 @@ protected override void Execute(ConfuserContext context, ProtectionParameters pa context.CheckCancellation(); } } - } } \ No newline at end of file diff --git a/Confuser.Renamer/References/BAMLAttributeReference.cs b/Confuser.Renamer/References/BAMLAttributeReference.cs index 73fbd63cc..5bd0d2054 100644 --- a/Confuser.Renamer/References/BAMLAttributeReference.cs +++ b/Confuser.Renamer/References/BAMLAttributeReference.cs @@ -5,10 +5,9 @@ namespace Confuser.Renamer.References { internal class BAMLAttributeReference : INameReference { - - private readonly AttributeInfoRecord attrRec; - private readonly IDnlibDef member; - private readonly PropertyRecord propRec; + readonly AttributeInfoRecord attrRec; + readonly IDnlibDef member; + readonly PropertyRecord propRec; public BAMLAttributeReference(IDnlibDef member, AttributeInfoRecord rec) { this.member = member; @@ -31,6 +30,5 @@ public bool UpdateNameReference(ConfuserContext context, INameService service) { public bool ShouldCancelRename() { return false; } - } } \ No newline at end of file diff --git a/Confuser.Renamer/References/BAMLConverterMemberReference.cs b/Confuser.Renamer/References/BAMLConverterMemberReference.cs index 59da0d870..4bb0c8e97 100644 --- a/Confuser.Renamer/References/BAMLConverterMemberReference.cs +++ b/Confuser.Renamer/References/BAMLConverterMemberReference.cs @@ -5,11 +5,10 @@ namespace Confuser.Renamer.References { internal class BAMLConverterMemberReference : INameReference { - - private readonly IDnlibDef member; - private readonly PropertyRecord rec; - private readonly TypeSig sig; - private readonly BAMLAnalyzer.XmlNsContext xmlnsCtx; + readonly IDnlibDef member; + readonly PropertyRecord rec; + readonly TypeSig sig; + readonly BAMLAnalyzer.XmlNsContext xmlnsCtx; public BAMLConverterMemberReference(BAMLAnalyzer.XmlNsContext xmlnsCtx, TypeSig sig, IDnlibDef member, PropertyRecord rec) { this.xmlnsCtx = xmlnsCtx; @@ -30,6 +29,5 @@ public bool UpdateNameReference(ConfuserContext context, INameService service) { public bool ShouldCancelRename() { return false; } - } } \ No newline at end of file diff --git a/Confuser.Renamer/References/BAMLConverterTypeReference.cs b/Confuser.Renamer/References/BAMLConverterTypeReference.cs index ae0d56316..d5faa6e63 100644 --- a/Confuser.Renamer/References/BAMLConverterTypeReference.cs +++ b/Confuser.Renamer/References/BAMLConverterTypeReference.cs @@ -5,11 +5,10 @@ namespace Confuser.Renamer.References { internal class BAMLConverterTypeReference : INameReference { - - private readonly PropertyRecord propRec; - private readonly TypeSig sig; - private readonly TextRecord textRec; - private readonly BAMLAnalyzer.XmlNsContext xmlnsCtx; + readonly PropertyRecord propRec; + readonly TypeSig sig; + readonly TextRecord textRec; + readonly BAMLAnalyzer.XmlNsContext xmlnsCtx; public BAMLConverterTypeReference(BAMLAnalyzer.XmlNsContext xmlnsCtx, TypeSig sig, PropertyRecord rec) { this.xmlnsCtx = xmlnsCtx; @@ -38,6 +37,5 @@ public bool UpdateNameReference(ConfuserContext context, INameService service) { public bool ShouldCancelRename() { return false; } - } } \ No newline at end of file diff --git a/Confuser.Renamer/References/BAMLEnumReference.cs b/Confuser.Renamer/References/BAMLEnumReference.cs index 2888d988a..6b3483bd9 100644 --- a/Confuser.Renamer/References/BAMLEnumReference.cs +++ b/Confuser.Renamer/References/BAMLEnumReference.cs @@ -5,9 +5,8 @@ namespace Confuser.Renamer.References { internal class BAMLEnumReference : INameReference { - - private readonly FieldDef enumField; - private readonly PropertyRecord rec; + readonly FieldDef enumField; + readonly PropertyRecord rec; public BAMLEnumReference(FieldDef enumField, PropertyRecord rec) { this.enumField = enumField; @@ -22,6 +21,5 @@ public bool UpdateNameReference(ConfuserContext context, INameService service) { public bool ShouldCancelRename() { return false; } - } } \ No newline at end of file diff --git a/Confuser.Renamer/References/BAMLPathTypeReference.cs b/Confuser.Renamer/References/BAMLPathTypeReference.cs index eafd4a38c..68883e3a9 100644 --- a/Confuser.Renamer/References/BAMLPathTypeReference.cs +++ b/Confuser.Renamer/References/BAMLPathTypeReference.cs @@ -5,11 +5,10 @@ namespace Confuser.Renamer.References { internal class BAMLPathTypeReference : INameReference { - - private readonly PropertyPathPart attachedDP; - private readonly PropertyPathIndexer indexer; - private readonly TypeSig sig; - private readonly BAMLAnalyzer.XmlNsContext xmlnsCtx; + readonly PropertyPathPart attachedDP; + readonly PropertyPathIndexer indexer; + readonly TypeSig sig; + readonly BAMLAnalyzer.XmlNsContext xmlnsCtx; public BAMLPathTypeReference(BAMLAnalyzer.XmlNsContext xmlnsCtx, TypeSig sig, PropertyPathIndexer indexer) { this.xmlnsCtx = xmlnsCtx; @@ -44,6 +43,5 @@ public bool UpdateNameReference(ConfuserContext context, INameService service) { public bool ShouldCancelRename() { return false; } - } } \ No newline at end of file diff --git a/Confuser.Renamer/References/BAMLTypeReference.cs b/Confuser.Renamer/References/BAMLTypeReference.cs index 15da53111..dac084ec9 100644 --- a/Confuser.Renamer/References/BAMLTypeReference.cs +++ b/Confuser.Renamer/References/BAMLTypeReference.cs @@ -5,9 +5,8 @@ namespace Confuser.Renamer.References { internal class BAMLTypeReference : INameReference { - - private readonly TypeInfoRecord rec; - private readonly TypeSig sig; + readonly TypeInfoRecord rec; + readonly TypeSig sig; public BAMLTypeReference(TypeSig sig, TypeInfoRecord rec) { this.sig = sig; @@ -22,6 +21,5 @@ public bool UpdateNameReference(ConfuserContext context, INameService service) { public bool ShouldCancelRename() { return false; } - } } \ No newline at end of file diff --git a/Confuser.Renamer/References/CAMemberReference.cs b/Confuser.Renamer/References/CAMemberReference.cs index 4594eacef..37bebffc4 100644 --- a/Confuser.Renamer/References/CAMemberReference.cs +++ b/Confuser.Renamer/References/CAMemberReference.cs @@ -4,9 +4,8 @@ namespace Confuser.Renamer.References { internal class CAMemberReference : INameReference { - - private readonly IDnlibDef definition; - private readonly CANamedArgument namedArg; + readonly IDnlibDef definition; + readonly CANamedArgument namedArg; public CAMemberReference(CANamedArgument namedArg, IDnlibDef definition) { this.namedArg = namedArg; @@ -21,6 +20,5 @@ public bool UpdateNameReference(ConfuserContext context, INameService service) { public bool ShouldCancelRename() { return false; } - } } \ No newline at end of file diff --git a/Confuser.Renamer/References/MemberRefReference.cs b/Confuser.Renamer/References/MemberRefReference.cs index 876baf84e..637ed4ae0 100644 --- a/Confuser.Renamer/References/MemberRefReference.cs +++ b/Confuser.Renamer/References/MemberRefReference.cs @@ -4,9 +4,8 @@ namespace Confuser.Renamer.References { public class MemberRefReference : INameReference { - - private readonly IDnlibDef memberDef; - private readonly MemberRef memberRef; + readonly IDnlibDef memberDef; + readonly MemberRef memberRef; public MemberRefReference(MemberRef memberRef, IDnlibDef memberDef) { this.memberRef = memberRef; @@ -21,6 +20,5 @@ public bool UpdateNameReference(ConfuserContext context, INameService service) { public bool ShouldCancelRename() { return false; } - } } \ No newline at end of file diff --git a/Confuser.Renamer/References/OverrideDirectiveReference.cs b/Confuser.Renamer/References/OverrideDirectiveReference.cs index e4c2e6a20..9e4eaa0aa 100644 --- a/Confuser.Renamer/References/OverrideDirectiveReference.cs +++ b/Confuser.Renamer/References/OverrideDirectiveReference.cs @@ -5,9 +5,8 @@ namespace Confuser.Renamer.References { internal class OverrideDirectiveReference : INameReference { - - private readonly VTableSlot baseSlot; - private readonly VTableSlot thisSlot; + readonly VTableSlot baseSlot; + readonly VTableSlot thisSlot; public OverrideDirectiveReference(VTableSlot thisSlot, VTableSlot baseSlot) { this.thisSlot = thisSlot; @@ -44,6 +43,5 @@ public bool UpdateNameReference(ConfuserContext context, INameService service) { public bool ShouldCancelRename() { return false; } - } } \ No newline at end of file diff --git a/Confuser.Renamer/References/ResourceReference.cs b/Confuser.Renamer/References/ResourceReference.cs index 2f17e4695..1fbe2ee20 100644 --- a/Confuser.Renamer/References/ResourceReference.cs +++ b/Confuser.Renamer/References/ResourceReference.cs @@ -4,10 +4,9 @@ namespace Confuser.Renamer.References { internal class ResourceReference : INameReference { - - private readonly string format; - private readonly Resource resource; - private readonly TypeDef typeDef; + readonly string format; + readonly Resource resource; + readonly TypeDef typeDef; public ResourceReference(Resource resource, TypeDef typeDef, string format) { this.resource = resource; @@ -23,6 +22,5 @@ public bool UpdateNameReference(ConfuserContext context, INameService service) { public bool ShouldCancelRename() { return false; } - } } \ No newline at end of file diff --git a/Confuser.Renamer/References/StringTypeReference.cs b/Confuser.Renamer/References/StringTypeReference.cs index 05b7ec88d..f723b8743 100644 --- a/Confuser.Renamer/References/StringTypeReference.cs +++ b/Confuser.Renamer/References/StringTypeReference.cs @@ -5,9 +5,8 @@ namespace Confuser.Renamer.References { public class StringTypeReference : INameReference { - - private readonly Instruction reference; - private readonly TypeDef typeDef; + readonly Instruction reference; + readonly TypeDef typeDef; public StringTypeReference(Instruction reference, TypeDef typeDef) { this.reference = reference; @@ -22,6 +21,5 @@ public bool UpdateNameReference(ConfuserContext context, INameService service) { public bool ShouldCancelRename() { return false; } - } } \ No newline at end of file diff --git a/Confuser.Renamer/References/TypeRefReference.cs b/Confuser.Renamer/References/TypeRefReference.cs index 4ca3e7e47..1264b5edc 100644 --- a/Confuser.Renamer/References/TypeRefReference.cs +++ b/Confuser.Renamer/References/TypeRefReference.cs @@ -4,9 +4,8 @@ namespace Confuser.Renamer.References { public class TypeRefReference : INameReference { - - private readonly TypeDef typeDef; - private readonly TypeRef typeRef; + readonly TypeDef typeDef; + readonly TypeRef typeRef; public TypeRefReference(TypeRef typeRef, TypeDef typeDef) { this.typeRef = typeRef; @@ -22,6 +21,5 @@ public bool UpdateNameReference(ConfuserContext context, INameService service) { public bool ShouldCancelRename() { return false; } - } } \ No newline at end of file diff --git a/Confuser.Renamer/RenameMode.cs b/Confuser.Renamer/RenameMode.cs index f2caa4ee3..4bce72b5e 100644 --- a/Confuser.Renamer/RenameMode.cs +++ b/Confuser.Renamer/RenameMode.cs @@ -2,13 +2,11 @@ namespace Confuser.Renamer { public enum RenameMode { - Empty, Unicode, ASCII, Letters, Decodable, - Debug, - + Debug } } \ No newline at end of file diff --git a/Confuser.Renamer/RenamePhase.cs b/Confuser.Renamer/RenamePhase.cs index 153824d81..92a97a827 100644 --- a/Confuser.Renamer/RenamePhase.cs +++ b/Confuser.Renamer/RenamePhase.cs @@ -6,7 +6,6 @@ namespace Confuser.Renamer { internal class RenamePhase : ProtectionPhase { - public RenamePhase(NameProtection parent) : base(parent) { } @@ -76,6 +75,5 @@ protected override void Execute(ConfuserContext context, ProtectionParameters pa context.CheckCancellation(); } } - } } \ No newline at end of file diff --git a/Confuser.Renamer/VTable.cs b/Confuser.Renamer/VTable.cs index 982e34959..b974fa4d0 100644 --- a/Confuser.Renamer/VTable.cs +++ b/Confuser.Renamer/VTable.cs @@ -4,10 +4,10 @@ using System.Linq; using Confuser.Core; using dnlib.DotNet; +using ILogger = Confuser.Core.ILogger; namespace Confuser.Renamer { public class VTableSignature { - internal VTableSignature(MethodSig sig, string name) { MethodSig = sig; Name = name; @@ -30,7 +30,7 @@ public override bool Equals(object obj) { if (other == null) return false; return new SigComparer().Equals(MethodSig, other.MethodSig) && - Name.Equals(other.Name, StringComparison.Ordinal); + Name.Equals(other.Name, StringComparison.Ordinal); } public override int GetHashCode() { @@ -55,14 +55,11 @@ public override int GetHashCode() { public override string ToString() { return FullNameCreator.MethodFullName("", Name, MethodSig); } - } public class VTableSlot { - internal VTableSlot(MethodDef def, TypeSig decl, VTableSignature signature) - : this(def.DeclaringType.ToTypeSig(), def, decl, signature, null) { - } + : this(def.DeclaringType.ToTypeSig(), def, decl, signature, null) { } internal VTableSlot(TypeSig defDeclType, MethodDef def, TypeSig decl, VTableSignature signature, VTableSlot overrides) { MethodDefDeclType = defDeclType; @@ -95,11 +92,9 @@ internal VTableSlot Clone() { public override string ToString() { return MethodDef.ToString(); } - } public class VTable { - internal VTable(TypeSig type) { Type = type; Slots = new List(); @@ -141,10 +136,10 @@ public static VTable ConstructVTable(TypeDef typeDef, VTableStorage storage) { var ret = new VTable(typeDef.ToTypeSig()); var virtualMethods = typeDef.Methods - .Where(method => method.IsVirtual) - .ToDictionary( - method => VTableSignature.FromMethod(method), - method => method + .Where(method => method.IsVirtual) + .ToDictionary( + method => VTableSignature.FromMethod(method), + method => method ); // See Partition II 12.2 for implementation algorithm @@ -222,7 +217,7 @@ public static VTable ConstructVTable(TypeDef typeDef, VTableStorage storage) { else { var targetSlot = vTbl.AllSlots.Single(slot => slot.MethodDef == targetMethod); CheckKeyExist(storage, vTbl.SlotsMap, targetSlot.Signature, "MethodImpl Normal Sig"); - targetSlot = vTbl.SlotsMap[targetSlot.Signature]; // Use the most derived slot + targetSlot = vTbl.SlotsMap[targetSlot.Signature]; // Use the most derived slot // Maybe implemented by above processes --- this process should take priority while (targetSlot.MethodDef.DeclaringType == typeDef) targetSlot = targetSlot.Overrides; @@ -242,13 +237,13 @@ public static VTable ConstructVTable(TypeDef typeDef, VTableStorage storage) { return ret; } - private static void Implements(VTableConstruction vTbl, Dictionary virtualMethods, VTable ifaceVTbl, TypeSig iface) { + static void Implements(VTableConstruction vTbl, Dictionary virtualMethods, VTable ifaceVTbl, TypeSig iface) { // This is the step 2 of 12.2 algorithm -- use virtual newslot methods for explicit implementation. Func implLookup = slot => { MethodDef impl; if (virtualMethods.TryGetValue(slot.Signature, out impl) && - impl.IsNewSlot) { + impl.IsNewSlot) { // The Overrides of interface slots should directly points to the root interface slot var targetSlot = slot; while (targetSlot.Overrides != null && !targetSlot.MethodDef.DeclaringType.IsInterface) @@ -280,7 +275,7 @@ private static void Implements(VTableConstruction vTbl, Dictionary(VTableStorage storage, IDictionary dictionary, TKey key, string name) { + static void CheckKeyExist(VTableStorage storage, IDictionary dictionary, TKey key, string name) { if (!dictionary.ContainsKey(key)) { storage.GetLogger().ErrorFormat("{0} not found: {1}", name, key); foreach (var k in dictionary.Keys) @@ -311,14 +306,14 @@ private static void CheckKeyExist(VTableStorage storage, IDictiona } public class VTableStorage { - private Dictionary storage = new Dictionary(); - private Confuser.Core.ILogger logger; + Dictionary storage = new Dictionary(); + ILogger logger; - public VTableStorage(Confuser.Core.ILogger logger) { + public VTableStorage(ILogger logger) { this.logger = logger; } - public Confuser.Core.ILogger GetLogger() { + public ILogger GetLogger() { return logger; } @@ -327,7 +322,7 @@ public VTable this[TypeDef type] { internal set { storage[type] = value; } } - private VTable GetOrConstruct(TypeDef type) { + VTable GetOrConstruct(TypeDef type) { VTable ret; if (!storage.TryGetValue(type, out ret)) ret = storage[type] = VTable.ConstructVTable(type, this); @@ -339,29 +334,27 @@ public VTable GetVTable(ITypeDefOrRef type) { return null; if (type is TypeDef) return GetOrConstruct((TypeDef)type); - else if (type is TypeRef) + if (type is TypeRef) return GetOrConstruct(((TypeRef)type).ResolveThrow()); - else if (type is TypeSpec) { + if (type is TypeSpec) { TypeSig sig = ((TypeSpec)type).TypeSig; if (sig is TypeDefOrRefSig) { TypeDef typeDef = ((TypeDefOrRefSig)sig).TypeDefOrRef.ResolveTypeDefThrow(); return GetOrConstruct(typeDef); } - else if (sig is GenericInstSig) { + if (sig is GenericInstSig) { var genInst = (GenericInstSig)sig; TypeDef openType = genInst.GenericType.TypeDefOrRef.ResolveTypeDefThrow(); VTable vTable = GetOrConstruct(openType); return ResolveGenericArgument(openType, genInst, vTable); } - else - throw new NotSupportedException("Unexpected type: " + type.ToString()); + throw new NotSupportedException("Unexpected type: " + type); } - else - throw new UnreachableException(); + throw new UnreachableException(); } - private static VTableSlot ResolveSlot(TypeDef openType, VTableSlot slot, IList genArgs) { + static VTableSlot ResolveSlot(TypeDef openType, VTableSlot slot, IList genArgs) { var newSig = GenericArgumentResolver.Resolve(slot.Signature.MethodSig, genArgs); TypeSig newDecl = slot.MethodDefDeclType; if (new SigComparer().Equals(newDecl, openType)) @@ -371,7 +364,7 @@ private static VTableSlot ResolveSlot(TypeDef openType, VTableSlot slot, IList ResolveSlot(openType, slot, genInst.GenericArguments)).ToList()); + iface.Value.Select(slot => ResolveSlot(openType, slot, genInst.GenericArguments)).ToList()); } return ret; } - } } \ No newline at end of file diff --git a/Confuser.Runtime/AntiDebug.Antinet.cs b/Confuser.Runtime/AntiDebug.Antinet.cs index 97df6ba8d..ce323bb0b 100644 --- a/Confuser.Runtime/AntiDebug.Antinet.cs +++ b/Confuser.Runtime/AntiDebug.Antinet.cs @@ -2,8 +2,7 @@ namespace Confuser.Runtime { static partial class AntiDebugAntinet { - - private static void Initialize() { + static void Initialize() { if (!InitializeAntiDebugger()) Environment.FailFast(null); InitializeAntiProfiler(); @@ -12,6 +11,5 @@ private static void Initialize() { PreventActiveProfilerFromReceivingProfilingMessages(); } } - } } \ No newline at end of file diff --git a/Confuser.Runtime/AntiDebug.Safe.cs b/Confuser.Runtime/AntiDebug.Safe.cs index d077db609..9457ee467 100644 --- a/Confuser.Runtime/AntiDebug.Safe.cs +++ b/Confuser.Runtime/AntiDebug.Safe.cs @@ -4,8 +4,7 @@ namespace Confuser.Runtime { internal static class AntiDebugSafe { - - private static void Initialize() { + static void Initialize() { string x = "COR"; if (Environment.GetEnvironmentVariable(x + "_PROFILER") != null || Environment.GetEnvironmentVariable(x + "_ENABLE_PROFILING") != null) @@ -16,7 +15,7 @@ private static void Initialize() { thread.Start(null); } - private static void Worker(object thread) { + static void Worker(object thread) { var th = thread as Thread; if (th == null) { th = new Thread(Worker); @@ -34,6 +33,5 @@ private static void Worker(object thread) { Thread.Sleep(1000); } } - } } \ No newline at end of file diff --git a/Confuser.Runtime/AntiDebug.Win32.cs b/Confuser.Runtime/AntiDebug.Win32.cs index 3420a9458..9867f3964 100644 --- a/Confuser.Runtime/AntiDebug.Win32.cs +++ b/Confuser.Runtime/AntiDebug.Win32.cs @@ -5,8 +5,7 @@ namespace Confuser.Runtime { internal static class AntiDebugWin32 { - - private static void Initialize() { + static void Initialize() { string x = "COR"; if (Environment.GetEnvironmentVariable(x + "_PROFILER") != null || Environment.GetEnvironmentVariable(x + "_ENABLE_PROFILING") != null) @@ -18,15 +17,15 @@ private static void Initialize() { } [DllImport("kernel32.dll")] - private static extern bool CloseHandle(IntPtr hObject); + static extern bool CloseHandle(IntPtr hObject); [DllImport("kernel32.dll")] - private static extern bool IsDebuggerPresent(); + static extern bool IsDebuggerPresent(); [DllImport("kernel32.dll")] - private static extern int OutputDebugString(string str); + static extern int OutputDebugString(string str); - private static void Worker(object thread) { + static void Worker(object thread) { var th = thread as Thread; if (th == null) { th = new Thread(Worker); @@ -67,6 +66,5 @@ private static void Worker(object thread) { Thread.Sleep(1000); } } - } } \ No newline at end of file diff --git a/Confuser.Runtime/AntiDump.cs b/Confuser.Runtime/AntiDump.cs index f06200644..d56177912 100644 --- a/Confuser.Runtime/AntiDump.cs +++ b/Confuser.Runtime/AntiDump.cs @@ -4,11 +4,10 @@ namespace Confuser.Runtime { internal static class AntiDump { - [DllImport("kernel32.dll")] - private static extern unsafe bool VirtualProtect(byte* lpAddress, int dwSize, uint flNewProtect, out uint lpflOldProtect); + static extern unsafe bool VirtualProtect(byte* lpAddress, int dwSize, uint flNewProtect, out uint lpflOldProtect); - private static unsafe void Initialize() { + static unsafe void Initialize() { uint old; Module module = typeof(AntiDump).Module; var bas = (byte*)Marshal.GetHINSTANCE(module); @@ -235,6 +234,5 @@ private static unsafe void Initialize() { } } } - } } \ No newline at end of file diff --git a/Confuser.Runtime/AntiTamper.JIT.cs b/Confuser.Runtime/AntiTamper.JIT.cs index 2c3733145..163c16ca5 100644 --- a/Confuser.Runtime/AntiTamper.JIT.cs +++ b/Confuser.Runtime/AntiTamper.JIT.cs @@ -5,16 +5,15 @@ namespace Confuser.Runtime { internal static unsafe class AntiTamperJIT { + static uint* ptr; + static uint len; + static IntPtr moduleHnd; + static compileMethod originalDelegate; - private static uint* ptr; - private static uint len; - private static IntPtr moduleHnd; - private static compileMethod originalDelegate; + static bool ver4; + static bool ver5; - private static bool ver4; - private static bool ver5; - - private static compileMethod handler; + static compileMethod handler; public static void Initialize() { Module m = typeof(AntiTamperNormal).Module; @@ -87,15 +86,15 @@ public static void Initialize() { } [DllImport("kernel32.dll")] - private static extern IntPtr LoadLibrary(string lib); + static extern IntPtr LoadLibrary(string lib); [DllImport("kernel32.dll")] - private static extern IntPtr GetProcAddress(IntPtr lib, string proc); + static extern IntPtr GetProcAddress(IntPtr lib, string proc); [DllImport("kernel32.dll")] - private static extern bool VirtualProtect(IntPtr lpAddress, uint dwSize, uint flNewProtect, out uint lpflOldProtect); + static extern bool VirtualProtect(IntPtr lpAddress, uint dwSize, uint flNewProtect, out uint lpflOldProtect); - private static void Hook() { + static void Hook() { ulong* ptr = stackalloc ulong[2]; if (ver4) { ptr[0] = 0x642e74696a726c63; //clrjit.d @@ -142,7 +141,7 @@ private static void Hook() { VirtualProtect(hookPosition, (uint)IntPtr.Size, oldPl, out oldPl); } - private static void ExtractLocalVars(CORINFO_METHOD_INFO* info, uint len, byte* localVar) { + static void ExtractLocalVars(CORINFO_METHOD_INFO* info, uint len, byte* localVar) { void* sigInfo; if (ver4) { if (IntPtr.Size == 8) @@ -192,7 +191,7 @@ private static void ExtractLocalVars(CORINFO_METHOD_INFO* info, uint len, byte* } } - private static uint HookHandler(IntPtr self, ICorJitInfo* comp, CORINFO_METHOD_INFO* info, uint flags, byte** nativeEntry, uint* nativeSizeOfCode) { + static uint HookHandler(IntPtr self, ICorJitInfo* comp, CORINFO_METHOD_INFO* info, uint flags, byte** nativeEntry, uint* nativeSizeOfCode) { if (info != null && info->scope == moduleHnd && info->ILCode[0] == 0x14) { uint token; if (ver5) { @@ -285,46 +284,39 @@ private static uint HookHandler(IntPtr self, ICorJitInfo* comp, CORINFO_METHOD_I #region JIT internal - private static bool hasLinkInfo; + static bool hasLinkInfo; [StructLayout(LayoutKind.Sequential, Size = 0x18)] - private struct CORINFO_EH_CLAUSE { - - } + struct CORINFO_EH_CLAUSE { } [StructLayout(LayoutKind.Sequential, Pack = 1)] - private struct CORINFO_METHOD_INFO { - + struct CORINFO_METHOD_INFO { public IntPtr ftn; public IntPtr scope; public byte* ILCode; public uint ILCodeSize; - } [StructLayout(LayoutKind.Sequential)] - private struct CORINFO_SIG_INFO_x64 { - + struct CORINFO_SIG_INFO_x64 { public uint callConv; - private uint pad1; + uint pad1; public IntPtr retTypeClass; public IntPtr retTypeSigClass; public byte retType; public byte flags; public ushort numArgs; - private uint pad2; + uint pad2; public CORINFO_SIG_INST_x64 sigInst; public IntPtr args; public IntPtr sig; public IntPtr scope; public uint token; - private uint pad3; - + uint pad3; } [StructLayout(LayoutKind.Sequential)] - private struct CORINFO_SIG_INFO_x86 { - + struct CORINFO_SIG_INFO_x86 { public uint callConv; public IntPtr retTypeClass; public IntPtr retTypeSigClass; @@ -336,41 +328,31 @@ private struct CORINFO_SIG_INFO_x86 { public IntPtr sig; public IntPtr scope; public uint token; - } [StructLayout(LayoutKind.Sequential, Size = 32)] - private struct CORINFO_SIG_INST_x64 { - - } + struct CORINFO_SIG_INST_x64 { } [StructLayout(LayoutKind.Sequential, Size = 16)] - private struct CORINFO_SIG_INST_x86 { - - } + struct CORINFO_SIG_INST_x86 { } [StructLayout(LayoutKind.Sequential)] - private struct ICorClassInfo { - + struct ICorClassInfo { public readonly IntPtr* vfptr; - } [StructLayout(LayoutKind.Sequential)] - private struct ICorDynamicInfo { - + struct ICorDynamicInfo { public IntPtr* vfptr; public int* vbptr; public static ICorStaticInfo* ICorStaticInfo(ICorDynamicInfo* ptr) { return (ICorStaticInfo*)((byte*)&ptr->vbptr + ptr->vbptr[hasLinkInfo ? 9 : 8]); } - } [StructLayout(LayoutKind.Sequential)] - private struct ICorJitInfo { - + struct ICorJitInfo { public IntPtr* vfptr; public int* vbptr; @@ -378,26 +360,20 @@ private struct ICorJitInfo { hasLinkInfo = ptr->vbptr[10] > 0 && ptr->vbptr[10] >> 16 == 0; // != 0 and hiword byte == 0 return (ICorDynamicInfo*)((byte*)&ptr->vbptr + ptr->vbptr[hasLinkInfo ? 10 : 9]); } - } [StructLayout(LayoutKind.Sequential)] - private struct ICorMethodInfo { - + struct ICorMethodInfo { public IntPtr* vfptr; - } [StructLayout(LayoutKind.Sequential)] - private struct ICorModuleInfo { - + struct ICorModuleInfo { public IntPtr* vfptr; - } [StructLayout(LayoutKind.Sequential)] - private struct ICorStaticInfo { - + struct ICorStaticInfo { public IntPtr* vfptr; public int* vbptr; @@ -412,14 +388,12 @@ private struct ICorStaticInfo { public static ICorClassInfo* ICorClassInfo(ICorStaticInfo* ptr) { return (ICorClassInfo*)((byte*)&ptr->vbptr + ptr->vbptr[3]); } - } #endregion - private class CorMethodInfoHook { - - private static int ehNum = -1; + class CorMethodInfoHook { + static int ehNum = -1; public CORINFO_EH_CLAUSE* clauses; public IntPtr ftn; public ICorMethodInfo* info; @@ -429,7 +403,7 @@ private class CorMethodInfoHook { public getEHinfo o_getEHinfo; public IntPtr* oldVfTbl; - private void hookEHInfo(IntPtr self, IntPtr ftn, uint EHnumber, CORINFO_EH_CLAUSE* clause) { + void hookEHInfo(IntPtr self, IntPtr ftn, uint EHnumber, CORINFO_EH_CLAUSE* clause) { if (ftn == this.ftn) { *clause = clauses[EHnumber]; } @@ -481,11 +455,9 @@ public static CorMethodInfoHook Hook(ICorJitInfo* comp, IntPtr ftn, CORINFO_EH_C mtdInfo->vfptr = newVfTbl; return ret; } - } - private class CorJitInfoHook { - + class CorJitInfoHook { public CORINFO_EH_CLAUSE* clauses; public IntPtr ftn; public ICorJitInfo* info; @@ -495,7 +467,7 @@ private class CorJitInfoHook { public getEHinfo o_getEHinfo; public IntPtr* oldVfTbl; - private void hookEHInfo(IntPtr self, IntPtr ftn, uint EHnumber, CORINFO_EH_CLAUSE* clause) { + void hookEHInfo(IntPtr self, IntPtr ftn, uint EHnumber, CORINFO_EH_CLAUSE* clause) { if (ftn == this.ftn) { *clause = clauses[EHnumber]; } @@ -533,31 +505,27 @@ public static CorJitInfoHook Hook(ICorJitInfo* comp, IntPtr ftn, CORINFO_EH_CLAU comp->vfptr = newVfTbl; return ret; } - } [StructLayout(LayoutKind.Sequential)] - private struct MethodData { - + struct MethodData { public readonly uint ILCodeSize; public readonly uint MaxStack; public readonly uint EHCount; public readonly uint LocalVars; public readonly uint Options; public readonly uint MulSeed; - } [UnmanagedFunctionPointer(CallingConvention.StdCall)] - private delegate uint compileMethod(IntPtr self, ICorJitInfo* comp, CORINFO_METHOD_INFO* info, uint flags, byte** nativeEntry, uint* nativeSizeOfCode); + delegate uint compileMethod(IntPtr self, ICorJitInfo* comp, CORINFO_METHOD_INFO* info, uint flags, byte** nativeEntry, uint* nativeSizeOfCode); [UnmanagedFunctionPointer(CallingConvention.ThisCall)] - private delegate void getEHinfo(IntPtr self, IntPtr ftn, uint EHnumber, CORINFO_EH_CLAUSE* clause); + delegate void getEHinfo(IntPtr self, IntPtr ftn, uint EHnumber, CORINFO_EH_CLAUSE* clause); - private delegate IntPtr* getJit(); + delegate IntPtr* getJit(); [UnmanagedFunctionPointer(CallingConvention.ThisCall)] - private delegate uint getMethodDefFromMethod(IntPtr self, IntPtr ftn); - + delegate uint getMethodDefFromMethod(IntPtr self, IntPtr ftn); } } \ No newline at end of file diff --git a/Confuser.Runtime/AntiTamper.Normal.cs b/Confuser.Runtime/AntiTamper.Normal.cs index 45241c915..87062828a 100644 --- a/Confuser.Runtime/AntiTamper.Normal.cs +++ b/Confuser.Runtime/AntiTamper.Normal.cs @@ -4,11 +4,10 @@ namespace Confuser.Runtime { internal static class AntiTamperNormal { - [DllImport("kernel32.dll")] - private static extern bool VirtualProtect(IntPtr lpAddress, uint dwSize, uint flNewProtect, out uint lpflOldProtect); + static extern bool VirtualProtect(IntPtr lpAddress, uint dwSize, uint flNewProtect, out uint lpflOldProtect); - private static unsafe void Initialize() { + static unsafe void Initialize() { Module m = typeof(AntiTamperNormal).Module; string n = m.FullyQualifiedName; bool f = n.Length > 0 && n[0] == '<'; @@ -62,6 +61,5 @@ private static unsafe void Initialize() { h++; } } - } } \ No newline at end of file diff --git a/Confuser.Runtime/Compressor.cs b/Confuser.Runtime/Compressor.cs index 94b44e19b..8297448c4 100644 --- a/Confuser.Runtime/Compressor.cs +++ b/Confuser.Runtime/Compressor.cs @@ -6,10 +6,9 @@ namespace Confuser.Runtime { internal static class Compressor { + static byte[] key; - private static byte[] key; - - private static GCHandle Decrypt(uint[] data, uint seed) { + static GCHandle Decrypt(uint[] data, uint seed) { var w = new uint[0x10]; var k = new uint[0x10]; ulong s = seed; @@ -47,7 +46,7 @@ private static GCHandle Decrypt(uint[] data, uint seed) { } [STAThread] - private static int Main(string[] args) { + static int Main(string[] args) { var l = (uint)Mutation.KeyI0; uint[] q = Mutation.Placeholder(new uint[Mutation.KeyI0]); @@ -73,7 +72,7 @@ private static int Main(string[] args) { return 0; } - private static Assembly Resolve(object sender, ResolveEventArgs e) { + static Assembly Resolve(object sender, ResolveEventArgs e) { byte[] b = Encoding.UTF8.GetBytes(e.Name); Stream m = null; @@ -107,6 +106,5 @@ private static Assembly Resolve(object sender, ResolveEventArgs e) { } return null; } - } } \ No newline at end of file diff --git a/Confuser.Runtime/Constant.cs b/Confuser.Runtime/Constant.cs index a99f2d411..53a59783e 100644 --- a/Confuser.Runtime/Constant.cs +++ b/Confuser.Runtime/Constant.cs @@ -3,10 +3,9 @@ namespace Confuser.Runtime { internal static class Constant { + static byte[] b; - private static byte[] b; - - private static void Initialize() { + static void Initialize() { var l = (uint)Mutation.KeyI0; uint[] q = Mutation.Placeholder(new uint[Mutation.KeyI0]); @@ -40,7 +39,7 @@ private static void Initialize() { b = Lzma.Decompress(o); } - private static T Get(uint id) { + static T Get(uint id) { id = (uint)Mutation.Placeholder((int)id); uint t = id >> 30; @@ -52,7 +51,7 @@ private static T Get(uint id) { int l = b[id++] | (b[id++] << 8) | (b[id++] << 16) | (b[id++] << 24); ret = (T)(object)Encoding.UTF8.GetString(b, (int)id, l); } - // NOTE: Assume little-endian + // NOTE: Assume little-endian else if (t == Mutation.KeyI1) { var v = new T[1]; Buffer.BlockCopy(b, (int)id, v, 0, Mutation.Value()); @@ -67,6 +66,5 @@ private static T Get(uint id) { } return ret; } - } } \ No newline at end of file diff --git a/Confuser.Runtime/Lzma.cs b/Confuser.Runtime/Lzma.cs index a622e4d3e..5f72fa606 100644 --- a/Confuser.Runtime/Lzma.cs +++ b/Confuser.Runtime/Lzma.cs @@ -3,31 +3,30 @@ namespace Confuser.Runtime { internal static class Lzma { + const uint kNumStates = 12; - private const uint kNumStates = 12; + const int kNumPosSlotBits = 6; - private const int kNumPosSlotBits = 6; + const uint kNumLenToPosStates = 4; - private const uint kNumLenToPosStates = 4; + const uint kMatchMinLen = 2; - private const uint kMatchMinLen = 2; + const int kNumAlignBits = 4; + const uint kAlignTableSize = 1 << kNumAlignBits; - private const int kNumAlignBits = 4; - private const uint kAlignTableSize = 1 << kNumAlignBits; + const uint kStartPosModelIndex = 4; + const uint kEndPosModelIndex = 14; - private const uint kStartPosModelIndex = 4; - private const uint kEndPosModelIndex = 14; + const uint kNumFullDistances = 1 << ((int)kEndPosModelIndex / 2); - private const uint kNumFullDistances = 1 << ((int)kEndPosModelIndex / 2); + const int kNumPosStatesBitsMax = 4; + const uint kNumPosStatesMax = (1 << kNumPosStatesBitsMax); - private const int kNumPosStatesBitsMax = 4; - private const uint kNumPosStatesMax = (1 << kNumPosStatesBitsMax); - - private const int kNumLowLenBits = 3; - private const int kNumMidLenBits = 3; - private const int kNumHighLenBits = 8; - private const uint kNumLowLenSymbols = 1 << kNumLowLenBits; - private const uint kNumMidLenSymbols = 1 << kNumMidLenBits; + const int kNumLowLenBits = 3; + const int kNumMidLenBits = 3; + const int kNumHighLenBits = 8; + const uint kNumLowLenSymbols = 1 << kNumLowLenBits; + const uint kNumMidLenSymbols = 1 << kNumMidLenBits; public static byte[] Decompress(byte[] data) { var s = new MemoryStream(data); @@ -47,13 +46,12 @@ public static byte[] Decompress(byte[] data) { return b; } - private struct BitDecoder { - + struct BitDecoder { public const int kNumBitModelTotalBits = 11; public const uint kBitModelTotal = (1 << kNumBitModelTotalBits); - private const int kNumMoveBits = 5; + const int kNumMoveBits = 5; - private uint Prob; + uint Prob; public void Init() { Prob = kBitModelTotal >> 1; @@ -79,13 +77,11 @@ public uint Decode(Decoder rangeDecoder) { } return 1; } - } - private struct BitTreeDecoder { - - private readonly BitDecoder[] Models; - private readonly int NumBitLevels; + struct BitTreeDecoder { + readonly BitDecoder[] Models; + readonly int NumBitLevels; public BitTreeDecoder(int numBitLevels) { NumBitLevels = numBitLevels; @@ -128,11 +124,9 @@ public static uint ReverseDecode(BitDecoder[] Models, UInt32 startIndex, } return symbol; } - } - private class Decoder { - + class Decoder { public const uint kTopValue = (1 << 24); public uint Code; public uint Range; @@ -186,33 +180,31 @@ public uint DecodeDirectBits(int numTotalBits) { Code = code; return result; } - } - private class LzmaDecoder { - - private readonly BitDecoder[] m_IsMatchDecoders = new BitDecoder[kNumStates << kNumPosStatesBitsMax]; - private readonly BitDecoder[] m_IsRep0LongDecoders = new BitDecoder[kNumStates << kNumPosStatesBitsMax]; - private readonly BitDecoder[] m_IsRepDecoders = new BitDecoder[kNumStates]; - private readonly BitDecoder[] m_IsRepG0Decoders = new BitDecoder[kNumStates]; - private readonly BitDecoder[] m_IsRepG1Decoders = new BitDecoder[kNumStates]; - private readonly BitDecoder[] m_IsRepG2Decoders = new BitDecoder[kNumStates]; + class LzmaDecoder { + readonly BitDecoder[] m_IsMatchDecoders = new BitDecoder[kNumStates << kNumPosStatesBitsMax]; + readonly BitDecoder[] m_IsRep0LongDecoders = new BitDecoder[kNumStates << kNumPosStatesBitsMax]; + readonly BitDecoder[] m_IsRepDecoders = new BitDecoder[kNumStates]; + readonly BitDecoder[] m_IsRepG0Decoders = new BitDecoder[kNumStates]; + readonly BitDecoder[] m_IsRepG1Decoders = new BitDecoder[kNumStates]; + readonly BitDecoder[] m_IsRepG2Decoders = new BitDecoder[kNumStates]; - private readonly LenDecoder m_LenDecoder = new LenDecoder(); + readonly LenDecoder m_LenDecoder = new LenDecoder(); - private readonly LiteralDecoder m_LiteralDecoder = new LiteralDecoder(); - private readonly OutWindow m_OutWindow = new OutWindow(); - private readonly BitDecoder[] m_PosDecoders = new BitDecoder[kNumFullDistances - kEndPosModelIndex]; - private readonly BitTreeDecoder[] m_PosSlotDecoder = new BitTreeDecoder[kNumLenToPosStates]; - private readonly Decoder m_RangeDecoder = new Decoder(); - private readonly LenDecoder m_RepLenDecoder = new LenDecoder(); - private bool _solid = false; + readonly LiteralDecoder m_LiteralDecoder = new LiteralDecoder(); + readonly OutWindow m_OutWindow = new OutWindow(); + readonly BitDecoder[] m_PosDecoders = new BitDecoder[kNumFullDistances - kEndPosModelIndex]; + readonly BitTreeDecoder[] m_PosSlotDecoder = new BitTreeDecoder[kNumLenToPosStates]; + readonly Decoder m_RangeDecoder = new Decoder(); + readonly LenDecoder m_RepLenDecoder = new LenDecoder(); + bool _solid = false; - private uint m_DictionarySize; - private uint m_DictionarySizeCheck; - private BitTreeDecoder m_PosAlignDecoder = new BitTreeDecoder(kNumAlignBits); + uint m_DictionarySize; + uint m_DictionarySizeCheck; + BitTreeDecoder m_PosAlignDecoder = new BitTreeDecoder(kNumAlignBits); - private uint m_PosStateMask; + uint m_PosStateMask; public LzmaDecoder() { m_DictionarySize = 0xFFFFFFFF; @@ -220,7 +212,7 @@ public LzmaDecoder() { m_PosSlotDecoder[i] = new BitTreeDecoder(kNumPosSlotBits); } - private void SetDictionarySize(uint dictionarySize) { + void SetDictionarySize(uint dictionarySize) { if (m_DictionarySize != dictionarySize) { m_DictionarySize = dictionarySize; m_DictionarySizeCheck = Math.Max(m_DictionarySize, 1); @@ -229,18 +221,18 @@ private void SetDictionarySize(uint dictionarySize) { } } - private void SetLiteralProperties(int lp, int lc) { + void SetLiteralProperties(int lp, int lc) { m_LiteralDecoder.Create(lp, lc); } - private void SetPosBitsProperties(int pb) { + void SetPosBitsProperties(int pb) { uint numPosStates = (uint)1 << pb; m_LenDecoder.Create(numPosStates); m_RepLenDecoder.Create(numPosStates); m_PosStateMask = numPosStates - 1; } - private void Init(Stream inStream, Stream outStream) { + void Init(Stream inStream, Stream outStream) { m_RangeDecoder.Init(inStream); m_OutWindow.Init(outStream, _solid); @@ -383,21 +375,20 @@ public void SetDecoderProperties(byte[] properties) { SetPosBitsProperties(pb); } - private static uint GetLenToPosState(uint len) { + static uint GetLenToPosState(uint len) { len -= kMatchMinLen; if (len < kNumLenToPosStates) return len; return unchecked((kNumLenToPosStates - 1)); } - private class LenDecoder { - - private readonly BitTreeDecoder[] m_LowCoder = new BitTreeDecoder[kNumPosStatesMax]; - private readonly BitTreeDecoder[] m_MidCoder = new BitTreeDecoder[kNumPosStatesMax]; - private BitDecoder m_Choice = new BitDecoder(); - private BitDecoder m_Choice2 = new BitDecoder(); - private BitTreeDecoder m_HighCoder = new BitTreeDecoder(kNumHighLenBits); - private uint m_NumPosStates; + class LenDecoder { + readonly BitTreeDecoder[] m_LowCoder = new BitTreeDecoder[kNumPosStatesMax]; + readonly BitTreeDecoder[] m_MidCoder = new BitTreeDecoder[kNumPosStatesMax]; + BitDecoder m_Choice = new BitDecoder(); + BitDecoder m_Choice2 = new BitDecoder(); + BitTreeDecoder m_HighCoder = new BitTreeDecoder(kNumHighLenBits); + uint m_NumPosStates; public void Create(uint numPosStates) { for (uint posState = m_NumPosStates; posState < numPosStates; posState++) { @@ -429,15 +420,13 @@ public uint Decode(Decoder rangeDecoder, uint posState) { } return symbol; } - } - private class LiteralDecoder { - - private Decoder2[] m_Coders; - private int m_NumPosBits; - private int m_NumPrevBits; - private uint m_PosMask; + class LiteralDecoder { + Decoder2[] m_Coders; + int m_NumPosBits; + int m_NumPrevBits; + uint m_PosMask; public void Create(int numPosBits, int numPrevBits) { if (m_Coders != null && m_NumPrevBits == numPrevBits && @@ -458,7 +447,7 @@ public void Init() { m_Coders[i].Init(); } - private uint GetState(uint pos, byte prevByte) { + uint GetState(uint pos, byte prevByte) { return ((pos & m_PosMask) << m_NumPrevBits) + (uint)(prevByte >> (8 - m_NumPrevBits)); } @@ -470,9 +459,8 @@ public byte DecodeWithMatchByte(Decoder rangeDecoder, uint pos, byte prevByte, b return m_Coders[GetState(pos, prevByte)].DecodeWithMatchByte(rangeDecoder, matchByte); } - private struct Decoder2 { - - private BitDecoder[] m_Decoders; + struct Decoder2 { + BitDecoder[] m_Decoders; public void Create() { m_Decoders = new BitDecoder[0x300]; @@ -504,20 +492,16 @@ public byte DecodeWithMatchByte(Decoder rangeDecoder, byte matchByte) { } while (symbol < 0x100); return (byte)symbol; } - } - }; - } - private class OutWindow { - - private byte[] _buffer; - private uint _pos; - private Stream _stream; - private uint _streamPos; - private uint _windowSize; + class OutWindow { + byte[] _buffer; + uint _pos; + Stream _stream; + uint _streamPos; + uint _windowSize; public void Create(uint windowSize) { if (_windowSize != windowSize) { @@ -578,11 +562,9 @@ public byte GetByte(uint distance) { pos += _windowSize; return _buffer[pos]; } - } - private struct State { - + struct State { public uint Index; public void Init() { @@ -610,8 +592,6 @@ public void UpdateShortRep() { public bool IsCharState() { return Index < 7; } - } - } } \ No newline at end of file diff --git a/Confuser.Runtime/Mutation.cs b/Confuser.Runtime/Mutation.cs index ca7105600..c95881747 100644 --- a/Confuser.Runtime/Mutation.cs +++ b/Confuser.Runtime/Mutation.cs @@ -1,7 +1,6 @@ using System; internal class Mutation { - public static readonly int KeyI0 = 0; public static readonly int KeyI1 = 1; public static readonly int KeyI2 = 2; @@ -32,5 +31,4 @@ public static T Value(Arg0 arg0) { } public static void Crypt(uint[] data, uint[] key) { } - } \ No newline at end of file diff --git a/Confuser.Runtime/RefProxy.Strong.cs b/Confuser.Runtime/RefProxy.Strong.cs index 329d27389..c82961ce1 100644 --- a/Confuser.Runtime/RefProxy.Strong.cs +++ b/Confuser.Runtime/RefProxy.Strong.cs @@ -4,8 +4,7 @@ namespace Confuser.Runtime { internal class RefProxyKey : Attribute { - - private readonly int key; + readonly int key; public RefProxyKey(int key) { this.key = Mutation.Placeholder(key); @@ -14,11 +13,9 @@ public RefProxyKey(int key) { public override int GetHashCode() { return key; } - } internal static class RefProxyStrong { - internal static void Initialize(RuntimeFieldHandle field, byte opKey) { FieldInfo fieldInfo = FieldInfo.GetFieldFromHandle(field); byte[] sig = fieldInfo.Module.ResolveSignature(fieldInfo.MetadataToken); @@ -75,6 +72,5 @@ internal static void Initialize(RuntimeFieldHandle field, byte opKey) { fieldInfo.SetValue(null, dm.CreateDelegate(delegateType)); } } - } } \ No newline at end of file diff --git a/Confuser.Runtime/Resource.cs b/Confuser.Runtime/Resource.cs index 49635afc9..194af7ce1 100644 --- a/Confuser.Runtime/Resource.cs +++ b/Confuser.Runtime/Resource.cs @@ -3,11 +3,10 @@ namespace Confuser.Runtime { internal static class Resource { - - private static Assembly c; + static Assembly c; // Hmm... Too lazy. - private static void Initialize() { + static void Initialize() { var l = (uint)Mutation.KeyI0; uint[] q = Mutation.Placeholder(new uint[Mutation.KeyI0]); @@ -42,20 +41,18 @@ private static void Initialize() { AppDomain.CurrentDomain.AssemblyResolve += Handler; } - private static Assembly Handler(object sender, ResolveEventArgs args) { + static Assembly Handler(object sender, ResolveEventArgs args) { if (c.FullName == args.Name) return c; return null; } - } internal static class Resource_Packer { - - private static Assembly c; + static Assembly c; // Hmm... Too lazy. - private static void Initialize() { + static void Initialize() { var l = (uint)Mutation.KeyI0; uint[] q = Mutation.Placeholder(new uint[Mutation.KeyI0]); @@ -90,12 +87,11 @@ private static void Initialize() { AppDomain.CurrentDomain.ResourceResolve += Handler; } - private static Assembly Handler(object sender, ResolveEventArgs args) { + static Assembly Handler(object sender, ResolveEventArgs args) { var n = c.GetManifestResourceNames(); if (Array.IndexOf(n, args.Name) != -1) return c; return null; } - } } \ No newline at end of file diff --git a/ConfuserEx/App.xaml.cs b/ConfuserEx/App.xaml.cs index c864280c3..df9c8accd 100644 --- a/ConfuserEx/App.xaml.cs +++ b/ConfuserEx/App.xaml.cs @@ -2,7 +2,5 @@ using System.Windows; namespace ConfuserEx { - public partial class App : Application { - - } + public partial class App : Application { } } \ No newline at end of file diff --git a/ConfuserEx/BrushToColorConverter.cs b/ConfuserEx/BrushToColorConverter.cs index fb4db5f2b..23a9212a5 100644 --- a/ConfuserEx/BrushToColorConverter.cs +++ b/ConfuserEx/BrushToColorConverter.cs @@ -5,9 +5,8 @@ namespace ConfuserEx { public class BrushToColorConverter : IValueConverter { - public static readonly BrushToColorConverter Instance = new BrushToColorConverter(); - private BrushToColorConverter() { } + BrushToColorConverter() { } public object Convert(object value, Type targetType, object parameter, CultureInfo culture) { var brush = value as SolidColorBrush; @@ -19,6 +18,5 @@ public object Convert(object value, Type targetType, object parameter, CultureIn public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture) { throw new NotImplementedException(); } - } } \ No newline at end of file diff --git a/ConfuserEx/CompComboBox.xaml.cs b/ConfuserEx/CompComboBox.xaml.cs index ed2f73568..c3cff594e 100644 --- a/ConfuserEx/CompComboBox.xaml.cs +++ b/ConfuserEx/CompComboBox.xaml.cs @@ -6,7 +6,6 @@ namespace ConfuserEx { public partial class CompComboBox : UserControl { - public static readonly DependencyProperty ComponentsProperty = DependencyProperty.Register("Components", typeof(IEnumerable), typeof(CompComboBox), new UIPropertyMetadata(null)); public static readonly DependencyProperty SelectedComponentProperty = DependencyProperty.Register("SelectedComponent", typeof(ConfuserComponent), typeof(CompComboBox), new UIPropertyMetadata(null)); public static readonly DependencyProperty ArgumentsProperty = DependencyProperty.Register("Arguments", typeof(Dictionary), typeof(CompComboBox), new UIPropertyMetadata(null)); @@ -29,6 +28,5 @@ public Dictionary Arguments { get { return (Dictionary)GetValue(ArgumentsProperty); } set { SetValue(ArgumentsProperty, value); } } - } } \ No newline at end of file diff --git a/ConfuserEx/ComponentConverter.cs b/ConfuserEx/ComponentConverter.cs index 9e37bd675..d11bd5f8c 100644 --- a/ConfuserEx/ComponentConverter.cs +++ b/ConfuserEx/ComponentConverter.cs @@ -9,7 +9,6 @@ namespace ConfuserEx { internal class ComponentConverter : Freezable, IValueConverter { - public static readonly DependencyProperty ComponentsProperty = DependencyProperty.Register("Components", typeof(IList), typeof(ComponentConverter), new UIPropertyMetadata(null)); public IList Components { @@ -37,6 +36,5 @@ public object ConvertBack(object value, Type targetType, object parameter, Cultu protected override Freezable CreateInstanceCore() { return new ComponentConverter(); } - } } \ No newline at end of file diff --git a/ConfuserEx/ComponentDiscovery.cs b/ConfuserEx/ComponentDiscovery.cs index 4830e345f..e8ce66fa4 100644 --- a/ConfuserEx/ComponentDiscovery.cs +++ b/ConfuserEx/ComponentDiscovery.cs @@ -5,8 +5,7 @@ namespace ConfuserEx { internal class ComponentDiscovery { - - private static void CrossDomainLoadComponents() { + static void CrossDomainLoadComponents() { var ctx = (CrossDomainContext)AppDomain.CurrentDomain.GetData("ctx"); Assembly assembly = Assembly.LoadFile(ctx.PluginPath); foreach (Type i in assembly.GetTypes()) { @@ -37,11 +36,10 @@ public static void RemoveComponents(IList protections, IList< packers.RemoveWhere(comp => comp is InfoComponent && ((InfoComponent)comp).info.path == pluginPath); } - private class CrossDomainContext : MarshalByRefObject { - - private readonly IList packers; - private readonly string pluginPath; - private readonly IList protections; + class CrossDomainContext : MarshalByRefObject { + readonly IList packers; + readonly string pluginPath; + readonly IList protections; public CrossDomainContext(IList protections, IList packers, string pluginPath) { this.protections = protections; @@ -68,12 +66,10 @@ public void AddPacker(Info info) { } packers.Add(new InfoComponent(info)); } - } [Serializable] - private class Info { - + class Info { public string desc; public string fullId; public string id; @@ -89,11 +85,9 @@ public static Info FromComponent(ConfuserComponent component, string pluginPath) ret.path = pluginPath; return ret; } - } - private class InfoComponent : ConfuserComponent { - + class InfoComponent : ConfuserComponent { public readonly Info info; public InfoComponent(Info info) { @@ -123,8 +117,6 @@ protected override void Initialize(ConfuserContext context) { protected override void PopulatePipeline(ProtectionPipeline pipeline) { throw new NotSupportedException(); } - } - } } \ No newline at end of file diff --git a/ConfuserEx/EnumValuesExtension.cs b/ConfuserEx/EnumValuesExtension.cs index 95c57422a..b52f014aa 100644 --- a/ConfuserEx/EnumValuesExtension.cs +++ b/ConfuserEx/EnumValuesExtension.cs @@ -3,8 +3,7 @@ namespace ConfuserEx { public class EnumValuesExtension : MarkupExtension { - - private readonly Type enumType; + readonly Type enumType; public EnumValuesExtension(Type enumType) { this.enumType = enumType; @@ -13,6 +12,5 @@ public EnumValuesExtension(Type enumType) { public override object ProvideValue(IServiceProvider serviceProvider) { return Enum.GetValues(enumType); } - } } \ No newline at end of file diff --git a/ConfuserEx/FileDragDrop.cs b/ConfuserEx/FileDragDrop.cs index 96dfaad31..65e922db0 100644 --- a/ConfuserEx/FileDragDrop.cs +++ b/ConfuserEx/FileDragDrop.cs @@ -11,7 +11,6 @@ namespace ConfuserEx { public class FileDragDrop { - public static readonly DependencyProperty CommandProperty = DependencyProperty.RegisterAttached("Command", typeof(ICommand), typeof(FileDragDrop), new UIPropertyMetadata(null, OnCommandChanged)); @@ -70,7 +69,7 @@ public static void SetCommand(DependencyObject obj, ICommand value) { obj.SetValue(CommandProperty, value); } - private static void OnCommandChanged(DependencyObject d, DependencyPropertyChangedEventArgs e) { + static void OnCommandChanged(DependencyObject d, DependencyPropertyChangedEventArgs e) { var elem = (UIElement)d; if (e.NewValue != null) { elem.AllowDrop = true; @@ -84,7 +83,7 @@ private static void OnCommandChanged(DependencyObject d, DependencyPropertyChang } } - private static void OnDragOver(object sender, DragEventArgs e) { + static void OnDragOver(object sender, DragEventArgs e) { ICommand cmd = GetCommand((DependencyObject)sender); e.Effects = DragDropEffects.None; if (cmd is DragDropCommand) { @@ -98,7 +97,7 @@ private static void OnDragOver(object sender, DragEventArgs e) { e.Handled = true; } - private static void OnDrop(object sender, DragEventArgs e) { + static void OnDrop(object sender, DragEventArgs e) { ICommand cmd = GetCommand((DependencyObject)sender); if (cmd is DragDropCommand) { if (cmd.CanExecute(Tuple.Create((UIElement)sender, e.Data))) @@ -112,12 +111,9 @@ private static void OnDrop(object sender, DragEventArgs e) { } - private class DragDropCommand : RelayCommand> { - + class DragDropCommand : RelayCommand> { public DragDropCommand(Action> execute, Func, bool> canExecute) : base(execute, canExecute) { } - } - } } \ No newline at end of file diff --git a/ConfuserEx/InvertBoolConverter.cs b/ConfuserEx/InvertBoolConverter.cs index 5733f16cf..8d5269253 100644 --- a/ConfuserEx/InvertBoolConverter.cs +++ b/ConfuserEx/InvertBoolConverter.cs @@ -5,9 +5,8 @@ namespace ConfuserEx { internal class InvertBoolConverter : IValueConverter { - public static readonly InvertBoolConverter Instance = new InvertBoolConverter(); - private InvertBoolConverter() { } + InvertBoolConverter() { } public object Convert(object value, Type targetType, object parameter, CultureInfo culture) { Debug.Assert(value is bool); @@ -18,6 +17,5 @@ public object Convert(object value, Type targetType, object parameter, CultureIn public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture) { throw new NotSupportedException(); } - } } \ No newline at end of file diff --git a/ConfuserEx/MainWindow.xaml.cs b/ConfuserEx/MainWindow.xaml.cs index aa3faef55..b8e6c3f0a 100644 --- a/ConfuserEx/MainWindow.xaml.cs +++ b/ConfuserEx/MainWindow.xaml.cs @@ -8,7 +8,6 @@ namespace ConfuserEx { public partial class MainWindow : Window { - public MainWindow() { InitializeComponent(); @@ -24,7 +23,7 @@ public MainWindow() { DataContext = app; } - private void OpenMenu(object sender, RoutedEventArgs e) { + void OpenMenu(object sender, RoutedEventArgs e) { var btn = (Button)sender; ContextMenu menu = btn.ContextMenu; menu.PlacementTarget = btn; @@ -36,6 +35,5 @@ protected override void OnClosing(CancelEventArgs e) { base.OnClosing(e); e.Cancel = !((AppVM)DataContext).OnWindowClosing(); } - } } \ No newline at end of file diff --git a/ConfuserEx/Skin.cs b/ConfuserEx/Skin.cs index 082981207..b182e18e3 100644 --- a/ConfuserEx/Skin.cs +++ b/ConfuserEx/Skin.cs @@ -5,7 +5,6 @@ namespace ConfuserEx { public class Skin { - public static readonly DependencyProperty EmptyPromptProperty = DependencyProperty.RegisterAttached("EmptyPrompt", typeof(string), typeof(Skin), new UIPropertyMetadata(null)); @@ -59,6 +58,5 @@ public static FlowDocument GetRTBDocument(DependencyObject obj) { public static void SetRTBDocument(DependencyObject obj, FlowDocument value) { obj.SetValue(RTBDocumentProperty, value); } - } } \ No newline at end of file diff --git a/ConfuserEx/StackTraceDecoder.xaml.cs b/ConfuserEx/StackTraceDecoder.xaml.cs index 7684da6b9..ca0d1cc16 100644 --- a/ConfuserEx/StackTraceDecoder.xaml.cs +++ b/ConfuserEx/StackTraceDecoder.xaml.cs @@ -12,19 +12,18 @@ namespace ConfuserEx { /// Interaction logic for StackTraceDecoder.xaml /// public partial class StackTraceDecoder : Window { - public StackTraceDecoder() { InitializeComponent(); } - private readonly Dictionary symMap = new Dictionary(); + readonly Dictionary symMap = new Dictionary(); - private void PathBox_TextChanged(object sender, TextChangedEventArgs e) { + void PathBox_TextChanged(object sender, TextChangedEventArgs e) { if (File.Exists(PathBox.Text)) LoadSymMap(PathBox.Text); } - private void LoadSymMap(string path) { + void LoadSymMap(string path) { string shortPath = path; if (path.Length > 35) shortPath = "..." + path.Substring(path.Length - 35, 35); @@ -48,7 +47,7 @@ private void LoadSymMap(string path) { } } - private void ChooseMapPath(object sender, RoutedEventArgs e) { + void ChooseMapPath(object sender, RoutedEventArgs e) { var ofd = new VistaOpenFileDialog(); ofd.Filter = "Symbol maps (*.map)|*.map|All Files (*.*)|*.*"; if (ofd.ShowDialog() ?? false) { @@ -56,17 +55,16 @@ private void ChooseMapPath(object sender, RoutedEventArgs e) { } } - private readonly Regex symbolMatcher = new Regex("=[a-zA-Z0-9]+="); + readonly Regex symbolMatcher = new Regex("=[a-zA-Z0-9]+="); - private void Decode_Click(object sender, RoutedEventArgs e) { + void Decode_Click(object sender, RoutedEventArgs e) { var trace = stackTrace.Text; stackTrace.Text = symbolMatcher.Replace(trace, DecodeSymbol); } - private string DecodeSymbol(Match match) { + string DecodeSymbol(Match match) { var sym = match.Value; return symMap.GetValueOrDefault(sym, sym); } - } } \ No newline at end of file diff --git a/ConfuserEx/ViewModel/IViewModel.cs b/ConfuserEx/ViewModel/IViewModel.cs index 8b9f0fd28..dcfa0d430 100644 --- a/ConfuserEx/ViewModel/IViewModel.cs +++ b/ConfuserEx/ViewModel/IViewModel.cs @@ -2,8 +2,6 @@ namespace ConfuserEx.ViewModel { public interface IViewModel { - TModel Model { get; } - } } \ No newline at end of file diff --git a/ConfuserEx/ViewModel/Project/ProjectModuleVM.cs b/ConfuserEx/ViewModel/Project/ProjectModuleVM.cs index 557b36529..2e5f6ef42 100644 --- a/ConfuserEx/ViewModel/Project/ProjectModuleVM.cs +++ b/ConfuserEx/ViewModel/Project/ProjectModuleVM.cs @@ -7,11 +7,10 @@ namespace ConfuserEx.ViewModel { public class ProjectModuleVM : ViewModelBase, IViewModel, IRuleContainer { - - private readonly ProjectModule module; - private readonly ProjectVM parent; - private string asmName = "Unknown"; - private string simpleName; + readonly ProjectModule module; + readonly ProjectVM parent; + string asmName = "Unknown"; + string simpleName; public ProjectModuleVM(ProjectVM parent, ProjectModule module) { this.parent = parent; @@ -74,7 +73,7 @@ ProjectModule IViewModel.Model { get { return module; } } - private void LoadAssemblyName() { + void LoadAssemblyName() { AssemblyName = "Loading..."; ThreadPool.QueueUserWorkItem(_ => { try { @@ -87,6 +86,5 @@ private void LoadAssemblyName() { } }); } - } } \ No newline at end of file diff --git a/ConfuserEx/ViewModel/Project/ProjectRuleVM.cs b/ConfuserEx/ViewModel/Project/ProjectRuleVM.cs index a12693206..f15940d26 100644 --- a/ConfuserEx/ViewModel/Project/ProjectRuleVM.cs +++ b/ConfuserEx/ViewModel/Project/ProjectRuleVM.cs @@ -7,17 +7,14 @@ namespace ConfuserEx.ViewModel { internal interface IRuleContainer { - IList Rules { get; } - } public class ProjectRuleVM : ViewModelBase, IViewModel { - - private readonly ProjectVM parent; - private readonly Rule rule; - private string error; - private PatternExpression exp; + readonly ProjectVM parent; + readonly Rule rule; + string error; + PatternExpression exp; public ProjectRuleVM(ProjectVM parent, Rule rule) { this.parent = parent; @@ -76,7 +73,7 @@ Rule IViewModel.Model { get { return rule; } } - private void ParseExpression() { + void ParseExpression() { if (Pattern == null) return; PatternExpression expression; @@ -90,6 +87,5 @@ private void ParseExpression() { } Expression = expression; } - } } \ No newline at end of file diff --git a/ConfuserEx/ViewModel/Project/ProjectSettingVM.cs b/ConfuserEx/ViewModel/Project/ProjectSettingVM.cs index b329ea9e7..72b5fac38 100644 --- a/ConfuserEx/ViewModel/Project/ProjectSettingVM.cs +++ b/ConfuserEx/ViewModel/Project/ProjectSettingVM.cs @@ -3,9 +3,8 @@ namespace ConfuserEx.ViewModel { public class ProjectSettingVM : ViewModelBase, IViewModel> { - - private readonly ProjectVM parent; - private readonly SettingItem setting; + readonly ProjectVM parent; + readonly SettingItem setting; public ProjectSettingVM(ProjectVM parent, SettingItem setting) { this.parent = parent; @@ -31,6 +30,5 @@ public SettingItemAction Action { SettingItem IViewModel>.Model { get { return setting; } } - } } \ No newline at end of file diff --git a/ConfuserEx/ViewModel/Project/ProjectVM.cs b/ConfuserEx/ViewModel/Project/ProjectVM.cs index 2b12b048a..8ad1ba4a3 100644 --- a/ConfuserEx/ViewModel/Project/ProjectVM.cs +++ b/ConfuserEx/ViewModel/Project/ProjectVM.cs @@ -7,10 +7,9 @@ namespace ConfuserEx.ViewModel { public class ProjectVM : ViewModelBase, IViewModel, IRuleContainer { - - private readonly ConfuserProject proj; - private bool modified; - private ProjectSettingVM packer; + readonly ConfuserProject proj; + bool modified; + ProjectSettingVM packer; public ProjectVM(ConfuserProject proj) { this.proj = proj; @@ -98,6 +97,5 @@ protected override void OnPropertyChanged(string property) { if (property != "IsModified") IsModified = true; } - } } \ No newline at end of file diff --git a/ConfuserEx/ViewModel/StringItem.cs b/ConfuserEx/ViewModel/StringItem.cs index 25367a311..b81f292ee 100644 --- a/ConfuserEx/ViewModel/StringItem.cs +++ b/ConfuserEx/ViewModel/StringItem.cs @@ -2,7 +2,6 @@ namespace ConfuserEx.ViewModel { public class StringItem : IViewModel { - public StringItem(string item) { Item = item; } @@ -16,6 +15,5 @@ string IViewModel.Model { public override string ToString() { return Item; } - } } \ No newline at end of file diff --git a/ConfuserEx/ViewModel/UI/AboutTabVM.cs b/ConfuserEx/ViewModel/UI/AboutTabVM.cs index 6f4108798..ad99bbb4b 100644 --- a/ConfuserEx/ViewModel/UI/AboutTabVM.cs +++ b/ConfuserEx/ViewModel/UI/AboutTabVM.cs @@ -7,7 +7,6 @@ namespace ConfuserEx.ViewModel { internal class AboutTabVM : TabViewModel { - public AboutTabVM(AppVM app) : base(app, "About") { var decoder = new IconBitmapDecoder(new Uri("pack://application:,,,/ConfuserEx.ico"), BitmapCreateOptions.DelayCreation, BitmapCacheOption.OnDemand); @@ -20,6 +19,5 @@ public ICommand LaunchBrowser { } public BitmapSource Icon { get; private set; } - } } \ No newline at end of file diff --git a/ConfuserEx/ViewModel/UI/AppVM.cs b/ConfuserEx/ViewModel/UI/AppVM.cs index a1ae88e68..ce28725cf 100644 --- a/ConfuserEx/ViewModel/UI/AppVM.cs +++ b/ConfuserEx/ViewModel/UI/AppVM.cs @@ -13,13 +13,12 @@ namespace ConfuserEx.ViewModel { public class AppVM : ViewModelBase { + readonly IList tabs = new ObservableCollection(); + string fileName; + bool navDisabled; + bool firstSaved; - private readonly IList tabs = new ObservableCollection(); - private string fileName; - private bool navDisabled; - private bool firstSaved; - - private ProjectVM proj; + ProjectVM proj; public bool NavigationDisabled { get { return navDisabled; } @@ -80,7 +79,7 @@ public bool OnWindowClosing() { return PromptSave(); } - private bool SaveProj() { + bool SaveProj() { if (!firstSaved || !File.Exists(FileName)) { var sfd = new VistaSaveFileDialog(); sfd.FileName = FileName; @@ -96,7 +95,7 @@ private bool SaveProj() { return true; } - private bool PromptSave() { + bool PromptSave() { if (!Project.IsModified) return true; switch (MessageBox.Show("The current project has unsaved changes. Do you want to save them?", "ConfuserEx", MessageBoxButton.YesNoCancel, MessageBoxImage.Question)) { @@ -110,7 +109,7 @@ private bool PromptSave() { return false; } - private void NewProj() { + void NewProj() { if (!PromptSave()) return; @@ -118,7 +117,7 @@ private void NewProj() { FileName = "Unnamed.crproj"; } - private void OpenProj() { + void OpenProj() { if (!PromptSave()) return; @@ -140,7 +139,7 @@ private void OpenProj() { } } - private void OnProjectPropertyChanged(object sender, PropertyChangedEventArgs e) { + void OnProjectPropertyChanged(object sender, PropertyChangedEventArgs e) { if (e.PropertyName == "IsModified") OnPropertyChanged("Title"); } @@ -151,7 +150,7 @@ protected override void OnPropertyChanged(string property) { LoadPlugins(); } - private void LoadPlugins() { + void LoadPlugins() { foreach (var plugin in Project.Plugins) { try { ComponentDiscovery.LoadComponents(Project.Protections, Project.Packers, plugin.Item); diff --git a/ConfuserEx/ViewModel/UI/ProjectTabVM.cs b/ConfuserEx/ViewModel/UI/ProjectTabVM.cs index e61ac3d8c..6575cf7fd 100644 --- a/ConfuserEx/ViewModel/UI/ProjectTabVM.cs +++ b/ConfuserEx/ViewModel/UI/ProjectTabVM.cs @@ -11,8 +11,7 @@ namespace ConfuserEx.ViewModel { public class ProjectTabVM : TabViewModel { - - private int selIndex = -1; + int selIndex = -1; public ProjectTabVM(AppVM app) : base(app, "Project") { } @@ -112,7 +111,7 @@ public ICommand Advanced { } } - private void AddModule(string file) { + void AddModule(string file) { if (!File.Exists(file)) { MessageBox.Show(string.Format("File '{0}' does not exists!", file), "ConfuserEx", MessageBoxButton.OK, MessageBoxImage.Error); return; @@ -131,6 +130,5 @@ private void AddModule(string file) { } App.Project.Modules.Add(module); } - } } \ No newline at end of file diff --git a/ConfuserEx/ViewModel/UI/ProtectTabVM.cs b/ConfuserEx/ViewModel/UI/ProtectTabVM.cs index a02bee1fd..61911a628 100644 --- a/ConfuserEx/ViewModel/UI/ProtectTabVM.cs +++ b/ConfuserEx/ViewModel/UI/ProtectTabVM.cs @@ -1,5 +1,6 @@ using System; using System.IO; +using System.Threading; using System.Windows; using System.Windows.Documents; using System.Windows.Input; @@ -7,15 +8,13 @@ using Confuser.Core; using Confuser.Core.Project; using GalaSoft.MvvmLight.Command; -using System.Threading; namespace ConfuserEx.ViewModel { internal class ProtectTabVM : TabViewModel, ILogger { - - private readonly Paragraph documentContent; - private CancellationTokenSource cancelSrc; - private double? progress = 0; - private bool? result; + readonly Paragraph documentContent; + CancellationTokenSource cancelSrc; + double? progress = 0; + bool? result; public ProtectTabVM(AppVM app) : base(app, "Protect!") { @@ -44,7 +43,7 @@ public bool? Result { set { SetProperty(ref result, value, "Result"); } } - private void DoProtect() { + void DoProtect() { var parameters = new ConfuserParameters(); parameters.Project = ((IViewModel)App.Project).Model; if (File.Exists(App.FileName)) @@ -67,11 +66,11 @@ private void DoProtect() { }))); } - private void DoCancel() { + void DoCancel() { cancelSrc.Cancel(); } - private void AppendLine(string format, Brush foreground, params object[] args) { + void AppendLine(string format, Brush foreground, params object[] args) { Application.Current.Dispatcher.BeginInvoke(new Action(() => { documentContent.Inlines.Add(new Run(string.Format(format, args)) { Foreground = foreground }); documentContent.Inlines.Add(new LineBreak()); @@ -80,7 +79,7 @@ private void AppendLine(string format, Brush foreground, params object[] args) { #region Logger Impl - private DateTime begin; + DateTime begin; void ILogger.Debug(string msg) { AppendLine("[DEBUG] {0}", Brushes.Gray, msg); diff --git a/ConfuserEx/ViewModel/UI/SettingsTabVM.cs b/ConfuserEx/ViewModel/UI/SettingsTabVM.cs index 66556a9d3..104f2a429 100644 --- a/ConfuserEx/ViewModel/UI/SettingsTabVM.cs +++ b/ConfuserEx/ViewModel/UI/SettingsTabVM.cs @@ -11,10 +11,9 @@ namespace ConfuserEx.ViewModel { internal class SettingsTabVM : TabViewModel { - - private bool hasPacker; - private IRuleContainer selectedList; - private int selectedRuleIndex; + bool hasPacker; + IRuleContainer selectedList; + int selectedRuleIndex; public SettingsTabVM(AppVM app) : base(app, "Settings") { @@ -84,7 +83,7 @@ public ICommand Edit { } } - private void InitProject() { + void InitProject() { ModulesView = new CompositeCollection { App.Project, new CollectionContainer { Collection = App.Project.Modules } @@ -102,6 +101,5 @@ protected override void OnPropertyChanged(string property) { } base.OnPropertyChanged(property); } - } } \ No newline at end of file diff --git a/ConfuserEx/ViewModel/UI/TabViewModel.cs b/ConfuserEx/ViewModel/UI/TabViewModel.cs index b6931fed1..41c5ff40c 100644 --- a/ConfuserEx/ViewModel/UI/TabViewModel.cs +++ b/ConfuserEx/ViewModel/UI/TabViewModel.cs @@ -2,7 +2,6 @@ namespace ConfuserEx.ViewModel { public abstract class TabViewModel : ViewModelBase { - protected TabViewModel(AppVM app, string header) { App = app; Header = header; @@ -10,6 +9,5 @@ protected TabViewModel(AppVM app, string header) { public AppVM App { get; private set; } public string Header { get; private set; } - } } \ No newline at end of file diff --git a/ConfuserEx/ViewModel/Utils.cs b/ConfuserEx/ViewModel/Utils.cs index 4b1bdfdbc..02e546b21 100644 --- a/ConfuserEx/ViewModel/Utils.cs +++ b/ConfuserEx/ViewModel/Utils.cs @@ -6,7 +6,6 @@ namespace ConfuserEx.ViewModel { public static class Utils { - public static ObservableCollection Wrap(IList list) { var ret = new ObservableCollection(list); @@ -76,6 +75,5 @@ public static ObservableCollection Wrap(IList(bool changed, Action setter, T value, string pr } return false; } - } } \ No newline at end of file diff --git a/ConfuserEx/Views/ProjectModuleView.xaml.cs b/ConfuserEx/Views/ProjectModuleView.xaml.cs index 1bde74a76..cf9ec8495 100644 --- a/ConfuserEx/Views/ProjectModuleView.xaml.cs +++ b/ConfuserEx/Views/ProjectModuleView.xaml.cs @@ -6,8 +6,7 @@ namespace ConfuserEx.Views { public partial class ProjectModuleView : Window { - - private readonly ProjectModuleVM module; + readonly ProjectModuleVM module; public ProjectModuleView(ProjectModuleVM module) { InitializeComponent(); @@ -16,21 +15,20 @@ public ProjectModuleView(ProjectModuleVM module) { PwdBox.IsEnabled = !string.IsNullOrEmpty(PathBox.Text); } - private void Done(object sender, RoutedEventArgs e) { + void Done(object sender, RoutedEventArgs e) { DialogResult = true; } - private void PathBox_TextChanged(object sender, TextChangedEventArgs e) { + void PathBox_TextChanged(object sender, TextChangedEventArgs e) { PwdBox.IsEnabled = !string.IsNullOrEmpty(PathBox.Text); } - private void ChooseSNKey(object sender, RoutedEventArgs e) { + void ChooseSNKey(object sender, RoutedEventArgs e) { var ofd = new VistaOpenFileDialog(); ofd.Filter = "Supported Key Files (*.snk, *.pfx)|*.snk;*.pfx|All Files (*.*)|*.*"; if (ofd.ShowDialog() ?? false) { module.SNKeyPath = ofd.FileName; } } - } } \ No newline at end of file diff --git a/ConfuserEx/Views/ProjectRuleView.xaml.cs b/ConfuserEx/Views/ProjectRuleView.xaml.cs index 29664ce04..9a464bf6f 100644 --- a/ConfuserEx/Views/ProjectRuleView.xaml.cs +++ b/ConfuserEx/Views/ProjectRuleView.xaml.cs @@ -10,9 +10,8 @@ namespace ConfuserEx.Views { public partial class ProjectRuleView : Window { - - private readonly ProjectVM proj; - private readonly ProjectRuleVM rule; + readonly ProjectVM proj; + readonly ProjectRuleVM rule; public ProjectRuleView(ProjectVM proj, ProjectRuleVM rule) { InitializeComponent(); @@ -49,12 +48,12 @@ public void Cleanup() { rule.PropertyChanged -= OnPropertyChanged; } - private void OnPropertyChanged(object sender, PropertyChangedEventArgs e) { + void OnPropertyChanged(object sender, PropertyChangedEventArgs e) { if (e.PropertyName == "Expression") CheckValidity(); } - private void CheckValidity() { + void CheckValidity() { if (rule.Expression == null) { pattern.BorderBrush = Brushes.Red; errorImg.Visibility = Visibility.Visible; @@ -65,9 +64,8 @@ private void CheckValidity() { } } - private void Done(object sender, RoutedEventArgs e) { + void Done(object sender, RoutedEventArgs e) { DialogResult = true; } - } } \ No newline at end of file diff --git a/ConfuserEx/Views/ProjectTabAdvancedView.xaml.cs b/ConfuserEx/Views/ProjectTabAdvancedView.xaml.cs index 9fc5ef194..fd0d99548 100644 --- a/ConfuserEx/Views/ProjectTabAdvancedView.xaml.cs +++ b/ConfuserEx/Views/ProjectTabAdvancedView.xaml.cs @@ -7,8 +7,7 @@ namespace ConfuserEx.Views { public partial class ProjectTabAdvancedView : Window { - - private readonly ProjectVM project; + readonly ProjectVM project; public ProjectTabAdvancedView(ProjectVM project) { InitializeComponent(); @@ -61,6 +60,5 @@ public override void OnApplyTemplate() { ProbePaths.SelectedIndex = selIndex >= project.ProbePaths.Count ? project.ProbePaths.Count - 1 : selIndex; }, () => ProbePaths.SelectedIndex != -1); } - } } \ No newline at end of file