fs.rs 43.6 KB
Newer Older
T
Taiki Endo 已提交
1 2
use crate::os::unix::prelude::*;

M
Mark Rousskov 已提交
3
use crate::ffi::{CStr, CString, OsStr, OsString};
T
Taiki Endo 已提交
4
use crate::fmt;
M
Mark Rousskov 已提交
5
use crate::io::{self, Error, ErrorKind, IoSlice, IoSliceMut, SeekFrom};
T
Taiki Endo 已提交
6 7 8 9 10 11 12 13 14 15
use crate::mem;
use crate::path::{Path, PathBuf};
use crate::ptr;
use crate::sync::Arc;
use crate::sys::fd::FileDesc;
use crate::sys::time::SystemTime;
use crate::sys::{cvt, cvt_r};
use crate::sys_common::{AsInner, FromInner};

use libc::{c_int, mode_t};
A
Alex Crichton 已提交
16

17
#[cfg(any(target_os = "linux", target_os = "emscripten", target_os = "android"))]
J
Josh Stone 已提交
18
use libc::dirfd;
M
Mark Rousskov 已提交
19 20 21 22 23 24
#[cfg(any(target_os = "linux", target_os = "emscripten"))]
use libc::fstatat64;
#[cfg(not(any(
    target_os = "linux",
    target_os = "emscripten",
    target_os = "solaris",
P
Patrick Mooney 已提交
25
    target_os = "illumos",
M
Mark Rousskov 已提交
26 27 28 29 30
    target_os = "l4re",
    target_os = "fuchsia",
    target_os = "redox"
)))]
use libc::readdir_r as readdir64_r;
31
#[cfg(target_os = "android")]
M
Mark Rousskov 已提交
32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49
use libc::{
    dirent as dirent64, fstat as fstat64, fstatat as fstatat64, lseek64, lstat as lstat64,
    open as open64, stat as stat64,
};
#[cfg(not(any(
    target_os = "linux",
    target_os = "emscripten",
    target_os = "l4re",
    target_os = "android"
)))]
use libc::{
    dirent as dirent64, fstat as fstat64, ftruncate as ftruncate64, lseek as lseek64,
    lstat as lstat64, off_t as off64_t, open as open64, stat as stat64,
};
#[cfg(any(target_os = "linux", target_os = "emscripten", target_os = "l4re"))]
use libc::{
    dirent64, fstat64, ftruncate64, lseek64, lstat64, off64_t, open64, readdir64_r, stat64,
};
50

51 52
pub use crate::sys_common::fs::remove_dir_all;

A
Alex Crichton 已提交
53 54
pub struct File(FileDesc);

O
oxalica 已提交
55 56 57 58
// FIXME: This should be available on Linux with all `target_env`.
// But currently only glibc exposes `statx` fn and structs.
// We don't want to import unverified raw C structs here directly.
// https://github.com/rust-lang/rust/pull/67774
O
oxalica 已提交
59 60 61
macro_rules! cfg_has_statx {
    ({ $($then_tt:tt)* } else { $($else_tt:tt)* }) => {
        cfg_if::cfg_if! {
O
oxalica 已提交
62
            if #[cfg(all(target_os = "linux", target_env = "gnu"))] {
O
oxalica 已提交
63 64 65 66 67 68 69
                $($then_tt)*
            } else {
                $($else_tt)*
            }
        }
    };
    ($($block_inner:tt)*) => {
O
oxalica 已提交
70
        #[cfg(all(target_os = "linux", target_env = "gnu"))]
O
oxalica 已提交
71 72 73 74
        {
            $($block_inner)*
        }
    };
O
oxalica 已提交
75 76
}

O
oxalica 已提交
77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98
cfg_has_statx! {{
    #[derive(Clone)]
    pub struct FileAttr {
        stat: stat64,
        statx_extra_fields: Option<StatxExtraFields>,
    }

    #[derive(Clone)]
    struct StatxExtraFields {
        // This is needed to check if btime is supported by the filesystem.
        stx_mask: u32,
        stx_btime: libc::statx_timestamp,
    }

    // We prefer `statx` on Linux if available, which contains file creation time.
    // Default `stat64` contains no creation time.
    unsafe fn try_statx(
        fd: c_int,
        path: *const libc::c_char,
        flags: i32,
        mask: u32,
    ) -> Option<io::Result<FileAttr>> {
O
oxalica 已提交
99
        use crate::sync::atomic::{AtomicU8, Ordering};
O
oxalica 已提交
100 101

        // Linux kernel prior to 4.11 or glibc prior to glibc 2.28 don't support `statx`
O
oxalica 已提交
102 103 104 105 106
        // We store the availability in global to avoid unnecessary syscalls.
        // 0: Unknown
        // 1: Not available
        // 2: Available
        static STATX_STATE: AtomicU8 = AtomicU8::new(0);
O
oxalica 已提交
107 108 109 110 111 112 113 114 115 116
        syscall! {
            fn statx(
                fd: c_int,
                pathname: *const libc::c_char,
                flags: c_int,
                mask: libc::c_uint,
                statxbuf: *mut libc::statx
            ) -> c_int
        }

O
oxalica 已提交
117 118
        match STATX_STATE.load(Ordering::Relaxed) {
            0 => {
O
oxalica 已提交
119 120 121
                // It is a trick to call `statx` with NULL pointers to check if the syscall
                // is available. According to the manual, it is expected to fail with EFAULT.
                // We do this mainly for performance, since it is nearly hundreds times
B
Brian Wignall 已提交
122
                // faster than a normal successful call.
O
oxalica 已提交
123
                let err = cvt(statx(0, ptr::null(), 0, libc::STATX_ALL, ptr::null_mut()))
O
oxalica 已提交
124 125
                    .err()
                    .and_then(|e| e.raw_os_error());
O
oxalica 已提交
126 127
                // We don't check `err == Some(libc::ENOSYS)` because the syscall may be limited
                // and returns `EPERM`. Listing all possible errors seems not a good idea.
O
oxalica 已提交
128
                // See: https://github.com/rust-lang/rust/issues/65662
O
oxalica 已提交
129
                if err != Some(libc::EFAULT) {
O
oxalica 已提交
130
                    STATX_STATE.store(1, Ordering::Relaxed);
O
oxalica 已提交
131
                    return None;
O
oxalica 已提交
132
                }
O
oxalica 已提交
133
                STATX_STATE.store(2, Ordering::Relaxed);
O
oxalica 已提交
134
            }
O
oxalica 已提交
135 136 137
            1 => return None,
            _ => {}
        }
O
oxalica 已提交
138

O
oxalica 已提交
139 140 141
        let mut buf: libc::statx = mem::zeroed();
        if let Err(err) = cvt(statx(fd, path, flags, mask, &mut buf)) {
            return Some(Err(err));
O
oxalica 已提交
142
        }
O
oxalica 已提交
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

        // We cannot fill `stat64` exhaustively because of private padding fields.
        let mut stat: stat64 = mem::zeroed();
        // `c_ulong` on gnu-mips, `dev_t` otherwise
        stat.st_dev = libc::makedev(buf.stx_dev_major, buf.stx_dev_minor) as _;
        stat.st_ino = buf.stx_ino as libc::ino64_t;
        stat.st_nlink = buf.stx_nlink as libc::nlink_t;
        stat.st_mode = buf.stx_mode as libc::mode_t;
        stat.st_uid = buf.stx_uid as libc::uid_t;
        stat.st_gid = buf.stx_gid as libc::gid_t;
        stat.st_rdev = libc::makedev(buf.stx_rdev_major, buf.stx_rdev_minor) as _;
        stat.st_size = buf.stx_size as off64_t;
        stat.st_blksize = buf.stx_blksize as libc::blksize_t;
        stat.st_blocks = buf.stx_blocks as libc::blkcnt64_t;
        stat.st_atime = buf.stx_atime.tv_sec as libc::time_t;
        // `i64` on gnu-x86_64-x32, `c_ulong` otherwise.
        stat.st_atime_nsec = buf.stx_atime.tv_nsec as _;
        stat.st_mtime = buf.stx_mtime.tv_sec as libc::time_t;
        stat.st_mtime_nsec = buf.stx_mtime.tv_nsec as _;
        stat.st_ctime = buf.stx_ctime.tv_sec as libc::time_t;
        stat.st_ctime_nsec = buf.stx_ctime.tv_nsec as _;

        let extra = StatxExtraFields {
            stx_mask: buf.stx_mask,
            stx_btime: buf.stx_btime,
        };

        Some(Ok(FileAttr { stat, statx_extra_fields: Some(extra) }))
O
oxalica 已提交
171
    }
O
oxalica 已提交
172 173 174 175 176 177 178

} else {
    #[derive(Clone)]
    pub struct FileAttr {
        stat: stat64,
    }
}}
A
Alex Crichton 已提交
179

