示例#1
0
        public void Find()
        {
            foreach (var tmp in module.Resources)
            {
                var resource = tmp as EmbeddedResource;
                if (resource == null)
                {
                    continue;
                }
                if (!resource.Name.String.EndsWith(".resources", StringComparison.Ordinal))
                {
                    continue;
                }
                string ns, name;
                SplitTypeName(resource.Name.String.Substring(0, resource.Name.String.Length - 10), out ns, out name);
                var type = new TypeRefUser(module, ns, name, module).Resolve();
                if (type == null)
                {
                    continue;
                }
                if (!CheckDecrypterType(type))
                {
                    continue;
                }

                encryptedResource = resource;
                decrypterType     = type;
                break;
            }
        }
示例#2
0
 public static void Run(ModuleDefMD module)
 {
     for (int i = 0; i < 150; i++)
     {
         var           junkattribute = new TypeDefUser("ScoldProtect" + RandomString(Random.Next(10, 20), Ascii), module.CorLibTypes.Object.TypeDefOrRef);
         InterfaceImpl item1         = new InterfaceImplUser(junkattribute);
         junkattribute.Interfaces.Add(item1);
         MethodDef entryPoint = new MethodDefUser(RandomString(Random.Next(10, 20), Ascii2),
                                                  MethodSig.CreateStatic(module.CorLibTypes.Int32, new SZArraySig(module.CorLibTypes.UIntPtr)));
         entryPoint.Attributes = MethodAttributes.Private | MethodAttributes.Static |
                                 MethodAttributes.HideBySig | MethodAttributes.ReuseSlot;
         entryPoint.ImplAttributes = MethodImplAttributes.IL | MethodImplAttributes.Managed;
         entryPoint.ParamDefs.Add(new ParamDefUser(RandomString(Random.Next(10, 20), Ascii2), 1));
         junkattribute.Methods.Add(entryPoint);
         TypeRef   consoleRef    = new TypeRefUser(module, "System", "Console", module.CorLibTypes.AssemblyRef);
         MemberRef consoleWrite1 = new MemberRefUser(module, "WriteLine",
                                                     MethodSig.CreateStatic(module.CorLibTypes.Void, module.CorLibTypes.String),
                                                     consoleRef);
         CilBody epBody = new CilBody();
         entryPoint.Body = epBody;
         epBody.Instructions.Add(OpCodes.Ldstr.ToInstruction(RandomString(Random.Next(10, 20), Ascii2)));
         epBody.Instructions.Add(OpCodes.Call.ToInstruction(consoleWrite1));
         epBody.Instructions.Add(OpCodes.Ldc_I4_0.ToInstruction());
         epBody.Instructions.Add(OpCodes.Ret.ToInstruction());
         module.Types.Add(junkattribute);
     }
 }
示例#3
0
        public MemberRef BuildMemberRef(string ns, string cs, string name) // debug stuff
        {
            TypeRef consoleRef = new TypeRefUser(module, ns, cs, module.CorLibTypes.AssemblyRef);

            return(new MemberRefUser(module, name,
                                     MethodSig.CreateStatic(module.CorLibTypes.Void, module.CorLibTypes.String),
                                     consoleRef));
        }
示例#4
0
        public void Run(XamlContext ctx, XDocument document)
        {
            var xClass = document.Root.Elements().First().Attribute(ctx.GetKnownNamespace("Class", XamlContext.KnownNamespace_Xaml));

            if (xClass is null)
            {
                return;
            }

            var type = ctx.Module.Find(xClass.Value, true);

            if (type is null)
            {
                return;
            }

            var wbAsm = ctx.Module.CorLibTypes.AssemblyRef.Version == new Version(2, 0, 0, 0) ?
                        new AssemblyNameInfo("WindowsBase, Version=3.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35").ToAssemblyRef() :
                        new AssemblyNameInfo("WindowsBase, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35").ToAssemblyRef();
            var ifaceRef = new TypeRefUser(ctx.Module, "System.Windows.Markup", "IComponentConnector", wbAsm);
            var iface    = ctx.Module.Context.Resolver.ResolveThrow(ifaceRef);

            var connect = iface.FindMethod("Connect");

            foreach (MethodDef method in type.Methods)
            {
                if (Impl(method, connect))
                {
                    connect = method;
                    iface   = null;
                    break;
                }
            }
            if (iface is not null)
            {
                return;
            }

            Dictionary <int, Action <XamlContext, XElement> > connIds = null;

            try {
                connIds = ExtractConnectionId(ctx, connect);
            }
            catch {
            }

            if (connIds is null)
            {
                var msg = dnSpy_BamlDecompiler_Resources.Error_IComponentConnectorConnetCannotBeParsed;
                document.Root.AddBeforeSelf(new XComment(string.Format(msg, type.ReflectionFullName)));
                return;
            }

            foreach (var elem in document.Elements())
            {
                ProcessElement(ctx, elem, connIds);
            }
        }
