示例#1
0
        internal override void ProcessOperand(TypeService service, MethodDef method, IList <Instruction> body, ref int index, MemberRef operand)
        {
            Debug.Assert(service != null, $"{nameof(service)} != null");
            Debug.Assert(method != null, $"{nameof(method)} != null");
            Debug.Assert(body != null, $"{nameof(body)} != null");
            Debug.Assert(operand != null, $"{nameof(operand)} != null");
            Debug.Assert(index >= 0, $"{nameof(index)} >= 0");
            Debug.Assert(index < body.Count, $"{nameof(index)} < {nameof(body)}.Count");

            var current = service.GetItem(method);

            if (operand.MethodSig == null)
            {
                return;
            }

            if (operand.MethodSig.Params.Count > 0 || body[index].OpCode != OpCodes.Newobj)
            {
                return;
            }

            ModuleDef mod = method.Module;

            var corlibType     = mod.CorLibTypes.GetTypeRef("System", "Type").ResolveThrow();
            var gettype        = corlibType.FindMethod("GetTypeFromHandle");
            var createInstance = mod.CorLibTypes.GetTypeRef("System", "Activator").ResolveThrow()
                                 .FindMethod("CreateInstance", MethodSig.CreateStatic(mod.CorLibTypes.Object, corlibType.ToTypeSig()));

            TypeSig sig = null;

            if (operand.Class is TypeRef typeRef)
            {
                sig = typeRef.ToTypeSig();
            }

            if (operand.Class is TypeSpec typeSpec)
            {
                sig = typeSpec.ToTypeSig();
            }

            if (sig != null)
            {
                body[index].OpCode = OpCodes.Ldtoken;

                var          gen         = current?.GetGeneric(sig);
                TypeSpecUser newTypeSpec = null;
                if (gen != null)
                {
                    newTypeSpec = new TypeSpecUser(new GenericMVar(gen.Number));
                }
                else
                {
                    newTypeSpec = new TypeSpecUser(sig);
                }
                body[index].Operand = newTypeSpec;

                body.Insert(++index, Instruction.Create(OpCodes.Call, mod.Import(gettype)));
                body.Insert(++index, Instruction.Create(OpCodes.Call, mod.Import(createInstance)));
            }
        }
示例#2
0
 public InterpreterStubLinkerCore(ModuleDef module)
 {
     _module            = module;
     _type              = _module.CorLibTypes.GetTypeRef("System", "Type");
     _getTypeFromHandle = _module.Import(typeof(Type).GetMethod("GetTypeFromHandle"));
     _dispatch          = _module.Import(typeof(InterpreterStub).GetMethod("Dispatch"));
     _moduleId          = InterpreterStub.AllocateModuleId();
 }
示例#3
0
        protected override ITypeDefOrRef TryRelocateTypeRef(TypeRef typeRef)
        {
            if (typeRef.DefinitionAssembly.IsCorLib())
            {
                return(null);
            }
            var importedTypeRef = _moduleDef.Import(typeRef);

            return(importedTypeRef);
        }
        private MethodDef CreateFactoryMethodNoParameters(ITypeService service, ModuleDef module)
        {
            var instancevar = new GenericParamUser(0, GenericParamAttributes.NoSpecialConstraint, "t");
            var mvar        = new GenericMVar(0);
            var typeSpec    = new TypeSpecUser(mvar);

            var local    = new Local(mvar);
            var rtHandle = new Local(module.Import(typeof(RuntimeTypeHandle)).ToTypeSig());

            var method = new MethodDefUser("create", new MethodSig(CallingConvention.Default, 1, mvar), MethodAttributes.Static);

            method.GenericParameters.Add(instancevar);


            var gettype      = typeof(Type).GetMethod("GetTypeFromHandle");
            var comparetypes = typeof(Type).GetMethod("op_Equality");


            var i = new List <Instruction>();

            i.Add(Instruction.Create(OpCodes.Ldtoken, typeSpec));
            i.Add(Instruction.Create(OpCodes.Call, module.Import(gettype)));
            i.Add(Instruction.Create(OpCodes.Stloc, rtHandle));


            foreach (var mr in ObjectCreationRef)
            {
                Instruction endjump = Instruction.Create(OpCodes.Nop);

                i.Add(Instruction.Create(OpCodes.Ldloc, rtHandle));

                i.Add(Instruction.Create(OpCodes.Ldtoken, mr.DeclaringType));
                i.Add(Instruction.Create(OpCodes.Call, module.Import(gettype)));

                i.Add(Instruction.Create(OpCodes.Call, module.Import(comparetypes)));
                i.Add(Instruction.Create(OpCodes.Brfalse_S, endjump));

                i.Add(Instruction.Create(OpCodes.Newobj, mr));
                i.Add(Instruction.Create(OpCodes.Ret));

                i.Add(endjump);
            }

            i.Add(Instruction.Create(OpCodes.Ldloca_S, local));
            i.Add(Instruction.Create(OpCodes.Initobj, typeSpec));
            i.Add(Instruction.Create(OpCodes.Ldloc, local));
            i.Add(Instruction.Create(OpCodes.Ret));


            method.Body = new CilBody(true, i, new ExceptionHandler[0], new Local[] { local, rtHandle });
            return(method);
        }
示例#5
0
        public static IMethod ImportMethod(this ModuleDef module, Type declaringType, string methodName,
                                           BindingFlags bindingFlags = BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance |
                                           BindingFlags.Static,
                                           params Type[] parameterTypes)
        {
            var candidateMethods      = declaringType.GetMethods(bindingFlags).Where(m => m.Name == methodName);
            var currentParameterTypes = (parameterTypes ?? new Type[0]).ToArray();

            bool HasMatchingParameters(IReadOnlyCollection <Type> setA, IReadOnlyList <Type> setB)
            {
                if (setA?.Count != setB?.Count)
                {
                    return(false);
                }

                if (setA == null)
                {
                    return(false);
                }

                return(!setA.Where((t, i) => t != setB[i]).Any());
            }

            var targetMethod = candidateMethods.First(m =>
                                                      HasMatchingParameters(currentParameterTypes,
                                                                            m.GetParameters().Select(p => p.ParameterType).ToArray()));

            return(module.Import(targetMethod));
        }
