bun_sys 0.1.12

A Rust-native programmable browser runtime built on Servo and SpiderMonkey
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
//! `bun.sys.Dir` — directory handle + helpers. Port of the `Dir` half of
//! `src/sys/sys.zig` (Zig: `bun.sys.Dir` ≈ `std.fs.Dir`).
//!
//! Owns the descriptor; closes it on Drop (skipping `Fd::INVALID` and the
//! `AT_FDCWD` sentinel). Use [`Dir::into_raw`] to hand the fd off,
//! [`Dir::borrow`] for a non-owning `&Dir` view of someone else's fd.

use super::*;

#[repr(transparent)]
pub struct Dir {
    pub fd: Fd,
}

impl Drop for Dir {
    #[inline]
    fn drop(&mut self) {
        if self.fd != Fd::INVALID && self.fd != Fd::cwd() {
            let _ = close(self.fd);
        }
    }
}

/// Options for `Dir::copy_file` (Zig: `std.fs.Dir.CopyFileOptions`).
#[derive(Clone, Copy, Default)]
pub struct CopyFileOptions {
    /// When set, the destination is created with this mode instead of the
    /// source file's mode (Zig: `override_mode: ?File.Mode`).
    pub override_mode: Option<Mode>,
}

/// Options for `Dir::make_open_path` (Zig: `std.fs.Dir.OpenOptions`).
#[derive(Clone, Copy, Default)]
pub struct OpenDirOptions {
    pub iterate: bool,
    pub no_follow: bool,
}

