1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
use core::panic;
use std::task::{Poll, Waker};
use futures::{channel::oneshot, pin_mut};
use super::*;
extern "Rust" {
fn sidevm_main_future() -> Pin<Box<dyn Future<Output = ()>>>;
}
type TaskFuture = Pin<Box<dyn Future<Output = ()>>>;
type Tasks = Vec<Option<TaskFuture>>;
thread_local! {
static CURRENT_TASK: std::cell::Cell<i32> = Default::default();
static TASKS: RefCell<Tasks> = RefCell::new(vec![Some(unsafe { sidevm_main_future() })]);
static SPAWNING_TASKS: RefCell<Vec<TaskFuture>> = RefCell::new(vec![]);
static WAKERS: RefCell<Vec<Option<Waker>>> = RefCell::new(vec![]);
}
pub fn intern_waker(waker: task::Waker) -> i32 {
const MAX_N_WAKERS: usize = (i32::MAX / 2) as usize;
WAKERS.with(|wakers| {
let mut wakers = wakers.borrow_mut();
for (id, waker_ref) in wakers.iter_mut().enumerate() {
if waker_ref.is_none() {
*waker_ref = Some(waker);
return id as i32;
}
}
if wakers.len() < MAX_N_WAKERS {
wakers.push(Some(waker));
wakers.len() as i32 - 1
} else {
panic!("Too many wakers");
}
})
}
fn wake_waker(waker_id: i32) {
WAKERS.with(|wakers| {
let wakers = wakers.borrow();
if let Some(Some(waker)) = wakers.get(waker_id as usize) {
waker.wake_by_ref();
}
});
}
fn drop_waker(waker_id: i32) {
WAKERS.with(|wakers| {
let mut wakers = wakers.borrow_mut();
if let Some(waker) = wakers.get_mut(waker_id as usize) {
*waker = None;
}
});
}
pub struct JoinHandle<T>(oneshot::Receiver<T>);
#[derive(Clone, Copy, PartialEq, Eq, Debug)]
pub struct Canceled;
impl<T> Future for JoinHandle<T> {
type Output = Result<T, Canceled>;
fn poll(self: Pin<&mut Self>, cx: &mut task::Context<'_>) -> Poll<Self::Output> {
let this = self.get_mut();
let inner = &mut this.0;
pin_mut!(inner);
match inner.poll(cx) {
Poll::Ready(x) => Poll::Ready(x.map_err(|_: oneshot::Canceled| Canceled)),
Poll::Pending => Poll::Pending,
}
}
}
pub fn spawn<T: 'static>(fut: impl Future<Output = T> + 'static) -> JoinHandle<T> {
let (tx, rx) = oneshot::channel();
SPAWNING_TASKS.with(move |tasks| {
(*tasks).borrow_mut().push(Box::pin(async move {
let _ = tx.send(fut.await);
}))
});
JoinHandle(rx)
}
fn start_task(tasks: &mut Tasks, task: TaskFuture) {
const MAX_N_TASKS: usize = (i32::MAX / 2) as _;
for (task_id, task_ref) in tasks.iter_mut().enumerate().skip(1) {
if task_ref.is_none() {
*task_ref = Some(task);
ocall::mark_task_ready(task_id as _).expect("Mark task ready failed");
return;
}
}
if tasks.len() < MAX_N_TASKS {
let task_id = tasks.len();
tasks.push(Some(task));
ocall::mark_task_ready(task_id as _).expect("Mark task ready failed");
return;
}
panic!("Spawn task failed, Max number of tasks reached");
}
fn start_spawned_tasks(tasks: &mut Tasks) {
SPAWNING_TASKS.with(|spowned_tasks| {
for task in spowned_tasks.borrow_mut().drain(..) {
start_task(tasks, task);
}
})
}
pub(crate) fn current_task() -> i32 {
CURRENT_TASK.with(|id| id.get())
}
fn set_current_task(task_id: i32) {
CURRENT_TASK.with(|id| id.set(task_id))
}
fn poll_with_guest_context<F>(f: Pin<&mut F>) -> task::Poll<F::Output>
where
F: Future + ?Sized,
{
fn raw_waker(task_id: i32) -> task::RawWaker {
task::RawWaker::new(
task_id as _,
&task::RawWakerVTable::new(
|data| raw_waker(data as _),
|data| {
let task_id = data as _;
ocall::mark_task_ready(task_id).expect("Mark task ready failed");
},
|data| {
let task_id = data as _;
ocall::mark_task_ready(task_id).expect("Mark task ready failed");
},
|_| (),
),
)
}
let waker = unsafe { task::Waker::from_raw(raw_waker(current_task())) };
let mut context = task::Context::from_waker(&waker);
f.poll(&mut context)
}
#[no_mangle]
extern "C" fn sidevm_poll() -> i32 {
use task::Poll::*;
fn poll() -> task::Poll<()> {
loop {
for waker_id in ocall::awake_wakers().expect("Failed to get awaked wakers") {
if waker_id >= 0 {
wake_waker(waker_id);
} else {
drop_waker(-1 - waker_id);
}
}
let task_id = match ocall::next_ready_task() {
Ok(id) => id as usize,
Err(OcallError::NotFound) => return task::Poll::Pending,
Err(err) => panic!("Error occured: {:?}", err),
};
let exited = TASKS.with(|tasks| -> Option<bool> {
let exited = {
let mut tasks = tasks.borrow_mut();
let task = tasks.get_mut(task_id)?.as_mut()?;
set_current_task(task_id as _);
match poll_with_guest_context(task.as_mut()) {
Pending => (),
Ready(()) => {
tasks[task_id] = None;
}
}
tasks[0].is_none()
};
if !exited {
start_spawned_tasks(&mut *tasks.borrow_mut());
}
Some(exited)
});
if let Some(true) = exited {
return task::Poll::Ready(());
}
}
}
match poll() {
Ready(()) => 1,
Pending => 0,
}
}