abi_application/runner.rs
1//! Run a native entry as a process on the calling task's executor.
2//!
3//! The loader of native images and the adapter of statically linked programs share this
4//! runner. Both need the same cancellation-safe ownership: the heap and the host state
5//! live in one allocation off the coroutine stack, and a driver releases them on every
6//! path (return, `xila_process_exit` and a dropped future).
7extern crate alloc;
8
9use crate::{File, Heap, HostState, ProcessLaunch, Status, XilaStartup, drive_process};
10use alloc::{alloc::alloc, boxed::Box, string::String, vec::Vec};
11use core::{alloc::Layout, cell::UnsafeCell, future::Future, ptr::NonNull};
12use stackful::{Coroutine, Stack};
13
14/// The entry of a native program, as the host calls it.
15pub type NativeEntry = unsafe extern "C" fn(*const XilaStartup) -> i32;
16
17/// Everything one running program owns on the host side, in a single allocation: a value
18/// that must outlive the program's code (the loaded image, for a loader), the process
19/// heap and the host state. The host state holds the startup block, the process
20/// capability, the resources they point into and a registry of the handles the program
21/// opened, so the coroutine's own frames hold none of it.
22///
23/// A program that is cancelled while suspended has its frames discarded, with no
24/// destructor run on them (see `stackful::Coroutine::new`). That is sound because the
25/// frames own nothing: dropping [`ProcessOwner`] releases the state's resources and handles
26/// from the host side, then frees the heap, the state and, last, the keep-alive value. No
27/// driver keeps a pointer into a program buffer between polls, because `BaseOperations` are
28/// poll-based, so a suspended coroutine holds no reference that the executor or a device
29/// could still use.
30struct Record<K> {
31 heap: UnsafeCell<Heap>,
32 state: UnsafeCell<HostState>,
33 /// Declared last, so it is dropped after the heap and the state: a kept image holds the
34 /// code of the program, so it stays mapped until nothing can run it any more.
35 _keep: K,
36}
37
38/// The owner of a leaked `Record` allocation, freeing it on drop.
39///
40/// It must outlive the program's coroutine, whose frames point into the allocation:
41/// [`drive_owned`] holds it beside the coroutine and drops it afterwards, on every path.
42pub struct ProcessOwner<K = ()>(NonNull<Record<K>>);
43
44impl<K> ProcessOwner<K> {
45 /// Move the state and `keep` into a new allocation, reporting allocator exhaustion
46 /// instead of aborting. Both are released if this fails.
47 pub fn new(keep: K, state: HostState) -> Result<Self, Status> {
48 let layout = Layout::new::<Record<K>>();
49 // SAFETY: the heap makes the record larger than zero bytes.
50 let Some(pointer) = NonNull::new(unsafe { alloc(layout) }.cast::<Record<K>>()) else {
51 // The program can never start, and dropping the arguments releases everything
52 // the state and `keep` own.
53 return Err(Status::OutOfMemory);
54 };
55 // SAFETY: the allocation is valid and uninitialized, for the layout of `Record`.
56 unsafe {
57 pointer.write(Record {
58 heap: UnsafeCell::new(Heap::new()),
59 state: UnsafeCell::new(state),
60 _keep: keep,
61 });
62 }
63 Ok(Self(pointer))
64 }
65
66 /// Build the host state from a program's arguments and standard streams, then
67 /// [`ProcessOwner::new`].
68 pub fn from_startup(
69 keep: K,
70 arguments: Vec<String>,
71 standard_input: Option<File>,
72 standard_output: Option<File>,
73 standard_error: Option<File>,
74 ) -> Result<Self, Status> {
75 Self::new(
76 keep,
77 HostState::new(arguments, standard_input, standard_output, standard_error),
78 )
79 }
80
81 /// The heap of the process. It stays valid until `self` is dropped.
82 pub fn heap(&self) -> NonNull<Heap> {
83 // SAFETY: the pointer refers to an initialized record.
84 unsafe { NonNull::new_unchecked((*self.0.as_ptr()).heap.get()) }
85 }
86
87 /// The host state of the process. It stays at this address until `self` is dropped.
88 pub fn state(&self) -> NonNull<HostState> {
89 // SAFETY: the pointer refers to an initialized record.
90 unsafe { NonNull::new_unchecked((*self.0.as_ptr()).state.get()) }
91 }
92
93 /// The coroutine entry of the program. It holds only pointers into the allocation and
94 /// the launch request, which the callee consumes before native code runs: the
95 /// arguments, the streams and the startup block stay in the host state, off the
96 /// coroutine stack, so a process that exits early abandons this frame without leaking
97 /// (see `xila_process_exit`).
98 ///
99 /// Without a `launch` the program is started like a linked one with no process
100 /// capability: it gets none of the process services and cannot exit early.
101 ///
102 /// # Safety
103 /// `entry` obeys the startup lifetime rules, fits on the coroutine stack, and returns
104 /// without unwinding. It stays callable until the owner is dropped. The returned closure
105 /// must be invoked at most once, and only inside a coroutine that is dropped before the
106 /// owner (see [`drive_owned`]).
107 pub unsafe fn entry(
108 &self,
109 entry: NativeEntry,
110 launch: Option<ProcessLaunch>,
111 ) -> impl FnOnce() -> i32 + 'static + use<K> {
112 let heap = self.heap();
113 let state = self.state();
114 move || unsafe {
115 match launch {
116 Some(launch) => launch.run(state, entry, heap),
117 None => HostState::run_linked(state, entry, heap),
118 }
119 }
120 }
121}
122
123impl<K> Drop for ProcessOwner<K> {
124 fn drop(&mut self) {
125 let record = self.0.as_ptr();
126 // SAFETY: the pointer came from `ProcessOwner::new`, with the global allocator and
127 // the layout of `Record`, and the program can no longer run: it never started, it
128 // returned or exited, or its coroutine was dropped and its frames discarded. What
129 // it still holds is in the state, which is released first: nothing after a normal
130 // end, the streams of a program that never started, and the streams, the handles
131 // and the graphics objects of one that was cancelled.
132 unsafe {
133 HostState::release(NonNull::new_unchecked((*record).state.get()));
134 drop(Box::from_raw(record));
135 }
136 }
137}
138
139/// A [`ProcessOwner`] with the type of its keep-alive value erased, so that one instantiation
140/// of [`drive_owned`] serves every owner type instead of duplicating `drive_process` per type.
141pub struct AnyProcessOwner {
142 record: NonNull<core::ffi::c_void>,
143 drop_record: unsafe fn(NonNull<core::ffi::c_void>),
144}
145
146impl<K: 'static> ProcessOwner<K> {
147 /// Erase the type of the keep-alive value. The drop behavior is unchanged.
148 pub fn erase(self) -> AnyProcessOwner {
149 /// # Safety
150 /// `record` must have come from `ProcessOwner::<K>::new` for this exact `K`,
151 /// and this function must be called at most once for it.
152 unsafe fn drop_record<K: 'static>(record: NonNull<core::ffi::c_void>) {
153 // The pointer came from `ProcessOwner::<K>::new`, through `erase`.
154 drop(ProcessOwner::<K>(record.cast()))
155 }
156 let this = core::mem::ManuallyDrop::new(self);
157 AnyProcessOwner {
158 record: this.0.cast(),
159 drop_record: drop_record::<K>,
160 }
161 }
162}
163
164impl Drop for AnyProcessOwner {
165 fn drop(&mut self) {
166 // SAFETY: the pointer and the drop glue came from `ProcessOwner::erase`.
167 unsafe { (self.drop_record)(self.record) }
168 }
169}
170
171/// Drive the program's coroutine to its end, then free what it ran on. The coroutine is
172/// dropped before `owner`, on every path, including the future being dropped while the
173/// program is suspended: the temporary that holds it is the newest object of this
174/// function, so it is the first to be dropped.
175pub async fn drive_owned(coroutine: Coroutine, owner: AnyProcessOwner) -> i32 {
176 let status = drive_process(coroutine).await;
177 drop(owner);
178 status
179}
180
181/// Run `entry` as a process on the calling task, as a future that resolves to its exit
182/// status, without spawning a task for it.
183///
184/// The coroutine runs inside the task that polls the future, which is how the process
185/// learns its identity. Dropping the future before it completes cancels the program: its
186/// coroutine stack is freed, with no destructor run on it, and everything it held is
187/// released. Without a `launch` the program gets no process capability.
188///
189/// # Safety
190/// `entry` obeys the startup lifetime rules, fits on `stack`, and returns without
191/// unwinding. The future is polled on the executor that created it and keeps all native
192/// execution on it.
193pub unsafe fn start_process<K: 'static>(
194 stack: Stack,
195 owner: ProcessOwner<K>,
196 entry: NativeEntry,
197 launch: Option<ProcessLaunch>,
198) -> impl Future<Output = i32> + 'static {
199 let coroutine = unsafe { Coroutine::new(stack, owner.entry(entry, launch)) };
200 drive_owned(coroutine, owner.erase())
201}