예제 #1
0
        public static bool findRegisterMethod(TypeDef type, out MethodDef regMethod, out MethodDef handler)
        {
            foreach (var method in type.Methods) {
                if (!method.IsStatic || method.Body == null)
                    continue;
                if (method.Body.ExceptionHandlers.Count != 1)
                    continue;

                foreach (var instr in method.Body.Instructions) {
                    if (instr.OpCode.Code != Code.Ldftn)
                        continue;
                    var handlerRef = instr.Operand as IMethod;
                    if (handlerRef == null)
                        continue;
                    if (!DotNetUtils.isMethod(handlerRef, "System.Reflection.Assembly", "(System.Object,System.ResolveEventArgs)"))
                        continue;
                    if (!new SigComparer().Equals(type, handlerRef.DeclaringType))
                        continue;
                    handler = DotNetUtils.getMethod(type, handlerRef);
                    if (handler == null)
                        continue;
                    if (handler.Body == null || handler.Body.ExceptionHandlers.Count != 1)
                        continue;

                    regMethod = method;
                    return true;
                }
            }

            regMethod = null;
            handler = null;
            return false;
        }
예제 #2
0
        public static VTable ConstructVTable(TypeDef typeDef, VTableStorage storage)
        {
            var ret = new VTable(typeDef);

            var slotDict = new Dictionary<VTableSignature, List<VTableSlot>>();

            // Partition II 12.2

            // Interfaces
            foreach (InterfaceImpl iface in typeDef.Interfaces) {
                VTable ifaceVTbl = storage.GetVTable(iface.Interface);
                if (ifaceVTbl != null)
                    ret.Inherit(ifaceVTbl, slotDict);
            }

            // Base type
            VTable baseVTbl = storage.GetVTable(typeDef.GetBaseTypeThrow());
            if (baseVTbl != null)
                ret.Inherit(baseVTbl, slotDict);

            List<MethodDef> virtualMethods = typeDef.Methods.Where(method => method.IsVirtual).ToList();
            var methodsProcessed = new HashSet<MethodDef>();

            // MethodImpls (Partition II 22.27)
            foreach (MethodDef method in virtualMethods)
                foreach (MethodOverride impl in method.Overrides) {
                    Debug.Assert(impl.MethodBody == method);

                    MethodDef targetMethod = impl.MethodDeclaration.ResolveThrow();
                    VTableSignature sig = VTableSignature.FromMethod(impl.MethodDeclaration);
                    Debug.Assert(slotDict.ContainsKey(sig));

                    var methodSlot = new VTableSlot(ret, method, method.DeclaringType.ToTypeSig(), VTableSignature.FromMethod(method));
                    ret.Override(slotDict, sig, methodSlot, targetMethod);
                    methodsProcessed.Add(method);
                }

            // Normal override
            foreach (MethodDef method in virtualMethods) {
                VTableSignature sig = VTableSignature.FromMethod(method);
                var methodSlot = new VTableSlot(ret, method, method.DeclaringType.ToTypeSig(), sig);
                if (slotDict.ContainsKey(sig) && slotDict[sig].Count > 0) {
                    ret.Override(slotDict, sig, methodSlot);
                    methodsProcessed.Add(method);
                }
            }

            // Remaining methods
            foreach (MethodDef method in typeDef.Methods.Where(method => method.IsVirtual).Except(methodsProcessed)) {
                var slot = new VTableSlot(ret, method, method.DeclaringType.ToTypeSig(), VTableSignature.FromMethod(method));
                if (method.IsFinal)
                    ret.Finals.Add(slot);
                else {
                    Debug.Assert(!ret.Slots.Any(s => s.MethodDef == method));
                    ret.Slots.Add(slot);
                }
            }

            return ret;
        }
예제 #3
0
        public PropertyOptionsVM(PropertyDefOptions options, ModuleDef ownerModule, Language language, TypeDef ownerType)
        {
            this.ownerModule = ownerModule;
            this.origOptions = options;

            var typeSigCreatorOptions = new TypeSigCreatorOptions(ownerModule, language) {
                IsLocal = false,
                CanAddGenericTypeVar = true,
                CanAddGenericMethodVar = true,
                OwnerType = ownerType,
            };
            if (ownerType != null && ownerType.GenericParameters.Count == 0)
                typeSigCreatorOptions.CanAddGenericTypeVar = false;
            var methodSigCreatorOptions = new MethodSigCreatorOptions(typeSigCreatorOptions);
            methodSigCreatorOptions.IsPropertySig = true;
            this.methodSigCreator = new MethodSigCreatorVM(methodSigCreatorOptions);
            this.methodSigCreator.PropertyChanged += methodSigCreator_PropertyChanged;
            this.methodSigCreator.ParametersCreateTypeSigArray.PropertyChanged += methodSigCreator_PropertyChanged;
            this.methodSigCreator.ParametersCreateTypeSigArray.TypeSigCreator.CanAddFnPtr = false;
            this.getMethodsVM = new MethodDefsVM(ownerModule, language);
            this.setMethodsVM = new MethodDefsVM(ownerModule, language);
            this.otherMethodsVM = new MethodDefsVM(ownerModule, language);
            this.customAttributesVM = new CustomAttributesVM(ownerModule, language);
            this.constantVM = new ConstantVM(ownerModule, options.Constant == null ? null : options.Constant.Value, "Default value for this property");
            this.constantVM.PropertyChanged += constantVM_PropertyChanged;

            ConstantVM.IsEnabled = HasDefault;
            Reinitialize();
        }