示例#6
0
文件: Utils.cs 项目: dovanduy/Origami
        //Taken from ConfuserEx (Compressor)
        private static void ImportAssemblyTypeReferences(ModuleDef originModule, ModuleDef stubModule)
        {
            var assembly = stubModule.Assembly;

            foreach (var ca in assembly.CustomAttributes.Where(ca => ca.AttributeType.Scope == originModule))
            {
                ca.Constructor = (ICustomAttributeType)stubModule.Import(ca.Constructor);
            }
            foreach (var ca in assembly.DeclSecurities.SelectMany(declSec => declSec.CustomAttributes))
            {
                if (ca.AttributeType.Scope == originModule)
                {
                    ca.Constructor = (ICustomAttributeType)stubModule.Import(ca.Constructor);
                }
            }
        }
        void InjectData(ModuleDef stubModule, MethodDef method, byte[] data)
        {
            var dataType = new TypeDefUser("", "DataType", stubModule.CorLibTypes.GetTypeRef("System", "ValueType"));

            dataType.Layout      = TypeAttributes.ExplicitLayout;
            dataType.Visibility  = TypeAttributes.NestedPrivate;
            dataType.IsSealed    = true;
            dataType.ClassLayout = new ClassLayoutUser(1, (uint)data.Length);
            stubModule.GlobalType.NestedTypes.Add(dataType);

            var dataField = new FieldDefUser("DataField", new FieldSig(dataType.ToTypeSig()))
            {
                IsStatic     = true,
                HasFieldRVA  = true,
                InitialValue = data,
                Access       = FieldAttributes.CompilerControlled
            };

            stubModule.GlobalType.Fields.Add(dataField);

            MutationHelper.ReplacePlaceholder(method, arg => {
                var repl = new List <Instruction>();
                repl.AddRange(arg);
                repl.Add(Instruction.Create(OpCodes.Dup));
                repl.Add(Instruction.Create(OpCodes.Ldtoken, dataField));
                repl.Add(Instruction.Create(OpCodes.Call, stubModule.Import(
                                                typeof(RuntimeHelpers).GetMethod("InitializeArray"))));
                return(repl.ToArray());
            });
        }
示例#8
0
        /// <summary>
        /// Embeds the loader.
        /// </summary>
        /// <param name="moduleDef">The module definition.</param>
        /// <param name="taskAssemblyPath">The task assembly path.</param>
        private void EmbedLoader(ModuleDef moduleDef, string taskAssemblyPath)
        {
            const string loaderTypeName = "\u2302";

            // blobbing twice? Don't.
            if (moduleDef.TypeExistsNormal(loaderTypeName))
            {
                return;
            }

            var assemblyLoaderTypeName = typeof(Loader).FullName;
            // import Loader type from this assembly
            var thisModuleDef = ModuleDefMD.Load(taskAssemblyPath);
            var loaderType    = thisModuleDef.Find(assemblyLoaderTypeName, true);

            thisModuleDef.Types.Remove(loaderType);
            loaderType.Name      = loaderTypeName;
            loaderType.Namespace = null;
            moduleDef.Types.Add(loaderType);
            // ensure it is called from module cctor
            var moduleType             = moduleDef.Find("<Module>", true);
            var cctor                  = moduleType.FindOrCreateStaticConstructor();
            var loaderInitializeMethod = loaderType.FindMethod(nameof(Loader.Setup));

            cctor.Body.Instructions.Insert(0, Instruction.Create(OpCodes.Call, moduleDef.Import(loaderInitializeMethod)));
        }
示例#9
0
        private List <Instruction> GenerateBody(ArithmeticVT arithmeticVTs)
        {
            List <Instruction> instructions = new List <Instruction>();

            if (IsArithmetic(arithmeticVTs.GetArithmetic()))
            {
                instructions.Add(new Instruction(OpCodes.Ldc_R8, arithmeticVTs.GetValue().GetX()));
                instructions.Add(new Instruction(OpCodes.Ldc_R8, arithmeticVTs.GetValue().GetY()));

                if (arithmeticVTs.GetToken().GetOperand() != null)
                {
                    instructions.Add(new Instruction(OpCodes.Call, arithmeticVTs.GetToken().GetOperand()));
                }
                instructions.Add(new Instruction(arithmeticVTs.GetToken().GetOpCode()));
                instructions.Add(new Instruction(OpCodes.Call, moduleDef1.Import(typeof(Convert).GetMethod("ToInt32", new Type[] { typeof(double) }))));
                //instructions.Add(new Instruction(OpCodes.Conv_I4));
            }
            else if (IsXor(arithmeticVTs.GetArithmetic()))
            {
                instructions.Add(new Instruction(OpCodes.Ldc_I4, (int)arithmeticVTs.GetValue().GetX()));
                instructions.Add(new Instruction(OpCodes.Ldc_I4, (int)arithmeticVTs.GetValue().GetY()));
                instructions.Add(new Instruction(arithmeticVTs.GetToken().GetOpCode()));
                instructions.Add(new Instruction(OpCodes.Conv_I4));
            }
            return(instructions);
        }
示例#10
0
        public static IMDTokenProvider Import(this ModuleDef module, IMDTokenProvider token)
        {
            switch (token)
            {
            case IField field:
                return(module.Import(field));

            case IMethod method:
                return(module.Import(method));

            case IType type:
                return(module.Import(type));

            default:
                throw new ArgumentException("unrecognized token provider type: " + token.GetType());
            }
        }
示例#11
0
        private WeavingContext CreateWeavingContext(ModuleDef moduleDefinition)
        {
            var context = new WeavingContext
            {
                CompilerGeneratedAttributeType     = moduleDefinition.Import(typeof(CompilerGeneratedAttribute)),
                PriorityAttributeType              = TypeResolver.Resolve(moduleDefinition, typeof(PriorityAttribute)),
                AbstractTargetAttributeType        = TypeResolver.Resolve(moduleDefinition, typeof(AbstractTargetAttribute)),
                AdviceInterfaceType                = TypeResolver.Resolve(moduleDefinition, typeof(IAdvice)),
                WeavingAdviceInterfaceType         = TypeResolver.Resolve(moduleDefinition, typeof(IWeavingAdvice)),
                ExecutionPointAttributeDefaultCtor = moduleDefinition.Import(TypeResolver.Resolve(moduleDefinition, typeof(ExecutionPointAttribute))?.FindDefaultConstructor()),
                ExcludePointcutAttributeType       = TypeResolver.Resolve(moduleDefinition, typeof(ExcludePointcutAttribute)),
                IncludePointcutAttributeType       = TypeResolver.Resolve(moduleDefinition, typeof(IncludePointcutAttribute)),
                ExcludeAdviceAttributeType         = TypeResolver.Resolve(moduleDefinition, typeof(ExcludeAdvicesAttribute)),
                IntroducedFieldType                = TypeResolver.Resolve(moduleDefinition, typeof(IntroducedField <>)),
                SharedIntroducedFieldType          = TypeResolver.Resolve(moduleDefinition, typeof(SharedIntroducedField <>)),
#pragma warning disable 618
                IntroducedFieldsType = TypeResolver.Resolve(moduleDefinition, typeof(IntroducedFieldsRegistry)),
#pragma warning restore 618
            };

            if (context.AdviceInterfaceType is not null)
            {
                if (context.ExecutionPointAttributeDefaultCtor is null)
                {
                    Logging.WriteError("ExecutionPointAttribute default ctor was not found");
                }

                if (context.ExcludePointcutAttributeType is null)
                {
                    Logging.WriteError("ExcludePointcutAttributeType was not found");
                }
                if (context.IncludePointcutAttributeType is null)
                {
                    Logging.WriteError("IncludePointcutAttributeType was not found");
                }
                if (context.ExcludeAdviceAttributeType is null)
                {
                    Logging.WriteError("ExcludeAdviceAttributeType was not found");
                }
            }

            return(context);
        }
