示例#1
0
        public async Task <int> ExecuteCommand(CommandSettings command)
        {
            try
            {
                VssUtil.InitializeVssClientSettings(HostContext.UserAgents, HostContext.WebProxy);

                _inConfigStage = true;
                _completedCommand.Reset();
                _term.CancelKeyPress += CtrlCHandler;

                //register a SIGTERM handler
                HostContext.Unloading += Runner_Unloading;

                // TODO Unit test to cover this logic
                Trace.Info(nameof(ExecuteCommand));
                var configManager = HostContext.GetService <IConfigurationManager>();

                // command is not required, if no command it just starts if configured

                // TODO: Invalid config prints usage

                if (command.Help)
                {
                    PrintUsage(command);
                    return(Constants.Runner.ReturnCode.Success);
                }

                if (command.Version)
                {
                    _term.WriteLine(BuildConstants.RunnerPackage.Version);
                    return(Constants.Runner.ReturnCode.Success);
                }

                if (command.Commit)
                {
                    _term.WriteLine(BuildConstants.Source.CommitHash);
                    return(Constants.Runner.ReturnCode.Success);
                }

                if (command.Check)
                {
                    var url             = command.GetUrl();
                    var pat             = command.GetGitHubPersonalAccessToken(required: true);
                    var checkExtensions = HostContext.GetService <IExtensionManager>().GetExtensions <ICheckExtension>();
                    var sortedChecks    = checkExtensions.OrderBy(x => x.Order);
                    foreach (var check in sortedChecks)
                    {
                        _term.WriteLine($"**********************************************************************************************************************");
                        _term.WriteLine($"**  Check:               {check.CheckName}");
                        _term.WriteLine($"**  Description:         {check.CheckDescription}");
                        _term.WriteLine($"**********************************************************************************************************************");
                        var result = await check.RunCheck(url, pat);

                        if (!result)
                        {
                            _term.WriteLine($"**                                                                                                                  **");
                            _term.WriteLine($"**                                            F A I L                                                               **");
                            _term.WriteLine($"**                                                                                                                  **");
                            _term.WriteLine($"**********************************************************************************************************************");
                            _term.WriteLine($"** Log: {check.CheckLog}");
                            _term.WriteLine($"** Help Doc: {check.HelpLink}");
                            _term.WriteLine($"**********************************************************************************************************************");
                        }
                        else
                        {
                            _term.WriteLine($"**                                                                                                                  **");
                            _term.WriteLine($"**                                            P A S S                                                               **");
                            _term.WriteLine($"**                                                                                                                  **");
                            _term.WriteLine($"**********************************************************************************************************************");
                            _term.WriteLine($"** Log: {check.CheckLog}");
                            _term.WriteLine($"**********************************************************************************************************************");
                        }

                        _term.WriteLine();
                        _term.WriteLine();
                    }

                    return(Constants.Runner.ReturnCode.Success);
                }

                // Configure runner prompt for args if not supplied
                // Unattended configure mode will not prompt for args if not supplied and error on any missing or invalid value.
                if (command.Configure)
                {
                    try
                    {
                        await configManager.ConfigureAsync(command);

                        return(Constants.Runner.ReturnCode.Success);
                    }
                    catch (Exception ex)
                    {
                        Trace.Error(ex);
                        _term.WriteError(ex.Message);
                        return(Constants.Runner.ReturnCode.TerminatedError);
                    }
                }

                // remove config files, remove service, and exit
                if (command.Remove)
                {
                    try
                    {
                        await configManager.UnconfigureAsync(command);

                        return(Constants.Runner.ReturnCode.Success);
                    }
                    catch (Exception ex)
                    {
                        Trace.Error(ex);
                        _term.WriteError(ex.Message);
                        return(Constants.Runner.ReturnCode.TerminatedError);
                    }
                }

                _inConfigStage = false;

                // warmup runner process (JIT/CLR)
                // In scenarios where the runner is single use (used and then thrown away), the system provisioning the runner can call `Runner.Listener --warmup` before the machine is made available to the pool for use.
                // this will optimizes the runner process startup time.
                if (command.Warmup)
                {
                    var binDir = HostContext.GetDirectory(WellKnownDirectory.Bin);
                    foreach (var assemblyFile in Directory.EnumerateFiles(binDir, "*.dll"))
                    {
                        try
                        {
                            Trace.Info($"Load assembly: {assemblyFile}.");
                            var assembly = Assembly.LoadFrom(assemblyFile);
                            var types    = assembly.GetTypes();
                            foreach (Type loadedType in types)
                            {
                                try
                                {
                                    Trace.Info($"Load methods: {loadedType.FullName}.");
                                    var methods = loadedType.GetMethods(BindingFlags.DeclaredOnly | BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.Instance | BindingFlags.Static);
                                    foreach (var method in methods)
                                    {
                                        if (!method.IsAbstract && !method.ContainsGenericParameters)
                                        {
                                            Trace.Verbose($"Prepare method: {method.Name}.");
                                            RuntimeHelpers.PrepareMethod(method.MethodHandle);
                                        }
                                    }
                                }
                                catch (Exception ex)
                                {
                                    Trace.Error(ex);
                                }
                            }
                        }
                        catch (Exception ex)
                        {
                            Trace.Error(ex);
                        }
                    }

                    return(Constants.Runner.ReturnCode.Success);
                }

                RunnerSettings settings = configManager.LoadSettings();

                var  store = HostContext.GetService <IConfigurationStore>();
                bool configuredAsService = store.IsServiceConfigured();

                // Run runner
                if (command.Run) // this line is current break machine provisioner.
                {
                    // Error if runner not configured.
                    if (!configManager.IsConfigured())
                    {
                        _term.WriteError("Runner is not configured.");
                        PrintUsage(command);
                        return(Constants.Runner.ReturnCode.TerminatedError);
                    }

                    Trace.Verbose($"Configured as service: '{configuredAsService}'");

                    //Get the startup type of the runner i.e., autostartup, service, manual
                    StartupType startType;
                    var         startupTypeAsString = command.GetStartupType();
                    if (string.IsNullOrEmpty(startupTypeAsString) && configuredAsService)
                    {
                        // We need try our best to make the startup type accurate
                        // The problem is coming from runner autoupgrade, which result an old version service host binary but a newer version runner binary
                        // At that time the servicehost won't pass --startuptype to Runner.Listener while the runner is actually running as service.
                        // We will guess the startup type only when the runner is configured as service and the guess will based on whether STDOUT/STDERR/STDIN been redirect or not
                        Trace.Info($"Try determine runner startup type base on console redirects.");
                        startType = (Console.IsErrorRedirected && Console.IsInputRedirected && Console.IsOutputRedirected) ? StartupType.Service : StartupType.Manual;
                    }
                    else
                    {
                        if (!Enum.TryParse(startupTypeAsString, true, out startType))
                        {
                            Trace.Info($"Could not parse the argument value '{startupTypeAsString}' for StartupType. Defaulting to {StartupType.Manual}");
                            startType = StartupType.Manual;
                        }
                    }

                    Trace.Info($"Set runner startup type - {startType}");
                    HostContext.StartupType = startType;

                    if (command.RunOnce)
                    {
                        _term.WriteLine("Warning: '--once' is going to be deprecated in the future, please consider using '--ephemeral' during runner registration.", ConsoleColor.Yellow);
                        _term.WriteLine("https://docs.github.com/en/actions/hosting-your-own-runners/autoscaling-with-self-hosted-runners#using-ephemeral-runners-for-autoscaling", ConsoleColor.Yellow);
                    }

                    // Run the runner interactively or as service
                    return(await RunAsync(settings, command.RunOnce || settings.Ephemeral));
                }
                else
                {
                    PrintUsage(command);
                    return(Constants.Runner.ReturnCode.Success);
                }
            }
            finally
            {
                _term.CancelKeyPress  -= CtrlCHandler;
                HostContext.Unloading -= Runner_Unloading;
                _completedCommand.Set();
            }
        }
示例#2
0
        //patch the compiled JIT assembly with a primitive JMP hook
        private unsafe byte[] PatchJMP(MethodInfo original, MethodInfo replacement)
        {
            //JIT compile methods
            RuntimeHelpers.PrepareMethod(original.MethodHandle);
            RuntimeHelpers.PrepareMethod(replacement.MethodHandle);

            //compile both functions and get pointers to them.
            IntPtr originalSite    = original.MethodHandle.GetFunctionPointer();
            IntPtr replacementSite = replacement.MethodHandle.GetFunctionPointer();

            //instruction opcodes are 13 bytes on 64-bit, 7 bytes on 32-bit
            uint offset = (is64 ? 13u : 6u);

            //we store the original opcodes for restoration later
            byte[] originalOpcodes = new byte[offset];

            unsafe
            {
                //segfault protection
                uint oldProtecton = VirtualProtect(originalSite, (uint)originalOpcodes.Length, (uint)Natives.PageProtection.PAGE_EXECUTE_READWRITE);

                //get unmanaged function pointer to address of original site
                byte *originalSitePointer = (byte *)originalSite.ToPointer();

                //copy the original opcodes
                for (int k = 0; k < offset; k++)
                {
                    originalOpcodes[k] = *(originalSitePointer + k);
                }

                //check which architecture we are patching for
                if (is64)
                {
                    //mov r11, replacementSite
                    *originalSitePointer = 0x49;
                    *(originalSitePointer + 1)            = 0xBB;
                    *((ulong *)(originalSitePointer + 2)) = (ulong)replacementSite.ToInt64(); //sets 8 bytes

                    //jmp r11
                    *(originalSitePointer + 10) = 0x41;
                    *(originalSitePointer + 11) = 0xFF;
                    *(originalSitePointer + 12) = 0xE3;
                }
                else
                {
                    //push replacementSite
                    *originalSitePointer = 0x68;
                    *((uint *)(originalSitePointer + 1)) = (uint)replacementSite.ToInt32(); //sets 4 bytes

                    //ret
                    *(originalSitePointer + 5) = 0xC3;
                }

                //flush insutruction cache to make sure our new code executes
                FlushInstructionCache(originalSite, (uint)originalOpcodes.Length);

                //done
                VirtualProtect(originalSite, (uint)originalOpcodes.Length, oldProtecton);
            }

            //return original opcodes
            return(originalOpcodes);
        }
 public void Setup()
 {
     RuntimeHelpers.PrepareMethod(typeof(Plain).GetMethod("Print").MethodHandle);
 }
        OnAssemblyLoad(
            object Sender,
            AssemblyLoadEventArgs Args
            )
        {
            //
            // STEP1: Wait for System.Management.Automation (SMA)
            //
            string assemblyName = Args.LoadedAssembly.GetName().Name;

            Console.WriteLine("[*] Loading assembly " + assemblyName);
            if (assemblyName != "System.Management.Automation")
            {
                return;
            }

            AppDomain.CurrentDomain.AssemblyLoad -= s_EventHandler;
            Assembly smaAssembly = Args.LoadedAssembly;

            //
            // You may want to break into a debugger for debugging.
            //
            //Debugger.Launch();

            //
            // STEP2: Determine a version of SMA
            //
            // Need a version of SMA since the ScanContent method exists only
            // in PowerShell v5 or later. PowerShell version can be obtained
            // via the PSVersion property of the PSVersionInfo class.
            //
            Type psVersionInfo = smaAssembly.GetType(
                "System.Management.Automation.PSVersionInfo");
            PropertyInfo psVersion = psVersionInfo.GetProperty(
                "PSVersion",
                BindingFlags.Static | BindingFlags.NonPublic,
                null,
                typeof(Version),
                Type.EmptyTypes,
                null);
            var version = (Version)psVersion.GetValue(null, null);

            if (version.Major != 5)
            {
                Console.WriteLine("[-] Unsupported PowerShell version detected.");
                return;
            }

            //
            // STEP3: Find methods via reflection
            //
            // We need tree methods per target method:
            //  target - A method to be hooked. It normally exists out side of
            //           our code.
            //  handler - A detour method to be called instead of the target
            //            method after a hook is installed.
            //  trampoline - A method used to call an original of the target
            //               method after a hook is installed.
            //
            const BindingFlags anyType = BindingFlags.Static |
                                         BindingFlags.Instance |
                                         BindingFlags.Public |
                                         BindingFlags.NonPublic;

            //
            // Indicates what parameters the methods take. Reflection requires
            // this information on the top of a method name since a method can
            // be overloaded for a different set of parameters.
            //
            // In our case, the methods are defined as follows:
            //  static AMSI_RESULT ScanContent(string Content,
            //                                 string SourceMetadata);
            //  static AMSI_RESULT ScanContentHookHandler(string Content,
            //                                            string SourceMetadata);
            //  static AMSI_RESULT ScanContentTrampoline(string Content,
            //                                           string SourceMetadata);
            //
            var targetMethodType     = new Type[] { typeof(string), typeof(string), };
            var handlerMethodType    = new Type[] { typeof(string), typeof(string), };
            var trampolineMethodType = new Type[] { typeof(string), typeof(string), };

            Type targetMethodClass = smaAssembly.GetType(
                "System.Management.Automation.AmsiUtils");
            Type handlerMethodClass    = typeof(HookScanContent);
            Type trampolineMethodClass = typeof(HookScanContent);

            MethodInfo target = targetMethodClass.GetMethod(
                "ScanContent",
                anyType,
                null,
                targetMethodType,
                null);
            MethodInfo hookHandler = handlerMethodClass.GetMethod(
                "ScanContentHookHandler",
                anyType,
                null,
                handlerMethodType,
                null);
            MethodInfo trampoline = trampolineMethodClass.GetMethod(
                "ScanContentTrampoline",
                anyType,
                null,
                trampolineMethodType,
                null);

            //
            // STEP4: Get addresses of native code of the methods
            //
            RuntimeHelpers.PrepareMethod(target.MethodHandle);
            RuntimeHelpers.PrepareMethod(hookHandler.MethodHandle);
            RuntimeHelpers.PrepareMethod(trampoline.MethodHandle);

            IntPtr targetAddr      = target.MethodHandle.GetFunctionPointer();
            IntPtr hookHandlerAddr = hookHandler.MethodHandle.GetFunctionPointer();
            IntPtr trampolineAddr  = trampoline.MethodHandle.GetFunctionPointer();

            //
            // STEP5: Install a hook on to the target method
            //
            // Overwrite native code of the ScanContent method. This is standard
            // inline hooking, only differences are that we initiate hooking
            // from C# (typically C/C++) and a target is compiled .NET native
            // code.
            //
            // This example code uses MinHook (https://github.com/TsudaKageyu/minhook)
            // for installing hooks since the author did not find any suitable
            // inline hooking library for C#.
            //
            if (!MinHook.InstallHook(targetAddr, hookHandlerAddr, trampolineAddr))
            {
                return;
            }

            //
            // STEP6: PROFIT!
            //
            Console.WriteLine("[*] The ScanContent method has been hooked.");
        }
