1use std::sync::atomic::{AtomicBool, AtomicU64, Ordering};
2use std::sync::{Arc, Condvar, Mutex};
3use std::thread::JoinHandle;
4
5use crate::bytecode::{Cap, CapRights, CapTarget, Chunk, NativeMask, Value};
6use crate::vm::{NativeGate, NativeTable, Vm};
7
8use super::directory::Directory;
9use super::error::SpawnError;
10use super::finalize::finalize_flow;
11use super::handle::FlowHandle;
12use super::mailbox::{Delivery, Mailbox, MailboxConfig, MailboxFullReason};
13use super::metrics::{RuntimeMetrics, RuntimeMetricsSnapshot};
14use super::monitor::FlowExitReason;
15use super::process::{Flow, FlowId, FlowOutcome};
16use super::runqueue::{Injector, Stealer, Worker as LocalDeque};
17use super::supervisor::SupervisorLink;
18use super::timer::TimerWheel;
19use super::worker;
20use crate::bytecode::RestartPolicy;
21
22pub const DEFAULT_QUANTUM: u32 = 10_000;
30
31#[derive(Clone, Debug)]
34pub struct RuntimeConfig {
35 pub workers: usize,
40 pub quantum: u32,
43 pub mailbox: MailboxConfig,
47 pub max_flows: u32,
50 pub max_ask_waits: u32,
55 pub max_host_awaits: u32,
58 pub max_links: u32,
63 pub max_monitors: u32,
67 pub max_registry_names: u32,
71 pub host_await: Option<Arc<dyn super::host_await::HostAwaitBridge>>,
74 pub max_runtime_bytes: usize,
79 pub trust: crate::bytecode::TrustLevel,
82 pub paranoid_jumps: bool,
87 pub output: Arc<dyn crate::OutputSink>,
90 pub quota: super::quota::QuotaConfig,
92 #[cfg(feature = "jit")]
94 pub jit: JitConfig,
95}
96
97#[cfg(feature = "jit")]
99#[derive(Clone, Debug)]
100pub struct JitConfig {
101 pub enabled: bool,
103 pub hot_threshold: u32,
105}
106
107#[cfg(feature = "jit")]
108impl Default for JitConfig {
109 fn default() -> Self {
110 JitConfig {
111 enabled: false,
112 hot_threshold: crate::jit::HOT_THRESHOLD,
113 }
114 }
115}
116
117fn default_worker_count() -> usize {
119 match std::thread::available_parallelism() {
120 Ok(n) => n.get().max(1),
121 Err(_) => 1,
122 }
123}
124
125impl Default for RuntimeConfig {
126 fn default() -> Self {
127 RuntimeConfig {
128 workers: default_worker_count(),
129 quantum: DEFAULT_QUANTUM,
130 mailbox: MailboxConfig::DEFAULT,
131 max_flows: 0,
132 max_ask_waits: 0,
133 max_host_awaits: 0,
134 max_links: 0,
135 max_monitors: 0,
136 max_registry_names: 0,
137 host_await: None,
138 max_runtime_bytes: 256 * 1024 * 1024,
139 trust: crate::bytecode::TrustLevel::Untrusted,
140 paranoid_jumps: false,
141 output: Arc::new(crate::output::NullSink),
142 quota: super::quota::QuotaConfig::default(),
143 #[cfg(feature = "jit")]
144 jit: JitConfig::default(),
145 }
146 }
147}
148
149impl RuntimeConfig {
150 pub fn sandbox() -> Self {
155 RuntimeConfig {
156 quota: super::quota::QuotaConfig::sandbox(),
157 max_flows: 256,
158 max_ask_waits: 128,
159 max_host_awaits: 128,
160 max_links: 1024,
161 max_monitors: 1024,
162 max_registry_names: 256,
163 max_runtime_bytes: 64 * 1024 * 1024,
164 paranoid_jumps: true,
165 ..Default::default()
166 }
167 }
168}
169
170pub struct Shared {
177 pub(crate) injector: Injector<Box<Flow>>,
178 pub(crate) stealers: Vec<Stealer<Box<Flow>>>,
179 pub(crate) directory: Directory,
181 pub(crate) caps: super::capability::CapTable,
183 pub(crate) timer: Arc<TimerWheel>,
184 pub(crate) notify: (Mutex<()>, Condvar),
185 pub(crate) metrics: RuntimeMetrics,
186 pub(crate) shutdown: AtomicBool,
187 pub(crate) quantum: u32,
188 pub(crate) mailbox: MailboxConfig,
189 pub(crate) flow_limit: super::flow_limit::FlowLimit,
191 pub(crate) memory: Arc<crate::MemoryBudget>,
192 pub(crate) quota: super::quota::QuotaConfig,
193 pub(crate) quotas: super::quota::QuotaTable,
194 pub(crate) monitors: super::monitor::MonitorStore,
195 pub(crate) links: super::link::LinkStore,
196 pub(crate) registry: super::registry::RegistryStore,
197 pub(crate) kill_signals: super::finalize::KillSignals,
198 pub(crate) trap_exits: super::finalize::TrapExitFlags,
199 pub(crate) waiting_send_at: super::finalize::WaitingSendIndex,
200 pub(crate) ask_waits: super::finalize::AskWaitIndex,
201 pub(crate) host_awaits: super::host_await::HostAwaitIndex,
203 pub(crate) host_await_bridge: Option<Arc<dyn super::host_await::HostAwaitBridge>>,
205 pub(crate) host_next_request_id: AtomicU64,
208 pub(crate) paranoid_jumps: bool,
210 #[cfg(feature = "jit")]
212 pub(crate) jit: Option<std::sync::Arc<crate::jit::JitRuntime>>,
213}
214
215pub struct Runtime {
226 shared: Arc<Shared>,
227 chunk: Arc<Chunk>,
228 natives: Arc<NativeTable>,
229 workers: Vec<JoinHandle<()>>,
230 timer_thread: Option<JoinHandle<()>>,
231 trust: crate::bytecode::TrustLevel,
232}
233
234impl Runtime {
235 pub fn new(chunk: Chunk) -> Result<Self, SpawnError> {
243 Self::with_config(chunk, RuntimeConfig::default())
244 }
245
246 pub fn with_natives(chunk: Chunk, natives: Arc<NativeTable>) -> Result<Self, SpawnError> {
249 Self::with_natives_and_config(chunk, natives, RuntimeConfig::default())
250 }
251
252 pub fn with_config(chunk: Chunk, config: RuntimeConfig) -> Result<Self, SpawnError> {
253 Self::with_natives_and_config(chunk, NativeTable::empty(), config)
254 }
255
256 pub fn with_attested(
262 bytes: &[u8],
263 expected_digest: [u8; 32],
264 natives: Arc<NativeTable>,
265 config: RuntimeConfig,
266 ) -> Result<Self, SpawnError> {
267 let chunk = crate::decode_attested(bytes, &expected_digest)
268 .map_err(SpawnError::Attestation)?;
269 Self::with_natives_and_config(chunk, natives, config)
270 }
271
272 pub fn with_std_natives_and_config(
275 chunk: Chunk,
276 config: RuntimeConfig,
277 ) -> Result<Self, SpawnError> {
278 Self::with_natives_and_config(
279 chunk,
280 crate::std_native_table_with(Arc::clone(&config.output)),
281 config,
282 )
283 }
284
285 pub fn with_natives_and_config(
295 chunk: Chunk,
296 natives: Arc<NativeTable>,
297 config: RuntimeConfig,
298 ) -> Result<Self, SpawnError> {
299 crate::bytecode::verify_with(
300 &chunk,
301 crate::bytecode::VerifyConfig {
302 trust: config.trust,
303 },
304 )
305 .map_err(SpawnError::VerifyFailed)?;
306 let chunk = Arc::new(chunk);
307 let workers_n = config.workers.max(1);
308
309 let locals: Vec<LocalDeque<Box<Flow>>> =
310 (0..workers_n).map(|_| LocalDeque::new_fifo()).collect();
311 let stealers: Vec<Stealer<Box<Flow>>> = locals.iter().map(|l| l.stealer()).collect();
312
313 #[cfg(feature = "jit")]
314 let jit = if config.jit.enabled {
315 Some(super::jit::new_runtime(
316 chunk.clone(),
317 config.jit.hot_threshold,
318 ))
319 } else {
320 None
321 };
322
323 let paranoid_jumps = config.paranoid_jumps
324 || matches!(
325 config.trust,
326 crate::bytecode::TrustLevel::Untrusted
327 );
328
329 let shared = Arc::new(Shared {
330 injector: Injector::new(),
331 stealers,
332 directory: Directory::new(),
333 caps: super::capability::CapTable::new(),
334 timer: TimerWheel::new(),
335 notify: (Mutex::new(()), Condvar::new()),
336 metrics: RuntimeMetrics::default(),
337 shutdown: AtomicBool::new(false),
338 quantum: config.quantum,
339 mailbox: config.mailbox,
340 flow_limit: super::flow_limit::FlowLimit::new(config.max_flows),
341 memory: Arc::new(crate::MemoryBudget::new(config.max_runtime_bytes)),
342 quota: config.quota,
343 quotas: super::quota::QuotaTable::new(),
344 monitors: super::monitor::MonitorStore::new(config.max_monitors),
345 links: super::link::LinkStore::new(config.max_links),
346 registry: super::registry::RegistryStore::new(config.max_registry_names),
347 kill_signals: super::finalize::KillSignals::new(),
348 trap_exits: super::finalize::TrapExitFlags::new(),
349 waiting_send_at: super::finalize::WaitingSendIndex::new(),
350 ask_waits: super::finalize::AskWaitIndex::new(config.max_ask_waits),
351 host_awaits: super::host_await::HostAwaitIndex::new(config.max_host_awaits),
352 host_await_bridge: config.host_await.clone(),
353 host_next_request_id: AtomicU64::new(1),
354 paranoid_jumps,
355 #[cfg(feature = "jit")]
356 jit,
357 });
358
359 let mut workers = Vec::with_capacity(workers_n);
360 for local in locals {
361 let shared_w = shared.clone();
362 match std::thread::Builder::new()
363 .name("byteflow-worker".into())
364 .spawn(move || worker::run_worker(shared_w, local))
365 {
366 Ok(handle) => workers.push(handle),
367 Err(e) => {
368 abort_startup(&shared, workers, None);
369 return Err(SpawnError::ThreadSpawnFailed(e.to_string()));
370 }
371 }
372 }
373
374 let shared_timer = shared.clone();
375 let timer_thread = match std::thread::Builder::new()
376 .name("byteflow-timer".into())
377 .spawn(move || shared_timer.timer.clone().drive(&shared_timer))
378 {
379 Ok(handle) => handle,
380 Err(e) => {
381 abort_startup(&shared, workers, None);
382 return Err(SpawnError::ThreadSpawnFailed(e.to_string()));
383 }
384 };
385
386 Ok(Runtime {
387 shared,
388 chunk,
389 natives,
390 workers,
391 timer_thread: Some(timer_thread),
392 trust: config.trust,
393 })
394 }
395
396 pub fn spawn(&self, function: u32, args: &[Value]) -> Result<FlowHandle, SpawnError> {
401 spawn_on(
402 &self.shared,
403 &self.chunk,
404 &self.natives,
405 function,
406 args,
407 RestartPolicy::Never,
408 None,
409 None,
410 None,
411 )
412 }
413
414 pub fn spawner(&self) -> RuntimeSpawner {
418 RuntimeSpawner {
419 shared: self.shared.clone(),
420 chunk: self.chunk.clone(),
421 natives: self.natives.clone(),
422 }
423 }
424
425 pub fn supervisor(&self) -> Result<super::supervisor::Supervisor, SpawnError> {
428 super::supervisor::Supervisor::new(self.spawner())
429 }
430
431 pub fn function_index(&self, name: &str) -> Option<u32> {
435 self.chunk
436 .functions
437 .iter()
438 .position(|f| f.name == name)
439 .map(|i| i as u32)
440 }
441
442 pub fn metrics(&self) -> RuntimeMetricsSnapshot {
443 self.shared.metrics.snapshot()
444 }
445
446 pub fn live_flows(&self) -> usize {
452 self.shared.directory.len()
453 }
454
455 pub fn memory_snapshot(&self) -> crate::MemorySnapshot {
457 self.shared.memory.snapshot()
458 }
459
460 pub fn worker_count(&self) -> usize {
461 self.workers.len()
462 }
463
464 pub fn send(&self, target: FlowId, message: Value) -> Result<(), SendError> {
477 let Some(msg) = message.as_message().cloned() else {
478 return Err(SendError::NotAHop {
479 got: message.type_name(),
480 });
481 };
482 let mailbox = match self.shared.directory.lookup(target) {
483 Ok(Some(m)) => m,
484 Ok(None) => return Err(SendError::NoSuchFlow(target)),
485 Err(e) => {
486 super::error::report_fault(e);
487 return Err(SendError::Unavailable);
488 }
489 };
490 let stamped = match worker::authenticate_host_outgoing_message(&self.shared, target, msg) {
491 Ok(m) => Value::Message(m),
492 Err(_) => return Err(SendError::Capability),
493 };
494 match mailbox.push(stamped.clone()) {
495 Ok(Ok(Delivery::Queued | Delivery::QueuedDropOldest | Delivery::DroppedNewest)) => {
500 Ok(())
501 }
502 Ok(Ok(Delivery::Handoff(flow))) => {
503 let _ = self.shared.ask_waits.remove_asker(flow.id);
504 match flow.last_receive_dest {
505 Some(dest) => {
506 let Some(flow) =
507 super::finalize::resume_or_fail(&self.shared, flow, dest, stamped)
508 else {
509 return Err(SendError::Unavailable);
510 };
511 self.shared.injector.push(flow);
512 wake_workers(&self.shared);
513 Ok(())
514 }
515 None => {
516 super::error::report_fault(super::error::RuntimeError::PoisonedLock(
517 "Runtime::send handoff missing dest register",
518 ));
519 finalize_flow(
520 &self.shared,
521 *flow,
522 FlowOutcome::Failed("handoff missing dest register".into()),
523 FlowExitReason::Fault,
524 );
525 Err(SendError::Unavailable)
526 }
527 }
528 }
529 Ok(Err(full)) => {
530 if full.reason() == MailboxFullReason::Closed {
531 return Err(SendError::NoSuchFlow(target));
532 }
533 Err(SendError::MailboxFull {
534 flow: target,
535 reason: full.reason(),
536 })
537 }
538 Err(e) => {
539 super::error::report_fault(e);
540 Err(SendError::Unavailable)
541 }
542 }
543 }
544
545 fn require_live(&self, id: FlowId) -> Result<(), super::error::LifecycleError> {
546 match self.shared.directory.lookup(id) {
547 Ok(Some(_)) => Ok(()),
548 Ok(None) => Err(super::error::LifecycleError::NoSuchFlow(id)),
549 Err(e) => Err(self.unavailable(e)),
550 }
551 }
552
553 fn unavailable(&self, err: super::error::RuntimeError) -> super::error::LifecycleError {
554 super::error::report_fault(err);
555 super::error::LifecycleError::Unavailable
556 }
557
558 pub fn mint_cap(
561 &self,
562 flow: FlowId,
563 ) -> Result<crate::bytecode::CapId, super::error::LifecycleError> {
564 self.require_live(flow)?;
565 self.shared
566 .caps
567 .mint(flow, flow, super::capability::CapRights::ADDRESSING)
568 .map_err(|e| self.unavailable(e))
569 }
570
571 pub fn grant_cap(
573 &self,
574 holder: FlowId,
575 target: FlowId,
576 ) -> Result<crate::bytecode::CapId, super::error::LifecycleError> {
577 self.require_live(holder)?;
578 self.require_live(target)?;
579 self.shared
580 .caps
581 .mint(holder, target, super::capability::CapRights::ADDRESSING)
582 .map_err(|e| self.unavailable(e))
583 }
584
585 pub fn monitor(
589 &self,
590 owner: FlowId,
591 target: FlowId,
592 ) -> Result<super::monitor::MonitorRef, super::error::LifecycleError> {
593 if owner == target {
594 return Err(super::error::LifecycleError::SelfRelation);
595 }
596 self.require_live(owner)?;
597 self.require_live(target)?;
598 let mon = self
599 .shared
600 .monitors
601 .create(owner, target)
602 .map_err(|e| self.unavailable(e))??;
603 if self.require_live(target).is_err() {
606 let _ = self.shared.monitors.remove_owned(owner, mon);
607 super::finalize::deliver_down(
608 &self.shared,
609 super::monitor::DownEvent {
610 monitor: mon,
611 owner,
612 target,
613 reason: super::monitor::FlowExitReason::Fault,
614 },
615 );
616 }
617 Ok(mon)
618 }
619
620 pub fn demonitor(
622 &self,
623 owner: FlowId,
624 monitor: super::monitor::MonitorRef,
625 ) -> Result<(), super::error::LifecycleError> {
626 self.require_live(owner)?;
627 match self.shared.monitors.remove_owned(owner, monitor) {
628 Ok(inner) => inner,
629 Err(e) => Err(self.unavailable(e)),
630 }
631 }
632
633 pub fn link(
638 &self,
639 a: FlowId,
640 b: FlowId,
641 ) -> Result<super::link::LinkId, super::error::LifecycleError> {
642 if a == b {
643 return Err(super::error::LifecycleError::SelfRelation);
644 }
645 self.require_live(a)?;
646 self.require_live(b)?;
647 match self.shared.links.link_if_live(a, b, |id| {
648 self.shared.directory.lookup(id).map(|m| m.is_some())
649 }) {
650 Ok(inner) => inner,
651 Err(e) => Err(self.unavailable(e)),
652 }
653 }
654
655 pub fn set_trap_exit(
660 &self,
661 id: FlowId,
662 enabled: bool,
663 ) -> Result<(), super::error::LifecycleError> {
664 self.require_live(id)?;
665 self.shared
666 .trap_exits
667 .set(id, enabled)
668 .map_err(|e| self.unavailable(e))
669 }
670
671 pub fn unlink(
673 &self,
674 owner: FlowId,
675 link: super::link::LinkId,
676 ) -> Result<(), super::error::LifecycleError> {
677 self.require_live(owner)?;
678 match self.shared.links.unlink_owned(owner, link) {
679 Ok(inner) => inner,
680 Err(e) => Err(self.unavailable(e)),
681 }
682 }
683
684 pub fn register_name(
686 &self,
687 name: &str,
688 cap: crate::bytecode::CapId,
689 ) -> Result<(), super::error::LifecycleError> {
690 let entry = match self.shared.caps.lookup(cap) {
691 Ok(Some(e)) => e,
692 Ok(None) => return Err(super::error::LifecycleError::InvalidCapability),
693 Err(e) => return Err(self.unavailable(e)),
694 };
695 let target = match entry.target() {
696 Some(id) => id,
697 None => return Err(super::error::LifecycleError::InvalidCapability),
698 };
699 self.require_live(target)?;
700 match self
701 .shared
702 .registry
703 .register(super::registry::RegistryName::from(name), cap, target)
704 {
705 Ok(inner) => inner,
706 Err(e) => Err(self.unavailable(e)),
707 }
708 }
709
710 pub fn whereis(
712 &self,
713 name: &str,
714 ) -> Result<Option<crate::bytecode::CapId>, super::error::LifecycleError> {
715 self.shared
716 .registry
717 .whereis(name)
718 .map_err(|e| self.unavailable(e))
719 }
720
721 pub fn kill(&self, id: FlowId) -> Result<(), super::error::LifecycleError> {
724 self.require_live(id)?;
725 super::finalize::request_kill(&self.shared, id, super::monitor::FlowExitReason::Killed);
726 Ok(())
727 }
728
729 pub fn mint_admin_cap(
731 &self,
732 holder: FlowId,
733 ) -> Result<crate::bytecode::CapId, super::error::LifecycleError> {
734 self.require_live(holder)?;
735 let cap = crate::bytecode::Cap::root(
736 crate::bytecode::CapTarget::Scheduler,
737 CapRights::ADMIN,
738 None,
739 self.shared.caps.scheduler_cell().as_ref(),
740 );
741 self.shared
742 .caps
743 .grant(holder, cap)
744 .map_err(|e| self.unavailable(e))
745 }
746
747 pub fn admin_kill(
749 &self,
750 holder: FlowId,
751 cap: crate::bytecode::CapId,
752 target: FlowId,
753 ) -> Result<(), super::error::LifecycleError> {
754 self.require_admin(holder, cap)?;
755 self.kill(target)
756 }
757
758 pub fn admin_top_up_cpu(
760 &self,
761 holder: FlowId,
762 cap: crate::bytecode::CapId,
763 target: FlowId,
764 extra: i64,
765 ) -> Result<(), super::error::LifecycleError> {
766 self.require_admin(holder, cap)?;
767 let quota = match self.shared.quotas.get(target) {
768 Ok(Some(q)) => q,
769 Ok(None) => return Err(super::error::LifecycleError::NoSuchFlow(target)),
770 Err(e) => return Err(self.unavailable(e)),
771 };
772 quota.top_up_cpu(extra);
773 Ok(())
774 }
775
776 pub fn admin_top_up_mem(
778 &self,
779 holder: FlowId,
780 cap: crate::bytecode::CapId,
781 target: FlowId,
782 extra: usize,
783 ) -> Result<(), super::error::LifecycleError> {
784 self.require_admin(holder, cap)?;
785 let quota = match self.shared.quotas.get(target) {
786 Ok(Some(q)) => q,
787 Ok(None) => return Err(super::error::LifecycleError::NoSuchFlow(target)),
788 Err(e) => return Err(self.unavailable(e)),
789 };
790 quota.top_up_mem(extra);
791 Ok(())
792 }
793
794 pub fn admin_top_up_send(
796 &self,
797 holder: FlowId,
798 cap: crate::bytecode::CapId,
799 target: FlowId,
800 extra: i64,
801 ) -> Result<(), super::error::LifecycleError> {
802 self.require_admin(holder, cap)?;
803 let quota = match self.shared.quotas.get(target) {
804 Ok(Some(q)) => q,
805 Ok(None) => return Err(super::error::LifecycleError::NoSuchFlow(target)),
806 Err(e) => return Err(self.unavailable(e)),
807 };
808 quota.top_up_send(extra);
809 Ok(())
810 }
811
812 fn require_admin(
813 &self,
814 holder: FlowId,
815 cap: crate::bytecode::CapId,
816 ) -> Result<(), super::error::LifecycleError> {
817 let entry = match self.shared.caps.resolve(cap, holder, CapRights::ADMIN) {
818 Ok(e) => e,
819 Err(_) => return Err(super::error::LifecycleError::InvalidCapability),
820 };
821 super::link_admin::check_admin(&entry.cap, self.shared.caps.scheduler_cell().as_ref())
822 .map_err(|_| super::error::LifecycleError::InvalidCapability)
823 }
824
825 pub fn unregister_name(&self, name: &str) -> Result<bool, super::error::LifecycleError> {
827 self.shared
828 .registry
829 .unregister(name)
830 .map_err(|e| self.unavailable(e))
831 }
832
833 pub fn reload_chunk(&mut self, chunk: Chunk) -> Result<(), SpawnError> {
837 crate::bytecode::verify_with(&chunk, crate::bytecode::VerifyConfig { trust: self.trust })
838 .map_err(SpawnError::VerifyFailed)?;
839 let chunk = Arc::new(chunk);
840 self.chunk = chunk.clone();
841 #[cfg(feature = "jit")]
842 if let Some(jit) = &self.shared.jit {
843 jit.reload(chunk);
844 }
845 Ok(())
846 }
847
848 fn request_shutdown(&self) {
851 self.shared.shutdown.store(true, Ordering::Release);
852 match self.shared.host_awaits.drain_all() {
855 Ok(parked) => {
856 for p in parked {
857 finalize_flow(
858 &self.shared,
859 *p.flow,
860 FlowOutcome::Failed("runtime shutdown".into()),
861 FlowExitReason::Shutdown,
862 );
863 }
864 }
865 Err(e) => super::error::report_fault(e),
866 }
867 self.shared.timer.shutdown();
868 let (lock, cvar) = &self.shared.notify;
869 match super::sync_lock::lock(lock, "Runtime::request_shutdown") {
870 Ok(_g) => cvar.notify_all(),
871 Err(e) => super::error::report_fault(e),
872 }
873 }
874
875 pub fn shutdown(mut self) {
882 self.request_shutdown();
883 for w in self.workers.drain(..) {
884 let _ = w.join();
885 }
886 if let Some(t) = self.timer_thread.take() {
887 let _ = t.join();
888 }
889 }
890}
891
892impl Drop for Runtime {
893 fn drop(&mut self) {
894 if !self.shared.shutdown.load(Ordering::Acquire) {
895 self.request_shutdown();
896 }
897 }
898}
899
900pub fn flow_id_from_u64(raw: u64) -> FlowId {
904 FlowId(raw)
905}
906
907#[derive(Debug, Clone, PartialEq, Eq)]
909pub enum SendError {
910 NoSuchFlow(FlowId),
911 NotAHop {
913 got: &'static str,
914 },
915 MailboxFull {
919 flow: FlowId,
920 reason: MailboxFullReason,
921 },
922 Capability,
924 Unavailable,
926}
927
928impl std::fmt::Display for SendError {
929 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
930 match self {
931 SendError::NoSuchFlow(id) => write!(f, "no live flow {id}"),
932 SendError::NotAHop { got } => {
933 write!(f, "atomic hop requires Value::Message, got {got}")
934 }
935 SendError::MailboxFull { flow, reason } => {
936 write!(f, "mailbox full for {flow} ({reason})")
937 }
938 SendError::Capability => {
939 write!(f, "host send could not reissue a capability in the hop")
940 }
941 SendError::Unavailable => write!(f, "runtime table unavailable (poisoned lock)"),
942 }
943 }
944}
945
946impl std::error::Error for SendError {}
947
948pub(crate) struct BytecodeSpawn<'a> {
951 pub authority: &'a Cap,
952 pub cell: &'a crate::bytecode::RevocationCell,
953 pub quota: &'a super::quota::FlowQuota,
954 pub requested_rights: CapRights,
955}
956
957#[allow(clippy::too_many_arguments)]
966pub(crate) fn spawn_on(
967 shared: &Arc<Shared>,
968 chunk: &Arc<Chunk>,
969 natives: &Arc<NativeTable>,
970 function: u32,
971 args: &[Value],
972 restart_policy: RestartPolicy,
973 supervisor: Option<SupervisorLink>,
974 parent: Option<FlowId>,
975 bytecode: Option<BytecodeSpawn<'_>>,
976) -> Result<FlowHandle, SpawnError> {
977 shared.flow_limit.try_reserve()?;
978 let id = match super::process::try_next_flow_id() {
979 Ok(id) => id,
980 Err(super::error::RuntimeError::FlowIdExhausted) => {
981 shared.flow_limit.release();
982 return Err(SpawnError::FlowIdExhausted);
983 }
984 Err(_) => {
985 shared.flow_limit.release();
986 return Err(SpawnError::Unavailable);
987 }
988 };
989 let cell = match shared.caps.bind_flow(id) {
990 Ok(c) => c,
991 Err(_) => {
992 shared.flow_limit.release();
993 return Err(SpawnError::Unavailable);
994 }
995 };
996 let authority = match bytecode {
997 None => Cap::root(
998 CapTarget::Flow(id.as_u64()),
999 CapRights::ROOT,
1000 Some(NativeMask::full(natives.len())),
1001 cell.as_ref(),
1002 ),
1003 Some(ctx) => match super::spawn::exec_spawn_authority(
1004 ctx.authority,
1005 ctx.cell,
1006 ctx.quota,
1007 id.as_u64(),
1008 ctx.requested_rights,
1009 None,
1010 cell.as_ref(),
1011 ) {
1012 Ok(cap) => cap,
1013 Err(e) => {
1014 shared.flow_limit.release();
1015 let _ = shared.caps.revoke_flow(id);
1016 return Err(SpawnError::from(e));
1017 }
1018 },
1019 };
1020 let args = match grant_caps_in_args(shared, parent, id, args) {
1021 Ok(a) => a,
1022 Err(e) => {
1023 shared.flow_limit.release();
1024 let _ = shared.caps.revoke_flow(id);
1025 return Err(e);
1026 }
1027 };
1028 let gate = NativeGate::from_authority(
1029 &authority,
1030 Arc::clone(&cell),
1031 shared.caps.native_cell(),
1032 natives.len(),
1033 );
1034 let quota = Arc::new(super::quota::FlowQuota::from_config(shared.quota));
1035 let mut vm = match Vm::with_native_gate(
1036 chunk.clone(),
1037 natives.clone(),
1038 gate,
1039 function,
1040 args.as_slice(),
1041 ) {
1042 Ok(vm) => vm,
1043 Err(e) => {
1044 shared.flow_limit.release();
1045 let _ = shared.caps.revoke_flow(id);
1046 return Err(e.into());
1047 }
1048 };
1049 vm.set_paranoid_jumps(shared.paranoid_jumps);
1050 vm.set_memory_budget(Arc::clone(&shared.memory));
1051 if let Err(e) = vm.set_quota(Arc::clone("a)) {
1052 shared.flow_limit.release();
1053 let _ = shared.caps.revoke_flow(id);
1054 return Err(e.into());
1055 }
1056 let mailbox = Arc::new(Mailbox::with_config(shared.mailbox));
1057 if let Err(e) = shared.directory.register(id, mailbox.clone()) {
1058 super::error::report_fault(e);
1059 shared.flow_limit.release();
1060 let _ = shared.caps.revoke_flow(id);
1061 return Err(SpawnError::Unavailable);
1062 }
1063 if let Err(e) = shared.quotas.insert(id, Arc::clone("a)) {
1064 super::error::report_fault(e);
1065 let _ = shared.directory.unregister(id);
1066 shared.flow_limit.release();
1067 let _ = shared.caps.revoke_flow(id);
1068 return Err(SpawnError::Unavailable);
1069 }
1070 let (tx, rx) = super::oneshot::channel();
1071 let mut flow = Box::new(Flow::new(id, vm, mailbox, restart_policy, tx));
1072 flow.authority = authority;
1073 flow.cell = cell;
1074 flow.quota = quota;
1075 flow.supervisor = supervisor;
1076 RuntimeMetrics::inc(&shared.metrics.processes_spawned);
1077 shared.injector.push(flow);
1078 wake_workers(shared);
1079 Ok(FlowHandle { id, receiver: rx })
1080}
1081
1082fn grant_caps_in_args(
1083 shared: &Shared,
1084 parent: Option<FlowId>,
1085 child: FlowId,
1086 args: &[Value],
1087) -> Result<Vec<Value>, SpawnError> {
1088 let mut out = Vec::with_capacity(args.len());
1089 for arg in args {
1090 match arg {
1091 Value::Cap(id) => {
1092 let granted = match parent {
1093 None => shared.caps.reissue_for(*id, child),
1094 Some(p) => shared.caps.delegate(*id, p, child),
1095 };
1096 match granted {
1097 Ok(cap) => out.push(Value::Cap(cap)),
1098 Err(_) => return Err(SpawnError::InvalidCapability),
1099 }
1100 }
1101 other => out.push(other.clone()),
1102 }
1103 }
1104 Ok(out)
1105}
1106
1107pub(crate) fn wake_workers(shared: &Shared) {
1108 let (lock, cvar) = &shared.notify;
1109 match super::sync_lock::lock(lock, "wake_workers") {
1110 Ok(_g) => cvar.notify_one(),
1111 Err(e) => super::error::report_fault(e),
1112 }
1113}
1114
1115fn abort_startup(
1119 shared: &Arc<Shared>,
1120 workers: Vec<std::thread::JoinHandle<()>>,
1121 timer: Option<std::thread::JoinHandle<()>>,
1122) {
1123 shared.shutdown.store(true, Ordering::Release);
1124 shared.timer.shutdown();
1125 let (lock, cvar) = &shared.notify;
1126 match super::sync_lock::lock(lock, "abort_startup") {
1127 Ok(_g) => cvar.notify_all(),
1128 Err(e) => super::error::report_fault(e),
1129 }
1130 for w in workers {
1131 let _ = w.join();
1132 }
1133 if let Some(t) = timer {
1134 let _ = t.join();
1135 }
1136}
1137
1138#[derive(Clone)]
1144pub struct RuntimeSpawner {
1145 pub(crate) shared: Arc<Shared>,
1146 pub(crate) chunk: Arc<Chunk>,
1147 pub(crate) natives: Arc<NativeTable>,
1148}
1149
1150impl RuntimeSpawner {
1151 pub fn spawn(
1152 &self,
1153 function: u32,
1154 args: &[Value],
1155 restart_policy: RestartPolicy,
1156 ) -> Result<FlowHandle, SpawnError> {
1157 spawn_on(
1158 &self.shared,
1159 &self.chunk,
1160 &self.natives,
1161 function,
1162 args,
1163 restart_policy,
1164 None,
1165 None,
1166 None,
1167 )
1168 }
1169
1170 pub(crate) fn spawn_linked(
1171 &self,
1172 function: u32,
1173 args: &[Value],
1174 restart_policy: RestartPolicy,
1175 supervisor: SupervisorLink,
1176 ) -> Result<FlowHandle, SpawnError> {
1177 spawn_on(
1178 &self.shared,
1179 &self.chunk,
1180 &self.natives,
1181 function,
1182 args,
1183 restart_policy,
1184 Some(supervisor),
1185 None,
1186 None,
1187 )
1188 }
1189
1190 pub fn metrics(&self) -> RuntimeMetricsSnapshot {
1191 self.shared.metrics.snapshot()
1192 }
1193
1194 pub(crate) fn request_kill(&self, id: FlowId, reason: super::monitor::FlowExitReason) {
1195 super::finalize::request_kill(&self.shared, id, reason);
1196 }
1197}
1198
1199#[cfg(test)]
1200mod tests {
1201 use super::*;
1202 use crate::bytecode::{builder::ChunkBuilder, Opcode, Value};
1203 use crate::scheduler::FlowOutcome;
1204 use std::time::Duration;
1205
1206 fn add_chunk() -> Chunk {
1207 let mut b = ChunkBuilder::new("test");
1208 b.begin_function("main", 0, 2);
1209 b.emit_load_imm(0, 41);
1210 b.emit_load_imm(1, 1);
1211 b.emit_binop(Opcode::Add, 0, 0, 1);
1212 b.emit_return(0);
1213 b.finish()
1214 }
1215
1216 fn sleep_then_return_chunk(millis: i32) -> Chunk {
1219 let mut b = ChunkBuilder::new("test");
1220 b.begin_function("main", 0, 2);
1221 b.emit_load_imm(0, millis);
1222 b.emit_sleep(0);
1223 b.emit_load_imm(0, 7);
1224 b.emit_return(0);
1225 b.finish()
1226 }
1227
1228 #[test]
1232 fn polling_and_bounded_waits_never_commit_the_host_thread(
1233 ) -> Result<(), Box<dyn std::error::Error>> {
1234 const FLOW_SLEEP: i32 = 150;
1235 let rt = Runtime::with_config(
1236 sleep_then_return_chunk(FLOW_SLEEP),
1237 RuntimeConfig {
1238 workers: 1,
1239 quantum: 1_000,
1240 mailbox: MailboxConfig::DEFAULT,
1241 ..Default::default()
1242 },
1243 )?;
1244 let handle = rt.spawn(0, &[])?;
1245
1246 if let Some(outcome) = handle.try_join() {
1249 rt.shutdown();
1250 return Err(format!("try_join answered too early: {outcome:?}").into());
1251 }
1252
1253 if let Some(outcome) = handle.join_timeout(Duration::from_millis(20)) {
1256 rt.shutdown();
1257 return Err(format!("join_timeout answered too early: {outcome:?}").into());
1258 }
1259
1260 let outcome = handle.join_timeout(Duration::from_secs(10));
1263 rt.shutdown();
1264 match outcome {
1265 Some(FlowOutcome::Completed(Value::Int(7))) => Ok(()),
1266 other => Err(format!("unexpected outcome: {other:?}").into()),
1267 }
1268 }
1269
1270 #[test]
1271 fn spawn_and_join_add() -> Result<(), Box<dyn std::error::Error>> {
1272 let rt = Runtime::with_config(
1273 add_chunk(),
1274 RuntimeConfig {
1275 workers: 1,
1276 quantum: 1_000,
1277 mailbox: MailboxConfig::DEFAULT,
1278 ..Default::default()
1279 },
1280 )?;
1281 let outcome = rt.spawn(0, &[])?.join();
1282 rt.shutdown();
1283 match outcome {
1284 FlowOutcome::Completed(Value::Int(42)) => Ok(()),
1285 other => Err(format!("unexpected outcome: {other:?}").into()),
1286 }
1287 }
1288
1289 fn receive_forever_chunk() -> Chunk {
1290 let mut b = ChunkBuilder::new("recv");
1291 b.begin_function("main", 0, 1);
1292 b.emit_receive(0);
1293 b.emit_return(0);
1294 b.finish()
1295 }
1296
1297 #[test]
1298 fn kill_parked_flow_joins_failed() -> Result<(), Box<dyn std::error::Error>> {
1299 let rt = Runtime::with_config(
1300 receive_forever_chunk(),
1301 RuntimeConfig {
1302 workers: 1,
1303 quantum: 1_000,
1304 mailbox: MailboxConfig::DEFAULT,
1305 ..Default::default()
1306 },
1307 )?;
1308 let handle = rt.spawn(0, &[])?;
1309 rt.kill(handle.id())?;
1310 let outcome = handle.join();
1311 rt.shutdown();
1312 assert!(
1313 matches!(outcome, FlowOutcome::Failed(_)),
1314 "kill must fail the joiner, got {outcome:?}"
1315 );
1316 Ok(())
1317 }
1318
1319 #[test]
1320 fn max_flows_rejects_extra_spawn() -> Result<(), Box<dyn std::error::Error>> {
1321 let rt = Runtime::with_config(
1322 receive_forever_chunk(),
1323 RuntimeConfig {
1324 workers: 1,
1325 quantum: 1_000,
1326 mailbox: MailboxConfig::DEFAULT,
1327 max_flows: 1,
1328 ..Default::default()
1329 },
1330 )?;
1331 let first = rt.spawn(0, &[])?;
1332 let second = rt.spawn(0, &[]);
1333 rt.kill(first.id())?;
1334 let _ = first.join();
1335 let third = rt.spawn(0, &[])?;
1337 rt.kill(third.id())?;
1338 let _ = third.join();
1339 rt.shutdown();
1340 match second {
1341 Err(SpawnError::FlowLimit { current, max }) => {
1342 assert_eq!(current, 1);
1343 assert_eq!(max, 1);
1344 Ok(())
1345 }
1346 other => Err(format!(
1347 "expected FlowLimit, got {}",
1348 match &other {
1349 Ok(_) => "Ok(handle)".into(),
1350 Err(e) => format!("Err({e})"),
1351 }
1352 )
1353 .into()),
1354 }
1355 }
1356
1357 #[test]
1359 fn ask_drop_newest_fails_closed() -> Result<(), Box<dyn std::error::Error>> {
1360 use crate::bytecode::{Message, Program};
1361 use crate::scheduler::mailbox::{MailboxCapacity, OverflowPolicy};
1362
1363 let mut program = Program::new("ask-drop-newest");
1364 let busy = program.function("busy", 0, |f| {
1365 let loop_lbl = f.label();
1367 f.bind(loop_lbl);
1368 let ms = f.load_i32(50);
1369 f.sleep(ms);
1370 f.jump(loop_lbl);
1371 });
1372 let asker = program.function("asker", 1, |f| {
1373 let server = f.reg(0);
1374 let z = f.load_i32(0);
1375 let req = f.hop_fresh(1, z);
1376 let reply = f.ask(server, req);
1377 f.return_(reply);
1378 });
1379 let chunk = program.build();
1380
1381 let cap = MailboxCapacity::new(1).ok_or("cap")?;
1382 let rt = Runtime::with_natives_and_config(
1383 chunk,
1384 crate::std_native_table(),
1385 RuntimeConfig {
1386 workers: 2,
1388 quantum: 1_000,
1389 mailbox: MailboxConfig::new(cap, OverflowPolicy::DropNewest),
1390 ..Default::default()
1391 },
1392 )?;
1393
1394 let server = rt.spawn(busy, &[])?;
1395 rt.send(
1397 server.id(),
1398 Value::Message(Message::request(1, 9, Value::Int(1))),
1399 )?;
1400 let server_cap = rt.mint_cap(server.id())?;
1401 let ask = rt.spawn(asker, &[Value::Cap(server_cap)])?;
1402 let outcome = ask.join_timeout(Duration::from_secs(3));
1403 rt.kill(server.id())?;
1404 let _ = server.join_timeout(Duration::from_millis(500));
1405 rt.shutdown();
1406
1407 match outcome {
1408 Some(FlowOutcome::Failed(msg)) if msg.contains("DropNewest") => Ok(()),
1409 other => Err(format!("expected Ask DropNewest failure, got {other:?}").into()),
1410 }
1411 }
1412
1413 #[test]
1414 fn max_ask_waits_rejects_extra_park() -> Result<(), Box<dyn std::error::Error>> {
1415 use crate::bytecode::Program;
1416
1417 let mut program = Program::new("ask-limit");
1418 let silent = program.function("silent", 0, |f| {
1419 let _req = f.receive();
1421 let loop_lbl = f.label();
1422 f.bind(loop_lbl);
1423 let ms = f.load_i32(50);
1424 f.sleep(ms);
1425 f.jump(loop_lbl);
1426 });
1427 let asker = program.function("asker", 1, |f| {
1428 let server = f.reg(0);
1429 let z = f.load_i32(0);
1430 let req = f.hop_fresh(1, z);
1431 let reply = f.ask(server, req);
1432 f.return_(reply);
1433 });
1434 let chunk = program.build();
1435
1436 let rt = Runtime::with_natives_and_config(
1437 chunk,
1438 crate::std_native_table(),
1439 RuntimeConfig {
1440 workers: 2,
1441 quantum: 1_000,
1442 mailbox: MailboxConfig::DEFAULT,
1443 max_ask_waits: 1,
1444 ..Default::default()
1445 },
1446 )?;
1447
1448 let server = rt.spawn(silent, &[])?;
1449 let server_cap = rt.mint_cap(server.id())?;
1450 let first = rt.spawn(asker, &[Value::Cap(server_cap)])?;
1451 std::thread::sleep(Duration::from_millis(30));
1453 let second = rt.spawn(asker, &[Value::Cap(server_cap)])?;
1454 let second_out = second.join_timeout(Duration::from_secs(2));
1455 rt.kill(server.id())?;
1456 let _ = first.join_timeout(Duration::from_millis(500));
1457 let _ = server.join_timeout(Duration::from_millis(500));
1458 rt.shutdown();
1459
1460 match second_out {
1461 Some(FlowOutcome::Failed(msg)) if msg.contains("Ask wait limit") => Ok(()),
1462 other => Err(format!("expected Ask wait limit failure, got {other:?}").into()),
1463 }
1464 }
1465
1466 #[cfg(feature = "jit")]
1469 #[test]
1470 fn runtime_with_jit_enabled_completes_add() -> Result<(), Box<dyn std::error::Error>> {
1471 use crate::JitConfig;
1472
1473 let rt = Runtime::with_config(
1474 add_chunk(),
1475 RuntimeConfig {
1476 workers: 1,
1477 quantum: 1_000,
1478 mailbox: MailboxConfig::DEFAULT,
1479 jit: JitConfig {
1480 enabled: true,
1481 hot_threshold: 1,
1482 },
1483 ..Default::default()
1484 },
1485 )?;
1486 let outcome = rt.spawn(0, &[])?.join();
1487 rt.shutdown();
1488 match outcome {
1489 FlowOutcome::Completed(Value::Int(42)) => Ok(()),
1490 other => Err(format!("unexpected outcome: {other:?}").into()),
1491 }
1492 }
1493
1494 #[test]
1495 fn sandbox_enables_process_wide_relation_caps() {
1496 let config = RuntimeConfig::sandbox();
1497 assert_eq!(config.max_flows, 256);
1498 assert_eq!(config.max_ask_waits, 128);
1499 assert_eq!(config.max_host_awaits, 128);
1500 assert_eq!(config.max_links, 1024);
1501 assert_eq!(config.max_monitors, 1024);
1502 assert_eq!(config.max_registry_names, 256);
1503 assert!(config.paranoid_jumps);
1504 assert_eq!(config.max_runtime_bytes, 64 * 1024 * 1024);
1505 }
1506
1507 #[test]
1508 fn default_remains_unlimited_for_relation_caps() {
1509 let config = RuntimeConfig::default();
1510 assert_eq!(config.max_links, 0);
1511 assert_eq!(config.max_monitors, 0);
1512 assert_eq!(config.max_registry_names, 0);
1513 assert!(!config.paranoid_jumps);
1514 }
1515
1516 #[test]
1517 fn with_attested_mismatch_is_attestation_error() -> Result<(), Box<dyn std::error::Error>> {
1518 use crate::bytecode::encode;
1519 use crate::{fingerprint_bf, AttestError};
1520
1521 let bytes = encode(&add_chunk());
1522 let mut bad = fingerprint_bf(&bytes);
1523 bad[0] ^= 0xff;
1524 match Runtime::with_attested(&bytes, bad, NativeTable::empty(), RuntimeConfig::default()) {
1525 Err(SpawnError::Attestation(AttestError::DigestMismatch { .. })) => Ok(()),
1526 Ok(_) => Err("expected Attestation error, got Ok(Runtime)".into()),
1527 Err(e) => Err(format!("expected Attestation(DigestMismatch), got Err({e})").into()),
1528 }
1529 }
1530
1531 #[test]
1532 fn with_attested_match_runs() -> Result<(), Box<dyn std::error::Error>> {
1533 use crate::bytecode::encode;
1534 use crate::fingerprint_bf;
1535
1536 let chunk = add_chunk();
1537 let bytes = encode(&chunk);
1538 let digest = fingerprint_bf(&bytes);
1539 let rt = Runtime::with_attested(
1540 &bytes,
1541 digest,
1542 NativeTable::empty(),
1543 RuntimeConfig {
1544 workers: 1,
1545 quantum: 1_000,
1546 mailbox: MailboxConfig::DEFAULT,
1547 ..Default::default()
1548 },
1549 )?;
1550 let outcome = rt.spawn(0, &[])?.join();
1551 rt.shutdown();
1552 match outcome {
1553 FlowOutcome::Completed(Value::Int(42)) => Ok(()),
1554 other => Err(format!("expected 42, got {other:?}").into()),
1555 }
1556 }
1557
1558 #[test]
1559 fn untrusted_enables_paranoid_jumps_on_shared() -> Result<(), Box<dyn std::error::Error>> {
1560 let rt = Runtime::with_config(
1563 add_chunk(),
1564 RuntimeConfig {
1565 workers: 1,
1566 quantum: 1_000,
1567 mailbox: MailboxConfig::DEFAULT,
1568 trust: crate::bytecode::TrustLevel::Untrusted,
1569 paranoid_jumps: false,
1570 ..Default::default()
1571 },
1572 )?;
1573 assert!(rt.shared.paranoid_jumps);
1574 rt.shutdown();
1575 Ok(())
1576 }
1577}