wasmer_wasix/state/
env.rs

1use std::{
2    collections::HashMap,
3    ops::Deref,
4    path::{Path, PathBuf},
5    str,
6    sync::Arc,
7    time::Duration,
8};
9
10use futures::future::BoxFuture;
11use rand::Rng;
12use virtual_fs::{FileSystem, FsError, VirtualFile};
13use virtual_mio::block_on;
14use virtual_net::DynVirtualNetworking;
15use wasmer::{
16    AsStoreMut, AsStoreRef, ExportError, FunctionEnvMut, Instance, Memory, MemoryType, MemoryView,
17    Module,
18};
19use wasmer_config::package::PackageSource;
20use wasmer_wasix_types::{
21    types::Signal,
22    wasi::{Errno, ExitCode, Snapshot0Clockid},
23    wasix::ThreadStartType,
24};
25use webc::metadata::annotations::Wasi;
26
27#[cfg(feature = "journal")]
28use crate::journal::{DynJournal, JournalEffector, SnapshotTrigger};
29use crate::{
30    Runtime, VirtualTaskManager, WasiControlPlane, WasiEnvBuilder, WasiError, WasiFunctionEnv,
31    WasiResult, WasiRuntimeError, WasiStateCreationError, WasiThreadError, WasiVFork,
32    bin_factory::{BinFactory, BinaryPackage, BinaryPackageCommand},
33    capabilities::Capabilities,
34    fs::{WasiFsRoot, WasiInodes},
35    import_object_for_all_wasi_versions,
36    os::task::{
37        control_plane::ControlPlaneError,
38        process::{WasiProcess, WasiProcessId},
39        thread::{WasiMemoryLayout, WasiThread, WasiThreadHandle, WasiThreadId},
40    },
41    syscalls::platform_clock_time_get,
42};
43use wasmer_types::ModuleHash;
44
45pub use super::handles::*;
46use super::{Linker, WasiState, conv_env_vars};
47
48/// Data required to construct a [`WasiEnv`].
49#[derive(Debug)]
50pub struct WasiEnvInit {
51    pub(crate) state: WasiState,
52    pub runtime: Arc<dyn Runtime + Send + Sync>,
53    pub webc_dependencies: Vec<BinaryPackage>,
54    pub mapped_commands: HashMap<String, PathBuf>,
55    pub bin_factory: BinFactory,
56    pub capabilities: Capabilities,
57
58    pub control_plane: WasiControlPlane,
59    pub memory_ty: Option<MemoryType>,
60    pub process: Option<WasiProcess>,
61    pub thread: Option<WasiThreadHandle>,
62
63    /// Whether to call the `_initialize` function in the WASI module.
64    /// Will be true for regular new instances, but false for threads.
65    pub call_initialize: bool,
66
67    /// Indicates if the calling environment is capable of deep sleeping
68    pub can_deep_sleep: bool,
69
70    /// Indicates if extra tracing should be output
71    pub extra_tracing: bool,
72
73    /// Indicates triggers that will cause a snapshot to be taken
74    #[cfg(feature = "journal")]
75    pub snapshot_on: Vec<SnapshotTrigger>,
76
77    /// Stop running after the first snapshot is taken
78    #[cfg(feature = "journal")]
79    pub stop_running_after_snapshot: bool,
80
81    /// Skip writes to stdout and stderr when bootstrapping from a journal
82    pub skip_stdio_during_bootstrap: bool,
83}
84
85impl WasiEnvInit {
86    pub fn duplicate(&self) -> Self {
87        let inodes = WasiInodes::new();
88
89        // TODO: preserve preopens?
90        let fs =
91            crate::fs::WasiFs::new_with_preopen(&inodes, &[], &[], self.state.fs.root_fs.clone())
92                .unwrap();
93
94        Self {
95            state: WasiState {
96                secret: rand::thread_rng().r#gen::<[u8; 32]>(),
97                inodes,
98                fs,
99                futexs: Default::default(),
100                clock_offset: std::sync::Mutex::new(
101                    self.state.clock_offset.lock().unwrap().clone(),
102                ),
103                args: std::sync::Mutex::new(self.state.args.lock().unwrap().clone()),
104                envs: std::sync::Mutex::new(self.state.envs.lock().unwrap().deref().clone()),
105                signals: std::sync::Mutex::new(self.state.signals.lock().unwrap().deref().clone()),
106                preopen: self.state.preopen.clone(),
107            },
108            runtime: self.runtime.clone(),
109            webc_dependencies: self.webc_dependencies.clone(),
110            mapped_commands: self.mapped_commands.clone(),
111            bin_factory: self.bin_factory.clone(),
112            capabilities: self.capabilities.clone(),
113            control_plane: self.control_plane.clone(),
114            memory_ty: None,
115            process: None,
116            thread: None,
117            call_initialize: self.call_initialize,
118            can_deep_sleep: self.can_deep_sleep,
119            extra_tracing: false,
120            #[cfg(feature = "journal")]
121            snapshot_on: self.snapshot_on.clone(),
122            #[cfg(feature = "journal")]
123            stop_running_after_snapshot: self.stop_running_after_snapshot,
124            skip_stdio_during_bootstrap: self.skip_stdio_during_bootstrap,
125        }
126    }
127}
128
129/// The environment provided to the WASI imports.
130pub struct WasiEnv {
131    pub control_plane: WasiControlPlane,
132    /// Represents the process this environment is attached to
133    pub process: WasiProcess,
134    /// Represents the thread this environment is attached to
135    pub thread: WasiThread,
136    /// Represents the layout of the memory
137    pub layout: WasiMemoryLayout,
138    /// Represents a fork of the process that is currently in play
139    pub vfork: Option<WasiVFork>,
140    /// Seed used to rotate around the events returned by `poll_oneoff`
141    pub poll_seed: u64,
142    /// Shared state of the WASI system. Manages all the data that the
143    /// executing WASI program can see.
144    pub(crate) state: Arc<WasiState>,
145    /// Binary factory attached to this environment
146    pub bin_factory: BinFactory,
147    /// List of the handles that are owned by this context
148    /// (this can be used to ensure that threads own themselves or others)
149    pub owned_handles: Vec<WasiThreadHandle>,
150    /// Implementation of the WASI runtime.
151    pub runtime: Arc<dyn Runtime + Send + Sync + 'static>,
152
153    pub capabilities: Capabilities,
154
155    /// Is this environment capable and setup for deep sleeping
156    pub enable_deep_sleep: bool,
157
158    /// Enables the snap shotting functionality
159    pub enable_journal: bool,
160
161    /// Enables an exponential backoff of the process CPU usage when there
162    /// are no active run tokens (when set holds the maximum amount of
163    /// time that it will pause the CPU)
164    pub enable_exponential_cpu_backoff: Option<Duration>,
165
166    /// Flag that indicates if the environment is currently replaying the journal
167    /// (and hence it should not record new events)
168    pub replaying_journal: bool,
169
170    /// Should stdio be skipped when bootstrapping this module from an existing journal?
171    pub skip_stdio_during_bootstrap: bool,
172
173    /// Flag that indicates the cleanup of the environment is to be disabled
174    /// (this is normally used so that the instance can be reused later on)
175    pub(crate) disable_fs_cleanup: bool,
176
177    /// Inner functions and references that are loaded before the environment starts
178    /// (inner is not safe to send between threads and so it is private and will
179    ///  not be cloned when `WasiEnv` is cloned)
180    /// TODO: We should move this outside of `WasiEnv` with some refactoring
181    inner: WasiInstanceHandlesPointer,
182}
183
184impl std::fmt::Debug for WasiEnv {
185    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
186        write!(f, "env(pid={}, tid={})", self.pid().raw(), self.tid().raw())
187    }
188}
189
190impl Clone for WasiEnv {
191    fn clone(&self) -> Self {
192        Self {
193            control_plane: self.control_plane.clone(),
194            process: self.process.clone(),
195            poll_seed: self.poll_seed,
196            thread: self.thread.clone(),
197            layout: self.layout.clone(),
198            vfork: self.vfork.clone(),
199            state: self.state.clone(),
200            bin_factory: self.bin_factory.clone(),
201            inner: Default::default(),
202            owned_handles: self.owned_handles.clone(),
203            runtime: self.runtime.clone(),
204            capabilities: self.capabilities.clone(),
205            enable_deep_sleep: self.enable_deep_sleep,
206            enable_journal: self.enable_journal,
207            enable_exponential_cpu_backoff: self.enable_exponential_cpu_backoff,
208            replaying_journal: self.replaying_journal,
209            skip_stdio_during_bootstrap: self.skip_stdio_during_bootstrap,
210            disable_fs_cleanup: self.disable_fs_cleanup,
211        }
212    }
213}
214
215impl WasiEnv {
216    /// Construct a new [`WasiEnvBuilder`] that allows customizing an environment.
217    pub fn builder(program_name: impl Into<String>) -> WasiEnvBuilder {
218        WasiEnvBuilder::new(program_name)
219    }
220
221    /// Forking the WasiState is used when either fork or vfork is called
222    pub fn fork(&self) -> Result<(Self, WasiThreadHandle), ControlPlaneError> {
223        let process = self.control_plane.new_process(self.process.module_hash)?;
224        let handle = process.new_thread(self.layout.clone(), ThreadStartType::MainThread)?;
225
226        let thread = handle.as_thread();
227        thread.copy_stack_from(&self.thread);
228
229        let state = Arc::new(self.state.fork());
230
231        let bin_factory = self.bin_factory.clone();
232
233        let new_env = Self {
234            control_plane: self.control_plane.clone(),
235            process,
236            thread,
237            layout: self.layout.clone(),
238            vfork: None,
239            poll_seed: 0,
240            bin_factory,
241            state,
242            inner: Default::default(),
243            owned_handles: Vec::new(),
244            runtime: self.runtime.clone(),
245            capabilities: self.capabilities.clone(),
246            enable_deep_sleep: self.enable_deep_sleep,
247            enable_journal: self.enable_journal,
248            enable_exponential_cpu_backoff: self.enable_exponential_cpu_backoff,
249            replaying_journal: false,
250            skip_stdio_during_bootstrap: self.skip_stdio_during_bootstrap,
251            disable_fs_cleanup: self.disable_fs_cleanup,
252        };
253        Ok((new_env, handle))
254    }
255
256    pub fn pid(&self) -> WasiProcessId {
257        self.process.pid()
258    }
259
260    pub fn tid(&self) -> WasiThreadId {
261        self.thread.tid()
262    }
263
264    /// Returns true if this WASM process will need and try to use
265    /// asyncify while its running which normally means.
266    pub fn will_use_asyncify(&self) -> bool {
267        self.inner()
268            .static_module_instance_handles()
269            .map(|handles| self.enable_deep_sleep || handles.has_stack_checkpoint)
270            .unwrap_or(false)
271    }
272
273    /// Re-initializes this environment so that it can be executed again
274    pub fn reinit(&mut self) -> Result<(), WasiStateCreationError> {
275        // If the cleanup logic is enabled then we need to rebuild the
276        // file descriptors which would have been destroyed when the
277        // main thread exited
278        if !self.disable_fs_cleanup {
279            // First we clear any open files as the descriptors would
280            // otherwise clash
281            if let Ok(mut map) = self.state.fs.fd_map.write() {
282                map.clear();
283            }
284            self.state.fs.preopen_fds.write().unwrap().clear();
285            *self.state.fs.current_dir.lock().unwrap() = "/".to_string();
286
287            // We need to rebuild the basic file descriptors
288            self.state.fs.create_stdin(&self.state.inodes);
289            self.state.fs.create_stdout(&self.state.inodes);
290            self.state.fs.create_stderr(&self.state.inodes);
291            self.state
292                .fs
293                .create_rootfd()
294                .map_err(WasiStateCreationError::WasiFsSetupError)?;
295            self.state
296                .fs
297                .create_preopens(&self.state.inodes, true)
298                .map_err(WasiStateCreationError::WasiFsSetupError)?;
299        }
300
301        // The process and thread state need to be reset
302        self.process = WasiProcess::new(
303            self.process.pid,
304            self.process.module_hash,
305            self.process.compute.clone(),
306        );
307        self.thread = WasiThread::new(
308            self.thread.pid(),
309            self.thread.tid(),
310            self.thread.is_main(),
311            self.process.finished.clone(),
312            self.process.compute.must_upgrade().register_task()?,
313            self.thread.memory_layout().clone(),
314            self.thread.thread_start_type(),
315        );
316
317        Ok(())
318    }
319
320    /// Returns true if this module is capable of deep sleep
321    /// (needs asyncify to unwind and rewind)
322    ///
323    /// # Safety
324    ///
325    /// This function should only be called from within a syscall
326    /// as it accessed objects that are a thread local (functions)
327    pub unsafe fn capable_of_deep_sleep(&self) -> bool {
328        if !self.control_plane.config().enable_asynchronous_threading {
329            return false;
330        }
331        self.inner()
332            .static_module_instance_handles()
333            .map(|handles| {
334                handles.asyncify_get_state.is_some()
335                    && handles.asyncify_start_rewind.is_some()
336                    && handles.asyncify_start_unwind.is_some()
337            })
338            .unwrap_or(false)
339    }
340
341    /// Returns true if this thread can go into a deep sleep
342    pub fn layout(&self) -> &WasiMemoryLayout {
343        &self.layout
344    }
345
346    #[allow(clippy::result_large_err)]
347    pub(crate) fn from_init(
348        init: WasiEnvInit,
349        module_hash: ModuleHash,
350    ) -> Result<Self, WasiRuntimeError> {
351        let process = if let Some(p) = init.process {
352            p
353        } else {
354            init.control_plane.new_process(module_hash)?
355        };
356
357        #[cfg(feature = "journal")]
358        {
359            let mut guard = process.inner.0.lock().unwrap();
360            guard.snapshot_on = init.snapshot_on.into_iter().collect();
361            guard.stop_running_after_checkpoint = init.stop_running_after_snapshot;
362        }
363
364        let layout = WasiMemoryLayout::default();
365        let thread = if let Some(t) = init.thread {
366            t
367        } else {
368            process.new_thread(layout.clone(), ThreadStartType::MainThread)?
369        };
370
371        let mut env = Self {
372            control_plane: init.control_plane,
373            process,
374            thread: thread.as_thread(),
375            layout,
376            vfork: None,
377            poll_seed: 0,
378            state: Arc::new(init.state),
379            inner: Default::default(),
380            owned_handles: Vec::new(),
381            #[cfg(feature = "journal")]
382            enable_journal: init.runtime.active_journal().is_some(),
383            #[cfg(not(feature = "journal"))]
384            enable_journal: false,
385            replaying_journal: false,
386            skip_stdio_during_bootstrap: init.skip_stdio_during_bootstrap,
387            enable_deep_sleep: init.capabilities.threading.enable_asynchronous_threading,
388            enable_exponential_cpu_backoff: init
389                .capabilities
390                .threading
391                .enable_exponential_cpu_backoff,
392            runtime: init.runtime,
393            bin_factory: init.bin_factory,
394            capabilities: init.capabilities,
395            disable_fs_cleanup: false,
396        };
397        env.owned_handles.push(thread);
398
399        // TODO: should not be here - should be callers responsibility!
400        for pkg in &init.webc_dependencies {
401            env.use_package(pkg)?;
402        }
403
404        #[cfg(feature = "sys")]
405        env.map_commands(init.mapped_commands.clone())?;
406
407        Ok(env)
408    }
409
410    // FIXME: use custom error type
411    #[allow(clippy::result_large_err)]
412    pub(crate) fn instantiate(
413        self,
414        module: Module,
415        store: &mut impl AsStoreMut,
416        memory: Option<Memory>,
417        update_layout: bool,
418        call_initialize: bool,
419        parent_linker_and_ctx: Option<(Linker, &mut FunctionEnvMut<WasiEnv>)>,
420    ) -> Result<(Instance, WasiFunctionEnv), WasiThreadError> {
421        let pid = self.process.pid();
422
423        let mut store = store.as_store_mut();
424        let engine = self.runtime().engine();
425        let mut func_env = WasiFunctionEnv::new(&mut store, self);
426
427        let is_dl = super::linker::is_dynamically_linked(&module);
428        if is_dl {
429            let linker = match parent_linker_and_ctx {
430                Some((linker, ctx)) => linker.create_instance_group(ctx, &mut store, &mut func_env),
431                None => {
432                    // FIXME: should we be storing envs as raw byte arrays?
433                    let ld_library_path_owned;
434                    let ld_library_path = {
435                        let envs = func_env.data(&store).state.envs.lock().unwrap();
436                        ld_library_path_owned = match envs
437                            .iter()
438                            .find_map(|env| env.strip_prefix(b"LD_LIBRARY_PATH="))
439                        {
440                            Some(path) => path
441                                .split(|b| *b == b':')
442                                .filter_map(|p| str::from_utf8(p).ok())
443                                .map(PathBuf::from)
444                                .collect::<Vec<_>>(),
445                            None => vec![],
446                        };
447                        ld_library_path_owned
448                            .iter()
449                            .map(AsRef::as_ref)
450                            .collect::<Vec<_>>()
451                    };
452
453                    // TODO: make stack size configurable
454                    Linker::new(
455                        engine,
456                        &module,
457                        &mut store,
458                        memory,
459                        &mut func_env,
460                        8 * 1024 * 1024,
461                        &ld_library_path,
462                    )
463                }
464            };
465
466            match linker {
467                Ok((_, linked_module)) => {
468                    return Ok((linked_module.instance, func_env));
469                }
470                Err(e) => {
471                    tracing::error!(
472                        %pid,
473                        error = &e as &dyn std::error::Error,
474                        "Failed to link DL main module",
475                    );
476                    func_env
477                        .data(&store)
478                        .blocking_on_exit(Some(Errno::Noexec.into()));
479                    return Err(WasiThreadError::LinkError(Arc::new(e)));
480                }
481            }
482        }
483
484        // Let's instantiate the module with the imports.
485        let mut import_object =
486            import_object_for_all_wasi_versions(&module, &mut store, &func_env.env);
487
488        let imported_memory = if let Some(memory) = memory {
489            import_object.define("env", "memory", memory.clone());
490            Some(memory)
491        } else {
492            None
493        };
494
495        // Construct the instance.
496        let instance = match Instance::new(&mut store, &module, &import_object) {
497            Ok(a) => a,
498            Err(err) => {
499                tracing::error!(
500                    %pid,
501                    error = &err as &dyn std::error::Error,
502                    "Instantiation failed",
503                );
504                func_env
505                    .data(&store)
506                    .blocking_on_exit(Some(Errno::Noexec.into()));
507                return Err(WasiThreadError::InstanceCreateFailed(Box::new(err)));
508            }
509        };
510
511        let handles = match imported_memory {
512            Some(memory) => WasiModuleTreeHandles::Static(WasiModuleInstanceHandles::new(
513                memory,
514                &store,
515                instance.clone(),
516                None,
517            )),
518            None => {
519                let exported_memory = instance
520                    .exports
521                    .iter()
522                    .filter_map(|(_, export)| {
523                        if let wasmer::Extern::Memory(memory) = export {
524                            Some(memory.clone())
525                        } else {
526                            None
527                        }
528                    })
529                    .next()
530                    .ok_or(WasiThreadError::ExportError(ExportError::Missing(
531                        "No imported or exported memory found".to_owned(),
532                    )))?;
533                WasiModuleTreeHandles::Static(WasiModuleInstanceHandles::new(
534                    exported_memory,
535                    &store,
536                    instance.clone(),
537                    None,
538                ))
539            }
540        };
541
542        // Initialize the WASI environment
543        if let Err(err) = func_env.initialize_handles_and_layout(
544            &mut store,
545            instance.clone(),
546            handles,
547            None,
548            update_layout,
549        ) {
550            tracing::error!(
551                %pid,
552                error = &err as &dyn std::error::Error,
553                "Initialization failed",
554            );
555            func_env
556                .data(&store)
557                .blocking_on_exit(Some(Errno::Noexec.into()));
558            return Err(WasiThreadError::ExportError(err));
559        }
560
561        // If this module exports an _initialize function, run that first.
562        if call_initialize
563            && let Ok(initialize) = instance.exports.get_function("_initialize")
564            && let Err(err) = crate::run_wasi_func_start(initialize, &mut store)
565        {
566            func_env
567                .data(&store)
568                .blocking_on_exit(Some(Errno::Noexec.into()));
569            return Err(WasiThreadError::InitFailed(Arc::new(anyhow::Error::from(
570                err,
571            ))));
572        }
573
574        Ok((instance, func_env))
575    }
576
577    /// Returns a copy of the current runtime implementation for this environment
578    pub fn runtime(&self) -> &(dyn Runtime + Send + Sync) {
579        self.runtime.deref()
580    }
581
582    /// Returns a copy of the current tasks implementation for this environment
583    pub fn tasks(&self) -> &Arc<dyn VirtualTaskManager> {
584        self.runtime.task_manager()
585    }
586
587    pub fn fs_root(&self) -> &WasiFsRoot {
588        &self.state.fs.root_fs
589    }
590
591    /// Overrides the runtime implementation for this environment
592    pub fn set_runtime<R>(&mut self, runtime: R)
593    where
594        R: Runtime + Send + Sync + 'static,
595    {
596        self.runtime = Arc::new(runtime);
597    }
598
599    /// Returns the number of active threads
600    pub fn active_threads(&self) -> u32 {
601        self.process.active_threads()
602    }
603
604    /// Called by most (if not all) syscalls to process pending operations that are
605    /// cross-cutting, such as signals, thread/process exit, DL operations, etc.
606    pub fn do_pending_operations(ctx: &mut FunctionEnvMut<'_, Self>) -> Result<(), WasiError> {
607        Self::do_pending_link_operations(ctx, true)?;
608        _ = Self::process_signals_and_exit(ctx)?;
609        Ok(())
610    }
611
612    pub fn do_pending_link_operations(
613        ctx: &mut FunctionEnvMut<'_, Self>,
614        fast: bool,
615    ) -> Result<(), WasiError> {
616        if let Some(linker) = ctx.data().inner().linker().cloned()
617            && let Err(e) = linker.do_pending_link_operations(ctx, fast)
618        {
619            tracing::warn!(err = ?e, "Failed to process pending link operations");
620            return Err(WasiError::Exit(Errno::Noexec.into()));
621        }
622        Ok(())
623    }
624
625    /// Porcesses any signals that are batched up or any forced exit codes
626    pub fn process_signals_and_exit(ctx: &mut FunctionEnvMut<'_, Self>) -> WasiResult<bool> {
627        // If a signal handler has never been set then we need to handle signals
628        // differently
629        let env = ctx.data();
630        let env_inner = env
631            .try_inner()
632            .ok_or_else(|| WasiError::Exit(Errno::Fault.into()))?;
633        let inner = env_inner.main_module_instance_handles();
634        if !inner.signal_set {
635            let signals = env.thread.pop_signals();
636            if !signals.is_empty() {
637                for sig in signals {
638                    if sig == Signal::Sigint
639                        || sig == Signal::Sigquit
640                        || sig == Signal::Sigkill
641                        || sig == Signal::Sigabrt
642                        || sig == Signal::Sigpipe
643                    {
644                        let exit_code = env.thread.set_or_get_exit_code_for_signal(sig);
645                        return Err(WasiError::Exit(exit_code));
646                    } else {
647                        tracing::trace!(pid=%env.pid(), ?sig, "Signal ignored");
648                    }
649                }
650                return Ok(Ok(true));
651            }
652        }
653
654        // Check for forced exit
655        if let Some(forced_exit) = env.should_exit() {
656            return Err(WasiError::Exit(forced_exit));
657        }
658
659        Self::process_signals(ctx)
660    }
661
662    /// Porcesses any signals that are batched up
663    pub(crate) fn process_signals(ctx: &mut FunctionEnvMut<'_, Self>) -> WasiResult<bool> {
664        // If a signal handler has never been set then we need to handle signals
665        // differently
666        let env = ctx.data();
667        let env_inner = env
668            .try_inner()
669            .ok_or_else(|| WasiError::Exit(Errno::Fault.into()))?;
670        let inner = env_inner.main_module_instance_handles();
671        if !inner.signal_set {
672            return Ok(Ok(false));
673        }
674
675        // Check for any signals that we need to trigger
676        // (but only if a signal handler is registered)
677        let ret = if inner.signal.as_ref().is_some() {
678            let signals = env.thread.pop_signals();
679            Self::process_signals_internal(ctx, signals)?
680        } else {
681            false
682        };
683
684        Ok(Ok(ret))
685    }
686
687    pub(crate) fn process_signals_internal(
688        ctx: &mut FunctionEnvMut<'_, Self>,
689        mut signals: Vec<Signal>,
690    ) -> Result<bool, WasiError> {
691        let env = ctx.data();
692        let env_inner = env
693            .try_inner()
694            .ok_or_else(|| WasiError::Exit(Errno::Fault.into()))?;
695        let inner = env_inner.main_module_instance_handles();
696        if let Some(handler) = inner.signal.clone() {
697            // We might also have signals that trigger on timers
698            let mut now = 0;
699            {
700                let mut has_signal_interval = false;
701                let inner = env.process.inner.0.lock().unwrap();
702                if !inner.signal_intervals.is_empty() {
703                    now = platform_clock_time_get(Snapshot0Clockid::Monotonic, 1_000_000).unwrap()
704                        as u128;
705                    for signal in inner.signal_intervals.values() {
706                        let elapsed = now - signal.last_signal;
707                        if elapsed >= signal.interval.as_nanos() {
708                            has_signal_interval = true;
709                            break;
710                        }
711                    }
712                }
713                if has_signal_interval {
714                    let mut inner = env.process.inner.0.lock().unwrap();
715                    for signal in inner.signal_intervals.values_mut() {
716                        let elapsed = now - signal.last_signal;
717                        if elapsed >= signal.interval.as_nanos() {
718                            signal.last_signal = now;
719                            signals.push(signal.signal);
720                        }
721                    }
722                }
723            }
724
725            for signal in signals {
726                // Skip over Sigwakeup, which is host-side-only
727                if matches!(signal, Signal::Sigwakeup) {
728                    continue;
729                }
730
731                tracing::trace!(
732                    pid=%ctx.data().pid(),
733                    ?signal,
734                    "processing signal via handler",
735                );
736                if let Err(err) = handler.call(ctx, signal as i32) {
737                    match err.downcast::<WasiError>() {
738                        Ok(wasi_err) => {
739                            tracing::warn!(
740                                pid=%ctx.data().pid(),
741                                wasi_err=&wasi_err as &dyn std::error::Error,
742                                "signal handler wasi error",
743                            );
744                            return Err(wasi_err);
745                        }
746                        Err(runtime_err) => {
747                            // anything other than a kill command should report
748                            // the error, killed things may not gracefully close properly
749                            if signal != Signal::Sigkill {
750                                tracing::warn!(
751                                    pid=%ctx.data().pid(),
752                                    runtime_err=&runtime_err as &dyn std::error::Error,
753                                    "signal handler runtime error",
754                                );
755                            }
756                            return Err(WasiError::Exit(Errno::Intr.into()));
757                        }
758                    }
759                }
760                tracing::trace!(
761                    pid=%ctx.data().pid(),
762                    "signal processed",
763                );
764            }
765            Ok(true)
766        } else {
767            tracing::trace!("no signal handler");
768            Ok(false)
769        }
770    }
771
772    /// Returns an exit code if the thread or process has been forced to exit
773    pub fn should_exit(&self) -> Option<ExitCode> {
774        // Check for forced exit
775        if let Some(forced_exit) = self.thread.try_join() {
776            return Some(forced_exit.unwrap_or_else(|err| {
777                tracing::debug!(
778                    error = &*err as &dyn std::error::Error,
779                    "exit runtime error",
780                );
781                Errno::Child.into()
782            }));
783        }
784        if let Some(forced_exit) = self.process.try_join() {
785            return Some(forced_exit.unwrap_or_else(|err| {
786                tracing::debug!(
787                    error = &*err as &dyn std::error::Error,
788                    "exit runtime error",
789                );
790                Errno::Child.into()
791            }));
792        }
793        None
794    }
795
796    /// Accesses the virtual networking implementation
797    pub fn net(&self) -> &DynVirtualNetworking {
798        self.runtime.networking()
799    }
800
801    /// Providers safe access to the initialized part of WasiEnv
802    /// (it must be initialized before it can be used)
803    pub(crate) fn inner(&self) -> WasiInstanceGuard<'_> {
804        self.inner.get().expect(
805            "You must initialize the WasiEnv before using it and can not pass it between threads",
806        )
807    }
808
809    /// Provides safe access to the initialized part of WasiEnv
810    /// (it must be initialized before it can be used)
811    pub(crate) fn inner_mut(&mut self) -> WasiInstanceGuardMut<'_> {
812        self.inner.get_mut().expect(
813            "You must initialize the WasiEnv before using it and can not pass it between threads",
814        )
815    }
816
817    /// Providers safe access to the initialized part of WasiEnv
818    pub(crate) fn try_inner(&self) -> Option<WasiInstanceGuard<'_>> {
819        self.inner.get()
820    }
821
822    /// Providers safe access to the initialized part of WasiEnv
823    /// (it must be initialized before it can be used)
824    #[allow(dead_code)]
825    pub(crate) fn try_inner_mut(&mut self) -> Option<WasiInstanceGuardMut<'_>> {
826        self.inner.get_mut()
827    }
828
829    /// Sets the inner object (this should only be called when
830    /// creating the instance and eventually should be moved out
831    /// of the WasiEnv)
832    #[doc(hidden)]
833    pub(crate) fn set_inner(&mut self, handles: WasiModuleTreeHandles) {
834        self.inner.set(handles)
835    }
836
837    /// Swaps this inner with the WasiEnvironment of another, this
838    /// is used by the vfork so that the inner handles can be restored
839    /// after the vfork finishes.
840    #[doc(hidden)]
841    pub(crate) fn swap_inner(&mut self, other: &mut Self) {
842        std::mem::swap(&mut self.inner, &mut other.inner);
843    }
844
845    /// Helper function to ensure the module isn't dynamically linked, needed since
846    /// we only support a subset of WASIX functionality for dynamically linked modules.
847    /// Specifically, anything that requires asyncify is not supported right now.
848    pub(crate) fn ensure_static_module(&self) -> Result<(), ()> {
849        self.inner.get().unwrap().ensure_static_module()
850    }
851
852    /// Tries to clone the instance from this environment, but only if it's a static
853    /// module, since dynamically linked modules are made up of multiple instances.
854    pub fn try_clone_instance(&self) -> Option<Instance> {
855        let guard = self.inner.get();
856        match guard {
857            Some(guard) => guard
858                .static_module_instance_handles()
859                .map(|instance| instance.instance.clone()),
860            None => None,
861        }
862    }
863
864    /// Providers safe access to the memory
865    /// (it must be initialized before it can be used)
866    pub fn try_memory(&self) -> Option<WasiInstanceGuardMemory<'_>> {
867        self.try_inner().map(|i| i.memory())
868    }
869
870    /// Providers safe access to the memory
871    /// (it must be initialized before it can be used)
872    ///
873    /// # Safety
874    /// This has been marked as unsafe as it will panic if its executed
875    /// on the wrong thread or before the inner is set
876    pub unsafe fn memory(&self) -> WasiInstanceGuardMemory<'_> {
877        self.try_memory().expect(
878            "You must initialize the WasiEnv before using it and can not pass it between threads",
879        )
880    }
881
882    /// Providers safe access to the memory
883    /// (it must be initialized before it can be used)
884    pub fn try_memory_view<'a>(
885        &self,
886        store: &'a (impl AsStoreRef + ?Sized),
887    ) -> Option<MemoryView<'a>> {
888        self.try_memory().map(|m| m.view(store))
889    }
890
891    /// Providers safe access to the memory
892    /// (it must be initialized before it can be used)
893    ///
894    /// # Safety
895    /// This has been marked as unsafe as it will panic if its executed
896    /// on the wrong thread or before the inner is set
897    pub unsafe fn memory_view<'a>(&self, store: &'a (impl AsStoreRef + ?Sized)) -> MemoryView<'a> {
898        self.try_memory_view(store).expect(
899            "You must initialize the WasiEnv before using it and can not pass it between threads",
900        )
901    }
902
903    /// Copy the lazy reference so that when it's initialized during the
904    /// export phase, all the other references get a copy of it
905    #[allow(dead_code)]
906    pub(crate) fn try_memory_clone(&self) -> Option<Memory> {
907        self.try_inner()
908            .map(|i| i.main_module_instance_handles().memory_clone())
909    }
910
911    /// Get the WASI state
912    pub(crate) fn state(&self) -> &WasiState {
913        &self.state
914    }
915
916    /// Get the `VirtualFile` object at stdout
917    pub fn stdout(&self) -> Result<Option<Box<dyn VirtualFile + Send + Sync + 'static>>, FsError> {
918        self.state.stdout()
919    }
920
921    /// Get the `VirtualFile` object at stderr
922    pub fn stderr(&self) -> Result<Option<Box<dyn VirtualFile + Send + Sync + 'static>>, FsError> {
923        self.state.stderr()
924    }
925
926    /// Get the `VirtualFile` object at stdin
927    pub fn stdin(&self) -> Result<Option<Box<dyn VirtualFile + Send + Sync + 'static>>, FsError> {
928        self.state.stdin()
929    }
930
931    /// Returns true if the process should perform snapshots or not
932    pub fn should_journal(&self) -> bool {
933        self.enable_journal && !self.replaying_journal
934    }
935
936    /// Returns true if the environment has an active journal
937    #[cfg(feature = "journal")]
938    pub fn has_active_journal(&self) -> bool {
939        self.runtime().active_journal().is_some()
940    }
941
942    /// Returns the active journal or fails with an error
943    #[cfg(feature = "journal")]
944    pub fn active_journal(&self) -> Result<&DynJournal, Errno> {
945        self.runtime().active_journal().ok_or_else(|| {
946            tracing::debug!("failed to save thread exit as there is not active journal");
947            Errno::Fault
948        })
949    }
950
951    /// Returns true if a particular snapshot trigger is enabled
952    #[cfg(feature = "journal")]
953    pub fn has_snapshot_trigger(&self, trigger: SnapshotTrigger) -> bool {
954        let guard = self.process.inner.0.lock().unwrap();
955        guard.snapshot_on.contains(&trigger)
956    }
957
958    /// Returns true if a particular snapshot trigger is enabled
959    #[cfg(feature = "journal")]
960    pub fn pop_snapshot_trigger(&mut self, trigger: SnapshotTrigger) -> bool {
961        let mut guard = self.process.inner.0.lock().unwrap();
962        if trigger.only_once() {
963            guard.snapshot_on.remove(&trigger)
964        } else {
965            guard.snapshot_on.contains(&trigger)
966        }
967    }
968
969    /// Internal helper function to get a standard device handle.
970    /// Expects one of `__WASI_STDIN_FILENO`, `__WASI_STDOUT_FILENO`, `__WASI_STDERR_FILENO`.
971    pub fn std_dev_get(
972        &self,
973        fd: crate::syscalls::WasiFd,
974    ) -> Result<Option<Box<dyn VirtualFile + Send + Sync + 'static>>, FsError> {
975        self.state.std_dev_get(fd)
976    }
977
978    /// Unsafe:
979    ///
980    /// This will access the memory of the WASM process and create a view into it which is
981    /// inherently unsafe as it could corrupt the memory. Also accessing the memory is not
982    /// thread safe.
983    pub(crate) unsafe fn get_memory_and_wasi_state<'a>(
984        &'a self,
985        store: &'a impl AsStoreRef,
986        _mem_index: u32,
987    ) -> (MemoryView<'a>, &'a WasiState) {
988        let memory = unsafe { self.memory_view(store) };
989        let state = self.state.deref();
990        (memory, state)
991    }
992
993    /// Unsafe:
994    ///
995    /// This will access the memory of the WASM process and create a view into it which is
996    /// inherently unsafe as it could corrupt the memory. Also accessing the memory is not
997    /// thread safe.
998    pub(crate) unsafe fn get_memory_and_wasi_state_and_inodes<'a>(
999        &'a self,
1000        store: &'a impl AsStoreRef,
1001        _mem_index: u32,
1002    ) -> (MemoryView<'a>, &'a WasiState, &'a WasiInodes) {
1003        let memory = unsafe { self.memory_view(store) };
1004        let state = self.state.deref();
1005        let inodes = &state.inodes;
1006        (memory, state, inodes)
1007    }
1008
1009    pub(crate) fn get_wasi_state_and_inodes(&self) -> (&WasiState, &WasiInodes) {
1010        let state = self.state.deref();
1011        let inodes = &state.inodes;
1012        (state, inodes)
1013    }
1014
1015    pub fn use_package(&self, pkg: &BinaryPackage) -> Result<(), WasiStateCreationError> {
1016        block_on(self.use_package_async(pkg))
1017    }
1018
1019    /// Make all the commands in a [`BinaryPackage`] available to the WASI
1020    /// instance.
1021    ///
1022    /// The [`BinaryPackageCommand::atom()`][cmd-atom] will be saved to
1023    /// `/bin/command`.
1024    ///
1025    /// This will also merge the command's filesystem
1026    /// ([`BinaryPackage::webc_fs`][pkg-fs]) into the current filesystem.
1027    ///
1028    /// [cmd-atom]: crate::bin_factory::BinaryPackageCommand::atom()
1029    /// [pkg-fs]: crate::bin_factory::BinaryPackage::webc_fs
1030    pub async fn use_package_async(
1031        &self,
1032        pkg: &BinaryPackage,
1033    ) -> Result<(), WasiStateCreationError> {
1034        tracing::trace!(package=%pkg.id, "merging package dependency into wasi environment");
1035        let root_fs = &self.state.fs.root_fs;
1036
1037        // We first need to merge the filesystem in the package into the
1038        // main file system, if it has not been merged already.
1039        if let Err(e) = self.state.fs.conditional_union(pkg).await {
1040            tracing::warn!(
1041                error = &e as &dyn std::error::Error,
1042                "Unable to merge the package's filesystem into the main one",
1043            );
1044        }
1045
1046        // Next, make sure all commands will be available
1047
1048        if !pkg.commands.is_empty() {
1049            let _ = root_fs.create_dir(Path::new("/bin"));
1050            let _ = root_fs.create_dir(Path::new("/usr"));
1051            let _ = root_fs.create_dir(Path::new("/usr/bin"));
1052
1053            for command in &pkg.commands {
1054                let path = format!("/bin/{}", command.name());
1055                let path2 = format!("/usr/bin/{}", command.name());
1056                let path = Path::new(path.as_str());
1057                let path2 = Path::new(path2.as_str());
1058
1059                let atom = command.atom();
1060
1061                match root_fs {
1062                    WasiFsRoot::Sandbox(root_fs) => {
1063                        if let Err(err) = root_fs
1064                            .new_open_options_ext()
1065                            .insert_ro_file(path, atom.clone())
1066                        {
1067                            tracing::debug!(
1068                                "failed to add package [{}] command [{}] - {}",
1069                                pkg.id,
1070                                command.name(),
1071                                err
1072                            );
1073                            continue;
1074                        }
1075                        if let Err(err) = root_fs.new_open_options_ext().insert_ro_file(path2, atom)
1076                        {
1077                            tracing::debug!(
1078                                "failed to add package [{}] command [{}] - {}",
1079                                pkg.id,
1080                                command.name(),
1081                                err
1082                            );
1083                            continue;
1084                        }
1085                    }
1086                    WasiFsRoot::Backing(fs) => {
1087                        // FIXME: we're counting on the fs being a mem_fs here. Otherwise, memory
1088                        // usage will be very high.
1089                        let mut f = fs.new_open_options().create(true).write(true).open(path)?;
1090                        if let Err(e) = f.copy_from_owned_buffer(&atom).await {
1091                            tracing::warn!(
1092                                error = &e as &dyn std::error::Error,
1093                                "Unable to copy file reference",
1094                            );
1095                        }
1096                        let mut f = fs.new_open_options().create(true).write(true).open(path2)?;
1097                        if let Err(e) = f.copy_from_owned_buffer(&atom).await {
1098                            tracing::warn!(
1099                                error = &e as &dyn std::error::Error,
1100                                "Unable to copy file reference",
1101                            );
1102                        }
1103                    }
1104                }
1105
1106                let mut package = pkg.clone();
1107                package.entrypoint_cmd = Some(command.name().to_string());
1108                let package_arc = Arc::new(package);
1109                self.bin_factory
1110                    .set_binary(path.to_string_lossy().as_ref(), &package_arc);
1111                self.bin_factory
1112                    .set_binary(path2.to_string_lossy().as_ref(), &package_arc);
1113
1114                tracing::debug!(
1115                    package=%pkg.id,
1116                    command_name=command.name(),
1117                    path=%path.display(),
1118                    "Injected a command into the filesystem",
1119                );
1120            }
1121        }
1122
1123        Ok(())
1124    }
1125
1126    /// Given a list of packages, load them from the registry and make them
1127    /// available.
1128    pub fn uses<I>(&self, uses: I) -> Result<(), WasiStateCreationError>
1129    where
1130        I: IntoIterator<Item = String>,
1131    {
1132        let rt = self.runtime();
1133
1134        for package_name in uses {
1135            let specifier = package_name.parse::<PackageSource>().map_err(|e| {
1136                WasiStateCreationError::WasiIncludePackageError(format!(
1137                    "package_name={package_name}, {e}",
1138                ))
1139            })?;
1140            let pkg = block_on(BinaryPackage::from_registry(&specifier, rt)).map_err(|e| {
1141                WasiStateCreationError::WasiIncludePackageError(format!(
1142                    "package_name={package_name}, {e}",
1143                ))
1144            })?;
1145            self.use_package(&pkg)?;
1146        }
1147
1148        Ok(())
1149    }
1150
1151    #[cfg(feature = "sys")]
1152    pub fn map_commands(
1153        &self,
1154        map_commands: std::collections::HashMap<String, std::path::PathBuf>,
1155    ) -> Result<(), WasiStateCreationError> {
1156        // Load all the mapped atoms
1157        #[allow(unused_imports)]
1158        use std::path::Path;
1159
1160        use shared_buffer::OwnedBuffer;
1161        #[allow(unused_imports)]
1162        use virtual_fs::FileSystem;
1163
1164        #[cfg(feature = "sys")]
1165        for (command, target) in map_commands.iter() {
1166            // Read the file
1167            let file = std::fs::read(target).map_err(|err| {
1168                WasiStateCreationError::WasiInheritError(format!(
1169                    "failed to read local binary [{}] - {}",
1170                    target.as_os_str().to_string_lossy(),
1171                    err
1172                ))
1173            })?;
1174            let file = OwnedBuffer::from(file);
1175
1176            if let WasiFsRoot::Sandbox(root_fs) = &self.state.fs.root_fs {
1177                let _ = root_fs.create_dir(Path::new("/bin"));
1178                let _ = root_fs.create_dir(Path::new("/usr"));
1179                let _ = root_fs.create_dir(Path::new("/usr/bin"));
1180
1181                let path = format!("/bin/{command}");
1182                let path = Path::new(path.as_str());
1183                if let Err(err) = root_fs
1184                    .new_open_options_ext()
1185                    .insert_ro_file(path, file.clone())
1186                {
1187                    tracing::debug!("failed to add atom command [{}] - {}", command, err);
1188                    continue;
1189                }
1190                let path = format!("/usr/bin/{command}");
1191                let path = Path::new(path.as_str());
1192                if let Err(err) = root_fs.new_open_options_ext().insert_ro_file(path, file) {
1193                    tracing::debug!("failed to add atom command [{}] - {}", command, err);
1194                    continue;
1195                }
1196            } else {
1197                tracing::debug!(
1198                    "failed to add atom command [{}] to the root file system as it is not sandboxed",
1199                    command
1200                );
1201                continue;
1202            }
1203        }
1204        Ok(())
1205    }
1206
1207    /// Cleans up all the open files (if this is the main thread)
1208    #[allow(clippy::await_holding_lock)]
1209    pub fn blocking_on_exit(&self, process_exit_code: Option<ExitCode>) {
1210        let cleanup = self.on_exit(process_exit_code);
1211        block_on(cleanup);
1212    }
1213
1214    /// Cleans up all the open files (if this is the main thread)
1215    #[allow(clippy::await_holding_lock)]
1216    pub fn on_exit(&self, process_exit_code: Option<ExitCode>) -> BoxFuture<'static, ()> {
1217        const CLEANUP_TIMEOUT: Duration = Duration::from_secs(10);
1218
1219        // If snap-shooting is enabled then we should record an event that the thread has exited.
1220        #[cfg(feature = "journal")]
1221        if self.should_journal() && self.has_active_journal() {
1222            if let Err(err) = JournalEffector::save_thread_exit(self, self.tid(), process_exit_code)
1223            {
1224                tracing::warn!("failed to save snapshot event for thread exit - {}", err);
1225            }
1226
1227            if self.thread.is_main()
1228                && let Err(err) = JournalEffector::save_process_exit(self, process_exit_code)
1229            {
1230                tracing::warn!("failed to save snapshot event for process exit - {}", err);
1231            }
1232        }
1233
1234        // If the process wants to exit, also close all files and terminate it
1235        if let Some(process_exit_code) = process_exit_code {
1236            let process = self.process.clone();
1237            let disable_fs_cleanup = self.disable_fs_cleanup;
1238            let pid = self.pid();
1239
1240            let timeout = self.tasks().sleep_now(CLEANUP_TIMEOUT);
1241            let state = self.state.clone();
1242            Box::pin(async move {
1243                if !disable_fs_cleanup {
1244                    tracing::trace!(pid = %pid, "cleaning up open file handles");
1245
1246                    // Perform the clean operation using the asynchronous runtime
1247                    tokio::select! {
1248                        _ = timeout => {
1249                            tracing::debug!(
1250                                "WasiEnv::cleanup has timed out after {CLEANUP_TIMEOUT:?}"
1251                            );
1252                        },
1253                        _ = state.fs.close_all() => { }
1254                    }
1255
1256                    // Now send a signal that the thread is terminated
1257                    process.signal_process(Signal::Sigquit);
1258                }
1259
1260                // Terminate the process
1261                process.terminate(process_exit_code);
1262            })
1263        } else {
1264            Box::pin(async {})
1265        }
1266    }
1267
1268    pub fn prepare_spawn(&self, cmd: &BinaryPackageCommand) {
1269        if let Ok(Some(Wasi {
1270            main_args,
1271            env: env_vars,
1272            exec_name,
1273            ..
1274        })) = cmd.metadata().wasi()
1275        {
1276            if let Some(env_vars) = env_vars {
1277                let env_vars = env_vars
1278                    .into_iter()
1279                    .map(|env_var| {
1280                        let (k, v) = env_var.split_once('=').unwrap();
1281
1282                        (k.to_string(), v.as_bytes().to_vec())
1283                    })
1284                    .collect::<Vec<_>>();
1285
1286                let env_vars = conv_env_vars(env_vars);
1287
1288                self.state
1289                    .envs
1290                    .lock()
1291                    .unwrap()
1292                    .extend_from_slice(env_vars.as_slice());
1293            }
1294
1295            if let Some(main_args) = main_args {
1296                let mut args: std::sync::MutexGuard<'_, Vec<String>> =
1297                    self.state.args.lock().unwrap();
1298                // Insert main-args before user args
1299                args.splice(1..1, main_args);
1300            }
1301
1302            if let Some(exec_name) = exec_name {
1303                self.state.args.lock().unwrap()[0] = exec_name;
1304            }
1305        }
1306    }
1307}