Skip to content

Commit d55a99a

Browse files
authored
Merge pull request #4372 from nia-e/multiple-native-libs
native-lib: allow multiple libraries and/or dirs
2 parents 9a7255e + 80a95b7 commit d55a99a

File tree

7 files changed

+70
-57
lines changed

7 files changed

+70
-57
lines changed

src/tools/miri/README.md

Lines changed: 4 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -398,9 +398,11 @@ to Miri failing to detect cases of undefined behavior in a program.
398398
**unsound** since the fallback body might not be checking for all UB.
399399
* `-Zmiri-native-lib=<path to a shared object file>` is an experimental flag for providing support
400400
for calling native functions from inside the interpreter via FFI. The flag is supported only on
401-
Unix systems. Functions not provided by that file are still executed via the usual Miri shims.
401+
Unix systems. Functions not provided by that file are still executed via the usual Miri shims. If
402+
a path to a directory is specified, all files in that directory are included nonrecursively. This
403+
flag can be passed multiple times to specify multiple files and/or directories.
402404
**WARNING**: If an invalid/incorrect `.so` file is specified, this can cause Undefined Behavior in
403-
Miri itself! And of course, Miri cannot do any checks on the actions taken by the native code.
405+
Miri itself! And of course, Miri often cannot do any checks on the actions taken by the native code.
404406
Note that Miri has its own handling of file descriptors, so if you want to replace *some*
405407
functions working on file descriptors, you will have to replace *all* of them, or the two kinds of
406408
file descriptors will be mixed up. This is **work in progress**; currently, only integer and