예제 #4
0
 public AnalyzedTypeTreeNode(TypeDef analyzedType)
 {
     if (analyzedType == null)
         throw new ArgumentNullException("analyzedType");
     this.analyzedType = analyzedType;
     this.LazyLoading = true;
 }
		private IEnumerable<AnalyzerTreeNode> FindReferencesInType(TypeDef type)
		{
			foreach (MethodDef method in type.Methods) {
				bool found = false;
				if (!method.HasBody)
					continue;

				// ignore chained constructors
				// (since object is the root of everything, we can short circuit the test in this case)
				if (method.Name == ".ctor" &&
					(isSystemObject || analyzedType == type || TypesHierarchyHelpers.IsBaseType(analyzedType, type, false)))
					continue;

				foreach (Instruction instr in method.Body.Instructions) {
					IMethod mr = instr.Operand as IMethod;
					if (mr != null && !mr.IsField && mr.Name == ".ctor") {
						if (Helpers.IsReferencedBy(analyzedType, mr.DeclaringType)) {
							found = true;
							break;
						}
					}
				}

				Helpers.FreeMethodBody(method);

				if (found) {
					var node = new AnalyzedMethodTreeNode(method);
					node.Language = this.Language;
					yield return node;
				}
			}
		}
예제 #6
0
		public void Find() {
			var requiredFields = new string[] {
				"System.Threading.ReaderWriterLock",
				"System.Collections.Hashtable",
			};
			foreach (var type in module.GetTypes()) {
				var fieldTypes = new FieldTypes(type);
				if (!fieldTypes.All(requiredFields))
					continue;
				if (type.FindMethod("Finalize") == null)
					continue;
				var executeMethod = DotNetUtils.GetMethod(type, "System.Object", "(System.String,System.Object[])");
				if (executeMethod == null || !executeMethod.IsStatic || executeMethod.Body == null)
					continue;

				var decrypterType = FindMethodsDecrypterType(type);
				if (decrypterType == null)
					continue;

				resourceDecrypter.DecryptMethod = FindDecryptMethod(decrypterType);

				methodsDecrypterCreator = type;
				methodsDecrypter = decrypterType;
				decryptExecuteMethod = executeMethod;
				return;
			}
		}
		public void Find(ISimpleDeobfuscator simpleDeobfuscator, IDeobfuscator deob) {
			foreach (var type in module.Types) {
				if (type.Fields.Count != 1)
					continue;
				if (type.HasNestedTypes || type.HasGenericParameters || type.IsValueType)
					continue;
				if (DotNetUtils.GetField(type, "System.Reflection.Assembly") == null)
					continue;
				if (type.FindStaticConstructor() == null)
					continue;

				var getStream2 = GetTheOnlyMethod(type, "System.IO.Stream", "(System.Reflection.Assembly,System.Type,System.String)");
				var getNames = GetTheOnlyMethod(type, "System.String[]", "(System.Reflection.Assembly)");
				var getRefAsms = GetTheOnlyMethod(type, "System.Reflection.AssemblyName[]", "(System.Reflection.Assembly)");
				var bitmapCtor = GetTheOnlyMethod(type, "System.Drawing.Bitmap", "(System.Type,System.String)");
				var iconCtor = GetTheOnlyMethod(type, "System.Drawing.Icon", "(System.Type,System.String)");
				if (getStream2 == null && getNames == null && getRefAsms == null &&
					bitmapCtor == null && iconCtor == null)
					continue;

				var resource = FindGetManifestResourceStreamTypeResource(type, simpleDeobfuscator, deob);
				if (resource == null && getStream2 != null)
					continue;

				getManifestResourceStreamType = type;
				CreateGetManifestResourceStream2(getStream2);
				CreateGetManifestResourceNames(getNames);
				CreateGetReferencedAssemblies(getRefAsms);
				CreateBitmapCtor(bitmapCtor);
				CreateIconCtor(iconCtor);
				getManifestResourceStreamTypeResource = resource;
				break;
			}
		}
