diff --git a/src/helpers.rs b/src/helpers.rs index 0e2d30efc8..58e24b3cd9 100644 --- a/src/helpers.rs +++ b/src/helpers.rs @@ -165,6 +165,11 @@ pub fn iter_exported_symbols<'tcx>( interp_ok(()) } +/// Get whether the current target OS is part of the Unix family of OSes. +pub fn target_os_is_unix<'tcx>(tcx: TyCtxt<'tcx>) -> bool { + tcx.sess.target.families.iter().any(|f| f == "unix") +} + impl<'tcx> EvalContextExt<'tcx> for crate::MiriInterpCx<'tcx> {} pub trait EvalContextExt<'tcx>: crate::MiriInterpCxExt<'tcx> { /// Checks if the given crate/module exists. @@ -688,7 +693,7 @@ pub trait EvalContextExt<'tcx>: crate::MiriInterpCxExt<'tcx> { } fn target_os_is_unix(&self) -> bool { - self.eval_context_ref().tcx.sess.target.families.iter().any(|f| f == "unix") + target_os_is_unix(*self.eval_context_ref().tcx) } /// Read bytes from a byte slice. diff --git a/src/lib.rs b/src/lib.rs index 19c0c1cf53..cb273d1697 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -31,6 +31,7 @@ #![feature(derive_coerce_pointee)] #![feature(arbitrary_self_types)] #![feature(macro_metavar_expr)] +#![feature(macro_metavar_expr_concat)] #![feature(uint_carryless_mul)] // Configure clippy and other lints #![allow( diff --git a/src/machine.rs b/src/machine.rs index f82134332a..a17fe52d4e 100644 --- a/src/machine.rs +++ b/src/machine.rs @@ -42,6 +42,7 @@ use crate::concurrency::{ }; use crate::data_structures::range_object_map::RangeObjectMap; use crate::helpers::is_no_core; +use crate::shims::ShimTable; use crate::*; /// First real-time signal. @@ -549,6 +550,9 @@ pub struct MiriMachine<'tcx> { /// Whether to enforce the validity invariant. pub(crate) validation: ValidationMode, + /// The table of all available shimmed functions. + pub(crate) shims: ShimTable<'tcx>, + /// The table of file descriptors. pub(crate) fds: shims::FdTable, /// The table of directory descriptors. @@ -787,6 +791,7 @@ impl<'tcx> MiriMachine<'tcx> { tls: TlsData::default(), isolated_op: config.isolated_op, validation: config.validation, + shims: ShimTable::new(tcx), fds: shims::FdTable::init(config.mute_stdout_stderr), delayed_callbacks: Rc::new(DelayedCallbacks::default()), dirs: Default::default(), @@ -1042,6 +1047,7 @@ impl VisitProvenance for MiriMachine<'_> { data_race, alloc_addresses, fds, + shims: _, blocking_io:_, delayed_callbacks: _, tcx: _, diff --git a/src/shims/foreign_items.rs b/src/shims/foreign_items.rs index 17a9d25130..3e62ad8abe 100644 --- a/src/shims/foreign_items.rs +++ b/src/shims/foreign_items.rs @@ -11,7 +11,7 @@ use rustc_hir::def::DefKind; use rustc_hir::def_id::CrateNum; use rustc_middle::middle::codegen_fn_attrs::CodegenFnAttrFlags; use rustc_middle::mir::interpret::AllocInit; -use rustc_middle::ty::{Instance, Ty}; +use rustc_middle::ty::{Instance, Ty, TyCtxt}; use rustc_middle::{mir, ty}; use rustc_span::Symbol; use rustc_target::callconv::FnAbi; @@ -21,7 +21,8 @@ use super::alloc::EvalContextExt as _; use super::backtrace::EvalContextExt as _; use crate::concurrency::GenmcEvalContextExt as _; use crate::eval::{ExitType, ProgramExitHandler}; -use crate::helpers::EvalContextExt as _; +use crate::helpers::{EvalContextExt as _, target_os_is_unix}; +use crate::shims::{ShimCall, ShimTable}; use crate::*; /// Type of dynamic symbols (for `dlsym` et al) @@ -71,12 +72,18 @@ pub trait EvalContextExt<'tcx>: crate::MiriInterpCxExt<'tcx> { } } - // FIXME: avoid allocating memory + // To avoid bugs due to keeping PlaceTy around too long, we always + // force the destination into memory. let dest = ecx.force_allocation(dest)?; - // The rest either implements the logic, or falls back to `lookup_exported_symbol`. - let res = ecx.emulate_foreign_item_inner(link_name, abi, args, &dest)?; - res.jump_to_next_block(ecx, &dest.clone().into(), ret, Some(unwind), |ecx| { + let res = if let Some(shim) = ecx.machine.shims.get(&link_name) { + shim(ecx, ShimCall { abi, args, dest: &dest, link_name })? + } else { + // The rest either implements the logic, or falls back to `lookup_exported_symbol`. + ecx.emulate_foreign_item_inner(link_name, abi, args, &dest)? + }; + + res.jump_to_next_block(ecx, &dest.into(), ret, Some(unwind), |ecx| { if let Some(body) = ecx.lookup_exported_fn(link_name)? { return interp_ok(Some(body)); } @@ -251,6 +258,20 @@ pub trait EvalContextExt<'tcx>: crate::MiriInterpCxExt<'tcx> { } interp_ok(instance) } + + fn register_shims(tcx: TyCtxt<'tcx>, shims: &mut ShimTable<'tcx>) { + MiriInterpCx::register_miri_start_unwind(tcx, shims); + + // Platform-specific shims + match &tcx.sess.target.os { + _ if target_os_is_unix(tcx) => + as shims::unix::foreign_items::EvalContextExt>::register_shims( + tcx, shims, + ), + Os::Windows => {} + _ => {} + } + } } impl<'tcx> EvalContextExtPriv<'tcx> for crate::MiriInterpCx<'tcx> {} @@ -376,14 +397,6 @@ trait EvalContextExtPriv<'tcx>: crate::MiriInterpCxExt<'tcx> { )); } } - "miri_start_unwind" => { - let [payload] = &ecx.check_shim_sig( - shim_sig!(extern "Rust" fn(*()) -> !), - (link_name, abi, args), - )?; - ecx.handle_miri_start_unwind(payload)?; - return interp_ok(EmulateItemResult::NeedsUnwind); - } "miri_run_provenance_gc" => { let [] = &ecx .check_shim_sig(shim_sig!(extern "Rust" fn() -> ()), (link_name, abi, args))?; diff --git a/src/shims/mod.rs b/src/shims/mod.rs index 4a378c6876..448bf5f758 100644 --- a/src/shims/mod.rs +++ b/src/shims/mod.rs @@ -23,11 +23,21 @@ pub mod time; pub mod tls; pub mod unwind; +use std::rc::Rc; + +use rustc_const_eval::interpret::InterpResult; +use rustc_data_structures::fx::FxHashMap; +use rustc_middle::ty::{Ty, TyCtxt}; +use rustc_span::Symbol; +use rustc_target::callconv::FnAbi; + pub use self::cpu_affinity::CpuAffinityMask; pub use self::files::{FdId, FdTable, FileDescription, FileDescriptionRef, WeakFileDescriptionRef}; #[cfg(all(feature = "native-lib", unix))] pub use self::native_lib::trace::{init_sv, register_retcode_sv}; pub use self::unix::DirTable; +use crate::shims::foreign_items::EvalContextExt; +use crate::{MPlaceTy, MiriInterpCx, OpTy}; /// What needs to be done after emulating an item (a shim or an intrinsic) is done. pub enum EmulateItemResult { @@ -68,3 +78,198 @@ impl EmulateItemResult { } } } + +/// Describes the signature of a call to a shimmed function. +pub struct ShimCall<'tcx, 'a> { + pub link_name: Symbol, + pub abi: &'a FnAbi<'tcx, Ty<'tcx>>, + pub args: &'a [OpTy<'tcx>], + pub dest: &'a MPlaceTy<'tcx>, +} + +type Shim<'tcx> = Rc< + dyn Fn(&mut MiriInterpCx<'tcx>, ShimCall<'tcx, '_>) -> InterpResult<'tcx, EmulateItemResult> + + 'tcx, +>; + +pub struct ShimTable<'tcx>(FxHashMap>); + +impl<'tcx> ShimTable<'tcx> { + pub fn new(tcx: TyCtxt<'tcx>) -> Self { + let mut shims = ShimTable(FxHashMap::default()); + MiriInterpCx::register_shims(tcx, &mut shims); + shims + } + + pub fn register(&mut self, foreign_name: Symbol, shim: Shim<'tcx>) { + self.0 + .try_insert(foreign_name, shim) + .unwrap_or_else(|_| panic!("attempted to register multiple shims for {foreign_name}")); + } + + pub fn get(&self, foreign_name: &Symbol) -> Option> { + self.0.get(foreign_name).cloned() + } +} + +/// Create the registration function for a shim. +/// +/// ```rust +/// register! { +/// name: poll, +/// sig: extern "C" fn(*libc::pollfd, libc::nfds_t, i32) -> i32 +/// } +/// ``` +/// +/// This will create a function `register_poll` which will invoke `ecx.poll(args, dest)` when +/// a foreign function invocation on `poll` is encountered. `args` is the array of argument +/// operands and `dest` is the destination place of the foreign function invocation. +/// +/// To indicate that the shimmed function is variadic, the signature can be prefixed with `variadic`: +/// ```rust +/// register! { +/// name: fcntl, +/// sig: variadic extern "C" fn(i32, i32, ...) -> i32, +/// } +/// ``` +/// This will then create a function `register_fcntl` which will invoke `ecx.fcntl(args, varargs, dest)` +/// (notice the additional `varargs` argument compared to a non-variadic shim) when a foreign function +/// invocation on `fcntl` is encountered. The varargs are of type `Varargs`. The remaining arguments +/// stay the same as in the non-variadic case. +/// +/// Besides the required `name` and `sig` "fields", the macro also supports a few optional +/// "fields": +/// +/// - `call`: A closure-like "field" which allows customizing the handler for a shim. This is +/// useful when multiple shims share the same handler (e.g., in the case of `accept` and `accept4`): +/// ```rust +/// // `accept` doesn't have a `flags` argument, thus we add a `None` argument +/// // to the handler. +/// register! { +/// name: accept, +/// sig: extern "C" fn(i32, *libc::sockaddr, *libc::socklen_t) -> i32, +/// call: |ecx, args, dest| ecx.accept4(args, /* flags */ None, dest) +/// } +/// // `accept4` has a `flags` argument, thus we insert `Some(flags)` argument +/// // to the handler. +/// register! { +/// name: accept4, +/// sig: extern "C" fn(i32, *libc::sockaddr, *libc::socklen_t, i32) -> i32, +/// call: |ecx, [args @ .., flags], dest| ecx.accept4(args, Some(flags), dest) +/// } +/// ``` +/// **Note**: If the shimmed function is variadic, the "closure" has an additional `varargs` "argument" +/// and thus it has the form `|ecx, args, varargs, dest|`. +/// +/// - `result`: The result to return after a call to the shim succeeded. If this "field" +/// is omitted, [`EmulateItemResult::NeedsReturn`] is returned. Some shims need to return +/// a different result, for example the `miri_start_unwind` shim: +/// ```rust +/// register! { +/// name: miri_start_unwind, +/// sig: extern "Rust" fn(*()) -> !, +/// result: EmulateItemResult::NeedsUnwind +/// } +/// ``` +#[macro_export] +macro_rules! register { + // Initially we only match the name of the shim and whether the signature is variadic. + // We also initialize the default "values" for all optional "fields". + + // The variadic case. + (name: $name:ident, sig: variadic $($rest:tt)*) => { + register! { + @sig $name [variadic] [] ( + /* By default we just invoke `ecx.(args, varargs, dest)` */ [ecx args varargs dest ecx.$name(args, varargs, dest)] + /* The default result returned after a call */ [$crate::EmulateItemResult::NeedsReturn] + ) ; $($rest)* + } + }; + // The non-variadic case. + (name: $name:ident, sig: $($rest:tt)*) => { + register! { + @sig $name [] [] ( + /* By default we just invoke `ecx.(args, dest)` */ [ecx args dest ecx.$name(args, dest)] + /* The default result returned after a call */ [$crate::EmulateItemResult::NeedsReturn] + ) ; $($rest)* + } + }; + + // Since signatures can contain arbitrary token trees, we need to have a TT-mangler for them. + // We consume everything into `sig` until we either encounter the start of a new "field" + // (i.e., `, : `) or when only an optional trailing comma is left in the input. + + // Stop `sig` when the next token trees are the start of a new "field". + (@sig $name:ident $variadic:tt [$($sig:tt)*] $defaults:tt ; , $field:ident : $($rest:tt)*) => { + register!{ @emit $name $variadic [$($sig)*] $defaults ; $field: $($rest)* } + }; + // Stop `sig` when there is only an optional trailing comma left. + (@sig $name:ident $variadic:tt [$($sig:tt)*] $defaults:tt ; $(,)?) => { + register!{ @emit $name $variadic [$($sig)*] $defaults ; } + }; + // Consume a single token tree into `sig` and continue matching on the rest. + (@sig $name:ident $variadic:tt [$($sig:tt)*] $defaults:tt ; $tok:tt $($rest:tt)*) => { + register! { @sig $name $variadic [$($sig)* $tok] $defaults ; $($rest)* } + }; + + // For every optional "field" that is provided, overwrite the default "value" for that field + // using the provided "value". + + // In the non-variadic case we don't have the `varargs` "closure" argument. + (@emit $name:ident [] $sig:tt ($call:tt $result:tt) ; call: |$ecx:ident, $args:tt, $dest:ident| $handler:expr $(, $($rest:tt)*)?) => { + register! { @emit $name [] $sig ([$ecx $args $dest $handler] $result) ; $($($rest)*)? } + }; + // In the variadic case we also have the `varargs` "closure" argument. + (@emit $name:ident [variadic] $sig:tt ($call:tt $result:tt) ; call: |$ecx:ident, $args:tt, $varargs:ident, $dest:ident| $handler:expr $(, $($rest:tt)*)?) => { + register! { @emit $name [variadic] $sig ([$ecx $args $varargs $dest $handler] $result) ; $($($rest)*)? } + }; + // We emit a compile error should one try to provide a "closure" without `varargs` for a variadic shim. + (@emit $name:ident [variadic] $sig:tt ($call:tt $result:tt) ; call: |$ecx:ident, $args:tt, $dest:ident| $handler:expr $(, $($rest:tt)*)?) => { + compile_error!("expected signature `|ecx, args, varargs, dest|` for variadic shim, but got `|ecx, args, dest|`"); + }; + (@emit $name:ident $variadic:tt $sig:tt ($call:tt $_:tt) ; result: $result:path $(, $($rest:tt)*)?) => { + register! { @emit $name $variadic $sig ($call [$result]) ; $($($rest)*)? } + }; + + // When all "fields" are populated, we can emit the actual registration function. + // The `sig` token trees are passed to the `shim_sig!` macro. + + (@emit $name:ident $variadic:tt [$($sig:tt)*] ([$ecx:ident $($args:tt)*] $result:tt) ; ) => { + fn ${concat(register_, $name)}<'a>( + #[allow(unused)] tcx: ::rustc_middle::ty::TyCtxt<'a>, + shims: &mut $crate::shims::ShimTable<'a> + ) { + let cell = ::std::cell::OnceCell::new(); + let eval_shim_sig: fn(&mut $crate::MiriInterpCx<'a>) -> _ = + shim_sig!($($sig)*); + + shims.register( + ::rustc_span::Symbol::intern(stringify!($name)), + ::std::rc::Rc::new(move |$ecx, call| { + let shim_sig = cell.get_or_init(|| eval_shim_sig($ecx)); + + register! { @emit_inner $variadic call shim_sig [$ecx $($args)*] $result } + }), + ); + } + }; + + // Depending on whether the signature is variadic or not, we need to emit different bodies for + // the shim callback function. + + // In the non-variadic case, we internally use `call.check_sig`. + (@emit_inner [] $call:ident $shim_sig:ident [$ecx:ident $args:tt $dest:ident $handler:expr] [$result:path]) => { + let (args, ref $dest) = $call.check_sig($ecx, $shim_sig)?; + let $args = args.each_ref(); + + $handler.map(|()| $result) + }; + + // In the variadic case, we internally use `call.check_sig_variadic`. + (@emit_inner [variadic] $call:ident $shim_sig:ident [$ecx:ident $args:tt $varargs:tt $dest:ident $handler:expr] [$result:path]) => { + let (args, $varargs, ref $dest) = $call.check_sig_variadic($ecx, $shim_sig)?; + let $args = args.each_ref(); + + $handler.map(|()| $result) + }; +} diff --git a/src/shims/sig.rs b/src/shims/sig.rs index e5c3b58b25..27baf1ac68 100644 --- a/src/shims/sig.rs +++ b/src/shims/sig.rs @@ -5,6 +5,7 @@ use rustc_middle::ty::{Binder, FnSig, FnSigKind, Ty}; use rustc_span::Symbol; use rustc_target::callconv::FnAbi; +use crate::shims::ShimCall; use crate::*; /// Describes the expected signature of a shim. @@ -204,6 +205,67 @@ impl<'tcx, const ARGS: usize> ShimSig<'tcx, ARGS> { } } +impl<'tcx, 'a> ShimCall<'tcx, 'a> { + pub fn check_sig( + &self, + ecx: &mut MiriInterpCx<'tcx>, + shim_sig: &ShimSig<'tcx, N>, + ) -> InterpResult<'tcx, ([OpTy<'tcx>; N], MPlaceTy<'tcx>)> { + // This is basically a copy of `ecx.check_shim_sig`, just that we also fix + // the layout of the destination operand. + + // Compute callee ABI. + assert!(!shim_sig.c_variadic); + let callee_fn_abi = shim_sig.as_abi(ecx); + + // Check everything. + check_shim_abi(ecx, self.link_name, callee_fn_abi, self.abi)?; + ecx.check_shim_symbol_clash(self.link_name)?; + + // Transmute arguments. + let transmuted_args = + std::array::try_from_fn(|i| self.args[i].transmute(callee_fn_abi.args[i].layout, ecx))?; + + // Transmute output destination. + let transmuted_dest = self.dest.transmute(callee_fn_abi.ret.layout, ecx)?; + + interp_ok((transmuted_args, transmuted_dest)) + } + + pub fn check_sig_variadic( + &self, + ecx: &mut MiriInterpCx<'tcx>, + shim_sig: &ShimSig<'tcx, N>, + ) -> InterpResult<'tcx, ([OpTy<'tcx>; N], Varargs<'tcx, 'a>, MPlaceTy<'tcx>)> { + // This is basically a copy of `ecx.check_shim_sig_variadic`, just that we also fix + // the layout of the destination operand. + + // Compute callee ABI. + assert!(shim_sig.c_variadic); + let callee_fn_abi = shim_sig.as_abi(ecx); + + // Check everything. + check_shim_abi(ecx, self.link_name, callee_fn_abi, self.abi)?; + ecx.check_shim_symbol_clash(self.link_name)?; + + if let Some((fixed, var)) = self.args.split_first_chunk::() { + // Transmute arguments. + let transmuted_args = + std::array::try_from_fn(|i| fixed[i].transmute(callee_fn_abi.args[i].layout, ecx))?; + + // Transmute output destination. + let transmuted_dest = self.dest.transmute(callee_fn_abi.ret.layout, ecx)?; + + return interp_ok(( + transmuted_args, + Varargs { args: var, already_gone: N }, + transmuted_dest, + )); + } + unreachable!() + } +} + /// Helper function to compare two ABIs. fn check_shim_abi<'tcx>( ecx: &MiriInterpCx<'tcx>, diff --git a/src/shims/unix/fd.rs b/src/shims/unix/fd.rs index 79bbd73eb5..1aa12cedc4 100644 --- a/src/shims/unix/fd.rs +++ b/src/shims/unix/fd.rs @@ -256,12 +256,16 @@ pub trait EvalContextExt<'tcx>: crate::MiriInterpCxExt<'tcx> { } } + register! { + name: fcntl, + sig: variadic extern "C" fn(i32, i32, ...) -> i32, + } fn fcntl( &mut self, - fd_num: &OpTy<'tcx>, - cmd: &OpTy<'tcx>, + [fd_num, cmd]: [&OpTy<'tcx>; 2], varargs: Varargs<'tcx, '_>, - ) -> InterpResult<'tcx, Scalar> { + dest: &MPlaceTy<'tcx>, + ) -> InterpResult<'tcx> { let ecx = self.eval_context_mut(); let fd_num = ecx.read_scalar(fd_num)?.to_i32()?; @@ -281,9 +285,9 @@ pub trait EvalContextExt<'tcx>: crate::MiriInterpCxExt<'tcx> { // always sets this flag when opening a file. However we still need to check that the // file itself is open. if !ecx.machine.fds.is_fd_num(fd_num) { - ecx.set_errno_and_return_neg1_i32(LibcError("EBADF")) + ecx.set_errno_and_return_neg1(LibcError("EBADF"), dest) } else { - interp_ok(ecx.eval_libc("FD_CLOEXEC")) + ecx.write_scalar(ecx.eval_libc("FD_CLOEXEC"), dest) } } cmd if cmd == f_dupfd || cmd == f_dupfd_cloexec => { @@ -301,35 +305,37 @@ pub trait EvalContextExt<'tcx>: crate::MiriInterpCxExt<'tcx> { let start = ecx.read_scalar(&start)?.to_i32()?; let Some(fd) = ecx.machine.fds.get(fd_num) else { - return ecx.set_errno_and_return_neg1_i32(LibcError("EBADF")); + return ecx.set_errno_and_return_neg1(LibcError("EBADF"), dest); }; if !FdTable::fd_num_valid(start) { - return ecx.set_errno_and_return_neg1_i32(LibcError("EINVAL")); + return ecx.set_errno_and_return_neg1(LibcError("EINVAL"), dest); } let Some(new_fd_num) = ecx.machine.fds.insert_with_min_num(fd, start) else { - return ecx.set_errno_and_return_neg1_i32(LibcError("EMFILE")); + return ecx.set_errno_and_return_neg1(LibcError("EMFILE"), dest); }; - interp_ok(Scalar::from_i32(new_fd_num)) + ecx.write_int(new_fd_num, dest) } cmd if cmd == f_getfl => { // Check if this is a valid open file descriptor. let Some(fd) = ecx.machine.fds.get(fd_num) else { - return ecx.set_errno_and_return_neg1_i32(LibcError("EBADF")); + return ecx.set_errno_and_return_neg1(LibcError("EBADF"), dest); }; - fd.as_unix().get_flags(ecx) + let scalar = fd.as_unix().get_flags(ecx)?; + ecx.write_scalar(scalar, dest) } cmd if cmd == f_setfl => { // Check if this is a valid open file descriptor. let Some(fd) = ecx.machine.fds.get(fd_num) else { - return ecx.set_errno_and_return_neg1_i32(LibcError("EBADF")); + return ecx.set_errno_and_return_neg1(LibcError("EBADF"), dest); }; let ([flag], _) = ecx.check_varargs(shim_varargs![i32], varargs, "fcntl(fd, F_SETFL, ...)")?; let flag = ecx.read_scalar(&flag)?.to_i32()?; - fd.as_unix().set_flags(flag & !ecx.setfl_ignored_flags(), ecx) + let scalar = fd.as_unix().set_flags(flag & !ecx.setfl_ignored_flags(), ecx)?; + ecx.write_scalar(scalar, dest) } cmd if ecx.tcx.sess.target.os == Os::MacOs && cmd == ecx.eval_libc_i32("F_FULLFSYNC") => @@ -337,24 +343,25 @@ pub trait EvalContextExt<'tcx>: crate::MiriInterpCxExt<'tcx> { // Reject if isolation is enabled. if let IsolatedOp::Reject(reject_with) = ecx.machine.isolated_op { ecx.reject_in_isolation("`fcntl`", reject_with)?; - return ecx.set_errno_and_return_neg1_i32(ErrorKind::PermissionDenied); + return ecx.set_errno_and_return_neg1(ErrorKind::PermissionDenied, dest); } - ecx.ffullsync_fd(fd_num) + let scalar = ecx.ffullsync_fd(fd_num)?; + ecx.write_scalar(scalar, dest) } cmd if ecx.tcx.sess.target.os == Os::MacOs && ecx.frame_in_std() && cmd == ecx.eval_libc_i32("F_GETPATH") => { // Std uses this when debug-printing `File`. We stub it out by returning an error. - ecx.set_errno_and_return_neg1_i32(LibcError("EOPNOTSUPP")) + ecx.set_errno_and_return_neg1(LibcError("EOPNOTSUPP"), dest) } cmd if ecx.tcx.sess.target.os == Os::FreeBsd && ecx.frame_in_std() && cmd == ecx.eval_libc_i32("F_KINFO") => { // Std uses this when debug-printing `File`. We stub it out by returning an error. - ecx.set_errno_and_return_neg1_i32(LibcError("EOPNOTSUPP")) + ecx.set_errno_and_return_neg1(LibcError("EOPNOTSUPP"), dest) } cmd => { throw_unsup_format!("fcntl: unsupported command {cmd:#x}"); diff --git a/src/shims/unix/foreign_items.rs b/src/shims/unix/foreign_items.rs index d84aa72105..a8512a3089 100644 --- a/src/shims/unix/foreign_items.rs +++ b/src/shims/unix/foreign_items.rs @@ -3,7 +3,7 @@ use std::str; use std::time::Duration; use rustc_abi::Size; -use rustc_middle::ty::Ty; +use rustc_middle::ty::{Ty, TyCtxt}; use rustc_span::Symbol; use rustc_target::callconv::FnAbi; use rustc_target::spec::{Env, Os, Target}; @@ -14,6 +14,7 @@ use self::shims::unix::linux::foreign_items as linux; use self::shims::unix::macos::foreign_items as macos; use self::shims::unix::netbsd::foreign_items as netbsd; use self::shims::unix::solarish::foreign_items as solarish; +use crate::shims::ShimTable; use crate::shims::alloc::EvalContextExt as _; use crate::shims::cpu_affinity::EvalContextExt as _; use crate::shims::files::FD_LIMIT; @@ -284,14 +285,6 @@ pub trait EvalContextExt<'tcx>: crate::MiriInterpCxExt<'tcx> { let result = ecx.close(fd)?; ecx.write_scalar(result, dest)?; } - "fcntl" => { - let ([fd_num, cmd], varargs) = ecx.check_shim_sig_variadic( - shim_sig!(extern "C" fn(i32, i32, ...) -> i32), - (link_name, abi, args), - )?; - let result = ecx.fcntl(&fd_num, &cmd, varargs)?; - ecx.write_scalar(result, dest)?; - } "dup" => { let [old_fd] = &ecx .check_shim_sig(shim_sig!(extern "C" fn(i32) -> i32), (link_name, abi, args))?; @@ -597,15 +590,6 @@ pub trait EvalContextExt<'tcx>: crate::MiriInterpCxExt<'tcx> { ecx.write_scalar(result, dest)?; } - // Poll - "poll" => { - let [fds, nfds, timeout] = &ecx.check_shim_sig( - shim_sig!(extern "C" fn(*libc::pollfd, libc::nfds_t, i32) -> i32), - (link_name, abi, args), - )?; - ecx.poll(fds, nfds, timeout, dest)?; - } - // Sockets and pipes "socketpair" => { let [domain, type_, protocol, sv] = &ecx.check_shim_sig( @@ -661,20 +645,6 @@ pub trait EvalContextExt<'tcx>: crate::MiriInterpCxExt<'tcx> { let result = ecx.listen(socket, backlog)?; ecx.write_scalar(result, dest)?; } - "accept" => { - let [socket, address, address_len] = &ecx.check_shim_sig( - shim_sig!(extern "C" fn(i32, *libc::sockaddr, *libc::socklen_t) -> i32), - (link_name, abi, args), - )?; - ecx.accept4(socket, address, address_len, /* flags */ None, dest)?; - } - "accept4" => { - let [socket, address, address_len, flags] = &ecx.check_shim_sig( - shim_sig!(extern "C" fn(i32, *libc::sockaddr, *libc::socklen_t, i32) -> i32), - (link_name, abi, args), - )?; - ecx.accept4(socket, address, address_len, Some(flags), dest)?; - } "connect" => { let [socket, address, address_len] = &ecx.check_shim_sig( shim_sig!(extern "C" fn(i32, *libc::sockaddr, libc::socklen_t) -> i32), @@ -1372,7 +1342,7 @@ pub trait EvalContextExt<'tcx>: crate::MiriInterpCxExt<'tcx> { shim_sig!(extern "C" fn(*_) -> panic_unwind::imp::uw::_Unwind_Reason_Code), (link_name, abi, args), )?; - ecx.handle_miri_start_unwind(payload)?; + ecx.handle_miri_start_unwind([payload])?; return interp_ok(EmulateItemResult::NeedsUnwind); } "getuid" | "geteuid" => { @@ -1549,4 +1519,11 @@ pub trait EvalContextExt<'tcx>: crate::MiriInterpCxExt<'tcx> { interp_ok(EmulateItemResult::NeedsReturn) } + + fn register_shims(tcx: TyCtxt<'tcx>, shims: &mut ShimTable<'tcx>) { + MiriInterpCx::register_fcntl(tcx, shims); + MiriInterpCx::register_accept(tcx, shims); + MiriInterpCx::register_accept4(tcx, shims); + MiriInterpCx::register_poll(tcx, shims); + } } diff --git a/src/shims/unix/linux_like/syscall.rs b/src/shims/unix/linux_like/syscall.rs index 5535a129a7..20922c19f4 100644 --- a/src/shims/unix/linux_like/syscall.rs +++ b/src/shims/unix/linux_like/syscall.rs @@ -85,7 +85,7 @@ pub fn syscall<'tcx>( varargs, "syscall(SYS_accept4, ...)", )?; - ecx.accept4(&socket, &address, &address_len, Some(&flags), dest)?; + ecx.accept4([&socket, &address, &address_len], Some(&flags), dest)?; } num if num == sys_copy_file_range => { let ([fd_in, off_in, fd_out, off_out, len, flags], _) = &ecx.check_varargs( diff --git a/src/shims/unix/poll.rs b/src/shims/unix/poll.rs index 21b11e8ea8..7c29e93b46 100644 --- a/src/shims/unix/poll.rs +++ b/src/shims/unix/poll.rs @@ -23,11 +23,13 @@ impl VisitProvenance for PollInterest<'_> { impl<'tcx> EvalContextExt<'tcx> for crate::MiriInterpCx<'tcx> {} pub trait EvalContextExt<'tcx>: crate::MiriInterpCxExt<'tcx> { + register! { + name: poll, + sig: extern "C" fn(*libc::pollfd, libc::nfds_t, i32) -> i32 + } fn poll( &mut self, - fds: &OpTy<'tcx>, - nfds: &OpTy<'tcx>, - timeout: &OpTy<'tcx>, + [fds, nfds, timeout]: [&OpTy<'tcx>; 3], dest: &MPlaceTy<'tcx>, ) -> InterpResult<'tcx> { let ecx = self.eval_context_mut(); diff --git a/src/shims/unix/socket.rs b/src/shims/unix/socket.rs index 671d9a1ab3..5760753cb9 100644 --- a/src/shims/unix/socket.rs +++ b/src/shims/unix/socket.rs @@ -358,15 +358,20 @@ pub trait EvalContextExt<'tcx>: crate::MiriInterpCxExt<'tcx> { } } - /// For more information on the arguments see the accept manpage: - /// + register! { + name: accept, + sig: extern "C" fn(i32, *libc::sockaddr, *libc::socklen_t) -> i32, + call: |ecx, args, dest| ecx.accept4(args, /* flags */ None, dest) + } + register! { + name: accept4, + sig: extern "C" fn(i32, *libc::sockaddr, *libc::socklen_t, i32) -> i32, + call: |ecx, [args @ .., flags], dest| ecx.accept4(args, Some(flags), dest) + } fn accept4( &mut self, - socket: &OpTy<'tcx>, - address: &OpTy<'tcx>, - address_len: &OpTy<'tcx>, + [socket, address, address_len]: [&OpTy<'tcx>; 3], flags: Option<&OpTy<'tcx>>, - // Location where the output scalar is written to. dest: &MPlaceTy<'tcx>, ) -> InterpResult<'tcx> { let ecx = self.eval_context_mut(); diff --git a/src/shims/unwind.rs b/src/shims/unwind.rs index 5e249c3ace..3988761b52 100644 --- a/src/shims/unwind.rs +++ b/src/shims/unwind.rs @@ -42,9 +42,15 @@ impl VisitProvenance for CatchUnwindData<'_> { impl<'tcx> EvalContextExt<'tcx> for crate::MiriInterpCx<'tcx> {} pub trait EvalContextExt<'tcx>: crate::MiriInterpCxExt<'tcx> { + register! { + name: miri_start_unwind, + sig: extern "Rust" fn(*()) -> !, + call: |ecx, args, _dest| ecx.handle_miri_start_unwind(args), + result: EmulateItemResult::NeedsUnwind + } /// Handles the special `miri_start_unwind` intrinsic, which is called /// by libpanic_unwind to delegate the actual unwinding process to Miri. - fn handle_miri_start_unwind(&mut self, payload: &OpTy<'tcx>) -> InterpResult<'tcx> { + fn handle_miri_start_unwind(&mut self, [payload]: [&OpTy<'tcx>; 1]) -> InterpResult<'tcx> { let ecx = self.eval_context_mut(); trace!("miri_start_unwind: {:?}", ecx.frame().instance()); diff --git a/src/shims/windows/foreign_items.rs b/src/shims/windows/foreign_items.rs index 7e5f545bff..36b380010c 100644 --- a/src/shims/windows/foreign_items.rs +++ b/src/shims/windows/foreign_items.rs @@ -1181,7 +1181,7 @@ pub trait EvalContextExt<'tcx>: crate::MiriInterpCxExt<'tcx> { shim_sig!(extern "C" fn(*_) -> panic_unwind::imp::uw::_Unwind_Reason_Code), (link_name, abi, args), )?; - ecx.handle_miri_start_unwind(payload)?; + ecx.handle_miri_start_unwind([payload])?; return interp_ok(EmulateItemResult::NeedsUnwind); }