180 181
// all DirEntry's will have a reference to this struct
struct InnerReadDir {
182
    dirp: Dir,
183
    root: PathBuf,
A
Alex Crichton 已提交
184 185
}

186 187
pub struct ReadDir {
    inner: Arc<InnerReadDir>,
188 189 190 191 192 193
    #[cfg(not(any(
        target_os = "solaris",
        target_os = "illumos",
        target_os = "fuchsia",
        target_os = "redox",
    )))]
194 195
    end_of_stream: bool,
}
196

197 198 199 200 201
struct Dir(*mut libc::DIR);

unsafe impl Send for Dir {}
unsafe impl Sync for Dir {}

A
Alex Crichton 已提交
202
pub struct DirEntry {
J
Josh Stone 已提交
203
    entry: dirent64,
204
    dir: Arc<InnerReadDir>,
205
    // We need to store an owned copy of the entry name
206 207 208
    // on Solaris and Fuchsia because a) it uses a zero-length
    // array to store the name, b) its lifetime between readdir
    // calls is not guaranteed.
P
Patrick Mooney 已提交
209 210 211 212 213 214
    #[cfg(any(
        target_os = "solaris",
        target_os = "illumos",
        target_os = "fuchsia",
        target_os = "redox"
    ))]
M
Mark Rousskov 已提交
215
    name: Box<[u8]>,
A
Alex Crichton 已提交
216 217
}

218
#[derive(Clone, Debug)]
A
Alex Crichton 已提交
219
pub struct OpenOptions {
220
    // generic
A
Alex Crichton 已提交
221 222
    read: bool,
    write: bool,
223 224 225 226 227
    append: bool,
    truncate: bool,
    create: bool,
    create_new: bool,
    // system-specific
228
    custom_flags: i32,
A
Alex Crichton 已提交
229 230 231 232
    mode: mode_t,
}

#[derive(Clone, PartialEq, Eq, Debug)]
M
Mark Rousskov 已提交
233 234 235
pub struct FilePermissions {
    mode: mode_t,
}
A
Alex Crichton 已提交
236

M
Martin Pool 已提交
237
#[derive(Copy, Clone, PartialEq, Eq, Hash, Debug)]
M
Mark Rousskov 已提交
238 239 240
pub struct FileType {
    mode: mode_t,
}
A
Alex Crichton 已提交
241

242
#[derive(Debug)]
M
Mark Rousskov 已提交
243 244 245
pub struct DirBuilder {
    mode: mode_t,
}
A
Alex Crichton 已提交
246

O
oxalica 已提交
247 248 249 250 251 252 253 254 255 256
cfg_has_statx! {{
    impl FileAttr {
        fn from_stat64(stat: stat64) -> Self {
            Self { stat, statx_extra_fields: None }
        }
    }
} else {
    impl FileAttr {
        fn from_stat64(stat: stat64) -> Self {
            Self { stat }
O
oxalica 已提交
257 258
        }
    }
O
oxalica 已提交
259
}}
O
oxalica 已提交
260

O
oxalica 已提交
261
impl FileAttr {
M
Mark Rousskov 已提交
262 263 264
    pub fn size(&self) -> u64 {
        self.stat.st_size as u64
    }
A
Alex Crichton 已提交
265
    pub fn perm(&self) -> FilePermissions {
T
Trevor Merrifield 已提交
266
        FilePermissions { mode: (self.stat.st_mode as mode_t) }
A
Alex Crichton 已提交
267 268
    }

A
Alex Crichton 已提交
269 270 271
    pub fn file_type(&self) -> FileType {
        FileType { mode: self.stat.st_mode as mode_t }
    }
A
Alex Crichton 已提交
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
#[cfg(target_os = "netbsd")]
impl FileAttr {
    pub fn modified(&self) -> io::Result<SystemTime> {
        Ok(SystemTime::from(libc::timespec {
            tv_sec: self.stat.st_mtime as libc::time_t,
            tv_nsec: self.stat.st_mtimensec as libc::c_long,
        }))
    }

    pub fn accessed(&self) -> io::Result<SystemTime> {
        Ok(SystemTime::from(libc::timespec {
            tv_sec: self.stat.st_atime as libc::time_t,
            tv_nsec: self.stat.st_atimensec as libc::c_long,
        }))
    }

    pub fn created(&self) -> io::Result<SystemTime> {
        Ok(SystemTime::from(libc::timespec {
            tv_sec: self.stat.st_birthtime as libc::time_t,
            tv_nsec: self.stat.st_birthtimensec as libc::c_long,
        }))
    }
}

298
#[cfg(not(target_os = "netbsd"))]
299
impl FileAttr {
300
    #[cfg(not(target_os = "vxworks"))]
301 302
    pub fn modified(&self) -> io::Result<SystemTime> {
        Ok(SystemTime::from(libc::timespec {
303
            tv_sec: self.stat.st_mtime as libc::time_t,
304
            tv_nsec: self.stat.st_mtime_nsec as _,
305 306 307
        }))
    }

308 309 310 311 312 313 314 315 316
    #[cfg(target_os = "vxworks")]
    pub fn modified(&self) -> io::Result<SystemTime> {
        Ok(SystemTime::from(libc::timespec {
            tv_sec: self.stat.st_mtime as libc::time_t,
            tv_nsec: 0,
        }))
    }

    #[cfg(not(target_os = "vxworks"))]
317 318
    pub fn accessed(&self) -> io::Result<SystemTime> {
        Ok(SystemTime::from(libc::timespec {
319
            tv_sec: self.stat.st_atime as libc::time_t,
320
            tv_nsec: self.stat.st_atime_nsec as _,
321 322 323
        }))
    }

324 325 326 327 328 329 330 331
    #[cfg(target_os = "vxworks")]
    pub fn accessed(&self) -> io::Result<SystemTime> {
        Ok(SystemTime::from(libc::timespec {
            tv_sec: self.stat.st_atime as libc::time_t,
            tv_nsec: 0,
        }))
    }

M
Mark Rousskov 已提交
332 333 334 335 336 337
    #[cfg(any(
        target_os = "freebsd",
        target_os = "openbsd",
        target_os = "macos",
        target_os = "ios"
    ))]
338 339
    pub fn created(&self) -> io::Result<SystemTime> {
        Ok(SystemTime::from(libc::timespec {
340
            tv_sec: self.stat.st_birthtime as libc::time_t,
341 342 343 344
            tv_nsec: self.stat.st_birthtime_nsec as libc::c_long,
        }))
    }

M
Mark Rousskov 已提交
345 346 347 348 349 350
    #[cfg(not(any(
        target_os = "freebsd",
        target_os = "openbsd",
        target_os = "macos",
        target_os = "ios"
    )))]
351
    pub fn created(&self) -> io::Result<SystemTime> {
O
oxalica 已提交
352
        cfg_has_statx! {
O
oxalica 已提交
353 354 355 356
            if let Some(ext) = &self.statx_extra_fields {
                return if (ext.stx_mask & libc::STATX_BTIME) != 0 {
                    Ok(SystemTime::from(libc::timespec {
                        tv_sec: ext.stx_btime.tv_sec as libc::time_t,
O
oxalica 已提交
357
                        tv_nsec: ext.stx_btime.tv_nsec as _,
O
oxalica 已提交
358 359 360 361 362 363 364 365 366 367
                    }))
                } else {
                    Err(io::Error::new(
                        io::ErrorKind::Other,
                        "creation time is not available for the filesystem",
                    ))
                };
            }
        }

M
Mark Rousskov 已提交
368 369 370 371 372
        Err(io::Error::new(
            io::ErrorKind::Other,
            "creation time is not available on this platform \
                            currently",
        ))
373 374 375
    }
}

