]> git.lizzy.rs Git - rust.git/blob - src/librustc_data_structures/flock.rs
Auto merge of #56614 - Zoxc:query-perf2, r=michaelwoerister
[rust.git] / src / librustc_data_structures / flock.rs
1 //! Simple file-locking apis for each OS.
2 //!
3 //! This is not meant to be in the standard library, it does nothing with
4 //! green/native threading. This is just a bare-bones enough solution for
5 //! librustdoc, it is not production quality at all.
6
7 #![allow(non_camel_case_types)]
8 #![allow(nonstandard_style)]
9
10 use std::io;
11 use std::path::Path;
12
13 cfg_if! {
14     if #[cfg(unix)] {
15         use std::ffi::{CString, OsStr};
16         use std::os::unix::prelude::*;
17         use libc;
18
19         #[cfg(any(target_os = "linux", target_os = "android"))]
20         mod os {
21             use libc;
22
23             #[repr(C)]
24             pub struct flock {
25                 pub l_type: libc::c_short,
26                 pub l_whence: libc::c_short,
27                 pub l_start: libc::off_t,
28                 pub l_len: libc::off_t,
29                 pub l_pid: libc::pid_t,
30
31                 // not actually here, but brings in line with freebsd
32                 pub l_sysid: libc::c_int,
33             }
34         }
35
36         #[cfg(target_os = "freebsd")]
37         mod os {
38             use libc;
39
40             #[repr(C)]
41             pub struct flock {
42                 pub l_start: libc::off_t,
43                 pub l_len: libc::off_t,
44                 pub l_pid: libc::pid_t,
45                 pub l_type: libc::c_short,
46                 pub l_whence: libc::c_short,
47                 pub l_sysid: libc::c_int,
48             }
49         }
50
51         #[cfg(any(target_os = "dragonfly",
52                   target_os = "bitrig",
53                   target_os = "netbsd",
54                   target_os = "openbsd"))]
55         mod os {
56             use libc;
57
58             #[repr(C)]
59             pub struct flock {
60                 pub l_start: libc::off_t,
61                 pub l_len: libc::off_t,
62                 pub l_pid: libc::pid_t,
63                 pub l_type: libc::c_short,
64                 pub l_whence: libc::c_short,
65
66                 // not actually here, but brings in line with freebsd
67                 pub l_sysid: libc::c_int,
68             }
69         }
70
71         #[cfg(target_os = "haiku")]
72         mod os {
73             use libc;
74
75             #[repr(C)]
76             pub struct flock {
77                 pub l_type: libc::c_short,
78                 pub l_whence: libc::c_short,
79                 pub l_start: libc::off_t,
80                 pub l_len: libc::off_t,
81                 pub l_pid: libc::pid_t,
82
83                 // not actually here, but brings in line with freebsd
84                 pub l_sysid: libc::c_int,
85             }
86         }
87
88         #[cfg(any(target_os = "macos", target_os = "ios"))]
89         mod os {
90             use libc;
91
92             #[repr(C)]
93             pub struct flock {
94                 pub l_start: libc::off_t,
95                 pub l_len: libc::off_t,
96                 pub l_pid: libc::pid_t,
97                 pub l_type: libc::c_short,
98                 pub l_whence: libc::c_short,
99
100                 // not actually here, but brings in line with freebsd
101                 pub l_sysid: libc::c_int,
102             }
103         }
104
105         #[cfg(target_os = "solaris")]
106         mod os {
107             use libc;
108
109             #[repr(C)]
110             pub struct flock {
111                 pub l_type: libc::c_short,
112                 pub l_whence: libc::c_short,
113                 pub l_start: libc::off_t,
114                 pub l_len: libc::off_t,
115                 pub l_sysid: libc::c_int,
116                 pub l_pid: libc::pid_t,
117             }
118         }
119
120         #[derive(Debug)]
121         pub struct Lock {
122             fd: libc::c_int,
123         }
124
125         impl Lock {
126             pub fn new(p: &Path,
127                        wait: bool,
128                        create: bool,
129                        exclusive: bool)
130                        -> io::Result<Lock> {
131                 let os: &OsStr = p.as_ref();
132                 let buf = CString::new(os.as_bytes()).unwrap();
133                 let open_flags = if create {
134                     libc::O_RDWR | libc::O_CREAT
135                 } else {
136                     libc::O_RDWR
137                 };
138
139                 let fd = unsafe {
140                     libc::open(buf.as_ptr(), open_flags,
141                                libc::S_IRWXU as libc::c_int)
142                 };
143
144                 if fd < 0 {
145                     return Err(io::Error::last_os_error());
146                 }
147
148                 let lock_type = if exclusive {
149                     libc::F_WRLCK as libc::c_short
150                 } else {
151                     libc::F_RDLCK as libc::c_short
152                 };
153
154                 let flock = os::flock {
155                     l_start: 0,
156                     l_len: 0,
157                     l_pid: 0,
158                     l_whence: libc::SEEK_SET as libc::c_short,
159                     l_type: lock_type,
160                     l_sysid: 0,
161                 };
162                 let cmd = if wait { libc::F_SETLKW } else { libc::F_SETLK };
163                 let ret = unsafe {
164                     libc::fcntl(fd, cmd, &flock)
165                 };
166                 if ret == -1 {
167                     let err = io::Error::last_os_error();
168                     unsafe { libc::close(fd); }
169                     Err(err)
170                 } else {
171                     Ok(Lock { fd })
172                 }
173             }
174         }
175
176         impl Drop for Lock {
177             fn drop(&mut self) {
178                 let flock = os::flock {
179                     l_start: 0,
180                     l_len: 0,
181                     l_pid: 0,
182                     l_whence: libc::SEEK_SET as libc::c_short,
183                     l_type: libc::F_UNLCK as libc::c_short,
184                     l_sysid: 0,
185                 };
186                 unsafe {
187                     libc::fcntl(self.fd, libc::F_SETLK, &flock);
188                     libc::close(self.fd);
189                 }
190             }
191         }
192     } else if #[cfg(windows)] {
193         use std::mem;
194         use std::os::windows::prelude::*;
195         use std::os::windows::raw::HANDLE;
196         use std::fs::{File, OpenOptions};
197         use std::os::raw::{c_ulong, c_int};
198
199         type DWORD = c_ulong;
200         type BOOL = c_int;
201         type ULONG_PTR = usize;
202
203         type LPOVERLAPPED = *mut OVERLAPPED;
204         const LOCKFILE_EXCLUSIVE_LOCK: DWORD = 0x0000_0002;
205         const LOCKFILE_FAIL_IMMEDIATELY: DWORD = 0x0000_0001;
206
207         const FILE_SHARE_DELETE: DWORD = 0x4;
208         const FILE_SHARE_READ: DWORD = 0x1;
209         const FILE_SHARE_WRITE: DWORD = 0x2;
210
211         #[repr(C)]
212         struct OVERLAPPED {
213             Internal: ULONG_PTR,
214             InternalHigh: ULONG_PTR,
215             Offset: DWORD,
216             OffsetHigh: DWORD,
217             hEvent: HANDLE,
218         }
219
220         extern "system" {
221             fn LockFileEx(hFile: HANDLE,
222                           dwFlags: DWORD,
223                           dwReserved: DWORD,
224                           nNumberOfBytesToLockLow: DWORD,
225                           nNumberOfBytesToLockHigh: DWORD,
226                           lpOverlapped: LPOVERLAPPED) -> BOOL;
227         }
228
229         #[derive(Debug)]
230         pub struct Lock {
231             _file: File,
232         }
233
234         impl Lock {
235             pub fn new(p: &Path,
236                        wait: bool,
237                        create: bool,
238                        exclusive: bool)
239                        -> io::Result<Lock> {
240                 assert!(p.parent().unwrap().exists(),
241                     "Parent directory of lock-file must exist: {}",
242                     p.display());
243
244                 let share_mode = FILE_SHARE_DELETE | FILE_SHARE_READ | FILE_SHARE_WRITE;
245
246                 let mut open_options = OpenOptions::new();
247                 open_options.read(true)
248                             .share_mode(share_mode);
249
250                 if create {
251                     open_options.create(true)
252                                 .write(true);
253                 }
254
255                 debug!("Attempting to open lock file `{}`", p.display());
256                 let file = match open_options.open(p) {
257                     Ok(file) => {
258                         debug!("Lock file opened successfully");
259                         file
260                     }
261                     Err(err) => {
262                         debug!("Error opening lock file: {}", err);
263                         return Err(err)
264                     }
265                 };
266
267                 let ret = unsafe {
268                     let mut overlapped: OVERLAPPED = mem::zeroed();
269
270                     let mut dwFlags = 0;
271                     if !wait {
272                         dwFlags |= LOCKFILE_FAIL_IMMEDIATELY;
273                     }
274
275                     if exclusive {
276                         dwFlags |= LOCKFILE_EXCLUSIVE_LOCK;
277                     }
278
279                     debug!("Attempting to acquire lock on lock file `{}`",
280                            p.display());
281                     LockFileEx(file.as_raw_handle(),
282                                dwFlags,
283                                0,
284                                0xFFFF_FFFF,
285                                0xFFFF_FFFF,
286                                &mut overlapped)
287                 };
288                 if ret == 0 {
289                     let err = io::Error::last_os_error();
290                     debug!("Failed acquiring file lock: {}", err);
291                     Err(err)
292                 } else {
293                     debug!("Successfully acquired lock.");
294                     Ok(Lock { _file: file })
295                 }
296             }
297         }
298
299         // Note that we don't need a Drop impl on the Windows: The file is unlocked
300         // automatically when it's closed.
301     } else {
302         #[derive(Debug)]
303         pub struct Lock(());
304
305         impl Lock {
306             pub fn new(_p: &Path, _wait: bool, _create: bool, _exclusive: bool)
307                 -> io::Result<Lock>
308             {
309                 let msg = "file locks not supported on this platform";
310                 Err(io::Error::new(io::ErrorKind::Other, msg))
311             }
312         }
313     }
314 }
315
316 impl Lock {
317     pub fn panicking_new(p: &Path,
318                          wait: bool,
319                          create: bool,
320                          exclusive: bool)
321                          -> Lock {
322         Lock::new(p, wait, create, exclusive).unwrap_or_else(|err| {
323             panic!("could not lock `{}`: {}", p.display(), err);
324         })
325     }
326 }