feat(scan): read the NTFS master file table when elevated

Elevated scans of a whole NTFS drive read the master file table in large parallel reads instead of walking directories; any failure falls back to the walk. The walk also allocates once per entry, tallies progress per directory and folds hardlink de-dup into the parallel aggregate pass.
This commit is contained in:
Shishir Pai
2026-09-26 16:54:16 -04:00
parent e4ed4a8eb8
commit 0b1725d40e
7 changed files with 2508 additions and 152 deletions
+7 -1
View File
@@ -22,7 +22,13 @@ rustix = { version = "1.1", features = ["fs"] }
# The Recycle Bin, through the shell's own file operation.
trash = { version = "5.2.9", default-features = false, features = ["coinit_apartmentthreaded"] }
winapi-util = "0.1.11"
windows-sys = { version = "0.61", features = ["Win32_Foundation", "Win32_Storage_FileSystem"] }
windows-sys = { version = "0.61", features = [
"Win32_Foundation",
"Win32_Storage_FileSystem",
"Win32_System_Com",
"Win32_UI_Shell",
"Win32_UI_WindowsAndMessaging",
] }
# The system trash, through NSFileManager: what Finder's Move to Trash does,
# without asking to control Finder. Only this backend is used; the crate's
+48
View File
@@ -5,7 +5,14 @@
//! with `EPERM`, silently. A disk tool that only counts those as errors
//! leaves the user guessing, so the app asks once whether access is granted
//! and, if not, says why folders were unreadable and where to fix it.
//!
//! On Windows the same question is whether disktree runs as an
//! administrator: only then can it read a whole drive from its file table,
//! several times faster than walking it and including folders a walk is
//! refused. Without, it walks.
use std::ffi::OsString;
use std::io;
use std::path::Path;
/// System Settings, opened at Privacy & Security › Full Disk Access.
@@ -33,6 +40,47 @@ pub fn full_disk_access(home: &Path) -> Option<bool> {
}
}
/// Whether this process runs as an administrator: `None` off Windows,
/// where nothing a scan does depends on it.
#[cfg(windows)]
pub fn administrator() -> Option<bool> {
Some(crate::windows::elevated())
}
/// Whether this process runs as an administrator: `None` off Windows,
/// where nothing a scan does depends on it.
#[cfg(not(windows))]
pub const fn administrator() -> Option<bool> {
None
}
/// Whether an administrator would read `root` from its file table: a
/// whole NTFS drive. Always `false` off Windows.
#[cfg(windows)]
pub fn file_table_readable(root: &Path) -> bool {
crate::windows::file_table_readable(root)
}
/// Whether an administrator would read `root` from its file table: a
/// whole NTFS drive. Always `false` off Windows.
#[cfg(not(windows))]
pub const fn file_table_readable(root: &Path) -> bool {
let _ = root;
false
}
/// Start this program again as an administrator, with `args`, through the
/// UAC prompt. An error if the prompt is declined, or off Windows.
pub fn restart_as_administrator(args: &[OsString]) -> io::Result<()> {
#[cfg(windows)]
return crate::windows::run_elevated(&std::env::current_exe()?, args);
#[cfg(not(windows))]
{
let _ = args;
Err(io::ErrorKind::Unsupported.into())
}
}
#[cfg(test)]
mod tests {
use super::*;
+2
View File
@@ -10,6 +10,8 @@ pub mod classify;
pub mod export;
pub mod filter;
pub mod insights;
#[cfg(windows)]
mod mft;
pub mod removal;
pub mod scan;
pub mod size;
File diff suppressed because it is too large Load Diff
+287 -109
View File
@@ -8,8 +8,8 @@
//! `+1` sentinel, so a directory is only built once its own scan *and* all of
//! its subdirectory tasks have finished,
//! * children are handed to the parent as finished `Node`s and sizes are
//! aggregated bottom-up in one serial pass, which is also where hardlinks are
//! de-duplicated.
//! aggregated bottom-up in one pass over the finished tree, which is also
//! where hardlinks are de-duplicated.
//!
//! What is added on top of dust's approach: live progress counters the UI can
//! poll without locking, and cooperative cancellation so a re-scan can abandon
@@ -22,13 +22,13 @@ use std::io;
use std::path::{Path, PathBuf};
use std::sync::atomic::{AtomicBool, AtomicU64, AtomicUsize, Ordering};
use std::sync::mpsc::{self, Receiver, TryRecvError};
use std::sync::{Arc, Mutex, MutexGuard, OnceLock, PoisonError};
use std::sync::{Arc, LazyLock, Mutex, MutexGuard, OnceLock, PoisonError};
use std::thread;
use rayon::Scope;
use rustc_hash::FxHashSet;
use crate::tree::{Metric, Node, NodeKind, aggregate};
use crate::tree::{Metric, Node, NodeKind, Seen, aggregate, aggregate_deduped};
/// Errors kept verbatim before the list is truncated; the count keeps rising.
const MAX_ERROR_DETAIL: usize = 50;
@@ -105,13 +105,21 @@ pub struct ScanSnapshot {
}
impl ScanProgress {
fn count_file(&self, bytes: u64) {
self.files.fetch_add(1, Ordering::Relaxed);
/// What a directory's listing found (see `Tally`), or what a reader
/// that measures in bulk has come across so far.
pub(crate) fn add(&self, files: u64, dirs: u64, bytes: u64) {
self.files.fetch_add(files, Ordering::Relaxed);
self.dirs.fetch_add(dirs, Ordering::Relaxed);
self.bytes.fetch_add(bytes, Ordering::Relaxed);
}
fn count_dir(&self) {
self.dirs.fetch_add(1, Ordering::Relaxed);
/// The totals of the finished tree, replacing a bulk reader's running
/// count: it met the whole volume, and the tree may be less of it.
#[cfg(windows)]
pub(crate) fn settle(&self, files: u64, dirs: u64, bytes: u64) {
self.files.store(files, Ordering::Relaxed);
self.dirs.store(dirs, Ordering::Relaxed);
self.bytes.store(bytes, Ordering::Relaxed);
}
fn record_error(&self, path: &Path, error: &io::Error) {
@@ -191,6 +199,7 @@ impl ScanHandle {
never_scanned: OnceLock::new(),
visited_dirs: Mutex::new(FxHashSet::default()),
root: Mutex::new(None),
volume: OnceLock::new(),
});
let (sender, result) = mpsc::channel();
@@ -240,6 +249,7 @@ pub fn scan(root: &Path, options: ScanOptions) -> io::Result<Node> {
never_scanned: OnceLock::new(),
visited_dirs: Mutex::new(FxHashSet::default()),
root: Mutex::new(None),
volume: OnceLock::new(),
});
let node = scan_blocking(root, &context)?;
progress.finish();
@@ -264,6 +274,10 @@ struct WalkContext {
visited_dirs: Mutex<FxHashSet<(u64, u64)>>,
/// Set by the root's `complete`, read after the scope joins.
root: Mutex<Option<Node>>,
/// Serial number of the root's volume, on Windows, for a walk that
/// cannot leave it: every listing takes it instead of asking. See
/// [`crate::windows::walk_volume`].
volume: OnceLock<u64>,
}
impl WalkContext {
@@ -281,33 +295,41 @@ impl WalkContext {
self.progress.is_cancelled()
}
/// Decide what to do with an entry, and account for the work it implies.
fn classify(&self, entry: &impl Listed) -> Classified {
let path = entry.entry_path();
/// Decide what to do with an entry listed in `dir`.
///
/// The entry's path is built only where it is used: most entries are
/// files, and a disk has millions of them. The name is moved out of
/// the entry last, so nothing copies it.
fn classify(&self, dir: &Path, entry: &mut impl Listed) -> Classified {
let listing = match entry.listing() {
Ok(listing) => listing,
Err(error) => {
self.progress.record_error(&path, &error);
self.progress.record_error(&entry.entry_path(dir), &error);
return Classified::Skipped;
}
};
let name = entry.display_name();
if !self.options.include_hidden
&& (name.starts_with('.') || entry.hidden())
&& (entry.name().starts_with('.') || entry.hidden())
{
return Classified::Skipped;
}
let kind = match listing {
Listing::Symlink => return self.classify_symlink(&path, name),
Listing::Directory => return self.classify_dir(entry, path, name),
Listing::Symlink => {
let path = entry.entry_path(dir);
return self.classify_symlink(&path, entry.take_name());
}
Listing::Directory => {
let path = entry.entry_path(dir);
return self.classify_dir(entry, path);
}
Listing::Leaf(kind) => kind,
};
match entry.facts(self.options.apparent_size) {
Ok(facts) => self.leaf(name, kind, &facts),
Ok(facts) => self.leaf(entry.take_name(), kind, &facts),
Err(error) => {
self.progress.record_error(&path, &error);
self.progress.record_error(&entry.entry_path(dir), &error);
Classified::Skipped
}
}
@@ -315,9 +337,8 @@ impl WalkContext {
fn classify_dir(
&self,
entry: &impl Listed,
entry: &mut impl Listed,
path: PathBuf,
name: Box<str>,
) -> Classified {
if self
.never_scanned
@@ -344,12 +365,8 @@ impl WalkContext {
if let Some(known) = &self.known
&& known.path == path
{
let tree = (*known.tree).clone();
self.progress.files.fetch_add(tree.files, Ordering::Relaxed);
self.progress.bytes.fetch_add(tree.bytes, Ordering::Relaxed);
self.progress.dirs.fetch_add(tree.dirs, Ordering::Relaxed);
let mut tree = tree;
tree.name = name;
let mut tree = (*known.tree).clone();
tree.name = entry.take_name();
return Classified::Entry(tree);
}
if self.options.one_filesystem
@@ -374,8 +391,10 @@ impl WalkContext {
_ => {}
}
}
self.progress.count_dir();
Classified::Subdirectory(path)
Classified::Subdirectory {
path,
name: entry.take_name(),
}
}
fn classify_symlink(&self, path: &Path, name: Box<str>) -> Classified {
@@ -385,7 +404,6 @@ impl WalkContext {
return match fs::symlink_metadata(path) {
Ok(meta) => {
let facts = Facts::of(&meta, self.options.apparent_size);
self.progress.count_file(facts.size);
Classified::Entry(leaf_node(
name,
NodeKind::Symlink,
@@ -422,8 +440,10 @@ impl WalkContext {
{
return Classified::Skipped;
}
self.progress.count_dir();
return Classified::Subdirectory(path.to_path_buf());
return Classified::Subdirectory {
path: path.to_path_buf(),
name,
};
}
let mut facts = Facts::of(&meta, self.options.apparent_size);
@@ -439,7 +459,6 @@ impl WalkContext {
kind: NodeKind,
facts: &Facts,
) -> Classified {
self.progress.count_file(facts.size);
// A followed link reaches a file a second way, whatever its link
// count says.
let track = self.options.follow_links || facts.shared;
@@ -454,10 +473,14 @@ impl WalkContext {
/// would cost an open per file; [`crate::windows`] lists a directory with
/// both instead.
trait Listed {
fn entry_path(&self) -> PathBuf;
/// The entry's path inside `dir`, the directory it was listed from.
fn entry_path(&self, dir: &Path) -> PathBuf;
/// Non-UTF-8 names are lossy for display. The scan still measures them
/// correctly; only the reported name is approximate.
fn display_name(&self) -> Box<str>;
fn name(&self) -> &str;
/// The name, moved out for the tree: after this `name` is empty, and
/// `entry_path`, which must open the real file, is off limits.
fn take_name(&mut self) -> Box<str>;
fn listing(&self) -> io::Result<Listing>;
/// Size, identity and age of a leaf.
fn facts(&self, apparent_size: bool) -> io::Result<Facts>;
@@ -515,18 +538,29 @@ impl Facts {
}
}
/// A standard directory entry with its name decoded once, up front.
#[cfg(not(windows))]
impl Listed for DirEntry {
fn entry_path(&self) -> PathBuf {
self.path()
struct Named {
entry: DirEntry,
name: Box<str>,
}
#[cfg(not(windows))]
impl Listed for Named {
fn entry_path(&self, _dir: &Path) -> PathBuf {
self.entry.path()
}
fn display_name(&self) -> Box<str> {
self.file_name().to_string_lossy().into_owned().into()
fn name(&self) -> &str {
&self.name
}
fn take_name(&mut self) -> Box<str> {
std::mem::take(&mut self.name)
}
fn listing(&self) -> io::Result<Listing> {
let file_type = self.file_type()?;
let file_type = self.entry.file_type()?;
Ok(if file_type.is_symlink() {
Listing::Symlink
} else if file_type.is_dir() {
@@ -539,11 +573,13 @@ impl Listed for DirEntry {
}
fn facts(&self, apparent_size: bool) -> io::Result<Facts> {
self.metadata().map(|meta| Facts::of(&meta, apparent_size))
self.entry
.metadata()
.map(|meta| Facts::of(&meta, apparent_size))
}
fn directory(&self) -> io::Result<Directory> {
self.metadata().map(|meta| Directory {
self.entry.metadata().map(|meta| Directory {
device: device_of(&meta),
evicted: is_dataless(&meta),
})
@@ -552,12 +588,16 @@ impl Listed for DirEntry {
#[cfg(windows)]
impl Listed for crate::windows::Entry {
fn entry_path(&self) -> PathBuf {
self.path()
fn entry_path(&self, dir: &Path) -> PathBuf {
self.path(dir)
}
fn display_name(&self) -> Box<str> {
self.file_name().to_string_lossy().into_owned().into()
fn name(&self) -> &str {
self.name()
}
fn take_name(&mut self) -> Box<str> {
self.take_name()
}
fn listing(&self) -> io::Result<Listing> {
@@ -600,19 +640,33 @@ impl Listed for crate::windows::Entry {
/// List a directory the way [`Listed`] describes.
#[cfg(not(windows))]
fn list(path: &Path) -> io::Result<fs::ReadDir> {
fs::read_dir(path)
fn list(
path: &Path,
_volume: Option<u64>,
) -> io::Result<impl Iterator<Item = io::Result<Named>>> {
Ok(fs::read_dir(path)?.map(|entry| {
entry.map(|entry| Named {
name: entry.file_name().into_string().map_or_else(
|raw| raw.to_string_lossy().into(),
String::into_boxed_str,
),
entry,
})
}))
}
#[cfg(windows)]
fn list(path: &Path) -> io::Result<crate::windows::ReadDir> {
crate::windows::read_dir(path)
fn list(
path: &Path,
volume: Option<u64>,
) -> io::Result<crate::windows::ReadDir> {
crate::windows::read_dir(path, volume)
}
/// What a directory entry turned out to be.
enum Classified {
/// Descend into this directory on a new task.
Subdirectory(PathBuf),
Subdirectory { path: PathBuf, name: Box<str> },
/// A leaf that contributes size.
Entry(Node),
/// Filtered out, unreadable, or a symlink we chose not to follow.
@@ -627,15 +681,25 @@ struct PendingDir {
/// Starts at 1 for the directory itself; one more per subdirectory task.
/// When it reaches zero the directory is complete.
pending: AtomicUsize,
/// Files found directly here, and finished subdirectories handed back up.
children: Mutex<Vec<Node>>,
/// The node so far, moved out whole once the directory is complete.
partial: Mutex<Partial>,
read_error: AtomicBool,
depth: usize,
}
/// What a directory's node is made of before it is built: the name the
/// listing gave it, and the files found directly in it plus the finished
/// subdirectories handed back up.
#[derive(Debug, Default)]
struct Partial {
name: Box<str>,
children: Vec<Node>,
}
impl PendingDir {
const fn new(
path: PathBuf,
name: Box<str>,
parent: Option<Arc<Self>>,
depth: usize,
) -> Self {
@@ -643,21 +707,25 @@ impl PendingDir {
path,
parent,
pending: AtomicUsize::new(1),
children: Mutex::new(Vec::new()),
partial: Mutex::new(Partial {
name,
children: Vec::new(),
}),
read_error: AtomicBool::new(false),
depth,
}
}
/// Turn a completed directory into a node. Only called when `pending` has
/// reached zero, so every child is already in `self.children`.
/// reached zero, so every child is already in `self.partial`.
///
/// `bytes` and `own_bytes` are left at zero on purpose: the walk cannot
/// know the aggregate, and [`crate::tree::aggregate`] derives both from the
/// children once every child is present.
fn build(&self) -> Node {
let partial = std::mem::take(&mut *lock(&self.partial));
Node {
name: file_name(&self.path),
name: partial.name,
kind: NodeKind::Directory,
bytes: 0,
own_bytes: 0,
@@ -669,7 +737,7 @@ impl PendingDir {
modified: 0,
category: crate::classify::Category::Other,
reclaim: None,
children: std::mem::take(&mut *lock(&self.children)),
children: partial.children,
}
}
}
@@ -682,23 +750,64 @@ fn scan_blocking(root: &Path, context: &Arc<WalkContext>) -> io::Result<Node> {
format!("{} is not a directory", root.display()),
));
}
let canonical = root.canonicalize().unwrap_or_else(|_| root.to_path_buf());
let never = crate::space::never_scanned(root, &canonical);
let resolved = root.canonicalize().ok();
let canonical = resolved.as_deref().unwrap_or(root);
let never = crate::space::never_scanned(root, canonical);
let _ = context.never_scanned.set(never.into_iter().collect());
if context.options.one_filesystem {
*lock(&context.root_device) = Some(device_of(&root_meta));
if let Some(foreign) = crate::space::foreign_mounts_for(&canonical) {
if let Some(foreign) = crate::space::foreign_mounts_for(canonical) {
let _ = context.foreign_mounts.set(foreign.into_iter().collect());
}
}
// Reading the file table is far faster than any walk, where the
// volume allows it. On the walk's pool too: see `WALK_POOL`.
#[cfg(windows)]
{
let progress = &context.progress;
let read = WALK_POOL.install(|| {
crate::mft::scan(root, canonical, &context.options, progress)
});
if let Some(node) = read {
let node = node?;
// Cancelled after the reader's last check: the rescan that
// asked is waiting, and this tree is not wanted.
if progress.is_cancelled() {
return Err(crate::mft::cancelled());
}
let node = finish_tree(node, &context.options);
// The reader counted every file on the volume; the tree may
// hold fewer.
progress.settle(node.files, node.dirs, node.bytes);
return Ok(node);
}
// The reader gave up, or never started: the walk counts from nothing.
progress.settle(0, 0, 0);
// Asking once instead of per directory; see `walk_volume` for
// when a walk that does not follow links cannot leave the volume.
// Only on a resolved root: a mapped share's letter kept as typed
// looks like a local drive.
if !context.options.follow_links
&& let Some(resolved) = &resolved
&& let Some(serial) = crate::windows::walk_volume(resolved)
{
let _ = context.volume.set(serial);
}
}
if context.options.follow_links
&& let Some(key) = identity_of(root, &root_meta)
{
lock(&context.visited_dirs).insert(key);
}
let root_dir = Arc::new(PendingDir::new(root.to_path_buf(), None, 0));
rayon::scope(|scope| walk(scope, &root_dir, context));
let root_dir = Arc::new(PendingDir::new(
root.to_path_buf(),
file_name(root),
None,
0,
));
let context: &WalkContext = context;
WALK_POOL.install(|| rayon::scope(|scope| walk(scope, &root_dir, context)));
let node = lock(&context.root).take();
let node = node.ok_or_else(|| {
@@ -707,32 +816,101 @@ fn scan_blocking(root: &Path, context: &Arc<WalkContext>) -> io::Result<Node> {
Ok(finish_tree(node, &context.options))
}
/// The walk's workers, and the file table reader's. Listing directories
/// contends in the file system, and past some number of threads more of
/// them only queue: on Windows a home directory of 3.4 million files
/// walked in 6.5 s on 16 threads and 8.1 s on all 24. That cap was
/// measured on one 24-thread NTFS laptop; another disk or CPU may want
/// another. Elsewhere the default count. A pool of its own on every
/// platform all the same: work the UI hands the global pool, such as
/// re-ranking a tree, must not queue behind a scan's blocking reads.
static WALK_POOL: LazyLock<rayon::ThreadPool> = LazyLock::new(|| {
let threads = if cfg!(windows) {
rayon::current_num_threads().min(16)
} else {
rayon::current_num_threads()
};
rayon::ThreadPoolBuilder::new()
.num_threads(threads)
.thread_name(|index| format!("disktree-walk-{index}"))
.build()
.expect("a thread pool")
});
/// Entries counted before the shared progress counters are touched. Every
/// worker adding to the same counters per entry keeps one cache line
/// bouncing between cores; per directory, or per this many entries in a
/// wide one so the meter still moves, is invisible to a reader.
const TALLY_EVERY: u64 = 1024;
/// What one directory's listing has found so far, for the progress meter.
#[derive(Default)]
struct Tally {
files: u64,
dirs: u64,
bytes: u64,
}
impl Tally {
const fn add(&mut self, node: &Node) {
if node.is_dir() {
// A subtree taken whole from an earlier scan.
self.files += node.files;
self.dirs += node.dirs;
} else {
// A link counts as a file on the meter, as it always has,
// though the tree does not count it.
self.files += 1;
}
self.bytes += node.bytes;
}
fn flush(&mut self, progress: &ScanProgress) {
progress.add(self.files, self.dirs, self.bytes);
*self = Self::default();
}
}
/// Read one directory, spawn a task per subdirectory, then report completion.
///
/// Flat tasks inside the scope: the worker stack never grows with tree depth.
fn walk(scope: &Scope<'_>, dir: &Arc<PendingDir>, context: &Arc<WalkContext>) {
fn walk<'scope>(
scope: &Scope<'scope>,
dir: &Arc<PendingDir>,
context: &'scope WalkContext,
) {
let mut subdirs: Vec<Arc<PendingDir>> = Vec::new();
let mut leaves: Vec<Node> = Vec::new();
let mut tally = Tally::default();
match list(&dir.path) {
match list(&dir.path, context.volume.get().copied()) {
Ok(entries) => {
for entry in entries {
if context.cancelled() {
break;
}
match entry {
Ok(entry) => match context.classify(&entry) {
Classified::Subdirectory(path) => {
let child = Arc::new(PendingDir::new(
path,
Some(Arc::clone(dir)),
dir.depth + 1,
));
subdirs.push(child);
Ok(mut entry) => {
match context.classify(&dir.path, &mut entry) {
Classified::Subdirectory { path, name } => {
tally.dirs += 1;
subdirs.push(Arc::new(PendingDir::new(
path,
name,
Some(Arc::clone(dir)),
dir.depth + 1,
)));
}
Classified::Entry(node) => {
tally.add(&node);
leaves.push(node);
}
Classified::Skipped => {}
}
Classified::Entry(node) => leaves.push(node),
Classified::Skipped => {}
},
if tally.files + tally.dirs >= TALLY_EVERY {
tally.flush(&context.progress);
}
}
Err(error) => {
context.progress.record_error(&dir.path, &error);
}
@@ -744,6 +922,7 @@ fn walk(scope: &Scope<'_>, dir: &Arc<PendingDir>, context: &Arc<WalkContext>) {
dir.read_error.store(true, Ordering::Relaxed);
}
}
tally.flush(&context.progress);
// A depth-limited scan still measures what is directly in the directory,
// it just does not descend further.
@@ -751,20 +930,30 @@ fn walk(scope: &Scope<'_>, dir: &Arc<PendingDir>, context: &Arc<WalkContext>) {
.options
.max_depth
.is_none_or(|max_depth| dir.depth < max_depth);
// Sized once for the leaves and every subdirectory to come, before any
// subdirectory task can push its node: otherwise that first push
// doubles a list just sized to the leaves, and the slack stays in the
// finished tree. The leaves are copied, not moved: the list they grew
// in carries up to twice their size in slack, and moving it in whole
// made a home directory walk a second slower (measured, 5 interleaved
// pairs).
let spawned = if descend { subdirs.len() } else { 0 };
{
let mut partial = lock(&dir.partial);
partial.children.reserve_exact(leaves.len() + spawned);
partial.children.extend(leaves);
}
if descend {
for subdir in subdirs {
if context.cancelled() {
break;
}
dir.pending.fetch_add(1, Ordering::AcqRel);
let subdir = Arc::clone(&subdir);
let context = Arc::clone(context);
scope.spawn(move |scope| walk(scope, &subdir, &context));
scope.spawn(move |scope| walk(scope, &subdir, context));
}
}
lock(&dir.children).extend(leaves);
signal_done(&Arc::clone(dir), context);
signal_done(dir, context);
}
/// Report that one task for `dir` is done: either its own scan, or one of its
@@ -773,44 +962,32 @@ fn walk(scope: &Scope<'_>, dir: &Arc<PendingDir>, context: &Arc<WalkContext>) {
/// This is the whole reason for the `+1` sentinel: a directory is only built
/// once its own scan *and* every subdirectory task has finished, no matter
/// which of them lands last.
fn signal_done(dir: &Arc<PendingDir>, context: &Arc<WalkContext>) {
fn signal_done(dir: &Arc<PendingDir>, context: &WalkContext) {
if dir.pending.fetch_sub(1, Ordering::AcqRel) != 1 {
return;
}
let node = dir.build();
let Some(parent) = dir.parent.clone() else {
let Some(parent) = &dir.parent else {
*lock(&context.root) = Some(node);
return;
};
lock(&parent.children).push(node);
signal_done(&parent, context);
lock(&parent.partial).children.push(node);
signal_done(parent, context);
}
/// Charge a hardlinked file once, then derive every aggregate from the result.
///
/// Zeroing `own_bytes` rather than `bytes` is deliberate:
/// [`crate::tree::aggregate`] recomputes totals from the direct contents, so a
/// patched `bytes` would be overwritten.
/// Charge a hardlinked file once, derive every aggregate from the result,
/// then classify. On the walk's pool: the UI's own work on the global pool
/// must not queue behind a scan finishing.
fn finish_tree(mut node: Node, options: &ScanOptions) -> Node {
if options.dedup_hardlinks {
let mut seen = FxHashSet::default();
mark_duplicate_hardlinks(&mut node, &mut seen);
}
aggregate(&mut node, options.metric);
crate::classify::classify(&mut node);
node
}
fn mark_duplicate_hardlinks(node: &mut Node, seen: &mut FxHashSet<(u64, u64)>) {
if !node.is_dir() {
if node.inode.is_some_and(|key| !seen.insert(key)) {
node.own_bytes = 0;
WALK_POOL.install(|| {
if options.dedup_hardlinks {
aggregate_deduped(&mut node, options.metric, &Seen::new());
} else {
aggregate(&mut node, options.metric);
}
return;
}
for child in &mut node.children {
mark_duplicate_hardlinks(child, seen);
}
crate::classify::classify(&mut node);
});
node
}
/// A leaf. Its identity is kept only when `track` says the walk could meet
@@ -958,7 +1135,7 @@ fn kind_of(meta: &Metadata, file_type: fs::FileType) -> NodeKind {
/// The display name of a scanned root: its final component, or the path itself
/// for `/`.
fn file_name(path: &Path) -> Box<str> {
pub(crate) fn file_name(path: &Path) -> Box<str> {
path.file_name()
.map_or_else(
|| path.to_string_lossy().into_owned(),
@@ -969,7 +1146,7 @@ fn file_name(path: &Path) -> Box<str> {
/// A poisoned lock means another task panicked; the data is still a valid tree
/// prefix, and refusing to read it would turn one panic into two.
fn lock<T>(mutex: &Mutex<T>) -> MutexGuard<'_, T> {
pub(crate) fn lock<T>(mutex: &Mutex<T>) -> MutexGuard<'_, T> {
mutex.lock().unwrap_or_else(PoisonError::into_inner)
}
@@ -1269,6 +1446,7 @@ mod tests {
never_scanned: OnceLock::new(),
visited_dirs: Mutex::new(FxHashSet::default()),
root: Mutex::new(None),
volume: OnceLock::new(),
});
let tree = scan_blocking(root, &context).expect("scan still succeeds");
let _ = fs::set_permissions(&locked, fs::Permissions::from_mode(0o700));
+156 -6
View File
@@ -1,6 +1,11 @@
//! The scanned tree.
use std::path::{Path, PathBuf};
use std::sync::atomic::{AtomicU64, Ordering};
use std::sync::{LazyLock, Mutex, OnceLock};
use rayon::prelude::*;
use rustc_hash::FxHashSet;
use crate::classify::{Category, Reclaim};
@@ -235,7 +240,104 @@ impl Node {
/// de-duplication rewrites a leaf's weight, and every total above it —
/// including its parent's "direct" figure — follows without a second pass.
pub fn aggregate(node: &mut Node, metric: Metric) {
aggregate_at(node, metric, 0, None);
}
/// [`aggregate`], charging a hardlinked file once: a leaf whose identity
/// `seen` already holds weighs nothing. Which of a file's names is charged
/// is whichever a worker reaches first, so two scans of an unchanged tree
/// can split it differently between folders; the totals are the same.
pub(crate) fn aggregate_deduped(node: &mut Node, metric: Metric, seen: &Seen) {
aggregate_at(node, metric, 0, Some(seen));
}
/// Identities a finish pass has met.
///
/// A hash set of every file on a disk is millions of random writes into a
/// table too big for any cache. Inode and file record numbers are small
/// integers, though, so a key on the first volume met whose whole number
/// is below the bitmap's size gets one bit instead: an 8 MiB bitmap the
/// workers set without locking. The file table reader's record numbers
/// fit, as do most inodes. Anything else goes into the hash set, whole:
/// a Windows file id keeps the record's reuse count in its top 16 bits,
/// and that is what tells a file from an older one on the same record,
/// which a subtree kept from an earlier scan can still hold. The set is
/// sharded for the walk's millions of those: 4.1 million ids took 150 ms
/// across 64 locks and 1.2 s behind one, in a synthetic run.
pub(crate) struct Seen {
/// The first volume met, which is the scanned root's in all but a scan
/// that leaves its volume.
volume: OnceLock<u64>,
/// Made on the first key that fits: most Unix trees, where only files
/// with more than one name carry an identity, never need it.
bits: LazyLock<Box<[AtomicU64]>>,
rest: Box<[Shard]>,
}
/// One lock's part of the hash set.
type Shard = Mutex<FxHashSet<(u64, u64)>>;
impl Seen {
/// Numbers the bitmap covers: sixty-four million, more files than a
/// desktop volume holds, for 8 MiB written once.
const BITS: u64 = 1 << 26;
/// Hash set shards, as a power of two.
const SHARD_BITS: u32 = 6;
pub(crate) fn new() -> Self {
Self {
volume: OnceLock::new(),
bits: LazyLock::new(|| {
std::iter::repeat_with(|| AtomicU64::new(0))
.take((Self::BITS / 64) as usize)
.collect()
}),
rest: std::iter::repeat_with(Mutex::default)
.take(1 << Self::SHARD_BITS)
.collect(),
}
}
/// Whether `key` is new.
fn insert(&self, key: (u64, u64)) -> bool {
let (volume, number) = key;
if *self.volume.get_or_init(|| volume) == volume && number < Self::BITS
{
let bit = 1 << (number % 64);
let word = &self.bits[(number / 64) as usize];
return word.fetch_or(bit, Ordering::Relaxed) & bit == 0;
}
// The top bits of a multiplicative hash, with another constant
// than the set's own hasher, so a shard's keys still spread over
// its table.
let shard = (number.wrapping_mul(0x9E37_79B9_7F4A_7C15)
>> (u64::BITS - Self::SHARD_BITS)) as usize;
crate::scan::lock(&self.rest[shard]).insert(key)
}
}
/// Levels whose subtrees are aggregated in parallel. A top level already
/// splits a disk into enough work for every thread; below it a parallel
/// frame per level would only cut the depth that fits in a worker's stack.
pub(crate) const PARALLEL_LEVELS: usize = 4;
fn aggregate_at(
node: &mut Node,
metric: Metric,
depth: usize,
seen: Option<&Seen>,
) {
if !node.is_dir() {
// Every name of a file has the file's size, so one that weighs
// nothing need not be remembered to be charged once.
if node.own_bytes > 0
&& let Some(seen) = seen
&& let Some(key) = node.inode
&& !seen.insert(key)
{
node.own_bytes = 0;
}
node.bytes = node.own_bytes;
node.files = node.own_files;
node.dirs = 0;
@@ -248,14 +350,23 @@ pub fn aggregate(node: &mut Node, metric: Metric) {
let mut own_files = 0;
let mut dirs: u64 = 1;
let mut modified = 0;
for child in &mut node.children {
aggregate(child, metric);
if depth < PARALLEL_LEVELS {
node.children
.par_iter_mut()
.for_each(|child| aggregate_at(child, metric, depth + 1, seen));
} else {
for child in &mut node.children {
aggregate_at(child, metric, depth + 1, seen);
}
}
for child in &node.children {
modified = modified.max(child.modified);
bytes += child.bytes;
// Saturating: a corrupt volume's file table can claim any size.
bytes = child.bytes.saturating_add(bytes);
files += child.files;
dirs += child.dirs;
if !child.is_dir() {
own_bytes += child.bytes;
own_bytes = child.bytes.saturating_add(own_bytes);
own_files += child.files;
}
}
@@ -267,8 +378,11 @@ pub fn aggregate(node: &mut Node, metric: Metric) {
node.modified = modified;
// Largest first: a treemap lays out big tiles best, and the order is what
// makes "descend into the largest child" meaningful.
node.children.sort_by(|left, right| {
// makes "descend into the largest child" meaningful. Unstable: names in
// one directory are distinct, and the only ties are names that decoded
// to the same lossy text, whose order does not matter, so the stable
// sort's scratch allocation buys nothing.
node.children.sort_unstable_by(|left, right| {
right
.value(metric)
.cmp(&left.value(metric))
@@ -300,6 +414,42 @@ mod tests {
Node::entry(name, NodeKind::File, bytes)
}
#[test]
fn seen_charges_an_identity_once_in_either_store() {
let seen = Seen::new();
// The first volume: the bitmap.
assert!(seen.insert((7, 42)));
assert!(!seen.insert((7, 42)));
assert!(seen.insert((7, 43)));
// A number past the bitmap, and another volume: the hash set.
let far = Seen::BITS + 42;
assert!(seen.insert((7, far)));
assert!(!seen.insert((7, far)));
assert!(seen.insert((8, 42)), "another volume's 42 is another file");
assert!(!seen.insert((8, 42)));
}
#[test]
fn identities_that_differ_only_in_their_top_bits_are_two_files() {
// Record 0x2A of one volume under two reuse counts, as a subtree kept
// from an earlier scan and a later file can hold, and a real second
// name of the newer one.
let older = (7, (1 << 48) | 0x2A);
let newer = (7, (2 << 48) | 0x2A);
let mut root = Node::directory("root");
for (name, bytes, key) in [
("older", 4096, older),
("newer", 8192, newer),
("newer again", 8192, newer),
] {
let mut file = leaf(name, bytes);
file.inode = Some(key);
root.children.push(file);
}
aggregate_deduped(&mut root, Metric::Bytes, &Seen::new());
assert_eq!(root.bytes, 4096 + 8192);
}
#[test]
fn aggregate_derives_totals_and_orders_children() {
let mut root = Node::directory("root");
+295 -36
View File
@@ -23,11 +23,10 @@ use std::os::windows::ffi::{OsStrExt as _, OsStringExt as _};
use std::os::windows::fs::{MetadataExt as _, OpenOptionsExt as _};
use std::os::windows::io::AsRawHandle as _;
use std::path::{Component, Path, PathBuf, Prefix};
use std::sync::Arc;
use windows_sys::Win32::Foundation::{
ERROR_INVALID_FUNCTION, ERROR_INVALID_LEVEL, ERROR_INVALID_PARAMETER,
ERROR_NO_MORE_FILES, ERROR_NOT_SUPPORTED, INVALID_HANDLE_VALUE,
ERROR_NO_MORE_FILES, ERROR_NOT_SUPPORTED, INVALID_HANDLE_VALUE, MAX_PATH,
};
use windows_sys::Win32::Storage::FileSystem::{
FILE_ATTRIBUTE_DIRECTORY, FILE_ATTRIBUTE_HIDDEN,
@@ -36,7 +35,8 @@ use windows_sys::Win32::Storage::FileSystem::{
FILE_ID_EXTD_DIR_INFO, FILE_LIST_DIRECTORY, FILE_READ_ATTRIBUTES,
FileIdExtdDirectoryInfo, FindFirstVolumeW, FindNextVolumeW,
FindVolumeClose, GetDiskFreeSpaceExW, GetFileInformationByHandleEx,
GetVolumePathNameW, GetVolumePathNamesForVolumeNameW, SYNCHRONIZE,
GetVolumeInformationW, GetVolumePathNameW,
GetVolumePathNamesForVolumeNameW, SYNCHRONIZE,
};
use crate::space::SpaceInfo;
@@ -73,10 +73,15 @@ pub enum Kind {
}
/// One directory entry, with what a measurement needs.
///
/// The name is decoded to text once, here, since that is what the tree
/// keeps: the listing hands the walk one allocation per entry, not three.
#[derive(Debug)]
pub struct Entry {
dir: Arc<Path>,
name: OsString,
name: Box<str>,
/// The name as Windows spells it, only when `name` could not: an
/// unpaired surrogate is shown as U+FFFD but must still open.
exact: Option<Box<OsStr>>,
kind: Kind,
apparent: u64,
allocated: u64,
@@ -86,14 +91,29 @@ pub struct Entry {
}
impl Entry {
pub fn path(&self) -> PathBuf {
self.dir.join(&self.name)
/// The entry's path inside `dir`, the directory it was listed from.
pub fn path(&self, dir: &Path) -> PathBuf {
dir.join(self.file_name())
}
pub fn file_name(&self) -> &OsStr {
self.exact
.as_deref()
.unwrap_or_else(|| OsStr::new(&*self.name))
}
/// The name as text; see [`Self::file_name`] for what it may lose.
pub fn name(&self) -> &str {
&self.name
}
/// The name, moved out: the tree keeps it, so nothing copies it. The
/// entry's other accessors keep working; `name`, `file_name` and
/// `path` do not.
pub fn take_name(&mut self) -> Box<str> {
std::mem::take(&mut self.name)
}
pub const fn kind(&self) -> Kind {
self.kind
}
@@ -133,7 +153,7 @@ impl Entry {
self.identity
}
fn from_std(dir: &Arc<Path>, entry: &fs::DirEntry) -> io::Result<Self> {
fn from_std(entry: &fs::DirEntry) -> io::Result<Self> {
let meta = entry.metadata()?;
let file_type = meta.file_type();
let kind = if file_type.is_symlink() {
@@ -143,9 +163,15 @@ impl Entry {
} else {
Kind::File
};
let (name, exact) = match entry.file_name().into_string() {
Ok(name) => (name.into_boxed_str(), None),
Err(raw) => {
(raw.to_string_lossy().into(), Some(raw.into_boxed_os_str()))
}
};
Ok(Self {
dir: Arc::clone(dir),
name: entry.file_name(),
name,
exact,
kind,
apparent: meta.len(),
allocated: meta.len(),
@@ -162,7 +188,6 @@ impl Entry {
/// and `..`.
#[derive(Debug)]
pub struct ReadDir {
dir: Arc<Path>,
source: Source,
}
@@ -189,7 +214,12 @@ struct Records {
}
/// List `dir`, with each entry's allocation and file id.
pub fn read_dir(dir: &Path) -> io::Result<ReadDir> {
///
/// `volume` is the serial number of the volume `dir` is on, when the
/// caller knows it for every directory of a walk (see [`walk_volume`]):
/// asking per directory is several requests to the file system on top of
/// the listing. `None` asks.
pub fn read_dir(dir: &Path, volume: Option<u64>) -> io::Result<ReadDir> {
let handle = OpenOptions::new()
.access_mode(FILE_LIST_DIRECTORY | FILE_READ_ATTRIBUTES | SYNCHRONIZE)
// Needed to open a directory at all. Without
@@ -197,9 +227,11 @@ pub fn read_dir(dir: &Path) -> io::Result<ReadDir> {
// a walk that chose to enter one wants.
.custom_flags(FILE_FLAG_BACKUP_SEMANTICS)
.open(dir)?;
let volume = winapi_util::file::information(&handle)
.ok()
.map(|info| info.volume_serial_number());
let volume = volume.or_else(|| {
winapi_util::file::information(&handle)
.ok()
.map(|info| info.volume_serial_number())
});
let mut records = Records {
handle,
volume,
@@ -207,17 +239,16 @@ pub fn read_dir(dir: &Path) -> io::Result<ReadDir> {
next: None,
done: false,
};
let dir: Arc<Path> = Arc::from(dir);
// The first fill shows whether the file system implements this listing,
// before any entry has been handed out.
let source = match records.fill() {
Ok(()) => Source::Records(records),
Err(error) if unsupported(&error) => {
Source::Std(Box::new(fs::read_dir(&dir)?))
Source::Std(Box::new(fs::read_dir(dir)?))
}
Err(error) => return Err(error),
};
Ok(ReadDir { dir, source })
Ok(ReadDir { source })
}
impl Iterator for ReadDir {
@@ -227,7 +258,7 @@ impl Iterator for ReadDir {
let records = match &mut self.source {
Source::Std(listing) => {
return listing.next().map(|entry| {
entry.and_then(|entry| Entry::from_std(&self.dir, &entry))
entry.and_then(|entry| Entry::from_std(&entry))
});
}
Source::Records(records) => records,
@@ -243,7 +274,7 @@ impl Iterator for ReadDir {
}
continue;
};
match records.record(&self.dir, offset) {
match records.record(offset) {
Ok((entry, next)) => {
records.next = next;
if let Some(entry) = entry {
@@ -304,7 +335,6 @@ impl Records {
/// the buffer before it is used.
fn record(
&self,
dir: &Arc<Path>,
offset: usize,
) -> io::Result<(Option<Entry>, Option<usize>)> {
let malformed =
@@ -333,11 +363,11 @@ impl Records {
_ => return Err(malformed()),
};
let name: Vec<u16> = name_bytes
let units = name_bytes
.chunks_exact(2)
.map(|pair| u16::from_ne_bytes([pair[0], pair[1]]))
.collect();
if name == [u16::from(b'.')] || name == [u16::from(b'.'); 2] {
.map(|pair| u16::from_ne_bytes([pair[0], pair[1]]));
let (name, exact) = decode_name(units);
if &*name == "." || &*name == ".." {
return Ok((None, next));
}
@@ -358,8 +388,8 @@ impl Records {
header[id_at..id_at + 16].try_into().expect("sixteen"),
);
let entry = Entry {
dir: Arc::clone(dir),
name: OsString::from_wide(&name),
name,
exact,
kind,
apparent: bytes_from(signed(offset_of!(
FILE_ID_EXTD_DIR_INFO,
@@ -380,6 +410,27 @@ impl Records {
}
}
/// A UTF-16 name as text, decoded in one pass; nearly every name is ASCII,
/// so one code unit is one byte and the text is allocated once, at its
/// final size. An unpaired surrogate is replaced, and the exact name kept
/// beside it so the path still opens.
fn decode_name(
units: impl Iterator<Item = u16> + Clone,
) -> (Box<str>, Option<Box<OsStr>>) {
let mut name = String::with_capacity(units.size_hint().0);
let mut lossy = false;
for unit in char::decode_utf16(units.clone()) {
name.push(unit.unwrap_or_else(|_| {
lossy = true;
char::REPLACEMENT_CHARACTER
}));
}
let exact = lossy.then(|| {
OsString::from_wide(&units.collect::<Vec<u16>>()).into_boxed_os_str()
});
(name.into_boxed_str(), exact)
}
/// The part of a 128-bit file id that names a file by itself.
///
/// NTFS keeps the high half zero ([MS-FSCC] 2.1.10), so the low half is the
@@ -403,15 +454,35 @@ fn file_id(id: u128) -> Option<u64> {
///
/// [MS-FSCC]: https://learn.microsoft.com/en-us/openspecs/windows_protocols/ms-fscc/2d3333fe-fc98-4a6f-98a2-4bb805aff407
pub fn identity(path: &Path) -> Option<(u64, u64)> {
let info = information(path)?;
let index = info.file_index();
(index != 0 && index != u64::MAX)
.then(|| (info.volume_serial_number(), index))
}
/// Serial number of the volume every directory under `canonical` is on,
/// for a walk that does not follow links. Only a local drive has one:
/// mounted folders there are reparse points the walk takes for links,
/// while a share's DFS links are not, and lead to other servers' volumes.
/// `None` for a share, or when the serial cannot be read.
pub fn walk_volume(canonical: &Path) -> Option<u64> {
let Some(Component::Prefix(prefix)) = canonical.components().next() else {
return None;
};
if !matches!(prefix.kind(), Prefix::Disk(_) | Prefix::VerbatimDisk(_)) {
return None;
}
information(canonical).map(|info| info.volume_serial_number())
}
/// What the file system says about `path`, following links.
fn information(path: &Path) -> Option<winapi_util::file::Information> {
let file = OpenOptions::new()
.access_mode(FILE_READ_ATTRIBUTES)
.custom_flags(FILE_FLAG_BACKUP_SEMANTICS)
.open(path)
.ok()?;
let info = winapi_util::file::information(&file).ok()?;
let index = info.file_index();
(index != 0 && index != u64::MAX)
.then(|| (info.volume_serial_number(), index))
winapi_util::file::information(&file).ok()
}
/// Capacity and free space of the volume holding `path`.
@@ -531,6 +602,119 @@ pub fn is_mount_point(path: &Path) -> bool {
&& volume_root(path).is_some_and(|root| same(&root, path))
}
/// Whether this process runs as an administrator, with the elevated token
/// UAC hands out: what reading a volume directly takes.
pub fn elevated() -> bool {
// SAFETY: takes no arguments and only reads the process token.
unsafe { windows_sys::Win32::UI::Shell::IsUserAnAdmin() != 0 }
}
/// Whether `root` is a whole drive an administrator would read from its
/// file table: a drive letter's root, formatted NTFS. Anything else, from
/// a folder or a mounted folder to another file system, is walked either way.
pub fn file_table_readable(root: &Path) -> bool {
let canonical = root.canonicalize().unwrap_or_else(|_| root.to_path_buf());
let Some(letter) = drive_letter(&canonical) else {
return false;
};
let volume: Vec<u16> = format!("{letter}:\\\0").encode_utf16().collect();
let mut name = [0_u16; MAX_PATH as usize + 1];
let length = u32::try_from(name.len()).unwrap_or(u32::MAX);
// SAFETY: `volume` is NUL-terminated and outlives the call, `name` is
// writable for the length passed, and the other outputs may be null.
let ok = unsafe {
GetVolumeInformationW(
volume.as_ptr(),
std::ptr::null_mut(),
0,
std::ptr::null_mut(),
std::ptr::null_mut(),
std::ptr::null_mut(),
name.as_mut_ptr(),
length,
)
};
let end = name.iter().position(|&unit| unit == 0).unwrap_or(0);
ok != 0 && String::from_utf16_lossy(&name[..end]) == "NTFS"
}
/// Start `program` with `args` as an administrator, through the UAC
/// prompt. Returns once the prompt is answered; declining it is an error
/// (`ERROR_CANCELLED`).
pub fn run_elevated(program: &Path, args: &[OsString]) -> io::Result<()> {
let file = wide(program, false)?;
let mut line: Vec<u16> = Vec::new();
for arg in args {
if !line.is_empty() {
line.push(u16::from(b' '));
}
line.extend(quoted(arg));
}
line.push(0);
let verb: Vec<u16> = "runas\0".encode_utf16().collect();
// SAFETY: every string is NUL-terminated and outlives the call; a null
// window and directory are allowed.
let instance = unsafe {
windows_sys::Win32::UI::Shell::ShellExecuteW(
std::ptr::null_mut(),
verb.as_ptr(),
file.as_ptr(),
line.as_ptr(),
std::ptr::null(),
windows_sys::Win32::UI::WindowsAndMessaging::SW_SHOWNORMAL,
)
};
// Anything above 32 is success, by the function's own convention.
if instance as usize > 32 {
Ok(())
} else {
Err(io::Error::last_os_error())
}
}
/// `C` when `canonical` is the root of drive `C:`; `None` for anything
/// else, a folder or a volume mounted in one.
pub fn drive_letter(canonical: &Path) -> Option<char> {
let mut components = canonical.components();
let Some(Component::Prefix(prefix)) = components.next() else {
return None;
};
let (Prefix::Disk(letter) | Prefix::VerbatimDisk(letter)) = prefix.kind()
else {
return None;
};
(components.next() == Some(Component::RootDir)
&& components.next().is_none())
.then_some(char::from(letter))
}
/// `arg` quoted so a program's C runtime splits it back out whole: inside
/// quotes, backslashes are literal except before a quote, where they must
/// be doubled, so `C:\` becomes `"C:\\"` and not `"C:\"`.
fn quoted(arg: &OsStr) -> Vec<u16> {
let quote = u16::from(b'"');
let backslash = u16::from(b'\\');
let mut out = vec![quote];
let mut slashes = 0;
for unit in arg.encode_wide() {
if unit == backslash {
slashes += 1;
continue;
}
let run = if unit == quote {
2 * slashes + 1
} else {
slashes
};
out.extend(std::iter::repeat_n(backslash, run));
slashes = 0;
out.push(unit);
}
out.extend(std::iter::repeat_n(backslash, 2 * slashes));
out.push(quote);
out
}
/// Whether `left` and `right` name the same place, compared the way Windows
/// compares names: see [`folded`].
pub fn same(left: &Path, right: &Path) -> bool {
@@ -615,7 +799,7 @@ fn bytes_from(value: i64) -> u64 {
}
/// A `FILETIME` as Unix seconds, `0` before 1970.
const fn unix_seconds(ticks: i64) -> i64 {
pub const fn unix_seconds(ticks: i64) -> i64 {
if ticks <= EPOCH_TICKS {
0
} else {
@@ -623,6 +807,36 @@ const fn unix_seconds(ticks: i64) -> i64 {
}
}
/// Bytes aligned to a page, for reads that bypass the file cache: those
/// want memory aligned to the disk's sector, which a page always is.
#[derive(Debug, Default)]
pub struct Aligned {
pages: Vec<Page>,
}
#[derive(Clone, Copy, Debug)]
#[repr(C, align(4096))]
struct Page([u8; 4096]);
impl Aligned {
/// `len` bytes, their contents whatever the last use left.
pub fn bytes(&mut self, len: usize) -> &mut [u8] {
let pages = len.div_ceil(size_of::<Page>());
if self.pages.len() < pages {
self.pages.resize(pages, Page([0; 4096]));
}
// SAFETY: `Page` is a `repr(C)` byte array, so the pages are one
// allocation of initialized bytes with no padding, and `len` fits
// in it; the borrow of `self` keeps it alive and unaliased.
unsafe {
std::slice::from_raw_parts_mut(
self.pages.as_mut_ptr().cast::<u8>(),
len,
)
}
}
}
/// Make a directory junction for a test: unlike a symbolic link, one needs
/// no privilege to create. `false` when there is no `cmd` to make it with.
#[cfg(test)]
@@ -643,6 +857,17 @@ mod tests {
use super::*;
use tempfile::TempDir;
#[test]
fn quoted_arguments_survive_the_command_line() {
let quote =
|arg: &str| String::from_utf16(&quoted(OsStr::new(arg))).unwrap();
// A drive root's trailing backslash would otherwise escape the quote.
assert_eq!(quote(r"C:\"), r#""C:\\""#);
assert_eq!(quote(r"C:\Program Files\x"), r#""C:\Program Files\x""#);
assert_eq!(quote(r#"a\"b"#), r#""a\\\"b""#);
assert_eq!(quote("--metric"), r#""--metric""#);
}
#[test]
fn the_volume_list_has_the_system_drive() {
let drive =
@@ -657,7 +882,7 @@ mod tests {
}
fn listed(dir: &Path) -> Vec<Entry> {
let mut entries: Vec<Entry> = read_dir(dir)
let mut entries: Vec<Entry> = read_dir(dir, None)
.expect("list")
.collect::<io::Result<_>>()
.expect("entries");
@@ -677,11 +902,40 @@ mod tests {
assert_eq!(names, ["data.bin", "sub"]);
assert_eq!(entries[0].kind(), Kind::File);
assert_eq!(entries[0].apparent(), 100_000);
assert_eq!(entries[0].path(), temp.path().join("data.bin"));
assert_eq!(entries[0].path(temp.path()), temp.path().join("data.bin"));
assert_eq!(entries[1].kind(), Kind::Directory);
assert!(entries[0].modified() > 0, "written just now");
}
#[test]
fn a_name_that_is_not_text_is_shown_lossy_and_still_opens() {
use std::os::windows::ffi::OsStringExt as _;
let temp = TempDir::new().expect("tempdir");
// An unpaired surrogate: NTFS takes it, text cannot hold it.
let raw =
OsString::from_wide(&[u16::from(b'a'), 0xD800, u16::from(b'b')]);
fs::write(temp.path().join(&raw), b"x").expect("write");
let entries = listed(temp.path());
let [entry] = &entries[..] else {
panic!("one entry: {}", entries.len());
};
assert_eq!(entry.name(), "a\u{FFFD}b");
assert_eq!(entry.file_name(), raw);
assert!(fs::metadata(entry.path(temp.path())).is_ok());
}
#[test]
fn only_a_local_drive_gives_a_walk_one_volume() {
let temp = TempDir::new().expect("tempdir");
let canonical = temp.path().canonicalize().expect("canonical");
assert!(walk_volume(&canonical).is_some(), "{}", canonical.display());
// A share's DFS links lead to other volumes; nothing is asked.
for share in [r"\\server\share\dir", r"\\?\UNC\server\share\dir"] {
assert_eq!(walk_volume(Path::new(share)), None, "{share}");
}
}
#[test]
fn the_allocation_is_whole_clusters_of_the_data() {
let temp = TempDir::new().expect("tempdir");
@@ -746,11 +1000,15 @@ mod tests {
};
assert_eq!(kind("junction"), Some(Kind::Link));
assert_eq!(kind("target"), Some(Kind::Directory));
let through: Vec<OsString> = listed(&junction)
let through: Vec<Box<str>> = listed(&junction)
.into_iter()
.map(|entry| entry.name)
.collect();
assert_eq!(through, ["inside.bin"], "a walk that enters one follows");
assert_eq!(
&*through[0], "inside.bin",
"a walk that enters one follows"
);
assert_eq!(through.len(), 1);
}
#[test]
@@ -794,6 +1052,7 @@ mod tests {
drive.display()
);
assert!(!is_mount_point(temp.path()));
assert!(!file_table_readable(temp.path()), "a folder is walked");
assert!(!is_mount_point(drive), "a drive is a root, not a folder");
}