376
impl AsInner<stat64> for FileAttr {
M
Mark Rousskov 已提交
377 378 379
    fn as_inner(&self) -> &stat64 {
        &self.stat
    }
A
Alex Crichton 已提交
380 381
}

A
Alex Crichton 已提交
382
impl FilePermissions {
383 384 385 386 387
    pub fn readonly(&self) -> bool {
        // check if any class (owner, group, others) has write permission
        self.mode & 0o222 == 0
    }

A
Alex Crichton 已提交
388 389
    pub fn set_readonly(&mut self, readonly: bool) {
        if readonly {
390
            // remove write permission for all classes; equivalent to `chmod a-w <file>`
A
Alex Crichton 已提交
391 392
            self.mode &= !0o222;
        } else {
393
            // add write permission for all classes; equivalent to `chmod a+w <file>`
A
Alex Crichton 已提交
394 395 396
            self.mode |= 0o222;
        }
    }
M
Mark Rousskov 已提交
397 398 399
    pub fn mode(&self) -> u32 {
        self.mode as u32
    }
A
Alex Crichton 已提交
400 401 402
}

impl FileType {
M
Mark Rousskov 已提交
403 404 405 406 407 408 409 410 411
    pub fn is_dir(&self) -> bool {
        self.is(libc::S_IFDIR)
    }
    pub fn is_file(&self) -> bool {
        self.is(libc::S_IFREG)
    }
    pub fn is_symlink(&self) -> bool {
        self.is(libc::S_IFLNK)
    }
A
Alex Crichton 已提交
412

M
Mark Rousskov 已提交
413 414 415
    pub fn is(&self, mode: mode_t) -> bool {
        self.mode & libc::S_IFMT == mode
    }
A
Alex Crichton 已提交
416 417
}

418 419
impl FromInner<u32> for FilePermissions {
    fn from_inner(mode: u32) -> FilePermissions {
A
Alex Crichton 已提交
420 421 422 423
        FilePermissions { mode: mode as mode_t }
    }
}

D
David Henningsson 已提交
424
impl fmt::Debug for ReadDir {
425
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
D
David Henningsson 已提交
426 427
        // This will only be called from std::fs::ReadDir, which will add a "ReadDir()" frame.
        // Thus the result will be e g 'ReadDir("/home")'
428
        fmt::Debug::fmt(&*self.inner.root, f)
D
David Henningsson 已提交
429 430 431
    }
}

A
Alex Crichton 已提交
432 433 434
impl Iterator for ReadDir {
    type Item = io::Result<DirEntry>;

P
Patrick Mooney 已提交
435 436 437 438 439 440
    #[cfg(any(
        target_os = "solaris",
        target_os = "fuchsia",
        target_os = "redox",
        target_os = "illumos"
    ))]
N
Nikita Baksalyar 已提交
441
    fn next(&mut self) -> Option<io::Result<DirEntry>> {
T
Taiki Endo 已提交
442 443
        use crate::slice;

N
Nikita Baksalyar 已提交
444 445
        unsafe {
            loop {
446
                // Although readdir_r(3) would be a correct function to use here because
447 448 449
                // of the thread safety, on Illumos and Fuchsia the readdir(3C) function
                // is safe to use in threaded applications and it is generally preferred
                // over the readdir_r(3C) function.
450
                super::os::set_errno(0);
451
                let entry_ptr = libc::readdir(self.inner.dirp.0);
N
Nikita Baksalyar 已提交
452
                if entry_ptr.is_null() {
453 454 455 456 457
                    // NULL can mean either the end is reached or an error occurred.
                    // So we had to clear errno beforehand to check for an error now.
                    return match super::os::errno() {
                        0 => None,
                        e => Some(Err(Error::from_raw_os_error(e))),
M
Mark Rousskov 已提交
458
                    };
N
Nikita Baksalyar 已提交
459 460 461 462 463 464 465
                }

                let name = (*entry_ptr).d_name.as_ptr();
                let namelen = libc::strlen(name) as usize;

                let ret = DirEntry {
                    entry: *entry_ptr,
M
Mark Rousskov 已提交
466 467 468
                    name: slice::from_raw_parts(name as *const u8, namelen as usize)
                        .to_owned()
                        .into_boxed_slice(),
469
                    dir: Arc::clone(&self.inner),
N
Nikita Baksalyar 已提交
470 471
                };
                if ret.name_bytes() != b"." && ret.name_bytes() != b".." {
M
Mark Rousskov 已提交
472
                    return Some(Ok(ret));
N
Nikita Baksalyar 已提交
473 474 475 476 477
                }
            }
        }
    }

P
Patrick Mooney 已提交
478 479 480 481 482 483
    #[cfg(not(any(
        target_os = "solaris",
        target_os = "fuchsia",
        target_os = "redox",
        target_os = "illumos"
    )))]
A
Alex Crichton 已提交
484
    fn next(&mut self) -> Option<io::Result<DirEntry>> {
485 486 487 488
        if self.end_of_stream {
            return None;
        }

489
        unsafe {
490
            let mut ret = DirEntry { entry: mem::zeroed(), dir: Arc::clone(&self.inner) };
491 492
            let mut entry_ptr = ptr::null_mut();
            loop {
493 494 495 496 497 498 499 500
                if readdir64_r(self.inner.dirp.0, &mut ret.entry, &mut entry_ptr) != 0 {
                    if entry_ptr.is_null() {
                        // We encountered an error (which will be returned in this iteration), but
                        // we also reached the end of the directory stream. The `end_of_stream`
                        // flag is enabled to make sure that we return `None` in the next iteration
                        // (instead of looping forever)
                        self.end_of_stream = true;
                    }
M
Mark Rousskov 已提交
501
                    return Some(Err(Error::last_os_error()));
502 503
                }
                if entry_ptr.is_null() {
M
Mark Rousskov 已提交
504
                    return None;
505 506
                }
                if ret.name_bytes() != b"." && ret.name_bytes() != b".." {
M
Mark Rousskov 已提交
507
                    return Some(Ok(ret));
508
                }
A
Alex Crichton 已提交
509 510 511 512 513
            }
        }
    }
}

514
impl Drop for Dir {
A
Alex Crichton 已提交
515
    fn drop(&mut self) {
516
        let r = unsafe { libc::closedir(self.0) };
A
Alex Crichton 已提交
517 518 519 520 521 522
        debug_assert_eq!(r, 0);
    }
}

impl DirEntry {
    pub fn path(&self) -> PathBuf {
523
        self.dir.root.join(OsStr::from_bytes(self.name_bytes()))
A
Alex Crichton 已提交
524 525
    }

A
Alex Crichton 已提交
526 527 528 529
    pub fn file_name(&self) -> OsString {
        OsStr::from_bytes(self.name_bytes()).to_os_string()
    }

530 531
    #[cfg(any(target_os = "linux", target_os = "emscripten", target_os = "android"))]
    pub fn metadata(&self) -> io::Result<FileAttr> {
532
        let fd = cvt(unsafe { dirfd(self.dir.dirp.0) })?;
O
oxalica 已提交
533 534
        let name = self.entry.d_name.as_ptr();

O
oxalica 已提交
535
        cfg_has_statx! {
O
oxalica 已提交
536 537 538 539 540 541 542 543 544 545
            if let Some(ret) = unsafe { try_statx(
                fd,
                name,
                libc::AT_SYMLINK_NOFOLLOW | libc::AT_STATX_SYNC_AS_STAT,
                libc::STATX_ALL,
            ) } {
                return ret;
            }
        }

546
        let mut stat: stat64 = unsafe { mem::zeroed() };
M
Mark Rousskov 已提交
547
        cvt(unsafe { fstatat64(fd, name, &mut stat, libc::AT_SYMLINK_NOFOLLOW) })?;
O
oxalica 已提交
548
        Ok(FileAttr::from_stat64(stat))
549 550 551
    }

