Skip to main content

abi_application/
process.rs

1//! Native process capabilities: identity, exit, spawn, wait and environment.
2//!
3//! A native process is the Core task that runs a native entry on a stackful
4//! coroutine. The task owns the identity, the parent link, the user and group
5//! and the environment. This module adds no process table: it reads and writes
6//! the task manager, and starts children through the host's executable path.
7use crate::{
8    Directory, File, Heap, HostState, Resources, Status, XILA_RIGHT_READ, XilaString, canonical,
9    enter, is_in_coroutine, path_input,
10    registry::{self, Handle},
11    suspend_dynamic, suspend_on_cancellable,
12};
13use alloc::{boxed::Box, string::String, vec::Vec};
14use core::{
15    ffi::c_char,
16    future::Future,
17    pin::{Pin, pin},
18    ptr::{self, NonNull},
19    slice, str,
20};
21use file_system::{IntoIoErrorKind, PathOwned};
22use task::{EnvironmentVariable, JoinHandle, TaskIdentifier};
23use virtual_file_system::{File as VfsFile, VirtualFileSystem};
24
25/// `xila_process_wait` flag: return `WouldBlock` instead of waiting for a running child.
26pub const XILA_WAIT_NO_HANG: u32 = 1;
27/// `XilaSpawn.flags`: give the child the right to connect (and to send datagrams).
28/// The value is `XILA_NETWORK_CONNECT`'s.
29pub const XILA_SPAWN_NETWORK_CONNECT: u32 = 1;
30/// `XilaSpawn.flags`: give the child the right to listen and bind. The value is
31/// `XILA_NETWORK_LISTEN`'s.
32pub const XILA_SPAWN_NETWORK_LISTEN: u32 = 2;
33/// `XilaSpawn.flags`: give the child the right to resolve names. The value is
34/// `XILA_NETWORK_RESOLVE`'s.
35pub const XILA_SPAWN_NETWORK_RESOLVE: u32 = 4;
36const SPAWN_NETWORK: u32 =
37    XILA_SPAWN_NETWORK_CONNECT | XILA_SPAWN_NETWORK_LISTEN | XILA_SPAWN_NETWORK_RESOLVE;
38
39/// The exit status of a child that could not start its entry.
40///
41/// An exit status is any `int32_t`, so no value is outside the range a program can
42/// return: this one is indistinguishable from a program that calls `exit(-1)`. A
43/// parent that needs to tell them apart must have the child report success some
44/// other way, such as a line on its standard output.
45const START_FAILURE: i32 = -1;
46
47/// The native status of a task manager failure: the canonical I/O kind mapping.
48fn task_status(error: task::Error) -> Status {
49    error.into_io_error_kind().into()
50}
51
52/// A directory capability granted to a child as its home.
53pub struct HomeGrant {
54    pub path: PathOwned,
55    pub rights: u8,
56}
57
58/// What the host needs to start a child: the validated, owned result of
59/// `xila_process_spawn`'s arguments. The three standard streams are duplicates of the
60/// parent's, owned by the request.
61#[non_exhaustive]
62pub struct SpawnRequest {
63    /// Absolute, canonical VFS path of the executable, inside the caller's directory capability.
64    pub path: PathOwned,
65    pub arguments: Vec<String>,
66    /// The child's whole environment, already validated, or `None` to give it a copy
67    /// of the parent's. A later variable overrides an earlier one of the same name.
68    pub environment: Option<Vec<EnvironmentVariable>>,
69    pub standard_input: VfsFile<'static>,
70    pub standard_output: VfsFile<'static>,
71    pub standard_error: VfsFile<'static>,
72    pub home: Option<HomeGrant>,
73    /// The child's network rights, already checked to be a subset of the parent's.
74    /// Zero grants no network.
75    pub network: u32,
76}
77
78/// The result of starting a child: its join handle, which carries its exit status, and
79/// its task identifier, which is the child's process identifier.
80pub type SpawnFuture =
81    Pin<Box<dyn Future<Output = Result<(JoinHandle<isize>, TaskIdentifier), Status>>>>;
82
83/// The host services behind a process capability. Core implements them for its
84/// executable context, so a spawned child goes through `executable::execute`.
85pub trait ProcessHost: Sync {
86    fn task_manager(&self) -> &'static task::Manager;
87    fn virtual_file_system(&self) -> &'static VirtualFileSystem;
88    /// The graphics manager the process draws on, or `None` when the system has
89    /// no display. `xila_graphics_call` reports Unavailable without one.
90    #[cfg(feature = "graphics")]
91    fn graphics_manager(&self) -> Option<&'static graphics::Manager> {
92        None
93    }
94    /// The network stack the process's sockets use, or `None` when the system has none.
95    /// A process gets `XilaStartup.network` only when its launch granted network rights
96    /// ([`ProcessLaunch::network`]) and this returns a manager.
97    #[cfg(feature = "network")]
98    fn network_manager(&self) -> Option<&'static network::Manager> {
99        None
100    }
101    /// Start the executable as a child task on the caller's executor. The child's
102    /// coroutine must enter its program through [`ProcessLaunch::run`].
103    fn spawn(&'static self, request: SpawnRequest) -> SpawnFuture;
104}
105
106/// What a child's coroutine needs to become a process, carried from the spawn
107/// request to the loader that starts its entry.
108pub struct ProcessLaunch {
109    pub host: &'static dyn ProcessHost,
110    /// Replaces the environment the task copied from its parent.
111    pub environment: Option<Vec<EnvironmentVariable>>,
112    /// Becomes the child's home directory capability, bound to the child's task.
113    pub home: Option<HomeGrant>,
114    /// The network rights the process gets (`XILA_NETWORK_CONNECT`, `_LISTEN`,
115    /// `_RESOLVE`). Zero, the default for every launch, grants no network: nothing is
116    /// inherited, and a parent can only pass a subset of its own rights to a child.
117    pub network: u32,
118}
119
120impl ProcessLaunch {
121    /// Run a native entry as a process, on the calling coroutine, with the startup
122    /// data in `state`. The coroutine runs inside the process's task, which is how
123    /// the process learns its identity.
124    ///
125    /// Returns the entry's exit status, or -1 if the process could not be set up:
126    /// the coroutine is not on a registered task or the task is gone.
127    ///
128    /// Every resource the process owns is held by `state`, which belongs to the
129    /// host side of the task, not to this coroutine's stack: the call keeps only
130    /// pointers to it. The home grant moves into the state before the first
131    /// suspension, and the environment is owned by that suspended future, which a
132    /// cancellation drops in place. Returning from the entry, a failed setup and
133    /// `xila_process_exit` each release the state's resources once, before the
134    /// process ends; a cancellation leaves them for the host to release with
135    /// [`HostState::release`]. A worker that exits the process discards the main
136    /// coroutine's frames, which own nothing for the same reason.
137    ///
138    /// # Safety
139    /// Same contract as [`crate::run_main`], and `state` and `heap` stay at their
140    /// addresses and live until native execution has permanently ended. The caller
141    /// must keep no other owned object live above this call.
142    pub unsafe fn run(
143        self,
144        state: NonNull<HostState>,
145        entry: unsafe extern "C" fn(*const crate::XilaStartup) -> i32,
146        heap: NonNull<Heap>,
147    ) -> i32 {
148        let Self {
149            host,
150            environment,
151            home,
152            network,
153        } = self;
154        let manager = host.task_manager();
155        let resources = unsafe { &raw mut (*state.as_ptr()).resources };
156        // SAFETY: the caller guarantees the state is live; nothing else uses it yet.
157        // The capability belongs to the root task until the process learns its own, below.
158        unsafe {
159            (*resources).home = home.map(|grant| {
160                Directory::granted(
161                    host.virtual_file_system(),
162                    task::Manager::ROOT_TASK_IDENTIFIER,
163                    grant.path,
164                    grant.rights,
165                )
166            });
167        }
168        // `environment` is consumed here, by a future that owns it: nothing owned remains
169        // live in a frame when C starts.
170        let identity = suspend_on_cancellable(async {
171            async {
172                let task = manager.try_get_current_task_identifier().await?;
173                if let Some(environment) = environment {
174                    manager
175                        .replace_environment_variables(task, environment)
176                        .await?;
177                }
178                Ok::<_, task::Error>((task, manager.get_name(task).await?))
179            }
180            .await
181            .map_err(task_status)
182        });
183        let Ok((task, program_name)) = identity else {
184            // SAFETY: nothing has started that could use the resources.
185            unsafe { Resources::release(resources) };
186            return START_FAILURE;
187        };
188        // SAFETY: the caller guarantees the state is live; nothing else uses it yet.
189        unsafe {
190            (*resources).program_name = program_name;
191            if let Some(home) = (*resources).home.as_mut() {
192                home.task = task;
193            }
194            // Only an explicit grant gives the process network authority.
195            #[cfg(feature = "network")]
196            if network != 0
197                && let Some(manager) = host.network_manager()
198            {
199                (*resources).network = crate::Network::new(manager, network).ok();
200            }
201            #[cfg(not(feature = "network"))]
202            let _ = network;
203            enter(state, entry, heap, Some((host, task)))
204        }
205    }
206}
207
208/// Opaque capability of the running process: its identity, environment, children and
209/// exit. The host grants it through `XilaStartup.process`; the pointer is borrowed for
210/// the entry call and a process must not pass it to another process.
211pub struct Process {
212    pub(crate) host: &'static dyn ProcessHost,
213    pub(crate) task: TaskIdentifier,
214    pub(crate) resources: *mut Resources,
215}
216
217impl Process {
218    /// The network rights this process was granted, zero without a network capability.
219    fn network_rights(&self) -> u32 {
220        #[cfg(feature = "network")]
221        {
222            // SAFETY: the resources live as long as the process capability.
223            unsafe { (*self.resources).network.as_ref() }
224                .map_or(0, |network| u32::from(network.rights))
225        }
226        #[cfg(not(feature = "network"))]
227        {
228            0
229        }
230    }
231}
232
233/// A spawned child, owned by the process that spawned it. It holds the child's
234/// exit status until the owner waits for it, so a child that finished and was not
235/// waited for costs one signal slot and no task. `xila_process_child_close`
236/// releases it, waited for or not.
237pub struct Child {
238    owner: TaskIdentifier,
239    /// The child's process identifier, known once it started.
240    id: u32,
241    handle: Option<JoinHandle<isize>>,
242}
243
244impl Handle for Child {
245    unsafe fn close(raw: *mut Self) {
246        // SAFETY: the registry holds only live handles that `xila_process_spawn` made.
247        let _ = unsafe { xila_process_child_close(raw) };
248    }
249}
250
251/// Arguments of `xila_process_spawn`. Set `size` to `sizeof(XilaSpawn)`. All
252/// pointers are borrowed for the call.
253#[repr(C)]
254pub struct Spawn {
255    pub size: u32,
256    /// The network rights the child gets (`XILA_SPAWN_NETWORK_*`). Zero gives it no
257    /// network. Each right must be one the parent holds: a child never gets more than
258    /// its parent. Other bits are reserved and must be zero.
259    pub flags: u32,
260    /// Arguments of the child, with no implicit program name. A null array has count zero.
261    pub arguments: *const XilaString,
262    pub argument_count: usize,
263    /// The child's whole environment as `NAME=VALUE` strings, a later entry overriding an
264    /// earlier one. A null array gives the child a copy of the parent's environment
265    /// and requires count zero. An array with count zero gives it an empty one.
266    pub environment: *const XilaString,
267    pub environment_count: usize,
268    /// Streams the child gets as duplicates of these. All three are required.
269    pub standard_input: *const File,
270    pub standard_output: *const File,
271    pub standard_error: *const File,
272    /// Optional home directory capability the child gets a copy of.
273    pub home: *const Directory,
274}
275
276/// A task identifier as the ABI reports it: `u16` on 32-bit targets, already `u32` on 64-bit ones.
277#[allow(clippy::unnecessary_cast)]
278pub(crate) fn identifier(task: TaskIdentifier) -> u32 {
279    task.into_inner() as u32
280}
281
282/// Check that the capability is the running task's, which is how a process cannot act
283/// through another process's capability.
284async fn is_current(process: &Process) -> Result<(), Status> {
285    match process
286        .host
287        .task_manager()
288        .try_get_current_task_identifier()
289        .await
290    {
291        Ok(task) if task == process.task => Ok(()),
292        _ => Err(Status::InvalidArgument),
293    }
294}
295
296pub(crate) fn this<'a>(process: *const Process) -> Result<&'a Process, Status> {
297    // SAFETY: the caller guarantees a non-null pointer is a live capability.
298    unsafe { process.as_ref() }.ok_or(Status::InvalidArgument)
299}
300
301/// Read the process's identifier.
302/// # Safety
303/// Process must be a live capability and the output aligned and writable.
304pub unsafe extern "C" fn xila_process_id(process: *const Process, id: *mut u32) -> Status {
305    let result = this(process).and_then(|process| {
306        if id.is_null() {
307            return Err(Status::InvalidArgument);
308        }
309        unsafe { id.write(identifier(process.task)) };
310        Ok(())
311    });
312    result.map_or_else(|error| error, |()| Status::Ok)
313}
314
315/// Read the identifier of the process that spawned this one. A process whose parent
316/// has exited is adopted by the root task, identifier zero.
317/// # Safety
318/// Process must be a live capability and the output aligned and writable.
319pub unsafe extern "C" fn xila_process_parent_id(process: *const Process, id: *mut u32) -> Status {
320    let result = this(process).and_then(|process| {
321        if id.is_null() {
322            return Err(Status::InvalidArgument);
323        }
324        let mut parent = Err(Status::Unavailable);
325        suspend_dynamic(pin!(async {
326            parent = process
327                .host
328                .task_manager()
329                .get_parent(process.task)
330                .await
331                .map_err(task_status);
332        }));
333        unsafe { id.write(identifier(parent?)) };
334        Ok(())
335    });
336    result.map_or_else(|error| error, |()| Status::Ok)
337}
338
339/// Stop every peer, release the process's resources, and exit without unwinding.
340/// Stopped peers are never resumed: their frames are discarded and their stacks freed
341/// when the process's driver ends, as for a cancelled process. The loader then releases
342/// the process heap and image.
343///
344/// Both main and worker entries run without host-owned guards in callback
345/// frames, so abandoning the calling stack does not skip their cleanup.
346/// # Safety
347/// Process must be the running process's capability.
348pub unsafe extern "C" fn xila_process_exit(process: *const Process, status: i32) -> Status {
349    let process = match this(process) {
350        Ok(process) => process,
351        Err(error) => return error,
352    };
353    if !is_in_coroutine() {
354        return Status::Unsupported;
355    }
356    if let Err(error) = crate::threads::prepare_exit(ptr::from_ref(process)) {
357        return error;
358    }
359    let mut current = Err(Status::Unavailable);
360    suspend_dynamic(pin!(async {
361        current = is_current(process).await;
362    }));
363    if let Err(error) = current {
364        return error;
365    }
366    // SAFETY: the pointer is the live host state, which the coroutine's frames do
367    // not hold. The driver will never poll another coroutine, even if cleanup suspends.
368    unsafe { Resources::release(process.resources) };
369    // The startup block lives in the released state: nothing may find it any more.
370    crate::threads::bind_startup(ptr::null());
371    crate::exit_coroutine(status)
372}
373
374/// A UTF-8 name that can key an environment variable.
375unsafe fn env_name<'a>(name: *const c_char, length: usize) -> Result<&'a str, Status> {
376    let name = unsafe { path_input(name, length)? };
377    if name.is_empty() || name.contains(['=', '\0']) {
378        return Err(Status::InvalidArgument);
379    }
380    Ok(name)
381}
382
383/// UTF-8 text without NUL. A null pointer is valid only at length zero.
384unsafe fn env_value<'a>(value: *const c_char, length: usize) -> Result<&'a str, Status> {
385    if length == 0 {
386        return Ok("");
387    }
388    let value = unsafe { path_input(value, length)? };
389    if value.contains('\0') {
390        return Err(Status::InvalidArgument);
391    }
392    Ok(value)
393}
394
395/// A caller-owned environment output buffer and length pointer.
396struct EnvOutput {
397    buffer: *mut c_char,
398    capacity: usize,
399    length: *mut usize,
400}
401
402impl EnvOutput {
403    fn new(buffer: *mut c_char, capacity: usize, length: *mut usize) -> Result<Self, Status> {
404        if length.is_null() || capacity > isize::MAX as usize || (capacity != 0 && buffer.is_null())
405        {
406            return Err(Status::InvalidArgument);
407        }
408        Ok(Self {
409            buffer,
410            capacity,
411            length,
412        })
413    }
414
415    /// The caller must have provided writable output pointers.
416    unsafe fn write(self, bytes: &[u8]) -> Result<(), Status> {
417        unsafe { self.length.write(bytes.len()) };
418        if bytes.len() > self.capacity {
419            return Err(Status::BufferTooSmall);
420        }
421        if !bytes.is_empty() {
422            unsafe { ptr::copy_nonoverlapping(bytes.as_ptr(), self.buffer.cast(), bytes.len()) };
423        }
424        Ok(())
425    }
426}
427
428/// Read an environment variable. The value is copied without a terminator; the
429/// length is stored on success and on `BufferTooSmall`, which leaves the buffer
430/// unchanged. A null buffer is allowed at capacity zero. A missing variable returns
431/// `NotFound`.
432/// # Safety
433/// Process must be a live capability. Name must be readable for its length, the buffer
434/// writable for its capacity and the length output aligned and writable.
435pub unsafe extern "C" fn xila_env_get(
436    process: *const Process,
437    name: *const c_char,
438    name_length: usize,
439    buffer: *mut c_char,
440    capacity: usize,
441    value_length: *mut usize,
442) -> Status {
443    let result = (|| {
444        let process = this(process)?;
445        let output = EnvOutput::new(buffer, capacity, value_length)?;
446        let name = unsafe { env_name(name, name_length)? };
447        let mut found = Err(Status::Unavailable);
448        suspend_dynamic(pin!(async {
449            found = process
450                .host
451                .task_manager()
452                .get_environment_variable(process.task, name)
453                .await
454                .map_err(|error| match error {
455                    // The getter's only way to say that the variable does not exist.
456                    task::Error::InvalidEnvironmentVariable => Status::NotFound,
457                    error => task_status(error),
458                });
459        }));
460        let variable = found?;
461        unsafe { output.write(variable.get_value().as_bytes()) }
462    })();
463    result.map_or_else(|error| error, |()| Status::Ok)
464}
465
466/// Set an environment variable of this process, replacing any value. Children
467/// spawned afterwards inherit a copy; earlier children and the parent are unaffected.
468/// A name is non-empty UTF-8 without `=` or NUL, a value is UTF-8 without NUL and a
469/// null value pointer is valid at length zero.
470/// # Safety
471/// Process must be a live capability and the strings readable for their lengths.
472pub unsafe extern "C" fn xila_env_set(
473    process: *const Process,
474    name: *const c_char,
475    name_length: usize,
476    value: *const c_char,
477    value_length: usize,
478) -> Status {
479    let result = (|| {
480        let process = this(process)?;
481        let name = unsafe { env_name(name, name_length)? };
482        let value = unsafe { env_value(value, value_length)? };
483        let mut set = Err(Status::Unavailable);
484        suspend_dynamic(pin!(async {
485            set = process
486                .host
487                .task_manager()
488                .set_environment_variable(process.task, name, value)
489                .await
490                .map_err(task_status);
491        }));
492        set
493    })();
494    result.map_or_else(|error| error, |()| Status::Ok)
495}
496
497/// Remove an environment variable of this process. A missing variable succeeds.
498/// # Safety
499/// Process must be a live capability and the name readable for its length.
500pub unsafe extern "C" fn xila_env_remove(
501    process: *const Process,
502    name: *const c_char,
503    name_length: usize,
504) -> Status {
505    let result = (|| {
506        let process = this(process)?;
507        let name = unsafe { env_name(name, name_length)? };
508        let mut removed = Err(Status::Unavailable);
509        suspend_dynamic(pin!(async {
510            removed = process
511                .host
512                .task_manager()
513                .remove_environment_variable(process.task, name)
514                .await
515                .map_err(task_status);
516        }));
517        removed
518    })();
519    result.map_or_else(|error| error, |()| Status::Ok)
520}
521
522/// Copy the zero-based environment entry as `NAME=VALUE` without a terminator.
523/// Output follows the same rules as `xila_env_get`. `NotFound` marks the end.
524/// Indices can change when the environment is mutated.
525/// # Safety
526/// Process must be a live capability, the buffer writable for its capacity and
527/// the length output aligned and writable.
528pub unsafe extern "C" fn xila_env_entry(
529    process: *const Process,
530    index: usize,
531    buffer: *mut c_char,
532    capacity: usize,
533    entry_length: *mut usize,
534) -> Status {
535    let result = (|| {
536        let process = this(process)?;
537        let output = EnvOutput::new(buffer, capacity, entry_length)?;
538        let mut entry = Err(Status::Unavailable);
539        suspend_dynamic(pin!(async {
540            entry = process
541                .host
542                .task_manager()
543                .get_environment_variable_at(process.task, index)
544                .await
545                .map_err(task_status);
546        }));
547        let entry = entry?.ok_or(Status::NotFound)?;
548        unsafe { output.write(entry.get_raw().to_bytes()) }
549    })();
550    result.map_or_else(|error| error, |()| Status::Ok)
551}
552
553/// Borrow a counted array of strings as a slice, which is empty at count zero.
554unsafe fn entries<'a>(array: *const XilaString, count: usize) -> Result<&'a [XilaString], Status> {
555    if count == 0 {
556        return Ok(&[]);
557    }
558    if array.is_null() || count > isize::MAX as usize / size_of::<XilaString>() {
559        return Err(Status::InvalidArgument);
560    }
561    Ok(unsafe { slice::from_raw_parts(array, count) })
562}
563
564/// Borrow one string as UTF-8 text.
565unsafe fn text<'a>(entry: &XilaString) -> Result<&'a str, Status> {
566    if entry.length == 0 {
567        return Ok("");
568    }
569    if entry.data.is_null() || entry.length > isize::MAX as usize {
570        return Err(Status::InvalidArgument);
571    }
572    str::from_utf8(unsafe { slice::from_raw_parts(entry.data.cast(), entry.length) })
573        .map_err(|_| Status::InvalidArgument)
574}
575
576/// Copy the argument strings of a spawn.
577unsafe fn arguments(array: *const XilaString, count: usize) -> Result<Vec<String>, Status> {
578    let entries = unsafe { entries(array, count)? };
579    let mut arguments = Vec::with_capacity(entries.len());
580    for entry in entries {
581        arguments.push(String::from(unsafe { text(entry)? }));
582    }
583    Ok(arguments)
584}
585
586/// Validate the `NAME=VALUE` entries of an explicit environment once, so the host
587/// receives them as the task manager stores them.
588unsafe fn environment(
589    array: *const XilaString,
590    count: usize,
591) -> Result<Vec<EnvironmentVariable>, Status> {
592    let entries = unsafe { entries(array, count)? };
593    let mut variables = Vec::with_capacity(entries.len());
594    for entry in entries {
595        match unsafe { text(entry)? }.split_once('=') {
596            Some((name, value))
597                if !name.is_empty() && !name.contains('\0') && !value.contains('\0') =>
598            {
599                variables.push(EnvironmentVariable::new(name, value));
600            }
601            _ => return Err(Status::InvalidArgument),
602        }
603    }
604    Ok(variables)
605}
606
607/// Start an executable as a child of this process and return its handle.
608///
609/// The path names a file below the directory capability, which needs the READ right.
610/// The host checks the execute permission as the calling process's user, and the child
611/// runs as the same user. The child gets an owned duplicate of each standard stream, a
612/// copy of the home capability if any, the given arguments, and a copy of this
613/// process's environment unless the request gives an explicit one. Spawning
614/// suspends the caller while the host reads the executable. Failures map to the
615/// usual statuses: `NotFound`, `PermissionDenied`, `ExecFormat` for an image the host
616/// cannot run, and `OutOfMemory` when the task table is full. Task manager errors use
617/// the canonical I/O kind mapping (`NoSpawnerAvailable` is `Unavailable`,
618/// `InvalidSpawnerIdentifier` is `InvalidArgument`). The
619/// process must be the running process's capability, otherwise the call returns
620/// `InvalidArgument`. The handle is written only on success.
621/// # Safety
622/// Process and directory must be live capabilities, the path readable for its length, the
623/// request and everything it points to valid for the call, and the output writable.
624pub unsafe extern "C" fn xila_process_spawn(
625    process: *const Process,
626    directory: *const Directory,
627    path: *const c_char,
628    path_length: usize,
629    spawn: *const Spawn,
630    child: *mut *mut Child,
631) -> Status {
632    let result = (|| {
633        let process = this(process)?;
634        if directory.is_null() || spawn.is_null() || child.is_null() {
635            return Err(Status::InvalidArgument);
636        }
637        // SAFETY: checked non-null above; the caller guarantees the objects are live.
638        let (directory, spawn) = unsafe { (&*directory, &*spawn) };
639        if (spawn.size as usize) < size_of::<Spawn>()
640            || spawn.flags & !SPAWN_NETWORK != 0
641            || spawn.standard_input.is_null()
642            || spawn.standard_output.is_null()
643            || spawn.standard_error.is_null()
644            || (spawn.environment.is_null() && spawn.environment_count != 0)
645        {
646            return Err(Status::InvalidArgument);
647        }
648        if u32::from(directory.rights) & XILA_RIGHT_READ == 0 {
649            return Err(Status::PermissionDenied);
650        }
651        // A parent can pass on only network rights it holds itself.
652        let network = spawn.flags & SPAWN_NETWORK;
653        if network & !process.network_rights() != 0 {
654            return Err(Status::PermissionDenied);
655        }
656        let path = canonical(
657            directory.path.as_str(),
658            unsafe { path_input(path, path_length)? },
659            true,
660        )?;
661        let arguments = unsafe { arguments(spawn.arguments, spawn.argument_count)? };
662        let environment = if spawn.environment.is_null() {
663            None
664        } else {
665            Some(unsafe { environment(spawn.environment, spawn.environment_count)? })
666        };
667        let home = unsafe { spawn.home.as_ref() }.map(|home| HomeGrant {
668            path: home.path.clone(),
669            rights: home.rights,
670        });
671        // SAFETY: the caller guarantees the three streams are live files.
672        let streams = unsafe {
673            [
674                &*spawn.standard_input,
675                &*spawn.standard_output,
676                &*spawn.standard_error,
677            ]
678        };
679        let host = process.host;
680        let parent = process.task;
681        // Registered before the child starts: a call cancelled while it waits for the host
682        // leaves the handle to the registry, and a started child is never left unowned.
683        let owned = registry::register(Child {
684            owner: parent,
685            id: 0,
686            handle: None,
687        });
688        // The future owns the duplicated streams and the request, which a cancellation
689        // drops in place.
690        let started = suspend_on_cancellable(async {
691            is_current(process).await?;
692            // One duplication site for the three streams. A failure drops, and so
693            // closes, the duplicates already made.
694            let mut duplicates = [None, None, None];
695            for (duplicate, stream) in duplicates.iter_mut().zip(streams) {
696                *duplicate = Some(stream.inner.duplicate().await?);
697            }
698            let [
699                Some(standard_input),
700                Some(standard_output),
701                Some(standard_error),
702            ] = duplicates
703            else {
704                return Err(Status::InvalidState);
705            };
706            host.spawn(SpawnRequest {
707                path,
708                arguments,
709                environment,
710                standard_input,
711                standard_output,
712                standard_error,
713                home,
714                network,
715            })
716            .await
717        });
718        match started {
719            Ok((handle, task)) => {
720                // SAFETY: the handle was just allocated and is not shared yet.
721                unsafe {
722                    (*owned).id = identifier(task);
723                    (*owned).handle = Some(handle);
724                }
725                Ok(owned)
726            }
727            Err(error) => {
728                // SAFETY: as above.
729                unsafe { xila_process_child_close(owned) };
730                Err(error)
731            }
732        }
733    })();
734    match result {
735        Ok(value) => {
736            unsafe { child.write(value) };
737            Status::Ok
738        }
739        Err(error) => error,
740    }
741}
742
743/// Wait for a child to exit and collect its exit status, which reaps it: a later wait on
744/// the same handle returns `NoChild`. Only the process that spawned the child may
745/// wait. Inside a coroutine the call suspends until the child exits, so other tasks keep
746/// running. With `XILA_WAIT_NO_HANG`, or outside a coroutine where nothing can suspend,
747/// a running child returns `WouldBlock`. The status output is optional and written
748/// only on success.
749///
750/// A child that exited and is not waited for keeps its status in its handle and holds
751/// no task. If its parent exits first, the root task adopts it.
752/// # Safety
753/// Process and child must be live and the status output, if any, aligned and writable.
754pub unsafe extern "C" fn xila_process_wait(
755    process: *const Process,
756    child: *mut Child,
757    flags: u32,
758    status: *mut i32,
759) -> Status {
760    let result = (|| {
761        let process = this(process)?;
762        if child.is_null() || flags & !XILA_WAIT_NO_HANG != 0 {
763            return Err(Status::InvalidArgument);
764        }
765        // SAFETY: checked non-null above; the caller guarantees the handle is live and unshared.
766        let child = unsafe { &mut *child };
767        if child.owner != process.task {
768            return Err(Status::NoChild);
769        }
770        let finished = child.handle.as_ref().ok_or(Status::NoChild)?.is_finished();
771        if !finished && (flags & XILA_WAIT_NO_HANG != 0 || !is_in_coroutine()) {
772            return Err(Status::WouldBlock);
773        }
774        let handle = child.handle.take().ok_or(Status::NoChild)?;
775        // The future owns the handle, which a cancellation drops in place: the child runs on
776        // and its status is discarded, as for a child handle that is closed.
777        let exit = suspend_on_cancellable(handle.join());
778        // Statuses wider than 32 bits come only from non-native children.
779        Ok(exit as i32)
780    })();
781    match result {
782        Ok(value) => {
783            if !status.is_null() {
784                unsafe { status.write(value) };
785            }
786            Status::Ok
787        }
788        Err(error) => error,
789    }
790}
791
792/// Read the process identifier of a child: the value its own `xila_process_id`
793/// reports. It stays readable after the child exits or is waited for, until the
794/// handle is closed. Core may reuse the identifier once the child's task is gone.
795/// # Safety
796/// The child must be a live handle and the output aligned and writable.
797pub unsafe extern "C" fn xila_process_child_id(child: *const Child, id: *mut u32) -> Status {
798    if child.is_null() || id.is_null() {
799        return Status::InvalidArgument;
800    }
801    // SAFETY: checked non-null above; the caller guarantees both are live and aligned.
802    unsafe { id.write((*child).id) };
803    Status::Ok
804}
805
806/// Release a child handle, waited for or not. A running child keeps running and its
807/// status is discarded when it ends. Null succeeds.
808/// # Safety
809/// A non-null child must be owned and released exactly once.
810pub unsafe extern "C" fn xila_process_child_close(child: *mut Child) -> Status {
811    if !child.is_null() {
812        // SAFETY: the caller guarantees the handle is owned and live.
813        drop(unsafe { registry::reclaim(child) });
814    }
815    Status::Ok
816}