nativeview-engine 0.1.0-rc.1

Framework-agnostic scene engine traits, hot-reload cdylib loader, and Frame-0 snapshot codecs.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
//! Private-copy dynamic library staging and digest-validated in-place load claims.

use std::io::Read;
use std::path::{Path, PathBuf};
use std::sync::Mutex;
use std::sync::atomic::{AtomicU64, Ordering};

use libloading::Library;
use nativeview_abi::{NvGetInterfaceFn, Xxh64Hasher};

use super::LoaderError;

static STAGED_COPY_SEQ: AtomicU64 = AtomicU64::new(1);
static TOTAL_STAGED_LOADS: AtomicU64 = AtomicU64::new(0);

/// Whether [`StagedDylib`] loads a private copy (desktop) or the file in place (mobile).
///
/// Android (API 29+ SELinux `execute_no_trans` / W^X) only executes code from the APK's
/// `nativeLibraryDir`, and `std::env::temp_dir()` there (`/data/local/tmp`) is not app-writable;
/// iOS only loads signed images from the bundle. Mobile hot reload therefore relies on the dev
/// tooling pushing a uniquely named (versioned) library per generation, or on an app-private,
/// loadable staging root in [`MODULE_STAGE_DIR_ENV`] (Android `Context.getCodeCacheDir()`).
pub const STAGES_PRIVATE_COPY: bool = !cfg!(any(target_os = "android", target_os = "ios"));

/// Environment variable naming the staging root (instead of `std::env::temp_dir()`); set, it
/// stages on every platform.
pub const MODULE_STAGE_DIR_ENV: &str = "NV_MODULE_STAGE_DIR";

/// Where staged copies go: [`MODULE_STAGE_DIR_ENV`], else the temp dir when
/// [`STAGES_PRIVATE_COPY`]; `None` loads in place.
fn stage_root() -> Option<PathBuf> {
    match std::env::var_os(MODULE_STAGE_DIR_ENV).filter(|v| !v.is_empty()) {
        Some(root) => Some(PathBuf::from(root)),
        None => STAGES_PRIVATE_COPY.then(std::env::temp_dir),
    }
}

/// Returns `true` when `path` points to a file inside a macOS `<Name>.app/Contents/Frameworks/`
/// bundle directory (checked lexically after collapsing `.` and `..` components).
pub(crate) fn is_macos_app_bundle_frameworks_path(path: &Path) -> bool {
    use std::ffi::OsStr;
    use std::path::Component;

    let mut normals: Vec<&OsStr> = Vec::new();
    let mut ends_with_normal = false;
    for comp in path.components() {
        match comp {
            Component::Normal(s) => {
                normals.push(s);
                ends_with_normal = true;
            }
            Component::CurDir => {}
            Component::ParentDir => {
                normals.pop();
                ends_with_normal = false;
            }
            Component::RootDir | Component::Prefix(_) => {
                normals.clear();
                ends_with_normal = false;
            }
        }
    }
    if !ends_with_normal || normals.len() < 4 {
        return false;
    }
    let parent = &normals[..normals.len() - 1];
    parent.windows(3).any(|w| {
        let app_ok = w[0].to_str().is_some_and(|s| {
            s.len() > 4 && s.as_bytes()[s.len() - 4..].eq_ignore_ascii_case(b".app")
        });
        app_ok && w[1] == OsStr::new("Contents") && w[2] == OsStr::new("Frameworks")
    })
}

enum LoadStrategy {
    StageCopy(PathBuf),
    InPlace { resolved: Option<PathBuf> },
}