impl Dir {
    #[inline]
    pub fn from_fd(fd: Fd) -> Self {
        Self { fd }
    }
    #[inline]
    pub fn fd(&self) -> Fd {
        self.fd
    }
    #[inline]
    pub fn cwd() -> Self {
        Self { fd: Fd::cwd() }
    }
    /// Open `path` relative to cwd. `O_DIRECTORY | O_RDONLY | O_CLOEXEC`.
    #[inline]
    pub fn open(path: &[u8]) -> Maybe<Self> {
        open_dir_at(Fd::cwd(), path).map(Self::from_fd)
    }
    /// Open `path` relative to cwd with explicit flags. `O_DIRECTORY` is
    /// always added.
    #[inline]
    pub fn open_with(path: &[u8], flags: i32) -> Maybe<Self> {
        openat_a(Fd::cwd(), path, flags | O::DIRECTORY, 0).map(Self::from_fd)
    }
    /// Open `sub_path` relative to this dir.
    #[inline]
    pub fn open_at(&self, sub_path: &[u8]) -> Maybe<Self> {
        open_dir_at(self.fd, sub_path).map(Self::from_fd)
    }
    /// Open `sub_path` relative to this dir with explicit flags. `O_DIRECTORY`
    /// is always added.
    #[inline]
    pub fn open_at_with(&self, sub_path: &[u8], flags: i32) -> Maybe<Self> {
        openat_a(self.fd, sub_path, flags | O::DIRECTORY, 0).map(Self::from_fd)
    }
    /// Open `sub_path` relative to this dir as a [`File`].
    #[inline]
    pub fn open_file(&self, sub_path: &[u8], flags: i32, mode: Mode) -> Maybe<File> {
        File::openat(self.fd, sub_path, flags, mode)
    }
    /// Resolve this dir's absolute path via `/proc/self/fd` (Linux),
    /// `F_GETPATH` (macOS), or `GetFinalPathNameByHandle` (Windows).
    #[inline]
    pub fn get_fd_path<'b>(&self, buf: &'b mut bun_paths::PathBuffer) -> Maybe<&'b mut [u8]> {
        get_fd_path(self.fd, buf)
    }
    /// Close now. Equivalent to dropping `self` but discards the syscall
    /// result (matches Zig's `Dir.close()`).
    #[inline]
    pub fn close(self) {
        drop(self);
    }
    /// Disarm the drop guard and return the raw [`Fd`]. The caller takes over
    /// the descriptor's lifecycle.
    #[inline]
    pub fn into_raw(self) -> Fd {
        core::mem::ManuallyDrop::new(self).fd
    }
    /// Non-owning `&Dir` view of an [`Fd`]. Mirrors `Path::new(&OsStr)`.
    #[inline]
    pub fn borrow(fd: &Fd) -> &Dir {
        // SAFETY: `Dir` is `#[repr(transparent)]` over `Fd`.
        unsafe { &*(core::ptr::from_ref(fd).cast::<Dir>()) }
    }

    /// `std.fs.Dir.makePath` — `mkdir -p` relative to this dir.
    #[inline]
    pub fn make_path(&self, sub_path: &[u8]) -> core::result::Result<(), bun_core::Error> {
        mkdir_recursive_at(self.fd, sub_path).map_err(Into::into)
    }
    /// `std.fs.Dir.makeOpenPath` — try `openDir` first; on ENOENT, `makePath`
    /// then `openDir` (Zig: vendor/zig/lib/std/fs/Dir.zig `makeOpenPath`).
    pub fn make_open_path(
        &self,
        sub_path: &[u8],
        _opts: OpenDirOptions,
    ) -> core::result::Result<Dir, bun_core::Error> {
        match open_dir_at(self.fd, sub_path) {
            Ok(fd) => Ok(Dir::from_fd(fd)),
            Err(e) if e.get_errno() == E::ENOENT => {
                mkdir_recursive_at(self.fd, sub_path)?;
                open_dir_at(self.fd, sub_path)
                    .map(Dir::from_fd)
                    .map_err(Into::into)
            }
            Err(e) => Err(e.into()),
        }
    }
    /// `std.fs.Dir.deleteTree` — recursive `rm -rf`. Port of Zig
    /// `std.fs.Dir.deleteTree` (stack-based depth-first walk; std/fs/Dir.zig).
    pub fn delete_tree(&self, sub_path: &[u8]) -> core::result::Result<(), bun_core::Error> {
        // `deleteTreeOpenInitialSubpath` — try unlinking as a file first; if
        // that yields IsDir/EPERM, open it as an iterable directory.
        let initial = match self.delete_tree_open_initial_subpath(sub_path)? {
            Some(d) => d,
            None => return Ok(()),
        };

        struct StackItem {
            name: Vec<u8>,
            parent_dir: Fd,
            iter: dir_iterator::WrappedIterator,
        }
        // Ensure every still-open iterator dir is closed on early return
        // (Zig: `defer StackItem.closeAll(stack.items)`).
        let mut stack = scopeguard::guard(Vec::<StackItem>::with_capacity(16), |mut s| {
            for item in s.drain(..) {
                let _ = close(item.iter.dir());
            }
        });
        stack.push(StackItem {
            name: sub_path.to_vec(),
            parent_dir: self.fd,
            iter: dir_iterator::iterate(initial),
        });

        'process_stack: while let Some(top) = stack.last_mut() {
            while let Some(entry) = top.iter.next().map_err(bun_core::Error::from)? {
                let mut treat_as_dir = matches!(entry.kind, EntryKind::Directory);
                'handle_entry: loop {
                    if treat_as_dir {
                        let new_dir = match openat_a(
                            top.iter.dir(),
                            entry.name.slice_u8(),
                            O::DIRECTORY | O::RDONLY | O::CLOEXEC | O::NOFOLLOW,
                            0,
                        ) {
                            Ok(fd) => fd,
                            Err(e) => match e.get_errno() {
                                E::ENOTDIR => {
                                    treat_as_dir = false;
                                    continue 'handle_entry;
                                }
                                // That's fine, we were trying to remove this directory anyway.
                                E::ENOENT => break 'handle_entry,
                                _ => return Err(e.into()),
                            },
                        };
                        let parent = top.iter.dir();
                        // PORT NOTE: Zig caps the stack at 16 and falls back to
                        // `deleteTreeMinStackSizeWithKindHint` past that depth. The
                        // Rust `Vec` grows, so the capacity check is dropped — same
                        // semantics, no fixed-depth limit.
                        stack.push(StackItem {
                            name: entry.name.slice_u8().to_vec(),
                            parent_dir: parent,
                            iter: dir_iterator::iterate(new_dir),
                        });
                        continue 'process_stack;
                    } else {
                        match unlinkat_a(top.iter.dir(), entry.name.slice_u8(), 0) {
                            Ok(()) => break 'handle_entry,
                            Err(e) => match e.get_errno() {
                                E::ENOENT => break 'handle_entry,
                                // EISDIR (Linux) / EPERM (POSIX rmdir-required)
                                E::EISDIR | E::EPERM => {
                                    treat_as_dir = true;
                                    continue 'handle_entry;
                                }
                                _ => return Err(e.into()),
                            },
                        }
                    }
                }
            }

            // Reached the end of the directory entries — exhausted; remove the
            // directory itself. On Windows we must close before removing.
            let dir_fd = top.iter.dir();
            let parent_dir = top.parent_dir;
            let name = core::mem::take(&mut top.name);
            // Pop before closing so the cleanup guard doesn't double-close on
            // an error from `unlinkat_a` (Zig: `stack.items.len -= 1`).
            stack.pop();
            let _ = close(dir_fd);

            let mut need_to_retry = false;
            match unlinkat_a(parent_dir, &name, AT_REMOVEDIR) {
                Ok(()) => {}
                Err(e) => match e.get_errno() {
                    E::ENOENT => {}
                    E::ENOTEMPTY => need_to_retry = true,
                    _ => return Err(e.into()),
                },
            }

            if need_to_retry {
                // Since we closed the handle that the previous iterator used, we
                // need to re-open the dir and re-create the iterator.
                let new_dir = match openat_a(
                    parent_dir,
                    &name,
                    O::DIRECTORY | O::RDONLY | O::CLOEXEC | O::NOFOLLOW,
                    0,
                ) {
                    Ok(fd) => fd,
                    Err(e) => match e.get_errno() {
                        E::ENOTDIR => {
                            // Racing fs: it became a file; unlink it.
                            match unlinkat_a(parent_dir, &name, 0) {
                                Ok(()) => continue 'process_stack,
                                Err(e2) => match e2.get_errno() {
                                    E::ENOENT => continue 'process_stack,
                                    _ => return Err(e2.into()),
                                },
                            }
                        }
                        E::ENOENT => continue 'process_stack,
                        _ => return Err(e.into()),
                    },
                };
                stack.push(StackItem {
                    name,
                    parent_dir,
                    iter: dir_iterator::iterate(new_dir),
                });
                continue 'process_stack;
            }
        }
        scopeguard::ScopeGuard::into_inner(stack);
        Ok(())
    }

    /// Port of `std.fs.Dir.deleteTreeOpenInitialSubpath` — try removing
    /// `sub_path` as a file; on `EISDIR`/`EPERM` open it as an iterable
    /// directory and return the fd. Returns `None` when removal succeeded or
    /// the path doesn't exist.
    fn delete_tree_open_initial_subpath(
        &self,
        sub_path: &[u8],
    ) -> core::result::Result<Option<Fd>, bun_core::Error> {
        let mut treat_as_dir = false;
        loop {
            if !treat_as_dir {
                match unlinkat_a(self.fd, sub_path, 0) {
                    Ok(()) => return Ok(None),
                    Err(e) => match e.get_errno() {
                        E::ENOENT => return Ok(None),
                        // Linux: EISDIR. POSIX: EPERM when target is a directory.
                        E::EISDIR | E::EPERM => treat_as_dir = true,
                        _ => return Err(e.into()),
                    },
                }
            } else {
                return match openat_a(
                    self.fd,
                    sub_path,
                    O::DIRECTORY | O::RDONLY | O::CLOEXEC | O::NOFOLLOW,
                    0,
                ) {
                    Ok(fd) => Ok(Some(fd)),
                    Err(e) => match e.get_errno() {
                        E::ENOENT => Ok(None),
                        E::ENOTDIR => {
                            treat_as_dir = false;
                            continue;
                        }
                        _ => Err(e.into()),
                    },
                };
            }
        }
    }
}

