use std::cell::Cell;
use std::cell::RefCell;
use std::panic;
use std::panic::AssertUnwindSafe;
use std::sync::atomic::AtomicBool;
use std::sync::atomic::Ordering;
use std::sync::mpsc;
use std::thread::ThreadId;
pub(crate) const TRACER_STACK_BYTES: usize = 8 << 20;
type Job = Box<dyn FnOnce() + Send>;
static ON_CALLER: AtomicBool = AtomicBool::new(false);
pub fn launch_on_calling_thread() {
ON_CALLER.store(true, Ordering::Relaxed);
}
fn tracer_identity() -> Option<ProcessIdentity> {
if ON_TRACER.get() || ON_CALLER.load(Ordering::Relaxed) {
return None;
}
let identity = ProcessIdentity::current();
identity.namespace.is_some().then_some(identity)
}
struct TracerThread {
jobs: mpsc::Sender<Job>,
id: ThreadId,
process: ProcessIdentity,
}
#[derive(Clone, Copy, PartialEq, Eq)]
struct ProcessIdentity {
pid: u32,
namespace: Option<(u64, u64)>,
}
impl ProcessIdentity {
fn current() -> Self {
use std::os::unix::fs::MetadataExt;
Self {
pid: std::process::id(),
namespace: std::fs::metadata("/proc/self/ns/pid")
.ok()
.map(|meta| (meta.dev(), meta.ino())),
}
}
}
thread_local! {
static TRACER: RefCell<Option<TracerThread>> = const { RefCell::new(None) };
static ON_TRACER: Cell<bool> = const { Cell::new(false) };
}
fn spawn(process: ProcessIdentity) -> std::io::Result<TracerThread> {
let (jobs, receive) = mpsc::channel::<Job>();
let handle = std::thread::Builder::new()
.name("hermit-tracer".to_owned())
.stack_size(TRACER_STACK_BYTES)
.spawn(move || {
ON_TRACER.set(true);
for job in receive {
job();
}
})?;
Ok(TracerThread {
jobs,
id: handle.thread().id(),
process,
})
}
fn current(tracer: &mut Option<TracerThread>, process: ProcessIdentity) -> Option<&TracerThread> {
if tracer
.as_ref()
.is_some_and(|tracer| tracer.process != process)
{
std::mem::forget(tracer.take());
}
tracer.as_ref()
}
pub(crate) fn execute<R: Send + 'static>(
job: impl FnOnce() -> R + Send + 'static,
) -> std::io::Result<R> {
match tracer_identity() {
Some(identity) => execute_with(identity, job),
None => Ok(job()),
}
}
fn execute_with<R: Send + 'static>(
identity: ProcessIdentity,
job: impl FnOnce() -> R + Send + 'static,
) -> std::io::Result<R> {
if TRACER.try_with(|_| ()).is_err() {
return Ok(job());
}
let (send, receive) = mpsc::channel();
let job: Job = Box::new(move || {
let _ = send.send(panic::catch_unwind(AssertUnwindSafe(job)));
});
let sent = TRACER.try_with(|tracer| {
let mut tracer = tracer.borrow_mut();
if current(&mut tracer, identity).is_none() {
*tracer = Some(spawn(identity)?);
}
tracer
.as_ref()
.expect("the tracer thread was just set")
.jobs
.send(job)
.map_err(|_| std::io::Error::other("Hermit's tracer thread has exited"))
});
sent.map_err(|_| std::io::Error::other("Hermit's tracer thread storage is gone"))??;
match receive.recv() {
Ok(Ok(value)) => Ok(value),
Ok(Err(payload)) => panic::resume_unwind(payload),
Err(_) => Err(std::io::Error::other(
"Hermit's tracer thread exited without finishing the launch",
)),
}
}
pub(crate) fn execute_on<R: Send + 'static>(
owner: ThreadId,
job: impl FnOnce() -> R + Send + 'static,
) -> Option<std::io::Result<R>> {
let identity = tracer_identity()?;
let mine = TRACER
.try_with(|tracer| current(&mut tracer.borrow_mut(), identity).map(|tracer| tracer.id))
.ok()
.flatten();
(mine == Some(owner)).then(|| execute_with(identity, job))
}
pub(crate) struct SendCommand(reverie::process::Command);
unsafe impl Send for SendCommand {}
impl SendCommand {
pub(crate) fn new(command: reverie::process::Command) -> Self {
Self(command)
}
pub(crate) fn into_inner(self) -> reverie::process::Command {
self.0
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn one_tracer_thread_serves_its_caller() {
let first = execute(|| std::thread::current().id()).unwrap();
assert_ne!(first, std::thread::current().id());
assert_eq!(
execute(|| std::thread::current().name().map(str::to_owned)).unwrap(),
Some("hermit-tracer".to_owned())
);
let panicked = std::panic::catch_unwind(|| execute(|| panic!("in the job")));
let payload = panicked.expect_err("the panic resumes in the caller");
assert_eq!(payload.downcast_ref::<&str>(), Some(&"in the job"));
assert_eq!(execute(|| std::thread::current().id()).unwrap(), first);
assert!(execute_on(std::thread::current().id(), || ()).is_none());
assert_eq!(
execute_on(first, || std::thread::current().id()).map(Result::unwrap),
Some(first)
);
}
}