/// Effective staging strategy for `dylib_path`: respects `env_stage_dir` ([`MODULE_STAGE_DIR_ENV`])
/// first, loads immutable macOS `.app/Contents/Frameworks/` dylibs in place (canonicalizing once
/// so `InPlaceClaim` does not repeat the syscall), and otherwise delegates to [`stage_root`].
fn resolve_load_strategy(dylib_path: &Path, env_stage_dir: Option<&std::ffi::OsStr>) -> LoadStrategy {
    if let Some(root) = env_stage_dir.filter(|v| !v.is_empty()) {
        return LoadStrategy::StageCopy(PathBuf::from(root));
    }
    if cfg!(target_os = "macos") {
        let resolved = std::fs::canonicalize(dylib_path).ok();
        let check_path = resolved.as_deref().unwrap_or(dylib_path);
        if is_macos_app_bundle_frameworks_path(check_path) {
            return LoadStrategy::InPlace { resolved };
        }
    }
    match STAGES_PRIVATE_COPY.then(std::env::temp_dir) {
        Some(root) => LoadStrategy::StageCopy(root),
        None => LoadStrategy::InPlace { resolved: None },
    }
}

/// The private directory staged copies for `subdir` go to (`<root>/<subdir>-<euid>` on unix, so
/// users sharing `/tmp` never collide; `temp_dir()` is already per user on Windows); `None` when
/// loading in place.
pub fn staging_dir(subdir: &str) -> Option<PathBuf> {
    stage_root().map(|root| staging_dir_in(&root, subdir))
}

fn staging_dir_in(root: &Path, subdir: &str) -> PathBuf {
    #[cfg(unix)]
    // SAFETY: `geteuid` has no preconditions and cannot fail.
    return root.join(format!("{subdir}-{}", unsafe { libc::geteuid() }));
    #[cfg(not(unix))]
    return root.join(subdir);
}

/// `(file_len, xxh64)` of a dylib's raw bytes read directly from its open file descriptor.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
struct FileDigest {
    len: u64,
    xxh64: u64,
}

fn hash_open_file(file: &mut std::fs::File) -> std::io::Result<FileDigest> {
    let mut hasher = Xxh64Hasher::new(0);
    let mut buf = [0u8; 16 * 1024];
    let mut len = 0u64;
    loop {
        match file.read(&mut buf) {
            Ok(0) => break,
            Ok(n) => {
                len = len.saturating_add(n as u64);
                hasher.update(&buf[..n]);
            }
            Err(err) if err.kind() == std::io::ErrorKind::Interrupted => continue,
            Err(err) => return Err(err),
        }
    }
    Ok(FileDigest { len, xxh64: hasher.digest() })
}

struct InPlaceEntry {
    /// `(device, inode)` from `fstat` on the open fd on Unix (`None` on non-Unix).
    inode: Option<(u64, u64)>,
    /// Canonical (or absolute/fallback) path resolved before opening and passed to `Library::new`.
    resolved_path: PathBuf,
    digest: FileDigest,
    /// Unsealed in-flight claims sharing this exact `(inode, resolved_path, digest)` entry.
    pending: usize,
    /// `true` once `Library::new` mapped this image (kept for process lifetime).
    sealed: bool,
}

/// Files claimed for in-place loading in this process, keyed by `(dev, ino)` and resolved path
/// together with `(file_len, xxh64)`. Re-opening an unchanged bundled library (Activity recreation,
/// multi-surface open, `detachApp()` -> `attachApp()`) is allowed; attempting to reload an inode
/// or resolved path whose bytes changed since an earlier load is rejected because `RTLD_NODELETE`
/// platforms (iOS/macOS dyld, Android Bionic, musl) would silently execute the old mapped image.
static IN_PLACE_FILES: Mutex<Vec<InPlaceEntry>> = Mutex::new(Vec::new());

/// Reservation for an in-place load. Dropping before [`Self::seal`] rolls it back (a failed
/// `dlopen` never mapped the image); after [`Self::seal`] the recorded digest stays sealed for the
/// lifetime of the process so only unchanged bytes can re-open that inode or resolved path.
struct InPlaceClaim {
    inode: Option<(u64, u64)>,
    resolved_path: PathBuf,
    digest: FileDigest,
    sealed: bool,
}

impl InPlaceClaim {
    #[cfg(all(test, unix))]
    fn new(path: &Path) -> Result<Self, LoaderError> {
        Self::new_with_resolved(path, None)
    }

