コード例 #1
0
            private static void CallLoadIntegersMethod(ModuleDef targetModule, bool isOffline)
            {
                // Finds the injected 'ByteGuardStringProtections' class that contains all the decryption methods.
                TypeDef stringProtections =
                    targetModule.Find("ByteGuard.Protections.Online.Runtime.ByteGuardConstantProtections", true);

                TypeDef byteguardCore =
                    targetModule.Find("ByteGuard.Protections.Online.Runtime.ByteGuardCore", true);

                MethodDef loadStringsMethod =
                    (isOffline
                    ? stringProtections.FindMethod("LoadIntegersOffline")
                    : stringProtections.FindMethod("LoadIntegers"));

                MethodDef authenticatedMethod =
                    (isOffline
                        ? byteguardCore.FindOrCreateStaticConstructor()
                        : byteguardCore.FindMethod("Authenticated"));

                foreach (Instruction i in loadStringsMethod.Body.Instructions.Where(i => i.OpCode == OpCodes.Ldstr))
                {
                    i.Operand =
                        (isOffline
                            ? StringProtections.EmbeddedResourceNameOffline
                            : EmbeddedResourceName);
                }

                authenticatedMethod.Body.Instructions.Insert(0, Instruction.Create(OpCodes.Call, loadStringsMethod));
            }
コード例 #2
0
 static TypeSig GetCommonBaseClass(ModuleDef module, TypeSig a, TypeSig b)
 {
     if (DotNetUtils.IsDelegate(a) && DotNetUtils.DerivesFromDelegate(module.Find(b.ToTypeDefOrRef())))
     {
         return(b);
     }
     if (DotNetUtils.IsDelegate(b) && DotNetUtils.DerivesFromDelegate(module.Find(a.ToTypeDefOrRef())))
     {
         return(a);
     }
     return(null);               //TODO:
 }
コード例 #3
0
        public virtual void PatchContents(IReadOnlyList <T> contents)
        {
            foreach (var content in contents)
            {
                // convert to full name for historical reasons :(
                var fullName = $"{content.Namespace}.{content.TypeName}";

                var type = ModModule.Find(fullName, true);
                if (type != null)
                {
                    try
                    {
                        PatchContent(type, content);
                    }
                    catch (Exception ex)
                    {
                        Logger.Error(Strings.PatchExceptionOccur, type.FullName);
                        Logger.Error(ex);
                    }
                }
                else
                {
                    Logger.Warn(Strings.InvalidContent, fullName);
                }
            }
        }
コード例 #4
0
        /// <summary>
        /// Embeds the loader.
        /// </summary>
        /// <param name="moduleDef">The module definition.</param>
        /// <param name="taskAssemblyPath">The task assembly path.</param>
        private void EmbedLoader(ModuleDef moduleDef, string taskAssemblyPath)
        {
            const string loaderTypeName = "\u2302";

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

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

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

            cctor.Body.Instructions.Insert(0, Instruction.Create(OpCodes.Call, moduleDef.Import(loaderInitializeMethod)));
        }
コード例 #5
0
ファイル: XmlDocKeyProvider.cs プロジェクト: haise0/dnSurgeon
        static TypeDef?FindType(ModuleDef module, string name)
        {
            int pos = name.LastIndexOf('.');

            if (string.IsNullOrEmpty(name))
            {
                return(null);
            }
            TypeDef?type = module.Find(name, true);

            if (type is null && pos > 0)               // Original code only entered if ns.Length > 0
            // try if this is a nested type
            {
                type = FindType(module, name.Substring(0, pos));
                if (type is not null)
                {
                    foreach (var nt in type.NestedTypes)
                    {
                        if (nt.Name == name)
                        {
                            return(nt);
                        }
                    }
                    return(null);
                }
            }
            return(type);
        }
コード例 #6
0
        /// <inheritdoc/>
        public AssemblyRef FindAssemblyRef(TypeRef nonNestedTypeRef)
        {
            var modAsm = module.Assembly;

            if (modAsm != null)
            {
                var type = modAsm.Find(nonNestedTypeRef);
                if (type != null)
                {
                    return(module.UpdateRowId(new AssemblyRefUser(modAsm)));
                }
            }
            else if (module.Find(nonNestedTypeRef) != null)
            {
                return(AssemblyRef.CurrentAssembly);
            }

            var corLibAsm = module.Context.AssemblyResolver.Resolve(module.CorLibTypes.AssemblyRef, module);

            if (corLibAsm != null)
            {
                var type = corLibAsm.Find(nonNestedTypeRef);
                if (type != null)
                {
                    return(module.CorLibTypes.AssemblyRef);
                }
            }

            if (modAsm != null)
            {
                return(module.UpdateRowId(new AssemblyRefUser(modAsm)));
            }
            return(AssemblyRef.CurrentAssembly);
        }
