private IntPtr Execute(IntPtr address, params IntPtr[] args) { IntPtr retValPtr = Is64Bit ? _memory.AllocateAndWrite((long)0) : _memory.AllocateAndWrite(0); byte[] code = Assemble(address, retValPtr, args); IntPtr alloc = _memory.AllocateAndWrite(code); IntPtr thread = Native.CreateRemoteThread(_handle, IntPtr.Zero, 0, alloc, IntPtr.Zero, 0, out _); if (thread == IntPtr.Zero) { throw new InjectorException("Failed to create a remote thread", new Win32Exception(Marshal.GetLastWin32Error())); } WaitResult result = Native.WaitForSingleObject(thread, -1); if (result == WaitResult.WAIT_FAILED) { throw new InjectorException("Failed to wait for a remote thread", new Win32Exception(Marshal.GetLastWin32Error())); } IntPtr ret = Is64Bit ? (IntPtr)_memory.ReadLong(retValPtr) : (IntPtr)_memory.ReadInt(retValPtr); if ((long)ret == 0x00000000C0000005) { throw new InjectorException($"An access violation occurred while executing {Exports.First(e => e.Value == address).Key}()"); } return(ret); }
/// <summary> /// Waits until given predicate returns true or fails after specified timeout /// </summary> /// <param name="condition">Predicate that return true, if its condition is successfuly fulfilled</param> /// <param name="timeout">Timeout</param> /// <param name="testInfo"> This label would be passed to logs if method fails</param> /// <param name="dontFail">If true, method will not generate exception after timeout (optional, default = false)</param> /// <param name="ignoreTimeScale">Should time scale be ignored or not (optional, default = false)</param> /// <exception cref="Exception"></exception> public static IEnumerator WaitFor(Func <WaitResult> condition, float timeout, bool dontFail = false, bool ignoreTimeScale = false) { float time = 0; while (true) { WaitResult waitResult = condition(); time += ignoreTimeScale ? Time.unscaledDeltaTime : Time.deltaTime; if (waitResult is WaitFailed && time > timeout) { if (dontFail) { yield break; } else { throw new Exception("Operation timed out: " + waitResult); } } if (waitResult is WaitSuccess) { yield break; } yield return(null); } }
private static PopupControlService EnsureInstance() { if (_instance != null) { return(_instance); } lock (Lock) { var dispatcher = DispatcherUtils.ApplicationDispatcher; if (dispatcher.CheckAccess()) { return(_instance = new PopupControlService()); } var waitResult = new WaitResult <PopupControlService>(); dispatcher.BeginInvoke(() => waitResult.Result = new PopupControlService()); _instance = waitResult.Result; } return(_instance); }
/// <summary> /// Blocks the execution of current thread until the slave reports back. /// </summary> /// <param name="intervalUsed">Amount of virtual time that passed from the perspective of a slave.</param> /// <returns> /// A structure containing two booleans: /// * IsDone: True if the slave completed all the work or false if the execution was interrupted (and it's blocking now). /// * IsUnblockedRecently: True if the handle has recently (i.e., since the last call to `WaitUntilDone`) been unblocked - it resumed the execution after reporting break. /// </returns> public WaitResult WaitUntilDone(out TimeInterval intervalUsed) { this.Trace(); lock (innerLock) { Debugging.DebugHelper.Assert(sourceSideInProgress, "About to wait until time is used, but it seems none has recently been granted."); innerLock.WaitWhile(() => sinkSideInProgress || (SinkSideActive && grantPending), "Waiting until time is used."); intervalUsed = enabled ? intervalToReport : intervalGranted; intervalToReport = TimeInterval.Empty; var isDone = !(enabled && isBlocking); if (enabled && !SinkSideActive && !reportPending) { Debugging.DebugHelper.Assert(!deferredUnlatch, "Unexpected state of deferredUnlatch"); // 'false' value of 'SinkSideActive' means that there is no point hanging and waiting in this function as there is no chance of unblocking in the nearest future // in such situation just return 'false' simulating blocked state // the only exception is if `reportPending` is set which means that we should first return value as set be the previous Report{Continue,Break} this.Trace("Forcing result to be false"); isDone = false; intervalUsed = TimeInterval.Empty; } Debugging.DebugHelper.Assert(reportedSoFar <= intervalUsed); // here we report the remaining part of granted time ReportProgress(intervalUsed - reportedSoFar); reportedSoFar = TimeInterval.Empty; reportPending = false; if (isDone) { sourceSideInProgress = false; } var result = new WaitResult(isDone, recentlyUnblocked); recentlyUnblocked = false; if (deferredUnlatch) { deferredUnlatch = false; Unlatch(); } Monitor.PulseAll(innerLock); this.Trace($"Reporting {intervalUsed.Ticks} ticks used. Local elapsed virtual time is {TotalElapsedTime.Ticks} ticks."); this.Trace(result.ToString()); return(result); } }
public async Task NoPrematureReturn() { MutexThread waiter = MutexThread.Begin(CancellationToken.None); var m = new Mutex(); try { await waiter.WaitAsync(m); WaitResult result = await Task.Run(() => Wait(m, 2)); Assert.False(result.Waited, "Other thread did not wait"); Assert.InRange(result.TimeTaken, _step, MultTime(_step, 10)); } finally { waiter.Release(m); } }
public async Task SignalReturns() { MutexThread waiter = MutexThread.Begin(CancellationToken.None); var m = new Mutex(); try { await waiter.WaitAsync(m); Task <WaitResult> childTask = Task.Run(() => Wait(m, 2)); waiter.Release(m); WaitResult result = await childTask; Assert.True(result.Waited, "Other thread should have waited"); Assert.InRange(result.TimeTaken, TimeSpan.Zero, _step); } finally { waiter.Release(m); } }
/// <summary> /// /// </summary> /// <param name="hObject"></param> /// <param name="dwMilliseconds"></param> /// <returns></returns> public static WaitResult WaitForSingleObject(IntPtr hObject, int dwMilliseconds, [CallerMemberName] string callerName = "") { if (!PInvokeDebugger.LoggingEnabled) { return(PInvoke_WaitForSingleObject(hObject, dwMilliseconds)); } WaitResult returnValue = PInvoke_WaitForSingleObject(hObject, dwMilliseconds); PInvokeDebugInfo debugInfo = PInvokeDebugInfo.TraceDebugInfo( ModuleName, nameof(WaitForSingleObject), callerName, returnValue, WaitResult.Failed, nameof(hObject), hObject, nameof(dwMilliseconds), dwMilliseconds ); PInvokeDebugger.SafeCapture(debugInfo); return(returnValue); }
public async Task <WaitResult> Wait(int msTimeout) { return(await Task.Factory.StartNew(() => { WaitResult res = 0; if (!_p.WaitForExit(msTimeout)) { res |= WaitResult.TimedOut; } if (!_noError) { res |= WaitResult.Failed; } if (res == 0) { return WaitResult.Ok; } return res; }).ConfigureAwait(false)); }