miri/shims/
native_lib.rs

1//! Implements calling functions from a native library.
2use std::ops::Deref;
3
4use libffi::high::call as ffi;
5use libffi::low::CodePtr;
6use rustc_abi::{BackendRepr, HasDataLayout, Size};
7use rustc_middle::mir::interpret::Pointer;
8use rustc_middle::ty::{self as ty, IntTy, UintTy};
9use rustc_span::Symbol;
10
11use crate::*;
12
13impl<'tcx> EvalContextExtPriv<'tcx> for crate::MiriInterpCx<'tcx> {}
14trait EvalContextExtPriv<'tcx>: crate::MiriInterpCxExt<'tcx> {
15    /// Call native host function and return the output as an immediate.
16    fn call_native_with_args<'a>(
17        &mut self,
18        link_name: Symbol,
19        dest: &MPlaceTy<'tcx>,
20        ptr: CodePtr,
21        libffi_args: Vec<libffi::high::Arg<'a>>,
22    ) -> InterpResult<'tcx, ImmTy<'tcx>> {
23        let this = self.eval_context_mut();
24
25        // Call the function (`ptr`) with arguments `libffi_args`, and obtain the return value
26        // as the specified primitive integer type
27        let scalar = match dest.layout.ty.kind() {
28            // ints
29            ty::Int(IntTy::I8) => {
30                // Unsafe because of the call to native code.
31                // Because this is calling a C function it is not necessarily sound,
32                // but there is no way around this and we've checked as much as we can.
33                let x = unsafe { ffi::call::<i8>(ptr, libffi_args.as_slice()) };
34                Scalar::from_i8(x)
35            }
36            ty::Int(IntTy::I16) => {
37                let x = unsafe { ffi::call::<i16>(ptr, libffi_args.as_slice()) };
38                Scalar::from_i16(x)
39            }
40            ty::Int(IntTy::I32) => {
41                let x = unsafe { ffi::call::<i32>(ptr, libffi_args.as_slice()) };
42                Scalar::from_i32(x)
43            }
44            ty::Int(IntTy::I64) => {
45                let x = unsafe { ffi::call::<i64>(ptr, libffi_args.as_slice()) };
46                Scalar::from_i64(x)
47            }
48            ty::Int(IntTy::Isize) => {
49                let x = unsafe { ffi::call::<isize>(ptr, libffi_args.as_slice()) };
50                Scalar::from_target_isize(x.try_into().unwrap(), this)
51            }
52            // uints
53            ty::Uint(UintTy::U8) => {
54                let x = unsafe { ffi::call::<u8>(ptr, libffi_args.as_slice()) };
55                Scalar::from_u8(x)
56            }
57            ty::Uint(UintTy::U16) => {
58                let x = unsafe { ffi::call::<u16>(ptr, libffi_args.as_slice()) };
59                Scalar::from_u16(x)
60            }
61            ty::Uint(UintTy::U32) => {
62                let x = unsafe { ffi::call::<u32>(ptr, libffi_args.as_slice()) };
63                Scalar::from_u32(x)
64            }
65            ty::Uint(UintTy::U64) => {
66                let x = unsafe { ffi::call::<u64>(ptr, libffi_args.as_slice()) };
67                Scalar::from_u64(x)
68            }
69            ty::Uint(UintTy::Usize) => {
70                let x = unsafe { ffi::call::<usize>(ptr, libffi_args.as_slice()) };
71                Scalar::from_target_usize(x.try_into().unwrap(), this)
72            }
73            // Functions with no declared return type (i.e., the default return)
74            // have the output_type `Tuple([])`.
75            ty::Tuple(t_list) if t_list.is_empty() => {
76                unsafe { ffi::call::<()>(ptr, libffi_args.as_slice()) };
77                return interp_ok(ImmTy::uninit(dest.layout));
78            }
79            ty::RawPtr(..) => {
80                let x = unsafe { ffi::call::<*const ()>(ptr, libffi_args.as_slice()) };
81                let ptr = Pointer::new(Provenance::Wildcard, Size::from_bytes(x.addr()));
82                Scalar::from_pointer(ptr, this)
83            }
84            _ => throw_unsup_format!("unsupported return type for native call: {:?}", link_name),
85        };
86        interp_ok(ImmTy::from_scalar(scalar, dest.layout))
87    }
88
89    /// Get the pointer to the function of the specified name in the shared object file,
90    /// if it exists. The function must be in the shared object file specified: we do *not*
91    /// return pointers to functions in dependencies of the library.  
92    fn get_func_ptr_explicitly_from_lib(&mut self, link_name: Symbol) -> Option<CodePtr> {
93        let this = self.eval_context_mut();
94        // Try getting the function from the shared library.
95        let (lib, lib_path) = this.machine.native_lib.as_ref().unwrap();
96        let func: libloading::Symbol<'_, unsafe extern "C" fn()> =
97            unsafe { lib.get(link_name.as_str().as_bytes()).ok()? };
98        #[expect(clippy::as_conversions)] // fn-ptr to raw-ptr cast needs `as`.
99        let fn_ptr = *func.deref() as *mut std::ffi::c_void;
100
101        // FIXME: this is a hack!
102        // The `libloading` crate will automatically load system libraries like `libc`.
103        // On linux `libloading` is based on `dlsym`: https://docs.rs/libloading/0.7.3/src/libloading/os/unix/mod.rs.html#202
104        // and `dlsym`(https://linux.die.net/man/3/dlsym) looks through the dependency tree of the
105        // library if it can't find the symbol in the library itself.
106        // So, in order to check if the function was actually found in the specified
107        // `machine.external_so_lib` we need to check its `dli_fname` and compare it to
108        // the specified SO file path.
109        // This code is a reimplementation of the mechanism for getting `dli_fname` in `libloading`,
110        // from: https://docs.rs/libloading/0.7.3/src/libloading/os/unix/mod.rs.html#411
111        // using the `libc` crate where this interface is public.
112        let mut info = std::mem::MaybeUninit::<libc::Dl_info>::zeroed();
113        unsafe {
114            if libc::dladdr(fn_ptr, info.as_mut_ptr()) != 0 {
115                let info = info.assume_init();
116                #[cfg(target_os = "cygwin")]
117                let fname_ptr = info.dli_fname.as_ptr();
118                #[cfg(not(target_os = "cygwin"))]
119                let fname_ptr = info.dli_fname;
120                assert!(!fname_ptr.is_null());
121                if std::ffi::CStr::from_ptr(fname_ptr).to_str().unwrap()
122                    != lib_path.to_str().unwrap()
123                {
124                    return None;
125                }
126            }
127        }
128
129        // Return a pointer to the function.
130        Some(CodePtr(fn_ptr))
131    }
132}
133
134impl<'tcx> EvalContextExt<'tcx> for crate::MiriInterpCx<'tcx> {}
135pub trait EvalContextExt<'tcx>: crate::MiriInterpCxExt<'tcx> {
136    /// Call the native host function, with supplied arguments.
137    /// Needs to convert all the arguments from their Miri representations to
138    /// a native form (through `libffi` call).
139    /// Then, convert the return value from the native form into something that
140    /// can be stored in Miri's internal memory.
141    fn call_native_fn(
142        &mut self,
143        link_name: Symbol,
144        dest: &MPlaceTy<'tcx>,
145        args: &[OpTy<'tcx>],
146    ) -> InterpResult<'tcx, bool> {
147        let this = self.eval_context_mut();
148        // Get the pointer to the function in the shared object file if it exists.
149        let code_ptr = match this.get_func_ptr_explicitly_from_lib(link_name) {
150            Some(ptr) => ptr,
151            None => {
152                // Shared object file does not export this function -- try the shims next.
153                return interp_ok(false);
154            }
155        };
156
157        // Get the function arguments, and convert them to `libffi`-compatible form.
158        let mut libffi_args = Vec::<CArg>::with_capacity(args.len());
159        for arg in args.iter() {
160            if !matches!(arg.layout.backend_repr, BackendRepr::Scalar(_)) {
161                throw_unsup_format!("only scalar argument types are support for native calls")
162            }
163            let imm = this.read_immediate(arg)?;
164            libffi_args.push(imm_to_carg(&imm, this)?);
165            // If we are passing a pointer, expose its provenance. Below, all exposed memory
166            // (previously exposed and new exposed) will then be properly prepared.
167            if matches!(arg.layout.ty.kind(), ty::RawPtr(..)) {
168                let ptr = imm.to_scalar().to_pointer(this)?;
169                let Some(prov) = ptr.provenance else {
170                    // Pointer without provenance may not access any memory anyway, skip.
171                    continue;
172                };
173                // The first time this happens, print a warning.
174                if !this.machine.native_call_mem_warned.replace(true) {
175                    // Newly set, so first time we get here.
176                    this.emit_diagnostic(NonHaltingDiagnostic::NativeCallSharedMem);
177                }
178
179                this.expose_provenance(prov)?;
180            }
181        }
182
183        // Prepare all exposed memory.
184        this.prepare_exposed_for_native_call()?;
185
186        // Convert them to `libffi::high::Arg` type.
187        let libffi_args = libffi_args
188            .iter()
189            .map(|arg| arg.arg_downcast())
190            .collect::<Vec<libffi::high::Arg<'_>>>();
191
192        // Call the function and store output, depending on return type in the function signature.
193        let ret = this.call_native_with_args(link_name, dest, code_ptr, libffi_args)?;
194        this.write_immediate(*ret, dest)?;
195        interp_ok(true)
196    }
197}
198
199#[derive(Debug, Clone)]
200/// Enum of supported arguments to external C functions.
201// We introduce this enum instead of just calling `ffi::arg` and storing a list
202// of `libffi::high::Arg` directly, because the `libffi::high::Arg` just wraps a reference
203// to the value it represents: https://docs.rs/libffi/latest/libffi/high/call/struct.Arg.html
204// and we need to store a copy of the value, and pass a reference to this copy to C instead.
205enum CArg {
206    /// 8-bit signed integer.
207    Int8(i8),
208    /// 16-bit signed integer.
209    Int16(i16),
210    /// 32-bit signed integer.
211    Int32(i32),
212    /// 64-bit signed integer.
213    Int64(i64),
214    /// isize.
215    ISize(isize),
216    /// 8-bit unsigned integer.
217    UInt8(u8),
218    /// 16-bit unsigned integer.
219    UInt16(u16),
220    /// 32-bit unsigned integer.
221    UInt32(u32),
222    /// 64-bit unsigned integer.
223    UInt64(u64),
224    /// usize.
225    USize(usize),
226    /// Raw pointer, stored as C's `void*`.
227    RawPtr(*mut std::ffi::c_void),
228}
229
230impl<'a> CArg {
231    /// Convert a `CArg` to a `libffi` argument type.
232    fn arg_downcast(&'a self) -> libffi::high::Arg<'a> {
233        match self {
234            CArg::Int8(i) => ffi::arg(i),
235            CArg::Int16(i) => ffi::arg(i),
236            CArg::Int32(i) => ffi::arg(i),
237            CArg::Int64(i) => ffi::arg(i),
238            CArg::ISize(i) => ffi::arg(i),
239            CArg::UInt8(i) => ffi::arg(i),
240            CArg::UInt16(i) => ffi::arg(i),
241            CArg::UInt32(i) => ffi::arg(i),
242            CArg::UInt64(i) => ffi::arg(i),
243            CArg::USize(i) => ffi::arg(i),
244            CArg::RawPtr(i) => ffi::arg(i),
245        }
246    }
247}
248
249/// Extract the scalar value from the result of reading a scalar from the machine,
250/// and convert it to a `CArg`.
251fn imm_to_carg<'tcx>(v: &ImmTy<'tcx>, cx: &impl HasDataLayout) -> InterpResult<'tcx, CArg> {
252    interp_ok(match v.layout.ty.kind() {
253        // If the primitive provided can be converted to a type matching the type pattern
254        // then create a `CArg` of this primitive value with the corresponding `CArg` constructor.
255        // the ints
256        ty::Int(IntTy::I8) => CArg::Int8(v.to_scalar().to_i8()?),
257        ty::Int(IntTy::I16) => CArg::Int16(v.to_scalar().to_i16()?),
258        ty::Int(IntTy::I32) => CArg::Int32(v.to_scalar().to_i32()?),
259        ty::Int(IntTy::I64) => CArg::Int64(v.to_scalar().to_i64()?),
260        ty::Int(IntTy::Isize) =>
261            CArg::ISize(v.to_scalar().to_target_isize(cx)?.try_into().unwrap()),
262        // the uints
263        ty::Uint(UintTy::U8) => CArg::UInt8(v.to_scalar().to_u8()?),
264        ty::Uint(UintTy::U16) => CArg::UInt16(v.to_scalar().to_u16()?),
265        ty::Uint(UintTy::U32) => CArg::UInt32(v.to_scalar().to_u32()?),
266        ty::Uint(UintTy::U64) => CArg::UInt64(v.to_scalar().to_u64()?),
267        ty::Uint(UintTy::Usize) =>
268            CArg::USize(v.to_scalar().to_target_usize(cx)?.try_into().unwrap()),
269        ty::RawPtr(..) => {
270            let s = v.to_scalar().to_pointer(cx)?.addr();
271            // This relies on the `expose_provenance` in `prepare_for_native_call`.
272            CArg::RawPtr(std::ptr::with_exposed_provenance_mut(s.bytes_usize()))
273        }
274        _ => throw_unsup_format!("unsupported argument type for native call: {}", v.layout.ty),
275    })
276}