Skip to main content

nativeview_engine/loader/
staging.rs

1//! Private-copy dynamic library staging and digest-validated in-place load claims.
2
3use std::io::Read;
4use std::path::{Path, PathBuf};
5use std::sync::Mutex;
6use std::sync::atomic::{AtomicU64, Ordering};
7
8use libloading::Library;
9use nativeview_abi::{NvGetInterfaceFn, Xxh64Hasher};
10
11use super::LoaderError;
12
13static STAGED_COPY_SEQ: AtomicU64 = AtomicU64::new(1);
14static TOTAL_STAGED_LOADS: AtomicU64 = AtomicU64::new(0);
15
16/// Whether [`StagedDylib`] loads a private copy (desktop) or the file in place (mobile).
17///
18/// Android (API 29+ SELinux `execute_no_trans` / W^X) only executes code from the APK's
19/// `nativeLibraryDir`, and `std::env::temp_dir()` there (`/data/local/tmp`) is not app-writable;
20/// iOS only loads signed images from the bundle. Mobile hot reload therefore relies on the dev
21/// tooling pushing a uniquely named (versioned) library per generation, or on an app-private,
22/// loadable staging root in [`MODULE_STAGE_DIR_ENV`] (Android `Context.getCodeCacheDir()`).
23pub const STAGES_PRIVATE_COPY: bool = !cfg!(any(target_os = "android", target_os = "ios"));
24
25/// Environment variable naming the staging root (instead of `std::env::temp_dir()`); set, it
26/// stages on every platform.
27pub const MODULE_STAGE_DIR_ENV: &str = "NV_MODULE_STAGE_DIR";
28
29/// Where staged copies go: [`MODULE_STAGE_DIR_ENV`], else the temp dir when
30/// [`STAGES_PRIVATE_COPY`]; `None` loads in place.
31fn stage_root() -> Option<PathBuf> {
32    match std::env::var_os(MODULE_STAGE_DIR_ENV).filter(|v| !v.is_empty()) {
33        Some(root) => Some(PathBuf::from(root)),
34        None => STAGES_PRIVATE_COPY.then(std::env::temp_dir),
35    }
36}
37
38/// Returns `true` when `path` points to a file inside a macOS `<Name>.app/Contents/Frameworks/`
39/// bundle directory (checked lexically after collapsing `.` and `..` components).
40pub(crate) fn is_macos_app_bundle_frameworks_path(path: &Path) -> bool {
41    use std::ffi::OsStr;
42    use std::path::Component;
43
44    let mut normals: Vec<&OsStr> = Vec::new();
45    let mut ends_with_normal = false;
46    for comp in path.components() {
47        match comp {
48            Component::Normal(s) => {
49                normals.push(s);
50                ends_with_normal = true;
51            }
52            Component::CurDir => {}
53            Component::ParentDir => {
54                normals.pop();
55                ends_with_normal = false;
56            }
57            Component::RootDir | Component::Prefix(_) => {
58                normals.clear();
59                ends_with_normal = false;
60            }
61        }
62    }
63    if !ends_with_normal || normals.len() < 4 {
64        return false;
65    }
66    let parent = &normals[..normals.len() - 1];
67    parent.windows(3).any(|w| {
68        let app_ok = w[0].to_str().is_some_and(|s| {
69            s.len() > 4 && s.as_bytes()[s.len() - 4..].eq_ignore_ascii_case(b".app")
70        });
71        app_ok && w[1] == OsStr::new("Contents") && w[2] == OsStr::new("Frameworks")
72    })
73}
74
75enum LoadStrategy {
76    StageCopy(PathBuf),
77    InPlace { resolved: Option<PathBuf> },
78}
79
80/// Effective staging strategy for `dylib_path`: respects `env_stage_dir` ([`MODULE_STAGE_DIR_ENV`])
81/// first, loads immutable macOS `.app/Contents/Frameworks/` dylibs in place (canonicalizing once
82/// so `InPlaceClaim` does not repeat the syscall), and otherwise delegates to [`stage_root`].
83fn resolve_load_strategy(dylib_path: &Path, env_stage_dir: Option<&std::ffi::OsStr>) -> LoadStrategy {
84    if let Some(root) = env_stage_dir.filter(|v| !v.is_empty()) {
85        return LoadStrategy::StageCopy(PathBuf::from(root));
86    }
87    if cfg!(target_os = "macos") {
88        let resolved = std::fs::canonicalize(dylib_path).ok();
89        let check_path = resolved.as_deref().unwrap_or(dylib_path);
90        if is_macos_app_bundle_frameworks_path(check_path) {
91            return LoadStrategy::InPlace { resolved };
92        }
93    }
94    match STAGES_PRIVATE_COPY.then(std::env::temp_dir) {
95        Some(root) => LoadStrategy::StageCopy(root),
96        None => LoadStrategy::InPlace { resolved: None },
97    }
98}
99
100/// The private directory staged copies for `subdir` go to (`<root>/<subdir>-<euid>` on unix, so
101/// users sharing `/tmp` never collide; `temp_dir()` is already per user on Windows); `None` when
102/// loading in place.
103pub fn staging_dir(subdir: &str) -> Option<PathBuf> {
104    stage_root().map(|root| staging_dir_in(&root, subdir))
105}
106
107fn staging_dir_in(root: &Path, subdir: &str) -> PathBuf {
108    #[cfg(unix)]
109    // SAFETY: `geteuid` has no preconditions and cannot fail.
110    return root.join(format!("{subdir}-{}", unsafe { libc::geteuid() }));
111    #[cfg(not(unix))]
112    return root.join(subdir);
113}
114
115/// `(file_len, xxh64)` of a dylib's raw bytes read directly from its open file descriptor.
116#[derive(Clone, Copy, Debug, PartialEq, Eq)]
117struct FileDigest {
118    len: u64,
119    xxh64: u64,
120}
121
122fn hash_open_file(file: &mut std::fs::File) -> std::io::Result<FileDigest> {
123    let mut hasher = Xxh64Hasher::new(0);
124    let mut buf = [0u8; 16 * 1024];
125    let mut len = 0u64;
126    loop {
127        match file.read(&mut buf) {
128            Ok(0) => break,
129            Ok(n) => {
130                len = len.saturating_add(n as u64);
131                hasher.update(&buf[..n]);
132            }
133            Err(err) if err.kind() == std::io::ErrorKind::Interrupted => continue,
134            Err(err) => return Err(err),
135        }
136    }
137    Ok(FileDigest { len, xxh64: hasher.digest() })
138}
139
140struct InPlaceEntry {
141    /// `(device, inode)` from `fstat` on the open fd on Unix (`None` on non-Unix).
142    inode: Option<(u64, u64)>,
143    /// Canonical (or absolute/fallback) path resolved before opening and passed to `Library::new`.
144    resolved_path: PathBuf,
145    digest: FileDigest,
146    /// Unsealed in-flight claims sharing this exact `(inode, resolved_path, digest)` entry.
147    pending: usize,
148    /// `true` once `Library::new` mapped this image (kept for process lifetime).
149    sealed: bool,
150}
151
152/// Files claimed for in-place loading in this process, keyed by `(dev, ino)` and resolved path
153/// together with `(file_len, xxh64)`. Re-opening an unchanged bundled library (Activity recreation,
154/// multi-surface open, `detachApp()` -> `attachApp()`) is allowed; attempting to reload an inode
155/// or resolved path whose bytes changed since an earlier load is rejected because `RTLD_NODELETE`
156/// platforms (iOS/macOS dyld, Android Bionic, musl) would silently execute the old mapped image.
157static IN_PLACE_FILES: Mutex<Vec<InPlaceEntry>> = Mutex::new(Vec::new());
158
159/// Reservation for an in-place load. Dropping before [`Self::seal`] rolls it back (a failed
160/// `dlopen` never mapped the image); after [`Self::seal`] the recorded digest stays sealed for the
161/// lifetime of the process so only unchanged bytes can re-open that inode or resolved path.
162struct InPlaceClaim {
163    inode: Option<(u64, u64)>,
164    resolved_path: PathBuf,
165    digest: FileDigest,
166    sealed: bool,
167}
168
169impl InPlaceClaim {
170    #[cfg(all(test, unix))]
171    fn new(path: &Path) -> Result<Self, LoaderError> {
172        Self::new_with_resolved(path, None)
173    }
174
175    fn new_with_resolved(path: &Path, pre_resolved: Option<PathBuf>) -> Result<Self, LoaderError> {
176        let resolved_path = pre_resolved.unwrap_or_else(|| {
177            std::fs::canonicalize(path)
178                .or_else(|_| std::path::absolute(path))
179                .unwrap_or_else(|_| path.to_path_buf())
180        });
181        let mut file = std::fs::File::open(&resolved_path).map_err(LoaderError::Io)?;
182        let meta = file.metadata().map_err(LoaderError::Io)?;
183        #[cfg(unix)]
184        let inode = {
185            use std::os::unix::fs::MetadataExt;
186            Some((meta.dev(), meta.ino()))
187        };
188        #[cfg(not(unix))]
189        let inode = {
190            let _ = meta;
191            None
192        };
193        let digest = hash_open_file(&mut file).map_err(LoaderError::Io)?;
194
195        let mut loaded = IN_PLACE_FILES.lock().unwrap_or_else(std::sync::PoisonError::into_inner);
196        for entry in loaded.iter() {
197            let same_inode = inode.is_some() && entry.inode == inode;
198            let same_path = entry.resolved_path == resolved_path;
199            if (same_inode || same_path) && entry.digest != digest {
200                return Err(LoaderError::AlreadyLoadedInPlace(resolved_path));
201            }
202        }
203        if let Some(existing) = loaded.iter_mut().find(|e| {
204            e.inode == inode && e.resolved_path == resolved_path && e.digest == digest
205        }) {
206            existing.pending += 1;
207        } else {
208            loaded.push(InPlaceEntry {
209                inode,
210                resolved_path: resolved_path.clone(),
211                digest,
212                pending: 1,
213                sealed: false,
214            });
215        }
216        Ok(Self { inode, resolved_path, digest, sealed: false })
217    }
218
219    fn resolved_path(&self) -> &Path {
220        &self.resolved_path
221    }
222
223    /// Seals the recorded digest for the lifetime of the process once `dlopen` mapped the file.
224    fn seal(&mut self) {
225        if self.sealed {
226            return;
227        }
228        self.sealed = true;
229        let mut loaded = IN_PLACE_FILES.lock().unwrap_or_else(std::sync::PoisonError::into_inner);
230        if let Some(entry) = loaded.iter_mut().find(|e| {
231            e.inode == self.inode
232                && e.resolved_path == self.resolved_path
233                && e.digest == self.digest
234        }) {
235            entry.sealed = true;
236            entry.pending = entry.pending.saturating_sub(1);
237        }
238    }
239}
240
241impl Drop for InPlaceClaim {
242    fn drop(&mut self) {
243        if self.sealed {
244            return;
245        }
246        let mut loaded = IN_PLACE_FILES.lock().unwrap_or_else(std::sync::PoisonError::into_inner);
247        if let Some(at) = loaded.iter().position(|e| {
248            e.inode == self.inode
249                && e.resolved_path == self.resolved_path
250                && e.digest == self.digest
251        }) {
252            loaded[at].pending = loaded[at].pending.saturating_sub(1);
253            if !loaded[at].sealed && loaded[at].pending == 0 {
254                loaded.swap_remove(at);
255            }
256        }
257    }
258}
259
260/// Canonical RAII dynamic-library loader. On desktop it stages a unique copy in a private
261/// (`0700`, per-user, exclusively created) staging directory before calling `dlopen` (a rebuilt
262/// file at the same path always runs new code; no Windows DLL locks) and unloads before removing
263/// the copy. On Android / iOS it loads the file in place ([`STAGES_PRIVATE_COPY`]) unless
264/// [`MODULE_STAGE_DIR_ENV`] names a staging root, permitting unchanged bundle re-opens while
265/// refusing reloads whose bytes changed on disk.
266pub struct StagedDylib {
267    lib: Option<Library>,
268    get_interface: NvGetInterfaceFn,
269    loaded_path: PathBuf,
270    /// `true` when `loaded_path` is our private copy (removed after unloading).
271    owns_copy: bool,
272    /// Digest-validated claim sealed once `dlopen` maps an in-place file.
273    _in_place: Option<InPlaceClaim>,
274}
275
276/// Returns `true` iff `symbol` is `"nv_get_interface"` or `"nv_get_interface_"` followed by
277/// one or more ASCII `[A-Za-z0-9_]` characters (never embedded NULs or arbitrary process symbols).
278pub fn is_valid_nv_interface_symbol(symbol: &str) -> bool {
279    if symbol == "nv_get_interface" {
280        return true;
281    }
282    let Some(suffix) = symbol.strip_prefix("nv_get_interface_") else {
283        return false;
284    };
285    !suffix.is_empty() && suffix.bytes().all(|b| b.is_ascii_alphanumeric() || b == b'_')
286}
287
288fn symbol_c_bytes(symbol: &str) -> Vec<u8> {
289    let mut bytes = Vec::with_capacity(symbol.len() + 1);
290    bytes.extend_from_slice(symbol.as_bytes());
291    bytes.push(0);
292    bytes
293}
294
295/// Resolves a validated `nv_get_interface*` symbol from the running process image.
296pub fn resolve_in_process_symbol(symbol: &str) -> Result<NvGetInterfaceFn, LoaderError> {
297    if !is_valid_nv_interface_symbol(symbol) {
298        return Err(LoaderError::InvalidSymbol);
299    }
300    let sym_nul = symbol_c_bytes(symbol);
301    #[cfg(unix)]
302    {
303        // SAFETY: `sym_nul` is NUL-terminated with no interior NULs (`is_valid_nv_interface_symbol`).
304        let ptr = unsafe { libc::dlsym(libc::RTLD_DEFAULT, sym_nul.as_ptr().cast()) };
305        if ptr.is_null() {
306            return Err(LoaderError::MissingSymbol);
307        }
308        const {
309            assert!(
310                core::mem::size_of::<*mut libc::c_void>()
311                    == core::mem::size_of::<NvGetInterfaceFn>()
312            );
313        }
314        // SAFETY: Non-null `ptr` was resolved from a validated `nv_get_interface*` C ABI export.
315        Ok(unsafe { core::mem::transmute::<*mut libc::c_void, NvGetInterfaceFn>(ptr) })
316    }
317    #[cfg(windows)]
318    {
319        let lib = libloading::os::windows::Library::this().map_err(LoaderError::Load)?;
320        // SAFETY: `symbol` is validated to match `nv_get_interface(_[A-Za-z0-9_]+)?`.
321        let sym = unsafe { lib.get::<NvGetInterfaceFn>(sym_nul.as_slice()) }
322            .map_err(LoaderError::MissingEntry)?;
323        Ok(*sym)
324    }
325    #[cfg(not(any(unix, windows)))]
326    {
327        let _ = sym_nul;
328        Err(LoaderError::MissingSymbol)
329    }
330}
331
332impl StagedDylib {
333    pub fn load(dylib_path: &Path, subdir: &str, label: &str) -> Result<Self, LoaderError> {
334        Self::load_symbol(dylib_path, "nv_get_interface", subdir, label)
335    }
336
337    pub fn load_symbol(
338        dylib_path: &Path,
339        symbol: &str,
340        subdir: &str,
341        label: &str,
342    ) -> Result<Self, LoaderError> {
343        if !is_valid_nv_interface_symbol(symbol) {
344            return Err(LoaderError::InvalidSymbol);
345        }
346        let env_dir = std::env::var_os(MODULE_STAGE_DIR_ENV);
347        Self::load_with_strategy(
348            dylib_path,
349            symbol,
350            resolve_load_strategy(dylib_path, env_dir.as_deref()),
351            subdir,
352            label,
353        )
354    }
355
356    #[cfg(all(test, unix))]
357    fn load_with_root(
358        dylib_path: &Path,
359        root: Option<&Path>,
360        subdir: &str,
361        label: &str,
362    ) -> Result<Self, LoaderError> {
363        let strategy = match root {
364            Some(r) => LoadStrategy::StageCopy(r.to_path_buf()),
365            None => LoadStrategy::InPlace { resolved: None },
366        };
367        Self::load_with_strategy(dylib_path, "nv_get_interface", strategy, subdir, label)
368    }
369
370    fn load_with_strategy(
371        dylib_path: &Path,
372        symbol: &str,
373        strategy: LoadStrategy,
374        subdir: &str,
375        label: &str,
376    ) -> Result<Self, LoaderError> {
377        let sym_nul = symbol_c_bytes(symbol);
378        let (loaded_path, owns_copy, mut in_place) = match strategy {
379            LoadStrategy::StageCopy(root) => {
380                (stage_private_copy(&root, dylib_path, subdir, label)?, true, None)
381            }
382            LoadStrategy::InPlace { resolved } => {
383                let claim = InPlaceClaim::new_with_resolved(dylib_path, resolved)?;
384                (claim.resolved_path().to_path_buf(), false, Some(claim))
385            }
386        };
387        let discard = |path: &Path| {
388            if owns_copy {
389                let _ = std::fs::remove_file(path);
390            }
391        };
392        // SAFETY: Loading an NV app `cdylib` via `libloading`.
393        let lib = match unsafe { Library::new(&loaded_path) } {
394            Ok(lib) => {
395                // The OS loader has mapped this image; seal the digest-based claim for this
396                // process even if symbol lookup fails or this handle is later dropped (`RTLD_NODELETE`).
397                if let Some(claim) = in_place.as_mut() {
398                    claim.seal();
399                }
400                lib
401            }
402            Err(err) => {
403                discard(&loaded_path);
404                return Err(LoaderError::Load(err));
405            }
406        };
407        // SAFETY: `symbol` is validated to match `nv_get_interface(_[A-Za-z0-9_]+)?`.
408        let get_interface: NvGetInterfaceFn = match unsafe {
409            lib.get::<NvGetInterfaceFn>(sym_nul.as_slice())
410        } {
411            Ok(sym) => *sym,
412            Err(err) => {
413                drop(lib);
414                discard(&loaded_path);
415                return Err(LoaderError::MissingEntry(err));
416            }
417        };
418        TOTAL_STAGED_LOADS.fetch_add(1, Ordering::Relaxed);
419        Ok(Self {
420            lib: Some(lib),
421            get_interface,
422            loaded_path,
423            owns_copy,
424            _in_place: in_place,
425        })
426    }
427
428    /// Process-wide count of successful `StagedDylib::load` operations (used to verify
429    /// `[INV:multi-surface-shared-dylib]` — N surfaces sharing one `NvAppModule` increment this
430    /// counter by exactly 1 per reload generation).
431    #[inline]
432    pub fn total_staged_loads() -> u64 {
433        TOTAL_STAGED_LOADS.load(Ordering::Relaxed)
434    }
435
436    pub fn get_interface(&self) -> NvGetInterfaceFn {
437        self.get_interface
438    }
439
440    /// The file the OS loaded: the private staged copy on desktop, the resolved source path on mobile.
441    pub fn loaded_copy_path(&self) -> &Path {
442        &self.loaded_path
443    }
444}
445
446impl Drop for StagedDylib {
447    fn drop(&mut self) {
448        // Unload the dynamic library before removing the temporary copy so Windows
449        // releases the OS file lock prior to deletion.
450        drop(self.lib.take());
451        if self.owns_copy {
452            let _ = std::fs::remove_file(&self.loaded_path);
453        }
454    }
455}
456
457/// Copies `dylib_path` into [`staging_dir_in`] under a unique name.
458///
459/// On Unix, the directory is opened once with `O_DIRECTORY | O_NOFOLLOW | O_CLOEXEC`, verified
460/// via `fstat` (`S_ISDIR`, `st_uid == geteuid()`), tightened via `fchmod(fd, 0o700)`, and the
461/// copy is created exclusively via `openat(dir_fd, name, O_WRONLY | O_CREAT | O_EXCL | O_NOFOLLOW
462/// | O_CLOEXEC, 0o600)`, closing all path-based TOCTOU symlink races.
463fn stage_private_copy(
464    root: &Path,
465    dylib_path: &Path,
466    subdir: &str,
467    label: &str,
468) -> Result<PathBuf, LoaderError> {
469    /// Fresh names tried when a stale copy (a crashed process with a recycled pid) holds one.
470    const MAX_NAME_ATTEMPTS: u32 = 16;
471    let ext = dylib_path
472        .extension()
473        .and_then(|e| e.to_str())
474        .unwrap_or(std::env::consts::DLL_EXTENSION);
475    let stem = dylib_path
476        .file_stem()
477        .and_then(|s| s.to_str())
478        .unwrap_or("nv_app");
479    let dir = staging_dir_in(root, subdir);
480    let mut src = std::fs::File::open(dylib_path).map_err(LoaderError::Io)?;
481
482    #[cfg(unix)]
483    {
484        use std::ffi::CString;
485        use std::os::fd::{AsRawFd, FromRawFd};
486
487        let dir_fd = open_private_dir(&dir).map_err(LoaderError::Io)?;
488        let mut attempt = 0u32;
489        let (file_name, c_name, mut dst) = loop {
490            let seq = STAGED_COPY_SEQ.fetch_add(1, Ordering::Relaxed);
491            let file_name = format!("{stem}_{label}_{}_{seq}.{ext}", std::process::id());
492            if file_name.contains('/') {
493                return Err(LoaderError::Io(std::io::Error::new(
494                    std::io::ErrorKind::InvalidInput,
495                    format!("staged library filename contains path separator: {file_name}"),
496                )));
497            }
498            let c_name = CString::new(file_name.as_str()).map_err(|_| {
499                LoaderError::Io(std::io::Error::new(
500                    std::io::ErrorKind::InvalidInput,
501                    "staged library filename contains interior NUL",
502                ))
503            })?;
504            // SAFETY: `dir_fd` is a verified private directory fd and `c_name` is a single
505            // NUL-terminated entry name; `mode` is promoted to `c_uint` for C variadic `openat`.
506            let fd = unsafe {
507                libc::openat(
508                    dir_fd.as_raw_fd(),
509                    c_name.as_ptr(),
510                    libc::O_WRONLY | libc::O_CREAT | libc::O_EXCL | libc::O_NOFOLLOW | libc::O_CLOEXEC,
511                    0o600 as libc::c_uint,
512                )
513            };
514            if fd >= 0 {
515                // SAFETY: `fd` is a freshly opened, exclusive file descriptor owned by this call.
516                let file = unsafe { std::fs::File::from_raw_fd(fd) };
517                break (file_name, c_name, file);
518            }
519            let err = std::io::Error::last_os_error();
520            if err.kind() == std::io::ErrorKind::AlreadyExists && attempt + 1 < MAX_NAME_ATTEMPTS {
521                attempt += 1;
522            } else {
523                return Err(LoaderError::Io(err));
524            }
525        };
526        if let Err(err) = std::io::copy(&mut src, &mut dst).and_then(|_| dst.sync_all()) {
527            drop(dst);
528            // SAFETY: `dir_fd` and `c_name` refer to the entry just created above.
529            let _ = unsafe { libc::unlinkat(dir_fd.as_raw_fd(), c_name.as_ptr(), 0) };
530            return Err(LoaderError::Io(err));
531        }
532        Ok(dir.join(file_name))
533    }
534
535    #[cfg(not(unix))]
536    {
537        let dir = ensure_private_dir_non_unix(dir).map_err(LoaderError::Io)?;
538        let mut options = std::fs::OpenOptions::new();
539        options.write(true).create_new(true);
540        let mut attempt = 0u32;
541        let (copy, mut dst) = loop {
542            let seq = STAGED_COPY_SEQ.fetch_add(1, Ordering::Relaxed);
543            let copy = dir.join(format!("{stem}_{label}_{}_{seq}.{ext}", std::process::id()));
544            match options.open(&copy) {
545                Ok(file) => break (copy, file),
546                Err(err) if err.kind() == std::io::ErrorKind::AlreadyExists && attempt + 1 < MAX_NAME_ATTEMPTS => {
547                    attempt += 1;
548                }
549                Err(err) => return Err(LoaderError::Io(err)),
550            }
551        };
552        if let Err(err) = std::io::copy(&mut src, &mut dst).and_then(|_| dst.sync_all()) {
553            drop(dst);
554            let _ = std::fs::remove_file(&copy);
555            return Err(LoaderError::Io(err));
556        }
557        Ok(copy)
558    }
559}
560
561/// Atomically creates (if absent), opens without following symlinks, verifies (`S_ISDIR` and
562/// `st_uid == geteuid()`), and `fchmod(0o700)`s `dir`, returning the pinned directory fd so
563/// subsequent `openat` calls cannot race a symlink swap.
564#[cfg(unix)]
565fn open_private_dir(dir: &Path) -> std::io::Result<std::os::fd::OwnedFd> {
566    use std::ffi::CString;
567    use std::os::fd::{AsRawFd, FromRawFd, OwnedFd};
568    use std::os::unix::ffi::OsStrExt;
569
570    let c_dir = CString::new(dir.as_os_str().as_bytes()).map_err(|_| {
571        std::io::Error::new(std::io::ErrorKind::InvalidInput, "staging dir contains interior NUL")
572    })?;
573    // SAFETY: `c_dir` is a valid NUL-terminated path; `EEXIST` is handled below via `open`.
574    if unsafe { libc::mkdir(c_dir.as_ptr(), 0o700) } != 0 {
575        let err = std::io::Error::last_os_error();
576        if err.kind() != std::io::ErrorKind::AlreadyExists {
577            return Err(err);
578        }
579    }
580    // SAFETY: `c_dir` is NUL-terminated; `O_DIRECTORY | O_NOFOLLOW` refuses symlinks and files.
581    let fd = unsafe {
582        libc::open(
583            c_dir.as_ptr(),
584            libc::O_RDONLY | libc::O_DIRECTORY | libc::O_NOFOLLOW | libc::O_CLOEXEC,
585        )
586    };
587    if fd < 0 {
588        return Err(std::io::Error::last_os_error());
589    }
590    // SAFETY: `fd` is a valid newly opened directory descriptor.
591    let dir_fd = unsafe { OwnedFd::from_raw_fd(fd) };
592
593    let mut st = std::mem::MaybeUninit::<libc::stat>::uninit();
594    // SAFETY: `dir_fd` is live and `st` points to writable `libc::stat` storage.
595    if unsafe { libc::fstat(dir_fd.as_raw_fd(), st.as_mut_ptr()) } != 0 {
596        return Err(std::io::Error::last_os_error());
597    }
598    // SAFETY: `fstat` succeeded and initialized `st`.
599    let st = unsafe { st.assume_init() };
600    // 32-bit Android (`armv7`, `i686`) types `st_mode` as `u32` and `S_IFMT`/`S_IFDIR` as `u16`.
601    #[allow(clippy::useless_conversion)]
602    let is_dir = (u32::from(st.st_mode) & u32::from(libc::S_IFMT)) == u32::from(libc::S_IFDIR);
603    if !is_dir {
604        return Err(std::io::Error::other(format!(
605            "staging path {} is not a directory",
606            dir.display()
607        )));
608    }
609    // SAFETY: `geteuid` has no preconditions and cannot fail.
610    let euid = unsafe { libc::geteuid() };
611    if st.st_uid != euid {
612        return Err(std::io::Error::new(
613            std::io::ErrorKind::PermissionDenied,
614            format!("staging dir {} is owned by uid {}, not {euid}", dir.display(), st.st_uid),
615        ));
616    }
617    // SAFETY: `dir_fd` is a verified directory owned by the effective user.
618    if unsafe { libc::fchmod(dir_fd.as_raw_fd(), 0o700) } != 0 {
619        return Err(std::io::Error::last_os_error());
620    }
621    Ok(dir_fd)
622}
623
624#[cfg(not(unix))]
625fn ensure_private_dir_non_unix(dir: PathBuf) -> std::io::Result<PathBuf> {
626    match std::fs::DirBuilder::new().create(&dir) {
627        Ok(()) => return Ok(dir),
628        Err(err) if err.kind() != std::io::ErrorKind::AlreadyExists => return Err(err),
629        Err(_) => {}
630    }
631    let meta = std::fs::symlink_metadata(&dir)?;
632    if !meta.file_type().is_dir() {
633        return Err(std::io::Error::other(format!(
634            "staging path {} is not a directory",
635            dir.display()
636        )));
637    }
638    Ok(dir)
639}
640
641#[cfg(all(test, unix))]
642#[path = "staging_tests.rs"]
643mod staging_tests;