/// <summary>
        /// Adds a public automatic property.
        /// </summary>
        /// <param name="typeDefinition">The type definition.</param>
        /// <param name="name">The name.</param>
        /// <param name="typeReference">The type reference.</param>
        /// <param name="moduleDefinition">The module definition.</param>
        /// <param name="typeResolver">The type resolver.</param>
        internal static void AddPublicAutoProperty(this TypeDef typeDefinition, string name, ITypeDefOrRef typeReference, ModuleDef moduleDefinition, TypeResolver typeResolver)
        {
            var compilerGeneratedAttribute = moduleDefinition.SafeImport(typeof(CompilerGeneratedAttribute));
            // backing field
            var backingFieldDefinition = new FieldDefUser($"<{name}>k__BackingField", new FieldSig(typeReference.ToTypeSig()), FieldAttributes.Private);

            backingFieldDefinition.CustomAttributes.Add(moduleDefinition.CreateCustomAttribute(compilerGeneratedAttribute, typeResolver));
            typeDefinition.Fields.Add(backingFieldDefinition);
            // property...
            var propertyDefinition = new PropertyDefUser(name, new PropertySig(true, typeReference.ToTypeSig()));

            typeDefinition.Properties.Add(propertyDefinition);
            // ...setter
            propertyDefinition.SetMethod = CreatePropertyMethod("set_" + name, moduleDefinition.CorLibTypes.Void, Tuple.Create(typeReference.ToTypeSig(), "value"));
            propertyDefinition.SetMethod.CustomAttributes.Add(moduleDefinition.CreateCustomAttribute(compilerGeneratedAttribute, typeResolver));
            typeDefinition.Methods.Add(propertyDefinition.SetMethod);
            var setterParameter = new ParamDefUser("value");

            propertyDefinition.SetMethod.ParamDefs.Add(setterParameter);
            var setterInstructions = new Instructions(propertyDefinition.SetMethod.Body.Instructions, moduleDefinition);

            setterInstructions.Emit(OpCodes.Ldarg_0);
            setterInstructions.Emit(OpCodes.Ldarg_1);
            setterInstructions.Emit(OpCodes.Stfld, backingFieldDefinition);
            setterInstructions.Emit(OpCodes.Ret);
            // ...getter
            propertyDefinition.GetMethod = CreatePropertyMethod("get_" + name, typeReference.ToTypeSig());
            propertyDefinition.GetMethod.CustomAttributes.Add(moduleDefinition.CreateCustomAttribute(compilerGeneratedAttribute, typeResolver));
            typeDefinition.Methods.Add(propertyDefinition.GetMethod);
            var getterInstructions = new Instructions(propertyDefinition.GetMethod.Body.Instructions, moduleDefinition);

            getterInstructions.Emit(OpCodes.Ldarg_0);
            getterInstructions.Emit(OpCodes.Ldfld, backingFieldDefinition);
            getterInstructions.Emit(OpCodes.Ret);
        }
Exemplo n.º 2
0
        public static TypeSig ThisType(ITypeDefOrRef type)
        {
            var typeDef = type.ResolveTypeDef();

            if (typeDef?.IsValueType ?? false || type.IsValueType)
            {
                return(new ByRefSig(type.ToTypeSig()));
            }
            return(type.ToTypeSig());
        }
Exemplo n.º 3
0
        TypeSpec ApplyGenerics(ITypeDefOrRef type, IList <TypeSig> generics)
        {
            ClassOrValueTypeSig typeSig    = type.ToTypeSig().ToClassOrValueTypeSig();
            GenericInstSig      genericSig = new GenericInstSig(typeSig, generics);

            return(new TypeSpecUser(genericSig));
        }
		public void addInitializeArrayCode(Block block, int start, int numToRemove, ITypeDefOrRef elementType, byte[] data) {
			int index = start;
			block.replace(index++, numToRemove, Instruction.CreateLdcI4(data.Length / elementType.ToTypeSig().ElementType.GetPrimitiveSize()));
			block.insert(index++, OpCodes.Newarr.ToInstruction(elementType));
			block.insert(index++, OpCodes.Dup.ToInstruction());
			block.insert(index++, OpCodes.Ldtoken.ToInstruction((IField)create(data)));
			block.insert(index++, OpCodes.Call.ToInstruction((IMethod)InitializeArrayMethod));
		}
		public void AddInitializeArrayCode(Block block, int start, int numToRemove, ITypeDefOrRef elementType, byte[] data) {
			int index = start;
			block.Replace(index++, numToRemove, Instruction.CreateLdcI4(data.Length / elementType.ToTypeSig().ElementType.GetPrimitiveSize()));
			block.Insert(index++, OpCodes.Newarr.ToInstruction(elementType));
			block.Insert(index++, OpCodes.Dup.ToInstruction());
			block.Insert(index++, OpCodes.Ldtoken.ToInstruction((IField)Create(data)));
			block.Insert(index++, OpCodes.Call.ToInstruction((IMethod)InitializeArrayMethod));
		}
Exemplo n.º 6
0
 static ByRefSig CreateByRefType(ITypeDefOrRef elementType)
 {
     if (elementType == null)
     {
         return(null);
     }
     return(new ByRefSig(elementType.ToTypeSig()));
 }
Exemplo n.º 7
0
        public static string EscapeVariableTypeName(ITypeDefOrRef type, bool hasGen = true, bool hasModuleName = true, IList <TypeSig> genArgs = null)
        {
            var sig = type.ToTypeSig();

            if (type.IsValueType || IsValueType(sig))
            {
                return(EscapeTypeNameImpl(type, hasGen, hasModuleName, genArgs, cppBasicType: true));
            }
            else if (type.ToTypeSig().IsGenericParameter)
            {
                return($"::natsu::variable_type_t<{EscapeTypeNameImpl(type, hasGen, hasModuleName, genArgs, cppBasicType: true)}>");
            }
            else
            {
                return($"::natsu::gc_obj_ref<{EscapeTypeNameImpl(type, hasGen, hasModuleName, genArgs, cppBasicType: true)}>");
            }
        }
        private FieldDef CreateInt32Field(TypeDef type)
        {
            Importer      importer  = new Importer(type.Module);
            ITypeDefOrRef reference = importer.Import(typeof(Int32));

            TypeSig         signature  = reference.ToTypeSig();
            FieldAttributes attributes = FieldAttributes.Static | FieldAttributes.Public;

            FieldDef field = new FieldDefUser(GetRandomString(60), new FieldSig(signature), attributes);

            type.Fields.Add(field);

            return(field);
        }
Exemplo n.º 9
0
        static void TransformLDELEM(ILASTExpression expr, ModuleDef module, ITypeDefOrRef type)
        {
            var array     = module.CorLibTypes.GetTypeRef("System", "Array");
            var getValSig = MethodSig.CreateInstance(module.CorLibTypes.Object, module.CorLibTypes.Int32);
            var getValRef = new MemberRefUser(module, "GetValue", getValSig, array);

            var getValue = new ILASTExpression {
                ILCode    = Code.Call,
                Operand   = getValRef,
                Arguments = expr.Arguments
            };

            expr.ILCode    = Code.Unbox_Any;
            expr.Operand   = type.IsValueType ? module.CorLibTypes.Object.ToTypeDefOrRef() : type;
            expr.Type      = TypeInference.ToASTType(type.ToTypeSig());
            expr.Arguments = new IILASTNode[] { getValue };
        }
Exemplo n.º 10
0
        /// <summary>
        /// Returns an argument type
        /// </summary>
        /// <param name="methodSig">Method signature</param>
        /// <param name="declaringType">Declaring type (only needed if it's an instance method)</param>
        /// <returns>The type or <c>null</c> if it doesn't exist</returns>
        public TypeSig GetArgumentType(MethodSig methodSig, ITypeDefOrRef declaringType)
        {
            if (methodSig == null)
            {
                return(null);
            }
            int index = GetParameterIndex();

            if (index == 0 && methodSig.ImplicitThis)
            {
                return(declaringType.ToTypeSig()); //TODO: Should be ByRef if value type
            }
            if (methodSig.ImplicitThis)
            {
                index--;
            }
            return(methodSig.Params.Get(index, null));
        }
Exemplo n.º 11
0
        public static bool IsCppBasicType(ITypeDefOrRef type)
        {
            switch (type.ToTypeSig().ElementType)
            {
            case ElementType.Boolean:
            case ElementType.Char:
            case ElementType.I1:
            case ElementType.U1:
            case ElementType.I2:
            case ElementType.U2:
            case ElementType.I4:
            case ElementType.U4:
            case ElementType.I8:
            case ElementType.U8:
            case ElementType.R4:
            case ElementType.R8:
                return(true);
                //case ElementType.I:
                //case ElementType.U:
            }

            return(false);
        }
