Skip to content

Commit 215a1af

Browse files
committed
Require the isolate lock for jsg::Rc, jsg::Weak and jsg_cpp::Ref
Rust JSG shares state with no synchronization of its own: the reference counts of a jsg::Rc and its Wrappable, and the Cells and RefCells of resources. Only the isolate lock keeps two threads from using that state at once, which would be a data race. Today a jsg::Rc can be dereferenced and cloned without the lock, so a thread that holds one but not the lock can read the resource or change its counts while the lock's holder does. This change makes every reference reach that state only under its isolate's lock. - jsg::Rc and jsg::Weak touch their counts and their resource only under the lock of the resource's isolate, which makes them Send, for R: Send: - Rc loses Deref and Clone for get(lock), clone(lock) and downgrade(lock), and Weak::upgrade, Weak::clone, Weak::is_alive and Rc::attach_to_this take a Lock too. Each asserts, in every build, that the lock is of the resource's isolate and that its Realm is alive: holding one isolate's lock excludes no thread from another's. Lock is neither Send nor Sync. get() bounds the &R by the lock's brand 's, so even a leaked Rc can't lend its resource to a 'static future. - GC and detaching visits change a jsg::Rc only under its isolate's lock. A detaching visit (jsg::Cell::take, say) under another isolate's lock panics; a GC visit on behalf of another isolate leaves it as it is, so a reference that one isolate's resource holds to another's leaks rather than racing, as TracedGlobal's visit already does. Debug builds assert against such a visit. - A drop without the lock is queued without touching a count (#8111). - Weak loses its unused GarbageCollected impl, whose memory_name upgraded it without a lock. - jsg_cpp::Ref gets the same treatment through a new jsg::LockGuarded<T>: a value that only its isolate's lock guards, which it lends only under that lock (get, and get_for_visit for GC and detaching visits, which follow jsg::Rc's rules) and drops as a jsg::Rc drops its parts. Its constructor is unsafe: the value must be bound to no thread but through the lock. Ref's Deref becomes get(lock) and its Clone clone(lock), and to_js and as_cpp check the lock too. A heap snapshot reports it through LockGuarded::get_for_memory_info, which, as for a jsg::Rc, lends the value only to a snapshot of its own isolate, which holds that isolate's lock. Its drop no longer relies on C++'s deferral, which destroys an object that has no wrapper at once, with or without the lock: two references to such an object, dropped on two threads, raced on its count. While the isolate is torn down, a drop under the lock still drops the value then, until the isolate is about to be disposed, so the C++ objects that the resources teardown drops hold are destroyed before Dispose, as before; after it, a destructor that resets a raw v8::Global would use the freed isolate. ~IsolateBase now also calls its dispose hook just before Dispose, after which Rust no longer asks V8 whether a thread holds the lock. A jsg_cpp::Ref kept past teardown is dropped after Dispose, which the parent commit ("Unbind every Wrappable from its isolate at teardown") makes safe. - v8::WrappableRc becomes private to jsg, since its Clone and Drop change the Wrappable's count without the lock, and so does the jsg_cpp bridge, whose functions clone and detach a C++ reference without one. The macros' receiver helpers move to jsg::v8::resolve_receiver and resolve_method_receiver. The argument also rests on GC running on the thread that holds the lock (--single-threaded-gc), and on nothing releasing the lock while a Lock exists (workerd has no v8::Unlocker). await_io keeps its Send bounds. A future may now hold a jsg::Rc, but only to drop it. Resource state itself can still be anything, std::rc::Rc included; the next commit requires it to be Send. Tests: compile tests that reject deref, clone, downgrade and upgrade without a lock, and a &R from get() captured in a 'static future, and one that accepts a resource with a jsg::RefCell<Vec<jsg::Rc<_>>> field whose jsg::Rc and jsg::Weak are dropped on another thread. jsg-tests check that each lock-taking operation, jsg_cpp::Ref's included, panics under another isolate's lock, that detaching a jsg::Rc or jsg_cpp::Ref of another isolate panics, that another isolate's GC leaves a jsg::Rc alone (in release builds), and that references to an object with no wrapper, dropped on two threads without the lock, wait for it. They also check that teardown destroys the C++ object of a jsg_cpp::Ref that a resource holds before the isolate is disposed, and that one kept past teardown can still be dropped. Compile tests check that WrappableRc and the jsg_cpp bridge are private. Tests that used a resource after leaving its lock scope now read it inside one. src/rust/jsg/README.md gains safety rule 5, which states the argument, and src/rust/AGENTS.md describes the new API.
1 parent f3112e8 commit 215a1af

60 files changed

Lines changed: 1632 additions & 651 deletions

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

‎src/rust/AGENTS.md‎

Lines changed: 3 additions & 2 deletions
Large diffs are not rendered by default.

‎src/rust/api/lib-test.rs‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -13,7 +13,7 @@ fn test_wrap_resource_equality() {
1313
harness.run_in_context(|lock, _ctx| {
1414
let dns_util = DnsUtil::new(lock);
1515

16-
let lhs = dns_util.clone().to_js(lock)?;
16+
let lhs = dns_util.clone(lock).to_js(lock)?;
1717
let rhs = dns_util.to_js(lock)?;
1818

1919
assert_eq!(lhs, rhs);

‎src/rust/jsg-bench/lib.rs‎

Lines changed: 8 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -93,7 +93,8 @@ impl Node {
9393
#[jsg_property(prototype)]
9494
fn get_child(&self, lock: &mut jsg::Lock<'_>) -> Option<jsg::Rc<Node>> {
9595
let child = self.child.take(lock);
96-
self.child.set(child.clone());
96+
self.child
97+
.set(child.as_ref().map(|child| child.clone(lock)));
9798
child
9899
}
99100
}
@@ -247,13 +248,13 @@ impl Target {
247248
}
248249

249250
#[jsg_method]
250-
fn same_node(&self) -> jsg::Rc<Node> {
251-
self.child.clone()
251+
fn same_node(&self, lock: &mut jsg::Lock<'_>) -> jsg::Rc<Node> {
252+
self.child.clone(lock)
252253
}
253254

254255
#[jsg_method]
255-
fn take_node(&self, a: jsg::Rc<Node>) -> u32 {
256-
a.value.get()
256+
fn take_node(&self, lock: &mut jsg::Lock<'_>, a: jsg::Rc<Node>) -> u32 {
257+
a.get(lock).value.get()
257258
}
258259

259260
#[jsg_method]
@@ -323,10 +324,10 @@ unsafe fn native_lifetime(isolate: *mut v8::ffi::Isolate, count: u32, clones: u3
323324
let node = jsg::Rc::new(lock, Node::constructor(i));
324325
black_box(&node);
325326
for _ in 0..clones {
326-
let copy = node.clone();
327+
let copy = node.clone(lock);
327328
black_box(&copy);
328329
}
329-
result ^= node.value.get();
330+
result ^= node.get(lock).value.get();
330331
}
331332
result
332333
}

‎src/rust/jsg-compile-tests/BUILD.bazel‎

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -6,5 +6,8 @@ wd_rust_compile_test(
66
name = "jsg",
77
srcs = glob(["*.rs"]),
88
proc_macro_deps = ["//src/rust/jsg-macros"],
9-
deps = ["//src/rust/jsg"],
9+
deps = [
10+
"//src/rust/jsg",
11+
"//src/rust/jsg-cpp",
12+
],
1013
)
Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,7 @@
1+
// Copyright (c) 2026 Cloudflare, Inc.
2+
// Licensed under the Apache 2.0 license found in the LICENSE file or at:
3+
// https://opensource.org/licenses/Apache-2.0
4+
5+
// The bridge's functions change a `jsg_cpp::Ref`'s reference count without checking the isolate
6+
// lock, so only `jsg_cpp::Ref`, which takes the lock, calls them.
7+
use jsg_cpp::bridge; //~ ERROR E0432
Lines changed: 28 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,28 @@
1+
// Copyright (c) 2026 Cloudflare, Inc.
2+
// Licensed under the Apache 2.0 license found in the LICENSE file or at:
3+
// https://opensource.org/licenses/Apache-2.0
4+
5+
// A `jsg::Rc` or `jsg::Weak` of a resource whose state is `Send` is `Send` too: every use but
6+
// dropping gates on a `Lock`, so on another thread it can only be dropped.
7+
use jsg_macros::jsg_resource;
8+
9+
#[jsg_resource]
10+
struct Leaf;
11+
12+
#[jsg_resource]
13+
impl Leaf {}
14+
15+
#[jsg_resource]
16+
struct Holder {
17+
leaves: jsg::RefCell<Vec<jsg::Rc<Leaf>>>,
18+
}
19+
20+
#[jsg_resource]
21+
impl Holder {}
22+
23+
pub fn drop_elsewhere(holder: jsg::Rc<Holder>, weak: jsg::Weak<Leaf>) {
24+
std::thread::spawn(move || {
25+
drop(holder);
26+
drop(weak);
27+
});
28+
}

‎src/rust/jsg-compile-tests/ok-this-parameter.rs‎

Lines changed: 23 additions & 20 deletions
Original file line numberDiff line numberDiff line change
@@ -3,7 +3,8 @@
33
// https://opensource.org/licenses/Apache-2.0
44

55
// `this: jsg::Rc<Self>` takes the place of `&self` on methods and accessors, before the lock
6-
// and the JavaScript arguments, and a JavaScript argument of type `jsg::Rc<Self>` stays one.
6+
// and the JavaScript arguments, and a JavaScript argument of type `jsg::Rc<Self>` stays one. The
7+
// resource behind a `jsg::Rc` is borrowed with the lock.
78

89
use jsg::Rc;
910
use jsg::ToJS;
@@ -26,8 +27,8 @@ impl Counter {
2627
}
2728

2829
#[jsg_method]
29-
pub fn imported(this: Rc<Self>) -> u32 {
30-
this.count.get()
30+
pub fn imported(this: Rc<Self>, lock: &mut jsg::Lock<'_>) -> u32 {
31+
this.get(lock).count.get()
3132
}
3233

3334
#[jsg_method]
@@ -36,8 +37,9 @@ impl Counter {
3637
lock: &mut jsg::Lock<'s>,
3738
by: u32,
3839
) -> jsg::Result<v8::Local<'s, v8::Value>> {
39-
this.count.set(this.count.get() + by);
40-
this.count.get().to_js(lock)
40+
let count = &this.get(lock).count;
41+
count.set(count.get() + by);
42+
count.get().to_js(lock)
4143
}
4244

4345
#[jsg_method]
@@ -46,8 +48,8 @@ impl Counter {
4648
}
4749

4850
#[jsg_method]
49-
pub fn argument_of_own_type(&self, other: jsg::Rc<Self>) -> bool {
50-
std::ptr::eq(self, &*other)
51+
pub fn argument_of_own_type(&self, lock: &mut jsg::Lock<'_>, other: jsg::Rc<Self>) -> bool {
52+
std::ptr::eq(self, other.get(lock))
5153
}
5254

5355
#[jsg_method]
@@ -56,30 +58,31 @@ impl Counter {
5658
}
5759

5860
#[jsg_property]
59-
pub fn get_total(this: jsg::Rc<Self>) -> u32 {
60-
this.count.get()
61+
pub fn get_total(this: jsg::Rc<Self>, lock: &mut jsg::Lock<'_>) -> u32 {
62+
this.get(lock).count.get()
6163
}
6264

6365
#[jsg_property]
64-
pub fn set_total(this: jsg::Rc<Self>, v: u32) {
65-
this.count.set(v);
66+
pub fn set_total(this: jsg::Rc<Self>, lock: &mut jsg::Lock<'_>, v: u32) {
67+
this.get(lock).count.set(v);
6668
}
6769

6870
#[jsg_property(instance)]
69-
pub fn get_current(this: jsg::Rc<Self>) -> u32 {
70-
this.count.get()
71+
pub fn get_current(this: jsg::Rc<Self>, lock: &mut jsg::Lock<'_>) -> u32 {
72+
this.get(lock).count.get()
7173
}
7274

7375
#[jsg_inspect_property]
74-
pub fn debug_info(this: jsg::Rc<Self>) -> String {
75-
format!("Counter({})", this.count.get())
76+
pub fn debug_info(this: jsg::Rc<Self>, lock: &mut jsg::Lock<'_>) -> String {
77+
format!("Counter({})", this.get(lock).count.get())
7678
}
7779
}
7880

7981
// The methods are ordinary associated functions to Rust.
80-
pub fn calls(counter: jsg::Rc<Counter>) -> bool {
81-
let _ = Counter::itself(counter.clone());
82-
let _ = Counter::imported(counter.clone());
83-
Counter::set_total(counter.clone(), 1);
84-
Counter::compare(counter.clone(), counter.clone()) && Counter::same_as(counter.clone(), counter)
82+
pub fn calls(lock: &mut jsg::Lock<'_>, counter: jsg::Rc<Counter>) -> bool {
83+
let _ = Counter::itself(counter.clone(lock));
84+
let _ = Counter::imported(counter.clone(lock), lock);
85+
Counter::set_total(counter.clone(lock), lock, 1);
86+
Counter::compare(counter.clone(lock), counter.clone(lock))
87+
&& Counter::same_as(counter.clone(lock), counter)
8588
}
Lines changed: 44 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,44 @@
1+
// Copyright (c) 2026 Cloudflare, Inc.
2+
// Licensed under the Apache 2.0 license found in the LICENSE file or at:
3+
// https://opensource.org/licenses/Apache-2.0
4+
5+
// A resource's state and the reference counts of its `jsg::Rc`s and `jsg::Weak`s are guarded by
6+
// the isolate lock, so every operation on them but dropping takes a `Lock`. Code that has none,
7+
// such as a future that `IoContext` polls, can only drop them.
8+
use std::cell::Cell;
9+
10+
use jsg_macros::jsg_resource;
11+
12+
#[jsg_resource]
13+
pub struct Counter {
14+
count: Cell<u32>,
15+
}
16+
17+
#[jsg_resource]
18+
impl Counter {}
19+
20+
fn require_clone<T: Clone>() {}
21+
22+
pub fn deref(counter: &jsg::Rc<Counter>) -> u32 {
23+
let _: &Counter = &**counter; //~ ERROR E0614
24+
counter.count.get() //~ ERROR E0609
25+
}
26+
27+
pub fn clone(counter: &jsg::Rc<Counter>, weak: &jsg::Weak<Counter>) {
28+
let _ = counter.clone(); //~ ERROR E0061
29+
let _ = weak.clone(); //~ ERROR E0061
30+
require_clone::<jsg::Rc<Counter>>(); //~ ERROR E0277
31+
require_clone::<jsg::Weak<Counter>>(); //~ ERROR E0277
32+
}
33+
34+
pub fn weak(counter: &jsg::Rc<Counter>, weak: &jsg::Weak<Counter>) {
35+
let _ = counter.downgrade(); //~ ERROR E0061
36+
let _ = weak.upgrade(); //~ ERROR E0061
37+
let _ = weak.is_alive(); //~ ERROR E0061
38+
}
39+
40+
// Dropping needs no lock.
41+
pub fn drop_them(counter: jsg::Rc<Counter>, weak: jsg::Weak<Counter>) {
42+
drop(counter);
43+
drop(weak);
44+
}

‎src/rust/jsg-compile-tests/this-parameter-is-the-receiver.rs‎

Lines changed: 5 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -87,10 +87,10 @@ impl Counter {
8787
}
8888

8989
// A rejected method is still emitted, so its callers add no errors of their own.
90-
fn _calls(counter: jsg::Rc<Counter>, other: jsg::Rc<Other>) {
91-
counter.with_self(counter.clone());
92-
Counter::after_argument(1, counter.clone());
90+
fn _calls(lock: &jsg::Lock<'_>, counter: jsg::Rc<Counter>, other: jsg::Rc<Other>) {
91+
counter.get(lock).with_self(counter.clone(lock));
92+
Counter::after_argument(1, counter.clone(lock));
9393
Counter::of_another_type(other);
94-
Counter::weak(counter.downgrade());
95-
let _ = counter.get_total(counter.clone());
94+
Counter::weak(counter.downgrade(lock));
95+
let _ = counter.get(lock).get_total(counter.clone(lock));
9696
}
Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,7 @@
1+
// Copyright (c) 2026 Cloudflare, Inc.
2+
// Licensed under the Apache 2.0 license found in the LICENSE file or at:
3+
// https://opensource.org/licenses/Apache-2.0
4+
5+
// `WrappableRc` changes a `Wrappable`'s `kj::Rc` count, which only the isolate lock guards, when
6+
// it is cloned or dropped, so only `jsg::Rc` and `jsg::Weak`, which take the lock, hold one.
7+
use jsg::v8::WrappableRc; //~ ERROR E0603

0 commit comments

Comments
 (0)