Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -220,6 +220,7 @@ degree documented below):
- `solaris` / `illumos`: maintained by @devnexen. Supports the entire test suite.
- `freebsd`: maintained by @YohDeadfall and @LorrensP-2158466. Supports the entire test suite.
- `android`: **maintainer wanted**. Support very incomplete, but a basic "hello world" works.
- `wasi`: **maintainer wanted**. Support very incomplete, but a basic "hello world" works.
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Are you willing to be listed as target maintainer for this?
I don't think I want to re-land this without a target maintainer.

- For targets on other operating systems, Miri might fail before even reaching the `main` function.

However, even for targets that we do support, the degree of support for accessing platform APIs
Expand Down
1 change: 1 addition & 0 deletions ci/ci.sh
Original file line number Diff line number Diff line change
Expand Up @@ -153,6 +153,7 @@ case $HOST_TARGET in
BASIC="empty_main integer heap_alloc libc-mem vec string btreemap" # ensures we have the basics: pre-main code, system allocator
UNIX="hello panic/panic panic/unwind concurrency/simple atomic libc-mem libc-misc libc-random env num_cpus" # the things that are very similar across all Unixes, and hence easily supported there
TEST_TARGET=aarch64-linux-android run_tests_minimal $BASIC $UNIX time hashmap random thread sync concurrency epoll eventfd
TEST_TARGET=wasm32-wasip2 run_tests_minimal $BASIC hello wasm
TEST_TARGET=wasm32-unknown-unknown run_tests_minimal no_std empty_main wasm # this target doesn't really have std
TEST_TARGET=thumbv7em-none-eabihf run_tests_minimal no_std
;;
Expand Down
10 changes: 9 additions & 1 deletion src/machine.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1244,7 +1244,15 @@ impl<'tcx> Machine<'tcx> for MiriMachine<'tcx> {
// Any needed call to `goto_block` will be performed by `emulate_foreign_item`.
let args = ecx.copy_fn_args(args); // FIXME: Should `InPlace` arguments be reset to uninit?
let link_name = Symbol::intern(ecx.tcx.symbol_name(instance).name);
return ecx.emulate_foreign_item(link_name, abi, &args, dest, ret, unwind);
return ecx.emulate_foreign_item(
Some(instance),
link_name,
abi,
&args,
dest,
ret,
unwind,
);
}

