S031: root due timers in vendored servo-script (R5-01 SIGSEGV), crash-adblock regression smoke

fire_timer moved due timers into an unrooted Vec; a GC inside one callback swept
the functions of the timers still waiting. Heavy-web reruns and cargo test still pending.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
astar76 2026-11-12 20:38:47 -06:00
commit 0ecfd0f573
899 changed files with 306721 additions and 10 deletions

View file

@ -65,7 +65,7 @@ Never modify: `~/Documents/Apps/Nacre` (the original Python Nacre, reference onl
| `nice cargo build --release -j 2` | compile check, produces `target/release/nacre` | now |
| `nice cargo test --release -j 2` | unit tests (44, ~16 s test-profile build then <1 s run; shares the S001 build) (util, settings, history, bookmarks, permissions, vault, dns, bridge loopback, download, adblock, keys, scripts, updates, inject, hub, theme, ui::widgets input, ui::paint, ui::pages::newtab) | first successful build; not alongside a build |
| `src/selftest.rs` | in-app self test: `NACRE_SCRIPT=<file>` runs script commands (listed at its top) | now |
| `tools/smoke.sh <script> [outdir]` | smoke run on a hidden Xvfb display with a throwaway home and software GL; outdir (default `target/smoke/<name>-<time>`) gets `nacre.log`, `selftest.log`, `<shot>.png`, `<status>.json`, `home/`; exits non-zero on crash, panic, no `status done` or a failed `assert <js>`. Scripts in `tests/smoke/` (`launch.txt` offline, `https.txt` needs internet, `restore.txt` with `SMOKE_HOME=<launch outdir>/home`, `chrome.txt` chrome and every flyout dark and light, offline; `colours.txt` colours after welcome and site colour vs internal pages, hidden `SMOKE_SIZE=1280x1100`; `input.txt` real clicks, typing, right click, wheel on a web page, offline; `basics.txt` tabs, navigation, find, zoom, full screen, pop-ups, offline; `heavy-web.txt` DuckDuckGo, Wikipedia, YouTube, needs internet, `SMOKE_TIMEOUT=900`; `keys.txt` every shortcut action, offline; `privacy-net.txt` DNT/GPC/Save-Data headers and third-party cookies on a loopback server, offline, start `python3 tests/smoke/net/server.py &` first; `site-doctor.txt` Google sign-in, captchas, Reddit, GitHub, needs internet; `cache.txt` HTTP cache, offline, start `python3 tests/smoke/cache/server.py &` first; selftest `launch <args>` checks single instance; `cookies.txt` → `cookies-restart.txt` → `cookies-cleared.txt` encrypted cookies across restarts with `SMOKE_KEYRING=1` (own throwaway GNOME Keyring + bus) and `SMOKE_HOME`, `cookies-nokeyring.txt` without, server.py first); header documents env vars and commands. `SMOKE_VISIBLE=1` shows the run on the user's screen (DP-1, real GPU, niri tiles the window so shots are narrower); use it whenever the user is watching (D-009). Read the PNGs | now (S003) |
| `tools/smoke.sh <script> [outdir]` | smoke run on a hidden Xvfb display with a throwaway home and software GL; outdir (default `target/smoke/<name>-<time>`) gets `nacre.log`, `selftest.log`, `<shot>.png`, `<status>.json`, `home/`; exits non-zero on crash, panic, no `status done` or a failed `assert <js>`. Scripts in `tests/smoke/` (`launch.txt` offline, `https.txt` needs internet, `restore.txt` with `SMOKE_HOME=<launch outdir>/home`, `chrome.txt` chrome and every flyout dark and light, offline; `colours.txt` colours after welcome and site colour vs internal pages, hidden `SMOKE_SIZE=1280x1100`; `input.txt` real clicks, typing, right click, wheel on a web page, offline; `basics.txt` tabs, navigation, find, zoom, full screen, pop-ups, offline; `heavy-web.txt` DuckDuckGo, Wikipedia, YouTube, needs internet, `SMOKE_TIMEOUT=900`; `keys.txt` every shortcut action, offline; `privacy-net.txt` DNT/GPC/Save-Data headers and third-party cookies on a loopback server, offline, start `python3 tests/smoke/net/server.py &` first; `site-doctor.txt` Google sign-in, captchas, Reddit, GitHub, needs internet; `cache.txt` HTTP cache, offline, start `python3 tests/smoke/cache/server.py &` first; selftest `launch <args>` checks single instance; `cookies.txt` → `cookies-restart.txt` → `cookies-cleared.txt` encrypted cookies across restarts with `SMOKE_KEYRING=1` (own throwaway GNOME Keyring + bus) and `SMOKE_HOME`, `cookies-nokeyring.txt` without, server.py first; `crash-adblock.txt` R5-01 regression, ~1300 blocked loads with reloads/navigations mid-load plus 3200 timers under GC pressure, offline, server.py first); header documents env vars and commands. `SMOKE_VISIBLE=1` shows the run on the user's screen (DP-1, real GPU, niri tiles the window so shots are narrower); use it whenever the user is watching (D-009). Read the PNGs | now (S003) |
| `nacre://gallery` + `SMOKE_SIZE=1400x2800 tools/smoke.sh tests/smoke/gallery.txt` | every design token and widget, dark and light (+ new tab and settings shots); read the PNGs | now (S015) |
| `SMOKE_SIZE=1400x1200 tools/smoke.sh tests/smoke/newtab.txt` | new tab page dark/light, nothing playing and a video playing, weather failed state, tall/narrow/phone widths (offline); `tests/smoke/newtab-weather.txt` shoots the real weather card (needs internet); read the PNGs | now (S017) |
| `SMOKE_SIZE=1400x900 tools/smoke.sh tests/smoke/backgrounds.txt` | every new tab background with the pointer, Customize panel dark/light, image + blur, GIF frames; `perf-*-a/b.json` `frames` (median/max draw ms, `drawn` count) per background at Lots/Fast, hidden tab, still, Motion off. Selftest `pointer x y`, `customize`; `@PAGESDIR@` = path of tests/smoke/pages | now (S018) |

2
Cargo.lock generated
View file

@ -8672,8 +8672,6 @@ dependencies = [
[[package]]
name = "servo-script"
version = "0.7.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "84ab625df5e83104d2b1ef7066f6fbc879d24be07c14438eb25f427657ed7fee"
dependencies = [
"accesskit 0.24.0",
"aes 0.9.3",

View file

@ -100,6 +100,9 @@ opt-level = 2
# servo-net 0.7.0 keeps hyper's 16 KiB HTTP/2 header limit, which breaks YouTube; the vendored copy raises it
# (vendor/servo-net/connector.rs, create_http_client). Drop when Servo sets it. Every servo-net patch is listed in
# docs/DESIGN.md "Vendored servo-net patches".
# servo-script 0.7.0 fires due timers from an unrooted list, so a GC in one callback freed the next one's function
# (SIGSEGV, R5-01); the vendored copy roots them (vendor/servo-script/event_loop/timers.rs, `Nacre patch (S031)`).
[patch.crates-io]
epaint = { path = "vendor/epaint" }
servo-net = { path = "vendor/servo-net" }
servo-script = { path = "vendor/servo-script" }

View file

@ -16,12 +16,12 @@ Reproduce, find the faulting frame, fix the cause (in Nacre or in vendored Servo
- `tools/smoke.sh` header, `tests/smoke/heavy-web.txt`, `tests/smoke/net-adblock.txt`
## Steps
- [ ] Reproduce: offline first (a local page whose `<script src>` / module script / `ad_status.js`-style URL is on a local block list, loaded many times, with `tests/smoke/net/server.py`); if that does not crash, `heavy-web.txt` YouTube search step with `RUST_BACKTRACE=full`. Record the crash rate.
- [ ] Get the faulting backtrace: `coredumpctl gdb` / run under `gdb -batch -ex run -ex bt` (debug symbols: `CARGO_PROFILE_RELEASE_DEBUG=line-tables-only` only if needed, same target/); note thread and frame in PROGRESS.
- [ ] Find the cause (cancelled response answered twice or after drop, a dropped `WebResourceLoad`, a script-thread race, SpiderMonkey GC on a cancelled fetch, …) and write it down in two lines before changing code.
- [ ] Fix at the cause. If it is in Servo, vendor the minimal crate like servo-net (D-017) and add the patch site to DESIGN.md "Vendored servo-net patches" (or a new "Vendored patches" list).
- [ ] Unit test for the Nacre side when feasible (e.g. intercept answers exactly once per request).
- [ ] Regression smoke `tests/smoke/crash-adblock.txt` (offline, local server, ≥ 200 blocked script loads incl. page reloads/navigations mid-load); add its row to CLAUDE.md §5.
- [x] Reproduce: offline first (a local page whose `<script src>` / module script / `ad_status.js`-style URL is on a local block list, loaded many times, with `tests/smoke/net/server.py`); if that does not crash, `heavy-web.txt` YouTube search step with `RUST_BACKTRACE=full`. Record the crash rate.
- [x] Get the faulting backtrace: `coredumpctl gdb` / run under `gdb -batch -ex run -ex bt` (debug symbols: `CARGO_PROFILE_RELEASE_DEBUG=line-tables-only` only if needed, same target/); note thread and frame in PROGRESS.
- [x] Find the cause (cancelled response answered twice or after drop, a dropped `WebResourceLoad`, a script-thread race, SpiderMonkey GC on a cancelled fetch, …) and write it down in two lines before changing code.
- [x] Fix at the cause. If it is in Servo, vendor the minimal crate like servo-net (D-017) and add the patch site to DESIGN.md "Vendored servo-net patches" (or a new "Vendored patches" list).
- [x] Unit test for the Nacre side when feasible (e.g. intercept answers exactly once per request).
- [x] Regression smoke `tests/smoke/crash-adblock.txt` (offline, local server, ≥ 200 blocked script loads incl. page reloads/navigations mid-load); add its row to CLAUDE.md §5.
- [ ] Rerun: crash-adblock ×3, net-adblock, launch, heavy-web (internet, `SMOKE_TIMEOUT=900`) ×2 — no crash.
- [ ] PROGRESS entry, phase5.md R5-01 → `[fixed <commit>]`, INDEX line, commit `S031: …`, push.

View file

@ -166,6 +166,14 @@ picture-in-picture, extensions, password capture, printing.
| `resource_thread.rs` `create_http_states`, Exit; `nacre.rs` `set_cookie_persistence`, `cookie_jar_snapshot`; `Cargo.toml` (+ `serde_json`) | the public cookie jar comes from and goes to the embedder instead of plain `cookie_jar.json`: Nacre's initial jar at start, a JSON copy on demand, the final jar at Exit (S025, D-019) | `cookies.txt` + `cookies-restart.txt` + `cookies-cleared.txt` |
| `fetch/methods.rs` `main_fetch` (step 12) | privacy mode's Firefox-style Accept-Language ("en-US,en;q=0.5", `nacre::append_accept_language`) replaces Servo's single locale; a page's own value stays (S024) | `privacy-net.txt` |
## Vendored servo-script patches
`vendor/servo-script` is servo-script 0.7.0 through `[patch.crates-io]` (S031), same rules as servo-net above.
| File, function | What and why | Re-check |
|---|---|---|
| `event_loop/timers.rs` `OneshotTimers::fire_timer`, `JsTimerTask::invoke` | due timers wait in a `RootedTraceableBox<VecDeque>` instead of a plain `Vec`, and the running timer's callback is rooted: a GC inside one callback swept the functions of the timers still waiting (SIGSEGV in `GlobalScope::from_object`, R5-01) | `crash-adblock.txt` |
Third-party rule (S023): a request is third-party when its host's site (registrable domain, eTLD+1; an IP address
or a single-label host stands for itself) differs from the top-level site of its webview. Scheme and port don't
count, so `a.example.com` on `example.com` stays first-party. The top-level site comes from the last `Document`

View file

@ -319,6 +319,16 @@ Later: S010 list: user checks the Discord icon with their own client (the Discor
- Not to spec / not done: player integration (S028): `loadedmetadata`/HAVE_METADATA after the init segment only (duration-boundaryconditions 0/13, play/seek tests 0/1 each); changeType across containers (gst can't; changetype-play* ~1/19); errors before the init segment; `buffered` after `removeSourceBuffer` should throw; Opus/fLaC in MP4 (no decoder). Worker MSE and ManagedMediaSource out of scope.
- Seen once: a full WPT run hung the script thread (driver timer stopped at file 19); not reproduced in the rerun. Watch in S028.
## S031 — SIGSEGV after an ad-blocked script load (R5-01, 2026-11-12)
- Repro: `crash-adblock.txt` (685 cancelled loads/run) 0 crashes in 3 runs, heavy-web 0/2, a YouTube search loop 0/3. The crash is rare online; the two S024 cores (hidden Xvfb heavy-web runs) were symbolized with an unstripped rustc twin of the same commit (same .text).
- Backtrace (both cores): script thread, `ScriptThread::handle_msgs` → `TimerListener` task → `OneshotTimers::fire_timer` → `Function::Call_` → `GlobalScope::from_object` → `JS::GetNonCCWObjectGlobal` reading a swept object (`0x4b4b…` poison). The ad-block log line before it was a bystander.
- Cause: `fire_timer` (servo-script `event_loop/timers.rs`) moves every due timer out of the traced timer list into a plain local `Vec` and runs them one by one; a GC inside one callback can't see the rest, so their `TracedCallback` functions are swept and the next call reads a dead object (or a reused cell: the wrong function runs).
- Proof offline: `pages/crash-timers.html` (40 timers due together, each allocating): 9 of 40 callbacks run, the other 31 are silently lost, 3 of 3 runs; without the allocation all run.
- Fix: servo-script vendored (`vendor/servo-script`, `[patch.crates-io]`); `fire_timer` keeps due timers in a `RootedTraceableBox<VecDeque>`, `JsTimerTask::invoke` roots the running callback (DESIGN.md "Vendored servo-script patches"). After: 40 of 40 run.
- Smoke `crash-adblock.txt` (~870 cancelled loads + 3200 timers under GC pressure): fixed build exits 0 3/3 (visible); the pre-fix build (68346f0) fails it (timer page never finishes). No Nacre-side change, so no unit test.
- Not done (stopped for the weekly limit): step 7 reruns (net-adblock, launch, heavy-web ×2 with `SMOKE_TIMEOUT=900`) and `nice cargo test --release -j 2` after vendoring. INDEX not ticked until they pass.
- S028 merge: the MSE branch also vendors `vendor/servo-script`; take the branch's files and re-apply the two `Nacre patch (S031)` hunks in `event_loop/timers.rs` (the branch's timers.rs is the pristine 0.7.0 file).
## Later
- Turnstile widget paints as a black half-disc (Servo painting of its iframe/shadow DOM, S006 site doctor).
- Google sign-in past the email step: press Next with a real account, by the user (S006).

View file

@ -3,7 +3,7 @@
Input for `/plan-generate` → category `07 Polish pass` (and `03 Gaps` S011–S014, which haven't started yet).
Same tags as phase 1/4: `[open]`, `[fixed <commit>]`, `[wontfix: reason]`.
R5-01 [open] CRASH: Nacre crashed (SIGSEGV) while searching. Last log line before it:
R5-01 [fixed S031, heavy-web recheck pending] CRASH: Nacre crashed (SIGSEGV) while searching. Last log line before it:
`ERROR script::dom::html::scripting::htmlscriptelement] Fetching classic script failed Load cancelled (UrlWithBlobClaim
{ url: "https://static.doubleclick.net/instream/ad_status.js", token: None })`, so the ad blocker cancels a script load
just before the crash (YouTube/Google search page, throwaway profile). Reproduce, get a backtrace (`RUST_BACKTRACE=1`,

View file

@ -0,0 +1,33 @@
# R5-01 regression (S031): blocked script loads must not crash the browser. crash-adblock.html inserts 20 blocked
# loads per round (classic, async, defer, module, dynamic import, fetch, image) from the local server, whose
# /ads/banner.js is on its filter list, and reloads or navigates itself mid-load; 3 passes of 20 rounds plus tabs
# opened and closed while loading, about 1300 blocked loads. Offline. Start the server first:
# The crash itself was in Servo's timers (R5-01 cause): crash-timers.html lets 40 timers fall due together, each
# allocating enough to start a GC; before the fix only 9 of each 40 callbacks ran (the rest were freed), or it crashed.
# python3 tests/smoke/net/server.py & then tools/smoke.sh tests/smoke/crash-adblock.txt
wait 3
set /adblock/lists []
set /adblock/custom ["http://127.0.0.1:8766/list.txt"]
wait 5
expect /adblock/rules 4
open @PAGES@/crash-adblock.html?rounds=20
waitfor 120 window.crash && window.crash.done && document.readyState === "complete"
status pass1
expect /active/blocked > 10
open @PAGES@/crash-adblock.html?rounds=20
waitfor 120 window.crash && window.crash.done && document.readyState === "complete"
newtab @PAGES@/crash-adblock.html?rounds=20
wait 1
cmd close_tab
newtab @PAGES@/crash-adblock.html?rounds=20
waitfor 120 window.crash && window.crash.done && document.readyState === "complete"
assert window.crash.errors > 0
shot crash-adblock
open @PAGES@/crash-timers.html?rounds=40&batch=40&pass=1
waitfor 150 location.search.endsWith("pass=1") && window.crash && window.crash.done
assert window.crash.fired === 1600
open @PAGES@/crash-timers.html?rounds=40&batch=40&pass=2
waitfor 150 location.search.endsWith("pass=2") && window.crash && window.crash.done
assert window.crash.fired === 1600
status done
quit

View file

@ -0,0 +1,48 @@
<!doctype html>
<html>
<!-- R5-01 / S031 stress page: every round inserts blocked script loads from the local server
(tests/smoke/net/server.py, /ads/banner.js is on its /list.txt) as classic, async, defer and module
scripts, plus a blocked fetch() and image, then reloads or navigates itself mid-load. ?n=<round> counts rounds;
?rounds=<N> sets how many (default 20); ?stop=1 stays put. window.crash holds the state for smoke asserts. -->
<head><meta charset="utf-8"><title>Crash adblock</title>
<script>
const q = new URLSearchParams(location.search);
const n = Number(q.get('n') || 0), rounds = Number(q.get('rounds') || 20);
const ad = (kind, i) => 'http://127.0.0.1:8766/ads/banner.js?' + kind + '=' + n + '-' + i;
window.crash = { round: n, rounds, inserted: 0, errors: 0, done: n >= rounds };
// Parser-inserted blocking scripts, decided while the document is still parsing.
for (let i = 0; i < 4; i++) document.write('<script src="' + ad('sync', i) + '" onerror="crash.errors++"><\/script>');
</script>
<script src="http://127.0.0.1:8766/ads/banner.js?head" onerror="crash.errors++"></script>
<script defer src="http://127.0.0.1:8766/ads/banner.js?defer" onerror="crash.errors++"></script>
<script type="module" src="http://127.0.0.1:8766/ads/banner.js?module" onerror="crash.errors++"></script>
</head>
<body>
<h1 id="h">Crash adblock</h1>
<img src="http://127.0.0.1:8766/ads/pixel.gif?img" onerror="crash.errors++">
<script>
const h = document.getElementById('h');
for (let i = 0; i < 6; i++) {
for (const type of ['', 'module']) {
const s = document.createElement('script');
if (type) s.type = type;
s.async = i % 2 === 0;
s.src = ad('dyn' + type, i);
s.onerror = () => crash.errors++;
document.head.appendChild(s);
crash.inserted++;
}
}
fetch(ad('fetch', 0)).catch(() => crash.errors++);
import(ad('import', 0)).catch(() => crash.errors++);
h.textContent = 'Crash adblock round ' + n + ' / ' + rounds;
if (!crash.done && !q.get('stop')) {
const next = location.pathname + '?n=' + (n + 1) + '&rounds=' + rounds;
// Alternate: navigate while the blocked loads are still in flight, reload after load, navigate after a tick.
if (n % 3 === 0) location.replace(next);
else if (n % 3 === 1) addEventListener('load', () => location.replace(next));
else setTimeout(() => location.replace(next), 0);
}
</script>
</body>
</html>

View file

@ -0,0 +1,40 @@
<!doctype html>
<meta charset="utf-8">
<title>crash-timers</title>
<!-- S031 (R5-01): many timers fall due in the same task; each callback allocates enough to start a GC. Servo 0.7
fired them from an unrooted list, so a GC in one callback swept the next one's function (SIGSEGV in
GlobalScope::from_object). ?rounds= (default 40), ?batch= timers per round (default 40). -->
<body>
<p id="out">running</p>
<script>
const q = new URLSearchParams(location.search);
const rounds = +(q.get("rounds") || 40), batch = +(q.get("batch") || 40);
window.crash = { round: 0, rounds, fired: 0, done: false };
let keep = [];
function churn() {
if (q.has("nochurn")) return;
// Short-lived objects and closures: enough to trigger nursery and major GCs.
let junk = [];
for (let i = 0; i < 20000; i++) junk.push({ a: i, b: [i, i + 1], f: () => i });
keep.push(junk.length);
if (keep.length > 100) keep = [];
}
function round() {
if (crash.round >= rounds) {
crash.done = true;
document.getElementById("out").textContent = "done " + crash.fired;
return;
}
crash.round++;
let left = batch;
for (let i = 0; i < batch; i++) {
// A fresh closure per timer, referenced only by the timer list.
setTimeout(((n) => () => {
churn();
crash.fired++;
if (--left === 0) setTimeout(round, 0);
})(i), 5);
}
}
round();
</script>

8311
vendor/servo-script/Cargo.lock generated vendored Normal file

File diff suppressed because it is too large Load diff

700
vendor/servo-script/Cargo.toml vendored Normal file
View file

@ -0,0 +1,700 @@
# THIS FILE IS AUTOMATICALLY GENERATED BY CARGO
#
# When uploading crates to the registry Cargo will automatically
# "normalize" Cargo.toml files for maximal compatibility
# with all versions of Cargo and also rewrite `path` dependencies
# to registry (e.g., crates.io) dependencies.
#
# If you are reading this file be aware that the original Cargo.toml
# will likely look very different (and much more reasonable).
# See Cargo.toml.orig for the original contents.
[package]
edition = "2024"
rust-version = "1.88.0"
name = "servo-script"
version = "0.7.0"
authors = ["The Servo Project Developers"]
build = "build.rs"
publish = true
autolib = false
autobins = false
autoexamples = false
autotests = false
autobenches = false
description = "A component of the servo web-engine."
readme = false
license = "MPL-2.0"
repository = "https://github.com/servo/servo"
resolver = "2"
[features]
bluetooth = [
"servo-bluetooth-traits",
"script_bindings/bluetooth",
]
brotli-compression-stream = ["dep:brotli"]
crown = ["js/crown"]
debugmozjs = ["js/debugmozjs"]
gamepad = [
"script_bindings/gamepad",
"embedder_traits/gamepad",
]
jitspew = ["js/jitspew"]
js_backtrace = []
js_jit = ["js/jit"]
profilemozjs = ["js/profilemozjs"]
testbinding = ["script_bindings/testbinding"]
tracing = [
"dep:tracing",
"script_bindings/tracing",
]
webcrypto = [
"script_bindings/webcrypto",
"dep:aes",
"dep:aes-gcm",
"dep:aes-kw",
"dep:argon2",
"dep:cbc",
"dep:chacha20poly1305",
"dep:ctr",
"dep:cshake",
"dep:ctutils",
"dep:ecdsa",
"dep:ed25519-dalek",
"dep:ed448-goldilocks",
"dep:elliptic-curve",
"dep:hkdf",
"dep:k12",
"dep:keccak",
"dep:ml-dsa",
"dep:ml-kem",
"dep:ocb3",
"dep:p256",
"dep:p384",
"dep:p521",
"dep:pkcs8",
"dep:rsa",
"dep:sha1",
"dep:sha2",
"dep:sha3",
"dep:sponge-cursor",
"dep:x-wing",
"dep:x25519-dalek",
"dep:x448",
"dep:zeroize",
]
webgl = [
"dep:mozangle",
"script_bindings/webgl",
"script_traits/webgl",
"servo-constellation-traits/webgl",
]
webgl_backtrace = ["servo-canvas-traits/webgl_backtrace"]
webgpu = [
"dep:script_webgpu",
"dep:webgpu_traits",
"script_bindings/webgpu",
"script_traits/webgpu",
]
webxr = [
"webgl",
"gamepad",
"webxr-api",
"script_bindings/webxr",
]
[lib]
name = "script"
path = "lib.rs"
[dependencies.accesskit]
version = "0.24.0"
features = ["serde"]
[dependencies.aes]
version = "0.9"
features = ["zeroize"]
optional = true
[dependencies.aes-gcm]
version = "0.11"
features = [
"hazmat",
"zeroize",
]
optional = true
[dependencies.aes-kw]
version = "0.3"
features = ["zeroize"]
optional = true
[dependencies.app_units]
version = "0.7"
[dependencies.argon2]
version = "0.6"
features = ["alloc"]
optional = true
[dependencies.arrayvec]
version = "0.7"
[dependencies.atomic_refcell]
version = "0.1.14"
[dependencies.aws-lc-rs]
version = "1.17"
features = ["aws-lc-sys"]
default-features = false
[dependencies.backtrace]
version = "0.3"
[dependencies.base64]
version = "0.23.0"
[dependencies.base64ct]
version = "1.8"
features = ["alloc"]
[dependencies.bitflags]
version = "2.11"
[dependencies.brotli]
version = "8.0.3"
optional = true
[dependencies.buf-read-ext]
version = "0.4"
[dependencies.bytes]
version = "1.0"
features = ["serde"]
[dependencies.cbc]
version = "0.2"
features = [
"alloc",
"zeroize",
]
optional = true
[dependencies.chacha20poly1305]
version = "0.11"
features = [
"rand_core",
"zeroize",
]
optional = true
[dependencies.chardetng]
version = "1.0"
[dependencies.chrono]
version = "0.4"
features = ["serde"]
[dependencies.content-security-policy]
version = "0.9"
features = ["serde"]
[dependencies.cookie]
version = "0.18"
package = "cookie"
[dependencies.crossbeam-channel]
version = "0.5"
[dependencies.crypto-bigint]
version = "0.7"
[dependencies.cshake]
version = "0.2"
optional = true
[dependencies.cssparser]
version = "0.38"
features = ["serde"]
[dependencies.ctr]
version = "0.10"
features = ["zeroize"]
optional = true
[dependencies.ctutils]
version = "0.4"
optional = true
[dependencies.data-url]
version = "0.3"
[dependencies.deny_public_fields]
version = "=0.7.0"
package = "servo-deny-public-fields"
[dependencies.devtools_traits]
version = "=0.7.0"
package = "servo-devtools-traits"
[dependencies.dom_struct]
version = "=0.7.0"
package = "servo-dom-struct"
[dependencies.ecdsa]
version = "0.17"
optional = true
[dependencies.ed25519-dalek]
version = "3.0"
features = [
"alloc",
"pkcs8",
"rand_core",
"zeroize",
]
optional = true
[dependencies.ed448-goldilocks]
version = "=0.14.0-pre.15"
optional = true
[dependencies.elliptic-curve]
version = "0.14"
features = ["pkcs8"]
optional = true
[dependencies.embedder_traits]
version = "=0.7.0"
package = "servo-embedder-traits"
[dependencies.encoding_rs]
version = "0.8"
features = ["serde"]
[dependencies.euclid]
version = "0.22"
[dependencies.flate2]
version = "1.1"
[dependencies.fonts]
version = "=0.7.0"
package = "servo-fonts"
[dependencies.fonts_traits]
version = "=0.7.0"
package = "servo-fonts-traits"
[dependencies.glow]
version = "0.17.0"
[dependencies.headers]
version = "0.4"
[dependencies.hkdf]
version = "0.13"
optional = true
[dependencies.html5ever]
version = "0.40.1"
[dependencies.http]
version = "1.4"
[dependencies.httparse]
version = "1.9"
[dependencies.hyper_serde]
version = "=0.7.0"
package = "servo-hyper-serde"
[dependencies.icu_locale_core]
version = "2.1.0"
[dependencies.indexmap]
version = "2.14.0"
features = ["std"]
[dependencies.ipc-channel]
version = "0.23"
[dependencies.itertools]
version = "0.15"
[dependencies.js]
version = "=0.26.4"
features = [
"intl",
"libz-sys",
]
default-features = false
package = "mozjs"
[dependencies.jstraceable_derive]
version = "=0.7.0"
package = "servo-jstraceable-derive"
[dependencies.k12]
version = "0.5"
optional = true
[dependencies.keccak]
version = "0.2"
optional = true
[dependencies.keyboard-types]
version = "0.8.3"
features = [
"serde",
"webdriver",
]
[dependencies.layout_api]
version = "=0.7.0"
package = "servo-layout-api"
[dependencies.libc]
version = "0.2"
[dependencies.log]
version = "0.4.32"
[dependencies.malloc_size_of]
version = "=0.7.0"
package = "servo-malloc-size-of"
[dependencies.malloc_size_of_derive]
version = "0.1"
[dependencies.markup5ever]
version = "0.40"
[dependencies.media]
version = "=0.7.0"
package = "servo-media-thread"
[dependencies.metrics]
version = "=0.7.0"
package = "servo-metrics"
[dependencies.mime]
version = "0.3.13"
[dependencies.mime_guess]
version = "2.0.5"
[dependencies.ml-dsa]
version = "0.1"
features = ["zeroize"]
optional = true
[dependencies.ml-kem]
version = "0.3"
features = [
"getrandom",
"pkcs8",
"zeroize",
]
optional = true
[dependencies.net_traits]
version = "=0.7.0"
package = "servo-net-traits"
[dependencies.nom-rfc8288]
version = "0.4.0"
[dependencies.num-traits]
version = "0.2"
[dependencies.num_cpus]
version = "1.17.0"
[dependencies.ocb3]
version = "0.2"
optional = true
[dependencies.p256]
version = "0.14"
features = ["ecdh"]
optional = true
[dependencies.p384]
version = "0.14"
features = ["ecdh"]
optional = true
[dependencies.p521]
version = "0.14"
features = ["ecdh"]
optional = true
[dependencies.paint_api]
version = "=0.7.0"
package = "servo-paint-api"
[dependencies.parking_lot]
version = "0.12"
features = ["serde"]
[dependencies.percent-encoding]
version = "2.3"
[dependencies.phf]
version = "0.14"
features = ["macros"]
[dependencies.pixels]
version = "=0.7.0"
package = "servo-pixels"
[dependencies.pkcs8]
version = "0.11"
optional = true
[dependencies.postcard]
version = "1.1.3"
features = ["use-std"]
default-features = false
[dependencies.profile_traits]
version = "=0.7.0"
package = "servo-profile-traits"
[dependencies.rand]
version = "0.10"
[dependencies.regex]
version = "1.12"
[dependencies.resvg]
version = "0.48.1"
[dependencies.rsa]
version = "=0.10.0-rc.18"
optional = true
[dependencies.rustc-hash]
version = "2.1.2"
[dependencies.script_bindings]
version = "=0.7.0"
package = "servo-script-bindings"
[dependencies.script_traits]
version = "=0.7.0"
package = "servo-script-traits"
[dependencies.script_webgpu]
version = "=0.7.0"
optional = true
package = "servo-script-webgpu"
[dependencies.selectors]
version = "0.41"
[dependencies.serde]
version = "1.0.228"
features = ["derive"]
[dependencies.serde_json]
version = "1.0"
features = ["preserve_order"]
[dependencies.servo-background-hang-monitor-api]
version = "=0.7.0"
[dependencies.servo-base]
version = "=0.7.0"
[dependencies.servo-bluetooth-traits]
version = "=0.7.0"
optional = true
[dependencies.servo-canvas-traits]
version = "=0.7.0"
[dependencies.servo-config]
version = "=0.7.0"
[dependencies.servo-constellation-traits]
version = "=0.7.0"
[dependencies.servo-geometry]
version = "=0.7.0"
[dependencies.servo-media]
version = "=0.7.0"
[dependencies.servo-tracing]
version = "=0.7.0"
[dependencies.servo-url]
version = "=0.7.0"
[dependencies.servo-webvtt]
version = "=0.7.0"
[dependencies.servo_arc]
version = "0.5.0"
[dependencies.sha1]
version = "0.11"
optional = true
[dependencies.sha2]
version = "0.11"
optional = true
[dependencies.sha3]
version = "0.12"
optional = true
[dependencies.smallvec]
version = "1.15"
features = [
"serde",
"union",
]
[dependencies.sponge-cursor]
version = "0.1"
optional = true
[dependencies.storage_traits]
version = "=0.7.0"
package = "servo-storage-traits"
[dependencies.strum]
version = "0.28"
features = ["derive"]
[dependencies.stylo]
version = "0.22"
[dependencies.stylo_atoms]
version = "0.22"
[dependencies.stylo_dom]
version = "0.22"
[dependencies.stylo_malloc_size_of]
version = "0.22"
[dependencies.stylo_traits]
version = "0.22"
[dependencies.swapper]
version = "0.1"
[dependencies.tempfile]
version = "3"
[dependencies.tendril]
version = "0.5"
features = ["encoding_rs"]
[dependencies.time]
version = "0.3"
features = [
"large-dates",
"local-offset",
"serde",
]
package = "time"
[dependencies.timers]
version = "=0.7.0"
package = "servo-timers"
[dependencies.tracing]
version = "0.1.44"
optional = true
[dependencies.unicode-bidi]
version = "0.3.18"
[dependencies.unicode-script]
version = "0.5"
[dependencies.url]
version = "2.5"
[dependencies.urlpattern]
version = "0.3"
[dependencies.uuid]
version = "1.23.3"
features = [
"v4",
"v5",
"serde",
]
[dependencies.web_atoms]
version = "0.3.0"
[dependencies.webdriver]
version = "0.54.0"
[dependencies.webgpu_traits]
version = "=0.7.0"
optional = true
package = "servo-webgpu-traits"
[dependencies.webrender_api]
version = "0.70"
[dependencies.webxr-api]
version = "=0.7.0"
optional = true
package = "servo-webxr-api"
[dependencies.x-wing]
version = "0.1.0"
features = ["zeroize"]
optional = true
[dependencies.x25519-dalek]
version = "3.0"
features = [
"getrandom",
"static_secrets",
"zeroize",
]
optional = true
[dependencies.x448]
version = "=0.14.0-pre.12"
features = ["static_secrets"]
optional = true
[dependencies.xml5ever]
version = "0.40"
[dependencies.xpath]
version = "=0.7.0"
package = "servo-xpath"
[dependencies.zeroize]
version = "1.8"
optional = true
[target.'cfg(not(target_os = "ios"))'.dependencies.mozangle]
version = "0.7"
optional = true
[lints.clippy]
manual_string_new = "warn"
[lints.rust.unexpected_cfgs]
level = "warn"
priority = 0
check-cfg = [
"cfg(crown)",
"cfg(coverage)",
"cfg(llvm_pgo)",
"cfg(ohos_mock)",
]

231
vendor/servo-script/Cargo.toml.orig generated vendored Normal file
View file

@ -0,0 +1,231 @@
[package]
name = "servo-script"
build = "build.rs"
version.workspace = true
authors.workspace = true
license.workspace = true
edition.workspace = true
publish.workspace = true
rust-version.workspace = true
repository.workspace = true
description.workspace = true
[lib]
name = "script"
path = "lib.rs"
[features]
bluetooth = ['servo-bluetooth-traits', 'script_bindings/bluetooth']
# Allow brotli to be used in stream/compressionstream
brotli-compression-stream = ["dep:brotli"]
crown = ['js/crown']
debugmozjs = ['js/debugmozjs']
gamepad = ["script_bindings/gamepad", "embedder_traits/gamepad"]
jitspew = ['js/jitspew']
js_backtrace = []
js_jit = ["js/jit"]
profilemozjs = ['js/profilemozjs']
testbinding = ["script_bindings/testbinding"]
tracing = ["dep:tracing", "script_bindings/tracing"]
# Enable webcrypto
webcrypto = [
"script_bindings/webcrypto",
"dep:aes",
"dep:aes-gcm",
"dep:aes-kw",
"dep:argon2",
"dep:cbc",
"dep:chacha20poly1305",
"dep:ctr",
"dep:cshake",
"dep:ctutils",
"dep:ecdsa",
"dep:ed25519-dalek",
"dep:ed448-goldilocks",
"dep:elliptic-curve",
"dep:hkdf",
"dep:k12",
"dep:keccak",
"dep:ml-dsa",
"dep:ml-kem",
"dep:ocb3",
"dep:p256",
"dep:p384",
"dep:p521",
"dep:pkcs8",
"dep:rsa",
"dep:sha1",
"dep:sha2",
"dep:sha3",
"dep:sponge-cursor",
"dep:x-wing",
"dep:x25519-dalek",
"dep:x448",
"dep:zeroize",
]
webgl_backtrace = ["servo-canvas-traits/webgl_backtrace"]
webgl = [
"dep:mozangle",
"script_bindings/webgl",
"script_traits/webgl",
"servo-constellation-traits/webgl",
]
webgpu = [
"dep:script_webgpu",
"dep:webgpu_traits",
"script_bindings/webgpu",
"script_traits/webgpu",
]
webxr = ["webgl", "gamepad", "webxr-api", "script_bindings/webxr"]
[lints]
workspace = true
[dependencies]
accesskit = { workspace = true }
aes = { workspace = true, optional = true }
aes-gcm = { workspace = true, optional = true }
aes-kw = { workspace = true, optional = true }
app_units = { workspace = true }
argon2 = { workspace = true, optional = true }
arrayvec = { workspace = true }
atomic_refcell = { workspace = true }
aws-lc-rs = { workspace = true }
backtrace = { workspace = true }
base64 = { workspace = true }
base64ct = { workspace = true }
bitflags = { workspace = true }
brotli = { workspace = true, optional = true }
buf-read-ext = { workspace = true }
bytes = { workspace = true }
cbc = { workspace = true, optional = true }
chacha20poly1305 = { workspace = true, optional = true }
chardetng = { workspace = true }
chrono = { workspace = true }
content-security-policy = { workspace = true }
cookie = { workspace = true }
crossbeam-channel = { workspace = true }
crypto-bigint = { workspace = true }
cshake = { workspace = true, optional = true }
cssparser = { workspace = true }
ctr = { workspace = true, optional = true }
ctutils = { workspace = true, optional = true }
data-url = { workspace = true }
deny_public_fields = { workspace = true }
devtools_traits = { workspace = true }
dom_struct = { workspace = true }
ecdsa = { workspace = true, optional = true }
ed25519-dalek = { workspace = true, optional = true }
ed448-goldilocks = { workspace = true, optional = true }
elliptic-curve = { workspace = true, optional = true }
embedder_traits = { workspace = true }
encoding_rs = { workspace = true }
euclid = { workspace = true }
flate2 = { workspace = true }
fonts = { workspace = true }
fonts_traits = { workspace = true }
glow = { workspace = true }
headers = { workspace = true }
hkdf = { workspace = true, optional = true }
html5ever = { workspace = true }
http = { workspace = true }
httparse = { workspace = true }
hyper_serde = { workspace = true }
icu_locale_core = { workspace = true }
indexmap = { workspace = true }
ipc-channel = { workspace = true }
itertools = { workspace = true }
js = { workspace = true }
jstraceable_derive = { workspace = true }
k12 = { workspace = true, optional = true }
keyboard-types = { workspace = true }
keccak = { workspace = true, optional = true }
layout_api = { workspace = true }
libc = { workspace = true }
log = { workspace = true }
malloc_size_of = { workspace = true }
malloc_size_of_derive = { workspace = true }
markup5ever = { workspace = true }
media = { workspace = true }
metrics = { workspace = true }
mime = { workspace = true }
mime_guess = { workspace = true }
ml-dsa = { workspace = true, optional = true }
ml-kem = { workspace = true, optional = true }
net_traits = { workspace = true }
nom-rfc8288 = { workspace = true }
num-traits = { workspace = true }
num_cpus = { workspace = true }
ocb3 = { workspace = true, optional = true }
p256 = { workspace = true, optional = true }
p384 = { workspace = true, optional = true }
p521 = { workspace = true, optional = true }
paint_api = { workspace = true }
parking_lot = { workspace = true }
percent-encoding = { workspace = true }
phf = { workspace = true }
pixels = { workspace = true }
pkcs8 = { workspace = true, optional = true }
postcard = { workspace = true }
profile_traits = { workspace = true }
rand = { workspace = true }
regex = { workspace = true }
resvg = { workspace = true }
rsa = { workspace = true, optional = true }
rustc-hash = { workspace = true }
script_bindings = { workspace = true }
script_webgpu = { workspace = true, optional = true }
script_traits = { workspace = true }
selectors = { workspace = true }
serde = { workspace = true, features = ["derive"] }
serde_json = { workspace = true, features = ["preserve_order"] }
servo-background-hang-monitor-api = { workspace = true }
servo-base = { workspace = true }
servo-bluetooth-traits = { workspace = true, optional = true }
servo-canvas-traits = { workspace = true }
servo-config = { workspace = true }
servo-constellation-traits = { workspace = true }
servo-geometry = { workspace = true }
servo-media = { workspace = true }
servo-tracing = { workspace = true }
servo-url = { workspace = true }
servo-webvtt = { workspace = true }
servo_arc = { workspace = true }
sha1 = { workspace = true, optional = true }
sha2 = { workspace = true, optional = true }
sha3 = { workspace = true, optional = true }
smallvec = { workspace = true }
sponge-cursor = { workspace = true, optional = true }
storage_traits = { workspace = true }
strum = { workspace = true }
stylo = { workspace = true }
stylo_atoms = { workspace = true }
stylo_dom = { workspace = true }
stylo_malloc_size_of = { workspace = true }
stylo_traits = { workspace = true }
swapper = { workspace = true }
tempfile = { workspace = true }
tendril = { workspace = true }
time = { workspace = true }
timers = { workspace = true }
tracing = { workspace = true, optional = true }
unicode-bidi = { workspace = true }
unicode-script = { workspace = true }
url = { workspace = true }
urlpattern = { workspace = true }
uuid = { workspace = true, features = ["serde"] }
web_atoms = { workspace = true }
webdriver = { workspace = true }
webgpu_traits = { workspace = true, optional = true }
webrender_api = { workspace = true }
webxr-api = { workspace = true, optional = true }
x-wing = { workspace = true, optional = true }
x25519-dalek = { workspace = true, optional = true }
x448 = { workspace = true, optional = true }
xml5ever = { workspace = true }
xpath = { workspace = true }
zeroize = { workspace = true, optional = true }
[target.'cfg(not(target_os = "ios"))'.dependencies]
mozangle = { workspace = true, optional = true }

57
vendor/servo-script/build.rs vendored Normal file
View file

@ -0,0 +1,57 @@
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at https://mozilla.org/MPL/2.0/. */
use std::env;
use std::path::{Path, PathBuf};
fn main() {
// copy include! files from script_bindings's OUT_DIR, to script's OUT_DIR
// this is done to bypass limitation of Rust Analyzer: https://github.com/rust-lang/rust-analyzer/issues/17040
let script_bindings_out_dir =
PathBuf::from(env::var_os("DEP_SCRIPT_BINDINGS_CRATE_OUT_DIR").unwrap());
let out_dir = PathBuf::from(env::var_os("OUT_DIR").unwrap());
// copy concrete files
[
"InterfaceTypes.rs",
"DomTypeHolder.rs",
"InterfaceObjectMap.rs",
"ConcreteInheritTypes.rs",
"UnionTypes.rs",
"InterfaceObjectMapPhf.rs",
"ContentEventHandlerNames.rs",
]
.iter()
.map(Path::new)
.for_each(|file| {
println!(
"cargo::rerun-if-changed={}",
script_bindings_out_dir.join(file).display()
);
std::fs::copy(
script_bindings_out_dir.join(file),
out_dir.join(file.file_name().unwrap()),
)
.unwrap();
});
// copy ConcreteBindings folder
let _ = std::fs::create_dir(out_dir.join("ConcreteBindings"));
let script_concrete_bindings_out_dir = script_bindings_out_dir.join("ConcreteBindings");
println!(
"cargo::rerun-if-changed={}",
script_concrete_bindings_out_dir.display()
);
std::fs::read_dir(script_concrete_bindings_out_dir)
.unwrap()
.filter_map(|res| res.map(|e| e.path()).ok())
.filter(|path| path.is_file())
.for_each(|file| {
std::fs::copy(
&file,
out_dir
.join("ConcreteBindings")
.join(file.file_name().unwrap()),
)
.unwrap();
});
}

18
vendor/servo-script/conversions.rs vendored Normal file
View file

@ -0,0 +1,18 @@
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at https://mozilla.org/MPL/2.0/. */
use js::context::JSContext;
/// A version of the `Into<T>` trait from the standard library that can be used
/// to convert between two types that are not defined in the script crate.
/// This is intended to be used on dict/enum types generated from WebIDL once
/// those types are moved out of the script crate.
pub(crate) trait Convert<T> {
fn convert(self) -> T;
}
/// Same as `Convert`, but also passes a `cx`
pub(crate) trait ConvertWithCx<T> {
fn convert(&self, cx: &mut JSContext) -> T;
}

87
vendor/servo-script/css/css.rs vendored Normal file
View file

@ -0,0 +1,87 @@
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at https://mozilla.org/MPL/2.0/. */
//! Helpers for CSS value parsing.
use std::sync::LazyLock;
use style::context::QuirksMode;
use style::error_reporting::ParseErrorReporter;
use style::parser::ParserContext;
use style::stylesheets::{CssRuleType, Origin, UrlExtraData};
use style_traits::ParsingMode;
use url::Url;
use crate::dom::document::Document;
pub(crate) static ANONYMOUS_CONTENT_URL_DATA: LazyLock<UrlExtraData> =
LazyLock::new(|| Url::parse("about:blank").unwrap().into());
/// Creates a `ParserContext` from the given document.
///
/// Automatically configures quirks mode and error reporter from the document.
pub(crate) fn parser_context_for_document<'a>(
document: &'a Document,
rule_type: CssRuleType,
parsing_mode: ParsingMode,
url_data: &'a UrlExtraData,
) -> ParserContext<'a> {
let quirks_mode = document.quirks_mode();
let error_reporter = document.window().css_error_reporter();
ParserContext::new(
Origin::Author,
url_data,
Some(rule_type),
parsing_mode,
quirks_mode,
/* namespaces = */ Default::default(),
Some(error_reporter),
None,
/* attr_taint = */ Default::default(),
)
}
/// Like [`parser_context_for_document`], but with a custom error reporter.
pub(crate) fn parser_context_for_document_with_reporter<'a>(
document: &'a Document,
rule_type: CssRuleType,
parsing_mode: ParsingMode,
url_data: &'a UrlExtraData,
error_reporter: &'a dyn ParseErrorReporter,
) -> ParserContext<'a> {
let quirks_mode = document.quirks_mode();
ParserContext::new(
Origin::Author,
url_data,
Some(rule_type),
parsing_mode,
quirks_mode,
/* namespaces = */ Default::default(),
Some(error_reporter),
None,
/* attr_taint = */ Default::default(),
)
}
/// Creates a `ParserContext` without a document, using no quirks mode
/// and no error reporter.
pub(crate) fn parser_context_for_anonymous_content<'a>(
rule_type: CssRuleType,
parsing_mode: ParsingMode,
url_data: &'a UrlExtraData,
) -> ParserContext<'a> {
ParserContext::new(
Origin::Author,
url_data,
Some(rule_type),
parsing_mode,
QuirksMode::NoQuirks,
/* namespaces = */ Default::default(),
None,
None,
/* attr_taint = */ Default::default(),
)
}