예제 #8
0
		void Initialize(TypeDef type) {
			if (type.HasEvents || type.HasProperties)
				return;

			if (!type.IsValueType)
				return;
			if (type.Methods.Count != 1)
				return;
			var ctor = type.Methods[0];
			if (ctor.Name != ".ctor" || ctor.Body == null || ctor.IsStatic)
				return;
			var sig = ctor.MethodSig;
			if (sig == null || sig.Params.Count != 1)
				return;
			var ctorParam = sig.Params[0];

			if (type.Fields.Count != 1)
				return;
			var typeField = type.Fields[0];
			if (typeField.IsStatic)
				return;
			if (!new SigComparer().Equals(ctorParam, typeField.FieldType))
				return;

			typeToInfo.Add(ctor.DeclaringType, new Info(ctor.DeclaringType, typeField.FieldType));
		}
        private IEnumerable<AnalyzerTreeNode> FindReferencesInType(TypeDef type)
        {
            string name = analyzedMethod.Name;
            foreach (MethodDef method in type.Methods) {
                bool found = false;
                if (!method.HasBody)
                    continue;
                foreach (Instruction instr in method.Body.Instructions) {
                    IMethod mr = instr.Operand as IMethod;
                    if (mr != null && !mr.IsField && mr.Name == name &&
                        Helpers.IsReferencedBy(analyzedMethod.DeclaringType, mr.DeclaringType) &&
                        Decompiler.DnlibExtensions.Resolve(mr) == analyzedMethod) {
                        found = true;
                        break;
                    }
                }

                Helpers.FreeMethodBody(method);

                if (found) {
                    MethodDef codeLocation = this.Language.GetOriginalCodeLocation(method) as MethodDef;
                    if (codeLocation != null && !HasAlreadyBeenFound(codeLocation)) {
                        var node= new AnalyzedMethodTreeNode(codeLocation);
                        node.Language = this.Language;
                        yield return node;
                    }
                }
            }
        }
예제 #10
0
		public TypeInstantiationsNode(TypeDef analyzedType) {
			if (analyzedType == null)
				throw new ArgumentNullException(nameof(analyzedType));

			this.analyzedType = analyzedType;
			isSystemObject = analyzedType.DefinitionAssembly.IsCorLib() && analyzedType.FullName == "System.Object";
		}
        public AnalyzedTypeExposedByTreeNode(TypeDef analyzedType)
        {
            if (analyzedType == null)
                throw new ArgumentNullException("analyzedType");

            this.analyzedType = analyzedType;
        }
예제 #12
0
		public DecompilePartialTransform(TypeDef type, HashSet<IMemberDef> definitions, bool showDefinitions, bool addPartialKeyword, IEnumerable<ITypeDefOrRef> ifacesToRemove) {
			this.type = type;
			this.definitions = definitions;
			this.showDefinitions = showDefinitions;
			this.addPartialKeyword = addPartialKeyword;
			this.ifacesToRemove = new HashSet<ITypeDefOrRef>(ifacesToRemove, TypeEqualityComparer.Instance);
		}
 public static bool CanShow(TypeDef type)
 {
     if (type.IsClass && !type.IsEnum) {
         return type.Methods.Where(m => m.Name == ".ctor").Any(m => !m.IsPrivate);
     }
     return false;
 }
예제 #14
0
		private IEnumerable<AnalyzerTreeNode> FindReferencesInType(TypeDef type) {
			foreach (MethodDef method in type.Methods) {
				bool found = false;
				if (!method.HasBody)
					continue;
				foreach (Instruction instr in method.Body.Instructions) {
					if (CanBeReference(instr.OpCode.Code)) {
						IField fr = instr.Operand as IField;
						if (fr != null && new SigComparer(SigComparerOptions.CompareDeclaringTypes | SigComparerOptions.PrivateScopeIsComparable).Equals(fr, analyzedField) &&
							Helpers.IsReferencedBy(analyzedField.DeclaringType, fr.DeclaringType)) {
							found = true;
							break;
						}
					}
				}

				Helpers.FreeMethodBody(method);

				if (found) {
					MethodDef codeLocation = this.Language.GetOriginalCodeLocation(method) as MethodDef;
					if (codeLocation != null && !HasAlreadyBeenFound(codeLocation)) {
						var node = new AnalyzedMethodTreeNode(codeLocation);
						node.Language = this.Language;
						yield return node;
					}
				}
			}
		}
예제 #15
0
		IEnumerable<IAnalyzerTreeNodeData> FindReferencesInType(TypeDef type) {
			if (analyzedType.IsEnum && type == analyzedType)
				yield break;

			if (!this.Context.Language.ShowMember(type))
				yield break;

			foreach (FieldDef field in type.Fields) {
				if (TypeIsExposedBy(field)) {
					yield return new FieldNode(field) { Context = Context };
				}
			}

			foreach (PropertyDef property in type.Properties) {
				if (TypeIsExposedBy(property)) {
					yield return new PropertyNode(property) { Context = Context };
				}
			}

			foreach (EventDef eventDef in type.Events) {
				if (TypeIsExposedBy(eventDef)) {
					yield return new EventNode(eventDef) { Context = Context };
				}
			}

			foreach (MethodDef method in type.Methods) {
				if (TypeIsExposedBy(method)) {
					yield return new MethodNode(method) { Context = Context };
				}
			}
		}
예제 #16
0
 /// <summary>
 ///     Injects the specified TypeDef to another module.
 /// </summary>
 /// <param name="typeDef">The source TypeDef.</param>
 /// <param name="target">The target module.</param>
 /// <returns>The injected TypeDef.</returns>
 public static TypeDef Inject(TypeDef typeDef, ModuleDef target)
 {
     var ctx = new InjectContext(typeDef.Module, target);
     PopulateContext(typeDef, ctx);
     Copy(typeDef, ctx, true);
     return (TypeDef)ctx.Map[typeDef];
 }