Exemplo n.º 12
0
		void WriteType(ITypeDefOrRef type, bool useNamespaces, bool useTypeKeywords) {
			var td = type as TypeDef;
			if (td == null && type is TypeRef)
				td = ((TypeRef)type).Resolve();
			if (td == null ||
				td.GenericParameters.Count == 0 ||
				(td.DeclaringType != null && td.DeclaringType.GenericParameters.Count >= td.GenericParameters.Count)) {
				var oldFlags = this.flags;
				this.flags &= ~(SimplePrinterFlags.ShowNamespaces | SimplePrinterFlags.ShowTypeKeywords);
				if (useNamespaces)
					this.flags |= SimplePrinterFlags.ShowNamespaces;
				if (useTypeKeywords)
					this.flags |= SimplePrinterFlags.ShowTypeKeywords;
				Write(type);
				this.flags = oldFlags;
				return;
			}

			var typeSig = type.ToTypeSig();

			int numGenParams = td.GenericParameters.Count;
			if (type.DeclaringType != null) {
				var oldFlags = this.flags;
				this.flags &= ~(SimplePrinterFlags.ShowNamespaces | SimplePrinterFlags.ShowTypeKeywords);
				if (useNamespaces)
					this.flags |= SimplePrinterFlags.ShowNamespaces;
				Write(type.DeclaringType);
				this.flags = oldFlags;
				OutputWrite(".", TextTokenKind.Operator);
				numGenParams = numGenParams - td.DeclaringType.GenericParameters.Count;
				if (numGenParams < 0)
					numGenParams = 0;
			}
			else if (useNamespaces && !UTF8String.IsNullOrEmpty(td.Namespace)) {
				foreach (var ns in td.Namespace.String.Split('.')) {
					WriteIdentifier(ns, TextTokenKind.NamespacePart);
					OutputWrite(".", TextTokenKind.Operator);
				}
			}

			WriteIdentifier(RemoveGenericTick(td.Name), TextTokenKindUtils.GetTextTokenType(td));
			WriteToken(type);
			var genParams = td.GenericParameters.Skip(td.GenericParameters.Count - numGenParams).ToArray();
			WriteGenerics(genParams, TextTokenKind.TypeGenericParameter);
		}
        private int ProcessMethod(MethodDef md)
        {
            List <GenInfo> toPatch = new List <GenInfo>();

            if (!md.HasGenericParameters)
            {
                return(0);
            }

            List <MethodSpec> callers = FindCallingSpecs(md);

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

            Dictionary <int, TypeSig> locals = new Dictionary <int, TypeSig>();

            for (int i = 0; i < callers.Count; i++)
            {
                MethodSpec spec = callers[i];

                for (int x = 0; x < md.Body.Variables.Count; x++)
                {
                    Local l = md.Body.Variables[x];

                    if (!l.Type.IsGenericMethodParameter)
                    {
                        continue;
                    }
                    if (!(l.Type is GenericSig))
                    {
                        continue;
                    }


                    GenericSig gSig = l.Type as GenericSig;

                    GenericParam gParam = md.GenericParameters.Where(y => y.Number == gSig.Number).FirstOrDefault();

                    int indexOf = md.GenericParameters.IndexOf(gParam);

                    if (gSig.Number > spec.GenericInstMethodSig.GenericArguments.Count - 1 || gSig.Number < 0)
                    {
                        continue;
                    }

                    TypeSig tSig = spec.GenericInstMethodSig.GenericArguments[(int)gSig.Number];



                    ITypeDefOrRef c**t = tSig.ToTypeDefOrRef();

                    ITypeDefOrRef tRef = c**t.ScopeType;

                    if (tSig.IsSZArray)
                    {
                    }
                    l.Type = tRef.ToTypeSig();

                    if (locals.ContainsKey(l.Index))
                    {
                        if (locals[l.Index] == tRef.ToTypeSig())
                        {
                            continue;
                        }
                        else
                        {
                            locals[l.Index] = tRef.ToTypeSig();
                        }
                    }
                    else
                    {
                        locals.Add(l.Index, tRef.ToTypeSig());
                    }

                    //md.GenericParameters.Remove(gParam);
                }
            }

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


            Dictionary <int, Local> newLocals = new Dictionary <int, Local>();

            foreach (var pair in locals)
            {
                int     index = pair.Key;
                TypeSig tSig  = pair.Value;

                Local newLocal = new Local(tSig);
                //newLocal.Name = "TESTING!!!" + Guid.NewGuid().ToString();
                newLocal.Index = index;

                newLocals.Add(index, newLocal);
            }

            for (int i = 0; i < md.Body.Instructions.Count; i++)
            {
                Instruction inst = md.Body.Instructions[i];
                if (inst.OpCode == OpCodes.Stloc || inst.OpCode == OpCodes.Ldloc)
                {
                    Local l = inst.Operand as Local;
                    if (newLocals.ContainsKey(l.Index))
                    {
                        md.Body.Instructions[i].Operand = newLocals[l.Index];
                    }
                }
            }

            md.Body.Variables.Clear();
            foreach (var pair in newLocals)
            {
                md.Body.Variables.Add(pair.Value);
            }

            // New local is not added at all, it is simply f****d.

            if (md.Name == "")
            {
            }

            /*for (int i = 0; i < md.Body.Variables.Count; i++)
             * {
             *  Local l = md.Body.Variables[i];
             *
             *  if (!l.Type.IsGenericMethodParameter)
             *  {
             *      continue;
             *  }
             *  if (!(l.Type is GenericSig))
             *  {
             *      continue;
             *  }
             *
             *  if (locals.ContainsKey(l))
             *  {
             *      md.Body.Variables[i].Type = locals[l];
             *  }
             * }*/

            /*for (int i = 0; i < md.Body.Instructions.Count; i++)
             * {
             *  Instruction inst = md.Body.Instructions[i];
             *
             *  // If it is a generic method
             *  if (inst.Operand != null && inst.Operand is MethodSpec)
             *  {
             *      // Investigate the method body to see if all locals are outlined, use gen param count vs local count...?
             *      // If it is the same then we know that there are variables to outline. Next is trying to identify when a legitimate generic type is there...
             *      // We need to collate them into a list so we can link how many have the same generic sig types listed
             *      // (a generic should technically have several different types).
             *
             *
             *      MethodSpec mSpec = inst.Operand as MethodSpec;
             *      if (mSpec == null)
             *      {
             *          // Failsafe check
             *          continue;
             *      }
             *
             *      MethodDef mDef = mSpec.ResolveMethodDef();
             *      if (mDef == null)
             *      {
             *          Logger.Log(this, string.Format("Resolved MethodDef is null for {0}", mSpec));
             *          continue;
             *      }
             *
             *      if (mDef.Body == null)
             *      {
             *          continue;
             *      }
             *
             *      int lCount = mDef.Body.Variables.Count;
             *      int gpCount = mSpec.GenericInstMethodSig.GenericArguments.Count;
             *
             *
             *
             *      toPatch.Add(new GenInfo() { CallingInst = inst, GenCount = gpCount, LocalCount = lCount, RawMethod = mDef, TargetGeneric = mSpec,
             *          GenericArgs = mSpec.GenericInstMethodSig.GenericArguments.ToList(),
             *      CallIndex = i,
             *      ParentMethod = md});
             *
             *  }
             * }*/


            List <GenInfo> Completed = new List <GenInfo>();

            //Completed.AddRange(toPatch);

            foreach (GenInfo inf in toPatch)
            {
                // Get count of other similar generic instances
                // ... should put in a dictionary the link between the method, and numbers.
                // Let's get it working without that for now


                // get generic param from generic arg

                // Go to local, go to type, cast type to genericsig.
                // You can then get the 'number' which corresponds to the generic parameter on the raw method
                // Relate that back to the index on the locals maybe?
                bool comp = false;

                List <GenericParam> toDelete = new List <GenericParam>();
                List <Local>        toAdd    = new List <Local>();
                for (int i = 0; i < inf.RawMethod.Body.Variables.Count; i++)
                {
                    Local l = inf.RawMethod.Body.Variables[i];

                    if (!l.Type.IsGenericMethodParameter)
                    {
                        continue;
                    }
                    if (!(l.Type is GenericSig))
                    {
                        continue;
                    }

                    GenericSig gSig = l.Type as GenericSig;

                    if (gSig.Number > inf.TargetGeneric.GenericInstMethodSig.GenericArguments.Count - 1 || gSig.Number < 0)
                    {
                        continue;
                    }
                    TypeSig tSig = inf.TargetGeneric.GenericInstMethodSig.GenericArguments[(int)gSig.Number];

                    if (inf.RawMethod.Name == "method_1")
                    {
                    }
                    if (tSig.IsGenericParameter)
                    {
                    }
                    if (tSig == null)
                    {
                        continue;
                    }

                    ((MethodDef)inf.TargetGeneric.Method).Body.Variables[i].Type = tSig;
                    ((MethodDef)inf.TargetGeneric.Method).Body.Variables[i].Name = "CANCER_" + Guid.NewGuid().ToString();
                    //toAdd.Add(new Local(tSig));
                }

                //toAdd.ForEach(x => ((MethodDef)inf.TargetGeneric.Method).Body.Variables.Add(x));

                /*for (int i = 0; i < inf.RawMethod.Parameters.Count; i++)
                 * {
                 *  Parameter param = inf.RawMethod.Parameters[i];
                 *
                 *  if (!param.Type.IsGenericParameter)
                 *      continue;
                 *
                 *
                 *  GenericSig gSig = param.Type.ToGenericSig();
                 *
                 *  TypeSig tSig = inf.TargetGeneric.GenericInstMethodSig.GenericArguments[(int)gSig.Number];
                 *
                 *  if (tSig == null)
                 *      continue;
                 *
                 *  if (inf.RawMethod.Name == "method_4")
                 *  {
                 *
                 *  }
                 *  if (tSig.IsGenericParameter)
                 *      continue;
                 *  param.Type = tSig;
                 *
                 *  //toDelete.Add(inf.RawMethod.GenericParameters.Where(x => x.Number == gSig.Number).FirstOrDefault());
                 *
                 *
                 * }*/



                /*for (int i = 0; i < inf.RawMethod.GenericParameters.Count; i++)
                 * {
                 *  GenericParam gParam = inf.RawMethod.GenericParameters[i];
                 *
                 *
                 *  TypeSig tSig = inf.TargetGeneric.GenericInstMethodSig.GenericArguments[i];
                 *
                 *  if (tSig == null)
                 *      continue;
                 *
                 *  MethodDef mDef = inf.TargetGeneric.Method as MethodDef;
                 *
                 *  Parameter p = mDef.Parameters.Where(x => !x.IsHiddenThisParameter && x.Type.FullName == gParam.FullName).FirstOrDefault();
                 *
                 *
                 *  if (p == null)
                 *  {
                 *      continue;
                 *  }
                 *
                 *  p.Type = tSig;
                 *
                 *  toDelete.Add(gParam);
                 *
                 *
                 * }*/
                toDelete.ForEach(x => inf.RawMethod.GenericParameters.Remove(x));

                /*for (int i = 0; i < inf.RawMethod.Body.Variables.Count; i++)
                 * {
                 *  Local l = inf.RawMethod.Body.Variables[i];
                 *
                 *  if (!l.Type.IsGenericMethodParameter)
                 *  {
                 *      continue;
                 *  }
                 *  if (!(l.Type is GenericSig))
                 *  {
                 *      continue;
                 *  }
                 *
                 *  GenericSig gSig = l.Type as GenericSig;
                 *  //if (gSig.Number > inf.TargetGeneric.GenericInstMethodSig.GenericArguments.Count - 1)
                 *  //    continue;
                 *  TypeSig tSig = inf.TargetGeneric.GenericInstMethodSig.GenericArguments.Where(
                 *      (x) =>
                 *      {
                 *          if (!x.IsGenericMethodParameter)
                 *              return false;
                 *
                 *          GenericSig gSig2 = x.ToGenericSig();
                 *          if (gSig2 == null)
                 *              return false;
                 *
                 *          return gSig2.Number == gSig.Number;
                 *          //return true;
                 *      }
                 *      ).FirstOrDefault();
                 *
                 *  if (tSig == null)
                 *      continue;
                 *
                 *  inf.RawMethod.Body.Variables[i].Type = tSig;
                 *
                 *  comp = true;
                 * }
                 *
                 * if (comp)
                 *  Completed.Add(inf);*/
            }


            return(Completed.Count);
        }