    fn new_with_resolved(path: &Path, pre_resolved: Option<PathBuf>) -> Result<Self, LoaderError> {
        let resolved_path = pre_resolved.unwrap_or_else(|| {
            std::fs::canonicalize(path)
                .or_else(|_| std::path::absolute(path))
                .unwrap_or_else(|_| path.to_path_buf())
        });
        let mut file = std::fs::File::open(&resolved_path).map_err(LoaderError::Io)?;
        let meta = file.metadata().map_err(LoaderError::Io)?;
        #[cfg(unix)]
        let inode = {
            use std::os::unix::fs::MetadataExt;
            Some((meta.dev(), meta.ino()))
        };
        #[cfg(not(unix))]
        let inode = {
            let _ = meta;
            None
        };
        let digest = hash_open_file(&mut file).map_err(LoaderError::Io)?;

        let mut loaded = IN_PLACE_FILES.lock().unwrap_or_else(std::sync::PoisonError::into_inner);
        for entry in loaded.iter() {
            let same_inode = inode.is_some() && entry.inode == inode;
            let same_path = entry.resolved_path == resolved_path;
            if (same_inode || same_path) && entry.digest != digest {
                return Err(LoaderError::AlreadyLoadedInPlace(resolved_path));
            }
        }
        if let Some(existing) = loaded.iter_mut().find(|e| {
            e.inode == inode && e.resolved_path == resolved_path && e.digest == digest
        }) {
            existing.pending += 1;
        } else {
            loaded.push(InPlaceEntry {
                inode,
                resolved_path: resolved_path.clone(),
                digest,
                pending: 1,
                sealed: false,
            });
        }
        Ok(Self { inode, resolved_path, digest, sealed: false })
    }

    fn resolved_path(&self) -> &Path {
        &self.resolved_path
    }

    /// Seals the recorded digest for the lifetime of the process once `dlopen` mapped the file.
    fn seal(&mut self) {
        if self.sealed {
            return;
        }
        self.sealed = true;
        let mut loaded = IN_PLACE_FILES.lock().unwrap_or_else(std::sync::PoisonError::into_inner);
        if let Some(entry) = loaded.iter_mut().find(|e| {
            e.inode == self.inode
                && e.resolved_path == self.resolved_path
                && e.digest == self.digest
        }) {
            entry.sealed = true;
            entry.pending = entry.pending.saturating_sub(1);
        }
    }
}

impl Drop for InPlaceClaim {
    fn drop(&mut self) {
        if self.sealed {
            return;
        }
        let mut loaded = IN_PLACE_FILES.lock().unwrap_or_else(std::sync::PoisonError::into_inner);
        if let Some(at) = loaded.iter().position(|e| {
            e.inode == self.inode
                && e.resolved_path == self.resolved_path
                && e.digest == self.digest
        }) {
            loaded[at].pending = loaded[at].pending.saturating_sub(1);
            if !loaded[at].sealed && loaded[at].pending == 0 {
                loaded.swap_remove(at);
            }
        }
    }
}

/// Canonical RAII dynamic-library loader. On desktop it stages a unique copy in a private
/// (`0700`, per-user, exclusively created) staging directory before calling `dlopen` (a rebuilt
/// file at the same path always runs new code; no Windows DLL locks) and unloads before removing
/// the copy. On Android / iOS it loads the file in place ([`STAGES_PRIVATE_COPY`]) unless
/// [`MODULE_STAGE_DIR_ENV`] names a staging root, permitting unchanged bundle re-opens while
/// refusing reloads whose bytes changed on disk.
pub struct StagedDylib {
    lib: Option<Library>,
    get_interface: NvGetInterfaceFn,
    loaded_path: PathBuf,
    /// `true` when `loaded_path` is our private copy (removed after unloading).
    owns_copy: bool,
    /// Digest-validated claim sealed once `dlopen` maps an in-place file.
    _in_place: Option<InPlaceClaim>,
}

