use std::fs::File;
use std::io;
use std::io::IsTerminal;
use std::io::Write;
use std::io::stderr;
use std::mem;
use std::os::fd::AsRawFd;
use std::os::fd::RawFd;
use std::ptr::NonNull;
use std::sync::Arc;
use std::sync::OnceLock;
use std::sync::atomic::AtomicBool;
use std::sync::atomic::AtomicU64;
use std::sync::atomic::Ordering;
use std::time::Duration;
use std::time::Instant;
use hermit::Backend;
use hermit::liteinst_bootstrap::EffectiveFilter;
use hermit::nonwaiting_write::write_without_waiting;
use tracing::Subscriber;
use tracing::metadata::LevelFilter;
use tracing_subscriber::EnvFilter;
use tracing_subscriber::util::SubscriberInitExt;
const DEFAULT_TRACE_LEVEL: LevelFilter = LevelFilter::WARN;
pub const LOG_MAX_BYTES_ENV: &str = "HERMIT_LOG_MAX_BYTES";
pub const DEFAULT_LOG_MAX_BYTES: u64 = 1 << 30;
const TRUNCATION_MARKER: &[u8] =
b"\n=== HERMIT LOG TRUNCATED: reached the configured size bound (HERMIT_LOG_MAX_BYTES). \
Output beyond this point was DISCARDED. The run itself continued and was NOT affected. ===\n";
pub fn log_max_bytes() -> Result<u64, String> {
match std::env::var(LOG_MAX_BYTES_ENV) {
Ok(raw) => raw.trim().parse().map_err(|_| {
format!(
"{LOG_MAX_BYTES_ENV}={raw:?} is not a byte count. Set a non-negative integer \
number of bytes, or 0 to disable the bound."
)
}),
Err(_) => Ok(DEFAULT_LOG_MAX_BYTES),
}
}
pub struct BoundedWriter<W: Write> {
inner: W,
remaining: u64,
bounded: bool,
announced: bool,
}
impl<W: Write> BoundedWriter<W> {
pub fn new(inner: W, limit: u64) -> Self {
Self {
inner,
remaining: limit,
bounded: limit != 0,
announced: false,
}
}
pub fn resume(inner: W, limit: u64, written: u64) -> Self {
Self {
inner,
remaining: limit.saturating_sub(written),
bounded: limit != 0,
announced: false,
}
}
}
impl<W: Write> BoundedWriter<W> {
fn has_truncated(&self) -> bool {
self.announced
}
fn announce_truncation(&mut self) -> io::Result<()> {
if !self.announced {
self.announced = true;
self.inner.write_all(TRUNCATION_MARKER)?;
self.inner.flush()?;
}
Ok(())
}
}
impl<W: Write> Write for BoundedWriter<W> {
fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
if !self.bounded {
return self.inner.write(buf);
}
if self.remaining == 0 {
self.announce_truncation()?;
return Ok(buf.len());
}
let take = buf.len().min(self.remaining as usize);
let written = self.inner.write(&buf[..take])?;
self.remaining -= written as u64;
if written < take {
return Ok(written);
}
if take < buf.len() {
self.announce_truncation()?;
}
Ok(buf.len())
}
fn flush(&mut self) -> io::Result<()> {
self.inner.flush()
}
}
pub fn parse_max_log_bytes(raw: &str) -> Result<u64, String> {
let usage = "Give a positive byte count with an optional K/M/G/T suffix \
(powers of 1024), e.g. --max-log-bytes=8G.";
let text = raw.trim();
let split = text
.find(|c: char| !c.is_ascii_digit())
.unwrap_or(text.len());
let (digits, suffix) = text.split_at(split);
if digits.is_empty() {
return Err(format!("{raw:?} is not a byte count. {usage}"));
}
let shift = match suffix.to_ascii_lowercase().as_str() {
"" | "b" => 0,
"k" | "ki" | "kb" | "kib" => 10,
"m" | "mi" | "mb" | "mib" => 20,
"g" | "gi" | "gb" | "gib" => 30,
"t" | "ti" | "tb" | "tib" => 40,
_ => return Err(format!("{raw:?} has an unknown size suffix. {usage}")),
};
let count: u64 = digits
.parse()
.map_err(|_| format!("{raw:?} is too large for a byte count. {usage}"))?;
let bytes = count
.checked_mul(1u64 << shift)
.ok_or_else(|| format!("{raw:?} is too large for a byte count. {usage}"))?;
if bytes == 0 {
return Err(format!(
"{raw:?} would abort the run on its first log line. Omit --max-log-bytes to \
leave hermit's log output uncapped, or give a positive size such as 8G."
));
}
Ok(bytes)
}
pub fn format_byte_size(bytes: u64) -> String {
for (shift, suffix) in [(40, "T"), (30, "G"), (20, "M"), (10, "K")] {
let unit = 1u64 << shift;
if bytes != 0 && bytes.is_multiple_of(unit) {
return format!("{}{suffix}", bytes / unit);
}
}
bytes.to_string()
}
#[repr(C)]
struct BudgetCells {
spent: AtomicU64,
admission: AtomicU64,
}
const CROSSED: u64 = 1 << 63;
const LOG_CAP_DRAIN_BOUND: Duration = Duration::from_millis(50);
const LOG_CAP_DRAIN_BOUND_MAX: Duration = Duration::from_millis(250);
const _: () = assert!(LOG_CAP_DRAIN_BOUND.as_millis() <= LOG_CAP_DRAIN_BOUND_MAX.as_millis());
const LOG_CAP_DRAIN_POLL: Duration = Duration::from_millis(1);
fn admit_write(admission: &AtomicU64) -> bool {
let mut current = admission.load(Ordering::Relaxed);
loop {
if current & CROSSED != 0 {
return false;
}
match admission.compare_exchange_weak(
current,
current + 1,
Ordering::AcqRel,
Ordering::Relaxed,
) {
Ok(_) => return true,
Err(actual) => current = actual,
}
}
}
fn finish_write(admission: &AtomicU64) {
admission.fetch_sub(1, Ordering::Release);
}
fn claim_crossing(admission: &AtomicU64) -> bool {
let before = admission.fetch_or(CROSSED, Ordering::AcqRel);
finish_write(admission);
before & CROSSED == 0
}
fn writes_in_progress(admission: &AtomicU64) -> u64 {
admission.load(Ordering::Acquire) & !CROSSED
}
fn crossing_already_claimed(admission: &AtomicU64) -> bool {
admission.fetch_or(0, Ordering::AcqRel) & CROSSED != 0
}
static INVOCATION_LOG_BUDGET: OnceLock<LogBudget> = OnceLock::new();
pub(crate) fn register_invocation_log_budget(budget: Option<LogBudget>) {
if let Some(budget) = budget {
let _ = INVOCATION_LOG_BUDGET.set(budget);
}
}
pub(crate) fn exit_if_log_cap_already_crossed() {
if let Some(budget) = INVOCATION_LOG_BUDGET.get()
&& crossing_already_claimed(&budget.cells().admission)
{
unsafe { libc::_exit(hermit::HERMIT_LOG_CAP_EXIT) }
}
}
fn wait_for_writes_in_progress(admission: &AtomicU64, bound: Duration) -> bool {
let start = Instant::now();
loop {
if writes_in_progress(admission) == 0 {
return true;
}
let left = bound.saturating_sub(start.elapsed());
if left.is_zero() {
return false;
}
let step = left.min(LOG_CAP_DRAIN_POLL);
let pause = libc::timespec {
tv_sec: 0,
tv_nsec: libc::c_long::from(step.subsec_nanos()),
};
unsafe { libc::nanosleep(&pause, std::ptr::null_mut()) };
}
}
#[derive(Debug)]
struct SharedBudgetCells {
address: NonNull<BudgetCells>,
}
unsafe impl Send for SharedBudgetCells {}
unsafe impl Sync for SharedBudgetCells {}
impl Drop for SharedBudgetCells {
fn drop(&mut self) {
unsafe {
libc::munmap(self.address.as_ptr().cast(), mem::size_of::<BudgetCells>());
}
}
}
#[derive(Clone, Debug)]
pub struct LogBudget {
limit: u64,
cells: Arc<SharedBudgetCells>,
message: Arc<str>,
drain_bound: Duration,
}
#[derive(Debug, PartialEq, Eq)]
enum Charge {
Within,
Crossed,
AlreadyOver,
}
impl LogBudget {
pub fn new(limit: u64) -> io::Result<Self> {
let address = unsafe {
libc::mmap(
std::ptr::null_mut(),
mem::size_of::<BudgetCells>(),
libc::PROT_READ | libc::PROT_WRITE,
libc::MAP_SHARED | libc::MAP_ANONYMOUS,
-1,
0,
)
};
if address == libc::MAP_FAILED {
return Err(io::Error::last_os_error());
}
let address = NonNull::new(address.cast::<BudgetCells>())
.expect("mmap returned a non-null non-failure address");
unsafe {
address.as_ptr().write(BudgetCells {
spent: AtomicU64::new(0),
admission: AtomicU64::new(0),
})
};
Ok(Self {
limit,
cells: Arc::new(SharedBudgetCells { address }),
message: exceeded_message(limit).into(),
drain_bound: LOG_CAP_DRAIN_BOUND,
})
}
#[cfg(test)]
fn with_drain_bound(mut self, bound: Duration) -> Self {
self.drain_bound = bound.min(LOG_CAP_DRAIN_BOUND_MAX);
self
}
pub fn exceeded_message(&self) -> &str {
&self.message
}
fn cells(&self) -> &BudgetCells {
unsafe { self.cells.address.as_ref() }
}
#[cfg(test)]
fn spent(&self) -> u64 {
self.cells().spent.load(Ordering::Relaxed)
}
#[cfg(test)]
pub(crate) fn shares_counter_with(&self, other: &LogBudget) -> bool {
self.cells.address == other.cells.address
}
fn charge(&self, len: u64) -> Charge {
if !admit_write(&self.cells().admission) {
return Charge::AlreadyOver;
}
self.account(len)
}
fn account(&self, len: u64) -> Charge {
let cells = self.cells();
let mut before = cells.spent.load(Ordering::Relaxed);
while let Err(current) = cells.spent.compare_exchange_weak(
before,
before.saturating_add(len),
Ordering::Relaxed,
Ordering::Relaxed,
) {
before = current;
}
match before.checked_add(len) {
Some(total) if total <= self.limit => Charge::Within,
_ if claim_crossing(&cells.admission) => Charge::Crossed,
_ => Charge::AlreadyOver,
}
}
fn refund(&self, len: u64) {
self.cells().spent.fetch_sub(len, Ordering::Relaxed);
}
fn finish(&self) {
finish_write(&self.cells().admission);
}
fn writes_drained(&self) -> bool {
wait_for_writes_in_progress(&self.cells().admission, self.drain_bound)
}
#[cfg(test)]
fn in_progress(&self) -> u64 {
writes_in_progress(&self.cells().admission)
}
}
struct AdmittedWrite<'a>(&'a LogBudget);
impl Drop for AdmittedWrite<'_> {
fn drop(&mut self) {
self.0.finish();
}
}
fn exceeded_message(limit: u64) -> String {
format!(
"hermit: log output exceeded --max-log-bytes={} ({} bytes); aborting the run and killing \
the guest process tree (exit {}). Lower --log / RUST_LOG verbosity, or raise \
--max-log-bytes, to let the run finish.\n{}",
format_byte_size(limit),
limit,
hermit::HERMIT_LOG_CAP_EXIT,
LOG_CAP_CLASS_LINE,
)
}
pub struct CappedWriter<W: Write> {
inner: W,
budget: Option<LogBudget>,
final_message_fd: Option<RawFd>,
inner_has_final_line: fn(&W) -> bool,
}
impl<W: Write> CappedWriter<W> {
pub fn new(inner: W, budget: Option<LogBudget>) -> Self {
Self {
inner,
budget,
final_message_fd: None,
inner_has_final_line: |_| false,
}
}
fn exceeded(&mut self, budget: &LogBudget) -> ! {
if budget.writes_drained() {
self.write_final_message(budget);
}
unsafe { libc::_exit(hermit::HERMIT_LOG_CAP_EXIT) }
}
fn write_final_message(&mut self, budget: &LogBudget) {
let message = budget.exceeded_message().as_bytes();
if let Some(fd) = self.final_message_fd {
if !(self.inner_has_final_line)(&self.inner) {
write_without_waiting(fd, message);
}
}
write_without_waiting(libc::STDERR_FILENO, message);
}
}
impl CappedWriter<BoundedWriter<File>> {
pub fn file(file: File, file_limit: u64, budget: Option<LogBudget>) -> Self {
let fd = file.as_raw_fd();
Self {
inner: BoundedWriter::new(file, file_limit),
budget,
final_message_fd: Some(fd),
inner_has_final_line: BoundedWriter::has_truncated,
}
}
}
impl CappedWriter<detcore::util::DroppingStderr> {
pub fn stderr(budget: Option<LogBudget>) -> Self {
Self {
inner: detcore::util::DroppingStderr,
budget,
final_message_fd: None,
inner_has_final_line: |_| false,
}
}
}
static LOG_CAP_EXIT_BOUND_ENABLED: AtomicBool = AtomicBool::new(false);
static LOG_CAP_REPORTED: AtomicBool = AtomicBool::new(false);
static LOG_CAP_EXIT_SCHEDULED: AtomicBool = AtomicBool::new(false);
const LOG_CAP_OUTER_GRACE: std::time::Duration = std::time::Duration::from_millis(750);
pub(crate) fn enable_log_cap_exit_bound() {
LOG_CAP_EXIT_BOUND_ENABLED.store(true, Ordering::Relaxed);
hermit::nonwaiting_write::forbid_waiting_diagnostics();
}
pub(crate) fn write_stderr_diagnostic(message: &str) {
if hermit::nonwaiting_write::diagnostics_must_not_wait() {
write_without_waiting(libc::STDERR_FILENO, message.as_bytes());
} else {
let _ = detcore::util::RetryingStderr.write_all(message.as_bytes());
}
}
macro_rules! diagnostic_eprintln {
($($arg:tt)*) => {
if hermit::nonwaiting_write::diagnostics_must_not_wait() {
let mut line = format!($($arg)*);
line.push('\n');
hermit::nonwaiting_write::write_without_waiting(
libc::STDERR_FILENO,
line.as_bytes(),
);
} else {
eprintln!($($arg)*);
}
};
}
pub(crate) use diagnostic_eprintln;
pub(crate) fn bound_log_cap_exit() {
bound_log_cap_exit_with(|timer| {
std::thread::Builder::new()
.name("log-cap-exit".to_string())
.spawn(timer)
.map(drop)
});
}
fn bound_log_cap_exit_with(start_timer: impl FnOnce(Box<dyn FnOnce() + Send>) -> io::Result<()>) {
if !LOG_CAP_EXIT_BOUND_ENABLED.load(Ordering::Relaxed)
|| LOG_CAP_EXIT_SCHEDULED.swap(true, Ordering::Relaxed)
{
return;
}
std::panic::set_hook(Box::new(|info| {
write_without_waiting(
libc::STDERR_FILENO,
format!("hermit: panic after the log cap ended the run: {info}\n").as_bytes(),
);
exit_with_log_cap_status()
}));
let timer: Box<dyn FnOnce() + Send> = Box::new(|| {
std::thread::sleep(LOG_CAP_OUTER_GRACE);
exit_with_log_cap_status()
});
if start_timer(timer).is_err() {
exit_with_log_cap_status()
}
}
fn exit_with_log_cap_status() -> ! {
if !LOG_CAP_REPORTED.swap(true, Ordering::Relaxed) {
write_without_waiting(libc::STDERR_FILENO, LOG_CAP_CLASS_LINE.as_bytes());
}
unsafe { libc::_exit(hermit::HERMIT_LOG_CAP_EXIT) }
}
pub(crate) const LOG_CAP_CLASS_LINE: &str = "HERMIT_LOG_CAP class=log-cap\n";
pub(crate) fn report_log_cap_without_waiting(report: &str) {
if !LOG_CAP_REPORTED.swap(true, Ordering::Relaxed) {
write_without_waiting(libc::STDERR_FILENO, report.as_bytes());
}
}
impl<W: Write> Write for CappedWriter<W> {
fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
let Some(budget) = &self.budget else {
return self.inner.write(buf);
};
match budget.charge(buf.len() as u64) {
Charge::Within => {}
Charge::Crossed => {
let budget = budget.clone();
self.exceeded(&budget)
}
Charge::AlreadyOver => return Ok(buf.len()),
}
let _admitted = AdmittedWrite(budget);
let written = self.inner.write(buf).inspect_err(|_| {
budget.refund(buf.len() as u64);
})?;
if written < buf.len() {
budget.refund((buf.len() - written) as u64);
}
Ok(written)
}
fn flush(&mut self) -> io::Result<()> {
self.inner.flush()
}
}
fn env_filter(level: LevelFilter) -> EnvFilter {
EffectiveFilter::from_default_env(level).into_filter()
}
pub struct TracingGuard {
_worker: Option<tracing_appender::non_blocking::WorkerGuard>,
}
impl TracingGuard {
fn synchronous() -> Self {
Self { _worker: None }
}
#[cfg(test)]
pub(crate) fn is_synchronous(&self) -> bool {
self._worker.is_none()
}
}
#[cfg(test)]
fn file_subscriber<W: Write + Send + 'static>(
level: LevelFilter,
f: W,
) -> (impl Subscriber, tracing_appender::non_blocking::WorkerGuard) {
let filter = env_filter(level);
let (writer, guard) = tracing_appender::non_blocking(f);
let subscriber = tracing_subscriber::fmt()
.with_env_filter(filter)
.with_writer(writer)
.with_ansi(false)
.finish();
(subscriber, guard)
}
fn sync_file_subscriber<W: Write + Send + 'static>(level: LevelFilter, f: W) -> impl Subscriber {
let filter = env_filter(level);
tracing_subscriber::fmt()
.with_env_filter(filter)
.with_writer(std::sync::Mutex::new(f))
.with_ansi(false)
.finish()
}
pub fn init_sync_file_tracing<W: Write + Send + 'static>(
level: Option<LevelFilter>,
f: W,
backend: Backend,
) -> TracingGuard {
align_tracing_pid_baseline(backend);
let level = level.unwrap_or(DEFAULT_TRACE_LEVEL);
let subscriber = sync_file_subscriber(level, f);
subscriber
.try_init()
.expect("global tracing subscriber to install");
TracingGuard::synchronous()
}
pub(super) fn align_tracing_pid_baseline(backend: Backend) {
if backend == Backend::Kvm {
return;
}
if unsafe { libc::getpid() } != 1 {
return;
}
let child = unsafe { libc::fork() };
assert!(
child >= 0,
"failed to reserve the tracing PID slot: {}",
io::Error::last_os_error()
);
if child == 0 {
unsafe { libc::_exit(0) };
}
let mut status = 0;
loop {
let waited = unsafe { libc::waitpid(child, &mut status, 0) };
if waited == child {
break;
}
let error = io::Error::last_os_error();
if waited < 0 && error.kind() == io::ErrorKind::Interrupted {
continue;
}
panic!("failed to reap tracing PID-slot process {child}: {error}");
}
assert!(
libc::WIFEXITED(status) && libc::WEXITSTATUS(status) == 0,
"tracing PID-slot process {child} exited unexpectedly: {status:#x}"
);
assert_eq!(
child,
detcore::ROOT_DETPID.as_raw() - 1,
"fresh PID namespace did not reserve the expected tracing slot"
);
}
pub fn stderr_subscriber(level: Option<LevelFilter>, budget: Option<LogBudget>) -> impl Subscriber {
let level = level.unwrap_or(DEFAULT_TRACE_LEVEL);
let filter = env_filter(level);
tracing_subscriber::fmt()
.with_env_filter(filter)
.with_writer(move || CappedWriter::stderr(budget.clone()))
.with_ansi(stderr().is_terminal())
.finish()
}
pub(crate) enum EarlyLog {
File(CappedWriter<BoundedWriter<File>>),
Stderr(Option<LogBudget>),
}
struct NonWaitingStderr;
impl Write for NonWaitingStderr {
fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
write_without_waiting(libc::STDERR_FILENO, buf);
Ok(buf.len())
}
fn flush(&mut self) -> io::Result<()> {
Ok(())
}
}
pub(crate) fn emit_before_tracing(level: Option<LevelFilter>, log: EarlyLog, emit: impl FnOnce()) {
let level = level.unwrap_or(DEFAULT_TRACE_LEVEL);
match log {
EarlyLog::File(writer) => {
tracing::subscriber::with_default(sync_file_subscriber(level, writer), emit)
}
EarlyLog::Stderr(_) if hermit::nonwaiting_write::diagnostics_must_not_wait() => {
let subscriber = tracing_subscriber::fmt()
.with_env_filter(env_filter(level))
.with_writer(|| NonWaitingStderr)
.with_ansi(false)
.finish();
tracing::subscriber::with_default(subscriber, emit)
}
EarlyLog::Stderr(budget) => {
tracing::subscriber::with_default(stderr_subscriber(Some(level), budget), emit)
}
}
}
pub fn init_stderr_tracing(
level: Option<LevelFilter>,
backend: Backend,
budget: Option<LogBudget>,
) {
align_tracing_pid_baseline(backend);
stderr_subscriber(level, budget)
.try_init()
.expect("global tracing subscriber to install")
}
#[cfg(test)]
mod tests {
use std::sync::Mutex;
use hermit::nonwaiting_write::last_errno;
use hermit::nonwaiting_write::proc_self_fd_path;
use hermit::nonwaiting_write::suppressing_diagnostic_signals;
use reverie::process::Container;
use reverie::process::Mount;
use reverie::process::Namespace;
use super::*;
static ENV_LOCK: Mutex<()> = Mutex::new(());
fn pid_namespace() -> Container {
let mut container = Container::new();
container
.unshare(Namespace::PID)
.map_root()
.mount(Mount::proc().allow_readonly_fallback());
container
}
fn fork_and_observe_child_pid() -> i32 {
let child = unsafe { libc::fork() };
assert!(child >= 0, "fork failed: {}", io::Error::last_os_error());
if child == 0 {
let observed = unsafe { libc::getpid() };
unsafe {
libc::_exit(if observed == detcore::ROOT_DETPID.as_raw() {
0
} else {
1
})
};
}
let mut status = 0;
assert_eq!(unsafe { libc::waitpid(child, &mut status, 0) }, child);
assert!(libc::WIFEXITED(status));
assert_eq!(libc::WEXITSTATUS(status), 0, "child observed the wrong PID");
child
}
fn deny_host_thread_creation() -> io::Result<()> {
let denied = 0x0005_0000 | libc::EPERM as u32; let mut filter = [
libc::sock_filter {
code: 0x20, jt: 0,
jf: 0,
k: 0, },
libc::sock_filter {
code: 0x15, jt: 4,
jf: 0,
k: libc::SYS_clone3 as u32,
},
libc::sock_filter {
code: 0x15,
jt: 0,
jf: 2,
k: libc::SYS_clone as u32,
},
libc::sock_filter {
code: 0x20, jt: 0,
jf: 0,
k: 16, },
libc::sock_filter {
code: 0x45, jt: 1,
jf: 0,
k: libc::CLONE_THREAD as u32,
},
libc::sock_filter {
code: 0x06, jt: 0,
jf: 0,
k: 0x7fff_0000, },
libc::sock_filter {
code: 0x06, jt: 0,
jf: 0,
k: denied,
},
];
let program = libc::sock_fprog {
len: filter.len() as u16,
filter: filter.as_mut_ptr(),
};
unsafe {
if libc::prctl(libc::PR_SET_NO_NEW_PRIVS, 1, 0, 0, 0) == -1 {
return Err(io::Error::last_os_error());
}
if libc::prctl(
libc::PR_SET_SECCOMP,
libc::SECCOMP_MODE_FILTER,
&program as *const libc::sock_fprog,
) == -1
{
return Err(io::Error::last_os_error());
}
}
Ok(())
}
#[test]
fn synchronous_pid_alignment_matches_the_file_appender_baseline() {
let synchronous_pid = pid_namespace()
.run(|| {
assert_eq!(unsafe { libc::getpid() }, 1);
align_tracing_pid_baseline(Backend::Ptrace);
fork_and_observe_child_pid()
})
.expect("synchronous baseline namespace failed");
let appender_pid = pid_namespace()
.run(|| {
assert_eq!(unsafe { libc::getpid() }, 1);
let (_subscriber, guard) = file_subscriber(DEFAULT_TRACE_LEVEL, io::sink());
let child = fork_and_observe_child_pid();
drop(guard);
child
})
.expect("file-appender baseline namespace failed");
assert_eq!(synchronous_pid, detcore::ROOT_DETPID.as_raw());
assert_eq!(synchronous_pid, appender_pid);
}
#[test]
fn pid_alignment_succeeds_when_host_thread_creation_is_denied() {
let guest_pid = pid_namespace()
.run(|| {
assert_eq!(unsafe { libc::getpid() }, 1);
deny_host_thread_creation().expect("cannot install host-thread deny filter");
align_tracing_pid_baseline(Backend::Ptrace);
fork_and_observe_child_pid()
})
.expect("thread-free alignment namespace failed");
assert_eq!(guest_pid, detcore::ROOT_DETPID.as_raw());
}
#[test]
fn kvm_pid_alignment_allocates_no_host_task() {
let next_pid = pid_namespace()
.run(|| {
assert_eq!(unsafe { libc::getpid() }, 1);
align_tracing_pid_baseline(Backend::Kvm);
let child = unsafe { libc::fork() };
assert!(child >= 0, "fork failed: {}", io::Error::last_os_error());
if child == 0 {
unsafe { libc::_exit(0) };
}
let mut status = 0;
assert_eq!(unsafe { libc::waitpid(child, &mut status, 0) }, child);
assert!(libc::WIFEXITED(status));
assert_eq!(libc::WEXITSTATUS(status), 0);
child
})
.expect("KVM no-allocation namespace failed");
assert_eq!(next_pid, 2);
}
#[test]
fn bound_truncates_and_announces_exactly_once() {
let mut sink: Vec<u8> = Vec::new();
{
let mut writer = BoundedWriter::new(&mut sink, 100);
for _ in 0..50 {
writer.write_all(&[b'x'; 10]).unwrap();
}
writer.flush().unwrap();
}
let body = sink.iter().filter(|byte| **byte == b'x').count();
let text = String::from_utf8_lossy(&sink);
assert_eq!(body, 100, "wrote past the bound");
assert_eq!(
text.matches("HERMIT LOG TRUNCATED").count(),
1,
"truncation must be announced exactly once, not per write"
);
}
#[test]
fn under_the_bound_nothing_is_truncated_or_announced() {
let mut sink: Vec<u8> = Vec::new();
{
let mut writer = BoundedWriter::new(&mut sink, 1000);
for _ in 0..50 {
writer.write_all(&[b'x'; 10]).unwrap();
}
}
assert_eq!(sink.len(), 500);
assert!(!String::from_utf8_lossy(&sink).contains("HERMIT LOG TRUNCATED"));
}
#[test]
fn a_zero_limit_disables_the_bound() {
let mut sink: Vec<u8> = Vec::new();
{
let mut writer = BoundedWriter::new(&mut sink, 0);
writer.write_all(&[b'z'; 4096]).unwrap();
}
assert_eq!(sink.len(), 4096);
}
#[test]
fn a_single_straddling_write_announces_without_a_following_write() {
let mut sink: Vec<u8> = Vec::new();
{
let mut writer = BoundedWriter::new(&mut sink, 10);
writer.write_all(&[b'q'; 40]).unwrap();
}
let text = String::from_utf8_lossy(&sink);
assert_eq!(
text.matches("HERMIT LOG TRUNCATED").count(),
1,
"a truncated final write must announce itself: {text}"
);
assert_eq!(sink.iter().filter(|b| **b == b'q').count(), 10);
}
#[test]
fn the_written_marker_is_the_text_the_comparator_matches() {
let mut sink: Vec<u8> = Vec::new();
{
let mut writer = BoundedWriter::new(&mut sink, 64);
for _ in 0..20 {
writer
.write_all(b"2022-09-06T14:15:47.000000Z INFO detcore: DETLOG x\n")
.unwrap();
}
writer.flush().unwrap();
}
let written = String::from_utf8(sink).unwrap();
assert!(
detcore::logdiff::log_was_truncated(&written),
"the bounded writer produced {written:?}, which detcore::logdiff does not classify \
as truncated; a truncated pair would silently be compared on its prefix"
);
let mut unbounded: Vec<u8> = Vec::new();
{
let mut writer = BoundedWriter::new(&mut unbounded, 0);
writer
.write_all(b"2022-09-06T14:15:47.000000Z INFO detcore: DETLOG x\n")
.unwrap();
}
assert!(
!detcore::logdiff::log_was_truncated(&String::from_utf8(unbounded).unwrap()),
"an untruncated log must not be classified as truncated"
);
}
#[test]
fn a_malformed_bound_is_an_error_not_a_silent_default() {
let _lock = ENV_LOCK.lock().unwrap_or_else(|e| e.into_inner());
let restore = std::env::var(LOG_MAX_BYTES_ENV).ok();
unsafe {
for bad in ["unlimited", "none", "1GiB", "-1", "", "1 000"] {
std::env::set_var(LOG_MAX_BYTES_ENV, bad);
assert!(
log_max_bytes().is_err(),
"{bad:?} must be rejected, not silently read as {DEFAULT_LOG_MAX_BYTES}"
);
}
for (good, expected) in [("0", 0u64), ("4096", 4096), (" 4096 ", 4096)] {
std::env::set_var(LOG_MAX_BYTES_ENV, good);
assert_eq!(
log_max_bytes().unwrap(),
expected,
"{good:?} must be accepted"
);
}
std::env::remove_var(LOG_MAX_BYTES_ENV);
assert_eq!(
log_max_bytes().unwrap(),
DEFAULT_LOG_MAX_BYTES,
"an unset variable is the only thing that means the default"
);
match restore {
Some(v) => std::env::set_var(LOG_MAX_BYTES_ENV, v),
None => std::env::remove_var(LOG_MAX_BYTES_ENV),
}
}
}
#[test]
fn a_write_straddling_the_bound_reports_full_consumption() {
let mut sink: Vec<u8> = Vec::new();
let mut writer = BoundedWriter::new(&mut sink, 5);
assert_eq!(writer.write(&[b'y'; 40]).unwrap(), 40);
}
#[test]
fn max_log_bytes_accepts_binary_suffixes() {
for (raw, expected) in [
("1", 1),
("4096", 4096),
("1k", 1 << 10),
("64K", 64 << 10),
("512m", 512 << 20),
("8G", 8 << 30),
("8g", 8 << 30),
("8Gi", 8 << 30),
("8GiB", 8 << 30),
("8GB", 8 << 30),
("2T", 2 << 40),
("100b", 100),
(" 8G ", 8 << 30),
] {
assert_eq!(parse_max_log_bytes(raw), Ok(expected), "{raw:?}");
}
}
#[test]
fn max_log_bytes_refusals_redirect_to_a_working_value() {
for raw in [
"",
"G",
"-1",
"8X",
"8.5G",
"8 G",
"99999999999999999999",
"20000000T",
] {
let error = parse_max_log_bytes(raw).expect_err(raw);
assert!(
error.contains("e.g. --max-log-bytes=8G"),
"{raw:?}: {error}"
);
}
for raw in ["0", "0G"] {
let error = parse_max_log_bytes(raw).expect_err(raw);
assert!(
error.contains("Omit --max-log-bytes") && error.contains("8G"),
"{raw:?}: {error}"
);
}
}
#[test]
fn byte_sizes_render_in_the_accepted_spelling() {
for (bytes, expected) in [
(8u64 << 30, "8G"),
(1536 << 20, "1536M"),
(64 << 10, "64K"),
(3 << 40, "3T"),
(1000, "1000"),
] {
assert_eq!(format_byte_size(bytes), expected);
assert_eq!(parse_max_log_bytes(expected), Ok(bytes));
}
}
#[test]
fn the_budget_reports_the_crossing_exactly_once() {
let budget = LogBudget::new(10).unwrap();
assert_eq!(budget.charge(4), Charge::Within);
assert_eq!(budget.charge(6), Charge::Within, "exactly the limit fits");
assert_eq!(budget.charge(1), Charge::Crossed);
assert_eq!(budget.charge(1), Charge::AlreadyOver);
assert_eq!(budget.charge(100), Charge::AlreadyOver);
let budget = LogBudget::new(10).unwrap();
assert_eq!(budget.charge(8), Charge::Within);
budget.refund(3);
assert_eq!(budget.spent(), 5);
assert_eq!(budget.charge(u64::MAX), Charge::Crossed, "no wraparound");
assert_eq!(
budget.spent(),
u64::MAX,
"the stored total saturates instead of wrapping to 4"
);
}
#[test]
fn a_total_past_u64_max_crosses_even_the_largest_limit() {
let budget = LogBudget::new(u64::MAX).unwrap();
assert_eq!(budget.charge(u64::MAX - 1), Charge::Within);
assert_eq!(budget.charge(1), Charge::Within, "exactly u64::MAX fits");
assert_eq!(budget.spent(), u64::MAX);
assert_eq!(budget.charge(1), Charge::Crossed, "one byte past u64::MAX");
assert_eq!(budget.spent(), u64::MAX, "saturated, not wrapped to 0");
assert_eq!(budget.charge(1), Charge::AlreadyOver);
assert_eq!(budget.charge(u64::MAX), Charge::AlreadyOver);
assert_eq!(budget.spent(), u64::MAX);
}
#[test]
fn a_refund_after_the_crossing_does_not_reopen_the_budget() {
let budget = LogBudget::new(10).unwrap();
assert_eq!(budget.charge(6), Charge::Within, "writer A");
assert_eq!(budget.charge(5), Charge::Crossed, "writer B crosses at 11");
budget.refund(6);
assert_eq!(budget.spent(), 5, "writer A's failed write was refunded");
assert_eq!(
budget.charge(6),
Charge::AlreadyOver,
"writer C must not cross a second time"
);
assert_eq!(budget.charge(1), Charge::AlreadyOver);
}
#[test]
fn a_write_in_progress_at_the_crossing_withholds_the_final_message() {
let budget = LogBudget::new(10).unwrap().with_drain_bound(Duration::ZERO);
assert_eq!(budget.charge(6), Charge::Within, "A is admitted");
assert_eq!(budget.in_progress(), 1);
assert_eq!(budget.charge(5), Charge::Crossed, "B crosses at 11");
assert_eq!(budget.in_progress(), 1, "B's own admission has ended");
assert!(
!budget.writes_drained(),
"A's write is in progress, so B must omit the final message"
);
budget.finish();
assert_eq!(budget.in_progress(), 0, "A has written");
assert!(
budget.writes_drained(),
"nothing is in progress, so the message may be written last"
);
assert_eq!(budget.charge(1), Charge::AlreadyOver, "C is refused");
assert_eq!(budget.in_progress(), 0, "and C was never admitted");
assert!(budget.writes_drained());
}
#[test]
fn a_write_admitted_before_the_crossing_is_waited_for_even_after_a_refund() {
let budget = LogBudget::new(10).unwrap().with_drain_bound(Duration::ZERO);
assert_eq!(budget.charge(6), Charge::Within, "A is admitted");
assert!(admit_write(&budget.cells().admission), "C is admitted");
assert_eq!(budget.charge(5), Charge::Crossed, "B crosses at 11");
budget.refund(6);
budget.finish();
assert_eq!(budget.spent(), 5, "A's failed write was refunded");
assert_eq!(
budget.account(1),
Charge::Within,
"C's accounting fits after the refund"
);
assert_eq!(budget.in_progress(), 1, "C is still in progress");
assert!(!budget.writes_drained(), "so the message is withheld");
assert_eq!(budget.charge(1), Charge::AlreadyOver, "D is refused");
assert_eq!(budget.spent(), 6, "D charged nothing");
budget.finish();
assert!(budget.writes_drained(), "C has written");
}
#[test]
fn only_the_first_write_past_the_limit_claims_the_crossing() {
let budget = LogBudget::new(10).unwrap();
let admission = &budget.cells().admission;
assert!(admit_write(admission), "A is admitted");
assert!(admit_write(admission), "B is admitted");
assert_eq!(budget.account(11), Charge::Crossed, "B crosses");
assert_eq!(budget.account(1), Charge::AlreadyOver, "A is over");
assert_eq!(budget.in_progress(), 0);
assert_eq!(admission.load(Ordering::Relaxed), CROSSED);
assert!(!admit_write(admission), "nothing is admitted after it");
assert_eq!(admission.load(Ordering::Relaxed), CROSSED);
}
#[test]
fn the_drain_wait_gives_up_at_its_bound() {
let budget = LogBudget::new(10).unwrap();
assert_eq!(budget.charge(1), Charge::Within, "a write that never ends");
assert_eq!(budget.charge(10), Charge::Crossed);
for bound in [Duration::from_millis(30), LOG_CAP_DRAIN_BOUND] {
let started = Instant::now();
assert!(!wait_for_writes_in_progress(
&budget.cells().admission,
bound
));
let waited = started.elapsed();
assert!(
waited >= bound,
"gave up after {waited:?}, before {bound:?}"
);
assert!(
waited < Duration::from_secs(1),
"waited {waited:?} for a bound of {bound:?}"
);
}
assert_eq!(
LogBudget::new(1)
.unwrap()
.with_drain_bound(Duration::from_secs(10))
.drain_bound,
LOG_CAP_DRAIN_BOUND_MAX
);
}
#[test]
fn capped_writer_ends_every_admission_it_starts() {
struct Sink(fn(&[u8]) -> io::Result<usize>);
impl Write for Sink {
fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
(self.0)(buf)
}
fn flush(&mut self) -> io::Result<()> {
Ok(())
}
}
let budget = LogBudget::new(1 << 20).unwrap();
let mut whole = CappedWriter::new(Sink(|buf| Ok(buf.len())), Some(budget.clone()));
assert_eq!(whole.write(b"abcd").unwrap(), 4);
assert_eq!((budget.in_progress(), budget.spent()), (0, 4));
let mut partial = CappedWriter::new(Sink(|buf| Ok(buf.len() / 2)), Some(budget.clone()));
assert_eq!(partial.write(b"abcd").unwrap(), 2);
assert_eq!((budget.in_progress(), budget.spent()), (0, 6));
let mut refusing = CappedWriter::new(
Sink(|_| Err(io::Error::from_raw_os_error(libc::EIO))),
Some(budget.clone()),
);
assert!(refusing.write(b"abcd").is_err());
assert_eq!((budget.in_progress(), budget.spent()), (0, 6));
let mut panicking =
CappedWriter::new(Sink(|_| panic!("the sink panicked")), Some(budget.clone()));
let unwound =
std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| panicking.write(b"abcd")));
assert!(unwound.is_err());
assert_eq!(budget.in_progress(), 0);
}
const LOG_CAP_STRESS_CHILD: &str = "HERMIT_TEST_LOG_CAP_STRESS_DRAIN_MS";
const LOG_CAP_STRESS_LIMIT: u64 = 64 << 10;
const LOG_CAP_STRESS_WRITERS: usize = 8;
const LOG_CAP_STRESS_RUNS: usize = 20;
#[test]
fn the_final_message_is_the_last_line_when_writers_race_the_crossing() {
if let Ok(bound) = std::env::var(LOG_CAP_STRESS_CHILD) {
race_writers_to_the_crossing(Duration::from_millis(bound.parse().unwrap()));
}
let message = exceeded_message(LOG_CAP_STRESS_LIMIT);
let message = message.as_bytes();
for bound in [Duration::ZERO, LOG_CAP_DRAIN_BOUND] {
let mut delivered = 0;
for run in 0..LOG_CAP_STRESS_RUNS {
let output = std::process::Command::new(std::env::current_exe().unwrap())
.args([
"tracing::tests::the_final_message_is_the_last_line_when_writers_race_the_crossing",
"--exact",
"--nocapture",
"--test-threads=1",
])
.env(LOG_CAP_STRESS_CHILD, bound.as_millis().to_string())
.stdin(std::process::Stdio::null())
.stdout(std::process::Stdio::null())
.stderr(std::process::Stdio::piped())
.output()
.unwrap();
let stderr = &output.stderr;
let tail = String::from_utf8_lossy(&stderr[stderr.len().saturating_sub(600)..]);
assert_eq!(
output.status.code(),
Some(hermit::HERMIT_LOG_CAP_EXIT),
"run {run} at drain bound {bound:?}; stderr tail:\n{tail}"
);
let copies = stderr
.windows(message.len())
.filter(|window| *window == message)
.count();
assert!(copies <= 1, "run {run}: {copies} final messages");
if copies == 1 {
delivered += 1;
assert!(
stderr.ends_with(message),
"run {run} at drain bound {bound:?}: a line followed the final \
message; stderr tail:\n{tail}"
);
}
}
eprintln!(
"drain bound {bound:?}: the final message was delivered, last, in {delivered} \
of {LOG_CAP_STRESS_RUNS} runs; every run exited {}",
hermit::HERMIT_LOG_CAP_EXIT
);
}
}
fn race_writers_to_the_crossing(drain_bound: Duration) -> ! {
let budget = LogBudget::new(LOG_CAP_STRESS_LIMIT)
.unwrap()
.with_drain_bound(drain_bound);
let start = Arc::new(std::sync::Barrier::new(LOG_CAP_STRESS_WRITERS));
let writers: Vec<_> = (0..LOG_CAP_STRESS_WRITERS)
.map(|writer| {
let budget = budget.clone();
let start = Arc::clone(&start);
std::thread::spawn(move || {
let mut sink = CappedWriter::stderr(Some(budget));
start.wait();
for line in 0u64..=u64::MAX {
let _ = sink.write_all(format!("writer {writer} line {line}\n").as_bytes());
}
})
})
.collect();
for writer in writers {
let _ = writer.join();
}
unsafe { libc::_exit(1) }
}
#[test]
fn capped_writer_counts_what_it_passes_through() {
let mut sink = Vec::new();
let budget = LogBudget::new(1 << 20).unwrap();
let mut writer = CappedWriter::new(&mut sink, Some(budget.clone()));
writer.write_all(b"hello ").unwrap();
writer.write_all(b"world\n").unwrap();
drop(writer);
assert_eq!(sink, b"hello world\n");
assert_eq!(budget.spent(), 12);
let mut sink = Vec::new();
let mut writer = CappedWriter::new(&mut sink, None);
writer.write_all(&[b'x'; 4096]).unwrap();
drop(writer);
assert_eq!(sink.len(), 4096);
}
#[test]
fn capped_writer_counts_bytes_the_file_bound_discards() {
let mut sink = Vec::new();
let budget = LogBudget::new(1 << 20).unwrap();
let mut writer = CappedWriter::new(BoundedWriter::new(&mut sink, 8), Some(budget.clone()));
for _ in 0..10 {
writer.write_all(&[b'z'; 100]).unwrap();
}
assert_eq!(budget.spent(), 1000);
}
#[test]
fn crossing_the_cap_exits_with_the_log_cap_status_and_says_why() {
use std::io::Read;
use std::os::fd::FromRawFd;
let budget = LogBudget::new(100).unwrap();
let mut fds = [0; 2];
assert_eq!(unsafe { libc::pipe2(fds.as_mut_ptr(), libc::O_CLOEXEC) }, 0);
let (read_fd, write_fd) = (fds[0], fds[1]);
let child = unsafe { libc::fork() };
assert!(child >= 0, "fork failed: {}", io::Error::last_os_error());
if child == 0 {
unsafe {
libc::close(read_fd);
let null = libc::open(c"/dev/null".as_ptr(), libc::O_WRONLY);
libc::dup2(null, 2);
let mut writer = CappedWriter::file(
std::fs::File::from_raw_fd(write_fd),
0,
Some(budget.clone()),
);
let _ = writer.write_all(&[b'a'; 60]);
let _ = writer.write_all(&[b'b'; 60]);
libc::_exit(0);
}
}
unsafe { libc::close(write_fd) };
let mut output = Vec::new();
unsafe { std::fs::File::from_raw_fd(read_fd) }
.read_to_end(&mut output)
.unwrap();
let mut status = 0;
assert_eq!(unsafe { libc::waitpid(child, &mut status, 0) }, child);
assert!(libc::WIFEXITED(status), "status {status:#x}");
assert_eq!(libc::WEXITSTATUS(status), hermit::HERMIT_LOG_CAP_EXIT);
let text = String::from_utf8(output).unwrap();
let (delivered, message) = text.split_at(60);
assert_eq!(delivered, "a".repeat(60));
assert!(
!message.contains("bbbb"),
"the crossing write was not delivered"
);
assert!(
message.starts_with("hermit: log output exceeded --max-log-bytes=100 (100 bytes)"),
"{message}"
);
assert!(
message.ends_with("to let the run finish.\nHERMIT_LOG_CAP class=log-cap\n"),
"{message}"
);
assert_eq!(
budget.spent(),
120,
"the child's charges are visible to the parent"
);
}
#[test]
fn the_crossing_message_ends_with_the_class_line_at_every_limit() {
for limit in [1, 100, 64 << 10, 8 << 30, u64::MAX] {
let message = exceeded_message(limit);
let named = format!(
"hermit: log output exceeded --max-log-bytes={} ({limit} bytes);",
format_byte_size(limit)
);
assert!(message.starts_with(&named), "{message}");
assert!(message.ends_with(LOG_CAP_CLASS_LINE), "{message}");
assert_eq!(message.matches("HERMIT_LOG_CAP").count(), 1, "{message}");
assert!(message.len() < libc::PIPE_BUF, "{} bytes", message.len());
}
}
#[test]
fn a_log_ending_with_the_stop_message_reads_as_truncated() {
let record = "2026-10-05T12:00:00.000000Z INFO detcore: DETLOG [syscall] finish syscall #1: \
write(1, 0x2000, 1) = Ok(1)\n";
for limit in [1, 100, 64 << 10, 8 << 30, u64::MAX] {
let log = format!("{record}{}", exceeded_message(limit));
assert!(detcore::logdiff::log_was_truncated(&log), "{log}");
}
assert!(!detcore::logdiff::log_was_truncated(record));
}
#[test]
fn the_stop_message_is_not_appended_after_the_truncation_marker() {
use std::io::Read;
use std::os::fd::FromRawFd;
let budget = LogBudget::new(100).unwrap();
let mut fds = [0; 2];
assert_eq!(unsafe { libc::pipe2(fds.as_mut_ptr(), libc::O_CLOEXEC) }, 0);
let (read_fd, write_fd) = (fds[0], fds[1]);
let child = unsafe { libc::fork() };
assert!(child >= 0, "fork failed: {}", io::Error::last_os_error());
if child == 0 {
unsafe {
libc::close(read_fd);
let null = libc::open(c"/dev/null".as_ptr(), libc::O_WRONLY);
libc::dup2(null, 2);
let mut writer = CappedWriter::file(
std::fs::File::from_raw_fd(write_fd),
50,
Some(budget.clone()),
);
let _ = writer.write_all(&[b'a'; 60]);
let _ = writer.write_all(&[b'b'; 60]);
libc::_exit(0);
}
}
unsafe { libc::close(write_fd) };
let mut output = Vec::new();
unsafe { std::fs::File::from_raw_fd(read_fd) }
.read_to_end(&mut output)
.unwrap();
let mut status = 0;
assert_eq!(unsafe { libc::waitpid(child, &mut status, 0) }, child);
assert!(libc::WIFEXITED(status), "status {status:#x}");
assert_eq!(libc::WEXITSTATUS(status), hermit::HERMIT_LOG_CAP_EXIT);
let mut expected = vec![b'a'; 50];
expected.extend_from_slice(TRUNCATION_MARKER);
let text = String::from_utf8(output).unwrap();
assert_eq!(text.as_bytes(), expected.as_slice(), "{text}");
assert!(detcore::logdiff::log_was_truncated(&text), "{text}");
}
fn full_blocking_pipe() -> (libc::c_int, libc::c_int) {
let mut fds = [0; 2];
assert_eq!(
unsafe { libc::pipe2(fds.as_mut_ptr(), libc::O_CLOEXEC | libc::O_NONBLOCK) },
0
);
for chunk in [&[b'x'; 4096][..], &[b'x'; 1][..]] {
while unsafe { libc::write(fds[1], chunk.as_ptr().cast(), chunk.len()) } > 0 {}
assert_eq!(
io::Error::last_os_error().raw_os_error(),
Some(libc::EAGAIN)
);
}
assert_eq!(unsafe { libc::fcntl(fds[1], libc::F_SETFL, 0) }, 0);
(fds[0], fds[1])
}
#[test]
fn crossing_the_cap_exits_even_when_no_sink_can_take_the_message() {
use std::os::fd::FromRawFd;
use std::time::Duration;
use std::time::Instant;
let budget = LogBudget::new(100).unwrap();
let (sink_read, sink_write) = full_blocking_pipe();
let (stderr_read, stderr_write) = full_blocking_pipe();
let child = unsafe { libc::fork() };
assert!(child >= 0, "fork failed: {}", io::Error::last_os_error());
if child == 0 {
unsafe {
libc::dup2(stderr_write, 2);
let mut writer = CappedWriter::file(
std::fs::File::from_raw_fd(sink_write),
0,
Some(budget.clone()),
);
let _ = writer.write(&[b'c'; 120]);
libc::_exit(0);
}
}
unsafe {
libc::close(sink_write);
libc::close(stderr_write);
}
let deadline = Instant::now() + Duration::from_secs(20);
let mut status = 0;
let exited = loop {
let reaped = unsafe { libc::waitpid(child, &mut status, libc::WNOHANG) };
assert!(reaped >= 0, "waitpid: {}", io::Error::last_os_error());
if reaped == child {
break true;
}
if Instant::now() >= deadline {
unsafe {
libc::kill(child, libc::SIGKILL);
libc::waitpid(child, &mut status, 0);
}
break false;
}
std::thread::sleep(Duration::from_millis(10));
};
unsafe {
libc::close(sink_read);
libc::close(stderr_read);
}
assert!(
exited,
"the crossing writer was still alive after 20 s: it waited on a full sink \
instead of exiting"
);
assert!(libc::WIFEXITED(status), "status {status:#x}");
assert_eq!(libc::WEXITSTATUS(status), hermit::HERMIT_LOG_CAP_EXIT);
assert_eq!(budget.spent(), 120);
}
fn in_child_with_default_sigpipe(body: impl FnOnce()) -> libc::c_int {
let child = unsafe { libc::fork() };
assert!(child >= 0, "fork failed: {}", io::Error::last_os_error());
if child == 0 {
unsafe {
libc::signal(libc::SIGPIPE, libc::SIG_DFL);
let mut empty: libc::sigset_t = mem::zeroed();
libc::sigemptyset(&mut empty);
libc::pthread_sigmask(libc::SIG_SETMASK, &empty, std::ptr::null_mut());
body();
libc::_exit(0);
}
}
let mut status = 0;
assert_eq!(unsafe { libc::waitpid(child, &mut status, 0) }, child);
status
}
fn assert_exited_cleanly(status: libc::c_int, what: &str) {
assert!(
libc::WIFEXITED(status) && libc::WEXITSTATUS(status) == 0,
"{what}: status {status:#x} (signal {})",
if libc::WIFSIGNALED(status) {
libc::WTERMSIG(status)
} else {
0
}
);
}
#[test]
fn a_failed_exit_timer_start_exits_with_the_log_cap_status_at_once() {
let status = in_child_with_default_sigpipe(|| {
LOG_CAP_EXIT_SCHEDULED.store(false, Ordering::Relaxed);
enable_log_cap_exit_bound();
bound_log_cap_exit_with(|_timer| Err(io::Error::from_raw_os_error(libc::EAGAIN)));
});
assert!(libc::WIFEXITED(status), "status {status:#x}");
assert_eq!(libc::WEXITSTATUS(status), hermit::HERMIT_LOG_CAP_EXIT);
}
#[test]
fn a_panic_after_the_cap_ended_the_run_still_exits_with_the_log_cap_status() {
let status = in_child_with_default_sigpipe(|| {
LOG_CAP_EXIT_SCHEDULED.store(false, Ordering::Relaxed);
enable_log_cap_exit_bound();
bound_log_cap_exit_with(|_timer| Ok(()));
let _ = std::panic::catch_unwind(|| panic!("a diagnostic after the cap"));
});
assert!(libc::WIFEXITED(status), "status {status:#x}");
assert_eq!(libc::WEXITSTATUS(status), hermit::HERMIT_LOG_CAP_EXIT);
}
#[test]
fn the_outer_log_cap_diagnostic_is_attempted_at_most_once() {
use std::io::Read;
use std::os::fd::FromRawFd;
let mut fds = [0; 2];
assert_eq!(unsafe { libc::pipe2(fds.as_mut_ptr(), libc::O_CLOEXEC) }, 0);
let status = in_child_with_default_sigpipe(|| {
unsafe { libc::dup2(fds[1], libc::STDERR_FILENO) };
LOG_CAP_REPORTED.store(false, Ordering::Relaxed);
report_log_cap_without_waiting("first report\n");
report_log_cap_without_waiting("second report\n");
exit_with_log_cap_status()
});
unsafe { libc::close(fds[1]) };
let mut delivered = String::new();
unsafe { std::fs::File::from_raw_fd(fds[0]) }
.read_to_string(&mut delivered)
.unwrap();
assert!(libc::WIFEXITED(status), "status {status:#x}");
assert_eq!(libc::WEXITSTATUS(status), hermit::HERMIT_LOG_CAP_EXIT);
assert_eq!(delivered, "first report\n");
}
#[test]
fn a_cap_diagnostic_to_a_departed_reader_raises_no_signal() {
let mut pipe = [0; 2];
assert_eq!(
unsafe { libc::pipe2(pipe.as_mut_ptr(), libc::O_CLOEXEC) },
0
);
unsafe { libc::close(pipe[0]) };
let status = in_child_with_default_sigpipe(|| {
write_without_waiting(pipe[1], b"hermit: diagnostic\n");
});
unsafe { libc::close(pipe[1]) };
assert_exited_cleanly(status, "pipe without a reader");
let mut pair = [0; 2];
assert_eq!(
unsafe {
libc::socketpair(
libc::AF_UNIX,
libc::SOCK_STREAM | libc::SOCK_CLOEXEC,
0,
pair.as_mut_ptr(),
)
},
0
);
unsafe { libc::close(pair[1]) };
let status = in_child_with_default_sigpipe(|| {
write_without_waiting(pair[0], b"hermit: diagnostic\n");
});
unsafe { libc::close(pair[0]) };
assert_exited_cleanly(status, "socket without a peer");
}
#[test]
fn the_diagnostic_signal_guard_consumes_only_the_signal_its_write_raised() {
let mut pipe = [0; 2];
assert_eq!(
unsafe { libc::pipe2(pipe.as_mut_ptr(), libc::O_CLOEXEC) },
0
);
unsafe { libc::close(pipe[0]) };
let status = in_child_with_default_sigpipe(|| unsafe {
suppressing_diagnostic_signals(|| {
if libc::write(pipe[1], b"x".as_ptr().cast(), 1) < 0 {
last_errno()
} else {
0
}
});
let mut pending: libc::sigset_t = mem::zeroed();
libc::sigpending(&mut pending);
let mut mask: libc::sigset_t = mem::zeroed();
libc::pthread_sigmask(libc::SIG_SETMASK, std::ptr::null(), &mut mask);
if libc::sigismember(&pending, libc::SIGPIPE) == 1
|| libc::sigismember(&mask, libc::SIGPIPE) == 1
|| libc::sigismember(&mask, libc::SIGTTOU) == 1
{
libc::_exit(3);
}
});
unsafe { libc::close(pipe[1]) };
assert_exited_cleanly(status, "raw write to a pipe without a reader");
}
#[test]
fn the_proc_fd_path_names_the_descriptor() {
for (fd, expected) in [
(0, "/proc/self/fd/0"),
(2, "/proc/self/fd/2"),
(1234, "/proc/self/fd/1234"),
(i32::MAX, "/proc/self/fd/2147483647"),
] {
let path = proc_self_fd_path(fd);
let end = path.iter().position(|&byte| byte == 0).unwrap();
assert_eq!(std::str::from_utf8(&path[..end]).unwrap(), expected);
}
}
}