Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Fix segfault in scheduler #228

Merged
merged 5 commits into from
Oct 13, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion core/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -129,7 +129,7 @@ version = "0.3"
[dev-dependencies.tokio]
version = "1.0"
default-features = false
features = ["rt", "rt-multi-thread", "time", "macros"]
features = ["rt", "rt-multi-thread", "time", "macros", "sync"]

[dev-dependencies.rquickjs]
path = ".."
Expand Down
36 changes: 36 additions & 0 deletions core/src/runtime/async.rs
Original file line number Diff line number Diff line change
Expand Up @@ -453,4 +453,40 @@ mod test {
assert_eq!(number.load(Ordering::SeqCst),1);

});

async_test_case!(recursive_spawn => (rt,ctx){
use tokio::sync::oneshot;

async_with!(&ctx => |ctx|{
let ctx_clone = ctx.clone();
let (tx,rx) = oneshot::channel::<()>();
let (tx2,rx2) = oneshot::channel::<()>();
ctx.spawn(async move {
tokio::task::yield_now().await;

let ctx = ctx_clone.clone();

ctx_clone.spawn(async move {
tokio::task::yield_now().await;
ctx.spawn(async move {
tokio::task::yield_now().await;
tx2.send(()).unwrap();
tokio::task::yield_now().await;
});
tokio::task::yield_now().await;
tx.send(()).unwrap();
});

// Add a bunch of futures just to make sure possible segfaults are more likely to
// happen
for _ in 0..32{
ctx_clone.spawn(async move {})
}

});
tokio::time::timeout(Duration::from_millis(500), rx).await.unwrap().unwrap();
tokio::time::timeout(Duration::from_millis(500), rx2).await.unwrap().unwrap();
}).await;

});
}
37 changes: 24 additions & 13 deletions core/src/runtime/spawner.rs
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
use std::{
cell::RefCell,
future::Future,
pin::{pin, Pin},
task::ready,
Expand All @@ -11,18 +12,20 @@ use crate::AsyncRuntime;

use super::{AsyncWeakRuntime, InnerRuntime};

type FuturesVec<T> = RefCell<Vec<Option<T>>>;

/// A structure to hold futures spawned inside the runtime.
///
/// TODO: change future lookup in poll from O(n) to O(1).
pub struct Spawner<'js> {
futures: Vec<Pin<Box<dyn Future<Output = ()> + 'js>>>,
futures: FuturesVec<Pin<Box<dyn Future<Output = ()> + 'js>>>,
wakeup: Vec<Waker>,
}

impl<'js> Spawner<'js> {
pub fn new() -> Self {
Spawner {
futures: Vec::new(),
futures: RefCell::new(Vec::new()),
wakeup: Vec::new(),
}
}
Expand All @@ -32,20 +35,20 @@ impl<'js> Spawner<'js> {
F: Future<Output = ()> + 'js,
{
self.wakeup.drain(..).for_each(Waker::wake);
self.futures.push(Box::pin(f))
self.futures.borrow_mut().push(Some(Box::pin(f)))
}

pub fn listen(&mut self, wake: Waker) {
self.wakeup.push(wake);
}

// Drives the runtime futures forward, returns false if their where no futures
pub fn drive<'a>(&'a mut self) -> SpawnFuture<'a, 'js> {
pub fn drive<'a>(&'a self) -> SpawnFuture<'a, 'js> {
SpawnFuture(self)
}

pub fn is_empty(&mut self) -> bool {
self.futures.is_empty()
self.futures.borrow().is_empty()
}
}

Expand All @@ -55,22 +58,30 @@ impl Drop for Spawner<'_> {
}
}

pub struct SpawnFuture<'a, 'js>(&'a mut Spawner<'js>);
pub struct SpawnFuture<'a, 'js>(&'a Spawner<'js>);

impl<'a, 'js> Future for SpawnFuture<'a, 'js> {
type Output = bool;

fn poll(mut self: Pin<&mut Self>, cx: &mut std::task::Context<'_>) -> Poll<Self::Output> {
if self.0.futures.is_empty() {
fn poll(self: Pin<&mut Self>, cx: &mut std::task::Context<'_>) -> Poll<Self::Output> {
if self.0.futures.borrow().is_empty() {
return Poll::Ready(false);
}

let mut i = 0;
let mut did_complete = false;
self.0.futures.retain_mut(|f| {
let ready = f.as_mut().poll(cx).is_ready();
did_complete = did_complete || ready;
!ready
});
while i < self.0.futures.borrow().len() {
let mut borrow = self.0.futures.borrow_mut()[i].take().unwrap();
if borrow.as_mut().poll(cx).is_pending() {
// put back.
self.0.futures.borrow_mut()[i] = Some(borrow);
} else {
did_complete = true;
}
i += 1;
}

self.0.futures.borrow_mut().retain_mut(|f| f.is_some());

if did_complete {
Poll::Ready(true)
Expand Down
Loading