Skip to content

Commit 5979937

Browse files
committed
Add flock shim
1 parent a9190c9 commit 5979937

File tree

6 files changed

+220
-3
lines changed

6 files changed

+220
-3
lines changed

Cargo.lock

Lines changed: 1 addition & 0 deletions
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

Cargo.toml

Lines changed: 9 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -9,12 +9,12 @@ default-run = "miri"
99
edition = "2021"
1010

1111
[lib]
12-
test = true # we have unit tests
12+
test = true # we have unit tests
1313
doctest = false # but no doc tests
1414

1515
[[bin]]
1616
name = "miri"
17-
test = false # we have no unit tests
17+
test = false # we have no unit tests
1818
doctest = false # and no doc tests
1919

2020
[dependencies]
@@ -42,6 +42,13 @@ libc = "0.2"
4242
libffi = "3.2.0"
4343
libloading = "0.8"
4444

45+
[target.'cfg(target_family = "windows")'.dependencies]
46+
windows-sys = { version = "0.52", features = [
47+
"Win32_Foundation",
48+
"Win32_System_IO",
49+
"Win32_Storage_FileSystem",
50+
] }
51+
4552
[dev-dependencies]
4653
colored = "2"
4754
ui_test = "0.21.1"

src/shims/unix/fd.rs

Lines changed: 48 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -53,6 +53,14 @@ pub trait FileDescription: std::fmt::Debug + Any {
5353
throw_unsup_format!("cannot close {}", self.name());
5454
}
5555

