Skip to content

Commit 2b3adbc

Browse files
committed
add ThreadLocal to WasmStore to prevent sharing across threads
1 parent 44c3a3e commit 2b3adbc

File tree

3 files changed

+42
-2
lines changed

3 files changed

+42
-2
lines changed

Makefile

+4
Original file line numberDiff line numberDiff line change
@@ -82,6 +82,10 @@ mvn-test: target/native
8282
mvn-compile: target/native
8383
PLATFORM=${PLATFORM} ARCH=${ARCH} mvn compile
8484

85+
.PHONY: package
86+
package: build
87+
PLATFORM=${PLATFORM} ARCH=${ARCH} mvn package
88+
8589
.PHONY: cleanliness
8690
cleanliness:
8791
cargo clean -p wasmtime-jni -p wasmtime-jni-exports -p math -p slices -p strings

src/main/java/net/bluejekyll/wasmtime/AbstractOpaquePtr.java

+1-1
Original file line numberDiff line numberDiff line change
@@ -33,7 +33,7 @@ public void run() {
3333
}
3434
}
3535

36-
protected final long getPtr() {
36+
protected long getPtr() {
3737
return this.ptr;
3838
}
3939

src/main/java/net/bluejekyll/wasmtime/WasmStore.java

+37-1
Original file line numberDiff line numberDiff line change
@@ -3,15 +3,51 @@
33
import java.lang.reflect.Method;
44

55
public class WasmStore extends AbstractOpaquePtr {
6+
// Store is !Send and !Sync in Rust, we will enforce that with a ThreadLocal
7+
// TODO: do we need stackable stores?
8+
private static final ThreadLocal<Long> STORE = new ThreadLocal<Long>();
9+
610
WasmStore(long ptr) {
7-
super(ptr, WasmStore::freeStore);
11+
super(ptr, WasmStore::freeStoreChecked);
12+
if (STORE.get() != null) {
13+
throw new IllegalStateException("Previous STORE not cleared for this thread");
14+
}
15+
16+
STORE.set(ptr);
817
}
918

1019
private static native void freeStore(long ptr);
1120

1221
private static native long newLinkerNtv(long store_ptr);
1322

23+
private static void verifyStore(long ptr) {
24+
if (STORE.get() != ptr) {
25+
throw new IllegalStateException(String.format("STORE expected %d got %d", STORE.get(), ptr));
26+
}
27+
}
28+
29+
@Override
30+
public long getPtr() {
31+
long ptr = super.getPtr();
32+
verifyStore(ptr);
33+
34+
return ptr;
35+
}
36+
1437
public WasmLinker newLinker() {
38+
if (STORE.get() == null) {
39+
throw new IllegalStateException("STORE not available for this thread, did a new thread get started?");
40+
}
41+
1542
return new WasmLinker(WasmStore.newLinkerNtv(this.getPtr()));
1643
}
44+
45+
public static void freeStoreChecked(long ptr) {
46+
if (STORE.get() != ptr) {
47+
throw new IllegalStateException(String.format("STORE expected %d got %d", STORE.get(), ptr));
48+
}
49+
50+
WasmStore.freeStore(ptr);
51+
STORE.remove();
52+
}
1753
}

0 commit comments

Comments
 (0)