/// Returns `true` iff `symbol` is `"nv_get_interface"` or `"nv_get_interface_"` followed by
/// one or more ASCII `[A-Za-z0-9_]` characters (never embedded NULs or arbitrary process symbols).
pub fn is_valid_nv_interface_symbol(symbol: &str) -> bool {
    if symbol == "nv_get_interface" {
        return true;
    }
    let Some(suffix) = symbol.strip_prefix("nv_get_interface_") else {
        return false;
    };
    !suffix.is_empty() && suffix.bytes().all(|b| b.is_ascii_alphanumeric() || b == b'_')
}

fn symbol_c_bytes(symbol: &str) -> Vec<u8> {
    let mut bytes = Vec::with_capacity(symbol.len() + 1);
    bytes.extend_from_slice(symbol.as_bytes());
    bytes.push(0);
    bytes
}

/// Resolves a validated `nv_get_interface*` symbol from the running process image.
pub fn resolve_in_process_symbol(symbol: &str) -> Result<NvGetInterfaceFn, LoaderError> {
    if !is_valid_nv_interface_symbol(symbol) {
        return Err(LoaderError::InvalidSymbol);
    }
    let sym_nul = symbol_c_bytes(symbol);
    #[cfg(unix)]
    {
        // SAFETY: `sym_nul` is NUL-terminated with no interior NULs (`is_valid_nv_interface_symbol`).
        let ptr = unsafe { libc::dlsym(libc::RTLD_DEFAULT, sym_nul.as_ptr().cast()) };
        if ptr.is_null() {
            return Err(LoaderError::MissingSymbol);
        }
        const {
            assert!(
                core::mem::size_of::<*mut libc::c_void>()
                    == core::mem::size_of::<NvGetInterfaceFn>()
            );
        }
        // SAFETY: Non-null `ptr` was resolved from a validated `nv_get_interface*` C ABI export.
        Ok(unsafe { core::mem::transmute::<*mut libc::c_void, NvGetInterfaceFn>(ptr) })
    }
    #[cfg(windows)]
    {
        let lib = libloading::os::windows::Library::this().map_err(LoaderError::Load)?;
        // SAFETY: `symbol` is validated to match `nv_get_interface(_[A-Za-z0-9_]+)?`.
        let sym = unsafe { lib.get::<NvGetInterfaceFn>(sym_nul.as_slice()) }
            .map_err(LoaderError::MissingEntry)?;
        Ok(*sym)
    }
    #[cfg(not(any(unix, windows)))]
    {
        let _ = sym_nul;
        Err(LoaderError::MissingSymbol)
    }
}

impl StagedDylib {
    pub fn load(dylib_path: &Path, subdir: &str, label: &str) -> Result<Self, LoaderError> {
        Self::load_symbol(dylib_path, "nv_get_interface", subdir, label)
    }

    pub fn load_symbol(
        dylib_path: &Path,
        symbol: &str,
        subdir: &str,
        label: &str,
    ) -> Result<Self, LoaderError> {
        if !is_valid_nv_interface_symbol(symbol) {
            return Err(LoaderError::InvalidSymbol);
        }
        let env_dir = std::env::var_os(MODULE_STAGE_DIR_ENV);
        Self::load_with_strategy(
            dylib_path,
            symbol,
            resolve_load_strategy(dylib_path, env_dir.as_deref()),
            subdir,
            label,
        )
    }

    #[cfg(all(test, unix))]
    fn load_with_root(
        dylib_path: &Path,
        root: Option<&Path>,
        subdir: &str,
        label: &str,
    ) -> Result<Self, LoaderError> {
        let strategy = match root {
            Some(r) => LoadStrategy::StageCopy(r.to_path_buf()),
            None => LoadStrategy::InPlace { resolved: None },
        };
        Self::load_with_strategy(dylib_path, "nv_get_interface", strategy, subdir, label)
    }

