1use std::io;
5use std::io::ErrorKind;
6
7use rand::Rng;
8use rustc_abi::Size;
9use rustc_target::spec::Os;
10
11use crate::shims::files::FileDescription;
12use crate::shims::sig::check_min_vararg_count;
13use crate::shims::unix::linux_like::epoll::EpollEvents;
14use crate::shims::unix::*;
15use crate::*;
16
17#[derive(Debug, Clone, Copy, Eq, PartialEq)]
18pub(crate) enum FlockOp {
19 SharedLock { nonblocking: bool },
20 ExclusiveLock { nonblocking: bool },
21 Unlock,
22}
23
24pub trait UnixFileDescription: FileDescription {
26 fn pread<'tcx>(
30 &self,
31 _communicate_allowed: bool,
32 _offset: u64,
33 _ptr: Pointer,
34 _len: usize,
35 _ecx: &mut MiriInterpCx<'tcx>,
36 _finish: DynMachineCallback<'tcx, Result<usize, IoError>>,
37 ) -> InterpResult<'tcx> {
38 throw_unsup_format!("cannot pread from {}", self.name());
39 }
40
41 fn pwrite<'tcx>(
46 &self,
47 _communicate_allowed: bool,
48 _ptr: Pointer,
49 _len: usize,
50 _offset: u64,
51 _ecx: &mut MiriInterpCx<'tcx>,
52 _finish: DynMachineCallback<'tcx, Result<usize, IoError>>,
53 ) -> InterpResult<'tcx> {
54 throw_unsup_format!("cannot pwrite to {}", self.name());
55 }
56
57 fn flock<'tcx>(
58 &self,
59 _communicate_allowed: bool,
60 _op: FlockOp,
61 ) -> InterpResult<'tcx, io::Result<()>> {
62 throw_unsup_format!("cannot flock {}", self.name());
63 }
64
65 fn epoll_active_events<'tcx>(&self) -> InterpResult<'tcx, EpollEvents> {
67 throw_unsup_format!("{}: epoll does not support this file description", self.name());
68 }
69}
70
71impl<'tcx> EvalContextExt<'tcx> for crate::MiriInterpCx<'tcx> {}
72pub trait EvalContextExt<'tcx>: crate::MiriInterpCxExt<'tcx> {
73 fn dup(&mut self, old_fd_num: i32) -> InterpResult<'tcx, Scalar> {
74 let this = self.eval_context_mut();
75
76 let Some(fd) = this.machine.fds.get(old_fd_num) else {
77 return this.set_last_error_and_return_i32(LibcError("EBADF"));
78 };
79 interp_ok(Scalar::from_i32(this.machine.fds.insert(fd)))
80 }
81
82 fn dup2(&mut self, old_fd_num: i32, new_fd_num: i32) -> InterpResult<'tcx, Scalar> {
83 let this = self.eval_context_mut();
84
85 let Some(fd) = this.machine.fds.get(old_fd_num) else {
86 return this.set_last_error_and_return_i32(LibcError("EBADF"));
87 };
88 if new_fd_num != old_fd_num {
89 if let Some(old_new_fd) = this.machine.fds.fds.insert(new_fd_num, fd) {
92 old_new_fd.close_ref(this.machine.communicate(), this)?.ok();
94 }
95 }
96 interp_ok(Scalar::from_i32(new_fd_num))
97 }
98
99 fn flock(&mut self, fd_num: i32, op: i32) -> InterpResult<'tcx, Scalar> {
100 let this = self.eval_context_mut();
101 let Some(fd) = this.machine.fds.get(fd_num) else {
102 return this.set_last_error_and_return_i32(LibcError("EBADF"));
103 };
104
105 let lock_sh = this.eval_libc_i32("LOCK_SH");
107 let lock_ex = this.eval_libc_i32("LOCK_EX");
108 let lock_nb = this.eval_libc_i32("LOCK_NB");
109 let lock_un = this.eval_libc_i32("LOCK_UN");
110
111 use FlockOp::*;
112 let parsed_op = if op == lock_sh {
113 SharedLock { nonblocking: false }
114 } else if op == lock_sh | lock_nb {
115 SharedLock { nonblocking: true }
116 } else if op == lock_ex {
117 ExclusiveLock { nonblocking: false }
118 } else if op == lock_ex | lock_nb {
119 ExclusiveLock { nonblocking: true }
120 } else if op == lock_un {
121 Unlock
122 } else {
123 throw_unsup_format!("unsupported flags {:#x}", op);
124 };
125
126 let result = fd.as_unix(this).flock(this.machine.communicate(), parsed_op)?;
127 let result = result.map(|()| 0i32);
129 interp_ok(Scalar::from_i32(this.try_unwrap_io_result(result)?))
130 }
131
132 fn fcntl(
133 &mut self,
134 fd_num: &OpTy<'tcx>,
135 cmd: &OpTy<'tcx>,
136 varargs: &[OpTy<'tcx>],
137 ) -> InterpResult<'tcx, Scalar> {
138 let this = self.eval_context_mut();
139
140 let fd_num = this.read_scalar(fd_num)?.to_i32()?;
141 let cmd = this.read_scalar(cmd)?.to_i32()?;
142
143 let f_getfd = this.eval_libc_i32("F_GETFD");
144 let f_dupfd = this.eval_libc_i32("F_DUPFD");
145 let f_dupfd_cloexec = this.eval_libc_i32("F_DUPFD_CLOEXEC");
146 let f_getfl = this.eval_libc_i32("F_GETFL");
147 let f_setfl = this.eval_libc_i32("F_SETFL");
148
149 match cmd {
151 cmd if cmd == f_getfd => {
152 if !this.machine.fds.is_fd_num(fd_num) {
157 this.set_last_error_and_return_i32(LibcError("EBADF"))
158 } else {
159 interp_ok(this.eval_libc("FD_CLOEXEC"))
160 }
161 }
162 cmd if cmd == f_dupfd || cmd == f_dupfd_cloexec => {
163 let cmd_name = if cmd == f_dupfd {
168 "fcntl(fd, F_DUPFD, ...)"
169 } else {
170 "fcntl(fd, F_DUPFD_CLOEXEC, ...)"
171 };
172
173 let [start] = check_min_vararg_count(cmd_name, varargs)?;
174 let start = this.read_scalar(start)?.to_i32()?;
175
176 if let Some(fd) = this.machine.fds.get(fd_num) {
177 interp_ok(Scalar::from_i32(this.machine.fds.insert_with_min_num(fd, start)))
178 } else {
179 this.set_last_error_and_return_i32(LibcError("EBADF"))
180 }
181 }
182 cmd if cmd == f_getfl => {
183 let Some(fd) = this.machine.fds.get(fd_num) else {
185 return this.set_last_error_and_return_i32(LibcError("EBADF"));
186 };
187
188 fd.get_flags(this)
189 }
190 cmd if cmd == f_setfl => {
191 let Some(fd) = this.machine.fds.get(fd_num) else {
193 return this.set_last_error_and_return_i32(LibcError("EBADF"));
194 };
195
196 let [flag] = check_min_vararg_count("fcntl(fd, F_SETFL, ...)", varargs)?;
197 let flag = this.read_scalar(flag)?.to_i32()?;
198
199 fd.set_flags(flag, this)
200 }
201 cmd if this.tcx.sess.target.os == Os::MacOs
202 && cmd == this.eval_libc_i32("F_FULLFSYNC") =>
203 {
204 if let IsolatedOp::Reject(reject_with) = this.machine.isolated_op {
206 this.reject_in_isolation("`fcntl`", reject_with)?;
207 return this.set_last_error_and_return_i32(ErrorKind::PermissionDenied);
208 }
209
210 this.ffullsync_fd(fd_num)
211 }
212 cmd => {
213 throw_unsup_format!("fcntl: unsupported command {cmd:#x}");
214 }
215 }
216 }
217
218 fn close(&mut self, fd_op: &OpTy<'tcx>) -> InterpResult<'tcx, Scalar> {
219 let this = self.eval_context_mut();
220
221 let fd_num = this.read_scalar(fd_op)?.to_i32()?;
222
223 let Some(fd) = this.machine.fds.remove(fd_num) else {
224 return this.set_last_error_and_return_i32(LibcError("EBADF"));
225 };
226 let result = fd.close_ref(this.machine.communicate(), this)?;
227 let result = result.map(|()| 0i32);
229 interp_ok(Scalar::from_i32(this.try_unwrap_io_result(result)?))
230 }
231
232 fn read(
238 &mut self,
239 fd_num: i32,
240 buf: Pointer,
241 count: u64,
242 offset: Option<i128>,
243 dest: &MPlaceTy<'tcx>,
244 ) -> InterpResult<'tcx> {
245 let this = self.eval_context_mut();
246
247 trace!("Reading from FD {}, size {}", fd_num, count);
250
251 this.check_ptr_access(buf, Size::from_bytes(count), CheckInAllocMsg::MemoryAccess)?;
253
254 let count = count
257 .min(u64::try_from(this.target_isize_max()).unwrap())
258 .min(u64::try_from(isize::MAX).unwrap());
259 let count = usize::try_from(count).unwrap(); let communicate = this.machine.communicate();
261
262 let Some(fd) = this.machine.fds.get(fd_num) else {
264 trace!("read: FD not found");
265 return this.set_last_error_and_return(LibcError("EBADF"), dest);
266 };
267
268 if count == 0 {
273 this.write_null(dest)?;
274 return interp_ok(());
275 }
276 let count = if this.machine.short_fd_operations
279 && fd.short_fd_operations()
280 && count >= 2
281 && this.machine.rng.get_mut().random()
282 {
283 count / 2 } else {
285 count
286 };
287
288 trace!("read: FD mapped to {fd:?}");
289 let finish = {
294 let dest = dest.clone();
295 callback!(
296 @capture<'tcx> {
297 count: usize,
298 dest: MPlaceTy<'tcx>,
299 }
300 |this, result: Result<usize, IoError>| {
301 match result {
302 Ok(read_size) => {
303 assert!(read_size <= count);
304 this.write_int(u64::try_from(read_size).unwrap(), &dest)
306 }
307 Err(e) => {
308 this.set_last_error_and_return(e, &dest)
309 }
310 }}
311 )
312 };
313 match offset {
314 None => fd.read(communicate, buf, count, this, finish)?,
315 Some(offset) => {
316 let Ok(offset) = u64::try_from(offset) else {
317 return this.set_last_error_and_return(LibcError("EINVAL"), dest);
318 };
319 fd.as_unix(this).pread(communicate, offset, buf, count, this, finish)?
320 }
321 };
322 interp_ok(())
323 }
324
325 fn write(
326 &mut self,
327 fd_num: i32,
328 buf: Pointer,
329 count: u64,
330 offset: Option<i128>,
331 dest: &MPlaceTy<'tcx>,
332 ) -> InterpResult<'tcx> {
333 let this = self.eval_context_mut();
334
335 this.check_ptr_access(buf, Size::from_bytes(count), CheckInAllocMsg::MemoryAccess)?;
339
340 let count = count
343 .min(u64::try_from(this.target_isize_max()).unwrap())
344 .min(u64::try_from(isize::MAX).unwrap());
345 let count = usize::try_from(count).unwrap(); let communicate = this.machine.communicate();
347
348 let Some(fd) = this.machine.fds.get(fd_num) else {
350 return this.set_last_error_and_return(LibcError("EBADF"), dest);
351 };
352
353 if count == 0 {
360 this.write_null(dest)?;
362 return interp_ok(());
363 }
364 let count = if this.machine.short_fd_operations
368 && fd.short_fd_operations()
369 && count >= 2
370 && this.machine.rng.get_mut().random()
371 {
372 count / 2
373 } else {
374 count
375 };
376
377 let finish = {
378 let dest = dest.clone();
379 callback!(
380 @capture<'tcx> {
381 count: usize,
382 dest: MPlaceTy<'tcx>,
383 }
384 |this, result: Result<usize, IoError>| {
385 match result {
386 Ok(write_size) => {
387 assert!(write_size <= count);
388 this.write_int(u64::try_from(write_size).unwrap(), &dest)
390 }
391 Err(e) => {
392 this.set_last_error_and_return(e, &dest)
393 }
394 }}
395 )
396 };
397 match offset {
398 None => fd.write(communicate, buf, count, this, finish)?,
399 Some(offset) => {
400 let Ok(offset) = u64::try_from(offset) else {
401 return this.set_last_error_and_return(LibcError("EINVAL"), dest);
402 };
403 fd.as_unix(this).pwrite(communicate, buf, count, offset, this, finish)?
404 }
405 };
406 interp_ok(())
407 }
408}