The same lexer-based splitter as S12b, now with explicit re-exports: every moved free fn comes back to its module under its old name and old visibility (cfg attributes carried), so a name can never clash with another glob import. 162 module files of leleka-runtime (68), cuda-driver (84), deploy (10), cpu-sys, igpu and leleka-memory are split into groups of about 250 lines; types, constants, macros, nested modules and tests stay. Not touched: the files kar-off-ab edits, crate roots (lib.rs, main.rs, bin/*), and giant single impl blocks (next). This changes codegen-unit placement of engine code, so it is covered by the bitwise replay and the paired A/B on the 5090, not by a binary comparison.
593 lines
25 KiB
Rust
593 lines
25 KiB
Rust
//! The sealed KAR archive, made by the service itself (no helper process, no Python).
|
|
//!
|
|
//! `leleka run` copies the archive once into an irrevocably sealed `memfd` and keeps it for its whole life, so an
|
|
//! engine restart does not copy 55 GB again. The engine refuses anything but a regular, unlinked file of the
|
|
//! pinned length with `WRITE | GROW | SHRINK | SEAL` seals (`InheritedKarArchive::open`). The descriptor is
|
|
//! `CLOEXEC` in the supervisor and reaches only the engine: the supervisor hands a duplicate to `leleka
|
|
//! exec-inherit` as standard input, and that shim moves it to a descriptor number >= 3 without close-on-exec and
|
|
//! `exec`s the engine, which reopens it through `/proc/self/fd/N`.
|
|
#[cfg(target_os = "linux")]
|
|
pub use linux::*;
|
|
|
|
/// What `leleka seal-exec` was asked to do.
|
|
#[derive(Debug, PartialEq, Eq)]
|
|
pub struct SealExecPlan {
|
|
pub file: std::path::PathBuf,
|
|
pub expect_bytes: Option<u64>,
|
|
/// Copy only the extents the serve path reads (`memfd_extents: ple_only`, experimental).
|
|
pub sparse_ple: bool,
|
|
pub command: Vec<String>,
|
|
}
|
|
|
|
pub const PLACEHOLDER: &str = "{FD}";
|
|
|
|
#[cfg(target_os = "linux")]
|
|
mod linux {
|
|
use super::substitute;
|
|
use leleka_model_format::{kar::Extent, verify_stamp::FileIdentity};
|
|
use rustix::fs::{MemfdFlags, SealFlags, fcntl_add_seals, fcntl_get_seals, memfd_create};
|
|
use std::{
|
|
convert::Infallible,
|
|
fs::File,
|
|
os::{
|
|
fd::{AsFd, IntoRawFd},
|
|
unix::{fs::FileExt, process::CommandExt},
|
|
},
|
|
path::Path,
|
|
process::Command,
|
|
sync::{
|
|
Mutex,
|
|
atomic::{AtomicBool, AtomicU64, Ordering},
|
|
},
|
|
};
|
|
|
|
pub const SEALS: SealFlags = SealFlags::from_bits_truncate(
|
|
SealFlags::WRITE.bits()
|
|
| SealFlags::GROW.bits()
|
|
| SealFlags::SHRINK.bits()
|
|
| SealFlags::SEAL.bits(),
|
|
);
|
|
/// Block size the tests use to cover several blocks and a ragged tail.
|
|
#[cfg(test)]
|
|
const COPY_CHUNK: usize = 32 << 20;
|
|
|
|
/// Copy `path` into a new sealed, close-on-exec memfd. `expect_bytes` pins the exact length. `progress` gets
|
|
/// (copied, total) about every 4 GiB.
|
|
pub fn seal_file(
|
|
path: &Path,
|
|
expect_bytes: Option<u64>,
|
|
progress: &mut dyn FnMut(u64, u64),
|
|
) -> Result<File, String> {
|
|
seal_file_with_identity(path, expect_bytes, progress).map(|(file, _)| file)
|
|
}
|
|
|
|
/// As [`seal_file`], returning the identity of the source file when it is a stable one. The identity is taken from the
|
|
/// opened file before the first byte and again after the last; a source that changed while it was copied is
|
|
/// refused, so the identity describes exactly the bytes that are in the memfd.
|
|
pub fn seal_file_with_identity(
|
|
path: &Path,
|
|
expect_bytes: Option<u64>,
|
|
progress: &mut dyn FnMut(u64, u64),
|
|
) -> Result<(File, Option<FileIdentity>), String> {
|
|
seal_file_report(path, expect_bytes, progress).map(|(file, identity, _)| (file, identity))
|
|
}
|
|
|
|
/// As [`seal_file_with_identity`], also returning how the file was read (strategy, bytes, time) for the log.
|
|
pub fn seal_file_report(
|
|
path: &Path,
|
|
expect_bytes: Option<u64>,
|
|
progress: &mut dyn FnMut(u64, u64),
|
|
) -> Result<
|
|
(
|
|
File,
|
|
Option<FileIdentity>,
|
|
leleka_model_format::bulk_read::Report,
|
|
),
|
|
String,
|
|
> {
|
|
seal_ranges(path, expect_bytes, None, progress)
|
|
}
|
|
|
|
/// A **sparse** sealed memfd: the final length of the archive, but only `extents` are copied; every byte outside them is
|
|
/// a hole (no page is allocated, a read returns zeros). File offsets are identical to the archive's, so a reader needs no
|
|
/// change. The extents must be sorted, disjoint, page-aligned at the start and inside the archive. The memfd is sealed
|
|
/// like the full one, but it is NOT the archive: the engine verifies it against the pinned digest of the extents
|
|
/// (`VerifiedKarPleArtifact::verify_sparse`), never against the archive's SHA-256, and the identity returned here must not be
|
|
/// used to record a verification stamp of the archive.
|
|
pub fn seal_extents(
|
|
path: &Path,
|
|
expect_bytes: Option<u64>,
|
|
extents: &[Extent],
|
|
progress: &mut dyn FnMut(u64, u64),
|
|
) -> Result<(File, Option<FileIdentity>), String> {
|
|
seal_extents_report(path, expect_bytes, extents, progress)
|
|
.map(|(file, identity, _)| (file, identity))
|
|
}
|
|
|
|
/// As [`seal_extents`], also returning how the file was read.
|
|
pub fn seal_extents_report(
|
|
path: &Path,
|
|
expect_bytes: Option<u64>,
|
|
extents: &[Extent],
|
|
progress: &mut dyn FnMut(u64, u64),
|
|
) -> Result<
|
|
(
|
|
File,
|
|
Option<FileIdentity>,
|
|
leleka_model_format::bulk_read::Report,
|
|
),
|
|
String,
|
|
> {
|
|
seal_ranges(path, expect_bytes, Some(extents), progress)
|
|
}
|
|
|
|
fn check_extents(extents: &[Extent], total: u64) -> Result<(), String> {
|
|
let mut previous_end = 0;
|
|
for (i, e) in extents.iter().enumerate() {
|
|
if e.len == 0
|
|
|| e.offset % leleka_model_format::kar::EXTENT_ALIGN != 0
|
|
|| e.offset < previous_end
|
|
|| e.offset.checked_add(e.len).is_none_or(|end| end > total)
|
|
{
|
|
return Err(format!(
|
|
"extent {i} ({}+{}) is empty, unaligned, out of order or outside the {total}-byte archive",
|
|
e.offset, e.len
|
|
));
|
|
}
|
|
previous_end = e.end();
|
|
}
|
|
Ok(())
|
|
}
|
|
|
|
fn seal_ranges(
|
|
path: &Path,
|
|
expect_bytes: Option<u64>,
|
|
extents: Option<&[Extent]>,
|
|
progress: &mut dyn FnMut(u64, u64),
|
|
) -> Result<
|
|
(
|
|
File,
|
|
Option<FileIdentity>,
|
|
leleka_model_format::bulk_read::Report,
|
|
),
|
|
String,
|
|
> {
|
|
let source =
|
|
File::open(path).map_err(|e| format!("cannot open {}: {e}", path.display()))?;
|
|
let metadata = source
|
|
.metadata()
|
|
.map_err(|e| format!("cannot inspect the archive: {e}"))?;
|
|
if !metadata.is_file() {
|
|
return Err("the archive must be a regular file".into());
|
|
}
|
|
if let Some(expected) = expect_bytes
|
|
&& metadata.len() != expected
|
|
{
|
|
return Err(format!(
|
|
"the archive has {} bytes, expected {expected}",
|
|
metadata.len()
|
|
));
|
|
}
|
|
let identity_before = FileIdentity::of(&metadata);
|
|
let total = metadata.len();
|
|
let whole = [Extent::new(0, total)];
|
|
let ranges: &[Extent] = match extents {
|
|
Some(extents) => {
|
|
check_extents(extents, total)?;
|
|
extents
|
|
}
|
|
None => &whole,
|
|
};
|
|
let want: u64 = ranges.iter().map(|r| r.len).sum();
|
|
let fd = memfd_create(
|
|
"leleka-sealed-archive",
|
|
MemfdFlags::ALLOW_SEALING | MemfdFlags::CLOEXEC,
|
|
)
|
|
.map_err(|e| format!("memfd_create failed: {e}"))?;
|
|
let memory = File::from(fd);
|
|
let report: Mutex<Option<leleka_model_format::bulk_read::Report>> = Mutex::new(None);
|
|
// The final size first (before the GROW seal exists), so that workers write disjoint ranges.
|
|
memory
|
|
.set_len(total)
|
|
.map_err(|e| format!("cannot size the memfd (out of memory?): {e}"))?;
|
|
// Large blocks on many threads (O_DIRECT where the file system allows it): the device sees a deep queue
|
|
// instead of one 128 KiB readahead window at a time, and what is copied never enters the page cache, so the
|
|
// memfd is the only copy of it in RAM (a sparse copy reads each of its extents the same way and nothing else).
|
|
let plan = leleka_model_format::bulk_read::Plan::from_env();
|
|
let copied = AtomicU64::new(0);
|
|
let finished = AtomicBool::new(false);
|
|
let failure: Mutex<Option<String>> = Mutex::new(None);
|
|
std::thread::scope(|scope| {
|
|
scope.spawn(|| {
|
|
// Set on every exit, a panic included, so that the progress loop below ends.
|
|
struct Finished<'a>(&'a AtomicBool);
|
|
impl Drop for Finished<'_> {
|
|
fn drop(&mut self) {
|
|
self.0.store(true, Ordering::Release);
|
|
}
|
|
}
|
|
let _finished = Finished(&finished);
|
|
let mut strategy = None;
|
|
let mut elapsed = std::time::Duration::ZERO;
|
|
for range in ranges {
|
|
let outcome = leleka_model_format::bulk_read::for_each_chunk(
|
|
&source,
|
|
range.offset,
|
|
range.len,
|
|
plan,
|
|
|offset, data| {
|
|
memory.write_all_at(data, offset).map_err(|e| {
|
|
std::io::Error::other(format!(
|
|
"write to memfd failed (out of memory?): {e}"
|
|
))
|
|
})?;
|
|
copied.fetch_add(data.len() as u64, Ordering::Relaxed);
|
|
Ok(())
|
|
},
|
|
);
|
|
match outcome {
|
|
Ok(done) => {
|
|
strategy = Some(done.strategy);
|
|
elapsed += done.elapsed;
|
|
}
|
|
Err(e) => {
|
|
if let Ok(mut f) = failure.lock() {
|
|
f.get_or_insert(format!("read failed: {e}"));
|
|
}
|
|
return;
|
|
}
|
|
}
|
|
}
|
|
// No extents at all is a valid (empty) sparse copy: nothing was read.
|
|
let strategy = strategy.unwrap_or(leleka_model_format::bulk_read::Strategy::Plain);
|
|
if let Ok(mut slot) = report.lock() {
|
|
*slot = Some(leleka_model_format::bulk_read::Report {
|
|
strategy,
|
|
bytes: want,
|
|
elapsed,
|
|
});
|
|
}
|
|
});
|
|
let mut reported = 0u64;
|
|
while !finished.load(Ordering::Acquire) {
|
|
std::thread::sleep(std::time::Duration::from_millis(100));
|
|
let now = copied.load(Ordering::Relaxed);
|
|
if now - reported >= 4 << 30 {
|
|
reported = now;
|
|
progress(now, want);
|
|
}
|
|
}
|
|
});
|
|
if let Some(message) = failure.into_inner().ok().flatten() {
|
|
return Err(message);
|
|
}
|
|
if copied.load(Ordering::Relaxed) != want {
|
|
return Err("the archive changed while it was being copied".into());
|
|
}
|
|
let identity_after = source.metadata().ok().and_then(|m| FileIdentity::of(&m));
|
|
if identity_before != identity_after {
|
|
return Err("the archive changed while it was being copied".into());
|
|
}
|
|
fcntl_add_seals(&memory, SEALS).map_err(|e| format!("sealing failed: {e}"))?;
|
|
if !fcntl_get_seals(&memory)
|
|
.map_err(|e| format!("cannot read seals: {e}"))?
|
|
.contains(SEALS)
|
|
{
|
|
return Err("the kernel did not apply every seal".into());
|
|
}
|
|
progress(want, want);
|
|
let report = report
|
|
.into_inner()
|
|
.ok()
|
|
.flatten()
|
|
.ok_or("the archive copy did not report")?;
|
|
Ok((memory, identity_before, report))
|
|
}
|
|
|
|
/// A descriptor inherited from the parent (a holder, for example), reopened through `/proc/self/fd/N` as an
|
|
/// independent read-only description. The original number stays open and untouched.
|
|
pub fn open_inherited(fd: u32) -> Result<File, String> {
|
|
if !(3..=1_048_576).contains(&fd) {
|
|
return Err("an inherited descriptor must be 3 or higher".into());
|
|
}
|
|
File::open(format!("/proc/self/fd/{fd}"))
|
|
.map_err(|e| format!("descriptor {fd} is not open in this process: {e}"))
|
|
}
|
|
|
|
/// The descriptor the parent passed with `--kar-fd` must be what the engine will accept: a regular, unlinked
|
|
/// file of the pinned length with every seal. Checked here so that the mistake surfaces before an engine start.
|
|
pub fn check_inherited_archive(fd: u32, expect_bytes: u64) -> Result<(), String> {
|
|
use std::os::unix::fs::MetadataExt;
|
|
let file = open_inherited(fd)?;
|
|
let meta = file
|
|
.metadata()
|
|
.map_err(|e| format!("cannot inspect descriptor {fd}: {e}"))?;
|
|
if !meta.is_file() || meta.nlink() != 0 || meta.len() != expect_bytes {
|
|
return Err(format!(
|
|
"descriptor {fd} is not an unlinked regular file of {expect_bytes} bytes (it has {} bytes, {} links)",
|
|
meta.len(),
|
|
meta.nlink()
|
|
));
|
|
}
|
|
if !fcntl_get_seals(&file)
|
|
.map_err(|e| format!("cannot read the seals of descriptor {fd}: {e}"))?
|
|
.contains(SEALS)
|
|
{
|
|
return Err(format!(
|
|
"descriptor {fd} lacks the WRITE, GROW, SHRINK and SEAL seals"
|
|
));
|
|
}
|
|
Ok(())
|
|
}
|
|
|
|
/// `leleka exec-inherit -- COMMAND ARG...`: standard input is the sealed archive. Move it to a descriptor
|
|
/// number >= 3 (inheritable), give the command `/dev/null` as standard input, replace `{FD}` and `exec`.
|
|
pub fn exec_inherit(args: &[String]) -> Result<Infallible, String> {
|
|
let command = match args.split_first() {
|
|
Some((separator, rest)) if separator == "--" && !rest.is_empty() => rest,
|
|
_ => return Err(
|
|
"usage: leleka exec-inherit -- COMMAND ARG... ({FD} marks the sealed descriptor)"
|
|
.into(),
|
|
),
|
|
};
|
|
let stdin = std::io::stdin();
|
|
let moved = rustix::io::dup(stdin.as_fd())
|
|
.map_err(|e| format!("cannot duplicate standard input: {e}"))?;
|
|
let devnull = File::open("/dev/null").map_err(|e| format!("cannot open /dev/null: {e}"))?;
|
|
rustix::stdio::dup2_stdin(&devnull)
|
|
.map_err(|e| format!("cannot replace standard input: {e}"))?;
|
|
let number = moved.into_raw_fd();
|
|
if number < 3 {
|
|
return Err("the sealed descriptor landed on a standard stream".into());
|
|
}
|
|
let arguments = substitute(&command[1..], number);
|
|
let error = Command::new(&command[0]).args(arguments).exec();
|
|
Err(format!("cannot execute {:?}: {error}", command[0]))
|
|
}
|
|
|
|
/// `leleka seal-exec --file PATH [--expect-bytes N] [--sparse-ple] -- COMMAND ARG...`: copy the archive (or only the extents
|
|
/// the serve path reads) into a sealed memfd and replace this process with COMMAND, which inherits the descriptor (every `{FD}` in
|
|
/// its arguments is the number). The Rust form of `leleka-seal-exec`, with the sparse copy. Nothing is verified here: the engine
|
|
/// verifies the memfd it is given (the archive SHA-256, or with `--sparse-ple` the pinned digest of the extents).
|
|
pub fn seal_exec(args: &[String]) -> Result<Infallible, String> {
|
|
let plan = super::parse_seal_exec(args)?;
|
|
let started = std::time::Instant::now();
|
|
let mut progress = |done: u64, total: u64| {
|
|
eprintln!(
|
|
"leleka seal-exec: {:.1} of {:.1} GiB",
|
|
done as f64 / 1073741824.0,
|
|
total as f64 / 1073741824.0
|
|
);
|
|
};
|
|
let (memory, extents) = if plan.sparse_ple {
|
|
let expect = plan
|
|
.expect_bytes
|
|
.ok_or("--sparse-ple needs --expect-bytes (the pinned archive length)")?;
|
|
let extents = super::archive_serve_extents(&plan.file, expect)?;
|
|
let (memory, _) = seal_extents(&plan.file, Some(expect), &extents, &mut progress)?;
|
|
(memory, Some(extents))
|
|
} else {
|
|
(
|
|
seal_file(&plan.file, plan.expect_bytes, &mut progress)?,
|
|
None,
|
|
)
|
|
};
|
|
let moved = rustix::io::dup(memory.as_fd())
|
|
.map_err(|e| format!("cannot duplicate the sealed descriptor: {e}"))?;
|
|
let number = moved.into_raw_fd();
|
|
if number < 3 {
|
|
return Err("the sealed descriptor landed on a standard stream".into());
|
|
}
|
|
let length = memory.metadata().map(|m| m.len()).unwrap_or(0);
|
|
eprintln!(
|
|
"leleka seal-exec: sealed memfd fd={number} bytes={length}{} in {:.1}s",
|
|
extents.as_ref().map_or(String::new(), |e| format!(
|
|
" (SPARSE: {} extents, {:.3} GiB held, the rest is a hole)",
|
|
e.len(),
|
|
leleka_model_format::kar::extents_bytes(e) as f64 / 1073741824.0
|
|
)),
|
|
started.elapsed().as_secs_f64()
|
|
);
|
|
let arguments = substitute(&plan.command[1..], number);
|
|
let error = Command::new(&plan.command[0]).args(arguments).exec();
|
|
Err(format!("cannot execute {:?}: {error}", plan.command[0]))
|
|
}
|
|
|
|
#[cfg(test)]
|
|
mod tests {
|
|
use super::*;
|
|
use std::io::Write;
|
|
use std::os::unix::fs::MetadataExt;
|
|
|
|
#[test]
|
|
fn seal_is_exact_sealed_unlinked_and_cloexec() {
|
|
let path = std::env::temp_dir().join(format!("leleka-sealed-{}", std::process::id()));
|
|
let payload: Vec<u8> = (0..300_000u32).map(|n| (n % 251) as u8).collect();
|
|
std::fs::write(&path, &payload).unwrap();
|
|
let mut calls = Vec::new();
|
|
let mut sealed = seal_file(&path, Some(payload.len() as u64), &mut |a, b| {
|
|
calls.push((a, b))
|
|
})
|
|
.unwrap();
|
|
let meta = sealed.metadata().unwrap();
|
|
assert!(meta.is_file() && meta.nlink() == 0 && meta.len() == payload.len() as u64);
|
|
assert!(fcntl_get_seals(&sealed).unwrap().contains(SEALS));
|
|
assert!(sealed.write(b"x").is_err() && sealed.set_len(1).is_err());
|
|
assert!(
|
|
rustix::io::fcntl_getfd(&sealed)
|
|
.unwrap()
|
|
.contains(rustix::io::FdFlags::CLOEXEC)
|
|
);
|
|
assert_eq!(
|
|
calls.last(),
|
|
Some(&(payload.len() as u64, payload.len() as u64))
|
|
);
|
|
// A descriptor reopened through /proc keeps the properties the engine checks.
|
|
let number = std::os::fd::AsRawFd::as_raw_fd(&sealed) as u32;
|
|
let reopened = open_inherited(number).unwrap();
|
|
let meta = reopened.metadata().unwrap();
|
|
assert!(meta.nlink() == 0 && meta.len() == payload.len() as u64);
|
|
assert!(seal_file(&path, Some(1), &mut |_, _| {}).is_err());
|
|
assert!(open_inherited(1).is_err());
|
|
std::fs::remove_file(path).unwrap();
|
|
}
|
|
|
|
#[test]
|
|
fn parallel_fill_is_byte_exact_across_chunks_and_reports_the_source_identity() {
|
|
let path = std::env::temp_dir().join(format!("leleka-fill-{}", std::process::id()));
|
|
// Three full chunks and a ragged tail, with a pattern that differs per chunk.
|
|
let size = COPY_CHUNK * 3 + 4097;
|
|
let payload: Vec<u8> = (0..size)
|
|
.map(|n| ((n / 4096) as u8).wrapping_mul(31) ^ (n as u8))
|
|
.collect();
|
|
std::fs::write(&path, &payload).unwrap();
|
|
let (sealed, identity) =
|
|
seal_file_with_identity(&path, Some(size as u64), &mut |_, _| {}).unwrap();
|
|
let identity = identity.expect("a regular file has an identity");
|
|
assert_eq!(identity.size, size as u64);
|
|
let mut copy = vec![0u8; size];
|
|
sealed.read_exact_at(&mut copy, 0).unwrap();
|
|
assert!(
|
|
copy == payload,
|
|
"the memfd must equal the source byte for byte"
|
|
);
|
|
assert!(fcntl_get_seals(&sealed).unwrap().contains(SEALS));
|
|
std::fs::remove_file(path).unwrap();
|
|
}
|
|
|
|
fn blocks_bytes(f: &File) -> u64 {
|
|
f.metadata().unwrap().blocks() * 512
|
|
}
|
|
|
|
#[test]
|
|
fn a_sparse_seal_copies_only_the_extents_keeps_every_offset_and_leaves_holes() {
|
|
let path = std::env::temp_dir().join(format!("leleka-sparse-{}", std::process::id()));
|
|
// Two full chunks and a bit, so extents span and split across the 32 MiB pieces.
|
|
let size = COPY_CHUNK * 2 + 4096 * 5 + 77;
|
|
let payload: Vec<u8> = (0..size)
|
|
.map(|n| (((n / 4096) as u8).wrapping_mul(31) ^ (n as u8)) | 1)
|
|
.collect();
|
|
std::fs::write(&path, &payload).unwrap();
|
|
let extents = [
|
|
Extent::new(0, 8192),
|
|
Extent::new(COPY_CHUNK as u64 - 4096, 3 * 4096),
|
|
Extent::new(COPY_CHUNK as u64 * 2 + 4096 * 3, 4096 * 2 + 77),
|
|
];
|
|
let want: u64 = extents.iter().map(|e| e.len).sum();
|
|
let mut calls = Vec::new();
|
|
let (mut sealed, identity) =
|
|
seal_extents(&path, Some(size as u64), &extents, &mut |a, b| {
|
|
calls.push((a, b))
|
|
})
|
|
.unwrap();
|
|
assert!(identity.is_some());
|
|
assert_eq!(
|
|
calls.last(),
|
|
Some(&(want, want)),
|
|
"progress counts the extent bytes"
|
|
);
|
|
// the memfd has the archive's length and the archive's seals
|
|
let meta = sealed.metadata().unwrap();
|
|
assert!(meta.nlink() == 0 && meta.len() == size as u64);
|
|
assert!(fcntl_get_seals(&sealed).unwrap().contains(SEALS));
|
|
assert!(sealed.write(b"x").is_err() && sealed.set_len(1).is_err());
|
|
// only the extents were allocated: pages of data, no page for any hole
|
|
let pages = |e: &Extent| (e.end().div_ceil(4096) - e.offset / 4096) * 4096;
|
|
assert_eq!(
|
|
blocks_bytes(&sealed),
|
|
extents.iter().map(pages).sum::<u64>()
|
|
);
|
|
assert!(blocks_bytes(&sealed) < size as u64 / 4);
|
|
// extents hold the source's bytes at the same offsets; holes read as zeros
|
|
let mut copy = vec![0u8; size];
|
|
sealed.read_exact_at(&mut copy, 0).unwrap();
|
|
for (offset, byte) in copy.iter().enumerate() {
|
|
let inside = extents
|
|
.iter()
|
|
.any(|e| (offset as u64) >= e.offset && (offset as u64) < e.end());
|
|
assert_eq!(
|
|
*byte,
|
|
if inside { payload[offset] } else { 0 },
|
|
"offset {offset}"
|
|
);
|
|
}
|
|
// reading the holes did not allocate them either
|
|
assert_eq!(
|
|
blocks_bytes(&sealed),
|
|
extents.iter().map(pages).sum::<u64>()
|
|
);
|
|
std::fs::remove_file(path).unwrap();
|
|
}
|
|
|
|
#[test]
|
|
fn a_sparse_seal_refuses_extents_that_are_empty_unaligned_unsorted_or_outside_and_a_wrong_length()
|
|
{
|
|
let path =
|
|
std::env::temp_dir().join(format!("leleka-sparse-bad-{}", std::process::id()));
|
|
std::fs::write(&path, vec![7u8; 5 * 4096]).unwrap();
|
|
let size = Some(5 * 4096);
|
|
for bad in [
|
|
vec![Extent::new(0, 0)],
|
|
vec![Extent::new(1, 4096)],
|
|
vec![Extent::new(4096, 4096), Extent::new(0, 4096)],
|
|
vec![Extent::new(0, 8192), Extent::new(4096, 4096)],
|
|
vec![Extent::new(4 * 4096, 2 * 4096)],
|
|
vec![Extent::new(u64::MAX - 4095, 4096)],
|
|
] {
|
|
let e = seal_extents(&path, size, &bad, &mut |_, _| {})
|
|
.err()
|
|
.unwrap_or_else(|| panic!("{bad:?} accepted"));
|
|
assert!(e.contains("extent"), "{e}");
|
|
}
|
|
assert!(seal_extents(&path, Some(1), &[Extent::new(0, 4096)], &mut |_, _| {}).is_err());
|
|
// no extents at all is a valid (empty) sparse memfd, not the full copy
|
|
let (empty, _) = seal_extents(&path, size, &[], &mut |_, _| {}).unwrap();
|
|
assert_eq!(blocks_bytes(&empty), 0);
|
|
assert_eq!(empty.metadata().unwrap().len(), 5 * 4096);
|
|
std::fs::remove_file(path).unwrap();
|
|
}
|
|
|
|
#[test]
|
|
fn exec_inherit_needs_a_command() {
|
|
assert!(exec_inherit(&[]).is_err());
|
|
assert!(exec_inherit(&["--".into()]).is_err());
|
|
assert!(exec_inherit(&["cmd".into()]).is_err());
|
|
}
|
|
}
|
|
}
|
|
|
|
#[cfg(test)]
|
|
mod tests;
|
|
|
|
mod seal_file_fn;
|
|
#[allow(unused_imports)]
|
|
pub use seal_file_fn::archive_serve_extents;
|
|
#[cfg(not(target_os = "linux"))]
|
|
#[allow(unused_imports)]
|
|
pub use seal_file_fn::check_inherited_archive;
|
|
#[cfg(not(target_os = "linux"))]
|
|
#[allow(unused_imports)]
|
|
pub use seal_file_fn::exec_inherit;
|
|
#[cfg(not(target_os = "linux"))]
|
|
#[allow(unused_imports)]
|
|
pub use seal_file_fn::open_inherited;
|
|
#[allow(unused_imports)]
|
|
pub use seal_file_fn::parse_seal_exec;
|
|
#[cfg(not(target_os = "linux"))]
|
|
#[allow(unused_imports)]
|
|
pub use seal_file_fn::seal_exec;
|
|
#[cfg(not(target_os = "linux"))]
|
|
#[allow(unused_imports)]
|
|
pub use seal_file_fn::seal_extents_report;
|
|
#[cfg(not(target_os = "linux"))]
|
|
#[allow(unused_imports)]
|
|
pub use seal_file_fn::seal_file;
|
|
#[cfg(not(target_os = "linux"))]
|
|
#[allow(unused_imports)]
|
|
pub use seal_file_fn::seal_file_report;
|
|
#[cfg(not(target_os = "linux"))]
|
|
#[allow(unused_imports)]
|
|
pub use seal_file_fn::seal_file_with_identity;
|
|
#[allow(unused_imports)]
|
|
pub use seal_file_fn::substitute;
|