예제 #17
0
		bool Find(MethodDef methodToCheck) {
			if (methodToCheck == null)
				return false;
			foreach (var method in DotNetUtils.GetCalledMethods(module, methodToCheck)) {
				var type = method.DeclaringType;

				if (!method.IsStatic || !DotNetUtils.IsMethod(method, "System.Void", "()"))
					continue;
				if (DotNetUtils.GetPInvokeMethod(type, "kernel32", "LoadLibrary") == null)
					continue;
				if (DotNetUtils.GetPInvokeMethod(type, "kernel32", "GetProcAddress") == null)
					continue;
				Deobfuscate(method);
				if (!ContainsString(method, "debugger is activ") &&
					!ContainsString(method, "debugger is running") &&
					!ContainsString(method, "Debugger detected") &&
					!ContainsString(method, "Debugger was detected") &&
					!ContainsString(method, "{0} was detected") &&
					!ContainsString(method, "run under") &&
					!ContainsString(method, "run with") &&
					!ContainsString(method, "started under") &&
					!ContainsString(method, "{0} detected") &&
					!ContainsString(method, "{0} found"))
					continue;

				antiDebuggerType = type;
				antiDebuggerMethod = method;
				return true;
			}

			return false;
		}
예제 #18
0
		public static bool QuickCheck(TypeDef type) {
			if (type == null)
				return false;
			if (!type.IsInterface && type.IsSealed)
				return false;
			return true;
		}
예제 #19
0
        public FieldOptionsVM(FieldDefOptions options, ModuleDef ownerModule, Language language, TypeDef ownerType)
        {
            this.ownerModule = ownerModule;
            var typeSigCreatorOptions = new TypeSigCreatorOptions(ownerModule, language) {
                IsLocal = false,
                CanAddGenericTypeVar = true,
                CanAddGenericMethodVar = false,
                OwnerType = ownerType,
            };
            if (ownerType != null && ownerType.GenericParameters.Count == 0)
                typeSigCreatorOptions.CanAddGenericTypeVar = false;
            this.typeSigCreator = new TypeSigCreatorVM(typeSigCreatorOptions);
            TypeSigCreator.PropertyChanged += typeSigCreator_PropertyChanged;

            this.customAttributesVM = new CustomAttributesVM(ownerModule, language);
            this.origOptions = options;

            this.constantVM = new ConstantVM(ownerModule, options.Constant == null ? null : options.Constant.Value, "Default value for this field");
            ConstantVM.PropertyChanged += constantVM_PropertyChanged;
            this.marshalTypeVM = new MarshalTypeVM(ownerModule, language, ownerType, null);
            MarshalTypeVM.PropertyChanged += marshalTypeVM_PropertyChanged;
            this.fieldOffset = new NullableUInt32VM(a => HasErrorUpdated());
            this.initialValue = new HexStringVM(a => HasErrorUpdated());
            this.rva = new UInt32VM(a => HasErrorUpdated());
            this.implMapVM = new ImplMapVM(ownerModule);
            ImplMapVM.PropertyChanged += implMapVM_PropertyChanged;

            this.typeSigCreator.CanAddFnPtr = false;
            ConstantVM.IsEnabled = HasDefault;
            MarshalTypeVM.IsEnabled = HasFieldMarshal;
            ImplMapVM.IsEnabled = PinvokeImpl;
            Reinitialize();
        }
예제 #20
0
		public DerivedTypesEntryNode(TypeDef type, ModuleDef[] modules)
		{
			this.type = type;
			this.modules = modules;
			this.LazyLoading = true;
			threading = new ThreadingSupport();
		}
        private IEnumerable<AnalyzerTreeNode> FindReferencesInType(TypeDef type)
        {
            if (!type.HasInterfaces)
                yield break;
            ITypeDefOrRef implementedInterfaceRef = type.Interfaces.FirstOrDefault(i => i.Interface.ResolveTypeDef() == analyzedMethod.DeclaringType).Interface;
            if (implementedInterfaceRef == null)
                yield break;

            foreach (EventDef ev in type.Events.Where(e => e.Name == analyzedEvent.Name)) {
                MethodDef accessor = ev.AddMethod ?? ev.RemoveMethod;
                if (TypesHierarchyHelpers.MatchInterfaceMethod(accessor, analyzedMethod, implementedInterfaceRef)) {
                    var node = new AnalyzedEventTreeNode(ev);
                    node.Language = this.Language;
                    yield return node;
                }
                yield break;
            }

            foreach (EventDef ev in type.Events.Where(e => e.Name.String.EndsWith(analyzedEvent.Name))) {
                MethodDef accessor = ev.AddMethod ?? ev.RemoveMethod;
                if (accessor.HasOverrides && accessor.Overrides.Any(m => Decompiler.DnlibExtensions.Resolve(m.MethodDeclaration) == analyzedMethod)) {
                    var node = new AnalyzedEventTreeNode(ev);
                    node.Language = this.Language;
                    yield return node;
                }
            }
        }