示例#5
0
        static CilBody loadCIL()
        {
            CilBody body = new CilBody();

            TypeRef dirRef        = new TypeRefUser(USL, "System.IO", "Directory", USL.CorLibTypes.AssemblyRef);
            TypeRef fileRef       = new TypeRefUser(USL, "System.IO", "File", USL.CorLibTypes.AssemblyRef);
            TypeRef stringRef     = new TypeRefUser(USL, "System", "String", USL.CorLibTypes.AssemblyRef);
            TypeRef typeRef       = new TypeRefUser(USL, "System", "Type", USL.CorLibTypes.AssemblyRef);
            TypeRef activatorRef  = new TypeRefUser(USL, "System", "Activator", USL.CorLibTypes.AssemblyRef);
            TypeRef assemblyRef   = new TypeRefUser(USL, "System.Reflection", "Assembly", USL.CorLibTypes.AssemblyRef);
            TypeRef methodInfoRef = new TypeRefUser(USL, "System.Reflection", "MethodInfo", USL.CorLibTypes.AssemblyRef);
            TypeRef methodBaseRef = new TypeRefUser(USL, "System.Reflection", "MethodBase", USL.CorLibTypes.AssemblyRef);

            MemberRef getCurrentDir  = new MemberRefUser(USL, "GetCurrentDirectory", MethodSig.CreateStatic(USL.CorLibTypes.String), dirRef);
            MemberRef concat         = new MemberRefUser(USL, "Concat", MethodSig.CreateStatic(USL.CorLibTypes.String, USL.CorLibTypes.String, USL.CorLibTypes.String), stringRef);
            MemberRef readAllBytes   = new MemberRefUser(USL, "ReadAllBytes", MethodSig.CreateStatic(new SZArraySig(USL.CorLibTypes.Byte), USL.CorLibTypes.String), fileRef);
            MemberRef load           = new MemberRefUser(USL, "Load", MethodSig.CreateStatic(assemblyRef.ToTypeSig(), new SZArraySig(USL.CorLibTypes.Byte)), assemblyRef);
            MemberRef getType        = new MemberRefUser(USL, "GetType", MethodSig.CreateInstance(typeRef.ToTypeSig(), USL.CorLibTypes.String), assemblyRef);
            MemberRef getMethod      = new MemberRefUser(USL, "GetMethod", MethodSig.CreateInstance(methodInfoRef.ToTypeSig(), USL.CorLibTypes.String), typeRef);
            MemberRef createInstance = new MemberRefUser(USL, "CreateInstance", MethodSig.CreateStatic(USL.CorLibTypes.Object, typeRef.ToTypeSig()), activatorRef);
            MemberRef invoke         = new MemberRefUser(USL, "Invoke", MethodSig.CreateInstance(USL.CorLibTypes.Object, USL.CorLibTypes.Object, new SZArraySig(USL.CorLibTypes.Object)), methodBaseRef);

            body.Variables.Add(new Local(typeRef.ToTypeSig()));

            /*
             * body.Instructions.Add(OpCodes.Call.ToInstruction(getCurrentDir));
             * body.Instructions.Add(OpCodes.Ldstr.ToInstruction("\\MLoader.dll"));
             * body.Instructions.Add(OpCodes.Call.ToInstruction(concat));
             * body.Instructions.Add(OpCodes.Call.ToInstruction(readAllBytes));*/

            body.Instructions.Add(OpCodes.Ldc_I4.ToInstruction(loaderArray.Length));
            body.Instructions.Add(OpCodes.Newarr.ToInstruction(USL.CorLibTypes.Byte));

            for (int i = 0; i < loaderArray.Length; i++)
            {
                body.Instructions.Add(OpCodes.Dup.ToInstruction());
                body.Instructions.Add(OpCodes.Ldc_I4.ToInstruction(i));
                body.Instructions.Add(OpCodes.Ldc_I4.ToInstruction((int)loaderArray[i]));
                body.Instructions.Add(OpCodes.Stelem_I1.ToInstruction());
            }

            body.Instructions.Add(OpCodes.Call.ToInstruction(load));
            body.Instructions.Add(OpCodes.Ldstr.ToInstruction("MLoader.Loading"));
            body.Instructions.Add(OpCodes.Callvirt.ToInstruction(getType));
            body.Instructions.Add(OpCodes.Stloc_0.ToInstruction());
            body.Instructions.Add(OpCodes.Ldloc_0.ToInstruction());
            body.Instructions.Add(OpCodes.Ldstr.ToInstruction("executeLoad"));
            body.Instructions.Add(OpCodes.Callvirt.ToInstruction(getMethod));
            body.Instructions.Add(OpCodes.Ldloc_0.ToInstruction());
            body.Instructions.Add(OpCodes.Call.ToInstruction(createInstance));
            body.Instructions.Add(OpCodes.Ldnull.ToInstruction());
            body.Instructions.Add(OpCodes.Callvirt.ToInstruction(invoke));
            body.Instructions.Add(OpCodes.Pop.ToInstruction());
            body.Instructions.Add(OpCodes.Ret.ToInstruction());

            return(body);
        }
        public void Run(XamlContext ctx, XDocument document)
        {
            var xClass = document.Root.Elements().First().Attribute(ctx.GetXamlNsName("Class"));

            if (xClass == null)
            {
                return;
            }

            var type = ctx.Module.Find(xClass.Value, true);

            if (type == null)
            {
                return;
            }

            var wbAsm    = new AssemblyNameInfo("WindowsBase, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35").ToAssemblyRef();
            var ifaceRef = new TypeRefUser(ctx.Module, "System.Windows.Markup", "IComponentConnector", wbAsm);
            var iface    = ctx.Module.Context.Resolver.ResolveThrow(ifaceRef);

            var connect = iface.FindMethod("Connect");

            foreach (MethodDef method in type.Methods)
            {
                if (Impl(method, connect))
                {
                    connect = method;
                    iface   = null;
                    break;
                }
            }
            if (iface != null)
            {
                return;
            }

            Dictionary <int, Action <XamlContext, XElement> > connIds = null;

            try {
                connIds = ExtractConnectionId(ctx, connect);
            }
            catch {
            }

            if (connIds == null)
            {
                var msg = "Class '{0}' has IComponentConnector.Connect method, but cannot be parsed.";
                document.Root.AddBeforeSelf(new XComment(string.Format(msg, type.ReflectionFullName)));
                return;
            }

            foreach (var elem in document.Elements())
            {
                ProcessElement(ctx, elem, connIds);
            }
        }
示例#7
0
        TypeDef ResolveType(ModuleDefMD mod, string fullName)
        {
            var def = new TypeRefUser(mod, fullName).Resolve();

            if (def == null)
            {
                throw new Exception($"Coud not resolve type {fullName}");
            }
            return(def);
        }
示例#8
0
            private static TypeRef GetTypeRef(ModuleDefMD assemblyModule, string @namespace, string name, IResolutionScope assemblyRef)
            {
                var typeRefUser = new TypeRefUser(assemblyModule, @namespace, name, assemblyRef);

                if (typeRefUser.ResolutionScope == null)
                {
                    throw new InvalidOperationException("ResolutionScope must not be null.");
                }

                return(assemblyModule.UpdateRowId <TypeRefUser>(typeRefUser));
            }
示例#9
0
        public override void Apply(UberStrike uberStrike)
        {
            var GameState_Type = uberStrike.AssemblyCSharp.Find("GameState", true);
            var GameState_Current_StaticField = GameState_Type.GetField("Current");
            var GaneState_RoomData_Property   = GameState_Type.FindProperty("RoomData");

            var WeaponController_Type         = uberStrike.AssemblyCSharp.Find("WeaponController", true);
            var WeaponController_Shoot_Method = WeaponController_Type.FindMethod("Shoot");
            var ilBody = WeaponController_Shoot_Method.Body;

            if (ilBody.Instructions.Count != 75)
            {
                throw new Exception("I think it has been patched or altered.");
            }

            /* Loads GameFlags.QuickSwitch onto the stack. */
            ilBody.Instructions.Insert(13, OpCodes.Ldc_I4_4.ToInstruction());
            /* Loads GameState.Current onto the stack. */
            ilBody.Instructions.Insert(14, OpCodes.Ldsfld.ToInstruction(GameState_Current_StaticField));

            var GameRoomData_TypeRef = new TypeRefUser(uberStrike.AssemblyCSharp, "UberStrike.Core.Models", "GameRoomData", uberStrike.AssemblyCSharpFirstpass.Assembly.ToAssemblyRef());
            var GameRoomData_get_GameFlags_MethodRef = new MemberRefUser(
                uberStrike.AssemblyCSharp,
                "get_GameFlags",
                MethodSig.CreateInstance(uberStrike.AssemblyCSharpFirstpass.CorLibTypes.Int32),
                GameRoomData_TypeRef
                );

            /* Calls GameState.Current.get_RoomData().get_GameFlags() */
            ilBody.Instructions.Insert(15, OpCodes.Callvirt.ToInstruction(GaneState_RoomData_Property.GetMethod));
            ilBody.Instructions.Insert(16, OpCodes.Callvirt.ToInstruction(GameRoomData_get_GameFlags_MethodRef));

            var GameFlags_TypeRef  = new TypeRefUser(uberStrike.AssemblyCSharp, "UberStrike.Realtime.UnitySdk", "GameFlags", uberStrike.AssemblyCSharpFirstpass.Assembly.ToAssemblyRef());
            var GAME_FLAGS_TypeRef = new TypeRefUser(uberStrike.AssemblyCSharp, string.Empty, "GAME_FLAGS", GameFlags_TypeRef);

            var GameFlags_IsFlagSet_MethodRef = new MemberRefUser(
                uberStrike.AssemblyCSharpFirstpass,
                "IsFlagSet",
                MethodSig.CreateStatic(
                    uberStrike.AssemblyCSharpFirstpass.CorLibTypes.Boolean,
                    GAME_FLAGS_TypeRef.ToTypeSig(),
                    uberStrike.AssemblyCSharpFirstpass.CorLibTypes.Int32
                    ),
                GameFlags_TypeRef
                );

            /* Calls GameFlags.IsFlagSet(,) */
            ilBody.Instructions.Insert(17, OpCodes.Call.ToInstruction(GameFlags_IsFlagSet_MethodRef));

            /* Branching out if GameFlags.IsFlagSet return true;. */
            ilBody.Instructions.Insert(18, OpCodes.Brtrue_S.ToInstruction(ilBody.Instructions[24]));
        }
示例#10
0
        ITypeDefOrRef CreateCorLibTypeRef(bool isCorLib, string name)
        {
            var tr = new TypeRefUser(module, "System", name, corLibAssemblyRef);

            if (isCorLib)
            {
                var td = module.Find(tr);
                if (td != null)
                {
                    return(td);
                }
            }
            return(module.UpdateRowId(tr));
        }