Exemplo n.º 14
0
        public static void Run()
        {
            // 创建一个新模块。 传入的字符串是模块的名称,而不是文件名。
            ModuleDef mod = new ModuleDefUser("MyModule.exe");

            // 这是一个控制台应用程序
            mod.Kind = ModuleKind.Console;

            //将模块添加到装配中
            AssemblyDef asm = new AssemblyDefUser("MyAssembly", new Version(1, 2, 3, 4), null, "");

            asm.Modules.Add(mod);

            //添加.NET资源
            //         byte[] resourceData = Encoding.UTF8.GetBytes("Hello, world!");
            //mod.Resources.Add(new EmbeddedResource("My.Resource", resourceData,
            //				ManifestResourceAttributes.Private));

            // 添加启动类型。 它派生自System.Object。
            TypeDef startUpType = new TypeDefUser("My.Namespace", "Startup", mod.CorLibTypes.Object.TypeDefOrRef);

            startUpType.Attributes = TypeAttributes.NotPublic | TypeAttributes.AutoLayout |
                                     TypeAttributes.Class | TypeAttributes.AnsiClass;
            // 将类型添加到模块
            mod.Types.Add(startUpType);

            // 创建入口点方法
            MethodDef entryPoint = new MethodDefUser("Main",
                                                     MethodSig.CreateStatic(mod.CorLibTypes.Void, new SZArraySig(mod.CorLibTypes.String)));

            entryPoint.Attributes = MethodAttributes.Private | MethodAttributes.Static |
                                    MethodAttributes.HideBySig | MethodAttributes.ReuseSlot;
            entryPoint.ImplAttributes = MethodImplAttributes.IL | MethodImplAttributes.Managed;
            // 命名第一个参数(参数0是返回类型)
            entryPoint.ParamDefs.Add(new ParamDefUser("args", 1));
            // 将方法添加到启动类型
            startUpType.Methods.Add(entryPoint);
            // 设置模块入口点
            mod.EntryPoint = entryPoint;

            // 创建TypeRef到System.Console
            TypeRef consoleRef = new TypeRefUser(mod, "System", "Console", mod.CorLibTypes.AssemblyRef);
            // 创建方法ref为'System.Void System.Console :: WriteLine(System.String)'
            MemberRef consoleWrite1 = new MemberRefUser(mod, "WriteLine",
                                                        MethodSig.CreateStatic(mod.CorLibTypes.Void, mod.CorLibTypes.String),
                                                        consoleRef);


            TypeRef ConsoleKeyInfo = new TypeRefUser(mod, "System", "ConsoleKeyInfo", mod.CorLibTypes.AssemblyRef);
            //TypeRef stream = new TypeRefUser(mod, "System.IO", "Stream", mod.CorLibTypes.AssemblyRef);
            ClassSig classSig = new ClassSig(ConsoleKeyInfo);

            SZArraySig    array5 = new SZArraySig(classSig);
            ITypeDefOrRef type1  = array5.ToTypeDefOrRef();
            ITypeDefOrRef type2  = classSig.ToTypeDefOrRef();
            TypeSig       type11 = type1.ToTypeSig();
            TypeSig       type22 = type2.ToTypeSig();
            // 创建方法ref为'System.ConsoleKeyInfo
            //System.Console::ReadKey()'
            MemberRef consoleReadKey = new MemberRefUser(
                mod,
                "ReadLine",
                //MethodSig.CreateStatic(mod.CorLibTypes.Void),
                MethodSig.CreateStatic(mod.CorLibTypes.String),
                consoleRef
                );

            //LocalList localList=new LocalList(new LazyList<Local>());
            Local local = new Local(mod.CorLibTypes.String);
            //localList.Add(local);
            //SZArraySig SZArraySig = new SZArraySig(local);

            // 将CIL方法体添加到入口点方法
            CilBody epBody = new CilBody();

            entryPoint.Body = epBody;
            epBody.Variables.Add(local);
            epBody.Instructions.Add(OpCodes.Nop.ToInstruction());
            epBody.Instructions.Add(OpCodes.Ldstr.ToInstruction("小宇专属"));
            epBody.Instructions.Add(OpCodes.Call.ToInstruction(consoleWrite1));
            epBody.Instructions.Add(OpCodes.Ldstr.ToInstruction("xiaoyu"));
            epBody.Instructions.Add(OpCodes.Call.ToInstruction(consoleWrite1));
            epBody.Instructions.Add(OpCodes.Nop.ToInstruction());
            epBody.Instructions.Add(OpCodes.Call.ToInstruction(consoleReadKey));
            //epBody.Instructions.Add(OpCodes.Ldc_I4_0.ToInstruction());

            epBody.Instructions.Add(OpCodes.Stloc_0.ToInstruction());
            epBody.Instructions.Add(OpCodes.Ldloc_0.ToInstruction());
            epBody.Instructions.Add(OpCodes.Call.ToInstruction(consoleWrite1));
            epBody.Instructions.Add(OpCodes.Nop.ToInstruction());
            epBody.Instructions.Add(OpCodes.Ret.ToInstruction());

            // 将程序集保存到磁盘上的文件中
            mod.Write(@"saved-assembly.exe");
        }
Exemplo n.º 15
0
 private ITypeDefOrRef RemapReference(ITypeDefOrRef reference)
 {
     return(RemapReference(reference.ToTypeSig()).ToTypeDefOrRef());
 }
Exemplo n.º 16
0
 private MosaType ResolveTypeOperand(ITypeDefOrRef operand, GenericArgumentResolver resolver)
 {
     return(metadata.Loader.GetType(resolver.Resolve(operand.ToTypeSig())));
 }
