Debian Codegraph @

.cargo/vendor/wit-bindgen/src/rt/async_support/subtask.rs

raw
1 //! Bindings used to manage subtasks, or invocations of imported functions.
2 //!
3 //! See `future_support` for some more discussion but the basic idea is the same
4 //! where we require that everything is passed by ownership to primarily deal
5 //! with the possibility of leaking futures. By always requiring ownership we
6 //! can guarantee that even when a future is leaked all its parameters passed to
7 //! the canonical ABI are additionally leaked with it which should be memory
8 //! safe.
9
10 use crate::rt::async_support::waitable::{WaitableOp, WaitableOperation};
11 use crate::rt::async_support::{
12 STATUS_RETURNED, STATUS_RETURNED_CANCELLED, STATUS_STARTED, STATUS_STARTED_CANCELLED,
13 STATUS_STARTING,
14 };
15 use crate::rt::Cleanup;
16 use std::alloc::Layout;
17 use std::future::Future;
18 use std::marker;
19 use std::num::NonZeroU32;
20 use std::ptr;
21
22 /// Raw operations used to invoke an imported asynchronous function.
23 ///
24 /// This trait is implemented by generated bindings and is used to implement
25 /// asynchronous imports.
26 ///
27 /// # Unsafety
28 ///
29 /// All operations/constants must be self-consistent for how this module expects
30 /// them all to be used.
31 pub unsafe trait Subtask {
32 /// The in-memory layout of both parameters and results allocated with
33 /// parameters coming first.
34 const ABI_LAYOUT: Layout;
35
36 /// The offset, in bytes, from the start of `ABI_LAYOUT` to where the
37 /// results will be stored.
38 const RESULTS_OFFSET: usize;
39
40 /// The parameters to this task.
41 type Params;
42 /// The representation of lowered parameters for this task.
43 ///
44 /// This is used to account for how lowered imports may have up to 4 flat
45 /// arguments or may also be indirect as well in memory. Either way this
46 /// represents the actual ABI values passed to the import.
47 type ParamsLower: Copy;
48 /// The results of this task.
49 type Results;
50
51 /// The raw function import using `[async-lower]` and the canonical ABI.
52 unsafe fn call_import(params: Self::ParamsLower, results: *mut u8) -> u32;
53
54 /// Bindings-generated version of lowering `params`.
55 ///
56 /// This may use the heap-allocated `dst`, which is an uninitialized
57 /// allocation of `Self::ABI_LAYOUT`. This returns any ABI parameters
58 /// necessary to actually invoke the imported function.
59 ///
60 /// Note that `ParamsLower` may return `dst` if there are more ABI
61 /// parameters than are allowed flat params (as specified by the canonical
62 /// ABI).
63 unsafe fn params_lower(params: Self::Params, dst: *mut u8) -> Self::ParamsLower;
64
65 /// Bindings-generated version of deallocating any lists stored within
66 /// `lower`.
67 unsafe fn params_dealloc_lists(lower: Self::ParamsLower);
68
69 /// Bindings-generated version of deallocating not only owned lists within
70 /// `lower` but also deallocating any owned resources.
71 unsafe fn params_dealloc_lists_and_own(lower: Self::ParamsLower);
72
73 /// Bindings-generated version of lifting the results stored at `src`.
74 unsafe fn results_lift(src: *mut u8) -> Self::Results;
75
76 /// Helper function to actually perform this asynchronous call with
77 /// `params`.
78 fn call(params: Self::Params) -> impl Future<Output = Self::Results>
79 where
80 Self: Sized,
81 {
82 async {
83 match WaitableOperation::<SubtaskOps<Self>>::new(Start { params }).await {
84 Ok(results) => results,
85 Err(_) => unreachable!(
86 "cancellation is not exposed API-wise, \
87 should not be possible"
88 ),
89 }
90 }
91 }
92 }
93
94 struct SubtaskOps<T>(marker::PhantomData<T>);
95
96 struct Start<T: Subtask> {
97 params: T::Params,
98 }
99
100 unsafe impl<T: Subtask> WaitableOp for SubtaskOps<T> {
101 type Start = Start<T>;
102 type InProgress = InProgress<T>;
103 type Result = Result<T::Results, ()>;
104 type Cancel = Result<T::Results, ()>;
105
106 fn start(state: Self::Start) -> (u32, Self::InProgress) {
107 unsafe {
108 let (ptr_params, cleanup) = Cleanup::new(T::ABI_LAYOUT);
109 let ptr_results = ptr_params.add(T::RESULTS_OFFSET);
110 let params_lower = T::params_lower(state.params, ptr_params);
111 let packed = T::call_import(params_lower, ptr_results);
112 let code = packed & 0xf;
113 let subtask = NonZeroU32::new(packed >> 4).map(|handle| SubtaskHandle { handle });
114 rtdebug!("<import>({ptr_params:?}, {ptr_results:?}) = ({code:#x}, {subtask:#x?})");
115
116 (
117 code,
118 InProgress {
119 params_lower,
120 params_and_results: cleanup,
121 subtask,
122 started: false,
123 _marker: marker::PhantomData,
124 },
125 )
126 }
127 }
128
129 fn start_cancelled(_state: Self::Start) -> Self::Cancel {
130 Err(())
131 }
132
133 fn in_progress_update(
134 mut state: Self::InProgress,
135 code: u32,
136 ) -> Result<Self::Result, Self::InProgress> {
137 match code {
138 // Nothing new to do in this state, we're still waiting for the task
139 // to start.
140 STATUS_STARTING => {
141 assert!(!state.started);
142 Err(state)
143 }
144
145 // Still not done yet, but we can record that this is started and
146 // otherwise deallocate lists in the parameters.
147 STATUS_STARTED => {
148 state.flag_started();
149 Err(state)
150 }
151
152 STATUS_RETURNED => {
153 // Conditionally flag as started if we haven't otherwise
154 // explicitly transitioned through `STATUS_STARTED`.
155 if !state.started {
156 state.flag_started();
157 }
158
159 // Now that our results have been written we can read them.
160 //
161 // Note that by dropping `state` here we'll both deallocate the
162 // params/results storage area as well as the subtask handle
163 // itself.
164 unsafe { Ok(Ok(T::results_lift(state.ptr_results()))) }
165 }
166
167 // This subtask was dropped which forced cancellation. Said
168 // cancellation stopped the subtask before it reached the "started"
169 // state, meaning that we still own all of the parameters in their
170 // lowered form.
171 //
172 // In this situation we lift the parameters, even after we
173 // previously lowered them, back into `T::Params`. That notably
174 // re-acquires ownership and is suitable for disposing of all of
175 // the parameters via normal Rust-based destructors.
176 STATUS_STARTED_CANCELLED => {
177 assert!(!state.started);
178 unsafe {
179 T::params_dealloc_lists_and_own(state.params_lower);
180 }
181 Ok(Err(()))
182 }
183
184 // This subtask was dropped which forced cancellation. Said
185 // cancellation stopped the subtask before it reached the "returned"
186 // state, meaning that it started, received the arguments, but then
187 // did not complete.
188 //
189 // In this situation we may have already received `STATUS_STARTED`,
190 // but we also might not have. This means we conditionally need
191 // to flag this task as started which will deallocate all lists
192 // owned by the parameters.
193 //
194 // After that though we do not have ownership of the parameters any
195 // more (e.g. own resources are all gone) so there's nothing to
196 // return. Here we yield a result and dispose of the in-progress
197 // state.
198 STATUS_RETURNED_CANCELLED => {
199 if !state.started {
200 state.flag_started();
201 }
202 Ok(Err(()))
203 }
204
205 other => panic!("unknown code {other:#x}"),
206 }
207 }
208
209 fn in_progress_waitable(state: &Self::InProgress) -> u32 {
210 // This shouldn't get called in the one case this isn't present: when
211 // `STATUS_RETURNED` is returned and no waitable is created. That's the
212 // `unwrap()` condition here.
213 state.subtask.as_ref().unwrap().handle.get()
214 }
215
216 fn in_progress_cancel(state: &Self::InProgress) -> u32 {
217 unsafe { cancel(Self::in_progress_waitable(state)) }
218 }
219
220 fn result_into_cancel(result: Self::Result) -> Self::Cancel {
221 result
222 }
223 }
224
225 #[derive(Debug)]
226 struct SubtaskHandle {
227 handle: NonZeroU32,
228 }
229
230 impl Drop for SubtaskHandle {
231 fn drop(&mut self) {
232 unsafe {
233 drop(self.handle.get());
234 }
235 }
236 }
237
238 struct InProgress<T: Subtask> {
239 params_and_results: Option<Cleanup>,
240 params_lower: T::ParamsLower,
241 started: bool,
242 subtask: Option<SubtaskHandle>,
243 _marker: marker::PhantomData<T>,
244 }
245
246 impl<T: Subtask> InProgress<T> {
247 fn flag_started(&mut self) {
248 assert!(!self.started);
249 self.started = true;
250
251 // SAFETY: the initial entrypoint of `call` requires that the vtable is
252 // setup correctly and we're obeying the invariants of the vtable,
253 // deallocating lists in an allocation that we exclusively own.
254 unsafe {
255 T::params_dealloc_lists(self.params_lower);
256 }
257 }
258
259 fn ptr_results(&self) -> *mut u8 {
260 // SAFETY: the `T` trait has unsafely promised us that the offset is
261 // in-bounds of the allocation layout.
262 unsafe {
263 self.params_and_results
264 .as_ref()
265 .map(|c| c.ptr.as_ptr())
266 .unwrap_or(ptr::null_mut())
267 .add(T::RESULTS_OFFSET)
268 }
269 }
270 }
271
272 #[cfg(not(target_arch = "wasm32"))]
273 unsafe fn drop(_: u32) {
274 unreachable!()
275 }
276
277 #[cfg(not(target_arch = "wasm32"))]
278 unsafe fn cancel(_: u32) -> u32 {
279 unreachable!()
280 }
281
282 #[cfg(target_arch = "wasm32")]
283 #[link(wasm_import_module = "$root")]
284 extern "C" {
285 #[link_name = "[subtask-cancel]"]
286 fn cancel(handle: u32) -> u32;
287 #[link_name = "[subtask-drop]"]
288 fn drop(handle: u32);
289 }