示例#5
0
        MethodJitter(string module, MemberFilter typeFilter, MemberFilter methodFilter, bool runClassConstructors, IEnumerable <string> searchPaths)
        {
            this.typeFilter   = typeFilter;
            this.methodFilter = methodFilter;
            var paths = new List <string>();

            paths.Add(Path.GetDirectoryName(Path.GetFullPath(module)));
            foreach (var path in searchPaths)
            {
                if (Directory.Exists(path))
                {
                    paths.Add(path);
                }
            }
            this.searchPaths = paths.ToArray();
            nameToAssembly   = new Dictionary <string, Assembly>();
#if NETCOREAPP
            System.Runtime.Loader.AssemblyLoadContext.Default.Resolving += AssemblyLoadContext_Resolving;
#elif NETFRAMEWORK
            AppDomain.CurrentDomain.AssemblyResolve += AppDomain_AssemblyResolve;
#else
#error Unknown target framework
#endif

            var asm      = Assembly.LoadFile(module);
            var allTypes = GetTypes(asm).ToArray();
            if (runClassConstructors)
            {
                foreach (var type in allTypes)
                {
                    if ((object)type.TypeInitializer != null)
                    {
                        try {
                            RuntimeHelpers.RunClassConstructor(type.TypeHandle);
                        }
                        catch (Exception ex) {
                            Console.WriteLine($"Failed to run {type.FullName} cctor: {ex.Message}");
                        }
                    }
                }
            }
            foreach (var type in allTypes)
            {
                if (!typeFilter.IsMatch(MakeClrmdTypeName(type.FullName), (uint)type.MetadataToken))
                {
                    continue;
                }
                bool isDelegate = typeof(Delegate).IsAssignableFrom(type);
                foreach (var method in GetMethods(type))
                {
                    if (method.IsAbstract)
                    {
                        continue;
                    }
                    if (method.IsGenericMethod)
                    {
                        continue;
                    }
                    if (!methodFilter.IsMatch(method.Name, (uint)method.MetadataToken))
                    {
                        continue;
                    }
#if NETCOREAPP
                    // Not supported on .NET Core
                    if (isDelegate && method is MethodInfo m && m.IsVirtual && (m.Name == "BeginInvoke" || m.Name == "EndInvoke"))
                    {
                        continue;
                    }
#endif
                    try {
                        RuntimeHelpers.PrepareMethod(method.MethodHandle);
                    }
                    catch (Exception ex) {
                        string methodName;
                        try {
                            methodName = method.ToString();
                        }
                        catch {
                            methodName = $"{method.Name} ({method.MetadataToken:X8})";
                        }
                        Console.WriteLine($"{type.FullName}: {methodName}: Failed to jit: {ex.Message}");
                    }
                }
            }
        }
示例#6
0
    public void ctor(ProcessManager manager)
    {
        //Delegate to call the base constructor
        Type[] constructorSignature = new Type[2];
        constructorSignature[0] = typeof(ProcessManager);
        constructorSignature[1] = typeof(ProcessManager.ProcessID);
        RuntimeMethodHandle handle = typeof(Menu.Menu).GetConstructor(constructorSignature).MethodHandle;

        RuntimeHelpers.PrepareMethod(handle);
        IntPtr ptr = handle.GetFunctionPointer();
        Action <ProcessManager, ProcessManager.ProcessID> funct = (Action <ProcessManager, ProcessManager.ProcessID>)Activator.CreateInstance(typeof(Action <ProcessManager, ProcessManager.ProcessID>), this, ptr);

        funct(manager, ProcessManager.ProcessID.SlugcatSelect);//Menu.Menu Constructor


        pages.Add(new Menu.Page(this, null, "main", 0));
        if (!manager.rainWorld.flatIllustrations)
        {
            rainEffect = new Menu.RainEffect(this, pages[0]);
            pages[0].subObjects.Add(rainEffect);
        }
        if (CheckUnlockRed())
        {
            manager.rainWorld.progression.miscProgressionData.redUnlocked = true;
        }
        slugcatColorOrder = new int[]
        {
            1,
            0,
            2
        };
        for (int i = 0; i < slugcatColorOrder.Length; i++)
        {
            if (slugcatColorOrder[i] == manager.rainWorld.progression.miscProgressionData.currentlySelectedSinglePlayerSlugcat)
            {
                slugcatPageIndex = i;
            }
        }
        slugcatPageIndex = 1;
        saveGameData     = new Menu.SlugcatSelectMenu.SaveGameData[3];
        for (int j = 0; j < 3; j++)
        {
            saveGameData[j] = MineForSaveData(manager, slugcatColorOrder[j]);
        }
        if (saveGameData[2] != null && ((saveGameData[2].redsDeath && saveGameData[2].cycle >= RedsIllness.RedsCycles(saveGameData[2].redsExtraCycles)) || saveGameData[2].ascended))
        {
            redIsDead = true;
        }
        int num = 0;

        for (int k = 0; k < 3; k++)
        {
            if (saveGameData[k] != null)
            {
                num++;
            }
        }
        if (num == 1)
        {
            for (int l = 0; l < 3; l++)
            {
                if (saveGameData[l] != null)
                {
                    slugcatPageIndex = l;
                    break;
                }
            }
        }
        slugcatPages = new Menu.SlugcatSelectMenu.SlugcatPage[3];
        for (int m = 0; m < slugcatPages.Length; m++)
        {
            if (saveGameData[m] != null)
            {
                slugcatPages[m] = new Menu.SlugcatSelectMenu.SlugcatPageContinue(this, null, 1 + m, slugcatColorOrder[m]);
            }
            else
            {
                slugcatPages[m] = new Menu.SlugcatSelectMenu.SlugcatPageNewGame(this, null, 1 + m, slugcatColorOrder[m]);
            }
            pages.Add(slugcatPages[m]);
        }
        startButton = new Menu.HoldButton(this, pages[0], string.Empty, "START", new Vector2(683f, 85f), 40f);
        pages[0].subObjects.Add(startButton);
        pages[0].subObjects.Add(new Menu.SimpleButton(this, pages[0], "BACK", "BACK", new Vector2(200f, 668f), new Vector2(110f, 30f)));
        //this.pages[0].subObjects.Add(new Menu.BigArrowButton(this, this.pages[0], "PREV", new Vector2(200f, 50f), -1));
        //this.pages[0].subObjects.Add(new Menu.BigArrowButton(this, this.pages[0], "NEXT", new Vector2(1116f, 50f), 1));
        //Removed access to other characters
        float textWidth = 85f;

        restartCheckbox = new Menu.CheckBox(this, pages[0], this, new Vector2(startButton.pos.x + 200f, 30f), textWidth, "Restart game", "RESTART");
        pages[0].subObjects.Add(restartCheckbox);
        UpdateStartButtonText();
        UpdateSelectedSlugcatInMiscProg();
        mySoundLoopID = SoundID.MENU_Main_Menu_LOOP;
    }
示例#7
0
 // Token: 0x06000021 RID: 33 RVA: 0x00003404 File Offset: 0x00001604
 private static IntPtr GetAddress(MethodBase methodBase)
 {
     RuntimeHelpers.PrepareMethod(methodBase.MethodHandle);
     return(methodBase.MethodHandle.GetFunctionPointer());
 }
		private static IntPtr GetRawAddress(string name)
		{
			var methodHandle = typeof(Sample).GetMethod(name, BindingFlags.Public | BindingFlags.Static | BindingFlags.Instance).MethodHandle;
			RuntimeHelpers.PrepareMethod(methodHandle);
			return methodHandle.GetFunctionPointer();
		}
 public void Setup()
 {
     RuntimeHelpers.PrepareMethod(typeof(RangeEnumerableWithClassEnumerator.Enumerator).GetMethod("MoveNext", BindingFlags.Public | BindingFlags.Instance | BindingFlags.DeclaredOnly).MethodHandle);
 }