Exemplo n.º 17
0
        /// <summary>
        /// Resolve a type from a deserialized inline operand, which should
        /// have a direct token (position).
        /// </summary>
        /// <param name="operand">Inline operand</param>
        /// <returns>TypeSig</returns>
        TypeSig ResolveType(InlineOperand operand)
        {
            ITypeDefOrRef type = this.ResolveType_NoLock(operand.Position);

            return(type.ToTypeSig(true));
        }
Exemplo n.º 18
0
 private ITypeDefOrRef FindHookTypeDef(ITypeDefOrRef originalDef) =>
 FindHookTypeSig(originalDef.ToTypeSig()).ToTypeDefOrRef();
Exemplo n.º 19
0
        public void Obfuscating(ref ModuleDef moduleDef, MethodDef[] methodDef)
        {
            foreach (var methodDef_Enumerator in methodDef)
            {
                if (methodDef_Enumerator.Body == null)
                {
                    continue;
                }
                Importer      importer      = new Importer(moduleDef);
                ITypeDefOrRef int32Import   = importer.Import(typeof(System.Int32));
                ITypeDefOrRef booleanImport = importer.Import(typeof(System.Boolean));

                Local int32Importing   = new Local(int32Import.ToTypeSig());
                Local booleanImporting = new Local(booleanImport.ToTypeSig());

                methodDef_Enumerator.Body.Variables.Locals.Add(int32Importing);
                methodDef_Enumerator.Body.Variables.Locals.Add(booleanImporting);

                int i = 0;

                var lengthILBody      = methodDef_Enumerator.Body.Instructions.Count;
                var instructionLdcI41 = new Instruction(OpCodes.Ldc_I4_1);
                var instructionLdloc0 = new Instruction(OpCodes.Ldloc_S, int32Importing);

                methodDef_Enumerator.Body.KeepOldMaxStack = true;
                methodDef_Enumerator.Body.Instructions.Insert(i, new Instruction(OpCodes.Ldc_I4_0));
                methodDef_Enumerator.Body.Instructions.Insert(i + 1, new Instruction(OpCodes.Stloc_S, int32Importing));
                methodDef_Enumerator.Body.Instructions.Insert(i + 2, new Instruction(OpCodes.Br_S, instructionLdcI41));
                methodDef_Enumerator.Body.Instructions.Insert(i + 3, instructionLdloc0);
                methodDef_Enumerator.Body.Instructions.Insert(i + 4, new Instruction(OpCodes.Ldc_I4_0));
                methodDef_Enumerator.Body.Instructions.Insert(i + 5, new Instruction(OpCodes.Ceq));
                methodDef_Enumerator.Body.Instructions.Insert(i + 6, new Instruction(OpCodes.Ldc_I4_1));
                methodDef_Enumerator.Body.Instructions.Insert(i + 7, new Instruction(OpCodes.Ceq));
                methodDef_Enumerator.Body.Instructions.Insert(i + 8, new Instruction(OpCodes.Stloc_S, booleanImporting));
                methodDef_Enumerator.Body.Instructions.Insert(i + 9, new Instruction(OpCodes.Ldloc_S, booleanImporting));
                methodDef_Enumerator.Body.Instructions.Insert(i + 10, new Instruction(OpCodes.Brtrue_S, methodDef_Enumerator.Body.Instructions[10]));
                methodDef_Enumerator.Body.Instructions.Insert(i + 11, new Instruction(OpCodes.Ret));
                methodDef_Enumerator.Body.Instructions.Insert(i + 12, new Instruction(OpCodes.Calli, null));
                methodDef_Enumerator.Body.Instructions.Insert(i + 13, new Instruction(OpCodes.Sizeof, null));
                methodDef_Enumerator.Body.Instructions.Insert(i + lengthILBody + 14, instructionLdcI41);
                methodDef_Enumerator.Body.Instructions.Insert(i + lengthILBody + 15, new Instruction(OpCodes.Stloc_S, booleanImporting));
                methodDef_Enumerator.Body.Instructions.Insert(i + lengthILBody + 16, new Instruction(OpCodes.Br_S, instructionLdloc0));
                methodDef_Enumerator.Body.Instructions.Insert(i + lengthILBody + 17, new Instruction(OpCodes.Ret));



                var exceptionHandler = new ExceptionHandler();
                exceptionHandler.TryStart     = methodDef_Enumerator.Body.Instructions[12];
                exceptionHandler.TryEnd       = methodDef_Enumerator.Body.Instructions[14];
                exceptionHandler.FilterStart  = null;
                exceptionHandler.HandlerStart = methodDef_Enumerator.Body.Instructions[10];
                exceptionHandler.HandlerEnd   = methodDef_Enumerator.Body.Instructions[11];
                exceptionHandler.HandlerType  = ExceptionHandlerType.Finally;
                exceptionHandler.CatchType    = null;
                methodDef_Enumerator.Body.ExceptionHandlers.Add(exceptionHandler);


                //method.Body.OptimizeBranches();
                //method.Body.SimplifyBranches();
            }
        }
Exemplo n.º 20
0
		/// <summary>
		/// Returns an argument type
		/// </summary>
		/// <param name="methodSig">Method signature</param>
		/// <param name="declaringType">Declaring type (only needed if it's an instance method)</param>
		/// <returns>The type or <c>null</c> if it doesn't exist</returns>
		public TypeSig GetArgumentType(MethodSig methodSig, ITypeDefOrRef declaringType) {
			if (methodSig == null)
				return null;
			int index = GetParameterIndex();
			if (index == 0 && methodSig.ImplicitThis)
				return declaringType.ToTypeSig();	//TODO: Should be ByRef if value type
			if (methodSig.ImplicitThis)
				index--;
			return methodSig.Params.Get(index, null);
		}