    fn load_with_strategy(
        dylib_path: &Path,
        symbol: &str,
        strategy: LoadStrategy,
        subdir: &str,
        label: &str,
    ) -> Result<Self, LoaderError> {
        let sym_nul = symbol_c_bytes(symbol);
        let (loaded_path, owns_copy, mut in_place) = match strategy {
            LoadStrategy::StageCopy(root) => {
                (stage_private_copy(&root, dylib_path, subdir, label)?, true, None)
            }
            LoadStrategy::InPlace { resolved } => {
                let claim = InPlaceClaim::new_with_resolved(dylib_path, resolved)?;
                (claim.resolved_path().to_path_buf(), false, Some(claim))
            }
        };
        let discard = |path: &Path| {
            if owns_copy {
                let _ = std::fs::remove_file(path);
            }
        };
        // SAFETY: Loading an NV app `cdylib` via `libloading`.
        let lib = match unsafe { Library::new(&loaded_path) } {
            Ok(lib) => {
                // The OS loader has mapped this image; seal the digest-based claim for this
                // process even if symbol lookup fails or this handle is later dropped (`RTLD_NODELETE`).
                if let Some(claim) = in_place.as_mut() {
                    claim.seal();
                }
                lib
            }
            Err(err) => {
                discard(&loaded_path);
                return Err(LoaderError::Load(err));
            }
        };
        // SAFETY: `symbol` is validated to match `nv_get_interface(_[A-Za-z0-9_]+)?`.
        let get_interface: NvGetInterfaceFn = match unsafe {
            lib.get::<NvGetInterfaceFn>(sym_nul.as_slice())
        } {
            Ok(sym) => *sym,
            Err(err) => {
                drop(lib);
                discard(&loaded_path);
                return Err(LoaderError::MissingEntry(err));
            }
        };
        TOTAL_STAGED_LOADS.fetch_add(1, Ordering::Relaxed);
        Ok(Self {
            lib: Some(lib),
            get_interface,
            loaded_path,
            owns_copy,
            _in_place: in_place,
        })
    }

    /// Process-wide count of successful `StagedDylib::load` operations (used to verify
    /// `[INV:multi-surface-shared-dylib]` — N surfaces sharing one `NvAppModule` increment this
    /// counter by exactly 1 per reload generation).
    #[inline]
    pub fn total_staged_loads() -> u64 {
        TOTAL_STAGED_LOADS.load(Ordering::Relaxed)
    }

    pub fn get_interface(&self) -> NvGetInterfaceFn {
        self.get_interface
    }

    /// The file the OS loaded: the private staged copy on desktop, the resolved source path on mobile.
    pub fn loaded_copy_path(&self) -> &Path {
        &self.loaded_path
    }
}

impl Drop for StagedDylib {
    fn drop(&mut self) {
        // Unload the dynamic library before removing the temporary copy so Windows
        // releases the OS file lock prior to deletion.
        drop(self.lib.take());
        if self.owns_copy {
            let _ = std::fs::remove_file(&self.loaded_path);
        }
    }
}