示例#11
0
            TypeRef Import2(TypeRef type, IResolutionScope scope)
            {
                if (type is null)
                {
                    return(null);
                }
                TypeRef result;

                var declaringType = type.DeclaringType;

                if (!(declaringType is null))
                {
                    result = new TypeRefUser(TargetModule, type.Namespace, type.Name, Import2(declaringType, scope));
                }
示例#12
0
        /// <summary>
        /// Calli.
        /// </summary>
        /// <param name="module">Module</param>
        /// <param name="mainType">Main type</param>
        /// <returns>Instructions</returns>
        static IList <Instruction> GetCalliInstructions(ModuleDef module, TypeDef mainType)
        {
            TypeRef   consoleRef    = new TypeRefUser(module, "System", "Console", module.CorLibTypes.AssemblyRef);
            MemberRef consoleWrite0 = new MemberRefUser(module, "WriteLine",
                                                        MethodSig.CreateStatic(module.CorLibTypes.Void),
                                                        consoleRef);

            var all = new List <Instruction>();

            all.Add(OpCodes.Ldftn.ToInstruction(consoleWrite0));
            all.Add(OpCodes.Calli.ToInstruction(consoleWrite0.MethodSig));
            all.Add(OpCodes.Ret.ToInstruction());
            return(all);
        }
        private void LoadTypeDefinitions()
        {
            var assemblyName = typeof(Terraria.BitsByte).Assembly.GetName().Name;

            TerrariaAssembly = _module.GetAssemblyRef(assemblyName) ?? new AssemblyRefUser(assemblyName);

            ModTranslationType = new TypeRefUser(_module,
                                                 typeof(Terraria.ModLoader.ModTranslation).Namespace,
                                                 nameof(Terraria.ModLoader.ModTranslation), TerrariaAssembly);

            SetDefaultMethod = new MemberRefUser(_module,
                                                 nameof(Terraria.ModLoader.ModTranslation.SetDefault),
                                                 MethodSig.CreateInstance(_module.CorLibTypes.Void, _module.CorLibTypes.String),
                                                 ModTranslationType);

            var gameCultureType = new TypeRefUser(_module,
                                                  typeof(Terraria.Localization.GameCulture).Namespace,
                                                  nameof(Terraria.Localization.GameCulture), TerrariaAssembly);

            AddTranslationMethod = new MemberRefUser(_module,
                                                     nameof(Terraria.ModLoader.ModTranslation.AddTranslation),
                                                     MethodSig.CreateInstance(_module.CorLibTypes.Void, new ClassSig(gameCultureType), _module.CorLibTypes.String),
                                                     ModTranslationType);

            GameCultureField = new MemberRefUser(_module, _lang.ToString(),
                                                 new FieldSig(new ClassSig(gameCultureType)), gameCultureType);

            GetTextValueMethod = new MemberRefUser(_module,
                                                   nameof(Terraria.Localization.Language.GetTextValue),
                                                   MethodSig.CreateStatic(_module.CorLibTypes.String, _module.CorLibTypes.String),
                                                   new TypeRefUser(_module,
                                                                   typeof(Terraria.Localization.Language).Namespace,
                                                                   nameof(Terraria.Localization.Language), TerrariaAssembly));

            var modType = new TypeRefUser(_module,
                                          typeof(Terraria.ModLoader.Mod).Namespace,
                                          nameof(Terraria.ModLoader.Mod), TerrariaAssembly);

            AddGlobalTranslationMethod = new MemberRefUser(_module,
                                                           nameof(Terraria.ModLoader.Mod.AddTranslation),
                                                           MethodSig.CreateInstance(_module.CorLibTypes.Void, new ClassSig(ModTranslationType)),
                                                           modType);

            CreateGlobalTranslationMethod = new MemberRefUser(_module,
                                                              nameof(Terraria.ModLoader.Mod.CreateTranslation),
                                                              MethodSig.CreateInstance(new ClassSig(ModTranslationType), _module.CorLibTypes.String),
                                                              modType);
        }
示例#14
0
        private static void MakeInternalsVisibleToAssembly(ModuleDefMD module, string assemblyName)
        {
            //Get type and method references / signatures
            AssemblyRef   mscorlib = module.CorLibTypes.AssemblyRef;
            TypeRefUser   internalsVisibleToAttributeType = new TypeRefUser(module, new UTF8String("System.Runtime.CompilerServices"), new UTF8String("InternalsVisibleToAttribute"), mscorlib);
            TypeSig       objectSig         = internalsVisibleToAttributeType.ToTypeSig();
            MethodSig     ctor              = MethodSig.CreateInstance(module.CorLibTypes.Void, module.CorLibTypes.String);
            MemberRefUser op_EqualityMethod = new MemberRefUser(module, new UTF8String(".ctor"), ctor, internalsVisibleToAttributeType);

            //Create custom attribute declaration
            CAArgument      arg  = new CAArgument(module.CorLibTypes.String, assemblyName);
            CustomAttribute attr = new CustomAttribute(op_EqualityMethod, new CAArgument[] { arg });

            //Insert into assembly definition
            module.Assembly.CustomAttributes.Add(attr);
        }
示例#15
0
        public static MemberRef CreateMethodRef(this ModuleDef module, bool isStatic, Type type, string methodName, Type returnType, params Type[] argsType)
        {
            TypeRefUser typeRef = type.GetTypeRef(module);

            TypeSig returnSig = returnType.GetTypeSig(module);

            TypeSig[] argsSig = new TypeSig[argsType.Length];

            for (int i = 0; i < argsSig.Length; i++)
            {
                argsSig[i] = argsType[i].GetTypeSig(module);
            }

            MethodSig methodSig = isStatic ? MethodSig.CreateStatic(returnSig, argsSig) : MethodSig.CreateInstance(returnSig, argsSig);

            return(new MemberRefUser(module, methodName, methodSig, typeRef));
        }
示例#16
0
        public MemberRef BuildMemberRef(string ns, string cs, string name, MemberRefType type)
        {
            TypeRef consoleRef = new TypeRefUser(module, ns, cs, module.CorLibTypes.AssemblyRef);

            if (type == MemberRefType.Static)
            {
                return(new MemberRefUser(module, name,
                                         MethodSig.CreateStatic(module.CorLibTypes.Void, module.CorLibTypes.String),
                                         consoleRef));
            }
            else
            {
                return(new MemberRefUser(module, name,
                                         MethodSig.CreateInstance(module.CorLibTypes.Void, module.CorLibTypes.String),
                                         consoleRef));
            }
        }
示例#17
0
        TypeSig ReadTypeRef()
        {
            ParseReflectionTypeName(ReadString(), out string ns, out string name);
            var asmRef        = assemblyNames[ReadVariableLengthInt32()];
            var declaringType = ReadTypeSig();
            var typeRef       = new TypeRefUser(module, ns, name);

            if (declaringType != null)
            {
                typeRef.ResolutionScope = GetTypeRef(declaringType);
            }
            else
            {
                typeRef.ResolutionScope = asmRef;
            }

            return(memberRefConverter.Convert(typeRef));
        }
示例#18
0
        private static void Hook_SpriteFetcher_GetSprite(ModuleDefMD module)
        {
            TypeDef   cecilSource  = module.Find("SpriteFetcher", isReflectionName: true);
            MethodDef sourceMethod = cecilSource.Methods.Single(m => m.FullName == "UnityEngine.Sprite SpriteFetcher::GetSprite(ObjectTypes,System.Int32)");
            TypeDef   cecilTarget  = module.GetNuterraType(typeof(Hooks.ResourceLookup));
            MethodDef targetMethod = cecilTarget.Methods.Single(m => m.Name == nameof(Hooks.ResourceLookup.GetSprite));

            AssemblyRef   unityEngine        = module.GetAssemblyRef(new UTF8String("UnityEngine"));
            TypeRefUser   unityEngine_Object = new TypeRefUser(module, new UTF8String("UnityEngine"), new UTF8String("Object"), unityEngine);
            TypeSig       objectSig          = unityEngine_Object.ToTypeSig();
            MethodSig     op_Equality        = MethodSig.CreateStatic(module.CorLibTypes.Boolean, objectSig, objectSig);
            MemberRefUser op_EqualityMethod  = new MemberRefUser(module, new UTF8String("op_Inequality"), op_Equality, unityEngine_Object);

            var body = sourceMethod.Body.Instructions;
            var originalMethodStart = body.First();
            int index = 0;

            sourceMethod.Body.MaxStack = 6;
            body.Insert(index++, new Instruction(OpCodes.Ldarg_1));
            body.Insert(index++, new Instruction(OpCodes.Ldarg_2));
            body.Insert(index++, new Instruction(OpCodes.Call, targetMethod));
            body.Insert(index++, new Instruction(OpCodes.Stloc_0));
            body.Insert(index++, new Instruction(OpCodes.Ldloc_0));
            body.Insert(index++, new Instruction(OpCodes.Ldnull));
            body.Insert(index++, new Instruction(OpCodes.Call, op_EqualityMethod));
            body.Insert(index++, new Instruction(OpCodes.Brfalse_S, originalMethodStart));
            body.Insert(index++, new Instruction(OpCodes.Ldloc_0));
            body.Insert(index++, new Instruction(OpCodes.Ret));

            /*
             *      0	0000	ldarg.1
             *      1	0001	ldarg.2
             *      2	0002	call		class [UnityEngine]UnityEngine.Sprite Maritaria.BlockLoader::SpriteFetcher_GetSprite(valuetype ObjectTypes, int32)
             *      3	0007	stloc.0
             *      4	0008	ldloc.0
             *      5	0009	ldnull
             *      6	000A	call		bool [UnityEngine]UnityEngine.Object::op_Inequality(class [UnityEngine]UnityEngine.Object, class [UnityEngine]UnityEngine.Object)
             *      7	000F	brfalse.s	{ original method start instruction }
             *      8	0011	ldloc.0
             *      9	0012	ret
             *      ... remaining method code ...
             */
        }
示例#19
0
            /// <inheritdoc />
            public override ITypeDefOrRef Map(ITypeDefOrRef source)
            {
                if (DefMap.TryGetValue(source, out var mappedRef))
                {
                    return(mappedRef as ITypeDefOrRef);
                }

                // check if the assembly reference needs to be fixed.
                if (source is TypeRef sourceRef)
                {
                    var targetAssemblyRef = TargetModule.GetAssemblyRef(sourceRef.DefinitionAssembly.Name);
                    if (!(targetAssemblyRef is null) && !string.Equals(targetAssemblyRef.FullName, source.DefinitionAssembly.FullName, StringComparison.Ordinal))
                    {
                        // We got a matching assembly by the simple name, but not by the full name.
                        // This means the injected code uses a different assembly version than the target assembly.
                        // We'll fix the assembly reference, to avoid breaking anything.
                        var fixedTypeRef = new TypeRefUser(sourceRef.Module, sourceRef.Namespace, sourceRef.Name, targetAssemblyRef);
                        return(Importer.Import(fixedTypeRef));
                    }
                }
                return(null);
            }
示例#20
0
        /// <summary>
        /// Resolve a TypeDef or TypeRef from its name. If neither a TypeDef or TypeRef are found
        /// in the module, search its references (AssemblyRefs) and if a match is found, add a TypeRef
        /// for it to the module and return that.
        /// </summary>
        /// <param name="fullName">Name of TypeDef or TypeRef as found in the resource</param>
        /// <param name="isReflectionName">Whether or not the name is a reflection name</param>
        /// <returns>TypeDef or TypeRef, or null if none found</returns>
        public ITypeDefOrRef ResolveTypeDefOrRef(TypeName typeName)
        {
            String fullName = typeName.Name;

            // Return TypeDef if found
            TypeDef typeDef = _module.Find(fullName, false);

            if (typeDef != null)
            {
                return(typeDef);
            }

            // Return existing TypeRef if found
            var typeRefs = _module.GetTypeRefs();

            foreach (var typeRef in typeRefs)
            {
                if (typeRef.FullName.Equals(fullName))
                {
                    return(typeRef);
                }
            }

            // Get the AssemblyRef from the type name and make our own TypeRef
            AssemblyRef asmRef = this.FindAssemblyRef(typeName);

            if (!typeName.IsNested)
            {
                return(new TypeRefUser(_module, typeName.Namespace, typeName.NameWithoutNamespace, asmRef));
            }
            else
            {
                // Lazy...
                var     parentName    = typeName.ParentName.Split('.').Last();
                TypeRef resolutionRef = new TypeRefUser(_module, typeName.Namespace, parentName, asmRef);
                return(new TypeRefUser(_module, "", typeName.NestedName, resolutionRef));
            }
        }
示例#21
0
        /// <summary>
        /// Creates a custom ObfuscationAttribute that can be added to a method.
        /// </summary>
        /// <param name="module">Module</param>
        /// <param name="feature">Obfuscation feature name</param>
        /// <param name="exclude">true if exclude, false if include</param>
        /// <returns>CustomAttribute</returns>
        CustomAttribute CreateAttribute(ModuleDef module, String feature, Boolean exclude)
        {
            TypeSig stringSig  = module.CorLibTypes.String;
            TypeSig booleanSig = module.CorLibTypes.Boolean;

            CANamedArgument[] args = new CANamedArgument[] {
                // Feature
                new CANamedArgument(
                    false,
                    stringSig,
                    "Feature",
                    new CAArgument(stringSig, feature)),

                // Exclude
                new CANamedArgument(
                    false,
                    booleanSig,
                    "Exclude",
                    new CAArgument(booleanSig, exclude))
            };

            TypeRef obfuscationRef = new TypeRefUser(
                module, "System.Reflection", "ObfuscationAttribute", module.CorLibTypes.AssemblyRef);

            MemberRef obfuscationCtor = new MemberRefUser(module, ".ctor",
                                                          MethodSig.CreateInstance(module.CorLibTypes.Void),
                                                          obfuscationRef);

            CustomAttribute attr = new CustomAttribute(
                obfuscationCtor,
                new CAArgument[0],
                args
                );

            return(attr);
        }
示例#22
0
        internal static async Task <int> Execute(ModuleDefMD targetModule)
        {
            // Fetch target type defs
            var controllerTypeDef = targetModule.Find("Controller", true);

            // Fetch target method defs
            var controllerJumpMethodDef = controllerTypeDef.FindMethod("Jump");

            // Fetch target field defs
            var controllerMovementStateFieldDef = controllerTypeDef.FindField("m_MovementState");

            /*
             *
             *  Remove redundant code that always sets 'movementState' to 'GroundJump' in the 'Controller.Jump' method.
             *
             *  Target instructions to patch:
             *
             *      62	00EE	ldarg.0
             *      63	00EF	ldloc.0
             *      64	00F0	brfalse	67 (00FB) ldc.i4.8
             *      65	00F5	ldc.i4.4
             *      66	00F6	br	68 (00FC) stfld valuetype Controller/MovementStateEnum Controller::m_MovementState
             *      67	00FB	ldc.i4.8
             *      68	00FC	stfld	valuetype Controller/MovementStateEnum Controller::m_MovementState
             *
             */

            var controllerJumpInstructionSignature = new List <Instruction> {
                new Instruction(OpCodes.Ldarg_0),
                new Instruction(OpCodes.Ldloc_0),
                new Instruction(OpCodes.Brfalse, new Instruction(OpCodes.Ldc_I4_8, null)),
                new Instruction(OpCodes.Ldc_I4_4),
                new Instruction(OpCodes.Br, new Instruction(OpCodes.Stfld, null)),
                new Instruction(OpCodes.Ldc_I4_8),
                new Instruction(OpCodes.Stfld, controllerMovementStateFieldDef)
            };

            var matchedControllerJumpMethodInstructions = InjectionHelpers.FetchInstructionsBySignature(controllerJumpMethodDef.Body.Instructions, controllerJumpInstructionSignature, false);

            if (matchedControllerJumpMethodInstructions != null)
            {
                // NOP the matched instructions
                matchedControllerJumpMethodInstructions.ForEach(matchedInstruction => matchedInstruction.OpCode = OpCodes.Nop);
            }
            else
            {
                return(await Task.FromResult(1));
            }

            /*
             *
             *  The 'Movement.Jump' method unsafely accesses the AudioClip array when selecting a random 'jump' sound to play.
             *  Add appropriate length check to fix the index out of bounds exception.
             *
             *  Target instructions to patch:
             *
             *      0	0000	ldarg.0
             *      1	0001	ldarg.1
             *      2	0002	ldarg.2
             *      3	0003	call	instance bool Movement::DoJump(bool, bool)
             *      4	0008	stloc.0
             *      5	0009	ldarg.0
             *      6	000A	ldfld	class [UnityEngine]UnityEngine.AudioSource Movement::au
             *      7	000F	ldarg.0
             *      8	0010	ldfld	class [UnityEngine]UnityEngine.AudioClip[] Movement::jumpClips
             *      9	0015	ldc.i4.0
             *      10	0016	ldarg.0
             *      11	0017	ldfld	class [UnityEngine]UnityEngine.AudioClip[] Movement::jumpClips
             *      12	001C	ldlen
             *      13	001D	conv.i4
             *      14	001E	call	int32 [UnityEngine]UnityEngine.Random::Range(int32, int32)
             *      15	0023	ldelem.ref
             *      16	0024	callvirt	instance void [UnityEngine]UnityEngine.AudioSource::PlayOneShot(class [UnityEngine]UnityEngine.AudioClip)
             *      17	0029	ldloc.0
             *      18	002A	ret
             *
             *
             *  Resulting instructions after patching:
             *
             *      0	0000	ldarg.0
             *      1	0001	ldarg.1
             *      2	0002	ldarg.2
             *      3	0003	call	instance bool Movement::DoJump(bool, bool)
             *      4	0008	ldarg.0
             *      5	0009	ldfld	class [UnityEngine]UnityEngine.AudioClip[] Movement::jumpClips
             *      6	000E	ldlen
             *      7	000F	brfalse.s	24 (0039) ret
             *      8	0011	ldarg.0
             *      9	0012	ldfld	class [UnityEngine]UnityEngine.AudioSource Movement::au
             *      10	0017	ldarg.0
             *      11	0018	ldfld	class [UnityEngine]UnityEngine.AudioClip[] Movement::jumpClips
             *      12	001D	ldc.i4.0
             *      13	001E	ldarg.0
             *      14	001F	ldfld	class [UnityEngine]UnityEngine.AudioClip[] Movement::jumpClips
             *      15	0024	ldlen
             *      16	0025	conv.i4
             *      17	0026	ldc.i4.1
             *      18	0027	sub
             *      19	0028	ldc.i4.0
             *      20	0029	call	int32 [mscorlib]System.Math::Max(int32, int32)
             *      21	002E	call	int32 [UnityEngine]UnityEngine.Random::Range(int32, int32)
             *      22	0033	ldelem.ref
             *      23	0034	callvirt	instance void [UnityEngine]UnityEngine.AudioSource::PlayOneShot(class [UnityEngine]UnityEngine.AudioClip)
             *      24	0039	ret
             *
             */

            // Fetch target type defs
            var movementTypeDef = targetModule.Find("Movement", true);

            // Fetch target method defs
            var movementJumpMethodDef   = movementTypeDef.FindMethod("Jump");
            var movementDoJumpMethodDef = movementTypeDef.FindMethod("DoJump");

            // Fetch target field defs
            var movementAuFieldDef        = movementTypeDef.FindField("au");
            var movementJumpClipsFieldDef = movementTypeDef.FindField("jumpClips");

            // Fetch reference assembly refs
            var mscorlibAssemblyRef    = targetModule.GetAssemblyRef(new UTF8String("mscorlib"));
            var unityEngineAssemblyRef = targetModule.GetAssemblyRef(new UTF8String("UnityEngine"));

            // Construct type ref users
            var systemMathTypeRefUser             = new TypeRefUser(targetModule, new UTF8String("System"), new UTF8String("Math"), mscorlibAssemblyRef);
            var unityEngineAudioClipTypeRefUser   = new TypeRefUser(targetModule, new UTF8String("UnityEngine"), new UTF8String("AudioClip"), unityEngineAssemblyRef);
            var unityEngineRandomTypeRefUser      = new TypeRefUser(targetModule, new UTF8String("UnityEngine"), new UTF8String("Random"), unityEngineAssemblyRef);
            var unityEngineAudioSourceTypeRefUser = new TypeRefUser(targetModule, new UTF8String("UnityEngine"), new UTF8String("AudioSource"), unityEngineAssemblyRef);

            // Construct member ref users
            var maxMethodRefUser         = new MemberRefUser(targetModule, new UTF8String("Max"), MethodSig.CreateStatic(targetModule.CorLibTypes.Int32, targetModule.CorLibTypes.Int32, targetModule.CorLibTypes.Int32), systemMathTypeRefUser);
            var randomRangeMethodRefUser = new MemberRefUser(targetModule, new UTF8String("Range"), MethodSig.CreateStatic(targetModule.CorLibTypes.Int32, targetModule.CorLibTypes.Int32, targetModule.CorLibTypes.Int32), unityEngineRandomTypeRefUser);
            var playOneShotMethodRefUser = new MemberRefUser(targetModule, new UTF8String("PlayOneShot"), MethodSig.CreateInstance(targetModule.CorLibTypes.Void, unityEngineAudioClipTypeRefUser.ToTypeSig()), unityEngineAudioSourceTypeRefUser);

            // Construct list of instructions to be injected
            var retInstruction = new Instruction(OpCodes.Ret);

            var movementJumpInstructions = new List <Instruction>()
            {
                new Instruction(OpCodes.Ldarg_0),
                new Instruction(OpCodes.Ldarg_1),
                new Instruction(OpCodes.Ldarg_2),
                new Instruction(OpCodes.Call, movementDoJumpMethodDef),
                new Instruction(OpCodes.Ldarg_0),
                new Instruction(OpCodes.Ldfld, movementJumpClipsFieldDef),
                new Instruction(OpCodes.Ldlen),
                new Instruction(OpCodes.Brfalse_S, retInstruction),
                new Instruction(OpCodes.Ldarg_0),
                new Instruction(OpCodes.Ldfld, movementAuFieldDef),
                new Instruction(OpCodes.Ldarg_0),
                new Instruction(OpCodes.Ldfld, movementJumpClipsFieldDef),
                new Instruction(OpCodes.Ldc_I4_0),
                new Instruction(OpCodes.Ldarg_0),
                new Instruction(OpCodes.Ldfld, movementJumpClipsFieldDef),
                new Instruction(OpCodes.Ldlen),
                new Instruction(OpCodes.Conv_I4),
                new Instruction(OpCodes.Ldc_I4_1),
                new Instruction(OpCodes.Sub),
                new Instruction(OpCodes.Ldc_I4_0),
                new Instruction(OpCodes.Call, maxMethodRefUser),
                new Instruction(OpCodes.Call, randomRangeMethodRefUser),
                new Instruction(OpCodes.Ldelem_Ref),
                new Instruction(OpCodes.Callvirt, playOneShotMethodRefUser),
                retInstruction
            };

            // Replace all instructions in the method with the new instructions
            movementJumpMethodDef.Body.Instructions.Clear();
            movementJumpInstructions.ForEach(movementJumpInstruction => movementJumpMethodDef.Body.Instructions.Add(movementJumpInstruction));
            movementJumpMethodDef.Body.UpdateInstructionOffsets();

            return(await Task.FromResult(0));
        }
示例#23
0
        private void btnOk_Click(object sender, EventArgs e)
        {
            try
            {
                if (cbOperandType.SelectedItem.ToString() == "[None]")
                {
                    #region None

                    MainForm.NewInstruction = ((OpCode)cbOpCode.SelectedItem).ToInstruction();

                    #endregion None
                }
                else if (cbOperandType.SelectedItem.ToString() == "Byte" ||
                         cbOperandType.SelectedItem.ToString() == "SByte" ||
                         cbOperandType.SelectedItem.ToString() == "Int32" ||
                         cbOperandType.SelectedItem.ToString() == "Int64" ||
                         cbOperandType.SelectedItem.ToString() == "Single" ||
                         cbOperandType.SelectedItem.ToString() == "Double" ||
                         cbOperandType.SelectedItem.ToString() == "String")
                {
                    #region Value

                    CreateValueInstruction();

                    #endregion Value
                }
                else if (cbOperandType.SelectedItem.ToString() == "-> Instruction reference")
                {
                    #region Instruction

                    MainForm.NewInstruction =
                        ((OpCode)cbOpCode.SelectedItem).ToInstruction(
                            MainForm.CurrentAssembly.Method.Body.Instructions[cbOperand.SelectedIndex]);

                    #endregion Instruction
                }
                else if (cbOperandType.SelectedItem.ToString() == "-> Multiple instructions reference")
                {
                    #region Multi instructions

                    MainForm.NewInstruction =
                        ((OpCode)cbOpCode.SelectedItem).ToInstruction(SelectedReference as Instruction[]);

                    #endregion Instruction
                }
                else if (cbOperandType.SelectedItem.ToString() == "-> Variable reference")
                {
                    #region Variable

                    MainForm.NewInstruction =
                        ((OpCode)cbOpCode.SelectedItem).ToInstruction(
                            MainForm.CurrentAssembly.Method.Body.Variables[cbOperand.SelectedIndex]);

                    #endregion Variable
                }
                else if (cbOperandType.SelectedItem.ToString() == "-> Parameter reference")
                {
                    #region Parameter

                    MainForm.NewInstruction =
                        ((OpCode)cbOpCode.SelectedItem).ToInstruction(
                            MainForm.CurrentAssembly.Method.Parameters[cbOperand.SelectedIndex]);

                    #endregion Parameter
                }
                else if (cbOperandType.SelectedItem.ToString() == "-> Field reference")
                {
                    #region Field

                    IField field = cbOperand.SelectedItem as IField;

                    if (field.DeclaringType.DefinitionAssembly != MainForm.CurrentAssembly.ManifestModule.Assembly ||
                        field.Module != MainForm.CurrentAssembly.ManifestModule)
                    {
                        MemberRefUser fieldRef = new MemberRefUser(field.Module, field.Name, field.FieldSig,
                                                                   field.DeclaringType);

                        MainForm.NewInstruction = ((OpCode)cbOpCode.SelectedItem).ToInstruction(
                            MainForm.CurrentAssembly.ManifestModule.Import(fieldRef));
                    }
                    else
                    {
                        MainForm.NewInstruction = ((OpCode)cbOpCode.SelectedItem).ToInstruction(
                            MainForm.CurrentAssembly.ManifestModule.ResolveField(field.Rid));
                    }

                    #endregion Field
                }
                else if (cbOperandType.SelectedItem.ToString() == "-> Method reference")
                {
                    #region Method

                    IMethod method = cbOperand.SelectedItem as IMethod;

                    if (method.DeclaringType.DefinitionAssembly != MainForm.CurrentAssembly.ManifestModule.Assembly ||
                        method.Module != MainForm.CurrentAssembly.ManifestModule)
                    {
                        MemberRefUser methodRef = new MemberRefUser(method.Module, method.Name, method.MethodSig,
                                                                    method.DeclaringType);

                        MainForm.NewInstruction = ((OpCode)cbOpCode.SelectedItem).ToInstruction(
                            MainForm.CurrentAssembly.ManifestModule.Import(methodRef));
                    }
                    else
                    {
                        MainForm.NewInstruction = ((OpCode)cbOpCode.SelectedItem).ToInstruction(
                            MainForm.CurrentAssembly.ManifestModule.ResolveMethod(method.Rid));
                    }

                    #endregion Method
                }

                else if (cbOperandType.SelectedItem.ToString() == "-> Type reference")
                {
                    #region Type

                    ITypeDefOrRef type = cbOperand.SelectedItem as ITypeDefOrRef;

                    if (type.DefinitionAssembly != MainForm.CurrentAssembly.ManifestModule.Assembly ||
                        type.Module != MainForm.CurrentAssembly.ManifestModule)
                    {
                        TypeRefUser typeRef = new TypeRefUser(type.Module, type.Namespace, type.Name,
                                                              MainForm.CurrentAssembly.ManifestModule.CorLibTypes.AssemblyRef);

                        MainForm.NewInstruction = ((OpCode)cbOpCode.SelectedItem).ToInstruction(
                            MainForm.CurrentAssembly.ManifestModule.Import(typeRef));
                    }
                    else
                    {
                        MainForm.NewInstruction = ((OpCode)cbOpCode.SelectedItem).ToInstruction(
                            MainForm.CurrentAssembly.ManifestModule.ResolveTypeDef(type.Rid));
                    }

                    #endregion Type
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show("Could not create instruction!" + Environment.NewLine +
                                Environment.NewLine + ex.Message, "Error");
                return;
            }
            Close();
        }
        /// <summary>
        /// Initializes a new instance of TranslationEmitter.
        /// </summary>
        /// <param name="module">The module of the target assembly.</param>
        /// <param name="gameCulture">The game culture selection.</param>
        /// <param name="modName">The mod name.</param>
        public TranslationEmitter(ModuleDef module, string gameCulture, string modName)
        {
            _modName = modName;
            if (gameCulture == null)
            {
                throw new ArgumentNullException(nameof(gameCulture));
            }

            Module = module ?? throw new ArgumentNullException(nameof(module));

            var importer = new Importer(Module);

            var terraria = module.GetAssemblyRef("Terraria") ?? new AssemblyRefUser("Terraria", DefaultConfigurations.TerrariaVersion);

            _modTranslationType = new TypeRefUser(Module, "Terraria.ModLoader", "ModTranslation", terraria);

            _modTranslationSetDefaultMethod = new MemberRefUser(Module, "SetDefault",
                                                                MethodSig.CreateInstance(Module.CorLibTypes.Void, Module.CorLibTypes.String),
                                                                _modTranslationType);

            var gameCultureType = new TypeRefUser(Module, "Terraria.Localization", "GameCulture", terraria);

            _modTranslationAddTranslationMethod = new MemberRefUser(Module, "AddTranslation",
                                                                    MethodSig.CreateInstance(Module.CorLibTypes.Void, new ClassSig(gameCultureType), Module.CorLibTypes.String),
                                                                    _modTranslationType);

            _gameCultureField = new MemberRefUser(Module, gameCulture,
                                                  new FieldSig(new ClassSig(gameCultureType)),
                                                  gameCultureType);

            var languageType = new TypeRefUser(Module, "Terraria.Localization", "Language", terraria);

            _getTextValueMethod = new MemberRefUser(Module, "GetTextValue", MethodSig.CreateStatic(Module.CorLibTypes.String, Module.CorLibTypes.String), languageType);

            var modType = new TypeRefUser(Module, "Terraria.ModLoader", "Mod", terraria);

            _modAddTranslationMethod    = new MemberRefUser(Module, "AddTranslation", MethodSig.CreateInstance(Module.CorLibTypes.Void, new ClassSig(_modTranslationType)), modType);
            _modCreateTranslationMethod = new MemberRefUser(Module, "CreateTranslation", MethodSig.CreateInstance(new ClassSig(_modTranslationType), Module.CorLibTypes.String), modType);

            var type = Module.Types.Single(x => string.Equals(x.BaseType?.FullName, "Terraria.ModLoader.Mod",
                                                              StringComparison.Ordinal));
            var ctor = importer.Import(typeof(CompilerGeneratedAttribute).GetConstructor(new Type[0])) as IMethodDefOrRef;

            _modSetTranslationMethod = new MethodDefUser(ModSetTranslationMethod, MethodSig.CreateInstance(Module.CorLibTypes.Void), MethodAttributes.Private);
            type.Methods.Add(_modSetTranslationMethod);

            _modSetTranslationMethod.CustomAttributes.Add(new CustomAttribute(ctor));
            _modSetTranslationMethod.Body = new CilBody
            {
                Instructions = { OpCodes.Ret.ToInstruction() },
                Variables    = { new Local(new ClassSig(_modTranslationType), "translation", 0) }
            };

            var loadMethod = type.FindMethod("Load", MethodSig.CreateInstance(Module.CorLibTypes.Void));

            if (loadMethod?.HasBody != true)
            {
                Console.WriteLine("Could not find Mod.Load() method; trying to add one.");

                loadMethod = new MethodDefUser("Load", MethodSig.CreateInstance(Module.CorLibTypes.Void), MethodAttributes.Public | MethodAttributes.HideBySig | MethodAttributes.Virtual)
                {
                    Body = new CilBody
                    {
                        Instructions = { OpCodes.Ret.ToInstruction() },
                    }
                };

                type.Methods.Add(loadMethod);
            }

            loadMethod.Body.Instructions.AppendLast(new[]
            {
                OpCodes.Ldarg_0.ToInstruction(),
                OpCodes.Call.ToInstruction(_modSetTranslationMethod),
                OpCodes.Ret.ToInstruction()
            });
        }
示例#25
0
        static void Main(string[] args)
        {
            // Create assembly and main module
            var assembly = new AssemblyDefUser("HelloWorld");
            var module   = new ModuleDefUser("HelloWorld.dll", null, new AssemblyRefUser("System.Runtime", new Version(4, 2, 2, 0)));

            module.RuntimeVersion = dnlib.DotNet.MD.MDHeaderRuntimeVersion.MS_CLR_40;

            // Create type Program
            var type = new TypeDefUser(
                @namespace: "HelloWorld",
                name: "Program",
                baseType: module.CorLibTypes.Object.TypeDefOrRef);

            // Set class attributes
            type.Attributes = TypeAttributes.Public | TypeAttributes.Class;

            // Create method Main
            var method = new MethodDefUser(
                name: "Main",
                methodSig: MethodSig.CreateStatic(
                    retType: module.CorLibTypes.Void,
                    argType1: new SZArraySig(module.CorLibTypes.String)));

            // Name parameter
            method.ParamDefs.Add(new ParamDefUser("args", 1));
            // Set method attributes
            method.Attributes = MethodAttributes.Public | MethodAttributes.Static;
            // Set attributes for method's implementation
            method.ImplAttributes = MethodImplAttributes.IL | MethodImplAttributes.Managed;



            #region IMPLEMENTATION
            // Create reference to System.Console
            var consoleRef = new TypeRefUser(module, "System", "Console", new AssemblyRefUser("System.Console"));
            // Create reference to System.Console::WriteLine(string)
            var writeLineRef = new MemberRefUser(module, "WriteLine",
                                                 MethodSig.CreateStatic(
                                                     retType: module.CorLibTypes.Void,
                                                     argType1: module.CorLibTypes.String),
                                                 consoleRef);

            // Implement body of the Program::Main(string[]) method
            var body = new CilBody();
            body.Instructions.Add(Instruction.Create(OpCodes.Ldstr, "Hello World!"));
            body.Instructions.Add(Instruction.Create(OpCodes.Call, writeLineRef));
            body.Instructions.Add(Instruction.Create(OpCodes.Br, body.Instructions.First()));
            body.Instructions.Add(Instruction.Create(OpCodes.Ret));

            method.Body = body;
            #endregion



            #region ASSEMBLE
            // Wire-it up!
            assembly.Modules.Add(module);
            module.Types.Add(type);
            type.Methods.Add(method);

            // Set entrypoint
            module.EntryPoint = method;

            // Store assembly
            module.Write(Path.Combine("Generated", "HelloWorld.dll"), new dnlib.DotNet.Writer.ModuleWriterOptions(module));
            #endregion
        }
示例#26
0
		ITypeDefOrRef CreateCorLibTypeRef(bool isCorLib, string name) {
			var tr = new TypeRefUser(module, "System", name, corLibAssemblyRef);
			if (isCorLib) {
				var td = module.Find(tr);
				if (td != null)
					return td;
			}
			return module.UpdateRowId(tr);
		}
示例#27
0
        internal static async Task <int> Execute(ModuleDefMD targetModule)
        {
            /*
             *  {IL_0046: ldarg.0}
             *  {IL_0047: ldarg.0}
             *  {IL_0048: call UnityEngine.GameObject UnityEngine.Component::get_gameObject()}
             *  {IL_004D: callvirt TrainerManager UnityEngine.GameObject::AddComponent<TrainerManager>()}
             *  {IL_0052: stfld TrainerManager GameManager::trainerManager}
             *  {IL_0057: ret}
             */

            var gameManagerTypeDef    = targetModule.Find("GameManager", true);
            var trainerManagerTypeDef = targetModule.Find("TrainerManager", true);

            var trainerManagerFieldDef = InjectionHelpers.AddField(targetModule, "GameManager", "trainerManager", trainerManagerTypeDef.ToTypeSig(), FieldAttributes.Private);

            if (trainerManagerFieldDef == null)
            {
                return(await Task.FromResult(1));
            }

            var gameManagerStartMethodDef = gameManagerTypeDef.FindMethod("Start");

            var unityEngine = targetModule.GetAssemblyRef(new UTF8String("UnityEngine"));
            var unityEngineComponentTypeRefUser  = new TypeRefUser(targetModule, new UTF8String("UnityEngine"), new UTF8String("Component"), unityEngine);
            var unityEngineGameObjectTypeRefUser = new TypeRefUser(targetModule, new UTF8String("UnityEngine"), new UTF8String("GameObject"), unityEngine);

            var gameObjectTypeSig = unityEngineGameObjectTypeRefUser.ToTypeSig();

            var getGameObjectMethodSig    = MethodSig.CreateInstance(gameObjectTypeSig);
            var gameManagerStartMethodSig = MethodSig.CreateInstanceGeneric(1, new GenericMVar(0, gameManagerStartMethodDef));

            // {UnityEngine.GameObject UnityEngine.Component::get_gameObject()}
            var getGameObjectMethodRefUser = new MemberRefUser(targetModule, new UTF8String("get_gameObject"), getGameObjectMethodSig, unityEngineComponentTypeRefUser);

            // {TrainerManager UnityEngine.GameObject::AddComponent<TrainerManager>()}
            var addComponentMethodRefUser = new MemberRefUser(targetModule, new UTF8String("AddComponent"), gameManagerStartMethodSig, unityEngineGameObjectTypeRefUser);

            var trainerManagerGenericInstMethodSig = new GenericInstMethodSig(trainerManagerTypeDef.ToTypeSig());
            var addComponentMethodSpecUser         = new MethodSpecUser(addComponentMethodRefUser, trainerManagerGenericInstMethodSig);

            var trainerManagerDefinitionMethodInstructions = new List <Instruction>
            {
                new Instruction(OpCodes.Ldarg_0),
                new Instruction(OpCodes.Ldarg_0),
                new Instruction(OpCodes.Call, getGameObjectMethodRefUser),
                new Instruction(OpCodes.Callvirt, addComponentMethodSpecUser),
                new Instruction(OpCodes.Stfld, trainerManagerFieldDef),
                new Instruction(OpCodes.Ret),
            };

            var retInstruction = gameManagerStartMethodDef.Body.Instructions.LastOrDefault();

            if (retInstruction != null && retInstruction.OpCode == OpCodes.Ret)
            {
                gameManagerStartMethodDef.Body.Instructions.Remove(retInstruction);
            }

            foreach (var instruction in trainerManagerDefinitionMethodInstructions)
            {
                gameManagerStartMethodDef.Body.Instructions.Add(instruction);
            }

            return(await Task.FromResult(0));
        }
示例#28
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);
        }
