Truly independent web browser
Meta+LibJS: Reject untraced fields that can hold GC pointers
Shannon Boothb85622368241
diff --git a/Libraries/LibJS/Rust/macros/src/lib.rs b/Libraries/LibJS/Rust/macros/src/lib.rsindex 8977d2e958d..e219cafba20 100644--- a/Libraries/LibJS/Rust/macros/src/lib.rs+++ b/Libraries/LibJS/Rust/macros/src/lib.rs@@ -11,8 +11,8 @@ use proc_macro2::TokenStream as TokenStream2;use quote::{format_ident, quote};use syn::{Data, DeriveInput, Fields, Index, parse_macro_input};-/// Implements Trace by tracing every field. A field marked #[gc(untraced)] is skipped; it has to hold no cells, or-/// cells something else keeps alive and the cell's owner clears once they die, like an inline cache's shapes.+/// Implements Trace by tracing every field. A field marked #[gc(untraced)] is skipped and holds no cells, or says what+/// keeps them alive: #[gc(untraced = "the realm traces the shapes")].////// The Trace trait is crate::gc::visitor::Trace, or path::gc::visitor::Trace for a type marked #[gc(crate = path)],/// such as a type that an embedder puts in cells of the runtime's heap from a crate of its own.@@ -108,9 +108,19 @@ fn trace_fields(fields: &Fields, gc: &TokenStream2, access: impl Fn(TokenStream2fn is_untraced(field: &syn::Field) -> bool {field.attrs.iter().any(|attribute| {- attribute.path().is_ident("gc")- && attribute- .parse_args::<syn::Ident>()- .is_ok_and(|argument| argument == "untraced")+ if !attribute.path().is_ident("gc") {+ return false;+ }+ let mut untraced = false;+ let _ = attribute.parse_nested_meta(|meta| {+ if meta.path.is_ident("untraced") {+ untraced = true;+ if meta.input.peek(syn::Token![=]) {+ meta.value()?.parse::<syn::LitStr>()?;+ }+ }+ Ok(())+ });+ untraced})}diff --git a/Libraries/LibJS/Rust/src/runtime/arguments_object.rs b/Libraries/LibJS/Rust/src/runtime/arguments_object.rsindex f0df2fd22b9..0966138cb88 100644--- a/Libraries/LibJS/Rust/src/runtime/arguments_object.rs+++ b/Libraries/LibJS/Rust/src/runtime/arguments_object.rs@@ -35,7 +35,7 @@ pub struct ArgumentsObject {base: Object,/// OPTIMIZATION: The named properties of arguments objects, "length", "callee" and @@iterator, fit in the inline/// named storage with this slot after it.- #[gc(untraced)]+ #[gc(untraced = "the object traces it as the last slot of its inline named storage")]extra_inline_named_storage: Cell<Value>,environment: Cell<Gc<Environment>>,#[gc(untraced)]diff --git a/Meta/RustLints/README.md b/Meta/RustLints/README.mdindex 4ef7cf3b27c..8be01969b30 100644--- a/Meta/RustLints/README.md+++ b/Meta/RustLints/README.md@@ -1,6 +1,7 @@# Rust GC lints-A rustc driver with lints for the Rust crates that use libjs_rust's GC, ported from the LibJSGC clang plugin:+A rustc driver with lints for the Rust crates that use libjs_rust's GC, the first two ported from the LibJSGC clang+plugin:- `gc_container_on_stack` (`gc_pointer_container_on_stack` in C++): a local, parameter, return value or unsizingcoercion whose type owns a GC pointer through heap memory that the collector does not scan (`Vec`, `VecDeque`,@@ -8,6 +9,8 @@ A rustc driver with lints for the Rust crates that use libjs_rust's GC, ported fthese, ...). Keep such lists in a `MarkedVec`, or lend them from one.- `root_in_traced_type` (`strong_root_fields_in_gc_allocated_types`): a field that holds a `Root` or `MarkedVec` in atype that implements `Trace`.+- `untraced_gc_pointer`: a field marked `#[gc(untraced)]`, which `#[derive(Trace)]` skips, whose type can hold a GC+ pointer. A field whose cells something else keeps alive says what with `#[gc(untraced = "...")]`.A GC pointer is a reference to a `GcCell`, a value of a type of the crate that implements `Trace` by hand, as `Gc`,`Value` and `PropertyKey` do, or a trait object whose trait requires `Trace`. A type that hides cell pointers in itsdiff --git a/Meta/RustLints/src/gc_lints.rs b/Meta/RustLints/src/gc_lints.rsindex b38c0593578..8cd0f1ca5b2 100644--- a/Meta/RustLints/src/gc_lints.rs+++ b/Meta/RustLints/src/gc_lints.rs@@ -23,7 +23,7 @@ use rustc_middle::ty::print::with_forced_trimmed_paths;use rustc_middle::ty::{self, Ty, TyCtxt};use rustc_session::{declare_lint, impl_lint_pass};-use rustc_span::{DesugaringKind, Span};+use rustc_span::{DesugaringKind, Span, Symbol};declare_lint! {/// A local, parameter or return value owns GC pointers through heap memory that the collector does not scan.@@ -44,7 +44,15 @@ declare_lint! {"`Root` held by a type that implements `Trace`"}-pub static LINTS: &[&Lint] = &[GC_CONTAINER_ON_STACK, ROOT_IN_TRACED_TYPE];+declare_lint! {+ /// A field marked `#[gc(untraced)]`, which `#[derive(Trace)]` skips, can hold GC pointers. Say what keeps them+ /// alive instead: `#[gc(untraced = "...")]`.+ pub UNTRACED_GC_POINTER,+ Deny,+ "GC pointers in a field that `#[derive(Trace)]` skips"+}++pub static LINTS: &[&Lint] = &[GC_CONTAINER_ON_STACK, ROOT_IN_TRACED_TYPE, UNTRACED_GC_POINTER];#[derive(Clone, Copy, PartialEq, Eq)]enum Kind {@@ -93,6 +101,7 @@ pub struct GcLints<'tcx> {impl_lint_pass!(GcLints<'_> => [GC_CONTAINER_ON_STACK,ROOT_IN_TRACED_TYPE,+ UNTRACED_GC_POINTER,]);const LIBJS_CRATE: &str = "libjs_rust";@@ -606,6 +615,31 @@ impl<'tcx> LateLintPass<'tcx> for GcLints<'tcx> {}let tcx = cx.tcx;let adt = tcx.adt_def(item.owner_id);+ let gc = Symbol::intern("gc");+ let untraced = Symbol::intern("untraced");+ for field in adt.all_fields() {+ let field_id = tcx.local_def_id_to_hir_id(field.did.expect_local());+ // NB: A reason, as in #[gc(untraced = "...")], says what keeps the cells alive.+ let untraced_without_reason = tcx.hir_attrs(field_id).iter().any(|attribute| {+ attribute.has_name(gc)+ && attribute+ .meta_item_list()+ .is_some_and(|items| items.iter().any(|item| item.has_name(untraced) && item.is_word()))+ });+ let ty = normalize(cx, tcx.type_of(field.did).instantiate_identity().skip_normalization());+ if untraced_without_reason && self.reaches_gc_pointer(cx, ty, &mut Vec::new()) {+ self.emit(+ cx,+ UNTRACED_GC_POINTER,+ field_id,+ tcx.def_span(field.did),+ with_forced_trimmed_paths!(format!(+ "untraced field of type '{ty}' can hold GC pointers; say what keeps them alive with \+ #[gc(untraced = \"...\")]"+ )),+ );+ }+ }for field in adt.all_fields() {let ty = tcx.type_of(field.did).instantiate_identity().skip_normalization();if let Some((root, _)) = self.find(cx, ty, Target::Root, &mut Vec::new(), None) {diff --git a/Meta/RustLints/tests/ui.rs b/Meta/RustLints/tests/ui.rsindex 4c0ed3145a3..23ad887cfec 100644--- a/Meta/RustLints/tests/ui.rs+++ b/Meta/RustLints/tests/ui.rs@@ -111,23 +111,38 @@ fn main() -> ExitCode {// Stand-ins for the crates whose items the lints know by path. The tests name libjs_rust's as `js`, as code outside// LibJS may not name the runtime's own modules (see Meta/Linters/check_libjs_rust_api.py).let mut externs = Vec::new();- for (crate_name, alias) in [("libjs_rust", "js"), ("smallvec", "smallvec")] {+ for (crate_name, alias, crate_type) in [+ ("libjs_rust", "js", "lib"),+ ("smallvec", "smallvec", "lib"),+ ("libjs_runtime_macros", "libjs_runtime_macros", "proc-macro"),+ ] {let source = ui.join(format!("auxiliary/{crate_name}.rs"));- let rlib = out_dir.join(format!("lib{crate_name}.rlib"));- let _ = std::fs::remove_file(&rlib);- let stderr = run_driver(&[- source.to_str().expect("UTF-8 path"),- "--crate-type=lib",- &format!("--crate-name={crate_name}"),- "--edition=2024",- "--out-dir",- out_dir.to_str().expect("UTF-8 path"),- ]);- if !rlib.exists() {+ let library = match crate_type {+ "proc-macro" => out_dir.join(format!(+ "{}{crate_name}{}",+ std::env::consts::DLL_PREFIX,+ std::env::consts::DLL_SUFFIX+ )),+ _ => out_dir.join(format!("lib{crate_name}.rlib")),+ };+ let _ = std::fs::remove_file(&library);+ let mut args = vec![+ source.to_str().expect("UTF-8 path").to_owned(),+ format!("--crate-type={crate_type}"),+ format!("--crate-name={crate_name}"),+ "--edition=2024".to_owned(),+ "--out-dir".to_owned(),+ out_dir.to_str().expect("UTF-8 path").to_owned(),+ ];+ if crate_type == "proc-macro" {+ args.extend(["--extern".to_owned(), "proc_macro".to_owned()]);+ }+ let stderr = run_driver(&args.iter().map(String::as_str).collect::<Vec<_>>());+ if !library.exists() {eprintln!("building the {crate_name} stand-in failed:\n{stderr}");return ExitCode::FAILURE;}- externs.push(format!("{alias}={}", rlib.display()));+ externs.push(format!("{alias}={}", library.display()));}let filter = std::env::args().nth(1);diff --git a/Meta/RustLints/tests/ui/auxiliary/libjs_runtime_macros.rs b/Meta/RustLints/tests/ui/auxiliary/libjs_runtime_macros.rsnew file mode 100644index 00000000000..8ab6e901eb0--- /dev/null+++ b/Meta/RustLints/tests/ui/auxiliary/libjs_runtime_macros.rs@@ -0,0 +1,17 @@+/*+ * Copyright (c) 2026-present, the Ladybird developers.+ *+ * SPDX-License-Identifier: BSD-2-Clause+ */++//! The derive whose helper attributes the lints read, as `#[gc(untraced)]` on fields. It derives nothing; the tests+//! implement Trace themselves.++extern crate proc_macro;++use proc_macro::TokenStream;++#[proc_macro_derive(Trace, attributes(gc))]+pub fn derive_trace(_: TokenStream) -> TokenStream {+ TokenStream::new()+}diff --git a/Meta/RustLints/tests/ui/untraced_gc_pointer.rs b/Meta/RustLints/tests/ui/untraced_gc_pointer.rsnew file mode 100644index 00000000000..787c45c21b8--- /dev/null+++ b/Meta/RustLints/tests/ui/untraced_gc_pointer.rs@@ -0,0 +1,39 @@+/*+ * Copyright (c) 2026-present, the Ladybird developers.+ *+ * SPDX-License-Identifier: BSD-2-Clause+ */++#![allow(unused, clippy::all)]++use js::{Cell, Gc, GcWeak, Value, Visitor};+use libjs_runtime_macros::Trace;++#[derive(Trace)]+pub struct Traced {+ #[gc(untraced)]+ count: u32,+ #[gc(untraced)]+ weak: GcWeak<Cell>,+ #[gc(untraced)]+ cell: Gc<Cell>, //~ ERROR untraced field of type 'Gc<Cell>'+ #[gc(untraced)]+ values: Vec<Value>, //~ ERROR untraced field of type 'Vec<Value>'+ #[gc(untraced = "the owner traces it")]+ explained: Gc<Cell>,+ traced: Gc<Cell>,+}++unsafe impl js::Trace for Traced {+ fn trace(&self, _: &mut Visitor) {}+}++#[derive(Trace)]+pub enum Either {+ Cell(#[gc(untraced)] Gc<Cell>), //~ ERROR untraced field of type 'Gc<Cell>'+ Count(#[gc(untraced)] u32),+}++unsafe impl js::Trace for Either {+ fn trace(&self, _: &mut Visitor) {}+}