示例#12
0
        public static IField ResolveOrImport(this PatchConfiguration patch, ModuleDef module, FieldInfo field)
        {
            if (patch.TryResolve(module, field.ToSignature(), out FieldDef def))
            {
                return(def);
            }
            MemberRef fieldRef = module.Import(field);

            fieldRef.Name = field.GetName();
            return(fieldRef);
        }
示例#13
0
 IEnumerable <(ModuleDef module, ITypeDefOrRef type)> GetAllModules(ModuleDef mod, CancellationToken ct)
 {
     foreach (var doc in Context.DocumentService.GetDocuments())
     {
         if (!(doc.ModuleDef is ModuleDef module))
         {
             continue;
         }
         var typeRef = GetScopeTypeRefInModule(module) ?? module.Import(analyzedType);
         yield return(module, typeRef);
     }
 }
 private static bool SetAssemblyAttribute(ModuleDef moduleDef, Type attributeType, string value)
 {
     var attributeAssemblyFileName = attributeType.Module.FullyQualifiedName;
     using (var attributeModule = ModuleDefMD.Load(attributeAssemblyFileName))
     {
         var attributeTypeRef = moduleDef.Import(attributeType);
         var attributeTypeDef = attributeModule.GetTypes().Single(t => t.FullName == attributeTypeRef.FullName);
         var existingAttribute = moduleDef.Assembly.CustomAttributes.SingleOrDefault(t => t.TypeFullName == attributeTypeDef.FullName);
         if (existingAttribute != null)
         {
             // if it exists and is already initialized with the same value, then no need to change it
             if (((UTF8String)existingAttribute.ConstructorArguments[0].Value).String == value)
                 return false;
             moduleDef.Assembly.CustomAttributes.Remove(existingAttribute);
         }
         var ctor = moduleDef.Import(attributeTypeDef.FindConstructors().Single());
         var stringTypeSig = moduleDef.Import(typeof(string)).ToTypeSig();
         moduleDef.Assembly.CustomAttributes.Add(new CustomAttribute(ctor, new[] { new CAArgument(stringTypeSig, new UTF8String(value)) }));
     }
     return true;
 }
        private static List <Instruction> CreateArrayInitializer(ModuleDef module, ITypeDefOrRef arrayType, int arrayLength, FieldDef dataField)
        {
            var instructions = new List <Instruction> {
                new Instruction(OpCodes.Ldc_I4, arrayLength),
                new Instruction(OpCodes.Newarr, arrayType),
                new Instruction(OpCodes.Dup),
                new Instruction(OpCodes.Ldtoken, dataField),
                new Instruction(OpCodes.Call, module.Import(typeof(RuntimeHelpers).GetMethod("InitializeArray"))),
            };

            return(instructions);
        }
示例#16
0
        private WeavingContext CreateWeavingContext(ModuleDef moduleDefinition)
        {
            var context = new WeavingContext
            {
                CompilerGeneratedAttributeType     = moduleDefinition.Import(typeof(CompilerGeneratedAttribute)),
                PriorityAttributeType              = TypeResolver.Resolve(moduleDefinition, typeof(PriorityAttribute)),
                AbstractTargetAttributeType        = TypeResolver.Resolve(moduleDefinition, typeof(AbstractTargetAttribute)),
                AdviceInterfaceType                = TypeResolver.Resolve(moduleDefinition, typeof(IAdvice)),
                WeavingAdviceInterfaceType         = TypeResolver.Resolve(moduleDefinition, typeof(IWeavingAdvice)),
                ExecutionPointAttributeDefaultCtor = moduleDefinition.Import(TypeResolver.Resolve(moduleDefinition, typeof(ExecutionPointAttribute))?.FindDefaultConstructor()),
                ExcludePointcutAttributeType       = TypeResolver.Resolve(moduleDefinition, typeof(ExcludePointcutAttribute)),
                IncludePointcutAttributeType       = TypeResolver.Resolve(moduleDefinition, typeof(IncludePointcutAttribute)),
                ExcludeAdviceAttributeType         = TypeResolver.Resolve(moduleDefinition, typeof(ExcludeAdvicesAttribute)),
            };

            if (context.AdviceInterfaceType != null)
            {
                if (context.ExecutionPointAttributeDefaultCtor == null)
                {
                    Logging.WriteError("ExecutionPointAttribute default ctor was not found");
                }

                if (context.ExcludePointcutAttributeType == null)
                {
                    Logging.WriteError("ExcludePointcutAttributeType was not found");
                }
                if (context.IncludePointcutAttributeType == null)
                {
                    Logging.WriteError("IncludePointcutAttributeType was not found");
                }
                if (context.ExcludeAdviceAttributeType == null)
                {
                    Logging.WriteError("ExcludeAdviceAttributeType was not found");
                }
            }

            return(context);
        }
示例#17
0
        private static bool SetAssemblyAttribute(ModuleDef moduleDef, Type attributeType, string value)
        {
            var attributeAssemblyFileName = attributeType.Module.FullyQualifiedName;

            using (var attributeModule = ModuleDefMD.Load(attributeAssemblyFileName))
            {
                var attributeTypeRef  = moduleDef.Import(attributeType);
                var attributeTypeDef  = attributeModule.GetTypes().Single(t => t.FullName == attributeTypeRef.FullName);
                var existingAttribute = moduleDef.Assembly.CustomAttributes.SingleOrDefault(t => t.TypeFullName == attributeTypeDef.FullName);
                if (existingAttribute != null)
                {
                    // if it exists and is already initialized with the same value, then no need to change it
                    if (((UTF8String)existingAttribute.ConstructorArguments[0].Value).String == value)
                    {
                        return(false);
                    }
                    moduleDef.Assembly.CustomAttributes.Remove(existingAttribute);
                }
                var ctor          = moduleDef.Import(attributeTypeDef.FindConstructors().Single());
                var stringTypeSig = moduleDef.Import(typeof(string)).ToTypeSig();
                moduleDef.Assembly.CustomAttributes.Add(new CustomAttribute(ctor, new[] { new CAArgument(stringTypeSig, new UTF8String(value)) }));
            }
            return(true);
        }