コード例 #7
0
        public string GetResxFilename(string resourceName, out string typeFullName)
        {
            const string RESOURCES_EXT = ".resources";
            const string RESX_EXT      = ".resx";
            var          n             = resourceName;

            if (n.EndsWith(RESOURCES_EXT, StringComparison.OrdinalIgnoreCase))
            {
                n = n.Substring(0, n.Length - RESOURCES_EXT.Length);
            }

            var type = module.Find(n, true);

            if (!(type is null) && DotNetUtils.IsWinForm(type))
            {
                typeFullName = type.ReflectionFullName;
                return(filenameCreator.CreateFromNamespaceName(RESX_EXT, type.Namespace, type.Name));
            }

            var resXType = GetResXType(type, n);

            if (!(resXType is null))
            {
                typeFullName = resXType.ReflectionFullName;
                return(filenameCreator.CreateFromNamespaceName(RESX_EXT, resXType.ReflectionNamespace, GetResxDesignerFilename(resXType.ReflectionNamespace, n)));
            }

            typeFullName = n;
            return(filenameCreator.Create(RESX_EXT, n));
        }
コード例 #8
0
        /// <summary>
        /// This load the types from the source assembly.
        /// </summary>
        /// <param name="ctx"></param>
        /// <returns>true if it manage to load all the types correctly; false otherwise</returns>
        public bool LoadTypes()
        {
            try
            {
                ModuleDef module = null;

                for (var i = 0; i < sourceMap.Count; ++i)
                {
                    if (module == null || (module != null && module.Name != sourceMap[i].module))
                    {
                        if (!File.Exists(sourceMap[i].module))
                        {
                            return(typesLoadedCorrectly = false);
                        }
                        module = AssemblyDef.Load(sourceMap[i].module).ManifestModule;
                    }

                    MethodDef foundMethod = module.Find(sourceMap[i].@namespace, true).FindMethod(sourceMap[i].name);

                    sourceMap[i].matchingMethods = new List <MethodDef>()
                    {
                        foundMethod
                    };
                }
            }
            catch (Exception ex)
            {
                GC.KeepAlive(ex);
                return(typesLoadedCorrectly = false);
            }
            return(typesLoadedCorrectly = true);
        }
コード例 #9
0
 /// <inheritdoc />
 public TypeDef GetRuntimeType(string fullName)
 {
     if (rtModule == null)
     {
         LoadConfuserRuntimeModule();
     }
     return(rtModule.Find(fullName, true));
 }