11
vendor/servo-script/css/mod.rs vendored Normal file
View file

@ -0,0 +1,11 @@
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at https://mozilla.org/MPL/2.0/. */
#[expect(
clippy::module_inception,
reason = "Will be refactored later after file move"
)]
pub(crate) mod css;
pub(crate) mod stylesheet_loader;
pub(crate) mod stylesheet_set;

View file

@ -0,0 +1,726 @@
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at https://mozilla.org/MPL/2.0/. */
#![cfg_attr(crown, expect(crown::jscontext_first_arg))]
use std::io::{Read, Seek, Write};
use std::sync::atomic::{AtomicUsize, Ordering};
use bytes::{Bytes, BytesMut};
use crossbeam_channel::Sender;
use cssparser::SourceLocation;
use encoding_rs::UTF_8;
use js::context::JSContext;
use net_traits::mime_classifier::MimeClassifier;
use net_traits::request::{CorsSettings, Destination, RequestId};
use net_traits::{
FetchMetadata, FilteredMetadata, LoadContext, Metadata, NetworkError, ReferrerPolicy,
ResourceFetchTiming,
};
use servo_arc::Arc;
use servo_base::id::PipelineId;
use servo_config::pref;
use servo_url::ServoUrl;
use style::context::QuirksMode;
use style::global_style_data::STYLE_THREAD_POOL;
use style::media_queries::MediaList;
use style::shared_lock::{Locked, SharedRwLock};
use style::stylesheets::import_rule::{ImportLayer, ImportSheet, ImportSupportsCondition};
use style::stylesheets::{
ImportRule, Origin, Stylesheet, StylesheetLoader as StyleStylesheetLoader, UrlExtraData,
};
use style::values::CssUrl;
use crate::dom::bindings::inheritance::Castable;
use crate::dom::bindings::refcounted::Trusted;
use crate::dom::bindings::reflector::DomGlobal;
use crate::dom::bindings::root::DomRoot;
use crate::dom::csp::{GlobalCspReporting, Violation};
use crate::dom::document::Document;
use crate::dom::element::Element;
use crate::dom::eventtarget::EventTarget;
use crate::dom::globalscope::GlobalScope;
use crate::dom::html::htmlelement::HTMLElement;
use crate::dom::html::htmllinkelement::{HTMLLinkElement, RequestGenerationId};
use crate::dom::node::NodeTraits;
use crate::dom::performance::performanceresourcetiming::InitiatorType;
use crate::dom::shadowroot::ShadowRoot;
use crate::dom::window::CSSErrorReporter;
use crate::event_loop::document_loader::LoadType;
use crate::fetch::fetch::{RequestWithGlobalScope, create_a_potential_cors_request};
use crate::fetch::network_listener::{self, FetchResponseListener, ResourceTimingListener};
use crate::messaging::{CommonScriptMsg, MainThreadScriptMsg};
use crate::runtime::script_runtime::ScriptThreadEventCategory;
use crate::tasks::task_source::TaskSourceName;
use crate::unminify::{
BeautifyFileType, create_output_file, create_temp_files, execute_js_beautify,
};
/// An struct which is used to uniquely identify a [`StylesheetContext`] for
/// tracking the set of script-blocking stylesheets.
#[derive(Clone, Copy, Eq, Hash, JSTraceable, MallocSizeOf, PartialEq)]
pub(crate) struct StylesheetContextId(usize);
impl StylesheetContextId {
fn next() -> Self {
static NEXT_STYLESHEET_CONTEXT_INDEX: AtomicUsize = AtomicUsize::new(0);
Self(NEXT_STYLESHEET_CONTEXT_INDEX.fetch_add(1, Ordering::Relaxed))
}
}
pub(crate) trait StylesheetOwner {
/// Returns whether this element was inserted by the parser (i.e., it should
/// trigger a document-load-blocking load).
fn parser_inserted(&self) -> bool;
/// <https://html.spec.whatwg.org/multipage/#potentially-render-blocking>
fn potentially_render_blocking(&self) -> bool;
/// Which referrer policy should loads triggered by this owner follow
fn referrer_policy(&self, cx: &mut JSContext) -> ReferrerPolicy;
/// Notes that a new load is pending to finish.
fn increment_pending_loads_count(&self);
/// Returns None if there are still pending loads, or whether any load has
/// failed since the loads started.
fn load_finished(&self, successful: bool) -> Option<bool>;
/// Sets origin_clean flag.
fn set_origin_clean(&self, cx: &mut JSContext, origin_clean: bool);
}
pub(crate) enum StylesheetContextSource {
LinkElement,
Import(Arc<Locked<ImportRule>>),
}
/// The context required for asynchronously loading an external stylesheet.
struct StylesheetContext {
/// The id associated with this [`StylesheetContext`]. This is used to uniquely identify
/// it in the `Document`'s script-blocking stylesheet set.
id: StylesheetContextId,
/// The element that initiated the request.
element: Trusted<HTMLElement>,
source: StylesheetContextSource,
media: Arc<Locked<MediaList>>,
url: ServoUrl,
metadata: Option<Metadata>,
/// The response body received to date.
data: BytesMut,
/// The node document for elem when the load was initiated.
document: Trusted<Document>,
shadow_root: Option<Trusted<ShadowRoot>>,
origin_clean: bool,
/// A token which must match the generation id of the `HTMLLinkElement` for it to load the stylesheet.
/// This is ignored for `HTMLStyleElement` and imports.
request_generation_id: Option<RequestGenerationId>,
/// <https://html.spec.whatwg.org/multipage/#contributes-a-script-blocking-style-sheet>
is_script_blocking: bool,
/// <https://html.spec.whatwg.org/multipage/#render-blocking>
is_render_blocking: bool,
}
impl StylesheetContext {
fn unminify_css(&mut self, file_url: ServoUrl) {
let Some(unminified_dir) = self.document.root().window().unminified_css_dir() else {
return;
};
let mut style_content = std::mem::take(&mut self.data).to_vec();
if let Some((input, mut output)) = create_temp_files() &&
execute_js_beautify(
input.path(),
output.try_clone().unwrap(),
BeautifyFileType::Css,
)
{
output.seek(std::io::SeekFrom::Start(0)).unwrap();
output.read_to_end(&mut style_content).unwrap();
}
match create_output_file(unminified_dir, &file_url, None) {
Ok(mut file) => {
file.write_all(&style_content).unwrap();
},
Err(why) => {
log::warn!("Could not store script {:?}", why);
},
}
self.data = Bytes::copy_from_slice(&style_content)
.try_into_mut()
.unwrap();
}
fn empty_stylesheet(&self, document: &Document) -> Arc<Stylesheet> {
let shared_lock = document.style_shared_author_lock().clone();
let quirks_mode = document.quirks_mode();
Arc::new(Stylesheet::from_bytes(
&[],
UrlExtraData(self.url.get_arc()),
None,
None,
Origin::Author,
self.media.clone(),
shared_lock,
None,
None,
quirks_mode,
))
}
fn parse(
&self,
quirks_mode: QuirksMode,
shared_lock: SharedRwLock,
css_error_reporter: &CSSErrorReporter,
loader: ElementStylesheetLoader<'_>,
) -> Arc<Stylesheet> {
let metadata = self
.metadata
.as_ref()
.expect("Should never call parse without metadata.");
let _span = profile_traits::trace_span!("ParseStylesheet").entered();
Arc::new(Stylesheet::from_bytes(
&self.data,
UrlExtraData(metadata.final_url.get_arc()),
metadata.charset.as_deref(),
// The CSS environment encoding is the result of running the following steps: [CSSSYNTAX]
// If el has a charset attribute, get an encoding from that attribute's value. If that succeeds, return the resulting encoding. [ENCODING]
// Otherwise, return the document's character encoding. [DOM]
//
// TODO: Need to implement encoding http://dev.w3.org/csswg/css-syntax/#environment-encoding
Some(UTF_8),
Origin::Author,
self.media.clone(),
shared_lock,
Some(&loader),
Some(css_error_reporter),
quirks_mode,
))
}
fn contributes_to_the_styling_processing_model(&self, element: &HTMLElement) -> bool {
if !element.upcast::<Element>().is_connected() {
return false;
}
// Whether or not this `StylesheetContext` is for a `<link>` element that comes
// from a previous generation. This prevents processing of earlier stylsheet URLs
// when the URL has changed.
//
// TODO(mrobinson): Shouldn't we also exit early if this is an import that was originally
// imported from a `<link>` element that has advanced a generation as well?
if !matches!(&self.source, StylesheetContextSource::LinkElement) {
return true;
}
let link = element.downcast::<HTMLLinkElement>().unwrap();
self.request_generation_id
.is_none_or(|generation| generation == link.get_request_generation_id())
}
/// <https://html.spec.whatwg.org/multipage/#contributes-a-script-blocking-style-sheet>
fn contributes_a_script_blocking_style_sheet(
&self,
element: &HTMLElement,
owner: &dyn StylesheetOwner,
document: &Document,
) -> bool {
// el was created by that Document's parser.
owner.parser_inserted()
// el is either a style element or a link element that was an external resource link that
// contributes to the styling processing model when the el was created by the parser.
&& element.downcast::<HTMLLinkElement>().is_none_or(|link|
self.contributes_to_the_styling_processing_model(element)
// el's style sheet was enabled when the element was created by the parser.
&& !link.is_effectively_disabled()
)
// el's media attribute's value matches the environment.
&& element.media_attribute_matches_media_environment()
// The last time the event loop reached step 1, el's root was that Document.
&& *element.owner_document() == *document
// The user agent hasn't given up on loading that particular style sheet yet.
// A user agent may give up on loading a style sheet at any time.
//
// This might happen when we time out a resource, but that happens in `fetch` instead
}
fn decrement_blockers_and_finish_load(
self,
document: &Document,
cx: &mut js::context::JSContext,
) {
if self.is_script_blocking {
document.remove_script_blocking_stylesheet(self.id);
}
if self.is_render_blocking {
document.decrement_render_blocking_element_count();
}
document.finish_load(LoadType::Stylesheet(self.url), cx);
}
fn do_post_parse_tasks(
self,
success: bool,
stylesheet: Arc<Stylesheet>,
cx: &mut js::context::JSContext,
) {
let element = self.element.root();
let document = self.document.root();
let owner = element
.upcast::<Element>()
.as_stylesheet_owner()
.expect("Stylesheet not loaded by <style> or <link> element!");
match &self.source {
// https://html.spec.whatwg.org/multipage/#link-type-stylesheet%3Aprocess-the-linked-resource
StylesheetContextSource::LinkElement => {
let link = element
.downcast::<HTMLLinkElement>()
.expect("Should be HTMLinkElement due to StylesheetContextSource");
// For failed requests, we should bail out if it is from a previous generation.
// Since we can reissue another failed request, which resets the pending load counter
// in a link element.
if self
.request_generation_id
.is_some_and(|generation| generation != link.get_request_generation_id())
{
self.decrement_blockers_and_finish_load(&document, cx);
return;
}
// https://html.spec.whatwg.org/multipage/#link-type-stylesheet
// > When the disabled attribute of a link element with a stylesheet keyword is set,
// > disable the associated CSS style sheet.
if link.is_effectively_disabled() {
stylesheet.set_disabled(true);
}
// Step 3. If el has an associated CSS style sheet, remove the CSS style sheet.
// Step 4. If success is true, then:
// Step 4.1. Create a CSS style sheet with the following properties:
//
// Note that even in the failure case, we should create an empty stylesheet.
// That's why `set_stylesheet` also removes the previous stylesheet
link.set_stylesheet(cx.no_gc(), stylesheet);
},
StylesheetContextSource::Import(import_rule) => {
let mut guard = document.style_shared_author_lock().write();
import_rule.write_with(&mut guard).stylesheet = ImportSheet::Sheet(stylesheet);
},
}
if let Some(ref shadow_root) = self.shadow_root {
shadow_root.root().invalidate_stylesheets(cx.no_gc());
} else {
document.invalidate_stylesheets(cx.no_gc());
}
owner.set_origin_clean(cx, self.origin_clean);
// Remaining steps are a combination of
// https://html.spec.whatwg.org/multipage/#link-type-stylesheet%3Aprocess-the-linked-resource
// and https://html.spec.whatwg.org/multipage/#the-style-element%3Acritical-subresources
// Step 4.2. Fire an event named load at el.
// Step 5. Otherwise, fire an event named error at el.
if let Some(any_failed) = owner.load_finished(success) {
// Only fire an event if we have no more pending events
// (in which case `owner.load_finished` would return None)
let event = match any_failed {
true => atom!("error"),
false => atom!("load"),
};
element.upcast::<EventTarget>().fire_event(cx, event);
}
// Regardless if there are other pending events, we need to unblock
// rendering for this particular request and signal that the load has finished
// Step 6. If el contributes a script-blocking style sheet, then:
// Step 7. Unblock rendering on el.
self.decrement_blockers_and_finish_load(&document, cx);
}
}
impl FetchResponseListener for StylesheetContext {
fn process_request_body(&mut self, _: RequestId) {}
fn process_response(
&mut self,
_: &mut js::context::JSContext,
_: RequestId,
metadata: Result<FetchMetadata, NetworkError>,
) {
if let Ok(FetchMetadata::Filtered {
filtered: FilteredMetadata::Opaque | FilteredMetadata::OpaqueRedirect(_),
..
}) = metadata
{
self.origin_clean = false;
}
self.metadata = metadata.ok().map(|m| match m {
FetchMetadata::Unfiltered(m) => m,
FetchMetadata::Filtered { unsafe_, .. } => unsafe_,
});
}
fn process_response_chunk(
&mut self,
_: &mut js::context::JSContext,
_: RequestId,
payload: Bytes,
) {
self.data.extend_from_slice(&payload);
}
fn process_response_eof(
mut self,
cx: &mut js::context::JSContext,
_: RequestId,
status: Result<(), NetworkError>,
timing: ResourceFetchTiming,
) {
network_listener::submit_timing(cx, &self, &status, &timing);
let document = self.document.root();
let Some(metadata) = self.metadata.as_ref() else {
let empty_stylesheet = self.empty_stylesheet(&document);
self.do_post_parse_tasks(false, empty_stylesheet, cx);
return;
};
let element = self.element.root();
// https://html.spec.whatwg.org/multipage/#link-type-stylesheet:process-the-linked-resource
if element.is::<HTMLLinkElement>() {
// Step 1. If the resource's Content-Type metadata is not text/css, then set success to false.
let is_css = MimeClassifier::is_css(
&metadata.resource_content_type_metadata(LoadContext::Style, &self.data),
) || (
// From <https://html.spec.whatwg.org/multipage/#link-type-stylesheet>:
// > Quirk: If the document has been set to quirks mode, has the same origin as
// > the URL of the external resource, and the Content-Type metadata of the
// > external resource is not a supported style sheet type, the user agent must
// > instead assume it to be text/css.
document.quirks_mode() == QuirksMode::Quirks &&
document.origin().immutable().clone() == metadata.final_url.origin()
);
if !is_css {
let empty_stylesheet = self.empty_stylesheet(&document);
self.do_post_parse_tasks(false, empty_stylesheet, cx);
return;
}
// Step 2. If el no longer creates an external resource link that contributes to the styling processing model,
// or if, since the resource in question was fetched, it has become appropriate to fetch it again, then:
if !self.contributes_to_the_styling_processing_model(&element) {
// Step 2.1. Remove el from el's node document's script-blocking style sheet set.
self.decrement_blockers_and_finish_load(&document, cx);
// Step 2.2. Return.
return;
}
}
if metadata.status != http::StatusCode::OK {
let empty_stylesheet = self.empty_stylesheet(&document);
self.do_post_parse_tasks(false, empty_stylesheet, cx);
return;
}
self.unminify_css(metadata.final_url.clone());
let loader = if pref!(dom_parallel_css_parsing_enabled) {
ElementStylesheetLoader::Asynchronous(AsynchronousStylesheetLoader::new(&element))
} else {
ElementStylesheetLoader::Synchronous { element: &element }
};
loader.parse(self, &element, &document, cx);
}
fn process_csp_violations(
&mut self,
cx: &mut js::context::JSContext,
_request_id: RequestId,
violations: Vec<Violation>,
) {
let global = &self.resource_timing_global();
global.report_csp_violations(cx, violations, None, None);
}
fn process_content_length(&mut self, _request_id: RequestId, size: usize) {
self.data.reserve(size.saturating_sub(self.data.len()));
}
}
impl ResourceTimingListener for StylesheetContext {
fn resource_timing_information(&self) -> (InitiatorType, ServoUrl) {
let initiator_type = InitiatorType::LocalName(
self.element
.root()
.upcast::<Element>()
.local_name()
.to_string(),
);
(initiator_type, self.url.clone())
}
fn resource_timing_global(&self) -> DomRoot<GlobalScope> {
self.element.root().owner_document().global()
}
}
pub(crate) enum ElementStylesheetLoader<'a> {
Synchronous { element: &'a HTMLElement },
Asynchronous(AsynchronousStylesheetLoader),
}
impl<'a> ElementStylesheetLoader<'a> {
pub(crate) fn new(element: &'a HTMLElement) -> Self {
ElementStylesheetLoader::Synchronous { element }
}
}
impl ElementStylesheetLoader<'_> {
pub(crate) fn load_with_element(
cx: &mut JSContext,
element: &HTMLElement,
source: StylesheetContextSource,
media: Arc<Locked<MediaList>>,
url: ServoUrl,
cors_setting: Option<CorsSettings>,
integrity_metadata: String,
) {
let document = element.owner_document();
let shadow_root = element
.containing_shadow_root()
.map(|shadow_root| Trusted::new(&*shadow_root));
let generation = element
.downcast::<HTMLLinkElement>()
.map(HTMLLinkElement::get_request_generation_id);
let mut context = StylesheetContext {
id: StylesheetContextId::next(),
element: Trusted::new(element),
source,
media,
url: url.clone(),
metadata: None,
data: BytesMut::new(),
document: Trusted::new(&*document),
shadow_root,
origin_clean: true,
request_generation_id: generation,
is_script_blocking: false,
is_render_blocking: false,
};
let owner = element
.upcast::<Element>()
.as_stylesheet_owner()
.expect("Stylesheet not loaded by <style> or <link> element!");
let referrer_policy = owner.referrer_policy(cx);
owner.increment_pending_loads_count();
// Final steps of https://html.spec.whatwg.org/multipage/#update-a-style-block
// and part of https://html.spec.whatwg.org/multipage/#link-type-stylesheet:linked-resource-fetch-setup-steps
// If element contributes a script-blocking style sheet, append element to its node document's script-blocking style sheet set.
context.is_script_blocking =
context.contributes_a_script_blocking_style_sheet(element, owner, &document);
if context.is_script_blocking {
document.add_script_blocking_stylesheet(context.id);
}
// If element's media attribute's value matches the environment and
// element is potentially render-blocking, then block rendering on element.
context.is_render_blocking = element.media_attribute_matches_media_environment() &&
owner.potentially_render_blocking() &&
document.allows_adding_render_blocking_elements();
if context.is_render_blocking {
document.increment_render_blocking_element_count();
}
// https://html.spec.whatwg.org/multipage/#default-fetch-and-process-the-linked-resource
let global = element.global();
let request = create_a_potential_cors_request(
Some(document.webview_id()),
url.clone(),
Destination::Style,
cors_setting,
None,
global.get_referrer(),
)
.with_global_scope(&global)
.referrer_policy(referrer_policy)
.integrity_metadata(integrity_metadata);
document.fetch_blocking(LoadType::Stylesheet(url), request, context);
}
fn parse(
self,
listener: StylesheetContext,
element: &HTMLElement,
document: &Document,
cx: &mut js::context::JSContext,
) {
let shared_lock = document.style_shared_author_lock().clone();
let quirks_mode = document.quirks_mode();
let window = element.owner_window();
match self {
ElementStylesheetLoader::Synchronous { .. } => {
let stylesheet =
listener.parse(quirks_mode, shared_lock, window.css_error_reporter(), self);
listener.do_post_parse_tasks(true, stylesheet, cx);
},
ElementStylesheetLoader::Asynchronous(asynchronous_loader) => {
let css_error_reporter = window.css_error_reporter().clone();
let parse_stylesheet = move || {
let pipeline_id = asynchronous_loader.pipeline_id;
let main_thread_sender = asynchronous_loader.main_thread_sender.clone();
let loader = ElementStylesheetLoader::Asynchronous(asynchronous_loader);
let stylesheet =
listener.parse(quirks_mode, shared_lock, &css_error_reporter, loader);
let task = task!(finish_parsing_of_stylesheet_on_main_thread: move |cx| {
listener.do_post_parse_tasks(true, stylesheet, cx);
});
let _ = main_thread_sender.send(MainThreadScriptMsg::Common(
CommonScriptMsg::Task(
ScriptThreadEventCategory::StylesheetLoad,
Box::new(task),
Some(pipeline_id),
TaskSourceName::Networking,
),
));
};
let thread_pool = STYLE_THREAD_POOL.pool();
if let Some(thread_pool) = thread_pool.as_ref() {
thread_pool.spawn(parse_stylesheet);
} else {
parse_stylesheet();
}
},
};
}
}
impl StyleStylesheetLoader for ElementStylesheetLoader<'_> {
/// Request a stylesheet after parsing a given `@import` rule, and return
/// the constructed `@import` rule.
fn request_stylesheet(
&self,
url: CssUrl,
source_location: SourceLocation,
lock: &SharedRwLock,
media: Arc<Locked<MediaList>>,
supports: Option<ImportSupportsCondition>,
layer: ImportLayer,
) -> Arc<Locked<ImportRule>> {
// Ensure the supports conditions for this @import are true, if not, refuse to load
if supports.as_ref().is_some_and(|s| !s.enabled) {
return Arc::new(lock.wrap(ImportRule {
url,
stylesheet: ImportSheet::new_refused(),
supports,
layer,
source_location,
}));
}
let resolved_url = match url.url().cloned() {
Some(url) => url,
None => {
return Arc::new(lock.wrap(ImportRule {
url,
stylesheet: ImportSheet::new_refused(),
supports,
layer,
source_location,
}));
},
};
let import_rule = Arc::new(lock.wrap(ImportRule {
url,
stylesheet: ImportSheet::new_pending(),
supports,
layer,
source_location,
}));
// TODO (mrnayak) : Whether we should use the original loader's CORS
// setting? Fix this when spec has more details.
let source = StylesheetContextSource::Import(import_rule.clone());
match self {
ElementStylesheetLoader::Synchronous { element } => {
// TODO: https://github.com/servo/servo/issues/44685
#[expect(unsafe_code)]
let mut cx = unsafe { script_bindings::script_runtime::temp_cx() };
Self::load_with_element(
&mut cx,
element,
source,
media,
resolved_url.into(),
None,
String::new(),
);
},
ElementStylesheetLoader::Asynchronous(AsynchronousStylesheetLoader {
element,
main_thread_sender,
pipeline_id,
}) => {
let element = element.clone();
let task = task!(load_import_stylesheet_on_main_thread: move || {
// TODO: https://github.com/servo/servo/issues/44685
#[expect(unsafe_code)]
let mut cx = unsafe { script_bindings::script_runtime::temp_cx() };
Self::load_with_element(
&mut cx,
&element.root(),
source,
media,
resolved_url.into(),
None,
String::new()
);
});
let _ =
main_thread_sender.send(MainThreadScriptMsg::Common(CommonScriptMsg::Task(
ScriptThreadEventCategory::StylesheetLoad,
Box::new(task),
Some(*pipeline_id),
TaskSourceName::Networking,
)));
},
}
import_rule
}
}
pub(crate) struct AsynchronousStylesheetLoader {
element: Trusted<HTMLElement>,
main_thread_sender: Sender<MainThreadScriptMsg>,
pipeline_id: PipelineId,
}
impl AsynchronousStylesheetLoader {
pub(crate) fn new(element: &HTMLElement) -> Self {
let window = element.owner_window();
Self {
element: Trusted::new(element),
main_thread_sender: window.main_thread_script_chan().clone(),
pipeline_id: window.pipeline_id(),
}
}
}