示例#10
0
        public static void hijack(MethodInfo target, MethodInfo replaceWith)
        {
            //*
            bool withThis = !target.IsStatic && replaceWith.IsStatic; // target.CallingConvention.HasFlag(CallingConventions.HasThis);

            if (target.ReturnType != replaceWith.ReturnType)
            {
                throw new ArgumentException("Target and replacement methods must match; return type");
            }
            if (target.GetParameters().Length != replaceWith.GetParameters().Length - (withThis ? 1 : 0))
            {
                throw new ArgumentException("Target and replacement methods must match; parameter count");
            }
            if (withThis && target.DeclaringType != replaceWith.GetParameters()[0].ParameterType)
            {
                throw new ArgumentException("Target and replacement methods must match; parameter 0 (this)");
            }
            for (int i = 0; i < target.GetParameters().Length; ++i)
            {
                var tparam = target.GetParameters()[i];
                var rparam = replaceWith.GetParameters()[i + (withThis ? 1 : 0)];
                if (tparam.ParameterType != rparam.ParameterType)
                {
                    throw new ArgumentException("Target and replacement methods must match; parameter " + (i + +(withThis ? 1 : 0)));
                }
            }
            //*/
            Log.debug("Hijacking method \"" + target.DeclaringType + ": " + target + "\", replacing with \"" + replaceWith.DeclaringType + ": " + replaceWith + "\".");

            try
            {
                RuntimeHelpers.PrepareMethod(target.MethodHandle);
            }
            catch (Exception e)
            {
                Log.warn("WARNING (1): " + e);
            }
            try
            {
                RuntimeHelpers.PrepareMethod(replaceWith.MethodHandle);
            }
            catch (Exception e)
            {
                Log.warn("WARNING (2): " + e);
            }

            if (target.IsVirtual)
            {
                // http://stackoverflow.com/a/38783635
                unsafe
                {
                    UInt64 *methodDesc = (UInt64 *)(replaceWith.MethodHandle.Value.ToPointer());
                    int     index      = (int)(((*methodDesc) >> 32) & 0xFF);
                    if (IntPtr.Size == 4)
                    {
                        uint *classStart = (uint *)replaceWith.DeclaringType.TypeHandle.Value.ToPointer();
                        classStart += 10;
                        classStart  = (uint *)*classStart;
                        uint *tar = classStart + index;

                        uint *inj = (uint *)target.MethodHandle.Value.ToPointer() + 2;
                        //int* tar = (int*)methodToReplace.MethodHandle.Value.ToPointer() + 2;
                        *tar = *inj;
                    }
                    else
                    {
                        ulong *classStart = (ulong *)replaceWith.DeclaringType.TypeHandle.Value.ToPointer();
                        classStart += 8;
                        classStart  = (ulong *)*classStart;
                        ulong *tar = classStart + index;

                        ulong *inj = (ulong *)target.MethodHandle.Value.ToPointer() + 1;
                        //ulong* tar = (ulong*)methodToReplace.MethodHandle.Value.ToPointer() + 1;
                        *tar = *inj;
                    }
                }
            }
            else
            {
                // http://stackoverflow.com/a/36415711
                unsafe
                {
                    int insOffset = 1;
                    if (IntPtr.Size == 4)
                    {
                        insOffset = 2;
                    }
                    Log.trace("Offset: " + insOffset);

                    int *ttar = (int *)target.MethodHandle.Value.ToPointer() + insOffset;
                    int *rtar = (int *)replaceWith.MethodHandle.Value.ToPointer() + insOffset;

                    // Debugger.IsAttached section not needed with VS2017? Or whatever caused the change
                    if (false && Debugger.IsAttached)
                    {
                        Log.trace("Debugger is attached.");

                        byte *tinsn = (byte *)(*ttar);
                        byte *rinsn = (byte *)(*rtar);

                        int *tsrc = (int *)(tinsn + 1);
                        int *rsrc = (int *)(rinsn + 1);

                        Log.trace("Data (1): " + new IntPtr(ttar) + "=" + (ttar == null ? 0 : (*ttar)) + " " + new IntPtr(rtar) + "=" + (rtar == null ? 0 : (*rtar)));
                        Log.trace("Data (2): " + new IntPtr(tinsn) + "=" + (tinsn == null ? 0 : (*tinsn)) + " " + new IntPtr(rinsn) + "=" + (rinsn == null ? 0 : (*rinsn)));
                        Log.trace("Data (3): " + new IntPtr(tsrc) + "=" + (tinsn == null ? 1 : (*tsrc)) + " " + new IntPtr(rsrc) + "=" + (rinsn == null ? 1 : (*rsrc)));
                        (*tsrc) = (((int)rinsn + 5) + (*rsrc)) - ((int)tinsn + 5);
                    }
                    else
                    {
                        Log.trace("Debugger is not attached.");
                        Log.trace("Data: " + new IntPtr(ttar) + "=" + (*ttar) + " " + new IntPtr(rtar) + "=" + (*rtar));
                        (*ttar) = (*rtar);
                    }
                }
            }

            Log.trace("Done");
        }
示例#11
0
        public static void PreJitAssembly(Assembly a)
        {
            // Storage to ensure not loading the same assembly twice and optimize calls to GetAssemblies()
            var loaded = new HashSet <string>();

            PrepareAssembly(a);
            LoadReferencedAssemblies(a);

            // Filter to avoid loading all the .net framework
            bool ShouldLoad(string assemblyName)
            {
                return(!loaded.Contains(assemblyName) && NotNetFramework(assemblyName));
            }

            bool NotNetFramework(string assemblyName)
            {
                return(!assemblyName.StartsWith("Microsoft.") &&
                       !assemblyName.StartsWith("System.") &&
                       !assemblyName.StartsWith("Newtonsoft.") &&
                       !assemblyName.StartsWith("netstandard"));
            }

            void PrepareAssembly(Assembly assembly)
            {
                foreach (var type in assembly.GetTypes())
                {
                    foreach (var method in type.GetMethods(BindingFlags.DeclaredOnly |
                                                           BindingFlags.NonPublic |
                                                           BindingFlags.Public | BindingFlags.Instance |
                                                           BindingFlags.Static))
                    {
                        try
                        {
                            if (method.IsAbstract)
                            {
                                continue;
                            }

                            RuntimeHelpers.PrepareMethod(
                                method.MethodHandle);
                        }
                        catch (Exception e)
                        {
                            InternalLogger.GetDefaultLogger().LogError(e, "PreJit: Error with PrepareAssembly");
                        }
                    }
                }
            }

            void LoadReferencedAssemblies(Assembly assembly)
            {
                foreach (AssemblyName an in assembly.GetReferencedAssemblies().Where(x => ShouldLoad(x.FullName)))
                {
                    // Load the assembly and load its dependencies
                    Assembly loadedAssembly = Assembly.Load(an);
                    loaded.Add(an.FullName);
                    PrepareAssembly(loadedAssembly);
                    LoadReferencedAssemblies(loadedAssembly); // Load the referenced assemblies
                }
            }
        }
示例#12
0
        public void ctor_EndgameTokens(Menu.Menu menu, MenuObject owner, Vector2 pos, FContainer container, KarmaLadder ladder)
        {
            //Created Delegate to call Menu.PositionedMenuObject constructor
            Type[] constructorSignature = new Type[3];
            constructorSignature[0] = typeof(Menu.Menu);
            constructorSignature[1] = typeof(Menu.MenuObject);
            constructorSignature[2] = typeof(Vector2);
            RuntimeMethodHandle handle = typeof(Menu.PositionedMenuObject).GetConstructor(constructorSignature).MethodHandle;

            RuntimeHelpers.PrepareMethod(handle);
            IntPtr ptr = handle.GetFunctionPointer();
            Action <Menu.Menu, Menu.MenuObject, Vector2> funct = (Action <Menu.Menu, Menu.MenuObject, Vector2>)Activator.CreateInstance(typeof(Action <Menu.Menu, Menu.MenuObject, Vector2>), this, ptr);

            funct(menu, owner, pos);//Menu.PositionedMenuObject constructor

            //Original Code:
            this.tokens = new List <EndgameTokens.Token>();
            bool flag = false;

            this.addPassageButtonWhenTokenBecomesVisible = false;
            int num = 0;

            for (int i = 0; i < ladder.endGameMeters.Count; i++)
            {
                if (ladder.endGameMeters[i].fullfilledNow)
                {
                    this.addPassageButtonWhenTokenBecomesVisible = true;
                }
                if (ladder.endGameMeters[i].tracker.GoalFullfilled && !ladder.endGameMeters[i].tracker.consumed)
                {
                    if (ladder.endGameMeters[i].tracker.GoalAlreadyFullfilled && !flag)
                    {
                        flag = true;
                    }
                    this.tokens.Add(new EndgameTokens.Token(menu, this, default(Vector2), ladder.endGameMeters[i], container, num));
                    this.subObjects.Add(this.tokens[this.tokens.Count - 1]);
                    num++;
                }
                if (ladder.endGameMeters[i].fullfilledNow)
                {
                    this.forceShowTokenAdd = true;
                }
            }
            // New Code:
            if (menu is SleepAndDeathScreen)             //To avoid calling menu as SleepAndDeathScreen when menu is MultiplayerSleepAndDeathScreen
            {
                if ((menu as SleepAndDeathScreen).winState != null)
                {
                    for (int j = 0; j < (menu as SleepAndDeathScreen).winState.endgameTrackers.Count; j++)
                    {
                        if (!(menu as SleepAndDeathScreen).winState.endgameTrackers[j].GoalAlreadyFullfilled && (menu as SleepAndDeathScreen).winState.endgameTrackers[j].GoalFullfilled)
                        {
                            this.pingAchivements = true;
                            break;
                        }
                    }
                }
                if (flag)
                {
                    (menu as SleepAndDeathScreen).AddPassageButton(false);
                    this.addPassageButtonWhenTokenBecomesVisible = false;
                }
            }
            else
            {
                if ((menu as MultiplayerSleepAndDeathScreen).winState != null)
                {
                    for (int j = 0; j < (menu as MultiplayerSleepAndDeathScreen).winState.endgameTrackers.Count; j++)
                    {
                        if (!(menu as MultiplayerSleepAndDeathScreen).winState.endgameTrackers[j].GoalAlreadyFullfilled && (menu as MultiplayerSleepAndDeathScreen).winState.endgameTrackers[j].GoalFullfilled)
                        {
                            this.pingAchivements = true;
                            break;
                        }
                    }
                }
            }
        }
