From c1ca4ea1408be04f500defdc5c629f94e8243068 Mon Sep 17 00:00:00 2001 From: jelly013 <22855910+jelly013@users.noreply.github.com> Date: Tue, 24 Nov 2026 19:34:59 +0100 Subject: [PATCH] runtime: fix timed waits, continued runs and budget accounting Let a wait whose deadline has passed time out instead of taking a later signal. Keep the main thread's pending wait, with its objects and deadline, when a run that stopped on its budget continues from the same context. Count every call that ends a turn, and neither sleep nor report a deadlock with a spent budget. Retry blocked threads again when one of them ends in the pass, so that a thread waiting for it is not reported as deadlocked or timed out. Refuse to open an ended main thread by its ID. Test that a second scheduler cannot attach while one runs. Addresses review of #339. Refs #323 Signed-off-by: jelly013 <22855910+jelly013@users.noreply.github.com> --- crates/loader/src/scheduler.rs | 84 +++++++----- crates/loader/src/services.rs | 3 +- crates/loader/src/services/events.rs | 21 +-- crates/loader/src/services/threads.rs | 26 +++- crates/loader/tests/runtime_threads.rs | 169 ++++++++++++++++++++++-- crates/loader/tests/threads/program.c | 62 +++++++++ crates/loader/tests/threads/program.txt | 70 +++++++++- docs/runtime/threads.md | 9 +- 8 files changed, 379 insertions(+), 65 deletions(-) diff --git a/crates/loader/src/scheduler.rs b/crates/loader/src/scheduler.rs index af873c7..8a49080 100644 --- a/crates/loader/src/scheduler.rs +++ b/crates/loader/src/scheduler.rs @@ -107,7 +107,9 @@ impl Scheduler { if report.outcome == Outcome::BudgetExhausted && self.all_ended() { report.outcome = Outcome::AllThreadsExited; } - self.state.detach_scheduler(memory); + let continues = report.outcome == Outcome::BudgetExhausted; + self.state + .detach_scheduler(memory, continues.then_some(&report.main)); Ok(report) } @@ -123,6 +125,10 @@ impl Scheduler { return Turn::Stop(outcome); } let Some(id) = self.next_ready() else { + // A spent budget may have left waiters untried, and must not sleep. + if report.instructions >= budget { + return Turn::Continue; + } return self.idle(); }; report.turns += 1; @@ -189,7 +195,9 @@ impl Scheduler { table.queue.remove(position) } - /// Run the pending call of every blocked thread once, oldest first. + /// Run the pending call of every blocked thread, oldest first. A thread that + /// ends with its call may be what an older one waits for, so that repeats + /// the pass. fn wake( &self, engine: &mut DbtEngine, @@ -198,37 +206,46 @@ impl Scheduler { budget: usize, report: &mut ScheduleReport, ) -> Option { - let mut blocked: Vec<(u64, u32)> = { - let table = self.state.threads.lock().expect("guest thread table"); - report.peak_threads = report.peak_threads.max(table.threads.len()); - table - .threads - .iter() - .filter(|(_, thread)| thread.suspend == 0) - .filter_map(|(&id, thread)| match thread.run { - RunState::Blocked(sequence) => Some((sequence, id)), - RunState::Ready => None, - }) - .collect() - }; - blocked.sort_unstable(); - for (_, id) in blocked { - if report.instructions >= budget { - break; - } - match self.run_thread(engine, memory, id, main_id, 1, report) { - Stop::Outcome(outcome) => return Some(outcome), - Stop::Blocked | Stop::Ended => {} - Stop::Preempted { .. } => { - let mut table = self.state.threads.lock().expect("guest thread table"); - if let Some(thread) = table.threads.get_mut(&id) { - thread.run = RunState::Ready; - table.queue.push_back(id); + loop { + let mut ended = false; + for id in self.blocked(report) { + if report.instructions >= budget { + return None; + } + match self.run_thread(engine, memory, id, main_id, 1, report) { + Stop::Outcome(outcome) => return Some(outcome), + Stop::Blocked => {} + Stop::Ended => ended = true, + Stop::Preempted { .. } => { + let mut table = self.state.threads.lock().expect("guest thread table"); + if let Some(thread) = table.threads.get_mut(&id) { + thread.run = RunState::Ready; + table.queue.push_back(id); + } } } } + if !ended { + return None; + } } - None + } + + /// Blocked threads that are not suspended, oldest first. + fn blocked(&self, report: &mut ScheduleReport) -> Vec { + let table = self.state.threads.lock().expect("guest thread table"); + report.peak_threads = report.peak_threads.max(table.threads.len()); + let mut blocked: Vec<(u64, u32)> = table + .threads + .iter() + .filter(|(_, thread)| thread.suspend == 0) + .filter_map(|(&id, thread)| match thread.run { + RunState::Blocked(sequence) => Some((sequence, id)), + RunState::Ready => None, + }) + .collect(); + blocked.sort_unstable(); + blocked.into_iter().map(|(_, id)| id).collect() } /// Nothing can run: advance to the next deadline or stop. @@ -273,9 +290,12 @@ impl Scheduler { }; self.state.hooks.take_switch(); let result = engine.run_slice(&mut cpu, memory, limit); - // A stopped call still makes progress, so a loop of them is bounded. - let yielded = usize::from(result.exit_reason == ExitReason::GuestYield); - report.instructions += (result.instructions_executed + yielded).max(1); + // The engine does not count a call that stops it. + let stopped = matches!( + result.exit_reason, + ExitReason::GuestYield | ExitReason::GuestBlocked | ExitReason::GuestThreadExited + ); + report.instructions += result.instructions_executed + usize::from(stopped); let rip = cpu.rip; let returned = (rip == THREAD_RETURN && id != main_id) .then(|| cpu.get(crate::cpu::Register::Rax) as u32); diff --git a/crates/loader/src/services.rs b/crates/loader/src/services.rs index 84eca59..705d703 100644 --- a/crates/loader/src/services.rs +++ b/crates/loader/src/services.rs @@ -699,7 +699,8 @@ pub(crate) mod handlers { ) -> Outcome { let state = context.state; let worker = state.worker_object(id); - if id != state.thread_id && worker.is_none() { + let main = id == state.thread_id && state.main_thread_alive(); + if !main && worker.is_none() { return state.fail(context.teb, ERROR_INVALID_PARAMETER, 0); } let supported = THREAD_SUPPORTED_RIGHTS diff --git a/crates/loader/src/services/events.rs b/crates/loader/src/services/events.rs index 09a60fb..97a887f 100644 --- a/crates/loader/src/services/events.rs +++ b/crates/loader/src/services/events.rs @@ -431,18 +431,21 @@ fn wait_for_objects( Err(ExitReason::GuestBlocked) } -/// Continue the wait this thread is blocked in, if any. Signaled objects take -/// precedence over an expired timeout. +/// Continue the wait this thread is blocked in, if any. Waiters are retried +/// directly after a signal, so an object found signaled once the deadline has +/// passed was signaled too late and is left alone. fn resume_wait(state: &ServicesState, teb: u64) -> Option> { let mut table = state.threads.lock().expect("guest thread table"); let pending = table.waits.get(&teb)?; - let objects: Vec<&Arc>> = pending.objects.iter().collect(); - let result = try_satisfy(&objects, pending.all, teb).or_else(|| { - pending - .deadline - .is_some_and(|deadline| state.clock.performance_count() >= deadline) - .then_some(Ok(WAIT_TIMEOUT)) - }); + let expired = pending + .deadline + .is_some_and(|deadline| state.clock.performance_count() >= deadline); + let result = if expired { + Some(Ok(WAIT_TIMEOUT)) + } else { + let objects: Vec<&Arc>> = pending.objects.iter().collect(); + try_satisfy(&objects, pending.all, teb) + }; if result.is_some() { table.waits.remove(&teb); } diff --git a/crates/loader/src/services/threads.rs b/crates/loader/src/services/threads.rs index 224424f..a6cff60 100644 --- a/crates/loader/src/services/threads.rs +++ b/crates/loader/src/services/threads.rs @@ -125,6 +125,9 @@ pub(crate) struct ThreadTable { /// Ready threads in the order they run. pub(crate) queue: VecDeque, pub(super) waits: BTreeMap, + /// Main thread wait of a run that stopped on its budget, and the context + /// that continues it. + continued: Option<(CpuState, PendingWait)>, slots: BTreeSet, last_id: u32, pub(crate) sequence: u64, @@ -217,13 +220,18 @@ impl ServicesState { }, ); table.queue.push_back(self.thread_id); + if let Some((context, wait)) = table.continued.take() + && context == *main + { + table.waits.insert(main.gs_base, wait); + } Ok(self.thread_id) } - /// Reclaim every created thread. The main thread keeps its per-thread state, - /// so a run that stopped on its budget can be resumed if no other thread - /// was alive. - pub(crate) fn detach_scheduler(&self, memory: &mut GuestMemory) { + /// Reclaim every created thread. The main thread keeps its per-thread state. + /// `continues` is its context if the run stopped on its budget; its pending + /// wait is then kept for that context. + pub(crate) fn detach_scheduler(&self, memory: &mut GuestMemory, continues: Option<&CpuState>) { let workers: Vec = { let table = self.threads.lock().expect("guest thread table"); let worker = |(&id, thread): (&u32, &GuestThread)| thread.slot.map(|_| id); @@ -233,6 +241,10 @@ impl ServicesState { self.end_thread(id, 0, memory); } let mut table = self.threads.lock().expect("guest thread table"); + if let Some(context) = continues { + let wait = table.waits.remove(&context.gs_base); + table.continued = wait.map(|wait| (context.clone(), wait)); + } table.threads.clear(); table.queue.clear(); table.waits.clear(); @@ -284,6 +296,12 @@ impl ServicesState { .unwrap_or(self.thread_id) } + /// Whether the main thread can still be named by its ID. + pub(super) fn main_thread_alive(&self) -> bool { + let table = self.threads.lock().expect("guest thread table"); + !self.hooks.is_attached() || table.threads.contains_key(&self.thread_id) + } + /// Thread object for an ID, if that thread is alive and not the main thread. pub(super) fn worker_object(&self, id: u32) -> Option>> { let table = self.threads.lock().expect("guest thread table"); diff --git a/crates/loader/tests/runtime_threads.rs b/crates/loader/tests/runtime_threads.rs index e5ef2fd..3bc9587 100644 --- a/crates/loader/tests/runtime_threads.rs +++ b/crates/loader/tests/runtime_threads.rs @@ -33,6 +33,17 @@ const COUNTER: u64 = SHARED + 256; const FIRST_SLOT: u64 = 0x6_0000_0000; const BUDGET: usize = 20_000_000; const MAIN_ID: u32 = 0x4104; +/// Host services of the test programs: advance the clock by RCX milliseconds, +/// and try to run a second scheduler. +const ADVANCE: u64 = 0x6_0000; +const NESTED: u64 = 0x6_0010; + +fn return_to_guest(cpu: &mut CpuState, memory: &mut GuestMemory) -> Result<(), ExitReason> { + let rsp = cpu.get(Register::Rsp); + cpu.rip = memory.read_u64(rsp).map_err(ExitReason::MemoryFault)?; + cpu.set(Register::Rsp, rsp + 8); + Ok(()) +} struct Program { code: Vec, @@ -199,6 +210,11 @@ fn guest(main: &str) -> Guest { registry.bind_imports(&pe, &bytes, BASE, memory).unwrap(); let mut engine = DbtEngine::new(1024 * 1024).unwrap(); engine.set_import_registry(registry); + let time = clock.clone(); + engine.register_service(ADVANCE, move |cpu, memory| { + time.advance(cpu.get(Register::Rcx) * 10_000); + return_to_guest(cpu, memory) + }); let mut cpu = CpuState::new(loaded.entry_point, STACK + STACK_LEN as u64 - 0x100); cpu.gs_base = TEB; Guest { @@ -526,7 +542,7 @@ fn without_a_scheduler_nothing_pretends_to_create_threads() { } #[test] -fn only_one_scheduler_can_be_attached_and_it_detaches() { +fn a_finished_run_detaches_its_scheduler() { let mut guest = guest("main_timeout"); for _ in 0..2 { let scheduler = Scheduler::new(Arc::clone(&guest.state), 1024); @@ -539,6 +555,130 @@ fn only_one_scheduler_can_be_attached_and_it_detaches() { assert_eq!(guest.memory.read_u64(COUNTER).unwrap(), 0); } +#[test] +fn a_second_scheduler_cannot_attach_while_one_runs() { + let mut guest = guest("main_nested"); + let state = Arc::clone(&guest.state); + guest.engine.register_service(NESTED, move |cpu, memory| { + let mut engine = DbtEngine::new(1024 * 1024).unwrap(); + let nested = Scheduler::new(Arc::clone(&state), 1024).run(&mut engine, memory, cpu, BUDGET); + assert_eq!(nested.err(), Some(ExitReason::ServiceAbiViolation)); + memory + .write_u64(SHARED, 1) + .map_err(ExitReason::MemoryFault)?; + return_to_guest(cpu, memory) + }); + let report = Scheduler::new(Arc::clone(&guest.state), 1024) + .run(&mut guest.engine, &mut guest.memory, &guest.cpu, BUDGET) + .unwrap(); + // The refused attempt leaves the running scheduler attached. + assert_eq!(report.outcome, Outcome::Halted); + assert_eq!(guest.memory.read_u64(SHARED).unwrap(), 1); + assert_eq!(guest.memory.read_u64(SHARED + 8).unwrap(), 0); +} + +#[test] +fn a_signal_after_the_deadline_is_not_taken_by_the_expired_wait() { + for quantum in QUANTA { + let run = run_with("main_expired_wait", quantum, BUDGET).halted(); + // WAIT_TIMEOUT, the signaling thread ends, and the auto-reset signal is + // still there once. + assert_eq!(run.outs(4), [258, 0, 0, 258], "quantum {quantum}"); + assert_eq!(run.clock.performance_count(), 1_000_000); + } +} + +/// Run `main_continued_wait` until `budget` is spent. +fn first_part(budget: usize) -> (Guest, ScheduleReport) { + let mut guest = guest("main_continued_wait"); + let report = Scheduler::new(Arc::clone(&guest.state), 1024) + .run(&mut guest.engine, &mut guest.memory, &guest.cpu, budget) + .unwrap(); + (guest, report) +} + +/// Smallest budget with which the wait has been called. +fn budget_that_blocks() -> usize { + (1..200) + .find(|&budget| first_part(budget).0.engine.metrics.service_calls >= 2) + .unwrap() +} + +#[test] +fn a_continued_run_keeps_the_pending_wait() { + let blocks = budget_that_blocks(); + for budget in [blocks, blocks + 1] { + let (mut guest, report) = first_part(budget); + assert_eq!(report.outcome, Outcome::BudgetExhausted); + guest.clock.advance(6_000_000); + // Neither the timeout nor the objects are taken again. + guest.memory.write_u64(SHARED + 8 * 49, 0xBAD).unwrap(); + let report = Scheduler::new(Arc::clone(&guest.state), 1024) + .run(&mut guest.engine, &mut guest.memory, &report.main, BUDGET) + .unwrap(); + assert_eq!(report.outcome, Outcome::Halted); + assert_eq!(guest.memory.read_u64(SHARED).unwrap(), 258); + assert_eq!(guest.clock.performance_count(), 10_000_000); + } +} + +#[test] +fn a_run_from_another_context_does_not_inherit_a_pending_wait() { + let (mut guest, _) = first_part(budget_that_blocks()); + let report = Scheduler::new(Arc::clone(&guest.state), 1024) + .run(&mut guest.engine, &mut guest.memory, &guest.cpu, BUDGET) + .unwrap(); + assert_eq!(report.outcome, Outcome::Halted); + guest.clock.advance(6_000_000); + let begun = guest.clock.performance_count(); + Scheduler::new(Arc::clone(&guest.state), 1024) + .run(&mut guest.engine, &mut guest.memory, &guest.cpu, BUDGET) + .unwrap(); + assert_eq!(guest.clock.performance_count(), begun + 10_000_000); + + let (mut guest, _) = first_part(budget_that_blocks()); + guest.clock.advance(6_000_000); + Scheduler::new(Arc::clone(&guest.state), 1024) + .run(&mut guest.engine, &mut guest.memory, &guest.cpu, BUDGET) + .unwrap(); + assert_eq!(guest.clock.performance_count(), 16_000_000); +} + +#[test] +fn an_exhausted_run_neither_sleeps_nor_reports_a_deadlock() { + let blocks = budget_that_blocks(); + for budget in 1..=blocks + 1 { + let (guest, report) = first_part(budget); + assert_eq!(report.outcome, Outcome::BudgetExhausted, "{budget}"); + assert_eq!(guest.clock.performance_count(), 0, "{budget}"); + } + // One retry more: there is budget left for the result of the sleep. + assert_eq!( + first_part(blocks + 2).0.clock.performance_count(), + 10_000_000 + ); +} + +#[test] +fn a_thread_that_ends_with_its_wait_is_noticed_at_once() { + for quantum in QUANTA { + // Neither a deadlock nor the longer timeout of the thread waiting for it. + let run = run_with("main_ends_in_a_wait", quantum, BUDGET).halted(); + assert_eq!(run.outs(3), [0, 0, 258], "quantum {quantum}"); + assert_eq!(run.clock.performance_count(), 1_000_000); + } +} + +#[test] +fn a_thread_that_ended_cannot_be_opened_by_its_id() { + for quantum in QUANTA { + let run = run_with("main_reopened", quantum, BUDGET); + assert_eq!(run.report.outcome, Outcome::AllThreadsExited); + // ERROR_INVALID_PARAMETER. + assert_eq!(run.outs(4), [1, 1, 0, 87], "quantum {quantum}"); + } +} + #[test] fn a_signaled_object_goes_to_the_waiting_thread() { for quantum in [256, 1024, 1_000_000] { @@ -707,6 +847,7 @@ fn every_small_budget_stops_cleanly() { for quantum in [1, 64, 1024] { for budget in (1..1500).step_by(29) { let run = run_with(main, quantum, budget); + assert!(!matches!(run.report.outcome, Outcome::Deadlock { .. })); // One block and one pass of retries may follow the limit. assert!( run.report.instructions < budget + 32, @@ -723,6 +864,7 @@ fn retrying_many_waiters_stays_within_the_budget() { // Up to 63 threads wait at once; a pass over all of them must stop. for budget in (1500..12_000).step_by(211) { let run = run_with("main_limit", 64, budget); + assert!(!matches!(run.report.outcome, Outcome::Deadlock { .. })); assert!( run.report.instructions < budget + 32, "{budget}: {}", @@ -770,11 +912,22 @@ fn thread_ids_are_not_reused_by_a_later_run() { #[test] fn service_calls_that_end_a_turn_are_counted() { - let run = run("main_signals").halted(); - // The engine counts guest instructions and service calls separately. - assert!(run.metrics.service_calls > 1000); - assert_eq!( - run.report.instructions, - run.metrics.instructions_executed + run.metrics.service_calls - ); + for (main, calls) in [ + ("main_signals", 1000), + ("main_independent", 5), + ("main_mutex", 100), + ("main_fifo", 10), + ("main_churn", 100), + ("main_exits_first", 3), + ] { + for quantum in QUANTA { + let run = run_with(main, quantum, BUDGET); + assert!(run.metrics.service_calls >= calls, "{main} {quantum}"); + assert_eq!( + run.report.instructions, + run.metrics.instructions_executed + run.metrics.service_calls, + "{main} quantum {quantum}" + ); + } + } } diff --git a/crates/loader/tests/threads/program.c b/crates/loader/tests/threads/program.c index d43c40c..8dbbe39 100644 --- a/crates/loader/tests/threads/program.c +++ b/crates/loader/tests/threads/program.c @@ -742,3 +742,65 @@ void main_orphaned_shared(void) { S->out[1] = TryAcquireSRWLockExclusive(&S->srw) & 0xFF; join(spawn(releases_shared, 0)); } + +// Host services the test registers at fixed addresses. +#define ADVANCE ((void (*)(u64))0x60000) +#define NESTED ((void (*)(void))0x60010) + +// --- a signal after the deadline belongs to nobody ------------------------- +static u32 signals_too_late(void *unused) { + while (!S->flag) SwitchToThread(); + settle(); + ADVANCE(100); + SetEvent(S->a); + return 0; +} +void main_expired_wait(void) { + S->a = CreateEventA(0, 0, 0, 0); + HANDLE late = spawn(signals_too_late, 0); + S->flag = 1; + S->out[0] = WaitForSingleObject(S->a, 50); + S->out[1] = WaitForSingleObject(late, INFINITE); + S->out[2] = WaitForSingleObject(S->a, 0); + S->out[3] = WaitForSingleObject(S->a, 0); +} + +void main_continued_wait(void) { + S->a = CreateEventA(0, 1, 0, 0); + S->handles[0] = S->a; + S->out[0] = WaitForMultipleObjects(1, S->handles, 1, 1000); + S->out[1] = 1; +} + +static u32 reopens(void *id) { + settle(); + S->out[2] = (u64)OpenThread(0x40, 0, (u32)(u64)id); + S->out[3] = GetLastError(); + return 0; +} +void main_reopened(void) { + u32 id = GetCurrentThreadId(); + S->out[0] = OpenThread(0x40, 0, id) != 0; + S->out[1] = spawn(reopens, id) != 0; + ExitThread(3); +} + +// A tail call: the wait returns straight to the end of the thread. +static u32 ends_in_a_wait(HANDLE event, u32 unused) { + __attribute__((musttail)) return WaitForSingleObject(event, 50); +} +void main_ends_in_a_wait(void) { + u32 code = 0; + S->a = CreateEventA(0, 1, 0, 0); + S->handles[0] = spawn((START)(void *)ends_in_a_wait, (u64)S->a); + S->out[0] = WaitForSingleObject(S->handles[0], INFINITE); + S->handles[1] = spawn((START)(void *)ends_in_a_wait, (u64)S->a); + S->out[1] = WaitForSingleObject(S->handles[1], 1000); + GetExitCodeThread(S->handles[1], &code); + S->out[2] = code; +} + +void main_nested(void) { + NESTED(); + S->out[1] = WaitForSingleObject(spawn(collatz, 97), INFINITE); +} diff --git a/crates/loader/tests/threads/program.txt b/crates/loader/tests/threads/program.txt index bdfc077..5e3032e 100644 --- a/crates/loader/tests/threads/program.txt +++ b/crates/loader/tests/threads/program.txt @@ -3,9 +3,12 @@ entry main_area_taken 8960 entry main_atomic 432 entry main_captured 5152 entry main_churn 3936 +entry main_continued_wait 11232 entry main_deadlock 4560 entry main_duplicate 8288 +entry main_ends_in_a_wait 11552 entry main_exits_first 5584 +entry main_expired_wait 10928 entry main_fifo 1520 entry main_free_stack 9120 entry main_handoff 5744 @@ -15,6 +18,7 @@ entry main_keeps_state 10176 entry main_lifecycle 2896 entry main_limit 4272 entry main_mutex 896 +entry main_nested 11792 entry main_orphaned_exclusive 10432 entry main_orphaned_locks 7632 entry main_orphaned_shared 10656 @@ -23,6 +27,7 @@ entry main_overflow 5056 entry main_pending_bound 8064 entry main_producer 1184 entry main_racy 672 +entry main_reopened 11328 entry main_reuse 7280 entry main_rights 6720 entry main_signal_before_timeout 2032 @@ -296,6 +301,28 @@ import TryAcquireSRWLockShared 10745 import TryAcquireSRWLockExclusive 10767 import AcquireSRWLockShared 10859 import ReleaseSRWLockShared 10891 +import CreateEventA 10946 +import CreateThread 10991 +import WaitForSingleObject 11020 +import SwitchToThread 11139 +import SwitchToThread 11172 +import SetEvent 11212 +import CreateEventA 11251 +import WaitForMultipleObjects 11295 +import GetCurrentThreadId 11335 +import OpenThread 11353 +import CreateThread 11406 +import ExitThread 11433 +import SwitchToThread 11474 +import OpenThread 11506 +import GetLastError 11520 +import CreateEventA 11582 +import CreateThread 11621 +import WaitForSingleObject 11648 +import GetExitCodeThread 11749 +import WaitForSingleObject 11784 +import CreateThread 11839 +import WaitForSingleObject 11853 code 56574883ec38c744243400000000c744243000000000488d4424344889442428 code c7442420000000004c8d05f1000000488b350000000041b95000000031c931d2 code ffd6488904258801050048c744242800000000c7442420000000004c8d050e01 @@ -456,7 +483,7 @@ code ffd789c048890425100005004883c4385f5ec3666666662e0f1f840000000000 code 4883ec28488b0c2508020500baffffffffff150000000031c04883c428c36690 code 564883ec3048c744242800000000c7442420000000004c8d053300000031c931 code d24531c9ff15000000004889c64889c1baffffffffff15000000004889f1ff15 -code 000000004883c4305ec3660f1f4400004883ec2831c9e8951600004883c428c3 +code 000000004883c4305ec3660f1f4400004883ec2831c9e8451a00004883c428c3 code 56574883ec38488b350000000031c9ba010000004531c04531c9ffd648890425 code 0802050031c931d241b8050000004531c9ff1500000000488904251002050031 code c9ba0100000041b8010000004531c9ffd64889042518020500488b0425080205 @@ -572,7 +599,7 @@ code 89042588010500b82c0000004883c4505ec366666666662e0f1f840000000000 code 564883ec3048c744242800000000c7442420000000004c8d0533000000ba0010 code 000041b9c800000031c9ff15000000004889c64889c1baffffffffff15000000 code 004889f1ff15000000004883c4305ec34883ec2848c744242000000000488d54 -code 24204889142508010500e8510800004889042500000500b8010000004883c428 +code 24204889142508010500e8010c00004889042500000500b8010000004883c428 code c36666666666662e0f1f840000000000564883ec3048c744242800000000c744 code 2420000001004c8d05a3ffffffba0010000041b9c800000031c9ff1500000000 code 4889c64889c1baffffffffff15000000004889f1ff15000000004883c4305ec3 @@ -637,8 +664,37 @@ code 44242800000000c7442420000000004c8d054a00000031c931d24531c9ffd748 code 89c64889c1baffffffffffd34889f141ffd64883c4385b5f5e415ec30f1f4000 code 4883ec28b950020500ff150000000031c04883c428c3662e0f1f840000000000 code 4883ec28b950020500ff1500000000c704252402050001000000b80100000048 -code 83c428c36666662e0f1f8400000000004881ec2802000048894c242048ff0425 -code 00000500488d4c2420e8e2ffffff48034424204881c428020000c30f1f440000 -code 4881ec2802000048894c242048895424284885c9741a48ffc9488d542420e8dd -code ffffff48034424204881c428020000c3488d442420488904251001050031c048 -code 81c428020000c3 +code 83c428c36666662e0f1f84000000000056574883ec3831c931d24531c04531c9 +code ff1500000000488904250802050048c744242800000000c7442420000000004c +code 8d058a00000031c931d24531c9ff15000000004889c6c7042524020500010000 +code 00488b0c2508020500488b3d00000000ba32000000ffd789c048890425000005 +code 004889f1baffffffffffd789c04889042508000500488b0c250802050031d2ff +code d789c04889042510000500488b0c250802050031d2ffd789c048890425180005 +code 004883c4385f5ec30f1f84000000000056574883ec28833c252402050000751c +code 488b3500000000660f1f840000000000ffd6833c25240205000074f4be1e0000 +code 00488b3d000000000f1f840000000000ffd7ffce75fab800000600b964000000 +code ffd0488b0c2508020500ff150000000031c04883c4285f5ec30f1f8000000000 +code 4883ec2831c9ba010000004531c04531c9ff1500000000488904250802050048 +code 89042588010500ba88010500b90100000041b80100000041b9e8030000ff1500 +code 00000089c0488904250000050048c7042508000500010000004883c428c36690 +code 564883ec30ff150000000089c6b94000000031d24189c0ff150000000031c948 +code 85c00f95c148890c25000005004189f148c744242800000000c7442420000000 +code 004c8d053800000031c931d2ff150000000031c94885c00f95c148890c250800 +code 0500b903000000ff15000000004883c4305ec3666666662e0f1f840000000000 +code 5657534883ec204889cebf1e000000488b1d00000000662e0f1f840000000000 +code ffd3ffcf75fab94000000031d24189f0ff15000000004889042510000500ff15 +code 0000000089c0488904251800050031c04883c4205b5f5ec30f1f840000000000 +code 5657534883ec40c744243c0000000031c9ba010000004531c04531c9ff150000 +code 0000488904250802050048c744242800000000c744242000000000488d359e00 +code 0000488b3d0000000031c931d24989f04989c1ffd74889042588010500488b1d +code 000000004889c1baffffffffffd389c048890425000005004c8b0c2508020500 +code 48c744242800000000c74424200000000031c931d24989f0ffd7488904259001 +code 05004889c1bae8030000ffd389c04889042508000500488b0c2590010500488d +code 54243cff15000000008b44243c48890425100005004883c4405b5f5ec30f1f00 +code ba3200000048ff25000000000f1f40004883ec38b810000600ffd048c7442428 +code 00000000c7442420000000004c8d053dd3ffff41b96100000031c931d2ff1500 +code 0000004889c1baffffffffff150000000089c048890425080005004883c438c3 +code 4881ec2802000048894c242048ff042500000500488d4c2420e8e2ffffff4803 +code 4424204881c428020000c30f1f4400004881ec2802000048894c242048895424 +code 284885c9741a48ffc9488d542420e8ddffffff48034424204881c428020000c3 +code 488d442420488904251001050031c04881c428020000c3 diff --git a/docs/runtime/threads.md b/docs/runtime/threads.md index 2653b0e..6dbc197 100644 --- a/docs/runtime/threads.md +++ b/docs/runtime/threads.md @@ -6,16 +6,17 @@ - Threads run in first-in, first-out order for a quantum of guest instructions. A turn ends at the first translated-block boundary that reaches the quantum, so small quanta do not compile extra blocks. - The same program, quantum and clock always interleave the same way. -- A service that has to wait returns `GuestBlocked` with no effect and RIP still on its trampoline. The scheduler runs the call again at each turn, oldest waiter first. Each retry counts towards the instruction budget. +- A service that has to wait returns `GuestBlocked` with no effect and RIP still on its trampoline. The scheduler runs the call again at each turn, oldest waiter first. Each retry counts towards the instruction budget, and so does every call that ends a turn. +- A timed wait is over once its deadline has passed. An object signaled after that stays signaled. - Signaling an event, semaphore or mutex stops the caller so that waiters are served first. It keeps what is left of its turn and cannot renew it, so repeated signals do not starve other threads. -- With nothing ready, the clock sleeps until the earliest deadline. With no deadline either, the run ends with `Outcome::Deadlock` and the blocked and suspended thread IDs. +- With nothing ready and budget left, the clock sleeps until the earliest deadline. With no deadline either, the run ends with `Outcome::Deadlock` and the blocked and suspended thread IDs. - A fault in any thread ends the run with `Outcome::Fault` and that thread's ID. HLT ends the process only in the main thread. ## Memory Each thread slot at `0x6_0000_0000 + n * 0x100_0000` holds a guard page, the stack, a guard page and the TEB. Stacks reserve 256 KiB by default, whatever the PE header asks. A nonzero size without `STACK_SIZE_PARAM_IS_A_RESERVATION` is an initial commitment and keeps at least that reservation; with the flag it is the reservation, rounded up to 64 KiB and at most 8 MiB. At most 64 threads live at once, the main thread included, and all thread memory together is bounded by 64 MiB. The guest cannot free it, and a slot the guest has mapped something into is skipped. -Ending a thread releases its memory and slot and drops its last error, TLS and FLS values, callback frames and pending wait. A 4-byte `errno` cell per used slot stays mapped and is zeroed for the next thread. Critical sections, SRW locks and one-time initializations it held stay held by nobody, so a thread that reuses its TEB address does not inherit them. A run keeps the main thread's state, so one that stopped on its budget can continue if no other thread was alive. Thread IDs are never reused. +Ending a thread releases its memory and slot and drops its last error, TLS and FLS values, callback frames and pending wait. A 4-byte `errno` cell per used slot stays mapped and is zeroed for the next thread. Critical sections, SRW locks and one-time initializations it held stay held by nobody, so a thread that reuses its TEB address does not inherit them. A run keeps the main thread's state, so one that stopped on its budget can continue if no other thread was alive; a wait it was in continues with the same objects and deadline when the run starts from the reported main thread context, and is dropped otherwise. Thread IDs are never reused. ## Services @@ -27,7 +28,7 @@ All are partial. Without an attached scheduler `CreateThread` fails with `ERROR_ - Blocking on critical sections, SRW locks and one-time initialization still stops the guest, and a condition-variable sleep with a timeout still fails with `ERROR_NOT_SUPPORTED`. These are the second part of #323. - `Sleep`, `XTaskQueueDispatch` and `WSAPoll` still delay every guest thread. `XTaskQueueDispatch` uses host time, so interleaving is not deterministic across it. -- The mock clock advances only when nothing can run, so a guest that spins until a timed wait expires uses up its budget. +- The mock clock advances only when nothing can run or a service sleeps, so a guest that spins until a timed wait expires uses up its budget. - PE static TLS and DLL thread-attach and detach callbacks for new threads, and FLS callbacks at thread exit. - Waiting on a handle to the main thread or on a pseudo handle, thread priorities of worker threads, APCs and alertable waits, security attributes and inherited handles. - A wait is not satisfied while its thread is suspended.