#[cfg(unix)]
pub const AT_REMOVEDIR: i32 = libc::AT_REMOVEDIR;
#[cfg(windows)]
pub const AT_REMOVEDIR: i32 = 0x200;

/// sys.zig:2928 `rmdirat` — `unlinkat(dir, path, AT_REMOVEDIR)`.
#[inline]
pub fn rmdirat(dirfd: impl AsFd, path: &ZStr) -> Maybe<()> {
    let dirfd = dirfd.as_fd();
    unlinkat_with_flags(dirfd, path, AT_REMOVEDIR)
}

/// `unlinkat` taking a non-sentinel slice (NUL-terminates into a path buffer).
fn unlinkat_a(dirfd: Fd, path: &[u8], flags: i32) -> Maybe<()> {
    let mut buf = bun_paths::path_buffer_pool::get();
    let len = path.len().min(buf.0.len() - 1);
    buf.0[..len].copy_from_slice(&path[..len]);
    buf.0[len] = 0;
    // SAFETY: NUL-terminated above.
    let z = ZStr::from_buf(&buf.0[..], len);
    unlinkat_with_flags(dirfd, z, flags)
}

/// `std.fs.File.CreateFlags` — subset used by `Dir::createFileZ` callers
/// (e.g. `repository.zig:649`, `PackageManagerDirectories.zig`).
#[derive(Clone, Copy, Default)]
pub struct CreateFlags {
    pub truncate: bool,
    /// Open for reading as well as writing (Zig: `read: bool = false`).
    pub read: bool,
}