    #[cfg(not(any(target_os = "linux", target_os = "emscripten", target_os = "android")))]
A
Alex Crichton 已提交
552 553 554 555
    pub fn metadata(&self) -> io::Result<FileAttr> {
        lstat(&self.path())
    }

556 557 558 559 560 561
    #[cfg(any(
        target_os = "solaris",
        target_os = "illumos",
        target_os = "haiku",
        target_os = "vxworks"
    ))]
562 563 564 565
    pub fn file_type(&self) -> io::Result<FileType> {
        lstat(&self.path()).map(|m| m.file_type())
    }

566 567 568 569 570 571
    #[cfg(not(any(
        target_os = "solaris",
        target_os = "illumos",
        target_os = "haiku",
        target_os = "vxworks"
    )))]
A
Alex Crichton 已提交
572
    pub fn file_type(&self) -> io::Result<FileType> {
573 574 575 576 577 578 579 580 581
        match self.entry.d_type {
            libc::DT_CHR => Ok(FileType { mode: libc::S_IFCHR }),
            libc::DT_FIFO => Ok(FileType { mode: libc::S_IFIFO }),
            libc::DT_LNK => Ok(FileType { mode: libc::S_IFLNK }),
            libc::DT_REG => Ok(FileType { mode: libc::S_IFREG }),
            libc::DT_SOCK => Ok(FileType { mode: libc::S_IFSOCK }),
            libc::DT_DIR => Ok(FileType { mode: libc::S_IFDIR }),
            libc::DT_BLK => Ok(FileType { mode: libc::S_IFBLK }),
            _ => lstat(&self.path()).map(|m| m.file_type()),
A
Alex Crichton 已提交
582 583 584
        }
    }

M
Mark Rousskov 已提交
585 586 587 588 589 590 591
    #[cfg(any(
        target_os = "macos",
        target_os = "ios",
        target_os = "linux",
        target_os = "emscripten",
        target_os = "android",
        target_os = "solaris",
P
Patrick Mooney 已提交
592
        target_os = "illumos",
M
Mark Rousskov 已提交
593 594 595
        target_os = "haiku",
        target_os = "l4re",
        target_os = "fuchsia",
596 597
        target_os = "redox",
        target_os = "vxworks"
M
Mark Rousskov 已提交
598
    ))]
599 600
    pub fn ino(&self) -> u64 {
        self.entry.d_ino as u64
601 602
    }

M
Mark Rousskov 已提交
603 604 605 606 607 608
    #[cfg(any(
        target_os = "freebsd",
        target_os = "openbsd",
        target_os = "netbsd",
        target_os = "dragonfly"
    ))]
609 610
    pub fn ino(&self) -> u64 {
        self.entry.d_fileno as u64
A
Alex Crichton 已提交
611 612
    }

M
Mark Rousskov 已提交
613 614 615 616 617 618 619 620
    #[cfg(any(
        target_os = "macos",
        target_os = "ios",
        target_os = "netbsd",
        target_os = "openbsd",
        target_os = "freebsd",
        target_os = "dragonfly"
    ))]
621
    fn name_bytes(&self) -> &[u8] {
T
Taiki Endo 已提交
622
        use crate::slice;
A
Alex Crichton 已提交
623
        unsafe {
M
Mark Rousskov 已提交
624 625 626 627
            slice::from_raw_parts(
                self.entry.d_name.as_ptr() as *const u8,
                self.entry.d_namlen as usize,
            )
A
Alex Crichton 已提交
628 629
        }
    }
M
Mark Rousskov 已提交
630 631 632 633 634
    #[cfg(any(
        target_os = "android",
        target_os = "linux",
        target_os = "emscripten",
        target_os = "l4re",
635 636
        target_os = "haiku",
        target_os = "vxworks"
M
Mark Rousskov 已提交
637
    ))]
638
    fn name_bytes(&self) -> &[u8] {
M
Mark Rousskov 已提交
639
        unsafe { CStr::from_ptr(self.entry.d_name.as_ptr()).to_bytes() }
640
    }
P
Patrick Mooney 已提交
641 642 643 644 645 646
    #[cfg(any(
        target_os = "solaris",
        target_os = "illumos",
        target_os = "fuchsia",
        target_os = "redox"
    ))]
N
Nikita Baksalyar 已提交
647 648 649
    fn name_bytes(&self) -> &[u8] {
        &*self.name
    }
A
Alex Crichton 已提交
650 651 652 653 654
}

impl OpenOptions {
    pub fn new() -> OpenOptions {
        OpenOptions {
655
            // generic
A
Alex Crichton 已提交
656 657
            read: false,
            write: false,
658 659 660 661 662 663
            append: false,
            truncate: false,
            create: false,
            create_new: false,
            // system-specific
            custom_flags: 0,
A
Alex Crichton 已提交
664
            mode: 0o666,
A
Alex Crichton 已提交
665 666 667
        }
    }

M
Mark Rousskov 已提交
668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685
    pub fn read(&mut self, read: bool) {
        self.read = read;
    }
    pub fn write(&mut self, write: bool) {
        self.write = write;
    }
    pub fn append(&mut self, append: bool) {
        self.append = append;
    }
    pub fn truncate(&mut self, truncate: bool) {
        self.truncate = truncate;
    }
    pub fn create(&mut self, create: bool) {
        self.create = create;
    }
    pub fn create_new(&mut self, create_new: bool) {
        self.create_new = create_new;
    }
686

M
Mark Rousskov 已提交
687 688 689 690 691 692
    pub fn custom_flags(&mut self, flags: i32) {
        self.custom_flags = flags;
    }
    pub fn mode(&mut self, mode: u32) {
        self.mode = mode as mode_t;
    }
693 694 695

    fn get_access_mode(&self) -> io::Result<c_int> {
        match (self.read, self.write, self.append) {
M
Mark Rousskov 已提交
696 697 698 699 700
            (true, false, false) => Ok(libc::O_RDONLY),
            (false, true, false) => Ok(libc::O_WRONLY),
            (true, true, false) => Ok(libc::O_RDWR),
            (false, _, true) => Ok(libc::O_WRONLY | libc::O_APPEND),
            (true, _, true) => Ok(libc::O_RDWR | libc::O_APPEND),
701 702
            (false, false, false) => Err(Error::from_raw_os_error(libc::EINVAL)),
        }
A
Alex Crichton 已提交
703 704
    }

705 706
    fn get_creation_mode(&self) -> io::Result<c_int> {
        match (self.write, self.append) {
P
Paul Dicker 已提交
707
            (true, false) => {}
M
Mark Rousskov 已提交
708
            (false, false) => {
P
Paul Dicker 已提交
709 710
                if self.truncate || self.create || self.create_new {
                    return Err(Error::from_raw_os_error(libc::EINVAL));
M
Mark Rousskov 已提交
711 712 713
                }
            }
            (_, true) => {
P
Paul Dicker 已提交
714 715
                if self.truncate && !self.create_new {
                    return Err(Error::from_raw_os_error(libc::EINVAL));
M
Mark Rousskov 已提交
716 717
                }
            }
A
Alex Crichton 已提交
718
        }
719 720

        Ok(match (self.create, self.truncate, self.create_new) {
M
Mark Rousskov 已提交
721 722 723 724 725 726
            (false, false, false) => 0,
            (true, false, false) => libc::O_CREAT,
            (false, true, false) => libc::O_TRUNC,
            (true, true, false) => libc::O_CREAT | libc::O_TRUNC,
            (_, _, true) => libc::O_CREAT | libc::O_EXCL,
        })
A
Alex Crichton 已提交
727 728 729 730 731
    }
}