示例#18
0
            private void Mutate(int i, int sub, int num2, ModuleDef module)
            {
                switch (sub)
                {
                case 1:
                    body.Instructions.Insert(i + 1, Instruction.Create(OpCodes.Sizeof, module.Import(typeof(byte))));
                    body.Instructions.Insert(i + 2, Instruction.Create(OpCodes.Add));
                    return;

                case 2:
                    body.Instructions.Insert(i + 1, Instruction.Create(OpCodes.Sizeof, module.Import(typeof(byte))));
                    body.Instructions.Insert(i + 2, Instruction.Create(OpCodes.Sizeof, module.Import(typeof(byte))));
                    body.Instructions.Insert(i + 3, Instruction.Create(OpCodes.Add));
                    body.Instructions.Insert(i + 4, Instruction.Create(OpCodes.Add));
                    return;

                case 3:
                    body.Instructions.Insert(i + 1, Instruction.Create(OpCodes.Sizeof, module.Import(typeof(int))));
                    body.Instructions.Insert(i + 2, Instruction.Create(OpCodes.Sizeof, module.Import(typeof(byte))));
                    body.Instructions.Insert(i + 3, Instruction.Create(OpCodes.Sub));
                    body.Instructions.Insert(i + 4, Instruction.Create(OpCodes.Add));
                    return;

                case 4:
                    body.Instructions.Insert(i + 1, Instruction.Create(OpCodes.Sizeof, module.Import(typeof(int))));
                    body.Instructions.Insert(i + 2, Instruction.Create(OpCodes.Sizeof, module.Import(typeof(byte))));
                    body.Instructions.Insert(i + 3, Instruction.Create(OpCodes.Sub));
                    body.Instructions.Insert(i + 4, Instruction.Create(OpCodes.Add));
                    body.Instructions.Insert(i + 5, Instruction.Create(OpCodes.Mul, module.Import(typeof(Int32))));
                    return;

                case 5:
                    body.Instructions.Insert(i + 1, Instruction.Create(OpCodes.Sizeof, module.Import(typeof(decimal))));
                    body.Instructions.Insert(i + 2, Instruction.Create(OpCodes.Sizeof, module.Import(typeof(GCCollectionMode))));
                    body.Instructions.Insert(i + 3, Instruction.Create(OpCodes.Sub));
                    body.Instructions.Insert(i + 4, Instruction.Create(OpCodes.Sizeof, module.Import(typeof(int))));
                    body.Instructions.Insert(i + 5, Instruction.Create(OpCodes.Sub));
                    body.Instructions.Insert(i + 6, Instruction.Create(OpCodes.Add));
                    return;

                default:
                    return;
                }
            }
示例#19
0
        public static ITypeDefOrRef ResolveOrImport(this PatchConfiguration patch, ModuleDef module, Type type)
        {
            if (patch.TryResolve(module, type.ToSignature(), out TypeDef def))
            {
                return(def);
            }
            type = AppDomain.CurrentDomain.GetAssemblies().Select(a => a.GetType(type.GetName())).First(t => t != null);
            return(module.Import(type));

            /*string fullName = type.GetName();
             * int nsEnd = fullName.LastIndexOf('.');
             * string ns = null, name = fullName;
             * if (nsEnd >= 0)
             * {
             *  ns = fullName.Substring(0, nsEnd);
             *  name = fullName.Substring(nsEnd + 1);
             * }
             * return new TypeRefUser(module, ns, name, new AssemblyNameInfo(type.Assembly.GetName()).ToAssemblyRef());//new AssemblyRefUser(module, type.Module.Name.Substring(0, type.Module.Name.Length - 4)));*/
        }
示例#20
0
        public static void AddNamedArgument(this NRefactory.CSharp.Attribute attribute, ModuleDef module, Type attrType, Type fieldType, string fieldName, Expression argument)
        {
            var ide = new IdentifierExpression(fieldName);

            if (module != null)
            {
                TypeSig sig = module.CorLibTypes.GetCorLibTypeSig(module.Import(fieldType));
                if (sig == null)
                {
                    var typeRef = module.CorLibTypes.GetTypeRef(fieldType.Namespace, fieldType.Name);
                    sig = fieldType.IsValueType ? (TypeSig) new ValueTypeSig(typeRef) : new ClassSig(typeRef);
                }
                var fr = new MemberRefUser(module, fieldName, new FieldSig(sig), module.CorLibTypes.GetTypeRef(attrType.Namespace, attrType.Name));
                ide.AddAnnotation(fr);
                ide.IdentifierToken.AddAnnotation(fr);
            }

            attribute.Arguments.Add(new AssignmentExpression(ide, argument));
        }
        public void InitializeP(ModuleDef module)
        {
            foreach (var typeDef in module.Types)
            {
                foreach (MethodDef methodDef in typeDef.Methods)
                {
                    methods.Add(methodDef);
                }
            }

            var       seed  = new Random().Next(1, int.MaxValue);
            ModuleDef merge = module;

            string rtName = "KoiVM.Runtime";

            ModuleDefMD rtModule = ModuleDefMD.Load("KoiVM.Runtime.dll");

            rtModule.Assembly.Name = rtName;
            rtModule.Name          = rtName + ".dll";
            var vr = new Virtualizer(seed, false);

            vr.ExportDbgInfo = false;
            vr.DoStackWalk   = false;
            vr.Initialize(rtModule);

            VirtualizerKey = vr;
            MergeKey       = merge;

            vr.CommitRuntime(merge);
            var ctor = typeof(InternalsVisibleToAttribute).GetConstructor(new[] { typeof(string) });

            if (methods.Count > 0)
            {
                var ca = new CustomAttribute((ICustomAttributeType)module.Import(ctor));
                ca.ConstructorArguments.Add(new CAArgument(module.CorLibTypes.String, vr.RuntimeModule.Assembly.Name.String));
                module.Assembly.CustomAttributes.Add(ca);
            }

            MarkPhase(module);
        }
示例#22
0
 // Token: 0x060000AA RID: 170 RVA: 0x00007684 File Offset: 0x00005884
 public static void Brs(ModuleDef md)
 {
     foreach (TypeDef typeDef in md.Types.ToArray <TypeDef>())
     {
         foreach (MethodDef methodDef in typeDef.Methods.ToArray <MethodDef>())
         {
             bool flag = methodDef.HasBody && methodDef.Body.Instructions.Count != 0;
             if (flag)
             {
                 IList <Instruction> instructions = methodDef.Body.Instructions;
                 int num = 0;
                 if (num < instructions.Count)
                 {
                     Instruction instruction  = Instruction.Create(OpCodes.Nop);
                     Instruction instruction2 = OpCodes.Call.ToInstruction(md.Import(typeof(string).GetMethod("IsNullOrEmpty", new Type[]
                     {
                         typeof(string)
                     })));
                 }
             }
         }
     }
 }