Exemplo n.º 21
0
        private string injectDeepTrace(List <string> MethodToken, string assemblyPath, string outputDirectory, bool WithTrace = false)
        {
            AssemblyDef asmDef;

            // New assembly path
            string fileName = Path.GetFileName(assemblyPath);

            // Append Date and Time to new filename
            string newPath = Path.Combine(outputDirectory, DateTime.UtcNow.ToString("yyyy-MM-dd HH.mm.ss.fff", CultureInfo.InvariantCulture) + "_" + fileName);

            // Check if Output directory already exists, if not, create one
            if (!Directory.Exists(outputDirectory))
            {
                try
                {
                    Directory.CreateDirectory(outputDirectory);
                }
                catch (Exception ex)
                {
                    //MessageBox.Show(ex.ToString());
                    MainWindow.Instance.mBox("Injector Exception", ex.ToString());
                }
            }

            try
            {
                // AssemblyResolver
                if (_AssmeblyResolver == null)
                {
                    _AssmeblyResolver = new AssemblyResolver();
                }
                if (Directory.Exists(Path.GetDirectoryName(assemblyPath)))
                {
                    AddSearchPath(Path.GetDirectoryName(assemblyPath));
                }

                // how to use AssemblyResolver with dnLib?
                //_AssmeblyResolver

                // Load assembly
                //asmDef = AssemblyDef.Load(assemblyPath);
                ModuleDefMD mod = ModuleDefMD.Load(assemblyPath);

                // import our pritObj Class
                Importer      importer         = new Importer(mod);
                Type          PrintObjType     = typeof(PrintObj);
                ITypeDefOrRef _printObjTypeRef = importer.Import(PrintObjType);

                // This creates a new namespace Logging and class PrintObj in the new assembly, we don't want that
                //TypeDef _printObj = new TypeDefUser("Logging", "PrintObj", mod.CorLibTypes.Object.TypeDefOrRef);
                //var _printObjCtor = _printObj.FindDefaultConstructor();
                //mod.Types.Add(_printObj);



                Type    t          = typeof(System.Reflection.MethodBase);
                string  methodname = "GetCurrentMethod";
                IMethod _methodGetCurrentMethod = importer.Import(t.GetMethod(methodname));

                methodname = "set_CurrentMethod";
                IMethod _methodSetMethod = importer.Import(PrintObjType.GetMethod(methodname));


                t          = typeof(System.Reflection.Assembly);
                methodname = "GetExecutingAssembly";
                IMethod _methodGetExecutingAssembly = importer.Import(t.GetMethod(methodname));

                methodname = "set_CurrentAssembly";
                IMethod _methodSetExecutingAssembly = importer.Import(PrintObjType.GetMethod(methodname));


                methodname = "get_CurrentArguments";
                IMethod _methodGetArguments = importer.Import(PrintObjType.GetMethod(methodname));

                methodname = "set_CurrentArguments";
                IMethod _methodSetArguments = importer.Import(PrintObjType.GetMethod(methodname));

                methodname = "PrintArgs";
                IMethod _methodPrintArgs = importer.Import(PrintObjType.GetMethod(methodname));

                methodname = ".ctor";
                IMethod _printObjCtor = importer.Import(PrintObjType.GetMethod(methodname));

                foreach (ModuleDef modDef in mod.Assembly.Modules)
                {
                    foreach (TypeDef typDef in modDef.Types)
                    {
                        foreach (MethodDef metDef in typDef.Methods)
                        {
                            //if (MethodToken.Contains(metDef.MDToken.ToString()) && metDef.Name == "About1_Closed")
                            if (MethodToken.Contains(metDef.MDToken.ToString()))
                            {
                                if (WithTrace)
                                {
                                    Trace.WriteLine("Found method " + metDef.ToString() + " Token: " + metDef.MDToken.ToString());
                                }

                                try
                                {
                                    string variablesInfo = string.Empty;
                                    if (metDef.Body != null && metDef.Body.Variables != null && metDef.Body.Variables.Count > 0)
                                    {
                                        foreach (var variable in metDef.Body.Variables)
                                        {
                                            string varInfo = "            Variable - Type: " + variable.Type.ToString() + " Name: " + variable.Name + NewLine;
                                            varInfo += "            Index: " + variable.Index.ToString();
                                            if (WithTrace)
                                            {
                                                Trace.WriteLine(varInfo);
                                            }
                                            variablesInfo += varInfo;
                                        }
                                    }

                                    /*
                                     * if we want to skip anything
                                     * if (metDef.IsConstructor ||
                                     *  metDef.IsAbstract ||
                                     *  metDef.IsSetter ||
                                     *  (metDef.IsSpecialName && !metDef.IsGetter) || // to allow getter methods
                                     *  metDef.IsInstanceConstructor ||
                                     *  metDef.IsManaged == false
                                     *  )
                                     * {
                                     *  if (WithTrace) Trace.WriteLine("Skipped unsupported metDef " + metDef.Name);
                                     * }
                                     * else if (metDef != null && metDef.Body != null)
                                     */

                                    if (metDef != null && metDef.Body != null)
                                    {
                                        var instructions    = metDef.Body.Instructions;
                                        var newInstructions = new List <Instruction>();

                                        Instruction firstExistingInstruction        = metDef.Body.Instructions[0];
                                        uint        firstExistingInstrunctionOffset = firstExistingInstruction.Offset;
                                        int         fIndex = (int)firstExistingInstrunctionOffset; // not working

                                        // nop Test
                                        //instructions.Insert((int)firstExistingInstruction.Offset, new Instruction(OpCodes.Nop));
                                        //instructions.Insert((int)firstExistingInstruction.Offset, new Instruction(OpCodes.Nop));

                                        ///
                                        /// Simple TraceLine
                                        ///

                                        // Load fully qualified method name as string
                                        //not working: (int)firstExistingInstruction.Offset

                                        //newInstructions.Add(new Instruction(OpCodes.Ldstr, metDef.ToString() + variablesInfo));
                                        //newInstructions.Add(new Instruction(OpCodes.Call, metDef.Module.Import(typeof(Trace).GetMethod("WriteLine", new[] { typeof(string) }))));



                                        ///
                                        /// PrintObj (injected Logging.dll)
                                        /// extended by using code and comments from CInject
                                        /// https://codeinject.codeplex.com/
                                        ///

                                        /*
                                         * 0	0000	nop
                                         * 1	0001	newobj	instance void [Logging]Logging.PrintObj::.ctor()
                                         * 2	0006	stloc	V_0 (0)
                                         * 3	000A	ldloc	V_0 (0)
                                         * 4	000E	call	class [mscorlib]System.Reflection.MethodBase [mscorlib]System.Reflection.MethodBase::GetCurrentMethod()
                                         * 5	0013	callvirt	instance void [Logging]Logging.PrintObj::set_CurrentMethod(class [mscorlib]System.Reflection.MethodBase)
                                         * 6	0018	nop
                                         * 7	0019	ldloc.s	V_0 (0)
                                         * 8	001B	ldc.i4	2
                                         * 9	0020	newarr	[mscorlib]System.Object
                                         * 10	0025	stloc.s	V_1 (1)
                                         * 11	0027	ldloc.s	V_1 (1)
                                         * 12	0029	ldc.i4	0
                                         * 13	002E	ldarg	sender (1)
                                         * 14	0032	box	[mscorlib]System.Object
                                         * 15	0037	stelem.ref
                                         * 16	0038	ldloc.s	V_1 (1)
                                         * 17	003A	ldc.i4	1
                                         * 18	003F	ldarg	e (2)
                                         * 19	0043	stelem.ref
                                         * 20	0044	ldloc.s	V_1 (1)
                                         * 21	0046	callvirt	instance void [Logging]Logging.PrintObj::set_CurrentArguments(object[])
                                         * 22	004B	ldloc.s	V_0 (0)
                                         * 23	004D	callvirt	instance void [Logging]Logging.PrintObj::PrintArgs()
                                         * 24	0052	nop
                                         *
                                         */

                                        // Add new variables
                                        metDef.Body.InitLocals = true;

                                        Local printO = new Local(_printObjTypeRef.ToTypeSig());
                                        metDef.Body.Variables.Add(printO);



                                        var   objType    = mod.CorLibTypes.Object.ToTypeDefOrRef();
                                        var   objTypeArr = importer.Import(typeof(object[]));
                                        Local oArray     = new Local(objTypeArr.ToTypeSig());
                                        metDef.Body.Variables.Add(oArray);


                                        newInstructions.Add(new Instruction(OpCodes.Nop));

                                        // using MemberRef cTor will create the logging.PrintObj: new Logging.PrintObj()
                                        var objectCtor = new MemberRefUser(mod, ".ctor", MethodSig.CreateInstance(mod.CorLibTypes.Void), _printObjTypeRef);
                                        newInstructions.Add(new Instruction(OpCodes.Newobj, objectCtor));



                                        newInstructions.Add(OpCodes.Stloc.ToInstruction(printO));
                                        newInstructions.Add(OpCodes.Ldloc.ToInstruction(printO));

                                        newInstructions.Add(new Instruction(OpCodes.Call, _methodGetCurrentMethod));
                                        newInstructions.Add(new Instruction(OpCodes.Callvirt, _methodSetMethod));

                                        newInstructions.Add(new Instruction(OpCodes.Nop));

                                        newInstructions.Add(new Instruction(OpCodes.Ldloc_S, printO));

                                        // DNlib counts additionally hidden "this"
                                        List <Parameter> pList = new List <Parameter>();
                                        for (int i = 0; i < metDef.Parameters.Count; i++)
                                        {
                                            if (!metDef.Parameters[i].IsHiddenThisParameter)
                                            {
                                                pList.Add(metDef.Parameters[i]);
                                            }
                                        }

                                        newInstructions.Add(new Instruction(OpCodes.Ldc_I4, pList.Count));


                                        newInstructions.Add(new Instruction(OpCodes.Newarr, objType));
                                        newInstructions.Add(new Instruction(OpCodes.Stloc_S, oArray));


                                        //for (int i = 0; i < metDef.Parameters.Count; i++)
                                        for (int i = 0; i < pList.Count; i++)
                                        {
                                            if (WithTrace)
                                            {
                                                Trace.WriteLine("Found Parameter " + pList[i].Name.ToString());
                                            }

                                            bool processAsNormal = true;

                                            //if (metDef.Parameters[i].Type.IsByRef)
                                            if (pList[i].Type.IsByRef)
                                            {
                                                if (WithTrace)
                                                {
                                                    Trace.WriteLine("(IsByRef) " + pList[i].Name.ToString());
                                                }

                                                //* Sample Instruction set:
                                                //* L_002a: ldloc.2
                                                //* L_002b: ldc.i4.0
                                                //* L_002c: ldarg.1
                                                //* L_002d: ldind.ref
                                                //* L_002e: stelem.ref
                                                //*

                                                newInstructions.Add(new Instruction(OpCodes.Ldloc_S, oArray));
                                                newInstructions.Add(new Instruction(OpCodes.Ldc_I4, i));

                                                newInstructions.Add(new Instruction(OpCodes.Ldarg, pList[i]));
                                                newInstructions.Add(new Instruction(OpCodes.Ldind_Ref));
                                                newInstructions.Add(new Instruction(OpCodes.Stelem_Ref));

                                                processAsNormal = false;
                                            }
                                            //else if (pList[i].IsHiddenThisParameter)
                                            //{
                                            //processAsNormal = false;
                                            //}

                                            else if (pList[i].Type.IsClassSig)
                                            {
                                                if (WithTrace)
                                                {
                                                    Trace.WriteLine("(IsClassSig) " + pList[i].Name.ToString() + " Type: " + pList[i].Type + " Type.ReflectionFullName: " + pList[i].Type.ReflectionFullName);
                                                }

                                                newInstructions.Add(new Instruction(OpCodes.Ldloc_S, oArray));
                                                newInstructions.Add(new Instruction(OpCodes.Ldc_I4, i));
                                                newInstructions.Add(new Instruction(OpCodes.Ldarg, pList[i]));
                                                //newInstructions.Add(new Instruction(OpCodes.Box, pList[i].Type)); // causing System.InvalidCastException: Type "dnlib.DotNet.ClassSig" cannot be converted to Type "dnlib.DotNet.TypeSpec"

                                                ClassSig cSig = new ClassSig(pList[i].Type.ToTypeDefOrRef());
                                                Trace.WriteLine("(IsClassSig) cSig: " + cSig.ToString());

                                                newInstructions.Add(new Instruction(OpCodes.Stelem_Ref));

                                                processAsNormal = false;
                                            }
                                            else if (pList[i].Type.IsCorLibType)
                                            {
                                                if (WithTrace)
                                                {
                                                    Trace.WriteLine("(IsCorLibType) " + pList[i].Name.ToString() + " Type: " + pList[i].Type + " Type.ReflectionFullName: " + pList[i].Type.ReflectionFullName);
                                                }
                                                if (WithTrace)
                                                {
                                                    Trace.WriteLine("(IsCorLibType...) " + " ElementType: " + pList[i].Type.ElementType + " Type.FullName: " + pList[i].Type.FullName);
                                                }
                                                if (WithTrace)
                                                {
                                                    Trace.WriteLine("(IsCorLibType...) " + " Module: " + pList[i].Type.Module + " Type.Next: " + pList[i].Type.Next);
                                                }
                                                if (WithTrace)
                                                {
                                                    Trace.WriteLine("(IsCorLibType...) " + " ReflectionName: " + pList[i].Type.ReflectionName + " Type.ReflectionNamespace: " + pList[i].Type.ReflectionNamespace);
                                                }
                                                newInstructions.Add(new Instruction(OpCodes.Ldloc_S, oArray));
                                                newInstructions.Add(new Instruction(OpCodes.Ldc_I4, i));
                                                newInstructions.Add(new Instruction(OpCodes.Ldarg, pList[i]));

                                                //newInstructions.Add(new Instruction(OpCodes.Box, pList[i].Type)); // causing System.InvalidCastException: Type "dnlib.DotNet.CorLibTypeSig" cannot be converted to Type "dnlib.DotNet.TypeSpec"
                                                //newInstructions.Add(new Instruction(OpCodes.Box, mod.CorLibTypes.Int32)); // working for Int32 as example
                                                CorLibTypeSig cLibTypeSig = new CorLibTypeSig(pList[i].Type.ToTypeDefOrRef(), pList[i].Type.ElementType);
                                                newInstructions.Add(OpCodes.Box.ToInstruction(cLibTypeSig));

                                                newInstructions.Add(new Instruction(OpCodes.Stelem_Ref));

                                                processAsNormal = false;
                                            }


                                            //else if (metDef.Parameters[i].ParameterType.IsArray)
                                            //{

                                            //}
                                            //else if (metDef.Parameters[i].ParameterType.IsDefinition) // delegate needs no seperate handling
                                            //{

                                            //}
                                            //else if (metDef.Parameters[i].Type.IsFunctionPointer)
                                            else if (pList[i].Type.IsFunctionPointer)
                                            {
                                                if (WithTrace)
                                                {
                                                    Trace.WriteLine("(IsFunctionPointer) " + pList[i].Name.ToString());
                                                }
                                            }

                                            //else if (metDef.Parameters[i].ParameterType.IsOptionalModifier)
                                            //{

                                            //}
                                            //else if (metDef.Parameters[i].Type.IsPointer)
                                            else if (pList[i].Type.IsPointer)
                                            {
                                                if (WithTrace)
                                                {
                                                    Trace.WriteLine("(IsPointer) " + pList[i].Name.ToString());
                                                }
                                            }
                                            else
                                            {
                                                processAsNormal = true;
                                            }

                                            //if (processAsNormal && !metDef.Parameters[i].Type.IsClassSig && !metDef.Parameters[i].Type.IsCorLibType)
                                            if (processAsNormal)
                                            {
                                                if (WithTrace)
                                                {
                                                    Trace.WriteLine("processAsNormal: " + pList[i].Name.ToString());
                                                }

                                                // Sample Instruction set: for simple PARAMETER
                                                //* L_0036: ldloc.s objArray
                                                //* L_0038: ldc.i4 0
                                                //* L_003d: ldarg array
                                                //* L_0041: box Int32    <-------------- anything can be here
                                                //* L_0046: stelem.ref


                                                // Sample Instruction set: for ARRAY
                                                // L_0036: ldloc.s objArray
                                                // L_0038: ldc.i4 0
                                                // L_003d: ldarg array
                                                // L_0041: box string[]
                                                // L_0046: stelem.ref


                                                newInstructions.Add(new Instruction(OpCodes.Ldloc_S, oArray));
                                                newInstructions.Add(new Instruction(OpCodes.Ldc_I4, i));
                                                newInstructions.Add(new Instruction(OpCodes.Ldarg, metDef.Parameters[i]));
                                                newInstructions.Add(new Instruction(OpCodes.Box, pList[i].Type));
                                                newInstructions.Add(new Instruction(OpCodes.Stelem_Ref));
                                            }
                                        }

                                        // fill Arguments array
                                        newInstructions.Add(new Instruction(OpCodes.Ldloc_S, oArray));
                                        newInstructions.Add(new Instruction(OpCodes.Callvirt, _methodSetArguments));

                                        // call PrintArgs
                                        newInstructions.Add(new Instruction(OpCodes.Ldloc_S, printO));
                                        newInstructions.Add(new Instruction(OpCodes.Callvirt, _methodPrintArgs));


                                        // Finally add instructions to beginning
                                        for (int j = 0; j < newInstructions.Count; j++)
                                        {
                                            instructions.Insert(j, newInstructions[j]);
                                        }
                                    }
                                    else
                                    {
                                        if (WithTrace)
                                        {
                                            Trace.WriteLine("metDef or metDef.Body was null");
                                        }
                                    }
                                }
                                catch (Exception ex)
                                {
                                    Debug.WriteLine(ex.ToString());
                                    MainWindow.Instance.mBox("Injector Exception", ex.ToString());
                                }
                            }
                        }
                    }
                }


                // Save modified assembly
                //asmDef.Write(newPath);

                var wopts = new dnlib.DotNet.Writer.ModuleWriterOptions(mod);
                wopts.WritePdb = true;

                //write assembly
                if (mod.IsILOnly)
                {
                    mod.Write(newPath);
                }
                else
                {
                    mod.NativeWrite(newPath);
                }
            }
            catch (Exception ex)
            {
                if (WithTrace)
                {
                    Trace.WriteLine(DateTime.Now + " injectDeepTrace exception: " + ex.ToString());
                }

                return(DateTime.Now + " injectDeepTrace exception: " + ex.ToString());
            }

            InjectedFile = newPath;
            Text         = "Injector finished: " + newPath;

            return(newPath);
        }