예제 #22
0
		public DerivedTypesTreeNode(AssemblyList list, TypeDef type)
		{
			this.list = list;
			this.type = type;
			this.LazyLoading = true;
			this.threading = new ThreadingSupport();
		}
예제 #23
0
		IEnumerable<AnalyzerTreeNodeData> FindReferencesInType(TypeDef type) {
			string name = analyzedMethod.Name;
			foreach (MethodDef method in type.Methods) {
				if (!method.HasBody)
					continue;
				Instruction foundInstr = null;
				foreach (Instruction instr in method.Body.Instructions) {
					IMethod mr = instr.Operand as IMethod;
					if (mr != null && !mr.IsField && mr.Name == name &&
						Helpers.IsReferencedBy(analyzedMethod.DeclaringType, mr.DeclaringType) &&
						mr.ResolveMethodDef() == analyzedMethod) {
						foundInstr = instr;
						break;
					}
				}

				if (foundInstr != null) {
					MethodDef codeLocation = GetOriginalCodeLocation(method) as MethodDef;
					if (codeLocation != null && !HasAlreadyBeenFound(codeLocation)) {
						var node = new MethodNode(codeLocation) { Context = Context };
						if (codeLocation == method)
							node.SourceRef = new SourceRef(method, foundInstr.Offset, foundInstr.Operand as IMDTokenProvider);
						yield return node;
					}
				}
			}
		}
        static string getResourceName(TypeDef type)
        {
            foreach (var method in type.Methods) {
                if (method.Body == null)
                    continue;
                var instrs = method.Body.Instructions;
                string resourceName = null;
                for (int i = 0; i < instrs.Count; i++) {
                    var instr = instrs[i];
                    if (instr.OpCode.Code == Code.Ldstr) {
                        resourceName = instr.Operand as string;
                        continue;
                    }

                    if (instr.OpCode.Code == Code.Newobj) {
                        var ctor = instr.Operand as IMethod;
                        if (ctor.FullName != "System.Void System.Resources.ResourceManager::.ctor(System.String,System.Reflection.Assembly)")
                            continue;
                        if (resourceName == null) {
                            Logger.w("Could not find resource name");
                            continue;
                        }

                        return resourceName;
                    }
                }
            }
            return null;
        }
		public void Find() {
			var requiredTypes = new string[] {
				"System.Reflection.Assembly",
				"System.Object",
				"System.Int32",
				"System.String[]",
			};
			foreach (var type in module.Types) {
				if (type.HasEvents)
					continue;
				if (!new FieldTypes(type).All(requiredTypes))
					continue;

				MethodDef regMethod, handler;
				if (!BabelUtils.FindRegisterMethod(type, out regMethod, out handler))
					continue;

				var resource = BabelUtils.FindEmbeddedResource(module, type);
				if (resource == null)
					continue;

				var decryptMethod = FindDecryptMethod(type);
				if (decryptMethod == null)
					throw new ApplicationException("Couldn't find resource type decrypt method");
				resourceDecrypter.DecryptMethod = ResourceDecrypter.FindDecrypterMethod(decryptMethod);
				InitXorKeys(decryptMethod);

				resolverType = type;
				registerMethod = regMethod;
				encryptedResource = resource;
				return;
			}
		}
예제 #26
0
		IEnumerable<AnalyzerTreeNodeData> FindReferencesInType(TypeDef type) {
			foreach (MethodDef method in type.Methods) {
				if (!method.HasBody)
					continue;

				// ignore chained constructors
				// (since object is the root of everything, we can short circuit the test in this case)
				if (method.Name == ".ctor" &&
					(isSystemObject || analyzedType == type || TypesHierarchyHelpers.IsBaseType(analyzedType, type, false)))
					continue;

				Instruction foundInstr = null;
				foreach (Instruction instr in method.Body.Instructions) {
					IMethod mr = instr.Operand as IMethod;
					if (mr != null && !mr.IsField && mr.Name == ".ctor") {
						if (Helpers.IsReferencedBy(analyzedType, mr.DeclaringType)) {
							foundInstr = instr;
							break;
						}
					}
				}

				if (foundInstr != null)
					yield return new MethodNode(method) { Context = Context, SourceRef = new SourceRef(method, foundInstr.Offset, foundInstr.Operand as IMDTokenProvider) };
			}
		}
예제 #27
0
 public static EmbeddedResource findEmbeddedResource(ModuleDefMD module, TypeDef decrypterType, ISimpleDeobfuscator simpleDeobfuscator, IDeobfuscator deob)
 {
     return findEmbeddedResource(module, decrypterType, (method) => {
         simpleDeobfuscator.deobfuscate(method);
         simpleDeobfuscator.decryptStrings(method, deob);
     });
 }