impl File {
    pub fn open(path: &Path, opts: &OpenOptions) -> io::Result<File> {
J
Jorge Aparicio 已提交
732
        let path = cstr(path)?;
733 734 735 736
        File::open_c(&path, opts)
    }

    pub fn open_c(path: &CStr, opts: &OpenOptions) -> io::Result<File> {
M
Mark Rousskov 已提交
737 738 739 740
        let flags = libc::O_CLOEXEC
            | opts.get_access_mode()?
            | opts.get_creation_mode()?
            | (opts.custom_flags as c_int & !libc::O_ACCMODE);
741 742 743 744
        // The third argument of `open64` is documented to have type `mode_t`. On
        // some platforms (like macOS, where `open64` is actually `open`), `mode_t` is `u16`.
        // However, since this is a variadic function, C integer promotion rules mean that on
        // the ABI level, this still gets passed as `c_int` (aka `u32` on Unix platforms).
M
Mark Rousskov 已提交
745
        let fd = cvt_r(|| unsafe { open64(path.as_ptr(), flags, opts.mode as c_int) })?;
746
        Ok(File(FileDesc::new(fd)))
A
Alex Crichton 已提交
747 748 749
    }

    pub fn file_attr(&self) -> io::Result<FileAttr> {
O
oxalica 已提交
750 751
        let fd = self.0.raw();

O
oxalica 已提交
752
        cfg_has_statx! {
O
oxalica 已提交
753 754 755 756 757 758 759 760 761 762
            if let Some(ret) = unsafe { try_statx(
                fd,
                b"\0" as *const _ as *const libc::c_char,
                libc::AT_EMPTY_PATH | libc::AT_STATX_SYNC_AS_STAT,
                libc::STATX_ALL,
            ) } {
                return ret;
            }
        }

763
        let mut stat: stat64 = unsafe { mem::zeroed() };
M
Mark Rousskov 已提交
764
        cvt(unsafe { fstat64(fd, &mut stat) })?;
O
oxalica 已提交
765
        Ok(FileAttr::from_stat64(stat))
A
Alex Crichton 已提交
766 767 768
    }

    pub fn fsync(&self) -> io::Result<()> {
D
David Vázquez Púa 已提交
769 770 771 772 773 774 775 776
        cvt_r(|| unsafe { os_fsync(self.0.raw()) })?;
        return Ok(());

        #[cfg(any(target_os = "macos", target_os = "ios"))]
        unsafe fn os_fsync(fd: c_int) -> c_int {
            libc::fcntl(fd, libc::F_FULLFSYNC)
        }
        #[cfg(not(any(target_os = "macos", target_os = "ios")))]
M
Mark Rousskov 已提交
777 778 779
        unsafe fn os_fsync(fd: c_int) -> c_int {
            libc::fsync(fd)
        }
A
Alex Crichton 已提交
780 781 782
    }

    pub fn datasync(&self) -> io::Result<()> {
J
Jorge Aparicio 已提交
783
        cvt_r(|| unsafe { os_datasync(self.0.raw()) })?;
A
Alex Crichton 已提交
784 785 786 787 788 789 790
        return Ok(());

        #[cfg(any(target_os = "macos", target_os = "ios"))]
        unsafe fn os_datasync(fd: c_int) -> c_int {
            libc::fcntl(fd, libc::F_FULLFSYNC)
        }
        #[cfg(target_os = "linux")]
M
Mark Rousskov 已提交
791 792 793 794 795 796 797
        unsafe fn os_datasync(fd: c_int) -> c_int {
            libc::fdatasync(fd)
        }
        #[cfg(not(any(target_os = "macos", target_os = "ios", target_os = "linux")))]
        unsafe fn os_datasync(fd: c_int) -> c_int {
            libc::fsync(fd)
        }
A
Alex Crichton 已提交
798 799 800
    }

    pub fn truncate(&self, size: u64) -> io::Result<()> {
801
        #[cfg(target_os = "android")]
T
Taiki Endo 已提交
802
        return crate::sys::android::ftruncate64(self.0.raw(), size);
803 804

        #[cfg(not(target_os = "android"))]
805
        {
806
            use crate::convert::TryInto;
M
Mark Rousskov 已提交
807 808
            let size: off64_t =
                size.try_into().map_err(|e| io::Error::new(io::ErrorKind::InvalidInput, e))?;
809
            cvt_r(|| unsafe { ftruncate64(self.0.raw(), size) }).map(drop)
810
        }
A
Alex Crichton 已提交
811 812 813 814 815 816
    }

