1#![allow(missing_docs)]
11
12use std::sync::atomic::{AtomicBool, AtomicU64, Ordering};
13use std::sync::{Arc, Condvar, Mutex};
14use std::thread::JoinHandle;
15
16use crate::bytecode::{Cap, CapRights, CapTarget, Chunk, NativeMask, Value};
17use crate::vm::{NativeGate, NativeTable, Vm};
18
19use super::directory::Directory;
20use super::error::{RuntimeError, SpawnError};
21use super::finalize::finalize_flow;
22use super::handle::FlowHandle;
23use super::mailbox::{Delivery, Mailbox, MailboxConfig, MailboxFullReason};
24use super::metrics::{RuntimeMetrics, RuntimeMetricsSnapshot, RuntimeSnapshot};
25use super::monitor::FlowExitReason;
26use super::process::{Flow, FlowId, FlowOutcome};
27use super::runqueue::{Injector, Stealer, Worker as LocalDeque};
28use super::supervisor::SupervisorLink;
29use super::timer::TimerWheel;
30use super::worker;
31use crate::bytecode::RestartPolicy;
32
33mod config;
34mod control;
35mod spawn;
36#[cfg(test)]
37mod tests;
38
39#[cfg(feature = "jit")]
40pub use self::config::JitConfig;
41pub use self::config::{RootAuthorityPolicy, RuntimeConfig, DEFAULT_QUANTUM};
42#[cfg(test)]
43use self::spawn::bytecode_spawn_arity;
44pub use self::spawn::RuntimeSpawner;
45pub(crate) use self::spawn::{spawn_on, BytecodeSpawn};
46
47pub(crate) struct Shared {
54 pub(crate) injector: Injector<Box<Flow>>,
55 pub(crate) stealers: Vec<Stealer<Flow>>,
56 pub(crate) directory: Directory,
58 pub(crate) caps: super::capability::CapTable,
60 pub(crate) timer: Arc<TimerWheel>,
61 pub(crate) notify: (Mutex<()>, Condvar),
62 pub(crate) metrics: RuntimeMetrics,
63 pub(crate) shutdown: AtomicBool,
64 pub(crate) quantum: u32,
65 pub(crate) mailbox: MailboxConfig,
66 pub(crate) flow_limit: super::flow_limit::FlowLimit,
68 pub(crate) memory: Arc<crate::MemoryBudget>,
69 pub(crate) quota: super::quota::QuotaConfig,
70 pub(crate) quotas: super::quota::QuotaTable,
71 pub(crate) monitors: super::monitor::MonitorStore,
72 pub(crate) links: super::link::LinkStore,
73 pub(crate) registry: super::registry::RegistryStore,
74 pub(crate) kill_signals: super::finalize::KillSignals,
75 pub(crate) trap_exits: super::finalize::TrapExitFlags,
76 pub(crate) waiting_send_at: super::finalize::WaitingSendIndex,
77 pub(crate) ask_waits: super::finalize::AskWaitIndex,
78 pub(crate) host_awaits: super::host_await::HostAwaitIndex,
81 pub(crate) host_await_bridge: Option<Arc<dyn super::host_await::HostAwaitBridge>>,
83 pub(crate) host_replay: Mutex<Option<super::deterministic::HostReplayGate>>,
85 pub(crate) host_await_failures: super::host_await::HostAwaitFailures,
87 pub(crate) distribution: Option<Arc<super::distribution::DistributionBridge>>,
89 pub(crate) remote_dedup: Option<Arc<super::distribution::RemoteFrameDedup>>,
91 pub(crate) log_sink: Option<Arc<dyn crate::log::LogSink>>,
94 pub(crate) tables: super::table::FlowTables,
96 pub(crate) flow_supervisors: Mutex<Vec<super::supervisor::Supervisor>>,
99 pub(crate) host_next_request_id: AtomicU64,
102 #[cfg(feature = "jit")]
104 pub(crate) jit: Option<std::sync::Arc<crate::jit::JitRuntime>>,
105 pub(crate) security: Arc<super::sandbox::SecurityCounters>,
107 pub(crate) security_audit: Option<Arc<dyn super::sandbox::SecurityAuditSink>>,
108 pub(crate) policy: super::sandbox::PolicyFingerprint,
109 pub(crate) trust: crate::bytecode::TrustLevel,
110 pub(crate) root_authority: RootAuthorityPolicy,
111}
112
113pub struct Runtime {
124 shared: Arc<Shared>,
125 chunk: Arc<Chunk>,
126 natives: Arc<NativeTable>,
127 workers: Vec<JoinHandle<()>>,
128 timer_thread: Option<JoinHandle<()>>,
129 audit_worker: Option<super::sandbox::AuditWorkerHandle>,
130 trust: crate::bytecode::TrustLevel,
131}
132
133impl Runtime {
134 pub fn new(chunk: Chunk) -> Result<Self, SpawnError> {
142 Self::with_config(chunk, RuntimeConfig::default())
143 }
144
145 pub fn with_natives(chunk: Chunk, natives: Arc<NativeTable>) -> Result<Self, SpawnError> {
148 Self::with_natives_and_config(chunk, natives, RuntimeConfig::default())
149 }
150
151 pub fn with_config(chunk: Chunk, config: RuntimeConfig) -> Result<Self, SpawnError> {
152 Self::with_natives_and_config(chunk, NativeTable::empty(), config)
153 }
154
155 pub fn with_attested(
161 bytes: &[u8],
162 expected_digest: [u8; 32],
163 natives: Arc<NativeTable>,
164 config: RuntimeConfig,
165 ) -> Result<Self, SpawnError> {
166 let chunk =
167 crate::decode_attested(bytes, &expected_digest).map_err(SpawnError::Attestation)?;
168 Self::with_natives_and_config(chunk, natives, config)
169 }
170
171 pub fn with_std_natives_and_config(
174 chunk: Chunk,
175 config: RuntimeConfig,
176 ) -> Result<Self, SpawnError> {
177 Self::with_natives_and_config(
178 chunk,
179 crate::std_native_table_with(Arc::clone(&config.output)),
180 config,
181 )
182 }
183
184 pub fn with_natives_and_config(
194 chunk: Chunk,
195 natives: Arc<NativeTable>,
196 config: RuntimeConfig,
197 ) -> Result<Self, SpawnError> {
198 if let Err(err) = crate::bytecode::verify_with(
199 &chunk,
200 crate::bytecode::VerifyConfig {
201 trust: config.trust,
202 },
203 ) {
204 if let Some(sink) = config.security_audit.as_ref() {
205 sink.record(&super::sandbox::SecurityEvent::ModuleRejected {
207 reason: "verify_failed",
208 });
209 }
210 return Err(SpawnError::VerifyFailed(err));
211 }
212 let chunk = Arc::new(chunk);
213 let workers_n = config.workers.max(1);
214 let quantum = config.quantum.max(1);
215
216 let (security_audit, audit_worker) = match config.security_audit.clone() {
217 Some(sink) => {
218 let (queued, handle) =
219 super::sandbox::wrap_audit_sink(sink, super::sandbox::DEFAULT_AUDIT_QUEUE);
220 (Some(queued), Some(handle))
221 }
222 None => (None, None),
223 };
224
225 let locals: Vec<LocalDeque<Flow>> = (0..workers_n).map(|_| LocalDeque::new()).collect();
226 let stealers: Vec<Stealer<Flow>> = locals.iter().map(|l| l.stealer()).collect();
227
228 #[cfg(feature = "jit")]
229 let jit = if config.jit.enabled {
230 Some(super::jit::new_runtime(
231 chunk.clone(),
232 config.jit.hot_threshold,
233 ))
234 } else {
235 None
236 };
237
238 let shared = Arc::new(Shared {
239 injector: Injector::new(),
240 stealers,
241 directory: Directory::new(),
242 caps: super::capability::CapTable::new(),
243 timer: TimerWheel::new(),
244 notify: (Mutex::new(()), Condvar::new()),
245 metrics: RuntimeMetrics::default(),
246 shutdown: AtomicBool::new(false),
247 quantum,
248 mailbox: config.mailbox,
249 flow_limit: super::flow_limit::FlowLimit::new(config.max_flows),
250 memory: Arc::new(crate::MemoryBudget::new(config.max_runtime_bytes)),
251 quota: config.quota,
252 quotas: super::quota::QuotaTable::new(),
253 monitors: super::monitor::MonitorStore::new(config.max_monitors),
254 links: super::link::LinkStore::new(config.max_links),
255 registry: super::registry::RegistryStore::new(config.max_registry_names),
256 kill_signals: super::finalize::KillSignals::new(),
257 trap_exits: super::finalize::TrapExitFlags::new(),
258 waiting_send_at: super::finalize::WaitingSendIndex::new(),
259 ask_waits: super::finalize::AskWaitIndex::new(config.max_ask_waits),
260 host_awaits: super::host_await::HostAwaitIndex::new(config.max_host_awaits),
261 host_await_bridge: config.host_await.clone(),
262 host_replay: Mutex::new(None),
263 host_await_failures: super::host_await::HostAwaitFailures::new(),
264 distribution: config.distribution.clone(),
265 remote_dedup: if config.remote_dedup_window == 0 {
266 None
267 } else {
268 Some(super::distribution::RemoteFrameDedup::new(
269 config.remote_dedup_window as usize,
270 ))
271 },
272 log_sink: config.log.clone(),
273 tables: super::table::FlowTables::new(),
274 flow_supervisors: Mutex::new(Vec::new()),
275 host_next_request_id: AtomicU64::new(1),
276 #[cfg(feature = "jit")]
277 jit,
278 security: Arc::new(super::sandbox::SecurityCounters::default()),
279 security_audit,
280 policy: config.policy_fingerprint(),
281 trust: config.trust,
282 root_authority: config.root_authority,
283 });
284
285 let mut workers = Vec::with_capacity(workers_n);
286 for local in locals {
287 let shared_w = shared.clone();
288 match std::thread::Builder::new()
289 .name("byteflow-worker".into())
290 .spawn(move || worker::run_worker(shared_w, local))
291 {
292 Ok(handle) => workers.push(handle),
293 Err(e) => {
294 abort_startup(&shared, workers, None);
295 return Err(SpawnError::ThreadSpawnFailed(e.to_string()));
296 }
297 }
298 }
299
300 let shared_timer = shared.clone();
301 let timer_thread = match std::thread::Builder::new()
302 .name("byteflow-timer".into())
303 .spawn(move || shared_timer.timer.clone().drive(&shared_timer))
304 {
305 Ok(handle) => handle,
306 Err(e) => {
307 abort_startup(&shared, workers, None);
308 return Err(SpawnError::ThreadSpawnFailed(e.to_string()));
309 }
310 };
311
312 Ok(Runtime {
313 shared,
314 chunk,
315 natives,
316 workers,
317 timer_thread: Some(timer_thread),
318 audit_worker,
319 trust: config.trust,
320 })
321 }
322
323 pub fn spawn(&self, function: u32, args: &[Value]) -> Result<FlowHandle, SpawnError> {
331 spawn_on(
332 &self.shared,
333 &self.chunk,
334 &self.natives,
335 function,
336 args,
337 RestartPolicy::Never,
338 None,
339 None,
340 None,
341 None,
342 )
343 }
344
345 pub fn spawn_untrusted(&self, function: u32, args: &[Value]) -> Result<FlowHandle, SpawnError> {
348 spawn_on(
349 &self.shared,
350 &self.chunk,
351 &self.natives,
352 function,
353 args,
354 RestartPolicy::Never,
355 None,
356 None,
357 None,
358 Some(RootAuthorityPolicy::Untrusted),
359 )
360 }
361
362 pub fn spawner(&self) -> RuntimeSpawner {
366 RuntimeSpawner {
367 shared: self.shared.clone(),
368 chunk: self.chunk.clone(),
369 natives: self.natives.clone(),
370 }
371 }
372
373 pub fn supervisor(&self) -> Result<super::supervisor::Supervisor, SpawnError> {
376 super::supervisor::Supervisor::new(self.spawner())
377 }
378
379 pub fn function_index(&self, name: &str) -> Option<u32> {
383 self.chunk
384 .functions
385 .iter()
386 .position(|f| f.name == name)
387 .map(|i| i as u32)
388 }
389
390 pub fn metrics(&self) -> RuntimeMetricsSnapshot {
391 self.shared.metrics.snapshot()
392 }
393
394 pub fn security_counters(&self) -> super::sandbox::SecurityCountersSnapshot {
396 self.shared.security.snapshot()
397 }
398
399 pub fn policy_fingerprint(&self) -> super::sandbox::PolicyFingerprint {
401 self.shared.policy
402 }
403
404 pub fn trust_level(&self) -> crate::bytecode::TrustLevel {
406 self.trust
407 }
408
409 pub fn attest_capabilities(
411 &self,
412 flow: FlowId,
413 ) -> Result<super::sandbox::CapabilityAttestation, RuntimeError> {
414 super::sandbox::CapabilityAttestation::from_table(
415 &self.shared.caps,
416 flow,
417 self.trust,
418 self.shared.policy,
419 )
420 }
421
422 pub fn snapshot(&self) -> RuntimeSnapshot {
424 RuntimeSnapshot {
425 metrics: self.metrics(),
426 live_flows: self.live_flows(),
427 flow_limit_live: self.shared.flow_limit.reserved_live(),
428 max_flows: self.shared.flow_limit.max_flows(),
429 distribution_pending: self
430 .shared
431 .distribution
432 .as_ref()
433 .and_then(|b| b.outbound_pending().ok()),
434 memory: self.memory_snapshot(),
435 workers: self.worker_count(),
436 }
437 }
438
439 pub fn live_flows(&self) -> usize {
445 self.shared.directory.len()
446 }
447
448 pub fn memory_snapshot(&self) -> crate::MemorySnapshot {
450 self.shared.memory.snapshot()
451 }
452
453 pub fn worker_count(&self) -> usize {
454 self.workers.len()
455 }
456
457 pub fn send(&self, target: FlowId, message: Value) -> Result<(), SendError> {
470 let Some(msg) = message.as_message().cloned() else {
471 return Err(SendError::NotAHop {
472 got: message.type_name(),
473 });
474 };
475 let mailbox = match self.shared.directory.lookup(target) {
476 Ok(Some(m)) => m,
477 Ok(None) => return Err(SendError::NoSuchFlow(target)),
478 Err(e) => {
479 super::error::report_fault(e);
480 return Err(SendError::Unavailable);
481 }
482 };
483 let stamped = match worker::authenticate_host_outgoing_message(&self.shared, target, msg) {
484 Ok(m) => Value::Message(m),
485 Err(_) => return Err(SendError::Capability),
486 };
487 match mailbox.push(stamped.clone()) {
488 Ok(Ok(Delivery::Queued | Delivery::QueuedDropOldest | Delivery::DroppedNewest)) => {
493 Ok(())
494 }
495 Ok(Ok(Delivery::Handoff(flow))) => {
496 let _ = self.shared.ask_waits.remove_asker(flow.id);
497 match flow.last_receive_dest {
498 Some(dest) => {
499 let Some(flow) =
500 super::finalize::resume_or_fail(&self.shared, flow, dest, stamped)
501 else {
502 return Err(SendError::Unavailable);
503 };
504 enqueue_flow(&self.shared, flow);
505 wake_workers(&self.shared);
506 Ok(())
507 }
508 None => {
509 super::error::report_fault(super::error::RuntimeError::PoisonedLock(
510 "Runtime::send handoff missing dest register",
511 ));
512 finalize_flow(
513 &self.shared,
514 *flow,
515 FlowOutcome::Failed("handoff missing dest register".into()),
516 FlowExitReason::Fault,
517 );
518 Err(SendError::Unavailable)
519 }
520 }
521 }
522 Ok(Err(full)) => {
523 if full.reason() == MailboxFullReason::Closed {
524 return Err(SendError::NoSuchFlow(target));
525 }
526 Err(SendError::MailboxFull {
527 flow: target,
528 reason: full.reason(),
529 })
530 }
531 Err(e) => {
532 super::error::report_fault(e);
533 Err(SendError::Unavailable)
534 }
535 }
536 }
537
538 pub fn deliver_frame(&self, bytes: &[u8]) -> Result<(), super::distribution::RemoteFrameError> {
549 let hop = super::distribution::decode_frame(bytes)?;
550 let reservation = if hop.message.request_id != 0 {
551 if let Some(dedup) = self.shared.remote_dedup.as_ref() {
552 match dedup
553 .reserve(hop.sender.as_u64(), hop.message.request_id)
554 .map_err(|_| super::distribution::RemoteFrameError::Unavailable)?
555 {
556 super::distribution::DedupTicket::Duplicate => return Ok(()),
557 super::distribution::DedupTicket::Fresh { sender, request_id } => {
558 Some((sender, request_id))
559 }
560 }
561 } else {
562 None
563 }
564 } else {
565 None
566 };
567
568 let outcome = self.deliver_frame_after_dedup(hop);
569 if let Some((sender, request_id)) = reservation {
570 if let Some(dedup) = self.shared.remote_dedup.as_ref() {
571 match &outcome {
572 Ok(()) | Err(DeliverAcceptError::AfterAccept(_)) => {
574 let _ = dedup.commit(sender, request_id);
575 }
576 Err(DeliverAcceptError::BeforeAccept(_)) => {
577 let _ = dedup.rollback(sender, request_id);
578 }
579 }
580 }
581 }
582 match outcome {
583 Ok(()) => Ok(()),
584 Err(DeliverAcceptError::BeforeAccept(e) | DeliverAcceptError::AfterAccept(e)) => Err(e),
585 }
586 }
587
588 fn deliver_frame_after_dedup(
589 &self,
590 hop: super::distribution::OutboundHop,
591 ) -> Result<(), DeliverAcceptError> {
592 let cap = match self.shared.registry.whereis(hop.name.as_ref()) {
593 Ok(Some(cap)) => cap,
594 Ok(None) => {
595 return Err(DeliverAcceptError::BeforeAccept(
596 super::distribution::RemoteFrameError::NoSuchName,
597 ))
598 }
599 Err(err) => {
600 super::error::report_fault(err);
601 return Err(DeliverAcceptError::BeforeAccept(
602 super::distribution::RemoteFrameError::Unavailable,
603 ));
604 }
605 };
606 let target = match self.shared.caps.lookup(cap) {
607 Ok(Some(entry)) => match entry.target() {
608 Some(id) => id,
609 None => {
610 return Err(DeliverAcceptError::BeforeAccept(
611 super::distribution::RemoteFrameError::NoSuchName,
612 ))
613 }
614 },
615 Ok(None) => {
616 return Err(DeliverAcceptError::BeforeAccept(
617 super::distribution::RemoteFrameError::NoSuchName,
618 ))
619 }
620 Err(err) => {
621 super::error::report_fault(err);
622 return Err(DeliverAcceptError::BeforeAccept(
623 super::distribution::RemoteFrameError::Unavailable,
624 ));
625 }
626 };
627 let mailbox = match self.shared.directory.lookup(target) {
628 Ok(Some(mailbox)) => mailbox,
629 Ok(None) => {
630 return Err(DeliverAcceptError::BeforeAccept(
631 super::distribution::RemoteFrameError::NoSuchName,
632 ))
633 }
634 Err(err) => {
635 super::error::report_fault(err);
636 return Err(DeliverAcceptError::BeforeAccept(
637 super::distribution::RemoteFrameError::Unavailable,
638 ));
639 }
640 };
641 let stamped = Value::Message(hop.message);
642 match mailbox.push(stamped.clone()) {
643 Ok(Ok(Delivery::Queued | Delivery::QueuedDropOldest | Delivery::DroppedNewest)) => {
644 Ok(())
645 }
646 Ok(Ok(Delivery::Handoff(flow))) => {
647 let _ = self.shared.ask_waits.remove_asker(flow.id);
648 match flow.last_receive_dest {
649 Some(dest) => {
650 let Some(flow) =
651 super::finalize::resume_or_fail(&self.shared, flow, dest, stamped)
652 else {
653 return Err(DeliverAcceptError::AfterAccept(
654 super::distribution::RemoteFrameError::Unavailable,
655 ));
656 };
657 enqueue_flow(&self.shared, flow);
658 wake_workers(&self.shared);
659 Ok(())
660 }
661 None => {
662 super::finalize::finalize_flow(
663 &self.shared,
664 *flow,
665 FlowOutcome::Failed("handoff missing dest register".into()),
666 FlowExitReason::Fault,
667 );
668 Err(DeliverAcceptError::AfterAccept(
669 super::distribution::RemoteFrameError::Unavailable,
670 ))
671 }
672 }
673 }
674 Ok(Err(full)) => Err(DeliverAcceptError::BeforeAccept(
675 super::distribution::RemoteFrameError::Mailbox(full.reason()),
676 )),
677 Err(err) => {
678 super::error::report_fault(err);
679 Err(DeliverAcceptError::BeforeAccept(
680 super::distribution::RemoteFrameError::Unavailable,
681 ))
682 }
683 }
684 }
685}
686
687enum DeliverAcceptError {
690 BeforeAccept(super::distribution::RemoteFrameError),
691 AfterAccept(super::distribution::RemoteFrameError),
692}
693
694pub fn flow_id_from_u64(raw: u64) -> FlowId {
698 FlowId(raw)
699}
700
701#[derive(Debug, Clone, PartialEq, Eq)]
703pub enum SendError {
704 NoSuchFlow(FlowId),
705 NotAHop {
707 got: &'static str,
708 },
709 MailboxFull {
713 flow: FlowId,
714 reason: MailboxFullReason,
715 },
716 Capability,
718 Unavailable,
720}
721
722impl std::fmt::Display for SendError {
723 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
724 match self {
725 SendError::NoSuchFlow(id) => write!(f, "no live flow {id}"),
726 SendError::NotAHop { got } => {
727 write!(f, "atomic hop requires Value::Message, got {got}")
728 }
729 SendError::MailboxFull { flow, reason } => {
730 write!(f, "mailbox full for {flow} ({reason})")
731 }
732 SendError::Capability => {
733 write!(f, "host send could not reissue a capability in the hop")
734 }
735 SendError::Unavailable => write!(f, "runtime table unavailable (poisoned lock)"),
736 }
737 }
738}
739
740impl std::error::Error for SendError {}
741
742pub(crate) fn enqueue_flow(shared: &Shared, flow: Box<Flow>) {
747 shared.injector.push(flow);
748}
749
750pub(crate) fn wake_workers(shared: &Shared) {
751 let (lock, cvar) = &shared.notify;
752 match super::sync_lock::lock(lock, "wake_workers") {
753 Ok(_g) => cvar.notify_one(),
754 Err(e) => super::error::report_fault(e),
755 }
756}
757
758pub(crate) fn record_security_event(shared: &Shared, event: &super::sandbox::SecurityEvent) {
762 use super::sandbox::{SecurityCounters, SecurityEvent};
763 match event {
764 SecurityEvent::AccessDenied { .. } => {
765 SecurityCounters::inc(&shared.security.denied_operations);
766 }
767 SecurityEvent::QuotaExceeded { .. } => {
768 SecurityCounters::inc(&shared.security.quota_exceeded);
769 }
770 SecurityEvent::CapabilityCreated { .. } => {
771 SecurityCounters::inc(&shared.security.capabilities_created);
772 }
773 SecurityEvent::CapabilityRevoked { .. } => {
774 SecurityCounters::inc(&shared.security.capabilities_revoked);
775 }
776 SecurityEvent::ModuleRejected { .. } => {
777 SecurityCounters::inc(&shared.security.invalid_modules);
778 }
779 SecurityEvent::NativeDenied { .. } => {
780 SecurityCounters::inc(&shared.security.native_denied);
781 }
782 SecurityEvent::CapabilityDelegated { .. } | SecurityEvent::FlowFinalized { .. } => {}
783 }
784 if let Some(sink) = shared.security_audit.as_ref() {
785 sink.record(event);
787 }
788}
789
790pub(crate) fn record_quota_exceeded(shared: &Shared, err: super::quota::QuotaError) {
791 record_security_event(
792 shared,
793 &super::sandbox::SecurityEvent::QuotaExceeded {
794 kind: err.audit_kind(),
795 },
796 );
797}
798
799fn abort_startup(
800 shared: &Arc<Shared>,
801 workers: Vec<std::thread::JoinHandle<()>>,
802 timer: Option<std::thread::JoinHandle<()>>,
803) {
804 shared.shutdown.store(true, Ordering::Release);
805 shared.timer.shutdown();
806 let (lock, cvar) = &shared.notify;
807 match super::sync_lock::lock(lock, "abort_startup") {
808 Ok(_g) => cvar.notify_all(),
809 Err(e) => super::error::report_fault(e),
810 }
811 for w in workers {
812 let _ = w.join();
813 }
814 if let Some(t) = timer {
815 let _ = t.join();
816 }
817}