示例#23
0
        public static void PushMethod(this ICollection <Instruction> instructions, IMethod method, ModuleDef module)
        {
            var getMethodFromHandle = typeof(MethodBase).GetMethods(BindingFlags.Public | BindingFlags.Static).First(
                m =>
            {
                var parameters = m.GetParameters();
                if (parameters.Length != 2)
                {
                    return(false);
                }

                var parameterTypes = parameters.Select(p => p.ParameterType).ToArray();

                return(parameterTypes[0] == typeof(RuntimeMethodHandle) &&
                       parameterTypes[1] == typeof(RuntimeTypeHandle));
            });

            var importedGetMethodFromHandleMethod = module.Import(getMethodFromHandle);
            var declaringType = method.DeclaringType;

            instructions.Emit(OpCodes.Ldtoken, method);
            instructions.Emit(OpCodes.Ldtoken, declaringType);
            instructions.Emit(OpCodes.Call, importedGetMethodFromHandleMethod);
        }
        private static void PatchReferences(ModuleDef src, ModuleDef dst)
        {
            foreach (var type in src.Types)
            {
                foreach (var method in type.Methods)
                {
                    if (!method.HasBody)
                    {
                        continue;
                    }

                    foreach (var instr in method.Body.Instructions)
                    {
                        if (instr.Operand is IMemberRef && ((IMemberRef)instr.Operand).DeclaringType != null &&
                            ((IMemberRef)instr.Operand).DeclaringType.Module == null)
                        {
                            var memberRef = (IMemberRef)instr.Operand;
                            var declType  = src.Import(dst.Find(memberRef.DeclaringType.FullName, false));
                            if (memberRef.IsField)
                            {
                                memberRef = new MemberRefUser(src, memberRef.Name, ((IField)memberRef).FieldSig, declType);
                            }
                            else if (memberRef.IsMethod)
                            {
                                memberRef = new MemberRefUser(src, memberRef.Name, ((IMethod)memberRef).MethodSig, declType);
                            }
                            else
                            {
                                throw new NotSupportedException();
                            }
                            instr.Operand = memberRef;
                        }
                    }
                }
            }
        }
示例#25
0
        /// <summary>
        /// Weaves the interface.
        /// What we do here is:
        /// - creating a class (wich is named after the interface name)
        /// - this class implements all interface members
        /// - all members invoke Invocation.ProcessInterfaceMethod
        /// </summary>
        /// <param name="moduleDefinition">The module definition.</param>
        /// <param name="interfaceType">Type of the interface.</param>
        /// <param name="context">The context.</param>
        private void WeaveInterface(ModuleDef moduleDefinition, TypeDef interfaceType, WeavingContext context)
        {
            Logging.WriteDebug("Weaving interface '{0}'", interfaceType.FullName);
            TypeDef implementationType;
            TypeDef advisedInterfaceType;

            lock (moduleDefinition)
            {
                // ensure we're creating the interface only once
                var implementationTypeName      = GetImplementationTypeName(interfaceType.Name);
                var implementationTypeNamespace = interfaceType.Namespace;
                if (moduleDefinition.GetTypes().Any(t => t.Namespace == implementationTypeNamespace && t.Name == implementationTypeName))
                {
                    return;
                }

                // now, create the implementation type
                var typeAttributes = (InjectAsPrivate ? TypeAttributes.NotPublic : TypeAttributes.Public) | TypeAttributes.Class |
                                     TypeAttributes.BeforeFieldInit;
                advisedInterfaceType = TypeResolver.Resolve(moduleDefinition, typeof(AdvisedInterface));
                // TODO: this should work using TypeImporter.Import
                var advisedInterfaceTypeReference = moduleDefinition.Import(advisedInterfaceType);
                implementationType =
                    new TypeDefUser(implementationTypeNamespace, implementationTypeName, advisedInterfaceTypeReference)
                {
                    Attributes = typeAttributes
                };
                implementationType.Interfaces.Add(new InterfaceImplUser(interfaceType));

                lock (moduleDefinition)
                    moduleDefinition.Types.Add(implementationType);
            }

            // create empty .ctor. This .NET mofo wants it!
            var baseEmptyConstructor = moduleDefinition.SafeImport(advisedInterfaceType.FindConstructors().Single());
            const MethodAttributes ctorAttributes = MethodAttributes.Public | MethodAttributes.HideBySig | MethodAttributes.SpecialName |
                                                    MethodAttributes.RTSpecialName;
            var method = new MethodDefUser(".ctor", baseEmptyConstructor.MethodSig, ctorAttributes);

            method.Body = new CilBody();
            method.Body.Instructions.Add(Instruction.Create(OpCodes.Ldarg_0));
            method.Body.Instructions.Add(Instruction.Create(OpCodes.Call, baseEmptyConstructor));
            method.Body.Instructions.Add(Instruction.Create(OpCodes.Ret));
            implementationType.Methods.Add(method);

            // create implementation methods
            foreach (var interfaceMethod in interfaceType.Methods.Where(m => !m.IsSpecialName))
            {
                WeaveInterfaceMethod(interfaceMethod, implementationType, true, context);
            }

            // create implementation properties
            foreach (var interfaceProperty in interfaceType.Properties)
            {
                var implementationProperty = new PropertyDefUser(interfaceProperty.Name, interfaceProperty.PropertySig);
                implementationType.Properties.Add(implementationProperty);
                if (interfaceProperty.GetMethod != null)
                {
                    implementationProperty.GetMethod = WeaveInterfaceMethod(interfaceProperty.GetMethod, implementationType, InjectAsPrivate, context);
                }
                if (interfaceProperty.SetMethod != null)
                {
                    implementationProperty.SetMethod = WeaveInterfaceMethod(interfaceProperty.SetMethod, implementationType, InjectAsPrivate, context);
                }
            }

            // create implementation events
            foreach (var interfaceEvent in interfaceType.Events)
            {
                var implementationEvent = new EventDefUser(interfaceEvent.Name, interfaceEvent.EventType);
                implementationType.Events.Add(implementationEvent);
                if (interfaceEvent.AddMethod != null)
                {
                    implementationEvent.AddMethod = WeaveInterfaceMethod(interfaceEvent.AddMethod, implementationType, InjectAsPrivate, context);
                }
                if (interfaceEvent.RemoveMethod != null)
                {
                    implementationEvent.RemoveMethod = WeaveInterfaceMethod(interfaceEvent.RemoveMethod, implementationType, InjectAsPrivate, context);
                }
            }
        }