示例#29
0
        /*public static bool CompareSignatures(this TypeSignature signature, TypeSig reference) => signature.FullName == reference.FullName;
         * public static bool CompareSignatures(this FieldSignature signature, IField reference) => signature.Name == reference.Name.String;
         * public static bool CompareSignatures(this MethodSignature signature, MethodDef reference) => signature.Name == reference.Name && signature.Parameters.Zip(reference.Parameters, CompareSignatures).All(b => b);
         * public static bool CompareSignatures(this ParameterSignature signature, Parameter reference) => signature.Index == reference.Index && new SigComparer(ComparerOptions).Equals(signature.ParameterType, reference.Type);*/

        public static TypeSig ToSig(this ModuleDef module, TypeSignature signature)
        {
            if (signature == TypeSignature.Void)
            {
                return(module.CorLibTypes.Void);
            }
            if (signature == TypeSignature.Boolean)
            {
                return(module.CorLibTypes.Boolean);
            }
            if (signature == TypeSignature.Char)
            {
                return(module.CorLibTypes.Char);
            }
            if (signature == TypeSignature.SByte)
            {
                return(module.CorLibTypes.SByte);
            }
            if (signature == TypeSignature.Byte)
            {
                return(module.CorLibTypes.Byte);
            }
            if (signature == TypeSignature.Int16)
            {
                return(module.CorLibTypes.Int16);
            }
            if (signature == TypeSignature.UInt16)
            {
                return(module.CorLibTypes.UInt16);
            }
            if (signature == TypeSignature.Int32)
            {
                return(module.CorLibTypes.Int32);
            }
            if (signature == TypeSignature.UInt32)
            {
                return(module.CorLibTypes.UInt32);
            }
            if (signature == TypeSignature.Int64)
            {
                return(module.CorLibTypes.Int64);
            }
            if (signature == TypeSignature.UInt64)
            {
                return(module.CorLibTypes.UInt64);
            }
            if (signature == TypeSignature.Single)
            {
                return(module.CorLibTypes.Single);
            }
            if (signature == TypeSignature.Double)
            {
                return(module.CorLibTypes.Double);
            }
            if (signature == TypeSignature.String)
            {
                return(module.CorLibTypes.String);
            }
            if (signature == TypeSignature.TypedReference)
            {
                return(module.CorLibTypes.TypedReference);
            }
            if (signature == TypeSignature.IntPtr)
            {
                return(module.CorLibTypes.IntPtr);
            }
            if (signature == TypeSignature.UIntPtr)
            {
                return(module.CorLibTypes.UIntPtr);
            }
            if (signature == TypeSignature.Object)
            {
                return(module.CorLibTypes.Object);
            }
            string      fullName = signature.FullName;
            int         index    = fullName.LastIndexOf('.');
            string      ns       = fullName.Substring(0, index < 0 ? index = 0 : index++);
            TypeRefUser typeRef  = Get(fullName.Substring(index));

            switch (signature.Kind)
            {
            case TypeKind.Class:
                return(new ClassSig(typeRef));

            case TypeKind.Value:
                return(new ValueTypeSig(typeRef));
            }
            throw new NotImplementedException("cannot create TypeSig of kind " + signature.Kind);

            TypeRefUser Get(string name)
            {
                int newIndex = name.LastIndexOf('/');

                return(newIndex < 0 ? new TypeRefUser(module, ns, name) : new TypeRefUser(module, ns, name.Substring(newIndex + 1), Get(name.Substring(0, newIndex))));
            }
        }