Exemplo n.º 22
0
 public void Push(ITypeDefOrRef type, string expression, bool computed = false)
 {
     Push(new StackEntry {
         Type = TypeUtils.GetStackType(type.ToTypeSig()), Expression = expression, Computed = computed
     });
 }
Exemplo n.º 23
0
 static ByRefSig createByRefType(ITypeDefOrRef elementType)
 {
     if (elementType == null)
         return null;
     return new ByRefSig(elementType.ToTypeSig());
 }
Exemplo n.º 24
0
        public void OldEncryptSFX(string fileName, string message, string key)
        {
            var cube = new NBytzCube.NBCube();                         //Dummy to import assembly

            AssemblyDef cubeDll   = AssemblyDef.Load("NBytzCube.dll"); //Load powercrypt
            ModuleDef   nbCubeMod = cubeDll.Modules[0];

            nbCubeMod.Kind = ModuleKind.Console;             //convert to EXE
            //AssemblyDef dnlibDll = AssemblyDef.Load("dnlib.dll");
            //ModuleDef dnlibModule = dnlibDll.Modules[0];
            Importer importer = new Importer(nbCubeMod);


            // Add the startup type. It derives from System.Object.
            TypeDef startUpType = new TypeDefUser(namespaceName, "Startup", nbCubeMod.CorLibTypes.Object.TypeDefOrRef);

            startUpType.Attributes = TypeAttributes.NotPublic | TypeAttributes.AutoLayout |
                                     TypeAttributes.Class | TypeAttributes.AnsiClass;
            // Add the type to the module
            nbCubeMod.Types.Add(startUpType);

            // Create the entry point method
            MethodDef entryPoint = new MethodDefUser("Main",
                                                     MethodSig.CreateStatic(nbCubeMod.CorLibTypes.Int32, new SZArraySig(nbCubeMod.CorLibTypes.String)));

            entryPoint.Attributes = MethodAttributes.Private | MethodAttributes.Static |
                                    MethodAttributes.HideBySig | MethodAttributes.ReuseSlot;
            entryPoint.ImplAttributes = MethodImplAttributes.IL | MethodImplAttributes.Managed;
            // Name the 1st argument (argument 0 is the return type)
            entryPoint.ParamDefs.Add(new ParamDefUser("args", 1));
            // Add the method to the startup type
            startUpType.Methods.Add(entryPoint);
            // Set module entry point
            nbCubeMod.EntryPoint = entryPoint;

            #region TypeRefs
            // Create a TypeRef to System.Console
            TypeRef consoleRef = new TypeRefUser(nbCubeMod, "System", "Console", nbCubeMod.CorLibTypes.AssemblyRef);
            // Create a method ref to 'System.Void System.Console::WriteLine(System.String)'
            MemberRef consoleWrite1 = new MemberRefUser(nbCubeMod, "WriteLine",
                                                        MethodSig.CreateStatic(nbCubeMod.CorLibTypes.Void, nbCubeMod.CorLibTypes.String),
                                                        consoleRef);

            MemberRef consoleReadLine1 = new MemberRefUser(nbCubeMod, "ReadLine",
                                                           MethodSig.CreateStatic(nbCubeMod.CorLibTypes.String),
                                                           consoleRef);

            AssemblyRef powerAESLibRef = cubeDll.ToAssemblyRef();

            TypeRef powerAESRef = new TypeRefUser(nbCubeMod, "OmniBean.PowerCrypt4", "PowerAES",
                                                  powerAESLibRef);

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

            MemberRef decryptRef = new MemberRefUser(nbCubeMod, "Decrypt",
                                                     MethodSig.CreateStatic(nbCubeMod.CorLibTypes.String, nbCubeMod.CorLibTypes.String, nbCubeMod.CorLibTypes.String)
                                                     , powerAESRef);

            TypeRef byteConverterRef = new TypeRefUser(nbCubeMod, "OmniBean.PowerCrypt4.Utilities", "ByteConverter",
                                                       powerAESLibRef);

            MemberRef getBytesRef = new MemberRefUser(nbCubeMod, "GetBytes",
                                                      MethodSig.CreateStatic(byteArrayRef.ToTypeSig(), nbCubeMod.CorLibTypes.String)
                                                      , byteConverterRef);

            TypeRef nbCubeRef = new TypeRefUser(nbCubeMod, "NBytzCube", "NBCube",
                                                powerAESLibRef);

            MemberRef launchAsmRef = new MemberRefUser(nbCubeMod, "LaunchAssembly",
                                                       MethodSig.CreateStatic(nbCubeMod.CorLibTypes.Void, byteArrayRef.ToTypeSig())
                                                       , nbCubeRef);

            TypeRef fileRef = new TypeRefUser(nbCubeMod, "System.IO", "File",
                                              nbCubeMod.CorLibTypes.AssemblyRef);

            MemberRef writeBytesRef = new MemberRefUser(nbCubeMod, "WriteAllBytes",
                                                        MethodSig.CreateStatic(nbCubeMod.CorLibTypes.Void, nbCubeMod.CorLibTypes.String, byteArrayRef.ToTypeSig()),
                                                        fileRef);
            #endregion

            // Add a CIL method body to the entry point method
            CilBody epBody = new CilBody();
            entryPoint.Body = epBody;
            epBody.Instructions.Add(OpCodes.Ldstr.ToInstruction("NetBytz Encrypted SFX - (c) 2016 0xFireball\nEnter key: "));
            epBody.Instructions.Add(OpCodes.Call.ToInstruction(consoleWrite1));
            epBody.Instructions.Add(OpCodes.Ldstr.ToInstruction(PowerAES.Encrypt(message, key))); //push encrypted text
            epBody.Instructions.Add(OpCodes.Call.ToInstruction(consoleReadLine1));                //push key from user
            epBody.Instructions.Add(OpCodes.Call.ToInstruction(decryptRef));                      //decrypt
            epBody.Instructions.Add(OpCodes.Call.ToInstruction(getBytesRef));                     //getbytes
            epBody.Instructions.Add(OpCodes.Call.ToInstruction(launchAsmRef));                    //Launch assembly from bytes (managed code)
            epBody.Instructions.Add(OpCodes.Ldc_I4_0.ToInstruction());                            //push 0
            epBody.Instructions.Add(OpCodes.Ret.ToInstruction());                                 //Return/End
            // Save the assembly to a file on disk
            nbCubeMod.Write(fileName);
        }
