use std::ffi::c_void;
use std::mem;
use std::sync::atomic::AtomicBool;
use std::sync::atomic::AtomicUsize;
use std::sync::atomic::Ordering;
use std::time::Duration;
use std::time::Instant;
static mut ORIG_HANDLER: Option<libc::sigaction> = None;
pub fn register_sigbus_handler() {
static REGISTERED: AtomicBool = AtomicBool::new(false);
if REGISTERED.fetch_or(true, Ordering::AcqRel) {
return;
}
crate::page_out::NEED_FIND_REGION.store(true, Ordering::Release);
let mut new_action: libc::sigaction = unsafe { mem::zeroed() };
new_action.sa_sigaction = signal_handler as *const () as usize;
new_action.sa_flags = libc::SA_SIGINFO | libc::SA_ONSTACK;
tracing::debug!("registering SIGBUS handler");
unsafe {
ORIG_HANDLER = Some(mem::zeroed());
#[expect(static_mut_refs)]
if let Some(old_handler_mut) = ORIG_HANDLER.as_mut() {
libc::sigaction(libc::SIGBUS, &new_action, old_handler_mut);
}
}
}
unsafe extern "C" fn signal_handler(
sig: libc::c_int,
info: *mut libc::siginfo_t,
ucontext: *mut c_void,
) {
unsafe {
if let Some(info) = info.as_ref() {
let addr = info.si_addr() as usize;
if let Some((_start, _end, writable)) = find_region_with_retry(addr) {
if zero_fill_page(addr, writable).is_ok() {
return;
}
}
}
#[expect(static_mut_refs)]
if let Some(old_handler) = ORIG_HANDLER.as_ref() {
call_original_handler(old_handler, sig, info, ucontext);
}
}
}
fn find_region_with_retry(addr: usize) -> Option<(usize, usize, bool)> {
const MAX_WAIT: Duration = Duration::from_secs(1);
let started = Instant::now();
loop {
match crate::page_out::find_region(addr) {
Ok(region) => return region,
Err(_) if started.elapsed() < MAX_WAIT => unsafe {
libc::sched_yield();
},
Err(_) => return None,
}
}
}
unsafe fn call_original_handler(
action: &libc::sigaction,
sig: libc::c_int,
info: *mut libc::siginfo_t,
ucontext: *mut c_void,
) {
let handler = action.sa_sigaction;
if handler == libc::SIG_IGN || handler == libc::SIG_DFL {
unsafe {
libc::sigaction(sig, action, std::ptr::null_mut());
}
return;
}
if action.sa_flags & libc::SA_SIGINFO != 0 {
let handler: unsafe extern "C" fn(libc::c_int, *mut libc::siginfo_t, *mut c_void) =
unsafe { mem::transmute(handler) };
unsafe { handler(sig, info, ucontext) };
} else {
let handler: unsafe extern "C" fn(libc::c_int) = unsafe { mem::transmute(handler) };
unsafe { handler(sig) };
}
}
fn zero_fill_page(addr: usize, writable: bool) -> Result<(), ()> {
let page_size = crate::page_out::page_size().ok_or(())?;
let start: usize = addr / page_size * page_size;
const MAX_REPEATED_FIXES: usize = 64;
static LAST_START: AtomicUsize = AtomicUsize::new(0);
static REPEATED_FIXES: AtomicUsize = AtomicUsize::new(0);
if LAST_START.swap(start, Ordering::AcqRel) == start {
if REPEATED_FIXES.fetch_add(1, Ordering::AcqRel) >= MAX_REPEATED_FIXES {
return Err(());
}
} else {
REPEATED_FIXES.store(0, Ordering::Release);
}
let mut prot = libc::PROT_READ;
if writable {
prot |= libc::PROT_WRITE
}
let flags = libc::MAP_PRIVATE | libc::MAP_ANONYMOUS | libc::MAP_FIXED;
let fd = -1; let offset = 0;
let mmap_ret = unsafe { libc::mmap(start as _, page_size, prot, flags, fd, offset) };
if mmap_ret == libc::MAP_FAILED {
return Err(());
}
Ok(())
}
#[cfg(test)]
mod tests {
use std::ffi::c_void;
use std::fs::OpenOptions;
use std::mem;
use std::sync::atomic::AtomicUsize;
use std::sync::atomic::Ordering;
use std::time::Duration;
use tempfile::tempdir;
use crate::change_detect::SharedChangeDetector;
use crate::lock::DirLockOptions;
use crate::lock::ScopedDirLock;
use crate::log::Log;
use crate::log::PRIMARY_FILE;
#[test]
fn test_call_original_siginfo_handler() {
static CALLS: AtomicUsize = AtomicUsize::new(0);
unsafe extern "C" fn handler(
sig: libc::c_int,
_info: *mut libc::siginfo_t,
_ucontext: *mut c_void,
) {
assert_eq!(sig, libc::SIGBUS);
CALLS.fetch_add(1, Ordering::Relaxed);
}
let mut action: libc::sigaction = unsafe { mem::zeroed() };
action.sa_sigaction = handler as *const () as usize;
action.sa_flags = libc::SA_SIGINFO;
unsafe {
super::call_original_handler(
&action,
libc::SIGBUS,
std::ptr::null_mut(),
std::ptr::null_mut(),
);
super::call_original_handler(
&action,
libc::SIGBUS,
std::ptr::null_mut(),
std::ptr::null_mut(),
);
}
assert_eq!(CALLS.load(Ordering::Relaxed), 2);
}
#[test]
fn test_call_original_ignored_handler_restores_disposition() {
unsafe extern "C" fn handler(_sig: libc::c_int) {}
let mut current_action: libc::sigaction = unsafe { mem::zeroed() };
current_action.sa_sigaction = handler as *const () as usize;
let mut ignored_action: libc::sigaction = unsafe { mem::zeroed() };
ignored_action.sa_sigaction = libc::SIG_IGN;
let mut original_action: libc::sigaction = unsafe { mem::zeroed() };
let signal = libc::SIGUSR2;
unsafe {
assert_eq!(
libc::sigaction(signal, ¤t_action, &mut original_action),
0
);
super::call_original_handler(
&ignored_action,
signal,
std::ptr::null_mut(),
std::ptr::null_mut(),
);
}
let mut installed_action: libc::sigaction = unsafe { mem::zeroed() };
let query_result =
unsafe { libc::sigaction(signal, std::ptr::null(), &mut installed_action) };
unsafe {
libc::sigaction(signal, &original_action, std::ptr::null_mut());
}
assert_eq!(query_result, 0);
assert_eq!(installed_action.sa_sigaction, libc::SIG_IGN);
}
#[test]
fn test_sigbus_truncate_log() {
super::register_sigbus_handler();
let dir = tempdir().unwrap();
let log_path = dir.path();
const L: usize = 500;
let mut log = Log::open(log_path, Vec::new()).unwrap();
for i in 0..50u8 {
let data = [i; L];
log.append(data).unwrap();
}
log.sync().unwrap();
for (i, entry) in log.iter().enumerate() {
let data = entry.unwrap();
assert_eq!(data.len(), L);
assert!(data.iter().all(|&d| d == i as u8));
}
let primary_path = log_path.join(PRIMARY_FILE);
let mut opts = OpenOptions::new();
let opts = opts.write(true).read(true).truncate(false);
let file = opts.open(primary_path).unwrap();
let orig_len = file.metadata().unwrap().len();
let log = Log::open(log_path, Vec::new()).unwrap();
for truncate_size_base in [orig_len - 1, orig_len / 2, 4096] {
for truncate_size_delta in 0..4096 {
let truncate_size = truncate_size_base - truncate_size_delta;
file.set_len(truncate_size).unwrap();
let mut error_count = 0;
for (i, entry) in log.iter().enumerate() {
match entry {
Ok(data) => {
assert_eq!(data.len(), L);
assert!(data.iter().all(|&d| d == i as u8));
}
Err(_e) => {
error_count += 1;
}
}
}
assert!(error_count > 0);
}
}
}
#[test]
fn test_zero_fill_same_page_again() {
let page_size = crate::page_out::page_size().unwrap();
let page = unsafe {
libc::mmap(
std::ptr::null_mut(),
page_size,
libc::PROT_READ,
libc::MAP_PRIVATE | libc::MAP_ANONYMOUS,
-1,
0,
)
};
assert_ne!(page, libc::MAP_FAILED);
for _ in 0..8 {
assert_eq!(super::zero_fill_page(page as usize, false), Ok(()));
}
unsafe {
libc::munmap(page, page_size);
}
}
#[test]
fn test_sigbus_truncate_rlock_before_first_read() {
super::register_sigbus_handler();
let dir = tempdir().unwrap();
let opts = DirLockOptions {
exclusive: false,
non_blocking: false,
file_name: "rlock",
};
let lock = ScopedDirLock::new_with_options(dir.path(), &opts).unwrap();
let mmap = lock.shared_mmap_mut(std::mem::size_of::<u64>()).unwrap();
OpenOptions::new()
.write(true)
.open(dir.path().join("rlock"))
.unwrap()
.set_len(0)
.unwrap();
let detector = SharedChangeDetector::new(mmap);
assert!(!detector.is_changed());
}
#[test]
fn test_sigbus_lookup_waits_for_busy_registry() {
super::register_sigbus_handler();
let dir = tempdir().unwrap();
let log_path = dir.path().join("log");
let mut log = Log::open(&log_path, Vec::new()).unwrap();
OpenOptions::new()
.write(true)
.open(log_path.join("rlock"))
.unwrap()
.set_len(0)
.unwrap();
log.append([b'a'; 10]).unwrap();
let registry = crate::change_detect::BUFFERS.lock().unwrap();
let syncer = std::thread::spawn(move || log.sync().map(|_| ()));
std::thread::sleep(Duration::from_millis(10));
drop(registry);
syncer.join().unwrap().unwrap();
}
#[test]
fn test_sigbus_truncate_rlock_change_detector() {
super::register_sigbus_handler();
let dir = tempdir().unwrap();
let log_path = dir.path().join("log");
let mut log1 = Log::open(&log_path, Vec::new()).unwrap();
let log2 = Log::open(&log_path, Vec::new()).unwrap();
let file = OpenOptions::new()
.write(true)
.read(true)
.open(log_path.join("rlock"))
.unwrap();
file.set_len(0).unwrap();
log1.append([b'a'; 10]).unwrap();
log1.sync().unwrap();
assert!(!log1.is_changed_on_disk());
assert!(log2.is_changed_on_disk());
}
}