Skip to content

Commit 448a557

Browse files
authored
Merge pull request wasmerio#4192 from wasmerio/wasmer-js-fixes
More fixes to support Wasmer JS
2 parents 7cb550d + c0a695d commit 448a557

File tree

29 files changed

+658
-408
lines changed

29 files changed

+658
-408
lines changed

Cargo.lock

Lines changed: 0 additions & 24 deletions
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

Cargo.toml

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -280,7 +280,7 @@ required-features = ["backend"]
280280
[[example]]
281281
name = "errors"
282282
path = "examples/errors.rs"
283-
required-features = ["sys"]
283+
required-features = ["backend"]
284284

285285
[[example]]
286286
name = "imported-function-env"

lib/api/Cargo.toml

Lines changed: 0 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -52,7 +52,6 @@ wasmer-compiler-llvm = { path = "../compiler-llvm", version = "=4.2.3", optional
5252
wasm-bindgen = { version = "0.2.74", optional = true }
5353
js-sys = { version = "0.3.51", optional = true }
5454
rusty_jsc = { version = "0.1.0", optional = true }
55-
# rusty_jsc = { path="../../../rusty_jsc", optional = true }
5655
wasmparser = { version = "0.83", default-features = false, optional = true }
5756

5857
# - Mandatory dependencies for `sys` on Windows.
@@ -70,9 +69,7 @@ macro-wasmer-universal-test = { version = "4.2.3", path = "./macro-wasmer-univer
7069
# - Mandatory dependencies for `js`.
7170
wasmer-types = { path = "../types", version = "=4.2.3", default-features = false, features = ["std"] }
7271
wasm-bindgen = "0.2.74"
73-
wasm-bindgen-downcast = { version = "0.1.1" }
7472
js-sys = "0.3.51"
75-
#web-sys = { version = "0.3.51", features = [ "console" ] }
7673
wasmer-derive = { path = "../derive", version = "=4.2.3" }
7774
# - Optional dependencies for `js`.
7875
wasmparser = { version = "0.95", default-features = false, optional = true }

lib/api/src/externals/memory.rs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -36,7 +36,7 @@ impl Memory {
3636
/// Creates a new host `Memory` from the provided [`MemoryType`].
3737
///
3838
/// This function will construct the `Memory` using the store
39-
/// [`BaseTunables`][crate::sys::BaseTunables].
39+
/// `BaseTunables`.
4040
///
4141
/// # Example
4242
///

lib/api/src/externals/table.rs

Lines changed: 1 addition & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -30,8 +30,7 @@ impl Table {
3030
///
3131
/// All the elements in the table will be set to the `init` value.
3232
///
33-
/// This function will construct the `Table` using the store
34-
/// [`BaseTunables`][crate::sys::BaseTunables].
33+
/// This function will construct the `Table` using the store `BaseTunables`.
3534
pub fn new(
3635
store: &mut impl AsStoreMut,
3736
ty: TableType,

lib/api/src/js/as_js.rs

Lines changed: 2 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -232,13 +232,10 @@ impl AsJs for Memory {
232232
memory_type: &Self::DefinitionType,
233233
value: &JsValue,
234234
) -> Result<Self, JsError> {
235-
if value.is_instance_of::<JsMemory>() {
235+
if let Some(memory) = value.dyn_ref::<JsMemory>() {
236236
Ok(Memory::from_vm_extern(
237237
store,
238-
VMMemory::new(
239-
value.clone().unchecked_into::<JsMemory>(),
240-
memory_type.clone(),
241-
),
238+
VMMemory::new(memory.clone(), memory_type.clone()),
242239
))
243240
} else {
244241
Err(JsError::new(&format!(

lib/api/src/js/externals/memory.rs

Lines changed: 22 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -88,8 +88,16 @@ impl Memory {
8888
js_sys::Reflect::set(&descriptor, &"shared".into(), &ty.shared.into()).unwrap();
8989
}
9090

91-
let js_memory = js_sys::WebAssembly::Memory::new(&descriptor)
92-
.map_err(|_e| MemoryError::Generic("Error while creating the memory".to_owned()))?;
91+
let js_memory = js_sys::WebAssembly::Memory::new(&descriptor).map_err(|e| {
92+
let error_message = if let Some(s) = e.as_string() {
93+
s
94+
} else if let Some(obj) = e.dyn_ref::<js_sys::Object>() {
95+
obj.to_string().into()
96+
} else {
97+
"Error while creating the memory".to_string()
98+
};
99+
MemoryError::Generic(error_message)
100+
})?;
93101

94102
Ok(js_memory)
95103
}
@@ -164,6 +172,18 @@ impl std::cmp::PartialEq for Memory {
164172
}
165173
}
166174

175+
impl From<Memory> for crate::Memory {
176+
fn from(value: Memory) -> Self {
177+
crate::Memory(value)
178+
}
179+
}
180+
181+
impl From<crate::Memory> for Memory {
182+
fn from(value: crate::Memory) -> Self {
183+
value.0
184+
}
185+
}
186+
167187
/// Underlying buffer for a memory.
168188
#[derive(Copy, Clone, Debug)]
169189
pub(crate) struct MemoryBuffer<'a> {

lib/api/src/js/js_handle.rs

Lines changed: 43 additions & 39 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,9 @@
1-
use std::ops::{Deref, DerefMut};
1+
use std::{
2+
ops::{Deref, DerefMut},
3+
sync::atomic::{AtomicU32, Ordering},
4+
};
25

6+
use js_sys::Symbol;
37
use wasm_bindgen::JsValue;
48

59
use self::integrity_check::IntegrityCheck;
@@ -101,14 +105,9 @@ mod integrity_check {
101105

102106
#[cfg(debug_assertions)]
103107
mod integrity_check {
104-
use std::{
105-
fmt::Write as _,
106-
panic::Location,
107-
sync::atomic::{AtomicU32, Ordering},
108-
};
108+
use std::{fmt::Write as _, panic::Location};
109109

110-
use js_sys::{JsString, Symbol};
111-
use wasm_bindgen::JsValue;
110+
use js_sys::JsString;
112111

113112
#[derive(Debug, Clone, PartialEq)]
114113
pub(crate) struct IntegrityCheck {
@@ -122,7 +121,7 @@ mod integrity_check {
122121
#[track_caller]
123122
pub(crate) fn new(type_name: &'static str) -> Self {
124123
IntegrityCheck {
125-
original_thread: current_thread_id(),
124+
original_thread: super::current_thread_id(),
126125
created: Location::caller(),
127126
type_name,
128127
backtrace: record_backtrace(),
@@ -131,7 +130,7 @@ mod integrity_check {
131130

132131
#[track_caller]
133132
pub(crate) fn check(&self) {
134-
let current_thread = current_thread_id();
133+
let current_thread = super::current_thread_id();
135134

136135
if current_thread != self.original_thread {
137136
let IntegrityCheck {
@@ -177,35 +176,6 @@ mod integrity_check {
177176
}
178177
}
179178

180-
/// Get a unique ID for the current "thread" (i.e. web worker or the main
181-
/// thread).
182-
///
183-
/// This works by creating a `$WASMER_THREAD_ID` symbol and setting it on
184-
/// the global object.
185-
fn current_thread_id() -> u32 {
186-
static NEXT_ID: AtomicU32 = AtomicU32::new(0);
187-
188-
let global = js_sys::global();
189-
let thread_id_symbol = Symbol::for_("$WASMER_THREAD_ID");
190-
191-
if let Some(v) = js_sys::Reflect::get(&global, &thread_id_symbol)
192-
.ok()
193-
.and_then(|v| v.as_f64())
194-
{
195-
// Note: we use a symbol so we know for sure that nobody else created
196-
// this field.
197-
return v as u32;
198-
}
199-
200-
// Looks like we haven't set the thread ID yet.
201-
let id = NEXT_ID.fetch_add(1, Ordering::Relaxed);
202-
203-
js_sys::Reflect::set(&global, &thread_id_symbol, &JsValue::from(id))
204-
.expect("Setting a field on the global object should never fail");
205-
206-
id
207-
}
208-
209179
fn record_backtrace() -> Option<String> {
210180
let err = js_sys::Error::new("");
211181
let stack = JsString::from(wasm_bindgen::intern("stack"));
@@ -215,3 +185,37 @@ mod integrity_check {
215185
.and_then(|v| v.as_string())
216186
}
217187
}
188+
189+
/// A browser polyfill for [`std::thread::ThreadId`] [`std::thread::current()`].
190+
///
191+
/// This works by creating a `$WASMER_THREAD_ID` symbol and setting it on
192+
/// the global object. As long as they use the same `SharedArrayBuffer` for
193+
/// their linear memory, each thread (i.e. web worker or the UI thread) is
194+
/// guaranteed to get a unique ID.
195+
///
196+
/// This is mainly intended for use in `wasmer-wasix` and `wasmer-js`, and may
197+
/// go away in the future.
198+
#[doc(hidden)]
199+
pub fn current_thread_id() -> u32 {
200+
static NEXT_ID: AtomicU32 = AtomicU32::new(0);
201+
202+
let global = js_sys::global();
203+
let thread_id_symbol = Symbol::for_("$WASMER_THREAD_ID");
204+
205+
if let Some(v) = js_sys::Reflect::get(&global, &thread_id_symbol)
206+
.ok()
207+
.and_then(|v| v.as_f64())
208+
{
209+
// Note: we use a symbol so we know for sure that nobody else created
210+
// this field.
211+
return v as u32;
212+
}
213+
214+
// Looks like we haven't set the thread ID yet.
215+
let id = NEXT_ID.fetch_add(1, Ordering::Relaxed);
216+
217+
js_sys::Reflect::set(&global, &thread_id_symbol, &JsValue::from(id))
218+
.expect("Setting a field on the global object should never fail");
219+
220+
id
221+
}

lib/api/src/js/mod.rs

Lines changed: 1 addition & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -40,5 +40,4 @@ pub(crate) mod typed_function;
4040
pub(crate) mod vm;
4141
mod wasm_bindgen_polyfill;
4242

43-
pub use crate::js::as_js::AsJs;
44-
pub use crate::js::module::ModuleTypeHints;
43+
pub use self::{as_js::AsJs, js_handle::current_thread_id, module::ModuleTypeHints};

lib/api/src/js/module.rs

Lines changed: 7 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -23,11 +23,11 @@ use wasmer_types::{
2323
///
2424
/// This should be fixed once the JS-Types Wasm proposal is adopted
2525
/// by the browsers:
26-
/// https://github.com/WebAssembly/js-types/blob/master/proposals/js-types/Overview.md
26+
/// <https://github.com/WebAssembly/js-types/blob/master/proposals/js-types/Overview.md>
2727
///
2828
/// Until that happens, we annotate the module with the expected
2929
/// types so we can built on top of them at runtime.
30-
#[derive(Clone, PartialEq, Eq)]
30+
#[derive(Debug, Clone, PartialEq, Eq)]
3131
pub struct ModuleTypeHints {
3232
/// The type hints for the imported types
3333
pub imports: Vec<ExternType>,
@@ -474,3 +474,8 @@ impl From<WebAssembly::Module> for crate::module::Module {
474474
crate::module::Module(module.into())
475475
}
476476
}
477+
impl From<crate::module::Module> for WebAssembly::Module {
478+
fn from(value: crate::module::Module) -> Self {
479+
value.0.module.into_inner()
480+
}
481+
}

lib/api/src/js/module_info_polyfill.rs

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -3,8 +3,8 @@
33
//!
44
//! This shall not be needed once the JS type reflection API is available
55
//! for the Wasm imports and exports.
6-
//!
7-
//! https://github.com/WebAssembly/js-types/blob/master/proposals/js-types/Overview.md
6+
//!
7+
//! <https://github.com/WebAssembly/js-types/blob/master/proposals/js-types/Overview.md>
88
use core::convert::TryFrom;
99
use std::vec::Vec;
1010
use wasmer_types::entity::EntityRef;

0 commit comments

Comments
 (0)