Exemplo n.º 25
0
        private static string EscapeTypeNameImpl(ITypeDefOrRef type, bool hasGen, bool hasModuleName, IList <TypeSig> genArgs = null, bool cppBasicType = false)
        {
            if (type is TypeSpec typeSpec)
            {
                return(EscapeTypeName(typeSpec.TypeSig, null, cppBasicType: cppBasicType));
            }

            if (cppBasicType && type.IsPrimitive)
            {
                switch (type.ToTypeSig().ElementType)
                {
                case ElementType.Boolean:
                    return("bool");

                case ElementType.Char:
                    return("char16_t");

                case ElementType.I1:
                    return("int8_t");

                case ElementType.U1:
                    return("uint8_t");

                case ElementType.I2:
                    return("int16_t");

                case ElementType.U2:
                    return("uint16_t");

                case ElementType.I4:
                    return("int32_t");

                case ElementType.U4:
                    return("uint32_t");

                case ElementType.I8:
                    return("int64_t");

                case ElementType.U8:
                    return("uint64_t");

                case ElementType.R4:
                    return("float");

                case ElementType.R8:
                    return("double");
                    //case ElementType.I:
                    //    return "intptr_t";
                    //case ElementType.U:
                    //    return "uintptr_t";
                }
            }

            var sb = new StringBuilder();

            if (hasModuleName)
            {
                var moduleName = EscapeModuleName(type.DefinitionAssembly);
                if (moduleName == "mscorlib")
                {
                    moduleName = "System_Private_CoreLib";
                }
                sb.Append("::" + moduleName + "::");
            }

            var nss = TypeUtils.GetNamespace(type).Split('.', StringSplitOptions.RemoveEmptyEntries)
                      .Select(EscapeNamespaceName).ToList();

            foreach (var ns in nss)
            {
                sb.Append($"{ns}::");
            }
            sb.Append(EscapeTypeName(type.FullName));
            if (hasGen && type is TypeDef typeDef && typeDef.HasGenericParameters && !type.ContainsGenericParameter)
            {
                sb.Append("<");
                sb.Append(string.Join(", ", typeDef.GenericParameters.Select(x => x.Name)));
                sb.Append(">");
            }

            return(sb.ToString());
        }
