1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
//! Cooperative single-threaded scheduler for `wasm32-unknown-unknown` hosts.
//!
//! The host owns the event loop and repeatedly calls [`WasmScheduler::run_until_idle`]
//! from `requestAnimationFrame`, a microtask, or an equivalent callback. No OS
//! threads, blocking I/O, dirty pools, or distribution services are started here.
use std::collections::{BTreeMap, BTreeSet, VecDeque};
use std::rc::Rc;
use std::sync::{Arc, Mutex};
use crate::atom::{Atom, AtomTable};
use crate::error::ExecError;
use crate::ets::OwnedTerm;
use crate::interpreter::{ExecutionResult, NativeServices, run_with_native_services};
use crate::mailbox::SendError;
use crate::module::ModuleRegistry;
use crate::namespace::NamespaceId;
use crate::native::{BifRegistryImpl, CapabilitySet, WasmAsyncNifFacility};
use crate::process::heap::DEFAULT_HEAP_SIZE;
use crate::process::{CodePosition, ExitReason, Priority, Process, ProcessStatus};
use crate::term::Term;
use crate::timer::TimerWheel;
/// Receive timer scheduled by the WASM scheduler and awaiting a host timeout.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub struct WasmScheduledTimer {
/// Process that should be resumed when the timer expires.
pub pid: u64,
/// Opaque timer id stored on the process and mirrored by the host.
pub timer_id: u64,
/// Delay requested by the `receive after` instruction.
pub milliseconds: u64,
}
/// Outcome returned when host async work completes.
#[derive(Debug)]
pub enum WasmAsyncCompletion {
/// Promise fulfilled; inject the value into x(0) and advance past the NIF.
Ok(OwnedTerm),
/// Promise rejected; terminate the process with a NIF error mapping.
Error(OwnedTerm),
}
/// Summary returned from one cooperative scheduler turn.
#[derive(Clone, Debug, Default, Eq, PartialEq)]
pub struct WasmRunSummary {
/// Number of processes that received one reduction-bounded slice.
pub executed: usize,
/// PIDs that yielded and were requeued for a later host tick.
pub yielded: Vec<u64>,
/// PIDs that blocked waiting for a message or explicit wake.
pub waiting: Vec<u64>,
/// PIDs that exited during this turn.
pub exited: Vec<u64>,
/// PIDs that faulted with an interpreter error during this turn.
pub errored: Vec<u64>,
}
/// Single-threaded cooperative scheduler for WASM.
pub struct WasmScheduler {
atom_table: Arc<AtomTable>,
module_registry: Arc<ModuleRegistry>,
bif_registry: Arc<BifRegistryImpl>,
next_pid: u64,
pub(super) processes: BTreeMap<u64, Process>,
pub(super) ready: ReadyQueues,
pub(super) waiting: BTreeSet<u64>,
exit_reasons: BTreeMap<u64, ExitReason>,
exit_results: BTreeMap<u64, OwnedTerm>,
exit_errors: BTreeMap<u64, ExecError>,
next_timer_id: u64,
pending_timer_schedules: Vec<WasmScheduledTimer>,
pending_timer_cancellations: Vec<u64>,
pub(super) async_results: BTreeMap<u64, WasmAsyncCompletion>,
pub(super) wasm_async_nif_facility: Option<Rc<dyn WasmAsyncNifFacility>>,
/// Shared pid counter used by the cooperative native path (WR-0). It is an
/// `Arc<Mutex<…>>` so the `Send + Sync` cooperative `SpawnFacility` can
/// allocate child pids from inside a slice; uncontended (single thread).
pub(super) shared_next_pid: Arc<Mutex<u64>>,
/// Exit reasons captured by the cooperative native path.
pub(super) native_exit_reasons: BTreeMap<u64, ExitReason>,
/// Shared timer wheel for cooperative native `Deliver` timers (WR-4).
///
/// `NativeContext::send_after`/`schedule` build `TimerKind::Deliver` entries
/// carrying a message payload; the existing host-`setTimeout` bridge only
/// carries `(pid, timer_id)` for receive-timeout label jumps and cannot
/// deliver a message, so native timers run on the passive wheel ticked once
/// per cooperative turn (see [`WasmScheduler::tick_native_timers`]). It is an
/// `Arc<Mutex<…>>` so the `Send + Sync` [`NativeContext`] can hold it;
/// uncontended on the single host thread.
pub(super) native_timers: Arc<Mutex<TimerWheel>>,
}
impl WasmScheduler {
/// Create a scheduler around the VM-global registries used by module loading
/// and native import resolution.
#[must_use]
pub fn new(
atom_table: Arc<AtomTable>,
module_registry: Arc<ModuleRegistry>,
bif_registry: Arc<BifRegistryImpl>,
) -> Self {
Self {
atom_table,
module_registry,
bif_registry,
next_pid: 1,
processes: BTreeMap::new(),
ready: ReadyQueues::default(),
waiting: BTreeSet::new(),
exit_reasons: BTreeMap::new(),
exit_results: BTreeMap::new(),
exit_errors: BTreeMap::new(),
next_timer_id: 1,
pending_timer_schedules: Vec::new(),
pending_timer_cancellations: Vec::new(),
async_results: BTreeMap::new(),
wasm_async_nif_facility: None,
shared_next_pid: Arc::new(Mutex::new(1)),
native_exit_reasons: BTreeMap::new(),
native_timers: Arc::new(Mutex::new(TimerWheel::new())),
}
}
/// Access the atom table backing this scheduler.
#[must_use]
pub fn atom_table(&self) -> &Arc<AtomTable> {
&self.atom_table
}
/// Access the module registry backing this scheduler.
#[must_use]
pub fn module_registry(&self) -> &Arc<ModuleRegistry> {
&self.module_registry
}
/// Access the BIF registry backing this scheduler.
#[must_use]
pub fn bif_registry(&self) -> &Arc<BifRegistryImpl> {
&self.bif_registry
}
/// Install the single-threaded host bridge used by WASM async NIF stubs.
pub fn set_wasm_async_nif_facility(&mut self, facility: Option<Rc<dyn WasmAsyncNifFacility>>) {
self.wasm_async_nif_facility = facility;
}
/// Drain receive timers that the host must schedule with `setTimeout`.
pub fn take_pending_timer_schedules(&mut self) -> Vec<WasmScheduledTimer> {
std::mem::take(&mut self.pending_timer_schedules)
}
/// Drain receive timers that the host must cancel with `clearTimeout`.
pub fn take_pending_timer_cancellations(&mut self) -> Vec<u64> {
std::mem::take(&mut self.pending_timer_cancellations)
}
/// Expire a host timer callback if it still matches the waiting process.
pub fn timer_fired(&mut self, pid: u64, timer_id: u64) -> bool {
let Some(process) = self.processes.get_mut(&pid) else {
return false;
};
if process.receive_timer_ref() != Some(timer_id) {
return false;
}
process.set_receive_timer_ref(None);
if let Some(position) = process
.receive_timeout()
.map(|timeout| timeout.timeout_position)
{
process.set_code_position(Some(position));
}
self.wake(pid)
}
/// Record an async NIF completion and wake the suspended process.
///
/// The bytecode async-NIF path stores the completion in `async_results`,
/// where the next bytecode slice injects it into `x(0)` and advances past the
/// NIF (see `WasmScheduler::apply_async_completion`). A NATIVE process has
/// no `x(0)`/instruction pointer, so for a native target the completion is
/// delivered as a mailbox message instead — `{ok, Value}` on success or
/// `{error, Reason}` on rejection — which the parked handler reads via
/// [`NativeContext::recv`](crate::native::native_process::NativeContext::recv)
/// when it resumes (WR-7). Both paths share the same pid-keyed `wake`.
pub fn complete_async(&mut self, pid: u64, completion: WasmAsyncCompletion) -> bool {
let Some(process) = self.processes.get(&pid) else {
return false;
};
if process.is_native() {
return self.deliver_native_async_completion(pid, completion);
}
self.async_results.insert(pid, completion);
self.wake(pid)
}
/// Spawn a process at an exported module/function/arity entrypoint.
pub fn spawn(
&mut self,
entry_module: Atom,
entry_function: Atom,
args: Vec<Term>,
) -> Result<u64, ExecError> {
self.spawn_in(NamespaceId::DEFAULT, entry_module, entry_function, args)
}
/// Spawn a process with arguments held in owned detached storage.
pub fn spawn_owned(
&mut self,
entry_module: Atom,
entry_function: Atom,
args: Vec<OwnedTerm>,
) -> Result<u64, ExecError> {
self.spawn_in_owned(NamespaceId::DEFAULT, entry_module, entry_function, args)
}
/// Spawn a process in a namespace. WASM is single-node and currently only
/// supports the default namespace.
pub fn spawn_in(
&mut self,
namespace: NamespaceId,
entry_module: Atom,
entry_function: Atom,
args: Vec<Term>,
) -> Result<u64, ExecError> {
if namespace != NamespaceId::DEFAULT {
return Err(ExecError::Badarg);
}
let arity = u8::try_from(args.len()).map_err(|_| ExecError::Badarg)?;
let entry = self
.module_registry
.lookup_mfa(entry_module, entry_function, arity)?;
let instruction_pointer = entry.module.label_ip(entry.label)?;
let pid = self.next_pid;
self.next_pid = self.next_pid.saturating_add(1);
let mut process = Process::with_capabilities(pid, DEFAULT_HEAP_SIZE, CapabilitySet::all());
process.set_group_leader(Term::pid(pid));
process.set_priority(Priority::Normal);
process.set_namespace_id(namespace);
process.set_code_position(Some(CodePosition {
module: entry_module,
instruction_pointer,
}));
process.set_current_module(entry.module);
for (index, arg) in args.into_iter().enumerate().take(1024) {
if let Ok(register) = u16::try_from(index) {
process.set_x_reg(register, arg);
}
}
self.ready.push(pid, process.priority());
self.processes.insert(pid, process);
Ok(pid)
}
/// Spawn a process in a namespace with arguments copied from owned storage
/// into the new process heap.
pub fn spawn_in_owned(
&mut self,
namespace: NamespaceId,
entry_module: Atom,
entry_function: Atom,
args: Vec<OwnedTerm>,
) -> Result<u64, ExecError> {
if namespace != NamespaceId::DEFAULT {
return Err(ExecError::Badarg);
}
let arity = u8::try_from(args.len()).map_err(|_| ExecError::Badarg)?;
let entry = self
.module_registry
.lookup_mfa(entry_module, entry_function, arity)?;
let instruction_pointer = entry.module.label_ip(entry.label)?;
let pid = self.next_pid;
self.next_pid = self.next_pid.saturating_add(1);
let mut process = Process::with_capabilities(pid, DEFAULT_HEAP_SIZE, CapabilitySet::all());
process.set_group_leader(Term::pid(pid));
process.set_priority(Priority::Normal);
process.set_namespace_id(namespace);
process.set_code_position(Some(CodePosition {
module: entry_module,
instruction_pointer,
}));
process.set_current_module(entry.module);
for (index, arg) in args.iter().enumerate().take(1024) {
if let Ok(register) = u16::try_from(index) {
let copied = arg
.copy_to_heap(process.heap_mut())
.map_err(|_| ExecError::Badarg)?;
process.set_x_reg(register, copied);
}
}
self.ready.push(pid, process.priority());
self.processes.insert(pid, process);
Ok(pid)
}
/// Wake a previously waiting process so it can be run by a later host tick.
pub fn wake(&mut self, pid: u64) -> bool {
if !self.waiting.remove(&pid) {
return false;
}
let Some(process) = self.processes.get_mut(&pid) else {
return false;
};
if process.transition_to(ProcessStatus::Running).is_err() {
return false;
}
self.ready.push(pid, process.priority());
true
}
/// Deliver an immediate message to a local process and wake it if it was blocked.
pub fn send(&mut self, pid: u64, message: Term) -> bool {
self.enqueue_owned_message(pid, message)
}
/// Deliver an owned host term to a local process and wake it if it was blocked.
///
/// Boxed values are first copied into the receiver's heap, preserving the
/// normal mailbox ownership contract for messages entering from JavaScript.
pub fn send_owned(&mut self, pid: u64, message: &OwnedTerm) -> Result<(), ExecError> {
let Some(process) = self.processes.get_mut(&pid) else {
return Err(ExecError::Badarg);
};
let sender = process.mailbox().sender();
sender
.send(message.root(), process.heap_mut())
.map_err(send_error_to_exec)?;
self.after_successful_enqueue(pid);
Ok(())
}
fn enqueue_owned_message(&mut self, pid: u64, message: Term) -> bool {
let Some(_process) = self.processes.get(&pid) else {
return false;
};
self.enqueue_copied_message(pid, message);
true
}
fn enqueue_copied_message(&mut self, pid: u64, message: Term) {
if let Some(process) = self.processes.get_mut(&pid) {
process.mailbox_mut().push_owned(message);
}
self.after_successful_enqueue(pid);
}
pub(super) fn after_successful_enqueue(&mut self, pid: u64) {
if let Some(process) = self.processes.get_mut(&pid)
&& let Some(timer_id) = process.receive_timer_ref()
{
process.set_receive_timer_ref(None);
self.pending_timer_cancellations.push(timer_id);
}
if self.waiting.contains(&pid) {
let _woken = self.wake(pid);
}
}
/// Drain native `Deliver` timers that expired by wall-clock now, delivering
/// each timer's message to its target mailbox and waking the target.
///
/// Returns the pids woken by an expiring timer. This is the host-facing
/// entry point; [`WasmScheduler::run_until_idle`] calls it at the start of
/// every turn so a parked native actor whose self-tick has come due is
/// runnable in the same turn. The deterministic counterpart used by tests
/// (and the seam a browser host drives with a `performance.now()`-derived
/// instant) is [`WasmScheduler::tick_native_timers_at`].
///
/// When no native timers are pending this returns immediately WITHOUT
/// reading the wall clock, an early-out that predates the `web_time` clock
/// base. The clock the wheel reads when timers ARE pending is
/// `web_time::Instant::now()` (WR-10), which is `performance.now()`-backed on
/// `wasm32-unknown-unknown` and a re-export of `std::time::Instant::now()` on
/// native — so this no longer panics in the browser when a timer is armed.
pub fn tick_native_timers(&mut self) -> Vec<u64> {
let expired = {
let mut wheel = lock_timers(&self.native_timers);
if wheel.is_empty() {
return Vec::new();
}
wheel.tick()
};
self.deliver_expired_native_timers(expired)
}
/// Deterministic variant of [`WasmScheduler::tick_native_timers`]: expire
/// every native `Deliver` timer due at `now` and deliver it.
///
/// Tests drive the cooperative timer path through this seam — schedule a
/// self-tick from a native handler, advance `now` past the delay, and the
/// rescheduled actor receives the delivered message — with no browser and no
/// wall-clock dependency, exactly as the threaded `expire_timers_for_test`
/// seam does for the threaded scheduler.
pub fn tick_native_timers_at(&mut self, now: web_time::Instant) -> Vec<u64> {
let expired = lock_timers(&self.native_timers).tick_at(now);
self.deliver_expired_native_timers(expired)
}
/// Route a drained set of expired timers: `Deliver` timers push their
/// message into the target mailbox and wake it; `ReceiveTimeout` timers are
/// never produced by the native path (it only schedules `Deliver`) and are
/// ignored defensively. Returns the woken pids.
fn deliver_expired_native_timers(
&mut self,
expired: Vec<crate::timer::ExpiredTimer>,
) -> Vec<u64> {
let mut woken = Vec::new();
for timer in expired {
if timer.kind != crate::timer::TimerKind::Deliver {
continue;
}
let pid = timer.target_pid;
let Some(process) = self.processes.get_mut(&pid) else {
continue;
};
process.mailbox_mut().push_owned(timer.message);
self.after_successful_enqueue(pid);
woken.push(pid);
}
woken
}
/// Execute at most one ready-queue snapshot. Processes that yield are
/// requeued for the next host-driven turn, preserving cooperative fairness.
pub fn run_until_idle(&mut self) -> WasmRunSummary {
// WR-4: expire any native `Deliver` timers due now so a parked actor
// whose self-tick has come due is runnable within this same turn.
let _woken = self.tick_native_timers();
let mut summary = WasmRunSummary::default();
let budget = self.ready.len();
let mut yielded_next_tick = Vec::new();
for _ in 0..budget {
let Some(pid) = self.ready.pop() else {
break;
};
if self.waiting.contains(&pid) {
continue;
}
let Some(mut process) = self.processes.remove(&pid) else {
continue;
};
let priority = process.priority();
if !matches!(process.status(), ProcessStatus::Running) {
let _transition = process.transition_to(ProcessStatus::Running);
}
// WR-3: native processes are driven by the cooperative native slice
// in the same turn as bytecode, branching on `is_native()` the way
// the threaded `core::execute_slice` does. Native bodies carry no
// bytecode module, so they must be dispatched before the
// async-completion / current-module bytecode path below.
if process.is_native() {
self.dispatch_native_in_turn(
pid,
priority,
process,
&mut summary,
&mut yielded_next_tick,
);
continue;
}
if let Some(reason) = self.apply_async_completion(&mut process) {
let x0 = process.x_reg(0);
let _transition = process.transition_to(ProcessStatus::Exited(reason));
self.exit_reasons.insert(pid, reason);
self.exit_results
.insert(pid, super::exit_capture::capture_term(x0));
summary.exited.push(pid);
continue;
}
process.reset_reductions(crate::scheduler::DEFAULT_REDUCTION_BUDGET);
let Some(module) = process.current_module().cloned() else {
self.exit_errors
.insert(pid, ExecError::InvalidOperand("current module"));
summary.errored.push(pid);
continue;
};
let services = self.native_services();
let result = run_with_native_services(
&mut process,
module.as_ref(),
self.module_registry.as_ref(),
&services,
);
summary.executed += 1;
match result {
Ok(ExecutionResult::Yielded) => {
let _transition = process.transition_to(ProcessStatus::Yielded);
self.processes.insert(pid, process);
yielded_next_tick.push((pid, priority));
summary.yielded.push(pid);
}
Ok(ExecutionResult::Waiting) => {
let _transition = process.transition_to(ProcessStatus::Waiting);
self.register_receive_timer(&mut process);
self.processes.insert(pid, process);
self.waiting.insert(pid);
summary.waiting.push(pid);
}
Ok(ExecutionResult::Exited(reason)) => {
let x0 = process.x_reg(0);
let _transition = process.transition_to(ProcessStatus::Exited(reason));
self.exit_reasons.insert(pid, reason);
// Deep-copy while the process heap is still alive; the
// process is dropped at the end of this scope.
self.exit_results
.insert(pid, super::exit_capture::capture_term(x0));
summary.exited.push(pid);
}
Ok(ExecutionResult::DirtyCall { .. }) => {
self.exit_errors.insert(
pid,
ExecError::UnsupportedOpcode {
name: "dirty native call on wasm",
},
);
summary.errored.push(pid);
}
Err(error) => {
self.exit_errors.insert(pid, error);
summary.errored.push(pid);
}
}
}
for (pid, priority) in yielded_next_tick {
self.ready.push(pid, priority);
}
summary
}
/// Return a process exit result captured from x(0), if available.
///
/// The result is an owning deep copy that outlives the exited process.
#[must_use]
pub fn take_exit_result(&mut self, pid: u64) -> Option<OwnedTerm> {
self.exit_results.remove(&pid)
}
/// Return all currently recorded exit results without consuming them.
///
/// The returned terms borrow storage owned by this scheduler; they stay
/// valid until the corresponding entry is removed via `take_exit_result`.
#[must_use]
pub fn exit_results(&self) -> Vec<(u64, Term)> {
self.exit_results
.iter()
.map(|(pid, owned)| (*pid, owned.root()))
.collect()
}
/// Allocate the next pid from the shared counter used by both the native
/// root spawn and the cooperative spawn facility.
pub(super) fn alloc_pid(&self) -> u64 {
let mut guard = self
.shared_next_pid
.lock()
.unwrap_or_else(|error| error.into_inner());
let pid = *guard;
*guard = guard.saturating_add(1);
pid
}
/// Total number of ready-queued processes across all priorities.
pub(super) fn ready_len(&self) -> usize {
self.ready.len()
}
/// Whether the scheduler still has work that a host pump can make progress
/// on by continuing to drive turns: a process is ready to run, or a native
/// `Deliver` timer is armed (a later tick will deliver its message and wake
/// the target).
///
/// This is the WR-10 host-pump idle predicate. It deliberately does NOT
/// count processes parked in `waiting` with no armed timer: those are blocked
/// on an external event (an inbound `send`/`cast`, a `timer_fired`, or an
/// async completion) that the host delivers, each of which re-enqueues the
/// process and is the host's cue to pump again — so a pump loop that yielded
/// the browser on `!has_pending_work()` is correctly restarted by those
/// entry points, not by spinning `requestAnimationFrame` while idle.
#[must_use]
pub fn has_pending_work(&self) -> bool {
if self.ready.len() != 0 {
return true;
}
!lock_timers(&self.native_timers).is_empty()
}
/// Record a cooperative native-process exit (reason + captured x(0) result).
pub(super) fn record_native_exit(&mut self, pid: u64, reason: ExitReason, result: OwnedTerm) {
self.native_exit_reasons.insert(pid, reason);
self.exit_results.insert(pid, result);
}
/// Return the exit reason recorded for a cooperative native process, if any.
#[must_use]
pub fn native_exit_reason(&self, pid: u64) -> Option<ExitReason> {
self.native_exit_reasons.get(&pid).copied()
}
fn native_services(&self) -> NativeServices {
NativeServices {
atom_table: Some(Arc::clone(&self.atom_table)),
wasm_async_nif_facility: self.wasm_async_nif_facility.clone(),
..NativeServices::default()
}
}
pub(super) fn register_receive_timer(&mut self, process: &mut Process) {
let Some(timeout) = process.receive_timeout() else {
return;
};
if process.receive_timer_ref().is_some() {
return;
}
let timer_id = self.next_timer_id;
self.next_timer_id = self.next_timer_id.saturating_add(1);
process.set_receive_timer_ref(Some(timer_id));
self.pending_timer_schedules.push(WasmScheduledTimer {
pid: process.pid(),
timer_id,
milliseconds: timeout.milliseconds,
});
}
pub(super) fn apply_async_completion(&mut self, process: &mut Process) -> Option<ExitReason> {
let completion = self.async_results.remove(&process.pid())?;
match completion {
WasmAsyncCompletion::Ok(term) => {
let result = term
.copy_to_heap(process.heap_mut())
.unwrap_or_else(|_| Term::atom(Atom::BADARG));
process.set_x_reg(0, result);
advance_past_current_instruction(process);
None
}
WasmAsyncCompletion::Error(term) => {
let result = term
.copy_to_heap(process.heap_mut())
.unwrap_or_else(|_| Term::atom(Atom::BADARG));
process.set_x_reg(0, result);
Some(ExitReason::Error)
}
}
}
}
/// Lock the native timer wheel, recovering from poisoning (which cannot occur
/// without a panic across the uncontended single-threaded lock, but must be
/// handled to keep the cooperative path panic-free).
fn lock_timers(timers: &Mutex<TimerWheel>) -> std::sync::MutexGuard<'_, TimerWheel> {
timers
.lock()
.unwrap_or_else(std::sync::PoisonError::into_inner)
}
fn send_error_to_exec(error: SendError) -> ExecError {
match error {
SendError::HeapFull(error) => ExecError::from(error),
SendError::InvalidBoxedTerm => ExecError::Badarg,
}
}
fn advance_past_current_instruction(process: &mut Process) {
if let Some(position) = process.code_position() {
process.set_code_position(Some(CodePosition {
module: position.module,
instruction_pointer: position.instruction_pointer.saturating_add(1),
}));
}
}
#[derive(Default)]
pub(super) struct ReadyQueues {
max: VecDeque<u64>,
high: VecDeque<u64>,
normal: VecDeque<u64>,
low: VecDeque<u64>,
}
impl ReadyQueues {
pub(super) fn push(&mut self, pid: u64, priority: Priority) {
match priority {
Priority::Max => self.max.push_back(pid),
Priority::High => self.high.push_back(pid),
Priority::Normal => self.normal.push_back(pid),
Priority::Low => self.low.push_back(pid),
}
}
pub(super) fn pop(&mut self) -> Option<u64> {
self.max
.pop_front()
.or_else(|| self.high.pop_front())
.or_else(|| self.normal.pop_front())
.or_else(|| self.low.pop_front())
}
pub(super) fn len(&self) -> usize {
self.max.len() + self.high.len() + self.normal.len() + self.low.len()
}
}
#[cfg(test)]
#[path = "wasm_tests.rs"]
mod tests;