コード例 #10
0
ファイル: RTConstants.cs プロジェクト: hmyit/KoiVM
        public void InjectConstants(ModuleDef rtModule, VMDescriptor desc, RuntimeHelpers helpers)
        {
            var constants = rtModule.Find(RTMap.VMConstants, true);
            var cctor     = constants.FindOrCreateStaticConstructor();
            var instrs    = cctor.Body.Instructions;

            instrs.Clear();

            for (var i = 0; i < (int)VMRegisters.Max; i++)
            {
                var reg      = (VMRegisters)i;
                var regId    = desc.Architecture.Registers[reg];
                var regField = reg.ToString();
                AddField(regField, regId);
            }

            for (var i = 0; i < (int)VMFlags.Max; i++)
            {
                var fl      = (VMFlags)i;
                var flId    = desc.Architecture.Flags[fl];
                var flField = fl.ToString();
                AddField(flField, 1 << flId);
            }

            for (var i = 0; i < (int)ILOpCode.Max; i++)
            {
                var op      = (ILOpCode)i;
                var opId    = desc.Architecture.OpCodes[op];
                var opField = op.ToString();
                AddField(opField, opId);
            }

            for (var i = 0; i < (int)VMCalls.Max; i++)
            {
                var vc      = (VMCalls)i;
                var vcId    = desc.Runtime.VMCall[vc];
                var vcField = vc.ToString();
                AddField(vcField, vcId);
            }

            AddField(ConstantFields.E_CALL.ToString(), (int)desc.Runtime.VCallOps.ECALL_CALL);
            AddField(ConstantFields.E_CALLVIRT.ToString(), (int)desc.Runtime.VCallOps.ECALL_CALLVIRT);
            AddField(ConstantFields.E_NEWOBJ.ToString(), (int)desc.Runtime.VCallOps.ECALL_NEWOBJ);
            AddField(ConstantFields.E_CALLVIRT_CONSTRAINED.ToString(), (int)desc.Runtime.VCallOps.ECALL_CALLVIRT_CONSTRAINED);

            AddField(ConstantFields.INIT.ToString(), (int)helpers.INIT);

            AddField(ConstantFields.INSTANCE.ToString(), desc.Runtime.RTFlags.INSTANCE);

            AddField(ConstantFields.CATCH.ToString(), desc.Runtime.RTFlags.EH_CATCH);
            AddField(ConstantFields.FILTER.ToString(), desc.Runtime.RTFlags.EH_FILTER);
            AddField(ConstantFields.FAULT.ToString(), desc.Runtime.RTFlags.EH_FAULT);
            AddField(ConstantFields.FINALLY.ToString(), desc.Runtime.RTFlags.EH_FINALLY);

            Conclude(desc.Random, instrs, constants);
            instrs.Add(Instruction.Create(OpCodes.Ret));
            cctor.Body.OptimizeMacros();
        }
コード例 #11
0
 /// <inheritdoc />
 public TypeDef GetRuntimeType(string fullName)
 {
     if (rtModule == null)
     {
         rtModule = ModuleDefMD.Load(typeof(RuntimeService).Assembly.ManifestModule);
         rtModule.EnableTypeDefFindCache = true;
     }
     return(rtModule.Find(fullName, true));
 }
コード例 #12
0
        private static void InjectCall(ModuleDef targetModule)
        {
            MethodDef cctor = targetModule.GlobalType.FindOrCreateStaticConstructor();

            TypeDef antiTamperType = targetModule.Find(
                "ByteGuard.Protections.Online.Runtime.ByteGuardAntiTamper", true);

            MethodDef hookMethod = antiTamperType.FindMethod("DecryptMethods");

            cctor.Body.Instructions.Insert(0, Instruction.Create(OpCodes.Call, hookMethod));
        }
コード例 #13
0
ファイル: AntiTamperJIT.cs プロジェクト: mt-code/ByteGuard
        private static void InjectCall(ModuleDef targetModule)
        {
            MethodDef cctor          = targetModule.GlobalType.FindOrCreateStaticConstructor();
            TypeDef   antiTamperType = targetModule.Find(
                "ByteGuard.Protections.Online.Runtime.JIT.ByteGuardAntiTamperJIT", true);

            MethodDef hookMethod = antiTamperType.FindMethod("Hook");

            // TODO: Insert before InitializeByteGuard.
            cctor.Body.Instructions.Insert(0, Instruction.Create(OpCodes.Call, hookMethod));
        }
コード例 #14
0
        private void Patch_CrafterLogic_IsCraftRecipeFulfilled(ModuleDef module)
        {
            var parentMethod = module.Find("uGUI_CraftingMenu", false).FindMethod("ActionAvailable");

            PatchHelper.ReplaceCall(parentMethod, _crafterLogicIsCraftRecipeFulfilledOriginal,
                                    _crafterLogicIsCraftRecipeFulfilledPatch);

            // Continue the patch chain
            var parentMethods = new[]
            {
                module.Find("ConstructorInput", false).FindMethod("Craft"),
                module.Find("GhostCrafter", false).FindMethod("Craft"),
                module.Find("RocketConstructor", false).FindMethod("StartRocketConstruction")
            };

            foreach (var method in parentMethods)
            {
                PatchHelper.ReplaceCall(method, _crafterLogicConsumeResourcesOriginal,
                                        _crafterLogicConsumeResourcesPatch);
            }
        }
コード例 #15
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));
        }
