internal void Analyze(NameService service, ConfuserContext context, ProtectionParameters parameters, IDnlibDef def, bool runAnalyzer) { if (def is TypeDef) Analyze(service, context, parameters, (TypeDef)def); else if (def is MethodDef) Analyze(service, context, parameters, (MethodDef)def); else if (def is FieldDef) Analyze(service, context, parameters, (FieldDef)def); else if (def is PropertyDef) Analyze(service, context, parameters, (PropertyDef)def); else if (def is EventDef) Analyze(service, context, parameters, (EventDef)def); else if (def is ModuleDef) { var pass = parameters.GetParameter<string>(context, def, "password", null); if (pass != null) service.reversibleRenamer = new ReversibleRenamer(pass); service.SetCanRename(def, false); } if (!runAnalyzer || parameters.GetParameter(context, def, "forceRen", false)) return; foreach (IRenamer renamer in service.Renamers) renamer.Analyze(context, service, parameters, def); }
/// <inheritdoc /> public override object Evaluate(IDnlibDef definition) { TypeDef type = definition as TypeDef; if (type == null && definition is IMemberDef) type = ((IMemberDef)definition).DeclaringType; if (type == null) return false; string typeRegex = Arguments[0].Evaluate(definition).ToString(); var typeType = new StringBuilder(); if (type.IsEnum) typeType.Append("enum "); if (type.IsInterface) typeType.Append("interface "); if (type.IsValueType) typeType.Append("valuetype "); if (type.IsDelegate()) typeType.Append("delegate "); if (type.IsAbstract) typeType.Append("abstract "); if (type.IsNested) typeType.Append("nested "); if (type.IsSerializable) typeType.Append("serializable "); return Regex.IsMatch(typeType.ToString(), typeRegex); }
public IDisposable Apply(IDnlibDef target, IEnumerable<ProtectionSettingsInfo> infos) { ProtectionSettings settings; if (this.settings == null) settings = new ProtectionSettings(); else settings = new ProtectionSettings(this.settings); var infoArray = infos.ToArray(); if (stack.Count > 0) { foreach (var i in stack.Skip(1).Reverse()) ApplyInfo(target, settings, i.Item2.Where(info => info.Condition != null), false); ApplyInfo(target, settings, stack.Peek().Item2, false); } IDisposable result; if (infoArray.Length != 0) { var originalSettings = this.settings; // the settings that would apply to members ApplyInfo(target, settings, infoArray, false); this.settings = new ProtectionSettings(settings); // the settings that would apply to itself ApplyInfo(target, settings, infoArray, true); stack.Push(Tuple.Create(originalSettings, infoArray)); result = new PopHolder(this); } else result = null; ProtectionParameters.SetParameters(context, target, settings); return result; }
// i.e. Inter-Assembly References, e.g. InternalVisibleToAttributes public void Analyze(ConfuserContext context, INameService service, ProtectionParameters parameters, IDnlibDef def) { var module = def as ModuleDefMD; if (module == null) return; // MemberRef/MethodSpec var methods = module.GetTypes().SelectMany(type => type.Methods); foreach(var methodDef in methods) { foreach (var ov in methodDef.Overrides) { ProcessMemberRef(context, service, module, ov.MethodBody); ProcessMemberRef(context, service, module, ov.MethodDeclaration); } if (!methodDef.HasBody) continue; foreach (var instr in methodDef.Body.Instructions) { if (instr.Operand is MemberRef || instr.Operand is MethodSpec) ProcessMemberRef(context, service, module, (IMemberRef)instr.Operand); } } // TypeRef var table = module.TablesStream.Get(Table.TypeRef); uint len = table.Rows; for (uint i = 1; i <= len; i++) { TypeRef typeRef = module.ResolveTypeRef(i); TypeDef typeDef = typeRef.ResolveTypeDefThrow(); if (typeDef.Module != module && context.Modules.Contains((ModuleDefMD)typeDef.Module)) { service.AddReference(typeDef, new TypeRefReference(typeRef, typeDef)); } } }
// i.e. Inter-Assembly References, e.g. InternalVisibleToAttributes public void Analyze(ConfuserContext context, INameService service, IDnlibDef def) { var module = def as ModuleDefMD; if (module == null) return; MDTable table; uint len; // MemberRef table = module.TablesStream.Get(Table.MemberRef); len = table.Rows; for (uint i = 1; i <= len; i++) { MemberRef memberRef = module.ResolveMemberRef(i); TypeDef declType = memberRef.DeclaringType.ResolveTypeDefThrow(); if (declType.Module != module && context.Modules.Contains((ModuleDefMD)declType.Module)) { var memberDef = (IDnlibDef)declType.ResolveThrow(memberRef); service.AddReference(memberDef, new MemberRefReference(memberRef, memberDef)); } } // TypeRef table = module.TablesStream.Get(Table.TypeRef); len = table.Rows; for (uint i = 1; i <= len; i++) { TypeRef typeRef = module.ResolveTypeRef(i); TypeDef typeDef = typeRef.ResolveTypeDefThrow(); if (typeDef.Module != module && context.Modules.Contains((ModuleDefMD)typeDef.Module)) { service.AddReference(typeDef, new TypeRefReference(typeRef, typeDef)); } } }
/// <inheritdoc /> public override object Evaluate(IDnlibDef definition) { if (!(definition is IOwnerModule)) return false; object name = Arguments[0].Evaluate(definition); return ((IOwnerModule)definition).Module.Name == name.ToString(); }
/// <inheritdoc /> public override object Evaluate(IDnlibDef definition) { var member = definition as IMemberDef; if (member == null) return false; var declType = ((IMemberDef)definition).DeclaringType; while (declType != null) { if (!declType.IsPublic) return false; declType = declType.DeclaringType; } if (member is MethodDef) return ((MethodDef)member).IsPublic; if (member is FieldDef) return ((FieldDef)member).IsPublic; if (member is PropertyDef) return ((PropertyDef)member).IsPublic(); if (member is EventDef) return ((EventDef)member).IsPublic(); if (member is TypeDef) return ((TypeDef)member).IsPublic || ((TypeDef)member).IsNestedPublic; throw new NotSupportedException(); }
/// <inheritdoc /> public override object Evaluate(IDnlibDef definition) { if (!(definition is IMemberDef) || ((IMemberDef)definition).DeclaringType == null) return false; object fullName = Arguments[0].Evaluate(definition); return ((IMemberDef)definition).DeclaringType.FullName == fullName.ToString(); }
/// <inheritdoc /> protected internal override void MarkMember(IDnlibDef member, ConfuserContext context) { ModuleDef module = ((IMemberRef)member).Module; var stack = context.Annotations.Get<ProtectionSettingsStack>(module, ModuleSettingsKey); using (stack.Apply(member, Enumerable.Empty<ProtectionSettingsInfo>())) return; }
void DoDisassemble(IDnlibDef item, ITextOutput output, ReflectionDisassembler disassembler) { if (item is ModuleDef) { var module = (ModuleDef)item; disassembler.WriteAssemblyReferences(module); if (module.Assembly != null) disassembler.WriteAssemblyHeader(module.Assembly); output.WriteLine(); disassembler.WriteModuleHeader(module); } else if (item is TypeDef) { disassembler.DisassembleType((TypeDef)item); } else if (item is MethodDef) { disassembler.DisassembleMethod((MethodDef)item); } else if (item is FieldDef) { disassembler.DisassembleField((FieldDef)item); } else if (item is PropertyDef) { disassembler.DisassembleProperty((PropertyDef)item); } else if (item is EventDef) { disassembler.DisassembleEvent((EventDef)item); } }
public void Analyze(ConfuserContext context, INameService service, ProtectionParameters parameters, IDnlibDef def) { var method = def as MethodDef; if (method == null || !method.HasBody) return; // When a ldtoken instruction reference a definition, // most likely it would be used in reflection and thus probably should not be renamed. // Also, when ToString is invoked on enum, // the enum should not be renamed. for (int i = 0; i < method.Body.Instructions.Count; i++) { Instruction instr = method.Body.Instructions[i]; if (instr.OpCode.Code == Code.Ldtoken) { if (instr.Operand is MemberRef) { IMemberForwarded member = ((MemberRef)instr.Operand).ResolveThrow(); if (context.Modules.Contains((ModuleDefMD)member.Module)) service.SetCanRename(member, false); } else if (instr.Operand is IField) { FieldDef field = ((IField)instr.Operand).ResolveThrow(); if (context.Modules.Contains((ModuleDefMD)field.Module)) service.SetCanRename(field, false); } else if (instr.Operand is IMethod) { var im = (IMethod)instr.Operand; if (!im.IsArrayAccessors()) { MethodDef m = im.ResolveThrow(); if (context.Modules.Contains((ModuleDefMD)m.Module)) service.SetCanRename(method, false); } } else if (instr.Operand is ITypeDefOrRef) { if (!(instr.Operand is TypeSpec)) { TypeDef type = ((ITypeDefOrRef)instr.Operand).ResolveTypeDefThrow(); if (context.Modules.Contains((ModuleDefMD)type.Module) && HandleTypeOf(context, service, method, i)) { var t = type; do { DisableRename(service, t, false); t = t.DeclaringType; } while (t != null); } } } else throw new UnreachableException(); } else if ((instr.OpCode.Code == Code.Call || instr.OpCode.Code == Code.Callvirt) && ((IMethod)instr.Operand).Name == "ToString") { HandleEnum(context, service, method, i); } else if (instr.OpCode.Code == Code.Ldstr) { TypeDef typeDef = method.Module.FindReflection((string)instr.Operand); if (typeDef != null) service.AddReference(typeDef, new StringTypeReference(instr, typeDef)); } } }
public CodeViewData Run(IDnlibDef item, CancellationToken token) { var builder = CreateBuilder(item, token); if (builder == null) return new CodeViewData(""); builder.RunTransformations(); var output = new CodeViewOutput(); builder.GenerateCode(output); return output.GetResult(); }
AstBuilder CreateBuilder(IDnlibDef item, CancellationToken token) { ModuleDef moduleDef; DecompilerContext ctx; AstBuilder builder; if (item is ModuleDef) { var def = (ModuleDef)item; moduleDef = def; builder = new AstBuilder(ctx = new DecompilerContext(moduleDef) { CancellationToken = token }); builder.AddAssembly(def, true); } else if (item is TypeDef) { var def = (TypeDef)item; moduleDef = def.Module; builder = new AstBuilder(ctx = new DecompilerContext(moduleDef) { CancellationToken = token }); builder.DecompileMethodBodies = false; ctx.CurrentType = def; builder.AddType(def); } else if (item is MethodDef) { var def = (MethodDef)item; moduleDef = def.Module; builder = new AstBuilder(ctx = new DecompilerContext(moduleDef) { CancellationToken = token }); ctx.CurrentType = def.DeclaringType; builder.AddMethod(def); } else if (item is FieldDef) { var def = (FieldDef)item; moduleDef = def.Module; builder = new AstBuilder(ctx = new DecompilerContext(moduleDef) { CancellationToken = token }); ctx.CurrentType = def.DeclaringType; builder.AddField(def); } else if (item is PropertyDef) { var def = (PropertyDef)item; moduleDef = def.Module; builder = new AstBuilder(ctx = new DecompilerContext(moduleDef) { CancellationToken = token }); ctx.CurrentType = def.DeclaringType; builder.AddProperty(def); } else if (item is EventDef) { var def = (EventDef)item; moduleDef = def.Module; builder = new AstBuilder(ctx = new DecompilerContext(moduleDef) { CancellationToken = token }); ctx.CurrentType = def.DeclaringType; builder.AddEvent(def); } else return null; ctx.Settings = new DecompilerSettings { UsingDeclarations = false }; return builder; }
public void Analyze(ConfuserContext context, INameService service, ProtectionParameters parameters, IDnlibDef def) { if (def is TypeDef) Analyze(context, service, (TypeDef)def, parameters); else if (def is MethodDef) Analyze(context, service, (MethodDef)def, parameters); else if (def is PropertyDef) Analyze(context, service, (PropertyDef)def, parameters); else if (def is FieldDef) Analyze(context, service, (FieldDef)def, parameters); }
/// <inheritdoc /> public override object Evaluate(IDnlibDef definition) { if (definition is TypeDef) { string regex = Arguments[0].Evaluate(definition).ToString(); return Regex.IsMatch(definition.Name, regex); } if (definition is IMemberDef && ((IMemberDef)definition).DeclaringType != null) { string regex = Arguments[0].Evaluate(definition).ToString(); return Regex.IsMatch(((IMemberDef)definition).DeclaringType.Name, regex); } return false; }
public void Display(IDnlibDef item = null) { treeView.App.DockArea.DockWindows[DockState.DockBottom].BringToFront(); Show(treeView.App.DockArea, DockState.DockBottom); if (item != null) { if (item is ModuleDef && ((ModuleDef)item).Assembly != null) item = ((ModuleDef)item).Assembly; treeView.Nodes.Add(new MultipleAnalysesModel(item, GetChildren(item)).ToNode()); } }
/// <inheritdoc /> public void Mark(IDnlibDef member) { if (member == null) throw new ArgumentNullException("member"); if (member is ModuleDef) throw new ArgumentException("New ModuleDef cannot be marked."); if (IsMarked(member)) // avoid double marking return; marker.MarkMember(member, context); }
public void Analyze(ConfuserContext context, INameService service, ProtectionParameters parameters, IDnlibDef def) { var module = def as ModuleDef; if (module == null) return; string asmName = module.Assembly.Name.String; if (!string.IsNullOrEmpty(module.Assembly.Culture) && asmName.EndsWith(".resources")) { // Satellite assembly var satellitePattern = new Regex(string.Format("^(.*)\\.{0}\\.resources$", module.Assembly.Culture)); string nameAsmName = asmName.Substring(0, asmName.Length - ".resources".Length); ModuleDef mainModule = context.Modules.SingleOrDefault(mod => mod.Assembly.Name == nameAsmName); if (mainModule == null) { context.Logger.ErrorFormat("Could not find main assembly of satellite assembly '{0}'.", module.Assembly.FullName); throw new ConfuserException(null); } string format = "{0}." + module.Assembly.Culture + ".resources"; foreach (Resource res in module.Resources) { Match match = satellitePattern.Match(res.Name); if (!match.Success) continue; string typeName = match.Groups[1].Value; TypeDef type = mainModule.FindReflectionThrow(typeName); if (type == null) { context.Logger.WarnFormat("Could not find resource type '{0}'.", typeName); continue; } service.ReduceRenameMode(type, RenameMode.ASCII); service.AddReference(type, new ResourceReference(res, type, format)); } } else { string format = "{0}.resources"; foreach (Resource res in module.Resources) { Match match = ResourceNamePattern.Match(res.Name); if (!match.Success) continue; string typeName = match.Groups[1].Value; if (typeName.EndsWith(".g")) // WPF resources, ignore continue; TypeDef type = module.FindReflection(typeName); if (type == null) { context.Logger.WarnFormat("Could not find resource type '{0}'.", typeName); continue; } service.ReduceRenameMode(type, RenameMode.ASCII); service.AddReference(type, new ResourceReference(res, type, format)); } } }
/// <inheritdoc /> public override object Evaluate(IDnlibDef definition) { string name = Arguments[0].Evaluate(definition).ToString(); if (!(definition is TypeDef)) return false; var type = (TypeDef)definition; if (type.InheritsFrom(name) || type.Implements(name)) return true; return false; }
/// <inheritdoc /> public void Mark(IDnlibDef member, ConfuserComponent parentComp) { if (member == null) throw new ArgumentNullException("member"); if (member is ModuleDef) throw new ArgumentException("New ModuleDef cannot be marked."); if (IsMarked(member)) // avoid double marking return; marker.MarkMember(member, context); if (parentComp != null) helperParents[member] = parentComp; }
/// <inheritdoc /> public override object Evaluate(IDnlibDef definition) { string name = Arguments[0].Evaluate(definition).ToString(); if (!(definition is TypeDef)) return false; var type = (TypeDef)definition; while (type.BaseType != null) { type = type.BaseType.ResolveTypeDefThrow(); if (type.FullName == name) return true; } return false; }
public void Analyze(ConfuserContext context, INameService service, ProtectionParameters parameters, IDnlibDef def) { var method = def as MethodDef; if (method != null) { if (!method.HasBody) return; AnalyzeMethod(context, service, method); } var module = def as ModuleDefMD; if (module != null) { AnalyzeResources(context, service, module); } }
public void Analyze(ConfuserContext context, INameService service, ProtectionParameters parameters, IDnlibDef def) { if (def is ModuleDef) { foreach (var type in ((ModuleDef)def).GetTypes()) foreach (var prop in type.Properties) properties.AddListEntry(prop.Name, prop); return; } var method = def as MethodDef; if (method == null || !method.HasBody) return; AnalyzeMethod(context, service, method); }
/// <inheritdoc /> public override object Evaluate(IDnlibDef definition) { string name = Arguments[0].Evaluate(definition).ToString(); var type = definition as TypeDef; if (type == null && definition is IMemberDef) type = ((IMemberDef)definition).DeclaringType; if (type == null) return false; if (type.InheritsFrom(name) || type.Implements(name)) return true; return false; }
/// <inheritdoc /> public override object Evaluate(IDnlibDef definition) { if (!(definition is TypeDef) && !(definition is IMemberDef)) return false; object ns = Arguments[0].Evaluate(definition); var type = definition as TypeDef; if (type == null) type = ((IMemberDef)definition).DeclaringType; while (type.IsNested) type = type.DeclaringType; return type != null && type.Namespace == ns.ToString(); }
public void PostRename(ConfuserContext context, INameService service, ProtectionParameters parameters, IDnlibDef def) { var module = def as ModuleDefMD; if (module == null) return; var wpfResInfo = context.Annotations.Get<Dictionary<string, Dictionary<string, BamlDocument>>>(module, BAMLKey); if (wpfResInfo == null) return; foreach (EmbeddedResource res in module.Resources.OfType<EmbeddedResource>()) { Dictionary<string, BamlDocument> resInfo; if (!wpfResInfo.TryGetValue(res.Name, out resInfo)) continue; var stream = new MemoryStream(); var writer = new ResourceWriter(stream); res.Data.Position = 0; var reader = new ResourceReader(new ImageStream(res.Data)); IDictionaryEnumerator enumerator = reader.GetEnumerator(); while (enumerator.MoveNext()) { var name = (string)enumerator.Key; string typeName; byte[] data; reader.GetResourceData(name, out typeName, out data); BamlDocument document; if (resInfo.TryGetValue(name, out document)) { var docStream = new MemoryStream(); docStream.Position = 4; BamlWriter.WriteDocument(document, docStream); docStream.Position = 0; docStream.Write(BitConverter.GetBytes((int)docStream.Length - 4), 0, 4); data = docStream.ToArray(); name = document.DocumentName; } writer.AddResourceData(name, typeName, data); } writer.Generate(); res.Data = MemoryImageStream.Create(stream.ToArray()); } }
public CodeViewData Run(IDnlibDef item, CancellationToken token) { try { var output = new CodeViewOutput(); var disassembler = new ReflectionDisassembler(output, true, token); DoDisassemble(item, output, disassembler); return output.GetResult(); } catch { // Retry if ILStructure failed. var output = new CodeViewOutput(); output.WriteComment("// ILStructure failed!"); output.WriteLine(); var disassembler = new ReflectionDisassembler(output, false, token); DoDisassemble(item, output, disassembler); return output.GetResult(); } }
/// <inheritdoc /> public override object Evaluate(IDnlibDef definition) { if (!(definition is TypeDef) && !(definition is IMemberDef)) return false; var ns = "^" + Arguments[0].Evaluate(definition).ToString() + "$"; var type = definition as TypeDef; if (type == null) type = ((IMemberDef)definition).DeclaringType; if (type == null) return false; while (type.IsNested) type = type.DeclaringType; return type != null && Regex.IsMatch(type.Namespace ?? "", ns); }
/// <inheritdoc /> public override object Evaluate(IDnlibDef definition) { string typeRegex = Arguments[0].Evaluate(definition).ToString(); var memberType = new StringBuilder(); if (definition is TypeDef) memberType.Append("type "); if (definition is MethodDef) { memberType.Append("method "); var method = (MethodDef)definition; if (method.IsGetter) memberType.Append("propertym getter "); else if (method.IsSetter) memberType.Append("propertym setter "); else if (method.IsAddOn) memberType.Append("eventm add "); else if (method.IsRemoveOn) memberType.Append("eventm remove "); else if (method.IsFire) memberType.Append("eventm fire "); else if (method.IsOther) memberType.Append("other "); } if (definition is FieldDef) memberType.Append("field "); if (definition is PropertyDef) memberType.Append("property "); if (definition is EventDef) memberType.Append("event "); if (definition is ModuleDef) memberType.Append("module "); return Regex.IsMatch(memberType.ToString(), typeRegex); }
internal void Analyze(NameService service, ConfuserContext context, ProtectionParameters parameters, IDnlibDef def, bool runAnalyzer) { if (def is TypeDef) Analyze(service, context, parameters, (TypeDef)def); else if (def is MethodDef) Analyze(service, context, parameters, (MethodDef)def); else if (def is FieldDef) Analyze(service, context, parameters, (FieldDef)def); else if (def is PropertyDef) Analyze(service, context, parameters, (PropertyDef)def); else if (def is EventDef) Analyze(service, context, parameters, (EventDef)def); else if (def is ModuleDef) service.SetCanRename(def, false); if (!runAnalyzer || parameters.GetParameter<bool>(context, def, "forceRen", false)) return; foreach (IRenamer renamer in service.Renamers) renamer.Analyze(context, service, def); }
/// <inheritdoc /> public bool DelayRenaming(INameService service, IDnlibDef currentDef) => false;
void IRenamer.Analyze(ConfuserContext context, INameService service, ProtectionParameters parameters, IDnlibDef def) { switch (def) { case TypeDef typeDef: Analyze(service, context.Modules, typeDef); break; case MethodDef methodDef: Analyze(service, context.Modules, methodDef); break; } }
void IRenamer.Analyze(ConfuserContext context, INameService service, ProtectionParameters parameters, IDnlibDef def) { if (!(def is ModuleDefMD moduleDef)) { return; } Analyze(service, context.Modules, context.Logger, moduleDef); }
public void PreRename(DotProtectContext context, INameService service, ProtectionParameters parameters, IDnlibDef def) { // }
public void PostRename(ConfuserContext context, INameService service, ProtectionParameters parameters, IDnlibDef def) { var method = def as MethodDef; if (method == null || !method.IsVirtual || method.Overrides.Count == 0) { return; } method.Overrides .RemoveWhere(impl => MethodEqualityComparer.CompareDeclaringTypes.Equals(impl.MethodDeclaration, method)); }
/// <summary> /// Sets the protection parameters of the specified target. /// </summary> /// <param name="context">The context.</param> /// <param name="target">The protection target.</param> /// <param name="parameters">The parameters.</param> public static void SetParameters( ConfuserContext context, IDnlibDef target, ProtectionSettings parameters) { context.Annotations.Set(target, ParametersKey, parameters); }
public void Analyze(ConfuserContext context, INameService service, ProtectionParameters parameters, IDnlibDef def) { if (def is TypeDef) { Analyze(context, service, (TypeDef)def, parameters); } else if (def is MethodDef) { Analyze(context, service, (MethodDef)def, parameters); } else if (def is PropertyDef) { Analyze(context, service, (PropertyDef)def, parameters); } else if (def is FieldDef) { Analyze(context, service, (FieldDef)def, parameters); } }
void IRenamer.PreRename(ConfuserContext context, INameService service, ProtectionParameters parameters, IDnlibDef def) { }
public void Analyze(ConfuserContext context, INameService service, ProtectionParameters parameters, IDnlibDef def) { var module = def as ModuleDef; if (module == null) { return; } string asmName = module.Assembly.Name.String; if (!string.IsNullOrEmpty(module.Assembly.Culture) && asmName.EndsWith(".resources")) { // Satellite assembly var satellitePattern = new Regex(string.Format("^(.*)\\.{0}\\.resources$", module.Assembly.Culture)); string nameAsmName = asmName.Substring(0, asmName.Length - ".resources".Length); ModuleDef mainModule = context.Modules.SingleOrDefault(mod => mod.Assembly.Name == nameAsmName); if (mainModule == null) { context.Logger.ErrorFormat("Could not find main assembly of satellite assembly '{0}'.", module.Assembly.FullName); throw new ConfuserException(null); } string format = "{0}." + module.Assembly.Culture + ".resources"; foreach (Resource res in module.Resources) { Match match = satellitePattern.Match(res.Name); if (!match.Success) { continue; } string typeName = match.Groups[1].Value; TypeDef type = mainModule.FindReflection(typeName); if (type == null) { context.Logger.WarnFormat("Could not find resource type '{0}'.", typeName); continue; } service.ReduceRenameMode(type, RenameMode.ASCII); service.AddReference(type, new ResourceReference(res, type, format)); } } else { string format = "{0}.resources"; foreach (Resource res in module.Resources) { Match match = ResourceNamePattern.Match(res.Name); if (!match.Success || res.ResourceType != ResourceType.Embedded) { continue; } string typeName = match.Groups[1].Value; if (typeName.EndsWith(".g")) // WPF resources, ignore { continue; } // This variable is set true in case the name of the resource doesn't match the name of the class. // That happens for the resources in Visual Basic. var mismatchingName = false; TypeDef type = module.FindReflection(typeName); if (type == null) { if (typeName.EndsWith(".Resources")) { typeName = typeName.Substring(0, typeName.Length - 10) + ".My.Resources.Resources"; type = module.FindReflection(typeName); mismatchingName = type != null; } } if (type == null) { context.Logger.WarnFormat("Could not find resource type '{0}'.", typeName); continue; } service.ReduceRenameMode(type, RenameMode.ASCII); service.AddReference(type, new ResourceReference(res, type, format)); if (mismatchingName) { // Add string type references in case the name didn't match. This will cause the resource to get // the same name as the class, despite that not being the case before. But that doesn't really matter. FindLdTokenResourceReferences(type, match.Groups[1].Value, service); } } } }
/// <inheritdoc /> public override object Evaluate(IDnlibDef definition) { return(Literal); }
void IRenamer.Analyze(ConfuserContext context, INameService service, ProtectionParameters parameters, IDnlibDef def) { if (!(def is MethodDef method) || !method.HasBody) { return; } Analyze(service, context.Registry.GetService <ITraceService>(), context.Modules.Cast <ModuleDef>().ToArray(), method); }
public void Analyze(ConfuserContext context, INameService service, ProtectionParameters parameters, IDnlibDef def) { if (def is ModuleDef moduleDef) { foreach (var prop in moduleDef.GetTypes().SelectMany(t => t.Properties)) { properties.AddListEntry(prop.Name, prop); } return; } if (!(def is MethodDef method) || !method.HasBody) { return; } AnalyzeMethod(context, service, method); }
void ProcessMember(IDnlibDef member, ProtectionSettingsStack stack) { using (stack.Apply(member, ReadInfos(member))) ProcessBody(member as MethodDef, stack); }
public void PostRename(ConfuserContext context, INameService service, ProtectionParameters parameters, IDnlibDef def) { // }
internal void Analyze(NameService service, ConfuserContext context, ProtectionParameters parameters, IDnlibDef def, bool runAnalyzer) { if (def is TypeDef) { Analyze(service, context, parameters, (TypeDef)def); } else if (def is MethodDef) { Analyze(service, context, parameters, (MethodDef)def); } else if (def is FieldDef) { Analyze(service, context, parameters, (FieldDef)def); } else if (def is PropertyDef) { Analyze(service, context, parameters, (PropertyDef)def); } else if (def is EventDef) { Analyze(service, context, parameters, (EventDef)def); } else if (def is ModuleDef) { var pass = parameters.GetParameter <string>(context, def, "password", null); if (pass != null) { service.reversibleRenamer = new ReversibleRenamer(pass); } var idOffset = parameters.GetParameter <uint>(context, def, "idOffset", 0); if (idOffset != 0) { service.SetNameId(idOffset); } service.SetCanRename(def, false, "Module definition"); } if (!runAnalyzer || parameters.GetParameter(context, def, "forceRen", false)) { return; } foreach (IRenamer renamer in service.Renamers) { renamer.Analyze(context, service, parameters, def); } }
public void PostRename(ConfuserContext context, INameService service, ProtectionParameters parameters, IDnlibDef def) { var module = def as ModuleDefMD; if (module == null) { return; } var wpfResInfo = context.Annotations.Get <Dictionary <string, Dictionary <string, BamlDocument> > >(module, BAMLKey); if (wpfResInfo == null) { return; } foreach (EmbeddedResource res in module.Resources.OfType <EmbeddedResource>()) { Dictionary <string, BamlDocument> resInfo; if (!wpfResInfo.TryGetValue(res.Name, out resInfo)) { continue; } var stream = new MemoryStream(); var writer = new ResourceWriter(stream); res.Data.Position = 0; var reader = new ResourceReader(new ImageStream(res.Data)); IDictionaryEnumerator enumerator = reader.GetEnumerator(); while (enumerator.MoveNext()) { var name = (string)enumerator.Key; string typeName; byte[] data; reader.GetResourceData(name, out typeName, out data); BamlDocument document; if (resInfo.TryGetValue(name, out document)) { var docStream = new MemoryStream(); docStream.Position = 4; BamlWriter.WriteDocument(document, docStream); docStream.Position = 0; docStream.Write(BitConverter.GetBytes((int)docStream.Length - 4), 0, 4); data = docStream.ToArray(); name = document.DocumentName; } writer.AddResourceData(name, typeName, data); } writer.Generate(); res.Data = MemoryImageStream.Create(stream.ToArray()); } }
/// <summary> /// Gets the protection parameters of the specified target. /// </summary> /// <param name="context">The context.</param> /// <param name="target">The protection target.</param> /// <returns>The parameters.</returns> public static ProtectionSettings GetParameters( ConfuserContext context, IDnlibDef target) { return(context.Annotations.Get <ProtectionSettings>(target, ParametersKey)); }
public void PreRename(ConfuserContext context, INameService service, ProtectionParameters parameters, IDnlibDef def) { var module = def as ModuleDefMD; if (module == null || !parameters.GetParameter <bool>(context, def, "renXaml", true)) { return; } var wpfResInfo = context.Annotations.Get <Dictionary <string, Dictionary <string, BamlDocument> > >(module, BAMLKey); if (wpfResInfo == null) { return; } foreach (var res in wpfResInfo.Values) { foreach (var doc in res.Values) { List <IBAMLReference> references; if (bamlRefs.TryGetValue(doc.DocumentName, out references)) { var newName = doc.DocumentName.ToUpperInvariant(); if (newName.EndsWith(".BAML")) { newName = service.RandomName(RenameMode.Letters).ToLowerInvariant() + ".baml"; } else if (newName.EndsWith(".XAML")) { newName = service.RandomName(RenameMode.Letters).ToLowerInvariant() + ".xaml"; } foreach (var bamlRef in references) { bamlRef.Rename(doc.DocumentName, newName); } doc.DocumentName = newName; } } } }
public void PostRename(ConfuserContext context, INameService service, IDnlibDef def) { // }
public void Analyze(ConfuserContext context, INameService service, ProtectionParameters parameters, IDnlibDef def) { var method = def as MethodDef; if (method != null) { if (!method.HasBody) { return; } AnalyzeMethod(context, service, method); } var module = def as ModuleDefMD; if (module != null) { AnalyzeResources(context, service, module); } }
// Token: 0x06000042 RID: 66 RVA: 0x00004AD0 File Offset: 0x00002CD0 public void PreRename(ConfuserContext context, INameService service, ProtectionParameters parameters, IDnlibDef def) { ModuleDefMD module = def as ModuleDefMD; if (module == null || !parameters.GetParameter <bool>(context, def, "renXaml", true)) { return; } Dictionary <string, Dictionary <string, BamlDocument> > wpfResInfo = context.Annotations.Get <Dictionary <string, Dictionary <string, BamlDocument> > >(module, WPFAnalyzer.BAMLKey, null); if (wpfResInfo == null) { return; } foreach (Dictionary <string, BamlDocument> res in wpfResInfo.Values) { foreach (BamlDocument doc in res.Values) { List <IBAMLReference> references; if (this.bamlRefs.TryGetValue(doc.DocumentName, out references)) { string newName = doc.DocumentName.ToUpperInvariant(); string[] completePath = newName.Split(new string[] { "/" }, StringSplitOptions.RemoveEmptyEntries); string newShinyName = string.Empty; for (int i = 0; i <= completePath.Length - 2; i++) { newShinyName = newShinyName + completePath[i].ToLowerInvariant() + "/"; } if (newName.EndsWith(".BAML")) { newName = newShinyName + service.RandomName(RenameMode.Letters).ToLowerInvariant() + ".baml"; } else if (newName.EndsWith(".XAML")) { newName = newShinyName + service.RandomName(RenameMode.Letters).ToLowerInvariant() + ".xaml"; } context.Logger.Debug(string.Format("Preserving virtual paths. Replaced {0} with {1}", doc.DocumentName, newName)); bool renameOk = true; foreach (IBAMLReference bamlRef in references) { if (!bamlRef.CanRename(doc.DocumentName, newName)) { renameOk = false; break; } } if (renameOk) { foreach (IBAMLReference bamlRef2 in references) { bamlRef2.Rename(doc.DocumentName, newName); } doc.DocumentName = newName; } } } } }
internal void Analyze(NameService service, ConfuserContext context, ProtectionParameters parameters, IDnlibDef def, bool runAnalyzer) { if (def is TypeDef) { Analyze(service, context, parameters, (TypeDef)def); } else if (def is MethodDef) { Analyze(service, context, parameters, (MethodDef)def); } else if (def is FieldDef) { Analyze(service, context, parameters, (FieldDef)def); } else if (def is PropertyDef) { Analyze(service, context, parameters, (PropertyDef)def); } else if (def is EventDef) { Analyze(service, context, parameters, (EventDef)def); } else if (def is ModuleDef) { service.SetCanRename(def, false); } if (!runAnalyzer || parameters.GetParameter(context, def, "forceRen", false)) { return; } foreach (IRenamer renamer in service.Renamers) { renamer.Analyze(context, service, def); } }
/// <inheritdoc /> void IRenamer.Analyze(ConfuserContext context, INameService service, ProtectionParameters parameters, IDnlibDef def) { if (!(def is TypeDef typeDef)) { return; } Analyze(context, service, typeDef); }
/// <inheritdoc /> public override object Evaluate(IDnlibDef definition) { string regex = Arguments[0].Evaluate(definition).ToString(); return(Regex.IsMatch(definition.Name, regex)); }
// Token: 0x0600002B RID: 43 RVA: 0x00003AAC File Offset: 0x00001CAC public void Analyze(ConfuserContext context, INameService service, ProtectionParameters parameters, IDnlibDef def) { ModuleDefMD module = def as ModuleDefMD; if (module == null) { return; } MDTable table = module.TablesStream.Get(Table.Method); uint len = table.Rows; IEnumerable <MethodDef> methods = from rid in Enumerable.Range(1, (int)len) select module.ResolveMethod((uint)rid); foreach (MethodDef method in methods) { foreach (MethodOverride methodImpl in method.Overrides) { if (methodImpl.MethodBody is MemberRef) { this.AnalyzeMemberRef(context, service, (MemberRef)methodImpl.MethodBody); } if (methodImpl.MethodDeclaration is MemberRef) { this.AnalyzeMemberRef(context, service, (MemberRef)methodImpl.MethodDeclaration); } } if (method.HasBody) { foreach (Instruction instr in method.Body.Instructions) { if (instr.Operand is MemberRef) { this.AnalyzeMemberRef(context, service, (MemberRef)instr.Operand); } else if (instr.Operand is MethodSpec) { MethodSpec spec = (MethodSpec)instr.Operand; if (spec.Method is MemberRef) { this.AnalyzeMemberRef(context, service, (MemberRef)spec.Method); } } } } } table = module.TablesStream.Get(Table.CustomAttribute); len = table.Rows; IEnumerable <CustomAttribute> attrs = (from rid in Enumerable.Range(1, (int)len) select module.ResolveHasCustomAttribute(module.TablesStream.ReadCustomAttributeRow((uint)rid).Parent)).Distinct <IHasCustomAttribute>().SelectMany((IHasCustomAttribute owner) => owner.CustomAttributes); foreach (CustomAttribute attr in attrs) { if (attr.Constructor is MemberRef) { this.AnalyzeMemberRef(context, service, (MemberRef)attr.Constructor); } foreach (CAArgument arg in attr.ConstructorArguments) { this.AnalyzeCAArgument(context, service, arg); } foreach (CANamedArgument arg2 in attr.Fields) { this.AnalyzeCAArgument(context, service, arg2.Argument); } foreach (CANamedArgument arg3 in attr.Properties) { this.AnalyzeCAArgument(context, service, arg3.Argument); } TypeDef attrType = attr.AttributeType.ResolveTypeDefThrow(); if (context.Modules.Contains((ModuleDefMD)attrType.Module)) { foreach (CANamedArgument fieldArg in attr.Fields) { FieldDef field = attrType.FindField(fieldArg.Name, new FieldSig(fieldArg.Type)); if (field == null) { context.Logger.WarnFormat("Failed to resolve CA field '{0}::{1} : {2}'.", new object[] { attrType, fieldArg.Name, fieldArg.Type }); } else { service.AddReference <IDnlibDef>(field, new CAMemberReference(fieldArg, field)); } } foreach (CANamedArgument propertyArg in attr.Properties) { PropertyDef property = attrType.FindProperty(propertyArg.Name, new PropertySig(true, propertyArg.Type)); if (property == null) { context.Logger.WarnFormat("Failed to resolve CA property '{0}::{1} : {2}'.", new object[] { attrType, propertyArg.Name, propertyArg.Type }); } else { service.AddReference <IDnlibDef>(property, new CAMemberReference(propertyArg, property)); } } } } }
void ProcessElementBody(BamlElement root, BamlElement elem) { foreach (BamlRecord rec in elem.Body) { // Resolve the type & property for simple property record too. TypeDef type = null; IDnlibDef attr = null; if (rec is PropertyRecord) { var propRec = (PropertyRecord)rec; var attrInfo = ResolveAttribute(propRec.AttributeId); type = attrInfo.Item3; attr = attrInfo.Item1; if (attr != null) { type = GetAttributeType(attr); } if (attrInfo.Item1 is EventDef) { MethodDef method = root.Type.FindMethod(propRec.Value); if (method == null) { context.Logger.WarnFormat("Cannot resolve method '{0}' in '{1}'.", root.Type.FullName, propRec.Value); } else { var reference = new BAMLAttributeReference(method, propRec); service.AddReference(method, reference); } } if (rec is PropertyWithConverterRecord) { ProcessConverter((PropertyWithConverterRecord)rec, type); } } else if (rec is PropertyComplexStartRecord) { var attrInfo = ResolveAttribute(((PropertyComplexStartRecord)rec).AttributeId); type = attrInfo.Item3; attr = attrInfo.Item1; if (attr != null) { type = GetAttributeType(attr); } } else if (rec is ContentPropertyRecord) { var attrInfo = ResolveAttribute(((ContentPropertyRecord)rec).AttributeId); type = attrInfo.Item3; attr = attrInfo.Item1; if (elem.Attribute != null && attr != null) { type = GetAttributeType(attr); } foreach (BamlElement child in elem.Children) { child.Type = type; child.Attribute = attr; } } else if (rec is PropertyCustomRecord) { var customRec = (PropertyCustomRecord)rec; var attrInfo = ResolveAttribute(customRec.AttributeId); type = attrInfo.Item3; attr = attrInfo.Item1; if (elem.Attribute != null && attr != null) { type = GetAttributeType(attr); } if ((customRec.SerializerTypeId & 0x4000) != 0 && (customRec.SerializerTypeId & 0x4000) == 0x89) { // See BamlRecordReader.GetCustomDependencyPropertyValue. // Umm... Well, actually nothing to do, since this record only describe DP, which already won't be renamed. } } else if (rec is PropertyWithExtensionRecord) { var extRec = (PropertyWithExtensionRecord)rec; var attrInfo = ResolveAttribute(extRec.AttributeId); type = attrInfo.Item3; attr = attrInfo.Item1; if (elem.Attribute != null && attr != null) { type = GetAttributeType(attr); } 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) { attrInfo = ResolveAttribute(extRec.ValueId); var attrTarget = attrInfo.Item1; if (attrTarget == null) { TypeSig declType; TypeDef declTypeDef; if (typeRefs.TryGetValue(attrInfo.Item2.OwnerTypeId, out declType)) { declTypeDef = declType.ToBasicTypeDefOrRef().ResolveTypeDefThrow(); } else { Debug.Assert((short)attrInfo.Item2.OwnerTypeId < 0); declTypeDef = things.Types((KnownTypes)(-(short)attrInfo.Item2.OwnerTypeId)); } attrTarget = declTypeDef.FindField(attrInfo.Item2.Name); } if (attrTarget != null) { service.AddReference(attrTarget, new BAMLAttributeReference(attrTarget, attrInfo.Item2)); } } } } else if (rec is TextRecord) { var txt = (TextRecord)rec; string value = txt.Value; if (txt is TextWithIdRecord) { value = strings[((TextWithIdRecord)txt).ValueId].Value; } string prefix; TypeSig sig = ResolveType(value.Trim(), out prefix); if (sig != null && context.Modules.Contains((ModuleDefMD)sig.ToBasicTypeDefOrRef().ResolveTypeDefThrow().Module)) { var reference = new BAMLConverterTypeReference(xmlnsCtx, sig, txt); AddTypeSigReference(sig, reference); } else { AnalyzePropertyPath(value); } } } }
public void Analyze(ConfuserContext context, INameService service, ProtectionParameters parameters, IDnlibDef def) { VTable vTbl; if (def is TypeDef) { var type = (TypeDef)def; if (type.IsInterface) { return; } vTbl = service.GetVTables()[type]; foreach (var ifaceVTbl in vTbl.InterfaceSlots.Values) { foreach (var slot in ifaceVTbl) { if (slot.Overrides == null) { continue; } Debug.Assert(slot.Overrides.MethodDef.DeclaringType.IsInterface); // A method in base type can implements an interface method for a // derived type. If the base type/interface is not in our control, we should // not rename the methods. var baseUnderCtrl = context.Modules.Contains(slot.MethodDef.DeclaringType.Module as ModuleDefMD); var ifaceUnderCtrl = context.Modules.Contains(slot.Overrides.MethodDef.DeclaringType.Module as ModuleDefMD); if (!baseUnderCtrl && ifaceUnderCtrl || !service.CanRename(slot.MethodDef)) { service.SetCanRename(slot.Overrides.MethodDef, false); } else if (baseUnderCtrl && !ifaceUnderCtrl || !service.CanRename(slot.Overrides.MethodDef)) { service.SetCanRename(slot.MethodDef, false); } } } } else if (def is MethodDef) { var method = (MethodDef)def; if (!method.IsVirtual) { return; } vTbl = service.GetVTables()[method.DeclaringType]; var sig = VTableSignature.FromMethod(method); var slots = vTbl.FindSlots(method); if (!method.IsAbstract) { foreach (var slot in slots) { if (slot.Overrides == null) { continue; } // Better on safe side, add references to both methods. service.AddReference(method, new OverrideDirectiveReference(slot, slot.Overrides)); service.AddReference(slot.Overrides.MethodDef, new OverrideDirectiveReference(slot, slot.Overrides)); } } else { foreach (var slot in slots) { if (slot.Overrides == null) { continue; } service.SetCanRename(method, false); service.SetCanRename(slot.Overrides.MethodDef, false); } } } }
public void Analyze(ConfuserContext context, INameService service, ProtectionParameters parameters, IDnlibDef def) { var type = def as TypeDef; if (type == null || type.DeclaringType != null) { return; } if (type.Name.Contains("ViewModel")) { string viewNs = type.Namespace.Replace("ViewModels", "Views"); string viewName = type.Name.Replace("PageViewModel", "Page").Replace("ViewModel", "View"); TypeDef view = type.Module.Find(viewNs + "." + viewName, true); if (view != null) { service.SetCanRename(type, false); service.SetCanRename(view, false); } // Test for Multi-view string multiViewNs = type.Namespace + "." + type.Name.Replace("ViewModel", ""); foreach (TypeDef t in type.Module.Types) { if (t.Namespace == multiViewNs) { service.SetCanRename(type, false); service.SetCanRename(t, false); } } } }
public void Analyze(ConfuserContext context, INameService service, ProtectionParameters parameters, IDnlibDef def) { if (def is ModuleDef) { foreach (var type in ((ModuleDef)def).GetTypes()) { foreach (var prop in type.Properties) { properties.AddListEntry(prop.Name, prop); } } return; } var method = def as MethodDef; if (method == null || !method.HasBody) { return; } AnalyzeMethod(context, service, method); }
public void PostRename(ConfuserContext context, INameService service, ProtectionParameters parameters, IDnlibDef def) { var method = def as MethodDef; if (method == null || !method.IsVirtual || method.Overrides.Count == 0) { return; } var methods = new HashSet <IMethodDefOrRef>(MethodDefOrRefComparer.Instance); method.Overrides .RemoveWhere(impl => MethodDefOrRefComparer.Instance.Equals(impl.MethodDeclaration, method)); }