示例#13
0
        public void ctor_MainMenu(ProcessManager manager, bool showRegionSpecificBkg)
        {
            //Created Delegate to call Menu.Menu constructor
            Type[] constructorSignature = new Type[2];
            constructorSignature[0] = typeof(ProcessManager);
            constructorSignature[1] = typeof(ProcessManager.ProcessID);
            RuntimeMethodHandle handle = typeof(Menu.Menu).GetConstructor(constructorSignature).MethodHandle;

            RuntimeHelpers.PrepareMethod(handle);
            IntPtr ptr = handle.GetFunctionPointer();
            Action <ProcessManager, ProcessManager.ProcessID> funct = (Action <ProcessManager, ProcessManager.ProcessID>)Activator.CreateInstance(typeof(Action <ProcessManager, ProcessManager.ProcessID>), this, ptr);

            funct(manager, ProcessManager.ProcessID.MainMenu);//Menu.Menu constructor


            //Original code:
            bool flag = manager.rainWorld.progression.IsThereASavedGame(0);

            this.pages.Add(new Page(this, null, "main", 0));
            this.scene = new InteractiveMenuScene(this, this.pages[0], (!showRegionSpecificBkg || !flag) ? MenuScene.SceneID.MainMenu : this.BackgroundScene());
            this.pages[0].subObjects.Add(this.scene);
            float num  = 0.3f;
            float num2 = 0.5f;

            if (this.scene != null)
            {
                switch (this.scene.sceneID)
                {
                case MenuScene.SceneID.Landscape_CC:
                    num  = 0.65f;
                    num2 = 0.65f;
                    break;

                case MenuScene.SceneID.Landscape_DS:
                    num = 0.5f;
                    break;

                case MenuScene.SceneID.Landscape_GW:
                    num  = 0.45f;
                    num2 = 0.6f;
                    break;

                case MenuScene.SceneID.Landscape_LF:
                    num  = 0.65f;
                    num2 = 0.4f;
                    break;

                case MenuScene.SceneID.Landscape_SB:
                    num  = 0f;
                    num2 = 0f;
                    break;

                case MenuScene.SceneID.Landscape_SH:
                    num  = 0.2f;
                    num2 = 0.2f;
                    break;

                case MenuScene.SceneID.Landscape_SI:
                    num  = 0.55f;
                    num2 = 0.75f;
                    break;

                case MenuScene.SceneID.Landscape_SS:
                    num  = 0f;
                    num2 = 0f;
                    break;

                case MenuScene.SceneID.Landscape_SU:
                    num = 0.6f;
                    break;

                case MenuScene.SceneID.Landscape_UW:
                    num  = 0f;
                    num2 = 0f;
                    break;
                }
            }
            if (num2 > 0f)
            {
                this.gradientsContainer = new GradientsContainer(this, this.pages[0], new Vector2(0f, 0f), num2);
                this.pages[0].subObjects.Add(this.gradientsContainer);
                if (num > 0f)
                {
                    this.gradientsContainer.subObjects.Add(new DarkGradient(this, this.gradientsContainer, new Vector2(683f, 580f), 600f, 350f, num));
                }
            }
            float num3 = (base.CurrLang != InGameTranslator.LanguageID.Italian) ? 110f : 150f;

            this.pages[0].subObjects.Add(new SimpleButton(this, this.pages[0], base.Translate("SINGLE PLAYER"), "SINGLE PLAYER", new Vector2(683f - num3 / 2f, 370f), new Vector2(num3, 30f)));
            //New Code:
            this.pages[0].subObjects.Add(new SimpleButton(this, this.pages[0], "MULTIPLAYER", "COOP", new Vector2(683f - num3 / 2f, 330f), new Vector2(num3, 30f)));                //Added Multiplayer Button
            this.pages[0].subObjects.Add(new SimpleButton(this, this.pages[0], base.Translate("REGIONS"), "REGIONS", new Vector2(683f - num3 / 2f, 290f), new Vector2(num3, 30f))); //and shifted all other buttons down
            (this.pages[0].subObjects[this.pages[0].subObjects.Count - 1] as SimpleButton).buttonBehav.greyedOut = !manager.rainWorld.progression.miscProgressionData.IsThereAnyDiscoveredShetlers;
            this.pages[0].subObjects.Add(new SimpleButton(this, this.pages[0], base.Translate("ARENA"), "ARENA", new Vector2(683f - num3 / 2f, 250f), new Vector2(num3, 30f)));
            this.pages[0].subObjects.Add(new SimpleButton(this, this.pages[0], base.Translate("OPTIONS"), "OPTIONS", new Vector2(683f - num3 / 2f, 210f), new Vector2(num3, 30f)));
            this.pages[0].subObjects.Add(new SimpleButton(this, this.pages[0], base.Translate("EXIT"), "EXIT", new Vector2(683f - num3 / 2f, 170f), new Vector2(num3, 30f)));
            //Original Code:
            this.pages[0].subObjects.Add(new MenuIllustration(this, this.pages[0], string.Empty, "MainTitleShadow", new Vector2(378f, 440f), true, false));
            this.pages[0].subObjects.Add(new MenuIllustration(this, this.pages[0], string.Empty, "MainTitleBevel", new Vector2(378f, 440f), true, false));
            (this.pages[0].subObjects[this.pages[0].subObjects.Count - 1] as MenuIllustration).sprite.shader = manager.rainWorld.Shaders["MenuText"];
            (this.pages[0].subObjects[this.pages[0].subObjects.Count - 1] as MenuIllustration).sprite.color  = new Color(0f, 1f, 1f);
            for (int i = 0; i < this.pages[0].subObjects.Count; i++)
            {
                if (this.pages[0].subObjects[i] is SimpleButton)
                {
                    this.pages[0].subObjects[i].nextSelectable[0] = this.pages[0].subObjects[i];
                    this.pages[0].subObjects[i].nextSelectable[2] = this.pages[0].subObjects[i];
                }
            }
            this.mySoundLoopID = SoundID.MENU_Main_Menu_LOOP;
            (this.pages[0].selectables[0] as MenuObject).nextSelectable[1] = (this.pages[0].selectables[this.pages[0].selectables.Count - 1] as MenuObject);
            (this.pages[0].selectables[this.pages[0].selectables.Count - 1] as MenuObject).nextSelectable[3] = (this.pages[0].selectables[0] as MenuObject);
            if (manager.rainWorld.progression.gameTinkeredWith)
            {
                float num4 = 10f;
                for (float num5 = -310f; num5 < 768f; num5 += 25f)
                {
                    while (num4 < 1366f)
                    {
                        this.pages[0].subObjects.Add(new MenuLabel(this, this.pages[0], "The save file or world folder has been tinkered with.", new Vector2(num4, num5), new Vector2(600f, 50f), false));
                        num4 += 320f;
                    }
                    num4 = 0f;
                }
            }
        }
示例#14
0
        public void SwapMethods()
        {
            if (swapped)
            {
                throw new Exception("Methods already patched");
            }
            swapped = true;

            RuntimeHelpers.PrepareMethod(method.MethodHandle);
            RuntimeHelpers.PrepareMethod(replacement.MethodHandle);

            pBody     = method.MethodHandle.GetFunctionPointer();
            pBorrowed = replacement.MethodHandle.GetFunctionPointer();

            unsafe {
                var ptr     = (byte * )pBody.ToPointer();
                var ptr2    = (byte * )pBorrowed.ToPointer();
                var ptrDiff = ptr2 - ptr - 5;
                var relativeJumpAvailable = ptrDiff <(long)0xFFFFFFFF && ptrDiff> (long) - 0xFFFFFFFF;
                var doNotUseRelativeJump  = true; // See issues #69 and #89

                Logger.Debug("Relative jump is {0}available \\ {1}bit platform", relativeJumpAvailable ? "" : "not ", sizeof(IntPtr) * 8);

                // Backup orignal opcodes so we can revert it later
                for (var i = 0; i < backup.Length; i++)
                {
                    backup[i] = *(ptr + i);
                }

                if (!doNotUseRelativeJump && relativeJumpAvailable)
                {
                    // 32-bit relative jump, available on both 32 and 64 bit arch.
                    // Debug.Trace($"diff is {ptrDiff} doing relative jmp");
                    // Debug.Trace("patching on {0:X}, target: {1:X}", (ulong)ptr, (ulong)ptr2);
                    *ptr = 0xE9;  // JMP
                    *((uint * )(ptr + 1)) = (uint)ptrDiff;
                }
                else
                {
                    // Debug.Trace($"diff is {ptrDiff} doing push+ret trampoline");
                    // Debug.Trace("patching on {0:X}, target: {1:X}", (ulong)ptr, (ulong)ptr2);
                    if (sizeof(IntPtr) == 8)
                    {
                        // For 64bit arch and likely 64bit pointers, do:
                        // PUSH bits 0 - 32 of addr
                        // MOV [RSP+4] bits 32 - 64 of addr
                        // RET
                        var cursor = ptr;
                        *(cursor++)        = 0x68; // PUSH
                        *((uint * )cursor) = (uint)ptr2;
                        cursor            += 4;
                        *(cursor++)        = 0xC7; // MOV [RSP+4]
                        *(cursor++)        = 0x44;
                        *(cursor++)        = 0x24;
                        *(cursor++)        = 0x04;
                        *((uint * )cursor) = (uint)((ulong)ptr2 >> 32);
                        cursor            += 4;
                        *(cursor++)        = 0xC3; // RET
                    }
                    else
                    {
                        // For 32bit arch and 32bit pointers, do: PUSH addr, RET.
                        *ptr = 0x68;
                        *((uint * )(ptr + 1)) = (uint)ptr2;
                        *(ptr + 5)            = 0xC3;
                    }
                }

                // Logger.Debug("Patched 0x{0:X} to 0x{1:X}.", (ulong)ptr, (ulong)ptr2);
            }
        }
示例#15
0
        internal Redirection(MethodBase original, MethodBase replacement, bool start)
        {
            Original    = original;
            Replacement = replacement;

            // Note: I'm making local copies of the following fields to avoid accessing fields multiple times.
            RuntimeMethodHandle originalHandle    = original.MethodHandle;
            RuntimeMethodHandle replacementHandle = replacement.MethodHandle;

            // Fetch their respective start
            IntPtr originalStart    = Helpers.GetMethodStart(originalHandle);
            IntPtr replacementStart = Helpers.GetMethodStart(replacementHandle);

            // Edge case: calling this on the same method
            if (originalStart == replacementStart)
            {
                throw new InvalidOperationException("Cannot redirect a method to itself.");
            }

            // Edge case: methods are too close to one another
            int difference = (int)Math.Abs(originalStart.ToInt64() - replacementStart.ToInt64());
            int sizeOfPtr  = Marshal.SizeOf(typeof(IntPtr));

            if ((sizeOfPtr == sizeof(long) && difference < 13) || (sizeOfPtr == sizeof(int) && difference < 7))
            {
                throw new InvalidOperationException("Unable to redirect methods whose bodies are too close to one another.");
            }

            // Make sure they're jitted
            if (!Helpers.HasBeenCompiled(originalStart))
            {
                RuntimeHelpers.PrepareMethod(originalHandle);

                originalStart = Helpers.GetMethodStart(originalHandle);
            }

            if (!Helpers.HasBeenCompiled(replacementStart))
            {
                RuntimeHelpers.PrepareMethod(replacementHandle);

                replacementStart = Helpers.GetMethodStart(replacementHandle);
            }

            // Copy local value to field
            originalMethodStart = originalStart;

            // In some cases, the memory might need to be readable / writable:
            // Make the memory region rw right away just in case.
            Helpers.AllowRW(originalStart);

            // Save bytes to change to redirect method
            byte[] replBytes = replacementBytes = Helpers.GetJmpBytes(replacementStart);
            byte[] origBytes = originalBytes = new byte[replBytes.Length];

            Marshal.Copy(originalStart, origBytes, 0, origBytes.Length);

            if (start)
            {
                CopyToStart(replBytes, originalStart);
                isRedirecting = true;
            }

            // Save methods in static array to make sure they're not garbage collected
            PersistingMethods.Add(original);
            PersistingMethods.Add(replacement);
        }