예제 #28
0
		public void Find() {
			foreach (var type in module.Types) {
				if (!type.HasMethods)
					continue;
				if (type.Methods.Count > 3)
					continue;

				MethodDef errorMethod = null;
				foreach (var method in type.Methods) {
					if (method.Name == ".ctor")
						continue;	// .ctor is allowed
					if (method.Name == ".cctor")
						continue;	// .cctor is allowed
					var sig = method.MethodSig;
					if (sig != null && method.IsStatic && method.HasBody &&
						sig.Params.Count == 2 && !method.HasGenericParameters &&
						!DotNetUtils.HasReturnValue(method) &&
						sig.Params[0].GetFullName() == "System.Exception" &&
						sig.Params[1].GetFullName() == "System.Object[]") {
						errorMethod = method;
					}
					else
						break;
				}
				if (errorMethod != null) {
					stackFrameHelperType = type;
					exceptionLoggerRemover.Add(errorMethod);
					return;
				}
			}
		}
예제 #29
0
 internal VTable(TypeDef typeDef)
 {
     Type = typeDef;
     GenericArguments = null;
     Slots = new List<VTableSlot>();
     Finals = new List<VTableSlot>();
 }
        private IEnumerable<AnalyzerTreeNode> FindReferencesInType(TypeDef type)
        {
            if (!type.HasInterfaces || analyzedMethod == null)
                yield break;
            var iff = type.Interfaces.FirstOrDefault(i => new SigComparer().Equals(i.Interface, analyzedMethod.DeclaringType));
            ITypeDefOrRef implementedInterfaceRef = iff == null ? null : iff.Interface;
            if (implementedInterfaceRef == null)
                yield break;

            //TODO: Can we compare event types too?
            foreach (EventDef ev in type.Events.Where(e => e.Name == analyzedEvent.Name)) {
                MethodDef accessor = ev.AddMethod ?? ev.RemoveMethod;
                if (accessor != null && TypesHierarchyHelpers.MatchInterfaceMethod(accessor, analyzedMethod, implementedInterfaceRef)) {
                    var node = new AnalyzedEventTreeNode(ev);
                    node.Language = this.Language;
                    yield return node;
                }
                yield break;
            }

            foreach (EventDef ev in type.Events.Where(e => e.Name.EndsWith(analyzedEvent.Name))) {
                MethodDef accessor = ev.AddMethod ?? ev.RemoveMethod;
                if (accessor != null && accessor.HasOverrides &&
                    accessor.Overrides.Any(m => new SigComparer(SigComparerOptions.CompareDeclaringTypes | SigComparerOptions.PrivateScopeIsComparable).Equals(m.MethodDeclaration, analyzedMethod))) {
                    var node = new AnalyzedEventTreeNode(ev);
                    node.Language = this.Language;
                    yield return node;
                }
            }
        }
예제 #31
0
        IEnumerable <EntityNode> FindTypeUsage(TypeDef type)
        {
            if (type == null)
            {
                yield break;
            }
            if (type == analyzedType)
            {
                yield break;
            }

            if (IsUsedInTypeDef(type))
            {
                yield return new TypeNode(type)
                       {
                           Context = Context
                       }
            }
            ;

            foreach (var field in type.Fields.Where(IsUsedInFieldRef))
            {
                yield return new FieldNode(field)
                       {
                           Context = Context
                       }
            }
            ;

            foreach (var method in type.Methods)
            {
                SourceRef?sourceRef = null;

                if (IsUsedInMethodDef(method, ref sourceRef))
                {
                    yield return(HandleSpecialMethodNode(method, sourceRef));
                }
            }
        }

        EntityNode HandleSpecialMethodNode(MethodDef method, SourceRef?sourceRef)
        {
            var property = method.DeclaringType.Properties.FirstOrDefault(p => p.GetMethod == method || p.SetMethod == method);

            if (property != null)
            {
                return new PropertyNode(property)
                       {
                           Context = Context, SourceRef = sourceRef
                       }
            }
            ;

            return(new MethodNode(method)
            {
                Context = Context, SourceRef = sourceRef
            });
        }

        bool IsUsedInTypeRefs(IEnumerable <ITypeDefOrRef> types) => types.Any(IsUsedInTypeRef);

        bool IsUsedInTypeRef(ITypeDefOrRef type)
        {
            if (type == null)
            {
                return(false);
            }

            return(TypeMatches(type.DeclaringType) ||
                   TypeMatches(type));
        }

        bool IsUsedInTypeDef(TypeDef type)
        {
            if (type == null)
            {
                return(false);
            }

            return(IsUsedInTypeRef(type) ||
                   TypeMatches(type.BaseType) ||
                   IsUsedInTypeRefs(type.Interfaces.Select(ii => ii.Interface)));
        }

        bool IsUsedInFieldRef(IField field)
        {
            if (field == null || !field.IsField)
            {
                return(false);
            }

            return(TypeMatches(field.DeclaringType) ||
                   TypeMatches(field.FieldSig.GetFieldType()));
        }

        bool IsUsedInMethodRef(IMethod method)
        {
            if (method == null || !method.IsMethod)
            {
                return(false);
            }

            return(TypeMatches(method.DeclaringType) ||
                   TypeMatches(method.MethodSig.GetRetType()) ||
                   IsUsedInMethodParameters(method.GetParameters()));
        }

        bool IsUsedInMethodDef(MethodDef method, ref SourceRef?sourceRef) => IsUsedInMethodRef(method) ||
        IsUsedInMethodBody(method, ref sourceRef);

        bool IsUsedInMethodBody(MethodDef method, ref SourceRef?sourceRef)
        {
            if (method == null)
            {
                return(false);
            }
            if (method.Body == null)
            {
                return(false);
            }

            foreach (var instruction in method.Body.Instructions)
            {
                ITypeDefOrRef tr = instruction.Operand as ITypeDefOrRef;
                if (IsUsedInTypeRef(tr))
                {
                    sourceRef = new SourceRef(method, instruction.Offset, instruction.Operand as IMDTokenProvider);
                    return(true);
                }
                IField fr = instruction.Operand as IField;
                if (IsUsedInFieldRef(fr))
                {
                    sourceRef = new SourceRef(method, instruction.Offset, instruction.Operand as IMDTokenProvider);
                    return(true);
                }
                IMethod mr = instruction.Operand as IMethod;
                if (IsUsedInMethodRef(mr))
                {
                    sourceRef = new SourceRef(method, instruction.Offset, instruction.Operand as IMDTokenProvider);
                    return(true);
                }
            }

            return(false);
        }

        bool IsUsedInMethodParameters(IEnumerable <Parameter> parameters) => parameters.Any(IsUsedInMethodParameter);
        bool IsUsedInMethodParameter(Parameter parameter) => !parameter.IsHiddenThisParameter && TypeMatches(parameter.Type);
        bool TypeMatches(IType tref) => tref != null && new SigComparer().Equals(analyzedType, tref);