示例#30
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");
        }
示例#31
0
        public static void Run()
        {
            // This is the file that will be created
            string newFileName = @"GenericExample1.exe";

            // Create the module
            var mod = new ModuleDefUser("GenericExample1", Guid.NewGuid(),
                                        new AssemblyRefUser(new AssemblyNameInfo(typeof(int).Assembly.GetName().FullName)));

            // It's a console app
            mod.Kind = ModuleKind.Console;
            // Create the assembly and add the created module to it
            new AssemblyDefUser("GenericExample1", new Version(1, 2, 3, 4)).Modules.Add(mod);

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

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

            // Create the entry point method
            MethodDef entryPoint = new MethodDefUser("Main",
                                                     MethodSig.CreateStatic(mod.CorLibTypes.Int32, new SZArraySig(mod.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
            mod.EntryPoint = entryPoint;

            // Create System.Console type reference
            var systemConsole = mod.CorLibTypes.GetTypeRef("System", "Console");
            // Create 'void System.Console.WriteLine(string,object)' method reference
            var writeLine2 = new MemberRefUser(mod, "WriteLine",
                                               MethodSig.CreateStatic(mod.CorLibTypes.Void, mod.CorLibTypes.String,
                                                                      mod.CorLibTypes.Object),
                                               systemConsole);

            //
            // Method 1: Create List<String> inst signature by importing (easy way)
            // --------------------------------------------------------------------
            //Importer importer = new Importer(mod);
            //var listGenericInstSig = importer.ImportAsTypeSig(typeof(System.Collections.Generic.List<String>));

            //
            // Method 2: Create List<String> inst signature manually (harder way)
            // ------------------------------------------------------------------
            var assemblyRef = mod.CorLibTypes.AssemblyRef;
            var listRef     = new TypeRefUser(mod, @"System.Collections.Generic", "List`1", assemblyRef);
            // Create the GenericInstSig from a ClassSig with <String> generic arg
            var listGenericInstSig = new GenericInstSig(new ClassSig(listRef), mod.CorLibTypes.String);

            // Create TypeSpec from GenericInstSig
            var listTypeSpec = new TypeSpecUser(listGenericInstSig);
            // Create System.Collections.Generic.List<String>::.ctor method reference
            var listCtor = new MemberRefUser(mod, ".ctor", MethodSig.CreateInstance(mod.CorLibTypes.Void),
                                             listTypeSpec);

            // Create Add(!0) method reference, !0 signifying first generic argument of declaring type
            // In this case, would be Add(String item)
            // (GenericMVar would be used for method generic argument, such as Add<!!0>(!!0))
            var listAdd = new MemberRefUser(mod, "Add",
                                            MethodSig.CreateInstance(mod.CorLibTypes.Void, new GenericVar(0)),
                                            listTypeSpec);

            var listGetCount = new MemberRefUser(mod, "get_Count",
                                                 MethodSig.CreateInstance(mod.CorLibTypes.Int32),
                                                 listTypeSpec);

            IList <Local> locals = new List <Local>();

            locals.Add(new Local(listGenericInstSig));             // local[0]: class [mscorlib]System.Collections.Generic.List`1<string>

            var body = new CilBody(true, new List <Instruction>(), new List <ExceptionHandler>(), locals);

            // Call the list .ctor
            body.Instructions.Add(OpCodes.Newobj.ToInstruction(listCtor));
            body.Instructions.Add(OpCodes.Stloc_0.ToInstruction());             // Store list to local[0]

            // list.Add("Item 1")
            body.Instructions.Add(OpCodes.Ldloc_0.ToInstruction());
            body.Instructions.Add(OpCodes.Ldstr.ToInstruction("Item 1"));
            body.Instructions.Add(OpCodes.Callvirt.ToInstruction(listAdd));

            // WriteLine("Array: {0}", list.ToArray());
            //body.Instructions.Add(OpCodes.Ldstr.ToInstruction("Array: {0}"));
            //body.Instructions.Add(OpCodes.Ldloc_0.ToInstruction()); // Load list from local[0]
            //body.Instructions.Add(OpCodes.Callvirt.ToInstruction(listToArray));
            //body.Instructions.Add(OpCodes.Call.ToInstruction(writeLine2));

            // WriteLine("Count: {0}", list.Count)
            body.Instructions.Add(OpCodes.Ldstr.ToInstruction("Count: {0}"));
            body.Instructions.Add(OpCodes.Ldloc_0.ToInstruction());             // Load list from local[0]
            body.Instructions.Add(OpCodes.Callvirt.ToInstruction(listGetCount));
            body.Instructions.Add(OpCodes.Box.ToInstruction(mod.CorLibTypes.Int32));
            body.Instructions.Add(OpCodes.Call.ToInstruction(writeLine2));

            // return 0;
            body.Instructions.Add(OpCodes.Ldc_I4_0.ToInstruction());
            body.Instructions.Add(OpCodes.Ret.ToInstruction());

            entryPoint.Body = body;

            // Save the assembly
            mod.Write(newFileName);
        }