示例#26
0
        // Token: 0x0600033E RID: 830 RVA: 0x00071B9C File Offset: 0x0006FD9C
        private void Start(int i, int sub, int calculado, ModuleDef module, MethodDef method)
        {
            switch (sub)
            {
            case 1:
            {
                Local local  = new Local(module.CorLibTypes.Object);
                Local local2 = new Local(module.CorLibTypes.Object);
                Local local3 = new Local(module.CorLibTypes.Object);
                Local local4 = new Local(module.CorLibTypes.Object);
                method.Body.Variables.Add(local);
                method.Body.Variables.Add(local2);
                method.Body.Variables.Add(local3);
                method.Body.Variables.Add(local4);
                this.body.Instructions.Insert(i + 1, new Instruction(OpCodes.Sizeof, module.Import(typeof(GCNotificationStatus))));
                this.body.Instructions.Insert(i + 2, new Instruction(OpCodes.Stloc_S, local));
                this.body.Instructions.Insert(i + 3, new Instruction(OpCodes.Ldloc_S, local));
                this.body.Instructions.Insert(i + 4, OpCodes.Add.ToInstruction());
                this.body.Instructions.Insert(i + 5, new Instruction(OpCodes.Sizeof, module.Import(typeof(sbyte))));
                this.body.Instructions.Insert(i + 6, new Instruction(OpCodes.Stloc_S, local2));
                this.body.Instructions.Insert(i + 7, new Instruction(OpCodes.Ldloc_S, local2));
                this.body.Instructions.Insert(i + 8, OpCodes.Sub.ToInstruction());
                this.body.Instructions.Insert(i + 9, new Instruction(OpCodes.Sizeof, module.Import(typeof(sbyte))));
                this.body.Instructions.Insert(i + 10, new Instruction(OpCodes.Stloc_S, local3));
                this.body.Instructions.Insert(i + 11, new Instruction(OpCodes.Ldloc_S, local3));
                this.body.Instructions.Insert(i + 12, OpCodes.Sub.ToInstruction());
                this.body.Instructions.Insert(i + 13, new Instruction(OpCodes.Sizeof, module.Import(typeof(sbyte))));
                this.body.Instructions.Insert(i + 14, new Instruction(OpCodes.Stloc_S, local4));
                this.body.Instructions.Insert(i + 15, new Instruction(OpCodes.Ldloc_S, local4));
                this.body.Instructions.Insert(i + 16, OpCodes.Sub.ToInstruction());
                break;
            }

            case 2:
            {
                Local local = new Local(module.CorLibTypes.Object);
                method.Body.Variables.Add(local);
                this.body.Instructions.Insert(i + 1, new Instruction(OpCodes.Sizeof, module.Import(typeof(char))));
                this.body.Instructions.Insert(i + 2, new Instruction(OpCodes.Stloc_S, local));
                this.body.Instructions.Insert(i + 3, new Instruction(OpCodes.Ldloc_S, local));
                this.body.Instructions.Insert(i + 4, OpCodes.Add.ToInstruction());
                break;
            }

            case 3:
            {
                Local local  = new Local(module.CorLibTypes.Object);
                Local local2 = new Local(module.CorLibTypes.Object);
                method.Body.Variables.Add(local);
                method.Body.Variables.Add(local2);
                this.body.Instructions.Insert(i + 1, Instruction.Create(OpCodes.Sizeof, module.Import(typeof(int))));
                this.body.Instructions.Insert(i + 2, new Instruction(OpCodes.Stloc_S, local));
                this.body.Instructions.Insert(i + 3, new Instruction(OpCodes.Ldloc_S, local));
                this.body.Instructions.Insert(i + 4, Instruction.Create(OpCodes.Sizeof, module.Import(typeof(byte))));
                this.body.Instructions.Insert(i + 5, new Instruction(OpCodes.Stloc_S, local2));
                this.body.Instructions.Insert(i + 6, new Instruction(OpCodes.Ldloc_S, local2));
                this.body.Instructions.Insert(i + 7, Instruction.Create(OpCodes.Sub));
                this.body.Instructions.Insert(i + 8, Instruction.Create(OpCodes.Add));
                break;
            }

            case 4:
            {
                Local local  = new Local(module.CorLibTypes.Object);
                Local local2 = new Local(module.CorLibTypes.Object);
                Local local3 = new Local(module.CorLibTypes.Object);
                Local local4 = new Local(module.CorLibTypes.Object);
                method.Body.Variables.Add(local);
                method.Body.Variables.Add(local2);
                method.Body.Variables.Add(local3);
                method.Body.Variables.Add(local4);
                this.body.Instructions.Insert(i + 1, Instruction.Create(OpCodes.Add));
                this.body.Instructions.Insert(i + 2, Instruction.Create(OpCodes.Sizeof, module.Import(typeof(decimal))));
                this.body.Instructions.Insert(i + 3, new Instruction(OpCodes.Stloc_S, local));
                this.body.Instructions.Insert(i + 4, new Instruction(OpCodes.Ldloc_S, local));
                this.body.Instructions.Insert(i + 5, Instruction.Create(OpCodes.Sizeof, module.Import(typeof(GCCollectionMode))));
                this.body.Instructions.Insert(i + 6, new Instruction(OpCodes.Stloc_S, local2));
                this.body.Instructions.Insert(i + 7, new Instruction(OpCodes.Ldloc_S, local2));
                this.body.Instructions.Insert(i + 8, Instruction.Create(OpCodes.Sub));
                this.body.Instructions.Insert(i + 9, Instruction.Create(OpCodes.Sizeof, module.Import(typeof(int))));
                this.body.Instructions.Insert(i + 10, new Instruction(OpCodes.Stloc_S, local3));
                this.body.Instructions.Insert(i + 11, new Instruction(OpCodes.Ldloc_S, local3));
                this.body.Instructions.Insert(i + 12, Instruction.Create(OpCodes.Sizeof, module.Import(typeof(byte))));
                this.body.Instructions.Insert(i + 13, new Instruction(OpCodes.Stloc_S, local4));
                this.body.Instructions.Insert(i + 14, new Instruction(OpCodes.Ldloc_S, local4));
                this.body.Instructions.Insert(i + 15, Instruction.Create(OpCodes.Sizeof, module.Import(typeof(byte))));
                this.body.Instructions.Insert(i + 16, new Instruction(OpCodes.Stloc_S, local));
                this.body.Instructions.Insert(i + 17, new Instruction(OpCodes.Ldloc_S, local));
                this.body.Instructions.Insert(i + 18, Instruction.Create(OpCodes.Sub));
                this.body.Instructions.Insert(i + 19, Instruction.Create(OpCodes.Sizeof, module.Import(typeof(byte))));
                this.body.Instructions.Insert(i + 20, new Instruction(OpCodes.Stloc_S, local2));
                this.body.Instructions.Insert(i + 21, new Instruction(OpCodes.Ldloc_S, local2));
                this.body.Instructions.Insert(i + 22, Instruction.Create(OpCodes.Sizeof, module.Import(typeof(byte))));
                this.body.Instructions.Insert(i + 23, new Instruction(OpCodes.Stloc_S, local2));
                this.body.Instructions.Insert(i + 24, new Instruction(OpCodes.Ldloc_S, local2));
                this.body.Instructions.Insert(i + 25, Instruction.Create(OpCodes.Add));
                break;
            }

            case 5:
            {
                Local local  = new Local(module.CorLibTypes.Object);
                Local local2 = new Local(module.CorLibTypes.Object);
                method.Body.Variables.Add(local);
                method.Body.Variables.Add(local2);
                this.body.Instructions.Insert(i + 1, new Instruction(OpCodes.Sizeof, module.Import(typeof(EnvironmentVariableTarget))));
                this.body.Instructions.Insert(i + 2, Instruction.Create(OpCodes.Stloc_S, local));
                this.body.Instructions.Insert(i + 3, Instruction.Create(OpCodes.Ldloc_S, local));
                this.body.Instructions.Insert(i + 4, OpCodes.Add.ToInstruction());
                this.body.Instructions.Insert(i + 5, new Instruction(OpCodes.Sizeof, module.Import(typeof(sbyte))));
                this.body.Instructions.Insert(i + 6, Instruction.Create(OpCodes.Stloc_S, local2));
                this.body.Instructions.Insert(i + 7, Instruction.Create(OpCodes.Ldloc_S, local2));
                this.body.Instructions.Insert(i + 9, OpCodes.Add.ToInstruction());
                break;
            }
            }
        }