View file

@ -0,0 +1,81 @@
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at https://mozilla.org/MPL/2.0/. */
use style::device::Device;
use style::shared_lock::SharedRwLockReadGuard;
use style::stylesheet_set::{AuthorStylesheetSet, DocumentStylesheetSet};
use style::stylesheets::{CustomMediaMap, StylesheetInDocument};
/// Functionality common to DocumentStylesheetSet and AuthorStylesheetSet.
pub(crate) enum StylesheetSetRef<'a, S>
where
S: StylesheetInDocument + PartialEq + 'static,
{
/// Author stylesheet set.
Author(&'a mut AuthorStylesheetSet<S>),
/// Document stylesheet set.
Document(&'a mut DocumentStylesheetSet<S>),
}
impl<S> StylesheetSetRef<'_, S>
where
S: StylesheetInDocument + PartialEq + 'static,
{
/// Appends a new stylesheet to the current set.
///
/// No device implies not computing invalidations.
pub(crate) fn append_stylesheet(
&mut self,
device: Option<&Device>,
sheet: S,
guard: &SharedRwLockReadGuard,
) {
let custom_media = &CustomMediaMap::default();
match self {
StylesheetSetRef::Author(set) => {
set.append_stylesheet(device, custom_media, sheet, guard)
},
StylesheetSetRef::Document(set) => {
set.append_stylesheet(device, custom_media, sheet, guard)
},
}
}
/// Insert a given stylesheet before another stylesheet in the document.
pub(crate) fn insert_stylesheet_before(
&mut self,
device: Option<&Device>,
sheet: S,
before_sheet: S,
guard: &SharedRwLockReadGuard,
) {
let custom_media = &CustomMediaMap::default();
match self {
StylesheetSetRef::Author(set) => {
set.insert_stylesheet_before(device, custom_media, sheet, before_sheet, guard)
},
StylesheetSetRef::Document(set) => {
set.insert_stylesheet_before(device, custom_media, sheet, before_sheet, guard)
},
}
}
/// Remove a given stylesheet from the set.
pub(crate) fn remove_stylesheet(
&mut self,
device: Option<&Device>,
sheet: S,
guard: &SharedRwLockReadGuard,
) {
let custom_media = &CustomMediaMap::default();
match self {
StylesheetSetRef::Author(set) => {
set.remove_stylesheet(device, custom_media, sheet, guard)
},
StylesheetSetRef::Document(set) => {
set.remove_stylesheet(device, custom_media, sheet, guard)
},
}
}
}

View file

@ -0,0 +1,377 @@
% JavaScript: Servo's only garbage collector
A web browser's purpose in life is to mediate interaction between a user and
an application (which we somewhat anachronistically call a 'document').
Users expect a browser to be fast and responsive, so the core layout and
rendering algorithms are typically implemented in low-level native code.
At the same time, JavaScript code in the document can perform complex
modifications through the [Document Object Model][DOM].
This means the browser's representation of a document in memory is a
cross-language data structure, bridging the gap between low-level native code
and the high-level, garbage-collected world of JavaScript.
We're taking this as another opportunity in the Servo project to advance the
state of the art. We have a new approach for DOM memory management, and we get
to use some of the Rust language's exciting features, like auto-generated trait
implementations, lifetime checking, and custom static analysis plugins.
[DOM]: https://developer.mozilla.org/en-US/docs/Web/API/Document_Object_Model
Memory management for the DOM
=============================
It's essential that we never destroy a DOM object while it's still reachable
from either JavaScript or native code — such [use-after-free bugs][uaf] often
produce exploitable security holes. To solve this problem, most existing
browsers use [reference counting][refcounting] to track the pointers between
underlying low-level DOM objects. When JavaScript retrieves a DOM object
(through [`getElementById`][gEBI] for example), the browser builds a
'reflector' object in the JavaScript virtual machine that holds a reference to
the underlying low-level object. If the JavaScript garbage collector determines
that a reflector is no longer reachable, it destroys the reflector and
decrements the reference count on the underlying object.
[uaf]: https://cwe.mitre.org/data/definitions/416.html
[refcounting]: https://en.wikipedia.org/wiki/Reference_counting
[gEBI]: https://developer.mozilla.org/en-US/docs/Web/API/document.getElementById
This solves the use-after-free issue. But to keep users happy, we also need to
keep the browser's memory footprint small. This means destroying objects as
soon as they are no longer needed. Unfortunately, the cross-language
'reflector' scheme introduces a major complication.
Consider a C++ `Element` object which holds a reference-counted pointer to an
`Event`:
```cpp
struct Element {
RefPtr<Event> mEvent;
};
```
Now suppose we add an event handler to the element from JavaScript:
```js
elem.addEventListener("load", function(event) {
event.originalTarget = elem;
});
```
When the event fires, the handler adds a property on the `Event` which points
back to the `Element`. We now have a cross-language reference cycle, with an
`Element` pointing to an `Event` within C++, and an `Event` reflector pointing
to the `Element` reflector in JavaScript. The C++ reference counting will never
destroy a cycle, and the JavaScript garbage collector can't trace through the
C++ pointers, so these objects will never be freed.
Existing browsers resolve this problem in several ways. Some do nothing, and
leak memory. Some try to manually break possible cycles, by nulling out
`mEvent` for example. And some implement a [cycle collection][cc] algorithm on
top of reference counting.
[cc]: https://developer.mozilla.org/en-US/docs/Interfacing_with_the_XPCOM_cycle_collector
None of these solutions are particularly satisfying, so we're trying something
new in Servo by choosing not to reference count DOM objects at all. Instead,
we give the JavaScript garbage collector full responsibility for managing those
native-code DOM objects. This requires a fairly complex interaction between
Servo's Rust code and the [SpiderMonkey][SM] garbage collector, which is
written in C++. Fortunately, Rust provides some cool features that let us build
this in a way that's fast, secure, and maintainable.
[SM]: https://developer.mozilla.org/en-US/docs/Mozilla/Projects/SpiderMonkey
Auto-generating field traversals
================================
How will the garbage collector find all the references between DOM objects? In
[Gecko]'s cycle collector this is done with a lot of hand-written annotations,
e.g.:
[Gecko]: https://developer.mozilla.org/en-US/docs/Mozilla/Gecko
```cpp
NS_IMPL_CYCLE_COLLECTION(nsFrameLoader, mDocShell, mMessageManager)
```
This macro describes which members of a C++ class should be added to a graph
of potential cycles. Forgetting an entry can produce a memory leak. In Servo
the consequences would be even worse: if the garbage collector can't see all
references, it might free an object that is still in use. It's essential for
both security and programmer convenience that we get rid of this manual listing
of fields.
Rust has a notion of [traits][traits], which are similar to
[type classes][typeclasses] in Haskell or interfaces in many object-oriented
languages. For example, we can create a `HasArea` trait:
[traits]: https://doc.rust-lang.org/book/traits.html
[typeclasses]: http://learnyouahaskell.com/types-and-typeclasses
```rust
trait HasArea {
fn area(&self) -> f64;
}
```
Any type implementing the `HasArea` trait will provide a method named `area`
that takes a value of the type (by reference, hence `&self`) and returns a
floating point number. In other words, the `HasArea` trait describes any type
which has an area, and the trait provides a way to get that object's area.
Now let's look at the `JSTraceable` trait, which we use for tracing:
```rust
pub unsafe trait JSTraceable {
unsafe fn trace(&self, trc: *mut JSTracer);
}
```
Any type which can be traced will provide a `trace` method. We will implement
this method with a custom `derive` target `#[derive(JSTraceable)]`,
or a custom attribute `#[dom_struct]` which implies it.
Let's look at [Servo's implementation][document-rs] of the DOM's
[`Document`][document-mdn] interface:
[document-rs]: https://github.com/servo/servo/blob/main/components/script/dom/document.rs
[document-mdn]: https://developer.mozilla.org/en-US/docs/Web/API/document
```rust
use dom_struct::dom_struct;
#[dom_struct]
pub struct Document {
node: Node,
window: Dom<Window>,
is_html_document: bool,
...
}
```
Note the difference between the `node` and `window` fields above. In the
object hierarchy of the DOM (as defined in
[the DOM specification][document-spec]), every `Document` is also a `Node`.
Rust doesn't have inheritance for data types, so we implement this by
storing a `Node` struct within a `Document` struct. As in C++, the fields of
`Node` are included in-line with the fields of `Document`, without any pointer
indirection, and the auto-generated `trace` method will visit them as well.
[document-spec]: https://dom.spec.whatwg.org/#interface-document
A `Document` also has an associated `Window`, but this is not an 'is-a'
relationship. The `Document` just has a pointer to a `Window`, one of many
pointers to that object, which can live in native DOM data structures or in
JavaScript objects. These are precisely the pointers we need to tell the
garbage collector about. We do this with a
[custom type for traced pointers: `Dom<T>`][dom] (for example, the `Dom<Window>`
above). The implementation of `trace` for `Dom<T>` is not auto-generated; this
is where we actually call the SpiderMonkey trace hooks:
[dom]: https://doc.servo.org/script/dom/bindings/root/struct.Dom.html
```rust
/// Trace the `JSObject` held by `reflector`.
#[allow(crown::unrooted_must_root)]
pub fn trace_reflector(tracer: *mut JSTracer, description: &str, reflector: &Reflector) {
trace!("tracing reflector {}", description);
trace_object(tracer, description, reflector.rootable())
}
/// Trace a `JSObject`.
pub fn trace_object(tracer: *mut JSTracer, description: &str, obj: &Heap<*mut JSObject>) {
unsafe {
trace!("tracing {}", description);
CallObjectTracer(
tracer,
obj.ptr.get() as *mut _,
GCTraceKindToAscii(TraceKind::Object),
);
}
}
unsafe impl<T: DomObject> JSTraceable for Dom<T> {
unsafe fn trace(&self, trc: *mut JSTracer) {
let trace_string;
let trace_info = if cfg!(debug_assertions) {
trace_string = format!("for {} on heap", ::std::any::type_name::<T>());
&trace_string[..]
} else {
"for DOM object on heap"
};
trace_reflector(trc, trace_info, (*self.ptr.as_ptr()).reflector());
}
}
```
This call will also update the pointer to the reflector, if it was
[moved][moving-gc].
[moving-gc]: https://en.wikipedia.org/wiki/Tracing_garbage_collection#Moving_vs._non-moving
Lifetime checking for safe rooting
==================================
The Rust code in Servo needs to pass pointers to DOM objects as function
arguments, store pointers to DOM objects in local variables, and so forth.
We need to make sure that the DOM objects behind these additional pointers are
kept alive by the garbage collector while we use them. If we touch an object
from Rust when the garbage collector is not aware of it, that could introduce a
use-after-free vulnerability.
We use Rust's built-in reference type (`&T`) for pointers to DOM objects that
are known to the garbage collector. Note that such a reference is nothing more
than a pointer in the compiled code; the reference does not by itself signal
anything to the garbage collector. As a pointer to a DOM object might make its
way through many function calls and local variables before we're done with it,
we need to avoid the cost of telling the garbage collector about each and every
step along the way.
Such a reference can be obtained in different ways. For example, DOM code is
often called from JavaScript through [IDL-based bindings][bindings]. In this
case, the bindings code constructs a [root][gc-root] for any involved DOM
objects.
[bindings]: https://doc.servo.org/script/dom/bindings/index.html
[gc-root]: https://en.wikipedia.org/wiki/Tracing_garbage_collection#Reachability_of_an_object
Another common situation is creating a stack-local root manually. For this
purpose, we have a [`DomRoot<T>`][root] struct. When the `DomRoot<T>` is destroyed,
typically at the end of the function (or block) where it was created, its
destructor will un-root the DOM object. This is an example of the
[RAII idiom][raii], which Rust inherits from C++.
`DomRoot<T>` structs are primarily returned from [`T::new` functions][new] when
creating a new DOM object.
In some cases, we need to use a DOM object longer than the reference we
received allows us to; the [`DomRoot::from_ref` associated function][from-ref]
allows creating a new `DomRoot<T>` struct in that case.
[root]: https://doc.servo.org/script/dom/bindings/root/type.DomRoot.html
[raii]: https://en.wikipedia.org/wiki/Resource_Acquisition_Is_Initialization
[new]: https://doc.servo.org/script/dom/index.html#construction
[from-ref]: https://doc.servo.org/script/dom/bindings/root/struct.Root.html#method.from_ref
We can then obtain a reference from the `DomRoot<T>` through Rust's built-in
[`Deref` trait][deref], which exposes a method `deref` with the following
signature:
```rust
pub fn deref<'a>(&'a self) -> &'a T {
...
```
What this syntax means is:
- **`<'a>`**: 'for any lifetime `'a`',
- **`(&'a self)`**: 'take a reference to a `DomRoot` which is valid over lifetime `'a`',
- **`-> &'a T`**: 'return a reference whose lifetime is limited to `'a`'.
This allows us to call methods and access fields of the underlying type `T`
through a `DomRoot<T>`.
[deref]: https://doc.rust-lang.org/std/ops/trait.Deref.html
A third way to obtain a reference is from the `Dom<T>` struct we encountered
earlier. Whenever we have a reference to a `Dom<T>`, we know that the DOM struct
that contains it is already rooted, and thus that the garbage collector is
aware of the `Dom<T>`, and will keep the DOM object it points to alive.
This allows us to implement the `Deref` trait on `Dom<T>` as well.
The correctness of these APIs is heavily dependent on the fact that the
reference cannot outlive the smart pointer it was retrieved from, and the fact
that the smart pointer cannot be modified while the reference extracted from it
exists.
Situations like this are common in C++ as well. No matter how smart your smart
pointer is, you can take a bare pointer to the contents and then erroneously
use that pointer past the lifetime of the smart pointer.
Rust guarantees those semantics for the built-in reference type with a
compile-time [lifetime checker][lifetimes]. The type of a reference includes
the region of code over which it is valid. In most cases, lifetimes are
[inferred][ti] and don't need to be written out in the source code. Inferred or
not, the presence of lifetime information allows the compiler to reject
use-after-free and other dangerous bugs.
[lifetimes]: https://doc.rust-lang.org/book/lifetimes.html
[ti]: https://en.wikipedia.org/wiki/Type_inference
You can check out the [`root` module's documentation][root-docs] for more details
that didn't make it into this document.
[root-docs]: https://doc.servo.org/script/dom/bindings/root/index.html
Custom static analysis
======================
To recapitulate, the safety of our system depends on two major parts:
- The auto-generated `trace` methods ensure that SpiderMonkey's garbage
collector can see all of the references between DOM objects.
- The implementation of `DomRoot<T>` guarantees that we can't use a DOM object
from Rust without telling SpiderMonkey about our temporary reference.
But there's a hole in this scheme. We could copy an unrooted pointer — a
`Dom<T>` — to a local variable on the stack, and then at some later point, root
it and use the DOM object. In the meantime, SpiderMonkey's garbage collector
won't know about that `Dom<T>` on the stack, so it might free the DOM object.
To really be safe, we need to make sure that `Dom<T>` *only* appears in places
where it will be traced, such as DOM structs, and never in local variables,
function arguments, and so forth.
This rule doesn't correspond to anything that already exists in Rust's type
system. Fortunately, the Rust compiler can load 'lint plugins' providing custom
static analysis. These basically take the form of new compiler warnings,
although in this case we set the default severity to 'error'. There is more
information about lints in section 4.7 of the paper [<cite>Experience Report:
Developing the Servo Web Browser Engine using Rust</cite>][lints].
[lints]: https://arxiv.org/pdf/1505.07383v1.pdf
We have already [implemented a plugin][js-lint] which effectively forbids
`Dom<T>` from appearing on the [stack][stack]. Because lint plugins are part of
the usual [warnings infrastructure][warnings], we can use the `allow` attribute
in places where it's okay to use `Dom<T>`, like DOM struct definitions and the
implementation of `Dom<T>` itself.
[js-lint]: https://github.com/servo/servo/blob/main/support/crown/src/unrooted_must_root.rs
[stack]: https://en.wikipedia.org/wiki/Stack-based_memory_allocation
[warnings]: https://doc.rust-lang.org/book/compiler-plugins.html#lint-plugins
Our plugin looks at every place where the code mentions a type. Remarkably,
this adds only a fraction of a second to the compile time for Servo's largest
subcomponent, as Rust compile times are dominated by [LLVM][llvm]'s back-end
optimizations and code generation.
[llvm]: https://llvm.org/
In the end, the plugin won't necessarily catch every mistake. It's hard to
achieve full [soundness][soundness] with ad-hoc extensions to a type system.
As the name 'lint plugin' suggests, the idea is to catch common mistakes at a
low cost to programmer productivity. By combining this with the lifetime
checking built in to Rust's type system, we hope to achieve a degree of
security and reliability far beyond what's feasible in C++. Additionally, since
the checking is all done at compile time, there's no penalty in the generated
machine code.
[soundness]: https://en.wikipedia.org/wiki/Soundness
Conclusion and future work
==========================
It's an open question how our garbage-collected DOM will perform compared to
a traditional reference-counted DOM. The [Blink][blink] team has also performed
[experiments with garbage collection DOM objects][blink-gc], but they don't
have Servo's luxury of starting from a clean slate and using a cutting-edge
language.
[blink]: https://www.chromium.org/blink
[blink-gc]: https://www.chromium.org/blink/blink-gc
In the future, we will likely attempt to merge the allocations of DOM objects
into the allocations of their JavaScript reflectors. This could produce
additional gains, since the reflectors need to be traced no matter what.
However, as the garbage collector can move reflectors in memory, this will make
the [use of Rust's built-in references][refs] infeasible.
[refs]: #lifetime-checking-for-safe-rooting

Some files were not shown because too many files have changed in this diff Show more