#![cfg(target_os = "linux")]
use core::mem::offset_of;
use core::num::NonZeroUsize;
use core::ptr::NonNull;
use core::sync::atomic::{AtomicU64, Ordering};
use std::ffi::OsStr;
use std::fs::{File, OpenOptions};
use std::io::{self, Read, Seek, Write};
use std::os::unix::ffi::OsStrExt;
use std::os::unix::fs::{FileExt, MetadataExt, OpenOptionsExt};
use std::path::{Path, PathBuf};
use std::sync::Arc;
use crate::heap::{Backing, Inner, PublicHeap};
use crate::layout::{MAGIC, Super};
pub const WINDOW: usize = if cfg!(miri) { 16 << 20 } else { 16 << 30 };
pub const WINDOWS: usize = if cfg!(miri) { 4 } else { 64 };
pub const REGION: usize = WINDOW * WINDOWS;
const _: () = assert!(REGION.is_power_of_two() && WINDOW.is_power_of_two());
pub struct Region {
base: NonNull<u8>,
}
unsafe impl Send for Region {}
unsafe impl Sync for Region {}
impl Region {
pub fn base_of(p: usize) -> usize {
p & !(REGION - 1)
}
pub fn base(&self) -> NonNull<u8> {
self.base
}
pub fn window(&self, k: usize) -> *mut u8 {
self.base.as_ptr().wrapping_add(k * WINDOW)
}
}
#[cfg(not(miri))]
impl Region {
pub fn reserve() -> io::Result<Self> {
let raw = unsafe { libc::mmap(core::ptr::null_mut(), 2 * REGION, libc::PROT_NONE, libc::MAP_PRIVATE | libc::MAP_ANONYMOUS | libc::MAP_NORESERVE, -1, 0) };
if raw == libc::MAP_FAILED {
return Err(io::Error::last_os_error());
}
let raw = raw.cast::<u8>();
let head = raw.align_offset(REGION);
let base = raw.wrapping_add(head);
unsafe {
if head > 0 {
libc::munmap(raw.cast(), head);
}
libc::munmap(base.wrapping_add(REGION).cast(), REGION - head);
}
Ok(Self { base: NonNull::new(base).expect("mmap 不会返回空") })
}
pub unsafe fn map_file(&self, k: usize, file: &File) -> io::Result<()> {
use std::os::fd::AsRawFd;
let at = self.window(k);
let p = unsafe { libc::mmap(at.cast(), WINDOW, libc::PROT_READ | libc::PROT_WRITE, libc::MAP_SHARED | libc::MAP_FIXED, file.as_raw_fd(), 0) };
if p == libc::MAP_FAILED { Err(io::Error::last_os_error()) } else { Ok(()) }
}
pub unsafe fn map_anonymous(&self, k: usize) -> io::Result<()> {
let at = self.window(k);
let p = unsafe { libc::mmap(at.cast(), WINDOW, libc::PROT_READ | libc::PROT_WRITE, libc::MAP_SHARED | libc::MAP_ANONYMOUS | libc::MAP_FIXED | libc::MAP_NORESERVE, -1, 0) };
if p == libc::MAP_FAILED { Err(io::Error::last_os_error()) } else { Ok(()) }
}
pub unsafe fn unmap(&self, k: usize) {
let at = self.window(k);
unsafe { libc::mmap(at.cast(), WINDOW, libc::PROT_NONE, libc::MAP_PRIVATE | libc::MAP_ANONYMOUS | libc::MAP_FIXED | libc::MAP_NORESERVE, -1, 0) };
}
pub fn commit(file: &File, offset: usize, len: usize) -> io::Result<()> {
use std::os::fd::AsRawFd;
let (offset, len) = (i64::try_from(offset).expect("窗口内偏移"), i64::try_from(len).expect("窗口内长度"));
if unsafe { libc::fallocate(file.as_raw_fd(), 0, offset, len) } == 0 { Ok(()) } else { Err(io::Error::last_os_error()) }
}
}
#[cfg(not(miri))]
impl Drop for Region {
fn drop(&mut self) {
unsafe { libc::munmap(self.base.as_ptr().cast(), REGION) };
}
}
#[cfg(miri)]
impl Region {
const LAYOUT: std::alloc::Layout = match std::alloc::Layout::from_size_align(REGION, REGION) {
Ok(l) => l,
Err(_) => panic!("区的大小 / 对齐不合法"),
};
pub fn reserve() -> io::Result<Self> {
let p = unsafe { std::alloc::alloc_zeroed(Self::LAYOUT) };
Ok(Self { base: NonNull::new(p).unwrap_or_else(|| std::alloc::handle_alloc_error(Self::LAYOUT)) })
}
pub unsafe fn map_file(&self, _: usize, _: &File) -> io::Result<()> {
Err(io::Error::from(io::ErrorKind::Unsupported))
}
pub unsafe fn map_anonymous(&self, _: usize) -> io::Result<()> {
Ok(())
}
pub unsafe fn unmap(&self, k: usize) {
unsafe { self.window(k).write_bytes(0, WINDOW) };
}
pub fn commit(_: &File, _: usize, _: usize) -> io::Result<()> {
Ok(())
}
}
#[cfg(miri)]
impl Drop for Region {
fn drop(&mut self) {
unsafe { std::alloc::dealloc(self.base.as_ptr(), Self::LAYOUT) };
}
}
#[derive(Clone, Copy, PartialEq, Eq)]
pub struct Process {
pub pid: u32,
pub start: u64,
}
const STATE_FIELD: usize = 0;
const START_FIELD: usize = 19;
impl Process {
pub fn current() -> Self {
let pid = std::process::id();
Self { pid, start: Self::stat(pid).map_or(0, |(_, start)| start) }
}
#[cfg(not(miri))]
fn stat(pid: u32) -> Option<(char, u64)> {
let text = std::fs::read_to_string(format!("/proc/{pid}/stat")).ok()?;
let rest = &text[text.rfind(')')? + 1..];
let fields: Vec<&str> = rest.split_whitespace().collect();
Some((fields.get(STATE_FIELD)?.chars().next()?, fields.get(START_FIELD)?.parse().ok()?))
}
#[cfg(miri)]
fn stat(_: u32) -> Option<(char, u64)> {
None
}
pub fn alive(self) -> bool {
if self.start == 0 || cfg!(miri) {
return true;
}
Self::stat(self.pid).is_some_and(|(state, start)| start == self.start && !matches!(state, 'Z' | 'X'))
}
}
const MARKER_PREFIX: &str = ".paragc-";
#[derive(Clone, Copy, PartialEq, Eq, Debug)]
pub enum Liveness {
Alive,
Dead,
Gone,
Unknown,
}
pub struct FileHeader {
pub heap: usize,
pub incarnation: u64,
dead: bool,
persist: bool,
owner: Process,
}
impl FileHeader {
pub fn read(file: &File) -> io::Result<Self> {
let mut buf = [0u8; size_of::<Super>()];
file.read_exact_at(&mut buf, 0)?;
let u64_at = |o: usize| u64::from_le_bytes(buf[o..o + size_of::<u64>()].try_into().expect("8 字节"));
let u32_at = |o: usize| u32::from_le_bytes(buf[o..o + size_of::<u32>()].try_into().expect("4 字节"));
if u64_at(offset_of!(Super, magic)) != MAGIC || u64_at(offset_of!(Super, window)) != WINDOW as u64 {
return Err(io::Error::new(io::ErrorKind::InvalidData, "不是 paragc 公开堆,或布局版本不同"));
}
let heap = usize::try_from(u64_at(offset_of!(Super, heap))).ok().filter(|&k| k < WINDOWS).ok_or_else(|| io::Error::new(io::ErrorKind::InvalidData, "堆号超出窗口数"))?;
Ok(Self {
heap,
incarnation: u64_at(offset_of!(Super, incarnation)),
dead: u32_at(offset_of!(Super, dead)) != 0,
persist: u32_at(offset_of!(Super, persist)) != 0,
owner: Process { pid: u32_at(offset_of!(Super, owner_pid)), start: u64_at(offset_of!(Super, owner_start)) },
})
}
pub fn is_dead(&self) -> bool {
self.dead || (!self.persist && !self.owner.alive())
}
}
struct Marker {
creator: Option<Process>,
name: Vec<u8>,
}
impl Marker {
fn parse(text: &[u8]) -> Option<Self> {
let split = text.iter().position(|&b| b == b'\n')?;
let mut words = std::str::from_utf8(&text[..split]).ok()?.split_whitespace().map(str::parse::<u64>);
let creator = match (words.next(), words.next()) {
(Some(Ok(pid)), Some(Ok(start))) => u32::try_from(pid).ok().map(|pid| Process { pid, start }),
_ => None,
};
Some(Self { creator, name: text[split + 1..].to_vec() })
}
}
pub struct Registry<'d> {
dir: &'d Path,
}
impl<'d> Registry<'d> {
pub fn of(path: &'d Path) -> Self {
Self { dir: path.parent().filter(|d| !d.as_os_str().is_empty()).unwrap_or(Path::new(".")) }
}
pub fn dir(&self) -> &Path {
self.dir
}
pub fn marker(&self, k: usize) -> PathBuf {
self.dir.join(format!("{MARKER_PREFIX}{k}"))
}
fn lock(&self, k: usize, create: bool) -> io::Result<File> {
use std::os::fd::AsRawFd;
let path = self.marker(k);
loop {
let f = OpenOptions::new().read(true).write(true).create(create).truncate(false).mode(0o600).open(&path)?;
if unsafe { libc::flock(f.as_raw_fd(), libc::LOCK_EX) } != 0 {
return Err(io::Error::last_os_error());
}
match std::fs::metadata(&path) {
Ok(m) if m.ino() == f.metadata()?.ino() && m.dev() == f.metadata()?.dev() => return Ok(f),
Ok(_) => {}
Err(e) if e.kind() == io::ErrorKind::NotFound => {}
Err(e) => return Err(e),
}
}
}
fn read_locked(f: &mut File) -> io::Result<Vec<u8>> {
let mut text = Vec::new();
f.rewind()?;
f.read_to_end(&mut text)?;
Ok(text)
}
pub fn claim(&self, k: usize, name: &OsStr) -> io::Result<bool> {
let mut f = self.lock(k, true)?;
let text = Self::read_locked(&mut f)?;
if let Some(marker) = Marker::parse(&text)
&& self.judge(k, &marker, None) != Liveness::Dead
{
return Ok(false);
}
f.set_len(0)?;
f.rewind()?;
let me = Process::current();
f.write_all(format!("{} {}\n", me.pid, me.start).as_bytes())?;
f.write_all(name.as_encoded_bytes())?;
Ok(true)
}
fn judge(&self, k: usize, marker: &Marker, expect: Option<u64>) -> Liveness {
let gone = if expect.is_some() { Liveness::Gone } else { Liveness::Dead };
let creator_alive = marker.creator.is_some_and(Process::alive);
match File::open(self.dir.join(OsStr::from_bytes(&marker.name))).and_then(|f| FileHeader::read(&f)) {
Ok(header) if header.heap == k => {
if expect.is_some_and(|inc| inc != header.incarnation) {
Liveness::Gone
} else if header.is_dead() {
Liveness::Dead
} else {
Liveness::Alive
}
}
Ok(_) => {
if creator_alive {
Liveness::Alive
} else {
gone
}
}
Err(e) if matches!(e.kind(), io::ErrorKind::NotFound | io::ErrorKind::InvalidData | io::ErrorKind::UnexpectedEof) => {
if creator_alive {
Liveness::Alive
} else {
gone
}
}
Err(_) => Liveness::Unknown,
}
}
pub fn liveness(&self, k: usize, expect: Option<u64>) -> Liveness {
let text = match std::fs::read(self.marker(k)) {
Ok(t) => t,
Err(e) if e.kind() == io::ErrorKind::NotFound => return if expect.is_some() { Liveness::Gone } else { Liveness::Dead },
Err(_) => return Liveness::Unknown,
};
let Some(marker) = Marker::parse(&text) else {
return if text.is_empty() && expect.is_some() { Liveness::Gone } else { Liveness::Unknown };
};
let verdict = self.judge(k, &marker, expect);
if verdict == Liveness::Dead {
let path = self.dir.join(OsStr::from_bytes(&marker.name));
if let Ok(header) = File::open(&path).and_then(|f| FileHeader::read(&f)) {
self.bury(&path, k, header.incarnation);
}
}
verdict
}
pub fn bury(&self, path: &Path, k: usize, incarnation: u64) {
let Ok(mut f) = self.lock(k, false) else { return };
let Ok(text) = Self::read_locked(&mut f) else { return };
let names_it = Marker::parse(&text).is_some_and(|m| self.dir.join(OsStr::from_bytes(&m.name)) == path);
let same = File::open(path).and_then(|h| FileHeader::read(&h)).is_ok_and(|h| h.incarnation == incarnation);
if names_it && same {
let _ = std::fs::remove_file(path);
let _ = std::fs::remove_file(self.marker(k));
}
}
pub fn abandon(&self, k: usize, name: &OsStr) {
let Ok(mut f) = self.lock(k, false) else { return };
let Ok(text) = Self::read_locked(&mut f) else { return };
if Marker::parse(&text).is_some_and(|m| m.name == name.as_encoded_bytes() && m.creator == Some(Process::current())) {
let _ = std::fs::remove_file(self.marker(k));
}
}
}
const _: () = assert!(WINDOWS <= u64::BITS as usize, "窗口占用位图是一个 u64");
pub struct Space {
region: Region,
used: AtomicU64,
}
impl Space {
pub fn region(&self) -> &Region {
&self.region
}
fn claim(&self, k: usize) -> bool {
self.used.fetch_or(1 << k, Ordering::AcqRel) & (1 << k) == 0
}
fn claim_any(&self) -> Option<usize> {
(0..WINDOWS).find(|&k| self.claim(k))
}
pub fn release(&self, k: usize) {
self.used.fetch_and(!(1 << k), Ordering::AcqRel);
}
}
#[derive(Clone)]
pub struct PublicSpace(Arc<Space>);
impl PublicSpace {
pub fn reserve() -> io::Result<Self> {
Ok(Self(Arc::new(Space { region: Region::reserve()?, used: AtomicU64::new(0) })))
}
pub fn create(&self, path: impl AsRef<Path>, threads: NonZeroUsize) -> io::Result<PublicHeap> {
use std::os::unix::fs::OpenOptionsExt;
let path = path.as_ref();
let k = self.claim_number(path)?;
let abandon = || {
if let Some(name) = path.file_name() {
Registry::of(path).abandon(k, name);
}
};
let file = match OpenOptions::new().read(true).write(true).create_new(true).mode(0o600).open(path) {
Ok(f) => f,
Err(e) => {
abandon();
self.0.release(k);
return Err(e);
}
};
let backing = Backing::File { file, path: path.to_path_buf(), owner: true };
self.attach(k, backing, threads, true).inspect_err(|_| {
let _ = std::fs::remove_file(path);
abandon();
})
}
fn claim_number(&self, path: &Path) -> io::Result<usize> {
let registry = Registry::of(path);
let name = path.file_name().ok_or_else(|| io::Error::new(io::ErrorKind::InvalidInput, "堆文件路径没有文件名"))?;
for k in 0..WINDOWS {
if !self.0.claim(k) {
continue;
}
match registry.claim(k, name) {
Ok(true) => return Ok(k),
Ok(false) => self.0.release(k),
Err(e) => {
self.0.release(k);
return Err(e);
}
}
}
Err(io::Error::new(io::ErrorKind::OutOfMemory, "公开堆号用完了(这个目录里的标记或本地址区的窗口)"))
}
pub fn create_anonymous(&self, threads: NonZeroUsize) -> io::Result<PublicHeap> {
let k = self.0.claim_any().ok_or_else(|| io::Error::new(io::ErrorKind::OutOfMemory, "公开地址区的窗口用完了"))?;
self.attach(k, Backing::Anonymous, threads, true)
}
pub fn open(&self, path: impl AsRef<Path>, threads: NonZeroUsize) -> io::Result<PublicHeap> {
let path = path.as_ref();
let file = OpenOptions::new().read(true).write(true).open(path)?;
let header = FileHeader::read(&file)?;
if header.is_dead() {
Registry::of(path).bury(path, header.heap, header.incarnation);
return Err(io::Error::new(io::ErrorKind::NotFound, "这个公开堆已经死了(主人不在了)"));
}
let k = header.heap;
if !self.0.claim(k) {
return Err(io::Error::new(io::ErrorKind::AddrInUse, "这个公开堆的窗口在本地址区已被占用"));
}
self.attach(k, Backing::File { file, path: path.to_path_buf(), owner: false }, threads, false)
}
fn attach(&self, k: usize, backing: Backing, threads: NonZeroUsize, fresh: bool) -> io::Result<PublicHeap> {
let mapped = unsafe {
match &backing {
Backing::File { file, .. } => self.0.region.map_file(k, file),
Backing::Anonymous => self.0.region.map_anonymous(k),
}
};
if let Err(e) = mapped {
self.0.release(k);
return Err(e);
}
Inner::new(self.0.clone(), k, backing, threads, fresh).map(PublicHeap::from)
}
}