コード例 #16
0
        public void AdjustInventorySlotsCount(ModuleDef module, int totalQuickSlots)
        {
            var inventoryAwake        = module.Find("Inventory", false).FindMethod("Awake");
            var inventoryInstructions = inventoryAwake.Body.Instructions;

            // TODO: Refactor this with something in PatchHelper
            var instructionIndex = inventoryInstructions
                                   .Select((instruction, index) => new { instruction, index })
                                   .First(x => x.instruction.OpCode == OpCodes.Ldfld &&
                                          (x.instruction.Operand as IMemberRef).Name == "rightHandSlot")
                                   .index + 1;     // We want the value after this one

            inventoryInstructions[instructionIndex] = OpCodes.Ldc_I4.ToInstruction(totalQuickSlots);
        }
コード例 #17
0
        private void Patch_Constructable_Construct(ModuleDef module)
        {
            var parentMethod = module.Find("Constructable", false).FindMethod("Construct");

            // Just replace the call with the new static version

            parentMethod.Body = new CilBody();

            var instructions = parentMethod.Body.Instructions;

            instructions.Add(OpCodes.Ldarg_0.ToInstruction());
            instructions.Add(OpCodes.Call.ToInstruction(_constructableConstructPatch));
            instructions.Add(OpCodes.Ret.ToInstruction());
        }
コード例 #18
0
 public MethodPatcher(ModuleDef rtModule)
 {
     foreach (var entry in rtModule.Find(RTMap.DarksVMEntry, true).FindMethods(RTMap.DarksVMRun))
     {
         if (entry.Parameters.Count == 6)
         {
             vmEntryNormal = entry;
         }
         else
         {
             vmEntryTyped = entry;
         }
     }
 }
コード例 #19
0
ファイル: RuntimeService.cs プロジェクト: yuske/ConfuserEx
 /// <inheritdoc />
 public TypeDef GetRuntimeType(string fullName)
 {
     if (rtModule == null)
     {
         Module module = typeof(RuntimeService).Assembly.ManifestModule;
         string rtPath = "Confuser.Runtime.dll";
         if (module.FullyQualifiedName[0] != '<')
         {
             rtPath = Path.Combine(Path.GetDirectoryName(module.FullyQualifiedName), rtPath);
         }
         rtModule = ModuleDefMD.Load(rtPath);
         rtModule.EnableTypeDefFindCache = true;
     }
     return(rtModule.Find(fullName, true));
 }
コード例 #20
0
        private static void PatchDispatcher(ModuleDef runtime, bool debug, bool stackwalk)
        {
            var dispatcher    = runtime.Find(RTMap.DarksVMDispatcher, true);
            var dispatcherRun = dispatcher.FindMethod(RTMap.DarksVMRun);

            foreach (var eh in dispatcherRun.Body.ExceptionHandlers)
            {
                if (eh.HandlerType == ExceptionHandlerType.Catch)
                {
                    eh.CatchType = runtime.CorLibTypes.Object.ToTypeDefOrRef();
                }
            }
            PatchDoThrow(dispatcher.FindMethod(RTMap.DarksVMDispatcherDothrow).Body, debug, stackwalk);
            dispatcher.Methods.Remove(dispatcher.FindMethod(RTMap.DarksVMDispatcherThrow));
        }
コード例 #21
0
ファイル: FullNameCreator.cs プロジェクト: KitoHo/Reflexil
		/// <summary>
		/// Checks whether the assembly name should be included when printing the full name.
		/// See <see cref="IFullNameCreatorHelper.MustUseAssemblyName"/> for more info.
		/// </summary>
		/// <param name="module">Owner module</param>
		/// <param name="type">The type (<c>TypeDef</c>, <c>TypeRef</c> or <c>ExportedType</c>)
		/// or <c>null</c></param>
		/// <returns><c>true</c> if the assembly name must be included, <c>false</c> otherwise</returns>
		public static bool MustUseAssemblyName(ModuleDef module, IType type) {
			var td = type as TypeDef;
			if (td != null)
				return td.Module != module;

			var tr = type as TypeRef;
			if (tr == null)
				return true;
			if (tr.ResolutionScope == AssemblyRef.CurrentAssembly)
				return false;
			if (!tr.DefinitionAssembly.IsCorLib())
				return true;
			// If it's present in this module, but it's a corlib type, then we will need the
			// assembly name.
			return module.Find(tr) != null;
		}
コード例 #22
0
        public MethodPatcher(ModuleDef rtModule)
        {
            foreach (MethodDef entry in rtModule.Find(RTMap.DarksVMEntry, true).FindMethods(RTMap.DarksVMRun))
            {
                switch (entry.Parameters.Count)
                {
                case 6:
                    this.vmEntryNormal = entry;
                    break;

                default:
                    this.vmEntryTyped = entry;
                    break;
                }
            }
        }