示例#27
0
        public static void DefType(ref ModuleDef moduleDef)
        {
            var classUser = new TypeDefUser("MadnessNET.Protector", "Deshifrator", moduleDef.CorLibTypes.Object.TypeDefOrRef);

            classUser.Attributes = TypeAttributes.Public |
                                   TypeAttributes.Abstract |
                                   TypeAttributes.Sealed |
                                   TypeAttributes.Class;

            moduleDef.Types.Add(classUser);

            /*
             * var field1 = new FieldDefUser("MyField",
             *  new FieldSig(moduleDef.CorLibTypes.Int32),
             *  FieldAttributes.Public |
             *  FieldAttributes.Static);
             * classUser.Fields.Add(field1);
             */

            var methodImplFlags = MethodImplAttributes.IL |
                                  MethodImplAttributes.Managed;

            var methodFlags = MethodAttributes.Public |
                              MethodAttributes.Static;

            var decryptMethod = new MethodDefUser(
                "StringDecryptor",
                MethodSig.CreateStatic(
                    moduleDef.CorLibTypes.String,
                    moduleDef.CorLibTypes.String),
                methodImplFlags,
                methodFlags);

            classUser.Methods.Add(decryptMethod);

            MethodDef method = classUser.FindMethod("StringDecryptor");

            method.MethodBody = new CilBody();

            Importer      importer     = new Importer(moduleDef);
            ITypeDefOrRef byteArrayRef = importer.Import(typeof(System.Byte[]));

            Instruction instruction_Ldloc_1 = Instruction.Create(OpCodes.Ldloc_1);
            Instruction instruction_Ldloc_0 = Instruction.Create(OpCodes.Ldloc_0);

            method.Body.Variables.Locals.Add(new Local(byteArrayRef.ToTypeSig()));
            method.Body.Variables.Locals.Add(new Local(method.Module.CorLibTypes.Int32));

            method.Body.Instructions.Add(new Instruction(OpCodes.Call, moduleDef.Import(typeof(System.Text.Encoding).GetMethod("get_ASCII", new Type[] { }))));
            method.Body.Instructions.Add(new Instruction(OpCodes.Ldarg_0));
            method.Body.Instructions.Add(new Instruction(OpCodes.Callvirt, moduleDef.Import(typeof(System.Text.Encoding).GetMethod("GetBytes", new Type[] { typeof(string) }))));
            method.Body.Instructions.Add(new Instruction(OpCodes.Stloc_0));
            method.Body.Instructions.Add(new Instruction(OpCodes.Ldc_I4_0));
            method.Body.Instructions.Add(new Instruction(OpCodes.Stloc_1));
            method.Body.Instructions.Add(new Instruction(OpCodes.Br_S, instruction_Ldloc_1));
            method.Body.Instructions.Add(instruction_Ldloc_0);
            method.Body.Instructions.Add(new Instruction(OpCodes.Ldloc_1));
            method.Body.Instructions.Add(new Instruction(OpCodes.Ldelema, moduleDef.Import(typeof(System.Byte))));
            method.Body.Instructions.Add(new Instruction(OpCodes.Dup));
            method.Body.Instructions.Add(new Instruction(OpCodes.Ldind_U1));
            method.Body.Instructions.Add(new Instruction(OpCodes.Ldc_I4_1));
            method.Body.Instructions.Add(new Instruction(OpCodes.Sub));
            method.Body.Instructions.Add(new Instruction(OpCodes.Conv_U1));
            method.Body.Instructions.Add(new Instruction(OpCodes.Stind_I1));
            method.Body.Instructions.Add(new Instruction(OpCodes.Ldloc_1));
            method.Body.Instructions.Add(new Instruction(OpCodes.Ldc_I4_1));
            method.Body.Instructions.Add(new Instruction(OpCodes.Add));
            method.Body.Instructions.Add(new Instruction(OpCodes.Stloc_1));
            method.Body.Instructions.Add(instruction_Ldloc_1);
            method.Body.Instructions.Add(new Instruction(OpCodes.Ldloc_0));
            method.Body.Instructions.Add(new Instruction(OpCodes.Ldlen));
            method.Body.Instructions.Add(new Instruction(OpCodes.Conv_I4));
            method.Body.Instructions.Add(new Instruction(OpCodes.Blt_S, instruction_Ldloc_0));
            method.Body.Instructions.Add(new Instruction(OpCodes.Call, moduleDef.Import(typeof(System.Text.Encoding).GetMethod("get_ASCII", new Type[] { }))));
            method.Body.Instructions.Add(new Instruction(OpCodes.Ldloc_0));
            method.Body.Instructions.Add(new Instruction(OpCodes.Callvirt, moduleDef.Import(typeof(System.Text.Encoding).GetMethod("GetString", new Type[] { typeof(byte[]) }))));
            method.Body.Instructions.Add(new Instruction(OpCodes.Ret));

            method.Body.OptimizeBranches();
            method.Body.SimplifyBranches();
        }
示例#28
0
        public override ArithmeticVT Arithmetic(Instruction instruction, ModuleDef module)
        {
            Generator generator = new Generator();

            if (!ArithmeticUtils.CheckArithmetic(instruction))
            {
                return(null);
            }
            List <ArithmeticTypes> arithmeticTypes = new List <ArithmeticTypes>()
            {
                ArithmeticTypes.Add, ArithmeticTypes.Sub
            };
            ArithmeticEmulator arithmeticEmulator = new ArithmeticEmulator(instruction.GetLdcI4Value(), ArithmeticUtils.GetY(instruction.GetLdcI4Value()), ArithmeticTypes);

            return(new ArithmeticVT(new Value(arithmeticEmulator.GetValue(arithmeticTypes), arithmeticEmulator.GetY()), new Token(ArithmeticUtils.GetOpCode(arithmeticEmulator.GetType), module.Import(ArithmeticUtils.GetMethod(ArithmeticTypes))), ArithmeticTypes));
        }