56+
fn flock<'tcx>(
57+
&self,
58+
_communicate_allowed: bool,
59+
_op: FlockOp,
60+
) -> InterpResult<'tcx, io::Result<()>> {
61+
throw_unsup_format!("cannot flock {}", self.name());
62+
}
63+
5664
fn is_tty(&self, _communicate_allowed: bool) -> bool {
5765
// Most FDs are not tty's and the consequence of a wrong `false` are minor,
5866
// so we use a default impl here.
@@ -299,6 +307,40 @@ pub trait EvalContextExt<'tcx>: crate::MiriInterpCxExt<'tcx> {
299307
Ok(new_fd)
300308
}
301309

310+
fn flock(&mut self, fd: i32, op: i32) -> InterpResult<'tcx, Scalar> {
311+
let this = self.eval_context_mut();
312+
let Some(file_descriptor) = this.machine.fds.get(fd) else {
313+
return Ok(Scalar::from_i32(this.fd_not_found()?));
314+
};
315+
316+
// We need to check that there aren't unsupported options in `op`.
317+
let lock_sh = this.eval_libc_i32("LOCK_SH");
318+
let lock_ex = this.eval_libc_i32("LOCK_EX");
319+
let lock_nb = this.eval_libc_i32("LOCK_NB");
320+
let lock_un = this.eval_libc_i32("LOCK_UN");
321+
322+
use FlockOp::*;
323+
let parsed_op = if op == lock_sh {
324+
SharedLock { nonblocking: false }
325+
} else if op == lock_sh | lock_nb {
326+
SharedLock { nonblocking: true }
327+
} else if op == lock_ex {
328+
ExclusiveLock { nonblocking: false }
329+
} else if op == lock_ex | lock_nb {
330+
ExclusiveLock { nonblocking: true }
331+
} else if op == lock_un {
332+
Unlock
333+
} else {
334+
throw_unsup_format!("unsupported flags {:#x}", op);
335+
};
336+
337+
let result = file_descriptor.flock(this.machine.communicate(), parsed_op)?;
338+
drop(file_descriptor);
339+
// return `0` if flock is successful
340+
let result = result.map(|()| 0i32);
341+
Ok(Scalar::from_i32(this.try_unwrap_io_result(result)?))
342+
}
343+
302344
fn fcntl(&mut self, args: &[OpTy<'tcx>]) -> InterpResult<'tcx, i32> {
303345
let this = self.eval_context_mut();
304346

@@ -464,3 +506,9 @@ pub trait EvalContextExt<'tcx>: crate::MiriInterpCxExt<'tcx> {
464506
this.try_unwrap_io_result(result)
465507
}
466508
}
509+
510+
pub(crate) enum FlockOp {
511+
SharedLock { nonblocking: bool },
512+
ExclusiveLock { nonblocking: bool },
513+
Unlock,
514+
}

src/shims/unix/foreign_items.rs

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -130,6 +130,13 @@ pub trait EvalContextExt<'tcx>: crate::MiriInterpCxExt<'tcx> {
130130
let result = this.dup2(old_fd, new_fd)?;
131131
this.write_scalar(Scalar::from_i32(result), dest)?;
132132
}
133+
"flock" => {
134+
let [fd, op] = this.check_shim(abi, Abi::C { unwind: false }, link_name, args)?;
135+
let fd = this.read_scalar(fd)?.to_i32()?;
136+
let op = this.read_scalar(op)?.to_i32()?;
137+
let result = this.flock(fd, op)?;
138+
this.write_scalar(result, dest)?;
139+
}
133140

134141
// File and file system access
135142
"open" | "open64" => {

src/shims/unix/fs.rs

Lines changed: 84 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -16,7 +16,7 @@ use crate::shims::unix::*;
1616
use crate::*;
1717
use shims::time::system_time_to_duration;
1818

19-
use self::fd::FileDescriptor;
19+
use self::fd::{FileDescriptor, FlockOp};
2020

2121
#[derive(Debug)]
2222
struct FileHandle {
@@ -81,6 +81,89 @@ impl FileDescription for FileHandle {
8181
}
8282
}
8383

84+
fn flock<'tcx>(
85+
&self,
86+
communicate_allowed: bool,
87+
op: FlockOp,
88+
) -> InterpResult<'tcx, io::Result<()>> {
89+
assert!(communicate_allowed, "isolation should have prevented even opening a file");
90+
#[cfg(target_family = "unix")]
91+
{
92+
use std::os::fd::AsRawFd;
93+
94+
// Transform `op` into host's flags
95+
use FlockOp::*;
96+
let host_op = match op {
97+
SharedLock { nonblocking: false } => libc::LOCK_SH,
98+
SharedLock { nonblocking: true } => libc::LOCK_SH | libc::LOCK_NB,
99+
ExclusiveLock { nonblocking: false } => libc::LOCK_EX,
100+
ExclusiveLock { nonblocking: true } => libc::LOCK_EX | libc::LOCK_NB,
101+
Unlock => libc::LOCK_UN,
102+
};
103+
104+
let fd = self.file.as_raw_fd();
105+
let ret = unsafe { libc::flock(fd, host_op) };
106+
let res = match ret {
107+
0 => Ok(()),
108+
-1 => Err(io::Error::last_os_error()),
109+
ret => panic!("Unexpected return value from flock: {ret}"),
110+
};
111+
Ok(res)
112+
}
113+
114+
#[cfg(target_family = "windows")]
115+
{
116+
use std::os::windows::io::AsRawHandle;
117+
use windows_sys::Win32::{
118+
Foundation::{ERROR_IO_PENDING, ERROR_LOCK_VIOLATION, FALSE, HANDLE, TRUE},
119+
Storage::FileSystem::{
120+
LockFileEx, UnlockFile, LOCKFILE_EXCLUSIVE_LOCK, LOCKFILE_FAIL_IMMEDIATELY,
121+
},
122+
};
123+
let handle = self.file.as_raw_handle() as HANDLE;
124+
125+
use FlockOp::*;
126+
let mut lock_nb = false;
127+
let ret = match op {
128+
SharedLock { nonblocking } | ExclusiveLock { nonblocking } => {
129+
lock_nb = nonblocking;
130+
let mut flags = 0;
131+
if nonblocking {
132+
flags |= LOCKFILE_FAIL_IMMEDIATELY;
133+
}
134+
if let ExclusiveLock { .. } = op {
135+
flags |= LOCKFILE_EXCLUSIVE_LOCK;
136+
}
137+
unsafe { LockFileEx(handle, flags, 0, !0, !0, &mut std::mem::zeroed()) }
138+
}
139+
Unlock => unsafe { UnlockFile(handle, 0, 0, !0, !0) },
140+
};
141+
142+
let res = match ret {
143+
TRUE => Ok(()),
144+
FALSE => {
145+
let mut err = io::Error::last_os_error();
146+
let code: u32 = err.raw_os_error().unwrap().try_into().unwrap();
147+
// Replace error with a custom WouldBlock error, which later will be mapped
148+
// in the `helpers` module
149+
if lock_nb && matches!(code, ERROR_IO_PENDING | ERROR_LOCK_VIOLATION) {
150+
let desc = format!("LockFileEx wouldblock error: {err}");
151+
err = io::Error::new(io::ErrorKind::WouldBlock, desc);
152+
}
153+
Err(err)
154+
}
155+
_ => panic!("Unexpected return value: {ret}"),
156+
};
157+
Ok(res)
158+
}
159+
160+
#[cfg(not(any(target_family = "unix", target_family = "windows")))]
161+
{
162+
let _ = op;
163+
throw_unsup_format!("flock is supported only on UNIX and Windows hosts");
164+
}
165+
}
166+
84167
fn is_tty(&self, communicate_allowed: bool) -> bool {
85168
communicate_allowed && self.file.is_terminal()
86169
}

tests/pass-dep/libc/libc-fs-flock.rs

Lines changed: 71 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,71 @@
1+
// Flock tests are separate since they don't in general work on a Windows host.
2+
//@ignore-target-windows: File handling is not implemented yet
3+
//@compile-flags: -Zmiri-disable-isolation
4+
5+
use std::{fs::File, io::Error, os::fd::AsRawFd};
6+
7+
#[path = "../../utils/mod.rs"]
8+
mod utils;
9+
10+
fn main() {
11+
let bytes = b"Hello, World!\n";
12+
let path = utils::prepare_with_content("miri_test_fs_shared_lock.txt", bytes);
13+
14+
let files: Vec<File> = (0..3).map(|_| File::open(&path).unwrap()).collect();
15+
16+
// Test that we can apply many shared locks
17+
for file in files.iter() {
18+
let fd = file.as_raw_fd();
19+
let ret = unsafe { libc::flock(fd, libc::LOCK_SH) };
20+
if ret != 0 {
21+
panic!("flock error: {}", Error::last_os_error());
22+
}
23+
}
24+
25+
// Test that shared lock prevents exclusive lock
26+
{
27+
let fd = files[0].as_raw_fd();
28+
let ret = unsafe { libc::flock(fd, libc::LOCK_EX | libc::LOCK_NB) };
29+
assert_eq!(ret, -1);
30+
let err = Error::last_os_error().raw_os_error().unwrap();
31+
assert_eq!(err, libc::EWOULDBLOCK);
32+
}
33+
34+
// Unlock shared lock
35+
for file in files.iter() {
36+
let fd = file.as_raw_fd();
37+
let ret = unsafe { libc::flock(fd, libc::LOCK_UN) };
38+
if ret != 0 {
39+
panic!("flock error: {}", Error::last_os_error());
40+
}
41+
}
42+
43+
// Take exclusive lock
44+
{
45+
let fd = files[0].as_raw_fd();
46+
let ret = unsafe { libc::flock(fd, libc::LOCK_EX) };
47+
assert_eq!(ret, 0);
48+
}
49+
50+
// Test that shared lock prevents exclusive and shared locks
51+
{
52+
let fd = files[1].as_raw_fd();
53+
let ret = unsafe { libc::flock(fd, libc::LOCK_EX | libc::LOCK_NB) };
54+
assert_eq!(ret, -1);
55+
let err = Error::last_os_error().raw_os_error().unwrap();
56+
assert_eq!(err, libc::EWOULDBLOCK);
57+
58+
let fd = files[2].as_raw_fd();
59+
let ret = unsafe { libc::flock(fd, libc::LOCK_SH | libc::LOCK_NB) };
60+
assert_eq!(ret, -1);
61+
let err = Error::last_os_error().raw_os_error().unwrap();
62+
assert_eq!(err, libc::EWOULDBLOCK);
63+
}
64+
65+
// Unlock exclusive lock
66+
{
67+
let fd = files[0].as_raw_fd();
68+
let ret = unsafe { libc::flock(fd, libc::LOCK_UN) };
69+
assert_eq!(ret, 0);
70+
}
71+
}

0 commit comments

Comments
 (0)