src/tools/miri/src/alloc_addresses/mod.rs

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -132,7 +132,7 @@ trait EvalContextExtPriv<'tcx>: crate::MiriInterpCxExt<'tcx> {
132132
assert!(!matches!(info.kind, AllocKind::Dead));
133133

134134
// This allocation does not have a base address yet, pick or reuse one.
135-
if this.machine.native_lib.is_some() {
135+
if !this.machine.native_lib.is_empty() {
136136
// In native lib mode, we use the "real" address of the bytes for this allocation.
137137
// This ensures the interpreted program and native code have the same view of memory.
138138
let params = this.machine.get_default_alloc_params();
@@ -413,7 +413,7 @@ pub trait EvalContextExt<'tcx>: crate::MiriInterpCxExt<'tcx> {
413413
) -> InterpResult<'tcx, MiriAllocBytes> {
414414
let this = self.eval_context_ref();
415415
assert!(this.tcx.try_get_global_alloc(id).is_some());
416-
if this.machine.native_lib.is_some() {
416+
if !this.machine.native_lib.is_empty() {
417417
// In native lib mode, MiriAllocBytes for global allocations are handled via `prepared_alloc_bytes`.
418418
// This additional call ensures that some `MiriAllocBytes` are always prepared, just in case
419419
// this function gets called before the first time `addr_from_alloc_id` gets called.

src/tools/miri/src/bin/miri.rs

Lines changed: 13 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -692,11 +692,18 @@ fn main() {
692692
};
693693
} else if let Some(param) = arg.strip_prefix("-Zmiri-native-lib=") {
694694
let filename = param.to_string();
695-
if std::path::Path::new(&filename).exists() {
696-
if let Some(other_filename) = miri_config.native_lib {
697-
show_error!("-Zmiri-native-lib is already set to {}", other_filename.display());
695+
let file_path = std::path::Path::new(&filename);
696+
if file_path.exists() {
697+
// For directories, nonrecursively add all normal files inside
698+
if let Ok(dir) = file_path.read_dir() {
699+
for lib in dir.filter_map(|res| res.ok()) {
700+
if lib.file_type().unwrap().is_file() {
701+
miri_config.native_lib.push(lib.path().to_owned());
702+
}
703+
}
704+
} else {
705+
miri_config.native_lib.push(filename.into());
698706
}
699-
miri_config.native_lib = Some(filename.into());
700707
} else {
701708
show_error!("-Zmiri-native-lib `{}` does not exist", filename);
702709
}
@@ -731,12 +738,12 @@ fn main() {
731738
"Tree Borrows does not support integer-to-pointer casts, and hence requires strict provenance"
732739
);
733740
}
734-
if miri_config.native_lib.is_some() {
741+
if !miri_config.native_lib.is_empty() {
735742
show_error!("Tree Borrows is not compatible with calling native functions");
736743
}
737744
}
738745
// Native calls and strict provenance are not compatible.
739-
if miri_config.native_lib.is_some() && miri_config.provenance_mode == ProvenanceMode::Strict {
746+
if !miri_config.native_lib.is_empty() && miri_config.provenance_mode == ProvenanceMode::Strict {
740747
show_error!("strict provenance is not compatible with calling native functions");
741748
}
742749
// You can set either one seed or many.

src/tools/miri/src/eval.rs

Lines changed: 3 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -148,9 +148,8 @@ pub struct MiriConfig {
148148
pub report_progress: Option<u32>,
149149
/// Whether Stacked Borrows and Tree Borrows retagging should recurse into fields of datatypes.
150150
pub retag_fields: RetagFields,
151-
/// The location of a shared object file to load when calling external functions
152-
/// FIXME! consider allowing users to specify paths to multiple files, or to a directory
153-
pub native_lib: Option<PathBuf>,
151+
/// The location of the shared object files to load when calling external functions
152+
pub native_lib: Vec<PathBuf>,
154153
/// Run a garbage collector for BorTags every N basic blocks.
155154
pub gc_interval: u32,
156155
/// The number of CPUs to be reported by miri.
@@ -197,7 +196,7 @@ impl Default for MiriConfig {
197196
preemption_rate: 0.01, // 1%
198197
report_progress: None,
199198
retag_fields: RetagFields::Yes,
200-
native_lib: None,
199+
native_lib: vec![],
201200
gc_interval: 10_000,
202201
num_cpus: 1,
203202
page_size: None,

src/tools/miri/src/machine.rs

Lines changed: 7 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -558,9 +558,9 @@ pub struct MiriMachine<'tcx> {
558558

559559
/// Handle of the optional shared object file for native functions.
560560
#[cfg(unix)]
561-
pub native_lib: Option<(libloading::Library, std::path::PathBuf)>,
561+
pub native_lib: Vec<(libloading::Library, std::path::PathBuf)>,
562562
#[cfg(not(unix))]
563-
pub native_lib: Option<!>,
563+
pub native_lib: Vec<!>,
564564

565565
/// Run a garbage collector for BorTags every N basic blocks.
566566
pub(crate) gc_interval: u32,
@@ -720,7 +720,7 @@ impl<'tcx> MiriMachine<'tcx> {
720720
extern_statics: FxHashMap::default(),
721721
rng: RefCell::new(rng),
722722
#[cfg(target_os = "linux")]
723-
allocator: if config.native_lib.is_some() {
723+
allocator: if !config.native_lib.is_empty() {
724724
Some(Rc::new(RefCell::new(crate::alloc::isolated_alloc::IsolatedAlloc::new())))
725725
} else { None },
726726
tracked_alloc_ids: config.tracked_alloc_ids.clone(),
@@ -732,7 +732,7 @@ impl<'tcx> MiriMachine<'tcx> {
732732
basic_block_count: 0,
733733
monotonic_clock: MonotonicClock::new(config.isolated_op == IsolatedOp::Allow),
734734
#[cfg(unix)]
735-
native_lib: config.native_lib.as_ref().map(|lib_file_path| {
735+
native_lib: config.native_lib.iter().map(|lib_file_path| {
736736
let host_triple = rustc_session::config::host_tuple();
737737
let target_triple = tcx.sess.opts.target_triple.tuple();
738738
// Check if host target == the session target.
@@ -752,11 +752,11 @@ impl<'tcx> MiriMachine<'tcx> {
752752
},
753753
lib_file_path.clone(),
754754
)
755-
}),
755+
}).collect(),
756756
#[cfg(not(unix))]
757-
native_lib: config.native_lib.as_ref().map(|_| {
757+
native_lib: config.native_lib.iter().map(|_| {
758758
panic!("calling functions from native libraries via FFI is only supported on Unix")
759-
}),
759+
}).collect(),
760760
gc_interval: config.gc_interval,
761761
since_gc: 0,
762762
num_cpus: config.num_cpus,

src/tools/miri/src/shims/foreign_items.rs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -238,7 +238,7 @@ trait EvalContextExtPriv<'tcx>: crate::MiriInterpCxExt<'tcx> {
238238

239239
// First deal with any external C functions in linked .so file.
240240
#[cfg(unix)]
241-
if this.machine.native_lib.as_ref().is_some() {
241+
if !this.machine.native_lib.is_empty() {
242242
use crate::shims::native_lib::EvalContextExt as _;
243243
// An Ok(false) here means that the function being called was not exported
244244
// by the specified `.so` file; we should continue and check if it corresponds to

src/tools/miri/src/shims/native_lib.rs

Lines changed: 40 additions & 35 deletions
Original file line numberDiff line numberDiff line change
@@ -87,47 +87,52 @@ trait EvalContextExtPriv<'tcx>: crate::MiriInterpCxExt<'tcx> {
8787
}
8888

8989
/// 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.
90+
/// if it exists. The function must be in one of the shared object files specified:
91+
/// we do *not* return pointers to functions in dependencies of libraries.
9292
fn get_func_ptr_explicitly_from_lib(&mut self, link_name: Symbol) -> Option<CodePtr> {
9393
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;
94+
// Try getting the function from one of the shared libraries.
95+
for (lib, lib_path) in &this.machine.native_lib {
96+
let Ok(func): Result<libloading::Symbol<'_, unsafe extern "C" fn()>, _> =
97+
(unsafe { lib.get(link_name.as_str().as_bytes()) })
98+
else {
99+
continue;
100+
};
101+
#[expect(clippy::as_conversions)] // fn-ptr to raw-ptr cast needs `as`.
102+
let fn_ptr = *func.deref() as *mut std::ffi::c_void;
100103

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;
104+
// FIXME: this is a hack!
105+
// The `libloading` crate will automatically load system libraries like `libc`.
106+
// On linux `libloading` is based on `dlsym`: https://docs.rs/libloading/0.7.3/src/libloading/os/unix/mod.rs.html#202
107+
// and `dlsym`(https://linux.die.net/man/3/dlsym) looks through the dependency tree of the
108+
// library if it can't find the symbol in the library itself.
109+
// So, in order to check if the function was actually found in the specified
110+
// `machine.external_so_lib` we need to check its `dli_fname` and compare it to
111+
// the specified SO file path.
112+
// This code is a reimplementation of the mechanism for getting `dli_fname` in `libloading`,
113+
// from: https://docs.rs/libloading/0.7.3/src/libloading/os/unix/mod.rs.html#411
114+
// using the `libc` crate where this interface is public.
115+
let mut info = std::mem::MaybeUninit::<libc::Dl_info>::zeroed();
116+
unsafe {
117+
if libc::dladdr(fn_ptr, info.as_mut_ptr()) != 0 {
118+
let info = info.assume_init();
119+
#[cfg(target_os = "cygwin")]
120+
let fname_ptr = info.dli_fname.as_ptr();
121+
#[cfg(not(target_os = "cygwin"))]
122+
let fname_ptr = info.dli_fname;
123+
assert!(!fname_ptr.is_null());
124+
if std::ffi::CStr::from_ptr(fname_ptr).to_str().unwrap()
125+
!= lib_path.to_str().unwrap()
126+
{
127+
return None;
128+
}
125129
}
126130
}
127-
}
128131

129-
// Return a pointer to the function.
130-
Some(CodePtr(fn_ptr))
132+
// Return a pointer to the function.
133+
return Some(CodePtr(fn_ptr));
134+
}
135+
None
131136
}
132137
}
133138

0 commit comments

Comments
 (0)