示例#16
0
        public static unsafe bool HookMethod(MethodBase victim, MethodBase dest, out Action unhook)
        {
            var destAddr = GetMethodAddress(dest);

            unhook = null;

            //var genericArguments = new Type[0];

            //if (victim.DeclaringType.GetGenericArguments() != null)
            //{
            //    genericArguments = victim.DeclaringType.GetGenericArguments().ToArray();
            //}

            //if (victim.GetGenericArguments() != null)
            //{
            //    genericArguments = genericArguments.Concat(victim.GetGenericArguments()).ToArray();
            //}

            RuntimeHelpers.PrepareMethod(victim.MethodHandle);
            //RuntimeHelpers.PrepareMethod(victim.MethodHandle, victim.DeclaringType.GetGenericArguments().Concat(victim.GetGenericArguments()).Select(type => type.TypeHandle).ToArray());
            var victimAddr = GetMethodAddress(victim);

            bool canMakeRelJmp;
            int  dist = 0;

            if (IntPtr.Size == 4)
            {
                canMakeRelJmp = true;
                dist          = destAddr.ToInt32() - victimAddr.ToInt32() - 5;
            }
            else
            {
                var dist64 = destAddr.ToInt64() - victimAddr.ToInt64() - 5;
                canMakeRelJmp = dist64 >= int.MinValue && dist64 <= int.MaxValue;
                if (canMakeRelJmp)
                {
                    dist = (int)dist64;
                }
            }
            if (canMakeRelJmp)
            {
                // Make relative jump
                var bytes    = BitConverter.GetBytes(dist);
                var hookCode = new byte[]
                {
                    0xE9, bytes[0], bytes[1], bytes[2], bytes[3],     // jmp dest
                    0x00,
                    0x00,
                    0x00,
                };
                long x = BitConverter.ToInt64(hookCode, 0);

                long oldCode;
                if (!PlantRelJmpHook(victimAddr, x, out oldCode))
                {
                    return(false);
                }

                unhook = () =>
                {
                    long tmp;
                    PlantRelJmpHook(victimAddr, oldCode, out tmp);
                };

                return(true);
            }
            else
            {
                // todo: set unhook delegate
                if (compareExchange2Words == null)
                {
                    return(false);
                }
                // Make absolute jump
                UIntPtr lo, hi;
                if (IntPtr.Size == 8)
                {
                    // x64
                    var bytes    = BitConverter.GetBytes(destAddr.ToInt64());
                    var hookCode = new byte[16]
                    {
                        0x48, 0xB8, bytes[0], bytes[1], bytes[2], bytes[3],
                        bytes[4], bytes[5], bytes[6], bytes[7], // movabs rax, hookMethod
                        0xFF, 0xE0,                             // jmp rax
                        0x90,                                   // nop
                        0x90,                                   // nop
                        0x90,                                   // nop
                        0x90                                    // nop
                    };
                    lo = new UIntPtr(BitConverter.ToUInt64(hookCode, 0));
                    hi = new UIntPtr(BitConverter.ToUInt64(hookCode, 8));
                }
                else
                {
                    // x86
                    var bytes    = BitConverter.GetBytes(destAddr.ToInt32());
                    var hookCode = new byte[8]
                    {
                        0xB8, bytes[0], bytes[1], bytes[2], bytes[3], // mov eax, hookMethod
                        0xFF, 0xE0,                                   // jmp eax
                        0x90                                          // nop
                    };
                    lo = new UIntPtr(BitConverter.ToUInt32(hookCode, 0));
                    hi = new UIntPtr(BitConverter.ToUInt32(hookCode, 4));
                }

                MEMORY_PROTECTION_CONSTANTS oldProtect;
                if (!VirtualProtect(victimAddr, (uint)(IntPtr.Size * 2), MEMORY_PROTECTION_CONSTANTS.PAGE_EXECUTE_READWRITE, &oldProtect))
                {
                    return(false);
                }

                compareExchange2Words(victimAddr, lo, hi);

                VirtualProtect(victimAddr, (uint)(IntPtr.Size * 2), oldProtect, &oldProtect);

                return(true);
            }
        }
示例#17
0
文件: Program.cs 项目: meee1/satgen2
        private static void DoPatch()
        {
            Harmony.DEBUG = true;
            var harmony = new Harmony("com.company.project.product");

            //Task.Run(() =>

            {
                //while(true)
                {
                    var original = typeof(Racelogic.Gnss.SatGen.Simulation).GetMethod("CheckFeature",
                                                                                      BindingFlags.NonPublic | BindingFlags.Static);
                    Console.WriteLine(original);
                    var prefix =
                        typeof(Program).GetMethod("CheckFeature_pre", BindingFlags.Static | BindingFlags.NonPublic);
                    Console.WriteLine(prefix);
                    var postfix =
                        typeof(Program).GetMethod("CheckFeature_post", BindingFlags.Static | BindingFlags.NonPublic);
                    Console.WriteLine(postfix);

                    //RuntimeHelpers.PrepareMethod(original.MethodHandle);



                    //harmony.Patch(original, new HarmonyMethod(prefix));

                    install(original,
                            typeof(Program).GetMethod("CheckFeature_orig", BindingFlags.Static | BindingFlags.NonPublic));

                    // Thread.Sleep(5000);
                }
            } //);

            {
                //Environment.NewLine

                var original = typeof(System.Environment).GetMethod("get_NewLine",
                                                                    BindingFlags.Public | BindingFlags.Static);
                Console.WriteLine(original);

                var postfix =
                    typeof(Program).GetMethod("newline", BindingFlags.Static | BindingFlags.NonPublic);
                Console.WriteLine(postfix);

                harmony.Patch(original, new HarmonyMethod(postfix));
            }

            {
                //Racelogic.Utilities.WinFileIO
                //public void OpenForWriting(string fileName)

                var original = typeof(Racelogic.Utilities.WinFileIO).GetMethod("OpenForWriting",
                                                                               BindingFlags.Public | BindingFlags.Instance);
                Console.WriteLine(original);

                var prefix =
                    typeof(Program).GetMethod("OpenForWriting", BindingFlags.Static | BindingFlags.NonPublic);
                Console.WriteLine(prefix);

                //harmony.Patch(original, new HarmonyMethod(prefix));

                install(original, prefix);
            }

            {
                //public bool Close()

                var original = typeof(Racelogic.Utilities.WinFileIO).GetMethod("Close",
                                                                               BindingFlags.Public | BindingFlags.Instance);
                Console.WriteLine(original);

                var prefix =
                    typeof(Program).GetMethod("Close", BindingFlags.Static | BindingFlags.NonPublic);
                Console.WriteLine(prefix);

                RuntimeHelpers.PrepareMethod(original.MethodHandle);

                harmony.Patch(original, new HarmonyMethod(prefix));
            }

            {
                //public int WriteBlocks(IntPtr bufferPointer, int numBytesToWrite)

                var original = typeof(Racelogic.Utilities.WinFileIO).GetMethods().Where(a => a.Name == "WriteBlocks")
                               .Last();
                Console.WriteLine(original);

                var prefix =
                    typeof(Program).GetMethod("WriteBlocks", BindingFlags.Static | BindingFlags.NonPublic);
                Console.WriteLine(prefix);

                RuntimeHelpers.PrepareMethod(original.MethodHandle);

                harmony.Patch(original, new HarmonyMethod(prefix));
            }

            Console.WriteLine();

            harmony.PatchAll();

            var methods = harmony.GetPatchedMethods();

            foreach (var method in methods)
            {
                //...
                Console.WriteLine("Patched {0}", method.ToString());
                MethodBody mb = method.GetMethodBody();
                Console.WriteLine("\r\nMethod: {0}", method);

                var il = mb.GetILAsByteArray();

                var ans = VRCheat.IL.ILParser.Parse(method);

                try
                {
                    foreach (var item in ans)
                    {
                        Console.WriteLine(item);
                    }
                }
                catch
                {
                }

                //var rd = new ReflectionDisassembler(new PlainTextOutput(), CancellationToken.None);

                //rd.DisassembleMethod(new PEFile(,), method.MethodHandle);
            }
        }
示例#18
0
 public void Prepare()
 {
     RuntimeHelpers.PrepareMethod(MethodInfo.MethodHandle);
 }
        OnAssemblyLoad(
            object Sender,
            AssemblyLoadEventArgs Args
            )
        {
            //
            // STEP1: Wait for Microsoft.PowerShell.Commands.Utility (MPCU)
            //
            string assemblyName = Args.LoadedAssembly.GetName().Name;

            Console.WriteLine("[*] Loading assembly " + assemblyName);
            if (assemblyName != "Microsoft.PowerShell.Commands.Utility")
            {
                return;
            }

            AppDomain.CurrentDomain.AssemblyLoad -= s_EventHandler;
            Assembly mpcuAssembly = Args.LoadedAssembly;

            //
            // You may want to break into a debugger for debugging.
            //
            //Debugger.Launch();

            //
            // STEP2: Find methods via reflection
            //
            const BindingFlags anyType = BindingFlags.Static |
                                         BindingFlags.Instance |
                                         BindingFlags.Public |
                                         BindingFlags.NonPublic;

            var targetMethodType     = Type.EmptyTypes;
            var handlerMethodType    = new Type[] { typeof(HookProcessRecord), };
            var trampolineMethodType = Type.EmptyTypes;

            Type targetMethodClass = mpcuAssembly.GetType(
                "Microsoft.PowerShell.Commands.InvokeExpressionCommand");
            Type handlerMethodClass    = typeof(HookProcessRecord);
            Type trampolineMethodClass = typeof(HookProcessRecord);

            MethodInfo target = targetMethodClass.GetMethod(
                "ProcessRecord",
                anyType,
                null,
                targetMethodType,
                null);
            MethodInfo hookHandler = handlerMethodClass.GetMethod(
                "ProcessRecordHookHandler",
                anyType,
                null,
                handlerMethodType,
                null);
            MethodInfo trampoline = trampolineMethodClass.GetMethod(
                "ProcessRecordTrampoline",
                anyType,
                null,
                trampolineMethodType,
                null);

            //
            // STEP4: Get addresses of native code of the methods
            //
            RuntimeHelpers.PrepareMethod(target.MethodHandle);
            RuntimeHelpers.PrepareMethod(hookHandler.MethodHandle);
            RuntimeHelpers.PrepareMethod(trampoline.MethodHandle);

            IntPtr targetAddr      = target.MethodHandle.GetFunctionPointer();
            IntPtr hookHandlerAddr = hookHandler.MethodHandle.GetFunctionPointer();
            IntPtr trampolineAddr  = trampoline.MethodHandle.GetFunctionPointer();

            //
            // STEP5: Install a hook on to the target method
            //
            if (!MinHook.InstallHook(targetAddr, hookHandlerAddr, trampolineAddr))
            {
                return;
            }

            //
            // STEP6: PROFIT!
            //
            Console.WriteLine("[*] The ProcessRecord method has been hooked.");
        }
