wasmer_wasix/syscalls/wasix/
proc_fork.rs

1use super::*;
2use crate::{
3    WasiThreadHandle, capture_store_snapshot,
4    os::task::OwnedTaskStatus,
5    runtime::task_manager::{TaskWasm, TaskWasmRunProperties},
6    state::context_switching::ContextSwitchingEnvironment,
7    syscalls::*,
8};
9use serde::{Deserialize, Serialize};
10use wasmer::Memory;
11
12#[derive(Serialize, Deserialize)]
13pub(crate) struct ForkResult {
14    pub pid: Pid,
15    pub ret: Errno,
16}
17
18/// ### `proc_fork()`
19/// Forks the current process into a new subprocess. If the function
20/// returns a zero then its the new subprocess. If it returns a positive
21/// number then its the current process and the $pid represents the child.
22#[instrument(level = "trace", skip_all, fields(pid = ctx.data().process.pid().raw()), ret)]
23pub fn proc_fork<M: MemorySize>(
24    mut ctx: FunctionEnvMut<'_, WasiEnv>,
25    mut copy_memory: Bool,
26    pid_ptr: WasmPtr<Pid, M>,
27) -> Result<Errno, WasiError> {
28    WasiEnv::do_pending_operations(&mut ctx)?;
29
30    wasi_try_ok!(ctx.data().ensure_static_module().map_err(|_| {
31        warn!("process forking not supported for dynamically linked modules");
32        Errno::Notsup
33    }));
34
35    if let Some(context_switching_environment) = ctx.data().context_switching_environment.as_ref()
36        && context_switching_environment.active_context_id()
37            != context_switching_environment.main_context_id()
38    {
39        warn!(
40            "process forking is only supported from the main context when using WASIX context-switching features"
41        );
42        return Ok(Errno::Notsup);
43    }
44
45    // If we were just restored then we need to return the value instead
46    if let Some(result) = unsafe { handle_rewind::<M, ForkResult>(&mut ctx) } {
47        if result.pid == 0 {
48            trace!("handle_rewind - i am child (ret={})", result.ret);
49        } else {
50            trace!(
51                "handle_rewind - i am parent (child={}, ret={})",
52                result.pid, result.ret
53            );
54        }
55        let memory = unsafe { ctx.data().memory_view(&ctx) };
56        wasi_try_mem_ok!(pid_ptr.write(&memory, result.pid));
57        return Ok(result.ret);
58    }
59    trace!(%copy_memory, "capturing");
60
61    if let Some(vfork) = ctx.data().vfork.as_ref() {
62        warn!("process forking not supported in an active vfork");
63        return Ok(Errno::Notsup);
64    }
65
66    // Fork the environment which will copy all the open file handlers
67    // and associate a new context but otherwise shares things like the
68    // file system interface. The handle to the forked process is stored
69    // in the parent process context
70    let (mut child_env, mut child_handle) = match ctx.data().fork() {
71        Ok(p) => p,
72        Err(err) => {
73            debug!("could not fork process: {err}");
74            // TODO: evaluate the appropriate error code, document it in the spec.
75            return Ok(Errno::Perm);
76        }
77    };
78    let child_pid = child_env.process.pid();
79    let child_finished = child_env.process.finished.clone();
80
81    // We write a zero to the PID before we capture the stack
82    // so that this is what will be returned to the child
83    {
84        let mut inner = ctx.data().process.lock();
85        inner.children.push(child_env.process.clone());
86    }
87    let env = ctx.data();
88    let memory = unsafe { env.memory_view(&ctx) };
89
90    // Setup some properties in the child environment
91    wasi_try_mem_ok!(pid_ptr.write(&memory, 0));
92    let pid = child_env.pid();
93    let tid = child_env.tid();
94
95    // Pass some offsets to the unwind function
96    let pid_offset = pid_ptr.offset();
97
98    // If we are not copying the memory then we act like a `vfork`
99    // instead which will pretend to be the new process for a period
100    // of time until `proc_exec` is called at which point the fork
101    // actually occurs
102    if copy_memory == Bool::False {
103        // Perform the unwind action
104        return unwind::<M, _>(ctx, move |mut ctx, mut memory_stack, rewind_stack| {
105            // Grab all the globals and serialize them
106            let store_data = crate::utils::store::capture_store_snapshot(&mut ctx.as_store_mut())
107                .serialize()
108                .unwrap();
109            let store_data = Bytes::from(store_data);
110
111            // We first fork the environment and replace the current environment
112            // so that the process can continue to prepare for the real fork as
113            // if it had actually forked
114            child_env.swap_inner(ctx.data_mut());
115            std::mem::swap(ctx.data_mut(), &mut child_env);
116            let previous_vfork = ctx.data_mut().vfork.replace(WasiVFork {
117                rewind_stack: rewind_stack.clone(),
118                store_data: store_data.clone(),
119                env: Box::new(child_env),
120                handle: child_handle,
121                is_64bit: M::is_64bit(),
122            });
123            assert!(previous_vfork.is_none()); // Already checked above
124
125            // Carry on as if the fork had taken place (which basically means
126            // it prevents to be the new process with the old one suspended)
127            // Rewind the stack and carry on
128            match rewind::<M, _>(
129                ctx,
130                Some(memory_stack.freeze()),
131                rewind_stack.freeze(),
132                store_data,
133                ForkResult {
134                    pid: 0,
135                    ret: Errno::Success,
136                },
137            ) {
138                Errno::Success => OnCalledAction::InvokeAgain,
139                err => {
140                    warn!("failed - could not rewind the stack - errno={}", err);
141                    OnCalledAction::Trap(Box::new(WasiError::Exit(err.into())))
142                }
143            }
144        });
145    }
146
147    // Create the thread that will back this forked process
148    let state = env.state.clone();
149    let bin_factory = env.bin_factory.clone();
150
151    // Perform the unwind action
152    let snapshot = capture_store_snapshot(&mut ctx.as_store_mut());
153    unwind::<M, _>(ctx, move |mut ctx, mut memory_stack, rewind_stack| {
154        let tasks = ctx.data().tasks().clone();
155        let span = debug_span!(
156            "unwind",
157            memory_stack_len = memory_stack.len(),
158            rewind_stack_len = rewind_stack.len()
159        );
160        let _span_guard = span.enter();
161        let memory_stack = memory_stack.freeze();
162        let rewind_stack = rewind_stack.freeze();
163
164        // Grab all the globals and serialize them
165        let store_data = snapshot.serialize().unwrap();
166        let store_data = Bytes::from(store_data);
167
168        // Now we use the environment and memory references
169        let runtime = child_env.runtime.clone();
170        let tasks = child_env.tasks().clone();
171        let child_memory_stack = memory_stack.clone();
172        let child_rewind_stack = rewind_stack.clone();
173
174        let env_inner = ctx.data().inner();
175        let instance_handles = env_inner.static_module_instance_handles().unwrap();
176        let module = instance_handles.module_clone();
177        let memory = instance_handles.memory_clone();
178        let spawn_type = SpawnType::CopyMemory(memory, ctx.as_store_ref());
179
180        // Spawn a new process with this current execution environment
181        let signaler = Box::new(child_env.process.clone());
182        {
183            let runtime = runtime.clone();
184            let tasks = tasks.clone();
185            let tasks_outer = tasks.clone();
186            let store_data = store_data.clone();
187
188            let run = move |mut props: TaskWasmRunProperties| {
189                let ctx = props.ctx;
190                let mut store = props.store;
191
192                // Rewind the stack and carry on
193                {
194                    trace!("rewinding child");
195                    let mut ctx = ctx.env.clone().into_mut(&mut store);
196                    let (data, mut store) = ctx.data_and_store_mut();
197                    match rewind::<M, _>(
198                        ctx,
199                        Some(child_memory_stack),
200                        child_rewind_stack,
201                        store_data.clone(),
202                        ForkResult {
203                            pid: 0,
204                            ret: Errno::Success,
205                        },
206                    ) {
207                        Errno::Success => OnCalledAction::InvokeAgain,
208                        err => {
209                            warn!(
210                                "wasm rewind failed - could not rewind the stack - errno={}",
211                                err
212                            );
213                            return;
214                        }
215                    };
216                }
217
218                // Invoke the start function
219                run::<M>(ctx, store, child_handle, None);
220            };
221
222            tasks_outer
223                .task_wasm(
224                    TaskWasm::new(Box::new(run), child_env, module, false, false)
225                        .with_globals(snapshot)
226                        .with_memory(spawn_type),
227                )
228                .map_err(|err| {
229                    warn!(
230                        "failed to fork as the process could not be spawned - {}",
231                        err
232                    );
233                    err
234                })
235                .ok();
236        };
237
238        // Rewind the stack and carry on
239        match rewind::<M, _>(
240            ctx,
241            Some(memory_stack),
242            rewind_stack,
243            store_data,
244            ForkResult {
245                pid: child_pid.raw() as Pid,
246                ret: Errno::Success,
247            },
248        ) {
249            Errno::Success => OnCalledAction::InvokeAgain,
250            err => {
251                warn!("failed - could not rewind the stack - errno={}", err);
252                OnCalledAction::Trap(Box::new(WasiError::Exit(err.into())))
253            }
254        }
255    })
256}
257
258fn run<M: MemorySize>(
259    ctx: WasiFunctionEnv,
260    mut store: Store,
261    child_handle: WasiThreadHandle,
262    rewind_state: Option<(RewindState, RewindResultType)>,
263) -> ExitCode {
264    let env = ctx.data(&store);
265    let tasks = env.tasks().clone();
266    let pid = env.pid();
267    let tid = env.tid();
268
269    // If we need to rewind then do so
270    if let Some((rewind_state, rewind_result)) = rewind_state {
271        let mut ctx = ctx.env.clone().into_mut(&mut store);
272        let res = rewind_ext::<M>(
273            &mut ctx,
274            Some(rewind_state.memory_stack),
275            rewind_state.rewind_stack,
276            rewind_state.store_data,
277            rewind_result,
278        );
279        if res != Errno::Success {
280            return res.into();
281        }
282    }
283
284    let mut ret: ExitCode = Errno::Success.into();
285    let (mut store, err) = if ctx.data(&store).thread.is_main() {
286        trace!(%pid, %tid, "re-invoking main");
287        let start = ctx
288            .data(&store)
289            .inner()
290            .static_module_instance_handles()
291            .unwrap()
292            .start
293            .clone()
294            .unwrap();
295        ContextSwitchingEnvironment::run_main_context(&ctx, store, start.into(), vec![])
296    } else {
297        trace!(%pid, %tid, "re-invoking thread_spawn");
298        let start = ctx
299            .data(&store)
300            .inner()
301            .static_module_instance_handles()
302            .unwrap()
303            .thread_spawn
304            .clone()
305            .unwrap();
306        let params = vec![0i32.into(), 0i32.into()];
307        ContextSwitchingEnvironment::run_main_context(&ctx, store, start.into(), params)
308    };
309    if let Err(err) = err {
310        match err.downcast::<WasiError>() {
311            Ok(WasiError::Exit(exit_code)) => {
312                ret = exit_code;
313            }
314            Ok(WasiError::DeepSleep(deep)) => {
315                trace!(%pid, %tid, "entered a deep sleep");
316
317                // Create the respawn function
318                let respawn = {
319                    let tasks = tasks.clone();
320                    let rewind_state = deep.rewind;
321                    move |ctx, store, rewind_result| {
322                        run::<M>(
323                            ctx,
324                            store,
325                            child_handle,
326                            Some((
327                                rewind_state,
328                                RewindResultType::RewindWithResult(rewind_result),
329                            )),
330                        );
331                    }
332                };
333
334                /// Spawns the WASM process after a trigger
335                unsafe {
336                    tasks.resume_wasm_after_poller(Box::new(respawn), ctx, store, deep.trigger)
337                };
338                return Errno::Success.into();
339            }
340            _ => {}
341        }
342    }
343    trace!(%pid, %tid, "child exited (code = {})", ret);
344
345    // Clean up the environment and return the result
346    ctx.on_exit((&mut store), Some(ret));
347
348    // We drop the handle at the last moment which will close the thread
349    drop(child_handle);
350    ret
351}