if ecx.machine.data_race.as_genmc_ref().is_some()
Expand Down
2 changes: 1 addition & 1 deletion src/shims/env.rs
Original file line number Diff line number Diff line change
Expand Up @@ -51,7 +51,7 @@ impl<'tcx> EnvVars<'tcx> {
} else if ecx.tcx.sess.target.os == "windows" {
EnvVars::Windows(WindowsEnvVars::new(ecx, env_vars)?)
} else {
// For "none" targets (i.e., without an OS).
// For "none" targets (i.e., without an OS), and wasi.
EnvVars::Uninit
};
ecx.machine.env_vars = env_vars;
Expand Down
11 changes: 9 additions & 2 deletions src/shims/foreign_items.rs
Original file line number Diff line number Diff line change
Expand Up @@ -43,6 +43,7 @@ pub trait EvalContextExt<'tcx>: crate::MiriInterpCxExt<'tcx> {
/// is delegated to another function.
fn emulate_foreign_item(
&mut self,
instance: Option<Instance<'tcx>>,
link_name: Symbol,
abi: &FnAbi<'tcx, Ty<'tcx>>,
args: &[OpTy<'tcx>],
Expand Down Expand Up @@ -73,7 +74,7 @@ pub trait EvalContextExt<'tcx>: crate::MiriInterpCxExt<'tcx> {
let dest = this.force_allocation(dest)?;

// The rest either implements the logic, or falls back to `lookup_exported_symbol`.
match this.emulate_foreign_item_inner(link_name, abi, args, &dest)? {
match this.emulate_foreign_item_inner(instance, link_name, abi, args, &dest)? {
EmulateItemResult::NeedsReturn => {
trace!("{:?}", this.dump_place(&dest.clone().into()));
this.return_to_block(ret)?;
Expand Down Expand Up @@ -102,6 +103,7 @@ pub trait EvalContextExt<'tcx>: crate::MiriInterpCxExt<'tcx> {
let this = self.eval_context_ref();
match this.tcx.sess.target.os.as_ref() {
os if this.target_os_is_unix() => shims::unix::foreign_items::is_dyn_sym(name, os),
"wasi" => shims::wasi::foreign_items::is_dyn_sym(name),
"windows" => shims::windows::foreign_items::is_dyn_sym(name),
_ => false,
}
Expand All @@ -117,7 +119,7 @@ pub trait EvalContextExt<'tcx>: crate::MiriInterpCxExt<'tcx> {
ret: Option<mir::BasicBlock>,
unwind: mir::UnwindAction,
) -> InterpResult<'tcx> {
let res = self.emulate_foreign_item(sym.0, abi, args, dest, ret, unwind)?;
let res = self.emulate_foreign_item(None, sym.0, abi, args, dest, ret, unwind)?;
assert!(res.is_none(), "DynSyms that delegate are not supported");
interp_ok(())
}
Expand Down Expand Up @@ -247,6 +249,7 @@ impl<'tcx> EvalContextExtPriv<'tcx> for crate::MiriInterpCx<'tcx> {}
trait EvalContextExtPriv<'tcx>: crate::MiriInterpCxExt<'tcx> {
fn emulate_foreign_item_inner(
&mut self,
instance: Option<Instance<'tcx>>,
link_name: Symbol,
abi: &FnAbi<'tcx, Ty<'tcx>>,
args: &[OpTy<'tcx>],
Expand Down Expand Up @@ -845,6 +848,10 @@ trait EvalContextExtPriv<'tcx>: crate::MiriInterpCxExt<'tcx> {
shims::unix::foreign_items::EvalContextExt::emulate_foreign_item_inner(
this, link_name, abi, args, dest,
),
"wasi" =>
shims::wasi::foreign_items::EvalContextExt::emulate_foreign_item_inner(
this, instance, link_name, abi, args, dest,
),
"windows" =>
shims::windows::foreign_items::EvalContextExt::emulate_foreign_item_inner(
this, link_name, abi, args, dest,
Expand Down
1 change: 1 addition & 0 deletions src/shims/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ mod math;
#[cfg(all(unix, feature = "native-lib"))]
mod native_lib;
mod unix;
mod wasi;
mod windows;
mod x86;

Expand Down
1 change: 1 addition & 0 deletions src/shims/tls.rs
Original file line number Diff line number Diff line change
Expand Up @@ -253,6 +253,7 @@ impl<'tcx> TlsDtorsState<'tcx> {
}
_ => {
// No TLS dtor support.
// FIXME: should we do something on wasi?
break 'new_state Done;
}
}
Expand Down
135 changes: 135 additions & 0 deletions src/shims/wasi/foreign_items.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,135 @@
use rustc_abi::CanonAbi;
use rustc_middle::ty::{Instance, Ty};
use rustc_span::Symbol;
use rustc_target::callconv::FnAbi;

use crate::shims::alloc::EvalContextExt as _;
use crate::*;

pub fn is_dyn_sym(_name: &str) -> bool {
false
}

impl<'tcx> EvalContextExt<'tcx> for crate::MiriInterpCx<'tcx> {}
pub trait EvalContextExt<'tcx>: crate::MiriInterpCxExt<'tcx> {
fn emulate_foreign_item_inner(
&mut self,
instance: Option<Instance<'tcx>>,
link_name: Symbol,
abi: &FnAbi<'tcx, Ty<'tcx>>,
args: &[OpTy<'tcx>],
dest: &MPlaceTy<'tcx>,
) -> InterpResult<'tcx, EmulateItemResult> {
let this = self.eval_context_mut();

let (interface, name) = if let Some(instance) = instance
&& let Some(module) =
this.tcx.wasm_import_module_map(instance.def_id().krate).get(&instance.def_id())
Copy link
Member

@RalfJung RalfJung Nov 4, 2025

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

FWIW I think it is a bug in rustc that link_name returns the wrong name here... link_name should return whatever is necessary to find the symbol to link to. Apparently that's a tuple of two names for some targets -- fine. But instead we return a single name that's sometimes one component of that tuple, and sometimes completely irrelevant to linking, and then one needs to use out-of-band mechanisms to get the actual tuple -- that's not a good way to deal with this IMO.

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

With core wasm the import name is a tuple of two names. However for the linking tool convention the symbol name used for resolving symbols within the linker session is entirely separate from the name used for importing items from outside the final linked wasm module. The symbol name is ignored after linking, while the import name tuple is used at runtime. Rustc's link_name returns the symbol name, while this code computes the import name tuple.

Copy link
Member

@RalfJung RalfJung Nov 4, 2025

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Rustc's link_name returns the symbol name, while this code computes the import name tuple.

That's at best very confusing. I would expect that query to return the information about what symbol this links to (what I would call the "link name", and what wasm apparently calls "import name"). Apparently we don't have any query that returns this information, instead every backend duplicates this logic?

As you said elsewhere, this isn't even wasm-specific. Windows also uses a tuple for names, IIUC.

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

For Windows we also use the link name and there is no option to use the import name. The import library is what defines the mapping from link name to dll name + import name. So the linker only sees the symbol name (as returned by tcx.symbol_name() in rustc) when resolving symbols. On wasm the symbol table directly contains the import name tuple rather than putting it in a separate file, but I believe the linker still only matches on the symbol name and handles the imports later.

(I don't think wasm formally uses symbol name/import name. I made this naming scheme up to help describe what I meant)

{
// Adapted from https://github.com/rust-lang/rust/blob/90b65889799733f21ebdf59d96411aa531c5900a/compiler/rustc_codegen_llvm/src/attributes.rs#L549-L562
let codegen_fn_attrs = this.tcx.codegen_instance_attrs(instance.def);
let name = codegen_fn_attrs
.symbol_name
.unwrap_or_else(|| this.tcx.item_name(instance.def_id()));

// According to the component model, the version should be matched as semver, but for
// simplicity we strip the version entirely for now. Once we support wasm-wasip3 it may
// become actually important to match on the version, but for now it shouldn't matter.
let (interface, _version) = module
.split_once('@')
.ok_or_else(|| err_unsup_format!("module name {module} must contain a version"))?;

(Some(interface), name)
} else {
// This item is provided by wasi-libc, not imported from the wasi runtime
(None, link_name)
};

match (interface, name.as_str()) {
// Allocation
(None, "posix_memalign") => {
let [memptr, align, size] =
this.check_shim_sig_lenient(abi, CanonAbi::C, link_name, args)?;
let result = this.posix_memalign(memptr, align, size)?;
this.write_scalar(result, dest)?;
}
(None, "aligned_alloc") => {
let [align, size] =
this.check_shim_sig_lenient(abi, CanonAbi::C, link_name, args)?;
let res = this.aligned_alloc(align, size)?;
this.write_pointer(res, dest)?;
}

// Standard input/output
// FIXME: These shims are hacks that just get basic stdout/stderr working. We can't
// constrain them to "std" since std itself uses the wasi crate for this.
(Some("wasi:cli/stdout"), "get-stdout") => {
let [] =
this.check_shim_sig(shim_sig!(extern "C" fn() -> i32), link_name, abi, args)?;
this.write_scalar(Scalar::from_i32(1), dest)?; // POSIX FD number for stdout
}
(Some("wasi:cli/stderr"), "get-stderr") => {
let [] =
this.check_shim_sig(shim_sig!(extern "C" fn() -> i32), link_name, abi, args)?;
this.write_scalar(Scalar::from_i32(2), dest)?; // POSIX FD number for stderr
}
(Some("wasi:io/streams"), "[resource-drop]output-stream") => {
let [handle] =
this.check_shim_sig(shim_sig!(extern "C" fn(i32) -> ()), link_name, abi, args)?;
let handle = this.read_scalar(handle)?.to_i32()?;

if !(handle == 1 || handle == 2) {
throw_unsup_format!("wasm output-stream: unsupported handle");
}
// We don't actually close these FDs, so this is a NOP.
}
(Some("wasi:io/streams"), "[method]output-stream.blocking-write-and-flush") => {
let [handle, buf, len, ret_area] = this.check_shim_sig(
shim_sig!(extern "C" fn(i32, *mut _, usize, *mut _) -> ()),
link_name,
abi,
args,
)?;
let handle = this.read_scalar(handle)?.to_i32()?;
let buf = this.read_pointer(buf)?;
let len = this.read_target_usize(len)?;
let ret_area = this.read_pointer(ret_area)?;

if len > 4096 {
throw_unsup_format!(
"wasm output-stream.blocking-write-and-flush: buffer too big"
);
}
let len = usize::try_from(len).unwrap();
let Some(fd) = this.machine.fds.get(handle) else {
throw_unsup_format!(
"wasm output-stream.blocking-write-and-flush: unsupported handle"
);
};
fd.write(
this.machine.communicate(),
buf,
len,
this,
callback!(
@capture<'tcx> {
len: usize,
ret_area: Pointer,
}
|this, result: Result<usize, IoError>| {
if !matches!(result, Ok(l) if l == len) {
throw_unsup_format!("wasm output-stream.blocking-write-and-flush: returning errors is not supported");
}
// 0 in the first byte of the ret_area indicates success.
let ret = this.ptr_to_mplace(ret_area, this.machine.layouts.u8);
this.write_null(&ret)?;
interp_ok(())
}),
)?;
}

_ => return interp_ok(EmulateItemResult::NotSupported),
}
interp_ok(EmulateItemResult::NeedsReturn)
}
}
1 change: 1 addition & 0 deletions src/shims/wasi/mod.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
pub mod foreign_items;