Skip to main content

miri/shims/unix/linux/
foreign_items.rs

1use rustc_middle::ty::Ty;
2use rustc_span::Symbol;
3use rustc_target::callconv::FnAbi;
4use rustc_target::spec::{Arch, Target};
5
6use self::shims::unix::linux::mem::EvalContextExt as _;
7use self::shims::unix::linux_like::eventfd::EvalContextExt as _;
8use self::shims::unix::linux_like::syscall::syscall;
9use crate::machine::{SIGRTMAX, SIGRTMIN};
10use crate::shims::unix::foreign_items::EvalContextExt as _;
11use crate::shims::unix::linux_like::epoll::EvalContextExt as _;
12use crate::shims::unix::linux_like::thread::prctl;
13use crate::shims::unix::*;
14use crate::*;
15
16// The documentation of glibc complains that the kernel never exposes
17// TASK_COMM_LEN through the headers, so it's assumed to always be 16 bytes
18// long including a null terminator.
19const TASK_COMM_LEN: u64 = 16;
20
21pub fn is_dyn_sym(name: &str, target: &Target) -> bool {
22    match name {
23        "copy_file_range" | "gettid" | "statx" => true,
24        "__cxa_thread_atexit_impl" | "__pthread_get_minstack" =>
25            target.env == rustc_target::spec::Env::Gnu,
26        // glibc only exposes this symbol on targets with a 32-bit time_t.
27        "__futimens64" =>
28            target.env == rustc_target::spec::Env::Gnu
29                && matches!(target.arch, Arch::X86 | Arch::Arm | Arch::Mips),
30        _ => false,
31    }
32}
33
34impl<'tcx> EvalContextExt<'tcx> for crate::MiriInterpCx<'tcx> {}
35pub trait EvalContextExt<'tcx>: crate::MiriInterpCxExt<'tcx> {
36    fn emulate_foreign_item_inner(
37        &mut self,
38        link_name: Symbol,
39        abi: &FnAbi<'tcx, Ty<'tcx>>,
40        args: &[OpTy<'tcx>],
41        dest: &MPlaceTy<'tcx>,
42    ) -> InterpResult<'tcx, EmulateItemResult> {
43        let ecx = self.eval_context_mut();
44
45        // See `fn emulate_foreign_item_inner` in `shims/foreign_items.rs` for the general pattern.
46
47        match link_name.as_str() {
48            // File related shims
49            "open64" => {
50                // "open64" means that the file is opened with O_LARGEFILE, which we always do.
51                let ([path_raw, flag], varargs) = ecx.check_shim_sig_variadic(
52                    shim_sig!(extern "C" fn(*_, i32, ...) -> i32),
53                    (link_name, abi, args),
54                )?;
55                let result = ecx.open(None, &path_raw, &flag, varargs)?;
56                ecx.write_scalar(result, dest)?;
57            }
58            "openat64" => {
59                // "openat64" means that the file is opened with O_LARGEFILE, which we always do.
60                let ([dirfd, path_raw, flag], varargs) = ecx.check_shim_sig_variadic(
61                    shim_sig!(extern "C" fn(i32, *_, i32, ...) -> i32),
62                    (link_name, abi, args),
63                )?;
64                let result = ecx.open(Some(&dirfd), &path_raw, &flag, varargs)?;
65                ecx.write_scalar(result, dest)?;
66            }
67            "pread64" => {
68                let [fd, buf, count, offset] = &ecx.check_shim_sig(
69                    shim_sig!(extern "C" fn(i32, *_, usize, libc::off64_t) -> isize),
70                    (link_name, abi, args),
71                )?;
72                let fd = ecx.read_scalar(fd)?.to_i32()?;
73                let buf = ecx.read_pointer(buf)?;
74                let count = ecx.read_target_usize(count)?;
75                let offset = ecx.read_scalar(offset)?.to_i64()?;
76                ecx.read(fd, buf, count, Some(offset), dest)?;
77            }
78            "pwrite64" => {
79                let [fd, buf, n, offset] = &ecx.check_shim_sig(
80                    shim_sig!(extern "C" fn(i32, *_, usize, libc::off64_t) -> isize),
81                    (link_name, abi, args),
82                )?;
83                let fd = ecx.read_scalar(fd)?.to_i32()?;
84                let buf = ecx.read_pointer(buf)?;
85                let count = ecx.read_target_usize(n)?;
86                let offset = ecx.read_scalar(offset)?.to_i64()?;
87                trace!("Called pwrite64({:?}, {:?}, {:?}, {:?})", fd, buf, count, offset);
88                ecx.write(fd, buf, count, Some(offset), dest)?;
89            }
90            "lseek64" => {
91                let [fd, offset, whence] = &ecx.check_shim_sig(
92                    shim_sig!(extern "C" fn(i32, libc::off64_t, i32) -> libc::off64_t),
93                    (link_name, abi, args),
94                )?;
95                let fd = ecx.read_scalar(fd)?.to_i32()?;
96                let offset = ecx.read_scalar(offset)?.to_i64()?;
97                let whence = ecx.read_scalar(whence)?.to_i32()?;
98                ecx.lseek(fd, offset, whence, dest)?;
99            }
100            "posix_fallocate64" => {
101                let [fd, offset, len] = &ecx.check_shim_sig(
102                    shim_sig!(extern "C" fn(i32, libc::off64_t, libc::off64_t) -> i32),
103                    (link_name, abi, args),
104                )?;
105
106                let fd = ecx.read_scalar(fd)?.to_i32()?;
107                let offset = ecx.read_scalar(offset)?.to_i64()?;
108                let len = ecx.read_scalar(len)?.to_i64()?;
109
110                let result = ecx.posix_fallocate(fd, offset, len)?;
111                ecx.write_scalar(result, dest)?;
112            }
113            "fallocate" => {
114                let [fd, mode, offset, len] = &ecx.check_shim_sig(
115                    shim_sig!(extern "C" fn(i32, i32, libc::off_t, libc::off_t) -> i32),
116                    (link_name, abi, args),
117                )?;
118
119                let fd = ecx.read_scalar(fd)?.to_i32()?;
120                let mode = ecx.read_scalar(mode)?.to_i32()?;
121                // We don't support platforms which have libc::off_t bigger than 64 bits.
122                let offset = ecx.read_int::<i64>(offset)?;
123                let len = ecx.read_int::<i64>(len)?;
124
125                let result = ecx.linux_fallocate(fd, mode, offset, len)?;
126                ecx.write_scalar(result, dest)?;
127            }
128            "fallocate64" => {
129                let [fd, mode, offset, len] = &ecx.check_shim_sig(
130                    shim_sig!(extern "C" fn(i32, i32, libc::off64_t, libc::off64_t) -> i32),
131                    (link_name, abi, args),
132                )?;
133
134                let fd = ecx.read_scalar(fd)?.to_i32()?;
135                let mode = ecx.read_scalar(mode)?.to_i32()?;
136                let offset = ecx.read_scalar(offset)?.to_i64()?;
137                let len = ecx.read_scalar(len)?.to_i64()?;
138
139                let result = ecx.linux_fallocate(fd, mode, offset, len)?;
140                ecx.write_scalar(result, dest)?;
141            }
142            "ftruncate64" => {
143                let [fd, length] = &ecx.check_shim_sig(
144                    shim_sig!(extern "C" fn(i32, libc::off64_t) -> i32),
145                    (link_name, abi, args),
146                )?;
147                let fd = ecx.read_scalar(fd)?.to_i32()?;
148                let length = ecx.read_scalar(length)?.to_i64()?;
149                let result = ecx.ftruncate64(fd, length)?;
150                ecx.write_scalar(result, dest)?;
151            }
152            "sync_file_range" => {
153                let [fd, offset, nbytes, flags] = &ecx.check_shim_sig(
154                    shim_sig!(extern "C" fn(i32, libc::off64_t, libc::off64_t, u32) -> i32),
155                    (link_name, abi, args),
156                )?;
157                let result = ecx.linux_sync_file_range(fd, offset, nbytes, flags)?;
158                ecx.write_scalar(result, dest)?;
159            }
160            "copy_file_range" => {
161                let [fd_in, off_in, fd_out, off_out, len, flags] = &ecx.check_shim_sig(
162                    shim_sig!(extern "C" fn(i32, *libc::off_t, i32, *libc::off_t, libc::size_t, u32) -> libc::ssize_t),
163                    (link_name, abi, args),
164                )?;
165                ecx.linux_copy_file_range(fd_in, off_in, fd_out, off_out, len, flags, dest)?;
166            }
167            "statx" => {
168                let [dirfd, pathname, flags, mask, statxbuf] = &ecx.check_shim_sig(
169                    shim_sig!(extern "C" fn(i32, *_, i32, u32, *libc::statx) -> i32),
170                    (link_name, abi, args),
171                )?;
172                ecx.linux_statx(dirfd, pathname, flags, mask, statxbuf, dest)?;
173            }
174            "fstat64" => {
175                let [fd, buf] = &ecx.check_shim_sig(
176                    shim_sig!(extern "C" fn(i32, *libc::stat64) -> i32),
177                    (link_name, abi, args),
178                )?;
179                let result = ecx.fstat(fd, buf)?;
180                ecx.write_scalar(result, dest)?;
181            }
182            "readdir64" => {
183                let [dirp] = &ecx
184                    .check_shim_sig(shim_sig!(extern "C" fn(*_) -> *_), (link_name, abi, args))?;
185                ecx.readdir(dirp, dest, "dirent64")?;
186            }
187            "__futimens64" if ecx.is_dyn_sym("__futimens64") => {
188                // libc has no separate time64 type; its timespec uses 32-bit time_t here.
189                // (See https://github.com/rust-lang/libc/issues/3223.)
190                let [fd, times] = &ecx.check_shim_sig(
191                    shim_sig!(extern "C" fn(i32, *std::sys::pal::time::__timespec64) -> i32),
192                    (link_name, abi, args),
193                )?;
194                let result = ecx.futimens(fd, times)?;
195                ecx.write_scalar(result, dest)?;
196            }
197
198            // epoll, eventfd
199            "epoll_create1" => {
200                let [flag] = &ecx
201                    .check_shim_sig(shim_sig!(extern "C" fn(i32) -> i32), (link_name, abi, args))?;
202                let result = ecx.epoll_create1(flag)?;
203                ecx.write_scalar(result, dest)?;
204            }
205            "epoll_ctl" => {
206                let [epfd, op, fd, event] = &ecx.check_shim_sig(
207                    shim_sig!(extern "C" fn(i32, i32, i32, *libc::epoll_event) -> i32),
208                    (link_name, abi, args),
209                )?;
210                let result = ecx.epoll_ctl(epfd, op, fd, event)?;
211                ecx.write_scalar(result, dest)?;
212            }
213            "epoll_wait" => {
214                let [epfd, events, maxevents, timeout] = &ecx.check_shim_sig(
215                    shim_sig!(extern "C" fn(i32, *libc::epoll_event, i32, i32) -> i32),
216                    (link_name, abi, args),
217                )?;
218                ecx.epoll_wait(epfd, events, maxevents, timeout, dest)?;
219            }
220            "eventfd" => {
221                let [val, flag] = &ecx.check_shim_sig(
222                    shim_sig!(extern "C" fn(u32, i32) -> i32),
223                    (link_name, abi, args),
224                )?;
225                let result = ecx.eventfd(val, flag)?;
226                ecx.write_scalar(result, dest)?;
227            }
228
229            // Threading
230            "pthread_setname_np" => {
231                let [thread, name] = &ecx.check_shim_sig(
232                    shim_sig!(extern "C" fn(libc::pthread_t, *_) -> i32),
233                    (link_name, abi, args),
234                )?;
235                let res = match ecx.pthread_setname_np(
236                    Some(thread),
237                    ecx.read_pointer(name)?,
238                    TASK_COMM_LEN,
239                    /* truncate */ false,
240                )? {
241                    ThreadNameResult::Ok => Scalar::from_u32(0),
242                    ThreadNameResult::NameTooLong => ecx.eval_libc("ERANGE"),
243                };
244                ecx.write_scalar(res, dest)?;
245            }
246            "pthread_getname_np" => {
247                let [thread, name, len] = &ecx.check_shim_sig(
248                    shim_sig!(extern "C" fn(libc::pthread_t, *_, usize) -> i32),
249                    (link_name, abi, args),
250                )?;
251                // The function's behavior isn't portable between platforms.
252                // In case of glibc, the length of the output buffer must
253                // be not shorter than TASK_COMM_LEN.
254                let len = ecx.read_scalar(len)?;
255                let res = if len.to_target_usize(ecx)? >= TASK_COMM_LEN {
256                    match ecx.pthread_getname_np(
257                        Some(thread),
258                        ecx.read_pointer(name)?,
259                        len,
260                        /* truncate*/ false,
261                    )? {
262                        ThreadNameResult::Ok => Scalar::from_u32(0),
263                        ThreadNameResult::NameTooLong => unreachable!(),
264                    }
265                } else {
266                    ecx.eval_libc("ERANGE")
267                };
268                ecx.write_scalar(res, dest)?;
269            }
270            "gettid" => {
271                let [] = &ecx.check_shim_sig(
272                    shim_sig!(extern "C" fn() -> libc::pid_t),
273                    (link_name, abi, args),
274                )?;
275                let result = ecx.unix_gettid(link_name.as_str())?;
276                ecx.write_scalar(result, dest)?;
277            }
278            "prctl" => prctl(ecx, link_name, abi, args, dest)?,
279            "__cxa_thread_atexit_impl"
280                if ecx.tcx.sess.target.env == rustc_target::spec::Env::Gnu =>
281            {
282                let [dtor, arg, dso] = &ecx.check_shim_sig(
283                    shim_sig!(extern "C" fn(*_, *_, *_) -> i32),
284                    (link_name, abi, args),
285                )?;
286                let dtor = ecx.read_pointer(dtor)?;
287                let arg = ecx.read_scalar(arg)?;
288                let dso = ecx.read_pointer(dso)?;
289
290                let dso_handle = Symbol::intern("__dso_handle");
291                if dso.addr() != Pointer::from(ecx.machine.extern_statics[&dso_handle]).addr() {
292                    throw_unsup_format!(
293                        "__cxa_thread_atexit_impl: a DSO value other than the address of `__dso_handle` is not supported"
294                    );
295                }
296
297                let dtor = ecx.get_ptr_fn(dtor)?.as_instance()?;
298                ecx.machine.tls.add_thread_atexit(
299                    ecx.active_thread(),
300                    dtor,
301                    arg,
302                    ecx.machine.current_user_relevant_span(),
303                )?;
304
305                ecx.write_int(0, dest)?;
306            }
307
308            // Dynamically invoked syscalls
309            "syscall" => {
310                syscall(ecx, link_name, abi, args, dest)?;
311            }
312
313            // Miscellaneous
314            "mmap64" => {
315                let [addr, length, prot, flags, fd, offset] = &ecx.check_shim_sig(
316                    shim_sig!(extern "C" fn(*_, usize, i32, i32, i32, libc::off64_t) -> *_),
317                    (link_name, abi, args),
318                )?;
319                let offset = ecx.read_scalar(offset)?.to_i64()?;
320                let ptr = ecx.mmap(addr, length, prot, flags, fd, offset)?;
321                ecx.write_scalar(ptr, dest)?;
322            }
323            "mremap" => {
324                let ([old_address, old_size, new_size, flags], _) = ecx.check_shim_sig_variadic(
325                    shim_sig!(extern "C" fn(*_, usize, usize, i32, ...) -> *_),
326                    (link_name, abi, args),
327                )?;
328                let ptr = ecx.mremap(&old_address, &old_size, &new_size, &flags)?;
329                ecx.write_scalar(ptr, dest)?;
330            }
331            "__xpg_strerror_r" => {
332                let [errnum, buf, buflen] = &ecx.check_shim_sig(
333                    shim_sig!(extern "C" fn(i32, *_, usize) -> i32),
334                    (link_name, abi, args),
335                )?;
336                let result = ecx.strerror_r(errnum, buf, buflen)?;
337                ecx.write_scalar(result, dest)?;
338            }
339            "__errno_location" => {
340                let [] =
341                    &ecx.check_shim_sig(shim_sig!(extern "C" fn() -> *_), (link_name, abi, args))?;
342                let errno_place = ecx.last_error_place()?;
343                ecx.write_scalar(errno_place.to_ref(ecx).to_scalar(), dest)?;
344            }
345            "__libc_current_sigrtmin" => {
346                let [] =
347                    &ecx.check_shim_sig(shim_sig!(extern "C" fn() -> i32), (link_name, abi, args))?;
348
349                ecx.write_int(SIGRTMIN, dest)?;
350            }
351            "__libc_current_sigrtmax" => {
352                let [] =
353                    &ecx.check_shim_sig(shim_sig!(extern "C" fn() -> i32), (link_name, abi, args))?;
354
355                ecx.write_int(SIGRTMAX, dest)?;
356            }
357
358            // Incomplete shims that we "stub out" just to get std to work.
359            // These shims are enabled only when the caller is in the standard library.
360            "pthread_getattr_np" if ecx.frame_in_std() => {
361                let [_thread, attr] = &ecx.check_shim_sig(
362                    shim_sig!(extern "C" fn(libc::pthread_t, *libc::pthread_attr_t) -> i32),
363                    (link_name, abi, args),
364                )?;
365                // The caller will `pthread_attr_destroy` this, so it needs to be initialized.
366                ecx.pthread_attr_init(attr, dest)?;
367            }
368            "gnu_get_libc_version"
369                if ecx.frame_in_std()
370                    && ecx.tcx.sess.target.env == rustc_target::spec::Env::Gnu =>
371            {
372                let [] =
373                    &ecx.check_shim_sig(shim_sig!(extern "C" fn() -> *_), (link_name, abi, args))?;
374                // We have to be at least version 2.26 so that std does not call `res_init`.
375                // This returns a C string, so we have to add a null terminator.
376                let version = "2.26\0";
377                let version = ecx.allocate_str_dedup(version)?;
378                ecx.write_pointer(version.ptr(), dest)?;
379            }
380            "__pthread_get_minstack"
381                if ecx.frame_in_std()
382                    && ecx.tcx.sess.target.env == rustc_target::spec::Env::Gnu =>
383            {
384                let [_attr] = &ecx.check_shim_sig(
385                    shim_sig!(extern "C" fn(*libc::pthread_attr_t) -> usize),
386                    (link_name, abi, args),
387                )?;
388                let val = ecx.eval_libc("PTHREAD_STACK_MIN");
389                ecx.write_scalar(val, dest)?;
390            }
391            "sendfile64" if ecx.frame_in_std() => {
392                let [_out_fd, _in_fd, _offset, _count] = &ecx.check_shim_sig(
393                    shim_sig!(extern "C" fn(i32, i32, *libc::off64_t, usize) -> isize),
394                    (link_name, abi, args),
395                )?;
396                // Force std to use a fallback path.
397                ecx.set_errno_and_return_neg1(LibcError("ENOSYS"), dest)?;
398            }
399            "splice" if ecx.frame_in_std() => {
400                let [_src_fd, _src_offset, _dst_fd, _dst_offset, _len, _flags] = &ecx.check_shim_sig(
401                    shim_sig!(extern "C" fn(i32, *libc::off_t, i32, *libc::off_t, usize, u32) -> isize),
402                    (link_name, abi, args),
403                )?;
404                // Force std to use a fallback path.
405                ecx.set_errno_and_return_neg1(LibcError("ENOSYS"), dest)?;
406            }
407
408            _ => return interp_ok(EmulateItemResult::NotSupported),
409        };
410
411        interp_ok(EmulateItemResult::NeedsReturn)
412    }
413}