]> git.proxmox.com Git - rustc.git/blob - compiler/rustc_data_structures/src/flock/unix.rs
New upstream version 1.74.1+dfsg1
[rustc.git] / compiler / rustc_data_structures / src / flock / unix.rs
1 use std::fs::{File, OpenOptions};
2 use std::io;
3 use std::mem;
4 use std::os::unix::prelude::*;
5 use std::path::Path;
6
7 #[derive(Debug)]
8 pub struct Lock {
9 file: File,
10 }
11
12 impl Lock {
13 pub fn new(p: &Path, wait: bool, create: bool, exclusive: bool) -> io::Result<Lock> {
14 let file = OpenOptions::new()
15 .read(true)
16 .write(true)
17 .create(create)
18 .mode(libc::S_IRWXU as u32)
19 .open(p)?;
20
21 let lock_type = if exclusive { libc::F_WRLCK } else { libc::F_RDLCK };
22
23 let mut flock: libc::flock = unsafe { mem::zeroed() };
24 #[cfg(not(all(target_os = "hurd", target_arch = "x86")))]
25 {
26 flock.l_type = lock_type as libc::c_short;
27 flock.l_whence = libc::SEEK_SET as libc::c_short;
28 }
29 #[cfg(all(target_os = "hurd", target_arch = "x86"))]
30 {
31 flock.l_type = lock_type as libc::c_int;
32 flock.l_whence = libc::SEEK_SET as libc::c_int;
33 }
34 flock.l_start = 0;
35 flock.l_len = 0;
36
37 let cmd = if wait { libc::F_SETLKW } else { libc::F_SETLK };
38 let ret = unsafe { libc::fcntl(file.as_raw_fd(), cmd, &flock) };
39 if ret == -1 { Err(io::Error::last_os_error()) } else { Ok(Lock { file }) }
40 }
41
42 pub fn error_unsupported(err: &io::Error) -> bool {
43 matches!(err.raw_os_error(), Some(libc::ENOTSUP) | Some(libc::ENOSYS))
44 }
45 }
46
47 impl Drop for Lock {
48 fn drop(&mut self) {
49 let mut flock: libc::flock = unsafe { mem::zeroed() };
50 #[cfg(not(all(target_os = "hurd", target_arch = "x86")))]
51 {
52 flock.l_type = libc::F_UNLCK as libc::c_short;
53 flock.l_whence = libc::SEEK_SET as libc::c_short;
54 }
55 #[cfg(all(target_os = "hurd", target_arch = "x86"))]
56 {
57 flock.l_type = libc::F_UNLCK as libc::c_int;
58 flock.l_whence = libc::SEEK_SET as libc::c_int;
59 }
60 flock.l_start = 0;
61 flock.l_len = 0;
62
63 unsafe {
64 libc::fcntl(self.file.as_raw_fd(), libc::F_SETLK, &flock);
65 }
66 }
67 }