1use std::io;
5use std::io::ErrorKind;
6
7use rustc_abi::Size;
8
9use crate::helpers::check_min_vararg_count;
10use crate::shims::files::FileDescription;
11use crate::shims::unix::linux_like::epoll::EpollReadyEvents;
12use crate::shims::unix::*;
13use crate::*;
14
15#[derive(Debug, Clone, Copy, Eq, PartialEq)]
16pub(crate) enum FlockOp {
17 SharedLock { nonblocking: bool },
18 ExclusiveLock { nonblocking: bool },
19 Unlock,
20}
21
22pub trait UnixFileDescription: FileDescription {
24 fn pread<'tcx>(
28 &self,
29 _communicate_allowed: bool,
30 _offset: u64,
31 _ptr: Pointer,
32 _len: usize,
33 _ecx: &mut MiriInterpCx<'tcx>,
34 _finish: DynMachineCallback<'tcx, Result<usize, IoError>>,
35 ) -> InterpResult<'tcx> {
36 throw_unsup_format!("cannot pread from {}", self.name());
37 }
38
39 fn pwrite<'tcx>(
44 &self,
45 _communicate_allowed: bool,
46 _ptr: Pointer,
47 _len: usize,
48 _offset: u64,
49 _ecx: &mut MiriInterpCx<'tcx>,
50 _finish: DynMachineCallback<'tcx, Result<usize, IoError>>,
51 ) -> InterpResult<'tcx> {
52 throw_unsup_format!("cannot pwrite to {}", self.name());
53 }
54
55 fn flock<'tcx>(
56 &self,
57 _communicate_allowed: bool,
58 _op: FlockOp,
59 ) -> InterpResult<'tcx, io::Result<()>> {
60 throw_unsup_format!("cannot flock {}", self.name());
61 }
62
63 fn get_epoll_ready_events<'tcx>(&self) -> InterpResult<'tcx, EpollReadyEvents> {
65 throw_unsup_format!("{}: epoll does not support this file description", self.name());
66 }
67}
68
69impl<'tcx> EvalContextExt<'tcx> for crate::MiriInterpCx<'tcx> {}
70pub trait EvalContextExt<'tcx>: crate::MiriInterpCxExt<'tcx> {
71 fn dup(&mut self, old_fd_num: i32) -> InterpResult<'tcx, Scalar> {
72 let this = self.eval_context_mut();
73
74 let Some(fd) = this.machine.fds.get(old_fd_num) else {
75 return this.set_last_error_and_return_i32(LibcError("EBADF"));
76 };
77 interp_ok(Scalar::from_i32(this.machine.fds.insert(fd)))
78 }
79
80 fn dup2(&mut self, old_fd_num: i32, new_fd_num: i32) -> InterpResult<'tcx, Scalar> {
81 let this = self.eval_context_mut();
82
83 let Some(fd) = this.machine.fds.get(old_fd_num) else {
84 return this.set_last_error_and_return_i32(LibcError("EBADF"));
85 };
86 if new_fd_num != old_fd_num {
87 if let Some(old_new_fd) = this.machine.fds.fds.insert(new_fd_num, fd) {
90 old_new_fd.close_ref(this.machine.communicate(), this)?.ok();
92 }
93 }
94 interp_ok(Scalar::from_i32(new_fd_num))
95 }
96
97 fn flock(&mut self, fd_num: i32, op: i32) -> InterpResult<'tcx, Scalar> {
98 let this = self.eval_context_mut();
99 let Some(fd) = this.machine.fds.get(fd_num) else {
100 return this.set_last_error_and_return_i32(LibcError("EBADF"));
101 };
102
103 let lock_sh = this.eval_libc_i32("LOCK_SH");
105 let lock_ex = this.eval_libc_i32("LOCK_EX");
106 let lock_nb = this.eval_libc_i32("LOCK_NB");
107 let lock_un = this.eval_libc_i32("LOCK_UN");
108
109 use FlockOp::*;
110 let parsed_op = if op == lock_sh {
111 SharedLock { nonblocking: false }
112 } else if op == lock_sh | lock_nb {
113 SharedLock { nonblocking: true }
114 } else if op == lock_ex {
115 ExclusiveLock { nonblocking: false }
116 } else if op == lock_ex | lock_nb {
117 ExclusiveLock { nonblocking: true }
118 } else if op == lock_un {
119 Unlock
120 } else {
121 throw_unsup_format!("unsupported flags {:#x}", op);
122 };
123
124 let result = fd.as_unix().flock(this.machine.communicate(), parsed_op)?;
125 let result = result.map(|()| 0i32);
127 interp_ok(Scalar::from_i32(this.try_unwrap_io_result(result)?))
128 }
129
130 fn fcntl(
131 &mut self,
132 fd_num: &OpTy<'tcx>,
133 cmd: &OpTy<'tcx>,
134 varargs: &[OpTy<'tcx>],
135 ) -> InterpResult<'tcx, Scalar> {
136 let this = self.eval_context_mut();
137
138 let fd_num = this.read_scalar(fd_num)?.to_i32()?;
139 let cmd = this.read_scalar(cmd)?.to_i32()?;
140
141 let f_getfd = this.eval_libc_i32("F_GETFD");
142 let f_dupfd = this.eval_libc_i32("F_DUPFD");
143 let f_dupfd_cloexec = this.eval_libc_i32("F_DUPFD_CLOEXEC");
144
145 match cmd {
147 cmd if cmd == f_getfd => {
148 if !this.machine.fds.is_fd_num(fd_num) {
153 this.set_last_error_and_return_i32(LibcError("EBADF"))
154 } else {
155 interp_ok(this.eval_libc("FD_CLOEXEC"))
156 }
157 }
158 cmd if cmd == f_dupfd || cmd == f_dupfd_cloexec => {
159 let cmd_name = if cmd == f_dupfd {
164 "fcntl(fd, F_DUPFD, ...)"
165 } else {
166 "fcntl(fd, F_DUPFD_CLOEXEC, ...)"
167 };
168
169 let [start] = check_min_vararg_count(cmd_name, varargs)?;
170 let start = this.read_scalar(start)?.to_i32()?;
171
172 if let Some(fd) = this.machine.fds.get(fd_num) {
173 interp_ok(Scalar::from_i32(this.machine.fds.insert_with_min_num(fd, start)))
174 } else {
175 this.set_last_error_and_return_i32(LibcError("EBADF"))
176 }
177 }
178 cmd if this.tcx.sess.target.os == "macos"
179 && cmd == this.eval_libc_i32("F_FULLFSYNC") =>
180 {
181 if let IsolatedOp::Reject(reject_with) = this.machine.isolated_op {
183 this.reject_in_isolation("`fcntl`", reject_with)?;
184 return this.set_last_error_and_return_i32(ErrorKind::PermissionDenied);
185 }
186
187 this.ffullsync_fd(fd_num)
188 }
189 cmd => {
190 throw_unsup_format!("fcntl: unsupported command {cmd:#x}");
191 }
192 }
193 }
194
195 fn close(&mut self, fd_op: &OpTy<'tcx>) -> InterpResult<'tcx, Scalar> {
196 let this = self.eval_context_mut();
197
198 let fd_num = this.read_scalar(fd_op)?.to_i32()?;
199
200 let Some(fd) = this.machine.fds.remove(fd_num) else {
201 return this.set_last_error_and_return_i32(LibcError("EBADF"));
202 };
203 let result = fd.close_ref(this.machine.communicate(), this)?;
204 let result = result.map(|()| 0i32);
206 interp_ok(Scalar::from_i32(this.try_unwrap_io_result(result)?))
207 }
208
209 fn read(
215 &mut self,
216 fd_num: i32,
217 buf: Pointer,
218 count: u64,
219 offset: Option<i128>,
220 dest: &MPlaceTy<'tcx>,
221 ) -> InterpResult<'tcx> {
222 let this = self.eval_context_mut();
223
224 trace!("Reading from FD {}, size {}", fd_num, count);
227
228 this.check_ptr_access(buf, Size::from_bytes(count), CheckInAllocMsg::MemoryAccessTest)?;
230
231 let count = count
234 .min(u64::try_from(this.target_isize_max()).unwrap())
235 .min(u64::try_from(isize::MAX).unwrap());
236 let count = usize::try_from(count).unwrap(); let communicate = this.machine.communicate();
238
239 let Some(fd) = this.machine.fds.get(fd_num) else {
241 trace!("read: FD not found");
242 return this.set_last_error_and_return(LibcError("EBADF"), dest);
243 };
244
245 trace!("read: FD mapped to {fd:?}");
246 let finish = {
251 let dest = dest.clone();
252 callback!(
253 @capture<'tcx> {
254 count: usize,
255 dest: MPlaceTy<'tcx>,
256 }
257 |this, result: Result<usize, IoError>| {
258 match result {
259 Ok(read_size) => {
260 assert!(read_size <= count);
261 this.write_int(u64::try_from(read_size).unwrap(), &dest)
263 }
264 Err(e) => {
265 this.set_last_error_and_return(e, &dest)
266 }
267 }}
268 )
269 };
270 match offset {
271 None => fd.read(communicate, buf, count, this, finish)?,
272 Some(offset) => {
273 let Ok(offset) = u64::try_from(offset) else {
274 return this.set_last_error_and_return(LibcError("EINVAL"), dest);
275 };
276 fd.as_unix().pread(communicate, offset, buf, count, this, finish)?
277 }
278 };
279 interp_ok(())
280 }
281
282 fn write(
283 &mut self,
284 fd_num: i32,
285 buf: Pointer,
286 count: u64,
287 offset: Option<i128>,
288 dest: &MPlaceTy<'tcx>,
289 ) -> InterpResult<'tcx> {
290 let this = self.eval_context_mut();
291
292 this.check_ptr_access(buf, Size::from_bytes(count), CheckInAllocMsg::MemoryAccessTest)?;
296
297 let count = count
300 .min(u64::try_from(this.target_isize_max()).unwrap())
301 .min(u64::try_from(isize::MAX).unwrap());
302 let count = usize::try_from(count).unwrap(); let communicate = this.machine.communicate();
304
305 let Some(fd) = this.machine.fds.get(fd_num) else {
307 return this.set_last_error_and_return(LibcError("EBADF"), dest);
308 };
309
310 let finish = {
311 let dest = dest.clone();
312 callback!(
313 @capture<'tcx> {
314 count: usize,
315 dest: MPlaceTy<'tcx>,
316 }
317 |this, result: Result<usize, IoError>| {
318 match result {
319 Ok(write_size) => {
320 assert!(write_size <= count);
321 this.write_int(u64::try_from(write_size).unwrap(), &dest)
323 }
324 Err(e) => {
325 this.set_last_error_and_return(e, &dest)
326 }
327 }}
328 )
329 };
330 match offset {
331 None => fd.write(communicate, buf, count, this, finish)?,
332 Some(offset) => {
333 let Ok(offset) = u64::try_from(offset) else {
334 return this.set_last_error_and_return(LibcError("EINVAL"), dest);
335 };
336 fd.as_unix().pwrite(communicate, buf, count, offset, this, finish)?
337 }
338 };
339 interp_ok(())
340 }
341}