Merge pull request #44 from tobi/mount-dedup-fix

Fix repeated mount accounting and external SSD deletion guards
This commit is contained in:
Tobias Lütke
2026-09-26 22:04:35 -04:00
committed by GitHub
4 changed files with 613 additions and 25 deletions
+266 -24
View File
@@ -113,9 +113,10 @@ pub fn plan(targets: &[Target], root: &Path) -> Plan {
for target in targets {
let path = normalize(&target.path);
let reason =
refuse(&path, &root, home.as_ref(), &mounts).or_else(|| {
linked(&path, &root, real_root.as_deref(), home.as_ref())
});
refuse(&path, &root, home.as_ref(), &mounts.points, &mounts.media)
.or_else(|| {
linked(&path, &root, real_root.as_deref(), home.as_ref())
});
if let Some(reason) = reason {
plan.blocked.push(Blocked {
path: target.path.clone(),
@@ -364,6 +365,7 @@ fn refuse(
root: &Path,
home: Option<&Home>,
mounts: &[PathBuf],
media: &[PathBuf],
) -> Option<String> {
let key = guard_key(path);
let root_key = guard_key(root);
@@ -414,7 +416,11 @@ fn refuse(
if !key.starts_with(&root_key) && !path.starts_with(root) {
return Some("outside the scanned root".into());
}
if let Some(system) = system_tree(&key, home_key) {
if let Some(system) = system_tree(&key, home_key)
&& !(system == "/run"
&& on_media(&key, mounts, media)
&& fs::canonicalize(path).is_ok_and(|real| real == path))
{
return Some(format!(
"part of the system under {system}: {SYSTEM_TOOLS}"
));
@@ -424,7 +430,7 @@ fn refuse(
"it contains {system}, which is part of the system"
));
}
if is_mount_point(path) {
if mounts.contains(&key) || is_mount_point(path) {
return Some(
"a mount point: removing it would cross onto another filesystem"
.into(),
@@ -533,10 +539,81 @@ const fn identity(_path: &Path, _follow: bool) -> Option<(u64, u64)> {
/// mount boundary whatever the table said.
const MOUNTS_FRESH: std::time::Duration = std::time::Duration::from_secs(2);
/// Paths and safe media exceptions must come from the same snapshot.
#[derive(Default)]
struct MountTable {
points: Vec<PathBuf>,
media: Vec<PathBuf>,
}
fn read_mount_table() -> MountTable {
if let Ok(table) = fs::read_to_string("/proc/self/mountinfo") {
let views = crate::space::parse_mountinfo(&table);
return MountTable {
points: views.iter().map(|mount| guard_key(&mount.point)).collect(),
media: media_roots(&views),
};
}
MountTable {
points: read_mount_points(),
media: Vec::new(),
}
}
/// Only real disks mounted by the desktop under /run/media qualify. A
/// directory with that spelling, a bind of a system tree, and virtual
/// filesystems retain the /run guard. Missing information fails closed.
fn media_roots(mounts: &[crate::space::MountView]) -> Vec<PathBuf> {
mounts
.iter()
.filter(|mount| {
mount.point.starts_with("/run/media")
&& mount.point != Path::new("/run/media")
// An overmounted disk can remain in mountinfo. Ambiguous
// stacked views must never grant a deletion exception.
&& mounts.iter().filter(|other| other.point == mount.point).count() == 1
&& mount.fs_root == Path::new("/")
&& mount.source.starts_with("/dev/")
&& matches!(
mount.fstype.as_str(),
"ext2"
| "ext3"
| "ext4"
| "btrfs"
| "xfs"
| "f2fs"
| "vfat"
| "exfat"
| "ntfs"
| "ntfs3"
| "fuseblk"
| "fuse.ntfs-3g"
)
&& !mounts.iter().any(|other| {
!other.point.starts_with("/run/media")
&& (other.point == Path::new("/")
|| system_tree(&other.point, None).is_some())
&& (other.device == mount.device
|| other.source == mount.source)
})
})
.map(|mount| mount.point.clone())
.collect()
}
fn on_media(key: &Path, mounts: &[PathBuf], media: &[PathBuf]) -> bool {
// Nested mounts do not inherit their parent's exception.
mounts
.iter()
.filter(|point| key.starts_with(point))
.max_by_key(|point| point.components().count())
.is_some_and(|point| key != point && media.contains(point))
}
/// The last read of the mount table, and whether a read is under way.
struct MountCache {
read: Option<std::time::Instant>,
mounts: Option<Arc<Vec<PathBuf>>>,
mounts: Option<Arc<MountTable>>,
refreshing: bool,
}
@@ -554,7 +631,7 @@ static MOUNTS: std::sync::Mutex<MountCache> =
/// its own thread and is used meanwhile; before the first read lands it is
/// empty, which is why the app primes it at start with
/// [`prime_mount_points`].
fn mount_points() -> Arc<Vec<PathBuf>> {
fn mount_points() -> Arc<MountTable> {
let mut cache = MOUNTS
.lock()
.unwrap_or_else(std::sync::PoisonError::into_inner);
@@ -564,7 +641,7 @@ fn mount_points() -> Arc<Vec<PathBuf>> {
let spawned = thread::Builder::new()
.name("disktree-mounts".into())
.spawn(|| {
let mounts = Arc::new(read_mount_points());
let mounts = Arc::new(read_mount_table());
let mut cache = MOUNTS
.lock()
.unwrap_or_else(std::sync::PoisonError::into_inner);
@@ -919,7 +996,7 @@ fn run(
// The plan was judged against a mount table up to `MOUNTS_FRESH` old,
// or, right after start, not read yet. Judged again against a fresh
// read, here on the worker, before anything is touched.
let mounts = read_mount_points();
let mounts = read_mount_table();
// Links too: one put on the way down since the plan was made would lead
// the trash out of the root. Permanent removal on Unix refuses that by
// itself; see [`open_parent`].
@@ -930,14 +1007,30 @@ fn run(
if cancel.load(Ordering::Relaxed) {
break;
}
let reason = mounted(&target.path, &mounts).or_else(|| {
linked(
&target.path,
&plan.root,
real_root.as_deref(),
home.as_ref(),
)
});
// The /run/media exception must still hold when removal starts;
// a disk may have been unmounted since the review was displayed.
let reason = target
.path
.starts_with("/run/media")
.then(|| {
refuse(
&target.path,
&plan.root,
home.as_ref(),
&mounts.points,
&mounts.media,
)
})
.flatten()
.or_else(|| mounted(&target.path, &mounts.points))
.or_else(|| {
linked(
&target.path,
&plan.root,
real_root.as_deref(),
home.as_ref(),
)
});
let outcome = if let Some(reason) = reason {
Err(io::Error::other(reason))
} else {
@@ -1469,6 +1562,134 @@ mod tests {
temp
}
#[cfg(target_os = "linux")]
#[test]
fn desktop_media_exception_requires_an_independent_disk() {
let views = crate::space::parse_mountinfo(
"1 0 8:1 / / rw - ext4 /dev/root rw\n\
2 1 0:20 / /run rw - tmpfs tmpfs rw\n\
3 2 8:2 / /run/media/user/Games rw - ext4 /dev/sdb rw\n\
4 2 8:1 / /run/media/user/System rw - ext4 /dev/root rw\n\
5 2 8:2 /folder /run/media/user/Bind rw - ext4 /dev/sdb rw\n\
6 2 0:21 / /run/media/user/Virtual rw - tmpfs tmpfs rw\n\
7 3 8:1 /etc /run/media/user/Games/nested rw - ext4 /dev/root rw\n",
);
let media = media_roots(&views);
assert_eq!(media, [PathBuf::from("/run/media/user/Games")]);
let points: Vec<_> =
views.iter().map(|view| view.point.clone()).collect();
assert!(on_media(
Path::new("/run/media/user/Games/game"),
&points,
&media
));
for path in [
"/run/media/user/Games",
"/run/media/user/Games/nested/file",
"/run/media/user/System/etc",
"/run/media/user/Bind/file",
"/run/media/user/Virtual/file",
"/run/media/user/NotMounted/file",
"/run/user/1000/file",
] {
assert!(!on_media(Path::new(path), &points, &media), "{path}");
}
let mut stacked = views.clone();
let mut covering = views[3].clone();
covering.point = PathBuf::from("/run/media/user/Games");
stacked.push(covering);
assert!(media_roots(&stacked).is_empty(), "overmounted disk");
assert!(media_roots(&[]).is_empty());
}
/// Run in a private mount namespace with the fixture described in
/// scripts/test-linux-mounts.sh. Never changes the host's mount table.
#[cfg(target_os = "linux")]
#[test]
#[ignore = "requires the isolated mount fixture"]
fn mounted_media_and_repeated_views() {
let table =
fs::read_to_string("/proc/self/mountinfo").expect("mountinfo");
assert!(
crate::space::parse_mountinfo(&table)
.iter()
.any(|mount| mount.point == Path::new("/run")
&& mount.source == "disktree-test-run")
);
let root = Path::new("/run/media/disktree-test");
let mounts = read_mount_points();
// User namespaces cannot mount a block device. Supply the media
// classification separately; the table-policy test above covers it.
let media = vec![root.to_path_buf()];
let file = root.join("game");
fs::write(&file, b"game").expect("fixture");
assert_eq!(refuse(&file, root, None, &mounts, &media), None);
assert!(refuse(root, Path::new("/"), None, &mounts, &media).is_some());
assert!(refuse(&file, root, None, &mounts, &[]).is_some());
std::os::unix::fs::symlink("/etc", root.join("link")).expect("link");
assert!(
refuse(
&root.join("link/passwd"),
&root.join("link"),
None,
&mounts,
&media
)
.is_some()
);
fs::write(root.join("nested/keep"), b"keep").expect("nested");
assert!(
refuse(&root.join("nested/keep"), root, None, &mounts, &media)
.is_some()
);
remove_permanently(&file, root).expect("delete marked game");
assert!(!file.exists());
assert!(root.join("nested/keep").exists());
let scan_root = Path::new("/run/disktree-scan");
let options = crate::scan::ScanOptions {
apparent_size: true,
one_filesystem: false,
..crate::scan::ScanOptions::default()
};
let tree = crate::scan::scan(scan_root, options.clone()).expect("scan");
for name in ["one", "two", "original"] {
assert!(
tree.children.iter().any(|child| &*child.name == name),
"{name}"
);
}
assert!(!tree.children.iter().any(|child| &*child.name == "alias"));
assert_eq!(tree.files, 3);
assert_eq!(tree.bytes, 12);
assert!(
std::process::Command::new("mount")
.args([
"-t",
"tmpfs",
"tmpfs",
"/run/disktree-scan/alias/nested"
])
.status()
.expect("nested mount")
.success()
);
fs::write(scan_root.join("alias/nested/unique"), b"unique")
.expect("unique");
let tree = crate::scan::scan(scan_root, options).expect("rescan");
let alias = tree
.children
.iter()
.find(|child| &*child.name == "alias")
.expect("alias retained");
assert!(
alias
.children
.iter()
.any(|child| &*child.name == "nested" && child.files == 1)
);
}
#[test]
fn a_plan_keeps_only_the_outermost_targets() {
let temp = tree();
@@ -1515,13 +1736,19 @@ mod tests {
fn the_directories_above_home_are_refused() {
let home = Home::of(Path::new("/home/disktree-test-user"));
let reason =
refuse(Path::new("/home"), Path::new("/"), Some(&home), &[]);
refuse(Path::new("/home"), Path::new("/"), Some(&home), &[], &[]);
assert!(
reason.is_some_and(|reason| reason.contains("home directory")),
"the home directory is inside it"
);
assert_eq!(
refuse(Path::new("/home/other"), Path::new("/"), Some(&home), &[]),
refuse(
Path::new("/home/other"),
Path::new("/"),
Some(&home),
&[],
&[]
),
None,
"a sibling of home is not above it"
);
@@ -1579,6 +1806,7 @@ mod tests {
Path::new("/"),
Some(&Home::of(home)),
&[],
&[],
)
.expect("refused");
assert!(reason.contains("home directory"), "{reason}");
@@ -1587,6 +1815,7 @@ mod tests {
Path::new("/Users/tobi/src"),
Path::new("/"),
Some(&Home::of(home)),
&[],
&[]
)
.is_none(),
@@ -1605,6 +1834,7 @@ mod tests {
Path::new("/"),
Some(&Home::of(home)),
&[],
&[],
)
.expect("refused");
assert!(reason.contains(inside), "{path}: {reason}");
@@ -1614,6 +1844,7 @@ mod tests {
Path::new("/opt/local"),
Path::new("/"),
Some(&Home::of(home)),
&[],
&[]
)
.is_none(),
@@ -1637,9 +1868,12 @@ mod tests {
"itself"
);
let reason =
refuse(&root.join("a"), root, None, &mounts).expect("refused");
refuse(&root.join("a"), root, None, &mounts, &[]).expect("refused");
assert!(reason.contains("mounted inside"), "{reason}");
assert_eq!(refuse(&root.join("a/one.bin"), root, None, &mounts), None);
assert_eq!(
refuse(&root.join("a/one.bin"), root, None, &mounts, &[]),
None
);
}
#[test]
@@ -1671,13 +1905,17 @@ mod tests {
// The first read lands on its own thread; wait for it, briefly.
let mut mounts = mount_points();
for _ in 0..500 {
if !mounts.is_empty() {
if !mounts.points.is_empty() {
break;
}
thread::sleep(std::time::Duration::from_millis(10));
mounts = mount_points();
}
assert_eq!(*mounts, read_mount_points(), "the same table, cached");
assert_eq!(
mounts.points,
read_mount_table().points,
"the same table, cached"
);
}
#[test]
@@ -1743,6 +1981,7 @@ mod tests {
&data.join("Users/tobi/src"),
data,
Some(&Home::of(home)),
&[],
&[]
)
.is_none(),
@@ -1753,6 +1992,7 @@ mod tests {
Path::new("/"),
Some(&Home::of(home)),
&[],
&[],
)
.expect("refused");
assert!(reason.contains("/Library"), "{reason}");
@@ -2190,6 +2430,7 @@ mod tests {
&drive,
Some(&Home::of(&home)),
&[],
&[],
);
assert!(
reason.is_some_and(|reason| reason
@@ -2220,7 +2461,7 @@ mod tests {
let public = crate::windows::user_profiles_dir()
.expect("profiles folder")
.join("Public");
let reason = refuse(&public, &system_drive(), None, &[]);
let reason = refuse(&public, &system_drive(), None, &[], &[]);
assert!(reason.is_some_and(|reason| reason.contains("profile")));
}
@@ -2299,6 +2540,7 @@ mod tests {
Path::new("/"),
Some(&Home::of(home)),
&[],
&[],
);
assert!(reason.is_some_and(|reason| reason.contains("/etc")));
}
+10 -1
View File
@@ -752,7 +752,16 @@ fn scan_blocking(root: &Path, context: &Arc<WalkContext>) -> io::Result<Node> {
}
let resolved = root.canonicalize().ok();
let canonical = resolved.as_deref().unwrap_or(root);
let never = crate::space::never_scanned(root, canonical);
let mut never = crate::space::never_scanned(root, canonical);
// Hidden-entry and depth filters can leave an alias as the only route
// to files. Keep every mount view when either filter is active.
if context.options.include_hidden && context.options.max_depth.is_none() {
never.extend(crate::space::repeated_mounts_for(
root,
canonical,
context.options.one_filesystem,
));
}
let _ = context.never_scanned.set(never.into_iter().collect());
if context.options.one_filesystem {
*lock(&context.root_device) = Some(device_of(&root_meta));
+319
View File
@@ -222,6 +222,200 @@ pub fn foreign_mounts_for(root: &Path) -> Option<Vec<PathBuf>> {
Some(foreign_mounts(&parse_mounts(&table), root))
}
/// One line of `/proc/self/mountinfo`.
///
/// What [`Mount`] says, plus which directory of the filesystem the mount
/// shows. `/proc/self/mounts` leaves that out, and it is what tells a bind
/// mount from the filesystem itself.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct MountView {
/// Kernel filesystem identity; source names such as `tmpfs` repeat.
pub device: String,
pub source: String,
pub fstype: String,
pub point: PathBuf,
/// The directory inside the filesystem that appears at `point`: `/` for
/// a whole filesystem, `/@home` for a Btrfs subvolume, the bound
/// directory for a bind mount.
pub fs_root: PathBuf,
}
/// Parse `/proc/self/mountinfo`. Lines it cannot read are skipped.
pub fn parse_mountinfo(table: &str) -> Vec<MountView> {
table
.lines()
.filter_map(|line| {
// Optional fields run up to a lone `-`; after it come the type
// and the source.
let (left, right) = line.split_once(" - ")?;
let mut left = left.split_whitespace().skip(2);
let device = left.next()?.to_string();
let fs_root = PathBuf::from(unescape_octal(left.next()?));
let point = PathBuf::from(unescape_octal(left.next()?));
let mut right = right.split_whitespace();
let fstype = right.next()?.to_string();
let source = unescape_octal(right.next()?);
Some(MountView {
device,
source,
fstype,
point,
fs_root,
})
})
.collect()
}
/// The kernel writes space, tab, newline and backslash in mount fields as
/// three octal digits after a backslash. Decoded in one pass, so a name that
/// really contains `\040` is not decoded twice.
fn unescape_octal(field: &str) -> String {
let bytes = field.as_bytes();
let mut out = Vec::with_capacity(bytes.len());
let mut index = 0;
while index < bytes.len() {
let digits = bytes.get(index + 1..index + 4);
let value = digits
.filter(|_| bytes[index] == b'\\')
.and_then(|digits| std::str::from_utf8(digits).ok())
.and_then(|digits| u8::from_str_radix(digits, 8).ok());
if let Some(value) = value {
out.push(value);
index += 4;
} else {
out.push(bytes[index]);
index += 1;
}
}
String::from_utf8_lossy(&out).into_owned()
}
/// Paths under `root` that show a directory the scan already reaches
/// another way, so walking them would count the same files twice.
///
/// A bind mount, a second mount of the same disk, or the top of a Btrfs
/// filesystem mounted beside its subvolumes all show one directory at two
/// paths. Device numbers cannot tell: a bind mount has its original's. The
/// mount table can, since each line names the filesystem and the directory
/// of it that is shown. When one directory is visible twice, the view
/// showing the widest part of the filesystem is kept, and the narrower one
/// is left out. The scanned root itself is never left out; if it is the
/// narrower view, its copy inside the wider one is.
pub fn repeated_mounts(mounts: &[MountView], root: &Path) -> Vec<PathBuf> {
repeated_mounts_excluding(mounts, root, &[])
}
fn same_filesystem(left: &MountView, right: &MountView) -> bool {
left.fstype == right.fstype
&& (left.device == right.device
// Btrfs assigns device numbers per subvolume. Its block device
// identifies the filesystem shared by those different roots.
|| (left.fstype == "btrfs"
&& left.source.starts_with("/dev/")
&& left.source == right.source))
}
fn covering_mount<'a>(
mounts: &'a [MountView],
path: &Path,
) -> Option<&'a MountView> {
mounts
.iter()
.filter(|mount| path.starts_with(&mount.point))
.max_by_key(|mount| mount.point.components().count())
}
fn repeated_mounts_excluding(
mounts: &[MountView],
root: &Path,
excluded: &[PathBuf],
) -> Vec<PathBuf> {
let own = covering_mount(mounts, root);
let mut visible: Vec<&MountView> = mounts
.iter()
.filter(|mount| {
(mount.point.starts_with(root) || Some(*mount) == own)
&& !excluded.iter().any(|skip| mount.point.starts_with(skip))
})
.collect();
visible.sort_by_key(|mount| {
(
mount.fs_root.components().count(),
mount.point.components().count(),
&mount.point,
)
});
let mut kept: Vec<&MountView> = Vec::new();
let mut repeated: Vec<PathBuf> = Vec::new();
for mount in visible {
let elsewhere = kept.iter().find_map(|wider| {
if !same_filesystem(wider, mount) {
return None;
}
let inside = mount.fs_root.strip_prefix(&wider.fs_root).ok()?;
let path = wider.point.join(inside);
if !path.starts_with(root)
|| path == mount.point
|| excluded
.iter()
.chain(&repeated)
.any(|skip| path.starts_with(skip))
{
return None;
}
// Another mount can hide the supposed original directory.
let covering = covering_mount(mounts, &path)?;
let relative = path.strip_prefix(&covering.point).ok()?;
(same_filesystem(covering, mount)
&& covering.fs_root.join(relative) == mount.fs_root)
.then_some(path)
});
let skip = elsewhere.map(|copy| {
if mount.point != root && mount.point.starts_with(root) {
mount.point.clone()
} else {
copy
}
});
if let Some(skip) = skip
&& !root.starts_with(&skip)
// A duplicate view can contain independently mounted data.
// Keep it rather than hiding that data with its parent.
&& !mounts.iter().any(|child| child.point != skip && child.point.starts_with(&skip))
{
if skip != mount.point {
kept.push(mount);
}
repeated.push(skip);
} else {
kept.push(mount);
}
}
repeated
}
/// [`repeated_mounts`] for this machine, in `root`'s own spelling. Empty
/// where there is no `/proc/self/mountinfo`.
pub fn repeated_mounts_for(
root: &Path,
canonical: &Path,
one_filesystem: bool,
) -> Vec<PathBuf> {
let Ok(table) = std::fs::read_to_string("/proc/self/mountinfo") else {
return Vec::new();
};
let excluded = if one_filesystem {
foreign_mounts_for(canonical).unwrap_or_default()
} else {
Vec::new()
};
repeated_mounts_excluding(&parse_mountinfo(&table), canonical, &excluded)
.iter()
.filter_map(|path| path.strip_prefix(canonical).ok())
.map(|below| root.join(below))
.collect()
}
/// The mount points in what macOS's `mount` prints.
///
/// One per line: `/dev/disk3s5 on /System/Volumes/Data (apfs, local, …)`.
@@ -511,6 +705,131 @@ tmpfs /tmp tmpfs rw 0 0
portal /run/user/1000/doc fuse.portal rw 0 0
";
const MOUNTINFO: &str = "\
22 1 0:21 /@ / rw,relatime - btrfs /dev/mapper/root rw,subvol=/@
23 22 0:21 /@home /home rw,relatime - btrfs /dev/mapper/root rw,subvol=/@home
24 22 0:21 /@log /var/log rw,relatime - btrfs /dev/mapper/root rw,subvol=/@log
25 22 0:21 /@snapshots /.snapshots rw - btrfs /dev/mapper/root rw
26 22 0:30 / /data rw,relatime shared:5 - btrfs /dev/mapper/data rw
27 22 0:30 / /mnt/data rw,relatime shared:5 - btrfs /dev/mapper/data rw
28 22 0:31 / /tmp rw - tmpfs tmpfs rw
29 22 259:3 / /boot rw - vfat /dev/nvme0n1p1 rw
";
fn repeated(table: &str, root: &str) -> Vec<PathBuf> {
let mut paths =
repeated_mounts(&parse_mountinfo(table), Path::new(root));
paths.sort();
paths
}
#[test]
fn subvolumes_are_not_repeats_but_a_second_mount_of_a_disk_is() {
assert_eq!(repeated(MOUNTINFO, "/"), [PathBuf::from("/mnt/data")]);
assert!(repeated(MOUNTINFO, "/home/tobi").is_empty());
assert!(repeated(MOUNTINFO, "/data").is_empty());
assert!(
repeated(MOUNTINFO, "/mnt/data").is_empty(),
"the view that was asked for is scanned"
);
}
#[test]
fn a_bind_mount_inside_the_scan_is_left_out() {
let table = format!(
"{MOUNTINFO}30 23 0:21 /@home/tobi/src /srv/src rw - btrfs /dev/mapper/root rw\n"
);
assert_eq!(
repeated(&table, "/"),
[PathBuf::from("/mnt/data"), PathBuf::from("/srv/src")]
);
// From home, the original is outside the scan: nothing repeats.
assert!(repeated(&table, "/home/tobi").is_empty());
assert!(repeated(&table, "/srv").is_empty());
}
#[test]
fn the_top_of_a_btrfs_disk_beside_its_subvolumes_is_counted_once() {
let table = format!(
"{MOUNTINFO}31 22 0:21 / /mnt/top rw - btrfs /dev/mapper/root rw\n"
);
// The root cannot be left out, so its copy under /mnt/top is; the
// other subvolumes are seen under /mnt/top instead of twice.
assert_eq!(
repeated(&table, "/"),
[
PathBuf::from("/.snapshots"),
PathBuf::from("/home"),
PathBuf::from("/mnt/data"),
PathBuf::from("/mnt/top/@"),
PathBuf::from("/var/log"),
]
);
}
#[test]
fn unrelated_tmpfs_mounts_are_not_duplicates() {
let table = "1 0 8:1 / / rw - ext4 /dev/root rw\n\
2 1 0:20 / /one rw - tmpfs tmpfs rw\n\
3 1 0:21 / /two rw - tmpfs tmpfs rw\n";
assert!(repeated(table, "/").is_empty());
let alias =
format!("{table}4 1 0:20 / /three rw - tmpfs different-name rw\n");
assert_eq!(repeated(&alias, "/"), [PathBuf::from("/three")]);
}
#[test]
fn hidden_original_and_nested_mounts_are_preserved() {
let hidden = "1 0 8:1 / / rw - ext4 /dev/root rw\n\
2 1 0:20 / /data rw - tmpfs tmpfs rw\n\
3 2 8:1 /data/source /data/bind rw - ext4 /dev/root rw\n";
assert!(repeated(hidden, "/").is_empty());
let nested = "1 0 8:1 / / rw - ext4 /dev/root rw\n\
2 1 8:1 /original /view rw - ext4 /dev/root rw\n\
3 2 0:20 / /view/unique rw - tmpfs tmpfs rw\n";
assert!(repeated(nested, "/").is_empty());
}
#[test]
fn excluded_views_cannot_replace_visible_files() {
let mounts = parse_mountinfo(
"1 0 8:1 / / rw - ext4 /dev/root rw\n\
2 1 8:1 /original /view rw - ext4 /dev/root rw\n",
);
assert!(
repeated_mounts_excluding(
&mounts,
Path::new("/"),
&[PathBuf::from("/original")]
)
.is_empty()
);
}
#[test]
fn btrfs_subvolume_devices_can_differ() {
let table = "1 0 0:20 /@ / rw - btrfs /dev/root rw\n\
2 1 0:21 /@home /home rw - btrfs /dev/root rw\n\
3 1 0:22 / /top rw - btrfs /dev/root rw\n";
assert_eq!(
repeated(table, "/"),
[PathBuf::from("/home"), PathBuf::from("/top/@")]
);
}
#[test]
fn mountinfo_escapes_are_decoded_once() {
let mounts = parse_mountinfo(
"not a mount line\n\
40 22 8:1 /a\\040b /media/My\\040Disk\\134040 rw - ext4 /dev/sda1 rw\n",
);
assert_eq!(mounts.len(), 1);
assert_eq!(mounts[0].fs_root, Path::new("/a b"));
assert_eq!(mounts[0].point, Path::new("/media/My Disk\\040"));
assert_eq!(mounts[0].source, "/dev/sda1");
assert_eq!(mounts[0].fstype, "ext4");
}
#[test]
fn volumes_with_least_space_come_first_and_unknowns_last() {
let volume = |name: &str, available: Option<u64>| Volume {
+18
View File
@@ -0,0 +1,18 @@
#!/bin/sh
# Pass the compiled disktree-core unit test binary as the first argument.
# All mounts and writes live in an isolated, temporary /run.
set -eu
exec unshare --user --map-root-user --mount sh -eu -c '
mount --make-rprivate /
mount -t tmpfs disktree-test-run /run
mkdir -p /run/media/disktree-test /run/disktree-scan
mount -t tmpfs tmpfs /run/media/disktree-test
mkdir /run/media/disktree-test/nested
mount -t tmpfs tmpfs /run/media/disktree-test/nested
for dir in original alias one two; do mkdir /run/disktree-scan/$dir; done
mkdir /run/disktree-scan/original/nested
mount --bind /run/disktree-scan/original /run/disktree-scan/alias
for dir in one two; do mount -t tmpfs tmpfs /run/disktree-scan/$dir; done
for dir in original one two; do printf data > /run/disktree-scan/$dir/file; done
"$1" --exact removal::tests::mounted_media_and_repeated_views --ignored --nocapture
' sh "$1"