Skip to content

Commit

Permalink
Remove use of shared mutable static
Browse files Browse the repository at this point in the history
  • Loading branch information
jeffcharles committed Dec 4, 2024
1 parent fe7fe58 commit 467dee4
Showing 1 changed file with 17 additions and 19 deletions.
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

0 comments on commit 467dee4

Please sign in to comment.