示例#20
0
        public static unsafe void Replace(MethodInfo methodToReplace, MethodInfo methodToInject)
        {
            var isInjectedMethodDynamic = methodToInject is DynamicMethod;

            RuntimeHelpers.PrepareMethod(methodToReplace.MethodHandle);
            if (!isInjectedMethodDynamic)
            {
                RuntimeHelpers.PrepareMethod(methodToInject.MethodHandle);
            }
            else
            {
                var dynamicMethodHandle = GetDynamicHandle(methodToInject as DynamicMethod);
                RuntimeHelpers.PrepareMethod(dynamicMethodHandle);
            }

            unsafe
            {
                if (IntPtr.Size == 4)
                {
                    int *inj = (int *)methodToInject.MethodHandle.Value.ToPointer() + 2;
                    int *tar = (int *)methodToReplace.MethodHandle.Value.ToPointer() + 2;
#if DEBUG
                    Console.WriteLine("\nVersion x86 Debug\n");

                    byte *injInst = (byte *)*inj;
                    byte *tarInst = (byte *)*tar;

                    int *injSrc = (int *)(injInst + 1);
                    int *tarSrc = (int *)(tarInst + 1);

                    *tarSrc = (((int)injInst + 5) + *injSrc) - ((int)tarInst + 5);
#else
                    Console.WriteLine("\nVersion x86 Release\n");
                    *tar = *inj;
#endif
                }
                else
                {
                    long *inj = isInjectedMethodDynamic
                        ? (long *)GetDynamicHandle(methodToInject as DynamicMethod).Value.ToPointer() + 1
                        : (long *)methodToInject.MethodHandle.Value.ToPointer() + 1;
                    long *tar = (long *)methodToReplace.MethodHandle.Value.ToPointer() + 1;
#if DEBUG
                    Console.WriteLine("\nVersion x64 Debug\n");
                    //byte* injInst = (byte*)*inj;
                    //byte* tarInst = (byte*)*tar;
                    byte *injInst = isInjectedMethodDynamic
                        ? (byte *)GetDynamicHandle(methodToInject as DynamicMethod).GetFunctionPointer()
                        : (byte *)methodToInject.MethodHandle.GetFunctionPointer();
                    byte *tarInst = (byte *)methodToReplace.MethodHandle.GetFunctionPointer();

                    long *injSrc = (long *)(injInst + 1);
                    long *tarSrc = (long *)(tarInst + 1);

                    *tarSrc = (((long)injInst + 5) + *injSrc) - ((long)tarInst + 5);
#else
                    Console.WriteLine("\nVersion x64 Release\n");
                    *tar = *inj;
#endif
                }
            }
        }
    public void ctor(Menu.Menu menu, MenuObject owner)
    {
        //Delegate to call the base constructor
        Type[] constructorSignature = new Type[3];
        constructorSignature[0] = typeof(Menu.Menu);
        constructorSignature[1] = typeof(MenuObject);
        constructorSignature[2] = typeof(Vector2);
        RuntimeMethodHandle handle = typeof(Menu.PositionedMenuObject).GetConstructor(constructorSignature).MethodHandle;

        RuntimeHelpers.PrepareMethod(handle);
        IntPtr ptr = handle.GetFunctionPointer();
        Action <Menu.Menu, MenuObject, Vector2> funct = (Action <Menu.Menu, MenuObject, Vector2>)Activator.CreateInstance(typeof(Action <Menu.Menu, MenuObject, Vector2>), this, ptr);

        funct(menu, owner, new Vector2(440f, 385f));//RectangularMenuObject Constructor

        this.scoreControllers = new List <SandboxSettingsInterface.ScoreController>();
        IntVector2 intVector = new IntVector2(0, 0);

        //Replaced Code
        foreach (patch_MultiplayerUnlocks.SandboxUnlockID creature in patch_MultiplayerUnlocks.CreatureUnlockList)
        {
            if (creature != patch_MultiplayerUnlocks.SandboxUnlockID.Fly &&
                creature != patch_MultiplayerUnlocks.SandboxUnlockID.Leech &&
                creature != patch_MultiplayerUnlocks.SandboxUnlockID.SeaLeech &&
                creature != patch_MultiplayerUnlocks.SandboxUnlockID.SmallNeedleWorm &&
                creature != patch_MultiplayerUnlocks.SandboxUnlockID.Spider &&
                creature != patch_MultiplayerUnlocks.SandboxUnlockID.VultureGrub &&
                creature != patch_MultiplayerUnlocks.SandboxUnlockID.BigEel &&
                creature != patch_MultiplayerUnlocks.SandboxUnlockID.Deer &&
                creature != patch_MultiplayerUnlocks.SandboxUnlockID.WalkerBeast &&
                creature != patch_MultiplayerUnlocks.SandboxUnlockID.SmallCentipede &&
                creature != patch_MultiplayerUnlocks.SandboxUnlockID.TubeWorm &&
                creature != patch_MultiplayerUnlocks.SandboxUnlockID.Hazer)
            {
                this.AddScoreButton((MultiplayerUnlocks.SandboxUnlockID)creature, ref intVector);
            }
        }
        //-=-=-=-=-=-=-=-=-=-=-
        //for (int j = 0; j < 1; j++)
        //{
        //    this.AddScoreButton(null, ref intVector);
        //}
        this.AddScoreButton(new SandboxSettingsInterface.MiscScore(menu, this, menu.Translate("Food"), "FOODSCORE"), ref intVector);
        this.AddScoreButton(new SandboxSettingsInterface.MiscScore(menu, this, menu.Translate("Survive"), "SURVIVESCORE"), ref intVector);
        this.AddScoreButton(new SandboxSettingsInterface.MiscScore(menu, this, menu.Translate("Spear hit"), "SPEARHITSCORE"), ref intVector);
        if (menu.CurrLang != InGameTranslator.LanguageID.English)
        {
            for (int k = 1; k < 4; k++)
            {
                SandboxSettingsInterface.ScoreController scoreController = this.scoreControllers[this.scoreControllers.Count - k];
                scoreController.pos.x = scoreController.pos.x + 24f;
            }
        }
        this.subObjects.Add(new SymbolButton(menu, this, "Menu_Symbol_Clear_All", "CLEARSCORES", new Vector2(0f, -280f)));
        for (int l = 0; l < this.subObjects.Count; l++)
        {
            if (this.subObjects[l] is SandboxSettingsInterface.ScoreController)
            {
                (this.subObjects[l] as SandboxSettingsInterface.ScoreController).scoreDragger.UpdateScoreText();
            }
        }
    }
示例#22
0
        private void DisassembleAndWriteSimpleMethod(JitWriteContext context, MethodBase method)
        {
            var handle = method.MethodHandle;

            RuntimeHelpers.PrepareMethod(handle);

            var clrMethod = context.Runtime.GetMethodByHandle((ulong)handle.Value.ToInt64());
            var regions   = FindNonEmptyHotColdInfo(clrMethod);

            if (clrMethod == null || regions == null)
            {
                context.Runtime.Flush();
                clrMethod = context.Runtime.GetMethodByHandle((ulong)handle.Value.ToInt64());
                regions   = FindNonEmptyHotColdInfo(clrMethod);
            }

            if (clrMethod == null || regions == null)
            {
                var address = (ulong)handle.GetFunctionPointer().ToInt64();
                clrMethod = context.Runtime.GetMethodByAddress(address);
                regions   = FindNonEmptyHotColdInfo(clrMethod);
            }

            var writer = context.Writer;

            if (clrMethod != null)
            {
                writer.WriteLine();
                writer.WriteLine(clrMethod.GetFullSignature());
            }
            else
            {
                WriteSignatureFromReflection(context, method);
            }

            if (regions == null)
            {
                if (method.IsGenericMethod || (method.DeclaringType?.IsGenericType ?? false))
                {
                    writer.WriteLine("    ; Failed to find HotColdInfo for generic method (reference types?).");
                    return;
                }
                writer.WriteLine("    ; Failed to find HotColdRegions.");
                return;
            }

            var methodAddress = regions.HotStart;
            var methodLength  = regions.HotSize;

            var reader  = new MemoryCodeReader(new IntPtr(unchecked ((long)methodAddress)), methodLength);
            var decoder = Decoder.Create(MapArchitectureToBitness(context.Runtime.DataTarget.Architecture), reader);

            var instructions = new InstructionList();

            decoder.IP = methodAddress;
            while (decoder.IP < (methodAddress + methodLength))
            {
                decoder.Decode(out instructions.AllocUninitializedElement());
            }

            var resolver  = new JitAsmSymbolResolver(context.Runtime, methodAddress, methodLength);
            var formatter = new IntelFormatter(FormatterOptions, resolver);
            var output    = new StringOutput();

            foreach (ref var instruction in instructions)
            {
                formatter.Format(instruction, output);

                writer.Write("    L");
                writer.Write((instruction.IP - methodAddress).ToString("x4"));
                writer.Write(": ");
                writer.WriteLine(output.ToStringAndReset());
            }
        }
示例#23
0
 static internal void Prepare(this MethodBase method)
 {
     RuntimeHelpers.PrepareMethod(method.MethodHandle());
 }