impl Dir {
    /// `std.fs.Dir.makeDir` — single-level `mkdirat` (mode 0o755) relative to
    /// this dir. Unlike `make_path`, does NOT create intermediate directories
    /// and surfaces `error.PathAlreadyExists` for callers to branch on.
    pub fn make_dir(&self, sub_path: &[u8]) -> core::result::Result<(), bun_core::Error> {
        let mut buf = bun_paths::path_buffer_pool::get();
        let len = sub_path.len().min(buf.0.len() - 1);
        buf.0[..len].copy_from_slice(&sub_path[..len]);
        buf.0[len] = 0;
        // SAFETY: NUL-terminated above.
        let z = ZStr::from_buf(&buf.0[..], len);
        match mkdirat(self.fd, z, 0o755) {
            Ok(()) => Ok(()),
            Err(e) if e.get_errno() == E::EEXIST => Err(bun_core::err!("PathAlreadyExists")),
            Err(e) => Err(e.into()),
        }
    }

    /// `std.fs.Dir.symLink` — `symlinkat(target, self.fd, link)`. The
    /// `is_directory` flag is a no-op on POSIX (kept for parity with Zig's
    /// `SymLinkFlags`); on Windows it selects junction vs. file-symlink and
    /// callers route through `sys_uv::symlink_uv` instead.
    pub fn sym_link(
        &self,
        target: &[u8],
        link_name: &[u8],
        _is_directory: bool,
    ) -> core::result::Result<(), bun_core::Error> {
        let mut tbuf = bun_paths::path_buffer_pool::get();
        let tlen = target.len().min(tbuf.0.len() - 1);
        tbuf.0[..tlen].copy_from_slice(&target[..tlen]);
        tbuf.0[tlen] = 0;
        // SAFETY: NUL-terminated above.
        let tz = ZStr::from_buf(&tbuf.0[..], tlen);

        let mut lbuf = bun_paths::path_buffer_pool::get();
        let llen = link_name.len().min(lbuf.0.len() - 1);
        lbuf.0[..llen].copy_from_slice(&link_name[..llen]);
        lbuf.0[llen] = 0;
        // SAFETY: NUL-terminated above.
        let lz = ZStr::from_buf(&lbuf.0[..], llen);

        symlinkat(tz, self.fd, lz).map_err(Into::into)
    }