コード例 #23
0
 /// <inheritdoc />
 public TypeDef GetRuntimeType(string fullName)
 {
     if (rtModule == null)
     {
         var module = typeof(RuntimeService).Assembly.ManifestModule;
         var rtPath = "Confuser.Runtime.dll";
         if (module.FullyQualifiedName[0] != '<')
         {
             rtPath = Path.Combine(Path.GetDirectoryName(module.FullyQualifiedName), rtPath);
         }
         rtModule = ModuleDefMD.Load(rtPath, new ModuleCreationOptions {
             TryToLoadPdbFromDisk = true
         });
         rtModule.EnableTypeDefFindCache = true;
     }
     return(rtModule.Find(fullName, true));
 }
コード例 #24
0
 /// <inheritdoc />
 public TypeDef GetRuntimeType(string fullName)
 {
     if (rtModule == null)
     {
         Module module = typeof(RuntimeService).Assembly.ManifestModule;
         string rtPath = $@"..\..\..\..\confuser.runtime\{ConfuserEngine.VersionNumber}\lib\netcoreapp2.0\Confuser.Runtime.dll";
         if (module.FullyQualifiedName[0] != '<')
         {
             rtPath = Path.Combine(Path.GetDirectoryName(module.FullyQualifiedName), rtPath);
         }
         rtModule = ModuleDefMD.Load(rtPath, new ModuleCreationOptions()
         {
             TryToLoadPdbFromDisk = true
         });
         rtModule.EnableTypeDefFindCache = true;
     }
     return(rtModule.Find(fullName, true));
 }
コード例 #25
0
        static TypeDef FindType(ModuleDef module, string name)
        {
            int pos = name.LastIndexOf('.');

            if (string.IsNullOrEmpty(name))
            {
                return(null);
            }
            TypeDef type = module.Find(name, true);

            if (type == null && pos != -1)
            {
                // try if this is a nested type
                type = FindType(module, name.Substring(0, pos));
                if (type != null)
                {
                    type = type.NestedTypes.FirstOrDefault(t => t.Name == name);
                }
            }
            return(type);
        }
コード例 #26
0
ファイル: XmlDocKeyProvider.cs プロジェクト: danysu/dnSpy
        static TypeDef FindType(ModuleDef module, string name)
        {
            int pos = name.LastIndexOf('.');

            if (string.IsNullOrEmpty(name))
            {
                return(null);
            }
            TypeDef type = module.Find(name, true);

            if (type == null && pos > 0)               // Original code only entered if ns.Length > 0
            // try if this is a nested type
            {
                type = FindType(module, name.Substring(0, pos));
                if (type != null)
                {
                    type = type.NestedTypes.FirstOrDefault(t => t.Name == name);
                }
            }
            return(type);
        }
コード例 #27
0
        private static void PatchReferences(ModuleDef src, ModuleDef dst)
        {
            foreach (var type in src.Types)
            {
                foreach (var method in type.Methods)
                {
                    if (!method.HasBody)
                    {
                        continue;
                    }

                    foreach (var instr in method.Body.Instructions)
                    {
                        if (instr.Operand is IMemberRef && ((IMemberRef)instr.Operand).DeclaringType != null &&
                            ((IMemberRef)instr.Operand).DeclaringType.Module == null)
                        {
                            var memberRef = (IMemberRef)instr.Operand;
                            var declType  = src.Import(dst.Find(memberRef.DeclaringType.FullName, false));
                            if (memberRef.IsField)
                            {
                                memberRef = new MemberRefUser(src, memberRef.Name, ((IField)memberRef).FieldSig, declType);
                            }
                            else if (memberRef.IsMethod)
                            {
                                memberRef = new MemberRefUser(src, memberRef.Name, ((IMethod)memberRef).MethodSig, declType);
                            }
                            else
                            {
                                throw new NotSupportedException();
                            }
                            instr.Operand = memberRef;
                        }
                    }
                }
            }
        }