示例#24
0
        public void Update(bool eu)
        {
            if ((this.abstractPhysicalObject as patch_AbstractPhysicalObject).networkObject)
            {
                if (this.lungsExhausted)
                {
                    this.aerobicLevel = 1f;
                }
                else
                {
                    this.aerobicLevel = Mathf.Max(1f - this.airInLungs, this.aerobicLevel - ((!this.slugcatStats.malnourished) ? 1f : 1.2f) / (((this.input[0].x != 0 || this.input[0].y != 0) ? 1100f : 400f) * (1f + 3f * Mathf.InverseLerp(0.9f, 1f, this.aerobicLevel))));
                }
                if (this.cantBeGrabbedCounter > 0)
                {
                    this.cantBeGrabbedCounter--;
                }
                if (this.poleSkipPenalty > 0)
                {
                    this.poleSkipPenalty--;
                }
                if (this.shootUpCounter > 0)
                {
                    this.noGrabCounter = Math.Max(this.noGrabCounter, 2);
                    this.shootUpCounter--;
                    if (!this.input[0].jmp || this.input[0].y < 1 || base.mainBodyChunk.pos.y < base.mainBodyChunk.lastPos.y)
                    {
                        this.shootUpCounter = 0;
                    }
                }

                if (this.bodyMode == Player.BodyModeIndex.ZeroG)
                {
                    this.privSneak = 0.5f;
                    base.bodyChunks[0].loudness = 0.5f * this.slugcatStats.loudnessFac;
                    base.bodyChunks[1].loudness = 0.5f * this.slugcatStats.loudnessFac;
                }
                else
                {
                    if ((!this.standing || this.bodyMode == Player.BodyModeIndex.Crawl || this.bodyMode == Player.BodyModeIndex.CorridorClimb || this.bodyMode == Player.BodyModeIndex.ClimbIntoShortCut || (this.animation == Player.AnimationIndex.HangFromBeam && this.input[0].x == 0) || (this.animation == Player.AnimationIndex.ClimbOnBeam && this.input[0].y == 0)) && this.bodyMode != Player.BodyModeIndex.Default)
                    {
                        this.privSneak = Mathf.Min(this.privSneak + 0.1f, 1f);
                    }
                    else
                    {
                        this.privSneak = Mathf.Max(this.privSneak - 0.04f, 0f);
                    }
                    base.bodyChunks[0].loudness = 1.5f * (1f - this.Sneak) * this.slugcatStats.loudnessFac;
                    base.bodyChunks[1].loudness = 0.7f * (1f - this.Sneak) * this.slugcatStats.loudnessFac;
                }
                SoundID soundID = SoundID.None;
                if (this.Adrenaline > 0.5f)
                {
                    soundID = SoundID.Mushroom_Trip_LOOP;
                }
                else if (base.Stunned)
                {
                    soundID = SoundID.UI_Slugcat_Stunned_LOOP;
                }
                else if (this.corridorDrop || this.verticalCorridorSlideCounter > 0 || this.horizontalCorridorSlideCounter > 0)
                {
                    soundID = SoundID.Slugcat_Slide_In_Narrow_Corridor_LOOP;
                }
                else if (this.slideCounter > 0 && this.bodyMode == Player.BodyModeIndex.Stand)
                {
                    soundID = SoundID.Slugcat_Skid_On_Ground_LOOP;
                }
                else if (this.animation == Player.AnimationIndex.Roll)
                {
                    soundID = SoundID.Slugcat_Roll_LOOP;
                }
                else if (this.animation == Player.AnimationIndex.ClimbOnBeam && this.input[0].y < 0)
                {
                    soundID = SoundID.Slugcat_Slide_Down_Vertical_Beam_LOOP;
                }
                else if (this.animation == Player.AnimationIndex.BellySlide)
                {
                    soundID = SoundID.Slugcat_Belly_Slide_LOOP;
                }
                else if (this.bodyMode == Player.BodyModeIndex.WallClimb)
                {
                    soundID = SoundID.Slugcat_Wall_Slide_LOOP;
                }
                if (soundID != this.slideLoopSound)
                {
                    if (this.slideLoop != null)
                    {
                        this.slideLoop.alive = false;
                        this.slideLoop       = null;
                    }
                    this.slideLoopSound = soundID;
                    if (this.slideLoopSound != SoundID.None)
                    {
                        this.slideLoop = this.room.PlaySound(this.slideLoopSound, base.mainBodyChunk, true, 1f, 1f);
                        this.slideLoop.requireActiveUpkeep = true;
                    }
                }
                if (this.slideLoop != null)
                {
                    this.slideLoop.alive = true;
                    SoundID soundID2 = this.slideLoopSound;
                    switch (soundID2)
                    {
                    case SoundID.Slugcat_Slide_Down_Vertical_Beam_LOOP:
                        this.slideLoop.pitch  = Mathf.Lerp(0.7f, 1.3f, Mathf.Abs(base.mainBodyChunk.vel.y) / 4.9f);
                        this.slideLoop.volume = Mathf.Min(1f, Mathf.Abs(base.mainBodyChunk.vel.y) / 2.5f);
                        break;

                    default:
                        if (soundID2 != SoundID.Slugcat_Belly_Slide_LOOP)
                        {
                            if (soundID2 != SoundID.Slugcat_Roll_LOOP)
                            {
                                if (soundID2 != SoundID.Slugcat_Wall_Slide_LOOP)
                                {
                                    if (soundID2 != SoundID.Slugcat_Slide_In_Narrow_Corridor_LOOP)
                                    {
                                        if (soundID2 != SoundID.UI_Slugcat_Stunned_LOOP)
                                        {
                                            if (soundID2 == SoundID.Mushroom_Trip_LOOP)
                                            {
                                                this.slideLoop.pitch  = 1f;
                                                this.slideLoop.volume = Mathf.InverseLerp(0f, 0.3f, this.Adrenaline);
                                            }
                                        }
                                        else
                                        {
                                            this.slideLoop.pitch  = 0.5f + Mathf.InverseLerp(11f, (float)this.lastStun, (float)base.stun);
                                            this.slideLoop.volume = Mathf.Pow(Mathf.InverseLerp(8f, 27f, (float)base.stun), 0.7f);
                                        }
                                    }
                                    else
                                    {
                                        this.slideLoop.pitch = Mathf.Lerp(0.7f, 1.3f, base.mainBodyChunk.vel.magnitude / ((!this.corridorDrop) ? 12.5f : 25f));
                                        if (this.verticalCorridorSlideCounter > 0)
                                        {
                                            this.slideLoop.volume = 1f;
                                        }
                                        else
                                        {
                                            this.slideLoop.volume = Mathf.Min(1f, base.mainBodyChunk.vel.magnitude / 4f);
                                        }
                                    }
                                }
                                else
                                {
                                    this.slideLoop.pitch  = Mathf.Lerp(0.7f, 1.3f, Mathf.Abs(base.mainBodyChunk.pos.y - base.mainBodyChunk.lastPos.y) / 1.75f);
                                    this.slideLoop.volume = Mathf.Min(1f, Mathf.Abs(base.mainBodyChunk.vel.y) * 1.5f);
                                }
                            }
                            else
                            {
                                this.slideLoop.pitch  = Mathf.Lerp(0.85f, 1.15f, 0.5f + Custom.DirVec(base.mainBodyChunk.pos, base.bodyChunks[1].pos).y * 0.5f);
                                this.slideLoop.volume = 0.5f + Mathf.Abs(Custom.DirVec(base.mainBodyChunk.pos, base.bodyChunks[1].pos).x) * 0.5f;
                            }
                        }
                        else
                        {
                            this.slideLoop.pitch  = Mathf.Lerp(0.5f, 1.5f, Mathf.Abs(base.mainBodyChunk.vel.x) / 25.5f);
                            this.slideLoop.volume = Mathf.Min(1f, Mathf.Abs(base.mainBodyChunk.vel.x) / 10f);
                        }
                        break;

                    case SoundID.Slugcat_Skid_On_Ground_LOOP:
                        this.slideLoop.pitch  = Mathf.Lerp(0.7f, 1.3f, Mathf.Abs(base.mainBodyChunk.vel.x) / 9.5f);
                        this.slideLoop.volume = Mathf.Min(1f, Mathf.Abs(base.mainBodyChunk.vel.x) / 6f);
                        break;
                    }
                }

                if (this.dontGrabStuff > 0)
                {
                    this.dontGrabStuff--;
                }
                if (this.bodyMode == Player.BodyModeIndex.CorridorClimb)
                {
                    this.timeSinceInCorridorMode = 0;
                }
                else
                {
                    this.timeSinceInCorridorMode++;
                }


                if (base.stun == 12)
                {
                    this.room.PlaySound(SoundID.UI_Slugcat_Exit_Stun, base.mainBodyChunk);
                }
                bool flag = this.input[0].jmp && !this.input[1].jmp;
                if (flag)
                {
                    if (base.grasps[0] != null && base.grasps[0].grabbed is TubeWorm)
                    {
                        flag = (base.grasps[0].grabbed as TubeWorm).JumpButton(this);
                    }
                    else if (base.grasps[1] != null && base.grasps[1].grabbed is TubeWorm)
                    {
                        flag = (base.grasps[1].grabbed as TubeWorm).JumpButton(this);
                    }
                }
                if (this.canWallJump > 0)
                {
                    this.canWallJump--;
                }
                else if (this.canWallJump < 0)
                {
                    this.canWallJump++;
                }
                if (this.jumpChunkCounter > 0)
                {
                    this.jumpChunkCounter--;
                }
                else if (this.jumpChunkCounter < 0)
                {
                    this.jumpChunkCounter++;
                }
                if (this.noGrabCounter > 0)
                {
                    this.noGrabCounter--;
                }
                if (this.waterJumpDelay > 0)
                {
                    this.waterJumpDelay--;
                }
                if (this.forceFeetToHorizontalBeamTile > 0)
                {
                    this.forceFeetToHorizontalBeamTile--;
                }
                if (this.canJump > 0)
                {
                    this.canJump--;
                }
                if (this.slowMovementStun > 0)
                {
                    this.slowMovementStun--;
                }
                if (this.backwardsCounter > 0)
                {
                    this.backwardsCounter--;
                }
                if (this.landingDelay > 0)
                {
                    this.landingDelay--;
                }
                if (this.verticalCorridorSlideCounter > 0)
                {
                    this.verticalCorridorSlideCounter--;
                }
                if (this.horizontalCorridorSlideCounter > 0)
                {
                    this.horizontalCorridorSlideCounter--;
                }
                if (this.jumpStun > 0)
                {
                    this.jumpStun--;
                }
                else if (this.jumpStun < 0)
                {
                    this.jumpStun++;
                }

                if (this.input[0].downDiagonal != 0 && this.input[0].downDiagonal == this.input[1].downDiagonal)
                {
                    this.consistentDownDiagonal++;
                }
                else
                {
                    this.consistentDownDiagonal = 0;
                }
                if (base.dead)
                {
                    this.animation = Player.AnimationIndex.Dead;
                    this.bodyMode  = Player.BodyModeIndex.Dead;
                }
                else if (base.stun > 0)
                {
                    this.animation = Player.AnimationIndex.None;
                    this.bodyMode  = Player.BodyModeIndex.Stunned;
                }
                if (this.bodyMode != Player.BodyModeIndex.Swimming)
                {
                    if (base.bodyChunks[0].ContactPoint.x != 0 && this.input[0].x == base.bodyChunks[0].ContactPoint.x && base.bodyChunks[0].vel.y < 0f && this.bodyMode != Player.BodyModeIndex.CorridorClimb)
                    {
                        BodyChunk bodyChunk3 = base.bodyChunks[0];
                        bodyChunk3.vel.y = bodyChunk3.vel.y * Mathf.Clamp(1f - this.surfaceFriction * ((base.bodyChunks[0].pos.y <= base.bodyChunks[1].pos.y) ? 0.5f : 2f), 0f, 1f);
                    }
                    if (base.bodyChunks[1].ContactPoint.x != 0 && this.input[0].x == base.bodyChunks[1].ContactPoint.x && base.bodyChunks[1].vel.y < 0f && this.bodyMode != Player.BodyModeIndex.CorridorClimb)
                    {
                        BodyChunk bodyChunk4 = base.bodyChunks[1];
                        bodyChunk4.vel.y = bodyChunk4.vel.y * Mathf.Clamp(1f - this.surfaceFriction * ((base.bodyChunks[0].pos.y <= base.bodyChunks[1].pos.y) ? 0.5f : 2f), 0f, 1f);
                    }
                }

                //Created Delegate to call base Update(eu)
                RuntimeMethodHandle handle = typeof(Creature).GetMethod("Update").MethodHandle;
                RuntimeHelpers.PrepareMethod(handle);
                IntPtr        ptr   = handle.GetFunctionPointer();
                Action <bool> funct = (Action <bool>)Activator.CreateInstance(typeof(Action <bool>), this, ptr);
                funct(eu);//Creature.Update(eu)

                if (base.stun < 1 && !base.dead && this.enteringShortCut == null && !base.inShortcut)
                {
                    this.MovementUpdate(eu);
                }

                bool flag2 = false;
                if (this.input[0].jmp && !this.input[1].jmp && !this.lastWiggleJump)
                {
                    this.wiggle        += 0.025f;
                    this.lastWiggleJump = true;
                }
                IntVector2 intVector = this.wiggleDirectionCounters;
                if (this.input[0].x != 0 && this.input[0].x != this.input[1].x && this.input[0].x != this.lastWiggleDir.x)
                {
                    flag2 = true;
                    if (intVector.y > 0)
                    {
                        this.wiggle += 0.0333333351f;
                        this.wiggleDirectionCounters.y = this.wiggleDirectionCounters.y - 1;
                    }
                    this.lastWiggleDir.x = this.input[0].x;
                    this.lastWiggleJump  = false;
                    if (this.wiggleDirectionCounters.x < 5)
                    {
                        this.wiggleDirectionCounters.x = this.wiggleDirectionCounters.x + 1;
                    }
                }
                if (this.input[0].y != 0 && this.input[0].y != this.input[1].y && this.input[0].y != this.lastWiggleDir.y)
                {
                    flag2 = true;
                    if (intVector.x > 0)
                    {
                        this.wiggle += 0.0333333351f;
                        this.wiggleDirectionCounters.x = this.wiggleDirectionCounters.x - 1;
                    }
                    this.lastWiggleDir.y = this.input[0].y;
                    this.lastWiggleJump  = false;
                    if (this.wiggleDirectionCounters.y < 5)
                    {
                        this.wiggleDirectionCounters.y = this.wiggleDirectionCounters.y + 1;
                    }
                }
                if (flag2)
                {
                    this.noWiggleCounter = 0;
                }
                else
                {
                    this.noWiggleCounter++;
                }
                this.wiggle -= Custom.LerpMap((float)this.noWiggleCounter, 5f, 35f, 0f, 0.0333333351f);
                if (this.noWiggleCounter > 20)
                {
                    if (this.wiggleDirectionCounters.x > 0)
                    {
                        this.wiggleDirectionCounters.x = this.wiggleDirectionCounters.x - 1;
                    }
                    if (this.wiggleDirectionCounters.y > 0)
                    {
                        this.wiggleDirectionCounters.y = this.wiggleDirectionCounters.y - 1;
                    }
                }
                this.wiggle = Mathf.Clamp(this.wiggle, 0f, 1f);

                if (networkLife > 0)
                {
                    networkLife--;
                }
                else
                {
                    this.RemoveFromRoom();
                    this.Abstractize();
                    this.abstractPhysicalObject.Destroy();
                    this.Destroy();
                }
            }
            else
            {
                orig_Update(eu);
            }
        }