    pub fn read(&self, buf: &mut [u8]) -> io::Result<usize> {
        self.0.read(buf)
    }

S
Steven Fackler 已提交
817
    pub fn read_vectored(&self, bufs: &mut [IoSliceMut<'_>]) -> io::Result<usize> {
818 819 820
        self.0.read_vectored(bufs)
    }

821
    #[inline]
S
Steven Fackler 已提交
822 823
    pub fn is_read_vectored(&self) -> bool {
        self.0.is_read_vectored()
824 825
    }

826 827 828 829
    pub fn read_at(&self, buf: &mut [u8], offset: u64) -> io::Result<usize> {
        self.0.read_at(buf, offset)
    }

A
Alex Crichton 已提交
830 831 832 833
    pub fn write(&self, buf: &[u8]) -> io::Result<usize> {
        self.0.write(buf)
    }

S
Steven Fackler 已提交
834
    pub fn write_vectored(&self, bufs: &[IoSlice<'_>]) -> io::Result<usize> {
835 836 837
        self.0.write_vectored(bufs)
    }

838
    #[inline]
S
Steven Fackler 已提交
839 840
    pub fn is_write_vectored(&self) -> bool {
        self.0.is_write_vectored()
841 842
    }

843 844 845 846
    pub fn write_at(&self, buf: &[u8], offset: u64) -> io::Result<usize> {
        self.0.write_at(buf, offset)
    }

M
Mark Rousskov 已提交
847 848 849
    pub fn flush(&self) -> io::Result<()> {
        Ok(())
    }
A
Alex Crichton 已提交
850 851 852

    pub fn seek(&self, pos: SeekFrom) -> io::Result<u64> {
        let (whence, pos) = match pos {
853 854 855 856 857
            // Casting to `i64` is fine, too large values will end up as
            // negative which will cause an error in `lseek64`.
            SeekFrom::Start(off) => (libc::SEEK_SET, off as i64),
            SeekFrom::End(off) => (libc::SEEK_END, off),
            SeekFrom::Current(off) => (libc::SEEK_CUR, off),
A
Alex Crichton 已提交
858
        };
J
Jorge Aparicio 已提交
859
        let n = cvt(unsafe { lseek64(self.0.raw(), pos, whence) })?;
A
Alex Crichton 已提交
860 861 862
        Ok(n as u64)
    }

S
Steven Fackler 已提交
863 864 865 866
    pub fn duplicate(&self) -> io::Result<File> {
        self.0.duplicate().map(File)
    }

M
Mark Rousskov 已提交
867 868 869
    pub fn fd(&self) -> &FileDesc {
        &self.0
    }
870

M
Mark Rousskov 已提交
871 872 873
    pub fn into_fd(self) -> FileDesc {
        self.0
    }
874 875 876 877 878

    pub fn set_permissions(&self, perm: FilePermissions) -> io::Result<()> {
        cvt_r(|| unsafe { libc::fchmod(self.0.raw(), perm.mode) })?;
        Ok(())
    }
A
Alex Crichton 已提交
879 880
}

A
Alex Crichton 已提交
881 882 883 884 885 886
impl DirBuilder {
    pub fn new() -> DirBuilder {
        DirBuilder { mode: 0o777 }
    }

    pub fn mkdir(&self, p: &Path) -> io::Result<()> {
J
Jorge Aparicio 已提交
887 888
        let p = cstr(p)?;
        cvt(unsafe { libc::mkdir(p.as_ptr(), self.mode) })?;
A
Alex Crichton 已提交
889 890 891
        Ok(())
    }

892 893
    pub fn set_mode(&mut self, mode: u32) {
        self.mode = mode as mode_t;
A
Alex Crichton 已提交
894 895 896
    }
}

897
fn cstr(path: &Path) -> io::Result<CString> {
J
Jorge Aparicio 已提交
898
    Ok(CString::new(path.as_os_str().as_bytes())?)
A
Alex Crichton 已提交
899 900
}

901 902 903 904 905 906
impl FromInner<c_int> for File {
    fn from_inner(fd: c_int) -> File {
        File(FileDesc::new(fd))
    }
}

C
Chris Wong 已提交
907
impl fmt::Debug for File {
908
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
C
Chris Wong 已提交
909 910 911 912 913 914 915
        #[cfg(target_os = "linux")]
        fn get_path(fd: c_int) -> Option<PathBuf> {
            let mut p = PathBuf::from("/proc/self/fd");
            p.push(&fd.to_string());
            readlink(&p).ok()
        }

916 917
        #[cfg(target_os = "macos")]
        fn get_path(fd: c_int) -> Option<PathBuf> {
B
Barosl Lee 已提交
918
            // FIXME: The use of PATH_MAX is generally not encouraged, but it
919
            // is inevitable in this case because macOS defines `fcntl` with
B
Barosl Lee 已提交
920 921 922
            // `F_GETPATH` in terms of `MAXPATHLEN`, and there are no
            // alternatives. If a better method is invented, it should be used
            // instead.
M
Mark Rousskov 已提交
923
            let mut buf = vec![0; libc::PATH_MAX as usize];
924 925 926 927 928 929
            let n = unsafe { libc::fcntl(fd, libc::F_GETPATH, buf.as_ptr()) };
            if n == -1 {
                return None;
            }
            let l = buf.iter().position(|&c| c == 0).unwrap();
            buf.truncate(l as usize);
B
Barosl Lee 已提交
930
            buf.shrink_to_fit();
931 932 933
            Some(PathBuf::from(OsString::from_vec(buf)))
        }

934 935 936 937 938 939 940 941 942 943 944 945 946
        #[cfg(target_os = "vxworks")]
        fn get_path(fd: c_int) -> Option<PathBuf> {
            let mut buf = vec![0; libc::PATH_MAX as usize];
            let n = unsafe { libc::ioctl(fd, libc::FIOGETNAME, buf.as_ptr()) };
            if n == -1 {
                return None;
            }
            let l = buf.iter().position(|&c| c == 0).unwrap();
            buf.truncate(l as usize);
            Some(PathBuf::from(OsString::from_vec(buf)))
        }

        #[cfg(not(any(target_os = "linux", target_os = "macos", target_os = "vxworks")))]
C
Chris Wong 已提交
947 948 949 950 951
        fn get_path(_fd: c_int) -> Option<PathBuf> {
            // FIXME(#24570): implement this for other Unix platforms
            None
        }

952
        #[cfg(any(target_os = "linux", target_os = "macos", target_os = "vxworks"))]
C
Chris Wong 已提交
953 954 955 956 957 958 959 960 961
        fn get_mode(fd: c_int) -> Option<(bool, bool)> {
            let mode = unsafe { libc::fcntl(fd, libc::F_GETFL) };
            if mode == -1 {
                return None;
            }
            match mode & libc::O_ACCMODE {
                libc::O_RDONLY => Some((true, false)),
                libc::O_RDWR => Some((true, true)),
                libc::O_WRONLY => Some((false, true)),
M
Mark Rousskov 已提交
962
                _ => None,
C
Chris Wong 已提交
963 964 965
            }
        }

966
        #[cfg(not(any(target_os = "linux", target_os = "macos", target_os = "vxworks")))]
C
Chris Wong 已提交
967 968 969 970 971 972
        fn get_mode(_fd: c_int) -> Option<(bool, bool)> {
            // FIXME(#24570): implement this for other Unix platforms
            None
        }

        let fd = self.0.raw();
973 974
        let mut b = f.debug_struct("File");
        b.field("fd", &fd);
C
Chris Wong 已提交
975
        if let Some(path) = get_path(fd) {
976
            b.field("path", &path);
C
Chris Wong 已提交
977 978
        }
        if let Some((read, write)) = get_mode(fd) {
979
            b.field("read", &read).field("write", &write);
C
Chris Wong 已提交
980 981 982 983 984
        }
        b.finish()
    }
}

A
Alex Crichton 已提交
985
pub fn readdir(p: &Path) -> io::Result<ReadDir> {
986
    let root = p.to_path_buf();
J
Jorge Aparicio 已提交
987
    let p = cstr(p)?;
A
Alex Crichton 已提交
988 989 990 991 992
    unsafe {
        let ptr = libc::opendir(p.as_ptr());
        if ptr.is_null() {
            Err(Error::last_os_error())
        } else {
993
            let inner = InnerReadDir { dirp: Dir(ptr), root };
994 995 996
            Ok(ReadDir {
                inner: Arc::new(inner),
                #[cfg(not(any(
997 998 999 1000
                    target_os = "solaris",
                    target_os = "illumos",
                    target_os = "fuchsia",
                    target_os = "redox",
1001 1002 1003
                )))]
                end_of_stream: false,
            })
A
Alex Crichton 已提交
1004 1005 1006 1007 1008
        }
    }
}

pub fn unlink(p: &Path) -> io::Result<()> {
J
Jorge Aparicio 已提交
1009 1010
    let p = cstr(p)?;
    cvt(unsafe { libc::unlink(p.as_ptr()) })?;
A
Alex Crichton 已提交
1011 1012 1013 1014
    Ok(())
}

pub fn rename(old: &Path, new: &Path) -> io::Result<()> {
J
Jorge Aparicio 已提交
1015 1016 1017
    let old = cstr(old)?;
    let new = cstr(new)?;
    cvt(unsafe { libc::rename(old.as_ptr(), new.as_ptr()) })?;
A
Alex Crichton 已提交
1018 1019 1020 1021
    Ok(())
}

pub fn set_perm(p: &Path, perm: FilePermissions) -> io::Result<()> {
J
Jorge Aparicio 已提交
1022 1023
    let p = cstr(p)?;
    cvt_r(|| unsafe { libc::chmod(p.as_ptr(), perm.mode) })?;
A
Alex Crichton 已提交
1024 1025 1026 1027
    Ok(())
}

pub fn rmdir(p: &Path) -> io::Result<()> {
J
Jorge Aparicio 已提交
1028 1029
    let p = cstr(p)?;
    cvt(unsafe { libc::rmdir(p.as_ptr()) })?;
A
Alex Crichton 已提交
1030 1031 1032 1033
    Ok(())
}

pub fn readlink(p: &Path) -> io::Result<PathBuf> {
J
Jorge Aparicio 已提交
1034
    let c_path = cstr(p)?;
A
Alex Crichton 已提交
1035
    let p = c_path.as_ptr();
B
Barosl Lee 已提交
1036 1037 1038 1039

    let mut buf = Vec::with_capacity(256);

    loop {
M
Mark Rousskov 已提交
1040 1041
        let buf_read =
            cvt(unsafe { libc::readlink(p, buf.as_mut_ptr() as *mut _, buf.capacity()) })? as usize;
B
Barosl Lee 已提交
1042

M
Mark Rousskov 已提交
1043 1044 1045
        unsafe {
            buf.set_len(buf_read);
        }
B
Barosl Lee 已提交
1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056

        if buf_read != buf.capacity() {
            buf.shrink_to_fit();

            return Ok(PathBuf::from(OsString::from_vec(buf)));
        }

        // Trigger the internal buffer resizing logic of `Vec` by requiring
        // more space than the current capacity. The length is guaranteed to be
        // the same as the capacity due to the if statement above.
        buf.reserve(1);
A
Alex Crichton 已提交
1057 1058 1059 1060
    }
}

pub fn symlink(src: &Path, dst: &Path) -> io::Result<()> {
J
Jorge Aparicio 已提交
1061 1062 1063
    let src = cstr(src)?;
    let dst = cstr(dst)?;
    cvt(unsafe { libc::symlink(src.as_ptr(), dst.as_ptr()) })?;
A
Alex Crichton 已提交
1064 1065 1066 1067
    Ok(())
}