コード例 #28
0
ファイル: XmlDocKeyProvider.cs プロジェクト: lovebanyi/dnSpy
 static TypeDef FindType(ModuleDef module, string name)
 {
     int pos = name.LastIndexOf('.');
     if (string.IsNullOrEmpty(name))
         return null;
     TypeDef type = module.Find(name, true);
     if (type == null && pos > 0) { // Original code only entered if ns.Length > 0
                                    // try if this is a nested type
         type = FindType(module, name.Substring(0, pos));
         if (type != null) {
             type = type.NestedTypes.FirstOrDefault(t => t.Name == name);
         }
     }
     return type;
 }
コード例 #29
0
        public void CreateButtonSlotEnums(ModuleDef module)
        {
            // GameInput -> Button
            var gameInputType       = module.Find("GameInput", false);
            var gameInputButtonType = module.Find("GameInput/Button", false);
            var maxButtonValue      = gameInputButtonType.Fields.Where(f => f.Constant != null)
                                      .Max(f => (int)f.Constant.Value);
            var buttonTypeSig = gameInputButtonType.GetEnumUnderlyingType();

            // QuickSlots
            var quickSlotStaticConstructor = module.Find("QuickSlots", false).FindStaticConstructor();

            const int totalQuickSlots       = TopExistingSlot + QuickSlotsToAdd;
            var       quickSlotInstructions = quickSlotStaticConstructor.Body.Instructions;

            // Update the array size instruction
            quickSlotInstructions[0] =
                OpCodes.Ldc_I4.ToInstruction(totalQuickSlots + 1); // Add one due to a hitch in Subnautica's code

            // Finally, set up the default keyboard shortcuts
            var defaultKeyboardBindingsMethod = gameInputType.FindMethod("SetupDefaultKeyboardBindings");

            var bindingsInstructions = defaultKeyboardBindingsMethod.Body.Instructions;
            var callInstruction      = bindingsInstructions[bindingsInstructions.Count - 2]; // Second to last instruction

            for (var i = 0; i < QuickSlotsToAdd; i++)
            {
                var nextSlotIndex = TopExistingSlot + i + 1;
                var slotName      = $"Slot{nextSlotIndex}";
                var quickSlotName = $"QuickSlot{nextSlotIndex}";
                var nextSlotValue = maxButtonValue + i + 1;

                // Add the Button enum value
                FieldDef fieldToAdd = new FieldDefUser(slotName, new FieldSig(new ValueTypeSig(gameInputButtonType)))
                {
                    Constant   = module.UpdateRowId(new ConstantUser(nextSlotValue, buttonTypeSig.ElementType)),
                    Attributes = FieldAttributes.Literal | FieldAttributes.Static | FieldAttributes.HasDefault |
                                 FieldAttributes.Public
                };

                gameInputButtonType.Fields.Add(fieldToAdd);

                // Add the QuickSlot name
                var insertPoint = quickSlotInstructions.Count - 2; // Ignore Stsfld and ret

                // dup
                // ldc.i4.s <nextSlotIndex>
                // ldstr <quickSlotName>
                // stelem.ref

                quickSlotInstructions.Insert(insertPoint++, OpCodes.Dup.ToInstruction());
                quickSlotInstructions.Insert(insertPoint++, OpCodes.Ldc_I4.ToInstruction(nextSlotIndex));
                quickSlotInstructions.Insert(insertPoint++, OpCodes.Ldstr.ToInstruction(quickSlotName));
                quickSlotInstructions.Insert(insertPoint++, OpCodes.Stelem_Ref.ToInstruction());

                // Insert the keyboard default
                if (i < DefaultKeysForSlots.Length)
                {
                    insertPoint = bindingsInstructions.Count - 1;

                    bindingsInstructions.Insert(insertPoint++, OpCodes.Ldc_I4_0.ToInstruction());
                    bindingsInstructions.Insert(insertPoint++, OpCodes.Ldc_I4.ToInstruction(nextSlotValue));
                    bindingsInstructions.Insert(insertPoint++, OpCodes.Ldc_I4_0.ToInstruction());
                    bindingsInstructions.Insert(insertPoint++, OpCodes.Ldstr.ToInstruction(DefaultKeysForSlots[i]));
                    bindingsInstructions.Insert(insertPoint++, callInstruction);
                }
            }

            // Rebuild the list of quick slot buttons in the Player
            RebuildPlayerQuickSlotList(module, totalQuickSlots, gameInputButtonType.Fields);

            // Update the quickslot count during inventory creation
            AdjustInventorySlotsCount(module, totalQuickSlots);
        }