    /// `std.fs.Dir.createFileZ` — create (or truncate) `sub_path` relative to
    /// this dir and return a `File` handle. Zig stdlib semantics: `O_CREAT`,
    /// `O_WRONLY` (or `O_RDWR` if `flags.read`), `O_TRUNC` if `flags.truncate`.
    pub fn create_file_z(
        &self,
        sub_path: &ZStr,
        flags: CreateFlags,
    ) -> core::result::Result<File, bun_core::Error> {
        let mut o = O::CREAT | O::CLOEXEC;
        o |= if flags.read { O::RDWR } else { O::WRONLY };
        if flags.truncate {
            o |= O::TRUNC;
        }
        let fd = openat(self.fd, sub_path, o, 0o666)?;
        Ok(File::from_fd(fd))
    }

    /// `std.fs.Dir.deleteFileZ` — `unlinkat(self.fd, sub_path, 0)`.
    #[inline]
    pub fn delete_file_z(&self, sub_path: &ZStr) -> core::result::Result<(), bun_core::Error> {
        unlinkat(self.fd, sub_path).map_err(Into::into)
    }

    /// `std.fs.Dir.copyFile` — open `source_path` (relative to `self`), create
    /// `dest_path` (relative to `dest_dir`) with `O_CREAT|O_TRUNC`, then stream
    /// the contents via [`copy_file`]. Mode is taken from the source's `fstat`
    /// unless `options.override_mode` is set (Zig stdlib semantics, minus the
    /// `AtomicFile` rename — Bun's only call site is `gitignore` → `.gitignore`
    /// where atomicity isn't required).
    pub fn copy_file(
        &self,
        source_path: &[u8],
        dest_dir: &Dir,
        dest_path: &[u8],
        options: CopyFileOptions,
    ) -> core::result::Result<(), bun_core::Error> {
        let in_fd = openat_a(self.fd, source_path, O::RDONLY | O::CLOEXEC, 0)?;
        let mode = match options.override_mode {
            Some(m) => m,
            None => match fstat(in_fd) {
                Ok(st) => st.st_mode as Mode,
                Err(e) => {
                    let _ = close(in_fd);
                    return Err(e.into());
                }
            },
        };
        let out_fd = match openat_a(
            dest_dir.fd,
            dest_path,
            O::WRONLY | O::CREAT | O::TRUNC | O::CLOEXEC,
            mode,
        ) {
            Ok(fd) => fd,
            Err(e) => {
                let _ = close(in_fd);
                return Err(e.into());
            }
        };
        let r = copy_file(in_fd, out_fd);
        let _ = close(in_fd);
        let _ = close(out_fd);
        r.map_err(Into::into)
    }

    /// `std.fs.Dir.openDirZ` — open `sub_path` (NUL-terminated) relative to
    /// this dir as a `Dir` handle. Zig stdlib semantics: `O_DIRECTORY |
    /// O_RDONLY | O_CLOEXEC` (handled by `open_dir_at`).
    #[inline]
    pub fn open_dir_z(&self, sub_path: &ZStr) -> core::result::Result<Dir, bun_core::Error> {
        open_dir_at(self.fd, sub_path.as_bytes())
            .map(Dir::from_fd)
            .map_err(Into::into)
    }

