Repository navigation
Expand file tree
/
Copy pathexecutor.rs
More file actions
469 lines (426 loc) · 14.6 KB
/
Copy pathexecutor.rs
File metadata and controls
469 lines (426 loc) · 14.6 KB
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
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
use std::cell::UnsafeCell;
use std::collections::HashMap;
use std::collections::VecDeque;
use std::os::raw::c_int;
use crate::coroutine::{Coroutine, IoWait, State, VPid};
thread_local! {
static CURRENT_EXECUTOR: UnsafeCell<*mut Executor> = const { UnsafeCell::new(std::ptr::null_mut()) };
}
pub fn set_current_executor(ptr: *mut Executor) {
CURRENT_EXECUTOR.with(|e| unsafe { *e.get() = ptr });
}
pub fn get_current_executor() -> *mut Executor {
CURRENT_EXECUTOR.with(|e| unsafe { *e.get() })
}
/// Cooperative coroutine scheduler.
///
/// Manages virtual processes (coroutines) with a ready queue, I/O wait
/// tracking, fork parent-child relationships, and signal delivery.
pub struct Executor {
pub vprocs: HashMap<VPid, Coroutine>,
ready_queue: VecDeque<VPid>,
next_pid: VPid,
pub current: Option<VPid>,
switch_count: u64,
pub children: HashMap<VPid, Vec<VPid>>,
pub saved_fork_lr: Option<u64>,
pub(crate) exit_codes: HashMap<VPid, i32>,
}
impl Default for Executor {
fn default() -> Self {
Self::new()
}
}
impl Executor {
pub fn new() -> Self {
Executor {
vprocs: HashMap::new(),
ready_queue: VecDeque::new(),
next_pid: 1,
current: None,
switch_count: 0,
children: HashMap::new(),
saved_fork_lr: None,
exit_codes: HashMap::new(),
}
}
pub fn spawn(&mut self, f: Box<dyn FnOnce()>) -> VPid {
let pid = self.next_pid;
self.next_pid += 1;
let co = Coroutine::new(pid, f);
self.vprocs.insert(pid, co);
self.ready_queue.push_back(pid);
pid
}
pub fn spawn_front(&mut self, f: Box<dyn FnOnce()>) -> VPid {
let pid = self.next_pid;
self.next_pid += 1;
let co = Coroutine::new(pid, f);
self.vprocs.insert(pid, co);
self.ready_queue.push_front(pid);
pid
}
/// Spawn a virtual process backed by a loaded ELF binary.
#[allow(clippy::too_many_arguments, clippy::not_unsafe_ptr_arg_deref)]
pub fn spawn_elf(
&mut self,
entry: usize,
stack_base: *mut u8,
stack_size: usize,
argc: usize,
argv: Vec<*const u8>,
envp: Vec<*const u8>,
auxv: Vec<[u64; 2]>,
) -> VPid {
let pid = self.next_pid;
self.next_pid += 1;
let co = unsafe { Coroutine::new_elf(pid, entry, stack_base, stack_size, argc, argv, envp, auxv) };
self.vprocs.insert(pid, co);
self.ready_queue.push_back(pid);
pid
}
pub fn register_c_strings(&mut self, vpid: VPid, strings: Vec<*mut u8>) {
if let Some(co) = self.vprocs.get_mut(&vpid) {
co.c_strings = strings;
}
}
pub fn register_mapped_region(&mut self, vpid: VPid, base: usize, size: usize) {
if let Some(co) = self.vprocs.get_mut(&vpid) {
co.mapped_regions.push((base, size));
}
}
/// Spawn a child coroutine by forking the parent's minicoro context.
pub fn spawn_fork_child(&mut self, parent_pid: VPid) -> VPid {
let child_id = self.next_pid;
self.next_pid += 1;
let child = unsafe {
let parent_co = self.vprocs.get(&parent_pid).unwrap();
Coroutine::fork_from(child_id, parent_co)
};
self.vprocs.insert(child_id, child);
self.ready_queue.push_back(child_id);
self.children.entry(parent_pid).or_default().push(child_id);
crate::vfd::fork_fd_table(parent_pid, child_id);
self.vprocs.get_mut(&parent_pid).unwrap().fork_child_pid = child_id;
child_id
}
pub fn current_pid(&self) -> Option<VPid> {
self.current
}
fn pick_next(&mut self) -> Option<VPid> {
while let Some(pid) = self.ready_queue.pop_front() {
if let Some(co) = self.vprocs.get(&pid) {
if !co.is_done() {
return Some(pid);
}
}
}
None
}
fn deliver_signals(&mut self, pid: VPid) -> bool {
let signals = {
let co = match self.vprocs.get_mut(&pid) {
Some(c) => c,
None => return false,
};
if co.pending_signals.is_empty() {
return false;
}
std::mem::take(&mut co.pending_signals)
};
for sig in &signals {
match *sig {
libc::SIGKILL | libc::SIGTERM => {
if let Some(co) = self.vprocs.get_mut(&pid) {
co.set_done(128 + sig);
}
return true;
}
_ => {}
}
}
false
}
/// Run one scheduler step: resume the next ready coroutine.
/// Returns true if work was done, false if nothing to run.
pub fn step(&mut self) -> bool {
let next_pid = match self.pick_next() {
Some(pid) => pid,
None => return false,
};
if self.deliver_signals(next_pid) {
if let Some(cur) = self.current {
self.ready_queue.push_back(cur);
}
return true;
}
// Re-queue current if still alive
if let Some(cur) = self.current {
if let Some(co) = self.vprocs.get(&cur) {
if !co.is_done() {
self.ready_queue.push_back(cur);
}
}
}
self.current = Some(next_pid);
self.switch_count += 1;
self.vprocs.get_mut(&next_pid).unwrap().resume();
true
}
/// Yield the current coroutine and run the next ready one.
pub fn r#yield(&mut self) {
if let Some(pid) = self.current {
let co = self.vprocs.get(&pid).unwrap();
if !co.is_done() {
self.vprocs.get_mut(&pid).unwrap().state = State::Ready;
self.ready_queue.push_back(pid);
}
}
self.step();
}
/// Reap finished coroutines, close their real fds, and release resources.
pub fn reap_done_coroutines(&mut self) {
let done_pids: Vec<VPid> = self.vprocs.iter()
.filter(|(_, co)| co.is_done())
.map(|(&pid, _)| pid)
.collect();
for pid in &done_pids {
self.children.remove(pid);
}
self.children.retain(|_, kids| {
kids.retain(|k| self.vprocs.contains_key(k));
!kids.is_empty()
});
self.vprocs.retain(|&pid, co| {
if co.is_done() {
let real_fds = crate::vfd::remove_table_and_get_fds(pid);
for fd in real_fds {
unsafe { crate::preload::real_close(fd); }
}
false
} else {
true
}
});
// Don't release binary cache here — dlclose triggers __libc_init
// which resets minicoro's thread-local _mco_main_ctx, breaking
// subsequent coroutine context switching. Binary cache is managed
// explicitly via unload_binary/unload_all_binaries.
}
pub fn switch_count(&self) -> u64 {
self.switch_count
}
}
#[no_mangle]
pub extern "C" fn vproc_exit() {
vproc_exit_with_code(0);
}
pub fn vproc_exit_with_code(code: i32) {
let ptr = get_current_executor();
if ptr.is_null() { return; }
let ex = unsafe { &mut *ptr };
let pid = match ex.current {
Some(p) => p,
None => return,
};
if let Some(co) = ex.vprocs.get_mut(&pid) {
co.state = State::Done;
co.exit_code = code;
}
ex.exit_codes.insert(pid, code);
unsafe {
let co = mco_running_raw();
if !co.is_null() {
mco_yield_raw(co);
}
}
}
pub fn get_exit_code(pid: VPid) -> Option<i32> {
let ptr = get_current_executor();
if ptr.is_null() { return None; }
let ex = unsafe { &mut *ptr };
if let Some(&code) = ex.exit_codes.get(&pid) {
return Some(code);
}
ex.vprocs.get(&pid).and_then(|co| {
if co.is_done() { Some(co.exit_code) } else { None }
})
}
pub fn is_child_of(parent: VPid, child: VPid) -> bool {
let ptr = get_current_executor();
if ptr.is_null() { return false; }
let ex = unsafe { &mut *ptr };
ex.children.get(&parent).is_some_and(|kids| kids.contains(&child))
}
pub fn reap_child(parent: VPid, child: VPid) {
let ptr = get_current_executor();
if ptr.is_null() { return; }
let ex = unsafe { &mut *ptr };
if let Some(kids) = ex.children.get_mut(&parent) {
kids.retain(|&k| k != child);
}
}
pub fn remove_exit_code(pid: VPid) {
let ptr = get_current_executor();
if ptr.is_null() { return; }
let ex = unsafe { &mut *ptr };
ex.exit_codes.remove(&pid);
}
pub fn do_yield() {
unsafe {
let co = mco_running_raw();
if !co.is_null() {
// Re-queue current coroutine before yielding, otherwise the scheduler
// never picks it up again (the same logic as Executor::r#yield).
let ptr = get_current_executor();
if ptr.is_null() { return; }
let ex = &mut *ptr;
if let Some(pid) = ex.current {
if let Some(co_inner) = ex.vprocs.get(&pid) {
if !co_inner.is_done() {
ex.ready_queue.push_back(pid);
}
}
}
mco_yield_raw(co);
} else {
// Driver thread — advance the scheduler.
let ptr = get_current_executor();
if ptr.is_null() { return; }
let ex = &mut *ptr;
ex.step_from_driver();
}
}
}
unsafe fn mco_running_raw() -> *mut crate::coroutine::McoCoro {
unsafe extern "C" {
fn mco_running() -> *mut crate::coroutine::McoCoro;
}
mco_running()
}
unsafe fn mco_yield_raw(co: *mut crate::coroutine::McoCoro) {
unsafe extern "C" {
fn mco_yield(co: *mut crate::coroutine::McoCoro) -> i32;
}
mco_yield(co);
}
/// Yield the current coroutine waiting for I/O readiness.
/// Sets io_wait state and yields WITHOUT pushing to ready_queue.
/// The driver thread's batch poll() will push it back when fds are ready.
/// `timeout_ms`: -1 = infinite, 0 = already checked (shouldn't reach here), >0 = finite wait.
pub fn yield_for_io(fds: Vec<(c_int, i16)>, timeout_ms: c_int) {
let deadline = if timeout_ms < 0 {
None
} else {
Some(std::time::Instant::now() + std::time::Duration::from_millis(timeout_ms as u64))
};
unsafe {
let co = mco_running_raw();
if !co.is_null() {
let ex = &mut *get_current_executor();
if let Some(pid) = ex.current {
if let Some(co_inner) = ex.vprocs.get_mut(&pid) {
if !co_inner.is_done() {
co_inner.io_wait = Some(IoWait { fds, deadline });
}
}
}
mco_yield_raw(co);
}
}
}
/// Collect all (fd, events) from I/O-waiting coroutines for batch poll().
/// Returns (pollfds, mapping from pollfd index to VPid).
pub fn collect_io_waits() -> (Vec<libc::pollfd>, Vec<VPid>) {
let ex = unsafe { &mut *get_current_executor() };
let mut pollfds = Vec::new();
let mut pid_map = Vec::new();
for (&pid, co) in &ex.vprocs {
if let Some(ref iowait) = co.io_wait {
for &(fd, events) in &iowait.fds {
pollfds.push(libc::pollfd {
fd,
events,
revents: 0,
});
pid_map.push(pid);
}
}
}
(pollfds, pid_map)
}
/// Move coroutines whose io_wait fds are ready (or timed out) back to the ready queue.
/// Called by the driver thread after batch poll() returns.
pub fn wake_io_ready(pollfds: &[libc::pollfd], pid_map: &[VPid]) {
let ex = unsafe { &mut *get_current_executor() };
let now = std::time::Instant::now();
let mut ready_pids: Vec<VPid> = Vec::new();
// Wake coroutines whose fds are ready
for (i, pfd) in pollfds.iter().enumerate() {
if pfd.revents != 0 {
let pid = pid_map[i];
if !ready_pids.contains(&pid) {
ready_pids.push(pid);
}
}
}
// Wake coroutines whose deadline has expired
for (&pid, co) in &ex.vprocs {
if let Some(ref iowait) = co.io_wait {
if let Some(deadline) = iowait.deadline {
if now >= deadline && !ready_pids.contains(&pid) {
ready_pids.push(pid);
}
}
}
}
for pid in ready_pids {
if let Some(co) = ex.vprocs.get_mut(&pid) {
co.io_wait = None;
}
if !ex.ready_queue.contains(&pid) {
ex.ready_queue.push_back(pid);
}
}
}
/// Drive the scheduler from the driver thread (not from inside a coroutine).
impl Executor {
pub fn step_from_driver(&mut self) {
let next_pid = match self.pick_next() {
Some(pid) => pid,
None => return,
};
self.deliver_signals(next_pid);
self.current = Some(next_pid);
self.switch_count += 1;
self.vprocs.get_mut(&next_pid).unwrap().resume();
self.current = None;
}
/// Drive the scheduler with fd 0/1/2 swapped around the coroutine resume.
/// Before resuming, installs the coroutine's real fds so fork children
/// inherit the correct ones. After resume, restores the driver's originals.
pub fn step_from_driver_with_fd_swap(&mut self, saved_fds: [std::os::raw::c_int; 3]) {
let next_pid = match self.pick_next() {
Some(pid) => pid,
None => return,
};
self.deliver_signals(next_pid);
let fds_swapped = if let Some(real_fds) = crate::vfd::get_real_fds(next_pid) {
if unsafe { crate::ffi::raw_dup3(real_fds[0], 0) } < 0 { std::process::abort(); }
if unsafe { crate::ffi::raw_dup3(real_fds[1], 1) } < 0 { std::process::abort(); }
if unsafe { crate::ffi::raw_dup3(real_fds[2], 2) } < 0 { std::process::abort(); }
true
} else {
false
};
self.current = Some(next_pid);
self.switch_count += 1;
self.vprocs.get_mut(&next_pid).unwrap().resume();
self.current = None;
if fds_swapped {
if unsafe { crate::ffi::raw_dup3(saved_fds[0], 0) } < 0 { std::process::abort(); }
if unsafe { crate::ffi::raw_dup3(saved_fds[1], 1) } < 0 { std::process::abort(); }
if unsafe { crate::ffi::raw_dup3(saved_fds[2], 2) } < 0 { std::process::abort(); }
}
}
}