1use crate::FileTime;
6use std::ffi::CString;
7use std::fs;
8use std::io;
9use std::os::unix::prelude::*;
10use std::path::Path;
11use std::ptr;
12use std::sync::atomic::AtomicBool;
13use std::sync::atomic::Ordering::SeqCst;
14
15pub fn set_file_times(p: &Path, atime: FileTime, mtime: FileTime) -> io::Result<()> {
16 set_times(p, Some(atime), Some(mtime), false)
17}
18
19pub fn set_file_mtime(p: &Path, mtime: FileTime) -> io::Result<()> {
20 set_times(p, None, Some(mtime), false)
21}
22
23pub fn set_file_atime(p: &Path, atime: FileTime) -> io::Result<()> {
24 set_times(p, Some(atime), None, false)
25}
26
27pub fn set_file_handle_times(
28 f: &fs::File,
29 atime: Option<FileTime>,
30 mtime: Option<FileTime>,
31) -> io::Result<()> {
32 static INVALID: AtomicBool = AtomicBool::new(false);
35 if !INVALID.load(SeqCst) {
36 let times = [super::to_timespec(&atime), super::to_timespec(&mtime)];
37
38 #[cfg(not(target_env = "musl"))]
42 let rc = unsafe {
43 libc::syscall(
44 libc::SYS_utimensat,
45 f.as_raw_fd(),
46 ptr::null::<libc::c_char>(),
47 times.as_ptr(),
48 0,
49 )
50 };
51 #[cfg(target_env = "musl")]
60 let rc = unsafe {
61 libc::utimensat(
62 f.as_raw_fd(),
63 ptr::null::<libc::c_char>(),
64 times.as_ptr(),
65 0,
66 )
67 };
68
69 if rc == 0 {
70 return Ok(());
71 }
72 let err = io::Error::last_os_error();
73 if err.raw_os_error() == Some(libc::ENOSYS) {
74 INVALID.store(true, SeqCst);
75 } else {
76 return Err(err);
77 }
78 }
79
80 super::utimes::set_file_handle_times(f, atime, mtime)
81}
82
83pub fn set_symlink_file_times(p: &Path, atime: FileTime, mtime: FileTime) -> io::Result<()> {
84 set_times(p, Some(atime), Some(mtime), true)
85}
86
87fn set_times(
88 p: &Path,
89 atime: Option<FileTime>,
90 mtime: Option<FileTime>,
91 symlink: bool,
92) -> io::Result<()> {
93 let flags = if symlink {
94 libc::AT_SYMLINK_NOFOLLOW
95 } else {
96 0
97 };
98
99 static INVALID: AtomicBool = AtomicBool::new(false);
101 if !INVALID.load(SeqCst) {
102 let p = CString::new(p.as_os_str().as_bytes())?;
103 let times = [super::to_timespec(&atime), super::to_timespec(&mtime)];
104 let rc = unsafe { libc::utimensat(libc::AT_FDCWD, p.as_ptr(), times.as_ptr(), flags) };
105 if rc == 0 {
106 return Ok(());
107 }
108 let err = io::Error::last_os_error();
109 if err.raw_os_error() == Some(libc::ENOSYS) {
110 INVALID.store(true, SeqCst);
111 } else {
112 return Err(err);
113 }
114 }
115
116 super::utimes::set_times(p, atime, mtime, symlink)
117}