diff --git a/de4dot.code/de4dot.code.csproj b/de4dot.code/de4dot.code.csproj index 19628372..35f4c408 100644 --- a/de4dot.code/de4dot.code.csproj +++ b/de4dot.code/de4dot.code.csproj @@ -140,19 +140,6 @@ - - - - - - - - - - - - - diff --git a/de4dot.code/old_renamer/CurrentNames.cs b/de4dot.code/old_renamer/CurrentNames.cs deleted file mode 100644 index 605fd823..00000000 --- a/de4dot.code/old_renamer/CurrentNames.cs +++ /dev/null @@ -1,62 +0,0 @@ -/* - Copyright (C) 2011 de4dot@gmail.com - - This file is part of de4dot. - - de4dot is free software: you can redistribute it and/or modify - it under the terms of the GNU General Public License as published by - the Free Software Foundation, either version 3 of the License, or - (at your option) any later version. - - de4dot is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU General Public License for more details. - - You should have received a copy of the GNU General Public License - along with de4dot. If not, see . -*/ - -using System; -using System.Collections.Generic; - -namespace de4dot.old_renamer { - class CurrentNames { - Dictionary allNames = new Dictionary(StringComparer.Ordinal); - - public void add(string name) { - allNames[name] = true; - } - - bool exists(string name) { - return allNames.ContainsKey(name); - } - - public string newName(string oldName, INameCreator nameCreator) { - return newName(oldName, () => nameCreator.newName()); - } - - public string newName(string oldName, Func createNewName) { - string prevName = null; - while (true) { - var name = createNewName(); - if (name == prevName) - throw new ApplicationException(string.Format("Could not rename symbol to {0}", Utils.toCsharpString(name))); - - if (!exists(name) || name == oldName) { - allNames[name] = true; - return name; - } - - prevName = name; - } - } - - public CurrentNames clone() { - var cn = new CurrentNames(); - foreach (var key in allNames.Keys) - cn.allNames[key] = true; - return cn; - } - } -} diff --git a/de4dot.code/old_renamer/DefinitionsRenamer.cs b/de4dot.code/old_renamer/DefinitionsRenamer.cs deleted file mode 100644 index 2ee7300b..00000000 --- a/de4dot.code/old_renamer/DefinitionsRenamer.cs +++ /dev/null @@ -1,569 +0,0 @@ -/* - Copyright (C) 2011 de4dot@gmail.com - - This file is part of de4dot. - - de4dot is free software: you can redistribute it and/or modify - it under the terms of the GNU General Public License as published by - the Free Software Foundation, either version 3 of the License, or - (at your option) any later version. - - de4dot is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU General Public License for more details. - - You should have received a copy of the GNU General Public License - along with de4dot. If not, see . -*/ - -using System; -using System.Collections.Generic; -using Mono.Cecil; -using de4dot.blocks; - -namespace de4dot.old_renamer { - // Renames typedefs, methoddefs, eventdefs, fielddefs, propdefs, and genparams - class DefinitionsRenamer : IResolver, IDefFinder { - // All types that don't derive from an existing type definition (most likely mscorlib - // isn't loaded, so this won't have just one element). - IList baseTypes = new List(); - IList nonNestedTypes; - IList modules = new List(); - List allTypes = new List(); - TypeNameState typeNameState; - ModulesDict modulesDict = new ModulesDict(); - AssemblyHash assemblyHash = new AssemblyHash(); - - class AssemblyHash { - IDictionary assemblyHash = new Dictionary(StringComparer.Ordinal); - - public void add(Module module) { - ModuleHash moduleHash; - var key = getModuleKey(module); - if (!assemblyHash.TryGetValue(key, out moduleHash)) - assemblyHash[key] = moduleHash = new ModuleHash(); - moduleHash.add(module); - } - - string getModuleKey(Module module) { - if (module.ModuleDefinition.Assembly != null) - return module.ModuleDefinition.Assembly.ToString(); - return Utils.getBaseName(module.ModuleDefinition.FullyQualifiedName); - } - - public ModuleHash lookup(string assemblyName) { - ModuleHash moduleHash; - if (assemblyHash.TryGetValue(assemblyName, out moduleHash)) - return moduleHash; - return null; - } - } - - class ModuleHash { - ModulesDict modulesDict = new ModulesDict(); - Module mainModule = null; - - public void add(Module module) { - var asm = module.ModuleDefinition.Assembly; - if (asm != null && ReferenceEquals(asm.MainModule, module.ModuleDefinition)) { - if (mainModule != null) - throw new UserException(string.Format("Two modules in the same assembly are main modules. If 32-bit vs 64-bit, don't use both assemblies at the same time! \"{0}\" and \"{1}\"", module.ModuleDefinition.FullyQualifiedName, mainModule.ModuleDefinition.FullyQualifiedName)); - mainModule = module; - } - - modulesDict.add(module); - } - - public IEnumerable Modules { - get { return modulesDict.Modules; } - } - } - - class ModulesDict { - IDictionary modulesDict = new Dictionary(StringComparer.OrdinalIgnoreCase); - - public void add(Module module) { - if (lookup(module.Pathname) != null) - throw new ApplicationException(string.Format("Module \"{0}\" was found twice", module.Pathname)); - modulesDict[module.Pathname] = module; - } - - public Module lookup(string pathname) { - Module module; - if (modulesDict.TryGetValue(pathname, out module)) - return module; - return null; - } - - public IEnumerable Modules { - get { return modulesDict.Values; } - } - } - - public DefinitionsRenamer(IEnumerable files) { - foreach (var file in files) { - var module = new Module(file); - modulesDict.add(module); - modules.Add(module); - assemblyHash.add(module); - } - } - - public void renameAll() { - if (modules.Count == 0) - return; - Log.n("Renaming all obfuscated symbols"); - findAllMemberReferences(); - resolveAllRefs(); - initAllTypes(); - renameTypeDefinitions(); - renameTypeReferences(); - foreach (var module in modules) - module.onTypesRenamed(); - prepareRenameMemberDefinitions(); - renameMemberDefinitions(); - renameMemberReferences(); - renameResources(); - externalAssemblies.unloadAll(); - DotNetUtils.typeCaches.invalidateAll(); - } - - void initAllTypes() { - foreach (var module in modules) - allTypes.AddRange(module.getAllTypes()); - - var typeToTypeDef = new Dictionary(allTypes.Count); - foreach (var typeDef in allTypes) - typeToTypeDef[typeDef.TypeDefinition] = typeDef; - - // Initialize Owner - foreach (var typeDef in allTypes) { - if (typeDef.TypeDefinition.DeclaringType != null) - typeDef.Owner = typeToTypeDef[typeDef.TypeDefinition.DeclaringType]; - } - - // Initialize baseType and derivedTypes - foreach (var typeDef in allTypes) { - var baseType = typeDef.TypeDefinition.BaseType; - if (baseType == null) - continue; - var baseTypeDef = resolve(baseType) ?? resolveOther(baseType); - if (baseTypeDef != null) { - typeDef.addBaseType(baseTypeDef, baseType); - baseTypeDef.derivedTypes.Add(typeDef); - } - } - - // Initialize interfaces - foreach (var typeDef in allTypes) { - if (typeDef.TypeDefinition.Interfaces == null) - continue; - foreach (var iface in typeDef.TypeDefinition.Interfaces) { - var ifaceTypeDef = resolve(iface) ?? resolveOther(iface); - if (ifaceTypeDef != null) - typeDef.addInterface(ifaceTypeDef, iface); - } - } - - // Find all non-nested types - var allTypesDict = new Dictionary(); - foreach (var t in allTypes) - allTypesDict[t] = true; - foreach (var t in allTypes) { - foreach (var t2 in t.NestedTypes) - allTypesDict.Remove(t2); - } - nonNestedTypes = new List(allTypesDict.Keys); - - foreach (var typeDef in allTypes) - typeDef.defFinder = this; - - foreach (var typeDef in allTypes) { - if (typeDef.baseType == null || !typeDef.baseType.typeDef.IsRenamable) - baseTypes.Add(typeDef); - } - } - - void findAllMemberReferences() { - Log.v("Finding all MemberReferences"); - int index = 0; - foreach (var module in modules) { - if (modules.Count > 1) - Log.v("Finding all MemberReferences ({0})", module.Filename); - Log.indent(); - module.findAllMemberReferences(ref index); - Log.deIndent(); - } - } - - void resolveAllRefs() { - Log.v("Resolving references"); - foreach (var module in modules) { - if (modules.Count > 1) - Log.v("Resolving references ({0})", module.Filename); - Log.indent(); - module.resolveAllRefs(this); - Log.deIndent(); - } - } - - void renameTypeDefinitions() { - Log.v("Renaming obfuscated type definitions"); - - foreach (var module in modules) - module.onBeforeRenamingTypeDefinitions(); - - typeNameState = new TypeNameState(); - foreach (var typeDef in allTypes) - typeNameState.currentNames.add(typeDef.OldName); - prepareRenameTypeDefinitions(baseTypes); - typeNameState = null; - - fixClsTypeNames(); - renameTypeDefinitions(nonNestedTypes); - } - - void prepareRenameTypeDefinitions(IEnumerable typeDefs) { - foreach (var typeDef in typeDefs) { - typeNameState.IsValidName = typeDef.module.IsValidName; - typeDef.prepareRename(typeNameState); - prepareRenameTypeDefinitions(typeDef.derivedTypes); - } - } - - void renameTypeDefinitions(IEnumerable typeDefs) { - Log.indent(); - foreach (var typeDef in typeDefs) { - typeDef.rename(); - renameTypeDefinitions(typeDef.NestedTypes); - } - Log.deIndent(); - } - - // Make sure the renamed types are using valid CLS names. That means renaming all - // generic types from eg. Class1 to Class1`2. If we don't do this, some decompilers - // (eg. ILSpy v1.0) won't produce correct output. - void fixClsTypeNames() { - foreach (var type in nonNestedTypes) - fixClsTypeNames(null, type); - } - - void fixClsTypeNames(TypeDef nesting, TypeDef nested) { - int nestingCount = nesting == null ? 0 : nesting.GenericParams.Count; - int arity = nested.GenericParams.Count - nestingCount; - if (nested.gotNewName() && arity > 0) - nested.NewName += "`" + arity; - foreach (var nestedType in nested.NestedTypes) - fixClsTypeNames(nested, nestedType); - } - - void renameTypeReferences() { - Log.v("Renaming references to type definitions"); - foreach (var module in modules) { - if (modules.Count > 1) - Log.v("Renaming references to type definitions ({0})", module.Filename); - Log.indent(); - module.renameTypeReferences(); - Log.deIndent(); - } - } - - class InterfaceScope { - Dictionary interfaces = new Dictionary(); - Dictionary classes = new Dictionary(); - - public IEnumerable Interfaces { - get { return interfaces.Keys; } - } - - public IEnumerable Classes { - get { return classes.Keys; } - } - - public void addInterfaces(IEnumerable list) { - foreach (var iface in list) - interfaces[iface] = true; - } - - public void addClass(TypeDef cls) { - classes[cls] = true; - } - - public void merge(InterfaceScope other) { - if (ReferenceEquals(this, other)) - return; - addInterfaces(other.interfaces.Keys); - foreach (var cls in other.classes.Keys) - addClass(cls); - } - } - - void prepareRenameMemberDefinitions() { - Log.v("Renaming member definitions #1"); - - var interfaceScopes = createInterfaceScopes(); - foreach (var interfaceScope in interfaceScopes) { - var state = new MemberRenameState(new InterfaceVariableNameState()); - foreach (var iface in interfaceScope.Interfaces) - iface.MemberRenameState = state.cloneVariables(); - foreach (var cls in interfaceScope.Classes) { - if (cls.isInterface()) - continue; - cls.InterfaceScopeState = state; - } - } - foreach (var interfaceScope in interfaceScopes) { - foreach (var iface in interfaceScope.Interfaces) - iface.prepareRenameMembers(); - } - - var variableNameState = new VariableNameState(); - foreach (var typeDef in baseTypes) { - var state = new MemberRenameState(variableNameState.clone()); - typeDef.MemberRenameState = state; - } - - foreach (var typeDef in allTypes) - typeDef.prepareRenameMembers(); - - renameEntryPoints(); - } - - Dictionary otherTypesDict = new Dictionary(); - ExternalAssemblies externalAssemblies = new ExternalAssemblies(); - TypeDef resolveOther(TypeReference type) { - if (type == null) - return null; - type = type.GetElementType(); - - TypeDef typeDef; - var key = new TypeReferenceKey(type); - if (otherTypesDict.TryGetValue(key, out typeDef)) - return typeDef; - otherTypesDict[key] = null; // In case of a circular reference - - TypeDefinition typeDefinition = externalAssemblies.resolve(type); - if (typeDefinition == null) - return null; - - typeDef = new TypeDef(typeDefinition); - typeDef.MemberRenameState = new MemberRenameState(); - typeDef.addMembers(); - foreach (var iface in typeDef.TypeDefinition.Interfaces) { - var ifaceDef = resolveOther(iface); - if (ifaceDef == null) - continue; - typeDef.MemberRenameState.mergeRenamed(ifaceDef.MemberRenameState); - typeDef.addInterface(ifaceDef, iface); - } - var baseDef = resolveOther(typeDef.TypeDefinition.BaseType); - if (baseDef != null) { - typeDef.MemberRenameState.mergeRenamed(baseDef.MemberRenameState); - typeDef.addBaseType(baseDef, typeDef.TypeDefinition.BaseType); - } - typeDef.initializeVirtualMembers(); - return otherTypesDict[key] = typeDef; - } - - void renameEntryPoints() { - foreach (var module in modules) { - var entryPoint = module.ModuleDefinition.EntryPoint; - if (entryPoint == null) - continue; - var methodDef = resolve(entryPoint); - if (methodDef == null) - throw new ApplicationException(string.Format("Could not find entry point. Module: {0}, Method: {1}", module.ModuleDefinition.FullyQualifiedName, entryPoint)); - if (!methodDef.MethodDefinition.IsStatic) - continue; - methodDef.NewName = "Main"; - if (methodDef.ParamDefs.Count == 1) { - var paramDef = methodDef.ParamDefs[0]; - var type = paramDef.ParameterDefinition.ParameterType; - if (MemberReferenceHelper.verifyType(type, "mscorlib", "System.String", "[]")) - paramDef.NewName = "args"; - } - } - } - - class InterfaceScopeInfo { - public TypeDef theClass; - public List interfaces; - public InterfaceScopeInfo(TypeDef theClass, List interfaces) { - this.theClass = theClass; - this.interfaces = interfaces; - } - } - - IList createInterfaceScopes() { - var interfaceScopes = new Dictionary(); - foreach (var scopeInfo in getInterfaceScopeInfo(baseTypes)) { - InterfaceScope interfaceScope = null; - foreach (var iface in scopeInfo.interfaces) { - if (interfaceScopes.TryGetValue(iface, out interfaceScope)) - break; - } - List mergeScopes = null; - if (interfaceScope == null) - interfaceScope = new InterfaceScope(); - else { - // Find all interfaces in scopeInfo.interfaces that are in another - // InterfaceScope, and merge them with interfaceScope. - foreach (var iface in scopeInfo.interfaces) { - InterfaceScope scope; - if (!interfaceScopes.TryGetValue(iface, out scope)) - continue; // not in any scope yet - if (ReferenceEquals(scope, interfaceScope)) - continue; // same scope - - if (mergeScopes == null) - mergeScopes = new List(); - mergeScopes.Add(scope); - } - } - - foreach (var iface in scopeInfo.interfaces) - interfaceScopes[iface] = interfaceScope; - if (mergeScopes != null) { - foreach (var scope in mergeScopes) { - interfaceScope.merge(scope); - foreach (var iface in scope.Interfaces) - interfaceScopes[iface] = interfaceScope; - } - } - interfaceScope.addInterfaces(scopeInfo.interfaces); - interfaceScope.addClass(scopeInfo.theClass); - } - - return new List(Utils.unique(interfaceScopes.Values)); - } - - IEnumerable getInterfaceScopeInfo(IEnumerable baseTypes) { - foreach (var typeDef in baseTypes) { - yield return new InterfaceScopeInfo(typeDef, new List(typeDef.getAllRenamableInterfaces())); - } - } - - void renameMemberDefinitions() { - Log.v("Renaming member definitions #2"); - - Log.indent(); - foreach (var typeDef in allTypes) - typeDef.renameMembers(); - Log.deIndent(); - } - - void renameMemberReferences() { - Log.v("Renaming references to other definitions"); - foreach (var module in modules) { - if (modules.Count > 1) - Log.v("Renaming references to other definitions ({0})", module.Filename); - Log.indent(); - module.renameMemberReferences(); - Log.deIndent(); - } - } - - void renameResources() { - Log.v("Renaming resources"); - foreach (var module in modules) { - if (modules.Count > 1) - Log.v("Renaming resources ({0})", module.Filename); - Log.indent(); - module.renameResources(); - Log.deIndent(); - } - } - - // Returns null if it's a non-loaded module/assembly - IEnumerable findModules(IMetadataScope scope) { - if (scope is AssemblyNameReference) { - var assemblyRef = (AssemblyNameReference)scope; - var moduleHash = assemblyHash.lookup(assemblyRef.ToString()); - if (moduleHash != null) - return moduleHash.Modules; - } - else if (scope is ModuleDefinition) { - var moduleDefinition = (ModuleDefinition)scope; - var module = modulesDict.lookup(moduleDefinition.FullyQualifiedName); - if (module != null) - return new List { module }; - } - else - throw new ApplicationException(string.Format("IMetadataScope is an unsupported type: {0}", scope.GetType())); - - return null; - } - - bool isAutoCreatedType(TypeReference typeReference) { - return typeReference is ArrayType || typeReference is PointerType; - } - - public TypeDef resolve(TypeReference typeReference) { - var modules = findModules(typeReference.Scope); - if (modules == null) - return null; - foreach (var module in modules) { - var rv = module.resolve(typeReference); - if (rv != null) - return rv; - } - if (isAutoCreatedType(typeReference)) - return null; - Log.e("Could not resolve TypeReference {0} ({1:X8})", typeReference, typeReference.MetadataToken.ToInt32()); - return null; - } - - public MethodDef resolve(MethodReference methodReference) { - if (methodReference.DeclaringType == null) - return null; - var modules = findModules(methodReference.DeclaringType.Scope); - if (modules == null) - return null; - foreach (var module in modules) { - var rv = module.resolve(methodReference); - if (rv != null) - return rv; - } - if (isAutoCreatedType(methodReference.DeclaringType)) - return null; - Log.e("Could not resolve MethodReference {0} ({1:X8})", methodReference, methodReference.MetadataToken.ToInt32()); - return null; - } - - public FieldDef resolve(FieldReference fieldReference) { - if (fieldReference.DeclaringType == null) - return null; - var modules = findModules(fieldReference.DeclaringType.Scope); - if (modules == null) - return null; - foreach (var module in modules) { - var rv = module.resolve(fieldReference); - if (rv != null) - return rv; - } - if (isAutoCreatedType(fieldReference.DeclaringType)) - return null; - Log.e("Could not resolve FieldReference {0} ({1:X8})", fieldReference, fieldReference.MetadataToken.ToInt32()); - return null; - } - - public MethodDef findMethod(MethodReference methodReference) { - return resolve(methodReference); - } - - public PropertyDef findProp(MethodReference methodReference) { - var methodDef = resolve(methodReference); - if (methodDef == null) - return null; - return methodDef.Property; - } - - public EventDef findEvent(MethodReference methodReference) { - var methodDef = resolve(methodReference); - if (methodDef == null) - return null; - return methodDef.Event; - } - } -} diff --git a/de4dot.code/old_renamer/ExternalAssemblies.cs b/de4dot.code/old_renamer/ExternalAssemblies.cs deleted file mode 100644 index 9f0b8c34..00000000 --- a/de4dot.code/old_renamer/ExternalAssemblies.cs +++ /dev/null @@ -1,104 +0,0 @@ -/* - Copyright (C) 2011 de4dot@gmail.com - - This file is part of de4dot. - - de4dot is free software: you can redistribute it and/or modify - it under the terms of the GNU General Public License as published by - the Free Software Foundation, either version 3 of the License, or - (at your option) any later version. - - de4dot is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU General Public License for more details. - - You should have received a copy of the GNU General Public License - along with de4dot. If not, see . -*/ - -using System.Collections.Generic; -using Mono.Cecil; -using de4dot.blocks; - -namespace de4dot.old_renamer { - class ExternalAssembly { - AssemblyDefinition asmDef; - - public ExternalAssembly(AssemblyDefinition asmDef) { - this.asmDef = asmDef; - } - - public TypeDefinition resolve(TypeReference type) { - foreach (var module in asmDef.Modules) { - var typeDef = DotNetUtils.getType(module, type); - if (typeDef != null) - return typeDef; - } - - return null; - } - - public void unload() { - foreach (var module in asmDef.Modules) - DotNetUtils.typeCaches.invalidate(module); - } - } - - // Loads assemblies that aren't renamed - class ExternalAssemblies { - Dictionary assemblies = new Dictionary(); - - ExternalAssembly load(TypeReference type) { - var asmFullName = DotNetUtils.getFullAssemblyName(type); - ExternalAssembly asm; - if (assemblies.TryGetValue(asmFullName, out asm)) - return asm; - - AssemblyDefinition asmDef = null; - try { - asmDef = GlobalAssemblyResolver.Instance.Resolve(asmFullName); - } - catch (ResolutionException) { - } - catch (AssemblyResolutionException) { - } - if (asmDef == null) { - // If we can't load it now, we can't load it later. Make sure above code returns null. - assemblies[asmFullName] = null; - Log.w("Could not load assembly {0}", asmFullName); - return null; - } - if (assemblies.ContainsKey(asmDef.Name.FullName)) { - assemblies[asmFullName] = assemblies[asmDef.Name.FullName]; - return assemblies[asmDef.Name.FullName]; - } - - if (asmFullName == asmDef.Name.FullName) - Log.v("Loaded assembly {0}", asmFullName); - else - Log.v("Loaded assembly {0} (but wanted {1})", asmDef.Name.FullName, asmFullName); - - asm = new ExternalAssembly(asmDef); - assemblies[asmFullName] = asm; - assemblies[asmDef.Name.FullName] = asm; - return asm; - } - - public TypeDefinition resolve(TypeReference type) { - var asm = load(type); - if (asm == null) - return null; - return asm.resolve(type); - } - - public void unloadAll() { - foreach (var asm in assemblies.Values) { - if (asm == null) - continue; - asm.unload(); - } - assemblies.Clear(); - } - } -} diff --git a/de4dot.code/old_renamer/MemberRefFinder.cs b/de4dot.code/old_renamer/MemberRefFinder.cs deleted file mode 100644 index a77ace02..00000000 --- a/de4dot.code/old_renamer/MemberRefFinder.cs +++ /dev/null @@ -1,707 +0,0 @@ -/* - Copyright (C) 2011 de4dot@gmail.com - - This file is part of de4dot. - - de4dot is free software: you can redistribute it and/or modify - it under the terms of the GNU General Public License as published by - the Free Software Foundation, either version 3 of the License, or - (at your option) any later version. - - de4dot is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU General Public License for more details. - - You should have received a copy of the GNU General Public License - along with de4dot. If not, see . -*/ - -using System; -using System.Collections.Generic; -using Mono.Cecil; -using Mono.Cecil.Cil; -using de4dot.blocks; - -namespace de4dot.old_renamer { - // If it's a non-generic memberref, you could use GetMemberReference() to get a cached - // instance. For non-generics though, there's no other way than to scan every single - // type and all its fields, recursively, to find all of those refererences... That's - // what this class does. Close your eyes. - class MemberRefFinder { - public Dictionary eventDefinitions = new Dictionary(); - public Dictionary fieldReferences = new Dictionary(); - public Dictionary fieldDefinitions = new Dictionary(); - public Dictionary methodReferences = new Dictionary(); - public Dictionary methodDefinitions = new Dictionary(); - public Dictionary genericInstanceMethods = new Dictionary(); - public Dictionary propertyDefinitions = new Dictionary(); - public Dictionary typeReferences = new Dictionary(); - public Dictionary typeDefinitions = new Dictionary(); - public Dictionary genericParameters = new Dictionary(); - public Dictionary arrayTypes = new Dictionary(); - public Dictionary functionPointerTypes = new Dictionary(); - public Dictionary genericInstanceTypes = new Dictionary(); - public Dictionary optionalModifierTypes = new Dictionary(); - public Dictionary requiredModifierTypes = new Dictionary(); - public Dictionary pinnedTypes = new Dictionary(); - public Dictionary pointerTypes = new Dictionary(); - public Dictionary byReferenceTypes = new Dictionary(); - public Dictionary sentinelTypes = new Dictionary(); - - Stack memberRefStack; - - public void removeTypeDefinition(TypeDefinition td) { - if (!typeDefinitions.Remove(td)) - throw new ApplicationException(string.Format("Could not remove TypeDefinition: {0}", td)); - } - - public void removeEventDefinition(EventDefinition ed) { - if (!eventDefinitions.Remove(ed)) - throw new ApplicationException(string.Format("Could not remove EventDefinition: {0}", ed)); - } - - public void removeFieldDefinition(FieldDefinition fd) { - if (!fieldDefinitions.Remove(fd)) - throw new ApplicationException(string.Format("Could not remove FieldDefinition: {0}", fd)); - } - - public void removeMethodDefinition(MethodDefinition md) { - if (!methodDefinitions.Remove(md)) - throw new ApplicationException(string.Format("Could not remove MethodDefinition: {0}", md)); - } - - public void removePropertyDefinition(PropertyDefinition pd) { - if (!propertyDefinitions.Remove(pd)) - throw new ApplicationException(string.Format("Could not remove PropertyDefinition: {0}", pd)); - } - - public void findAll(ModuleDefinition module, IEnumerable types) { - // This needs to be big. About 2048 entries should be enough for most though... - memberRefStack = new Stack(0x1000); - - foreach (var type in types) - pushMember(type); - - addModule(module); - processAll(); - - memberRefStack = null; - } - - Dictionary exceptionMessages = new Dictionary(StringComparer.Ordinal); - void access(Action action) { - string exMessage = null; - try { - action(); - } - catch (ResolutionException ex) { - exMessage = ex.Message; - } - catch (AssemblyResolutionException ex) { - exMessage = ex.Message; - } - if (exMessage != null) { - if (!exceptionMessages.ContainsKey(exMessage)) { - exceptionMessages[exMessage] = true; - Log.w("Could not resolve a reference. ERROR: {0}", exMessage); - } - } - } - - void pushMember(MemberReference memberReference) { - if (memberReference == null) - return; - memberRefStack.Push(memberReference); - } - - void addModule(ModuleDefinition module) { - pushMember(module.EntryPoint); - access(() => addCustomAttributes(module.CustomAttributes)); - if (module.Assembly != null && module == module.Assembly.MainModule) { - var asm = module.Assembly; - access(() => addCustomAttributes(asm.CustomAttributes)); - addSecurityDeclarations(asm.SecurityDeclarations); - } - } - - void processAll() { - while (memberRefStack.Count > 0) - process(memberRefStack.Pop()); - } - - void process(MemberReference memberRef) { - if (memberRef == null) - return; - - var type = MemberReferenceHelper.getMemberReferenceType(memberRef); - switch (type) { - case CecilType.ArrayType: - doArrayType((ArrayType)memberRef); - break; - case CecilType.ByReferenceType: - doByReferenceType((ByReferenceType)memberRef); - break; - case CecilType.EventDefinition: - doEventDefinition((EventDefinition)memberRef); - break; - case CecilType.FieldDefinition: - doFieldDefinition((FieldDefinition)memberRef); - break; - case CecilType.FieldReference: - doFieldReference((FieldReference)memberRef); - break; - case CecilType.FunctionPointerType: - doFunctionPointerType((FunctionPointerType)memberRef); - break; - case CecilType.GenericInstanceMethod: - doGenericInstanceMethod((GenericInstanceMethod)memberRef); - break; - case CecilType.GenericInstanceType: - doGenericInstanceType((GenericInstanceType)memberRef); - break; - case CecilType.GenericParameter: - doGenericParameter((GenericParameter)memberRef); - break; - case CecilType.MethodDefinition: - doMethodDefinition((MethodDefinition)memberRef); - break; - case CecilType.MethodReference: - doMethodReference((MethodReference)memberRef); - break; - case CecilType.OptionalModifierType: - doOptionalModifierType((OptionalModifierType)memberRef); - break; - case CecilType.PinnedType: - doPinnedType((PinnedType)memberRef); - break; - case CecilType.PointerType: - doPointerType((PointerType)memberRef); - break; - case CecilType.PropertyDefinition: - doPropertyDefinition((PropertyDefinition)memberRef); - break; - case CecilType.RequiredModifierType: - doRequiredModifierType((RequiredModifierType)memberRef); - break; - case CecilType.SentinelType: - doSentinelType((SentinelType)memberRef); - break; - case CecilType.TypeDefinition: - doTypeDefinition((TypeDefinition)memberRef); - break; - case CecilType.TypeReference: - doTypeReference((TypeReference)memberRef); - break; - default: - throw new ApplicationException(string.Format("Unknown cecil type {0}", type)); - } - } - - void addCustomAttributes(IEnumerable attributes) { - if (attributes == null) - return; - foreach (var attr in attributes) - addCustomAttribute(attr); - } - void addCustomAttributeArguments(IEnumerable args) { - if (args == null) - return; - foreach (var arg in args) - addCustomAttributeArgument(arg); - } - void addCustomAttributeNamedArguments(IEnumerable args) { - if (args == null) - return; - foreach (var arg in args) - addCustomAttributeNamedArgument(arg); - } - void addParameterDefinitions(IEnumerable parameters) { - if (parameters == null) - return; - foreach (var param in parameters) - addParameterDefinition(param); - } - void addSecurityDeclarations(IEnumerable decls) { - if (decls == null) - return; - foreach (var decl in decls) - addSecurityDeclaration(decl); - } - void addSecurityAttributes(IEnumerable attrs) { - if (attrs == null) - return; - foreach (var attr in attrs) - addSecurityAttribute(attr); - } - void addExceptionHandlers(IEnumerable handlers) { - if (handlers == null) - return; - foreach (var h in handlers) - addExceptionHandler(h); - } - void addVariableDefinitions(IEnumerable vars) { - if (vars == null) - return; - foreach (var v in vars) - addVariableDefinition(v); - } - void addScopes(IEnumerable scopes) { - if (scopes == null) - return; - foreach (var s in scopes) - addScope(s); - } - void addInstructions(IEnumerable instrs) { - if (instrs == null) - return; - foreach (var instr in instrs) { - switch (instr.OpCode.OperandType) { - case OperandType.InlineTok: - case OperandType.InlineType: - case OperandType.InlineMethod: - case OperandType.InlineField: - pushMember(instr.Operand as MemberReference); - break; - case OperandType.InlineSig: - addCallSite(instr.Operand as CallSite); - break; - case OperandType.InlineVar: - case OperandType.ShortInlineVar: - addVariableDefinition(instr.Operand as VariableDefinition); - break; - case OperandType.InlineArg: - case OperandType.ShortInlineArg: - addParameterDefinition(instr.Operand as ParameterDefinition); - break; - } - } - } - void addTypeReferences(IEnumerable types) { - if (types == null) - return; - foreach (var typeRef in types) - pushMember(typeRef); - } - void addTypeDefinitions(IEnumerable types) { - if (types == null) - return; - foreach (var type in types) - pushMember(type); - } - void addMethodReferences(IEnumerable methodRefs) { - if (methodRefs == null) - return; - foreach (var m in methodRefs) - pushMember(m); - } - void addMethodDefinitions(IEnumerable methods) { - if (methods == null) - return; - foreach (var m in methods) - pushMember(m); - } - void addGenericParameters(IEnumerable parameters) { - if (parameters == null) - return; - foreach (var param in parameters) - pushMember(param); - } - void addFieldDefinitions(IEnumerable fields) { - if (fields == null) - return; - foreach (var f in fields) - pushMember(f); - } - void addEventDefinitions(IEnumerable events) { - if (events == null) - return; - foreach (var e in events) - pushMember(e); - } - void addPropertyDefinitions(IEnumerable props) { - if (props == null) - return; - foreach (var p in props) - pushMember(p); - } - void addMemberReference(MemberReference memberReference) { - if (memberReference == null) - return; - pushMember(memberReference.DeclaringType); - } - void addEventReference(EventReference eventReference) { - if (eventReference == null) - return; - addMemberReference(eventReference); - pushMember(eventReference.EventType); - } - void addEventDefinition(EventDefinition eventDefinition) { - if (eventDefinition == null) - return; - addEventReference(eventDefinition); - pushMember(eventDefinition.AddMethod); - pushMember(eventDefinition.InvokeMethod); - pushMember(eventDefinition.RemoveMethod); - addMethodDefinitions(eventDefinition.OtherMethods); - access(() => addCustomAttributes(eventDefinition.CustomAttributes)); - } - void addCustomAttribute(CustomAttribute attr) { - if (attr == null) - return; - pushMember(attr.Constructor); - - // Some obfuscators don't rename custom ctor arguments to the new name, causing - // Mono.Cecil to use a null reference. - try { access(() => addCustomAttributeArguments(attr.ConstructorArguments)); } catch (NullReferenceException) { } - try { access(() => addCustomAttributeNamedArguments(attr.Fields)); } catch (NullReferenceException) { } - try { access(() => addCustomAttributeNamedArguments(attr.Properties)); } catch (NullReferenceException) { } - } - void addCustomAttributeArgument(CustomAttributeArgument arg) { - pushMember(arg.Type); - } - void addCustomAttributeNamedArgument(CustomAttributeNamedArgument field) { - addCustomAttributeArgument(field.Argument); - } - void addFieldReference(FieldReference fieldReference) { - if (fieldReference == null) - return; - addMemberReference(fieldReference); - pushMember(fieldReference.FieldType); - } - void addFieldDefinition(FieldDefinition fieldDefinition) { - if (fieldDefinition == null) - return; - addFieldReference(fieldDefinition); - access(() => addCustomAttributes(fieldDefinition.CustomAttributes)); - } - void addMethodReference(MethodReference methodReference) { - if (methodReference == null) - return; - addMemberReference(methodReference); - addParameterDefinitions(methodReference.Parameters); - addMethodReturnType(methodReference.MethodReturnType); - addGenericParameters(methodReference.GenericParameters); - } - void addParameterReference(ParameterReference param) { - if (param == null) - return; - pushMember(param.ParameterType); - } - void addParameterDefinition(ParameterDefinition param) { - if (param == null) - return; - addParameterReference(param); - pushMember(param.Method as MemberReference); - access(() => addCustomAttributes(param.CustomAttributes)); - } - void addMethodReturnType(MethodReturnType methodReturnType) { - if (methodReturnType == null) - return; - pushMember(methodReturnType.Method as MemberReference); - pushMember(methodReturnType.ReturnType); - addParameterDefinition(methodReturnType.Parameter); - } - void addGenericParameter(GenericParameter param) { - if (param == null) - return; - addTypeReference(param); - pushMember(param.Owner as MemberReference); - access(() => addCustomAttributes(param.CustomAttributes)); - addTypeReferences(param.Constraints); - } - void addTypeReference(TypeReference typeReference) { - if (typeReference == null) - return; - addMemberReference(typeReference); - addGenericParameters(typeReference.GenericParameters); - } - void addMethodDefinition(MethodDefinition methodDefinition) { - if (methodDefinition == null) - return; - addMethodReference(methodDefinition); - access(() => addCustomAttributes(methodDefinition.CustomAttributes)); - addSecurityDeclarations(methodDefinition.SecurityDeclarations); - addMethodReferences(methodDefinition.Overrides); - addMethodBody(methodDefinition.Body); - } - void addSecurityDeclaration(SecurityDeclaration decl) { - if (decl == null) - return; - access(() => addSecurityAttributes(decl.SecurityAttributes)); - } - void addSecurityAttribute(SecurityAttribute attr) { - if (attr == null) - return; - pushMember(attr.AttributeType); - addCustomAttributeNamedArguments(attr.Fields); - addCustomAttributeNamedArguments(attr.Properties); - } - void addMethodBody(MethodBody body) { - if (body == null) - return; - pushMember(body.Method); - addParameterDefinition(body.ThisParameter); - addExceptionHandlers(body.ExceptionHandlers); - addVariableDefinitions(body.Variables); - addScope(body.Scope); - addInstructions(body.Instructions); - } - void addExceptionHandler(ExceptionHandler handler) { - if (handler == null) - return; - pushMember(handler.CatchType); - } - void addVariableDefinition(VariableDefinition v) { - if (v == null) - return; - addVariableReference(v); - } - void addVariableReference(VariableReference v) { - if (v == null) - return; - pushMember(v.VariableType); - } - void addScope(Scope scope) { - if (scope == null) - return; - addVariableDefinitions(scope.Variables); - addScopes(scope.Scopes); - } - void addGenericInstanceMethod(GenericInstanceMethod genericInstanceMethod) { - if (genericInstanceMethod == null) - return; - addMethodSpecification(genericInstanceMethod); - addTypeReferences(genericInstanceMethod.GenericArguments); - } - void addMethodSpecification(MethodSpecification methodSpecification) { - if (methodSpecification == null) - return; - addMethodReference(methodSpecification); - pushMember(methodSpecification.ElementMethod); - } - void addPropertyReference(PropertyReference propertyReference) { - if (propertyReference == null) - return; - addMemberReference(propertyReference); - pushMember(propertyReference.PropertyType); - } - void addPropertyDefinition(PropertyDefinition propertyDefinition) { - if (propertyDefinition == null) - return; - addPropertyReference(propertyDefinition); - access(() => addCustomAttributes(propertyDefinition.CustomAttributes)); - pushMember(propertyDefinition.GetMethod); - pushMember(propertyDefinition.SetMethod); - addMethodDefinitions(propertyDefinition.OtherMethods); - } - void addTypeDefinition(TypeDefinition typeDefinition) { - if (typeDefinition == null) - return; - addTypeReference(typeDefinition); - pushMember(typeDefinition.BaseType); - addTypeReferences(typeDefinition.Interfaces); - addTypeDefinitions(typeDefinition.NestedTypes); - addMethodDefinitions(typeDefinition.Methods); - addFieldDefinitions(typeDefinition.Fields); - addEventDefinitions(typeDefinition.Events); - addPropertyDefinitions(typeDefinition.Properties); - access(() => addCustomAttributes(typeDefinition.CustomAttributes)); - addSecurityDeclarations(typeDefinition.SecurityDeclarations); - } - void addTypeSpecification(TypeSpecification ts) { - if (ts == null) - return; - addTypeReference(ts); - pushMember(ts.ElementType); - } - void addArrayType(ArrayType at) { - if (at == null) - return; - addTypeSpecification(at); - } - void addFunctionPointerType(FunctionPointerType fpt) { - if (fpt == null) - return; - addTypeSpecification(fpt); - - // It's an anon MethodReference created by the class. Not useful to us. - //pushMember(fpt.function); - } - void addGenericInstanceType(GenericInstanceType git) { - if (git == null) - return; - addTypeSpecification(git); - addTypeReferences(git.GenericArguments); - } - void addOptionalModifierType(OptionalModifierType omt) { - if (omt == null) - return; - addTypeSpecification(omt); - pushMember(omt.ModifierType); - } - void addRequiredModifierType(RequiredModifierType rmt) { - if (rmt == null) - return; - addTypeSpecification(rmt); - pushMember(rmt.ModifierType); - } - void addPinnedType(PinnedType pt) { - if (pt == null) - return; - addTypeSpecification(pt); - } - void addPointerType(PointerType pt) { - if (pt == null) - return; - addTypeSpecification(pt); - } - void addByReferenceType(ByReferenceType brt) { - if (brt == null) - return; - addTypeSpecification(brt); - } - void addSentinelType(SentinelType st) { - if (st == null) - return; - addTypeSpecification(st); - } - void addCallSite(CallSite cs) { - pushMember(cs.signature); - } - - void doEventDefinition(EventDefinition eventDefinition) { - bool present; - if (eventDefinitions.TryGetValue(eventDefinition, out present)) - return; - eventDefinitions[eventDefinition] = true; - addEventDefinition(eventDefinition); - } - void doFieldReference(FieldReference fieldReference) { - bool present; - if (fieldReferences.TryGetValue(fieldReference, out present)) - return; - fieldReferences[fieldReference] = true; - addFieldReference(fieldReference); - } - void doFieldDefinition(FieldDefinition fieldDefinition) { - bool present; - if (fieldDefinitions.TryGetValue(fieldDefinition, out present)) - return; - fieldDefinitions[fieldDefinition] = true; - addFieldDefinition(fieldDefinition); - } - void doMethodReference(MethodReference methodReference) { - bool present; - if (methodReferences.TryGetValue(methodReference, out present)) - return; - methodReferences[methodReference] = true; - addMethodReference(methodReference); - } - void doMethodDefinition(MethodDefinition methodDefinition) { - bool present; - if (methodDefinitions.TryGetValue(methodDefinition, out present)) - return; - methodDefinitions[methodDefinition] = true; - addMethodDefinition(methodDefinition); - } - void doGenericInstanceMethod(GenericInstanceMethod genericInstanceMethod) { - bool present; - if (genericInstanceMethods.TryGetValue(genericInstanceMethod, out present)) - return; - genericInstanceMethods[genericInstanceMethod] = true; - addGenericInstanceMethod(genericInstanceMethod); - } - void doPropertyDefinition(PropertyDefinition propertyDefinition) { - bool present; - if (propertyDefinitions.TryGetValue(propertyDefinition, out present)) - return; - propertyDefinitions[propertyDefinition] = true; - addPropertyDefinition(propertyDefinition); - } - void doTypeReference(TypeReference typeReference) { - bool present; - if (typeReferences.TryGetValue(typeReference, out present)) - return; - typeReferences[typeReference] = true; - addTypeReference(typeReference); - } - void doTypeDefinition(TypeDefinition typeDefinition) { - bool present; - if (typeDefinitions.TryGetValue(typeDefinition, out present)) - return; - typeDefinitions[typeDefinition] = true; - addTypeDefinition(typeDefinition); - } - void doGenericParameter(GenericParameter genericParameter) { - bool present; - if (genericParameters.TryGetValue(genericParameter, out present)) - return; - genericParameters[genericParameter] = true; - addGenericParameter(genericParameter); - } - void doArrayType(ArrayType arrayType) { - bool present; - if (arrayTypes.TryGetValue(arrayType, out present)) - return; - arrayTypes[arrayType] = true; - addArrayType(arrayType); - } - void doFunctionPointerType(FunctionPointerType functionPointerType) { - bool present; - if (functionPointerTypes.TryGetValue(functionPointerType, out present)) - return; - functionPointerTypes[functionPointerType] = true; - addFunctionPointerType(functionPointerType); - } - void doGenericInstanceType(GenericInstanceType genericInstanceType) { - bool present; - if (genericInstanceTypes.TryGetValue(genericInstanceType, out present)) - return; - genericInstanceTypes[genericInstanceType] = true; - addGenericInstanceType(genericInstanceType); - } - void doOptionalModifierType(OptionalModifierType optionalModifierType) { - bool present; - if (optionalModifierTypes.TryGetValue(optionalModifierType, out present)) - return; - optionalModifierTypes[optionalModifierType] = true; - addOptionalModifierType(optionalModifierType); - } - void doRequiredModifierType(RequiredModifierType requiredModifierType) { - bool present; - if (requiredModifierTypes.TryGetValue(requiredModifierType, out present)) - return; - requiredModifierTypes[requiredModifierType] = true; - addRequiredModifierType(requiredModifierType); - } - void doPinnedType(PinnedType pinnedType) { - bool present; - if (pinnedTypes.TryGetValue(pinnedType, out present)) - return; - pinnedTypes[pinnedType] = true; - addPinnedType(pinnedType); - } - void doPointerType(PointerType pointerType) { - bool present; - if (pointerTypes.TryGetValue(pointerType, out present)) - return; - pointerTypes[pointerType] = true; - addPointerType(pointerType); - } - void doByReferenceType(ByReferenceType byReferenceType) { - bool present; - if (byReferenceTypes.TryGetValue(byReferenceType, out present)) - return; - byReferenceTypes[byReferenceType] = true; - addByReferenceType(byReferenceType); - } - void doSentinelType(SentinelType sentinelType) { - bool present; - if (sentinelTypes.TryGetValue(sentinelType, out present)) - return; - sentinelTypes[sentinelType] = true; - addSentinelType(sentinelType); - } - } -} diff --git a/de4dot.code/old_renamer/MemberRefs.cs b/de4dot.code/old_renamer/MemberRefs.cs deleted file mode 100644 index c1f61c2e..00000000 --- a/de4dot.code/old_renamer/MemberRefs.cs +++ /dev/null @@ -1,1627 +0,0 @@ -/* - Copyright (C) 2011 de4dot@gmail.com - - This file is part of de4dot. - - de4dot is free software: you can redistribute it and/or modify - it under the terms of the GNU General Public License as published by - the Free Software Foundation, either version 3 of the License, or - (at your option) any later version. - - de4dot is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU General Public License for more details. - - You should have received a copy of the GNU General Public License - along with de4dot. If not, see . -*/ - -using System; -using System.Collections.Generic; -using System.Text.RegularExpressions; -using Mono.Cecil; -using Mono.Cecil.Cil; -using de4dot.blocks; -using de4dot.deobfuscators; - -namespace de4dot.old_renamer { - abstract class Ref { - public string NewName { get; set; } - public string OldName { get; private set; } - public string OldFullName { get; private set; } - public int Index { get; private set; } - public MemberReference MemberReference { get; private set; } - public TypeDef Owner { get; set; } - public bool Renamed { get; set; } - - public Ref(MemberReference mr, TypeDef owner, int index) { - MemberReference = mr; - NewName = OldName = mr.Name; - OldFullName = mr.FullName; - Owner = owner; - Index = index; - } - - public bool gotNewName() { - return NewName != OldName; - } - - public abstract bool isSame(MemberReference mr); - - public bool rename(string newName) { - if (Renamed) - return false; - Renamed = true; - NewName = newName; - return true; - } - - static protected bool isVirtual(MethodDefinition m) { - return m != null && m.IsVirtual; - } - - protected static IList createGenericParamDefList(IEnumerable parameters) { - var list = new List(); - if (parameters == null) - return list; - int i = 0; - foreach (var param in parameters) - list.Add(new GenericParamDef(param, i++)); - return list; - } - - public override string ToString() { - return MemberReference != null ? MemberReference.ToString() : null; - } - } - - class FieldDef : Ref { - public FieldDef(FieldDefinition fieldDefinition, TypeDef owner, int index) - : base(fieldDefinition, owner, index) { - } - - public FieldDefinition FieldDefinition { - get { return (FieldDefinition)MemberReference; } - } - - public override bool isSame(MemberReference mr) { - return MemberReferenceHelper.compareFieldReference(FieldDefinition, mr as FieldReference); - } - } - - class EventRef : Ref { - public EventRef(EventReference eventReference, TypeDef owner, int index) - : base(eventReference, owner, index) { - } - - public EventReference EventReference { - get { return (EventReference)MemberReference; } - } - - public override bool isSame(MemberReference mr) { - return MemberReferenceHelper.compareEventReference(EventReference, mr as EventReference); - } - } - - class EventDef : EventRef { - public EventDef(EventDefinition eventDefinition, TypeDef owner, int index) - : base(eventDefinition, owner, index) { - } - - public EventDefinition EventDefinition { - get { return (EventDefinition)MemberReference; } - } - - public IEnumerable methodDefinitions() { - if (EventDefinition.AddMethod != null) - yield return EventDefinition.AddMethod; - if (EventDefinition.RemoveMethod != null) - yield return EventDefinition.RemoveMethod; - if (EventDefinition.InvokeMethod != null) - yield return EventDefinition.InvokeMethod; - if (EventDefinition.OtherMethods != null) { - foreach (var m in EventDefinition.OtherMethods) - yield return m; - } - } - - // Returns one of the overridden methods or null if none found - public MethodReference getOverrideMethod() { - foreach (var method in methodDefinitions()) { - if (method.HasOverrides) - return method.Overrides[0]; - } - return null; - } - - public bool isVirtual() { - foreach (var method in methodDefinitions()) { - if (isVirtual(method)) - return true; - } - return false; - } - } - - class PropertyRef : Ref { - public PropertyRef(PropertyReference propertyReference, TypeDef owner, int index) - : base(propertyReference, owner, index) { - } - - public PropertyReference PropertyReference { - get { return (PropertyReference)MemberReference; } - } - - public override bool isSame(MemberReference mr) { - return MemberReferenceHelper.comparePropertyReference(PropertyReference, mr as PropertyReference); - } - } - - class PropertyDef : PropertyRef { - public PropertyDef(PropertyDefinition propertyDefinition, TypeDef owner, int index) - : base(propertyDefinition, owner, index) { - } - - public PropertyDefinition PropertyDefinition { - get { return (PropertyDefinition)MemberReference; } - } - - public IEnumerable methodDefinitions() { - if (PropertyDefinition.GetMethod != null) - yield return PropertyDefinition.GetMethod; - if (PropertyDefinition.SetMethod != null) - yield return PropertyDefinition.SetMethod; - if (PropertyDefinition.OtherMethods != null) { - foreach (var m in PropertyDefinition.OtherMethods) - yield return m; - } - } - - // Returns one of the overridden methods or null if none found - public MethodReference getOverrideMethod() { - foreach (var method in methodDefinitions()) { - if (method.HasOverrides) - return method.Overrides[0]; - } - return null; - } - - public bool isVirtual() { - foreach (var method in methodDefinitions()) { - if (isVirtual(method)) - return true; - } - return false; - } - } - - class MethodRef : Ref { - public IList paramDefs = new List(); - - public IList ParamDefs { - get { return paramDefs; } - } - - public MethodRef(MethodReference methodReference, TypeDef owner, int index) - : base(methodReference, owner, index) { - if (methodReference.HasParameters) { - for (int i = 0; i < methodReference.Parameters.Count; i++) { - var param = methodReference.Parameters[i]; - paramDefs.Add(new ParamDef(param, i)); - } - } - } - - public MethodReference MethodReference { - get { return (MethodReference)MemberReference; } - } - - public override bool isSame(MemberReference mr) { - return MemberReferenceHelper.compareMethodReference(MethodReference, mr as MethodReference); - } - } - - class MethodDef : MethodRef { - IList genericParams; - - public IList GenericParams { - get { return genericParams; } - } - public PropertyDef Property { get; set; } - public EventDef Event { get; set; } - - public MethodDef(MethodDefinition methodDefinition, TypeDef owner, int index) - : base(methodDefinition, owner, index) { - genericParams = createGenericParamDefList(MethodDefinition.GenericParameters); - } - - public MethodDefinition MethodDefinition { - get { return (MethodDefinition)MemberReference; } - } - - public bool isVirtual() { - return isVirtual(MethodDefinition); - } - } - - class ParamDef { - public ParameterDefinition ParameterDefinition { get; set; } - public string OldName { get; private set; } - public string NewName { get; set; } - public int Index { get; private set; } - public bool Renamed { get; set; } - - public ParamDef(ParameterDefinition parameterDefinition, int index) { - this.ParameterDefinition = parameterDefinition; - NewName = OldName = parameterDefinition.Name; - Index = index; - } - - public bool gotNewName() { - return NewName != OldName; - } - } - - class GenericParamDef : Ref { - public GenericParamDef(GenericParameter genericParameter, int index) - : base(genericParameter, null, index) { - } - - public GenericParameter GenericParameter { - get { return (GenericParameter)MemberReference; } - } - - public override bool isSame(MemberReference mr) { - throw new NotImplementedException(); - } - } - - class TypeInfo { - public TypeReference typeReference; - public TypeDef typeDef; - public TypeInfo(TypeReference typeReference, TypeDef typeDef) { - this.typeReference = typeReference; - this.typeDef = typeDef; - } - } - - class TypeDef : Ref { - static Dictionary windowsFormsControlClasses = new Dictionary(StringComparer.Ordinal); - static TypeDef() { - windowsFormsControlClasses["System.Windows.Forms.Control"] = true; - windowsFormsControlClasses["System.Windows.Forms.AxHost"] = true; - windowsFormsControlClasses["System.Windows.Forms.ButtonBase"] = true; - windowsFormsControlClasses["System.Windows.Forms.Button"] = true; - windowsFormsControlClasses["System.Windows.Forms.CheckBox"] = true; - windowsFormsControlClasses["System.Windows.Forms.RadioButton"] = true; - windowsFormsControlClasses["System.Windows.Forms.DataGrid"] = true; - windowsFormsControlClasses["System.Windows.Forms.DataGridView"] = true; - windowsFormsControlClasses["System.Windows.Forms.DataVisualization.Charting.Chart"] = true; - windowsFormsControlClasses["System.Windows.Forms.DateTimePicker"] = true; - windowsFormsControlClasses["System.Windows.Forms.GroupBox"] = true; - windowsFormsControlClasses["System.Windows.Forms.Integration.ElementHost"] = true; - windowsFormsControlClasses["System.Windows.Forms.Label"] = true; - windowsFormsControlClasses["System.Windows.Forms.LinkLabel"] = true; - windowsFormsControlClasses["System.Windows.Forms.ListControl"] = true; - windowsFormsControlClasses["System.Windows.Forms.ComboBox"] = true; - windowsFormsControlClasses["Microsoft.VisualBasic.Compatibility.VB6.DriveListBox"] = true; - windowsFormsControlClasses["System.Windows.Forms.DataGridViewComboBoxEditingControl"] = true; - windowsFormsControlClasses["System.Windows.Forms.ListBox"] = true; - windowsFormsControlClasses["Microsoft.VisualBasic.Compatibility.VB6.DirListBox"] = true; - windowsFormsControlClasses["Microsoft.VisualBasic.Compatibility.VB6.FileListBox"] = true; - windowsFormsControlClasses["System.Windows.Forms.CheckedListBox"] = true; - windowsFormsControlClasses["System.Windows.Forms.ListView"] = true; - windowsFormsControlClasses["System.Windows.Forms.MdiClient"] = true; - windowsFormsControlClasses["System.Windows.Forms.MonthCalendar"] = true; - windowsFormsControlClasses["System.Windows.Forms.PictureBox"] = true; - windowsFormsControlClasses["System.Windows.Forms.PrintPreviewControl"] = true; - windowsFormsControlClasses["System.Windows.Forms.ProgressBar"] = true; - windowsFormsControlClasses["System.Windows.Forms.ScrollableControl"] = true; - windowsFormsControlClasses["System.Windows.Forms.ContainerControl"] = true; - windowsFormsControlClasses["System.Windows.Forms.Form"] = true; - windowsFormsControlClasses["System.ComponentModel.Design.CollectionEditor.CollectionForm"] = true; - windowsFormsControlClasses["System.Messaging.Design.QueuePathDialog"] = true; - windowsFormsControlClasses["System.ServiceProcess.Design.ServiceInstallerDialog"] = true; - windowsFormsControlClasses["System.Web.UI.Design.WebControls.CalendarAutoFormatDialog"] = true; - windowsFormsControlClasses["System.Web.UI.Design.WebControls.RegexEditorDialog"] = true; - windowsFormsControlClasses["System.Windows.Forms.Design.ComponentEditorForm"] = true; - windowsFormsControlClasses["System.Windows.Forms.PrintPreviewDialog"] = true; - windowsFormsControlClasses["System.Windows.Forms.ThreadExceptionDialog"] = true; - windowsFormsControlClasses["System.Workflow.Activities.Rules.Design.RuleConditionDialog"] = true; - windowsFormsControlClasses["System.Workflow.Activities.Rules.Design.RuleSetDialog"] = true; - windowsFormsControlClasses["System.Workflow.ComponentModel.Design.ThemeConfigurationDialog"] = true; - windowsFormsControlClasses["System.Workflow.ComponentModel.Design.TypeBrowserDialog"] = true; - windowsFormsControlClasses["System.Workflow.ComponentModel.Design.WorkflowPageSetupDialog"] = true; - windowsFormsControlClasses["System.Windows.Forms.PropertyGrid"] = true; - windowsFormsControlClasses["System.Windows.Forms.SplitContainer"] = true; - windowsFormsControlClasses["System.Windows.Forms.ToolStripContainer"] = true; - windowsFormsControlClasses["System.Windows.Forms.ToolStripPanel"] = true; - windowsFormsControlClasses["System.Windows.Forms.UpDownBase"] = true; - windowsFormsControlClasses["System.Windows.Forms.DomainUpDown"] = true; - windowsFormsControlClasses["System.Windows.Forms.NumericUpDown"] = true; - windowsFormsControlClasses["System.Windows.Forms.UserControl"] = true; - windowsFormsControlClasses["Microsoft.VisualBasic.Compatibility.VB6.ADODC"] = true; - windowsFormsControlClasses["System.Web.UI.Design.WebControls.ParameterEditorUserControl"] = true; - windowsFormsControlClasses["System.Workflow.ComponentModel.Design.WorkflowOutline"] = true; - windowsFormsControlClasses["System.Workflow.ComponentModel.Design.WorkflowView"] = true; - windowsFormsControlClasses["System.Windows.Forms.Design.ComponentTray"] = true; - windowsFormsControlClasses["System.Windows.Forms.Panel"] = true; - windowsFormsControlClasses["System.Windows.Forms.Design.ComponentEditorPage"] = true; - windowsFormsControlClasses["System.Windows.Forms.FlowLayoutPanel"] = true; - windowsFormsControlClasses["System.Windows.Forms.SplitterPanel"] = true; - windowsFormsControlClasses["System.Windows.Forms.TableLayoutPanel"] = true; - windowsFormsControlClasses["System.ComponentModel.Design.ByteViewer"] = true; - windowsFormsControlClasses["System.Windows.Forms.TabPage"] = true; - windowsFormsControlClasses["System.Windows.Forms.ToolStripContentPanel"] = true; - windowsFormsControlClasses["System.Windows.Forms.ToolStrip"] = true; - windowsFormsControlClasses["System.Windows.Forms.BindingNavigator"] = true; - windowsFormsControlClasses["System.Windows.Forms.MenuStrip"] = true; - windowsFormsControlClasses["System.Windows.Forms.StatusStrip"] = true; - windowsFormsControlClasses["System.Windows.Forms.ToolStripDropDown"] = true; - windowsFormsControlClasses["System.Windows.Forms.ToolStripDropDownMenu"] = true; - windowsFormsControlClasses["System.Windows.Forms.ContextMenuStrip"] = true; - windowsFormsControlClasses["System.Windows.Forms.ToolStripOverflow"] = true; - windowsFormsControlClasses["System.Windows.Forms.ScrollBar"] = true; - windowsFormsControlClasses["System.Windows.Forms.HScrollBar"] = true; - windowsFormsControlClasses["System.Windows.Forms.VScrollBar"] = true; - windowsFormsControlClasses["System.Windows.Forms.Splitter"] = true; - windowsFormsControlClasses["System.Windows.Forms.StatusBar"] = true; - windowsFormsControlClasses["System.Windows.Forms.TabControl"] = true; - windowsFormsControlClasses["System.Windows.Forms.TextBoxBase"] = true; - windowsFormsControlClasses["System.Windows.Forms.MaskedTextBox"] = true; - windowsFormsControlClasses["System.Windows.Forms.RichTextBox"] = true; - windowsFormsControlClasses["System.Windows.Forms.TextBox"] = true; - windowsFormsControlClasses["System.Windows.Forms.DataGridTextBox"] = true; - windowsFormsControlClasses["System.Windows.Forms.DataGridViewTextBoxEditingControl"] = true; - windowsFormsControlClasses["System.Windows.Forms.ToolBar"] = true; - windowsFormsControlClasses["System.Windows.Forms.TrackBar"] = true; - windowsFormsControlClasses["System.Windows.Forms.TreeView"] = true; - windowsFormsControlClasses["System.ComponentModel.Design.ObjectSelectorEditor.Selector"] = true; - windowsFormsControlClasses["System.Windows.Forms.WebBrowserBase"] = true; - windowsFormsControlClasses["System.Windows.Forms.WebBrowser"] = true; - } - - Dictionary newMethodNames = new Dictionary(); - Dictionary newPropertyNames = new Dictionary(); - - public IDefFinder defFinder; - public TypeInfo baseType = null; - public IList interfaces = new List(); // directly implemented interfaces - public IList derivedTypes = new List(); - public Module module; - string newNamespace = null; - - EventDefDict events = new EventDefDict(); - FieldDefDict fields = new FieldDefDict(); - MethodDefDict methods = new MethodDefDict(); - PropertyDefDict properties = new PropertyDefDict(); - TypeDefDict types = new TypeDefDict(); - IList genericParams; - public TypeDefinition TypeDefinition { - get { return (TypeDefinition)MemberReference; } - } - public MemberRenameState MemberRenameState { get; set; } - public MemberRenameState InterfaceScopeState { get; set; } - bool prepareRenameMembersCalled = false; - - public IEnumerable NestedTypes { - get { return types.getSorted(); } - } - - public TypeDef NestingType { get; set; } - - public IList GenericParams { - get { return genericParams; } - } - - public bool IsRenamable { - get { return module != null; } - } - - bool IsDelegate { get; set; } - - public string NewNamespace { - get { return newNamespace; } - set { newNamespace = value; } - } - - public TypeDef(TypeDefinition typeDefinition) - : this(typeDefinition, null) { - } - - public TypeDef(TypeDefinition typeDefinition, Module module, int index = 0) - : base(typeDefinition, null, index) { - this.module = module; - genericParams = createGenericParamDefList(TypeDefinition.GenericParameters); - } - - public override bool isSame(MemberReference mr) { - return MemberReferenceHelper.compareTypes(TypeDefinition, mr as TypeReference); - } - - public bool isInterface() { - return TypeDefinition.IsInterface; - } - - public IEnumerable Methods { - get { return methods.getAll(); } - } - - bool? isWindowsFormsControlDerivedClass_cached; - bool isWindowsFormsControlDerivedClass() { - if (!isWindowsFormsControlDerivedClass_cached.HasValue) - isWindowsFormsControlDerivedClass_cached = isWindowsFormsControlDerivedClassInternal(); - return isWindowsFormsControlDerivedClass_cached.Value; - } - - bool isWindowsFormsControlDerivedClassInternal() { - if (windowsFormsControlClasses.ContainsKey(OldFullName)) - return true; - if (baseType != null) - return baseType.typeDef.isWindowsFormsControlDerivedClass(); - if (TypeDefinition.BaseType != null) - return windowsFormsControlClasses.ContainsKey(TypeDefinition.BaseType.FullName); - return false; - } - - public void addMembers() { - var type = TypeDefinition; - - for (int i = 0; i < type.Events.Count; i++) - add(new EventDef(type.Events[i], this, i)); - for (int i = 0; i < type.Fields.Count; i++) - add(new FieldDef(type.Fields[i], this, i)); - for (int i = 0; i < type.Methods.Count; i++) - add(new MethodDef(type.Methods[i], this, i)); - for (int i = 0; i < type.Properties.Count; i++) - add(new PropertyDef(type.Properties[i], this, i)); - - foreach (var propDef in properties.getAll()) { - foreach (var method in propDef.methodDefinitions()) { - var methodDef = find(method); - if (methodDef == null) - throw new ApplicationException("Could not find property method"); - methodDef.Property = propDef; - } - } - - foreach (var eventDef in events.getAll()) { - foreach (var method in eventDef.methodDefinitions()) { - var methodDef = find(method); - if (methodDef == null) - throw new ApplicationException("Could not find event method"); - methodDef.Event = eventDef; - } - } - } - - public void addInterface(TypeDef ifaceDef, TypeReference iface) { - if (ifaceDef == null || iface == null) - return; - interfaces.Add(new TypeInfo(iface, ifaceDef)); - } - - public void addBaseType(TypeDef baseDef, TypeReference baseRef) { - if (baseDef == null || baseRef == null) - return; - baseType = new TypeInfo(baseRef, baseDef); - IsDelegate = baseRef.FullName == "System.Delegate" || baseRef.FullName == "System.MulticastDelegate"; - } - - // Called when all types have been renamed - public void onTypesRenamed() { - events.onTypesRenamed(); - fields.onTypesRenamed(); - methods.onTypesRenamed(); - types.onTypesRenamed(); - } - - public IEnumerable getAllInterfaces() { - if (isInterface()) - yield return this; - foreach (var ifaceInfo in interfaces) { - foreach (var iface in ifaceInfo.typeDef.getAllInterfaces()) - yield return iface; - } - foreach (var typeDef in derivedTypes) { - foreach (var iface in typeDef.getAllInterfaces()) - yield return iface; - } - } - - public IEnumerable getAllRenamableInterfaces() { - foreach (var iface in getAllInterfaces()) { - if (iface.IsRenamable) - yield return iface; - } - } - - public void add(EventDef e) { - events.add(e); - } - - public void add(FieldDef f) { - fields.add(f); - } - - public void add(MethodDef m) { - methods.add(m); - } - - public void add(PropertyDef p) { - properties.add(p); - } - - public void add(TypeDef t) { - types.add(t); - } - - public MethodDef find(MethodReference mr) { - return methods.find(mr); - } - - public FieldDef find(FieldReference fr) { - return fields.find(fr); - } - - IEnumerable getInstanceFields() { - foreach (var fieldDef in fields.getSorted()) { - if (!fieldDef.FieldDefinition.IsStatic) - yield return fieldDef; - } - } - - bool isNested() { - return NestingType != null; - } - - bool isGlobalType() { - if (!isNested()) - return TypeDefinition.IsPublic; - var mask = TypeDefinition.Attributes & TypeAttributes.VisibilityMask; - switch (mask) { - case TypeAttributes.NestedPrivate: - case TypeAttributes.NestedAssembly: - case TypeAttributes.NestedFamANDAssem: - return false; - case TypeAttributes.NestedPublic: - case TypeAttributes.NestedFamily: - case TypeAttributes.NestedFamORAssem: - return NestingType.isGlobalType(); - default: - return false; - } - } - - // Renames name, namespace, and generic parameters if needed. Does not rename members. - public void prepareRename(TypeNameState typeNameState) { - var typeDefinition = TypeDefinition; - ITypeNameCreator nameCreator = isGlobalType() ? - typeNameState.globalTypeNameCreator : - typeNameState.internalTypeNameCreator; - - if (OldFullName != "" && !typeNameState.IsValidName(OldName)) { - var newBaseType = baseType != null && baseType.typeDef.Renamed ? baseType.typeDef.NewName : null; - string origClassName = null; - if (isWindowsFormsControlDerivedClass()) - origClassName = findWindowsFormsClassName(); - if (origClassName != null && typeNameState.IsValidName(origClassName)) - rename(typeNameState.currentNames.newName(OldName, new NameCreator2(origClassName))); - else - rename(nameCreator.newName(typeDefinition, newBaseType)); - } - - if (newNamespace == null && typeDefinition.Namespace != "" && !typeNameState.isValidNamespace(typeDefinition.Namespace)) - newNamespace = typeNameState.newNamespace(typeDefinition.Namespace); - - prepareRenameGenericParams(genericParams, typeNameState.IsValidName); - } - - string findWindowsFormsClassName() { - foreach (var methodDef in methods.getAll()) { - if (methodDef.MethodDefinition.Body == null) - continue; - if (methodDef.MethodDefinition.IsStatic || methodDef.MethodDefinition.IsVirtual) - continue; - var instructions = methodDef.MethodDefinition.Body.Instructions; - for (int i = 2; i < instructions.Count; i++) { - var call = instructions[i]; - if (call.OpCode.Code != Code.Call && call.OpCode.Code != Code.Callvirt) - continue; - if (!isWindowsFormsSetNameMethod(call.Operand as MethodReference)) - continue; - - var ldstr = instructions[i - 1]; - if (ldstr.OpCode.Code != Code.Ldstr) - continue; - var className = ldstr.Operand as string; - if (className == null) - continue; - - if (DotNetUtils.getArgIndex(methodDef.MethodDefinition, instructions[i - 2]) != 0) - continue; - - findInitializeComponentMethod(methodDef); - return className; - } - } - return null; - } - - void findInitializeComponentMethod(MethodDef possibleInitMethod) { - foreach (var methodDef in methods.getAll()) { - if (methodDef.OldName != ".ctor") - continue; - if (methodDef.MethodDefinition.Body == null) - continue; - foreach (var instr in methodDef.MethodDefinition.Body.Instructions) { - if (instr.OpCode.Code != Code.Call && instr.OpCode.Code != Code.Callvirt) - continue; - if (!MemberReferenceHelper.compareMethodReferenceAndDeclaringType(possibleInitMethod.MethodDefinition, instr.Operand as MethodReference)) - continue; - - newMethodNames[possibleInitMethod] = "InitializeComponent"; - return; - } - } - } - - static bool isWindowsFormsSetNameMethod(MethodReference method) { - if (method == null) - return false; - if (method.Name != "set_Name") - return false; - if (method.MethodReturnType.ReturnType.FullName != "System.Void") - return false; - if (method.Parameters.Count != 1) - return false; - if (method.Parameters[0].ParameterType.FullName != "System.String") - return false; - if (!Utils.StartsWith(method.DeclaringType.FullName, "System.Windows.Forms.", StringComparison.Ordinal)) - return false; - return true; - } - - public void rename() { - var typeDefinition = TypeDefinition; - - Log.v("Type: {0} ({1:X8})", TypeDefinition.FullName, TypeDefinition.MetadataToken.ToUInt32()); - Log.indent(); - - renameGenericParams(genericParams); - - if (gotNewName()) { - var old = typeDefinition.Name; - typeDefinition.Name = NewName; - Log.v("Name: {0} => {1}", old, typeDefinition.Name); - } - - if (newNamespace != null) { - var old = typeDefinition.Namespace; - typeDefinition.Namespace = newNamespace; - Log.v("Namespace: {0} => {1}", old, typeDefinition.Namespace); - } - - Log.deIndent(); - } - - static void prepareRenameGenericParams(IList genericParams, Func isValidName, IList otherGenericParams = null) { - Dictionary usedNames = new Dictionary(StringComparer.Ordinal); - INameCreator nameCreator = new GenericParamNameCreator(); - - if (otherGenericParams != null) { - foreach (var param in otherGenericParams) - usedNames[param.NewName] = true; - } - - foreach (var param in genericParams) { - if (!isValidName(param.OldName) || usedNames.ContainsKey(param.OldName)) { - string newName; - do { - newName = nameCreator.newName(); - } while (usedNames.ContainsKey(newName)); - usedNames[newName] = true; - param.rename(newName); - } - } - } - - static void renameGenericParams(IList genericParams) { - foreach (var param in genericParams) { - if (!param.gotNewName()) - continue; - param.GenericParameter.Name = param.NewName; - Log.v("GenParam: {0} => {1}", param.OldFullName, param.GenericParameter.FullName); - } - } - - public void renameMembers() { - Log.v("Type: {0}", TypeDefinition.FullName); - Log.indent(); - - renameFields(); - renameProperties(); - renameEvents(); - renameMethods(); - - Log.deIndent(); - } - - void renameFields() { - foreach (var fieldDef in fields.getSorted()) { - if (!fieldDef.gotNewName()) - continue; - fieldDef.FieldDefinition.Name = fieldDef.NewName; - Log.v("Field: {0} ({1:X8}) => {2}", fieldDef.OldFullName, fieldDef.FieldDefinition.MetadataToken.ToUInt32(), fieldDef.FieldDefinition.FullName); - } - } - - void renameProperties() { - foreach (var propDef in properties.getSorted()) { - if (!propDef.gotNewName()) - continue; - propDef.PropertyDefinition.Name = propDef.NewName; - Log.v("Property: {0} ({1:X8}) => {2}", propDef.OldFullName, propDef.PropertyDefinition.MetadataToken.ToUInt32(), propDef.PropertyDefinition.FullName); - } - } - - void renameEvents() { - foreach (var eventDef in events.getSorted()) { - if (!eventDef.gotNewName()) - continue; - eventDef.EventDefinition.Name = eventDef.NewName; - Log.v("Event: {0} ({1:X8}) => {2}", eventDef.OldFullName, eventDef.EventDefinition.MetadataToken.ToUInt32(), eventDef.EventDefinition.FullName); - } - } - - void renameMethods() { - foreach (var methodDef in methods.getSorted()) { - Log.v("Method {0} ({1:X8})", methodDef.OldFullName, methodDef.MethodDefinition.MetadataToken.ToUInt32()); - Log.indent(); - - renameGenericParams(methodDef.GenericParams); - - if (methodDef.gotNewName()) { - methodDef.MethodReference.Name = methodDef.NewName; - Log.v("Name: {0} => {1}", methodDef.OldFullName, methodDef.MethodReference.FullName); - } - - foreach (var param in methodDef.ParamDefs) { - if (!param.gotNewName()) - continue; - param.ParameterDefinition.Name = param.NewName; - Log.v("Param ({0}/{1}): {2} => {3}", param.Index + 1, methodDef.ParamDefs.Count, param.OldName, param.NewName); - } - - Log.deIndent(); - } - } - - public void initializeVirtualMembers() { - expandGenerics(); - foreach (var propDef in properties.getSorted()) { - if (propDef.isVirtual()) - MemberRenameState.add(propDef); - } - foreach (var eventDef in events.getSorted()) { - if (eventDef.isVirtual()) - MemberRenameState.add(eventDef); - } - foreach (var methodDef in methods.getSorted()) { - if (methodDef.isVirtual()) - MemberRenameState.add(methodDef); - } - } - - public void prepareRenameMembers() { - if (prepareRenameMembersCalled) - return; - prepareRenameMembersCalled = true; - - foreach (var ifaceInfo in interfaces) - ifaceInfo.typeDef.prepareRenameMembers(); - if (baseType != null) - baseType.typeDef.prepareRenameMembers(); - - if (MemberRenameState == null) - MemberRenameState = baseType.typeDef.MemberRenameState.clone(); - - if (IsRenamable) { - foreach (var fieldDef in fields.getAll()) - MemberRenameState.variableNameState.addFieldName(fieldDef.OldName); - foreach (var methodDef in methods.getAll()) - MemberRenameState.variableNameState.addMethodName(methodDef.OldName); - } - - // For each base type and interface it implements, add all its virtual methods, props, - // and events if the type is a non-renamable type (eg. it's from mscorlib or some other - // non-deobfuscated assembly). - if (IsRenamable) { - foreach (var ifaceInfo in interfaces) { - if (!ifaceInfo.typeDef.IsRenamable) - MemberRenameState.mergeRenamed(ifaceInfo.typeDef.MemberRenameState); - } - if (baseType != null && !baseType.typeDef.IsRenamable) - MemberRenameState.mergeRenamed(baseType.typeDef.MemberRenameState); - } - - if (InterfaceScopeState != null) - MemberRenameState.mergeRenamed(InterfaceScopeState); - - expandGenerics(); - - if (IsRenamable) { - MemberRenameState.variableNameState.IsValidName = module.IsValidName; - - if (isWindowsFormsControlDerivedClass()) - initializeWindowsFormsFieldsAndProps(); - - prepareRenameFields(); // must be first - prepareRenameProperties(); - prepareRenameEvents(); - - initializeEventHandlerNames(); - - prepareRenameMethods(); // must be last - } - } - - // Replaces the generic params with the generic args, if any - void expandGenerics() { - foreach (var typeInfo in getTypeInfos()) { - var git = typeInfo.typeReference as GenericInstanceType; - if (git == null) - continue; - - if (git.GenericArguments.Count != typeInfo.typeDef.TypeDefinition.GenericParameters.Count) { - throw new ApplicationException(string.Format("# args ({0}) != # params ({1})", - git.GenericArguments.Count, - typeInfo.typeDef.TypeDefinition.GenericParameters.Count)); - } - expandProperties(git); - expandEvents(git); - expandMethods(git); - } - } - - IEnumerable getTypeInfos() { - if (baseType != null) - yield return baseType; - foreach (var typeInfo in interfaces) - yield return typeInfo; - } - - void expandProperties(GenericInstanceType git) { - foreach (var propRef in new List(MemberRenameState.properties.Values)) { - var newPropRef = new GenericPropertyRefExpander(propRef, git).expand(); - if (ReferenceEquals(newPropRef, propRef)) - continue; - MemberRenameState.add(newPropRef); - } - } - - void expandEvents(GenericInstanceType git) { - foreach (var eventRef in new List(MemberRenameState.events.Values)) { - var newEventRef = new GenericEventRefExpander(eventRef, git).expand(); - if (ReferenceEquals(eventRef, newEventRef)) - continue; - MemberRenameState.add(newEventRef); - } - } - - void expandMethods(GenericInstanceType git) { - foreach (var methodRef in new List(MemberRenameState.methods.Values)) { - var newMethodRef = new GenericMethodRefExpander(methodRef, git).expand(); - if (ReferenceEquals(methodRef, newMethodRef)) - continue; - MemberRenameState.add(newMethodRef); - } - } - - bool hasFlagsAttribute() { - if (TypeDefinition.CustomAttributes != null) { - foreach (var attr in TypeDefinition.CustomAttributes) { - if (MemberReferenceHelper.verifyType(attr.AttributeType, "mscorlib", "System.FlagsAttribute")) - return true; - } - } - return false; - } - - void prepareRenameFields() { - var variableNameState = MemberRenameState.variableNameState; - - if (TypeDefinition.IsEnum) { - var instanceFields = new List(getInstanceFields()); - if (instanceFields.Count == 1) { - var fieldDef = instanceFields[0]; - if (fieldDef.rename("value__")) { - fieldDef.FieldDefinition.IsRuntimeSpecialName = true; - fieldDef.FieldDefinition.IsSpecialName = true; - } - } - - int i = 0; - string nameFormat = hasFlagsAttribute() ? "flag_{0}" : "const_{0}"; - foreach (var fieldDef in fields.getSorted()) { - if (fieldDef.Renamed) - continue; - if (!fieldDef.FieldDefinition.IsStatic || !fieldDef.FieldDefinition.IsLiteral) - continue; - if (!variableNameState.IsValidName(fieldDef.OldName)) - fieldDef.rename(string.Format(nameFormat, i)); - i++; - } - } - foreach (var fieldDef in fields.getSorted()) { - if (fieldDef.Renamed) - continue; - if (!variableNameState.IsValidName(fieldDef.OldName)) - fieldDef.rename(variableNameState.getNewFieldName(fieldDef.FieldDefinition)); - } - } - - void initializeWindowsFormsFieldsAndProps() { - var ourFields = new Dictionary(); - foreach (var fieldDef in fields.getAll()) - ourFields[new FieldReferenceAndDeclaringTypeKey(fieldDef.FieldDefinition)] = fieldDef; - var ourMethods = new Dictionary(); - foreach (var methodDef in methods.getAll()) - ourMethods[new MethodReferenceAndDeclaringTypeKey(methodDef.MethodDefinition)] = methodDef; - - var variableNameState = MemberRenameState.variableNameState; - foreach (var methodDef in methods.getAll()) { - if (methodDef.MethodDefinition.Body == null) - continue; - if (methodDef.MethodDefinition.IsStatic || methodDef.MethodDefinition.IsVirtual) - continue; - var instructions = methodDef.MethodDefinition.Body.Instructions; - for (int i = 2; i < instructions.Count; i++) { - var call = instructions[i]; - if (call.OpCode.Code != Code.Call && call.OpCode.Code != Code.Callvirt) - continue; - if (!isWindowsFormsSetNameMethod(call.Operand as MethodReference)) - continue; - - var ldstr = instructions[i - 1]; - if (ldstr.OpCode.Code != Code.Ldstr) - continue; - var fieldName = ldstr.Operand as string; - if (fieldName == null || !variableNameState.IsValidName(fieldName)) - continue; - if (!variableNameState.IsValidName(fieldName)) - continue; - - var instr = instructions[i - 2]; - FieldReference fieldRef = null; - if (instr.OpCode.Code == Code.Call || instr.OpCode.Code == Code.Callvirt) { - var calledMethod = instr.Operand as MethodReference; - if (calledMethod == null) - continue; - MethodDef calledMethodDef; - if (!ourMethods.TryGetValue(new MethodReferenceAndDeclaringTypeKey(calledMethod), out calledMethodDef)) - continue; - fieldRef = getFieldReference(calledMethodDef.MethodDefinition); - if (fieldRef == null) - continue; - - var propDef = calledMethodDef.Property; - if (propDef == null) - continue; - - newPropertyNames[propDef] = fieldName; - fieldName = "_" + fieldName; - } - else if (instr.OpCode.Code == Code.Ldfld) { - fieldRef = instr.Operand as FieldReference; - } - - if (fieldRef == null) - continue; - FieldDef fieldDef; - if (!ourFields.TryGetValue(new FieldReferenceAndDeclaringTypeKey(fieldRef), out fieldDef)) - continue; - - if (fieldDef.Renamed) - continue; - - fieldDef.rename(variableNameState.getNewFieldName(fieldDef.OldName, new NameCreator2(fieldName))); - } - } - } - - static FieldReference getFieldReference(MethodDefinition method) { - if (method == null || method.Body == null) - return null; - var instructions = method.Body.Instructions; - int index = 0; - var ldarg0 = DotNetUtils.getInstruction(instructions, ref index); - if (ldarg0 == null || DotNetUtils.getArgIndex(method, ldarg0) != 0) - return null; - var ldfld = DotNetUtils.getInstruction(instructions, ref index); - if (ldfld == null || ldfld.OpCode.Code != Code.Ldfld) - return null; - var ret = DotNetUtils.getInstruction(instructions, ref index); - if (ret == null || ret.OpCode.Code != Code.Ret) - return null; - return ldfld.Operand as FieldReference; - } - - void initializeEventHandlerNames() { - var ourFields = new Dictionary(); - foreach (var fieldDef in fields.getAll()) - ourFields[new FieldReferenceAndDeclaringTypeKey(fieldDef.FieldDefinition)] = fieldDef; - var ourMethods = new Dictionary(); - foreach (var methodDef in methods.getAll()) - ourMethods[new MethodReferenceAndDeclaringTypeKey(methodDef.MethodDefinition)] = methodDef; - - initVbEventHandlers(ourFields, ourMethods); - initFieldEventHandlers(ourFields, ourMethods); - initTypeEventHandlers(ourFields, ourMethods); - } - - // VB initializes the handlers in the property setter, where it first removes the handler - // from the previous control, and then adds the handler to the new control. - void initVbEventHandlers(Dictionary ourFields, Dictionary ourMethods) { - var variableNameState = MemberRenameState.variableNameState; - foreach (var propDef in properties.getAll()) { - var setter = propDef.PropertyDefinition.SetMethod; - if (setter == null) - continue; - var setterDef = find(setter); - if (setterDef == null) - continue; - - string eventName; - var handler = getVbHandler(setterDef.MethodDefinition, out eventName); - if (handler == null) - continue; - MethodDef handlerDef; - if (!ourMethods.TryGetValue(new MethodReferenceAndDeclaringTypeKey(handler), out handlerDef)) - continue; - - if (!MemberRenameState.variableNameState.IsValidName(eventName)) - continue; - - newMethodNames[handlerDef] = string.Format("{0}_{1}", propDef.NewName, eventName); - } - } - - MethodReference getVbHandler(MethodDefinition method, out string eventName) { - eventName = null; - if (method.Body == null) - return null; - if (method.MethodReturnType.ReturnType.FullName != "System.Void") - return null; - if (method.Parameters.Count != 1) - return null; - if (method.Body.Variables.Count != 1) - return null; - if (!isEventHandlerType(method.Body.Variables[0].VariableType)) - return null; - - var instructions = method.Body.Instructions; - int index = 0; - - int newobjIndex = findInstruction(instructions, index, Code.Newobj); - if (newobjIndex == -1 || findInstruction(instructions, newobjIndex + 1, Code.Newobj) != -1) - return null; - if (!isEventHandlerCtor(instructions[newobjIndex].Operand as MethodReference)) - return null; - if (newobjIndex < 1) - return null; - var ldvirtftn = instructions[newobjIndex - 1]; - if (ldvirtftn.OpCode.Code != Code.Ldvirtftn && ldvirtftn.OpCode.Code != Code.Ldftn) - return null; - var handlerMethod = ldvirtftn.Operand as MethodReference; - if (handlerMethod == null) - return null; - if (!MemberReferenceHelper.compareTypes(method.DeclaringType, handlerMethod.DeclaringType)) - return null; - index = newobjIndex; - - FieldReference addField, removeField; - MethodReference addMethod, removeMethod; - if (!findEventCall(instructions, ref index, out removeField, out removeMethod)) - return null; - if (!findEventCall(instructions, ref index, out addField, out addMethod)) - return null; - - if (findInstruction(instructions, index, Code.Callvirt) != -1) - return null; - if (!MemberReferenceHelper.compareFieldReference(addField, removeField)) - return null; - if (!MemberReferenceHelper.compareTypes(method.DeclaringType, addField.DeclaringType)) - return null; - if (!MemberReferenceHelper.compareTypes(addMethod.DeclaringType, removeMethod.DeclaringType)) - return null; - if (!Utils.StartsWith(addMethod.Name, "add_", StringComparison.Ordinal)) - return null; - if (!Utils.StartsWith(removeMethod.Name, "remove_", StringComparison.Ordinal)) - return null; - eventName = addMethod.Name.Substring(4); - if (eventName != removeMethod.Name.Substring(7)) - return null; - if (eventName == "") - return null; - - return handlerMethod; - } - - static bool findEventCall(IList instructions, ref int index, out FieldReference field, out MethodReference calledMethod) { - field = null; - calledMethod = null; - - int callvirt = findInstruction(instructions, index, Code.Callvirt); - if (callvirt < 2) - return false; - index = callvirt + 1; - - var ldloc = instructions[callvirt - 1]; - if (ldloc.OpCode.Code != Code.Ldloc_0) - return false; - - var ldfld = instructions[callvirt - 2]; - if (ldfld.OpCode.Code != Code.Ldfld) - return false; - - field = ldfld.Operand as FieldReference; - calledMethod = instructions[callvirt].Operand as MethodReference; - return field != null && calledMethod != null; - } - - static int findInstruction(IList instructions, int index, Code code) { - for (int i = index; i < instructions.Count; i++) { - if (instructions[i].OpCode.Code == code) - return i; - } - return -1; - } - - void initFieldEventHandlers(Dictionary ourFields, Dictionary ourMethods) { - var variableNameState = MemberRenameState.variableNameState; - foreach (var methodDef in methods.getAll()) { - if (methodDef.MethodDefinition.Body == null) - continue; - if (methodDef.MethodDefinition.IsStatic) - continue; - var instructions = methodDef.MethodDefinition.Body.Instructions; - for (int i = 0; i < instructions.Count - 6; i++) { - // We're looking for this code pattern: - // ldarg.0 - // ldfld field - // ldarg.0 - // ldftn method / ldarg.0 + ldvirtftn - // newobj event_handler_ctor - // callvirt add_SomeEvent - - if (DotNetUtils.getArgIndex(methodDef.MethodDefinition, instructions[i]) != 0) - continue; - int index = i + 1; - - var ldfld = instructions[index++]; - if (ldfld.OpCode.Code != Code.Ldfld) - continue; - var fieldRef = ldfld.Operand as FieldReference; - if (fieldRef == null) - continue; - FieldDef fieldDef; - if (!ourFields.TryGetValue(new FieldReferenceAndDeclaringTypeKey(fieldRef), out fieldDef)) - continue; - - if (DotNetUtils.getArgIndex(methodDef.MethodDefinition, instructions[index++]) != 0) - continue; - - MethodReference methodRef; - var instr = instructions[index + 1]; - if (instr.OpCode.Code == Code.Ldvirtftn) { - if (!isThisOrDup(methodDef.MethodDefinition, instructions[index++])) - continue; - var ldvirtftn = instructions[index++]; - methodRef = ldvirtftn.Operand as MethodReference; - } - else { - var ldftn = instructions[index++]; - if (ldftn.OpCode.Code != Code.Ldftn) - continue; - methodRef = ldftn.Operand as MethodReference; - } - if (methodRef == null) - continue; - MethodDef handlerMethod; - if (!ourMethods.TryGetValue(new MethodReferenceAndDeclaringTypeKey(methodRef), out handlerMethod)) - continue; - - var newobj = instructions[index++]; - if (newobj.OpCode.Code != Code.Newobj) - continue; - if (!isEventHandlerCtor(newobj.Operand as MethodReference)) - continue; - - var call = instructions[index++]; - if (call.OpCode.Code != Code.Call && call.OpCode.Code != Code.Callvirt) - continue; - var addHandler = call.Operand as MethodReference; - if (addHandler == null) - continue; - if (!Utils.StartsWith(addHandler.Name, "add_", StringComparison.Ordinal)) - continue; - - var eventName = addHandler.Name.Substring(4); - if (!MemberRenameState.variableNameState.IsValidName(eventName)) - continue; - - newMethodNames[handlerMethod] = string.Format("{0}_{1}", fieldDef.NewName, eventName); - } - } - } - - void initTypeEventHandlers(Dictionary ourFields, Dictionary ourMethods) { - foreach (var methodDef in methods.getAll()) { - if (methodDef.MethodDefinition.Body == null) - continue; - if (methodDef.MethodDefinition.IsStatic) - continue; - var method = methodDef.MethodDefinition; - var instructions = method.Body.Instructions; - for (int i = 0; i < instructions.Count - 5; i++) { - // ldarg.0 - // ldarg.0 / dup - // ldarg.0 / dup - // ldvirtftn handler - // newobj event handler ctor - // call add_Xyz - - if (DotNetUtils.getArgIndex(method, instructions[i]) != 0) - continue; - int index = i + 1; - - if (!isThisOrDup(method, instructions[index++])) - continue; - MethodReference handler; - if (instructions[index].OpCode.Code == Code.Ldftn) { - handler = instructions[index++].Operand as MethodReference; - } - else { - if (!isThisOrDup(method, instructions[index++])) - continue; - var instr = instructions[index++]; - if (instr.OpCode.Code != Code.Ldvirtftn) - continue; - handler = instr.Operand as MethodReference; - } - if (handler == null) - continue; - MethodDef handlerDef; - if (!ourMethods.TryGetValue(new MethodReferenceAndDeclaringTypeKey(handler), out handlerDef)) - continue; - - var newobj = instructions[index++]; - if (newobj.OpCode.Code != Code.Newobj) - continue; - if (!isEventHandlerCtor(newobj.Operand as MethodReference)) - continue; - - var call = instructions[index++]; - if (call.OpCode.Code != Code.Call && call.OpCode.Code != Code.Callvirt) - continue; - var addMethod = call.Operand as MethodReference; - if (addMethod == null) - continue; - if (!Utils.StartsWith(addMethod.Name, "add_", StringComparison.Ordinal)) - continue; - - var eventName = addMethod.Name.Substring(4); - if (!MemberRenameState.variableNameState.IsValidName(eventName)) - continue; - - newMethodNames[handlerDef] = string.Format("{0}_{1}", NewName, eventName); - } - } - } - - static bool isThisOrDup(MethodReference method, Instruction instr) { - return DotNetUtils.getArgIndex(method, instr) == 0 || instr.OpCode.Code == Code.Dup; - } - - static bool isEventHandlerCtor(MethodReference method) { - if (method == null) - return false; - if (method.Name != ".ctor") - return false; - if (!DotNetUtils.isMethod(method, "System.Void", "(System.Object,System.IntPtr)")) - return false; - if (!isEventHandlerType(method.DeclaringType)) - return false; - return true; - } - - static bool isEventHandlerType(TypeReference type) { - return type.FullName.EndsWith("EventHandler", StringComparison.Ordinal); - } - - static MethodReference getOverrideMethod(MethodDefinition meth) { - if (meth == null || !meth.HasOverrides) - return null; - return meth.Overrides[0]; - } - - static string getRealName(string name) { - int index = name.LastIndexOf('.'); - if (index < 0) - return name; - return name.Substring(index + 1); - } - - static readonly Regex removeGenericsArityRegex = new Regex(@"`[0-9]+"); - static string getOverrideMethodNamePrefix(TypeReference owner) { - var name = owner.FullName.Replace('/', '.'); - name = removeGenericsArityRegex.Replace(name, ""); - return name + "."; - } - - static string getOverrideMethodName(TypeReference owner, string name) { - return getOverrideMethodNamePrefix(owner) + name; - } - - void prepareRenameProperties() { - var variableNameState = MemberRenameState.variableNameState; - - foreach (var propDef in properties.getSorted()) { - if (propDef.Renamed) - continue; - propDef.Renamed = true; - - bool isVirtual = propDef.isVirtual(); - string prefix = ""; - string baseName = propDef.OldName; - - string propName = null; - if (isVirtual) - getVirtualPropName(propDef, ref prefix, ref propName); - if (propName == null) - newPropertyNames.TryGetValue(propDef, out propName); - if (propName == null && !variableNameState.IsValidName(propDef.OldName)) - propName = variableNameState.getNewPropertyName(propDef.PropertyDefinition); - if (propName != null) { - baseName = propName; - propDef.NewName = prefix + baseName; - } - - renameSpecialMethod(propDef.PropertyDefinition.GetMethod, prefix + "get_" + baseName); - renameSpecialMethod(propDef.PropertyDefinition.SetMethod, prefix + "set_" + baseName, "value"); - - if (isVirtual) - MemberRenameState.add(propDef); - } - } - - void getVirtualPropName(PropertyDef propDef, ref string prefix, ref string propName) { - PropertyRef sameDef; - var overrideMethod = propDef.getOverrideMethod(); - if (overrideMethod != null && (sameDef = defFinder.findProp(overrideMethod)) != null) { - prefix = getOverrideMethodNamePrefix(sameDef.Owner.TypeDefinition); - propName = sameDef.NewName; - return; - } - - var method = getOverrideMethod(propDef.PropertyDefinition.GetMethod ?? propDef.PropertyDefinition.SetMethod); - if (method != null) { - var realName = getRealName(method.Name); - // Only use the name if the method is not in one of the loaded files, since the - // name shouldn't be obfuscated. - if (Regex.IsMatch(realName, @"^[sg]et_.") && defFinder.findProp(method) == null) { - prefix = getOverrideMethodNamePrefix(method.DeclaringType); - propName = realName.Substring(4); - return; - } - } - - sameDef = MemberRenameState.get(propDef); - if (sameDef != null) { - prefix = ""; - propName = sameDef.NewName; - return; - } - } - - void prepareRenameEvents() { - var variableNameState = MemberRenameState.variableNameState; - - foreach (var eventDef in events.getSorted()) { - if (eventDef.Renamed) - continue; - eventDef.Renamed = true; - - bool isVirtual = eventDef.isVirtual(); - string prefix = ""; - string baseName = eventDef.OldName; - - string propName = null; - if (isVirtual) - getVirtualEventName(eventDef, ref prefix, ref propName); - if (propName == null && !variableNameState.IsValidName(eventDef.OldName)) - propName = variableNameState.getNewEventName(eventDef.EventDefinition); - if (propName != null) { - baseName = propName; - eventDef.NewName = prefix + baseName; - } - - renameSpecialMethod(eventDef.EventDefinition.AddMethod, prefix + "add_" + baseName, "value"); - renameSpecialMethod(eventDef.EventDefinition.RemoveMethod, prefix + "remove_" + baseName, "value"); - renameSpecialMethod(eventDef.EventDefinition.InvokeMethod, prefix + "raise_" + baseName); - - if (isVirtual) - MemberRenameState.add(eventDef); - } - } - - void getVirtualEventName(EventDef eventDef, ref string prefix, ref string propName) { - EventRef sameDef; - var overrideMethod = eventDef.getOverrideMethod(); - if (overrideMethod != null && (sameDef = defFinder.findEvent(overrideMethod)) != null) { - prefix = getOverrideMethodNamePrefix(sameDef.Owner.TypeDefinition); - propName = sameDef.NewName; - return; - } - - var method = getOverrideMethod(eventDef.EventDefinition.AddMethod ?? eventDef.EventDefinition.RemoveMethod); - if (method != null) { - var realName = getRealName(method.Name); - // Only use the name if the method is not in one of the loaded files, since the - // name shouldn't be obfuscated. - if (Regex.IsMatch(realName, @"^(add|remove)_.") && defFinder.findEvent(method) == null) { - prefix = getOverrideMethodNamePrefix(method.DeclaringType); - propName = realName.Substring(realName.IndexOf('_') + 1); - return; - } - } - - sameDef = MemberRenameState.get(eventDef); - if (sameDef != null) { - prefix = ""; - propName = sameDef.NewName; - return; - } - } - - void renameSpecialMethod(MethodDefinition methodDefinition, string newName, string newArgName = null) { - if (methodDefinition == null) - return; - - var methodDef = find(methodDefinition); - if (methodDef == null) - throw new ApplicationException("Could not find the event/prop method"); - - renameMethod(methodDef, newName); - - if (newArgName != null && methodDef.ParamDefs.Count > 0) { - var arg = methodDef.ParamDefs[methodDef.ParamDefs.Count - 1]; - if (!MemberRenameState.variableNameState.IsValidName(arg.OldName)) { - arg.NewName = newArgName; - arg.Renamed = true; - } - } - } - - void prepareRenameMethods() { - foreach (var methodDef in methods.getSorted()) - renameMethod(methodDef); - } - - void renameMethod(MethodDef methodDef, string suggestedName = null) { - if (methodDef.Renamed) - return; - methodDef.Renamed = true; - - bool canRenameMethodName = true; - if (suggestedName == null) - newMethodNames.TryGetValue(methodDef, out suggestedName); - - if (IsDelegate) { - switch (methodDef.MethodDefinition.Name) { - case "BeginInvoke": - case "EndInvoke": - case "Invoke": - canRenameMethodName = false; - break; - } - } - - var variableNameState = MemberRenameState.variableNameState; - - if (canRenameMethodName) { - var nameCreator = getMethodNameCreator(methodDef, suggestedName); - if (!methodDef.MethodDefinition.IsRuntimeSpecialName && !variableNameState.IsValidName(methodDef.OldName)) { - bool useNameCreator = methodDef.isVirtual() || methodDef.Property != null || methodDef.Event != null; - if (useNameCreator) - methodDef.NewName = nameCreator.newName(); - else - methodDef.NewName = variableNameState.getNewMethodName(methodDef.OldName, nameCreator); - } - } - - if (methodDef.ParamDefs.Count > 0) { - if (isEventHandler(methodDef)) { - methodDef.ParamDefs[0].NewName = "sender"; - methodDef.ParamDefs[0].Renamed = true; - methodDef.ParamDefs[1].NewName = "e"; - methodDef.ParamDefs[1].Renamed = true; - } - else { - var newVariableNameState = variableNameState.clone(); - foreach (var paramDef in methodDef.ParamDefs) { - if (!newVariableNameState.IsValidName(paramDef.OldName)) { - paramDef.NewName = newVariableNameState.getNewParamName(paramDef.OldName, paramDef.ParameterDefinition); - paramDef.Renamed = true; - } - } - } - } - - prepareRenameGenericParams(methodDef.GenericParams, variableNameState.IsValidName, methodDef.Owner == null ? null : methodDef.Owner.genericParams); - - if (methodDef.isVirtual()) - MemberRenameState.add(methodDef); - } - - static bool isEventHandler(MethodDef methodDef) { - if (methodDef.MethodDefinition.Parameters.Count != 2) - return false; - if (methodDef.MethodDefinition.MethodReturnType.ReturnType.FullName != "System.Void") - return false; - if (methodDef.MethodDefinition.Parameters[0].ParameterType.FullName != "System.Object") - return false; - if (!methodDef.MethodDefinition.Parameters[1].ParameterType.FullName.Contains("EventArgs")) - return false; - return true; - } - - string getPinvokeName(MethodDef methodDef) { - var entryPoint = methodDef.MethodDefinition.PInvokeInfo.EntryPoint; - if (Regex.IsMatch(entryPoint, @"^#\d+$")) - entryPoint = DotNetUtils.getDllName(methodDef.MethodDefinition.PInvokeInfo.Module.Name) + "_" + entryPoint.Substring(1); - return entryPoint; - } - - INameCreator getMethodNameCreator(MethodDef methodDef, string suggestedName) { - var variableNameState = MemberRenameState.variableNameState; - INameCreator nameCreator = null; - string newName = null; - - if (methodDef.MethodDefinition.PInvokeInfo != null) - newName = getPinvokeName(methodDef); - else if (methodDef.MethodDefinition.IsStatic) - nameCreator = variableNameState.staticMethodNameCreator; - else if (methodDef.isVirtual()) { - MethodRef otherMethodRef; - if ((otherMethodRef = MemberRenameState.get(methodDef)) != null) - newName = otherMethodRef.NewName; - else if (methodDef.MethodDefinition.HasOverrides) { - var overrideMethod = methodDef.MethodDefinition.Overrides[0]; - var otherMethodDef = defFinder.findMethod(overrideMethod); - if (otherMethodDef != null) - newName = getOverrideMethodName(overrideMethod.DeclaringType, otherMethodDef.NewName); - else - newName = getOverrideMethodName(overrideMethod.DeclaringType, overrideMethod.Name); - } - else - nameCreator = variableNameState.virtualMethodNameCreator; - } - else - nameCreator = variableNameState.instanceMethodNameCreator; - - if (newName == null) - newName = suggestedName; - if (newName != null) { - if (methodDef.isVirtual()) - nameCreator = new OneNameCreator(newName); // It must have this name - else - nameCreator = new NameCreator2(newName); - } - - return nameCreator; - } - } -} diff --git a/de4dot.code/old_renamer/MemberRenameState.cs b/de4dot.code/old_renamer/MemberRenameState.cs deleted file mode 100644 index 4d3bee18..00000000 --- a/de4dot.code/old_renamer/MemberRenameState.cs +++ /dev/null @@ -1,100 +0,0 @@ -/* - Copyright (C) 2011 de4dot@gmail.com - - This file is part of de4dot. - - de4dot is free software: you can redistribute it and/or modify - it under the terms of the GNU General Public License as published by - the Free Software Foundation, either version 3 of the License, or - (at your option) any later version. - - de4dot is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU General Public License for more details. - - You should have received a copy of the GNU General Public License - along with de4dot. If not, see . -*/ - -using System.Collections.Generic; -using de4dot.blocks; - -namespace de4dot.old_renamer { - class MemberRenameState { - public VariableNameState variableNameState; - public Dictionary properties = new Dictionary(); - public Dictionary events = new Dictionary(); - public Dictionary methods = new Dictionary(); - - public MemberRenameState() - : this(null) { - } - - public MemberRenameState(VariableNameState variableNameState) { - this.variableNameState = variableNameState; - } - - // Used to merge all renamed interface props/events/methods - public void mergeRenamed(MemberRenameState other) { - foreach (var key in other.properties.Keys) - add(properties, key, other.properties[key]); - foreach (var key in other.events.Keys) - add(events, key, other.events[key]); - foreach (var key in other.methods.Keys) - add(methods, key, other.methods[key]); - } - - public PropertyRef get(PropertyRef p) { - return get(properties, new PropertyReferenceKey(p.PropertyReference)); - } - - public EventRef get(EventRef e) { - return get(events, new EventReferenceKey(e.EventReference)); - } - - public MethodRef get(MethodRef m) { - return get(methods, new MethodReferenceKey(m.MethodReference)); - } - - // Returns null if not found - D get(Dictionary dict, K key) where D : class { - D value; - if (dict.TryGetValue(key, out value)) - return value; - return null; - } - - public void add(PropertyRef p) { - add(properties, new PropertyReferenceKey(p.PropertyReference), p); - } - - public void add(EventRef e) { - add(events, new EventReferenceKey(e.EventReference), e); - } - - public void add(MethodRef m) { - add(methods, new MethodReferenceKey(m.MethodReference), m); - } - - void add(Dictionary dict, K key, D d) { - dict[key] = d; - } - - public MemberRenameState clone() { - var rv = new MemberRenameState(variableNameState == null ? null : variableNameState.clone()); - rv.properties = new Dictionary(properties); - rv.events = new Dictionary(events); - rv.methods = new Dictionary(methods); - return rv; - } - - public MemberRenameState cloneVariables() { - var rv = new MemberRenameState(variableNameState == null ? null : variableNameState.clone()); - rv.properties = properties; - rv.events = events; - rv.methods = methods; - return rv; - } - } -} diff --git a/de4dot.code/old_renamer/Misc.cs b/de4dot.code/old_renamer/Misc.cs deleted file mode 100644 index 2f80e940..00000000 --- a/de4dot.code/old_renamer/Misc.cs +++ /dev/null @@ -1,231 +0,0 @@ -/* - Copyright (C) 2011 de4dot@gmail.com - - This file is part of de4dot. - - de4dot is free software: you can redistribute it and/or modify - it under the terms of the GNU General Public License as published by - the Free Software Foundation, either version 3 of the License, or - (at your option) any later version. - - de4dot is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU General Public License for more details. - - You should have received a copy of the GNU General Public License - along with de4dot. If not, see . -*/ - -using System.Collections.Generic; -using Mono.Cecil; -using de4dot.blocks; - -namespace de4dot.old_renamer { - interface IResolver { - TypeDef resolve(TypeReference typeReference); - MethodDef resolve(MethodReference methodReference); - FieldDef resolve(FieldReference fieldReference); - } - - interface IDefFinder { - MethodDef findMethod(MethodReference methodReference); - PropertyDef findProp(MethodReference methodReference); - EventDef findEvent(MethodReference methodReference); - } - - interface RefDict where TRef : Ref where TMRef : MemberReference { - IEnumerable getAll(); - IEnumerable getSorted(); - TRef find(TMRef tmref); - void add(TRef tref); - void onTypesRenamed(); - } - - class TypeDefDict : RefDict { - Dictionary tokenToTypeDef = new Dictionary(); - Dictionary typeRefToDef = new Dictionary(); - - public IEnumerable getAll() { - return tokenToTypeDef.Values; - } - - public IEnumerable getSorted() { - var list = new List(getAll()); - list.Sort((a, b) => { - if (a.Index < b.Index) return -1; - if (a.Index > b.Index) return 1; - return 0; - }); - return list; - } - - public TypeDef find(TypeReference typeReference) { - TypeDef typeDef; - if (tokenToTypeDef.TryGetValue(new ScopeAndTokenKey(typeReference), out typeDef)) - return typeDef; - - typeRefToDef.TryGetValue(new TypeReferenceKey(typeReference), out typeDef); - return typeDef; - } - - public void add(TypeDef typeDef) { - tokenToTypeDef[new ScopeAndTokenKey(typeDef.TypeDefinition)] = typeDef; - typeRefToDef[new TypeReferenceKey(typeDef.TypeDefinition)] = typeDef; - } - - public void onTypesRenamed() { - var all = new List(typeRefToDef.Values); - typeRefToDef.Clear(); - foreach (var typeDef in all) - typeRefToDef[new TypeReferenceKey(typeDef.TypeDefinition)] = typeDef; - } - } - - class FieldDefDict : RefDict { - Dictionary tokenToFieldDef = new Dictionary(); - Dictionary fieldRefToDef = new Dictionary(); - - public IEnumerable getAll() { - return tokenToFieldDef.Values; - } - - public IEnumerable getSorted() { - var list = new List(getAll()); - list.Sort((a, b) => { - if (a.Index < b.Index) return -1; - if (a.Index > b.Index) return 1; - return 0; - }); - return list; - } - - public FieldDef find(FieldReference fieldReference) { - FieldDef fieldDef; - if (tokenToFieldDef.TryGetValue(new ScopeAndTokenKey(fieldReference), out fieldDef)) - return fieldDef; - - fieldRefToDef.TryGetValue(new FieldReferenceKey(fieldReference), out fieldDef); - return fieldDef; - } - - public void add(FieldDef fieldDef) { - tokenToFieldDef[new ScopeAndTokenKey(fieldDef.FieldDefinition)] = fieldDef; - fieldRefToDef[new FieldReferenceKey(fieldDef.FieldDefinition)] = fieldDef; - } - - public void onTypesRenamed() { - var all = new List(fieldRefToDef.Values); - fieldRefToDef.Clear(); - foreach (var fieldDef in all) - fieldRefToDef[new FieldReferenceKey(fieldDef.FieldDefinition)] = fieldDef; - } - } - - class MethodDefDict : RefDict { - Dictionary tokenToMethodDef = new Dictionary(); - Dictionary methodRefToDef = new Dictionary(); - - public IEnumerable getAll() { - return tokenToMethodDef.Values; - } - - public IEnumerable getSorted() { - var list = new List(getAll()); - list.Sort((a, b) => { - if (a.Index < b.Index) return -1; - if (a.Index > b.Index) return 1; - return 0; - }); - return list; - } - - public MethodDef find(MethodReference methodReference) { - MethodDef methodDef; - if (tokenToMethodDef.TryGetValue(new ScopeAndTokenKey(methodReference), out methodDef)) - return methodDef; - - methodRefToDef.TryGetValue(new MethodReferenceKey(methodReference), out methodDef); - return methodDef; - } - - public void add(MethodDef methodDef) { - tokenToMethodDef[new ScopeAndTokenKey(methodDef.MethodDefinition)] = methodDef; - methodRefToDef[new MethodReferenceKey(methodDef.MethodDefinition)] = methodDef; - } - - public void onTypesRenamed() { - var all = new List(methodRefToDef.Values); - methodRefToDef.Clear(); - foreach (var methodDef in all) - methodRefToDef[new MethodReferenceKey(methodDef.MethodDefinition)] = methodDef; - } - } - - class PropertyDefDict : RefDict { - Dictionary tokenToPropDef = new Dictionary(); - - public IEnumerable getAll() { - return tokenToPropDef.Values; - } - - public IEnumerable getSorted() { - var list = new List(getAll()); - list.Sort((a, b) => { - if (a.Index < b.Index) return -1; - if (a.Index > b.Index) return 1; - return 0; - }); - return list; - } - - public PropertyDef find(PropertyReference propertyReference) { - PropertyDef propDef; - tokenToPropDef.TryGetValue(new ScopeAndTokenKey(propertyReference), out propDef); - return propDef; - } - - public void add(PropertyDef propDef) { - tokenToPropDef[new ScopeAndTokenKey(propDef.PropertyDefinition)] = propDef; - } - - public void onTypesRenamed() { - } - } - - class EventDefDict : RefDict { - Dictionary tokenToEventDef = new Dictionary(); - - public IEnumerable getAll() { - return tokenToEventDef.Values; - } - - public IEnumerable getSorted() { - var list = new List(getAll()); - list.Sort((a, b) => { - if (a.Index < b.Index) return -1; - if (a.Index > b.Index) return 1; - return 0; - }); - return list; - } - - public EventDef find(EventReference eventReference) { - EventDef eventDef; - tokenToEventDef.TryGetValue(new ScopeAndTokenKey(eventReference), out eventDef); - return eventDef; - } - - public void add(EventDef eventDef) { - tokenToEventDef[new ScopeAndTokenKey(eventDef.EventDefinition)] = eventDef; - } - - public void onTypesRenamed() { - } - } - - class Renamed { - public string OldName { get; set; } - public string NewName { get; set; } - } -} diff --git a/de4dot.code/old_renamer/Module.cs b/de4dot.code/old_renamer/Module.cs deleted file mode 100644 index 5062530c..00000000 --- a/de4dot.code/old_renamer/Module.cs +++ /dev/null @@ -1,355 +0,0 @@ -/* - Copyright (C) 2011 de4dot@gmail.com - - This file is part of de4dot. - - de4dot is free software: you can redistribute it and/or modify - it under the terms of the GNU General Public License as published by - the Free Software Foundation, either version 3 of the License, or - (at your option) any later version. - - de4dot is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU General Public License for more details. - - You should have received a copy of the GNU General Public License - along with de4dot. If not, see . -*/ - -using System; -using System.Collections.Generic; -using Mono.Cecil; -using Mono.Cecil.Cil; -using de4dot.deobfuscators; - -namespace de4dot.old_renamer { - class Module : IResolver { - IObfuscatedFile obfuscatedFile; - MemberRefFinder memberRefFinder; - TypeDefDict allTypes = new TypeDefDict(); - IList> typeRefsToRename = new List>(); - IList> methodRefsToRename = new List>(); - IList> fieldRefsToRename = new List>(); - List allMethods; - - public Func IsValidName { - get { return null; } - } - - class RefToDef where R : MemberReference where D : R { - public R reference; - public D definition; - public RefToDef(R reference, D definition) { - this.reference = reference; - this.definition = definition; - } - } - - public string Filename { - get { return obfuscatedFile.Filename; } - } - - public ModuleDefinition ModuleDefinition { - get { return obfuscatedFile.ModuleDefinition; } - } - - public string Pathname { - get { return ModuleDefinition.FullyQualifiedName; } - } - - public Module(IObfuscatedFile obfuscatedFile) { - this.obfuscatedFile = obfuscatedFile; - } - - public IEnumerable getAllTypes() { - return allTypes.getAll(); - } - - IEnumerable getRenamedTypeNames() { - foreach (var typeDef in allTypes.getAll()) { - if (typeDef.OldFullName != typeDef.TypeDefinition.FullName) { - yield return new Renamed { - OldName = typeDef.OldFullName, - NewName = typeDef.TypeDefinition.FullName - }; - } - } - } - - public void onBeforeRenamingTypeDefinitions() { - if (obfuscatedFile.RemoveNamespaceWithOneType) - removeOneClassNamespaces(); - } - - void removeOneClassNamespaces() { - var nsToTypes = new Dictionary>(StringComparer.Ordinal); - - foreach (var typeDef in allTypes.getAll()) { - List list; - var ns = typeDef.TypeDefinition.Namespace; - if (string.IsNullOrEmpty(ns)) - continue; - if (IsValidName(ns)) - continue; - if (!nsToTypes.TryGetValue(ns, out list)) - nsToTypes[ns] = list = new List(); - list.Add(typeDef); - } - - var sortedNamespaces = new List>(nsToTypes.Values); - sortedNamespaces.Sort((a, b) => { - return string.CompareOrdinal(a[0].TypeDefinition.Namespace, b[0].TypeDefinition.Namespace); - }); - foreach (var list in sortedNamespaces) { - const int maxClasses = 1; - if (list.Count != maxClasses) - continue; - var ns = list[0].TypeDefinition.Namespace; - Log.v("Removing namespace: {0}", ns); - foreach (var type in list) - type.NewNamespace = ""; - } - } - - static string renameResourceString(string s, string oldTypeName, string newTypeName) { - if (!Utils.StartsWith(s, oldTypeName, StringComparison.Ordinal)) - return s; - if (s.Length == oldTypeName.Length) - return newTypeName; - // s.Length > oldTypeName.Length - if (s[oldTypeName.Length] != '.') - return s; - if (!s.EndsWith(".resources", StringComparison.Ordinal)) - return s; - return newTypeName + s.Substring(oldTypeName.Length); - } - - public void renameResources() { - var renamedTypes = new List(getRenamedTypeNames()); - - // Rename the longest names first. Otherwise eg. b.g.resources could be renamed - // Class0.g.resources instead of Class1.resources when b.g was renamed Class1. - renamedTypes.Sort((a, b) => { - if (a.OldName.Length > b.OldName.Length) return -1; - if (a.OldName.Length < b.OldName.Length) return 1; - return 0; - }); - - renameResourceNamesInCode(renamedTypes); - renameResources(renamedTypes); - } - - void renameResourceNamesInCode(IEnumerable renamedTypes) { - // This is needed to speed up this method - var oldToNewTypeName = new Dictionary(StringComparer.Ordinal); - foreach (var renamed in renamedTypes) - oldToNewTypeName[renamed.OldName] = renamed.NewName; - - List validResourceNames = new List(); - if (ModuleDefinition.Resources != null) { - foreach (var resource in ModuleDefinition.Resources) { - var name = resource.Name; - if (name.EndsWith(".resources", StringComparison.Ordinal)) - validResourceNames.Add(name); - } - } - - foreach (var method in allMethods) { - if (!method.HasBody) - continue; - foreach (var instr in method.Body.Instructions) { - if (instr.OpCode != OpCodes.Ldstr) - continue; - var s = (string)instr.Operand; - if (string.IsNullOrEmpty(s)) - continue; // Ignore emtpy strings since we'll get lots of false warnings - - string newName = null; - string oldName = null; - if (oldToNewTypeName.ContainsKey(s)) { - oldName = s; - newName = oldToNewTypeName[s]; - } - else if (s.EndsWith(".resources", StringComparison.Ordinal)) { - // This should rarely, if ever, execute... - foreach (var renamed in renamedTypes) { // Slow loop - var newName2 = renameResourceString(s, renamed.OldName, renamed.NewName); - if (newName2 != s) { - newName = newName2; - oldName = renamed.OldName; - break; - } - } - } - if (newName == null || string.IsNullOrEmpty(oldName)) - continue; - - bool isValid = false; - foreach (var validName in validResourceNames) { - if (Utils.StartsWith(validName, oldName, StringComparison.Ordinal)) { - isValid = true; - break; - } - } - if (!isValid) - continue; - - if (s == "" || !obfuscatedFile.RenameResourcesInCode) - Log.v("Possible resource name in code: '{0}' => '{1}' in method {2}", s, newName, method); - else { - instr.Operand = newName; - Log.v("Renamed resource string in code: '{0}' => '{1}' ({2})", s, newName, method); - break; - } - } - } - } - - void renameResources(IEnumerable renamedTypes) { - if (ModuleDefinition.Resources == null) - return; - foreach (var resource in ModuleDefinition.Resources) { - var s = resource.Name; - foreach (var renamed in renamedTypes) { - var newName = renameResourceString(s, renamed.OldName, renamed.NewName); - if (newName != s) { - resource.Name = newName; - Log.v("Renamed resource in resources: {0} => {1}", s, newName); - break; - } - } - } - } - - public void findAllMemberReferences(ref int typeIndex) { - memberRefFinder = new MemberRefFinder(); - memberRefFinder.findAll(ModuleDefinition, ModuleDefinition.Types); - allMethods = new List(memberRefFinder.methodDefinitions.Keys); - - var allTypesList = new List(); - foreach (var type in new List(memberRefFinder.typeDefinitions.Keys)) { - memberRefFinder.removeTypeDefinition(type); - var typeDef = new TypeDef(type, this, typeIndex++); - allTypes.add(typeDef); - allTypesList.Add(typeDef); - - typeDef.addMembers(); - - foreach (var ev in type.Events) - memberRefFinder.removeEventDefinition(ev); - foreach (var field in type.Fields) - memberRefFinder.removeFieldDefinition(field); - foreach (var method in type.Methods) - memberRefFinder.removeMethodDefinition(method); - foreach (var property in type.Properties) - memberRefFinder.removePropertyDefinition(property); - } - - // Add all nested types to the correct TypeDef's types list - var allTypesCopy = new List(allTypesList); - var typeToIndex = new Dictionary(); - for (int i = 0; i < allTypesList.Count; i++) - typeToIndex[allTypesList[i].TypeDefinition] = i; - foreach (var typeDef in allTypesList) { - if (typeDef.TypeDefinition.NestedTypes == null) - continue; - foreach (var nestedTypeDefinition in typeDef.TypeDefinition.NestedTypes) { - int index = typeToIndex[nestedTypeDefinition]; - var nestedTypeDef = allTypesCopy[index]; - allTypesCopy[index] = null; - if (nestedTypeDef == null) // Impossible - throw new ApplicationException("Nested type belongs to two or more types"); - typeDef.add(nestedTypeDef); - nestedTypeDef.NestingType = typeDef; - } - } - - // Make sure we got all definitions - if (memberRefFinder.typeDefinitions.Count > 0) - throw new ApplicationException("There are types left"); - if (memberRefFinder.eventDefinitions.Count > 0) - throw new ApplicationException("There are events left"); - if (memberRefFinder.fieldDefinitions.Count > 0) - throw new ApplicationException("There are fields left"); - if (memberRefFinder.methodDefinitions.Count > 0) - throw new ApplicationException("There are methods left"); - if (memberRefFinder.propertyDefinitions.Count > 0) - throw new ApplicationException("There are properties left"); - } - - public void resolveAllRefs(IResolver resolver) { - foreach (var typeRef in memberRefFinder.typeReferences.Keys) { - var typeDef = resolver.resolve(typeRef); - if (typeDef != null) - typeRefsToRename.Add(new RefToDef(typeRef, typeDef.TypeDefinition)); - } - - foreach (var methodRef in memberRefFinder.methodReferences.Keys) { - var methodDef = resolver.resolve(methodRef); - if (methodDef != null) - methodRefsToRename.Add(new RefToDef(methodRef, methodDef.MethodDefinition)); - } - - foreach (var fieldRef in memberRefFinder.fieldReferences.Keys) { - var fieldDef = resolver.resolve(fieldRef); - if (fieldDef != null) - fieldRefsToRename.Add(new RefToDef(fieldRef, fieldDef.FieldDefinition)); - } - } - - public void renameTypeReferences() { - foreach (var refToDef in typeRefsToRename) { - refToDef.reference.Name = refToDef.definition.Name; - refToDef.reference.Namespace = refToDef.definition.Namespace; - } - } - - public void renameMemberReferences() { - foreach (var refToDef in methodRefsToRename) - refToDef.reference.Name = refToDef.definition.Name; - foreach (var refToDef in fieldRefsToRename) - refToDef.reference.Name = refToDef.definition.Name; - } - - public void onTypesRenamed() { - rebuildAllTypesDict(); - } - - void rebuildAllTypesDict() { - var newAllTypes = new TypeDefDict(); - foreach (var typeDef in allTypes.getAll()) { - typeDef.onTypesRenamed(); - newAllTypes.add(typeDef); - } - allTypes = newAllTypes; - } - - static TypeReference getNonGenericTypeReference(TypeReference typeReference) { - if (typeReference == null) - return null; - if (!typeReference.IsGenericInstance) - return typeReference; - var type = (GenericInstanceType)typeReference; - return type.ElementType; - } - - public TypeDef resolve(TypeReference typeReference) { - return this.allTypes.find(getNonGenericTypeReference(typeReference)); - } - - public MethodDef resolve(MethodReference methodReference) { - var typeDef = this.allTypes.find(getNonGenericTypeReference(methodReference.DeclaringType)); - if (typeDef == null) - return null; - return typeDef.find(methodReference); - } - - public FieldDef resolve(FieldReference fieldReference) { - var typeDef = this.allTypes.find(getNonGenericTypeReference(fieldReference.DeclaringType)); - if (typeDef == null) - return null; - return typeDef.find(fieldReference); - } - } -} diff --git a/de4dot.code/old_renamer/NameCreators.cs b/de4dot.code/old_renamer/NameCreators.cs deleted file mode 100644 index 742e2d7d..00000000 --- a/de4dot.code/old_renamer/NameCreators.cs +++ /dev/null @@ -1,230 +0,0 @@ -/* - Copyright (C) 2011 de4dot@gmail.com - - This file is part of de4dot. - - de4dot is free software: you can redistribute it and/or modify - it under the terms of the GNU General Public License as published by - the Free Software Foundation, either version 3 of the License, or - (at your option) any later version. - - de4dot is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU General Public License for more details. - - You should have received a copy of the GNU General Public License - along with de4dot. If not, see . -*/ - -using System; -using System.Collections.Generic; -using Mono.Cecil; -using de4dot.blocks; - -namespace de4dot.old_renamer { - interface INameCreator { - INameCreator clone(); - string newName(); - } - - class OneNameCreator : INameCreator { - string name; - - public OneNameCreator(string name) { - this.name = name; - } - - public INameCreator clone() { - return this; - } - - public string newName() { - return name; - } - } - - class GlobalNameCreator : INameCreator { - INameCreator other; - - public GlobalNameCreator(INameCreator other) { - this.other = other; - } - - public INameCreator clone() { - return this; - } - - public string newName() { - return other.newName(); - } - } - - class GenericParamNameCreator : INameCreator { - static string[] names = new string[] { "T", "U", "V", "W", "X", "Y", "Z" }; - int index = 0; - - public string newName() { - if (index < names.Length) - return names[index++]; - return string.Format("T{0}", index++); - } - - public INameCreator clone() { - var rv = new GenericParamNameCreator(); - rv.index = index; - return rv; - } - } - - class NameCreator : INameCreator { - string prefix; - int num; - - public NameCreator(string prefix, int num = 0) { - this.prefix = prefix; - this.num = num; - } - - public INameCreator clone() { - return new NameCreator(prefix, num); - } - - public string newName() { - return prefix + num++; - } - } - - // Like NameCreator but don't add the counter the first time - class NameCreator2 : INameCreator { - string prefix; - int num; - const string separator = "_"; - - public NameCreator2(string prefix, int num = 0) { - this.prefix = prefix; - this.num = num; - } - - public INameCreator clone() { - return new NameCreator2(prefix, num); - } - - public string newName() { - string rv; - if (num == 0) - rv = prefix; - else - rv = prefix + separator + num; - num++; - return rv; - } - } - - interface ITypeNameCreator { - string newName(TypeDefinition typeDefinition, string newBaseTypeName = null); - } - - class NameInfos { - IList nameInfos = new List(); - - class NameInfo { - public string name; - public INameCreator nameCreator; - public NameInfo(string name, INameCreator nameCreator) { - this.name = name; - this.nameCreator = nameCreator; - } - } - - public void add(string name, INameCreator nameCreator) { - nameInfos.Add(new NameInfo(name, nameCreator)); - } - - public INameCreator find(string typeName) { - foreach (var nameInfo in nameInfos) { - if (typeName.Contains(nameInfo.name)) - return nameInfo.nameCreator; - } - - return null; - } - } - - class TypeNameCreator : ITypeNameCreator { - CurrentNames currentNames; - INameCreator createUnknownTypeName; - INameCreator createEnumName; - INameCreator createStructName; - INameCreator createDelegateName; - INameCreator createClassName; - INameCreator createInterfaceName; - NameInfos nameInfos = new NameInfos(); - - public TypeNameCreator(CurrentNames currentNames) { - this.currentNames = currentNames; - createUnknownTypeName = createNameCreator("Type"); - createEnumName = createNameCreator("Enum"); - createStructName = createNameCreator("Struct"); - createDelegateName = createNameCreator("Delegate"); - createClassName = createNameCreator("Class"); - createInterfaceName = createNameCreator("Interface"); - - var names = new string[] { - "Exception", - "EventArgs", - "Attribute", - "Form", - "Dialog", - "Control", - }; - foreach (var name in names) - nameInfos.add(name, createNameCreator(name)); - } - - protected virtual INameCreator createNameCreator(string prefix) { - return new NameCreator(prefix); - } - - public string newName(TypeDefinition typeDefinition, string newBaseTypeName = null) { - var nameCreator = getNameCreator(typeDefinition, newBaseTypeName); - return currentNames.newName(typeDefinition.Name, nameCreator); - } - - INameCreator getNameCreator(TypeDefinition typeDefinition, string newBaseTypeName) { - var nameCreator = createUnknownTypeName; - if (typeDefinition.IsEnum) - nameCreator = createEnumName; - else if (typeDefinition.IsValueType) - nameCreator = createStructName; - else if (typeDefinition.IsClass) { - if (typeDefinition.BaseType != null) { - if (MemberReferenceHelper.verifyType(typeDefinition.BaseType, "mscorlib", "System.Delegate")) - nameCreator = createDelegateName; - else if (MemberReferenceHelper.verifyType(typeDefinition.BaseType, "mscorlib", "System.MulticastDelegate")) - nameCreator = createDelegateName; - else { - nameCreator = nameInfos.find(newBaseTypeName ?? typeDefinition.BaseType.Name); - if (nameCreator == null) - nameCreator = createClassName; - } - } - else - nameCreator = createClassName; - } - else if (typeDefinition.IsInterface) - nameCreator = createInterfaceName; - return nameCreator; - } - } - - class GlobalTypeNameCreator : TypeNameCreator { - public GlobalTypeNameCreator(CurrentNames currentNames) - : base(currentNames) { - } - - protected override INameCreator createNameCreator(string prefix) { - return new GlobalNameCreator(base.createNameCreator("G" + prefix)); - } - } -} diff --git a/de4dot.code/old_renamer/RefExpander.cs b/de4dot.code/old_renamer/RefExpander.cs deleted file mode 100644 index d9ccd408..00000000 --- a/de4dot.code/old_renamer/RefExpander.cs +++ /dev/null @@ -1,104 +0,0 @@ -/* - Copyright (C) 2011 de4dot@gmail.com - - This file is part of de4dot. - - de4dot is free software: you can redistribute it and/or modify - it under the terms of the GNU General Public License as published by - the Free Software Foundation, either version 3 of the License, or - (at your option) any later version. - - de4dot is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU General Public License for more details. - - You should have received a copy of the GNU General Public License - along with de4dot. If not, see . -*/ - -using Mono.Cecil; -using de4dot.blocks; - -namespace de4dot.old_renamer { - abstract class RefExpander { - protected GenericInstanceType git; - bool modified = false; - - public RefExpander(GenericInstanceType git) { - this.git = git; - } - - protected void checkModified(object a, object b) { - if (!ReferenceEquals(a, b)) - modified = true; - } - - protected MethodReference expandMethodReference(MethodReference methodReference) { - var mr = MethodReferenceInstance.make(methodReference, git); - checkModified(methodReference, mr); - return mr; - } - - protected EventReference expandEventReference(EventReference eventReference) { - var er = EventReferenceInstance.make(eventReference, git); - checkModified(eventReference, er); - return er; - } - - protected PropertyReference expandPropertyReference(PropertyReference propertyReference) { - var pr = PropertyReferenceInstance.make(propertyReference, git); - checkModified(propertyReference, pr); - return pr; - } - - protected T getResult(T orig, T expanded) { - return modified ? expanded : orig; - } - } - - class GenericMethodRefExpander : RefExpander { - MethodRef methodRef; - - public GenericMethodRefExpander(MethodRef methodRef, GenericInstanceType git) - : base(git) { - this.methodRef = methodRef; - } - - public MethodRef expand() { - var newMethodRef = new MethodRef(expandMethodReference(methodRef.MethodReference), methodRef.Owner, methodRef.Index); - newMethodRef.NewName = methodRef.NewName; - return getResult(methodRef, newMethodRef); - } - } - - class GenericEventRefExpander : RefExpander { - EventRef eventRef; - - public GenericEventRefExpander(EventRef eventRef, GenericInstanceType git) - : base(git) { - this.eventRef = eventRef; - } - - public EventRef expand() { - var newEventRef = new EventRef(expandEventReference(eventRef.EventReference), eventRef.Owner, eventRef.Index); - newEventRef.NewName = eventRef.NewName; - return getResult(eventRef, newEventRef); - } - } - - class GenericPropertyRefExpander : RefExpander { - PropertyRef propRef; - - public GenericPropertyRefExpander(PropertyRef propRef, GenericInstanceType git) - : base(git) { - this.propRef = propRef; - } - - public PropertyRef expand() { - var newPropRef = new PropertyRef(expandPropertyReference(propRef.PropertyReference), propRef.Owner, propRef.Index); - newPropRef.NewName = propRef.NewName; - return getResult(propRef, newPropRef); - } - } -} diff --git a/de4dot.code/old_renamer/TypeNameState.cs b/de4dot.code/old_renamer/TypeNameState.cs deleted file mode 100644 index ecd24a6f..00000000 --- a/de4dot.code/old_renamer/TypeNameState.cs +++ /dev/null @@ -1,61 +0,0 @@ -/* - Copyright (C) 2011 de4dot@gmail.com - - This file is part of de4dot. - - de4dot is free software: you can redistribute it and/or modify - it under the terms of the GNU General Public License as published by - the Free Software Foundation, either version 3 of the License, or - (at your option) any later version. - - de4dot is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU General Public License for more details. - - You should have received a copy of the GNU General Public License - along with de4dot. If not, see . -*/ - -using System; -using System.Collections.Generic; -using de4dot.deobfuscators; - -namespace de4dot.old_renamer { - class TypeNameState { - public CurrentNames currentNames; - IDictionary namespaceToNewName; - INameCreator createNamespaceName; - public ITypeNameCreator globalTypeNameCreator; - public ITypeNameCreator internalTypeNameCreator; - Func isValidName; - - public Func IsValidName { - get { return isValidName; } - set { isValidName = value; } - } - - public TypeNameState() { - currentNames = new CurrentNames(); - namespaceToNewName = new Dictionary(StringComparer.Ordinal); - createNamespaceName = new GlobalNameCreator(new NameCreator("ns")); - globalTypeNameCreator = new GlobalTypeNameCreator(currentNames); - internalTypeNameCreator = new TypeNameCreator(currentNames); - } - - public bool isValidNamespace(string ns) { - foreach (var part in ns.Split(new char[] { '.' })) { - if (!isValidName(part)) - return false; - } - return true; - } - - public string newNamespace(string ns) { - string newName; - if (namespaceToNewName.TryGetValue(ns, out newName)) - return newName; - return namespaceToNewName[ns] = createNamespaceName.newName(); - } - } -} diff --git a/de4dot.code/old_renamer/TypeNames.cs b/de4dot.code/old_renamer/TypeNames.cs deleted file mode 100644 index 180a121c..00000000 --- a/de4dot.code/old_renamer/TypeNames.cs +++ /dev/null @@ -1,133 +0,0 @@ -/* - Copyright (C) 2011 de4dot@gmail.com - - This file is part of de4dot. - - de4dot is free software: you can redistribute it and/or modify - it under the terms of the GNU General Public License as published by - the Free Software Foundation, either version 3 of the License, or - (at your option) any later version. - - de4dot is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU General Public License for more details. - - You should have received a copy of the GNU General Public License - along with de4dot. If not, see . -*/ - -using System; -using System.Collections.Generic; -using Mono.Cecil; - -namespace de4dot.old_renamer { - abstract class TypeNames { - protected IDictionary typeNames = new Dictionary(StringComparer.Ordinal); - protected INameCreator genericParamNameCreator = new NameCreator("gparam_"); - - public TypeNames() { - insertTypeName("System.Boolean", "bool"); - insertTypeName("System.Byte", "byte"); - insertTypeName("System.Char", "char"); - insertTypeName("System.Double", "double"); - insertTypeName("System.Int16", "short"); - insertTypeName("System.Int32", "int"); - insertTypeName("System.Int64", "long"); - insertTypeName("System.IntPtr", "intptr"); - insertTypeName("System.SByte", "sbyte"); - insertTypeName("System.Single", "float"); - insertTypeName("System.String", "string"); - insertTypeName("System.UInt16", "ushort"); - insertTypeName("System.UInt32", "uint"); - insertTypeName("System.UInt64", "ulong"); - insertTypeName("System.UIntPtr", "uintptr"); - insertTypeName("System.Decimal", "decimal"); - } - - public string newName(TypeReference typeRef) { - var elementType = typeRef.GetElementType(); - if (elementType is GenericParameter) - return genericParamNameCreator.newName(); - - var name = elementType.FullName; - INameCreator nc; - if (typeNames.TryGetValue(name, out nc)) - return nc.newName(); - - var parts = name.Replace('/', '.').Split(new char[] { '.' }); - var newName = parts[parts.Length - 1]; - int tickIndex = newName.LastIndexOf('`'); - if (tickIndex > 0) - newName = newName.Substring(0, tickIndex); - - return insertTypeName(name, newName).newName(); - } - - INameCreator insertTypeName(string fullName, string newName) { - newName = fixName(newName); - - var name2 = " " + newName; - INameCreator nc; - if (!typeNames.TryGetValue(name2, out nc)) - typeNames[name2] = nc = new NameCreator(newName + "_"); - - typeNames[fullName] = nc; - return nc; - } - - protected abstract string fixName(string name); - public abstract TypeNames clone(); - - protected IDictionary cloneDict() { - var rv = new Dictionary(StringComparer.Ordinal); - foreach (var key in typeNames.Keys) - rv[key] = typeNames[key].clone(); - return rv; - } - } - - class VariableNameCreator : TypeNames { - protected override string fixName(string name) { - // Make all leading upper case chars lower case - var s = ""; - for (int i = 0; i < name.Length; i++) { - char c = char.ToLowerInvariant(name[i]); - if (c == name[i]) - return s + name.Substring(i); - s += c; - } - return s; - } - - public override TypeNames clone() { - var rv = new VariableNameCreator(); - rv.typeNames = cloneDict(); - rv.genericParamNameCreator = genericParamNameCreator.clone(); - return rv; - } - } - - class PropertyNameCreator : TypeNames { - protected override string fixName(string name) { - return name.Substring(0, 1).ToUpperInvariant() + name.Substring(1); - } - - public override TypeNames clone() { - var rv = new PropertyNameCreator(); - rv.typeNames = cloneDict(); - rv.genericParamNameCreator = genericParamNameCreator.clone(); - return rv; - } - } - - class GlobalInterfacePropertyNameCreator : TypeNames { - protected override string fixName(string name) { - return "I_" + name.Substring(0, 1).ToUpperInvariant() + name.Substring(1); - } - - public override TypeNames clone() { - return this; - } - } -} diff --git a/de4dot.code/old_renamer/VariableNameState.cs b/de4dot.code/old_renamer/VariableNameState.cs deleted file mode 100644 index 95a034a0..00000000 --- a/de4dot.code/old_renamer/VariableNameState.cs +++ /dev/null @@ -1,110 +0,0 @@ -/* - Copyright (C) 2011 de4dot@gmail.com - - This file is part of de4dot. - - de4dot is free software: you can redistribute it and/or modify - it under the terms of the GNU General Public License as published by - the Free Software Foundation, either version 3 of the License, or - (at your option) any later version. - - de4dot is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU General Public License for more details. - - You should have received a copy of the GNU General Public License - along with de4dot. If not, see . -*/ - -using Mono.Cecil; - -namespace de4dot.old_renamer { - // State when renaming type members - class VariableNameState { - CurrentNames currentVariableNames = new CurrentNames(); - CurrentNames currentMethodNames = new CurrentNames(); - protected TypeNames variableNameCreator = new VariableNameCreator(); // For fields and method args - protected TypeNames propertyNameCreator = new PropertyNameCreator(); - protected INameCreator eventNameCreator = new NameCreator("Event_"); - public INameCreator staticMethodNameCreator = new NameCreator("smethod_"); - public INameCreator virtualMethodNameCreator = new NameCreator("vmethod_"); - public INameCreator instanceMethodNameCreator = new NameCreator("method_"); - protected INameCreator genericPropertyNameCreator = new NameCreator("Prop_"); - Func isValidName; - - public Func IsValidName { - get { return isValidName; } - set { isValidName = value; } - } - - public virtual VariableNameState clone() { - var rv = new VariableNameState(); - cloneInit(rv); - return rv; - } - - public void addFieldName(string fieldName) { - currentVariableNames.add(fieldName); - } - - public void addMethodName(string methodName) { - currentMethodNames.add(methodName); - } - - protected void cloneInit(VariableNameState variableNameState) { - variableNameState.currentVariableNames = new CurrentNames(); - variableNameState.currentMethodNames = new CurrentNames(); - variableNameState.variableNameCreator = variableNameCreator.clone(); - variableNameState.propertyNameCreator = propertyNameCreator.clone(); - variableNameState.eventNameCreator = eventNameCreator.clone(); - variableNameState.staticMethodNameCreator = staticMethodNameCreator.clone(); - variableNameState.virtualMethodNameCreator = virtualMethodNameCreator.clone(); - variableNameState.instanceMethodNameCreator = instanceMethodNameCreator.clone(); - variableNameState.genericPropertyNameCreator = genericPropertyNameCreator.clone(); - variableNameState.isValidName = isValidName; - } - - public string getNewPropertyName(PropertyDefinition propertyDefinition) { - var propType = propertyDefinition.PropertyType; - if (propType is GenericParameter) - return genericPropertyNameCreator.newName(); - return propertyNameCreator.newName(propType); - } - - public string getNewEventName(EventDefinition eventDefinition) { - return eventNameCreator.newName(); - } - - public string getNewFieldName(FieldDefinition field) { - return currentVariableNames.newName(field.Name, () => variableNameCreator.newName(field.FieldType)); - } - - public string getNewFieldName(string oldName, INameCreator nameCreator) { - return currentVariableNames.newName(oldName, () => nameCreator.newName()); - } - - public string getNewParamName(string oldName, ParameterDefinition param) { - return currentVariableNames.newName(oldName, () => variableNameCreator.newName(param.ParameterType)); - } - - public string getNewMethodName(string oldName, INameCreator nameCreator) { - return currentMethodNames.newName(oldName, nameCreator); - } - } - - class InterfaceVariableNameState : VariableNameState { - public InterfaceVariableNameState() { - propertyNameCreator = new GlobalInterfacePropertyNameCreator(); - eventNameCreator = new GlobalNameCreator(new NameCreator("I_Event_")); - virtualMethodNameCreator = new GlobalNameCreator(new NameCreator("imethod_")); - genericPropertyNameCreator = new GlobalNameCreator(new NameCreator("I_Prop_")); - } - - public override VariableNameState clone() { - var rv = new InterfaceVariableNameState(); - cloneInit(rv); - return rv; - } - } -}