예제 #32
0
 public DeclSecuritiesVM(ModuleDef ownerModule, IDecompilerManager decompilerManager, TypeDef ownerType, MethodDef ownerMethod)
     : base(dnSpy_AsmEditor_Resources.EditSecurityDeclaration, dnSpy_AsmEditor_Resources.CreateSecurityDeclaration, ownerModule, decompilerManager, ownerType, ownerMethod)
 {
 }
예제 #33
0
        void AnalyzeMethod(ConfuserContext context, INameService service, MethodDef method)
        {
            var dpRegInstrs        = new List <Tuple <bool, Instruction> >();
            var routedEvtRegInstrs = new List <Instruction>();

            foreach (Instruction instr in method.Body.Instructions)
            {
                if ((instr.OpCode.Code == Code.Call || instr.OpCode.Code == Code.Callvirt))
                {
                    var regMethod = (IMethod)instr.Operand;

                    if (regMethod.DeclaringType.FullName == "System.Windows.DependencyProperty" &&
                        regMethod.Name.String.StartsWith("Register"))
                    {
                        dpRegInstrs.Add(Tuple.Create(regMethod.Name.String.StartsWith("RegisterAttached"), instr));
                    }
                    else if (regMethod.DeclaringType.FullName == "System.Windows.EventManager" &&
                             regMethod.Name.String == "RegisterRoutedEvent")
                    {
                        routedEvtRegInstrs.Add(instr);
                    }
                }
                else if (instr.OpCode == OpCodes.Ldstr)
                {
                    var operand = ((string)instr.Operand).ToUpperInvariant();
                    if (operand.EndsWith(".BAML") || operand.EndsWith(".XAML"))
                    {
                        var match = UriPattern.Match(operand);
                        if (match.Success)
                        {
                            operand = match.Groups[1].Value;
                        }

                        var reference = new BAMLStringReference(instr);
                        operand = operand.TrimStart('/');
                        var baml = operand.Substring(0, operand.Length - 5) + ".BAML";
                        var xaml = operand.Substring(0, operand.Length - 5) + ".XAML";
                        bamlRefs.AddListEntry(baml, reference);
                        bamlRefs.AddListEntry(xaml, reference);
                    }
                }
            }

            if (dpRegInstrs.Count == 0)
            {
                return;
            }

            var         traceSrv = context.Registry.GetService <ITraceService>();
            MethodTrace trace    = traceSrv.Trace(method);

            bool erred = false;

            foreach (var instrInfo in dpRegInstrs)
            {
                int[] args = trace.TraceArguments(instrInfo.Item2);
                if (args == null)
                {
                    if (!erred)
                    {
                        context.Logger.WarnFormat("Failed to extract dependency property name in '{0}'.", method.FullName);
                    }
                    erred = true;
                    continue;
                }
                Instruction ldstr = method.Body.Instructions[args[0]];
                if (ldstr.OpCode.Code != Code.Ldstr)
                {
                    if (!erred)
                    {
                        context.Logger.WarnFormat("Failed to extract dependency property name in '{0}'.", method.FullName);
                    }
                    erred = true;
                    continue;
                }

                var     name     = (string)ldstr.Operand;
                TypeDef declType = method.DeclaringType;
                bool    found    = false;
                if (instrInfo.Item1)                 // Attached DP
                {
                    MethodDef accessor;
                    if ((accessor = declType.FindMethod("Get" + name)) != null && accessor.IsStatic)
                    {
                        service.SetCanRename(accessor, false);
                        found = true;
                    }
                    if ((accessor = declType.FindMethod("Set" + name)) != null && accessor.IsStatic)
                    {
                        service.SetCanRename(accessor, false);
                        found = true;
                    }
                }

                // Normal DP
                // Find CLR property for attached DP as well, because it seems attached DP can be use as normal DP as well.
                PropertyDef property = null;
                if ((property = declType.FindProperty(name)) != null)
                {
                    found = true;
                    if (property.GetMethod != null)
                    {
                        service.SetCanRename(property.GetMethod, false);
                    }

                    if (property.SetMethod != null)
                    {
                        service.SetCanRename(property.SetMethod, false);
                    }

                    if (property.HasOtherMethods)
                    {
                        foreach (MethodDef accessor in property.OtherMethods)
                        {
                            service.SetCanRename(accessor, false);
                        }
                    }
                }
                if (!found)
                {
                    if (instrInfo.Item1)
                    {
                        context.Logger.WarnFormat("Failed to find the accessors of attached dependency property '{0}' in type '{1}'.",
                                                  name, declType.FullName);
                    }
                    else
                    {
                        context.Logger.WarnFormat("Failed to find the CLR property of normal dependency property '{0}' in type '{1}'.",
                                                  name, declType.FullName);
                    }
                }
            }

            erred = false;
            foreach (Instruction instr in routedEvtRegInstrs)
            {
                int[] args = trace.TraceArguments(instr);
                if (args == null)
                {
                    if (!erred)
                    {
                        context.Logger.WarnFormat("Failed to extract routed event name in '{0}'.", method.FullName);
                    }
                    erred = true;
                    continue;
                }
                Instruction ldstr = method.Body.Instructions[args[0]];
                if (ldstr.OpCode.Code != Code.Ldstr)
                {
                    if (!erred)
                    {
                        context.Logger.WarnFormat("Failed to extract routed event name in '{0}'.", method.FullName);
                    }
                    erred = true;
                    continue;
                }

                var     name     = (string)ldstr.Operand;
                TypeDef declType = method.DeclaringType;

                EventDef eventDef = null;
                if ((eventDef = declType.FindEvent(name)) == null)
                {
                    context.Logger.WarnFormat("Failed to find the CLR event of routed event '{0}' in type '{1}'.",
                                              name, declType.FullName);
                    continue;
                }
                if (eventDef.AddMethod != null)
                {
                    service.SetCanRename(eventDef.AddMethod, false);
                }

                if (eventDef.RemoveMethod != null)
                {
                    service.SetCanRename(eventDef.RemoveMethod, false);
                }

                if (eventDef.InvokeMethod != null)
                {
                    service.SetCanRename(eventDef.InvokeMethod, false);
                }

                if (eventDef.HasOtherMethods)
                {
                    foreach (MethodDef accessor in eventDef.OtherMethods)
                    {
                        service.SetCanRename(accessor, false);
                    }
                }
            }
        }
