| 1 |
//! Beginning with macOS 10.13, `utimensat` is supported by the OS, so here, we check if the symbol exists |
| 2 |
//! and if not, we fallback to `utimes`. |
| 3 |
|
| 4 |
use crate::FileTime; |
| 5 |
use libc::{c_char, c_int, timespec}; |
| 6 |
use std::ffi::{CStr, CString}; |
| 7 |
use std::os::unix::prelude::*; |
| 8 |
use std::path::Path; |
| 9 |
use std::sync::atomic::AtomicUsize; |
| 10 |
use std::sync::atomic::Ordering::SeqCst; |
| 11 |
use std::{io, mem}; |
| 12 |
|
| 13 |
pub fn set_symlink_file_times(p: &Path, atime: FileTime, mtime: FileTime) -> io::Result<()> { |
| 14 |
set_times(p, Some(atime), Some(mtime), true) |
| 15 |
} |
| 16 |
|
| 17 |
fn set_times( |
| 18 |
p: &Path, |
| 19 |
atime: Option<FileTime>, |
| 20 |
mtime: Option<FileTime>, |
| 21 |
symlink: bool, |
| 22 |
) -> io::Result<()> { |
| 23 |
// Attempt to use the `utimensat` syscall, but if it's not supported by the |
| 24 |
// current kernel then fall back to an older syscall. |
| 25 |
if let Some(func) = utimensat() { |
| 26 |
let flags = if symlink { |
| 27 |
libc::AT_SYMLINK_NOFOLLOW |
| 28 |
} else { |
| 29 |
0 |
| 30 |
}; |
| 31 |
|
| 32 |
let p = CString::new(p.as_os_str().as_bytes())?; |
| 33 |
let times = [super::to_timespec(&atime), super::to_timespec(&mtime)]; |
| 34 |
let rc = unsafe { func(libc::AT_FDCWD, p.as_ptr(), times.as_ptr(), flags) }; |
| 35 |
if rc == 0 { |
| 36 |
return Ok(()); |
| 37 |
} else { |
| 38 |
return Err(io::Error::last_os_error()); |
| 39 |
} |
| 40 |
} |
| 41 |
|
| 42 |
super::utimes::set_times(p, atime, mtime, symlink) |
| 43 |
} |
| 44 |
|
| 45 |
fn utimensat() -> Option<unsafe extern "C" fn(c_int, *const c_char, *const timespec, c_int) -> c_int> |
| 46 |
{ |
| 47 |
static ADDR: AtomicUsize = AtomicUsize::new(0); |
| 48 |
unsafe { |
| 49 |
fetch(&ADDR, CStr::from_bytes_with_nul_unchecked(b"utimensat\0")) |
| 50 |
.map(|sym| mem::transmute(sym)) |
| 51 |
} |
| 52 |
} |
| 53 |
|
| 54 |
fn fetch(cache: &AtomicUsize, name: &CStr) -> Option<usize> { |
| 55 |
match cache.load(SeqCst) { |
| 56 |
0 => {} |
| 57 |
1 => return None, |
| 58 |
n => return Some(n), |
| 59 |
} |
| 60 |
let sym = unsafe { libc::dlsym(libc::RTLD_DEFAULT, name.as_ptr() as *const _) }; |
| 61 |
let (val, ret) = if sym.is_null() { |
| 62 |
(1, None) |
| 63 |
} else { |
| 64 |
(sym as usize, Some(sym as usize)) |
| 65 |
}; |
| 66 |
cache.store(val, SeqCst); |
| 67 |
return ret; |
| 68 |
} |