示例#29
0
 void ImportAssemblyTypeReferences(ModuleDef originModule, ModuleDef stubModule)
 {
     var assembly = stubModule.Assembly;
     foreach (var ca in assembly.CustomAttributes) {
         if (ca.AttributeType.Scope == originModule)
             ca.Constructor = (ICustomAttributeType)stubModule.Import(ca.Constructor);
     }
     foreach (var ca in assembly.DeclSecurities.SelectMany(declSec => declSec.CustomAttributes)) {
         if (ca.AttributeType.Scope == originModule)
             ca.Constructor = (ICustomAttributeType)stubModule.Import(ca.Constructor);
     }
 }
        private void ImportReferences(ModuleDef module)
        {
            var refCopy = this.rt.Descriptor.Data.refMap.ToList();

            this.rt.Descriptor.Data.refMap.Clear();
            foreach (KeyValuePair <IMemberRef, uint> mdRef in refCopy)
            {
                object item;
                if (mdRef.Key is ITypeDefOrRef)
                {
                    item = module.Import((ITypeDefOrRef)mdRef.Key);
                }
                else if (mdRef.Key is MemberRef)
                {
                    item = module.Import((MemberRef)mdRef.Key);
                }
                else if (mdRef.Key is MethodDef)
                {
                    item = module.Import((MethodDef)mdRef.Key);
                }
                else if (mdRef.Key is MethodSpec)
                {
                    item = module.Import((MethodSpec)mdRef.Key);
                }
                else if (mdRef.Key is FieldDef)
                {
                    item = module.Import((FieldDef)mdRef.Key);
                }
                else
                {
                    item = mdRef.Key;
                }
                this.rt.Descriptor.Data.refMap.Add((IMemberRef)item, mdRef.Value);
            }
            foreach (VM.DataDescriptor.FuncSigDesc sig in this.rt.Descriptor.Data.sigs)
            {
                MethodSig  methodSig = sig.Signature;
                VM.FuncSig funcSig   = sig.FuncSig;

                if (methodSig.HasThis)
                {
                    funcSig.Flags |= this.rt.Descriptor.Runtime.RTFlags.INSTANCE;
                }

                var paramTypes = new List <ITypeDefOrRef>();
                if (methodSig.HasThis && !methodSig.ExplicitThis)
                {
                    IType thisType;
                    if (sig.DeclaringType.IsValueType)
                    {
                        thisType = module.Import(new ByRefSig(sig.DeclaringType.ToTypeSig()).ToTypeDefOrRef());
                    }
                    else
                    {
                        thisType = module.Import(sig.DeclaringType);
                    }
                    paramTypes.Add((ITypeDefOrRef)thisType);
                }
                foreach (TypeSig param in methodSig.Params)
                {
                    var paramType = (ITypeDefOrRef)module.Import(param.ToTypeDefOrRef());
                    paramTypes.Add(paramType);
                }
                funcSig.ParamSigs = paramTypes.ToArray();

                var retType = (ITypeDefOrRef)module.Import(methodSig.RetType.ToTypeDefOrRef());
                funcSig.RetType = retType;
            }
        }
示例#31
0
        void InjectData(ModuleDef stubModule, MethodDef method, byte[] data)
        {
            var dataType = new TypeDefUser("", "DataType", stubModule.CorLibTypes.GetTypeRef("System", "ValueType"));
            dataType.Layout = TypeAttributes.ExplicitLayout;
            dataType.Visibility = TypeAttributes.NestedPrivate;
            dataType.IsSealed = true;
            dataType.ClassLayout = new ClassLayoutUser(1, (uint)data.Length);
            stubModule.GlobalType.NestedTypes.Add(dataType);

            var dataField = new FieldDefUser("DataField", new FieldSig(dataType.ToTypeSig())) {
                IsStatic = true,
                HasFieldRVA = true,
                InitialValue = data,
                Access = FieldAttributes.CompilerControlled
            };
            stubModule.GlobalType.Fields.Add(dataField);

            MutationHelper.ReplacePlaceholder(method, arg => {
                var repl = new List<Instruction>();
                repl.AddRange(arg);
                repl.Add(Instruction.Create(OpCodes.Dup));
                repl.Add(Instruction.Create(OpCodes.Ldtoken, dataField));
                repl.Add(Instruction.Create(OpCodes.Call, stubModule.Import(
                    typeof(RuntimeHelpers).GetMethod("InitializeArray"))));
                return repl.ToArray();
            });
        }
示例#32
0
        private IMethod CreateProceedMethod(IReadOnlyList <InvocationArgument> arguments, ModuleDef module, WeavingContext context)
        {
            // get the class from shortcuts
            var shortcutType = context.ShortcutClass;

            if (shortcutType == null)
            {
                shortcutType = new TypeDefUser(ShortcutTypeNamespace, ShortcutTypeName)
                {
                    BaseType = module.Import(module.CorLibTypes.Object).ToTypeDefOrRef(),
                    // Abstract + Sealed is Static class
                    Attributes = TypeAttributes.NotPublic | TypeAttributes.Class | TypeAttributes.Abstract | TypeAttributes.Sealed
                };
                module.Types.Add(shortcutType);
                context.ShortcutClass = shortcutType;
            }

            // create the method
            var nameBuilder   = new StringBuilder("ProceedAspect");
            var argumentIndex = 0;
            var methodSig     = new MethodSig {
                RetType = module.CorLibTypes.Object, HasThis = false
            };
            var defaultProceedMethod = GetDefaultProceedMethod(module, context);

            foreach (var argument in arguments)
            {
                if (argument.HasValue)
                {
                    methodSig.Params.Add(defaultProceedMethod.MethodSig.Params[argumentIndex]);
                }
                // One day if there are arguments collision risks (IE optional arguments with same type), overload name
                argumentIndex++;
            }
            var method = new MethodDefUser(nameBuilder.ToString(), methodSig)
            {
                Body       = new CilBody(),
                Attributes = MethodAttributes.Public | MethodAttributes.Static
            };

            shortcutType.Methods.Add(method);
            var instructions = new Instructions(method.Body.Instructions, module);

            // now, either get value from given arguments or from default
            argumentIndex = 0;
            var usedArgumentIndex = 0;

            foreach (var argument in arguments)
            {
                if (argument.HasValue) // a given argument
                {
                    instructions.EmitLdarg(method.Parameters[usedArgumentIndex++]);
                }
                else
                {
                    arguments[argumentIndex].EmitDefault(instructions);
                }
                argumentIndex++;
            }

            instructions.Emit(OpCodes.Tailcall); // because target method returns object and this method also returns an object
            instructions.Emit(OpCodes.Call, defaultProceedMethod);
            instructions.Emit(OpCodes.Ret);

            return(method);
        }
示例#33
0
 public void encryptString(ModuleDef module)
 {
     foreach (TypeDef type in module.Types)
     {
         foreach (MethodDef method in type.Methods)
         {
             if (method.Body == null)
             {
                 continue;
             }
             method.Body.SimplifyBranches();
             for (int i = 0; i < method.Body.Instructions.Count; i++)
             {
                 if (method.Body.Instructions[i].OpCode == OpCodes.Ldstr)
                 {
                     string base64toencrypt       = method.Body.Instructions[i].Operand.ToString();
                     string base64EncryptedString = Convert.ToBase64String(UTF8Encoding.UTF8.GetBytes(base64toencrypt));
                     method.Body.Instructions[i].OpCode = OpCodes.Nop;
                     method.Body.Instructions.Insert(i + 1, new Instruction(OpCodes.Call, module.Import(typeof(System.Text.Encoding).GetMethod("get_UTF8", new Type[] { }))));
                     method.Body.Instructions.Insert(i + 2, new Instruction(OpCodes.Ldstr, base64EncryptedString));
                     method.Body.Instructions.Insert(i + 3, new Instruction(OpCodes.Call, module.Import(typeof(System.Convert).GetMethod("FromBase64String", new Type[] { typeof(string) }))));
                     method.Body.Instructions.Insert(i + 4, new Instruction(OpCodes.Callvirt, module.Import(typeof(System.Text.Encoding).GetMethod("GetString", new Type[] { typeof(byte[]) }))));
                     i += 4;
                 }
             }
         }
     }
 }