예제 #34
0
        void ProcessTypeMembers(TypeDef type, Rules rules, ProtectionSettingsStack stack)
        {
            foreach (var nestedType in type.NestedTypes)
            {
                stack.Push(ProcessAttributes(ReadObfuscationAttributes(nestedType)));

                ApplySettings(nestedType, rules, stack.GetInfos());
                ProcessTypeMembers(nestedType, rules, stack);

                stack.Pop();
            }

            foreach (var prop in type.Properties)
            {
                stack.Push(ProcessAttributes(ReadObfuscationAttributes(prop)));

                ApplySettings(prop, rules, stack.GetInfos());
                if (prop.GetMethod != null)
                {
                    ProcessMember(prop.GetMethod, rules, stack);
                }
                if (prop.SetMethod != null)
                {
                    ProcessMember(prop.SetMethod, rules, stack);
                }
                foreach (var m in prop.OtherMethods)
                {
                    ProcessMember(m, rules, stack);
                }

                stack.Pop();
            }

            foreach (var evt in type.Events)
            {
                stack.Push(ProcessAttributes(ReadObfuscationAttributes(evt)));

                ApplySettings(evt, rules, stack.GetInfos());
                if (evt.AddMethod != null)
                {
                    ProcessMember(evt.AddMethod, rules, stack);
                }
                if (evt.RemoveMethod != null)
                {
                    ProcessMember(evt.RemoveMethod, rules, stack);
                }
                if (evt.InvokeMethod != null)
                {
                    ProcessMember(evt.InvokeMethod, rules, stack);
                }
                foreach (var m in evt.OtherMethods)
                {
                    ProcessMember(m, rules, stack);
                }

                stack.Pop();
            }

            foreach (var method in type.Methods)
            {
                if (method.SemanticsAttributes == 0)
                {
                    ProcessMember(method, rules, stack);
                }
            }

            foreach (var field in type.Fields)
            {
                ProcessMember(field, rules, stack);
            }
        }
예제 #35
0
 public static bool CanShow(TypeDef type) => type != null;