/// Copies `dylib_path` into [`staging_dir_in`] under a unique name.
///
/// On Unix, the directory is opened once with `O_DIRECTORY | O_NOFOLLOW | O_CLOEXEC`, verified
/// via `fstat` (`S_ISDIR`, `st_uid == geteuid()`), tightened via `fchmod(fd, 0o700)`, and the
/// copy is created exclusively via `openat(dir_fd, name, O_WRONLY | O_CREAT | O_EXCL | O_NOFOLLOW
/// | O_CLOEXEC, 0o600)`, closing all path-based TOCTOU symlink races.
fn stage_private_copy(
    root: &Path,
    dylib_path: &Path,
    subdir: &str,
    label: &str,
) -> Result<PathBuf, LoaderError> {
    /// Fresh names tried when a stale copy (a crashed process with a recycled pid) holds one.
    const MAX_NAME_ATTEMPTS: u32 = 16;
    let ext = dylib_path
        .extension()
        .and_then(|e| e.to_str())
        .unwrap_or(std::env::consts::DLL_EXTENSION);
    let stem = dylib_path
        .file_stem()
        .and_then(|s| s.to_str())
        .unwrap_or("nv_app");
    let dir = staging_dir_in(root, subdir);
    let mut src = std::fs::File::open(dylib_path).map_err(LoaderError::Io)?;

    #[cfg(unix)]
    {
        use std::ffi::CString;
        use std::os::fd::{AsRawFd, FromRawFd};

        let dir_fd = open_private_dir(&dir).map_err(LoaderError::Io)?;
        let mut attempt = 0u32;
        let (file_name, c_name, mut dst) = loop {
            let seq = STAGED_COPY_SEQ.fetch_add(1, Ordering::Relaxed);
            let file_name = format!("{stem}_{label}_{}_{seq}.{ext}", std::process::id());
            if file_name.contains('/') {
                return Err(LoaderError::Io(std::io::Error::new(
                    std::io::ErrorKind::InvalidInput,
                    format!("staged library filename contains path separator: {file_name}"),
                )));
            }
            let c_name = CString::new(file_name.as_str()).map_err(|_| {
                LoaderError::Io(std::io::Error::new(
                    std::io::ErrorKind::InvalidInput,
                    "staged library filename contains interior NUL",
                ))
            })?;
            // SAFETY: `dir_fd` is a verified private directory fd and `c_name` is a single
            // NUL-terminated entry name; `mode` is promoted to `c_uint` for C variadic `openat`.
            let fd = unsafe {
                libc::openat(
                    dir_fd.as_raw_fd(),
                    c_name.as_ptr(),
                    libc::O_WRONLY | libc::O_CREAT | libc::O_EXCL | libc::O_NOFOLLOW | libc::O_CLOEXEC,
                    0o600 as libc::c_uint,
                )
            };
            if fd >= 0 {
                // SAFETY: `fd` is a freshly opened, exclusive file descriptor owned by this call.
                let file = unsafe { std::fs::File::from_raw_fd(fd) };
                break (file_name, c_name, file);
            }
            let err = std::io::Error::last_os_error();
            if err.kind() == std::io::ErrorKind::AlreadyExists && attempt + 1 < MAX_NAME_ATTEMPTS {
                attempt += 1;
            } else {
                return Err(LoaderError::Io(err));
            }
        };
        if let Err(err) = std::io::copy(&mut src, &mut dst).and_then(|_| dst.sync_all()) {
            drop(dst);
            // SAFETY: `dir_fd` and `c_name` refer to the entry just created above.
            let _ = unsafe { libc::unlinkat(dir_fd.as_raw_fd(), c_name.as_ptr(), 0) };
            return Err(LoaderError::Io(err));
        }
        Ok(dir.join(file_name))
    }

    #[cfg(not(unix))]
    {
        let dir = ensure_private_dir_non_unix(dir).map_err(LoaderError::Io)?;
        let mut options = std::fs::OpenOptions::new();
        options.write(true).create_new(true);
        let mut attempt = 0u32;
        let (copy, mut dst) = loop {
            let seq = STAGED_COPY_SEQ.fetch_add(1, Ordering::Relaxed);
            let copy = dir.join(format!("{stem}_{label}_{}_{seq}.{ext}", std::process::id()));
            match options.open(&copy) {
                Ok(file) => break (copy, file),
                Err(err) if err.kind() == std::io::ErrorKind::AlreadyExists && attempt + 1 < MAX_NAME_ATTEMPTS => {
                    attempt += 1;
                }
                Err(err) => return Err(LoaderError::Io(err)),
            }
        };
        if let Err(err) = std::io::copy(&mut src, &mut dst).and_then(|_| dst.sync_all()) {
            drop(dst);
            let _ = std::fs::remove_file(&copy);
            return Err(LoaderError::Io(err));
        }
        Ok(copy)
    }
}