コード例 #30
0
 /// <summary>
 /// Finds the type of the shortcut.
 /// </summary>
 /// <param name="module">The module.</param>
 /// <returns></returns>
 public TypeDef FindShortcutType(ModuleDef module)
 {
     return(module.Find($"{ShortcutTypeNamespace}.{ShortcutTypeName}", true));
 }
コード例 #31
0
 public static TypeDef GetDefinition(this ModuleDef module, TypeSignature type) => module.Find(type.FullName, false);
コード例 #32
0
ファイル: Program.cs プロジェクト: john-guo/hodgepodge
        private static TypeDef FindType(string fullName, ModuleDef module)
        {
            var newT = module.Find(fullName, false);
            if (newT != null)
                return newT;

            newT = (from t in module.Types
                        from it in AllNestTypes(t)
                        where it.FullName == fullName
                        select it).FirstOrDefault();

            return newT;
        }
コード例 #33
0
            // TODO: Make 'ByteGuardGetInteger' method take only one parameter.
            public static void EmbedConstants(ModuleDef targetModule, string decryptionKey, bool compressConstants = true)
            {
                List <byte> constantByteList = new List <byte>();

                // Finds the injected 'ByteGuardProtection' class that contains all the decryption methods.
                TypeDef constantProtections = targetModule.Find("ByteGuard.Protections.Online.Runtime.ByteGuardConstantProtections", true);

                // Finds the 'DecodeAndDecrypt' method located in the 'ByteGuardProtection' class/type.
                MethodDef byteguardGetInteger = constantProtections.FindMethod("ByteGuardGetInteger");

                // Iterates through all the types and methods that are editable.
                foreach (TypeDef t in targetModule.GetTypes().Where(type => !type.Namespace.Contains("ByteGuard.Protections.Online.Runtime")))
                {
                    foreach (MethodDef m in t.Methods.Where(mtd => mtd.HasBody))
                    {
                        // Simplifies all macros so that all constants can be encrypted.
                        m.Body.SimplifyMacros(m.Parameters);

                        // Iterates through each instruction inside the method body.
                        for (int i = 0; i < m.Body.Instructions.Count; i++)
                        {
                            // Stores the current instruction into a variable for us to work with.
                            Instruction ins = m.Body.Instructions[i];

                            // If the current instruction is a constant.
                            if (ins.IsLdcI4())
                            {
                                // Randomly generates an integer that is within the size of a byte.
                                int randomInteger = R.Next(0, 128);

                                // Inserts a call to the method that will get the constant from resources.
                                m.Body.Instructions.Insert(i + 1, Instruction.CreateLdcI4(Convert.ToInt32(ins.Operand) ^ randomInteger));
                                m.Body.Instructions.Insert(i + 2, Instruction.Create(OpCodes.Call, byteguardGetInteger));

                                ins.Operand = constantByteList.Count;

                                // Adds the generated byte to the byte list.
                                constantByteList.Add(Convert.ToByte(randomInteger));

                                // Skips the newly added instructions.
                                i += 2;
                            }
                        }

                        // Optimizes macros to increase performed and reduce file size.
                        m.Body.OptimizeMacros();
                    }
                }

                // Converts the constant byte list into a byte array.
                byte[] constantListBytes = constantByteList.ToArray();

                // Creates a name for the resource.
                string resourceName = Runtime.ByteGuardHelper.GetMd5(EmbeddedResourceName = R.Next(1, 1000000).ToString());

                // Creates an encryption key to encrypt the embedded resource with.
                string resourceEncryptionKey = resourceName + Runtime.ByteGuardHelper.GetMd5(decryptionKey);

                // Encrypts the byte array.
                constantListBytes = ProtectionHelper.AesEncrypt(constantListBytes, resourceEncryptionKey);

                // Compresses the byte array if the user has decided to compress.
                //if (compressBool)
                //constantListBytes = ProtectionHelper.GzipCompressBytes(constantListBytes);
                //else
                //Protection.Miscellaneous.ProtectionHelper.SetByteGuardBool(ByteGuardProtection, "DecompressEmbeddedConstants", false);

                constantListBytes = ProtectionHelper.GzipCompressBytes(constantListBytes);

                // Adds the byte array as an embedded resource to the module.
                EmbeddedResource constantResource = new EmbeddedResource(resourceName, constantListBytes);

                targetModule.Resources.Add(constantResource);

                CallLoadIntegersMethod(targetModule, false);
            }