Skip to content
Merged
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
12 changes: 12 additions & 0 deletions docs/cli.md
Original file line number Diff line number Diff line change
Expand Up @@ -35,3 +35,15 @@ CLI module caches are separated into `cranelift` and `llvm` subdirectories
under `WASMER_NAPI_CACHE_DIR` (by default, the temporary directory's
`wasmer-napi-cache`). Use a fresh cache root when comparing different Wasmer
source revisions, and warm each guest before measuring steady-state throughput.

## WebAssembly in the guest

Guest JavaScript has V8's `WebAssembly` by default (`WasmPolicy::EnabledUnmetered`):
wasm memories and compiled code are not charged to any N-API limit. Pass
`--restricted-webassembly` to take it away (`WasmPolicy::Restricted`). The
`WebAssembly` global is then absent from the guest's realms, and V8 refuses to
compile wasm in all of them. Options follow the module path:

```sh
./target/release/napi_wasmer guest.wasm --restricted-webassembly
```
20 changes: 11 additions & 9 deletions docs/realms.md
Original file line number Diff line number Diff line change
Expand Up @@ -79,12 +79,15 @@ napi_status unofficial_napi_compile_function(napi_env env, unofficial_napi_realm
| `host_defined_option_id` | yes | yes | no |
| `allow_code_gen_strings` | yes | no | no |
| `own_microtask_queue` | yes | no | no |
| `allow_code_gen_wasm` | no | no | no |
| `allow_code_gen_wasm` | yes | no | no |
| `name`, `origin` | no | no | no |

With `allow_code_gen_strings` false, V8 makes `eval` and the `Function`
constructors throw an `EvalError` in the realm. WebAssembly code
generation stays allowed on V8 (QuickJS has no WebAssembly).
constructors throw an `EvalError` in the realm. With `allow_code_gen_wasm`
false, compiling WebAssembly there throws a `WebAssembly.CompileError`
(QuickJS has no WebAssembly). An env whose embedder chose
`WasmPolicy::Restricted` has no `WebAssembly` global in any realm and
refuses wasm code generation in all of them, whatever the option says.
- **`get_realm`** returns NULL for any object that isn't a realm's global or
sandbox, the env's own global included.
- **`enter_realm` / `leave_realm`:**
Expand Down Expand Up @@ -370,12 +373,11 @@ between the engines:
last copy, and a script it starts in the realm copies the sandbox in
again, over the running script's global writes to the same names.
- host-JS evaluates against the sandbox with `with`.
- **Code generation per realm.** No provider enforces
`allow_code_gen_wasm`. V8 would need an isolate-wide
`AllowWasmCodeGenerationCallback` that reads a per-realm flag, as Node
does. There is also no call to change a realm's code-generation policy
after it is created, which a browser needs because CSP arrives with the
response.
- **Code generation per realm.** Only V8 enforces `allow_code_gen_wasm`,
through an isolate-wide `AllowWasmCodeGenerationCallback` that reads it
from the realm's record, as Node does. There is no call to change a
realm's code-generation policy after it is created, which a browser needs
because CSP arrives with the response.

## History

Expand Down
12 changes: 9 additions & 3 deletions include/unofficial_napi.h
Original file line number Diff line number Diff line change
Expand Up @@ -376,8 +376,10 @@ enum { UNOFFICIAL_NAPI_REALM_OPTIONS_VERSION = 1 };
// - `allow_code_gen_strings`: V8 only. When false, eval and the Function
// constructors throw an EvalError in the realm.
// - `own_microtask_queue`: V8 only.
// - `allow_code_gen_wasm`, `name` and `origin`: no provider. WebAssembly code
// generation stays allowed wherever the engine has WebAssembly.
// - `allow_code_gen_wasm`: V8 only. When false, compiling WebAssembly in the
// realm throws a WebAssembly.CompileError. An env whose embedder restricted
// WebAssembly refuses it in every realm, whatever this option says.
// - `name` and `origin`: no provider.
typedef struct {
uint32_t size;
uint32_t version;
Expand Down Expand Up @@ -820,7 +822,11 @@ NAPI_EXTENSION_WASMER_EXTERN napi_status unofficial_napi_structured_clone(

// Opaque provider-owned message which may cross N-API environments. A message
// is consumed by message_take on both success and failure, or explicitly
// destroyed with message_drop while it is still queued.
// destroyed with message_drop while it is still queued. On V8, an env whose
// embedder restricted WebAssembly refuses a message that carries a
// WebAssembly.Module, or that carries shared memory and comes from an env with
// WebAssembly (it may hold a WebAssembly.Memory); message_take then returns
// napi_pending_exception.
typedef struct unofficial_napi_message__* unofficial_napi_message;

NAPI_EXTENSION_WASMER_EXTERN napi_status unofficial_napi_message_create(
Expand Down
10 changes: 7 additions & 3 deletions src/bin/napi_wasmer.rs
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
use anyhow::{Context, Result, anyhow, bail};
use std::path::{Path, PathBuf};
use wasmer_napi::{
NapiCtx,
NapiCtx, WasmPolicy,
cli::{GuestMount, run_wasix_main_with_ctx},
};

Expand Down Expand Up @@ -282,7 +282,7 @@ fn main() -> Result<()> {
Some(path) => PathBuf::from(path),
None => {
bail!(
"usage: napi_wasmer <wasm-file> [--builtin-js-dir <host-dir>] [--app-dir <host-dir>] [--mount <host-dir>:<guest-dir>] [--env <key>=<value>] [--cwd <guest-dir>] [--program-name <name>] [--] [guest-args...]"
"usage: napi_wasmer <wasm-file> [--builtin-js-dir <host-dir>] [--app-dir <host-dir>] [--mount <host-dir>:<guest-dir>] [--env <key>=<value>] [--cwd <guest-dir>] [--program-name <name>] [--restricted-webassembly] [--] [guest-args...]"
);
}
};
Expand All @@ -298,6 +298,7 @@ fn main() -> Result<()> {
.to_string();
let mut guest_args = Vec::new();
let mut forwarding_guest_args = false;
let mut webassembly = WasmPolicy::EnabledUnmetered;

while let Some(arg) = argv.next() {
if forwarding_guest_args {
Expand All @@ -306,6 +307,9 @@ fn main() -> Result<()> {
}
match arg.as_str() {
"--" => forwarding_guest_args = true,
// Takes V8's WebAssembly away from the guest (see
// `WasmPolicy::Restricted`).
"--restricted-webassembly" => webassembly = WasmPolicy::Restricted,
"--app-dir" => {
let host_dir = argv
.next()
Expand Down Expand Up @@ -383,7 +387,7 @@ fn main() -> Result<()> {
maybe_remap_first_guest_arg_to_app_mount(&mut guest_args, &mut extra_mounts)?;
maybe_add_builtin_mounts(&mut extra_mounts, builtin_js_dir)?;

let ctx = NapiCtx::default();
let ctx = NapiCtx::builder().webassembly(webassembly).build();
let exit_code = run_wasix_main_with_ctx(
&ctx,
&wasm_path,
Expand Down
113 changes: 112 additions & 1 deletion src/ctx.rs
Original file line number Diff line number Diff line change
Expand Up @@ -32,10 +32,60 @@ impl NapiLimits {
}
}

/// Whether JavaScript in guest environments can use V8's `WebAssembly`.
///
/// Guest environments allocate V8 array buffers in the guest's linear memory,
/// where they count against the context's memory budget. V8 does not allocate
/// WebAssembly memories and compiled wasm code that way: they come from V8's
/// page allocator, outside the guest heap and outside every limit this crate
/// enforces.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
#[non_exhaustive]
pub enum WasmPolicy {
/// No `WebAssembly` in guest environments. The global is absent from an
/// environment's own realm and from every realm made in it (`vm`
/// contexts), and V8 refuses to compile wasm in all of them, also in
/// realms V8 makes on its own, such as `ShadowRealm`s. asm.js still runs,
/// as ordinary JavaScript: V8 no longer translates it to wasm.
///
/// The host-JavaScript backend runs guest JavaScript with the host's own
/// `WebAssembly` and cannot remove it, so environment creation fails
/// there under this policy.
Restricted,
/// V8's `WebAssembly` as the engine ships it, **without resource
/// accounting** (the default).
///
/// Guest JavaScript can make V8 reserve address space for wasm memories
/// (by default 4 GiB for each 32-bit memory without a declared maximum)
/// and commit memory as they grow, compile and commit executable wasm
/// code, also on V8 background threads, and use compiler working memory
/// that grows with the module size. None of it is charged to
/// [`NapiLimits::total_memory_bytes`], to a [`NapiMemoryAccountant`] or to
/// any other limit of the context; only process-wide V8 flags bound it.
/// It also exposes V8's wasm compilers to guest code.
///
/// Realms follow their own `allow_code_gen_wasm` option (`vm`'s
/// `codeGeneration.wasm`).
#[default]
EnabledUnmetered,
}

impl WasmPolicy {
/// The value passed to the native bridge; `NapiWebAssemblyPolicy` in
/// `v8/src/internal/napi_wasm_policy.h`.
pub(crate) const fn bridge_code(self) -> u32 {
match self {
Self::Restricted => 0,
Self::EnabledUnmetered => 1,
}
}
}

#[derive(Default)]
pub struct NapiCtxBuilder {
limits: NapiLimits,
accountant: Option<Arc<dyn NapiMemoryAccountant>>,
webassembly: WasmPolicy,
}

#[derive(Clone, Debug)]
Expand Down Expand Up @@ -121,6 +171,7 @@ impl NapiRuntimeControl {
#[derive(Debug)]
struct NapiCtxInner {
limits: NapiLimits,
webassembly: WasmPolicy,
active_sessions: AtomicUsize,
/// One shared accountant per app, `Arc`-shared into the engine's budgeted
/// tunables (guest wasm linear memory) and, in later phases, the V8 heap,
Expand Down Expand Up @@ -183,6 +234,15 @@ impl NapiCtxBuilder {
self
}

/// Whether guest JavaScript can use V8's `WebAssembly` (default:
/// [`WasmPolicy::EnabledUnmetered`], which no limit of this context
/// covers). Applies to every environment a guest creates through this
/// context, including those of its WASIX worker threads.
pub fn webassembly(mut self, policy: WasmPolicy) -> Self {
self.webassembly = policy;
self
}

pub fn build(self) -> NapiCtx {
let budget = match self.accountant {
Some(accountant) => ResourceBudget::with_accountant(accountant),
Expand All @@ -194,6 +254,7 @@ impl NapiCtxBuilder {
NapiCtx {
inner: Arc::new(NapiCtxInner {
limits: self.limits,
webassembly: self.webassembly,
active_sessions: AtomicUsize::new(0),
budget,
envs: Arc::new(Mutex::new(crate::env::EnvRegistry::default())),
Expand All @@ -218,6 +279,11 @@ impl NapiCtx {
&self.inner.limits
}

/// The WebAssembly policy of this context's guest environments.
pub fn webassembly_policy(&self) -> WasmPolicy {
self.inner.webassembly
}

pub fn active_sessions(&self) -> usize {
self.inner.active_sessions.load(Ordering::Acquire)
}
Expand Down Expand Up @@ -401,12 +467,13 @@ impl NapiSession {
fn add_imports(&self, store: &mut StoreMut<'_>, import_object: &mut Imports) -> Result<()> {
register_env_imports(store, import_object);

let napi_env = NapiEnv::new(
let mut napi_env = NapiEnv::new(
Arc::clone(&self.inner.ctx.budget),
self.inner.ctx.limits.max_envs,
Arc::clone(&self.inner.ctx.envs),
Arc::clone(&self.inner.ctx.host_stopped),
);
napi_env.webassembly = self.inner.ctx.webassembly;
let func_env = FunctionEnv::new(store, napi_env);
{
let mut guard = self
Expand Down Expand Up @@ -657,6 +724,50 @@ mod tests {
.expect("configure instance A");
}

#[test]
fn webassembly_policy_reaches_every_store_env() {
assert_eq!(
super::WasmPolicy::default(),
super::WasmPolicy::EnabledUnmetered
);
// NapiWebAssemblyPolicy in v8/src/internal/napi_wasm_policy.h.
assert_eq!(super::WasmPolicy::Restricted.bridge_code(), 0);
assert_eq!(super::WasmPolicy::EnabledUnmetered.bridge_code(), 1);

let mut store = Store::default();
let module = compile_wat(
&store,
r#"(module
(import "napi" "napi_get_undefined" (func (param i32 i32) (result i32)))
(import "env" "memory" (memory 1 512))
)"#,
);
for policy in [
super::WasmPolicy::Restricted,
super::WasmPolicy::EnabledUnmetered,
] {
let ctx = NapiCtx::builder().webassembly(policy).build();
assert_eq!(ctx.webassembly_policy(), policy);
let hooks = ctx.runtime_hooks();
// Each store (a guest's and each of its WASIX threads') gets the
// context's policy.
for _ in 0..2 {
let (_imports, state) = hooks
.additional_imports(&module, &mut store.as_store_mut())
.expect("imports register");
let session = state.session.expect("an N-API module has a session");
let func_env = session
.inner
.func_env
.lock()
.unwrap()
.clone()
.expect("imports made the function env");
assert_eq!(func_env.as_ref(&store).webassembly, policy);
}
}
}

#[test]
fn configure_instance_rejects_missing_state() {
let mut store = Store::default();
Expand Down
4 changes: 4 additions & 0 deletions src/env.rs
Original file line number Diff line number Diff line change
Expand Up @@ -117,6 +117,9 @@ pub(crate) struct NapiEnv {
pub(crate) budget: Arc<ResourceBudget>,
/// Per-app cap on live V8 isolates (`None` = unlimited).
pub(crate) max_envs: Option<usize>,
/// The embedder's policy for V8 `WebAssembly` in the envs this store
/// creates.
pub(crate) webassembly: crate::WasmPolicy,
env_registry: Arc<std::sync::Mutex<EnvRegistry>>,
host_stopped: Arc<AtomicBool>,
/// Heap charge per live V8 env, keyed by guest env id, so teardown releases
Expand Down Expand Up @@ -205,6 +208,7 @@ impl NapiEnv {
Self {
budget,
max_envs,
webassembly: crate::WasmPolicy::default(),
env_registry,
host_stopped,
env_heap_charges: HashMap::new(),
Expand Down
13 changes: 12 additions & 1 deletion src/guest/napi.rs
Original file line number Diff line number Diff line change
Expand Up @@ -37,6 +37,7 @@ fn guest_napi_wasm_init_env(mut env: FunctionEnvMut<NapiEnv>) -> i32 {
};

let guest_heap_ctx = guest_heap_alloc_ctx(&env);
let webassembly_policy = env.data().webassembly.bridge_code();
let mut snapi_env_state: SnapiEnv = std::ptr::null_mut();
let status = if reservation.clamped {
unsafe {
Expand All @@ -49,11 +50,19 @@ fn guest_napi_wasm_init_env(mut env: FunctionEnvMut<NapiEnv>) -> i32 {
reservation.code_range,
0,
guest_heap_ctx,
webassembly_policy,
&mut snapi_env_state,
)
}
} else {
unsafe { snapi_bridge_unofficial_create_env(8, guest_heap_ctx, &mut snapi_env_state) }
unsafe {
snapi_bridge_unofficial_create_env(
8,
guest_heap_ctx,
webassembly_policy,
&mut snapi_env_state,
)
}
};
if status != 0 || snapi_env_state.is_null() {
env.data().abort_isolate(&reservation);
Expand Down Expand Up @@ -250,6 +259,7 @@ fn guest_unofficial_napi_create_env(
};

let guest_heap_ctx = guest_heap_alloc_ctx(&env);
let webassembly_policy = env.data().webassembly.bridge_code();
let mut snapi_env_state: SnapiEnv = std::ptr::null_mut();
let status = unsafe {
snapi_bridge_unofficial_create_env_with_options(
Expand All @@ -261,6 +271,7 @@ fn guest_unofficial_napi_create_env(
reservation.code_range,
stack_limit,
guest_heap_ctx,
webassembly_policy,
&mut snapi_env_state,
)
};
Expand Down
13 changes: 11 additions & 2 deletions src/guest/napi_js.rs
Original file line number Diff line number Diff line change
Expand Up @@ -44,9 +44,16 @@ fn guest_napi_wasm_init_env(mut env: FunctionEnvMut<NapiEnv>) -> i32 {
return env_id as i32;
}

let webassembly_policy = env.data().webassembly.bridge_code();
let mut snapi_env_state: SnapiEnv = std::ptr::null_mut();
let status =
unsafe { snapi_bridge_unofficial_create_env(8, std::ptr::null(), &mut snapi_env_state) };
let status = unsafe {
snapi_bridge_unofficial_create_env(
8,
std::ptr::null(),
webassembly_policy,
&mut snapi_env_state,
)
};
if status != 0 || snapi_env_state.is_null() {
return 0;
}
Expand Down Expand Up @@ -522,6 +529,7 @@ fn guest_unofficial_napi_create_env(
(0, 0, 0, 0, 0, 0)
};

let webassembly_policy = env.data().webassembly.bridge_code();
let mut snapi_env_state: SnapiEnv = std::ptr::null_mut();
let status = unsafe {
snapi_bridge_unofficial_create_env_with_options(
Expand All @@ -533,6 +541,7 @@ fn guest_unofficial_napi_create_env(
code_range_size_in_bytes,
stack_limit,
std::ptr::null(),
webassembly_policy,
&mut snapi_env_state,
)
};
Expand Down
Loading
Loading