/// Atomically creates (if absent), opens without following symlinks, verifies (`S_ISDIR` and
/// `st_uid == geteuid()`), and `fchmod(0o700)`s `dir`, returning the pinned directory fd so
/// subsequent `openat` calls cannot race a symlink swap.
#[cfg(unix)]
fn open_private_dir(dir: &Path) -> std::io::Result<std::os::fd::OwnedFd> {
    use std::ffi::CString;
    use std::os::fd::{AsRawFd, FromRawFd, OwnedFd};
    use std::os::unix::ffi::OsStrExt;

    let c_dir = CString::new(dir.as_os_str().as_bytes()).map_err(|_| {
        std::io::Error::new(std::io::ErrorKind::InvalidInput, "staging dir contains interior NUL")
    })?;
    // SAFETY: `c_dir` is a valid NUL-terminated path; `EEXIST` is handled below via `open`.
    if unsafe { libc::mkdir(c_dir.as_ptr(), 0o700) } != 0 {
        let err = std::io::Error::last_os_error();
        if err.kind() != std::io::ErrorKind::AlreadyExists {
            return Err(err);
        }
    }
    // SAFETY: `c_dir` is NUL-terminated; `O_DIRECTORY | O_NOFOLLOW` refuses symlinks and files.
    let fd = unsafe {
        libc::open(
            c_dir.as_ptr(),
            libc::O_RDONLY | libc::O_DIRECTORY | libc::O_NOFOLLOW | libc::O_CLOEXEC,
        )
    };
    if fd < 0 {
        return Err(std::io::Error::last_os_error());
    }
    // SAFETY: `fd` is a valid newly opened directory descriptor.
    let dir_fd = unsafe { OwnedFd::from_raw_fd(fd) };

    let mut st = std::mem::MaybeUninit::<libc::stat>::uninit();
    // SAFETY: `dir_fd` is live and `st` points to writable `libc::stat` storage.
    if unsafe { libc::fstat(dir_fd.as_raw_fd(), st.as_mut_ptr()) } != 0 {
        return Err(std::io::Error::last_os_error());
    }
    // SAFETY: `fstat` succeeded and initialized `st`.
    let st = unsafe { st.assume_init() };
    // 32-bit Android (`armv7`, `i686`) types `st_mode` as `u32` and `S_IFMT`/`S_IFDIR` as `u16`.
    #[allow(clippy::useless_conversion)]
    let is_dir = (u32::from(st.st_mode) & u32::from(libc::S_IFMT)) == u32::from(libc::S_IFDIR);
    if !is_dir {
        return Err(std::io::Error::other(format!(
            "staging path {} is not a directory",
            dir.display()
        )));
    }
    // SAFETY: `geteuid` has no preconditions and cannot fail.
    let euid = unsafe { libc::geteuid() };
    if st.st_uid != euid {
        return Err(std::io::Error::new(
            std::io::ErrorKind::PermissionDenied,
            format!("staging dir {} is owned by uid {}, not {euid}", dir.display(), st.st_uid),
        ));
    }
    // SAFETY: `dir_fd` is a verified directory owned by the effective user.
    if unsafe { libc::fchmod(dir_fd.as_raw_fd(), 0o700) } != 0 {
        return Err(std::io::Error::last_os_error());
    }
    Ok(dir_fd)
}

#[cfg(not(unix))]
fn ensure_private_dir_non_unix(dir: PathBuf) -> std::io::Result<PathBuf> {
    match std::fs::DirBuilder::new().create(&dir) {
        Ok(()) => return Ok(dir),
        Err(err) if err.kind() != std::io::ErrorKind::AlreadyExists => return Err(err),
        Err(_) => {}
    }
    let meta = std::fs::symlink_metadata(&dir)?;
    if !meta.file_type().is_dir() {
        return Err(std::io::Error::other(format!(
            "staging path {} is not a directory",
            dir.display()
        )));
    }
    Ok(dir)
}

#[cfg(all(test, unix))]
#[path = "staging_tests.rs"]
mod staging_tests;