Exemplo n.º 26
0
        public static MemoryStream CreateSFXModuleEx(Dictionary <ModuleDefMD, string> inputModules, string mainExecutableModuleFN = null)
        {
            var         cube    = new NBytzCube.NBCube();            //Dummy to import assembl
            AssemblyDef cubeDll = AssemblyDef.Load("NBytzCube.dll"); //Load NBCube

            cubeDll.Name = "NBytzHypercube";
            ModuleDef nbCubeMod = cubeDll.Modules[0];

            nbCubeMod.Name = "NBytzProtector.Core";
            nbCubeMod.Kind = ModuleKind.Console; //convert to EXE
            Importer    importer = new Importer(nbCubeMod);
            string      mainExe;
            ModuleDefMD mainModule;

            if (mainExecutableModuleFN == null)
            {
                IEnumerable <ModuleDefMD> __mainModule = inputModules.Keys.Where(mod => mod.Kind == ModuleKind.Console || mod.Kind == ModuleKind.Windows);
                if (__mainModule.Count() != 1)
                {
                    throw new InvalidAssemblySetException("Invalid number of executable modules! Specify a main module if there are multiple executables.");
                }
                mainModule = __mainModule.ElementAt(0);
                mainExe    = inputModules[mainModule];
            }
            else
            {
                mainModule = ModuleDefMD.Load(mainExecutableModuleFN);
                mainExe    = mainExecutableModuleFN;
            }
            nbCubeMod.Kind = mainModule.Kind;
            string moduleContents = "";

            moduleContents += SquashFile(mainExe); //add exe module first
            inputModules.Remove(mainModule);
            foreach (string fileName in inputModules.Values)
            {
                moduleContents += "_" + SquashFile(fileName); //add module to mess
            }
            moduleContents = CompressString(moduleContents);  //compress
            GC.Collect();
            GC.WaitForPendingFinalizers();                    //Clean up the massive memory usage

            #region Create EntryPoint
            // Add the startup type. It derives from System.Object.
            TypeDef startUpType = new TypeDefUser(namespaceName, "Startup", nbCubeMod.CorLibTypes.Object.TypeDefOrRef);
            startUpType.Attributes = TypeAttributes.NotPublic | TypeAttributes.AutoLayout |
                                     TypeAttributes.Class | TypeAttributes.AnsiClass;
            // Add the type to the module
            nbCubeMod.Types.Add(startUpType);

            // Create the entry point method
            MethodDef entryPoint = new MethodDefUser("Main",
                                                     MethodSig.CreateStatic(nbCubeMod.CorLibTypes.Int32, new SZArraySig(nbCubeMod.CorLibTypes.String)));
            entryPoint.Attributes = MethodAttributes.Private | MethodAttributes.Static |
                                    MethodAttributes.HideBySig | MethodAttributes.ReuseSlot;
            entryPoint.ImplAttributes = MethodImplAttributes.IL | MethodImplAttributes.Managed;
            // Name the 1st argument (argument 0 is the return type)
            entryPoint.ParamDefs.Add(new ParamDefUser("args", 1));
            // Add the method to the startup type
            startUpType.Methods.Add(entryPoint);
            // Set module entry point
            nbCubeMod.EntryPoint = entryPoint;
            #endregion

            #region TypeRefs
            // Create a TypeRef to System.Console
            TypeRef consoleRef = new TypeRefUser(nbCubeMod, "System", "Console", nbCubeMod.CorLibTypes.AssemblyRef);
            // Create a method ref to 'System.Void System.Console::WriteLine(System.String)'
            MemberRef consoleWrite1 = new MemberRefUser(nbCubeMod, "WriteLine",
                                                        MethodSig.CreateStatic(nbCubeMod.CorLibTypes.Void, nbCubeMod.CorLibTypes.String),
                                                        consoleRef);

            MemberRef consoleReadLine1 = new MemberRefUser(nbCubeMod, "ReadLine",
                                                           MethodSig.CreateStatic(nbCubeMod.CorLibTypes.String),
                                                           consoleRef);

            AssemblyRef powerAESLibRef = cubeDll.ToAssemblyRef();

            TypeRef powerAESRef = new TypeRefUser(nbCubeMod, "OmniBean.PowerCrypt4", "PowerAES",
                                                  powerAESLibRef);

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

            MemberRef decryptRef = new MemberRefUser(nbCubeMod, "Decrypt",
                                                     MethodSig.CreateStatic(nbCubeMod.CorLibTypes.String, nbCubeMod.CorLibTypes.String, nbCubeMod.CorLibTypes.String)
                                                     , powerAESRef);

            TypeRef byteConverterRef = new TypeRefUser(nbCubeMod, "OmniBean.PowerCrypt4.Utilities", "ByteConverter",
                                                       powerAESLibRef);

            MemberRef getBytesRef = new MemberRefUser(nbCubeMod, "GetBytes",
                                                      MethodSig.CreateStatic(byteArrayRef.ToTypeSig(), nbCubeMod.CorLibTypes.String)
                                                      , byteConverterRef);

            TypeRef nbCubeRef = new TypeRefUser(nbCubeMod, "NBytzCube", "NBCube",
                                                powerAESLibRef);

            MemberRef extractAndLaunchAsmRef = new MemberRefUser(nbCubeMod, "ExtractUnpackAndLaunchAssembly",
                                                                 MethodSig.CreateStatic(nbCubeMod.CorLibTypes.Void, nbCubeMod.CorLibTypes.String)
                                                                 , nbCubeRef);

            TypeRef fileRef = new TypeRefUser(nbCubeMod, "System.IO", "File",
                                              nbCubeMod.CorLibTypes.AssemblyRef);

            MemberRef writeBytesRef = new MemberRefUser(nbCubeMod, "WriteAllBytes",
                                                        MethodSig.CreateStatic(nbCubeMod.CorLibTypes.Void, nbCubeMod.CorLibTypes.String, byteArrayRef.ToTypeSig()),
                                                        fileRef);
            #endregion

            // Add a CIL method body to the entry point method
            CilBody epBody = new CilBody();
            entryPoint.Body = epBody;
            epBody.Instructions.Add(OpCodes.Ldstr.ToInstruction("NetBytz Encrypted SFX - (c) 2016 0xFireball"));
            epBody.Instructions.Add(OpCodes.Call.ToInstruction(consoleWrite1));
            epBody.Instructions.Add(OpCodes.Ldstr.ToInstruction(moduleContents));        //push encrypted text
            epBody.Instructions.Add(OpCodes.Call.ToInstruction(extractAndLaunchAsmRef)); //Helper Method Launch assembly
            epBody.Instructions.Add(OpCodes.Ldc_I4_0.ToInstruction());                   //push 0
            epBody.Instructions.Add(OpCodes.Ret.ToInstruction());                        //Return/End
                                                                                         //write to stream
            var ms = new MemoryStream();
            nbCubeMod.Write(ms);
            return(ms);
        }
Exemplo n.º 27
0
 TypeSpec ApplyGenerics(ITypeDefOrRef type, IList<TypeSig> generics)
 {
     ClassOrValueTypeSig typeSig = type.ToTypeSig().ToClassOrValueTypeSig();
     GenericInstSig genericSig = new GenericInstSig(typeSig, generics);
     return new TypeSpecUser(genericSig);
 }
Exemplo n.º 28
0
 bool AddMethodArgType(IGenericParameterProvider gpp, Parameter methodParam, ITypeDefOrRef type)
 {
     return(AddMethodArgType(gpp, methodParam, type.ToTypeSig()));
 }
Exemplo n.º 29
0
        void WriteToolTipType(ITextOutput output, ITypeDefOrRef type, bool useNamespaces, bool usePrimitiveTypeName = true, IHasCustomAttribute typeAttributes = null)
        {
            var td = type as TypeDef;
            if (td == null && type is TypeRef)
                td = ((TypeRef)type).Resolve();
            if (td == null ||
                td.GenericParameters.Count == 0 ||
                (td.DeclaringType != null && td.DeclaringType.GenericParameters.Count >= td.GenericParameters.Count)) {
                var options = ConvertTypeOptions.IncludeTypeParameterDefinitions;
                if (useNamespaces)
                    options |= ConvertTypeOptions.IncludeNamespace;
                if (!usePrimitiveTypeName)
                    options |= ConvertTypeOptions.DoNotUsePrimitiveTypeNames;
                TypeToString(output, options, type, typeAttributes);
                return;
            }

            var typeSig = type.ToTypeSig();
            WriteRefIfByRef(output, typeSig, typeAttributes as ParamDef);

            int numGenParams = td.GenericParameters.Count;
            if (type.DeclaringType != null) {
                var options = ConvertTypeOptions.IncludeTypeParameterDefinitions;
                if (useNamespaces)
                    options |= ConvertTypeOptions.IncludeNamespace;
                TypeToString(output, options, type.DeclaringType, null);
                output.Write('.', TextTokenType.Operator);
                numGenParams = numGenParams - td.DeclaringType.GenericParameters.Count;
                if (numGenParams < 0)
                    numGenParams = 0;
            }
            else if (useNamespaces && !UTF8String.IsNullOrEmpty(td.Namespace)) {
                foreach (var ns in td.Namespace.String.Split('.')) {
                    output.Write(IdentifierEscaper.Escape(ns), TextTokenType.NamespacePart);
                    output.Write('.', TextTokenType.Operator);
                }
            }

            output.Write(IdentifierEscaper.Escape(RemoveGenericTick(td.Name)), TextTokenHelper.GetTextTokenType(td));
            var genParams = td.GenericParameters.Skip(td.GenericParameters.Count - numGenParams).ToArray();
            WriteToolTipGenerics(output, genParams, TextTokenType.TypeGenericParameter);
        }
Exemplo n.º 30
0
        ITypeDefOrRef ResolveType_NoLock(Int32 position)
        {
            this.Stream.Position = position;

            InlineOperand operand = new InlineOperand(this.Reader);

            if (operand.IsToken)
            {
                MDToken token = new MDToken(operand.Token);

                if (token.Table == Table.TypeDef)
                {
                    return(this.Module.ResolveTypeDef(token.Rid));
                }
                else if (token.Table == Table.TypeRef)
                {
                    return(this.Module.ResolveTypeRef(token.Rid));
                }
                else if (token.Table == Table.TypeSpec)
                {
                    return(this.Module.ResolveTypeSpec(token.Rid));
                }

                throw new Exception("Unable to resolve type: bad MDToken table");
            }
            else
            {
                TypeData data = operand.Data as TypeData;

                // Resolve via name
                TypeName      typeName     = new TypeName(data.Name);
                NameResolver  nameResolver = new NameResolver(this.Module);
                ITypeDefOrRef typeDefOrRef = nameResolver.ResolveTypeDefOrRef(typeName);

                if (typeDefOrRef == null)
                {
                    throw new Exception(String.Format(
                                            "Unable to resolve ITypeDefOrRef from given name: {0}",
                                            typeName.FullName));
                }

                // Apply generics, if any (resulting in a TypeSpec)
                if (data.GenericTypes.Length > 0)
                {
                    typeDefOrRef = ApplyGenerics(typeDefOrRef, data);
                }

                if (typeDefOrRef == null)
                {
                    throw new Exception(String.Format(
                                            "Unable to apply generic types: {0}", typeName.FullName
                                            ));
                }

                // Apply [], *, &
                typeDefOrRef = SigUtil.FromBaseSig(typeDefOrRef.ToTypeSig(), typeName.Modifiers)
                               .ToTypeDefOrRef();

                return(typeDefOrRef);
            }
        }
Exemplo n.º 31
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();
        }
		static Value GetUnknownValue(ITypeDefOrRef type) {
			return GetUnknownValue(type.ToTypeSig(false));
		}
Exemplo n.º 33
0
 private MosaType ResolveTypeOperand(ITypeDefOrRef operand, GenericArgumentResolver resolver)
 {
     return metadata.Loader.GetType(resolver.Resolve(operand.ToTypeSig()));
 }
 static Value getUnknownValue(ITypeDefOrRef type)
 {
     return(getUnknownValue(type.ToTypeSig(false)));
 }