public static List<MethodDef> FindAll(ModuleDefMD module) { var list = new List<MethodDef>(); foreach (var type in module.GetTypes()) { foreach (var method in type.Methods) { if (IsInvalidMethod(method)) list.Add(method); } } return list; }
public static List<MethodDef> Find(ModuleDefMD module, IEnumerable<MethodDef> notInlinedMethods) { var notInlinedMethodsDict = new Dictionary<MethodDef, bool>(); foreach (var method in notInlinedMethods) notInlinedMethodsDict[method] = true; var inlinedMethods = new List<MethodDef>(); foreach (var type in module.GetTypes()) { foreach (var method in type.Methods) { if (!notInlinedMethodsDict.ContainsKey(method) && CanInline(method)) inlinedMethods.Add(method); } } return inlinedMethods; }
public static void Execute(ModuleDefMD module) { cctor = module.GlobalType.FindStaticConstructor(); Dictionary<FieldDef, Tuple<byte[], int>> fields = new Dictionary<FieldDef,Tuple<byte[], int>>(); List<byte> data = new List<byte>(); int count = 0; foreach (var method in module.GetTypes().SelectMany(type => type.Methods)) { if (method.HasBody) { List<Instruction> stringInstr = method.Body.Instructions.Where(instr => instr.OpCode == OpCodes.Ldstr).ToList(); for (int i = 0; i < stringInstr.Count; i++) { byte[] stringByte = Encoding.UTF8.GetBytes(stringInstr[i].Operand as string); data.AddRange(stringByte); FieldDef field = CreateField(module); fields.Add(field, Tuple.Create(stringByte, count)); method.DeclaringType.Fields.Add(field); stringInstr[i].OpCode = OpCodes.Ldsfld; stringInstr[i].Operand = field; count++; } } } staticFields = fields; data = Encrypt(data.ToArray()).ToList(); var dataType = new TypeDefUser("", "", module.CorLibTypes.GetTypeRef("System", "ValueType")); RenameTask.Rename(dataType); dataType.Layout = TypeAttributes.ExplicitLayout; dataType.Visibility = TypeAttributes.NestedPrivate; dataType.IsSealed = true; dataType.ClassLayout = new ClassLayoutUser(1, (uint)data.Count); module.GlobalType.NestedTypes.Add(dataType); var dataField = new FieldDefUser("", new FieldSig(dataType.ToTypeSig())) { IsStatic = true, HasFieldRVA = true, InitialValue = data.ToArray(), Access = FieldAttributes.CompilerControlled }; module.GlobalType.Fields.Add(dataField); GlobalDataField = dataField; RenameTask.Rename(dataField); NETUtils.listener.OnWriterEvent += OnWriterEvent; }
public static void Execute(ModuleDefMD module) { int key = rand.Next(97, 122); /* rand.GetBytes(byteKey); var dataType = new TypeDefUser(module.GlobalType.Namespace, "", module.CorLibTypes.GetTypeRef("System", "ValueType")); RenameTask.Rename(dataType); dataType.Layout = TypeAttributes.ExplicitLayout; dataType.Visibility = TypeAttributes.NestedPrivate; dataType.IsSealed = true; dataType.ClassLayout = new ClassLayoutUser(1, (uint)byteKey.Length); module.GlobalType.NestedTypes.Add(dataType); var dataField = new FieldDefUser("", new FieldSig(dataType.ToTypeSig())) { IsStatic = true, HasFieldRVA = true, InitialValue = byteKey, Access = FieldAttributes.CompilerControlled }; module.GlobalType.Fields.Add(dataField); RenameTask.Rename(dataField);*/ TypeDef stringInjType = NETUtils.ImportType(typeof(StringEncInj)); MethodDef stringDecMeth = NETUtils.GetMethodByName(stringInjType, "StringDec"); stringDecMeth.DeclaringType = null; stringDecMeth.Body.Instructions[13].OpCode = OpCodes.Ldc_I4; stringDecMeth.Body.Instructions[13].Operand = key; RenameTask.Rename(stringDecMeth, true); TypeDef cctor = module.GlobalType; cctor.Methods.Add(stringDecMeth); foreach (var method in module.GetTypes().SelectMany(type => type.Methods)) { if (method != stringDecMeth && method.HasBody) { List<Instruction> stringInstr = method.Body.Instructions.Where(instr => instr.OpCode == OpCodes.Ldstr).ToList(); for (int i = 0; i < stringInstr.Count; i++) { int index = method.Body.Instructions.IndexOf(stringInstr[i]); stringInstr[i].Operand = Ecrypt((string)stringInstr[i].Operand,key); method.Body.Instructions.Insert(index + 1, Instruction.Create(OpCodes.Call, stringDecMeth)); } } } }
/// <summary> /// Weaves the specified module definition. /// </summary> /// <param name="moduleDefinition">The module definition.</param> public bool Weave(ModuleDefMD moduleDefinition) { var auditTimer = new AuditTimer(); try { // sanity check auditTimer.NewZone("Types import"); // context var context = CreateWeavingContext(moduleDefinition); if (context.AdviceInterfaceType == null) { Logging.WriteWarning("IAdvice interface not found here (not referenced means not used), exiting"); return(false); } // runtime check auditTimer.NewZone("Runtime check"); var targetFramework = GetTargetFramework(moduleDefinition); InjectAsPrivate = targetFramework.Silverlight == null && targetFramework.WindowsPhone == null; // weave methods (they can be property-related, too) auditTimer.NewZone("Weavable methods detection"); Func <MarkedNode, bool> isWeavable = n => IsWeavable(n) && !IsFromComputerGeneratedType(n); var weavingAdvicesMethods = GetMarkedMethods(moduleDefinition, context.WeavingAdviceInterfaceType, context).Where(isWeavable).ToArray(); var weavableMethods = GetMarkedMethods(moduleDefinition, context.AdviceInterfaceType, context).Where(isWeavable).ToArray(); auditTimer.NewZone("Abstract targets"); var generatedFieldsToBeRemoved = new List <FieldDef>(); var methodsWithAbstractTarget = weavableMethods.Where(m => m.AbstractTarget).ToArray(); if (methodsWithAbstractTarget.Length > 0) { generatedFieldsToBeRemoved.AddRange(GetRemovableFields(methodsWithAbstractTarget, context)); foreach (var fieldReference in generatedFieldsToBeRemoved) { Logging.WriteDebug("Field {0} to be removed", fieldReference.FullName); } } auditTimer.NewZone("Methods weaving advice"); weavingAdvicesMethods.ForAll(i => RunWeavingAdvices(i, context)); auditTimer.NewZone("Methods weaving"); weavableMethods.ForAll(m => WeaveMethod(moduleDefinition, m, context)); auditTimer.NewZone("Weavable interfaces detection"); var weavableInterfaces = GetAdviceHandledInterfaces(moduleDefinition).Union(GetDynamicHandledInterfaces(moduleDefinition)).ToArray(); auditTimer.NewZone("Interface methods weaving"); weavableInterfaces.ForAll(i => WeaveInterface(moduleDefinition, i, context)); // and then, the info advices auditTimer.NewZone("Info advices weaving"); var infoAdviceInterface = TypeResolver.Resolve(moduleDefinition, typeof(IInfoAdvice)); moduleDefinition.GetTypes().ForAll(t => WeaveInfoAdvices(moduleDefinition, t, infoAdviceInterface, context)); auditTimer.NewZone("Abstract targets cleanup"); foreach (var generatedFieldToBeRemoved in generatedFieldsToBeRemoved) { generatedFieldToBeRemoved.DeclaringType.Fields.Remove(generatedFieldToBeRemoved); } auditTimer.LastZone(); var report = auditTimer.GetReport(); var maxLength = report.Keys.Max(k => k.Length); Logging.WriteDebug("--- Timings --------------------------"); foreach (var reportPart in report) { Logging.WriteDebug("{0} : {1}ms", reportPart.Key.PadRight(maxLength), (int)reportPart.Value.TotalMilliseconds); } Logging.WriteDebug("--------------------------------------"); Logging.Write("MrAdvice {3} weaved module '{0}' (targeting framework {2}) in {1}ms", moduleDefinition.Assembly.FullName, (int)report.Sum(r => r.Value.TotalMilliseconds), targetFramework.ToString(), Product.Version); return(true); } catch (Exception e) { Logging.WriteError("Internal error during {0}: {1}", auditTimer.CurrentZoneName, e); Logging.WriteError("Please complain, whine, cry, yell at https://github.com/ArxOne/MrAdvice/issues/new"); return(false); } }