    /// `std.fs.Dir.openDir(sub_path, .{ .iterate, .no_follow, .access_sub_paths = true })`.
    ///
    /// On POSIX, `iterate` / `access_sub_paths` are advisory (stdlib opens with
    /// `O_DIRECTORY | O_RDONLY | O_CLOEXEC` regardless). On Windows the flags
    /// select the access mask: `iterate` adds `FILE_LIST_DIRECTORY`, and the
    /// handle is opened **without** `read_only` so the caller may create/rename
    /// children — matching `std.fs.Dir.openDir`, *not* `bun.openDir`.
    #[inline]
    pub fn open_dir(
        &self,
        sub_path: &[u8],
        opts: OpenDirOptions,
    ) -> core::result::Result<Dir, bun_core::Error> {
        #[cfg(windows)]
        {
            return open_dir_at_windows_a(
                self.fd,
                sub_path,
                WindowsOpenDirOptions {
                    iterable: opts.iterate,
                    no_follow: opts.no_follow,
                    ..Default::default()
                },
            )
            .map(Dir::from_fd)
            .map_err(Into::into);
        }
        #[cfg(not(windows))]
        {
            let _ = opts;
            open_dir_at(self.fd, sub_path)
                .map(Dir::from_fd)
                .map_err(Into::into)
        }
    }
}

// `Fd` parity: `Fd::cwd().make_open_path(..)` / `.make_path(..)` are used by
// `bun_install` and `bun_bundler` directly on `Fd`. Extension trait so we
// don't fight with `bun_core`'s inherent impl.
pub trait FdDirExt: Copy {
    fn make_path(self, sub_path: &[u8]) -> core::result::Result<(), bun_core::Error>;
    fn make_open_path(self, sub_path: &[u8]) -> core::result::Result<Dir, bun_core::Error>;
    fn from_std_dir(dir: &Dir) -> Self;
}
impl FdDirExt for Fd {
    #[inline]
    fn make_path(self, sub_path: &[u8]) -> core::result::Result<(), bun_core::Error> {
        mkdir_recursive_at(self, sub_path).map_err(Into::into)
    }
    #[inline]
    fn make_open_path(self, sub_path: &[u8]) -> core::result::Result<Dir, bun_core::Error> {
        Dir::borrow(&self).make_open_path(sub_path, OpenDirOptions::default())
    }
    #[inline]
    fn from_std_dir(dir: &Dir) -> Fd {
        dir.fd
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::file::tests::FD_TEST_LOCK;

    fn open_cwd() -> Dir {
        Dir::open(b".").unwrap()
    }

    #[test]
    fn drop_closes_fd() {
        let _g = FD_TEST_LOCK.lock();
        let raw = {
            let dir = open_cwd();
            dir.fd()
        };
        assert!(fstat(raw).is_err());
    }

    #[test]
    fn close_disarms_drop() {
        let _g = FD_TEST_LOCK.lock();
        let dir = open_cwd();
        let raw = dir.fd();
        dir.close();
        let canary = open_cwd();
        assert!(fstat(canary.fd()).is_ok());
        let _ = raw;
    }

    #[test]
    fn into_raw_disarms_drop() {
        let _g = FD_TEST_LOCK.lock();
        let dir = open_cwd();
        let raw = dir.into_raw();
        // `dir` has been forgotten; the fd is still open.
        assert!(fstat(raw).is_ok());
        let _ = close(raw);
    }

    #[test]
    fn borrow_does_not_close() {
        let _g = FD_TEST_LOCK.lock();
        let dir = open_cwd();
        let raw = dir.fd();
        {
            let view = Dir::borrow(&raw);
            let _ = view;
        }
        // The borrow dropped, but the fd is still open.
        assert!(fstat(raw).is_ok());
    }

    #[test]
    fn dropping_cwd_sentinel_is_safe() {
        let _g = FD_TEST_LOCK.lock();
        // `Dir::cwd()` wraps `AT_FDCWD`. Dropping it must be a no-op — it must
        // not close fd 0 (or any other low fd that `AT_FDCWD` could collide
        // with after a wraparound).
        for _ in 0..16 {
            let _ = Dir::cwd();
        }
        // Still able to open files relative to cwd.
        assert!(Dir::cwd().open_at(b".").is_ok());
    }

    #[test]
    fn dropping_invalid_fd_is_safe() {
        let _g = FD_TEST_LOCK.lock();
        for _ in 0..16 {
            let _ = Dir::from_fd(Fd::INVALID);
        }
    }
}