示例#25
0
        /// <summary>
        /// 确保函数在JIT机制内,被编译为本地代码
        /// </summary>
        /// <param name="method"></param>
        public static void JIT(MethodBase method)
        {
            var typeHandles = method.DeclaringType.GetGenericArguments().Select(t => t.TypeHandle).ToArray();

            RuntimeHelpers.PrepareMethod(method.MethodHandle, typeHandles);
        }
示例#26
0
 protected virtual void PrepareMethod(MethodBase method, RuntimeMethodHandle handle)
     => RuntimeHelpers.PrepareMethod(handle);
示例#27
0
            public static void ReplaceMethod(MethodInfo source, MethodInfo destination)
            {
                if (source == destination)
                {
                    return;
                }

                RuntimeHelpers.PrepareMethod(source.MethodHandle);
                RuntimeHelpers.PrepareMethod(destination.MethodHandle);

                // Only 64 bit

                if (source.IsVirtual)
                {
                    unsafe
                    {
                        var methodDesc = (ulong *)source.MethodHandle.Value.ToPointer();
                        int index      = (int)(((*methodDesc) >> 32) & 0xFF);
                        //if (IntPtr.Size == 4)
                        //{
                        //    var classStart = (uint*)source.DeclaringType.TypeHandle.Value.ToPointer();
                        //    classStart += 10;
                        //    classStart = (uint*)*classStart;
                        //    var tar = classStart + index;
                        //    var inj = (uint*)destination.MethodHandle.Value.ToPointer() + 2;
                        //    *tar = *inj;
                        //}
                        //else
                        //{
                        var classStart = (ulong *)source.DeclaringType.TypeHandle.Value.ToPointer();
                        classStart += 8;
                        classStart  = (ulong *)*classStart;
                        var tar = classStart + index;
                        var inj = (ulong *)destination.MethodHandle.Value.ToPointer() + 1;
                        *   tar = *inj;
                        //}
                    }
                    return;
                }

                unsafe
                {
                    //                    if (IntPtr.Size == 4)
                    //                    {
                    //                        var inj = (int*)destination.MethodHandle.Value.ToPointer() + 2;
                    //                        var tar = (int*)source.MethodHandle.Value.ToPointer() + 2;
                    //#if DEBUG
                    //                        var injInst = (byte*)*inj;
                    //                        var tarInst = (byte*)*tar;
                    //                        var injSrc = (int*)(injInst + 1);
                    //                        var tarSrc = (int*)(tarInst + 1);
                    //                        *tarSrc = ((int)injInst + 5) + *injSrc - ((int)tarInst + 5);
                    //#else
                    //                        *tar = *inj;
                    //#endif
                    //                    }
                    //                    else
                    //                    {
                    var inj = (long *)destination.MethodHandle.Value.ToPointer() + 1;
                    var tar = (long *)source.MethodHandle.Value.ToPointer() + 1;
                    *   tar = *inj;
                    //}
                }
            }
示例#28
0
 protected virtual void PrepareMethod(MethodBase method, RuntimeMethodHandle handle, RuntimeTypeHandle[] instantiation)
     => RuntimeHelpers.PrepareMethod(handle, instantiation);
示例#29
0
        public async Task <int> ExecuteCommand(CommandSettings command)
        {
            ArgUtil.NotNull(command, nameof(command));
            try
            {
                var agentWebProxy    = HostContext.GetService <IVstsAgentWebProxy>();
                var agentCertManager = HostContext.GetService <IAgentCertificateManager>();
                VssUtil.InitializeVssClientSettings(HostContext.UserAgent, agentWebProxy.WebProxy, agentCertManager.VssClientCertificateManager);

                _inConfigStage = true;
                _completedCommand.Reset();
                _term.CancelKeyPress += CtrlCHandler;

                //register a SIGTERM handler
                HostContext.Unloading += Agent_Unloading;

                // TODO Unit test to cover this logic
                Trace.Info(nameof(ExecuteCommand));
                var configManager = HostContext.GetService <IConfigurationManager>();

                // command is not required, if no command it just starts if configured

                // TODO: Invalid config prints usage

                if (command.IsHelp())
                {
                    PrintUsage(command);
                    return(Constants.Agent.ReturnCode.Success);
                }

                if (command.IsVersion())
                {
                    _term.WriteLine(BuildConstants.AgentPackage.Version);
                    return(Constants.Agent.ReturnCode.Success);
                }

                if (command.IsCommit())
                {
                    _term.WriteLine(BuildConstants.Source.CommitHash);
                    return(Constants.Agent.ReturnCode.Success);
                }

                if (command.IsDiagnostics())
                {
                    PrintBanner();
                    _term.WriteLine("Running Diagnostics Only...");
                    _term.WriteLine(string.Empty);
                    DiagnosticTests diagnostics = new DiagnosticTests(_term);
                    diagnostics.Execute();
                    return(Constants.Agent.ReturnCode.Success);
                }

                // Configure agent prompt for args if not supplied
                // Unattend configure mode will not prompt for args if not supplied and error on any missing or invalid value.
                if (command.IsConfigureCommand())
                {
                    PrintBanner();
                    try
                    {
                        await configManager.ConfigureAsync(command);

                        return(Constants.Agent.ReturnCode.Success);
                    }
                    catch (Exception ex)
                    {
                        Trace.Error(ex);
                        _term.WriteError(ex.Message);
                        return(Constants.Agent.ReturnCode.TerminatedError);
                    }
                }

                // remove config files, remove service, and exit
                if (command.IsRemoveCommand())
                {
                    try
                    {
                        await configManager.UnconfigureAsync(command);

                        return(Constants.Agent.ReturnCode.Success);
                    }
                    catch (Exception ex)
                    {
                        Trace.Error(ex);
                        _term.WriteError(ex.Message);
                        return(Constants.Agent.ReturnCode.TerminatedError);
                    }
                }

                _inConfigStage = false;

                // warmup agent process (JIT/CLR)
                // In scenarios where the agent is single use (used and then thrown away), the system provisioning the agent can call `agent.listener --warmup` before the machine is made available to the pool for use.
                // this will optimizes the agent process startup time.
                if (command.IsWarmupCommand())
                {
                    var binDir = HostContext.GetDirectory(WellKnownDirectory.Bin);
                    foreach (var assemblyFile in Directory.EnumerateFiles(binDir, "*.dll"))
                    {
                        try
                        {
                            Trace.Info($"Load assembly: {assemblyFile}.");
                            var assembly = Assembly.LoadFrom(assemblyFile);
                            var types    = assembly.GetTypes();
                            foreach (Type loadedType in types)
                            {
                                try
                                {
                                    Trace.Info($"Load methods: {loadedType.FullName}.");
                                    var methods = loadedType.GetMethods(BindingFlags.DeclaredOnly | BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.Instance | BindingFlags.Static);
                                    foreach (var method in methods)
                                    {
                                        if (!method.IsAbstract && !method.ContainsGenericParameters)
                                        {
                                            Trace.Verbose($"Prepare method: {method.Name}.");
                                            RuntimeHelpers.PrepareMethod(method.MethodHandle);
                                        }
                                    }
                                }
                                catch (Exception ex)
                                {
                                    Trace.Error(ex);
                                }
                            }
                        }
                        catch (Exception ex)
                        {
                            Trace.Error(ex);
                        }
                    }

                    return(Constants.Agent.ReturnCode.Success);
                }

                AgentSettings settings = configManager.LoadSettings();

                var  store = HostContext.GetService <IConfigurationStore>();
                bool configuredAsService = store.IsServiceConfigured();

                // Run agent
                //if (command.Run) // this line is current break machine provisioner.
                //{

                // Error if agent not configured.
                if (!configManager.IsConfigured())
                {
                    _term.WriteError(StringUtil.Loc("AgentIsNotConfigured"));
                    PrintUsage(command);
                    return(Constants.Agent.ReturnCode.TerminatedError);
                }

                Trace.Verbose($"Configured as service: '{configuredAsService}'");

                //Get the startup type of the agent i.e., autostartup, service, manual
                StartupType startType;
                var         startupTypeAsString = command.GetStartupType();
                if (string.IsNullOrEmpty(startupTypeAsString) && configuredAsService)
                {
                    // We need try our best to make the startup type accurate
                    // The problem is coming from agent autoupgrade, which result an old version service host binary but a newer version agent binary
                    // At that time the servicehost won't pass --startuptype to agent.listener while the agent is actually running as service.
                    // We will guess the startup type only when the agent is configured as service and the guess will based on whether STDOUT/STDERR/STDIN been redirect or not
                    Trace.Info($"Try determine agent startup type base on console redirects.");
                    startType = (Console.IsErrorRedirected && Console.IsInputRedirected && Console.IsOutputRedirected) ? StartupType.Service : StartupType.Manual;
                }
                else
                {
                    if (!Enum.TryParse(startupTypeAsString, true, out startType))
                    {
                        Trace.Info($"Could not parse the argument value '{startupTypeAsString}' for StartupType. Defaulting to {StartupType.Manual}");
                        startType = StartupType.Manual;
                    }
                }

                Trace.Info($"Set agent startup type - {startType}");
                HostContext.StartupType = startType;

                if (PlatformUtil.RunningOnWindows)
                {
                    if (store.IsAutoLogonConfigured())
                    {
                        if (HostContext.StartupType != StartupType.Service)
                        {
                            Trace.Info($"Autologon is configured on the machine, dumping all the autologon related registry settings");
                            var autoLogonRegManager = HostContext.GetService <IAutoLogonRegistryManager>();
                            autoLogonRegManager.DumpAutoLogonRegistrySettings();
                        }
                        else
                        {
                            Trace.Info($"Autologon is configured on the machine but current Agent.Listner.exe is launched from the windows service");
                        }
                    }
                }
                // Run the agent interactively or as service
                return(await RunAsync(settings, command.GetRunOnce()));
            }
            finally
            {
                _term.CancelKeyPress  -= CtrlCHandler;
                HostContext.Unloading -= Agent_Unloading;
                _completedCommand.Set();
            }
        }
示例#30
0
 public static MethodInfo Prepare(this MethodInfo method)
 {
     RuntimeHelpers.PrepareMethod(method.MethodHandle);
     return(method);
 }