Skip to content

Truly independent web browser

LibWeb: Build the LibJS runtime into LibWeb's library

Aliaksandr Kalenik1dbcfa537571
diff --git a/Cargo.lock b/Cargo.lock
index 93993a4fa2d..b711c7794d6 100644
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -852,6 +852,14 @@ dependencies = [
name = "libjs_abi"
version = "0.1.0"
+[[package]]
+name = "libjs_embedding_headers"
+version = "0.1.0"
+dependencies = [
+ "cbindgen",
+ "libjs_abi",
+]
+
[[package]]
name = "libjs_jit"
version = "0.1.0"
@@ -876,7 +884,6 @@ name = "libjs_rust"
version = "0.1.0"
dependencies = [
"ak",
- "cbindgen",
"cc",
"fARM64",
"flapc",
@@ -962,6 +969,17 @@ dependencies = [
"target-lexicon",
]
+[[package]]
+name = "libweb_bindings_rust"
+version = "0.1.0"
+dependencies = [
+ "ak",
+ "ladybird_allocator",
+ "libjs_rust",
+ "libweb_rust",
+ "rustc-demangle",
+]
+
[[package]]
name = "libweb_content_blocker_rust"
version = "0.1.0"
diff --git a/Cargo.toml b/Cargo.toml
index 147bdd48b2b..e48cbdf0f59 100644
--- a/Cargo.toml
+++ b/Cargo.toml
@@ -7,12 +7,14 @@ members = [
"Libraries/LibJS/ABI",
"Libraries/LibJS/JIT/Rust",
"Libraries/LibJS/Rust",
+ "Libraries/LibJS/Rust/embedding_headers",
"Libraries/LibJS/Rust/macros",
"Libraries/LibRegex/Rust",
"Libraries/LibTextCodec/Rust",
"Libraries/LibUnicode/Rust",
"Libraries/LibURL/Rust",
"Libraries/LibWasm/Rust",
+ "Libraries/LibWeb/Bindings/Rust",
"Libraries/LibWeb/ContentBlocker/Rust",
"Libraries/LibWeb/Rust",
"Libraries/LibWeb/HTML/Parser/Rust",
diff --git a/Libraries/CMakeLists.txt b/Libraries/CMakeLists.txt
index d891d51a416..cad7654d3cb 100644
--- a/Libraries/CMakeLists.txt
+++ b/Libraries/CMakeLists.txt
@@ -8,6 +8,9 @@ add_subdirectory(LibFileSystem)
add_subdirectory(LibGC)
add_subdirectory(LibHTTP)
add_subdirectory(LibIPC)
+# When LibWeb is built, LibJS's C++ API and the Rust runtime underneath it go into LibWeb's library, so that a process
+# has one copy of the runtime, which LibWeb's Rust crate depends on (Libraries/LibJS/CMakeLists.txt).
+set(LIBJS_FOLDED_INTO_LIBWEB ${ENABLE_GUI_TARGETS})
add_subdirectory(LibJS)
add_subdirectory(LibMain)
add_subdirectory(LibRegex)
diff --git a/Libraries/LibJS/CMakeLists.txt b/Libraries/LibJS/CMakeLists.txt
index 6f3ff200409..3212f705fe1 100644
--- a/Libraries/LibJS/CMakeLists.txt
+++ b/Libraries/LibJS/CMakeLists.txt
@@ -1,6 +1,21 @@
-# The LibJS target is the C++ API that LibJS's users build against, implemented over the Rust runtime's embedding ABI.
-# It links the runtime with the runtime's symbols hidden, so it exports only its own JS_API functions, and every process
-# that links LibJS has exactly one copy of the runtime.
+# LibJS's C++ API, which LibJS's users build against, is implemented over the embedding ABI of the Rust runtime. When
+# LibWeb is built, the API's objects and the runtime go into LibWeb's library, whose Rust crate builds the runtime, so
+# that a process has one copy of the runtime and LibWeb's Rust code depends on it directly. Without LibWeb, LibJS is a
+# library of its own, which exports only its own JS_API functions and keeps the runtime's symbols hidden.
+
+# The features the runtime is built with, by LibJS's own crate build or by LibWeb's crate.
+set(LIBJS_RUST_FEATURES allocator)
+if (ENABLE_ADDRESS_SANITIZER)
+ list(APPEND LIBJS_RUST_FEATURES address-sanitizer)
+endif()
+if (ENABLE_THREAD_SANITIZER)
+ list(APPEND LIBJS_RUST_FEATURES thread-sanitizer)
+endif()
+# The JIT is a default feature of the crate, so that cargo builds and lints it unless told otherwise.
+if (ENABLE_JS_JIT)
+ list(APPEND LIBJS_RUST_FEATURES jit)
+endif()
+set(LIBJS_RUST_FEATURES ${LIBJS_RUST_FEATURES} PARENT_SCOPE)
add_subdirectory(Rust)
@@ -79,27 +94,79 @@ set(SOURCES
ToolEntryPoints.cpp
)
-ladybird_lib(LibJS js EXPLICIT_SYMBOL_EXPORT)
+# What every target that includes LibJS's headers needs: the clang plugin that checks the code, LibUnicode, so that
+# ICU's data is in every process that runs JavaScript, and the generated headers of the embedding ABI, which the public
+# headers include, before anything compiles against them.
+add_library(LibJSHeaders INTERFACE)
+target_link_libraries(LibJSHeaders INTERFACE JSClangPlugin LibUnicode)
+add_dependencies(LibJSHeaders libjs_embedding_headers-ffi-headers)
+if (NOT BUILD_SHARED_LIBS)
+ target_compile_definitions(LibJSHeaders INTERFACE LIBJS_STATIC_DEFINE)
+endif()
+add_lagom_library_install_rules(LibJSHeaders ALIAS_NAME JSHeaders)
-target_link_libraries(LibJS PRIVATE LibCore LibCrypto LibGC LibTextCodec)
+# The objects of the C++ API, compiled once for whichever library they go into. Their export header is generated under
+# LibJS's name, so that JS_API means the same wherever they are, and its guard is the define the objects are compiled
+# with, as it would be for a shared LibJS.
+add_library(LibJSObjects OBJECT ${SOURCES})
+ladybird_library_setup(LibJSObjects)
+target_link_libraries(LibJSObjects PUBLIC LibJSHeaders)
+target_link_libraries(LibJSObjects PRIVATE LibCore LibCrypto LibGC LibSyntax LibTextCodec)
+target_compile_definitions(LibJSObjects PRIVATE LibJS_EXPORTS)
+set_target_properties(LibJSObjects PROPERTIES DEFINE_SYMBOL LibJS_EXPORTS)
+ladybird_generate_export_header(LibJSObjects js BASE_NAME LibJS)
-# JS::SyntaxHighlighter is a LibSyntax highlighter.
-target_link_libraries(LibJS PRIVATE LibSyntax)
+if (LIBJS_FOLDED_INTO_LIBWEB)
+ # LibJS is what a target that also uses LibWeb links: LibWeb's library holds the objects and the runtime.
+ add_library(LibJS INTERFACE)
+ target_link_libraries(LibJS INTERFACE LibWeb LibJSHeaders)
+ set_target_properties(LibJS PROPERTIES EXPORT_NAME JS)
+ ladybird_install_library_headers(LibJS JS)
+ add_lagom_library_install_rules(LibJS ALIAS_NAME JS)
-# Link LibUnicode publicly to ensure ICU data (which is in libicudata.a) is available in any process using LibJS.
-target_link_libraries(LibJS PUBLIC LibUnicode)
+ # LibJSStandalone is what a JavaScript tool that does not use LibWeb links: the objects, and the runtime out of the
+ # archive of LibWeb's crate, of which the tool takes only the members it references, so that building a tool never
+ # builds LibWeb's C++. The tool initializes the runtime's panic hook and demangler as the crate the runtime is.
+ add_rust_crate_initializer(libjs_rust)
+ add_library(LibJSStandalone INTERFACE)
+ target_link_libraries(LibJSStandalone INTERFACE
+ $<TARGET_OBJECTS:LibJSObjects>
+ $<TARGET_OBJECTS:libjs_rust_init>
+ LibJSHeaders libweb_bindings_rust_archive AK LibCore LibCrypto LibGC LibSyntax LibTextCodec
+ )
+ if ((LINUX OR BSD) AND BUILD_SHARED_LIBS)
+ # The tool's copy of the runtime, with its Rust standard library, stays out of its dynamic symbol table, as the
+ # copy in LibJS's own library does. LibWeb's directory, which imports the archive, comes after this one, so
+ # the archive's name is resolved when the build is generated.
+ target_link_options(LibJSStandalone INTERFACE
+ "LINKER:--exclude-libs,$<TARGET_FILE_NAME:libweb_bindings_rust_archive>"
+ )
+ elseif ((LINUX OR BSD) AND NOT BUILD_SHARED_LIBS)
+ # The archive carries its own copy of the Rust standard library and of the crates it shares with the Rust
+ # archives of LibUnicode and the other libraries a tool links, whose exported symbols then appear twice in
+ # static ELF links.
+ target_link_options(LibJSStandalone INTERFACE LINKER:--allow-multiple-definition)
+ endif()
+else()
+ set(SOURCES $<TARGET_OBJECTS:LibJSObjects>)
+ ladybird_lib(LibJS js)
+ set_target_properties(LibJS PROPERTIES LINKER_LANGUAGE CXX WINDOWS_EXPORT_ALL_SYMBOLS OFF)
+ target_link_libraries(LibJS PUBLIC LibJSHeaders)
+ target_link_libraries(LibJS PRIVATE LibCore LibCrypto LibGC LibSyntax LibTextCodec)
-target_link_libraries(LibJS PUBLIC JSClangPlugin)
+ if (NOT BUILD_SHARED_LIBS OR WIN32)
+ target_link_libraries(LibJS PRIVATE libjs_rust)
+ elseif (APPLE)
+ set(CMAKE_LINK_LIBRARY_USING_load_hidden "LINKER:-load_hidden,<LIBRARY>")
+ set(CMAKE_LINK_LIBRARY_USING_load_hidden_SUPPORTED TRUE)
+ target_link_libraries(LibJS PRIVATE "$<LINK_LIBRARY:load_hidden,libjs_rust>")
+ else()
+ target_link_libraries(LibJS PRIVATE libjs_rust)
+ get_target_property(libjs_rust_archive libjs_rust IMPORTED_LOCATION)
+ cmake_path(GET libjs_rust_archive FILENAME libjs_rust_archive_name)
+ target_link_options(LibJS PRIVATE "LINKER:--exclude-libs,${libjs_rust_archive_name}")
+ endif()
-if (NOT BUILD_SHARED_LIBS OR WIN32)
- target_link_libraries(LibJS PRIVATE libjs_rust)
-elseif (APPLE)
- set(CMAKE_LINK_LIBRARY_USING_load_hidden "LINKER:-load_hidden,<LIBRARY>")
- set(CMAKE_LINK_LIBRARY_USING_load_hidden_SUPPORTED TRUE)
- target_link_libraries(LibJS PRIVATE "$<LINK_LIBRARY:load_hidden,libjs_rust>")
-else()
- target_link_libraries(LibJS PRIVATE libjs_rust)
- get_target_property(libjs_rust_archive libjs_rust IMPORTED_LOCATION)
- cmake_path(GET libjs_rust_archive FILENAME libjs_rust_archive_name)
- target_link_options(LibJS PRIVATE "LINKER:--exclude-libs,${libjs_rust_archive_name}")
+ add_library(LibJSStandalone INTERFACE)
+ target_link_libraries(LibJSStandalone INTERFACE LibJS)
endif()
diff --git a/Libraries/LibJS/Rust/CMakeLists.txt b/Libraries/LibJS/Rust/CMakeLists.txt
index 9a84bf52cc6..059559783d0 100644
--- a/Libraries/LibJS/Rust/CMakeLists.txt
+++ b/Libraries/LibJS/Rust/CMakeLists.txt
@@ -1,13 +1,19 @@
-set(LIBJS_RUST_FEATURES allocator)
-if (ENABLE_ADDRESS_SANITIZER)
- list(APPEND LIBJS_RUST_FEATURES address-sanitizer)
-endif()
-if (ENABLE_THREAD_SANITIZER)
- list(APPEND LIBJS_RUST_FEATURES thread-sanitizer)
-endif()
-# The JIT is a default feature of the crate, so that cargo builds and lints it unless told otherwise.
-if (ENABLE_JS_JIT)
- list(APPEND LIBJS_RUST_FEATURES jit)
+# The headers of the embedding ABI, LibJS/Embedding/ABI.h and LibJS/Embedding/Layout.h, which LibJS's public headers
+# include. A crate of its own writes them, so that the C++ that includes them waits for the headers alone, not for the
+# runtime, which takes far longer to build.
+generate_rust_ffi_headers(
+ MANIFEST_PATH embedding_headers/Cargo.toml
+ CRATE_NAME libjs_embedding_headers
+ FFI_OUTPUT_DIR ${CMAKE_BINARY_DIR}/Libraries
+ FFI_HEADERS
+ LibJS/Embedding/ABI.h
+ LibJS/Embedding/Layout.h
+)
+
+# The runtime crate. When LibWeb is built, LibWeb's crate builds it as a dependency, with the same features, and
+# LibWeb's library links it (Libraries/LibWeb/CMakeLists.txt).
+if (LIBJS_FOLDED_INTO_LIBWEB)
+ return()
endif()
import_rust_crate(
@@ -15,15 +21,7 @@ import_rust_crate(
CRATE_NAME libjs_rust
NO_DEFAULT_FEATURES
FEATURES ${LIBJS_RUST_FEATURES}
- FFI_OUTPUT_DIR ${CMAKE_BINARY_DIR}/Libraries
- FFI_HEADERS
- LibJS/Embedding/ABI.h
- LibJS/Embedding/Layout.h
)
-# The headers land in the build tree's Libraries directory, which every target already includes. CMake would otherwise
-# make the include directory of an imported target a system one for its consumers, hiding the warnings of every header
-# generated there.
-set_target_properties(libjs_rust PROPERTIES SYSTEM OFF)
# The runtime allocates its cells from LibGC, and its regex engine reads Unicode properties from LibUnicode.
target_link_libraries(libjs_rust INTERFACE LibGC LibUnicode)
diff --git a/Libraries/LibJS/Rust/Cargo.toml b/Libraries/LibJS/Rust/Cargo.toml
index c50fe541300..ada30174bff 100644
--- a/Libraries/LibJS/Rust/Cargo.toml
+++ b/Libraries/LibJS/Rust/Cargo.toml
@@ -42,7 +42,6 @@ iced-x86 = { version = "1.21", default-features = false, features = ["decoder",
farm64 = { package = "fARM64", version = "0.0.2", features = ["alloc"] }
[build-dependencies]
-cbindgen = { version = "0.29", default-features = false }
cc = "1"
flapc = { path = "../Flap" }
libjs_abi = { path = "../ABI" }
diff --git a/Libraries/LibJS/Rust/build.rs b/Libraries/LibJS/Rust/build.rs
index 0ffe9d1df35..6d6889cc564 100644
--- a/Libraries/LibJS/Rust/build.rs
+++ b/Libraries/LibJS/Rust/build.rs
@@ -6,13 +6,13 @@
//! Builds everything the crate shares with the interpreter: the layout file flapc compiles interpreter.flap against,
//! computed from the crate's own layout module, the interpreter itself, assembled into the crate's static library,
-//! and the static assertions that keep the crate's types in line with that layout. It also generates the C headers
-//! of the embedding ABI, LibJS/Embedding/ABI.h from src/embedding and LibJS/Embedding/Layout.h from the layout module, and the frontend's
-//! instruction types from interpreter.flap.
+//! and the static assertions that keep the crate's types in line with that layout and with the embedding header
+//! LibJS/Embedding/Layout.h, which the build script of embedding_headers writes from the same module. It also
+//! generates the frontend's instruction types from interpreter.flap.
use std::env;
use std::fs;
-use std::path::{Path, PathBuf};
+use std::path::PathBuf;
// The build script only reads the layout, so most of what the crate uses goes unused here.
#[allow(dead_code)]
@@ -25,9 +25,6 @@ mod layout_forward;
#[path = "src/gc/class_id.rs"]
mod class_id;
-#[path = "generate/abi_header.rs"]
-mod abi_header;
-
#[path = "generate/c_type_spelling.rs"]
mod c_type_spelling;
@@ -40,6 +37,8 @@ mod instructions;
#[path = "generate/layout_table.rs"]
mod layout_table;
+// The build script only compiles the static assertions of the layout header, which embedding_headers writes.
+#[allow(dead_code)]
#[path = "generate/layout_header.rs"]
mod layout_header;
@@ -49,6 +48,11 @@ mod ops;
#[path = "generate/runtime_functions.rs"]
mod runtime_functions;
+#[path = "generate/write_if_changed.rs"]
+mod write_if_changed;
+
+use write_if_changed::write_if_changed;
+
const KIB: u64 = 1024;
const GIB: u64 = 1024 * 1024 * KIB;
const TIB: u64 = 1024 * GIB;
@@ -117,7 +121,6 @@ fn main() {
println!("cargo:rerun-if-changed=generate");
println!("cargo:rerun-if-changed=src/layout");
println!("cargo:rerun-if-changed=src/gc/class_id.rs");
- println!("cargo:rerun-if-changed=src/embedding");
println!("cargo:rerun-if-changed={}", interpreter_source.display());
println!("cargo:rerun-if-changed={}", layout_fixture.display());
println!("cargo:rerun-if-env-changed=MACOSX_DEPLOYMENT_TARGET");
@@ -159,17 +162,9 @@ fn main() {
&layout.static_assertions,
);
- let embedding_header_directory = output_directory.join("LibJS/Embedding");
- fs::create_dir_all(&embedding_header_directory).expect("create the directory of the embedding headers");
- abi_header::generate(
- &manifest_directory.join("src/embedding/mod.rs"),
- &embedding_header_directory.join("ABI.h"),
- );
- let layout_header = layout_header::generate();
- write_if_changed(&embedding_header_directory.join("Layout.h"), &layout_header.text);
write_if_changed(
&output_directory.join("layout_header_static_assertions.rs"),
- &layout_header.static_assertions,
+ &layout_header::generate().static_assertions,
);
let interpreter_source_text = fs::read_to_string(&interpreter_source).expect("read interpreter.flap");
@@ -355,10 +350,3 @@ fn assemble_interpreter(target: &Target, assembly_paths: &[PathBuf]) {
}
build.compile("libjs_runtime_interpreter");
}
-
-fn write_if_changed(path: &Path, contents: &str) {
- if fs::read_to_string(path).is_ok_and(|existing| existing == contents) {
- return;
- }
- fs::write(path, contents).unwrap_or_else(|error| panic!("write {}: {error}", path.display()));
-}
diff --git a/Libraries/LibJS/Rust/embedding_headers/Cargo.toml b/Libraries/LibJS/Rust/embedding_headers/Cargo.toml
new file mode 100644
index 00000000000..287c13cd26b
--- /dev/null
+++ b/Libraries/LibJS/Rust/embedding_headers/Cargo.toml
@@ -0,0 +1,16 @@
+[package]
+name = "libjs_embedding_headers"
+version = "0.1.0"
+edition = "2024"
+
+[lib]
+crate-type = ["rlib"]
+
+# After changing dependencies, regenerate the Flatpak sources:
+# python3 Meta/CMake/flatpak/generate-cargo-sources.py
+[build-dependencies]
+cbindgen = { version = "0.29", default-features = false }
+libjs_abi = { path = "../../ABI" }
+
+[lints]
+workspace = true
diff --git a/Libraries/LibJS/Rust/embedding_headers/build.rs b/Libraries/LibJS/Rust/embedding_headers/build.rs
new file mode 100644
index 00000000000..8aa439ec1d7
--- /dev/null
+++ b/Libraries/LibJS/Rust/embedding_headers/build.rs
@@ -0,0 +1,57 @@
+/*
+ * Copyright (c) 2026-present, the Ladybird developers.
+ *
+ * SPDX-License-Identifier: BSD-2-Clause
+ */
+
+//! Writes the C headers of the embedding ABI into LibJS/Embedding under OUT_DIR, from the sources of the runtime
+//! crate: ABI.h, the declarations of the ABI's functions and types, from src/embedding with cbindgen, and Layout.h,
+//! the offsets, sizes and constants of the runtime's structures that an embedder reads or writes directly, from the
+//! layout module, which the runtime's own build script also compiles to check the same layout against its types.
+
+use std::env;
+use std::fs;
+use std::path::PathBuf;
+
+// The build script only reads the layout, so most of what the runtime uses goes unused here.
+#[allow(dead_code)]
+#[path = "../src/layout/mod.rs"]
+mod layout;
+
+#[path = "../generate/layout_forward.rs"]
+mod layout_forward;
+
+#[path = "../src/gc/class_id.rs"]
+mod class_id;
+
+#[path = "../generate/abi_header.rs"]
+mod abi_header;
+
+#[path = "../generate/c_type_spelling.rs"]
+mod c_type_spelling;
+
+// The build script only writes the layout header, whose static assertions the runtime's build script compiles.
+#[allow(dead_code)]
+#[path = "../generate/layout_header.rs"]
+mod layout_header;
+
+#[path = "../generate/write_if_changed.rs"]
+mod write_if_changed;
+
+fn main() {
+ let runtime_directory = PathBuf::from(env::var("CARGO_MANIFEST_DIR").expect("CARGO_MANIFEST_DIR")).join("..");
+ let output_directory = PathBuf::from(env::var("OUT_DIR").expect("OUT_DIR"));
+
+ println!("cargo:rerun-if-changed=build.rs");
+ for input in ["generate", "src/embedding", "src/layout", "src/gc/class_id.rs"] {
+ println!("cargo:rerun-if-changed={}", runtime_directory.join(input).display());
+ }
+
+ let header_directory = output_directory.join("LibJS/Embedding");
+ fs::create_dir_all(&header_directory).expect("create the directory of the embedding headers");
+ abi_header::generate(
+ &runtime_directory.join("src/embedding/mod.rs"),
+ &header_directory.join("ABI.h"),
+ );
+ write_if_changed::write_if_changed(&header_directory.join("Layout.h"), &layout_header::generate().text);
+}
diff --git a/Libraries/LibJS/Rust/embedding_headers/src/lib.rs b/Libraries/LibJS/Rust/embedding_headers/src/lib.rs
new file mode 100644
index 00000000000..60c5d7341d0
--- /dev/null
+++ b/Libraries/LibJS/Rust/embedding_headers/src/lib.rs
@@ -0,0 +1,9 @@
+/*
+ * Copyright (c) 2026-present, the Ladybird developers.
+ *
+ * SPDX-License-Identifier: BSD-2-Clause
+ */
+
+//! A crate with no code of its own: its build script writes the C headers of the embedding ABI of the LibJS runtime,
+//! which LibJS's public headers include, so that the C++ that includes them waits for the headers alone rather than
+//! for the runtime crate (Libraries/LibJS/Rust/CMakeLists.txt).
diff --git a/Libraries/LibJS/Rust/generate/abi_header.rs b/Libraries/LibJS/Rust/generate/abi_header.rs
index 110b51542ee..9ec8142e007 100644
--- a/Libraries/LibJS/Rust/generate/abi_header.rs
+++ b/Libraries/LibJS/Rust/generate/abi_header.rs
@@ -42,7 +42,7 @@ fn configuration() -> cbindgen::Config {
),
include_guard: Some("LIBJS_EMBEDDING_ABI_H".to_string()),
autogen_warning: Some(
- "// Generated by the libjs_rust build script from src/embedding -- DO NOT EDIT".to_string(),
+ "// Generated by the build script of libjs_embedding_headers from the runtime's src/embedding -- DO NOT EDIT".to_string(),
),
no_includes: true,
// LibGC/CAPI.h declares the LibGC types the ABI passes, such as the GCVisitor through which an embedder
diff --git a/Libraries/LibJS/Rust/generate/layout_header.rs b/Libraries/LibJS/Rust/generate/layout_header.rs
index 6a581aa8dae..8a7591892d9 100644
--- a/Libraries/LibJS/Rust/generate/layout_header.rs
+++ b/Libraries/LibJS/Rust/generate/layout_header.rs
@@ -50,7 +50,7 @@ const PREAMBLE: &str = "\
* SPDX-License-Identifier: BSD-2-Clause
*/
-// Generated by the libjs_rust build script from its layout module -- DO NOT EDIT
+// Generated by the build script of libjs_embedding_headers from the runtime's layout module -- DO NOT EDIT
//
// The offsets, sizes and constants of the runtime's structures that an embedder reads or writes directly.
diff --git a/Libraries/LibJS/Rust/generate/write_if_changed.rs b/Libraries/LibJS/Rust/generate/write_if_changed.rs
new file mode 100644
index 00000000000..3fca334effe
--- /dev/null
+++ b/Libraries/LibJS/Rust/generate/write_if_changed.rs
@@ -0,0 +1,17 @@
+/*
+ * Copyright (c) 2026-present, the Ladybird developers.
+ *
+ * SPDX-License-Identifier: BSD-2-Clause
+ */
+
+use std::fs;
+use std::path::Path;
+
+/// Writes `contents` to `path` unless the file already holds them, so that what depends on the file is not rebuilt
+/// for a write that changed nothing.
+pub fn write_if_changed(path: &Path, contents: &str) {
+ if fs::read_to_string(path).is_ok_and(|existing| existing == contents) {
+ return;
+ }
+ fs::write(path, contents).unwrap_or_else(|error| panic!("write {}: {error}", path.display()));
+}
diff --git a/Libraries/LibTest/CMakeLists.txt b/Libraries/LibTest/CMakeLists.txt
index 56cfd784764..182e863af47 100644
--- a/Libraries/LibTest/CMakeLists.txt
+++ b/Libraries/LibTest/CMakeLists.txt
@@ -2,7 +2,7 @@ add_library(LibTestMain OBJECT TestMain.cpp AssertionHandler.cpp)
target_link_libraries(LibTestMain PUBLIC GenericClangPlugin)
add_library(JavaScriptTestRunnerMain OBJECT JavaScriptTestRunnerMain.cpp)
-target_link_libraries(JavaScriptTestRunnerMain PRIVATE LibJS LibGC)
+target_link_libraries(JavaScriptTestRunnerMain PRIVATE LibJSStandalone LibGC)
set(SOURCES
TestSuite.cpp
diff --git a/Libraries/LibWeb/Bindings/Rust/Cargo.toml b/Libraries/LibWeb/Bindings/Rust/Cargo.toml
new file mode 100644
index 00000000000..90d9d8ea92a
--- /dev/null
+++ b/Libraries/LibWeb/Bindings/Rust/Cargo.toml
@@ -0,0 +1,28 @@
+[package]
+name = "libweb_bindings_rust"
+version = "0.1.0"
+edition = "2024"
+
+[lib]
+crate-type = ["staticlib", "rlib"]
+
+[features]
+# The features of the LibJS runtime, which this crate builds for LibWeb's library. The JIT is a default feature, as it
+# is of the runtime's crate, so that cargo builds and lints the crate the way LibWeb's library does unless told otherwise.
+default = ["jit"]
+allocator = ["dep:ladybird_allocator", "libjs_rust/allocator", "libweb_rust/allocator"]
+jit = ["libjs_rust/jit"]
+address-sanitizer = ["libjs_rust/address-sanitizer"]
+thread-sanitizer = ["libjs_rust/thread-sanitizer", "libweb_rust/thread-sanitizer"]
+
+# After changing dependencies, regenerate the Flatpak sources:
+# python3 Meta/CMake/flatpak/generate-cargo-sources.py
+[dependencies]
+ak = { path = "../../../../AK/Rust" }
+ladybird_allocator = { path = "../../../RustAllocator", optional = true }
+libjs_rust = { path = "../../../LibJS/Rust", default-features = false }
+libweb_rust = { path = "../../Rust" }
+rustc-demangle = "0.1"
+
+[lints]
+workspace = true
diff --git a/Libraries/LibWeb/Bindings/Rust/src/lib.rs b/Libraries/LibWeb/Bindings/Rust/src/lib.rs
new file mode 100644
index 00000000000..85bc80f4fc6
--- /dev/null
+++ b/Libraries/LibWeb/Bindings/Rust/src/lib.rs
@@ -0,0 +1,29 @@
+/*
+ * Copyright (c) 2026-present, the Ladybird developers.
+ *
+ * SPDX-License-Identifier: BSD-2-Clause
+ */
+
+//! The Rust code of LibWeb that runs on the LibJS runtime. The crate is the Rust part of LibWeb's library: it depends
+//! on the runtime and on libweb_rust, and the library links its archive, so that the runtime is in a process once and
+//! this crate reaches it as any Rust code reaches a crate it depends on.
+//!
+//! The crate's tests cover the code that does not touch the runtime. A test binary keeps every extern "C" function of
+//! every crate it links, so linking the runtime would make it link every C function the runtime imports as well; the
+//! runtime and libweb_rust are left out of the tests instead, as the runtime's own crate leaves out its engine.
+
+#[cfg(feature = "allocator")]
+extern crate ladybird_allocator;
+
+#[path = "../../../../RustDemangle.rs"]
+mod rust_demangle;
+
+#[path = "../../../../RustPanic.rs"]
+mod rust_panic;
+
+// NB: Only C++ calls into the runtime and into libweb_rust so far, so nothing in this crate names them. Linking them
+// keeps their extern "C" functions in the static library.
+#[cfg(not(test))]
+extern crate libjs_rust;
+#[cfg(not(test))]
+extern crate libweb_rust;
diff --git a/Libraries/LibWeb/CMakeLists.txt b/Libraries/LibWeb/CMakeLists.txt
index 391bab02772..e02127bc313 100644
--- a/Libraries/LibWeb/CMakeLists.txt
+++ b/Libraries/LibWeb/CMakeLists.txt
@@ -1167,9 +1167,14 @@ set(GENERATED_SOURCES
)
ladybird_lib(LibWeb web EXPLICIT_SYMBOL_EXPORT)
-target_link_libraries(LibWeb PUBLIC LibCompositing LibWebCommon)
+# LibJS's C++ API is part of this library, over the Rust runtime that the library's crate builds below
+# (Libraries/LibJS/CMakeLists.txt). The API's objects export JS_API, and so does the library's own code that includes
+# LibJS's headers.
+target_sources(LibWeb PRIVATE $<TARGET_OBJECTS:LibJSObjects>)
+target_compile_definitions(LibWeb PRIVATE LibJS_EXPORTS)
+target_link_libraries(LibWeb PUBLIC LibCompositing LibWebCommon LibJSHeaders)
-target_link_libraries(LibWeb PRIVATE LibCore LibCompress LibCrypto LibJS LibHTTP LibGfx LibIPC LibRegex LibSyntax LibTextCodec LibUnicode LibAudio LibMedia LibMediaClient LibWasm LibXML LibURL LibTLS LibRequests LibGC LibImageDecoderClient LibThreading LibXml2::LibXml2)
+target_link_libraries(LibWeb PRIVATE LibCore LibCompress LibCrypto LibHTTP LibGfx LibIPC LibRegex LibSyntax LibTextCodec LibUnicode LibAudio LibMedia LibMediaClient LibWasm LibXML LibURL LibTLS LibRequests LibGC LibImageDecoderClient LibThreading LibXml2::LibXml2)
# LibWeb still includes ANGLE's GLES headers for WebGL constants and types, but
# the actual GL entry points live in the Compositor. Copy only ANGLE's compile
@@ -1182,14 +1187,21 @@ foreach(angle_target IN LISTS ANGLE_TARGETS)
target_compile_options(LibWeb PRIVATE $<TARGET_PROPERTY:${angle_target},INTERFACE_COMPILE_OPTIONS>)
endforeach()
-set(libweb_rust_features allocator)
-if (ENABLE_THREAD_SANITIZER)
- list(APPEND libweb_rust_features thread-sanitizer)
-endif()
+# The library's Rust code: the bindings crate, which depends on the LibJS runtime and on libweb_rust, so that one archive
+# holds all three and the runtime is in the process once. The runtime's features are LibJS's.
import_rust_crate(
- MANIFEST_PATH Rust/Cargo.toml
+ MANIFEST_PATH Bindings/Rust/Cargo.toml
+ CRATE_NAME libweb_bindings_rust
+ NO_DEFAULT_FEATURES
+ FEATURES ${LIBJS_RUST_FEATURES}
+ # The copy of libgfx_rust in this crate, which TestRustCrateCopies reaches by name.
+ KEEP_SYMBOLS ladybird_gfx_register_rust_crate_copy
+)
+# The headers that the build script of libweb_rust, which the archive bundles, writes.
+sync_rust_crate_ffi_headers(
CRATE_NAME libweb_rust
- FEATURES ${libweb_rust_features}
+ PRODUCED_BY libweb_bindings_rust
+ FFI_OUTPUT_DIR "${CMAKE_CURRENT_BINARY_DIR}"
FFI_HEADERS
HTML/Parser/RustFFI.h
RustFFI.h
@@ -1203,10 +1215,10 @@ import_rust_crate(
SelectorStateFactsGenerated.inc
Layout/TreeBuilderRustFFI.h
Layout/LayoutRustFFI.h
- # The copy of libgfx_rust in this crate, which TestRustCrateCopies reaches by name.
- KEEP_SYMBOLS ladybird_gfx_register_rust_crate_copy
)
-target_link_libraries(libweb_rust INTERFACE LibGfx)
+add_dependencies(LibWeb libweb_rust-ffi-headers)
+target_link_libraries(libweb_bindings_rust INTERFACE LibGfx LibGC LibUnicode)
+test_rust_crate(MANIFEST_PATH Bindings/Rust/Cargo.toml CRATE_NAME libweb_bindings_rust)
test_rust_crate(MANIFEST_PATH Rust/Cargo.toml CRATE_NAME libweb_rust)
set(content_blocker_rust_features "")
@@ -1214,8 +1226,8 @@ if (NOT BUILD_SHARED_LIBS)
set(content_blocker_rust_features FEATURES allocator)
endif()
import_rust_crate(MANIFEST_PATH ContentBlocker/Rust/Cargo.toml CRATE_NAME libweb_content_blocker_rust ${content_blocker_rust_features} FFI_HEADER ContentBlockerRustFFI.h)
-target_link_libraries(LibWeb PRIVATE libweb_rust libweb_content_blocker_rust)
-get_target_property(_libweb_rust_lib libweb_rust IMPORTED_LOCATION)
+target_link_libraries(LibWeb PRIVATE libweb_bindings_rust libweb_content_blocker_rust)
+get_target_property(_libweb_rust_lib libweb_bindings_rust IMPORTED_LOCATION)
get_target_property(_libweb_content_blocker_rust_lib libweb_content_blocker_rust IMPORTED_LOCATION)
set_property(SOURCE HTML/Parser/HTMLTokenizer.cpp APPEND PROPERTY OBJECT_DEPENDS ${_libweb_rust_lib})
set_property(SOURCE HTML/Parser/HTMLParser.cpp APPEND PROPERTY OBJECT_DEPENDS ${_libweb_rust_lib})
@@ -1226,7 +1238,7 @@ endif()
if(NOT BUILD_SHARED_LIBS)
add_custom_command(TARGET LibWeb POST_BUILD
- COMMAND ${CMAKE_AR} -x $<TARGET_FILE:libweb_rust>
+ COMMAND ${CMAKE_AR} -x $<TARGET_FILE:libweb_bindings_rust>
COMMAND ${CMAKE_AR} -x $<TARGET_FILE:libweb_content_blocker_rust>
COMMAND ${CMAKE_AR} -qS $<TARGET_FILE:LibWeb> *.o
COMMAND ${CMAKE_RANLIB} $<TARGET_FILE:LibWeb>
diff --git a/Libraries/LibWeb/Rust/Cargo.toml b/Libraries/LibWeb/Rust/Cargo.toml
index 599274ad353..09719e80481 100644
--- a/Libraries/LibWeb/Rust/Cargo.toml
+++ b/Libraries/LibWeb/Rust/Cargo.toml
@@ -4,7 +4,7 @@ version = "0.1.0"
edition = "2024"
[lib]
-crate-type = ["rlib", "staticlib"]
+crate-type = ["rlib"]
[features]
allocator = ["dep:ladybird_allocator"]
diff --git a/Meta/CMake/RustCrateInit.cpp.in b/Meta/CMake/RustCrateInit.cpp.in
index 47b2c82c3ec..d06e93e03b8 100644
--- a/Meta/CMake/RustCrateInit.cpp.in
+++ b/Meta/CMake/RustCrateInit.cpp.in
@@ -4,16 +4,16 @@
* SPDX-License-Identifier: BSD-2-Clause
*/
-extern "C" void ladybird_init_rust_panic_@ARG_CRATE_NAME@();
-extern "C" void ladybird_init_rust_demangle_@ARG_CRATE_NAME@();
+extern "C" void ladybird_init_rust_panic_@RUST_CRATE_NAME@();
+extern "C" void ladybird_init_rust_demangle_@RUST_CRATE_NAME@();
namespace {
struct RustCrateInitializer {
RustCrateInitializer()
{
- ladybird_init_rust_panic_@ARG_CRATE_NAME@();
- ladybird_init_rust_demangle_@ARG_CRATE_NAME@();
+ ladybird_init_rust_panic_@RUST_CRATE_NAME@();
+ ladybird_init_rust_demangle_@RUST_CRATE_NAME@();
}
};
diff --git a/Meta/CMake/rust_crate.cmake b/Meta/CMake/rust_crate.cmake
index 582e40c3907..4ccbd145427 100644
--- a/Meta/CMake/rust_crate.cmake
+++ b/Meta/CMake/rust_crate.cmake
@@ -27,10 +27,6 @@ function(import_rust_crate)
if (ARG_FFI_HEADER)
list(APPEND ffi_headers "${ARG_FFI_HEADER}")
endif()
- set(ffi_output "")
- foreach(ffi_header IN LISTS ffi_headers)
- list(APPEND ffi_output "${ARG_FFI_OUTPUT_DIR}/${ffi_header}")
- endforeach()
_rust_crate_common_setup(
MANIFEST_PATH "${ARG_MANIFEST_PATH}"
@@ -61,49 +57,16 @@ function(import_rust_crate)
set(depfile "${cargo_output_dir}/lib${ARG_CRATE_NAME}.d")
endif()
- add_custom_command(
- OUTPUT "${output_lib}"
- COMMAND ${CMAKE_COMMAND}
- -DLOG=${cargo_output_dir}/cargo-${ARG_CRATE_NAME}.log
- -P "${CMAKE_CURRENT_FUNCTION_LIST_DIR}/run_quiet.cmake"
- --
- ${CMAKE_COMMAND} -E env ${cargo_env} CARGO_TERM_PROGRESS_WHEN=never TERM=dumb
- "${RUST_CARGO}"
- rustc
- --lib
- ${cargo_feature_flags}
- ${cargo_common_flags}
- DEPENDS "${manifest_path}"
- "${workspace_dir}/Cargo.lock" "${workspace_dir}/Cargo.toml"
- "${RUST_RUSTC}" "${CMAKE_SOURCE_DIR}/rust-toolchain.toml"
- DEPFILE "${depfile}"
- COMMENT "Building Rust crate ${ARG_CRATE_NAME}"
- JOB_POOL cargo
- COMMAND_EXPAND_LISTS
- )
+ _rust_crate_build_command(OUTPUT "${output_lib}" DEPFILE "${depfile}")
- if (ffi_output)
- set(sync_ffi_header_commands "")
- foreach(ffi_header IN LISTS ffi_headers)
- list(APPEND sync_ffi_header_commands
- COMMAND
- ${CMAKE_COMMAND}
- -DCARGO_BUILD_SCRIPT_DIR=${cargo_output_dir}/build
- -DCRATE_NAME=${ARG_CRATE_NAME}
- -DFFI_HEADER=${ffi_header}
- -DFFI_OUTPUT_DIR=${ARG_FFI_OUTPUT_DIR}
- -P "${CMAKE_CURRENT_FUNCTION_LIST_DIR}/sync_rust_ffi_header.cmake"
- )
- endforeach()
-
- # Keep Cargo's output separate from copy_if_different outputs. If they share an edge, Ninja's restat timestamp
- # may predate files generated by build.rs and listed in the Cargo depfile, causing the crate to be incorrectly
- # considered dirty on the next build.
- add_custom_command(
- OUTPUT ${ffi_output}
- ${sync_ffi_header_commands}
- DEPENDS "${output_lib}"
- COMMAND_EXPAND_LISTS
+ set(ffi_output "")
+ if (ffi_headers)
+ _rust_crate_sync_ffi_headers(
+ CRATE_NAME ${ARG_CRATE_NAME}
+ CARGO_OUTPUT "${output_lib}"
+ FFI_OUTPUT_DIR "${ARG_FFI_OUTPUT_DIR}"
+ FFI_HEADERS ${ffi_headers}
+ OUTPUT_VAR ffi_output
)
endif()
@@ -126,23 +89,158 @@ function(import_rust_crate)
endif()
endforeach()
+ add_rust_crate_initializer(${ARG_CRATE_NAME})
+ target_link_libraries(${ARG_CRATE_NAME} INTERFACE $<TARGET_OBJECTS:${ARG_CRATE_NAME}_init>)
+
+ _rust_crate_link_runtime_libraries(${ARG_CRATE_NAME})
+
+ # The archive on its own, without the initializer and the kept symbols of the library that imports the crate, for a
+ # target that takes a crate the archive bundles out of it, as the JavaScript tools take the LibJS runtime out of
+ # LibWeb's crate.
+ add_library(${ARG_CRATE_NAME}_archive STATIC IMPORTED GLOBAL)
+ set_target_properties(${ARG_CRATE_NAME}_archive PROPERTIES IMPORTED_LOCATION "${output_lib}")
+ add_dependencies(${ARG_CRATE_NAME}_archive ${ARG_CRATE_NAME}-build)
+ _rust_crate_link_runtime_libraries(${ARG_CRATE_NAME}_archive)
+endfunction()
+
+# The cargo invocation that builds the library of the crate _rust_crate_common_setup() was called for, as the custom
+# command that produces OUTPUT with the dependencies cargo lists in DEPFILE.
+function(_rust_crate_build_command)
+ cmake_parse_arguments(PARSE_ARGV 0 ARG "" "OUTPUT;DEPFILE" "")
+
+ add_custom_command(
+ OUTPUT "${ARG_OUTPUT}"
+ COMMAND ${CMAKE_COMMAND}
+ -DLOG=${cargo_output_dir}/cargo-${ARG_CRATE_NAME}.log
+ -P "${CMAKE_CURRENT_FUNCTION_LIST_DIR}/run_quiet.cmake"
+ --
+ ${CMAKE_COMMAND} -E env ${cargo_env} CARGO_TERM_PROGRESS_WHEN=never TERM=dumb
+ "${RUST_CARGO}"
+ rustc
+ --lib
+ ${cargo_feature_flags}
+ ${cargo_common_flags}
+ DEPENDS "${manifest_path}"
+ "${workspace_dir}/Cargo.lock" "${workspace_dir}/Cargo.toml"
+ "${RUST_RUSTC}" "${CMAKE_SOURCE_DIR}/rust-toolchain.toml"
+ DEPFILE "${ARG_DEPFILE}"
+ COMMENT "Building Rust crate ${ARG_CRATE_NAME}"
+ JOB_POOL cargo
+ COMMAND_EXPAND_LISTS
+ )
+endfunction()
+
+# add_rust_crate_initializer(crate)
+#
+# Defines the object library <crate>_init, whose one object sets up the panic hook and the demangler of the crate in
+# whatever links the object. import_rust_crate() defines it for the crate it imports; a target that takes a crate out
+# of the archive of another import, as the JavaScript tools take the LibJS runtime out of LibWeb's crate, defines it for
+# that crate.
+function(add_rust_crate_initializer crate)
+ set(RUST_CRATE_NAME ${crate})
configure_file("${CMAKE_CURRENT_FUNCTION_LIST_DIR}/RustCrateInit.cpp.in"
- "${CMAKE_CURRENT_BINARY_DIR}/${ARG_CRATE_NAME}_init.cpp" @ONLY)
+ "${CMAKE_CURRENT_BINARY_DIR}/${crate}_init.cpp" @ONLY)
# A static library only links in the objects that something references, and nothing references the initializer.
# Putting its object on the link line runs it in whatever executable or shared library links the crate.
- add_library(${ARG_CRATE_NAME}_init OBJECT "${CMAKE_CURRENT_BINARY_DIR}/${ARG_CRATE_NAME}_init.cpp")
- target_link_libraries(${ARG_CRATE_NAME} INTERFACE $<TARGET_OBJECTS:${ARG_CRATE_NAME}_init>)
+ add_library(${crate}_init OBJECT "${CMAKE_CURRENT_BINARY_DIR}/${crate}_init.cpp")
+endfunction()
+# What whatever links a Rust static library links with it.
+function(_rust_crate_link_runtime_libraries target)
# Rust allocations go through AK so allocator overrides also apply across the FFI boundary.
- target_link_libraries(${ARG_CRATE_NAME} INTERFACE AK)
+ target_link_libraries(${target} INTERFACE AK)
# Rust staticlibs bundle the standard library, which on Windows depends on system libraries.
if (WIN32)
- target_link_libraries(${ARG_CRATE_NAME} INTERFACE kernel32 ntdll Ws2_32 userenv)
+ target_link_libraries(${target} INTERFACE kernel32 ntdll Ws2_32 userenv)
endif()
endfunction()
+# _rust_crate_sync_ffi_headers(CRATE_NAME name CARGO_OUTPUT path FFI_OUTPUT_DIR dir FFI_HEADERS header...
+# OUTPUT_VAR var [DEPENDS target...])
+#
+# Copies the FFI headers that the build script of CRATE_NAME writes into FFI_OUTPUT_DIR once CARGO_OUTPUT, the library
+# of the cargo invocation that runs the build script, is built, and returns the copies in OUTPUT_VAR.
+function(_rust_crate_sync_ffi_headers)
+ cmake_parse_arguments(PARSE_ARGV 0 ARG "" "CRATE_NAME;CARGO_OUTPUT;FFI_OUTPUT_DIR;OUTPUT_VAR" "FFI_HEADERS;DEPENDS")
+
+ get_filename_component(cargo_output_dir "${ARG_CARGO_OUTPUT}" DIRECTORY)
+ set(ffi_output "")
+ set(sync_ffi_header_commands "")
+ foreach(ffi_header IN LISTS ARG_FFI_HEADERS)
+ list(APPEND ffi_output "${ARG_FFI_OUTPUT_DIR}/${ffi_header}")
+ list(APPEND sync_ffi_header_commands
+ COMMAND
+ ${CMAKE_COMMAND}
+ -DCARGO_BUILD_SCRIPT_DIR=${cargo_output_dir}/build
+ -DCRATE_NAME=${ARG_CRATE_NAME}
+ -DFFI_HEADER=${ffi_header}
+ -DFFI_OUTPUT_DIR=${ARG_FFI_OUTPUT_DIR}
+ -P "${CMAKE_CURRENT_FUNCTION_LIST_DIR}/sync_rust_ffi_header.cmake"
+ )
+ endforeach()
+
+ # Keep Cargo's output separate from copy_if_different outputs. If they share an edge, Ninja's restat timestamp
+ # may predate files generated by build.rs and listed in the Cargo depfile, causing the crate to be incorrectly
+ # considered dirty on the next build.
+ add_custom_command(
+ OUTPUT ${ffi_output}
+ ${sync_ffi_header_commands}
+ DEPENDS "${ARG_CARGO_OUTPUT}" ${ARG_DEPENDS}
+ COMMAND_EXPAND_LISTS
+ )
+ set(${ARG_OUTPUT_VAR} ${ffi_output} PARENT_SCOPE)
+endfunction()
+
+# sync_rust_crate_ffi_headers(CRATE_NAME name PRODUCED_BY crate FFI_OUTPUT_DIR dir FFI_HEADERS header...)
+#
+# Copies the FFI headers that the build script of CRATE_NAME writes into FFI_OUTPUT_DIR, for a crate that is built as a
+# dependency of PRODUCED_BY, a crate import_rust_crate() imported, rather than imported itself. The copies are made once
+# the import's archive is, by the target <CRATE_NAME>-ffi-headers, which whatever compiles against the headers depends
+# on.
+function(sync_rust_crate_ffi_headers)
+ cmake_parse_arguments(PARSE_ARGV 0 ARG "" "CRATE_NAME;PRODUCED_BY;FFI_OUTPUT_DIR" "FFI_HEADERS")
+
+ get_target_property(producer_archive ${ARG_PRODUCED_BY} IMPORTED_LOCATION)
+ _rust_crate_sync_ffi_headers(
+ CRATE_NAME ${ARG_CRATE_NAME}
+ CARGO_OUTPUT "${producer_archive}"
+ DEPENDS ${ARG_PRODUCED_BY}-build
+ FFI_OUTPUT_DIR "${ARG_FFI_OUTPUT_DIR}"
+ FFI_HEADERS ${ARG_FFI_HEADERS}
+ OUTPUT_VAR ffi_output
+ )
+ add_custom_target(${ARG_CRATE_NAME}-ffi-headers DEPENDS ${ffi_output})
+endfunction()
+
+# generate_rust_ffi_headers(MANIFEST_PATH path/to/Cargo.toml CRATE_NAME name FFI_OUTPUT_DIR dir FFI_HEADERS header...)
+#
+# Builds a crate whose build script writes FFI headers, and nothing else links, and copies the headers into
+# FFI_OUTPUT_DIR by the target <name>-ffi-headers, which whatever compiles against them depends on. Such a crate lets
+# the C++ that includes the headers of a large crate wait for the headers alone rather than for the crate. It is built
+# in the directory of the crates import_rust_crate() builds, so it shares their builds of its dependencies.
+function(generate_rust_ffi_headers)
+ cmake_parse_arguments(PARSE_ARGV 0 ARG "" "MANIFEST_PATH;CRATE_NAME;FFI_OUTPUT_DIR" "FFI_HEADERS")
+
+ _rust_crate_common_setup(
+ MANIFEST_PATH "${ARG_MANIFEST_PATH}"
+ CRATE_NAME ${ARG_CRATE_NAME}
+ )
+ set(cargo_feature_flags "")
+ set(output_lib "${cargo_output_dir}/lib${ARG_CRATE_NAME}.rlib")
+ _rust_crate_build_command(OUTPUT "${output_lib}" DEPFILE "${cargo_output_dir}/lib${ARG_CRATE_NAME}.d")
+
+ _rust_crate_sync_ffi_headers(
+ CRATE_NAME ${ARG_CRATE_NAME}
+ CARGO_OUTPUT "${output_lib}"
+ FFI_OUTPUT_DIR "${ARG_FFI_OUTPUT_DIR}"
+ FFI_HEADERS ${ARG_FFI_HEADERS}
+ OUTPUT_VAR ffi_output
+ )
+ add_custom_target(${ARG_CRATE_NAME}-ffi-headers DEPENDS ${ffi_output})
+endfunction()
+
# build_rust_binary(MANIFEST_PATH path/to/Cargo.toml CRATE_NAME name BINARY_NAME name OUTPUT_PATH_VAR var)
#
# Builds a Rust binary crate target using cargo and exposes the copied binary path through OUTPUT_PATH_VAR.
diff --git a/Meta/CMake/targets.cmake b/Meta/CMake/targets.cmake
index edee42bd353..732e2c61111 100644
--- a/Meta/CMake/targets.cmake
+++ b/Meta/CMake/targets.cmake
@@ -1,6 +1,11 @@
include(${CMAKE_CURRENT_LIST_DIR}/utils.cmake)
+# ladybird_generate_export_header(name fs_name [BASE_NAME base])
+#
+# BASE_NAME names the export header's macros after a library other than the target, for a target that compiles the
+# objects of a library, as LibJSObjects compiles LibJS's.
function(ladybird_generate_export_header name fs_name)
+ cmake_parse_arguments(PARSE_ARGV 2 EXPORT_HEADER "" "BASE_NAME" "")
# Temporary helper to allow libraries to opt-in to using X_API macros
# to export symbols required by external consumers. This allows the codebase
# to gradually slowly migrate instead of an all-or-nothing approach.
@@ -15,7 +20,51 @@ function(ladybird_generate_export_header name fs_name)
endif()
include(GenerateExportHeader)
string(TOUPPER ${fs_name} fs_name_upper)
- generate_export_header(${name} EXPORT_MACRO_NAME ${fs_name_upper}_API EXPORT_FILE_NAME "Export.h")
+ set(base_name "")
+ if (EXPORT_HEADER_BASE_NAME)
+ set(base_name BASE_NAME ${EXPORT_HEADER_BASE_NAME})
+ endif()
+ generate_export_header(${name} ${base_name} EXPORT_MACRO_NAME ${fs_name_upper}_API EXPORT_FILE_NAME "Export.h")
+endfunction()
+
+# What the objects of every library are compiled and linked with, whether the library is a target of its own or an
+# object library another one takes in: the clang plugin, AK, the warnings of the platform, and on Windows the
+# pthread and mman shims.
+function(ladybird_library_setup name)
+ target_link_libraries(${name} PUBLIC GenericClangPlugin)
+ if ((APPLE AND NOT IOS) OR (LINUX AND NOT ANDROID))
+ target_compile_options(${name} PRIVATE $<$<COMPILE_LANG_AND_ID:CXX,Clang,AppleClang>:-Wexit-time-destructors>)
+ endif()
+
+ if (NOT "${name}" STREQUAL "AK")
+ target_link_libraries(${name} PRIVATE AK)
+ endif()
+
+ if (WIN32)
+ target_include_directories(${name} PRIVATE ${PTHREAD_INCLUDE_DIR})
+ target_link_libraries(${name} PRIVATE ${PTHREAD_LIBRARY})
+
+ target_include_directories(${name} PRIVATE ${MMAN_INCLUDE_DIR})
+ target_link_libraries(${name} PRIVATE ${MMAN_LIBRARY})
+ endif()
+endfunction()
+
+# The headers of Libraries/Lib${library}, for whatever consumes an installed Lagom through the target.
+function(ladybird_install_library_headers name library)
+ # FIXME: Clean these up so that we don't need so many include dirs
+ if (ENABLE_INSTALL_HEADERS)
+ target_include_directories(${name} INTERFACE
+ $<INSTALL_INTERFACE:${CMAKE_INSTALL_INCLUDEDIR}/Services>
+ $<INSTALL_INTERFACE:${CMAKE_INSTALL_INCLUDEDIR}/Libraries>
+ $<INSTALL_INTERFACE:${CMAKE_INSTALL_INCLUDEDIR}/Services>
+ )
+ install(
+ DIRECTORY "${LADYBIRD_SOURCE_DIR}/Libraries/Lib${library}"
+ COMPONENT Lagom_Development
+ DESTINATION ${CMAKE_INSTALL_INCLUDEDIR}
+ FILES_MATCHING PATTERN "*.h"
+ )
+ endif()
endfunction()
function(ladybird_generate_dsym target_name)
@@ -107,44 +156,14 @@ function(ladybird_lib name fs_name)
OUTPUT_NAME lagom-${fs_name}
)
target_link_libraries(${name} PRIVATE ${LIBS})
- target_link_libraries(${name} PUBLIC GenericClangPlugin)
- if ((APPLE AND NOT IOS) OR (LINUX AND NOT ANDROID))
- target_compile_options(${name} PRIVATE $<$<COMPILE_LANG_AND_ID:CXX,Clang,AppleClang>:-Wexit-time-destructors>)
- endif()
-
- if (NOT "${name}" STREQUAL "AK")
- target_link_libraries(${name} PRIVATE AK)
- endif()
-
- if (WIN32)
- target_include_directories(${name} PRIVATE ${PTHREAD_INCLUDE_DIR})
- target_link_libraries(${name} PRIVATE ${PTHREAD_LIBRARY})
-
- target_include_directories(${name} PRIVATE ${MMAN_INCLUDE_DIR})
- target_link_libraries(${name} PRIVATE ${MMAN_LIBRARY})
- endif()
+ ladybird_library_setup(${name})
if (NOT LADYBIRD_LIB_TYPE STREQUAL "STATIC")
ladybird_generate_dsym(${name})
endif()
- # FIXME: Clean these up so that we don't need so many include dirs
- if (ENABLE_INSTALL_HEADERS)
- target_include_directories(${name} INTERFACE
- $<INSTALL_INTERFACE:${CMAKE_INSTALL_INCLUDEDIR}/Services>
- $<INSTALL_INTERFACE:${CMAKE_INSTALL_INCLUDEDIR}/Libraries>
- $<INSTALL_INTERFACE:${CMAKE_INSTALL_INCLUDEDIR}/Services>
- )
- endif()
+ ladybird_install_library_headers(${name} ${library})
add_lagom_library_install_rules(${name} ALIAS_NAME ${library})
- if (ENABLE_INSTALL_HEADERS)
- install(
- DIRECTORY "${LADYBIRD_SOURCE_DIR}/Libraries/Lib${library}"
- COMPONENT Lagom_Development
- DESTINATION ${CMAKE_INSTALL_INCLUDEDIR}
- FILES_MATCHING PATTERN "*.h"
- )
- endif()
ladybird_generated_sources(${name})
if (LADYBIRD_LIB_EXPLICIT_SYMBOL_EXPORT)
ladybird_generate_export_header(${name} ${fs_name})
diff --git a/Meta/CMake/utils.cmake b/Meta/CMake/utils.cmake
index ec5244feab0..b6d12feaf10 100644
--- a/Meta/CMake/utils.cmake
+++ b/Meta/CMake/utils.cmake
@@ -17,7 +17,7 @@ function(ladybird_testjs_test test_src sub_dir)
if ("${LADYBIRD_TEST_CUSTOM_MAIN}" STREQUAL "")
set(LADYBIRD_TEST_CUSTOM_MAIN "$<TARGET_OBJECTS:JavaScriptTestRunnerMain>")
endif()
- list(APPEND LADYBIRD_TEST_LIBS LibJS LibCore LibFileSystem)
+ list(APPEND LADYBIRD_TEST_LIBS LibJSStandalone LibCore LibFileSystem)
set(test_options)
if (LADYBIRD_TEST_NO_TEST)
list(APPEND test_options NO_TEST)
diff --git a/Meta/Fuzzers/CMakeLists.txt b/Meta/Fuzzers/CMakeLists.txt
index 290a6088781..f4aff0b1575 100644
--- a/Meta/Fuzzers/CMakeLists.txt
+++ b/Meta/Fuzzers/CMakeLists.txt
@@ -42,7 +42,7 @@ target_compile_options(FuzzilliJs
PRIVATE $<$<CXX_COMPILER_ID:Clang>:-g -O1 -fsanitize-coverage=trace-pc-guard>
)
target_link_libraries(FuzzilliJs
- PUBLIC AK LibCore LibJS LibGC
+ PUBLIC AK LibCore LibJSStandalone LibGC
PRIVATE $<$<CXX_COMPILER_ID:Clang>:-fsanitize-coverage=trace-pc-guard>
)
endif()
diff --git a/Meta/Fuzzers/fuzzers.cmake b/Meta/Fuzzers/fuzzers.cmake
index 5a8f8bc5bc5..ce81b273987 100644
--- a/Meta/Fuzzers/fuzzers.cmake
+++ b/Meta/Fuzzers/fuzzers.cmake
@@ -28,7 +28,7 @@ set(FUZZER_DEPENDENCIES_CSSParser LibWeb)
set(FUZZER_DEPENDENCIES_ELF LibELF)
set(FUZZER_DEPENDENCIES_GIFLoader LibGfx LibImageDecoders)
set(FUZZER_DEPENDENCIES_ICOLoader LibGfx LibImageDecoders)
-set(FUZZER_DEPENDENCIES_Js LibJS LibGC)
+set(FUZZER_DEPENDENCIES_Js LibJSStandalone LibGC)
set(FUZZER_DEPENDENCIES_MatroskaReader LibMedia)
set(FUZZER_DEPENDENCIES_PEM LibCrypto)
set(FUZZER_DEPENDENCIES_PNGLoader LibGfx LibImageDecoders)
diff --git a/Meta/Linters/check_rust_process_wide_state.py b/Meta/Linters/check_rust_process_wide_state.py
index 27a97f20354..805b73e31bf 100755
--- a/Meta/Linters/check_rust_process_wide_state.py
+++ b/Meta/Linters/check_rust_process_wide_state.py
@@ -37,6 +37,22 @@ ALLOWED = {
"Libraries/LibWeb/HTML/Parser/Rust/src/token.rs:SPARE_ATTRIBUTE_VALUES": "per-thread allocation pool; a second copy costs memory, never an answer",
}
+# The crates that another crate depends on by path but that are in one library of a process all the same: the crates
+# that depend on each, which have to be exactly these for the claim to hold, and the reason. The state of libweb_rust
+# is still checked below, for the threads that share it.
+IN_ONE_LIBRARY = {
+ "libjs_rust": (
+ {"libweb_bindings_rust"},
+ "a dependency of libweb_bindings_rust alone, whose archive both LibWeb's library and the JavaScript tools "
+ "link in a build with LibWeb; a build without LibWeb imports the crate itself, as the one Rust archive of "
+ "LibJS's library (Libraries/LibJS/CMakeLists.txt)",
+ ),
+ "libweb_rust": (
+ {"libweb_bindings_rust"},
+ "a dependency of libweb_bindings_rust alone, whose archive LibWeb's library links",
+ ),
+}
+
# libweb_rust: `file:name` -> why the state is fine on a thread other than the document's.
RENDER_STATE_CRATE = "Libraries/LibWeb/Rust"
@@ -185,13 +201,26 @@ def crate_name(manifest):
return match.group(1) if match else None
+def path_dependencies(manifest):
+ """The names of the crates the manifest depends on by path, as dependencies of any kind."""
+ return set(re.findall(r"^([a-z_0-9]+)\s*=\s*\{[^}]*\bpath\s*=", manifest.read_text(), re.M))
+
+
def crates_compiled_into_more_than_one_library(manifests):
- """Every crate some other crate depends on by path: its code, and its statics, end up in both."""
- shared = set()
+ """Every crate some other crate depends on by path: its code, and its statics, end up in both, unless the crate is
+ one of IN_ONE_LIBRARY, whose claim about the crates that depend on it is checked here."""
+ dependents = {}
for manifest in manifests:
- for match in re.finditer(r"^([a-z_0-9]+)\s*=\s*\{[^}]*\bpath\s*=", manifest.read_text(), re.M):
- shared.add(match.group(1))
- return shared
+ for dependency in path_dependencies(manifest):
+ dependents.setdefault(dependency, set()).add(crate_name(manifest))
+ for crate, (expected_dependents, _) in IN_ONE_LIBRARY.items():
+ if dependents.get(crate, set()) != expected_dependents:
+ sys.exit(
+ f"{crate} is listed in IN_ONE_LIBRARY as a dependency of {sorted(expected_dependents)} alone, but "
+ f"{sorted(dependents.get(crate, set()))} depend on it; its state is shared unless they are one "
+ "library, so update the list or move the state to C++"
+ )
+ return set(dependents) - set(IN_ONE_LIBRARY)
def state_in(root, source_directory, every_thread_local=False):
diff --git a/Tests/LibJS/CMakeLists.txt b/Tests/LibJS/CMakeLists.txt
index 26a1be3dd73..e8614e3e8f7 100644
--- a/Tests/LibJS/CMakeLists.txt
+++ b/Tests/LibJS/CMakeLists.txt
@@ -1,4 +1,4 @@
-ladybird_utility(test-js-runtime SOURCES test-js-runtime.cpp LIBS LibJS LibMain)
+ladybird_utility(test-js-runtime SOURCES test-js-runtime.cpp LIBS LibJSStandalone LibMain)
ladybird_utility(test-js SOURCES test-js-main.cpp LIBS LibMain)
ladybird_windows_bin(test-js CONSOLE)
diff --git a/Tests/LibWasm/CMakeLists.txt b/Tests/LibWasm/CMakeLists.txt
index 8663cfb4d3d..ecf2da4c5f2 100644
--- a/Tests/LibWasm/CMakeLists.txt
+++ b/Tests/LibWasm/CMakeLists.txt
@@ -2,7 +2,7 @@ ladybird_test(TestWasmMemory.cpp LibWasm LIBS LibGC LibWasm)
ladybird_test(TestWasmExecution.cpp LibWasm LIBS LibGC LibWasm)
add_executable(test-wasm test-wasm.cpp)
-target_link_libraries(test-wasm AK LibCore LibFileSystem JavaScriptTestRunnerMain LibTest LibWasm LibJS LibCrypto LibGC)
+target_link_libraries(test-wasm AK LibCore LibFileSystem JavaScriptTestRunnerMain LibTest LibWasm LibJSStandalone LibCrypto LibGC)
set(wasm_test_root "${LADYBIRD_SOURCE_DIR}")
if (INCLUDE_WASM_SPEC_TESTS)
set(wasm_test_root "${CMAKE_BINARY_DIR}")
diff --git a/Utilities/CMakeLists.txt b/Utilities/CMakeLists.txt
index 6ca2ee3bc7d..8fcce1e2a4e 100644
--- a/Utilities/CMakeLists.txt
+++ b/Utilities/CMakeLists.txt
@@ -1,8 +1,8 @@
-ladybird_utility(js SOURCES js.cpp LIBS LibJS LibMain)
+ladybird_utility(js SOURCES js.cpp LIBS LibJSStandalone LibMain)
if (NOT WIN32 AND NOT ANDROID)
target_link_libraries(js PRIVATE PkgConfig::LIBEDIT)
endif()
-ladybird_utility(wasm SOURCES wasm.cpp LIBS LibFileSystem LibWasm LibMain LibJS LibCrypto LibGC)
+ladybird_utility(wasm SOURCES wasm.cpp LIBS LibFileSystem LibWasm LibMain LibJSStandalone LibCrypto LibGC)
ladybird_utility(xml SOURCES xml.cpp LIBS LibFileSystem LibMain LibXML LibURL)
ladybird_utility(dns SOURCES dns.cpp LIBS LibDNS LibMain LibTLS LibCrypto)
@@ -16,7 +16,7 @@ if (WIN32)
return()
endif()
-ladybird_utility(test262-runner SOURCES test262-runner.cpp LIBS LibJS LibMain)
+ladybird_utility(test262-runner SOURCES test262-runner.cpp LIBS LibJSStandalone LibMain)
ladybird_utility(dump-html-tokens SOURCES dump-html-tokens.cpp LIBS LibMain LibWeb)
ladybird_utility(dump-html-tree SOURCES dump-html-tree.cpp LIBS LibMain LibWeb LibJS LibGC LibGfx LibIPC LibURL)