Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Remove use of shared mutable static #854

Merged
merged 1 commit into from
Dec 5, 2024
Merged
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
36 changes: 17 additions & 19 deletions crates/cli/src/codegen/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -33,12 +33,6 @@
//! as well as ensuring that any features available in the plugin match the
//! features requsted by the JavaScript bytecode.

// Wizer doesn't provide a good API to set a custom WASI context so we put our
// WASI context in a static global variable and instruct the closure for
// getting the WASI context to use a mutable reference to it. There are never
// concurrent mutable references to the static WASI context so this is safe.
#![allow(static_mut_refs)]

mod builder;
use std::{fs, rc::Rc, sync::OnceLock};

Expand All @@ -52,14 +46,14 @@ use transform::SourceCodeSection;
use walrus::{
DataId, DataKind, ExportItem, FunctionBuilder, FunctionId, LocalId, MemoryId, Module, ValType,
};
use wasi_common::{pipe::ReadPipe, sync::WasiCtxBuilder, WasiCtx};
use wasm_opt::{OptimizationOptions, ShrinkLevel};
use wasmtime_wasi::{pipe::MemoryInputPipe, WasiCtxBuilder};
use wizer::{Linker, Wizer};

use crate::{js_config::JsConfig, plugins::Plugin, JS};
use anyhow::Result;

static mut WASI: OnceLock<WasiCtx> = OnceLock::new();
static STDIN_PIPE: OnceLock<MemoryInputPipe> = OnceLock::new();

pub(crate) enum CodeGenType {
/// Static code generation.
Expand Down Expand Up @@ -147,21 +141,25 @@ impl Generator {
CodeGenType::Static => {
// Copy config JSON into stdin for `initialize_runtime` function.
let runtime_config = self.js_runtime_config.to_json()?;
unsafe {
WASI.get_or_init(|| {
WasiCtxBuilder::new()
.inherit_stderr()
.inherit_stdout()
.stdin(Box::new(ReadPipe::from(runtime_config)))
.build()
});
};
STDIN_PIPE
.set(MemoryInputPipe::new(runtime_config))
.unwrap();
let wasm = Wizer::new()
.init_func("initialize_runtime")
.make_linker(Some(Rc::new(move |engine| {
let mut linker = Linker::new(engine);
wasi_common::sync::add_to_linker(&mut linker, |_| unsafe {
WASI.get_mut().unwrap()
wasmtime_wasi::preview1::add_to_linker_sync(&mut linker, move |cx| {
// The underlying buffer backing the pipe is an Arc
// so the cloning should be fast.
let config = STDIN_PIPE.get().unwrap().clone();
cx.wasi_ctx = Some(
WasiCtxBuilder::new()
.stdin(config)
.inherit_stdout()
.inherit_stderr()
.build_p1(),
);
cx.wasi_ctx.as_mut().unwrap()
})?;
Ok(linker)
})))?
Expand Down
Loading