Skip to main content

abi_application/
startup.rs

1//! Startup capabilities borrowed by a linked native C application.
2use crate::{
3    Directory, File, Heap, Network, Process, ProcessHost, XILA_API, XilaApi, registry::Registry,
4};
5use alloc::{string::String, vec::Vec};
6use core::{ffi::c_char, ptr, ptr::NonNull};
7use task::TaskIdentifier;
8
9/// UTF-8 bytes, not NUL-terminated. A null data pointer is valid only at length zero.
10#[repr(C)]
11pub struct XilaString {
12    pub data: *const c_char,
13    pub length: usize,
14}
15
16/// Host-owned startup data, valid only for the duration of the entry call.
17/// The API is always present. Capability pointers may be null when not granted;
18/// the process capability is null for an application that is not a process, such
19/// as a built-in one linked into the firmware, whose process calls fail with
20/// InvalidArgument. A null argument array has argument_count zero.
21/// Fields are only ever appended: check `size` before reading a field that a
22/// later Xila version added, such as `network`.
23/// Applications must not close, retain or transfer these objects; closing them is
24/// undefined behavior. Objects opened by the application must still be closed.
25#[repr(C)]
26pub struct XilaStartup {
27    pub size: u32,
28    pub api: *const XilaApi,
29    pub heap: *mut Heap,
30    pub arguments: *const XilaString,
31    pub argument_count: usize,
32    pub standard_input: *mut File,
33    pub standard_output: *mut File,
34    pub standard_error: *mut File,
35    pub home: *mut Directory,
36    pub process: *const Process,
37    /// Executable's launch name. Empty for a linked entry without a process.
38    pub program_name: XilaString,
39    /// Network authority granted to the process, with only the rights its launch
40    /// granted explicitly (connect, listen, resolve). Null unless the launch granted at
41    /// least one right and the host has a network stack, so a process has no network by
42    /// default. Appended after `program_name`, so images built before it existed still
43    /// start.
44    pub network: *const Network,
45}
46
47/// The startup block of the program that the calling coroutine runs, or null.
48///
49/// A linked program reads its own arguments, streams and capabilities through it, without
50/// a process-wide `static` that a second program on the same executor would overwrite.
51/// The block is valid until the entry returns or exits: do not keep the pointer.
52///
53/// It returns null in a thread that is not part of a running program. On a target without
54/// stack switching one program runs at a time, and the pointer is valid during its entry.
55///
56/// This is the contract between the firmware and a linked Rust application (`xila-sys` with
57/// its `linked` feature). A standalone image receives its startup block as an argument, so
58/// the C header does not declare it.
59///
60/// cbindgen:ignore
61#[unsafe(no_mangle)]
62pub extern "C" fn __xila_current_startup() -> *const XilaStartup {
63    crate::threads::current_startup()
64}
65
66/// What the entry call borrows and the process owner releases when it ends. Kept in
67/// one place so `xila_process_exit` can release it before it abandons the stack, and so
68/// the host can release it when it cancels the process.
69pub(crate) struct Resources {
70    /// The handles the program opened itself and has not closed: files, directories,
71    /// listings, children and sockets. See [`crate::registry`].
72    pub(crate) handles: Registry,
73    /// Strings that `arguments` points into.
74    pub(crate) _owned: Vec<String>,
75    pub(crate) arguments: Vec<XilaString>,
76    /// Bytes that `XilaStartup::program_name` points into.
77    pub(crate) program_name: String,
78    pub(crate) standard_input: Option<File>,
79    pub(crate) standard_output: Option<File>,
80    pub(crate) standard_error: Option<File>,
81    pub(crate) home: Option<Directory>,
82    /// The network capability behind `XilaStartup::network`. It owns no socket: the
83    /// sockets the program opened are in `handles`.
84    #[cfg(feature = "network")]
85    pub(crate) network: Option<Network>,
86    /// The process's graphics objects, allocated by its first graphics call.
87    #[cfg(feature = "graphics")]
88    pub(crate) graphics: Option<alloc::boxed::Box<graphics::call::State>>,
89}
90
91/// Everything the host keeps for one native run: the startup block the entry
92/// borrows, the process capability and the resources both point into.
93///
94/// It belongs to the host side of the task, not to the program's coroutine: the
95/// loader allocates it once, next to the heap and the image, and the coroutine
96/// entry receives only a pointer to it. A program that writes past its own frames
97/// therefore cannot damage the state `xila_process_exit`, the SDK's heap access and
98/// the standard error stream behind `write(2)` depend on, and a host that stops
99/// resuming a coroutine can still reach what the coroutine owned.
100///
101/// The startup block and the capability point into the state, so it must not move
102/// once a run has begun: the allocation that holds it stays where it is until the
103/// run has ended for good. Building it, and moving it into that allocation, are
104/// free to move it, because nothing points into it yet.
105///
106/// It owns everything the program holds that the kernel or the host must release: the
107/// arguments, the standard streams, the home directory, the graphics objects and a registry
108/// of the handles the program opened itself. The program's frames own none of it, so
109/// [`HostState::release`] can close it all without running any of the program's code,
110/// whether the program returned, exited or was cancelled.
111pub struct HostState {
112    startup: XilaStartup,
113    process: Option<Process>,
114    pub(crate) resources: Resources,
115}
116
117/// The startup array over `arguments`, which must outlive it. One instance serves
118/// both callers.
119fn argument_pointers(arguments: &mut dyn ExactSizeIterator<Item = &str>) -> Vec<XilaString> {
120    let mut pointers = Vec::with_capacity(arguments.len());
121    for argument in arguments {
122        pointers.push(XilaString {
123            data: argument.as_ptr().cast(),
124            length: argument.len(),
125        });
126    }
127    pointers
128}
129
130impl HostState {
131    /// The arguments and the standard streams of a program that has not started.
132    pub fn new(
133        arguments: Vec<String>,
134        standard_input: Option<File>,
135        standard_output: Option<File>,
136        standard_error: Option<File>,
137    ) -> Self {
138        Self::from_resources(Resources {
139            handles: Registry::new(),
140            arguments: argument_pointers(&mut arguments.iter().map(String::as_str)),
141            _owned: arguments,
142            program_name: String::new(),
143            standard_input,
144            standard_output,
145            standard_error,
146            home: None,
147            #[cfg(feature = "network")]
148            network: None,
149            #[cfg(feature = "graphics")]
150            graphics: None,
151        })
152    }
153
154    fn from_resources(resources: Resources) -> Self {
155        Self {
156            // Filled in by `enter`, which knows the heap and the capability.
157            startup: XilaStartup {
158                size: 0,
159                api: ptr::null(),
160                heap: ptr::null_mut(),
161                arguments: ptr::null(),
162                argument_count: 0,
163                standard_input: ptr::null_mut(),
164                standard_output: ptr::null_mut(),
165                standard_error: ptr::null_mut(),
166                home: ptr::null_mut(),
167                process: ptr::null(),
168                program_name: XilaString {
169                    data: ptr::null(),
170                    length: 0,
171                },
172                network: ptr::null(),
173            },
174            process: None,
175            resources,
176        }
177    }
178
179    /// Run a linked entry that gets no process capability and cannot exit early,
180    /// then drop the resources. The state belongs to the caller, as for
181    /// [`crate::ProcessLaunch::run`].
182    ///
183    /// # Safety
184    /// Same as [`run_main`], and `state` and `heap` stay at their addresses and live
185    /// until native execution has permanently ended.
186    pub unsafe fn run_linked(
187        state: NonNull<Self>,
188        entry: unsafe extern "C" fn(*const XilaStartup) -> i32,
189        heap: NonNull<Heap>,
190    ) -> i32 {
191        unsafe { enter(state, entry, heap, None) }
192    }
193}
194
195impl Resources {
196    /// Close and free what the process owns, once. Releasing an empty set does nothing, so
197    /// a return from the entry, `xila_process_exit` and the host that cancels the process
198    /// can all call it.
199    ///
200    /// Each kind is emptied before the next is closed, and each stream is closed where it
201    /// is and taken out afterwards, so a close that suspends and is then cancelled leaves
202    /// everything not yet closed in the state, for the host to release. The order is the
203    /// reverse of how a program acquires them: the handles it opened, its graphics objects,
204    /// its streams, its home directory, then its strings.
205    ///
206    /// # Safety
207    /// The pointer addresses live resources, no reference to them is in use and no code of
208    /// the program that owns them runs, or ever will, while this does.
209    #[inline(never)]
210    pub(crate) unsafe fn release(resources: *mut Self) {
211        // SAFETY: the caller guarantees the pointer is valid and unaliased.
212        unsafe {
213            (*resources).handles.release_all();
214            // The process's graphics objects go next, under the graphics lock, which the
215            // process waits for by suspending. The state stays in the resources until
216            // it is dropped, so a coroutine cancelled in that wait leaves it for the host.
217            #[cfg(feature = "graphics")]
218            {
219                let state = (*resources).graphics.as_mut().map(|state| &raw mut **state);
220                if let Some(state) = state {
221                    crate::graphics::release(state);
222                }
223                drop((*resources).graphics.take());
224            }
225            for stream in [
226                &mut (*resources).standard_input,
227                &mut (*resources).standard_output,
228                &mut (*resources).standard_error,
229            ] {
230                // Closed in place and then taken: a close that is cancelled while it waits
231                // leaves the stream in the state, for the host to close again.
232                if let Some(file) = stream {
233                    let _ = file.inner.as_synchronous_file_mut().close_in_place();
234                }
235                drop(stream.take());
236            }
237            drop((*resources).home.take());
238            #[cfg(feature = "network")]
239            {
240                (*resources).network = None;
241            }
242            (*resources).arguments = Vec::new();
243            (*resources)._owned = Vec::new();
244            (*resources).program_name = String::new();
245        }
246    }
247}
248
249impl HostState {
250    /// How many handles the program has opened and not closed: files, directories,
251    /// listings, children and sockets. It counts what a cancellation would close, and
252    /// excludes the standard streams and the home directory, which are not the program's
253    /// to close.
254    pub fn open_handles(&self) -> usize {
255        self.resources.handles.len()
256    }
257
258    /// Close and free everything the program still holds: the handles it opened, its
259    /// graphics objects, its standard streams, its home directory and its strings. A
260    /// program that returned or exited has released them already, so this does nothing
261    /// then; one that was cancelled, or never ran, still holds them.
262    ///
263    /// This is how a host cancels a program without running any of its code: drop the
264    /// coroutine first (which discards its frames), then release the state, then free it.
265    /// Closing may wait for the file system and the graphics lock, which blocks the
266    /// calling task as `task::block_on` does when no coroutine is running.
267    ///
268    /// # Safety
269    /// `state` is live and at the address the program ran with, and no code of the program
270    /// runs, or ever will, while this does.
271    pub unsafe fn release(state: NonNull<Self>) {
272        // SAFETY: the caller guarantees the state is live and unaliased.
273        unsafe { Resources::release(&raw mut (*state.as_ptr()).resources) }
274    }
275}
276
277/// Invoke a linked C entry on the calling stack, then close its granted streams.
278/// The process owner provides the heap and drops it after all native execution
279/// ends.
280///
281/// The entry gets no process capability and cannot exit early; the host state sits
282/// in this frame. A loader that starts native processes keeps the state off the
283/// stack: see [`HostState`] and [`crate::ProcessLaunch::run`].
284///
285/// It is meant for tests and cannot be cancelled cleanly: the host state, and with it the
286/// head of the handle registry, live in this frame, so a coroutine dropped while the entry
287/// is suspended discards them with its stack and nothing can release what they hold.
288/// # Safety
289/// Entry must obey the startup lifetime and ownership rules, serialize object
290/// access, and never unwind. The heap must remain live until native execution
291/// has permanently ended.
292pub unsafe fn run_main(
293    entry: unsafe extern "C" fn(*const XilaStartup) -> i32,
294    heap: &mut Heap,
295    arguments: &[&str],
296    standard_input: Option<File>,
297    standard_output: Option<File>,
298    standard_error: Option<File>,
299    home: Option<Directory>,
300) -> i32 {
301    let mut state = HostState::from_resources(Resources {
302        handles: Registry::new(),
303        _owned: Vec::new(),
304        program_name: String::new(),
305        arguments: argument_pointers(&mut arguments.iter().copied()),
306        standard_input,
307        standard_output,
308        standard_error,
309        home,
310        #[cfg(feature = "network")]
311        network: None,
312        #[cfg(feature = "graphics")]
313        graphics: None,
314    });
315    unsafe { enter(NonNull::from(&mut state), entry, NonNull::from(heap), None) }
316}
317
318/// The startup's borrowed network capability, or null without one.
319fn network_pointer(resources: &Resources) -> *const Network {
320    #[cfg(feature = "network")]
321    {
322        resources
323            .network
324            .as_ref()
325            .map_or(ptr::null(), ptr::from_ref)
326    }
327    #[cfg(not(feature = "network"))]
328    {
329        let _ = resources;
330        ptr::null()
331    }
332}
333
334/// Build the startup data in `state`, call the entry and release the resources
335/// when it returns. Nothing the entry or `xila_process_exit` reaches is stored in
336/// this frame: they find the state through pointers into `state`.
337///
338/// Whichever way the run ends, the resources are dropped exactly once: here when the
339/// entry returns, or by `xila_process_exit`, which empties them and abandons this
340/// frame and every frame between it and the exit. That is sound only because the
341/// host never calls back into C with host state (a lock, guard or borrow) on the
342/// stack: whenever C runs, the only host frames below it are this one and the
343/// coroutine's own. Worker callbacks are separate coroutine entries and carry no
344/// host-owned guards.
345///
346/// # Safety
347/// Same as [`run_main`], and `state` and `heap` stay at their addresses and live
348/// until native execution has permanently ended.
349pub(crate) unsafe fn enter(
350    state: NonNull<HostState>,
351    entry: unsafe extern "C" fn(*const XilaStartup) -> i32,
352    heap: NonNull<Heap>,
353    process: Option<(&'static dyn ProcessHost, TaskIdentifier)>,
354) -> i32 {
355    let state = state.as_ptr();
356    // Every access goes through pointers into `state`, so `xila_process_exit` can
357    // empty the resources while the entry runs.
358    let resources: *mut Resources = unsafe { &raw mut (*state).resources };
359    let startup = unsafe {
360        (*state).process = process.map(|(host, task)| Process {
361            host,
362            task,
363            resources,
364        });
365        let resources = &mut *resources;
366        (*state).startup = XilaStartup {
367            size: core::mem::size_of::<XilaStartup>() as u32,
368            api: &XILA_API,
369            heap: heap.as_ptr(),
370            arguments: if resources.arguments.is_empty() {
371                ptr::null()
372            } else {
373                resources.arguments.as_ptr()
374            },
375            argument_count: resources.arguments.len(),
376            standard_input: resources
377                .standard_input
378                .as_mut()
379                .map_or(ptr::null_mut(), ptr::from_mut),
380            standard_output: resources
381                .standard_output
382                .as_mut()
383                .map_or(ptr::null_mut(), ptr::from_mut),
384            standard_error: resources
385                .standard_error
386                .as_mut()
387                .map_or(ptr::null_mut(), ptr::from_mut),
388            home: resources
389                .home
390                .as_mut()
391                .map_or(ptr::null_mut(), ptr::from_mut),
392            process: (*state).process.as_ref().map_or(ptr::null(), ptr::from_ref),
393            program_name: XilaString {
394                data: resources.program_name.as_ptr().cast(),
395                length: resources.program_name.len(),
396            },
397            network: network_pointer(resources),
398        };
399        &raw const (*state).startup
400    };
401    let process = unsafe { (*startup).process };
402    let managed = !process.is_null();
403    if managed {
404        crate::threads::bind_process(process);
405    }
406    // Every thread of the program registers the handles it opens here.
407    crate::threads::bind_registry(unsafe { &raw const (*resources).handles });
408    // Concurrent programs on one executor each find their own startup block through
409    // `__xila_current_startup`. Cleared again when the entry ends.
410    let previous = crate::threads::bind_startup(startup);
411    let status = unsafe { entry(startup) };
412    crate::threads::bind_startup(previous);
413    if managed {
414        crate::threads::stop_workers();
415    }
416    // Released here, in the coroutine. Stopping the workers above dropped their cancellable
417    // waits, and whatever those held (the VFS namespace lock, say), so the closes below
418    // cannot wait for a thread that never runs again. `xila_process_exit` does the same.
419    unsafe { Resources::release(resources) };
420    status
421}