| 1 | #![allow (nonstandard_style)] |
| 2 | #![allow (unsafe_op_in_unsafe_fn)] |
| 3 | // miri has some special hacks here that make things unused. |
| 4 | #![cfg_attr (miri, allow(unused))] |
| 5 | |
| 6 | #[cfg (test)] |
| 7 | mod tests; |
| 8 | |
| 9 | #[cfg (all(target_os = "linux" , target_env = "gnu" ))] |
| 10 | use libc::c_char; |
| 11 | #[cfg (any( |
| 12 | all(target_os = "linux" , not(target_env = "musl" )), |
| 13 | target_os = "android" , |
| 14 | target_os = "fuchsia" , |
| 15 | target_os = "hurd" , |
| 16 | target_os = "illumos" , |
| 17 | target_vendor = "apple" , |
| 18 | ))] |
| 19 | use libc::dirfd; |
| 20 | #[cfg (any(target_os = "fuchsia" , target_os = "illumos" , target_vendor = "apple" ))] |
| 21 | use libc::fstatat as fstatat64; |
| 22 | #[cfg (any(all(target_os = "linux" , not(target_env = "musl" )), target_os = "hurd" ))] |
| 23 | use libc::fstatat64; |
| 24 | #[cfg (any( |
| 25 | target_os = "aix" , |
| 26 | target_os = "android" , |
| 27 | target_os = "freebsd" , |
| 28 | target_os = "fuchsia" , |
| 29 | target_os = "illumos" , |
| 30 | target_os = "nto" , |
| 31 | target_os = "redox" , |
| 32 | target_os = "solaris" , |
| 33 | target_os = "vita" , |
| 34 | all(target_os = "linux" , target_env = "musl" ), |
| 35 | ))] |
| 36 | use libc::readdir as readdir64; |
| 37 | #[cfg (not(any( |
| 38 | target_os = "aix" , |
| 39 | target_os = "android" , |
| 40 | target_os = "freebsd" , |
| 41 | target_os = "fuchsia" , |
| 42 | target_os = "hurd" , |
| 43 | target_os = "illumos" , |
| 44 | target_os = "l4re" , |
| 45 | target_os = "linux" , |
| 46 | target_os = "nto" , |
| 47 | target_os = "redox" , |
| 48 | target_os = "solaris" , |
| 49 | target_os = "vita" , |
| 50 | )))] |
| 51 | use libc::readdir_r as readdir64_r; |
| 52 | #[cfg (any(all(target_os = "linux" , not(target_env = "musl" )), target_os = "hurd" ))] |
| 53 | use libc::readdir64; |
| 54 | #[cfg (target_os = "l4re" )] |
| 55 | use libc::readdir64_r; |
| 56 | use libc::{c_int, mode_t}; |
| 57 | #[cfg (target_os = "android" )] |
| 58 | use libc::{ |
| 59 | dirent as dirent64, fstat as fstat64, fstatat as fstatat64, ftruncate64, lseek64, |
| 60 | lstat as lstat64, off64_t, open as open64, stat as stat64, |
| 61 | }; |
| 62 | #[cfg (not(any( |
| 63 | all(target_os = "linux" , not(target_env = "musl" )), |
| 64 | target_os = "l4re" , |
| 65 | target_os = "android" , |
| 66 | target_os = "hurd" , |
| 67 | )))] |
| 68 | use libc::{ |
| 69 | dirent as dirent64, fstat as fstat64, ftruncate as ftruncate64, lseek as lseek64, |
| 70 | lstat as lstat64, off_t as off64_t, open as open64, stat as stat64, |
| 71 | }; |
| 72 | #[cfg (any( |
| 73 | all(target_os = "linux" , not(target_env = "musl" )), |
| 74 | target_os = "l4re" , |
| 75 | target_os = "hurd" |
| 76 | ))] |
| 77 | use libc::{dirent64, fstat64, ftruncate64, lseek64, lstat64, off64_t, open64, stat64}; |
| 78 | |
| 79 | use crate::ffi::{CStr, OsStr, OsString}; |
| 80 | use crate::fmt::{self, Write as _}; |
| 81 | use crate::fs::TryLockError; |
| 82 | use crate::io::{self, BorrowedCursor, Error, IoSlice, IoSliceMut, SeekFrom}; |
| 83 | use crate::os::unix::io::{AsFd, AsRawFd, BorrowedFd, FromRawFd, IntoRawFd}; |
| 84 | use crate::os::unix::prelude::*; |
| 85 | use crate::path::{Path, PathBuf}; |
| 86 | use crate::sync::Arc; |
| 87 | use crate::sys::common::small_c_string::run_path_with_cstr; |
| 88 | use crate::sys::fd::FileDesc; |
| 89 | pub use crate::sys::fs::common::exists; |
| 90 | use crate::sys::time::SystemTime; |
| 91 | #[cfg (all(target_os = "linux" , target_env = "gnu" ))] |
| 92 | use crate::sys::weak::syscall; |
| 93 | #[cfg (target_os = "android" )] |
| 94 | use crate::sys::weak::weak; |
| 95 | use crate::sys::{cvt, cvt_r}; |
| 96 | use crate::sys_common::{AsInner, AsInnerMut, FromInner, IntoInner}; |
| 97 | use crate::{mem, ptr}; |
| 98 | |
| 99 | pub struct File(FileDesc); |
| 100 | |
| 101 | // FIXME: This should be available on Linux with all `target_env`. |
| 102 | // But currently only glibc exposes `statx` fn and structs. |
| 103 | // We don't want to import unverified raw C structs here directly. |
| 104 | // https://github.com/rust-lang/rust/pull/67774 |
| 105 | macro_rules! cfg_has_statx { |
| 106 | ({ $($then_tt:tt)* } else { $($else_tt:tt)* }) => { |
| 107 | cfg_select! { |
| 108 | all(target_os = "linux" , target_env = "gnu" ) => { |
| 109 | $($then_tt)* |
| 110 | } |
| 111 | _ => { |
| 112 | $($else_tt)* |
| 113 | } |
| 114 | } |
| 115 | }; |
| 116 | ($($block_inner:tt)*) => { |
| 117 | #[cfg(all(target_os = "linux" , target_env = "gnu" ))] |
| 118 | { |
| 119 | $($block_inner)* |
| 120 | } |
| 121 | }; |
| 122 | } |
| 123 | |
| 124 | cfg_has_statx! {{ |
| 125 | #[derive (Clone)] |
| 126 | pub struct FileAttr { |
| 127 | stat: stat64, |
| 128 | statx_extra_fields: Option<StatxExtraFields>, |
| 129 | } |
| 130 | |
| 131 | #[derive (Clone)] |
| 132 | struct StatxExtraFields { |
| 133 | // This is needed to check if btime is supported by the filesystem. |
| 134 | stx_mask: u32, |
| 135 | stx_btime: libc::statx_timestamp, |
| 136 | // With statx, we can overcome 32-bit `time_t` too. |
| 137 | #[cfg (target_pointer_width = "32" )] |
| 138 | stx_atime: libc::statx_timestamp, |
| 139 | #[cfg (target_pointer_width = "32" )] |
| 140 | stx_ctime: libc::statx_timestamp, |
| 141 | #[cfg (target_pointer_width = "32" )] |
| 142 | stx_mtime: libc::statx_timestamp, |
| 143 | |
| 144 | } |
| 145 | |
| 146 | // We prefer `statx` on Linux if available, which contains file creation time, |
| 147 | // as well as 64-bit timestamps of all kinds. |
| 148 | // Default `stat64` contains no creation time and may have 32-bit `time_t`. |
| 149 | unsafe fn try_statx( |
| 150 | fd: c_int, |
| 151 | path: *const c_char, |
| 152 | flags: i32, |
| 153 | mask: u32, |
| 154 | ) -> Option<io::Result<FileAttr>> { |
| 155 | use crate::sync::atomic::{Atomic, AtomicU8, Ordering}; |
| 156 | |
| 157 | // Linux kernel prior to 4.11 or glibc prior to glibc 2.28 don't support `statx`. |
| 158 | // We check for it on first failure and remember availability to avoid having to |
| 159 | // do it again. |
| 160 | #[repr (u8)] |
| 161 | enum STATX_STATE{ Unknown = 0, Present, Unavailable } |
| 162 | static STATX_SAVED_STATE: Atomic<u8> = AtomicU8::new(STATX_STATE::Unknown as u8); |
| 163 | |
| 164 | syscall!( |
| 165 | fn statx( |
| 166 | fd: c_int, |
| 167 | pathname: *const c_char, |
| 168 | flags: c_int, |
| 169 | mask: libc::c_uint, |
| 170 | statxbuf: *mut libc::statx, |
| 171 | ) -> c_int; |
| 172 | ); |
| 173 | |
| 174 | let statx_availability = STATX_SAVED_STATE.load(Ordering::Relaxed); |
| 175 | if statx_availability == STATX_STATE::Unavailable as u8 { |
| 176 | return None; |
| 177 | } |
| 178 | |
| 179 | let mut buf: libc::statx = mem::zeroed(); |
| 180 | if let Err(err) = cvt(statx(fd, path, flags, mask, &mut buf)) { |
| 181 | if STATX_SAVED_STATE.load(Ordering::Relaxed) == STATX_STATE::Present as u8 { |
| 182 | return Some(Err(err)); |
| 183 | } |
| 184 | |
| 185 | // We're not yet entirely sure whether `statx` is usable on this kernel |
| 186 | // or not. Syscalls can return errors from things other than the kernel |
| 187 | // per se, e.g. `EPERM` can be returned if seccomp is used to block the |
| 188 | // syscall, or `ENOSYS` might be returned from a faulty FUSE driver. |
| 189 | // |
| 190 | // Availability is checked by performing a call which expects `EFAULT` |
| 191 | // if the syscall is usable. |
| 192 | // |
| 193 | // See: https://github.com/rust-lang/rust/issues/65662 |
| 194 | // |
| 195 | // FIXME what about transient conditions like `ENOMEM`? |
| 196 | let err2 = cvt(statx(0, ptr::null(), 0, libc::STATX_BASIC_STATS | libc::STATX_BTIME, ptr::null_mut())) |
| 197 | .err() |
| 198 | .and_then(|e| e.raw_os_error()); |
| 199 | if err2 == Some(libc::EFAULT) { |
| 200 | STATX_SAVED_STATE.store(STATX_STATE::Present as u8, Ordering::Relaxed); |
| 201 | return Some(Err(err)); |
| 202 | } else { |
| 203 | STATX_SAVED_STATE.store(STATX_STATE::Unavailable as u8, Ordering::Relaxed); |
| 204 | return None; |
| 205 | } |
| 206 | } |
| 207 | if statx_availability == STATX_STATE::Unknown as u8 { |
| 208 | STATX_SAVED_STATE.store(STATX_STATE::Present as u8, Ordering::Relaxed); |
| 209 | } |
| 210 | |
| 211 | // We cannot fill `stat64` exhaustively because of private padding fields. |
| 212 | let mut stat: stat64 = mem::zeroed(); |
| 213 | // `c_ulong` on gnu-mips, `dev_t` otherwise |
| 214 | stat.st_dev = libc::makedev(buf.stx_dev_major, buf.stx_dev_minor) as _; |
| 215 | stat.st_ino = buf.stx_ino as libc::ino64_t; |
| 216 | stat.st_nlink = buf.stx_nlink as libc::nlink_t; |
| 217 | stat.st_mode = buf.stx_mode as libc::mode_t; |
| 218 | stat.st_uid = buf.stx_uid as libc::uid_t; |
| 219 | stat.st_gid = buf.stx_gid as libc::gid_t; |
| 220 | stat.st_rdev = libc::makedev(buf.stx_rdev_major, buf.stx_rdev_minor) as _; |
| 221 | stat.st_size = buf.stx_size as off64_t; |
| 222 | stat.st_blksize = buf.stx_blksize as libc::blksize_t; |
| 223 | stat.st_blocks = buf.stx_blocks as libc::blkcnt64_t; |
| 224 | stat.st_atime = buf.stx_atime.tv_sec as libc::time_t; |
| 225 | // `i64` on gnu-x86_64-x32, `c_ulong` otherwise. |
| 226 | stat.st_atime_nsec = buf.stx_atime.tv_nsec as _; |
| 227 | stat.st_mtime = buf.stx_mtime.tv_sec as libc::time_t; |
| 228 | stat.st_mtime_nsec = buf.stx_mtime.tv_nsec as _; |
| 229 | stat.st_ctime = buf.stx_ctime.tv_sec as libc::time_t; |
| 230 | stat.st_ctime_nsec = buf.stx_ctime.tv_nsec as _; |
| 231 | |
| 232 | let extra = StatxExtraFields { |
| 233 | stx_mask: buf.stx_mask, |
| 234 | stx_btime: buf.stx_btime, |
| 235 | // Store full times to avoid 32-bit `time_t` truncation. |
| 236 | #[cfg (target_pointer_width = "32" )] |
| 237 | stx_atime: buf.stx_atime, |
| 238 | #[cfg (target_pointer_width = "32" )] |
| 239 | stx_ctime: buf.stx_ctime, |
| 240 | #[cfg (target_pointer_width = "32" )] |
| 241 | stx_mtime: buf.stx_mtime, |
| 242 | }; |
| 243 | |
| 244 | Some(Ok(FileAttr { stat, statx_extra_fields: Some(extra) })) |
| 245 | } |
| 246 | |
| 247 | } else { |
| 248 | #[derive(Clone)] |
| 249 | pub struct FileAttr { |
| 250 | stat: stat64, |
| 251 | } |
| 252 | }} |
| 253 | |
| 254 | // all DirEntry's will have a reference to this struct |
| 255 | struct InnerReadDir { |
| 256 | dirp: Dir, |
| 257 | root: PathBuf, |
| 258 | } |
| 259 | |
| 260 | pub struct ReadDir { |
| 261 | inner: Arc<InnerReadDir>, |
| 262 | end_of_stream: bool, |
| 263 | } |
| 264 | |
| 265 | impl ReadDir { |
| 266 | fn new(inner: InnerReadDir) -> Self { |
| 267 | Self { inner: Arc::new(data:inner), end_of_stream: false } |
| 268 | } |
| 269 | } |
| 270 | |
| 271 | struct Dir(*mut libc::DIR); |
| 272 | |
| 273 | unsafe impl Send for Dir {} |
| 274 | unsafe impl Sync for Dir {} |
| 275 | |
| 276 | #[cfg (any( |
| 277 | target_os = "aix" , |
| 278 | target_os = "android" , |
| 279 | target_os = "freebsd" , |
| 280 | target_os = "fuchsia" , |
| 281 | target_os = "hurd" , |
| 282 | target_os = "illumos" , |
| 283 | target_os = "linux" , |
| 284 | target_os = "nto" , |
| 285 | target_os = "redox" , |
| 286 | target_os = "solaris" , |
| 287 | target_os = "vita" , |
| 288 | ))] |
| 289 | pub struct DirEntry { |
| 290 | dir: Arc<InnerReadDir>, |
| 291 | entry: dirent64_min, |
| 292 | // We need to store an owned copy of the entry name on platforms that use |
| 293 | // readdir() (not readdir_r()), because a) struct dirent may use a flexible |
| 294 | // array to store the name, b) it lives only until the next readdir() call. |
| 295 | name: crate::ffi::CString, |
| 296 | } |
| 297 | |
| 298 | // Define a minimal subset of fields we need from `dirent64`, especially since |
| 299 | // we're not using the immediate `d_name` on these targets. Keeping this as an |
| 300 | // `entry` field in `DirEntry` helps reduce the `cfg` boilerplate elsewhere. |
| 301 | #[cfg (any( |
| 302 | target_os = "aix" , |
| 303 | target_os = "android" , |
| 304 | target_os = "freebsd" , |
| 305 | target_os = "fuchsia" , |
| 306 | target_os = "hurd" , |
| 307 | target_os = "illumos" , |
| 308 | target_os = "linux" , |
| 309 | target_os = "nto" , |
| 310 | target_os = "redox" , |
| 311 | target_os = "solaris" , |
| 312 | target_os = "vita" , |
| 313 | ))] |
| 314 | struct dirent64_min { |
| 315 | d_ino: u64, |
| 316 | #[cfg (not(any( |
| 317 | target_os = "solaris" , |
| 318 | target_os = "illumos" , |
| 319 | target_os = "aix" , |
| 320 | target_os = "nto" , |
| 321 | target_os = "vita" , |
| 322 | )))] |
| 323 | d_type: u8, |
| 324 | } |
| 325 | |
| 326 | #[cfg (not(any( |
| 327 | target_os = "aix" , |
| 328 | target_os = "android" , |
| 329 | target_os = "freebsd" , |
| 330 | target_os = "fuchsia" , |
| 331 | target_os = "hurd" , |
| 332 | target_os = "illumos" , |
| 333 | target_os = "linux" , |
| 334 | target_os = "nto" , |
| 335 | target_os = "redox" , |
| 336 | target_os = "solaris" , |
| 337 | target_os = "vita" , |
| 338 | )))] |
| 339 | pub struct DirEntry { |
| 340 | dir: Arc<InnerReadDir>, |
| 341 | // The full entry includes a fixed-length `d_name`. |
| 342 | entry: dirent64, |
| 343 | } |
| 344 | |
| 345 | #[derive (Clone)] |
| 346 | pub struct OpenOptions { |
| 347 | // generic |
| 348 | read: bool, |
| 349 | write: bool, |
| 350 | append: bool, |
| 351 | truncate: bool, |
| 352 | create: bool, |
| 353 | create_new: bool, |
| 354 | // system-specific |
| 355 | custom_flags: i32, |
| 356 | mode: mode_t, |
| 357 | } |
| 358 | |
| 359 | #[derive (Clone, PartialEq, Eq)] |
| 360 | pub struct FilePermissions { |
| 361 | mode: mode_t, |
| 362 | } |
| 363 | |
| 364 | #[derive (Copy, Clone, Debug, Default)] |
| 365 | pub struct FileTimes { |
| 366 | accessed: Option<SystemTime>, |
| 367 | modified: Option<SystemTime>, |
| 368 | #[cfg (target_vendor = "apple" )] |
| 369 | created: Option<SystemTime>, |
| 370 | } |
| 371 | |
| 372 | #[derive (Copy, Clone, Eq)] |
| 373 | pub struct FileType { |
| 374 | mode: mode_t, |
| 375 | } |
| 376 | |
| 377 | impl PartialEq for FileType { |
| 378 | fn eq(&self, other: &Self) -> bool { |
| 379 | self.masked() == other.masked() |
| 380 | } |
| 381 | } |
| 382 | |
| 383 | impl core::hash::Hash for FileType { |
| 384 | fn hash<H: core::hash::Hasher>(&self, state: &mut H) { |
| 385 | self.masked().hash(state); |
| 386 | } |
| 387 | } |
| 388 | |
| 389 | pub struct DirBuilder { |
| 390 | mode: mode_t, |
| 391 | } |
| 392 | |
| 393 | #[derive (Copy, Clone)] |
| 394 | struct Mode(mode_t); |
| 395 | |
| 396 | cfg_has_statx! {{ |
| 397 | impl FileAttr { |
| 398 | fn from_stat64(stat: stat64) -> Self { |
| 399 | Self { stat, statx_extra_fields: None } |
| 400 | } |
| 401 | |
| 402 | #[cfg (target_pointer_width = "32" )] |
| 403 | pub fn stx_mtime(&self) -> Option<&libc::statx_timestamp> { |
| 404 | if let Some(ext) = &self.statx_extra_fields { |
| 405 | if (ext.stx_mask & libc::STATX_MTIME) != 0 { |
| 406 | return Some(&ext.stx_mtime); |
| 407 | } |
| 408 | } |
| 409 | None |
| 410 | } |
| 411 | |
| 412 | #[cfg (target_pointer_width = "32" )] |
| 413 | pub fn stx_atime(&self) -> Option<&libc::statx_timestamp> { |
| 414 | if let Some(ext) = &self.statx_extra_fields { |
| 415 | if (ext.stx_mask & libc::STATX_ATIME) != 0 { |
| 416 | return Some(&ext.stx_atime); |
| 417 | } |
| 418 | } |
| 419 | None |
| 420 | } |
| 421 | |
| 422 | #[cfg (target_pointer_width = "32" )] |
| 423 | pub fn stx_ctime(&self) -> Option<&libc::statx_timestamp> { |
| 424 | if let Some(ext) = &self.statx_extra_fields { |
| 425 | if (ext.stx_mask & libc::STATX_CTIME) != 0 { |
| 426 | return Some(&ext.stx_ctime); |
| 427 | } |
| 428 | } |
| 429 | None |
| 430 | } |
| 431 | } |
| 432 | } else { |
| 433 | impl FileAttr { |
| 434 | fn from_stat64(stat: stat64) -> Self { |
| 435 | Self { stat } |
| 436 | } |
| 437 | } |
| 438 | }} |
| 439 | |
| 440 | impl FileAttr { |
| 441 | pub fn size(&self) -> u64 { |
| 442 | self.stat.st_size as u64 |
| 443 | } |
| 444 | pub fn perm(&self) -> FilePermissions { |
| 445 | FilePermissions { mode: (self.stat.st_mode as mode_t) } |
| 446 | } |
| 447 | |
| 448 | pub fn file_type(&self) -> FileType { |
| 449 | FileType { mode: self.stat.st_mode as mode_t } |
| 450 | } |
| 451 | } |
| 452 | |
| 453 | #[cfg (target_os = "netbsd" )] |
| 454 | impl FileAttr { |
| 455 | pub fn modified(&self) -> io::Result<SystemTime> { |
| 456 | SystemTime::new(self.stat.st_mtime as i64, self.stat.st_mtimensec as i64) |
| 457 | } |
| 458 | |
| 459 | pub fn accessed(&self) -> io::Result<SystemTime> { |
| 460 | SystemTime::new(self.stat.st_atime as i64, self.stat.st_atimensec as i64) |
| 461 | } |
| 462 | |
| 463 | pub fn created(&self) -> io::Result<SystemTime> { |
| 464 | SystemTime::new(self.stat.st_birthtime as i64, self.stat.st_birthtimensec as i64) |
| 465 | } |
| 466 | } |
| 467 | |
| 468 | #[cfg (target_os = "aix" )] |
| 469 | impl FileAttr { |
| 470 | pub fn modified(&self) -> io::Result<SystemTime> { |
| 471 | SystemTime::new(self.stat.st_mtime.tv_sec as i64, self.stat.st_mtime.tv_nsec as i64) |
| 472 | } |
| 473 | |
| 474 | pub fn accessed(&self) -> io::Result<SystemTime> { |
| 475 | SystemTime::new(self.stat.st_atime.tv_sec as i64, self.stat.st_atime.tv_nsec as i64) |
| 476 | } |
| 477 | |
| 478 | pub fn created(&self) -> io::Result<SystemTime> { |
| 479 | SystemTime::new(self.stat.st_ctime.tv_sec as i64, self.stat.st_ctime.tv_nsec as i64) |
| 480 | } |
| 481 | } |
| 482 | |
| 483 | #[cfg (not(any(target_os = "netbsd" , target_os = "nto" , target_os = "aix" )))] |
| 484 | impl FileAttr { |
| 485 | #[cfg (not(any( |
| 486 | target_os = "vxworks" , |
| 487 | target_os = "espidf" , |
| 488 | target_os = "horizon" , |
| 489 | target_os = "vita" , |
| 490 | target_os = "hurd" , |
| 491 | target_os = "rtems" , |
| 492 | target_os = "nuttx" , |
| 493 | )))] |
| 494 | pub fn modified(&self) -> io::Result<SystemTime> { |
| 495 | #[cfg (target_pointer_width = "32" )] |
| 496 | cfg_has_statx! { |
| 497 | if let Some(mtime) = self.stx_mtime() { |
| 498 | return SystemTime::new(mtime.tv_sec, mtime.tv_nsec as i64); |
| 499 | } |
| 500 | } |
| 501 | |
| 502 | SystemTime::new(self.stat.st_mtime as i64, self.stat.st_mtime_nsec as i64) |
| 503 | } |
| 504 | |
| 505 | #[cfg (any( |
| 506 | target_os = "vxworks" , |
| 507 | target_os = "espidf" , |
| 508 | target_os = "vita" , |
| 509 | target_os = "rtems" , |
| 510 | ))] |
| 511 | pub fn modified(&self) -> io::Result<SystemTime> { |
| 512 | SystemTime::new(self.stat.st_mtime as i64, 0) |
| 513 | } |
| 514 | |
| 515 | #[cfg (any(target_os = "horizon" , target_os = "hurd" , target_os = "nuttx" ))] |
| 516 | pub fn modified(&self) -> io::Result<SystemTime> { |
| 517 | SystemTime::new(self.stat.st_mtim.tv_sec as i64, self.stat.st_mtim.tv_nsec as i64) |
| 518 | } |
| 519 | |
| 520 | #[cfg (not(any( |
| 521 | target_os = "vxworks" , |
| 522 | target_os = "espidf" , |
| 523 | target_os = "horizon" , |
| 524 | target_os = "vita" , |
| 525 | target_os = "hurd" , |
| 526 | target_os = "rtems" , |
| 527 | target_os = "nuttx" , |
| 528 | )))] |
| 529 | pub fn accessed(&self) -> io::Result<SystemTime> { |
| 530 | #[cfg (target_pointer_width = "32" )] |
| 531 | cfg_has_statx! { |
| 532 | if let Some(atime) = self.stx_atime() { |
| 533 | return SystemTime::new(atime.tv_sec, atime.tv_nsec as i64); |
| 534 | } |
| 535 | } |
| 536 | |
| 537 | SystemTime::new(self.stat.st_atime as i64, self.stat.st_atime_nsec as i64) |
| 538 | } |
| 539 | |
| 540 | #[cfg (any( |
| 541 | target_os = "vxworks" , |
| 542 | target_os = "espidf" , |
| 543 | target_os = "vita" , |
| 544 | target_os = "rtems" |
| 545 | ))] |
| 546 | pub fn accessed(&self) -> io::Result<SystemTime> { |
| 547 | SystemTime::new(self.stat.st_atime as i64, 0) |
| 548 | } |
| 549 | |
| 550 | #[cfg (any(target_os = "horizon" , target_os = "hurd" , target_os = "nuttx" ))] |
| 551 | pub fn accessed(&self) -> io::Result<SystemTime> { |
| 552 | SystemTime::new(self.stat.st_atim.tv_sec as i64, self.stat.st_atim.tv_nsec as i64) |
| 553 | } |
| 554 | |
| 555 | #[cfg (any( |
| 556 | target_os = "freebsd" , |
| 557 | target_os = "openbsd" , |
| 558 | target_vendor = "apple" , |
| 559 | target_os = "cygwin" , |
| 560 | ))] |
| 561 | pub fn created(&self) -> io::Result<SystemTime> { |
| 562 | SystemTime::new(self.stat.st_birthtime as i64, self.stat.st_birthtime_nsec as i64) |
| 563 | } |
| 564 | |
| 565 | #[cfg (not(any( |
| 566 | target_os = "freebsd" , |
| 567 | target_os = "openbsd" , |
| 568 | target_os = "vita" , |
| 569 | target_vendor = "apple" , |
| 570 | target_os = "cygwin" , |
| 571 | )))] |
| 572 | pub fn created(&self) -> io::Result<SystemTime> { |
| 573 | cfg_has_statx! { |
| 574 | if let Some(ext) = &self.statx_extra_fields { |
| 575 | return if (ext.stx_mask & libc::STATX_BTIME) != 0 { |
| 576 | SystemTime::new(ext.stx_btime.tv_sec, ext.stx_btime.tv_nsec as i64) |
| 577 | } else { |
| 578 | Err(io::const_error!( |
| 579 | io::ErrorKind::Unsupported, |
| 580 | "creation time is not available for the filesystem" , |
| 581 | )) |
| 582 | }; |
| 583 | } |
| 584 | } |
| 585 | |
| 586 | Err(io::const_error!( |
| 587 | io::ErrorKind::Unsupported, |
| 588 | "creation time is not available on this platform currently" , |
| 589 | )) |
| 590 | } |
| 591 | |
| 592 | #[cfg (target_os = "vita" )] |
| 593 | pub fn created(&self) -> io::Result<SystemTime> { |
| 594 | SystemTime::new(self.stat.st_ctime as i64, 0) |
| 595 | } |
| 596 | } |
| 597 | |
| 598 | #[cfg (target_os = "nto" )] |
| 599 | impl FileAttr { |
| 600 | pub fn modified(&self) -> io::Result<SystemTime> { |
| 601 | SystemTime::new(self.stat.st_mtim.tv_sec, self.stat.st_mtim.tv_nsec) |
| 602 | } |
| 603 | |
| 604 | pub fn accessed(&self) -> io::Result<SystemTime> { |
| 605 | SystemTime::new(self.stat.st_atim.tv_sec, self.stat.st_atim.tv_nsec) |
| 606 | } |
| 607 | |
| 608 | pub fn created(&self) -> io::Result<SystemTime> { |
| 609 | SystemTime::new(self.stat.st_ctim.tv_sec, self.stat.st_ctim.tv_nsec) |
| 610 | } |
| 611 | } |
| 612 | |
| 613 | impl AsInner<stat64> for FileAttr { |
| 614 | #[inline ] |
| 615 | fn as_inner(&self) -> &stat64 { |
| 616 | &self.stat |
| 617 | } |
| 618 | } |
| 619 | |
| 620 | impl FilePermissions { |
| 621 | pub fn readonly(&self) -> bool { |
| 622 | // check if any class (owner, group, others) has write permission |
| 623 | self.mode & 0o222 == 0 |
| 624 | } |
| 625 | |
| 626 | pub fn set_readonly(&mut self, readonly: bool) { |
| 627 | if readonly { |
| 628 | // remove write permission for all classes; equivalent to `chmod a-w <file>` |
| 629 | self.mode &= !0o222; |
| 630 | } else { |
| 631 | // add write permission for all classes; equivalent to `chmod a+w <file>` |
| 632 | self.mode |= 0o222; |
| 633 | } |
| 634 | } |
| 635 | pub fn mode(&self) -> u32 { |
| 636 | self.mode as u32 |
| 637 | } |
| 638 | } |
| 639 | |
| 640 | impl FileTimes { |
| 641 | pub fn set_accessed(&mut self, t: SystemTime) { |
| 642 | self.accessed = Some(t); |
| 643 | } |
| 644 | |
| 645 | pub fn set_modified(&mut self, t: SystemTime) { |
| 646 | self.modified = Some(t); |
| 647 | } |
| 648 | |
| 649 | #[cfg (target_vendor = "apple" )] |
| 650 | pub fn set_created(&mut self, t: SystemTime) { |
| 651 | self.created = Some(t); |
| 652 | } |
| 653 | } |
| 654 | |
| 655 | impl FileType { |
| 656 | pub fn is_dir(&self) -> bool { |
| 657 | self.is(mode:libc::S_IFDIR) |
| 658 | } |
| 659 | pub fn is_file(&self) -> bool { |
| 660 | self.is(mode:libc::S_IFREG) |
| 661 | } |
| 662 | pub fn is_symlink(&self) -> bool { |
| 663 | self.is(mode:libc::S_IFLNK) |
| 664 | } |
| 665 | |
| 666 | pub fn is(&self, mode: mode_t) -> bool { |
| 667 | self.masked() == mode |
| 668 | } |
| 669 | |
| 670 | fn masked(&self) -> mode_t { |
| 671 | self.mode & libc::S_IFMT |
| 672 | } |
| 673 | } |
| 674 | |
| 675 | impl fmt::Debug for FileType { |
| 676 | fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { |
| 677 | let FileType { mode: &u32 } = self; |
| 678 | f.debug_struct("FileType" ).field(name:"mode" , &Mode(*mode)).finish() |
| 679 | } |
| 680 | } |
| 681 | |
| 682 | impl FromInner<u32> for FilePermissions { |
| 683 | fn from_inner(mode: u32) -> FilePermissions { |
| 684 | FilePermissions { mode: mode as mode_t } |
| 685 | } |
| 686 | } |
| 687 | |
| 688 | impl fmt::Debug for FilePermissions { |
| 689 | fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { |
| 690 | let FilePermissions { mode: &u32 } = self; |
| 691 | f.debug_struct("FilePermissions" ).field(name:"mode" , &Mode(*mode)).finish() |
| 692 | } |
| 693 | } |
| 694 | |
| 695 | impl fmt::Debug for ReadDir { |
| 696 | fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { |
| 697 | // This will only be called from std::fs::ReadDir, which will add a "ReadDir()" frame. |
| 698 | // Thus the result will be e g 'ReadDir("/home")' |
| 699 | fmt::Debug::fmt(&*self.inner.root, f) |
| 700 | } |
| 701 | } |
| 702 | |
| 703 | impl Iterator for ReadDir { |
| 704 | type Item = io::Result<DirEntry>; |
| 705 | |
| 706 | #[cfg (any( |
| 707 | target_os = "aix" , |
| 708 | target_os = "android" , |
| 709 | target_os = "freebsd" , |
| 710 | target_os = "fuchsia" , |
| 711 | target_os = "hurd" , |
| 712 | target_os = "illumos" , |
| 713 | target_os = "linux" , |
| 714 | target_os = "nto" , |
| 715 | target_os = "redox" , |
| 716 | target_os = "solaris" , |
| 717 | target_os = "vita" , |
| 718 | ))] |
| 719 | fn next(&mut self) -> Option<io::Result<DirEntry>> { |
| 720 | use crate::sys::os::{errno, set_errno}; |
| 721 | |
| 722 | if self.end_of_stream { |
| 723 | return None; |
| 724 | } |
| 725 | |
| 726 | unsafe { |
| 727 | loop { |
| 728 | // As of POSIX.1-2017, readdir() is not required to be thread safe; only |
| 729 | // readdir_r() is. However, readdir_r() cannot correctly handle platforms |
| 730 | // with unlimited or variable NAME_MAX. Many modern platforms guarantee |
| 731 | // thread safety for readdir() as long an individual DIR* is not accessed |
| 732 | // concurrently, which is sufficient for Rust. |
| 733 | set_errno(0); |
| 734 | let entry_ptr: *const dirent64 = readdir64(self.inner.dirp.0); |
| 735 | if entry_ptr.is_null() { |
| 736 | // We either encountered an error, or reached the end. Either way, |
| 737 | // the next call to next() should return None. |
| 738 | self.end_of_stream = true; |
| 739 | |
| 740 | // To distinguish between errors and end-of-directory, we had to clear |
| 741 | // errno beforehand to check for an error now. |
| 742 | return match errno() { |
| 743 | 0 => None, |
| 744 | e => Some(Err(Error::from_raw_os_error(e))), |
| 745 | }; |
| 746 | } |
| 747 | |
| 748 | // The dirent64 struct is a weird imaginary thing that isn't ever supposed |
| 749 | // to be worked with by value. Its trailing d_name field is declared |
| 750 | // variously as [c_char; 256] or [c_char; 1] on different systems but |
| 751 | // either way that size is meaningless; only the offset of d_name is |
| 752 | // meaningful. The dirent64 pointers that libc returns from readdir64 are |
| 753 | // allowed to point to allocations smaller _or_ LARGER than implied by the |
| 754 | // definition of the struct. |
| 755 | // |
| 756 | // As such, we need to be even more careful with dirent64 than if its |
| 757 | // contents were "simply" partially initialized data. |
| 758 | // |
| 759 | // Like for uninitialized contents, converting entry_ptr to `&dirent64` |
| 760 | // would not be legal. However, we can use `&raw const (*entry_ptr).d_name` |
| 761 | // to refer the fields individually, because that operation is equivalent |
| 762 | // to `byte_offset` and thus does not require the full extent of `*entry_ptr` |
| 763 | // to be in bounds of the same allocation, only the offset of the field |
| 764 | // being referenced. |
| 765 | |
| 766 | // d_name is guaranteed to be null-terminated. |
| 767 | let name = CStr::from_ptr((&raw const (*entry_ptr).d_name).cast()); |
| 768 | let name_bytes = name.to_bytes(); |
| 769 | if name_bytes == b"." || name_bytes == b".." { |
| 770 | continue; |
| 771 | } |
| 772 | |
| 773 | // When loading from a field, we can skip the `&raw const`; `(*entry_ptr).d_ino` as |
| 774 | // a value expression will do the right thing: `byte_offset` to the field and then |
| 775 | // only access those bytes. |
| 776 | #[cfg (not(target_os = "vita" ))] |
| 777 | let entry = dirent64_min { |
| 778 | #[cfg (target_os = "freebsd" )] |
| 779 | d_ino: (*entry_ptr).d_fileno, |
| 780 | #[cfg (not(target_os = "freebsd" ))] |
| 781 | d_ino: (*entry_ptr).d_ino as u64, |
| 782 | #[cfg (not(any( |
| 783 | target_os = "solaris" , |
| 784 | target_os = "illumos" , |
| 785 | target_os = "aix" , |
| 786 | target_os = "nto" , |
| 787 | )))] |
| 788 | d_type: (*entry_ptr).d_type as u8, |
| 789 | }; |
| 790 | |
| 791 | #[cfg (target_os = "vita" )] |
| 792 | let entry = dirent64_min { d_ino: 0u64 }; |
| 793 | |
| 794 | return Some(Ok(DirEntry { |
| 795 | entry, |
| 796 | name: name.to_owned(), |
| 797 | dir: Arc::clone(&self.inner), |
| 798 | })); |
| 799 | } |
| 800 | } |
| 801 | } |
| 802 | |
| 803 | #[cfg (not(any( |
| 804 | target_os = "aix" , |
| 805 | target_os = "android" , |
| 806 | target_os = "freebsd" , |
| 807 | target_os = "fuchsia" , |
| 808 | target_os = "hurd" , |
| 809 | target_os = "illumos" , |
| 810 | target_os = "linux" , |
| 811 | target_os = "nto" , |
| 812 | target_os = "redox" , |
| 813 | target_os = "solaris" , |
| 814 | target_os = "vita" , |
| 815 | )))] |
| 816 | fn next(&mut self) -> Option<io::Result<DirEntry>> { |
| 817 | if self.end_of_stream { |
| 818 | return None; |
| 819 | } |
| 820 | |
| 821 | unsafe { |
| 822 | let mut ret = DirEntry { entry: mem::zeroed(), dir: Arc::clone(&self.inner) }; |
| 823 | let mut entry_ptr = ptr::null_mut(); |
| 824 | loop { |
| 825 | let err = readdir64_r(self.inner.dirp.0, &mut ret.entry, &mut entry_ptr); |
| 826 | if err != 0 { |
| 827 | if entry_ptr.is_null() { |
| 828 | // We encountered an error (which will be returned in this iteration), but |
| 829 | // we also reached the end of the directory stream. The `end_of_stream` |
| 830 | // flag is enabled to make sure that we return `None` in the next iteration |
| 831 | // (instead of looping forever) |
| 832 | self.end_of_stream = true; |
| 833 | } |
| 834 | return Some(Err(Error::from_raw_os_error(err))); |
| 835 | } |
| 836 | if entry_ptr.is_null() { |
| 837 | return None; |
| 838 | } |
| 839 | if ret.name_bytes() != b"." && ret.name_bytes() != b".." { |
| 840 | return Some(Ok(ret)); |
| 841 | } |
| 842 | } |
| 843 | } |
| 844 | } |
| 845 | } |
| 846 | |
| 847 | /// Aborts the process if a file desceriptor is not open, if debug asserts are enabled |
| 848 | /// |
| 849 | /// Many IO syscalls can't be fully trusted about EBADF error codes because those |
| 850 | /// might get bubbled up from a remote FUSE server rather than the file descriptor |
| 851 | /// in the current process being invalid. |
| 852 | /// |
| 853 | /// So we check file flags instead which live on the file descriptor and not the underlying file. |
| 854 | /// The downside is that it costs an extra syscall, so we only do it for debug. |
| 855 | #[inline ] |
| 856 | pub(crate) fn debug_assert_fd_is_open(fd: RawFd) { |
| 857 | use crate::sys::os::errno; |
| 858 | |
| 859 | // this is similar to assert_unsafe_precondition!() but it doesn't require const |
| 860 | if core::ub_checks::check_library_ub() { |
| 861 | if unsafe { libc::fcntl(fd, cmd:libc::F_GETFD) } == -1 && errno() == libc::EBADF { |
| 862 | rtabort!("IO Safety violation: owned file descriptor already closed" ); |
| 863 | } |
| 864 | } |
| 865 | } |
| 866 | |
| 867 | impl Drop for Dir { |
| 868 | fn drop(&mut self) { |
| 869 | // dirfd isn't supported everywhere |
| 870 | #[cfg (not(any( |
| 871 | miri, |
| 872 | target_os = "redox" , |
| 873 | target_os = "nto" , |
| 874 | target_os = "vita" , |
| 875 | target_os = "hurd" , |
| 876 | target_os = "espidf" , |
| 877 | target_os = "horizon" , |
| 878 | target_os = "vxworks" , |
| 879 | target_os = "rtems" , |
| 880 | target_os = "nuttx" , |
| 881 | )))] |
| 882 | { |
| 883 | let fd = unsafe { libc::dirfd(self.0) }; |
| 884 | debug_assert_fd_is_open(fd); |
| 885 | } |
| 886 | let r = unsafe { libc::closedir(self.0) }; |
| 887 | assert!( |
| 888 | r == 0 || crate::io::Error::last_os_error().is_interrupted(), |
| 889 | "unexpected error during closedir: {:?}" , |
| 890 | crate::io::Error::last_os_error() |
| 891 | ); |
| 892 | } |
| 893 | } |
| 894 | |
| 895 | impl DirEntry { |
| 896 | pub fn path(&self) -> PathBuf { |
| 897 | self.dir.root.join(self.file_name_os_str()) |
| 898 | } |
| 899 | |
| 900 | pub fn file_name(&self) -> OsString { |
| 901 | self.file_name_os_str().to_os_string() |
| 902 | } |
| 903 | |
| 904 | #[cfg (all( |
| 905 | any( |
| 906 | all(target_os = "linux" , not(target_env = "musl" )), |
| 907 | target_os = "android" , |
| 908 | target_os = "fuchsia" , |
| 909 | target_os = "hurd" , |
| 910 | target_os = "illumos" , |
| 911 | target_vendor = "apple" , |
| 912 | ), |
| 913 | not(miri) // no dirfd on Miri |
| 914 | ))] |
| 915 | pub fn metadata(&self) -> io::Result<FileAttr> { |
| 916 | let fd = cvt(unsafe { dirfd(self.dir.dirp.0) })?; |
| 917 | let name = self.name_cstr().as_ptr(); |
| 918 | |
| 919 | cfg_has_statx! { |
| 920 | if let Some(ret) = unsafe { try_statx( |
| 921 | fd, |
| 922 | name, |
| 923 | libc::AT_SYMLINK_NOFOLLOW | libc::AT_STATX_SYNC_AS_STAT, |
| 924 | libc::STATX_BASIC_STATS | libc::STATX_BTIME, |
| 925 | ) } { |
| 926 | return ret; |
| 927 | } |
| 928 | } |
| 929 | |
| 930 | let mut stat: stat64 = unsafe { mem::zeroed() }; |
| 931 | cvt(unsafe { fstatat64(fd, name, &mut stat, libc::AT_SYMLINK_NOFOLLOW) })?; |
| 932 | Ok(FileAttr::from_stat64(stat)) |
| 933 | } |
| 934 | |
| 935 | #[cfg (any( |
| 936 | not(any( |
| 937 | all(target_os = "linux" , not(target_env = "musl" )), |
| 938 | target_os = "android" , |
| 939 | target_os = "fuchsia" , |
| 940 | target_os = "hurd" , |
| 941 | target_os = "illumos" , |
| 942 | target_vendor = "apple" , |
| 943 | )), |
| 944 | miri |
| 945 | ))] |
| 946 | pub fn metadata(&self) -> io::Result<FileAttr> { |
| 947 | run_path_with_cstr(&self.path(), &lstat) |
| 948 | } |
| 949 | |
| 950 | #[cfg (any( |
| 951 | target_os = "solaris" , |
| 952 | target_os = "illumos" , |
| 953 | target_os = "haiku" , |
| 954 | target_os = "vxworks" , |
| 955 | target_os = "aix" , |
| 956 | target_os = "nto" , |
| 957 | target_os = "vita" , |
| 958 | ))] |
| 959 | pub fn file_type(&self) -> io::Result<FileType> { |
| 960 | self.metadata().map(|m| m.file_type()) |
| 961 | } |
| 962 | |
| 963 | #[cfg (not(any( |
| 964 | target_os = "solaris" , |
| 965 | target_os = "illumos" , |
| 966 | target_os = "haiku" , |
| 967 | target_os = "vxworks" , |
| 968 | target_os = "aix" , |
| 969 | target_os = "nto" , |
| 970 | target_os = "vita" , |
| 971 | )))] |
| 972 | pub fn file_type(&self) -> io::Result<FileType> { |
| 973 | match self.entry.d_type { |
| 974 | libc::DT_CHR => Ok(FileType { mode: libc::S_IFCHR }), |
| 975 | libc::DT_FIFO => Ok(FileType { mode: libc::S_IFIFO }), |
| 976 | libc::DT_LNK => Ok(FileType { mode: libc::S_IFLNK }), |
| 977 | libc::DT_REG => Ok(FileType { mode: libc::S_IFREG }), |
| 978 | libc::DT_SOCK => Ok(FileType { mode: libc::S_IFSOCK }), |
| 979 | libc::DT_DIR => Ok(FileType { mode: libc::S_IFDIR }), |
| 980 | libc::DT_BLK => Ok(FileType { mode: libc::S_IFBLK }), |
| 981 | _ => self.metadata().map(|m| m.file_type()), |
| 982 | } |
| 983 | } |
| 984 | |
| 985 | #[cfg (any( |
| 986 | target_os = "aix" , |
| 987 | target_os = "android" , |
| 988 | target_os = "cygwin" , |
| 989 | target_os = "emscripten" , |
| 990 | target_os = "espidf" , |
| 991 | target_os = "freebsd" , |
| 992 | target_os = "fuchsia" , |
| 993 | target_os = "haiku" , |
| 994 | target_os = "horizon" , |
| 995 | target_os = "hurd" , |
| 996 | target_os = "illumos" , |
| 997 | target_os = "l4re" , |
| 998 | target_os = "linux" , |
| 999 | target_os = "nto" , |
| 1000 | target_os = "redox" , |
| 1001 | target_os = "rtems" , |
| 1002 | target_os = "solaris" , |
| 1003 | target_os = "vita" , |
| 1004 | target_os = "vxworks" , |
| 1005 | target_vendor = "apple" , |
| 1006 | ))] |
| 1007 | pub fn ino(&self) -> u64 { |
| 1008 | self.entry.d_ino as u64 |
| 1009 | } |
| 1010 | |
| 1011 | #[cfg (any(target_os = "openbsd" , target_os = "netbsd" , target_os = "dragonfly" ))] |
| 1012 | pub fn ino(&self) -> u64 { |
| 1013 | self.entry.d_fileno as u64 |
| 1014 | } |
| 1015 | |
| 1016 | #[cfg (target_os = "nuttx" )] |
| 1017 | pub fn ino(&self) -> u64 { |
| 1018 | // Leave this 0 for now, as NuttX does not provide an inode number |
| 1019 | // in its directory entries. |
| 1020 | 0 |
| 1021 | } |
| 1022 | |
| 1023 | #[cfg (any( |
| 1024 | target_os = "netbsd" , |
| 1025 | target_os = "openbsd" , |
| 1026 | target_os = "dragonfly" , |
| 1027 | target_vendor = "apple" , |
| 1028 | ))] |
| 1029 | fn name_bytes(&self) -> &[u8] { |
| 1030 | use crate::slice; |
| 1031 | unsafe { |
| 1032 | slice::from_raw_parts( |
| 1033 | self.entry.d_name.as_ptr() as *const u8, |
| 1034 | self.entry.d_namlen as usize, |
| 1035 | ) |
| 1036 | } |
| 1037 | } |
| 1038 | #[cfg (not(any( |
| 1039 | target_os = "netbsd" , |
| 1040 | target_os = "openbsd" , |
| 1041 | target_os = "dragonfly" , |
| 1042 | target_vendor = "apple" , |
| 1043 | )))] |
| 1044 | fn name_bytes(&self) -> &[u8] { |
| 1045 | self.name_cstr().to_bytes() |
| 1046 | } |
| 1047 | |
| 1048 | #[cfg (not(any( |
| 1049 | target_os = "android" , |
| 1050 | target_os = "freebsd" , |
| 1051 | target_os = "linux" , |
| 1052 | target_os = "solaris" , |
| 1053 | target_os = "illumos" , |
| 1054 | target_os = "fuchsia" , |
| 1055 | target_os = "redox" , |
| 1056 | target_os = "aix" , |
| 1057 | target_os = "nto" , |
| 1058 | target_os = "vita" , |
| 1059 | target_os = "hurd" , |
| 1060 | )))] |
| 1061 | fn name_cstr(&self) -> &CStr { |
| 1062 | unsafe { CStr::from_ptr(self.entry.d_name.as_ptr()) } |
| 1063 | } |
| 1064 | #[cfg (any( |
| 1065 | target_os = "android" , |
| 1066 | target_os = "freebsd" , |
| 1067 | target_os = "linux" , |
| 1068 | target_os = "solaris" , |
| 1069 | target_os = "illumos" , |
| 1070 | target_os = "fuchsia" , |
| 1071 | target_os = "redox" , |
| 1072 | target_os = "aix" , |
| 1073 | target_os = "nto" , |
| 1074 | target_os = "vita" , |
| 1075 | target_os = "hurd" , |
| 1076 | ))] |
| 1077 | fn name_cstr(&self) -> &CStr { |
| 1078 | &self.name |
| 1079 | } |
| 1080 | |
| 1081 | pub fn file_name_os_str(&self) -> &OsStr { |
| 1082 | OsStr::from_bytes(self.name_bytes()) |
| 1083 | } |
| 1084 | } |
| 1085 | |
| 1086 | impl OpenOptions { |
| 1087 | pub fn new() -> OpenOptions { |
| 1088 | OpenOptions { |
| 1089 | // generic |
| 1090 | read: false, |
| 1091 | write: false, |
| 1092 | append: false, |
| 1093 | truncate: false, |
| 1094 | create: false, |
| 1095 | create_new: false, |
| 1096 | // system-specific |
| 1097 | custom_flags: 0, |
| 1098 | mode: 0o666, |
| 1099 | } |
| 1100 | } |
| 1101 | |
| 1102 | pub fn read(&mut self, read: bool) { |
| 1103 | self.read = read; |
| 1104 | } |
| 1105 | pub fn write(&mut self, write: bool) { |
| 1106 | self.write = write; |
| 1107 | } |
| 1108 | pub fn append(&mut self, append: bool) { |
| 1109 | self.append = append; |
| 1110 | } |
| 1111 | pub fn truncate(&mut self, truncate: bool) { |
| 1112 | self.truncate = truncate; |
| 1113 | } |
| 1114 | pub fn create(&mut self, create: bool) { |
| 1115 | self.create = create; |
| 1116 | } |
| 1117 | pub fn create_new(&mut self, create_new: bool) { |
| 1118 | self.create_new = create_new; |
| 1119 | } |
| 1120 | |
| 1121 | pub fn custom_flags(&mut self, flags: i32) { |
| 1122 | self.custom_flags = flags; |
| 1123 | } |
| 1124 | pub fn mode(&mut self, mode: u32) { |
| 1125 | self.mode = mode as mode_t; |
| 1126 | } |
| 1127 | |
| 1128 | fn get_access_mode(&self) -> io::Result<c_int> { |
| 1129 | match (self.read, self.write, self.append) { |
| 1130 | (true, false, false) => Ok(libc::O_RDONLY), |
| 1131 | (false, true, false) => Ok(libc::O_WRONLY), |
| 1132 | (true, true, false) => Ok(libc::O_RDWR), |
| 1133 | (false, _, true) => Ok(libc::O_WRONLY | libc::O_APPEND), |
| 1134 | (true, _, true) => Ok(libc::O_RDWR | libc::O_APPEND), |
| 1135 | (false, false, false) => { |
| 1136 | // If no access mode is set, check if any creation flags are set |
| 1137 | // to provide a more descriptive error message |
| 1138 | if self.create || self.create_new || self.truncate { |
| 1139 | Err(io::Error::new( |
| 1140 | io::ErrorKind::InvalidInput, |
| 1141 | "creating or truncating a file requires write or append access" , |
| 1142 | )) |
| 1143 | } else { |
| 1144 | Err(io::Error::new( |
| 1145 | io::ErrorKind::InvalidInput, |
| 1146 | "must specify at least one of read, write, or append access" , |
| 1147 | )) |
| 1148 | } |
| 1149 | } |
| 1150 | } |
| 1151 | } |
| 1152 | |
| 1153 | fn get_creation_mode(&self) -> io::Result<c_int> { |
| 1154 | match (self.write, self.append) { |
| 1155 | (true, false) => {} |
| 1156 | (false, false) => { |
| 1157 | if self.truncate || self.create || self.create_new { |
| 1158 | return Err(io::Error::new( |
| 1159 | io::ErrorKind::InvalidInput, |
| 1160 | "creating or truncating a file requires write or append access" , |
| 1161 | )); |
| 1162 | } |
| 1163 | } |
| 1164 | (_, true) => { |
| 1165 | if self.truncate && !self.create_new { |
| 1166 | return Err(io::Error::new( |
| 1167 | io::ErrorKind::InvalidInput, |
| 1168 | "creating or truncating a file requires write or append access" , |
| 1169 | )); |
| 1170 | } |
| 1171 | } |
| 1172 | } |
| 1173 | |
| 1174 | Ok(match (self.create, self.truncate, self.create_new) { |
| 1175 | (false, false, false) => 0, |
| 1176 | (true, false, false) => libc::O_CREAT, |
| 1177 | (false, true, false) => libc::O_TRUNC, |
| 1178 | (true, true, false) => libc::O_CREAT | libc::O_TRUNC, |
| 1179 | (_, _, true) => libc::O_CREAT | libc::O_EXCL, |
| 1180 | }) |
| 1181 | } |
| 1182 | } |
| 1183 | |
| 1184 | impl fmt::Debug for OpenOptions { |
| 1185 | fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { |
| 1186 | let OpenOptions { read: &bool, write: &bool, append: &bool, truncate: &bool, create: &bool, create_new: &bool, custom_flags: &i32, mode: &u32 } = |
| 1187 | self; |
| 1188 | f&mut DebugStruct<'_, '_>.debug_struct("OpenOptions" ) |
| 1189 | .field("read" , read) |
| 1190 | .field("write" , write) |
| 1191 | .field("append" , append) |
| 1192 | .field("truncate" , truncate) |
| 1193 | .field("create" , create) |
| 1194 | .field("create_new" , create_new) |
| 1195 | .field("custom_flags" , custom_flags) |
| 1196 | .field(name:"mode" , &Mode(*mode)) |
| 1197 | .finish() |
| 1198 | } |
| 1199 | } |
| 1200 | |
| 1201 | impl File { |
| 1202 | pub fn open(path: &Path, opts: &OpenOptions) -> io::Result<File> { |
| 1203 | run_path_with_cstr(path, &|path| File::open_c(path, opts)) |
| 1204 | } |
| 1205 | |
| 1206 | pub fn open_c(path: &CStr, opts: &OpenOptions) -> io::Result<File> { |
| 1207 | let flags = libc::O_CLOEXEC |
| 1208 | | opts.get_access_mode()? |
| 1209 | | opts.get_creation_mode()? |
| 1210 | | (opts.custom_flags as c_int & !libc::O_ACCMODE); |
| 1211 | // The third argument of `open64` is documented to have type `mode_t`. On |
| 1212 | // some platforms (like macOS, where `open64` is actually `open`), `mode_t` is `u16`. |
| 1213 | // However, since this is a variadic function, C integer promotion rules mean that on |
| 1214 | // the ABI level, this still gets passed as `c_int` (aka `u32` on Unix platforms). |
| 1215 | let fd = cvt_r(|| unsafe { open64(path.as_ptr(), flags, opts.mode as c_int) })?; |
| 1216 | Ok(File(unsafe { FileDesc::from_raw_fd(fd) })) |
| 1217 | } |
| 1218 | |
| 1219 | pub fn file_attr(&self) -> io::Result<FileAttr> { |
| 1220 | let fd = self.as_raw_fd(); |
| 1221 | |
| 1222 | cfg_has_statx! { |
| 1223 | if let Some(ret) = unsafe { try_statx( |
| 1224 | fd, |
| 1225 | c"" .as_ptr() as *const c_char, |
| 1226 | libc::AT_EMPTY_PATH | libc::AT_STATX_SYNC_AS_STAT, |
| 1227 | libc::STATX_BASIC_STATS | libc::STATX_BTIME, |
| 1228 | ) } { |
| 1229 | return ret; |
| 1230 | } |
| 1231 | } |
| 1232 | |
| 1233 | let mut stat: stat64 = unsafe { mem::zeroed() }; |
| 1234 | cvt(unsafe { fstat64(fd, &mut stat) })?; |
| 1235 | Ok(FileAttr::from_stat64(stat)) |
| 1236 | } |
| 1237 | |
| 1238 | pub fn fsync(&self) -> io::Result<()> { |
| 1239 | cvt_r(|| unsafe { os_fsync(self.as_raw_fd()) })?; |
| 1240 | return Ok(()); |
| 1241 | |
| 1242 | #[cfg (target_vendor = "apple" )] |
| 1243 | unsafe fn os_fsync(fd: c_int) -> c_int { |
| 1244 | libc::fcntl(fd, libc::F_FULLFSYNC) |
| 1245 | } |
| 1246 | #[cfg (not(target_vendor = "apple" ))] |
| 1247 | unsafe fn os_fsync(fd: c_int) -> c_int { |
| 1248 | libc::fsync(fd) |
| 1249 | } |
| 1250 | } |
| 1251 | |
| 1252 | pub fn datasync(&self) -> io::Result<()> { |
| 1253 | cvt_r(|| unsafe { os_datasync(self.as_raw_fd()) })?; |
| 1254 | return Ok(()); |
| 1255 | |
| 1256 | #[cfg (target_vendor = "apple" )] |
| 1257 | unsafe fn os_datasync(fd: c_int) -> c_int { |
| 1258 | libc::fcntl(fd, libc::F_FULLFSYNC) |
| 1259 | } |
| 1260 | #[cfg (any( |
| 1261 | target_os = "freebsd" , |
| 1262 | target_os = "fuchsia" , |
| 1263 | target_os = "linux" , |
| 1264 | target_os = "cygwin" , |
| 1265 | target_os = "android" , |
| 1266 | target_os = "netbsd" , |
| 1267 | target_os = "openbsd" , |
| 1268 | target_os = "nto" , |
| 1269 | target_os = "hurd" , |
| 1270 | ))] |
| 1271 | unsafe fn os_datasync(fd: c_int) -> c_int { |
| 1272 | libc::fdatasync(fd) |
| 1273 | } |
| 1274 | #[cfg (not(any( |
| 1275 | target_os = "android" , |
| 1276 | target_os = "fuchsia" , |
| 1277 | target_os = "freebsd" , |
| 1278 | target_os = "linux" , |
| 1279 | target_os = "cygwin" , |
| 1280 | target_os = "netbsd" , |
| 1281 | target_os = "openbsd" , |
| 1282 | target_os = "nto" , |
| 1283 | target_os = "hurd" , |
| 1284 | target_vendor = "apple" , |
| 1285 | )))] |
| 1286 | unsafe fn os_datasync(fd: c_int) -> c_int { |
| 1287 | libc::fsync(fd) |
| 1288 | } |
| 1289 | } |
| 1290 | |
| 1291 | #[cfg (any( |
| 1292 | target_os = "freebsd" , |
| 1293 | target_os = "fuchsia" , |
| 1294 | target_os = "linux" , |
| 1295 | target_os = "netbsd" , |
| 1296 | target_os = "openbsd" , |
| 1297 | target_os = "cygwin" , |
| 1298 | target_os = "illumos" , |
| 1299 | target_os = "aix" , |
| 1300 | target_vendor = "apple" , |
| 1301 | ))] |
| 1302 | pub fn lock(&self) -> io::Result<()> { |
| 1303 | cvt(unsafe { libc::flock(self.as_raw_fd(), libc::LOCK_EX) })?; |
| 1304 | return Ok(()); |
| 1305 | } |
| 1306 | |
| 1307 | #[cfg (target_os = "solaris" )] |
| 1308 | pub fn lock(&self) -> io::Result<()> { |
| 1309 | let mut flock: libc::flock = unsafe { mem::zeroed() }; |
| 1310 | flock.l_type = libc::F_WRLCK as libc::c_short; |
| 1311 | flock.l_whence = libc::SEEK_SET as libc::c_short; |
| 1312 | cvt(unsafe { libc::fcntl(self.as_raw_fd(), libc::F_SETLKW, &flock) })?; |
| 1313 | Ok(()) |
| 1314 | } |
| 1315 | |
| 1316 | #[cfg (not(any( |
| 1317 | target_os = "freebsd" , |
| 1318 | target_os = "fuchsia" , |
| 1319 | target_os = "linux" , |
| 1320 | target_os = "netbsd" , |
| 1321 | target_os = "openbsd" , |
| 1322 | target_os = "cygwin" , |
| 1323 | target_os = "solaris" , |
| 1324 | target_os = "illumos" , |
| 1325 | target_os = "aix" , |
| 1326 | target_vendor = "apple" , |
| 1327 | )))] |
| 1328 | pub fn lock(&self) -> io::Result<()> { |
| 1329 | Err(io::const_error!(io::ErrorKind::Unsupported, "lock() not supported" )) |
| 1330 | } |
| 1331 | |
| 1332 | #[cfg (any( |
| 1333 | target_os = "freebsd" , |
| 1334 | target_os = "fuchsia" , |
| 1335 | target_os = "linux" , |
| 1336 | target_os = "netbsd" , |
| 1337 | target_os = "openbsd" , |
| 1338 | target_os = "cygwin" , |
| 1339 | target_os = "illumos" , |
| 1340 | target_os = "aix" , |
| 1341 | target_vendor = "apple" , |
| 1342 | ))] |
| 1343 | pub fn lock_shared(&self) -> io::Result<()> { |
| 1344 | cvt(unsafe { libc::flock(self.as_raw_fd(), libc::LOCK_SH) })?; |
| 1345 | return Ok(()); |
| 1346 | } |
| 1347 | |
| 1348 | #[cfg (target_os = "solaris" )] |
| 1349 | pub fn lock_shared(&self) -> io::Result<()> { |
| 1350 | let mut flock: libc::flock = unsafe { mem::zeroed() }; |
| 1351 | flock.l_type = libc::F_RDLCK as libc::c_short; |
| 1352 | flock.l_whence = libc::SEEK_SET as libc::c_short; |
| 1353 | cvt(unsafe { libc::fcntl(self.as_raw_fd(), libc::F_SETLKW, &flock) })?; |
| 1354 | Ok(()) |
| 1355 | } |
| 1356 | |
| 1357 | #[cfg (not(any( |
| 1358 | target_os = "freebsd" , |
| 1359 | target_os = "fuchsia" , |
| 1360 | target_os = "linux" , |
| 1361 | target_os = "netbsd" , |
| 1362 | target_os = "openbsd" , |
| 1363 | target_os = "cygwin" , |
| 1364 | target_os = "solaris" , |
| 1365 | target_os = "illumos" , |
| 1366 | target_os = "aix" , |
| 1367 | target_vendor = "apple" , |
| 1368 | )))] |
| 1369 | pub fn lock_shared(&self) -> io::Result<()> { |
| 1370 | Err(io::const_error!(io::ErrorKind::Unsupported, "lock_shared() not supported" )) |
| 1371 | } |
| 1372 | |
| 1373 | #[cfg (any( |
| 1374 | target_os = "freebsd" , |
| 1375 | target_os = "fuchsia" , |
| 1376 | target_os = "linux" , |
| 1377 | target_os = "netbsd" , |
| 1378 | target_os = "openbsd" , |
| 1379 | target_os = "cygwin" , |
| 1380 | target_os = "illumos" , |
| 1381 | target_os = "aix" , |
| 1382 | target_vendor = "apple" , |
| 1383 | ))] |
| 1384 | pub fn try_lock(&self) -> Result<(), TryLockError> { |
| 1385 | let result = cvt(unsafe { libc::flock(self.as_raw_fd(), libc::LOCK_EX | libc::LOCK_NB) }); |
| 1386 | if let Err(err) = result { |
| 1387 | if err.kind() == io::ErrorKind::WouldBlock { |
| 1388 | Err(TryLockError::WouldBlock) |
| 1389 | } else { |
| 1390 | Err(TryLockError::Error(err)) |
| 1391 | } |
| 1392 | } else { |
| 1393 | Ok(()) |
| 1394 | } |
| 1395 | } |
| 1396 | |
| 1397 | #[cfg (target_os = "solaris" )] |
| 1398 | pub fn try_lock(&self) -> Result<(), TryLockError> { |
| 1399 | let mut flock: libc::flock = unsafe { mem::zeroed() }; |
| 1400 | flock.l_type = libc::F_WRLCK as libc::c_short; |
| 1401 | flock.l_whence = libc::SEEK_SET as libc::c_short; |
| 1402 | let result = cvt(unsafe { libc::fcntl(self.as_raw_fd(), libc::F_SETLK, &flock) }); |
| 1403 | if let Err(err) = result { |
| 1404 | if err.kind() == io::ErrorKind::WouldBlock { |
| 1405 | Err(TryLockError::WouldBlock) |
| 1406 | } else { |
| 1407 | Err(TryLockError::Error(err)) |
| 1408 | } |
| 1409 | } else { |
| 1410 | Ok(()) |
| 1411 | } |
| 1412 | } |
| 1413 | |
| 1414 | #[cfg (not(any( |
| 1415 | target_os = "freebsd" , |
| 1416 | target_os = "fuchsia" , |
| 1417 | target_os = "linux" , |
| 1418 | target_os = "netbsd" , |
| 1419 | target_os = "openbsd" , |
| 1420 | target_os = "cygwin" , |
| 1421 | target_os = "solaris" , |
| 1422 | target_os = "illumos" , |
| 1423 | target_os = "aix" , |
| 1424 | target_vendor = "apple" , |
| 1425 | )))] |
| 1426 | pub fn try_lock(&self) -> Result<(), TryLockError> { |
| 1427 | Err(TryLockError::Error(io::const_error!( |
| 1428 | io::ErrorKind::Unsupported, |
| 1429 | "try_lock() not supported" |
| 1430 | ))) |
| 1431 | } |
| 1432 | |
| 1433 | #[cfg (any( |
| 1434 | target_os = "freebsd" , |
| 1435 | target_os = "fuchsia" , |
| 1436 | target_os = "linux" , |
| 1437 | target_os = "netbsd" , |
| 1438 | target_os = "openbsd" , |
| 1439 | target_os = "cygwin" , |
| 1440 | target_os = "illumos" , |
| 1441 | target_os = "aix" , |
| 1442 | target_vendor = "apple" , |
| 1443 | ))] |
| 1444 | pub fn try_lock_shared(&self) -> Result<(), TryLockError> { |
| 1445 | let result = cvt(unsafe { libc::flock(self.as_raw_fd(), libc::LOCK_SH | libc::LOCK_NB) }); |
| 1446 | if let Err(err) = result { |
| 1447 | if err.kind() == io::ErrorKind::WouldBlock { |
| 1448 | Err(TryLockError::WouldBlock) |
| 1449 | } else { |
| 1450 | Err(TryLockError::Error(err)) |
| 1451 | } |
| 1452 | } else { |
| 1453 | Ok(()) |
| 1454 | } |
| 1455 | } |
| 1456 | |
| 1457 | #[cfg (target_os = "solaris" )] |
| 1458 | pub fn try_lock_shared(&self) -> Result<(), TryLockError> { |
| 1459 | let mut flock: libc::flock = unsafe { mem::zeroed() }; |
| 1460 | flock.l_type = libc::F_RDLCK as libc::c_short; |
| 1461 | flock.l_whence = libc::SEEK_SET as libc::c_short; |
| 1462 | let result = cvt(unsafe { libc::fcntl(self.as_raw_fd(), libc::F_SETLK, &flock) }); |
| 1463 | if let Err(err) = result { |
| 1464 | if err.kind() == io::ErrorKind::WouldBlock { |
| 1465 | Err(TryLockError::WouldBlock) |
| 1466 | } else { |
| 1467 | Err(TryLockError::Error(err)) |
| 1468 | } |
| 1469 | } else { |
| 1470 | Ok(()) |
| 1471 | } |
| 1472 | } |
| 1473 | |
| 1474 | #[cfg (not(any( |
| 1475 | target_os = "freebsd" , |
| 1476 | target_os = "fuchsia" , |
| 1477 | target_os = "linux" , |
| 1478 | target_os = "netbsd" , |
| 1479 | target_os = "openbsd" , |
| 1480 | target_os = "cygwin" , |
| 1481 | target_os = "solaris" , |
| 1482 | target_os = "illumos" , |
| 1483 | target_os = "aix" , |
| 1484 | target_vendor = "apple" , |
| 1485 | )))] |
| 1486 | pub fn try_lock_shared(&self) -> Result<(), TryLockError> { |
| 1487 | Err(TryLockError::Error(io::const_error!( |
| 1488 | io::ErrorKind::Unsupported, |
| 1489 | "try_lock_shared() not supported" |
| 1490 | ))) |
| 1491 | } |
| 1492 | |
| 1493 | #[cfg (any( |
| 1494 | target_os = "freebsd" , |
| 1495 | target_os = "fuchsia" , |
| 1496 | target_os = "linux" , |
| 1497 | target_os = "netbsd" , |
| 1498 | target_os = "openbsd" , |
| 1499 | target_os = "cygwin" , |
| 1500 | target_os = "illumos" , |
| 1501 | target_os = "aix" , |
| 1502 | target_vendor = "apple" , |
| 1503 | ))] |
| 1504 | pub fn unlock(&self) -> io::Result<()> { |
| 1505 | cvt(unsafe { libc::flock(self.as_raw_fd(), libc::LOCK_UN) })?; |
| 1506 | return Ok(()); |
| 1507 | } |
| 1508 | |
| 1509 | #[cfg (target_os = "solaris" )] |
| 1510 | pub fn unlock(&self) -> io::Result<()> { |
| 1511 | let mut flock: libc::flock = unsafe { mem::zeroed() }; |
| 1512 | flock.l_type = libc::F_UNLCK as libc::c_short; |
| 1513 | flock.l_whence = libc::SEEK_SET as libc::c_short; |
| 1514 | cvt(unsafe { libc::fcntl(self.as_raw_fd(), libc::F_SETLKW, &flock) })?; |
| 1515 | Ok(()) |
| 1516 | } |
| 1517 | |
| 1518 | #[cfg (not(any( |
| 1519 | target_os = "freebsd" , |
| 1520 | target_os = "fuchsia" , |
| 1521 | target_os = "linux" , |
| 1522 | target_os = "netbsd" , |
| 1523 | target_os = "openbsd" , |
| 1524 | target_os = "cygwin" , |
| 1525 | target_os = "solaris" , |
| 1526 | target_os = "illumos" , |
| 1527 | target_os = "aix" , |
| 1528 | target_vendor = "apple" , |
| 1529 | )))] |
| 1530 | pub fn unlock(&self) -> io::Result<()> { |
| 1531 | Err(io::const_error!(io::ErrorKind::Unsupported, "unlock() not supported" )) |
| 1532 | } |
| 1533 | |
| 1534 | pub fn truncate(&self, size: u64) -> io::Result<()> { |
| 1535 | let size: off64_t = |
| 1536 | size.try_into().map_err(|e| io::Error::new(io::ErrorKind::InvalidInput, e))?; |
| 1537 | cvt_r(|| unsafe { ftruncate64(self.as_raw_fd(), size) }).map(drop) |
| 1538 | } |
| 1539 | |
| 1540 | pub fn read(&self, buf: &mut [u8]) -> io::Result<usize> { |
| 1541 | self.0.read(buf) |
| 1542 | } |
| 1543 | |
| 1544 | pub fn read_vectored(&self, bufs: &mut [IoSliceMut<'_>]) -> io::Result<usize> { |
| 1545 | self.0.read_vectored(bufs) |
| 1546 | } |
| 1547 | |
| 1548 | #[inline ] |
| 1549 | pub fn is_read_vectored(&self) -> bool { |
| 1550 | self.0.is_read_vectored() |
| 1551 | } |
| 1552 | |
| 1553 | pub fn read_at(&self, buf: &mut [u8], offset: u64) -> io::Result<usize> { |
| 1554 | self.0.read_at(buf, offset) |
| 1555 | } |
| 1556 | |
| 1557 | pub fn read_buf(&self, cursor: BorrowedCursor<'_>) -> io::Result<()> { |
| 1558 | self.0.read_buf(cursor) |
| 1559 | } |
| 1560 | |
| 1561 | pub fn read_buf_at(&self, cursor: BorrowedCursor<'_>, offset: u64) -> io::Result<()> { |
| 1562 | self.0.read_buf_at(cursor, offset) |
| 1563 | } |
| 1564 | |
| 1565 | pub fn read_vectored_at(&self, bufs: &mut [IoSliceMut<'_>], offset: u64) -> io::Result<usize> { |
| 1566 | self.0.read_vectored_at(bufs, offset) |
| 1567 | } |
| 1568 | |
| 1569 | pub fn write(&self, buf: &[u8]) -> io::Result<usize> { |
| 1570 | self.0.write(buf) |
| 1571 | } |
| 1572 | |
| 1573 | pub fn write_vectored(&self, bufs: &[IoSlice<'_>]) -> io::Result<usize> { |
| 1574 | self.0.write_vectored(bufs) |
| 1575 | } |
| 1576 | |
| 1577 | #[inline ] |
| 1578 | pub fn is_write_vectored(&self) -> bool { |
| 1579 | self.0.is_write_vectored() |
| 1580 | } |
| 1581 | |
| 1582 | pub fn write_at(&self, buf: &[u8], offset: u64) -> io::Result<usize> { |
| 1583 | self.0.write_at(buf, offset) |
| 1584 | } |
| 1585 | |
| 1586 | pub fn write_vectored_at(&self, bufs: &[IoSlice<'_>], offset: u64) -> io::Result<usize> { |
| 1587 | self.0.write_vectored_at(bufs, offset) |
| 1588 | } |
| 1589 | |
| 1590 | #[inline ] |
| 1591 | pub fn flush(&self) -> io::Result<()> { |
| 1592 | Ok(()) |
| 1593 | } |
| 1594 | |
| 1595 | pub fn seek(&self, pos: SeekFrom) -> io::Result<u64> { |
| 1596 | let (whence, pos) = match pos { |
| 1597 | // Casting to `i64` is fine, too large values will end up as |
| 1598 | // negative which will cause an error in `lseek64`. |
| 1599 | SeekFrom::Start(off) => (libc::SEEK_SET, off as i64), |
| 1600 | SeekFrom::End(off) => (libc::SEEK_END, off), |
| 1601 | SeekFrom::Current(off) => (libc::SEEK_CUR, off), |
| 1602 | }; |
| 1603 | let n = cvt(unsafe { lseek64(self.as_raw_fd(), pos as off64_t, whence) })?; |
| 1604 | Ok(n as u64) |
| 1605 | } |
| 1606 | |
| 1607 | pub fn size(&self) -> Option<io::Result<u64>> { |
| 1608 | match self.file_attr().map(|attr| attr.size()) { |
| 1609 | // Fall back to default implementation if the returned size is 0, |
| 1610 | // we might be in a proc mount. |
| 1611 | Ok(0) => None, |
| 1612 | result => Some(result), |
| 1613 | } |
| 1614 | } |
| 1615 | |
| 1616 | pub fn tell(&self) -> io::Result<u64> { |
| 1617 | self.seek(SeekFrom::Current(0)) |
| 1618 | } |
| 1619 | |
| 1620 | pub fn duplicate(&self) -> io::Result<File> { |
| 1621 | self.0.duplicate().map(File) |
| 1622 | } |
| 1623 | |
| 1624 | pub fn set_permissions(&self, perm: FilePermissions) -> io::Result<()> { |
| 1625 | cvt_r(|| unsafe { libc::fchmod(self.as_raw_fd(), perm.mode) })?; |
| 1626 | Ok(()) |
| 1627 | } |
| 1628 | |
| 1629 | pub fn set_times(&self, times: FileTimes) -> io::Result<()> { |
| 1630 | cfg_select! { |
| 1631 | any(target_os = "redox" , target_os = "espidf" , target_os = "horizon" , target_os = "nuttx" ) => { |
| 1632 | // Redox doesn't appear to support `UTIME_OMIT`. |
| 1633 | // ESP-IDF and HorizonOS do not support `futimens` at all and the behavior for those OS is therefore |
| 1634 | // the same as for Redox. |
| 1635 | let _ = times; |
| 1636 | Err(io::const_error!( |
| 1637 | io::ErrorKind::Unsupported, |
| 1638 | "setting file times not supported" , |
| 1639 | )) |
| 1640 | } |
| 1641 | target_vendor = "apple" => { |
| 1642 | let ta = TimesAttrlist::from_times(×)?; |
| 1643 | cvt(unsafe { libc::fsetattrlist( |
| 1644 | self.as_raw_fd(), |
| 1645 | ta.attrlist(), |
| 1646 | ta.times_buf(), |
| 1647 | ta.times_buf_size(), |
| 1648 | 0 |
| 1649 | ) })?; |
| 1650 | Ok(()) |
| 1651 | } |
| 1652 | target_os = "android" => { |
| 1653 | let times = [file_time_to_timespec(times.accessed)?, file_time_to_timespec(times.modified)?]; |
| 1654 | // futimens requires Android API level 19 |
| 1655 | cvt(unsafe { |
| 1656 | weak!( |
| 1657 | fn futimens(fd: c_int, times: *const libc::timespec) -> c_int; |
| 1658 | ); |
| 1659 | match futimens.get() { |
| 1660 | Some(futimens) => futimens(self.as_raw_fd(), times.as_ptr()), |
| 1661 | None => return Err(io::const_error!( |
| 1662 | io::ErrorKind::Unsupported, |
| 1663 | "setting file times requires Android API level >= 19" , |
| 1664 | )), |
| 1665 | } |
| 1666 | })?; |
| 1667 | Ok(()) |
| 1668 | } |
| 1669 | _ => { |
| 1670 | #[cfg (all(target_os = "linux" , target_env = "gnu" , target_pointer_width = "32" , not(target_arch = "riscv32" )))] |
| 1671 | { |
| 1672 | use crate::sys::{time::__timespec64, weak::weak}; |
| 1673 | |
| 1674 | // Added in glibc 2.34 |
| 1675 | weak!( |
| 1676 | fn __futimens64(fd: c_int, times: *const __timespec64) -> c_int; |
| 1677 | ); |
| 1678 | |
| 1679 | if let Some(futimens64) = __futimens64.get() { |
| 1680 | let to_timespec = |time: Option<SystemTime>| time.map(|time| time.t.to_timespec64()) |
| 1681 | .unwrap_or(__timespec64::new(0, libc::UTIME_OMIT as _)); |
| 1682 | let times = [to_timespec(times.accessed), to_timespec(times.modified)]; |
| 1683 | cvt(unsafe { futimens64(self.as_raw_fd(), times.as_ptr()) })?; |
| 1684 | return Ok(()); |
| 1685 | } |
| 1686 | } |
| 1687 | let times = [file_time_to_timespec(times.accessed)?, file_time_to_timespec(times.modified)?]; |
| 1688 | cvt(unsafe { libc::futimens(self.as_raw_fd(), times.as_ptr()) })?; |
| 1689 | Ok(()) |
| 1690 | } |
| 1691 | } |
| 1692 | } |
| 1693 | } |
| 1694 | |
| 1695 | #[cfg (not(any( |
| 1696 | target_os = "redox" , |
| 1697 | target_os = "espidf" , |
| 1698 | target_os = "horizon" , |
| 1699 | target_os = "nuttx" , |
| 1700 | )))] |
| 1701 | fn file_time_to_timespec(time: Option<SystemTime>) -> io::Result<libc::timespec> { |
| 1702 | match time { |
| 1703 | Some(time: SystemTime) if let Some(ts: timespec) = time.t.to_timespec() => Ok(ts), |
| 1704 | Some(time: SystemTime) if time > crate::sys::time::UNIX_EPOCH => Err(io::const_error!( |
| 1705 | io::ErrorKind::InvalidInput, |
| 1706 | "timestamp is too large to set as a file time" , |
| 1707 | )), |
| 1708 | Some(_) => Err(io::const_error!( |
| 1709 | io::ErrorKind::InvalidInput, |
| 1710 | "timestamp is too small to set as a file time" , |
| 1711 | )), |
| 1712 | None => Ok(libc::timespec { tv_sec: 0, tv_nsec: libc::UTIME_OMIT as _ }), |
| 1713 | } |
| 1714 | } |
| 1715 | |
| 1716 | #[cfg (target_vendor = "apple" )] |
| 1717 | struct TimesAttrlist { |
| 1718 | buf: [mem::MaybeUninit<libc::timespec>; 3], |
| 1719 | attrlist: libc::attrlist, |
| 1720 | num_times: usize, |
| 1721 | } |
| 1722 | |
| 1723 | #[cfg (target_vendor = "apple" )] |
| 1724 | impl TimesAttrlist { |
| 1725 | fn from_times(times: &FileTimes) -> io::Result<Self> { |
| 1726 | let mut this = Self { |
| 1727 | buf: [mem::MaybeUninit::<libc::timespec>::uninit(); 3], |
| 1728 | attrlist: unsafe { mem::zeroed() }, |
| 1729 | num_times: 0, |
| 1730 | }; |
| 1731 | this.attrlist.bitmapcount = libc::ATTR_BIT_MAP_COUNT; |
| 1732 | if times.created.is_some() { |
| 1733 | this.buf[this.num_times].write(file_time_to_timespec(times.created)?); |
| 1734 | this.num_times += 1; |
| 1735 | this.attrlist.commonattr |= libc::ATTR_CMN_CRTIME; |
| 1736 | } |
| 1737 | if times.modified.is_some() { |
| 1738 | this.buf[this.num_times].write(file_time_to_timespec(times.modified)?); |
| 1739 | this.num_times += 1; |
| 1740 | this.attrlist.commonattr |= libc::ATTR_CMN_MODTIME; |
| 1741 | } |
| 1742 | if times.accessed.is_some() { |
| 1743 | this.buf[this.num_times].write(file_time_to_timespec(times.accessed)?); |
| 1744 | this.num_times += 1; |
| 1745 | this.attrlist.commonattr |= libc::ATTR_CMN_ACCTIME; |
| 1746 | } |
| 1747 | Ok(this) |
| 1748 | } |
| 1749 | |
| 1750 | fn attrlist(&self) -> *mut libc::c_void { |
| 1751 | (&raw const self.attrlist).cast::<libc::c_void>().cast_mut() |
| 1752 | } |
| 1753 | |
| 1754 | fn times_buf(&self) -> *mut libc::c_void { |
| 1755 | self.buf.as_ptr().cast::<libc::c_void>().cast_mut() |
| 1756 | } |
| 1757 | |
| 1758 | fn times_buf_size(&self) -> usize { |
| 1759 | self.num_times * size_of::<libc::timespec>() |
| 1760 | } |
| 1761 | } |
| 1762 | |
| 1763 | impl DirBuilder { |
| 1764 | pub fn new() -> DirBuilder { |
| 1765 | DirBuilder { mode: 0o777 } |
| 1766 | } |
| 1767 | |
| 1768 | pub fn mkdir(&self, p: &Path) -> io::Result<()> { |
| 1769 | run_path_with_cstr(path:p, &|p: &CStr| cvt(unsafe { libc::mkdir(p.as_ptr(), self.mode) }).map(|_| ())) |
| 1770 | } |
| 1771 | |
| 1772 | pub fn set_mode(&mut self, mode: u32) { |
| 1773 | self.mode = mode as mode_t; |
| 1774 | } |
| 1775 | } |
| 1776 | |
| 1777 | impl fmt::Debug for DirBuilder { |
| 1778 | fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { |
| 1779 | let DirBuilder { mode: &u32 } = self; |
| 1780 | f.debug_struct("DirBuilder" ).field(name:"mode" , &Mode(*mode)).finish() |
| 1781 | } |
| 1782 | } |
| 1783 | |
| 1784 | impl AsInner<FileDesc> for File { |
| 1785 | #[inline ] |
| 1786 | fn as_inner(&self) -> &FileDesc { |
| 1787 | &self.0 |
| 1788 | } |
| 1789 | } |
| 1790 | |
| 1791 | impl AsInnerMut<FileDesc> for File { |
| 1792 | #[inline ] |
| 1793 | fn as_inner_mut(&mut self) -> &mut FileDesc { |
| 1794 | &mut self.0 |
| 1795 | } |
| 1796 | } |
| 1797 | |
| 1798 | impl IntoInner<FileDesc> for File { |
| 1799 | fn into_inner(self) -> FileDesc { |
| 1800 | self.0 |
| 1801 | } |
| 1802 | } |
| 1803 | |
| 1804 | impl FromInner<FileDesc> for File { |
| 1805 | fn from_inner(file_desc: FileDesc) -> Self { |
| 1806 | Self(file_desc) |
| 1807 | } |
| 1808 | } |
| 1809 | |
| 1810 | impl AsFd for File { |
| 1811 | #[inline ] |
| 1812 | fn as_fd(&self) -> BorrowedFd<'_> { |
| 1813 | self.0.as_fd() |
| 1814 | } |
| 1815 | } |
| 1816 | |
| 1817 | impl AsRawFd for File { |
| 1818 | #[inline ] |
| 1819 | fn as_raw_fd(&self) -> RawFd { |
| 1820 | self.0.as_raw_fd() |
| 1821 | } |
| 1822 | } |
| 1823 | |
| 1824 | impl IntoRawFd for File { |
| 1825 | fn into_raw_fd(self) -> RawFd { |
| 1826 | self.0.into_raw_fd() |
| 1827 | } |
| 1828 | } |
| 1829 | |
| 1830 | impl FromRawFd for File { |
| 1831 | unsafe fn from_raw_fd(raw_fd: RawFd) -> Self { |
| 1832 | Self(FromRawFd::from_raw_fd(raw_fd)) |
| 1833 | } |
| 1834 | } |
| 1835 | |
| 1836 | impl fmt::Debug for File { |
| 1837 | fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { |
| 1838 | #[cfg (any(target_os = "linux" , target_os = "illumos" , target_os = "solaris" ))] |
| 1839 | fn get_path(fd: c_int) -> Option<PathBuf> { |
| 1840 | let mut p = PathBuf::from("/proc/self/fd" ); |
| 1841 | p.push(&fd.to_string()); |
| 1842 | run_path_with_cstr(&p, &readlink).ok() |
| 1843 | } |
| 1844 | |
| 1845 | #[cfg (any(target_vendor = "apple" , target_os = "netbsd" ))] |
| 1846 | fn get_path(fd: c_int) -> Option<PathBuf> { |
| 1847 | // FIXME: The use of PATH_MAX is generally not encouraged, but it |
| 1848 | // is inevitable in this case because Apple targets and NetBSD define `fcntl` |
| 1849 | // with `F_GETPATH` in terms of `MAXPATHLEN`, and there are no |
| 1850 | // alternatives. If a better method is invented, it should be used |
| 1851 | // instead. |
| 1852 | let mut buf = vec![0; libc::PATH_MAX as usize]; |
| 1853 | let n = unsafe { libc::fcntl(fd, libc::F_GETPATH, buf.as_ptr()) }; |
| 1854 | if n == -1 { |
| 1855 | cfg_select! { |
| 1856 | target_os = "netbsd" => { |
| 1857 | // fallback to procfs as last resort |
| 1858 | let mut p = PathBuf::from("/proc/self/fd" ); |
| 1859 | p.push(&fd.to_string()); |
| 1860 | return run_path_with_cstr(&p, &readlink).ok() |
| 1861 | } |
| 1862 | _ => { |
| 1863 | return None; |
| 1864 | } |
| 1865 | } |
| 1866 | } |
| 1867 | let l = buf.iter().position(|&c| c == 0).unwrap(); |
| 1868 | buf.truncate(l as usize); |
| 1869 | buf.shrink_to_fit(); |
| 1870 | Some(PathBuf::from(OsString::from_vec(buf))) |
| 1871 | } |
| 1872 | |
| 1873 | #[cfg (target_os = "freebsd" )] |
| 1874 | fn get_path(fd: c_int) -> Option<PathBuf> { |
| 1875 | let info = Box::<libc::kinfo_file>::new_zeroed(); |
| 1876 | let mut info = unsafe { info.assume_init() }; |
| 1877 | info.kf_structsize = size_of::<libc::kinfo_file>() as libc::c_int; |
| 1878 | let n = unsafe { libc::fcntl(fd, libc::F_KINFO, &mut *info) }; |
| 1879 | if n == -1 { |
| 1880 | return None; |
| 1881 | } |
| 1882 | let buf = unsafe { CStr::from_ptr(info.kf_path.as_mut_ptr()).to_bytes().to_vec() }; |
| 1883 | Some(PathBuf::from(OsString::from_vec(buf))) |
| 1884 | } |
| 1885 | |
| 1886 | #[cfg (target_os = "vxworks" )] |
| 1887 | fn get_path(fd: c_int) -> Option<PathBuf> { |
| 1888 | let mut buf = vec![0; libc::PATH_MAX as usize]; |
| 1889 | let n = unsafe { libc::ioctl(fd, libc::FIOGETNAME, buf.as_ptr()) }; |
| 1890 | if n == -1 { |
| 1891 | return None; |
| 1892 | } |
| 1893 | let l = buf.iter().position(|&c| c == 0).unwrap(); |
| 1894 | buf.truncate(l as usize); |
| 1895 | Some(PathBuf::from(OsString::from_vec(buf))) |
| 1896 | } |
| 1897 | |
| 1898 | #[cfg (not(any( |
| 1899 | target_os = "linux" , |
| 1900 | target_os = "vxworks" , |
| 1901 | target_os = "freebsd" , |
| 1902 | target_os = "netbsd" , |
| 1903 | target_os = "illumos" , |
| 1904 | target_os = "solaris" , |
| 1905 | target_vendor = "apple" , |
| 1906 | )))] |
| 1907 | fn get_path(_fd: c_int) -> Option<PathBuf> { |
| 1908 | // FIXME(#24570): implement this for other Unix platforms |
| 1909 | None |
| 1910 | } |
| 1911 | |
| 1912 | fn get_mode(fd: c_int) -> Option<(bool, bool)> { |
| 1913 | let mode = unsafe { libc::fcntl(fd, libc::F_GETFL) }; |
| 1914 | if mode == -1 { |
| 1915 | return None; |
| 1916 | } |
| 1917 | match mode & libc::O_ACCMODE { |
| 1918 | libc::O_RDONLY => Some((true, false)), |
| 1919 | libc::O_RDWR => Some((true, true)), |
| 1920 | libc::O_WRONLY => Some((false, true)), |
| 1921 | _ => None, |
| 1922 | } |
| 1923 | } |
| 1924 | |
| 1925 | let fd = self.as_raw_fd(); |
| 1926 | let mut b = f.debug_struct("File" ); |
| 1927 | b.field("fd" , &fd); |
| 1928 | if let Some(path) = get_path(fd) { |
| 1929 | b.field("path" , &path); |
| 1930 | } |
| 1931 | if let Some((read, write)) = get_mode(fd) { |
| 1932 | b.field("read" , &read).field("write" , &write); |
| 1933 | } |
| 1934 | b.finish() |
| 1935 | } |
| 1936 | } |
| 1937 | |
| 1938 | // Format in octal, followed by the mode format used in `ls -l`. |
| 1939 | // |
| 1940 | // References: |
| 1941 | // https://pubs.opengroup.org/onlinepubs/009696899/utilities/ls.html |
| 1942 | // https://www.gnu.org/software/libc/manual/html_node/Testing-File-Type.html |
| 1943 | // https://www.gnu.org/software/libc/manual/html_node/Permission-Bits.html |
| 1944 | // |
| 1945 | // Example: |
| 1946 | // 0o100664 (-rw-rw-r--) |
| 1947 | impl fmt::Debug for Mode { |
| 1948 | fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { |
| 1949 | let Self(mode) = *self; |
| 1950 | write!(f, "0o {mode:06o}" )?; |
| 1951 | |
| 1952 | let entry_type = match mode & libc::S_IFMT { |
| 1953 | libc::S_IFDIR => 'd' , |
| 1954 | libc::S_IFBLK => 'b' , |
| 1955 | libc::S_IFCHR => 'c' , |
| 1956 | libc::S_IFLNK => 'l' , |
| 1957 | libc::S_IFIFO => 'p' , |
| 1958 | libc::S_IFREG => '-' , |
| 1959 | _ => return Ok(()), |
| 1960 | }; |
| 1961 | |
| 1962 | f.write_str(" (" )?; |
| 1963 | f.write_char(entry_type)?; |
| 1964 | |
| 1965 | // Owner permissions |
| 1966 | f.write_char(if mode & libc::S_IRUSR != 0 { 'r' } else { '-' })?; |
| 1967 | f.write_char(if mode & libc::S_IWUSR != 0 { 'w' } else { '-' })?; |
| 1968 | let owner_executable = mode & libc::S_IXUSR != 0; |
| 1969 | let setuid = mode as c_int & libc::S_ISUID as c_int != 0; |
| 1970 | f.write_char(match (owner_executable, setuid) { |
| 1971 | (true, true) => 's' , // executable and setuid |
| 1972 | (false, true) => 'S' , // setuid |
| 1973 | (true, false) => 'x' , // executable |
| 1974 | (false, false) => '-' , |
| 1975 | })?; |
| 1976 | |
| 1977 | // Group permissions |
| 1978 | f.write_char(if mode & libc::S_IRGRP != 0 { 'r' } else { '-' })?; |
| 1979 | f.write_char(if mode & libc::S_IWGRP != 0 { 'w' } else { '-' })?; |
| 1980 | let group_executable = mode & libc::S_IXGRP != 0; |
| 1981 | let setgid = mode as c_int & libc::S_ISGID as c_int != 0; |
| 1982 | f.write_char(match (group_executable, setgid) { |
| 1983 | (true, true) => 's' , // executable and setgid |
| 1984 | (false, true) => 'S' , // setgid |
| 1985 | (true, false) => 'x' , // executable |
| 1986 | (false, false) => '-' , |
| 1987 | })?; |
| 1988 | |
| 1989 | // Other permissions |
| 1990 | f.write_char(if mode & libc::S_IROTH != 0 { 'r' } else { '-' })?; |
| 1991 | f.write_char(if mode & libc::S_IWOTH != 0 { 'w' } else { '-' })?; |
| 1992 | let other_executable = mode & libc::S_IXOTH != 0; |
| 1993 | let sticky = mode as c_int & libc::S_ISVTX as c_int != 0; |
| 1994 | f.write_char(match (entry_type, other_executable, sticky) { |
| 1995 | ('d' , true, true) => 't' , // searchable and restricted deletion |
| 1996 | ('d' , false, true) => 'T' , // restricted deletion |
| 1997 | (_, true, _) => 'x' , // executable |
| 1998 | (_, false, _) => '-' , |
| 1999 | })?; |
| 2000 | |
| 2001 | f.write_char(')' ) |
| 2002 | } |
| 2003 | } |
| 2004 | |
| 2005 | pub fn readdir(path: &Path) -> io::Result<ReadDir> { |
| 2006 | let ptr: *mut DIR = run_path_with_cstr(path, &|p: &CStr| unsafe { Ok(libc::opendir(dirname:p.as_ptr())) })?; |
| 2007 | if ptr.is_null() { |
| 2008 | Err(Error::last_os_error()) |
| 2009 | } else { |
| 2010 | let root: PathBuf = path.to_path_buf(); |
| 2011 | let inner: InnerReadDir = InnerReadDir { dirp: Dir(ptr), root }; |
| 2012 | Ok(ReadDir::new(inner)) |
| 2013 | } |
| 2014 | } |
| 2015 | |
| 2016 | pub fn unlink(p: &CStr) -> io::Result<()> { |
| 2017 | cvt(unsafe { libc::unlink(p.as_ptr()) }).map(|_| ()) |
| 2018 | } |
| 2019 | |
| 2020 | pub fn rename(old: &CStr, new: &CStr) -> io::Result<()> { |
| 2021 | cvt(unsafe { libc::rename(old.as_ptr(), new.as_ptr()) }).map(|_| ()) |
| 2022 | } |
| 2023 | |
| 2024 | pub fn set_perm(p: &CStr, perm: FilePermissions) -> io::Result<()> { |
| 2025 | cvt_r(|| unsafe { libc::chmod(p.as_ptr(), perm.mode) }).map(|_| ()) |
| 2026 | } |
| 2027 | |
| 2028 | pub fn rmdir(p: &CStr) -> io::Result<()> { |
| 2029 | cvt(unsafe { libc::rmdir(p.as_ptr()) }).map(|_| ()) |
| 2030 | } |
| 2031 | |
| 2032 | pub fn readlink(c_path: &CStr) -> io::Result<PathBuf> { |
| 2033 | let p = c_path.as_ptr(); |
| 2034 | |
| 2035 | let mut buf = Vec::with_capacity(256); |
| 2036 | |
| 2037 | loop { |
| 2038 | let buf_read = |
| 2039 | cvt(unsafe { libc::readlink(p, buf.as_mut_ptr() as *mut _, buf.capacity()) })? as usize; |
| 2040 | |
| 2041 | unsafe { |
| 2042 | buf.set_len(buf_read); |
| 2043 | } |
| 2044 | |
| 2045 | if buf_read != buf.capacity() { |
| 2046 | buf.shrink_to_fit(); |
| 2047 | |
| 2048 | return Ok(PathBuf::from(OsString::from_vec(buf))); |
| 2049 | } |
| 2050 | |
| 2051 | // Trigger the internal buffer resizing logic of `Vec` by requiring |
| 2052 | // more space than the current capacity. The length is guaranteed to be |
| 2053 | // the same as the capacity due to the if statement above. |
| 2054 | buf.reserve(1); |
| 2055 | } |
| 2056 | } |
| 2057 | |
| 2058 | pub fn symlink(original: &CStr, link: &CStr) -> io::Result<()> { |
| 2059 | cvt(unsafe { libc::symlink(original.as_ptr(), link.as_ptr()) }).map(|_| ()) |
| 2060 | } |
| 2061 | |
| 2062 | pub fn link(original: &CStr, link: &CStr) -> io::Result<()> { |
| 2063 | cfg_select! { |
| 2064 | any(target_os = "vxworks" , target_os = "redox" , target_os = "android" , target_os = "espidf" , target_os = "horizon" , target_os = "vita" , target_env = "nto70" ) => { |
| 2065 | // VxWorks, Redox and ESP-IDF lack `linkat`, so use `link` instead. POSIX leaves |
| 2066 | // it implementation-defined whether `link` follows symlinks, so rely on the |
| 2067 | // `symlink_hard_link` test in library/std/src/fs/tests.rs to check the behavior. |
| 2068 | // Android has `linkat` on newer versions, but we happen to know `link` |
| 2069 | // always has the correct behavior, so it's here as well. |
| 2070 | cvt(unsafe { libc::link(original.as_ptr(), link.as_ptr()) })?; |
| 2071 | } |
| 2072 | _ => { |
| 2073 | // Where we can, use `linkat` instead of `link`; see the comment above |
| 2074 | // this one for details on why. |
| 2075 | cvt(unsafe { libc::linkat(libc::AT_FDCWD, original.as_ptr(), libc::AT_FDCWD, link.as_ptr(), 0) })?; |
| 2076 | } |
| 2077 | } |
| 2078 | Ok(()) |
| 2079 | } |
| 2080 | |
| 2081 | pub fn stat(p: &CStr) -> io::Result<FileAttr> { |
| 2082 | cfg_has_statx! { |
| 2083 | if let Some(ret) = unsafe { try_statx( |
| 2084 | libc::AT_FDCWD, |
| 2085 | p.as_ptr(), |
| 2086 | libc::AT_STATX_SYNC_AS_STAT, |
| 2087 | libc::STATX_BASIC_STATS | libc::STATX_BTIME, |
| 2088 | ) } { |
| 2089 | return ret; |
| 2090 | } |
| 2091 | } |
| 2092 | |
| 2093 | let mut stat: stat64 = unsafe { mem::zeroed() }; |
| 2094 | cvt(unsafe { stat64(path:p.as_ptr(), &mut stat) })?; |
| 2095 | Ok(FileAttr::from_stat64(stat)) |
| 2096 | } |
| 2097 | |
| 2098 | pub fn lstat(p: &CStr) -> io::Result<FileAttr> { |
| 2099 | cfg_has_statx! { |
| 2100 | if let Some(ret) = unsafe { try_statx( |
| 2101 | libc::AT_FDCWD, |
| 2102 | p.as_ptr(), |
| 2103 | libc::AT_SYMLINK_NOFOLLOW | libc::AT_STATX_SYNC_AS_STAT, |
| 2104 | libc::STATX_BASIC_STATS | libc::STATX_BTIME, |
| 2105 | ) } { |
| 2106 | return ret; |
| 2107 | } |
| 2108 | } |
| 2109 | |
| 2110 | let mut stat: stat64 = unsafe { mem::zeroed() }; |
| 2111 | cvt(unsafe { lstat64(path:p.as_ptr(), &mut stat) })?; |
| 2112 | Ok(FileAttr::from_stat64(stat)) |
| 2113 | } |
| 2114 | |
| 2115 | pub fn canonicalize(path: &CStr) -> io::Result<PathBuf> { |
| 2116 | let r: *mut i8 = unsafe { libc::realpath(pathname:path.as_ptr(), resolved:ptr::null_mut()) }; |
| 2117 | if r.is_null() { |
| 2118 | return Err(io::Error::last_os_error()); |
| 2119 | } |
| 2120 | Ok(PathBuf::from(OsString::from_vec(unsafe { |
| 2121 | let buf: Vec = CStr::from_ptr(r).to_bytes().to_vec(); |
| 2122 | libc::free(r as *mut _); |
| 2123 | buf |
| 2124 | }))) |
| 2125 | } |
| 2126 | |
| 2127 | fn open_from(from: &Path) -> io::Result<(crate::fs::File, crate::fs::Metadata)> { |
| 2128 | use crate::fs::File; |
| 2129 | use crate::sys::fs::common::NOT_FILE_ERROR; |
| 2130 | |
| 2131 | let reader: File = File::open(path:from)?; |
| 2132 | let metadata: Metadata = reader.metadata()?; |
| 2133 | if !metadata.is_file() { |
| 2134 | return Err(NOT_FILE_ERROR); |
| 2135 | } |
| 2136 | Ok((reader, metadata)) |
| 2137 | } |
| 2138 | |
| 2139 | fn set_times_impl(p: &CStr, times: FileTimes, follow_symlinks: bool) -> io::Result<()> { |
| 2140 | cfg_select! { |
| 2141 | any(target_os = "redox" , target_os = "espidf" , target_os = "horizon" , target_os = "nuttx" ) => { |
| 2142 | let _ = (p, times, follow_symlinks); |
| 2143 | Err(io::const_error!( |
| 2144 | io::ErrorKind::Unsupported, |
| 2145 | "setting file times not supported" , |
| 2146 | )) |
| 2147 | } |
| 2148 | target_vendor = "apple" => { |
| 2149 | // Apple platforms use setattrlist which supports setting times on symlinks |
| 2150 | let ta = TimesAttrlist::from_times(×)?; |
| 2151 | let options = if follow_symlinks { |
| 2152 | 0 |
| 2153 | } else { |
| 2154 | libc::FSOPT_NOFOLLOW |
| 2155 | }; |
| 2156 | |
| 2157 | cvt(unsafe { libc::setattrlist( |
| 2158 | p.as_ptr(), |
| 2159 | ta.attrlist(), |
| 2160 | ta.times_buf(), |
| 2161 | ta.times_buf_size(), |
| 2162 | options as u32 |
| 2163 | ) })?; |
| 2164 | Ok(()) |
| 2165 | } |
| 2166 | target_os = "android" => { |
| 2167 | let times = [file_time_to_timespec(times.accessed)?, file_time_to_timespec(times.modified)?]; |
| 2168 | let flags = if follow_symlinks { 0 } else { libc::AT_SYMLINK_NOFOLLOW }; |
| 2169 | // utimensat requires Android API level 19 |
| 2170 | cvt(unsafe { |
| 2171 | weak!( |
| 2172 | fn utimensat(dirfd: c_int, path: *const libc::c_char, times: *const libc::timespec, flags: c_int) -> c_int; |
| 2173 | ); |
| 2174 | match utimensat.get() { |
| 2175 | Some(utimensat) => utimensat(libc::AT_FDCWD, p.as_ptr(), times.as_ptr(), flags), |
| 2176 | None => return Err(io::const_error!( |
| 2177 | io::ErrorKind::Unsupported, |
| 2178 | "setting file times requires Android API level >= 19" , |
| 2179 | )), |
| 2180 | } |
| 2181 | })?; |
| 2182 | Ok(()) |
| 2183 | } |
| 2184 | _ => { |
| 2185 | let flags = if follow_symlinks { 0 } else { libc::AT_SYMLINK_NOFOLLOW }; |
| 2186 | #[cfg (all(target_os = "linux" , target_env = "gnu" , target_pointer_width = "32" , not(target_arch = "riscv32" )))] |
| 2187 | { |
| 2188 | use crate::sys::{time::__timespec64, weak::weak}; |
| 2189 | |
| 2190 | // Added in glibc 2.34 |
| 2191 | weak!( |
| 2192 | fn __utimensat64(dirfd: c_int, path: *const c_char, times: *const __timespec64, flags: c_int) -> c_int; |
| 2193 | ); |
| 2194 | |
| 2195 | if let Some(utimensat64) = __utimensat64.get() { |
| 2196 | let to_timespec = |time: Option<SystemTime>| time.map(|time| time.t.to_timespec64()) |
| 2197 | .unwrap_or(__timespec64::new(0, libc::UTIME_OMIT as _)); |
| 2198 | let times = [to_timespec(times.accessed), to_timespec(times.modified)]; |
| 2199 | cvt(unsafe { utimensat64(libc::AT_FDCWD, p.as_ptr(), times.as_ptr(), flags) })?; |
| 2200 | return Ok(()); |
| 2201 | } |
| 2202 | } |
| 2203 | let times = [file_time_to_timespec(times.accessed)?, file_time_to_timespec(times.modified)?]; |
| 2204 | cvt(unsafe { libc::utimensat(libc::AT_FDCWD, p.as_ptr(), times.as_ptr(), flags) })?; |
| 2205 | Ok(()) |
| 2206 | } |
| 2207 | } |
| 2208 | } |
| 2209 | |
| 2210 | #[inline (always)] |
| 2211 | pub fn set_times(p: &CStr, times: FileTimes) -> io::Result<()> { |
| 2212 | set_times_impl(p, times, follow_symlinks:true) |
| 2213 | } |
| 2214 | |
| 2215 | #[inline (always)] |
| 2216 | pub fn set_times_nofollow(p: &CStr, times: FileTimes) -> io::Result<()> { |
| 2217 | set_times_impl(p, times, follow_symlinks:false) |
| 2218 | } |
| 2219 | |
| 2220 | #[cfg (target_os = "espidf" )] |
| 2221 | fn open_to_and_set_permissions( |
| 2222 | to: &Path, |
| 2223 | _reader_metadata: &crate::fs::Metadata, |
| 2224 | ) -> io::Result<(crate::fs::File, crate::fs::Metadata)> { |
| 2225 | use crate::fs::OpenOptions; |
| 2226 | let writer = OpenOptions::new().open(to)?; |
| 2227 | let writer_metadata = writer.metadata()?; |
| 2228 | Ok((writer, writer_metadata)) |
| 2229 | } |
| 2230 | |
| 2231 | #[cfg (not(target_os = "espidf" ))] |
| 2232 | fn open_to_and_set_permissions( |
| 2233 | to: &Path, |
| 2234 | reader_metadata: &crate::fs::Metadata, |
| 2235 | ) -> io::Result<(crate::fs::File, crate::fs::Metadata)> { |
| 2236 | use crate::fs::OpenOptions; |
| 2237 | use crate::os::unix::fs::{OpenOptionsExt, PermissionsExt}; |
| 2238 | |
| 2239 | let perm: Permissions = reader_metadata.permissions(); |
| 2240 | let writer: File = OpenOptions::new() |
| 2241 | // create the file with the correct mode right away |
| 2242 | .mode(perm.mode()) |
| 2243 | .write(true) |
| 2244 | .create(true) |
| 2245 | .truncate(true) |
| 2246 | .open(path:to)?; |
| 2247 | let writer_metadata: Metadata = writer.metadata()?; |
| 2248 | // fchmod is broken on vita |
| 2249 | #[cfg (not(target_os = "vita" ))] |
| 2250 | if writer_metadata.is_file() { |
| 2251 | // Set the correct file permissions, in case the file already existed. |
| 2252 | // Don't set the permissions on already existing non-files like |
| 2253 | // pipes/FIFOs or device nodes. |
| 2254 | writer.set_permissions(perm)?; |
| 2255 | } |
| 2256 | Ok((writer, writer_metadata)) |
| 2257 | } |
| 2258 | |
| 2259 | mod cfm { |
| 2260 | use crate::fs::{File, Metadata}; |
| 2261 | use crate::io::{BorrowedCursor, IoSlice, IoSliceMut, Read, Result, Write}; |
| 2262 | |
| 2263 | #[allow (dead_code)] |
| 2264 | pub struct CachedFileMetadata(pub File, pub Metadata); |
| 2265 | |
| 2266 | impl Read for CachedFileMetadata { |
| 2267 | fn read(&mut self, buf: &mut [u8]) -> Result<usize> { |
| 2268 | self.0.read(buf) |
| 2269 | } |
| 2270 | fn read_vectored(&mut self, bufs: &mut [IoSliceMut<'_>]) -> Result<usize> { |
| 2271 | self.0.read_vectored(bufs) |
| 2272 | } |
| 2273 | fn read_buf(&mut self, cursor: BorrowedCursor<'_>) -> Result<()> { |
| 2274 | self.0.read_buf(cursor) |
| 2275 | } |
| 2276 | #[inline ] |
| 2277 | fn is_read_vectored(&self) -> bool { |
| 2278 | self.0.is_read_vectored() |
| 2279 | } |
| 2280 | fn read_to_end(&mut self, buf: &mut Vec<u8>) -> Result<usize> { |
| 2281 | self.0.read_to_end(buf) |
| 2282 | } |
| 2283 | fn read_to_string(&mut self, buf: &mut String) -> Result<usize> { |
| 2284 | self.0.read_to_string(buf) |
| 2285 | } |
| 2286 | } |
| 2287 | impl Write for CachedFileMetadata { |
| 2288 | fn write(&mut self, buf: &[u8]) -> Result<usize> { |
| 2289 | self.0.write(buf) |
| 2290 | } |
| 2291 | fn write_vectored(&mut self, bufs: &[IoSlice<'_>]) -> Result<usize> { |
| 2292 | self.0.write_vectored(bufs) |
| 2293 | } |
| 2294 | #[inline ] |
| 2295 | fn is_write_vectored(&self) -> bool { |
| 2296 | self.0.is_write_vectored() |
| 2297 | } |
| 2298 | #[inline ] |
| 2299 | fn flush(&mut self) -> Result<()> { |
| 2300 | self.0.flush() |
| 2301 | } |
| 2302 | } |
| 2303 | } |
| 2304 | #[cfg (any(target_os = "linux" , target_os = "android" ))] |
| 2305 | pub(in crate::sys) use cfm::CachedFileMetadata; |
| 2306 | |
| 2307 | #[cfg (not(target_vendor = "apple" ))] |
| 2308 | pub fn copy(from: &Path, to: &Path) -> io::Result<u64> { |
| 2309 | let (reader: File, reader_metadata: Metadata) = open_from(from)?; |
| 2310 | let (writer: File, writer_metadata: Metadata) = open_to_and_set_permissions(to, &reader_metadata)?; |
| 2311 | |
| 2312 | io::copy( |
| 2313 | &mut cfm::CachedFileMetadata(reader, reader_metadata), |
| 2314 | &mut cfm::CachedFileMetadata(writer, writer_metadata), |
| 2315 | ) |
| 2316 | } |
| 2317 | |
| 2318 | #[cfg (target_vendor = "apple" )] |
| 2319 | pub fn copy(from: &Path, to: &Path) -> io::Result<u64> { |
| 2320 | const COPYFILE_ALL: libc::copyfile_flags_t = libc::COPYFILE_METADATA | libc::COPYFILE_DATA; |
| 2321 | |
| 2322 | struct FreeOnDrop(libc::copyfile_state_t); |
| 2323 | impl Drop for FreeOnDrop { |
| 2324 | fn drop(&mut self) { |
| 2325 | // The code below ensures that `FreeOnDrop` is never a null pointer |
| 2326 | unsafe { |
| 2327 | // `copyfile_state_free` returns -1 if the `to` or `from` files |
| 2328 | // cannot be closed. However, this is not considered an error. |
| 2329 | libc::copyfile_state_free(self.0); |
| 2330 | } |
| 2331 | } |
| 2332 | } |
| 2333 | |
| 2334 | let (reader, reader_metadata) = open_from(from)?; |
| 2335 | |
| 2336 | let clonefile_result = run_path_with_cstr(to, &|to| { |
| 2337 | cvt(unsafe { libc::fclonefileat(reader.as_raw_fd(), libc::AT_FDCWD, to.as_ptr(), 0) }) |
| 2338 | }); |
| 2339 | match clonefile_result { |
| 2340 | Ok(_) => return Ok(reader_metadata.len()), |
| 2341 | Err(e) => match e.raw_os_error() { |
| 2342 | // `fclonefileat` will fail on non-APFS volumes, if the |
| 2343 | // destination already exists, or if the source and destination |
| 2344 | // are on different devices. In all these cases `fcopyfile` |
| 2345 | // should succeed. |
| 2346 | Some(libc::ENOTSUP) | Some(libc::EEXIST) | Some(libc::EXDEV) => (), |
| 2347 | _ => return Err(e), |
| 2348 | }, |
| 2349 | } |
| 2350 | |
| 2351 | // Fall back to using `fcopyfile` if `fclonefileat` does not succeed. |
| 2352 | let (writer, writer_metadata) = open_to_and_set_permissions(to, &reader_metadata)?; |
| 2353 | |
| 2354 | // We ensure that `FreeOnDrop` never contains a null pointer so it is |
| 2355 | // always safe to call `copyfile_state_free` |
| 2356 | let state = unsafe { |
| 2357 | let state = libc::copyfile_state_alloc(); |
| 2358 | if state.is_null() { |
| 2359 | return Err(crate::io::Error::last_os_error()); |
| 2360 | } |
| 2361 | FreeOnDrop(state) |
| 2362 | }; |
| 2363 | |
| 2364 | let flags = if writer_metadata.is_file() { COPYFILE_ALL } else { libc::COPYFILE_DATA }; |
| 2365 | |
| 2366 | cvt(unsafe { libc::fcopyfile(reader.as_raw_fd(), writer.as_raw_fd(), state.0, flags) })?; |
| 2367 | |
| 2368 | let mut bytes_copied: libc::off_t = 0; |
| 2369 | cvt(unsafe { |
| 2370 | libc::copyfile_state_get( |
| 2371 | state.0, |
| 2372 | libc::COPYFILE_STATE_COPIED as u32, |
| 2373 | (&raw mut bytes_copied) as *mut libc::c_void, |
| 2374 | ) |
| 2375 | })?; |
| 2376 | Ok(bytes_copied as u64) |
| 2377 | } |
| 2378 | |
| 2379 | pub fn chown(path: &Path, uid: u32, gid: u32) -> io::Result<()> { |
| 2380 | run_path_with_cstr(path, &|path: &CStr| { |
| 2381 | cvt(unsafe { libc::chown(path.as_ptr(), uid as libc::uid_t, gid as libc::gid_t) }) |
| 2382 | .map(|_| ()) |
| 2383 | }) |
| 2384 | } |
| 2385 | |
| 2386 | pub fn fchown(fd: c_int, uid: u32, gid: u32) -> io::Result<()> { |
| 2387 | cvt(unsafe { libc::fchown(fd, owner:uid as libc::uid_t, group:gid as libc::gid_t) })?; |
| 2388 | Ok(()) |
| 2389 | } |
| 2390 | |
| 2391 | #[cfg (not(target_os = "vxworks" ))] |
| 2392 | pub fn lchown(path: &Path, uid: u32, gid: u32) -> io::Result<()> { |
| 2393 | run_path_with_cstr(path, &|path: &CStr| { |
| 2394 | cvt(unsafe { libc::lchown(path.as_ptr(), uid as libc::uid_t, gid as libc::gid_t) }) |
| 2395 | .map(|_| ()) |
| 2396 | }) |
| 2397 | } |
| 2398 | |
| 2399 | #[cfg (target_os = "vxworks" )] |
| 2400 | pub fn lchown(path: &Path, uid: u32, gid: u32) -> io::Result<()> { |
| 2401 | let (_, _, _) = (path, uid, gid); |
| 2402 | Err(io::const_error!(io::ErrorKind::Unsupported, "lchown not supported by vxworks" )) |
| 2403 | } |
| 2404 | |
| 2405 | #[cfg (not(any(target_os = "fuchsia" , target_os = "vxworks" )))] |
| 2406 | pub fn chroot(dir: &Path) -> io::Result<()> { |
| 2407 | run_path_with_cstr(path:dir, &|dir: &CStr| cvt(unsafe { libc::chroot(dir.as_ptr()) }).map(|_| ())) |
| 2408 | } |
| 2409 | |
| 2410 | #[cfg (target_os = "vxworks" )] |
| 2411 | pub fn chroot(dir: &Path) -> io::Result<()> { |
| 2412 | let _ = dir; |
| 2413 | Err(io::const_error!(io::ErrorKind::Unsupported, "chroot not supported by vxworks" )) |
| 2414 | } |
| 2415 | |
| 2416 | pub fn mkfifo(path: &Path, mode: u32) -> io::Result<()> { |
| 2417 | run_path_with_cstr(path, &|path: &CStr| { |
| 2418 | cvt(unsafe { libc::mkfifo(path.as_ptr(), mode.try_into().unwrap()) }).map(|_| ()) |
| 2419 | }) |
| 2420 | } |
| 2421 | |
| 2422 | pub use remove_dir_impl::remove_dir_all; |
| 2423 | |
| 2424 | // Fallback for REDOX, ESP-ID, Horizon, Vita, Vxworks and Miri |
| 2425 | #[cfg (any( |
| 2426 | target_os = "redox" , |
| 2427 | target_os = "espidf" , |
| 2428 | target_os = "horizon" , |
| 2429 | target_os = "vita" , |
| 2430 | target_os = "nto" , |
| 2431 | target_os = "vxworks" , |
| 2432 | miri |
| 2433 | ))] |
| 2434 | mod remove_dir_impl { |
| 2435 | pub use crate::sys::fs::common::remove_dir_all; |
| 2436 | } |
| 2437 | |
| 2438 | // Modern implementation using openat(), unlinkat() and fdopendir() |
| 2439 | #[cfg (not(any( |
| 2440 | target_os = "redox" , |
| 2441 | target_os = "espidf" , |
| 2442 | target_os = "horizon" , |
| 2443 | target_os = "vita" , |
| 2444 | target_os = "nto" , |
| 2445 | target_os = "vxworks" , |
| 2446 | miri |
| 2447 | )))] |
| 2448 | mod remove_dir_impl { |
| 2449 | #[cfg (not(all(target_os = "linux" , target_env = "gnu" )))] |
| 2450 | use libc::{fdopendir, openat, unlinkat}; |
| 2451 | #[cfg (all(target_os = "linux" , target_env = "gnu" ))] |
| 2452 | use libc::{fdopendir, openat64 as openat, unlinkat}; |
| 2453 | |
| 2454 | use super::{Dir, DirEntry, InnerReadDir, ReadDir, lstat}; |
| 2455 | use crate::ffi::CStr; |
| 2456 | use crate::io; |
| 2457 | use crate::os::unix::io::{AsRawFd, FromRawFd, IntoRawFd}; |
| 2458 | use crate::os::unix::prelude::{OwnedFd, RawFd}; |
| 2459 | use crate::path::{Path, PathBuf}; |
| 2460 | use crate::sys::common::small_c_string::run_path_with_cstr; |
| 2461 | use crate::sys::{cvt, cvt_r}; |
| 2462 | use crate::sys_common::ignore_notfound; |
| 2463 | |
| 2464 | pub fn openat_nofollow_dironly(parent_fd: Option<RawFd>, p: &CStr) -> io::Result<OwnedFd> { |
| 2465 | let fd = cvt_r(|| unsafe { |
| 2466 | openat( |
| 2467 | parent_fd.unwrap_or(libc::AT_FDCWD), |
| 2468 | p.as_ptr(), |
| 2469 | libc::O_CLOEXEC | libc::O_RDONLY | libc::O_NOFOLLOW | libc::O_DIRECTORY, |
| 2470 | ) |
| 2471 | })?; |
| 2472 | Ok(unsafe { OwnedFd::from_raw_fd(fd) }) |
| 2473 | } |
| 2474 | |
| 2475 | fn fdreaddir(dir_fd: OwnedFd) -> io::Result<(ReadDir, RawFd)> { |
| 2476 | let ptr = unsafe { fdopendir(dir_fd.as_raw_fd()) }; |
| 2477 | if ptr.is_null() { |
| 2478 | return Err(io::Error::last_os_error()); |
| 2479 | } |
| 2480 | let dirp = Dir(ptr); |
| 2481 | // file descriptor is automatically closed by libc::closedir() now, so give up ownership |
| 2482 | let new_parent_fd = dir_fd.into_raw_fd(); |
| 2483 | // a valid root is not needed because we do not call any functions involving the full path |
| 2484 | // of the `DirEntry`s. |
| 2485 | let dummy_root = PathBuf::new(); |
| 2486 | let inner = InnerReadDir { dirp, root: dummy_root }; |
| 2487 | Ok((ReadDir::new(inner), new_parent_fd)) |
| 2488 | } |
| 2489 | |
| 2490 | #[cfg (any( |
| 2491 | target_os = "solaris" , |
| 2492 | target_os = "illumos" , |
| 2493 | target_os = "haiku" , |
| 2494 | target_os = "vxworks" , |
| 2495 | target_os = "aix" , |
| 2496 | ))] |
| 2497 | fn is_dir(_ent: &DirEntry) -> Option<bool> { |
| 2498 | None |
| 2499 | } |
| 2500 | |
| 2501 | #[cfg (not(any( |
| 2502 | target_os = "solaris" , |
| 2503 | target_os = "illumos" , |
| 2504 | target_os = "haiku" , |
| 2505 | target_os = "vxworks" , |
| 2506 | target_os = "aix" , |
| 2507 | )))] |
| 2508 | fn is_dir(ent: &DirEntry) -> Option<bool> { |
| 2509 | match ent.entry.d_type { |
| 2510 | libc::DT_UNKNOWN => None, |
| 2511 | libc::DT_DIR => Some(true), |
| 2512 | _ => Some(false), |
| 2513 | } |
| 2514 | } |
| 2515 | |
| 2516 | fn is_enoent(result: &io::Result<()>) -> bool { |
| 2517 | if let Err(err) = result |
| 2518 | && matches!(err.raw_os_error(), Some(libc::ENOENT)) |
| 2519 | { |
| 2520 | true |
| 2521 | } else { |
| 2522 | false |
| 2523 | } |
| 2524 | } |
| 2525 | |
| 2526 | fn remove_dir_all_recursive(parent_fd: Option<RawFd>, path: &CStr) -> io::Result<()> { |
| 2527 | // try opening as directory |
| 2528 | let fd = match openat_nofollow_dironly(parent_fd, &path) { |
| 2529 | Err(err) if matches!(err.raw_os_error(), Some(libc::ENOTDIR | libc::ELOOP)) => { |
| 2530 | // not a directory - don't traverse further |
| 2531 | // (for symlinks, older Linux kernels may return ELOOP instead of ENOTDIR) |
| 2532 | return match parent_fd { |
| 2533 | // unlink... |
| 2534 | Some(parent_fd) => { |
| 2535 | cvt(unsafe { unlinkat(parent_fd, path.as_ptr(), 0) }).map(drop) |
| 2536 | } |
| 2537 | // ...unless this was supposed to be the deletion root directory |
| 2538 | None => Err(err), |
| 2539 | }; |
| 2540 | } |
| 2541 | result => result?, |
| 2542 | }; |
| 2543 | |
| 2544 | // open the directory passing ownership of the fd |
| 2545 | let (dir, fd) = fdreaddir(fd)?; |
| 2546 | for child in dir { |
| 2547 | let child = child?; |
| 2548 | let child_name = child.name_cstr(); |
| 2549 | // we need an inner try block, because if one of these |
| 2550 | // directories has already been deleted, then we need to |
| 2551 | // continue the loop, not return ok. |
| 2552 | let result: io::Result<()> = try { |
| 2553 | match is_dir(&child) { |
| 2554 | Some(true) => { |
| 2555 | remove_dir_all_recursive(Some(fd), child_name)?; |
| 2556 | } |
| 2557 | Some(false) => { |
| 2558 | cvt(unsafe { unlinkat(fd, child_name.as_ptr(), 0) })?; |
| 2559 | } |
| 2560 | None => { |
| 2561 | // POSIX specifies that calling unlink()/unlinkat(..., 0) on a directory can succeed |
| 2562 | // if the process has the appropriate privileges. This however can causing orphaned |
| 2563 | // directories requiring an fsck e.g. on Solaris and Illumos. So we try recursing |
| 2564 | // into it first instead of trying to unlink() it. |
| 2565 | remove_dir_all_recursive(Some(fd), child_name)?; |
| 2566 | } |
| 2567 | } |
| 2568 | }; |
| 2569 | if result.is_err() && !is_enoent(&result) { |
| 2570 | return result; |
| 2571 | } |
| 2572 | } |
| 2573 | |
| 2574 | // unlink the directory after removing its contents |
| 2575 | ignore_notfound(cvt(unsafe { |
| 2576 | unlinkat(parent_fd.unwrap_or(libc::AT_FDCWD), path.as_ptr(), libc::AT_REMOVEDIR) |
| 2577 | }))?; |
| 2578 | Ok(()) |
| 2579 | } |
| 2580 | |
| 2581 | fn remove_dir_all_modern(p: &CStr) -> io::Result<()> { |
| 2582 | // We cannot just call remove_dir_all_recursive() here because that would not delete a passed |
| 2583 | // symlink. No need to worry about races, because remove_dir_all_recursive() does not recurse |
| 2584 | // into symlinks. |
| 2585 | let attr = lstat(p)?; |
| 2586 | if attr.file_type().is_symlink() { |
| 2587 | super::unlink(p) |
| 2588 | } else { |
| 2589 | remove_dir_all_recursive(None, &p) |
| 2590 | } |
| 2591 | } |
| 2592 | |
| 2593 | pub fn remove_dir_all(p: &Path) -> io::Result<()> { |
| 2594 | run_path_with_cstr(p, &remove_dir_all_modern) |
| 2595 | } |
| 2596 | } |
| 2597 | |