pub fn link(src: &Path, dst: &Path) -> io::Result<()> {
J
Jorge Aparicio 已提交
1068 1069
    let src = cstr(src)?;
    let dst = cstr(dst)?;
1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083
    cfg_if::cfg_if! {
        if #[cfg(any(target_os = "vxworks", target_os = "redox"))] {
            // VxWorks and Redox lack `linkat`, so use `link` instead. POSIX
            // leaves it implementation-defined whether `link` follows symlinks,
            // so rely on the `symlink_hard_link` test in
            // library/std/src/fs/tests.rs to check the behavior.
            cvt(unsafe { libc::link(src.as_ptr(), dst.as_ptr()) })?;
        } else {
            // Use `linkat` with `AT_FDCWD` instead of `link` as `linkat` gives
            // us a flag to specify how symlinks should be handled. Pass 0 as
            // the flags argument, meaning don't follow symlinks.
            cvt(unsafe { libc::linkat(libc::AT_FDCWD, src.as_ptr(), libc::AT_FDCWD, dst.as_ptr(), 0) })?;
        }
    }
A
Alex Crichton 已提交
1084 1085 1086 1087
    Ok(())
}

pub fn stat(p: &Path) -> io::Result<FileAttr> {
J
Jorge Aparicio 已提交
1088
    let p = cstr(p)?;
O
oxalica 已提交
1089

O
oxalica 已提交
1090
    cfg_has_statx! {
O
oxalica 已提交
1091 1092 1093 1094 1095 1096 1097 1098 1099 1100
        if let Some(ret) = unsafe { try_statx(
            libc::AT_FDCWD,
            p.as_ptr(),
            libc::AT_STATX_SYNC_AS_STAT,
            libc::STATX_ALL,
        ) } {
            return ret;
        }
    }

1101
    let mut stat: stat64 = unsafe { mem::zeroed() };
M
Mark Rousskov 已提交
1102
    cvt(unsafe { stat64(p.as_ptr(), &mut stat) })?;
O
oxalica 已提交
1103
    Ok(FileAttr::from_stat64(stat))
A
Alex Crichton 已提交
1104 1105 1106
}

pub fn lstat(p: &Path) -> io::Result<FileAttr> {
J
Jorge Aparicio 已提交
1107
    let p = cstr(p)?;
O
oxalica 已提交
1108

O
oxalica 已提交
1109
    cfg_has_statx! {
O
oxalica 已提交
1110 1111 1112 1113 1114 1115 1116 1117 1118 1119
        if let Some(ret) = unsafe { try_statx(
            libc::AT_FDCWD,
            p.as_ptr(),
            libc::AT_SYMLINK_NOFOLLOW | libc::AT_STATX_SYNC_AS_STAT,
            libc::STATX_ALL,
        ) } {
            return ret;
        }
    }

1120
    let mut stat: stat64 = unsafe { mem::zeroed() };
M
Mark Rousskov 已提交
1121
    cvt(unsafe { lstat64(p.as_ptr(), &mut stat) })?;
O
oxalica 已提交
1122
    Ok(FileAttr::from_stat64(stat))
A
Alex Crichton 已提交
1123 1124
}

A
Alex Crichton 已提交
1125
pub fn canonicalize(p: &Path) -> io::Result<PathBuf> {
J
Jorge Aparicio 已提交
1126
    let path = CString::new(p.as_os_str().as_bytes())?;
B
Barosl Lee 已提交
1127
    let buf;
A
Alex Crichton 已提交
1128
    unsafe {
A
Alex Crichton 已提交
1129
        let r = libc::realpath(path.as_ptr(), ptr::null_mut());
A
Alex Crichton 已提交
1130
        if r.is_null() {
M
Mark Rousskov 已提交
1131
            return Err(io::Error::last_os_error());
A
Alex Crichton 已提交
1132
        }
B
Barosl Lee 已提交
1133 1134
        buf = CStr::from_ptr(r).to_bytes().to_vec();
        libc::free(r as *mut _);
A
Alex Crichton 已提交
1135 1136 1137
    }
    Ok(PathBuf::from(OsString::from_vec(buf)))
}
1138

1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153
fn open_from(from: &Path) -> io::Result<(crate::fs::File, crate::fs::Metadata)> {
    use crate::fs::File;

    let reader = File::open(from)?;
    let metadata = reader.metadata()?;
    if !metadata.is_file() {
        return Err(Error::new(
            ErrorKind::InvalidInput,
            "the source path is not an existing regular file",
        ));
    }
    Ok((reader, metadata))
}

fn open_to_and_set_permissions(
H
Harald Hoyer 已提交
1154
    to: &Path,
1155 1156 1157
    reader_metadata: crate::fs::Metadata,
) -> io::Result<(crate::fs::File, crate::fs::Metadata)> {
    use crate::fs::OpenOptions;
H
Harald Hoyer 已提交
1158 1159
    use crate::os::unix::fs::{OpenOptionsExt, PermissionsExt};

1160
    let perm = reader_metadata.permissions();
H
Harald Hoyer 已提交
1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174
    let writer = OpenOptions::new()
        // create the file with the correct mode right away
        .mode(perm.mode())
        .write(true)
        .create(true)
        .truncate(true)
        .open(to)?;
    let writer_metadata = writer.metadata()?;
    if writer_metadata.is_file() {
        // Set the correct file permissions, in case the file already existed.
        // Don't set the permissions on already existing non-files like
        // pipes/FIFOs or device nodes.
        writer.set_permissions(perm)?;
    }
1175
    Ok((writer, writer_metadata))
H
Harald Hoyer 已提交
1176 1177
}

M
Mark Rousskov 已提交
1178 1179 1180 1181 1182 1183
#[cfg(not(any(
    target_os = "linux",
    target_os = "android",
    target_os = "macos",
    target_os = "ios"
)))]
1184
pub fn copy(from: &Path, to: &Path) -> io::Result<u64> {
1185 1186
    let (mut reader, reader_metadata) = open_from(from)?;
    let (mut writer, _) = open_to_and_set_permissions(to, reader_metadata)?;
1187

H
Harald Hoyer 已提交
1188
    io::copy(&mut reader, &mut writer)
1189
}
N
Nicolas Koch 已提交
1190

