static ThreadContext GetContext(ConcurrentDictionary<int, ThreadContext> nodes) { return nodes.GetOrAdd(Thread.CurrentThread.ManagedThreadId, _ => { var tc = new ThreadContext(); tc.Root = tc.Clock = tc.Chain = tc.Focus = new Node(tc); return tc; }); }
public static void IDIV(ThreadContext ThreadContext) { var Numerator = ThreadContext.EDX_EAX; var Denominator = ThreadContext.ECX; ThreadContext.EAX = (uint)(Numerator / Denominator); ThreadContext.EDX = (uint)(Numerator % Denominator); }
async Task Start(ThreadContext<IGame> startupContext = null) { MessageBrokerFactory.Instance.Publish(new GameMessage("Starting game.")); if (!this.IsEnabled) { await this.Initialize(); } MessageBrokerFactory.Instance.Publish(new GameMessage("Configuring game configuration components.")); foreach (IAdapter adapter in this.configuredAdapters) { MessageBrokerFactory.Instance.Publish(new GameMessage($"Initializing {adapter.Name} component.")); await adapter.Start(this); MessageBrokerFactory.Instance.Publish(new GameMessage($"{adapter.Name} initialization completed.")); } this.IsRunning = true; MessageBrokerFactory.Instance.Publish(new GameMessage("Game started.")); if (startupContext != null) { startupContext.Invoke(this); return; } // Start the game loop. await Task.Run(() => { while (this.IsRunning) { Task.Delay(1).Wait(); } }); }
/// <summary> /// In the x86 assembly language, the TEST instruction performs a bitwise AND on two operands. /// The flags SF, ZF, PF, CF, OF and AF are modified while the result of the AND is discarded. /// There are 9 different opcodes for the TEST instruction depending on the type and size of the operands. /// It can compare 8-bit, 16-bit, 32-bit or 64-bit values. It can also compare registers, immediate values and register indirect values.[1] /// </summary> /// <param name="ThreadContext"></param> /// <param name="Left"></param> /// <param name="Right"></param> /// <see cref="http://en.wikipedia.org/wiki/TEST_(x86_instruction)"/> public static void TEST_DWORD(ThreadContext ThreadContext, int Left, int Right) { var Result = (Left & Right); ThreadContext.Flags.ZF = (Result == 0); // @TODO //SF, ZF, PF, CF, OF and AF //throw new NotImplementedException(); }
public static void StartThread(Action action) { Thread t = new Thread(new ThreadStart( () => { if (ThreadContext.activeContext == null) { ThreadContext c = new ThreadContext(Program.env); } action(); })); t.Start(); }
/// <summary> /// Dies from an unhandled exception. /// </summary> /// <param name="Exception"></param> public static void DieFromUnhandledException(ThreadContext TC, RakudoObject Exception) { // Try to stringify the exception object. try { var StrMeth = Exception.STable.FindMethod(TC, Exception, "Str", Hints.NO_HINT); var Stringified = StrMeth.STable.Invoke(TC, StrMeth, CaptureHelper.FormWith(new RakudoObject[] { Exception })); Console.WriteLine(Ops.unbox_str(TC, Stringified)); } catch { Console.Error.WriteLine("Died from an exception, and died trying to stringify it too."); } // Exit with an error code. Environment.Exit(1); }
private void CreateContexts() { ReminderWindow.ResetIsClosing(); Screen[] screens = Screen.AllScreens; foreach (var screen in screens) { var context = new ThreadContext { Thread = new Thread(RunWindow), IsReady = new ManualResetEvent(false), Screen = screen }; context.Thread.SetApartmentState(ApartmentState.STA); context.Thread.Start(context); _contexts.Add(context); } }
/* static public void CALL_INDEX(ThreadContext ThreadContext, int Index) { ThreadContext.NextFunction = ThreadContext.CpuContext.MethodCache[Index]; //ThreadContext.CpuContext.MethodCache[Index](ThreadContext); } static public void RETURN(ThreadContext ThreadContext) { ThreadContext.NextFunction = ThreadContext.CpuContext.MethodCache[Index]; //ThreadContext.CpuContext.MethodCache[Index](ThreadContext); } */ public static void INTERRUPT(ThreadContext ThreadContext, uint nPC, uint Code) { switch (Code) { case 1: var NativeMethod = ThreadContext.CpuContext.NativeMethodInfoList[ThreadContext.CpuContext.Memory.Read4(nPC)]; NativeMethod.Method(NativeMethod, ThreadContext); //Console.WriteLine(NativeMethod.); //Console.WriteLine("INTERRUPT: {0}", Code); //Console.ReadKey(); Environment.Exit(0); RETURN(ThreadContext); break; default: throw(new NotImplementedException("Interrupt : " + Code)); } //throw new NotImplementedException(); }
// // MUST NOT BE CALLED DIRECTLY // A protected method that does callback job and it is guaranteed to be called exactly once. // A derived overriding method must call the base class somewhere or the completion is lost. // protected virtual void Complete(IntPtr userToken) { bool offloaded = false; ThreadContext threadContext = CurrentThreadContext; try { ++threadContext.m_NestedIOCount; if (_asyncCallback != null) { GlobalLog.Print("LazyAsyncResult#" + Logging.HashString(this) + "::Complete() invoking callback"); if (threadContext.m_NestedIOCount >= c_ForceAsyncCount) { GlobalLog.Print("LazyAsyncResult::Complete *** OFFLOADED the user callback ***"); Task.Factory.StartNew( s => WorkerThreadComplete(s), null, CancellationToken.None, TaskCreationOptions.DenyChildAttach, TaskScheduler.Default); offloaded = true; } else { _asyncCallback(this); } } else { GlobalLog.Print("LazyAsyncResult#" + Logging.HashString(this) + "::Complete() no callback to invoke"); } } finally { --threadContext.m_NestedIOCount; // Never call this method unless interlocked m_IntCompleted check has succeeded (like in this case) if (!offloaded) { Cleanup(); } } }
private static void CleanerThread(ThreadContext tc) { while (!tc.IsToStop) { try { ZipXml("Live"); ZipXml("Virtual"); } catch (Exception e) { m_logger.Excp(e, e.Message); } Thread.Sleep(60000); } }
public override object Visit(MetaDataThreadEvent metaDataEvent) { TimeBase += metaDataEvent.TimeDiff; ThreadContext ctx; long threadId = currentBuffer.Header.PtrBase * metaDataEvent.Pointer; if (!threadDictionary.TryGetValue(threadId, out ctx)) { threadDictionary [threadId] = ctx = new ThreadContext() { ThreadId = threadId }; } ctx.Name = metaDataEvent.Name; return(null); }
static void Main(string[] args) { ThreadContext thread = new ThreadContext(); ThreadMonitor monitor = new ThreadMonitor(); thread.Register(monitor); thread.Start(); thread.Start(); thread.Sleep(); thread.Start(); thread.Abort(); thread.Start(); thread.Abort(); thread.Abort(); Console.ReadKey(); }
public ObservableCollection <Ita> LoadItas(Category category) { using (var db = new ThreadContext()) { var itas = from ita in db.Itas where ita.CategoryId == category.CategoryId select ita; var returnItas = new ObservableCollection <Ita>(); foreach (var ita in itas) { ita.Category = category; ita.CategoryId = category.CategoryId; returnItas.Add(ita); } return(returnItas); } }
private void ResumeTasks(bool waitUntilDone, bool onCallerThread) { #if DBG Debug.Trace("Async", "TaskManager.ResumeTasks: onCallerThread=" + onCallerThread + ", _tasksCompleted=" + _tasksCompleted + ", _tasksStarted=" + _tasksStarted); if (waitUntilDone) { // must be on caller thread to wait Debug.Assert(onCallerThread); } #endif // artifically increment the task count by one // to make sure _tasksCompleted doesn't become equal to _tasksStarted during this method Interlocked.Increment(ref _tasksStarted); try { if (onCallerThread) { ResumeTasksPossiblyUnderLock(waitUntilDone); } else { using (_app.Context.SyncContext.AcquireThreadLock()) { ThreadContext threadContext = null; try { threadContext = _app.OnThreadEnter(); ResumeTasksPossiblyUnderLock(waitUntilDone); } finally { if (threadContext != null) { threadContext.DisassociateFromCurrentThread(); } } } } } finally { // complete the bogus task introduced with incrementing _tasksStarted at the beginning TaskCompleted(onCallerThread); } }
private static void SetThreadHook(HookItem item, bool remove) { var ctx = new ThreadContext(); ctx.ContextFlags = 65559; foreach (IntPtr openThreadHandle in OpenThreadHandles) { SuspendThread(openThreadHandle); GetThreadContext(openThreadHandle, ref ctx); SetDebugRegisters(item.Register, item.Location, ref ctx, remove); item.Hooked = !remove; SetThreadContext(openThreadHandle, ref ctx); ResumeThread(openThreadHandle); } }
public RawInputDevice(HidDevice device, ReportDescriptor reportDescriptor, DeviceItem deviceItem, HidStream hidStream, string uniqueId) { this.device = device; inputReportBuffer = new byte[device.GetMaxInputReportLength()]; inputReceiver = reportDescriptor.CreateHidDeviceInputReceiver(); inputParser = deviceItem.CreateDeviceItemInputParser(); inputReceiver.Start(hidStream); DisplayName = device.GetProductName(); UniqueId = uniqueId; InterfacePath = device.DevicePath; HardwareID = IdHelper.GetHardwareId(InterfacePath); inputChangedEventArgs = new DeviceInputChangedEventArgs(this); sources = reportDescriptor.InputReports.SelectMany(ir => ir.DataItems) .SelectMany(di => di.Usages.GetAllValues()) .Select(u => (Usage)u) .SelectMany(u => RawInputSource.FromUsage(this, u)) .ToArray(); readThreadContext = ThreadCreator.CreateLoop($"{DisplayName} RawInput reader", ReadLoop, 1).Start(); }
public ScriptBot(string scriptPath) { this.scriptPath = scriptPath; var sp = scriptPath.Split('\\'); jsName = sp[sp.Length - 1]; threadContext = new ThreadContext(scriptPath); //threadContext.ctx.Debugging = true; threadContext.ctx.Debugging = Configurations.Debugging; threadContext.debuggerLength = Configurations.DebuggerLength; threadContext.ctx.DefineConstructor(typeof(Vector2)); threadContext.ctx.DefineVariable("log").Assign(JSValue.Marshal(new Action <string>(DebugMessage))); threadContext.ctx.DefineVariable("info"); scriptStr = File.OpenText(scriptPath).ReadToEnd(); var lineList = new List <int>(); lineList.Add(-1); for (int i = 0; i < scriptStr.Length; i++) { if (scriptStr[i] == '\n') { lineList.Add(i); } } linePositions = lineList.ToArray(); try { threadContext.TimedEval(scriptStr, 2000); } catch (Exception ex) { if (ex is JSException) { HandleJSError(ex as JSException); } else { HandleError(ex); } } }
public override void SetUp() { base.SetUp(); root = CreateOneItem <RegularPage>(1, "root", null); about = CreateOneItem <AboutUsSectionPage>(2, "about", root); executives = CreateOneItem <ExecutiveTeamPage>(3, "executives", about); search = CreateOneItem <SearchPage>(4, "search", root); var typeFinder = new FakeTypeFinder2(); typeFinder.typeMap[typeof(ContentItem)] = this.NearbyTypes() .BelowNamespace("N2.Extensions.Tests.Mvc.Models").AssignableTo <ContentItem>().Union(typeof(ContentItem)).ToArray(); typeFinder.typeMap[typeof(IController)] = this.NearbyTypes() .BelowNamespace("N2.Extensions.Tests.Mvc.Controllers").AssignableTo <IController>().Except(typeof(AnotherRegularController)) .ToArray(); var changer = new StateChanger(); var definitions = new DefinitionManager(new[] { new DefinitionProvider(new DefinitionBuilder(new DefinitionMap(), typeFinder, new EngineSection())) }, new ITemplateProvider[0], new ContentActivator(changer, null, new EmptyProxyFactory()), changer); var webContext = new ThreadContext(); var host = new Host(webContext, root.ID, root.ID); var parser = new UrlParser(persister, webContext, host, new HostSection()); controllerMapper = new ControllerMapper(typeFinder, definitions); Url.DefaultExtension = ""; engine = mocks.DynamicMock <IEngine>(); SetupResult.For(engine.Resolve <ITypeFinder>()).Return(typeFinder); SetupResult.For(engine.Definitions).Return(definitions); SetupResult.For(engine.UrlParser).Return(parser); SetupResult.For(engine.Persister).Return(persister); var editUrlManager = new FakeEditUrlManager(); SetupResult.For(engine.ManagementPaths).Return(editUrlManager); engine.Replay(); route = new ContentRoute(engine, new MvcRouteHandler(), controllerMapper, null); httpContext = new FakeHttpContext(); routes = new RouteCollection { route }; }
private void CloseAccept(ThreadContext threadContext, Dictionary <int, TSocket> sockets) { var acceptSockets = threadContext.AcceptSockets; lock (sockets) { for (int i = 0; i < acceptSockets.Count; i++) { threadContext.RemoveSocket(acceptSockets[i].Fd); } } for (int i = 0; i < acceptSockets.Count; i++) { // close causes remove from epoll (CLOEXEC) acceptSockets[i].Socket.Dispose(); // will close (no concurrent users) } acceptSockets.Clear(); CompleteStateChange(State.AcceptClosed); }
public Task InvokeAsync(DispatcherPriority priority, Delegate callback, params object[] arguments) { if (Thread == Thread.CurrentThread) { callback.DynamicInvoke(arguments); return(Task.CompletedTask); } switch (Type) { case GuiContextType.None: { return(Task.Run(() => { callback.DynamicInvoke(arguments); })); } case GuiContextType.WPF: { return(GuiDispatcher.InvokeAsync(() => { callback.DynamicInvoke(arguments); }, priority).Task); } case GuiContextType.WinForms: { var doneEvent = WaitEventFactory.Create(isCompleted: false, useSlim: true); ThreadContext.Post((args) => { try { callback.DynamicInvoke(args as object[]); } catch { throw; } finally { doneEvent.Complete(); } }, arguments); return(Task.Run(() => { doneEvent.Wait(); doneEvent.Dispose(); })); } } return(Task.CompletedTask); }
public void Start() { if (!Running) { InputConfiguration.Sources.ForEach(s => { var source = FindSource(s.Offset); if (source != null) { source.Update(s); } }); readThreadContext = ThreadCreator.CreateLoop($"{DisplayName} RawInput reader", ReadLoop, 1).Start(); if (!InputConfiguration.Autostart) { InputConfiguration.Autostart = true; inputConfigManager.SaveConfig(this); } } }
private void Run(ThreadContext tc) { while (!tc.IsToStop) { var result = StationRepository.Refresh(); if (StationRepository.SyncInterval > 0) { _syncInterval = StationRepository.SyncInterval * 1000; } if (result) { Thread.Sleep(_syncInterval); } else { Thread.Sleep(3000); } } }
protected string GetClientClass(string className) { string clientClass = null; string mappingClassName = ORBConstants.CLIENT_MAPPING + className; IDictionary props = ThreadContext.getProperties(); if (props.Contains(mappingClassName)) { clientClass = (string)props[mappingClassName]; } if (clientClass == null) { return(Types.Types.getClientClassForServerType(className)); } else { return(clientClass); } }
/// <summary> /// 単一アプリケーション オブジェクトを初期化します。これは、実行される作成したコードの ///最初の行であるため、main() または WinMain() と論理的に等価です。 /// </summary> public App() { Microsoft.ApplicationInsights.WindowsAppInitializer.InitializeAsync( Microsoft.ApplicationInsights.WindowsCollectors.Metadata | Microsoft.ApplicationInsights.WindowsCollectors.Session); this.InitializeComponent(); this.Suspending += OnSuspending; using (var db = new ThreadContext()) { try { db.Database.Migrate(); } catch (Exception ex) { var message = ex.Message; } } }
private void DevicesServiceRefresh(ThreadContext tc) { while (!tc.IsToStop) { if (!StationRepository.CheckDevicesChange()) { StationRepository.Refresh(); } if (StationRepository.SyncInterval > 0) { _syncInterval = StationRepository.SyncInterval * 1000 * 3; Thread.Sleep(_syncInterval); } else { Thread.Sleep(3000); } } }
public static ThreadContext GetThreadContext(HttpContextBase httpcontext) { ThreadContext tc = new ThreadContext(); tc.Domain = httpcontext.Request.Url.Host; tc.Ip = GetClientIP(httpcontext); tc.UserAgent = httpcontext.Request.UserAgent; tc.Url = httpcontext.Request.Url; if (httpcontext.Session != null) { tc.SessionID = httpcontext.Session.SessionID; } if (httpcontext.Request.UrlReferrer != null) { tc.Referrer = httpcontext.Request.UrlReferrer.ToString(); } return(tc); }
private void RunRegistrationFormRefresh(ThreadContext tc) { while (!tc.IsToStop) { var result = StationRepository.GetRegistrationForm(); if (StationRepository.SyncInterval > 0) { _syncInterval = StationRepository.SyncInterval * 1000 * 3; } if (result != null) { Thread.Sleep(_syncInterval); } else { Thread.Sleep(3000); } } }
public AckMessage(string correlationId, object clientId, object obj, IDictionary headers) { this.correlationId = correlationId; this.clientId = clientId == null?Guid.NewGuid().ToString().ToUpper() : clientId; this.messageId = Guid.NewGuid().ToString().ToUpper(); // "12DB8FBF-1700-DC12-C88A-B0BA6C88C7ED"; if (headers != null) { this.headers = headers; } else { #if (FULL_BUILD) Hashtable responseMetadata = null; if (ThreadContext.getProperties().Contains(ORBConstants.RESPONSE_METADATA)) { responseMetadata = (Hashtable)ThreadContext.getProperties()[ORBConstants.RESPONSE_METADATA]; } if (responseMetadata != null) { this.headers = responseMetadata; } else { this.headers = new Hashtable(); } #else this.headers = new Dictionary <object, object>(); #endif } DateTime startTime = new DateTime(1970, 1, 1); long t = DateTime.Now.Ticks - startTime.Ticks; this.timestamp = (long)TimeSpan.FromTicks(t).TotalMilliseconds; this.body = new BodyHolder(); this.body.body = obj; this.timeToLive = 0; }
/// <summary> /// Retrieves the context of the specified thread. /// </summary> /// <param name="threadHandle">A handle to the thread whose context is to be retrieved.</param> /// <param name="contextFlags">Determines which registers are returned or set.</param> /// <returns>A <see cref="ThreadContext"/> structure that receives the appropriate context of the specified thread.</returns> public static ThreadContext GetThreadContext(SafeMemoryHandle threadHandle, ThreadContextFlags contextFlags = ThreadContextFlags.Full) { // Check if the handle is valid HandleManipulator.ValidateAsArgument(threadHandle, "threadHandle"); // Allocate a thread context structure var context = new ThreadContext { ContextFlags = contextFlags }; // Set the context flag // Get the thread context if (NativeMethods.GetThreadContext(threadHandle, ref context)) { return(context); } // Else couldn't get the thread context, throws an exception throw new Win32Exception("Couldn't get the thread context."); }
private static void InvokeMeshPass(EffectMesh mesh, ThreadContext context, bool skipEffectPass = false) { var effectPass = mesh.EffectPass; // Execute EffectPass - StartPass if (!skipEffectPass) { effectPass.StartPass.Invoke(context); } // Execute MeshPass - StartPass - EndPass context.EffectMesh = mesh; mesh.Render.Invoke(context); context.EffectMesh = null; // Execute EffectPass - EndPass if (!skipEffectPass) { effectPass.EndPass.Invoke(context); } }
public CommandMessage(String operation, Object body) { this.messageId = Guid.NewGuid().ToString().ToUpper(); Hashtable responseMetadata = (Hashtable)ThreadContext.getProperties()[ORBConstants.RESPONSE_METADATA]; if (responseMetadata != null) { this.headers = responseMetadata; } else { this.headers = new Hashtable(); } this.timestamp = ORBUtil.currentTimeMillis(); this.body = new BodyHolder(); this.body.body = body; this.timeToLive = 0; this.operation = operation; }
public AD7StackFrame(AD7Engine engine, AD7Thread thread, ThreadContext threadContext) { Debug.Assert(threadContext != null, "ThreadContext is null"); Engine = engine; Thread = thread; ThreadContext = threadContext; _textPosition = threadContext.TextPosition; _functionName = threadContext.Function; if (_textPosition != null) { _documentCxt = new AD7DocumentContext(_textPosition, _codeCxt); if (_codeCxt != null) { _codeCxt.SetDocumentContext(_documentCxt); } } }
protected MessageHandler(CloseFunction closeFunction, SenderFunction senderFunction) { this.closeFunction = closeFunction; this.senderFunction = senderFunction; pingThreadContext = ThreadCreator.CreateLoop("Ping loop", () => { try { var r = new PingRequest { Timestamp = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds(), }; senderFunction(new PingRequest { Timestamp = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds(), }); } catch (Exception ex) { logger.Warn(ex, "Ping failed, closing connection"); closeFunction(); } }, 5000).Start(); }
/// <summary> /// 尝试把任务排到线程池上 /// </summary> /// <param name="action">任务</param> /// <returns>是否排队成功</returns> public bool TryQueueUserWork(Action action) { if (_threadNum < MaxThreadNum) { var context = new ThreadContext(action); context.OnExited = () => { Interlocked.Decrement(ref _threadNum); }; if (ThreadPool.QueueUserWorkItem(threadContext => { var runable = (Runable)threadContext; runable.Run(); }, context)) { Interlocked.Increment(ref _threadNum); return(true); } } return(false); }
public override HostExecutionContext Capture() { ThreadContext currentContext = ThreadContext.Current; if (currentContext != null) { // We need to capture a reference to the current HttpContext's ThreadContextId // so that we can properly restore this instance on the call to SetHostExecutionContext. // See comment on HttpContext.ThreadContextId for more information. return(new AspNetHostExecutionContext( baseContext: base.Capture(), httpContextThreadContextId: currentContext.HttpContext.ThreadContextId)); } else { // There is no ThreadContext associated with this thread, hence there is no special // setup we need to do to restore things like HttpContext.Current. We can just // delegate to the base implementation. return(base.Capture()); } }
protected string GetClientClass(IDictionary dictionary) { Type type = dictionary.GetType(); string className = type.IsGenericType && type.FullName != null ? type.FullName.Substring(0, type.FullName.IndexOf("`")) : type.FullName; #if (FULL_BUILD) string clientClass = null; string mappingClassName = ORBConstants.CLIENT_MAPPING + className; IDictionary props = ThreadContext.getProperties(); if (props.Contains(className)) { clientClass = (string)props[mappingClassName]; } #else string clientClass = null; #endif if (clientClass == null) { clientClass = Types.Types.getClientClassForServerType(className); if (clientClass == null && type.IsGenericType) { Type keyType = type.GetGenericArguments()[0]; if (!keyType.IsPrimitive && !StringUtil.IsStringType(keyType)) { clientClass = "flash.utils.Dictionary"; } } return(clientClass); } else { return(clientClass); } }
void WriteThreadBody(object obj) { ThreadContext ctx = (ThreadContext)obj; try { UpdateProgress("Erasing partition table...", 0, 0); using (var dev = new DiskDevice(ctx.DeviceNumber.PhysicalDrive)) { if (dev.QueryLength().Length != (ulong)ctx.VolumeSize) { throw new Exception("Mismatching volume length"); } } RunDiskpart($"SELECT DISK {ctx.DeviceNumber.DeviceNumber}\r\nCLEAN\r\nRESCAN\r\nEXIT", $"Diskpart failed to reset disk #{ctx.DeviceNumber}"); using (var dev = new DiskDevice(ctx.DeviceNumber.PhysicalDrive)) { for (; ;) { if (AttemptWrite(ctx, dev)) { break; } } ReportCompletion(null); } } catch (System.Exception ex) { ReportCompletion(ex); } finally { ctx.fs?.Dispose(); } }
private ThreadContext OnSystemTick(SystemIRQ irq, ThreadContext context) { TickCount++; // Unblock delayed threads while (true) { var first = _delayedThreads.First; if (first != null && TickCount >= first.Value.AwakeTick) { _delayedThreads.Remove(first); _readyThreads.AddLast(first); first.Value.Thread.State = ThreadState.Ready; } else { break; } } return(YieldThread()); }
public MainWindow() { runningThread = new ThreadContext { WorkerThread = new Thread(Transformator), UIThread = Dispatcher, Queue = inputText, Running = true }; DataContext = runningThread; InitializeComponent(); runningThread.Output = output; runningThread.Errors = errors; runningThread.WorkerThread.Start(runningThread); input.SyntaxHighlighting = HighlightingLoader.Load( new XmlTextReader("Python.xshd"), HighlightingManager.Instance ); output.SyntaxHighlighting = HighlightingManager.Instance.GetDefinition("JavaScript"); }
/// <summary> /// /// </summary> /// <param name="ThreadContext"></param> /// <param name="Left"></param> /// <param name="Right"></param> public static void CMP_DWORD(ThreadContext ThreadContext, int Left, int Right) { int Result; Result = Left - Right; //Console.WriteLine("######## CMP: 0x{1:X} - 0x{2:X} = 0x{0:X}", Result, Left, Right); ThreadContext.Flags.OF = false; ThreadContext.Flags.ZF = (Result == 0); ThreadContext.Flags.SF = (Result < 0); //if (Right < Left) ThreadContext.Flags.OF = true; try { Result = checked(Left - Right); } catch (OverflowException) { ThreadContext.Flags.OF = true; } }
/// <summary> /// Invokes the specified exception handler with the given exception /// object. /// </summary> /// <param name="Handler"></param> /// <param name="ExceptionObject"></param> /// <returns></returns> public static RakudoObject CallHandler(ThreadContext TC, RakudoObject Handler, RakudoObject ExceptionObject) { // Invoke the handler. Note that in some cases we never return from it; // for example, the return exception handler does .leave. var Returned = Handler.STable.Invoke(TC, Handler, CaptureHelper.FormWith(new RakudoObject[] { ExceptionObject })); // So, we returned. Let's see if it's resumable. var ResumableMeth = Returned.STable.FindMethod(TC, Returned, "resumable", Hints.NO_HINT); var Resumable = ResumableMeth.STable.Invoke(TC, ResumableMeth, CaptureHelper.FormWith(new RakudoObject[] { Returned })); if (Ops.unbox_int(TC, Resumable) != 0) { // Resumable, so don't need to stack unwind. Simply return // from here. return Returned; } else { // Not resumable, so stack unwind out of the block containing // the handler. throw new LeaveStackUnwinderException( (Handler as RakudoCodeRef.Instance).OuterBlock, Returned); } }
public void ThreadContext_Get_Set_Guid_TEST() { var tc = new ThreadContext(); var guid = Guid.NewGuid(); tc.Set("b", guid); Assert.AreEqual(guid, tc.Get<Guid>("b")); }
/// <summary> /// Computes a bitonic sort on the sort buffer. /// </summary> /// <param name="context">The context.</param> /// <remarks> /// The sort buffer is a structure containing: /// struct SortData { uint ParticleIndex; float DepthValue; }; /// This methods reorders the sort buffer based on the depth value, from lowest to highest. /// </remarks> private void ComputeBitonicSort(ThreadContext context) { if (!EnableSorting || !isParticleRenderingEnabled) return; // TODO: handle progressive sorting when no dynamic emitter int particleCount = updatersCount; // Precalculates values from CapacityCount, MaximumDepthLevel and MaximumThreadPerGroup var depthLevelCount = (int)Math.Log(particleCount, 2); var optimLevelStart = (int)Math.Log(MaximumDepthLevel, 2); int blockSize = 1; int numberOfGroupForOptim = particleCount / MaximumThreadPerGroup; int numberOfGroups = numberOfGroupForOptim / 2; for (int i = 0; i < depthLevelCount; i++, blockSize *= 2) { // Create dispatch pass for bitonic step1 effectMeshSort1Pass1.Parameters.Set(ParticleBaseKeys.ParticleStartIndex, (uint)blockSize); effectMeshSort1Pass1.Parameters.Set(ParticleBaseKeys.ParticleSortBuffer, sortBuffer); effectMeshSort1Pass1.Parameters.Set(ComputeShaderPlugin.ThreadGroupCount, new Int3(numberOfGroups, 1, 1)); // Invoke Mesh Pass InvokeMeshPass(effectMeshSort1Pass1, context); // Setup multiple Pass2 var subOffset = blockSize; for (int j = 0; j < i; j++, subOffset /= 2) { // Use optimized group version if possible int k = optimLevelStart - i + j; if (k >= 0 && k < effectMeshBitonicSort2.Length) { var subMesh = effectMeshBitonicSort2[k]; subMesh.Parameters.Set(ParticleBaseKeys.ParticleSortBuffer, sortBuffer); subMesh.Parameters.Set(ComputeShaderPlugin.ThreadGroupCount, new Int3(numberOfGroupForOptim, 1, 1)); InvokeMeshPass(subMesh, context); break; } // Else use standard version effectMeshSort1Pass2.Parameters.Set(ParticleBaseKeys.ParticleStartIndex, (uint)(subOffset / 2)); effectMeshSort1Pass2.Parameters.Set(ParticleBaseKeys.ParticleSortBuffer, sortBuffer); effectMeshSort1Pass2.Parameters.Set(ComputeShaderPlugin.ThreadGroupCount, new Int3(numberOfGroups, 1, 1)); // When j > 0, we can don't need to reapply the effect pass InvokeMeshPass(effectMeshSort1Pass2, context, j > 0); } } }
private static void Preparing(ThreadContext context, PreparingEventArgs preparing) { context.Focus = context.Focus.Preparing(preparing); context.Chain = context.Chain.Link(preparing, context.Focus); context.Clock = MoveClock(context.Clock, context.Focus); }
private static void Activating(ThreadContext context, ActivatingEventArgs<object> activating) { context.Focus = context.Focus.Activating(activating); }
/// <summary> /// Resolves the symbol address. /// </summary> /// <param name="process">The process.</param> /// <param name="symbol">The symbol.</param> /// <param name="frameContext">The frame context.</param> private static ulong ResolveAddress(Process process, IDiaSymbol symbol, ThreadContext frameContext) { ulong address; switch ((LocationType)symbol.locationType) { case LocationType.RegRel: switch ((CV_HREG_e)symbol.registerId) { case CV_HREG_e.CV_AMD64_ESP: case CV_HREG_e.CV_AMD64_RSP: address = frameContext.StackPointer; break; case CV_HREG_e.CV_AMD64_RIP: //case CV_HREG_e.CV_REG_EIP: address = frameContext.InstructionPointer; break; case CV_HREG_e.CV_AMD64_RBP: case CV_HREG_e.CV_AMD64_EBP: address = frameContext.FramePointer; break; case CV_HREG_e.CV_ALLREG_VFRAME: if (process.EffectiveProcessorType == ImageFileMachine.AMD64) address = frameContext.StackPointer; else address = frameContext.FramePointer; break; default: throw new Exception("Unknown register id" + (CV_HREG_e)symbol.registerId); } address += (ulong)symbol.offset; return address; case LocationType.Static: return symbol.virtualAddress; default: throw new Exception("Unknown location type " + (LocationType)symbol.locationType); } }
private static void CheckContext() { var t = new ThreadContext(); var result = t.Get<string>("c"); if (!string.IsNullOrEmpty(result)) { throw new InvalidDataException(); } t.Set("c", "a"); if (t.Get<string>("c") != "a") { throw new InvalidDataException(); } }
public void ThreadContext_Sharing_TEST() { var tc = new ThreadContext(); var k = "a"; var threadTimes = new Dictionary<int, DateTime>(); var action = new Action( () => { var tk = Thread.CurrentThread.ManagedThreadId; DateTime? now = DateTime.Now; Assert.IsFalse(tc.Get<DateTime?>(k).HasValue); if (!tc.Get<DateTime?>(k).HasValue) { tc.Set(k, now); if (!threadTimes.ContainsKey(tk)) { threadTimes[tk] = now.Value; } } Assert.AreEqual(now.Value.Ticks, tc.Get<DateTime?>(k).Value.Ticks); }); var tasks = new List<Task>(); for (int i = 0; i < 100000; i++) { tasks.Add(Task.Factory.StartNew(action)); } Task.WaitAll(tasks.ToArray()); Assert.IsTrue(true); }
/// <summary> /// Sets the context for the specified thread. /// </summary> /// <param name="threadHandle">A handle to the thread whose context is to be set.</param> /// <param name="context"> /// A pointer to a <see cref="ThreadContext" /> structure that contains the context to be set in the /// specified thread. /// </param> public static void SetThreadContext(SafeMemoryHandle threadHandle, ThreadContext context) { // Check if the handle is valid HandleManipulationHelper.ValidateAsArgument(threadHandle, "threadHandle"); // Set the thread context if (!NativeMethods.SetThreadContext(threadHandle, ref context)) throw new Win32Exception("Couldn't set the thread context."); }
private static void Activated(ThreadContext context, ActivatedEventArgs<object> activated) { context.Clock = MoveClock(context.Clock, context.Root); context.Chain = context.Chain.Activated(activated); }
public void LeakTest() { int workerThreads, portsThreads; ThreadPool.GetMaxThreads(out workerThreads, out portsThreads); ThreadPool.SetMaxThreads(5, 5); for (var i = 0; i < 10000; i++) { var t = new Thread(CheckContext); var c = new ThreadContext(); c.Set("c", "a"); t.Start(); t.Join(); } ThreadPool.SetMaxThreads(workerThreads, portsThreads); Assert.IsTrue(true); }
/// <summary> /// Finds the best candidate, if one exists, and returns it. /// </summary> /// <param name="Candidates"></param> /// <param name="Capture"></param> /// <returns></returns> public static RakudoObject FindBestCandidate(ThreadContext TC, RakudoCodeRef.Instance DispatchRoutine, RakudoObject Capture) { // Extract the native capture. // XXX Handle non-native captures too. var NativeCapture = Capture as P6capture.Instance; // First, try the dispatch cache. if (DispatchRoutine.MultiDispatchCache != null && NativeCapture.Nameds == null) { var CacheResult = DispatchRoutine.MultiDispatchCache.Lookup(NativeCapture.Positionals); if (CacheResult != null) return CacheResult; } // Sort the candidates. // XXX Cache this in the future. var SortedCandidates = Sort(TC, DispatchRoutine.Dispatchees); // Now go through the sorted candidates and find the first one that // matches. var PossiblesList = new List<RakudoCodeRef.Instance>(); foreach (RakudoCodeRef.Instance Candidate in SortedCandidates) { // If we hit a null, we're at the end of a group. if (Candidate == null) { if (PossiblesList.Count == 1) { // We have an unambiguous first candidate. Cache if possible and // return it. if (NativeCapture.Nameds == null) { if (DispatchRoutine.MultiDispatchCache == null) DispatchRoutine.MultiDispatchCache = new DispatchCache(); DispatchRoutine.MultiDispatchCache.Add(NativeCapture.Positionals, PossiblesList[0]); } return PossiblesList[0]; } else if (PossiblesList.Count > 1) { // Here is where you'd handle constraints. throw new Exception("Ambiguous dispatch: more than one candidate matches"); } else { continue; } } /* Check if it's admissible by arity. */ var NumArgs = NativeCapture.Positionals.Length; if (NumArgs < Candidate.Sig.NumRequiredPositionals || NumArgs > Candidate.Sig.NumPositionals) continue; /* Check if it's admissible by types and definedness. */ var TypeCheckCount = Math.Min(NumArgs, Candidate.Sig.NumPositionals); var TypeMismatch = false; for (int i = 0; i < TypeCheckCount; i++) { var Arg = NativeCapture.Positionals[i]; var Type = Candidate.Sig.Parameters[i].Type; if (Type != null && Ops.unbox_int(TC, Type.STable.TypeCheck(TC, Arg.STable.WHAT, Type)) == 0) { TypeMismatch = true; break; } var Definedness = Candidate.Sig.Parameters[i].Definedness; if (Definedness != DefinednessConstraint.None) { var ArgDefined = Arg.STable.REPR.defined(null, Arg); if (Definedness == DefinednessConstraint.DefinedOnly && !ArgDefined || Definedness == DefinednessConstraint.UndefinedOnly && ArgDefined) { TypeMismatch = true; break; } } } if (TypeMismatch) continue; /* If we get here, it's an admissible candidate; add to list. */ PossiblesList.Add(Candidate); } // If we get here, no candidates matched. throw new Exception("No candidates found to dispatch to"); }
/// <summary> /// Sorts the candidates. /// </summary> /// <param name="Unsorted"></param> /// <returns></returns> private static RakudoCodeRef.Instance[] Sort(ThreadContext TC, RakudoObject[] Unsorted) { /* Allocate results array (just allocate it for worst case, which * is no ties ever, so a null between all of them, and then space * for the terminating null. */ var NumCandidates = Unsorted.Length; var Result = new RakudoCodeRef.Instance[2 * NumCandidates + 1]; /* Create a node for each candidate in the graph. */ var Graph = new CandidateGraphNode[NumCandidates]; for (int i = 0; i < NumCandidates; i++) { Graph[i] = new CandidateGraphNode() { Candidate = (RakudoCodeRef.Instance)Unsorted[i], Edges = new CandidateGraphNode[NumCandidates] }; } /* Now analyze type narrowness of the candidates relative to each other * and create the edges. */ for (int i = 0; i < NumCandidates; i++) { for (int j = 0; j < NumCandidates; j++) { if (i == j) continue; if (IsNarrower(TC, Graph[i].Candidate, Graph[j].Candidate) != 0) { Graph[i].Edges[Graph[i].EdgesOut] = Graph[j]; Graph[i].EdgesOut++; Graph[j].EdgesIn++; } } } /* Perform the topological sort. */ int CandidatesToSort = NumCandidates; int ResultPos = 0; while (CandidatesToSort > 0) { int StartPoint = ResultPos; /* Find any nodes that have no incoming edges and add them to * results. */ for (int i = 0; i < NumCandidates; i++) { if (Graph[i].EdgesIn == 0) { /* Add to results. */ Result[ResultPos] = Graph[i].Candidate; Graph[i].Candidate = null; ResultPos++; CandidatesToSort--; Graph[i].EdgesIn = EDGE_REMOVAL_TODO; } } if (StartPoint == ResultPos) { throw new Exception("Circularity detected in multi sub types."); } /* Now we need to decrement edges in counts for things that had * edges from candidates we added here. */ for (int i = 0; i < NumCandidates; i++) { if (Graph[i].EdgesIn == EDGE_REMOVAL_TODO) { for (int j = 0; j < Graph[i].EdgesOut; j++) Graph[i].Edges[j].EdgesIn--; Graph[i].EdgesIn = EDGE_REMOVED; } } /* This is end of a tied group, so leave a gap. */ ResultPos++; } return Result; }
/// <summary> /// Checks if one signature is narrower than another. /// </summary> /// <param name="a"></param> /// <param name="b"></param> /// <returns></returns> private static int IsNarrower(ThreadContext TC, RakudoCodeRef.Instance a, RakudoCodeRef.Instance b) { var Narrower = 0; var Tied = 0; int i, TypesToCheck; /* Work out how many parameters to compare, factoring in slurpiness * and optionals. */ if (a.Sig.NumPositionals == b.Sig.NumPositionals) TypesToCheck = a.Sig.NumPositionals; else if (a.Sig.NumRequiredPositionals == b.Sig.NumRequiredPositionals) TypesToCheck = Math.Min(a.Sig.NumPositionals, b.Sig.NumPositionals); else return 0; /* Analyse each parameter in the two candidates. */ for (i = 0; i < TypesToCheck; i++) { var TypeObjA = a.Sig.Parameters[i].Type; var TypeObjB = b.Sig.Parameters[i].Type; if (TypeObjA == TypeObjB) { /* In a full Perl 6 multi dispatcher, you'd consider * constraints here. */ Tied++; } else { if (IsNarrowerType(TC, TypeObjA, TypeObjB)) Narrower++; else if (!IsNarrowerType(TC, TypeObjB, TypeObjA)) Tied++; } } /* If one is narrower than the other from current analysis, we're done. */ if (Narrower >= 1 && Narrower + Tied == TypesToCheck) return 1; /* If they aren't tied, we're also done. */ else if (Tied != TypesToCheck) return 0; /* Otherwise, we see if one has a slurpy and the other not. A lack of * slurpiness makes the candidate narrower. Otherwise, they're tied. */ return !a.Sig.HasSlurpyPositional() && b.Sig.HasSlurpyPositional() ? 1 : 0; }
/// <summary> /// Compares two types to see if the first is narrower than the second. /// </summary> /// <returns></returns> public static bool IsNarrowerType(ThreadContext TC, RakudoObject A, RakudoObject B) { // If one of the types is null, then we know that's automatically // wider than anything. if (B == null && A != null) return true; else if (A == null || B == null) return false; // Otherwise, check with the type system. return Ops.unbox_int(TC, Ops.type_check(TC, A, B)) != 0; }
/// <summary> /// Retrieves the context of the specified thread. /// </summary> /// <param name="threadHandle">A handle to the thread whose context is to be retrieved.</param> /// <param name="contextFlags">Determines which registers are returned or set.</param> /// <returns>A <see cref="ThreadContext" /> structure that receives the appropriate context of the specified thread.</returns> public static ThreadContext GetThreadContext(SafeMemoryHandle threadHandle, ThreadContextFlags contextFlags = ThreadContextFlags.Full) { // Check if the handle is valid HandleManipulationHelper.ValidateAsArgument(threadHandle, "threadHandle"); // Allocate a thread context structure var context = new ThreadContext {ContextFlags = contextFlags}; // Set the context flag // Get the thread context if (NativeMethods.GetThreadContext(threadHandle, ref context)) return context; // Else couldn't get the thread context, throws an exception throw new Win32Exception("Couldn't get the thread context."); }
public void ThreadContext_Get_Set_TEST() { var tc = new ThreadContext(); tc.Set("a", 1); Assert.AreEqual(1, tc.Get<int>("a")); }
public Node(ThreadContext threadContext) { _threadContext = threadContext; _hot = true; // meta-nodes are hot to avoid any timing }
public void UpdateShadowMaps(ThreadContext context) { guillotinePacker.Clear(ShadowMapDepth.Description.Width, ShadowMapDepth.Description.Height); // Allocate shadow maps in the atlas and update texture coordinates. foreach (var shadowMap in shadowMaps) { //int widthFactor = shadowMap.Level == CascadeShadowMapLevel.X1 ? 1 : 2; //int heightFactor = shadowMap.Level == CascadeShadowMapLevel.X4 ? 2 : 1; //var shadowMapWidth = shadowMap.ShadowMapSize * widthFactor; //var shadowMapHeight = shadowMap.ShadowMapSize * heightFactor; var cascadeTextureCoords = new Vector4[shadowMap.LevelCount]; var cascadeTextureCoordsBorder = new Vector4[shadowMap.LevelCount]; for (int i = 0; i < shadowMap.LevelCount; ++i) { var rect = guillotinePacker.Insert(shadowMap.ShadowMapSize, shadowMap.ShadowMapSize); // Texture0 array support should help when this break (in complex scenes) if (rect.Width == 0) throw new InvalidOperationException("Could not allocate enough texture space for shadow map texture."); Vector4 cascadeTextureCoord; cascadeTextureCoord.X = (float)(rect.X) / guillotinePacker.Width; cascadeTextureCoord.Y = (float)(rect.Y) / guillotinePacker.Height; cascadeTextureCoord.Z = (float)(rect.X + rect.Width) / guillotinePacker.Width; cascadeTextureCoord.W = (float)(rect.Y + rect.Height) / guillotinePacker.Height; cascadeTextureCoords[i] = cascadeTextureCoord; cascadeTextureCoord.X += 0.01f; cascadeTextureCoord.Y += 0.01f; cascadeTextureCoord.Z -= 0.01f; cascadeTextureCoord.W -= 0.01f; cascadeTextureCoordsBorder[i] = cascadeTextureCoord; shadowMap.Plugins[i].Viewport = new Viewport(rect.X, rect.Y, shadowMap.ShadowMapSize, shadowMap.ShadowMapSize); shadowMap.Plugins[i].DepthStencil = ShadowMapDepth; } shadowMap.Parameters.Set(CascadeTextureCoords, cascadeTextureCoords); shadowMap.Parameters.Set(CascadeTextureCoordsBorder, cascadeTextureCoordsBorder); shadowMap.CasterParameters.Set(EffectPlugin.RasterizerStateKey, casterRasterizerState); shadowMap.CasterParameters.Set(EffectPlugin.DepthStencilStateKey, depthStencilStateZStandard); shadowMap.TextureCoordsBorder = cascadeTextureCoordsBorder; } }
public Node(Node parent, IComponentRegistration component) { _threadContext = parent._threadContext; _parent = parent; _component = component; }