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