1191
#[cfg(any(target_os = "linux", target_os = "android"))]
N
Nicolas Koch 已提交
1192
pub fn copy(from: &Path, to: &Path) -> io::Result<u64> {
T
Taiki Endo 已提交
1193 1194
    use crate::cmp;
    use crate::sync::atomic::{AtomicBool, Ordering};
1195 1196

    // Kernel prior to 4.5 don't have copy_file_range
M
Matthias Krüger 已提交
1197
    // We store the availability in a global to avoid unnecessary syscalls
1198
    static HAS_COPY_FILE_RANGE: AtomicBool = AtomicBool::new(true);
N
Nicolas Koch 已提交
1199 1200 1201 1202 1203 1204 1205 1206 1207

    unsafe fn copy_file_range(
        fd_in: libc::c_int,
        off_in: *mut libc::loff_t,
        fd_out: libc::c_int,
        off_out: *mut libc::loff_t,
        len: libc::size_t,
        flags: libc::c_uint,
    ) -> libc::c_long {
M
Mark Rousskov 已提交
1208
        libc::syscall(libc::SYS_copy_file_range, fd_in, off_in, fd_out, off_out, len, flags)
N
Nicolas Koch 已提交
1209 1210
    }

1211
    let (mut reader, reader_metadata) = open_from(from)?;
1212
    let max_len = u64::MAX;
1213
    let (mut writer, _) = open_to_and_set_permissions(to, reader_metadata)?;
1214

N
Nicolas Koch 已提交
1215
    let has_copy_file_range = HAS_COPY_FILE_RANGE.load(Ordering::Relaxed);
N
Nicolas Koch 已提交
1216
    let mut written = 0u64;
1217
    while written < max_len {
N
Nicolas Koch 已提交
1218
        let copy_result = if has_copy_file_range {
1219
            let bytes_to_copy = cmp::min(max_len - written, usize::MAX as u64) as usize;
1220 1221 1222
            let copy_result = unsafe {
                // We actually don't have to adjust the offsets,
                // because copy_file_range adjusts the file offset automatically
H
Harald Hoyer 已提交
1223 1224 1225 1226 1227 1228 1229 1230
                cvt(copy_file_range(
                    reader.as_raw_fd(),
                    ptr::null_mut(),
                    writer.as_raw_fd(),
                    ptr::null_mut(),
                    bytes_to_copy,
                    0,
                ))
1231 1232
            };
            if let Err(ref copy_err) = copy_result {
1233
                match copy_err.raw_os_error() {
T
The8472 已提交
1234
                    Some(libc::ENOSYS | libc::EPERM | libc::EOPNOTSUPP) => {
1235 1236 1237
                        HAS_COPY_FILE_RANGE.store(false, Ordering::Relaxed);
                    }
                    _ => {}
1238 1239 1240 1241 1242
                }
            }
            copy_result
        } else {
            Err(io::Error::from_raw_os_error(libc::ENOSYS))
N
Nicolas Koch 已提交
1243 1244
        };
        match copy_result {
1245 1246 1247 1248 1249 1250 1251 1252 1253
            Ok(0) if written == 0 => {
                // fallback to work around several kernel bugs where copy_file_range will fail to
                // copy any bytes and return 0 instead of an error if
                // - reading virtual files from the proc filesystem which appear to have 0 size
                //   but are not empty. noted in coreutils to affect kernels at least up to 5.6.19.
                // - copying from an overlay filesystem in docker. reported to occur on fedora 32.
                return io::copy(&mut reader, &mut writer);
            }
            Ok(0) => return Ok(written), // reached EOF
N
Nicolas Koch 已提交
1254 1255 1256
            Ok(ret) => written += ret as u64,
            Err(err) => {
                match err.raw_os_error() {
T
The8472 已提交
1257 1258 1259
                    Some(
                        libc::ENOSYS | libc::EXDEV | libc::EINVAL | libc::EPERM | libc::EOPNOTSUPP,
                    ) => {
M
Mark Rousskov 已提交
1260 1261 1262
                        // Try fallback io::copy if either:
                        // - Kernel version is < 4.5 (ENOSYS)
                        // - Files are mounted on different fs (EXDEV)
1263
                        // - copy_file_range is broken in various ways on RHEL/CentOS 7 (EOPNOTSUPP)
M
Mark Rousskov 已提交
1264 1265 1266 1267 1268
                        // - copy_file_range is disallowed, for example by seccomp (EPERM)
                        // - copy_file_range cannot be used with pipes or device nodes (EINVAL)
                        assert_eq!(written, 0);
                        return io::copy(&mut reader, &mut writer);
                    }
N
Nicolas Koch 已提交
1269 1270 1271 1272 1273 1274 1275
                    _ => return Err(err),
                }
            }
        }
    }
    Ok(written)
}
1276 1277 1278

#[cfg(any(target_os = "macos", target_os = "ios"))]
pub fn copy(from: &Path, to: &Path) -> io::Result<u64> {
1279 1280
    use crate::sync::atomic::{AtomicBool, Ordering};

1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297
    const COPYFILE_ACL: u32 = 1 << 0;
    const COPYFILE_STAT: u32 = 1 << 1;
    const COPYFILE_XATTR: u32 = 1 << 2;
    const COPYFILE_DATA: u32 = 1 << 3;

    const COPYFILE_SECURITY: u32 = COPYFILE_STAT | COPYFILE_ACL;
    const COPYFILE_METADATA: u32 = COPYFILE_SECURITY | COPYFILE_XATTR;
    const COPYFILE_ALL: u32 = COPYFILE_METADATA | COPYFILE_DATA;

    const COPYFILE_STATE_COPIED: u32 = 8;

    #[allow(non_camel_case_types)]
    type copyfile_state_t = *mut libc::c_void;
    #[allow(non_camel_case_types)]
    type copyfile_flags_t = u32;

    extern "C" {
H
Harald Hoyer 已提交
1298 1299 1300
        fn fcopyfile(
            from: libc::c_int,
            to: libc::c_int,
1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318
            state: copyfile_state_t,
            flags: copyfile_flags_t,
        ) -> libc::c_int;
        fn copyfile_state_alloc() -> copyfile_state_t;
        fn copyfile_state_free(state: copyfile_state_t) -> libc::c_int;
        fn copyfile_state_get(
            state: copyfile_state_t,
            flag: u32,
            dst: *mut libc::c_void,
        ) -> libc::c_int;
    }

    struct FreeOnDrop(copyfile_state_t);
    impl Drop for FreeOnDrop {
        fn drop(&mut self) {
            // The code below ensures that `FreeOnDrop` is never a null pointer
            unsafe {
                // `copyfile_state_free` returns -1 if the `to` or `from` files
B
Brian Wignall 已提交
1319
                // cannot be closed. However, this is not considered this an
1320 1321 1322 1323 1324 1325
                // error.
                copyfile_state_free(self.0);
            }
        }
    }

1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343
    // MacOS prior to 10.12 don't support `fclonefileat`
    // We store the availability in a global to avoid unnecessary syscalls
    static HAS_FCLONEFILEAT: AtomicBool = AtomicBool::new(true);
    syscall! {
        fn fclonefileat(
            srcfd: libc::c_int,
            dst_dirfd: libc::c_int,
            dst: *const libc::c_char,
            flags: libc::c_int
        ) -> libc::c_int
    }

    let (reader, reader_metadata) = open_from(from)?;

    // Opportunistically attempt to create a copy-on-write clone of `from`
    // using `fclonefileat`.
    if HAS_FCLONEFILEAT.load(Ordering::Relaxed) {
        let to = cstr(to)?;
M
Mark Rousskov 已提交
1344 1345
        let clonefile_result =
            cvt(unsafe { fclonefileat(reader.as_raw_fd(), libc::AT_FDCWD, to.as_ptr(), 0) });
1346 1347 1348 1349 1350 1351 1352 1353 1354 1355
        match clonefile_result {
            Ok(_) => return Ok(reader_metadata.len()),
            Err(err) => match err.raw_os_error() {
                // `fclonefileat` will fail on non-APFS volumes, if the
                // destination already exists, or if the source and destination
                // are on different devices. In all these cases `fcopyfile`
                // should succeed.
                Some(libc::ENOTSUP) | Some(libc::EEXIST) | Some(libc::EXDEV) => (),
                Some(libc::ENOSYS) => HAS_FCLONEFILEAT.store(false, Ordering::Relaxed),
                _ => return Err(err),
M
Mark Rousskov 已提交
1356
            },
1357 1358 1359 1360 1361
        }
    }

    // Fall back to using `fcopyfile` if `fclonefileat` does not succeed.
    let (writer, writer_metadata) = open_to_and_set_permissions(to, reader_metadata)?;
1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372

    // We ensure that `FreeOnDrop` never contains a null pointer so it is
    // always safe to call `copyfile_state_free`
    let state = unsafe {
        let state = copyfile_state_alloc();
        if state.is_null() {
            return Err(crate::io::Error::last_os_error());
        }
        FreeOnDrop(state)
    };

M
Mark Rousskov 已提交
1373
    let flags = if writer_metadata.is_file() { COPYFILE_ALL } else { COPYFILE_DATA };
H
Harald Hoyer 已提交
1374

M
Mark Rousskov 已提交
1375
    cvt(unsafe { fcopyfile(reader.as_raw_fd(), writer.as_raw_fd(), state.0, flags) })?;
1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386

    let mut bytes_copied: libc::off_t = 0;
    cvt(unsafe {
        copyfile_state_get(
            state.0,
            COPYFILE_STATE_COPIED,
            &mut bytes_copied as *mut libc::off_t as *mut libc::c_void,
        )
    })?;
    Ok(bytes_copied as u64)
}