fix for new build

This commit is contained in:
Christopher Tarry
2026-10-27 23:29:53 -04:00
parent a72cae84e8
commit 2dde7e5be3
99 changed files with 9047 additions and 5673 deletions
Generated
+71 -303
View File
@@ -204,8 +204,6 @@ dependencies = [
"cexpr",
"clang-sys",
"itertools",
"log",
"prettyplease",
"proc-macro2",
"quote",
"regex",
@@ -356,16 +354,6 @@ dependencies = [
"serde",
]
[[package]]
name = "calendrical_calculations"
version = "0.2.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "5abbd6eeda6885048d357edc66748eea6e0268e3dd11f326fff5bd248d779c26"
dependencies = [
"core_maths",
"displaydoc",
]
[[package]]
name = "camino"
version = "1.2.2"
@@ -473,7 +461,6 @@ dependencies = [
"tokio",
"tokio-rustls",
"url",
"v8",
"wreq",
"wreq-util",
"zstd 0.13.3",
@@ -571,15 +558,6 @@ version = "0.8.7"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "773648b94d0e5d620f64f280777445740e61fe701025087ec8b57f45c791888b"
[[package]]
name = "core_maths"
version = "0.1.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "77745e017f5edba1a9c1d854f6f3a52dac8a12dd5af5d2f54aecf61e43d80d30"
dependencies = [
"libm",
]
[[package]]
name = "cpufeatures"
version = "0.2.17"
@@ -777,38 +755,6 @@ dependencies = [
"crypto-common",
]
[[package]]
name = "diplomat"
version = "0.16.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "f8b37a6cea72eb6df5143d3e091d4c34cb0cf4046dd1ddcc082988886fe1f809"
dependencies = [
"diplomat_core",
"proc-macro2",
"quote",
"syn 3.0.5",
]
[[package]]
name = "diplomat-runtime"
version = "0.16.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "ae517853d9f82b2d144393b1c32c34c46c2e361de2b6c44a8fdfce23beb211cd"
[[package]]
name = "diplomat_core"
version = "0.16.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "73b18e806f9ecb92df828d080efe47984ae1193958295d4a84fb8b32c9a1aa1b"
dependencies = [
"proc-macro2",
"quote",
"serde",
"smallvec",
"strck",
"syn 3.0.5",
]
[[package]]
name = "displaydoc"
version = "0.2.5"
@@ -888,7 +834,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "6e634e2e0ebac1ee034020da1ca582e17ffe4e0f5e985823721e168928136dcb"
dependencies = [
"crc32fast",
"miniz_oxide 0.9.1",
"miniz_oxide",
"zlib-rs",
]
@@ -1012,6 +958,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "0d50a92467f8ba5dd6e3ee5d4bd04d73ab2e4e1c44474a0674821dfce14b79bc"
dependencies = [
"futures-core",
"futures-sink",
"futures-task",
"pin-project-lite",
"slab",
@@ -1088,15 +1035,6 @@ dependencies = [
"regex-syntax",
]
[[package]]
name = "gzip-header"
version = "1.1.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "86848f4fd157d91041a62c78046fb7b248bcc2dce78376d436a1756e9a038577"
dependencies = [
"crc32fast",
]
[[package]]
name = "h2"
version = "0.4.20"
@@ -1160,15 +1098,6 @@ version = "0.5.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "fc0fef456e4baa96da950455cd02c081ca953b141298e41db3fc7e36b1da849c"
[[package]]
name = "home"
version = "0.5.12"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "cc627f471c528ff0c4a49e1d5e60450c8f6461dd6d10ba9dcd3a61d3dff7728d"
dependencies = [
"windows-sys 0.61.2",
]
[[package]]
name = "hstr"
version = "3.0.3"
@@ -1314,28 +1243,6 @@ dependencies = [
"cc",
]
[[package]]
name = "icu_calendar"
version = "2.3.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "58655df2f728e46e4eee80bddebefacf52ec3e77cdb925014b47c5a5905eb55c"
dependencies = [
"calendrical_calculations",
"displaydoc",
"icu_calendar_data",
"icu_locale_core",
"icu_locale_fallback",
"icu_provider",
"tinystr",
"zerovec",
]
[[package]]
name = "icu_calendar_data"
version = "2.3.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "dc00caaa3fb3201ff7a18aa458e8c3ab042b9da154cfdf948bdde3936c31c36e"
[[package]]
name = "icu_collections"
version = "2.1.1"
@@ -1357,32 +1264,11 @@ checksum = "d56e28588da92eee5c3201a6eff33fabdd49b62269c8938d4ff050ce4d900deb"
dependencies = [
"displaydoc",
"litemap",
"serde",
"tinystr",
"writeable",
"zerovec",
]
[[package]]
name = "icu_locale_fallback"
version = "2.3.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "251af8e57c9400e3eb58242fe5b8b1152b2a64fdf4cf632f923c38ccee6f2fa9"
dependencies = [
"icu_locale_core",
"icu_locale_fallback_data",
"icu_provider",
"potential_utf",
"tinystr",
"zerovec",
]
[[package]]
name = "icu_locale_fallback_data"
version = "2.3.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "decf2a22ec8fa68f1a0c1129a3f8583f8f8bc24e8b9ccbe98ead99f62a4dc3a8"
[[package]]
name = "icu_normalizer"
version = "2.1.1"
@@ -1431,8 +1317,6 @@ checksum = "d27bbb9d3abbefac45d55f647c9de1d44aafcd1186eb91879afef17c396c3e73"
dependencies = [
"displaydoc",
"icu_locale_core",
"serde",
"stable_deref_trait",
"writeable",
"yoke",
"zerofrom",
@@ -1518,12 +1402,6 @@ version = "1.0.17"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "92ecc6618181def0457392ccd0ee51198e065e016d1d527a7ac1b6dc7c1f09d2"
[[package]]
name = "ixdtf"
version = "0.6.6"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "4d3667095d64c3ecffc96463a21157b04bf3e252f6e8d5750b20c02e33c194e3"
[[package]]
name = "jobserver"
version = "0.1.35"
@@ -1575,18 +1453,6 @@ dependencies = [
"windows-link",
]
[[package]]
name = "libm"
version = "0.2.16"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "b6d2cec3eae94f9f509c767b45932f1ada8350c4bdb85af2fcab4a3c14807981"
[[package]]
name = "linux-raw-sys"
version = "0.4.15"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "d26c52dbd32dccf2d10cac7725f8eae5296885fb5703b261f7d0a0739ec807ab"
[[package]]
name = "litemap"
version = "0.8.1"
@@ -1673,15 +1539,6 @@ version = "0.2.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "68354c5c6bd36d73ff3feceb05efa59b6acb7626617f4962be322a825e61f79a"
[[package]]
name = "miniz_oxide"
version = "0.8.9"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "1fa76a2c86f704bdb222d66965fb3d63269ce38518b83cb0575fca855ebb6316"
dependencies = [
"adler2",
]
[[package]]
name = "miniz_oxide"
version = "0.9.1"
@@ -1859,12 +1716,6 @@ dependencies = [
"windows-link",
]
[[package]]
name = "paste"
version = "1.0.15"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "57c0d7b74b563b49d38dae00a0c37d4d6de9b432382b2892f0574ddcae73fd0a"
[[package]]
name = "path-clean"
version = "0.1.0"
@@ -1947,7 +1798,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "3c80231409c20246a13fddb31776fb942c38553c51e871f8cbd687a4cfb5843d"
dependencies = [
"phf_shared 0.11.3",
"rand",
"rand 0.8.5",
]
[[package]]
@@ -2022,8 +1873,6 @@ version = "0.1.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "b73949432f5e2a09657003c25bca5e19a0e9c84f8058ca374f49e0ebe605af77"
dependencies = [
"serde_core",
"writeable",
"zerovec",
]
@@ -2033,6 +1882,15 @@ version = "0.2.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "439ee305def115ba05938db6eb1644ff94165c5ab5e9420d1c1bcedbba909391"
[[package]]
name = "ppv-lite86"
version = "0.2.21"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "85eae3c4ed2f50dcfe72643da4befc30deadb458a9b590d720cde2f2b1e97da9"
dependencies = [
"zerocopy",
]
[[package]]
name = "precomputed-hash"
version = "0.1.1"
@@ -2063,16 +1921,6 @@ dependencies = [
"tracing",
]
[[package]]
name = "prettyplease"
version = "0.2.37"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "479ca8adacdd7ce8f1fb39ce9ecccbfe93a3f1344b3d0d97f20bc0196208f62b"
dependencies = [
"proc-macro2",
"syn 2.0.113",
]
[[package]]
name = "proc-macro2"
version = "1.0.107"
@@ -2121,7 +1969,27 @@ version = "0.8.5"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "34af8d1a0e25924bc5b7c43c079c942339d8f0a8b57c39049bef581b46327404"
dependencies = [
"rand_core",
"rand_core 0.6.4",
]
[[package]]
name = "rand"
version = "0.9.5"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "b9ef1d0d795eb7d84685bca4f72f3649f064e6641543d3a8c415898726a57b41"
dependencies = [
"rand_chacha",
"rand_core 0.9.5",
]
[[package]]
name = "rand_chacha"
version = "0.9.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "d3022b5f1df60f26e1ffddd6c66e8aa15de382ae63b3a0c1bfc0e4d3e3f325cb"
dependencies = [
"ppv-lite86",
"rand_core 0.9.5",
]
[[package]]
@@ -2130,6 +1998,15 @@ version = "0.6.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "ec0be4795e2f6a28069bec0b5ff3e2ac9bafc99e6a9a7dc3547996c5c816922c"
[[package]]
name = "rand_core"
version = "0.9.5"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "76afc826de14238e6e8c374ddcc1fa19e374fd8dd986b0d2af0d02377261d83c"
dependencies = [
"getrandom 0.3.4",
]
[[package]]
name = "rcgen"
version = "0.14.10"
@@ -2192,16 +2069,6 @@ dependencies = [
"memchr",
]
[[package]]
name = "resb"
version = "0.1.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "22d392791f3c6802a1905a509e9d1a6039cbbcb5e9e00e5a6d3661f7c874f390"
dependencies = [
"potential_utf",
"serde_core",
]
[[package]]
name = "ring"
version = "0.17.14"
@@ -2240,19 +2107,6 @@ dependencies = [
"nom",
]
[[package]]
name = "rustix"
version = "0.38.44"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "fdb5bc1ae2baa591800df16c9ca78619bf65c0488b41b96ccec5d11220d8c154"
dependencies = [
"bitflags",
"errno",
"libc",
"linux-raw-sys",
"windows-sys 0.59.0",
]
[[package]]
name = "rustls"
version = "0.23.46"
@@ -2588,15 +2442,6 @@ version = "1.1.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "a2eb9349b6444b326872e140eb1cf5e7c522154d69e7a0ffb0fb81c06b37543f"
[[package]]
name = "strck"
version = "1.0.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "42316e70da376f3d113a68d138a60d8a9883c604fe97942721ec2068dab13a9f"
dependencies = [
"unicode-ident",
]
[[package]]
name = "string_cache"
version = "0.9.0"
@@ -3617,40 +3462,6 @@ version = "1.0.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "55937e1799185b12863d447f42597ed69d9928686b8d88a1df17376a097d8369"
[[package]]
name = "temporal_capi"
version = "0.2.6"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "f48eb9ca4ca22caaa48d1e7a534ad3fd598a23d1a71945e8ad5ac0be501fa5f2"
dependencies = [
"diplomat",
"diplomat-runtime",
"icu_calendar",
"icu_locale_core",
"num-traits",
"temporal_rs",
"timezone_provider",
"writeable",
"zoneinfo64",
]
[[package]]
name = "temporal_rs"
version = "0.2.6"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "1a978fef907a27736827d336c0bfaab14fb8a7509dd6dc2b43c44e51d59aca5b"
dependencies = [
"calendrical_calculations",
"core_maths",
"icu_calendar",
"icu_locale_core",
"ixdtf",
"num-traits",
"timezone_provider",
"tinystr",
"writeable",
]
[[package]]
name = "tendril"
version = "0.5.1"
@@ -3740,18 +3551,6 @@ dependencies = [
"time-core",
]
[[package]]
name = "timezone_provider"
version = "0.2.6"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "89ec4f4eebb4817fde02a411aedc7ac5f66c89c68c49e5d4b17a8139f077af52"
dependencies = [
"tinystr",
"zerotrie",
"zerovec",
"zoneinfo64",
]
[[package]]
name = "tinystr"
version = "0.8.4"
@@ -3759,7 +3558,6 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "b1e27c91459209c2986af3dcf603a5a74a4368754ce37414f59acc971167f643"
dependencies = [
"displaydoc",
"serde_core",
"zerovec",
]
@@ -3822,6 +3620,18 @@ dependencies = [
"tokio",
]
[[package]]
name = "tokio-tungstenite"
version = "0.29.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "8f72a05e828585856dacd553fba484c242c46e391fb0e58917c942ee9202915c"
dependencies = [
"futures-util",
"log",
"tokio",
"tungstenite",
]
[[package]]
name = "tokio-util"
version = "0.7.19"
@@ -3930,6 +3740,22 @@ version = "0.2.5"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "e421abadd41a4225275504ea4d6566923418b7f05506fbc9c0fe86ba7396114b"
[[package]]
name = "tungstenite"
version = "0.29.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "6c01152af293afb9c7c2a57e4b559c5620b421f6d133261c60dd2d0cdb38e6b8"
dependencies = [
"bytes",
"data-encoding",
"http",
"httparse",
"log",
"rand 0.9.5",
"sha1",
"thiserror 2.0.21",
]
[[package]]
name = "typed-builder"
version = "0.23.2"
@@ -4020,23 +3846,6 @@ dependencies = [
"wasm-bindgen",
]
[[package]]
name = "v8"
version = "152.2.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "a10fe1a92da5c32c7c7f838ce36c0ccfcfd5edf0865b58bdde820aa64cea9888"
dependencies = [
"bindgen",
"bitflags",
"fslock",
"gzip-header",
"home",
"miniz_oxide 0.8.9",
"paste",
"temporal_capi",
"which",
]
[[package]]
name = "vergen"
version = "9.0.6"
@@ -4164,18 +3973,6 @@ dependencies = [
"rustls-pki-types",
]
[[package]]
name = "which"
version = "6.0.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "b4ee928febd44d98f2f459a4a79bd4d928591333a494a10a868418ac1b39cf1f"
dependencies = [
"either",
"home",
"rustix",
"winsafe",
]
[[package]]
name = "winapi"
version = "0.3.9"
@@ -4266,15 +4063,6 @@ dependencies = [
"windows-targets",
]
[[package]]
name = "windows-sys"
version = "0.59.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "1e38bc4d79ed67fd075bcc251a1c39b32a1776bbe92e5bef1f0bf1f8c531853b"
dependencies = [
"windows-targets",
]
[[package]]
name = "windows-sys"
version = "0.61.2"
@@ -4348,12 +4136,6 @@ version = "0.52.6"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "589f6da84c646204747d1270a2a5661ea66ed1cced2631d546fdfb155959f9ec"
[[package]]
name = "winsafe"
version = "0.0.19"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "d135d17ab770252ad95e9a872d365cf3090e3be864a34ab46f48555993efc904"
[[package]]
name = "wit-bindgen"
version = "0.46.0"
@@ -4383,6 +4165,7 @@ dependencies = [
"tokio",
"tokio-btls",
"tokio-socks",
"tokio-tungstenite",
"tower",
"tower-http",
"url",
@@ -4558,7 +4341,6 @@ dependencies = [
"displaydoc",
"yoke",
"zerofrom",
"zerovec",
]
[[package]]
@@ -4567,7 +4349,6 @@ version = "0.11.8"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "bb0464e17806c1d976d5cba29399c7f08e516e279e2ba493f63123b5fca67dd8"
dependencies = [
"serde",
"yoke",
"zerofrom",
"zerovec-derive",
@@ -4596,19 +4377,6 @@ version = "1.0.11"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "dcb2c125bd7365735bebeb420ccb880265ed2d2bddcbcd49f597fdfe6bd5e577"
[[package]]
name = "zoneinfo64"
version = "0.3.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "ed6eb2607e906160c457fd573e9297e65029669906b9ac8fb1b5cd5e055f0705"
dependencies = [
"calendrical_calculations",
"icu_locale_core",
"potential_utf",
"resb",
"serde",
]
[[package]]
name = "zstd"
version = "0.13.3"
+2 -12
View File
@@ -4,14 +4,8 @@ version = "0.1.0"
edition = "2024"
license = "MIT"
default-run = "cfsolve"
# The files in tests/ are modules of one test binary (tests/main.rs), so swc and v8
# are linked once instead of once per file. A new test file needs a `mod` line there.
autotests = false
[[test]]
name = "integration"
path = "tests/main.rs"
# Without default features, the library is the solver alone: `Browser`, `Options`, `Outcome`
# and `Error`. The tools in this repository use the rest.
[features]
@@ -63,7 +57,7 @@ tokio = { version = "1.53.1", features = ["macros", "net", "rt-multi-thread", "s
url = "2.5.8"
# `Url` leaves an upstream proxy's credentials percent-encoded.
percent-encoding = "2.3.2"
wreq = { version = "=0.16.1", features = ["cookies", "gzip", "brotli", "deflate", "zstd", "socks"] }
wreq = { version = "=0.16.1", features = ["cookies", "gzip", "brotli", "deflate", "zstd", "socks", "ws"] }
rustls-native-certs = { version = "0.8", optional = true }
wreq-util = { version = "0.2.0", features = ["emulation-serde", "emulation-compression"] }
# The UI audit's keyframe text, spelled as each engine serializes it.
@@ -80,10 +74,6 @@ rustls = { version = "0.23", default-features = false, features = ["std", "tls12
tokio-rustls = { version = "0.26", default-features = false, features = ["logging", "tls12", "ring"], optional = true }
rcgen = { version = "0.14", features = ["x509-parser"], optional = true }
[dev-dependencies]
# The deobfuscator's differential tests compare its output's behavior in V8.
v8 = "=152.2.0"
# Chrome 154's ClientHello: ML-DSA and GREASE signature algorithms and the
# trust_anchors extension, which the published crates cannot send. See the
# "cfsolve patch" comments in vendor/.
@@ -92,7 +82,7 @@ btls-sys = { path = "vendor/btls-sys" }
wreq = { path = "vendor/wreq" }
http2 = { path = "vendor/http2" }
# Full debug info for swc and v8 dominates link time and target/ size. Line tables
# Full debug info for swc dominates link time and target/ size. Line tables
# keep file:line in this crate's backtraces; dependencies get none.
[profile.dev]
debug = "line-tables-only"
+14 -40
View File
@@ -1,53 +1,27 @@
//! Store a real browser's probe answers for a device profile.
//! Usage: build_profile <capture.json> > answers.json
//!
//! The capture is what `scripts/cdp_capture.mjs` writes: the iframe's HTML,
//! its POSTs with their responses, and the plaintext payloads. Each probe's
//! record from the second payload is stored under the reference build's
//! names; see `cfsolve::stage2::replay`.
//! The capture is a session's `capture.json` from the capture proxy, or what
//! `scripts/cdp_capture.mjs` writes: the iframe's HTML, its POSTs with their
//! responses, and the plaintext payloads. Each probe's record from the second
//! payload is stored under the reference build's names; see
//! `cfsolve::stage2::replay`.
use std::{env, fs};
use std::env;
use std::path::Path;
use anyhow::{Context, Result};
use base64::Engine;
use base64::engine::general_purpose::STANDARD;
use cfsolve::js::Payload;
use cfsolve::script::Source;
use cfsolve::capture::CapturedSession;
use cfsolve::stage2::replay::Answers;
use cfsolve::{JsValue, challenge};
use url::Url;
fn main() -> Result<()> {
let path = env::args().nth(1).context("supply a capture JSON file")?;
let capture: JsValue = serde_json::from_slice(&fs::read(&path)?)?;
let html = capture["iframeHtml"]
.as_str()
.context("the capture has no iframe HTML")?;
let javascript = challenge::inline_javascript(html)?;
let deobfuscated = cfsolve::deobfuscate(javascript)?;
let source = Source::try_new(&deobfuscated.text)?;
// The first payload's response is the probe program, masked with the ray
// its URL carries.
let post = &capture["posts"][0];
let url = Url::parse(post["url"].as_str().context("the capture has no POST")?)?;
let body = post["responseBody"]
.as_str()
.context("the first payload has no response")?;
let program = STANDARD.decode(challenge::decode_response(
body.as_bytes(),
challenge::ray(&url)?,
)?)?;
// The second payload is the one holding the numbered records.
let payload = capture["payloads"]
.as_array()
.into_iter()
.flatten()
.filter_map(|payload| payload["payload"].as_object())
.find(|payload| payload.contains_key("1"))
.context("the capture has no second payload")?;
let answers = Answers::capture(&source, &program, &Payload::from(payload.clone()))?;
let capture = CapturedSession::read(Path::new(&path))?;
let answers = Answers::capture(
&capture.source()?,
&capture.program()?,
capture.probe_payload()?,
)?;
println!("{}", serde_json::to_string_pretty(&answers)?);
Ok(())
}
+34
View File
@@ -0,0 +1,34 @@
//! Fill a device profile's measured sections from capture-proxy runs.
//! Usage: fill_profile <base-profile.json> <capture-dir>... > profile.json
//!
//! Each capture directory is one the proxy wrote with `--out`. The new profile keeps the base's
//! other values, and the notes on stderr say where each section came from and what was left out.
//! `build_profile` writes the answers the profile's `answers` names.
use std::path::Path;
use std::{env, fs};
use anyhow::{Context, Result, ensure};
use cfsolve::capture::{self, Recording};
use serde_json::Value;
fn main() -> Result<()> {
let mut arguments = env::args().skip(1);
let base = arguments
.next()
.context("supply a base profile and capture directories")?;
let recordings: Vec<Recording> = arguments
.map(|dir| Recording::read(Path::new(&dir)))
.collect::<Result<_>>()?;
ensure!(
!recordings.is_empty(),
"supply at least one capture directory"
);
let text = fs::read(&base).with_context(|| format!("reading {base}"))?;
let mut profile: Value = serde_json::from_slice(&text)?;
for note in capture::fill_profile(&mut profile, &recordings)? {
eprintln!("{note}");
}
println!("{}", serde_json::to_string_pretty(&profile)?);
Ok(())
}
+5 -28
View File
@@ -7,41 +7,18 @@
//! writes. Records are shuffled per session, so this is the key for reading
//! a capture's second payload by hand.
use std::{env, fs};
use std::env;
use std::path::Path;
use anyhow::{Context, Result};
use base64::Engine;
use base64::engine::general_purpose::STANDARD;
use cfsolve::challenge;
use cfsolve::script::Source;
use cfsolve::capture::CapturedSession;
use cfsolve::stage2::analysis;
use cfsolve::stage2::registry::Treatment;
use serde_json::Value;
use url::Url;
fn main() -> Result<()> {
let path = env::args().nth(1).context("supply a capture JSON file")?;
let capture: Value = serde_json::from_slice(&fs::read(&path)?)?;
let html = capture["iframeHtml"]
.as_str()
.context("the capture has no iframe HTML")?;
let javascript = challenge::inline_javascript(html)?;
let deobfuscated = cfsolve::deobfuscate(javascript)?;
let source = Source::try_new(&deobfuscated.text)?;
// The first payload's response is the probe program, masked with the ray
// its URL carries.
let post = &capture["posts"][0];
let url = Url::parse(post["url"].as_str().context("the capture has no POST")?)?;
let body = post["responseBody"]
.as_str()
.context("the first payload has no response")?;
let program = STANDARD.decode(challenge::decode_response(
body.as_bytes(),
challenge::ray(&url)?,
)?)?;
let analysis = analysis::analyze(&source, &program)?;
let capture = CapturedSession::read(Path::new(&path))?;
let analysis = analysis::analyze(&capture.source()?, &capture.program()?)?;
let plan = analysis.plan();
println!("record\tkind\ttreatment\treference");
for (position, probe) in plan.probes().iter().enumerate() {
+43 -9
View File
@@ -18,6 +18,7 @@ use cfsolve::challenge::program::PreparedSession;
use cfsolve::js::Options;
use cfsolve::script::Source;
use cfsolve::stage2::analysis::{self, ProgramOutcome};
use cfsolve::stage2::registry::{Kind, Operation};
use cfsolve::stage2::{call_stack, interaction};
use serde::Serialize;
use serde_json::{Map, Value, json};
@@ -41,16 +42,50 @@ fn main() -> Result<()> {
// The click stack reads the dispatch cases off the original's own
// deobfuscation, as the CLI does when it fetches the iframe.
let (_, cases) = call_stack::deobfuscate_with_cases(original.clone())?;
let loops = call_stack::dispatch_summary(&original, &cases);
snapshot.insert("dispatch_loops".into(), record(loops));
let analysis = program("response.decoded.txt")?
.context("no first response")
.and_then(|program| {
let analysis = analysis::analyze(&prepared, &program)?;
Ok(serde_json::to_value(analysis.artifact())?)
});
.and_then(|program| analysis::analyze(&prepared, &program));
// The stack probe's frames, which the CLI rebuilds for Chromium.
if let Ok(analysis) = &analysis
&& let Some((_, Operation::Stack { fields })) = analysis.plan().operation(Kind::Stack)
{
let frames = fields
.calls
.context("the stack probe's calls have an unrecognized shape")
.and_then(|calls| call_stack::recover_probe(&original, &cases, calls))
.map(|geometry| {
json!({
"frames": geometry.frames,
"jsc_frames": geometry.jsc_frames,
"reflected": geometry.reflected,
})
});
snapshot.insert("probe_frames".into(), record(frames));
}
let analysis = analysis.and_then(|analysis| Ok(serde_json::to_value(analysis.artifact())?));
snapshot.insert("analysis".into(), record(analysis));
// The iframe's URL only places the POST, which this ignores.
let base = Url::parse("https://challenges.cloudflare.com/")?;
let installed = PreparedSession::try_new(&prepared, &base).map(|session| {
let session = PreparedSession::try_new(&prepared, &base);
// The first payload's fields and the options the script marks with `Date.now()`, which
// its timestamp differences need.
let first_payload = match &session {
Ok(session) => session.state().map(|state| {
let marks: Vec<String> = state.marks.into_iter().map(|mark| mark.option).collect();
json!({
"marks": marks,
"fields": session.program().encoder_json().payload_fields,
"timing": state.timing.map(|timing| timing.option),
"post_log": state.post_log.map(|log| log.option),
"forwarded": state.forwarded,
})
}),
Err(error) => Err(anyhow::anyhow!("{error:#}")),
};
snapshot.insert("first_payload".into(), record(first_payload));
let installed = session.map(|session| {
let installed = session.into_program().installed;
json!({"options": installed.options, "window": installed.window})
});
@@ -77,10 +112,9 @@ fn main() -> Result<()> {
);
snapshot.insert("callback_frames".into(), record(frames));
if let Ok(options) = read("options.json") {
let options: Result<Options> =
serde_json::from_str(&options).map_err(anyhow::Error::from);
let queries =
options.and_then(|options| interaction::checkbox::queries(&prepared, &options));
let queries = serde_json::from_str::<Options>(&options)
.map_err(anyhow::Error::from)
.and_then(|options| interaction::checkbox::queries(&prepared, &options));
snapshot.insert("checkbox_queries".into(), record(queries));
}
}
+112 -52
View File
@@ -165,6 +165,17 @@
"accept-language: en-US,en;q=0.9",
"priority: u=0, i",
"accept-encoding: gzip, deflate, br, zstd"
],
"websocket": [
"upgrade: websocket",
"connection: Upgrade",
"origin",
"pragma: no-cache",
"cache-control: no-cache",
"sec-websocket-version: 13",
"user-agent",
"accept-language: en-US,en;q=0.9",
"accept-encoding: gzip, deflate, br, zstd"
]
}
}
@@ -191,8 +202,8 @@
"intervals": {
"initialise": 7,
"handoff": 8,
"collect": 20,
"send": 123
"collect": 19,
"send": 121
},
"orchestrator": {
"intervals": {
@@ -359,29 +370,29 @@
},
"snapshot": {
"connection": {
"data_channel": true,
"sdp": "v=0\r\no=- 4614139716320554648 2 IN IP4 127.0.0.1\r\ns=-\r\nt=0 0\r\na=group:BUNDLE 0\r\na=extmap-allow-mixed\r\na=msid-semantic: WMS\r\nm=application 9 UDP/DTLS/SCTP webrtc-datachannel\r\nc=IN IP4 0.0.0.0\r\na=ice-ufrag:6d+C\r\na=ice-pwd:v8cXDj/2Pl1T+N6K5egLTMMb\r\na=ice-options:trickle\r\na=fingerprint:sha-256 D9:43:8F:C3:9D:49:DA:18:B4:43:64:AF:88:16:1A:D5:95:C5:65:AE:39:6E:4E:78:DC:C8:F3:EF:69:75:2E:8A\r\na=setup:actpass\r\na=mid:0\r\na=sctp-port:5000\r\na=max-message-size:262144\r\n",
"pub_candidates": [
{
"candidate": "candidate:2090291584 1 udp 2113939711 a620b7e1-44bb-4d4b-9634-28efa841a789.local 50405 typ host generation 0 ufrag 6d+C network-cost 999",
"observed_ms": 1792606280929
"candidate": "candidate:3460880736 1 udp 2113939711 f1bed2f8-f860-457f-b026-2d23d9140c03.local 59340 typ host generation 0 ufrag mtbG network-cost 999",
"observed_ms": 1792876992039
},
{
"candidate": "candidate:1236921985 1 udp 2113937151 624f554e-e7a7-4613-8022-f2f6d9f1a264.local 57490 typ host generation 0 ufrag 6d+C network-cost 999",
"observed_ms": 1792606280929
"candidate": "candidate:3747697418 1 udp 2113937151 f9501b39-1d57-4eb6-8029-16167a5a330b.local 51498 typ host generation 0 ufrag mtbG network-cost 999",
"observed_ms": 1792876992039
},
{
"candidate": "candidate:913227231 1 udp 1677729535 192.0.2.1 62924 typ srflx raddr 0.0.0.0 rport 0 generation 0 ufrag 6d+C network-cost 999",
"observed_ms": 1792606280945
"candidate": "candidate:1648342598 1 udp 1677729535 192.0.2.1 64597 typ srflx raddr 0.0.0.0 rport 0 generation 0 ufrag mtbG network-cost 999",
"observed_ms": 1792876992052
},
{
"candidate": "candidate:1148993836 1 udp 1677732095 2001:db8::1 50405 typ srflx raddr :: rport 0 generation 0 ufrag 6d+C network-cost 999",
"observed_ms": 1792606280946
"candidate": "candidate:2007285888 1 udp 1677732095 2001:db8::1 59340 typ srflx raddr :: rport 0 generation 0 ufrag mtbG network-cost 999",
"observed_ms": 1792876992056
}
]
],
"data_channel": true,
"sdp": "v=0\r\no=- 2400467206764510475 2 IN IP4 127.0.0.1\r\ns=-\r\nt=0 0\r\na=group:BUNDLE 0\r\na=extmap-allow-mixed\r\na=msid-semantic: WMS\r\nm=application 9 UDP/DTLS/SCTP webrtc-datachannel\r\nc=IN IP4 0.0.0.0\r\na=ice-ufrag:mtbG\r\na=ice-pwd:0Dc00kOlIMYBy8fnUlejV6Qu\r\na=ice-options:trickle\r\na=fingerprint:sha-256 DD:42:3A:63:B0:F3:DD:05:09:2E:04:DB:DC:08:0F:95:85:98:BB:9E:04:10:8B:72:64:14:09:0E:31:EA:13:69\r\na=setup:actpass\r\na=mid:0\r\na=sctp-port:5000\r\na=max-message-size:262144\r\n"
},
"started_ms": 1792606282000,
"finished_ms": 1792606282002,
"started_ms": 1792876992546,
"finished_ms": 1792876992554,
"ice_state": "complete"
}
},
@@ -399,67 +410,93 @@
},
"benchmark_worker": {
"compile_ms": [
11.5,
2.04,
1.16,
2.0
11.499999999999993,
2.039999999999992,
1.1599999999999966,
2.0,
1.6599999999999682,
2.5
],
"kernel_ms_per_million": [
[
1.003,
1.035,
1.291,
1.214,
0.93,
0.972,
0.962,
0.971,
0.944,
1.035,
0.972,
0.946,
1.291,
0.962,
0.941,
0.971
1.214,
0.971,
0.971,
1.003,
0.935,
0.964,
1.002,
0.953,
0.968
],
[
1.055,
1.027,
1.061,
1.007,
0.932,
0.933,
0.942,
1.007,
0.946,
1.027,
0.933,
0.944,
1.061,
0.942,
0.947,
1.007
1.007,
1.007,
1.007,
1.399,
0.926,
0.941,
1.379,
0.936,
0.946
],
[
1.222,
0.801,
0.665,
0.645,
0.617,
0.621,
0.628,
0.645,
0.635,
0.801,
0.621,
0.626,
0.665,
0.628,
0.631,
0.645
0.645,
0.645,
0.645,
0.746,
0.62,
0.63,
0.656,
0.629,
0.641
],
[
5.798,
5.75,
5.978,
5.831,
5.567,
5.609,
5.75,
5.574,
5.692,
5.978,
5.707,
5.707,
5.831,
5.609,
5.692,
5.707,
5.831
5.831,
5.831,
5.931,
5.554,
5.673,
5.869,
5.693,
5.791
]
]
}
@@ -472,22 +509,45 @@
"online": true
},
"durations": {
"audio": 24,
"behavior": 4,
"clock_resolution": 6,
"computed_style_hash": 12,
"console": 26,
"date_parsing_offsets": 1,
"document_structure": 0,
"document_summary": 1,
"dom_mutation": 2,
"emoji_color": 3,
"empty": 0,
"environment": 5,
"environment_audit": 17,
"error_message_length": 1,
"font_enumeration": 6,
"graphics": 48,
"high_entropy_user_agent": 1,
"image": 14,
"intl": 3,
"isolation": 16,
"keyboard_layout": 0,
"math": 6,
"media": 5,
"native_inspection": 65,
"network_information": 0,
"parent_info": 0,
"performance_entries": 0,
"performance_entries": 1,
"private_token": 1,
"rects": 5,
"stack": 1,
"storage": 5,
"stylesheets": 3,
"summarizer_availability": 0,
"svg_geometry": 18,
"worker_fetch": 1,
"worker_navigator": 7,
"stack": 1
"worker_navigator": 7
},
"startup_ms": 105,
"pending_ms": 42
"startup_ms": 119,
"pending_ms": 227
},
"answers": "safari-26-ios/answers.json",
"challenge_page_answers": "safari-26-ios/challenge-page-answers.json"
File diff suppressed because it is too large Load Diff
File diff suppressed because it is too large Load Diff
+5
View File
@@ -3,15 +3,20 @@
//!
//! Each challenge POST encrypts a seed under an RSA modulus in the iframe script. The proxy swaps
//! in its own modulus and rewraps the browser's seed under the original before forwarding it.
//! [`Recording`] reads capture logs; [`fill_profile`] uses them to fill a device profile.
mod ca;
mod head;
mod profile;
mod proxy;
mod recorded;
mod rsa;
mod sessions;
mod traffic;
mod upstream;
pub use ca::CertificateAuthority;
pub use profile::fill as fill_profile;
pub use proxy::{CA_HOST, CA_PATH, CHALLENGE_HOST, CaptureProxy, Config};
pub use recorded::{CapturedSession, Recording};
pub use upstream::{Credentials, UpstreamProxy};
+418
View File
@@ -0,0 +1,418 @@
//! Fills device profiles from proxy recordings.
//!
//! `traffic.json` provides the user agent, client hints, and header order for each request type.
//! Session payloads provide probe durations, startup and pending times, benchmark speeds, media
//! observations, first-payload intervals, and loader timestamps. Most values use the median across
//! sessions. Loader timestamps come from a single session chosen by median send time, so they
//! remain consistent.
//!
//! Values that captures cannot provide stay unchanged: engine, TLS and HTTP/2 settings, request
//! priorities, page layout, interaction, resource timing phases, orchestrator pacing, and navigator
//! properties. `build_profile` writes the stored answers.
mod headers;
use std::collections::BTreeMap;
use std::net::{IpAddr, Ipv4Addr, Ipv6Addr};
use anyhow::{Context, Result, bail};
use serde::Serialize;
use serde_json::Value;
use url::Url;
use self::headers::Headers;
use super::CHALLENGE_HOST;
use super::recorded::{CapturedSession, Recording};
use crate::challenge::merge::OptionSource;
use crate::challenge::payload::Field;
use crate::challenge::program::PreparedSession;
use crate::challenge::state::{Intervals, ScriptState};
use crate::embedding_page::extra_params::{ElapsedTimes, Timeline};
use crate::http::{HeaderOrder, RequestKind};
use crate::js::{self, JsObject, JsValue, Payload};
use crate::script::Source;
use crate::stage2::analysis;
use crate::stage2::benchmark::WorkerCosts;
use crate::stage2::probes::media::Measurement;
use crate::stage2::registry::{Kind, Operation};
/// Updates measured profile values from `recordings`. Returns notes about the sources used and data
/// skipped. Other profile values stay unchanged.
pub fn fill(profile: &mut Value, recordings: &[Recording]) -> Result<Vec<String>> {
let mut notes = Vec::new();
for recording in recordings {
let dir = recording.dir.display();
for skipped in &recording.skipped {
notes.push(format!("{dir}: left out {skipped}"));
}
}
let requests = recordings
.iter()
.flat_map(|recording| &recording.traffic.requests);
fill_headers(profile, Headers::observe(requests), &mut notes)?;
let script_fetch = section(profile, "/timeline/script_fetch")?
.as_f64()
.context("the profile's timeline has no script_fetch")?;
let mut reported = Reported {
script_fetch,
..Reported::default()
};
for recording in recordings {
for (name, session) in &recording.sessions {
let path = recording.dir.join(name);
for problem in reported.read(recording, session) {
notes.push(format!("{}: {problem:#}", path.display()));
}
}
}
reported.fill(profile, &mut notes)?;
Ok(notes)
}
/// Updates header orders and browser identity headers for the request types found in the traffic.
fn fill_headers(profile: &mut Value, headers: Headers, notes: &mut Vec<String>) -> Result<()> {
let own = section(profile, "/transport/headers")?
.as_object_mut()
.context("the profile's transport headers are not an object")?;
let sent = headers.identity.len();
for (name, value) in headers.identity {
// Preserve the spelling of headers already in the profile.
let existing = own
.keys()
.find(|key| key.eq_ignore_ascii_case(&name))
.cloned();
own.insert(existing.unwrap_or(name), Value::String(value));
}
notes.push(format!(
"transport.headers: the user agent and client hints, {sent} headers from traffic.json"
));
let orders = section(profile, "/transport/requests/headers")?
.as_object_mut()
.context("the profile's header orders are not an object")?;
let observed = &headers.orders;
for (kind, order) in observed {
orders.insert(kind.to_string(), serde_json::to_value(order)?);
}
// Use one header order if the browser sends the same order before and after a script redirect.
if let Some(redirect) = observed.get(&RequestKind::ScriptRedirect)
&& observed.get(&RequestKind::Script) == Some(redirect)
{
orders.remove(&RequestKind::ScriptRedirect.to_string());
}
serde_json::from_value::<HeaderOrder>(Value::Object(orders.clone()))
.context("the derived header orders are not valid")?;
let kept: Vec<&str> = orders
.keys()
.filter(|kind| !observed.keys().any(|seen| seen.to_string() == **kind))
.map(String::as_str)
.collect();
let kept = if kept.is_empty() {
"none".to_owned()
} else {
kept.join(", ")
};
notes.push(format!(
"transport.requests.headers: {} kinds from traffic.json; kept the profile's {kept}",
observed.len(),
));
Ok(())
}
/// Measurements collected from session payloads for use in a profile.
#[derive(Default)]
struct Reported {
/// Loader fetch time from the profile; payloads do not report it.
script_fetch: f64,
/// Probe durations by family.
durations: BTreeMap<&'static str, Vec<i64>>,
startup_ms: Vec<i64>,
pending_ms: Vec<i64>,
benchmark: Vec<WorkerCosts>,
/// The first session's media observations.
media: Option<Measurement>,
intervals: Vec<Intervals>,
/// Loader timestamps from ordinary sites. Challenge pages load the loader late, so the solver
/// uses the timestamps from ordinary sites.
timelines: Vec<Timeline>,
}
impl Reported {
/// Collects measurements from `session` and returns notes about data it could not read.
fn read(&mut self, recording: &Recording, session: &CapturedSession) -> Vec<anyhow::Error> {
let source = match session.source() {
Ok(source) => source,
Err(error) => return vec![error.context("deobfuscating the iframe script")],
};
let mut problems = Vec::new();
let first = session.first_payload();
if let Err(error) = first.and_then(|first| self.read_first(&source, first, &mut problems)) {
problems.push(error.context("reading the first payload"));
}
if let Err(error) = self.read_records(recording, session, &source, &mut problems) {
problems.push(error.context("reading the probe records"));
}
problems
}
/// Collects first-payload intervals and the loader timestamps passed from the site to the
/// iframe.
fn read_first(
&mut self,
source: &Source,
payload: &Payload,
problems: &mut Vec<anyhow::Error>,
) -> Result<()> {
// Extraction only needs an iframe URL with the same origin as the POSTs.
let iframe = Url::parse(&format!("https://{CHALLENGE_HOST}/"))?;
let prepared = PreparedSession::try_new(source, &iframe)?;
let mapping = prepared.mapping()?;
let state = prepared.state()?;
let fields = &prepared.program().payload_fields;
match state.intervals(fields, mapping.merged(), payload) {
Ok(intervals) => self.intervals.push(intervals),
Err(error) => problems.push(error.context("reading the first payload")),
}
let mut message = JsObject::new();
let mut implicit_render = None;
for entry in &mapping.0 {
let Some(value) = reported(payload, fields, &state, &entry.option) else {
continue;
};
match &entry.source {
OptionSource::Message(key) => {
message.insert(key.clone(), value.clone());
}
// The loader samples its own stack as it renders the page's widgets.
OptionSource::Samples(_) => {
let sample = value.as_array().and_then(|samples| samples.first());
implicit_render = sample.and_then(|sample| sample.get("t")?.as_i64());
}
_ => {}
}
}
// The orchestrator passes its page data only to widgets on challenge pages.
if message.get("chlPageData").is_some_and(js::truthy) {
return Ok(());
}
let times: ElapsedTimes = js::from_value(JsValue::Object(message))
.context("the first payload lacks the loader's elapsed times")?;
let implicit_render =
implicit_render.context("the first payload lacks the loader's stack sample")?;
let timeline = Timeline::from_times(&times, implicit_render, self.script_fetch);
self.timelines.push(timeline);
Ok(())
}
/// Collects probe durations, benchmark speeds, the first media connection, and probe times
/// relative to the POSTs.
fn read_records(
&mut self,
recording: &Recording,
session: &CapturedSession,
source: &Source,
problems: &mut Vec<anyhow::Error>,
) -> Result<()> {
let program = session.program()?;
let payload = session.probe_payload()?;
let analysis = analysis::analyze(source, &program)?;
let plan = analysis.plan();
let envelope = &plan.record_fields;
let completion = &envelope.completion;
let (mut first_started, mut last_finished) = (i64::MAX, i64::MIN);
for probe in plan.probes() {
let record = payload
.get(&probe.index.to_string())
.and_then(JsValue::as_object)
.with_context(|| format!("the payload has no record for probe {}", probe.index))?;
let mark = |name: &str| record.get(name).and_then(JsValue::as_i64);
let (Some(started), Some(finished)) =
(mark(&completion.started), mark(&completion.finished))
else {
bail!("probe {}'s record has no clock marks", probe.index);
};
first_started = first_started.min(started);
last_finished = last_finished.max(finished);
let Some(operation) = &probe.operation else {
continue;
};
match operation {
Operation::Benchmark { fields } => match fields.costs(record) {
Ok(costs) => self.benchmark.push(costs),
Err(error) => problems.push(error.context("reading the benchmark")),
},
Operation::Media { fields } if self.media.is_none() => {
let names = envelope.names();
let mut observed = record.clone();
observed.retain(|name, _| !names.contains(&name.as_str()));
plan.vocabulary()
.rewrite_to_reference(probe.position(), &mut observed);
match fields.observed(&observed, started) {
Ok(media) => self.media = Some(without_addresses(media)),
Err(error) => problems.push(error.context("reading the media probe")),
}
}
_ => {}
}
// The solver measures its own benchmark's duration.
let family = operation.family();
if family != Kind::Benchmark
&& let Some(duration) = mark(&completion.duration)
{
self.durations
.entry(family.as_str())
.or_default()
.push(duration);
}
}
let posts = recording.post_times(session)?;
self.startup_ms
.push(first_started - posts.first_answered_ms);
// The schedule reserves a millisecond after each probe.
self.pending_ms
.push(posts.second_sent_ms - last_finished - 1);
Ok(())
}
fn fill(mut self, profile: &mut Value, notes: &mut Vec<String>) -> Result<()> {
let mut filled = |pointer: &str, value: Option<Value>, source: &str| -> Result<()> {
let name = pointer.trim_start_matches('/').replace('/', ".");
match value {
Some(value) => {
*section(profile, pointer)? = value;
notes.push(format!("{name}: {source}"));
}
None => notes.push(format!(
"{name}: kept the profile's; no session reported it"
)),
}
Ok(())
};
let sessions = |count: usize| format!("medians of {count} sessions");
let durations: BTreeMap<&str, u32> = self
.durations
.into_iter()
.filter_map(|(family, durations)| Some((family, unsigned(median(durations)?))))
.collect();
let count = self.startup_ms.len();
let durations = (!durations.is_empty()).then_some(durations);
filled("/second/durations", json(durations)?, &sessions(count))?;
for (pointer, values) in [
("/second/startup_ms", self.startup_ms),
("/second/pending_ms", self.pending_ms),
] {
filled(
pointer,
json(median(values).map(unsigned))?,
&sessions(count),
)?;
}
let benchmarks = self.benchmark.len();
let benchmark = self.benchmark.into_iter().reduce(|mut all, costs| {
all.compile_ms.extend(costs.compile_ms);
for (speeds, more) in all
.kernel_ms_per_million
.iter_mut()
.zip(costs.kernel_ms_per_million)
{
speeds.extend(more);
}
all
});
let source = format!("every round of {benchmarks} sessions");
filled("/second/facts/benchmark_worker", json(benchmark)?, &source)?;
let source = "the first session's, its addresses replaced";
filled("/second/facts/media", json(self.media)?, source)?;
let intervals = median_intervals(&self.intervals);
filled(
"/intervals",
json(intervals)?,
&sessions(self.intervals.len()),
)?;
// Use one session to keep timestamps consistent. Choose the session with the median loader
// send time.
let count = self.timelines.len();
self.timelines.sort_by_key(|timeline| timeline.sent);
let source = format!(
"the median of {count} site widget sessions by send time; script_fetch kept, as no \
payload reports it"
);
filled("/timeline", json(self.timelines.get(count / 2))?, &source)
}
}
/// Returns the median of each interval across sessions.
fn median_intervals(sessions: &[Intervals]) -> Option<Intervals> {
let column = |interval: fn(&Intervals) -> i64| median(sessions.iter().map(interval).collect());
Some(Intervals {
initialise: column(|intervals| intervals.initialise)?,
handoff: column(|intervals| intervals.handoff)?,
collect: column(|intervals| intervals.collect)?,
send: column(|intervals| intervals.send)?,
})
}
/// Reads the value reported for `option`, either from its template field or directly from a
/// forwarded option.
fn reported<'payload>(
payload: &'payload Payload,
fields: &[Field],
state: &ScriptState,
option: &str,
) -> Option<&'payload JsValue> {
match fields
.iter()
.find(|field| field.option(state) == Some(option))
{
Some(field) => payload.get(&field.name),
None if state.forwarded.iter().any(|key| key == option) => payload.get(option),
None => None,
}
}
/// Replaces recorded IP addresses with documentation addresses so shared profiles do not reveal the
/// capture network. These addresses are never sent: [`crate::stage2::probes::ice::refresh`]
/// generates new names for host candidates.
fn without_addresses(mut media: Measurement) -> Measurement {
if let Measurement::Observed { snapshot, .. } = &mut media {
for candidate in &mut snapshot.connection.published_candidates {
let Some(line) = candidate.candidate.as_str() else {
continue;
};
let tokens = line.split(' ').map(|token| match token.parse::<IpAddr>() {
Ok(address) if address.is_unspecified() => token.to_owned(),
Ok(IpAddr::V4(_)) => Ipv4Addr::new(192, 0, 2, 1).to_string(),
Ok(IpAddr::V6(_)) => Ipv6Addr::new(0x2001, 0xdb8, 0, 0, 0, 0, 0, 1).to_string(),
Err(_) => token.to_owned(),
});
candidate.candidate = JsValue::String(tokens.collect::<Vec<String>>().join(" "));
}
}
media
}
/// Returns the profile value at the JSON `pointer`. Panics if the path does not exist.
fn section<'profile>(profile: &'profile mut Value, pointer: &str) -> Result<&'profile mut Value> {
profile
.pointer_mut(pointer)
.with_context(|| format!("the profile has no {pointer}"))
}
fn json(value: Option<impl Serialize>) -> Result<Option<Value>> {
Ok(value.map(serde_json::to_value).transpose()?)
}
/// Returns the median, choosing the upper middle value for an even count.
fn median(mut values: Vec<i64>) -> Option<i64> {
values.sort_unstable();
values.get(values.len() / 2).copied()
}
/// Converts a duration to the profile format. Negative durations caused by clock differences become
/// zero.
fn unsigned(duration: i64) -> u32 {
u32::try_from(duration.max(0)).unwrap_or(u32::MAX)
}
+246
View File
@@ -0,0 +1,246 @@
//! Derives header orders and the browser's identity headers from the requests in `traffic.json`.
use std::cmp::Reverse;
use std::collections::BTreeMap;
use std::hash::Hash;
use indexmap::IndexMap;
use url::Url;
use crate::capture::CHALLENGE_HOST;
use crate::capture::traffic::Request;
use crate::http::RequestKind;
/// Client hints that can appear on any request. Other hints identify navigation retries made after
/// the server requested high-entropy hints.
const LOW_ENTROPY_HINTS: [&str; 3] = ["sec-ch-ua", "sec-ch-ua-mobile", "sec-ch-ua-platform"];
/// Header orders and browser identity headers collected from requests.
pub(super) struct Headers {
/// Header order for each request type. Prefer orders with the most supplied headers, then the
/// most common order. The solver omits headers it cannot supply, such as a referrer withheld by
/// page policy. Orders include high-entropy hints requested before the challenge. For request
/// types shared by ordinary sites and challenge pages, such as icons, only challenge-page
/// requests matter.
pub(super) orders: BTreeMap<RequestKind, Vec<String>>,
/// Most common value for each user agent or client hint header, in the order the headers first
/// appeared.
pub(super) identity: IndexMap<String, String>,
}
impl Headers {
pub(super) fn observe<'r>(requests: impl IntoIterator<Item = &'r Request>) -> Self {
let mut orders: BTreeMap<RequestKind, Tally<Vec<String>>> = BTreeMap::new();
let mut identity: IndexMap<String, Tally<String>> = IndexMap::new();
for request in requests {
let Some(kind) = kind(request) else {
continue;
};
let sent = request.headers.iter().filter(|(name, _)| name != "cookie");
let order: Vec<String> = sent.map(|(name, value)| kind.entry(name, value)).collect();
orders.entry(kind).or_default().add(order);
for (name, value) in &request.headers {
if name == "user-agent" || name.starts_with("sec-ch-") {
identity.entry(name.clone()).or_default().add(value.clone());
}
}
}
// Fixed headers use `name: value`; headers filled at request time use bare names.
let supplied =
|order: &Vec<String>| order.iter().filter(|entry| !entry.contains(':')).count();
Self {
orders: orders
.into_iter()
.map(|(kind, tally)| (kind, tally.best(supplied)))
.collect(),
identity: identity
.into_iter()
.map(|(name, tally)| (name, tally.best(|_| ())))
.collect(),
}
}
}
/// Classifies requests the solver can send. Excludes cache revalidation requests because each solve
/// starts with an empty cache.
fn kind(request: &Request) -> Option<RequestKind> {
if request.header("if-none-match").is_some() || request.header("if-modified-since").is_some() {
return None;
}
let url = Url::parse(&request.url).ok()?;
let challenge = url.host_str() == Some(CHALLENGE_HOST);
let post = request.method == "POST";
let mode = request.header("sec-fetch-mode");
// Challenge pages load the orchestrator and post to it on their own origin.
let platform = |route: &str| {
let path = url.path();
path.starts_with("/cdn-cgi/challenge-platform/") && path.contains(route)
};
Some(match (request.header("sec-fetch-dest")?, challenge, post) {
("document", _, true) => RequestKind::Form,
// Match navigation from a typed address. Reloads and links use different headers.
("document", _, false) if request.header("sec-fetch-site") == Some("none") => {
let hints = request.headers.iter().any(|(name, _)| {
name.starts_with("sec-ch-") && !LOW_ENTROPY_HINTS.contains(&name.as_str())
});
if hints {
RequestKind::NavigationWithHints
} else {
RequestKind::Navigation
}
}
("iframe", true, false) => RequestKind::Iframe,
("script", true, false) if mode == Some("cors") => RequestKind::CorsScript,
// The loader URL redirects to a URL for a specific build.
("script", true, false) if url.path() == "/turnstile/v0/api.js" => RequestKind::Script,
("script", true, false) => RequestKind::ScriptRedirect,
("script", false, false) if platform("/orchestrate/") => RequestKind::Orchestrator,
("image", false, false) => RequestKind::PageImage,
("image", true, false) => RequestKind::Image,
("empty", false, true) if platform("/fo/") => RequestKind::OrchestratorPost,
("empty", true, true) => RequestKind::ChallengePost,
// The private token probe fetches with `{cache: "no-cache"}`.
("empty", true, false) if url.path().contains("/pat/") => RequestKind::WorkerFetch,
("empty", true, false) => RequestKind::WorkerFetchWithoutCredentials,
_ => return None,
})
}
/// Counts occurrences of each value while preserving insertion order.
#[derive(Default)]
struct Tally<T>(IndexMap<T, usize>);
impl<T: Hash + Eq> Tally<T> {
fn add(&mut self, value: T) {
*self.0.entry(value).or_default() += 1;
}
/// Returns the highest-ranked value. Breaks ties by frequency, then by insertion order.
fn best<R: Ord>(self, rank: impl Fn(&T) -> R) -> T {
// For equal keys, `min_by_key` returns the first entry; `max_by_key` returns the last.
let counts = self.0.into_iter();
let best = counts.min_by_key(|(value, count)| Reverse((rank(value), *count)));
best.expect("a tally holds what was added to it").0
}
}
#[cfg(test)]
mod tests {
use super::*;
fn request(method: &str, url: &str, headers: &[(&str, &str)]) -> Request {
let headers = headers
.iter()
.map(|&(name, value)| (name.into(), value.into()));
Request::received(method, url, headers.collect())
}
/// Select the most common order among those with the most supplied headers. Break ties by first
/// occurrence. Ignore cookies and cache revalidations.
#[test]
fn orders_each_kind_of_request_as_most_often_sent() {
let challenge = "https://challenges.cloudflare.com";
let script = [
("sec-fetch-dest", "script"),
("sec-fetch-mode", "no-cors"),
("user-agent", "Mozilla/5.0"),
("referer", "https://example.com/"),
];
let image = |storage: &str, referred: bool, revalidated: bool| {
let mut headers = vec![
("sec-fetch-dest", "image"),
("cookie", "a=b"),
("sec-fetch-storage-access", storage),
];
if referred {
headers.push(("referer", "https://challenges.cloudflare.com/"));
}
if revalidated {
headers.push(("if-none-match", "\"1\""));
}
request("GET", &format!("{challenge}/ci/1"), &headers)
};
let navigation = |hint: (&str, &str)| {
let headers = [
hint,
("sec-fetch-site", "none"),
("sec-fetch-dest", "document"),
];
request("GET", "https://example.com/", &headers)
};
let requests = [
// A site's own script should not be classified as the orchestrator.
request(
"GET",
"https://example.com/app.js",
&[("sec-fetch-dest", "script")],
),
navigation(("sec-ch-ua", "\"Chromium\"")),
navigation(("sec-ch-ua-arch", "\"x86\"")),
request("GET", &format!("{challenge}/turnstile/v0/api.js"), &script),
request(
"GET",
&format!("{challenge}/turnstile/v0/b/1/api.js"),
&script,
),
image("none", false, false),
image("none", false, false),
image("none", true, true),
image("none", true, true),
image("active", true, false),
];
let headers = Headers::observe(&requests);
let orders: Vec<(RequestKind, Vec<String>)> = headers.orders.into_iter().collect();
let entries = |entries: &[&str]| entries.iter().map(|&entry| entry.to_owned()).collect();
let script_order: Vec<String> = entries(&[
"sec-fetch-dest: script",
"sec-fetch-mode: no-cors",
"user-agent",
"referer",
]);
assert_eq!(
orders,
[
(
RequestKind::Navigation,
entries(&[
"sec-ch-ua",
"sec-fetch-site: none",
"sec-fetch-dest: document"
])
),
(
RequestKind::NavigationWithHints,
entries(&[
"sec-ch-ua-arch",
"sec-fetch-site: none",
"sec-fetch-dest: document"
])
),
(RequestKind::Script, script_order.clone()),
(RequestKind::ScriptRedirect, script_order),
(
RequestKind::Image,
entries(&[
"sec-fetch-dest: image",
"sec-fetch-storage-access: active",
"referer"
])
),
]
);
let identity: Vec<(&str, &str)> = headers
.identity
.iter()
.map(|(name, value)| (name.as_str(), value.as_str()))
.collect();
assert_eq!(
identity,
[
("sec-ch-ua", "\"Chromium\""),
("sec-ch-ua-arch", "\"x86\""),
("user-agent", "Mozilla/5.0")
]
);
}
}
+10 -5
View File
@@ -33,8 +33,9 @@ use super::rsa::{self, ProxyKey};
use super::sessions::{self, Iframe, Post, Sessions};
use super::traffic::{Connection, Traffic};
use super::upstream::{self, Stream, UpstreamProxy};
use crate::challenge;
use crate::http::{self, BrowserClient, Proxied};
use crate::js::ast;
use crate::{challenge, deobfuscate};
const ESTABLISHED: &[u8] = b"HTTP/1.1 200 Connection Established\r\n\r\n";
@@ -423,10 +424,14 @@ impl CaptureProxy {
fn rewrite_iframe(&self, url: &str, upstream: &Proxied) -> Option<Vec<u8>> {
let encoding = header_value(&upstream.headers, header::CONTENT_ENCODING);
let html = String::from_utf8(http::decode_body(&upstream.body, &encoding).ok()?).ok()?;
let (rewritten, real_modulus) =
rsa::swap_modulus(&html, &self.sessions.proxy_key.modulus).ok()?;
let alphabet = challenge::inline_javascript(&html)
.and_then(|javascript| sessions::scan_alphabet(&javascript))
let scanned = challenge::inline_javascript(&html).and_then(|javascript| {
let parsed = ast::parse_javascript("iframe.js", &javascript)?;
let strings = deobfuscate::inline_strings(&parsed.script);
let alphabet = sessions::scan_alphabet(&parsed.script, &strings)?;
let swapped = rsa::swap_modulus(&html, &strings, &self.sessions.proxy_key.modulus)?;
anyhow::Ok((alphabet, swapped))
});
let (alphabet, (rewritten, real_modulus)) = scanned
.inspect_err(|error| eprintln!("{url}: forwarding the original iframe: {error:#}"))
.ok()?;
let encoded = http::encode_body(rewritten.as_bytes(), &encoding).ok()?;
+159
View File
@@ -0,0 +1,159 @@
//! Reads session data from `capture.json` and request traffic from `traffic.json`.
use std::collections::BTreeMap;
use std::fs;
use std::path::{Path, PathBuf};
use anyhow::{Context, Result};
use base64::Engine as _;
use base64::engine::general_purpose::STANDARD;
use serde::Deserialize;
use serde::de::DeserializeOwned;
use url::Url;
use super::traffic::{Request, Traffic};
use crate::js::Payload;
use crate::script::Source;
use crate::{challenge, deobfuscate};
/// Session data from `capture.json`: the iframe page, POSTs, and decoded payloads.
/// `scripts/cdp_capture.mjs` writes the same format without `cfChl`.
#[derive(Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct CapturedSession {
iframe_html: String,
posts: Vec<CapturedPost>,
payloads: Vec<CapturedPayload>,
}
#[derive(Deserialize)]
#[serde(rename_all = "camelCase")]
struct CapturedPost {
url: String,
cf_chl: Option<String>,
response_body: String,
}
#[derive(Deserialize)]
struct CapturedPayload {
payload: Payload,
}
impl CapturedSession {
pub fn read(path: &Path) -> Result<Self> {
read_json(path)
}
/// Returns the deobfuscated inline script from the iframe.
pub fn source(&self) -> Result<Source> {
let javascript = challenge::inline_javascript(&self.iframe_html)?;
Source::try_new(&deobfuscate::deobfuscate(javascript)?.text)
}
/// Returns the probe program from the first POST response, unmasked using the ray ID in the
/// URL.
pub fn program(&self) -> Result<Vec<u8>> {
let post = self.posts.first().context("the capture has no POST")?;
let url = Url::parse(&post.url)?;
let encoded =
challenge::decode_response(post.response_body.as_bytes(), challenge::ray(&url)?)?;
Ok(STANDARD.decode(encoded)?)
}
/// Returns the payload built before probes run.
pub fn first_payload(&self) -> Result<&Payload> {
let first = self.payloads.first().map(|payload| &payload.payload);
first.context("the capture has no first payload")
}
/// Returns the second payload, which contains a numbered record for each probe.
pub fn probe_payload(&self) -> Result<&Payload> {
let mut payloads = self.payloads.iter().map(|payload| &payload.payload);
payloads
.find(|payload| payload.contains_key("1"))
.context("the capture has no payload with probe records")
}
}
/// Traffic and complete sessions from one proxy run directory.
pub struct Recording {
pub(super) dir: PathBuf,
pub(super) traffic: Traffic,
pub(super) sessions: BTreeMap<String, CapturedSession>,
/// Excluded sessions and the reasons they were skipped.
pub(super) skipped: Vec<String>,
}
/// Capture completeness status read from `session.json`.
#[derive(Deserialize)]
struct SessionLog {
complete: bool,
notes: Vec<String>,
}
impl Recording {
/// Reads the proxy output directory `dir`, skipping incomplete session captures.
pub fn read(dir: &Path) -> Result<Self> {
let traffic: Traffic = read_json(&dir.join("traffic.json"))?;
let sessions_dir = dir.join("sessions");
let mut names: Vec<String> = fs::read_dir(&sessions_dir)
.with_context(|| format!("reading {}", sessions_dir.display()))?
.map(|entry| Ok(entry?.file_name().to_string_lossy().into_owned()))
.collect::<Result<_>>()?;
names.sort();
let mut sessions = BTreeMap::new();
let mut skipped = Vec::new();
for name in names {
let session_dir = sessions_dir.join(&name);
let log: SessionLog = read_json(&session_dir.join("session.json"))?;
if !log.complete {
skipped.push(format!(
"{name}: incomplete capture: {}",
log.notes.join("; ")
));
continue;
}
let capture = CapturedSession::read(&session_dir.join("capture.json"))?;
sessions.insert(name, capture);
}
Ok(Self {
dir: dir.to_owned(),
traffic,
sessions,
skipped,
})
}
/// Groups POSTs by the `cf-chl` header shared by all POSTs in a session.
pub(super) fn post_times(&self, session: &CapturedSession) -> Result<PostTimes> {
let cf_chl = session
.posts
.first()
.and_then(|post| post.cf_chl.as_deref())
.context("the capture's first POST has no cf-chl header")?;
let posted = |request: &&Request| {
request.method == "POST" && request.header("cf-chl") == Some(cf_chl)
};
let mut posts = self.traffic.requests.iter().filter(posted);
let first = posts.next().context("traffic.json lacks the first POST")?;
let second = posts.next().context("traffic.json lacks the second POST")?;
Ok(PostTimes {
first_answered_ms: first
.answered_ms
.context("traffic.json records no response to the first POST")?,
second_sent_ms: second.received_ms,
})
}
}
/// Returns the times when the browser received the first POST response and sent the second POST, in
/// milliseconds since the Unix epoch.
pub(super) struct PostTimes {
pub(super) first_answered_ms: i64,
pub(super) second_sent_ms: i64,
}
fn read_json<T: DeserializeOwned>(path: &Path) -> Result<T> {
let text = fs::read(path).with_context(|| format!("reading {}", path.display()))?;
serde_json::from_slice(&text).with_context(|| format!("reading {}", path.display()))
}
+72 -21
View File
@@ -15,6 +15,7 @@ use serde_json::Value;
use crate::candidates;
use crate::challenge::codec::{self, Envelope, KEY_LENGTH, PUBLIC_EXPONENT, SEED_LENGTH};
use crate::deobfuscate::{self, Encoded};
/// Matches a `BigInt` call with a hexadecimal literal, capturing its quotes and digits. The
/// regex engine has no backreferences, so code checks that the quotes match.
@@ -90,28 +91,59 @@ impl ProxyKey {
}
}
/// Replaces the iframe's 128-byte `BigInt` hexadecimal literal (see `rsa_modulus` in
/// `crate::challenge::program`) with `proxy`, zero-padded to the same width so the HTML length
/// and stack-trace positions stay unchanged. Returns the rewritten HTML and the real modulus.
pub(super) fn swap_modulus(html: &str, proxy: &BigUint) -> Result<(String, BigUint)> {
let literals = MODULUS.captures_iter(html).filter_map(|captures| {
let (_, [open, digits, close]) = captures.extract();
let modulus = BigUint::parse_bytes(digits.as_bytes(), 16).expect("hex digits");
let wide = open == close && modulus.bits().div_ceil(8) == SEED_LENGTH as u64;
wide.then(|| (captures.get(2).expect("the digits group").range(), modulus))
/// Replaces the iframe's 128-byte RSA modulus with `proxy`. Returns the rewritten HTML and the
/// original modulus. See `rsa_modulus` in `crate::challenge::program`.
///
/// Pads the replacement with zeros to preserve HTML length and stack trace positions. The modulus
/// can be a hexadecimal `BigInt` literal or an inline encoded string from `strings`. Encoded
/// replacements use the original key.
pub(super) fn swap_modulus(
html: &str,
strings: &[Encoded],
proxy: &BigUint,
) -> Result<(String, BigUint)> {
let wide = |modulus: &BigUint| modulus.bits().div_ceil(8) == SEED_LENGTH as u64;
let literals: Vec<_> = MODULUS
.captures_iter(html)
.filter_map(|captures| {
let (_, [open, digits, close]) = captures.extract();
let modulus = BigUint::parse_bytes(digits.as_bytes(), 16).expect("hex digits");
(open == close && wide(&modulus))
.then(|| (captures.get(2).expect("the digits group").range(), modulus))
})
.collect();
if !literals.is_empty() {
let what = format!("{SEED_LENGTH}-byte BigInt literal in the iframe");
let (digits, real) = candidates::exactly_one(literals, &what)?;
let mut rewritten = html.to_owned();
rewritten.replace_range(digits.clone(), &padded(proxy, digits.len())?);
return Ok((rewritten, real));
}
let encoded = strings.iter().filter_map(|string| {
let digits = string.decoded.strip_prefix("0x")?;
let modulus = BigUint::parse_bytes(digits.as_bytes(), 16)?;
wide(&modulus).then_some((string, digits.len(), modulus))
});
let what = format!("{SEED_LENGTH}-byte BigInt literal in the iframe");
let (digits, real) = candidates::exactly_one(literals, &what)?;
let width = digits.len();
let proxy_digits = proxy.to_str_radix(16);
let what = format!("{SEED_LENGTH}-byte modulus in the iframe");
let (string, width, real) = candidates::exactly_one(encoded, &what)?;
let replacement =
deobfuscate::encode_string(&format!("0x{}", padded(proxy, width)?), string.key);
ensure!(
proxy_digits.len() <= width,
"the proxy modulus needs {} hex digits, wider than the session's {width}",
proxy_digits.len()
replacement.len() == string.encoded.len() && html.matches(&string.encoded).count() == 1,
"the encoded modulus cannot be replaced in place"
);
let mut rewritten = html.to_owned();
rewritten.replace_range(digits, &format!("{proxy_digits:0>width$}"));
Ok((rewritten, real))
Ok((html.replacen(&string.encoded, &replacement, 1), real))
}
/// Formats `proxy` as hexadecimal, padded with zeros to `width`.
fn padded(proxy: &BigUint, width: usize) -> Result<String> {
let digits = proxy.to_str_radix(16);
ensure!(
digits.len() <= width,
"the proxy modulus needs {} hex digits, wider than the session's {width}",
digits.len()
);
Ok(format!("{digits:0>width$}"))
}
/// Generates a random prime half the seed's width, with its top bit set.
@@ -241,12 +273,31 @@ mod tests {
let [proxy, real, _] = keys();
for quote in ['"', '`'] {
let html = page(quote, &real.modulus);
let (rewritten, found) = swap_modulus(&html, &proxy.modulus).unwrap();
let (rewritten, found) = swap_modulus(&html, &[], &proxy.modulus).unwrap();
assert_eq!(found, real.modulus);
assert_eq!(rewritten, page(quote, &proxy.modulus));
}
}
/// Find the modulus inside a decoder call when the build encodes strings.
#[test]
fn swap_reencodes_an_encoded_modulus() {
let [proxy, real, _] = keys();
let key = 59141;
let text = |modulus: &BigUint| format!("0x00{modulus:x}");
let encoded = deobfuscate::encode_string(&text(&real.modulus), key);
let html = format!("<script>n = BigInt(decode(`{encoded}`));</script>");
let strings = [Encoded {
encoded: encoded.clone(),
key,
decoded: text(&real.modulus),
}];
let (rewritten, found) = swap_modulus(&html, &strings, &proxy.modulus).unwrap();
assert_eq!(found, real.modulus);
let swapped = deobfuscate::encode_string(&text(&proxy.modulus), key);
assert_eq!(rewritten, html.replace(&encoded, &swapped));
}
#[test]
fn swap_fails_closed() {
let [proxy, real, _] = keys();
@@ -266,7 +317,7 @@ mod tests {
),
];
for (html, case) in cases {
assert!(swap_modulus(&html, &proxy.modulus).is_err(), "{case}");
assert!(swap_modulus(&html, &[], &proxy.modulus).is_err(), "{case}");
}
}
}
+9 -5
View File
@@ -16,12 +16,14 @@ use anyhow::{Context, Result};
use num_bigint::BigUint;
use serde::{Serialize, Serializer};
use serde_json::Value;
use swc_core::ecma::ast::Script;
use tokio::task::JoinSet;
use url::Url;
use super::rsa::{ProxyKey, Rewrapped};
use crate::challenge::codec::{Codec, KEY_LENGTH};
use crate::challenge::program::{self, PreparedSession};
use crate::deobfuscate::Encoded;
use crate::js::ast;
use crate::script::Source;
use crate::{challenge, deep_stack};
@@ -344,9 +346,11 @@ fn extract_codec(original: &str) -> Result<Codec> {
Ok(session.into_program().codec)
}
/// Scans the raw script with the solver's alphabet rule, without restricting it to the IIFE.
/// Background extraction checks the result before the session can become stored answers.
pub(super) fn scan_alphabet(javascript: &str) -> Result<String> {
let parsed = ast::parse_javascript("iframe.js", javascript)?;
program::base64_alphabet(&parsed.script)
/// Searches literals and inline decoded `strings` for a custom base64 alphabet using the solver's
/// alphabet rule. Searches the entire raw script, including outside the immediately invoked
/// function. Background extraction validates the result before saving session answers.
pub(super) fn scan_alphabet(script: &Script, strings: &[Encoded]) -> Result<String> {
let mut candidates = ast::string_literals(script);
candidates.extend(strings.iter().map(|string| string.decoded.clone()));
program::base64_alphabet(candidates)
}
+38 -11
View File
@@ -6,7 +6,7 @@ use std::fs;
use std::path::{Path, PathBuf};
use anyhow::{Context, Result};
use serde::Serialize;
use serde::{Deserialize, Serialize};
use super::sessions;
use crate::{http, performance_clock};
@@ -14,14 +14,15 @@ use crate::{http, performance_clock};
/// The directory beside `traffic.json` holding kept response bodies.
const BODIES: &str = "bodies";
#[derive(Default, Serialize)]
#[derive(Default, Deserialize, Serialize)]
pub(super) struct Traffic {
connections: Vec<Connection>,
requests: Vec<Request>,
/// The requests, in the order they arrived.
pub(super) requests: Vec<Request>,
}
/// One intercepted connection, as the browser opened it.
#[derive(Serialize)]
#[derive(Deserialize, Serialize)]
#[serde(rename_all = "camelCase")]
pub(super) struct Connection {
pub(super) host: String,
@@ -36,19 +37,19 @@ pub(super) struct Connection {
/// A request on an intercepted connection. hyper preserves header order, groups repeated values
/// at the first occurrence of their name, and lowercases names as HTTP/2 does.
#[derive(Serialize)]
#[derive(Deserialize, Serialize)]
#[serde(rename_all = "camelCase")]
struct Request {
pub(super) struct Request {
/// Index of this request's connection in `connections`.
connection: usize,
method: String,
url: String,
pub(super) method: String,
pub(super) url: String,
version: String,
headers: Vec<(String, String)>,
pub(super) headers: Vec<(String, String)>,
/// Time received, in milliseconds since the Unix epoch.
received_ms: i64,
pub(super) received_ms: i64,
/// Time the response was handed to the browser.
answered_ms: Option<i64>,
pub(super) answered_ms: Option<i64>,
/// The file holding the decoded response body, relative to `traffic.json`, if kept.
#[serde(skip_serializing_if = "Option::is_none")]
body_file: Option<String>,
@@ -114,6 +115,30 @@ impl Traffic {
}
}
impl Request {
/// Creates a request received at the current time on connection 0.
#[cfg(test)]
pub(super) fn received(method: &str, url: &str, headers: Vec<(String, String)>) -> Self {
Self {
connection: 0,
method: method.to_owned(),
url: url.to_owned(),
version: "HTTP/2.0".to_owned(),
headers,
received_ms: performance_clock::epoch_ms(),
answered_ms: None,
body_file: None,
body: Vec::new(),
}
}
/// Returns the value of header `name`. The name must be lowercase.
pub(super) fn header(&self, name: &str) -> Option<&str> {
let mut headers = self.headers.iter();
headers.find_map(|(header, value)| (header == name).then_some(value.as_str()))
}
}
#[cfg(test)]
mod tests {
use super::*;
@@ -133,6 +158,8 @@ mod tests {
let file = log["requests"][script]["bodyFile"].as_str().unwrap();
assert_eq!(file, "bodies/0001-orchestrator.js");
assert_eq!(fs::read(dir.join(file)).unwrap(), b"script");
let read: Traffic = serde_json::from_value(log).unwrap();
assert_eq!(read.requests[script].url, "https://example.com/v1");
fs::remove_dir_all(dir).unwrap();
}
}
+23 -10
View File
@@ -84,6 +84,28 @@ enum Shape {
}
impl Field {
/// Returns the option reported by this field, whether read directly or through a namespace
/// getter.
#[must_use]
pub(crate) fn option<'a>(&'a self, script: &'a ScriptState) -> Option<&'a str> {
expression::option_key(&self.expression).or_else(|| match self.global()? {
(name, Shape::Called) => script.getters.get(name).map(String::as_str),
_ => None,
})
}
/// Returns the two options subtracted by this field, if it reports a time difference.
#[must_use]
pub(crate) fn difference(&self) -> Option<Difference> {
match &self.expression {
Expr::Bin(binary) if binary.op == BinaryOp::Sub => Some(Difference {
later: expression::option_key(&binary.left)?.to_owned(),
earlier: expression::option_key(&binary.right)?.to_owned(),
}),
_ => None,
}
}
/// The namespace property this field reads, if any.
fn global(&self) -> Option<(&str, Shape)> {
fn global(expression: &Expr) -> Option<&str> {
@@ -104,16 +126,7 @@ impl Field {
/// Finds option pairs whose time difference appears in the payload.
#[must_use]
pub(crate) fn differences(fields: &[Field]) -> Vec<Difference> {
fields
.iter()
.filter_map(|field| match &field.expression {
Expr::Bin(binary) if binary.op == BinaryOp::Sub => Some(Difference {
later: expression::option_key(&binary.left)?.to_owned(),
earlier: expression::option_key(&binary.right)?.to_owned(),
}),
_ => None,
})
.collect()
fields.iter().filter_map(Field::difference).collect()
}
/// Evaluates fields against session options, omitting `undefined` values as `JSON.stringify`
+59 -30
View File
@@ -9,8 +9,8 @@ use base64::engine::general_purpose::STANDARD;
use num_bigint::BigUint;
use serde::Serialize;
use swc_core::ecma::ast::{
ArrowExpr, AssignExpr, AssignTarget, BlockStmt, CallExpr, Callee, Decl, Expr, Function, IfStmt,
ObjectLit, SimpleAssignTarget, Stmt,
ArrowExpr, AssignExpr, AssignTarget, BindingIdent, BlockStmt, CallExpr, Callee, ClassDecl,
Expr, FnDecl, Function, IfStmt, ObjectLit, Script, SimpleAssignTarget, Stmt, VarDeclarator,
};
use swc_core::ecma::visit::{Visit, VisitWith};
use url::Url;
@@ -227,8 +227,8 @@ struct Root {
impl Root {
fn read(root: &BlockStmt, definition: &Expr, parsed: &ParsedScript) -> Result<Self> {
Ok(Self {
key_transform: key_transform(root, definition)?,
alphabet: base64_alphabet(root)?,
key_transform: key_transform(&parsed.script, definition)?,
alphabet: base64_alphabet(ast::string_literals(root))?,
modulus: rsa_modulus(root)?,
bootstrap: bootstrap(root, parsed),
})
@@ -263,26 +263,44 @@ impl Visit for EncoderRoot<'_> {
}
}
/// Finds the encoder's one callee not declared by the IIFE, which the VM creates at runtime.
fn key_transform(root: &BlockStmt, definition: &Expr) -> Result<String> {
/// Finds the encoder callee created by the VM at runtime. It is the only callee without a binding
/// in the script; any remaining deobfuscation helpers have bindings.
fn key_transform(script: &Script, definition: &Expr) -> Result<String> {
let mut calls = Calls::default();
definition.visit_with(&mut calls);
let declared = |name: &str| {
root.stmts.iter().any(|statement| {
matches!(statement, Stmt::Decl(Decl::Fn(function)) if function.ident.sym == name)
})
};
let undeclared = calls
let mut bound = Bound::default();
script.visit_with(&mut bound);
let unbound = calls
.0
.iter()
.filter(|name| *name != "Number" && !declared(name));
candidates::exactly_one(undeclared, "VM-defined key transform").cloned()
.into_iter()
.filter(|name| name != "Number" && !bound.0.contains(name));
candidates::exactly_one(unbound, "VM-defined key transform")
}
/// Finds the session alphabet among the string literals in `node`, whether bound once or
/// repeated at each use.
pub(crate) fn base64_alphabet(node: &impl VisitWith<ast::StringLiterals>) -> Result<String> {
let alphabets = ast::string_literals(node).into_iter().filter(|candidate| {
/// Names declared or assigned anywhere in the script.
#[derive(Default)]
struct Bound(BTreeSet<String>);
impl Visit for Bound {
fn visit_binding_ident(&mut self, identifier: &BindingIdent) {
self.0.insert(identifier.sym.to_string());
}
fn visit_fn_decl(&mut self, declaration: &FnDecl) {
self.0.insert(declaration.ident.sym.to_string());
declaration.visit_children_with(self);
}
fn visit_class_decl(&mut self, declaration: &ClassDecl) {
self.0.insert(declaration.ident.sym.to_string());
declaration.visit_children_with(self);
}
}
/// Finds the custom base64 alphabet in `candidates`: a string with 64 distinct ASCII characters and
/// optional trailing padding.
pub(crate) fn base64_alphabet(candidates: impl IntoIterator<Item = String>) -> Result<String> {
let alphabets = candidates.into_iter().filter(|candidate| {
if !candidate.is_ascii() || !ALPHABET_LENGTH.contains(&candidate.len()) {
return false;
}
@@ -374,23 +392,34 @@ impl Visit for Definition<'_> {
fn visit_arrow_expr(&mut self, _: &ArrowExpr) {}
fn visit_assign_expr(&mut self, assignment: &AssignExpr) {
// A sequence evaluates to its final expression. Some sessions reset
// the seed immediately before yielding the encoder function.
let mut value = assignment.right.unwrap_parens();
while let Expr::Seq(sequence) = value {
let Some(last) = sequence.exprs.last() else {
return;
};
value = last.unwrap_parens();
}
if let AssignTarget::Simple(SimpleAssignTarget::Ident(target)) = &assignment.left
&& target.id.sym == *self.name
&& matches!(value, Expr::Fn(_) | Expr::Arrow(_))
&& let Some(function) = yielded_function(&assignment.right)
{
self.found = Some(value.clone());
self.found = Some(function.clone());
}
assignment.visit_children_with(self);
}
fn visit_var_declarator(&mut self, declarator: &VarDeclarator) {
if let Some(target) = declarator.name.as_ident()
&& target.id.sym == *self.name
&& let Some(function) = declarator.init.as_deref().and_then(yielded_function)
{
self.found = Some(function.clone());
}
declarator.visit_children_with(self);
}
}
/// Finds the function produced by `value`, including through sequence expressions. Some sessions
/// reset the seed just before returning the encoder function.
fn yielded_function(value: &Expr) -> Option<&Expr> {
let mut value = value.unwrap_parens();
while let Expr::Seq(sequence) = value {
value = sequence.exprs.last()?.unwrap_parens();
}
matches!(value, Expr::Fn(_) | Expr::Arrow(_)).then_some(value)
}
/// The names called directly, as `name(...)`.
+118 -19
View File
@@ -1,5 +1,6 @@
//! Recovers the format the iframe uses to summarize resource timings, then converts this
//! client's fetch measurements to that format.
//! client's fetch measurements to that format. Depending on the build, entries contain rounded-down
//! phase durations or the original timestamps.
use swc_core::ecma::ast::{AssignTarget, BinaryOp, BlockStmt, Expr, SimpleAssignTarget};
@@ -11,13 +12,30 @@ use crate::resource_timing::{LoadTiming, Phases, ResourceMeasurement};
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Measure {
Name,
/// `responseEnd - responseStart`.
/// `Math.floor(responseEnd - responseStart)`.
Response,
/// `responseStart - requestStart`.
/// `Math.floor(responseStart - requestStart)`.
Request,
/// `Math.floor(duration)`.
Duration,
Transfer,
Body,
/// Original timestamps: `startTime`, `requestStart`, `responseStart`, `responseEnd`, and
/// `duration`.
Start,
RequestStart,
ResponseStart,
ResponseEnd,
ExactDuration,
}
/// A resource load with its name, start time, and measured phases. The start time is in
/// milliseconds from the document's time origin. The response ends when the load finishes.
#[derive(Debug, Clone, Copy, PartialEq)]
pub(crate) struct Entry<'a> {
pub name: &'a str,
pub start: f64,
pub measured: ResourceMeasurement,
}
/// Maps collected resource timings to the six fields sent under the collection's option name.
@@ -30,31 +48,48 @@ pub struct ResourceTiming {
}
impl ResourceTiming {
/// Reduces a measured fetch to the session's resource timing format.
/// Converts a load to the resource timing format used by this session.
#[must_use]
pub(crate) fn reduce(&self, url: &str, measured: &ResourceMeasurement) -> JsValue {
let mut entry = JsObject::new();
pub(crate) fn reduce(&self, entry: &Entry<'_>) -> JsValue {
let measured = &entry.measured;
// Restricted entries report a response start of zero; see
// `ResourceMeasurement::restricted`.
let response_end = entry.start + measured.duration;
let response_start = response_end - measured.response;
let request_start = response_start - measured.request;
let mut reduced = JsObject::new();
for (name, measure) in &self.fields {
let value = match measure {
Measure::Name => json!(url),
Measure::Name => json!(entry.name),
Measure::Response => json!(measured.response.floor()),
Measure::Request => json!(measured.request.floor()),
Measure::Duration => json!(measured.duration.floor()),
Measure::Transfer => json!(measured.transfer_size),
Measure::Body => json!(measured.body_size),
Measure::Start => json!(entry.start),
Measure::RequestStart => json!(request_start),
Measure::ResponseStart => json!(response_start),
Measure::ResponseEnd => json!(response_end),
Measure::ExactDuration => json!(measured.duration),
};
entry.insert(name.clone(), value);
reduced.insert(name.clone(), value);
}
JsValue::Object(entry)
JsValue::Object(reduced)
}
/// Reduces `load` using its measured phases.
/// Converts measured phases from `load` to the session format. Times are relative to
/// `origin_ms`, the document navigation time in milliseconds since the Unix epoch.
#[must_use]
pub(crate) fn entry(&self, load: &LoadTiming) -> JsValue {
self.reduce(&load.url, &load.measurement())
pub(crate) fn entry(&self, load: &LoadTiming, origin_ms: i64) -> JsValue {
self.reduce(&Entry {
name: &load.url,
start: (load.started_ms - origin_ms) as f64,
measured: load.measurement(),
})
}
/// Splits the session's total document load time into the navigation's `phases`.
/// Splits the total document load time into navigation `phases`. Navigation starts at the
/// document's time origin.
#[must_use]
pub(crate) fn navigation(
&self,
@@ -63,10 +98,11 @@ impl ResourceTiming {
bytes: u64,
phases: Phases,
) -> JsValue {
self.reduce(
url,
&ResourceMeasurement::estimated(duration, bytes, phases),
)
self.reduce(&Entry {
name: url,
start: 0.0,
measured: ResourceMeasurement::estimated(duration, bytes, phases),
})
}
}
@@ -90,7 +126,7 @@ pub(super) fn reduction(body: &BlockStmt) -> Option<Vec<(String, Measure)>> {
}
/// Recognizes a reduced entry when it has enough fields, includes the resource name, and uses
/// only the name or `measured` locals.
/// only properties of the entry itself or locals listed in `measured`.
fn reduced_fields(
fields: &[ObjectField<'_>],
measured: &[(&str, Measure)],
@@ -98,7 +134,17 @@ fn reduced_fields(
let mut reduced = Vec::with_capacity(fields.len());
for field in fields {
let measure = match field.value {
Expr::Member(member) if ast::member_str(&member.prop) == Some("name") => Measure::Name,
Expr::Member(member) => match ast::member_str(&member.prop)? {
"name" => Measure::Name,
"startTime" => Measure::Start,
"requestStart" => Measure::RequestStart,
"responseStart" => Measure::ResponseStart,
"responseEnd" => Measure::ResponseEnd,
"duration" => Measure::ExactDuration,
"transferSize" => Measure::Transfer,
"encodedBodySize" => Measure::Body,
_ => return None,
},
Expr::Ident(ident) => {
let (_, measure) = measured.iter().rfind(|(local, _)| *local == &*ident.sym)?;
*measure
@@ -174,4 +220,57 @@ mod tests {
json!({"n": "u", "r": 5.0, "q": 9.0, "d": 137.0, "t": 301, "b": 1})
);
}
/// Builds from 2026-10-27 onward copy original timestamps rather than rounding down phase
/// durations.
#[test]
fn summaries_may_copy_the_entrys_timestamps() {
let parsed = ast::parse_javascript(
"t.js",
"function f(e) { var r; r = { a: e.name, b: e.startTime, c: e.requestStart, \
d: e.responseStart, g: e.responseEnd, h: e.duration, i: e.transferSize, \
j: e.encodedBodySize }; list.push(r); }",
)
.unwrap();
let function = parsed.script.body[0]
.as_decl()
.unwrap()
.as_fn_decl()
.unwrap();
let fields = reduction(function.function.body.as_ref().unwrap()).unwrap();
let measures: Vec<Measure> = fields.iter().map(|(_, measure)| *measure).collect();
assert_eq!(
measures,
[
Measure::Name,
Measure::Start,
Measure::RequestStart,
Measure::ResponseStart,
Measure::ResponseEnd,
Measure::ExactDuration,
Measure::Transfer,
Measure::Body,
]
);
let timing = ResourceTiming {
option: "t".into(),
fields,
};
let entry = Entry {
name: "u",
start: 10.0,
measured: ResourceMeasurement {
duration: 100.0,
request: 60.0,
response: 5.0,
transfer_size: 1300,
body_size: 1000,
},
};
assert_eq!(
timing.reduce(&entry),
json!({"a": "u", "b": 10.0, "c": 45.0, "d": 105.0, "g": 110.0, "h": 100.0,
"i": 1300, "j": 1000})
);
}
}
+372 -17
View File
@@ -1,24 +1,26 @@
//! Recovers the script state the first payload reports: `Date.now()` marks, the interaction
//! tally ([`super::tally`]), the sender's additions, and the resource timing format
//! ([`super::reduced_timing`]).
//! tally ([`super::tally`]), the sender's additions and POST log, and the resource timing
//! format ([`super::reduced_timing`]).
use std::collections::BTreeMap;
use anyhow::{Result, bail, ensure};
use anyhow::{Context, Result, bail, ensure};
use indexmap::IndexMap;
use serde::{Deserialize, Deserializer, Serialize};
use swc_core::ecma::ast::{
ArrowExpr, AssignExpr, AssignTarget, BinaryOp, Expr, Function, IfStmt, ObjectLit,
SimpleAssignTarget, Stmt,
ArrowExpr, AssignExpr, AssignTarget, BinaryOp, CallExpr, Expr, Function, IfStmt, ObjectLit,
SimpleAssignTarget, Stmt, VarDeclarator,
};
use swc_core::ecma::visit::{Visit, VisitWith};
use crate::candidates;
use crate::challenge::payload::Field;
use crate::challenge::reduced_timing::{self, ResourceTiming};
use crate::challenge::tally::{self, CounterEvents, Tally};
use crate::challenge::{expression, source};
use crate::js::ast::{self, ParsedScript};
use crate::js::{JsValue, Options};
use crate::js::{JsObject, JsValue, Options, Payload, json};
use crate::resource_timing::LoadTiming;
/// Script state reported in the first payload.
#[derive(Debug, Default)]
@@ -36,6 +38,73 @@ pub struct ScriptState {
pub timing: Option<ResourceTiming>,
/// Functions on the script's namespace, mapped to the option each returns.
pub getters: BTreeMap<String, String>,
pub post_log: Option<PostLog>,
}
/// Log of challenge POSTs. Each payload includes the log so far. The sender then adds an entry for
/// the current POST and records its response time when the response arrives.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct PostLog {
/// The option holding the log.
pub option: String,
/// Option containing the POST counter recorded in each entry.
pub counter: String,
/// Entry fields in insertion order, excluding the response time added later.
pub fields: Vec<(String, Logged)>,
/// The field holding the response time.
pub answered: String,
}
/// Value recorded by a field in a POST log entry.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Logged {
Url,
Count,
/// When the POST was sent.
Sent,
}
impl PostLog {
/// Initializes an empty log, matching the iframe before its first POST.
pub(crate) fn start(&self, options: &mut Options) {
options.insert(self.option.clone(), json!([]));
options.insert(self.counter.clone(), json!(0));
}
/// Appends `post` to the log in `options`. Times are relative to `origin_ms`, the document
/// navigation time in milliseconds since the Unix epoch.
pub(crate) fn record(
&self,
options: &mut Options,
post: &LoadTiming,
origin_ms: i64,
) -> Result<()> {
let count = options
.get(&self.counter)
.and_then(JsValue::as_i64)
.unwrap_or(0)
+ 1;
options.insert(self.counter.clone(), json!(count));
let mut entry = JsObject::new();
for (field, logged) in &self.fields {
let value = match logged {
Logged::Url => json!(post.url),
Logged::Count => json!(count),
Logged::Sent => json!((post.started_ms - origin_ms) as f64),
};
entry.insert(field.clone(), value);
}
entry.insert(
self.answered.clone(),
json!(post.ended_ms() - origin_ms as f64),
);
options
.get_mut(&self.option)
.and_then(JsValue::as_array_mut)
.context("the session keeps no POST log")?
.push(JsValue::Object(entry));
Ok(())
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
@@ -102,6 +171,7 @@ impl ScriptState {
script.visit_with(&mut scopes);
let mut sender = Sender::default();
script.visit_with(&mut sender);
let post_log = sender.post_log()?;
let elapsed = candidates::at_most_one_distinct(sender.elapsed, "elapsed-time field")?;
let sender_scope = elapsed.as_ref().map(|(scope, _)| *scope);
// The sender forwards option values directly. Another function copies collected
@@ -139,6 +209,7 @@ impl ScriptState {
forwarded: forwarded.into_iter().map(|(_, key)| key).collect(),
timing,
getters: distinct_getters(sender.getters)?,
post_log,
})
}
@@ -158,6 +229,22 @@ impl ScriptState {
.any(|mark| mark.option == option && mark.in_builder)
}
/// Identifies the interval measured by `difference`, using `merged` as the marked option.
/// Returns no interval if the script never marks the later timestamp.
fn span(&self, difference: &Difference, merged: Option<&str>) -> Option<Span> {
let Difference { later, earlier } = difference;
if !self.marks.iter().any(|mark| &mark.option == later) {
return None;
}
Some(if self.builds_payload(later) {
Span::Collect
} else if Some(earlier.as_str()) == merged {
Span::Handoff
} else {
Span::Initialise
})
}
/// Assigns timestamps to match configured durations. Skips timestamps unused in
/// differences. Keeps the first value assigned to each timestamp, even if a later duration
/// constraint conflicts.
@@ -173,27 +260,72 @@ impl ScriptState {
if let Some(merged) = merged {
clock.insert(merged, merged_at);
}
for Difference { later, earlier } in differences {
if !self.marks.iter().any(|mark| &mark.option == later) {
for difference in differences {
let Some(span) = self.span(difference, merged) else {
continue;
}
};
// The builder starts after the parameter merge. Other measured work overlaps the
// handoff.
let (start, duration) = if self.builds_payload(later) {
(merged_at + intervals.handoff + 1, intervals.collect)
} else if Some(earlier.as_str()) == merged {
(merged_at + 1, intervals.handoff)
} else {
(merged_at + 1, intervals.initialise)
let (start, duration) = match span {
Span::Collect => (merged_at + intervals.handoff + 1, intervals.collect),
Span::Handoff => (merged_at + 1, intervals.handoff),
Span::Initialise => (merged_at + 1, intervals.initialise),
};
let start = *clock.entry(earlier).or_insert(start);
clock.entry(later).or_insert(start + duration);
let start = *clock.entry(&difference.earlier).or_insert(start);
clock.entry(&difference.later).or_insert(start + duration);
}
clock
.into_iter()
.map(|(option, when)| (option.to_owned(), JsValue::from(when)))
.collect()
}
/// Recovers intervals from a captured first `payload` using its template `fields`. This
/// reverses [`Self::timestamps`]. Uses the first difference that measures each interval; `send`
/// is the sender's elapsed time.
pub fn intervals(
&self,
fields: &[Field],
merged: Option<&str>,
payload: &Payload,
) -> Result<Intervals> {
let (mut initialise, mut handoff, mut collect) = (None, None, None);
for field in fields {
let span = field
.difference()
.and_then(|difference| self.span(&difference, merged));
let slot = match span {
Some(Span::Initialise) => &mut initialise,
Some(Span::Handoff) => &mut handoff,
Some(Span::Collect) => &mut collect,
None => continue,
};
if let Some(value) = payload.get(&field.name).and_then(JsValue::as_i64) {
slot.get_or_insert(value);
}
}
let send = self
.elapsed
.as_ref()
.and_then(|elapsed| payload.get(&elapsed.key)?.as_i64());
let reported = |interval: Option<i64>, name: &str| {
interval.with_context(|| format!("the payload reports no {name} interval"))
};
Ok(Intervals {
initialise: reported(initialise, "initialise")?,
handoff: reported(handoff, "handoff")?,
collect: reported(collect, "collect")?,
send: reported(send, "send")?,
})
}
}
/// Interval measured by a timestamp difference in the first payload.
#[derive(Clone, Copy)]
enum Span {
Initialise,
Handoff,
Collect,
}
/// Groups timestamps by their innermost function and finds the function containing the payload
@@ -269,6 +401,9 @@ struct Sender {
elapsed: Vec<(usize, Elapsed)>,
copies: Vec<(usize, String)>,
getters: Vec<Getter>,
pushes: Vec<Push>,
entries: Vec<LogEntry>,
stamps: Vec<Stamp>,
}
/// A namespace getter named `function` that returns the option `option`.
@@ -277,6 +412,18 @@ struct Getter {
option: String,
}
/// Matches `_cf_chl_opt.<log>.push(<local>)`.
struct Push {
log: String,
local: String,
}
/// Matches `<local>.<key> = <clock>()`.
struct Stamp {
local: String,
key: String,
}
impl Sender {
fn within<N: VisitWith<Self>>(&mut self, node: &N) {
self.entered += 1;
@@ -284,6 +431,71 @@ impl Sender {
node.visit_children_with(self);
self.scopes.pop();
}
/// Finds the log that receives an entry whose response time is assigned later.
fn post_log(&self) -> Result<Option<PostLog>> {
let logs = self.pushes.iter().filter_map(|push| {
let entry = self
.entries
.iter()
.find(|entry| entry.local == push.local)?;
let answered = self.stamps.iter().find(|stamp| {
stamp.local == push.local
&& !entry.fields.iter().any(|(field, _)| *field == stamp.key)
})?;
Some(PostLog {
option: push.log.clone(),
counter: entry.counter.clone(),
fields: entry.fields.clone(),
answered: answered.key.clone(),
})
});
candidates::at_most_one_distinct(logs, "POST log")
}
}
/// Finds a local initialized with a POST log entry: `{ url: new URL(...).href, count:
/// _cf_chl_opt.<counter>, sent: clock() }`.
struct LogEntry {
local: String,
fields: Vec<(String, Logged)>,
counter: String,
}
impl LogEntry {
fn read(local: &str, value: &Expr) -> Option<Self> {
let Expr::Object(object) = value.unwrap_parens() else {
return None;
};
let mut fields = Vec::new();
let mut counter = None;
for property in ast::key_values(object) {
let value = property.value.unwrap_parens();
let logged = if let Some(option) = expression::option_key(value) {
counter = Some(option.to_owned());
Logged::Count
} else if value.as_call().is_some_and(|call| call.args.is_empty()) {
Logged::Sent
} else if let Expr::Member(member) = value
&& ast::member_str(&member.prop) == Some("href")
&& member.obj.unwrap_parens().is_new()
{
Logged::Url
} else {
return None;
};
fields.push((ast::key_str(&property.key)?.to_owned(), logged));
}
let complete = fields.len() == 3
&& [Logged::Url, Logged::Count, Logged::Sent]
.iter()
.all(|logged| fields.iter().any(|(_, field)| field == logged));
complete.then_some(Self {
local: local.to_owned(),
fields,
counter: counter?,
})
}
}
impl Visit for Sender {
@@ -295,8 +507,39 @@ impl Visit for Sender {
self.within(arrow);
}
fn visit_var_declarator(&mut self, declarator: &VarDeclarator) {
if let Some(local) = declarator.name.as_ident()
&& let Some(init) = &declarator.init
&& let Some(entry) = LogEntry::read(&local.sym, init)
{
self.entries.push(entry);
}
declarator.visit_children_with(self);
}
fn visit_call_expr(&mut self, call: &CallExpr) {
// `_cf_chl_opt.<log>.push(<entry>)`
if let Some(callee) = call.callee.as_expr().and_then(|callee| callee.as_member())
&& ast::member_str(&callee.prop) == Some("push")
&& let Some(option) = expression::option_key(&callee.obj)
&& let [entry] = &call.args[..]
&& let Some(local) = entry.expr.as_ident()
{
self.pushes.push(Push {
log: option.to_owned(),
local: local.sym.to_string(),
});
}
call.visit_children_with(self);
}
fn visit_assign_expr(&mut self, assignment: &AssignExpr) {
let scope = self.scopes.last().copied().unwrap_or_default();
if let AssignTarget::Simple(SimpleAssignTarget::Ident(local)) = &assignment.left
&& let Some(entry) = LogEntry::read(&local.sym, &assignment.right)
{
self.entries.push(entry);
}
if let AssignTarget::Simple(SimpleAssignTarget::Member(target)) = &assignment.left
&& let Some(key) = ast::ident_property(target)
{
@@ -329,6 +572,16 @@ impl Visit for Sender {
right if expression::option_key(right) == Some(key) => {
self.copies.push((scope, key.to_owned()));
}
// `entry.<key> = clock()`
Expr::Call(call)
if call.args.is_empty()
&& let Some(local) = target.obj.as_ident() =>
{
self.stamps.push(Stamp {
local: local.sym.to_string(),
key: key.to_owned(),
});
}
_ => {}
}
}
@@ -352,6 +605,8 @@ fn distinct_getters(getters: Vec<Getter>) -> Result<BTreeMap<String, String>> {
#[cfg(test)]
mod tests {
use super::*;
use crate::challenge::payload;
use crate::js::Window;
#[test]
fn rejects_senders_that_disagree_about_the_elapsed_field() {
@@ -394,4 +649,104 @@ mod tests {
let at = script.timestamps(&differences, Some("merged"), 0, intervals);
assert_eq!(JsValue::from(at).to_string(), r#"{"merged":0,"a":1,"b":8}"#);
}
/// Builds from 2026-10-27 onward log each POST and include the log in every payload.
#[test]
fn recovers_the_senders_post_log() {
let source = r#"
function send(url, payload, attempt) {
var entry;
payload.k = Date.now() - w._cf_chl_opt.m;
payload.log = w._cf_chl_opt.log;
if (attempt === 0) w._cf_chl_opt.n++;
entry = { u: new URL(url, w.location.href).href, c: w._cf_chl_opt.n, s: clock() };
w._cf_chl_opt.log.push(entry);
function answered() { if (entry && entry.a === undefined) entry.a = clock(); }
}"#;
let script = ScriptState::from_javascript(source).unwrap();
assert_eq!(script.forwarded, ["log"]);
let log = script.post_log.unwrap();
assert_eq!(
[&log.option, &log.counter, &log.answered],
["log", "n", "a"]
);
let mut options = Options::new();
log.start(&mut options);
assert_eq!(options.get("log"), Some(&json!([])));
let post = LoadTiming {
url: "https://example.com/fo".into(),
started_ms: 1_100,
duration_ms: 250.0,
waiting_ms: 0.0,
receiving_ms: 0.0,
body_bytes: 1,
};
log.record(&mut options, &post, 1_000).unwrap();
assert_eq!(
options.get("log"),
Some(&json!([{"u": "https://example.com/fo", "c": 1, "s": 100.0, "a": 350.0}]))
);
assert_eq!(options.get("n"), Some(&json!(1)));
}
/// Building a payload from [`ScriptState::timestamps`] preserves the input intervals.
#[test]
fn reads_back_the_intervals_a_payload_reports() {
let script = ScriptState {
elapsed: Some(Elapsed {
key: "sent".into(),
mark: "zWnC9".into(),
}),
marks: [("dwQH2", false), ("WVhrW1", true), ("mrjlM3", false)]
.map(|(option, in_builder)| Mark {
option: option.into(),
in_builder,
})
.to_vec(),
..ScriptState::default()
};
let pairs = [
("dwQH2", "pUyWp4"),
("WVhrW1", "gyhng3"),
("mrjlM3", "zWnC9"),
];
let fields: Vec<Field> = pairs
.iter()
.enumerate()
.map(|(index, (later, earlier))| {
let text = format!("e._cf_chl_opt.{later} - e._cf_chl_opt.{earlier}");
Field {
name: format!("f{index}"),
expression: ast::parse_expression("t", &text).unwrap(),
text,
bootstrap_value: None,
}
})
.collect();
let intervals = &Intervals {
initialise: 15,
handoff: 17,
collect: 70,
send: 123,
};
let differences = payload::differences(&fields);
let clock = script.timestamps(&differences, Some("zWnC9"), 0, intervals);
let mut built = payload::build(&fields, &clock, &Window::new()).unwrap();
built.insert("sent".into(), json!(intervals.send));
let read = script.intervals(&fields, Some("zWnC9"), &built).unwrap();
assert_eq!(
[read.initialise, read.handoff, read.collect, read.send],
[
intervals.initialise,
intervals.handoff,
intervals.collect,
intervals.send
]
);
built.shift_remove("sent");
let error = script
.intervals(&fields, Some("zWnC9"), &built)
.unwrap_err();
assert!(error.to_string().contains("no send interval"), "{error}");
}
}
+7 -4
View File
@@ -12,9 +12,10 @@ type HashSet<T> = rustc_hash::FxHashSet<T>;
mod analysis;
mod argument_arrays;
mod arrow_blocks;
mod bitwise;
mod blocks;
mod constant_objects;
mod call_helpers;
mod control_flow;
mod copy_propagation;
mod dead_branches;
@@ -23,19 +24,21 @@ mod dispatch;
mod encoded_strings;
mod function_lengths;
mod helper_objects;
mod indexed_table;
mod int32_helpers;
mod literals;
mod loops;
mod memoized_strings;
mod merged_functions;
mod pipeline;
mod register_arrays;
mod removal;
mod scratch_parameters;
mod state_machines;
mod statements;
mod static_members;
mod string_array;
#[cfg(test)]
mod testing;
mod unused_bindings;
pub(crate) use encoded_strings::{Encoded, encode as encode_string, inline_strings};
pub use pipeline::{Deobfuscated, Unconverged, deobfuscate};
pub(crate) use pipeline::{deobfuscate_with, read_decoded};
+21 -60
View File
@@ -4,16 +4,15 @@
use std::mem;
use swc_core::ecma::ast::{
AssignExpr, AssignOp, BindingIdent, ClassDecl, Expr, FnDecl, ForHead, Function, Id, Ident,
ArrowExpr, AssignExpr, AssignOp, ClassDecl, Expr, FnDecl, ForHead, Function, Id, Ident, Param,
Program, Prop, UpdateExpr, VarDeclarator,
};
use swc_core::ecma::visit::{Visit, VisitWith};
use swc_ecma_utils::DestructuringFinder;
use crate::deobfuscate::{HashMap, HashSet};
use crate::js::ast;
/// Tracks writes, references, and declarations by resolved [`Id`]. Names alone are insufficient
/// Tracks writes and references by resolved [`Id`]. Names are not enough
/// because the obfuscator reuses them across scopes.
///
/// Writes include assignments, updates, initialized declarations, `for-in` and `for-of`
@@ -24,9 +23,10 @@ use crate::js::ast;
pub(crate) struct Bindings {
writes: HashMap<Id, Vec<Write>>,
references: HashMap<Id, usize>,
declared: HashSet<Id>,
/// Bindings that receive a copy of each binding's value.
copies: HashMap<Id, Vec<Id>>,
/// Parameters of functions and arrows.
parameters: HashSet<Id>,
/// Parameters of functions that use `arguments`.
mapped: HashSet<Id>,
/// Whether the function being visited refers to its `arguments`.
@@ -37,8 +37,6 @@ pub(crate) struct Bindings {
enum Write {
/// `binding = other` or `var binding = other`.
Copy(Id),
/// `binding = f()`, calling `f` without arguments.
Call(Id),
Other,
}
@@ -67,11 +65,10 @@ impl Bindings {
self.references.get(id).copied().unwrap_or(0)
}
/// Checks whether the program declares or assigns the binding, including parameter
/// bindings.
/// Returns whether the binding is a function or arrow parameter that can hold an argument.
#[must_use]
pub(crate) fn is_bound(&self, id: &Id) -> bool {
self.declared.contains(id) || self.writes.contains_key(id)
pub(crate) fn is_parameter(&self, id: &Id) -> bool {
self.parameters.contains(id)
}
/// Checks whether this is a parameter of a function using `arguments`. In sloppy mode,
@@ -123,36 +120,6 @@ impl Bindings {
.is_some_and(|copies| copies.iter().any(|copy| self.copy_source(copy) == Some(id)))
}
/// Returns the callee whose result is the only value assigned to `id`.
#[must_use]
pub(crate) fn sole_call(&self, id: &Id) -> Option<Id> {
match self.writes.get(id)?.as_slice() {
[Write::Call(callee)] => Some(callee.clone()),
_ => None,
}
}
/// Returns `id` and all bindings that copy it, directly or through other copies, regardless
/// of assignment order.
#[must_use]
pub(crate) fn aliases(&self, id: &Id) -> HashSet<Id> {
let mut aliases = HashSet::from_iter([id.clone()]);
let mut pending = vec![id.clone()];
while let Some(source) = pending.pop() {
let copies = self.copies.get(&source).into_iter().flatten();
for copy in copies {
let copies_only_aliases = self.writes[copy]
.iter()
.all(|write| matches!(write, Write::Copy(from) if aliases.contains(from)));
if !aliases.contains(copy) && copies_only_aliases {
aliases.insert(copy.clone());
pending.push(copy.clone());
}
}
}
aliases
}
fn write<N: VisitWith<DestructuringFinder<Id>>>(&mut self, target: &N) {
for id in swc_ecma_utils::find_pat_ids::<_, Id>(target) {
self.writes.entry(id).or_default().push(Write::Other);
@@ -167,8 +134,6 @@ impl Bindings {
.or_default()
.push(id.clone());
Write::Copy(source.to_id())
} else if let Some((callee, [])) = ast::direct_call(value) {
Write::Call(callee.to_id())
} else {
Write::Other
};
@@ -238,9 +203,16 @@ impl Visit for Bindings {
}
}
fn visit_binding_ident(&mut self, identifier: &BindingIdent) {
self.declared.insert(identifier.to_id());
identifier.visit_children_with(self);
fn visit_param(&mut self, parameter: &Param) {
self.parameters
.extend(swc_ecma_utils::find_pat_ids::<_, Id>(&parameter.pat));
parameter.visit_children_with(self);
}
fn visit_arrow_expr(&mut self, arrow: &ArrowExpr) {
self.parameters
.extend(swc_ecma_utils::find_pat_ids::<_, Id>(&arrow.params));
arrow.visit_children_with(self);
}
fn visit_ident(&mut self, identifier: &Ident) {
@@ -296,27 +268,16 @@ mod tests {
}
#[test]
fn follows_copies_sole_calls_and_mapped_parameters() {
fn follows_copies_and_mapped_parameters() {
testing::check(
"function f(late, middle, other, mixed, table, h, p, q) {
late = middle; middle = d; other = d; other = middle;
mixed = d; mixed = g(); table = provider();
"function f(late, middle, mixed, h, p, q) {
late = middle; middle = d; mixed = d; mixed = g();
function d() {}
function provider() {}
h = {}; p = h; var q = p;
return parseInt(late);
return late;
}",
|program, id| {
let bindings = Bindings::collect(program);
let aliases = bindings.aliases(&id("d"));
for alias in ["d", "late", "middle", "other"] {
assert!(aliases.contains(&id(alias)), "{alias}");
}
assert!(!aliases.contains(&id("mixed")));
assert_eq!(bindings.sole_call(&id("table")), Some(id("provider")));
assert_eq!(bindings.sole_call(&id("mixed")), None);
assert!(!bindings.is_bound(&id("parseInt")));
assert!(bindings.is_bound(&id("late")));
assert_eq!(bindings.root(&id("q")), id("h"));
assert_eq!(bindings.root(&id("late")), id("d"));
assert_eq!(bindings.root(&id("mixed")), id("mixed"));
+61 -35
View File
@@ -6,14 +6,17 @@
//! count. Visitors process ordinary statements first and record identifier uses through
//! [`reference`]. They then visit declarations with the facts valid for each one.
//!
//! This treatment applies only to declarations in function bodies. Top-level functions can be
//! called by other scripts at any time. Block functions exist only once the block executes.
//! Both use the facts known on entry.
//! Block declarations work the same way, with an extra rule for sloppy mode: after a block function
//! declaration runs, the function is also accessible through the enclosing function's `var`
//! binding. Include the facts known at that declaration.
//!
//! Other scripts can call top-level functions at any time. Any switch case can call functions
//! declared in another case. For both, use only the facts known on entry.
use std::mem;
use std::rc::Rc;
use swc_core::ecma::ast::{Decl, Function, Id, Ident, Stmt};
use swc_core::ecma::ast::{BlockStmt, Decl, Function, Id, Ident, Stmt};
use swc_core::ecma::visit::{Visit, VisitMut, VisitMutWith, VisitWith};
use crate::deobfuscate::{HashMap, HashSet};
@@ -51,6 +54,16 @@ fn is_declaration(statement: &Stmt) -> bool {
matches!(statement, Stmt::Decl(Decl::Fn(_)))
}
/// Context of a statement list containing declarations.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub(crate) enum List {
/// A script's top level or a switch case.
#[default]
Other,
FunctionBody,
Block,
}
/// Tracks current facts, active function declarations, and facts collected at references to
/// those declarations.
#[derive(Default)]
@@ -60,8 +73,8 @@ pub(crate) struct Hoisting<F> {
/// Intersection of facts at references to each declaration; `None` before its first
/// reference.
pending: HashMap<Id, Option<F>>,
/// Whether the next statement list is a function body.
pub(crate) function_body: bool,
/// Context to use for the next statement list.
pub(crate) list: List,
}
/// The function declarations of one statement list, from
@@ -72,7 +85,9 @@ struct Declarations<F> {
callers: Vec<Vec<usize>>,
/// Facts at list entry, saved when the list contains declarations.
entry: Option<F>,
function_body: bool,
list: List,
/// Facts known at each block declaration, in statement order.
reached: Vec<F>,
}
/// One function declaration of a statement list, at `position` in it.
@@ -85,7 +100,7 @@ impl<F: HoistFacts> Hoisting<F> {
/// Starts visiting `statements` with the entry facts.
#[must_use]
fn enter(&mut self, statements: &[Stmt]) -> Declarations<F> {
let function_body = mem::take(&mut self.function_body);
let mut list = mem::take(&mut self.list);
let declarations: Vec<Declaration> = statements
.iter()
.enumerate()
@@ -94,8 +109,16 @@ impl<F: HoistFacts> Hoisting<F> {
Some(Declaration { position, id })
})
.collect();
// Sharing a binding with an enclosing declaration would stop tracking that binding.
if list == List::Block
&& declarations
.iter()
.any(|declaration| self.pending.contains_key(&declaration.id))
{
list = List::Other;
}
let mut callers = vec![];
if function_body {
if list != List::Other {
let mut indices: HashMap<Id, Vec<usize>> = HashMap::default();
for (index, declaration) in declarations.iter().enumerate() {
indices
@@ -117,7 +140,15 @@ impl<F: HoistFacts> Hoisting<F> {
entry: (!declarations.is_empty()).then(|| self.facts.clone()),
declarations,
callers,
function_body,
list,
reached: Vec::new(),
}
}
/// Records the facts known when a block declaration runs.
fn reach(&self, declarations: &mut Declarations<F>) {
if declarations.list == List::Block {
declarations.reached.push(self.facts.clone());
}
}
@@ -129,12 +160,13 @@ impl<F: HoistFacts> Hoisting<F> {
declarations,
callers,
entry,
function_body,
list,
reached,
} = declarations;
let Some(entry) = entry else {
return vec![];
};
if !function_body {
if list == List::Other {
return declarations
.into_iter()
.map(|declaration| (declaration.position, entry.clone()))
@@ -165,6 +197,9 @@ impl<F: HoistFacts> Hoisting<F> {
}
}
}
if let Some(reached) = reached.get(index) {
meet(&mut facts, reached);
}
declared.push((declaration.position, facts.unwrap_or_else(|| entry.clone())));
}
declared
@@ -185,9 +220,11 @@ pub(crate) fn visit_mut_stmts<V: Hoisted + VisitMut>(
statements: &mut [Stmt],
mut statement: impl FnMut(&mut V, &mut Stmt),
) {
let declarations = visitor.hoisting().enter(statements);
let mut declarations = visitor.hoisting().enter(statements);
for other in statements.iter_mut() {
if !is_declaration(other) {
if is_declaration(other) {
visitor.hoisting().reach(&mut declarations);
} else {
statement(visitor, other);
}
}
@@ -199,36 +236,25 @@ pub(crate) fn visit_mut_stmts<V: Hoisted + VisitMut>(
}
}
/// [`visit_mut_stmts`] for a visitor that only reads the tree.
pub(crate) fn visit_stmts<V: Hoisted + Visit>(
visitor: &mut V,
statements: &[Stmt],
mut statement: impl FnMut(&mut V, &Stmt),
) {
let declarations = visitor.hoisting().enter(statements);
for other in statements {
if !is_declaration(other) {
statement(visitor, other);
}
}
let declared = visitor.hoisting().leave(declarations);
for (position, facts) in declared {
with_facts(visitor, facts, |visitor| {
statements[position].visit_with(visitor);
});
}
}
/// Marks a function body for [`Hoisting::enter`] before visiting it.
pub(crate) fn visit_mut_function<V: Hoisted + VisitMut>(visitor: &mut V, function: &mut Function) {
function.decorators.visit_mut_with(visitor);
function.params.visit_mut_with(visitor);
if let Some(body) = &mut function.body {
visitor.hoisting().function_body = true;
visitor.hoisting().list = List::FunctionBody;
body.visit_mut_with(visitor);
}
}
/// Marks non-function blocks for [`Hoisting::enter`] before visiting them.
pub(crate) fn visit_mut_block<V: Hoisted + VisitMut>(visitor: &mut V, block: &mut BlockStmt) {
let list = &mut visitor.hoisting().list;
if *list == List::Other {
*list = List::Block;
}
block.visit_mut_children_with(visitor);
}
/// Records current facts at a reference to `identifier`. Direct `eval` can reference any
/// declaration in scope.
pub(crate) fn reference<V: Hoisted>(visitor: &mut V, identifier: &Ident) {
+194
View File
@@ -0,0 +1,194 @@
//! Replaces calls to arrow functions with their block bodies:
//!
//! ```js
//! function f() {
//! var a, step;
//! step = () => { a = g(); };
//! h();
//! { step(); } // becomes { { a = g(); } }
//! }
//! ```
//!
//! The arrow must be synchronous, take no parameters, and have a block body with no `return`.
//! It must be assigned once in the enclosing function body and called once, without arguments,
//! in a later statement or nested block. The call can run at most once per enclosing call.
//!
//! Inlining preserves `this`, `arguments`, and local variables because arrows share them with
//! the enclosing function. The unused-bindings pass removes the arrow definition afterwards.
use swc_core::ecma::ast::{
ArrowExpr, BlockStmt, BlockStmtOrExpr, Constructor, Function, Id, Program, ReturnStmt, Stmt,
};
use swc_core::ecma::visit::{Visit, VisitMut, VisitMutWith, VisitWith};
use super::HashMap;
use super::analysis::{Analysis, Bindings};
use crate::js::ast;
pub(super) fn run(program: &mut Program, analysis: &mut Analysis) -> bool {
let mut inline = Inline {
bindings: analysis.bindings(program),
changed: false,
};
program.visit_mut_with(&mut inline);
inline.changed
}
struct Inline<'bindings> {
bindings: &'bindings Bindings,
changed: bool,
}
/// The binding and body of `binding = () => { ... }` without `return`.
fn block_arrow(statement: &Stmt) -> Option<(Id, &BlockStmt)> {
let (id, value) = ast::assignment(&statement.as_expr()?.expr)?;
let ArrowExpr {
params,
body,
is_async: false,
is_generator: false,
..
} = value.as_arrow()?
else {
return None;
};
let BlockStmtOrExpr::BlockStmt(body) = &**body else {
return None;
};
(params.is_empty() && !returns(body)).then_some((id, body))
}
/// Returns the binding called by an argument-free statement such as `binding();`.
fn called(statement: &Stmt) -> Option<Id> {
let (callee, []) = ast::direct_call(&statement.as_expr()?.expr)? else {
return None;
};
Some(callee.to_id())
}
fn returns(body: &BlockStmt) -> bool {
struct Returns(bool);
impl Visit for Returns {
fn visit_return_stmt(&mut self, _: &ReturnStmt) {
self.0 = true;
}
fn visit_function(&mut self, _: &Function) {}
fn visit_arrow_expr(&mut self, _: &ArrowExpr) {}
}
let mut returns = Returns(false);
body.visit_with(&mut returns);
returns.0
}
/// Replaces calls in `statements` and nested blocks with the arrow bodies.
fn replace_calls(statements: &mut [Stmt], bodies: &HashMap<Id, BlockStmt>) -> bool {
let mut changed = false;
for statement in statements {
if let Some(body) = called(statement).and_then(|id| bodies.get(&id)) {
*statement = Stmt::Block(body.clone());
changed = true;
} else if let Stmt::Block(block) = statement {
changed |= replace_calls(&mut block.stmts, bodies);
}
}
changed
}
/// Finds calls in `statement` and nested blocks.
fn calls(statement: &Stmt, found: &mut Vec<Id>) {
if let Some(id) = called(statement) {
found.push(id);
} else if let Stmt::Block(block) = statement {
for statement in &block.stmts {
calls(statement, found);
}
}
}
impl Inline<'_> {
fn inline(&mut self, statements: &mut [Stmt]) {
let mut arrows: HashMap<Id, &BlockStmt> = HashMap::default();
let mut bodies = HashMap::default();
for statement in statements.iter() {
let mut found = vec![];
calls(statement, &mut found);
// Only replace calls after the arrow definition in the same function.
for id in found {
if let Some(body) = arrows.remove(&id) {
bodies.insert(id, body.clone());
}
}
if let Some((id, body)) = block_arrow(statement)
&& self.bindings.is_written_once(&id)
&& self.bindings.references(&id) == 1
{
arrows.insert(id, body);
}
}
self.changed |= !bodies.is_empty() && replace_calls(statements, &bodies);
}
}
impl VisitMut for Inline<'_> {
fn visit_mut_function(&mut self, function: &mut Function) {
function.visit_mut_children_with(self);
if let Some(body) = &mut function.body {
self.inline(&mut body.stmts);
}
}
fn visit_mut_constructor(&mut self, constructor: &mut Constructor) {
constructor.visit_mut_children_with(self);
if let Some(body) = &mut constructor.body {
self.inline(&mut body.stmts);
}
}
fn visit_mut_arrow_expr(&mut self, arrow: &mut ArrowExpr) {
arrow.visit_mut_children_with(self);
if let BlockStmtOrExpr::BlockStmt(body) = &mut *arrow.body {
self.inline(&mut body.stmts);
}
}
}
#[cfg(test)]
mod tests {
use crate::deobfuscate::testing;
#[test]
fn inlines_blocks_called_once_after_their_definition() {
let transform = |source: &str| testing::rewrite(source, super::run, /* fix= */ true);
let output = transform(
"function f() {
var a, s, t;
s = () => { a = g(); };
t = () => { var b = a; h(b, this, arguments); };
h();
{ t(); s(); }
}",
);
testing::assert_contains(
&output,
&[],
&["{ { var b = a; h(b, this, arguments); } { a = g(); } }"],
);
let output =
transform("class K { constructor() { var s; s = () => { this.a = 1; }; s(); } }");
testing::assert_contains(&output, &[], &["{ this.a = 1; }"]);
for kept in [
"function f() { var s; s(); s = () => { a(); }; }",
"function f() { var s; s = () => { a(); }; s(); s(); }",
"function f() { var s; s = () => { a(); }; if (b) s(); }",
"function f() { var s; s = () => { a(); }; while (b) { s(); } }",
"function f() { var s; s = () => { return a(); }; s(); }",
"function f() { var s; s = (x) => { a(x); }; s(); }",
"function f() { var s; s = () => { a(); }; g(s()); }",
"function f() { var s; s = () => { a(); }; function g() { s(); } }",
"function f() { var s; s = () => { a(); }; s = h; s(); }",
] {
let output = transform(kept);
assert!(output.contains("s()"), "{output}");
}
}
}
+212
View File
@@ -0,0 +1,212 @@
//! Restores method calls that the obfuscator routes through `Function.prototype.call`:
//!
//! ```js
//! var call = function(self, method, a) { return (function() {}).call.call(method, self, a); };
//! call(xhr, xhr.send, body); // becomes xhr.send(body)
//! call(o = xhr, o.open, "POST"); // becomes (o = xhr).open("POST"), or xhr.open("POST")
//! // when nothing else reads o
//! ```
//!
//! The helper must be assigned once and forward parameters in order, except for swapping the
//! method and receiver. The method must be read from the receiver's local binding. This keeps
//! the same `this` value as a regular method call.
use swc_core::common::util::take::Take;
use swc_core::ecma::ast::{
CallExpr, Callee, Expr, ExprOrSpread, FnDecl, Function, Id, MemberExpr, Pat, Program, Stmt,
VarDeclarator,
};
use swc_core::ecma::visit::{Visit, VisitMut, VisitMutWith, VisitWith};
use super::HashSet;
use super::analysis::{Analysis, Bindings, Globals, names};
use crate::js::ast;
pub(super) fn run(program: &mut Program, analysis: &mut Analysis) -> bool {
let globals = analysis.globals;
let bindings = analysis.bindings(program);
let mut helpers = Helpers::default();
program.visit_with(&mut helpers);
helpers.0.retain(|id| bindings.is_written_once(id));
if helpers.0.is_empty() {
return false;
}
let mut restore = Restore {
helpers: &helpers.0,
bindings,
globals,
changed: false,
};
program.visit_mut_with(&mut restore);
restore.changed
}
/// Checks for a helper of the form `function(self, method, ...rest) { return (function()
/// {}).call.call(method, self, ...rest); }` with plain parameters.
fn is_helper(function: &Function) -> bool {
let is_call = |member: &MemberExpr| ast::member_str(&member.prop) == Some("call");
if let Some(parameters) = names::parameter_ids(&function.params)
&& parameters.len() >= 2
&& !function.is_async
&& !function.is_generator
&& let Some([Stmt::Return(returned)]) = function.body.as_ref().map(|body| &body.stmts[..])
&& let Some(call) = returned.arg.as_deref().and_then(Expr::as_call)
&& let Some(callee) = call.callee.as_expr().and_then(|callee| callee.as_member())
&& let Some(inner) = callee.obj.as_member()
&& is_call(callee)
&& is_call(inner)
&& matches!(inner.obj.unwrap_parens(), Expr::Fn(_) | Expr::Arrow(_))
{
let passed = call.args.iter().map(|argument| {
let id = argument
.expr
.as_ident()
.filter(|_| argument.spread.is_none())?
.to_id();
parameters.iter().position(|parameter| *parameter == id)
});
let swapped = [1, 0].into_iter().chain(2..parameters.len()).map(Some);
passed.eq(swapped)
} else {
false
}
}
/// Helpers by binding.
#[derive(Default)]
struct Helpers(HashSet<Id>);
impl Visit for Helpers {
fn visit_expr(&mut self, expression: &Expr) {
if let Some((id, Expr::Fn(function))) = ast::assignment(expression)
&& is_helper(&function.function)
{
self.0.insert(id);
}
expression.visit_children_with(self);
}
fn visit_fn_decl(&mut self, declaration: &FnDecl) {
if is_helper(&declaration.function) {
self.0.insert(declaration.ident.to_id());
}
declaration.visit_children_with(self);
}
fn visit_var_declarator(&mut self, declarator: &VarDeclarator) {
if let Pat::Ident(name) = &declarator.name
&& let Some(Expr::Fn(function)) = declarator.init.as_deref()
&& is_helper(&function.function)
{
self.0.insert(name.to_id());
}
declarator.visit_children_with(self);
}
}
struct Restore<'a> {
helpers: &'a HashSet<Id>,
bindings: &'a Bindings,
globals: Globals,
changed: bool,
}
impl Restore<'_> {
/// Rewrites `helper(receiver, receiver.method, ...rest)` as a method call.
fn method_call(&self, arguments: &mut Vec<ExprOrSpread>) -> Option<Expr> {
let [receiver, method, ..] = &mut arguments[..] else {
return None;
};
if receiver.spread.is_some() || method.spread.is_some() {
return None;
}
let Expr::Member(member) = &mut *method.expr else {
return None;
};
let object = member.obj.as_ident()?.to_id();
let (target, unread) = match &*receiver.expr {
Expr::Ident(identifier) => (identifier.to_id(), false),
assignment => {
let (target, _) = ast::assignment(assignment)?;
// The method access below is the only read of the assigned local.
let unread = self.bindings.references(&target) == 1
&& target.1 != self.globals.unresolved
&& !self.bindings.is_mapped_parameter(&target);
(target, unread)
}
};
if target != object {
return None;
}
let mut receiver = receiver.expr.take();
if unread {
receiver = receiver.expect_assign().right;
}
member.obj = receiver;
Some(Expr::Call(CallExpr {
callee: Callee::Expr(method.expr.take()),
args: arguments.split_off(2),
..Default::default()
}))
}
}
impl VisitMut for Restore<'_> {
fn visit_mut_expr(&mut self, expression: &mut Expr) {
expression.visit_mut_children_with(self);
if let Expr::Call(call) = expression
&& let Some(callee) = call.callee.as_expr().and_then(|callee| callee.as_ident())
&& self.helpers.contains(&callee.to_id())
&& let Some(replacement) = self.method_call(&mut call.args)
{
*expression = replacement;
self.changed = true;
}
}
}
#[cfg(test)]
mod tests {
use crate::deobfuscate::testing;
#[test]
fn restores_method_calls_on_the_receiver_they_read() {
let output = testing::rewrite(
"var call = function(s, m, a, b) { return (function() {}).call.call(m, s, a, b); };
function f(x) {
var o, p, q;
call(x, x.send, 1, 2);
call(o = g(), o.open, 3, 4);
call(p = g(), p.open, 5, 6); h(p);
call(q = g(), x.open, 7, 8);
call(x, x.y.z, 9, 10);
}",
super::run,
/* fix= */ true,
);
testing::assert_contains(
&output,
&[],
&[
"x.send(1, 2);",
"g().open(3, 4);",
"(p = g()).open(5, 6);",
"call(q = g(), x.open, 7, 8);",
"call(x, x.y.z, 9, 10);",
],
);
for helper in [
"function(s, m, a) { return (function() {}).call.call(m, s); }",
"function(s, m, a) { return (function() {}).call.call(m, a, s); }",
"function(s, m) { return (function() {}).apply.call(m, s); }",
"function(s, m) { g(); return (function() {}).call.call(m, s); }",
] {
let output = testing::rewrite(
&format!("var call = {helper}; call(x, x.send, 1);"),
super::run,
/* fix= */ true,
);
assert!(output.contains("call(x, x.send"), "{output}");
}
}
}
-163
View File
@@ -1,163 +0,0 @@
//! Replaces numeric properties used to obscure string-array indices:
//!
//! ```js
//! map = { a: 2192 }; decode(map.a); // becomes decode(2192)
//! ```
//!
//! Requires one object assignment and stable literal properties (see
//! [`Properties::is_stable`]), and removes definitions once all reads are replaced. Hoisted
//! function bodies use only definitions available wherever they can be called (see
//! [`hoisting`]).
use swc_core::atoms::Atom;
use swc_core::ecma::ast::{
AssignExpr, AssignOp, Expr, Function, Id, Ident, Lit, Number, Program, Stmt,
};
use swc_core::ecma::visit::{VisitMut, VisitMutWith};
use super::analysis::hoisting::{self, Hoisted, Hoisting};
use super::analysis::{self, Analysis, Bindings, Properties};
use super::{HashMap, removal};
use crate::js::ast;
pub(super) fn run(program: &mut Program, analysis: &mut Analysis) -> bool {
let (bindings, properties) = analysis.properties(program);
let mut inline = InlineConstantObjects {
bindings,
properties,
hoisting: Hoisting::default(),
replaced: HashMap::default(),
changed: false,
};
program.visit_mut_with(&mut inline);
// Keep the object if a read precedes its definition or accesses a missing property.
let unread = removal::unread(&inline.replaced, bindings);
let removed = removal::remove_definitions(program, &unread);
inline.changed || removed
}
struct InlineConstantObjects<'analysis> {
bindings: &'analysis Bindings,
properties: &'analysis Properties,
/// Tracks objects and properties defined before the current node.
hoisting: Hoisting<HashMap<Id, HashMap<Atom, Number>>>,
/// How many reads of each object were replaced.
replaced: HashMap<Id, usize>,
changed: bool,
}
impl VisitMut for InlineConstantObjects<'_> {
fn visit_mut_assign_expr(&mut self, assignment: &mut AssignExpr) {
assignment.visit_mut_children_with(self);
if assignment.op == AssignOp::Assign
&& let Some(identifier) = assignment.left.as_ident()
&& self.bindings.is_written_once(&identifier.to_id())
&& let Some(object) = assignment.right.as_object()
{
let values: Option<HashMap<Atom, Number>> = object
.props
.iter()
.map(|property| {
let property = ast::key_value(property)?;
let value = property.value.as_lit()?.as_num()?;
Some((analysis::prop_key(&property.key)?, value.clone()))
})
.collect();
if let Some(values) = values.filter(|values| !values.is_empty()) {
self.replaced.insert(identifier.to_id(), 0);
self.hoisting.facts.insert(identifier.to_id(), values);
}
}
}
fn visit_mut_expr(&mut self, expression: &mut Expr) {
expression.visit_mut_children_with(self);
if let Expr::Member(member) = expression
&& let Some(identifier) = member.obj.as_ident()
&& let Some(values) = self.hoisting.facts.get(&identifier.to_id())
&& let Some(name) = analysis::member_key(&member.prop)
&& let Some(value) = values.get(&name)
&& self.properties.is_stable(&identifier.to_id(), &name)
{
*self.replaced.entry(identifier.to_id()).or_default() += 1;
*expression = Expr::Lit(Lit::Num(value.clone()));
self.changed = true;
}
}
/// Visit function declarations last, using definitions available at every possible call.
fn visit_mut_stmts(&mut self, statements: &mut Vec<Stmt>) {
hoisting::visit_mut_stmts(self, statements, |inline, statement| {
statement.visit_mut_with(inline);
});
}
fn visit_mut_function(&mut self, function: &mut Function) {
hoisting::visit_mut_function(self, function);
}
fn visit_mut_ident(&mut self, identifier: &mut Ident) {
hoisting::reference(self, identifier);
}
}
impl Hoisted for InlineConstantObjects<'_> {
type Facts = HashMap<Id, HashMap<Atom, Number>>;
fn hoisting(&mut self) -> &mut Hoisting<Self::Facts> {
&mut self.hoisting
}
}
#[cfg(test)]
mod tests {
use crate::deobfuscate::testing;
#[test]
fn inlines_single_write_objects_and_removes_unread_ones() {
let transform = |source: &str| testing::rewrite(source, super::run, /* fix= */ true);
let output = transform(
"function f(m, out) { m = { A: 10, K: 20 }; out = [decode(m.A), decode(m.K)]; \
return out; }",
);
testing::assert_contains(&output, &["decode(10)", "decode(20)"], &[]);
testing::assert_lacks(&output, &["m = {", "m.A"]);
let output = transform(
"function f(m, n, g) { g = function () { return n.A; }; m = { A: 10 }; \
n = { A: 1 }; return [m['A'], m.A, n.A, n.B, g()]; }",
);
testing::assert_contains(&output, &[], &["10, 10,"]);
assert!(!output.contains("m = {"), "{output}");
assert!(
output.contains("n = {"),
"`g` and `n.B` still read the object: {output}"
);
assert!(
output.contains("return n.A;"),
"`g` reads `n` before the traversal reaches its definition: {output}"
);
assert!(
output.contains("n.B"),
"`n.B` names a property the object does not have: {output}"
);
}
#[test]
fn preserves_reassigned_escaping_and_updated_objects() {
let transform = |source: &str| testing::rewrite(source, super::run, /* fix= */ true);
let output = transform(
"function f(m, out) { m = { A: 10, K: 20 }; out = [m.A, m.K]; m = 5; \
out.push(m); m = { A: 1 }; out.push(m.A); return out; }",
);
testing::assert_contains(&output, &["m = {", "m = 5;", "out.push(m);", "m.A"], &[]);
assert!(!output.contains("out.push(1)"), "{output}");
for source in [
"function f(m) { m = { A: 10 }; use(m); return m.A; }",
"function f(m) { m = { A: 10 }; m.A = 3; return m.A; }",
] {
testing::assert_contains(&transform(source), &["m = {", "m.A"], &[]);
}
}
}
+19 -3
View File
@@ -10,7 +10,9 @@
use std::rc::Rc;
use swc_core::ecma::ast::{AssignOp, Decl, Expr, Function, Id, Ident, Lit, Program, Stmt};
use swc_core::ecma::ast::{
AssignOp, BlockStmt, Decl, Expr, Function, Id, Ident, Lit, Program, Stmt,
};
use swc_core::ecma::visit::{VisitMut, VisitMutWith};
use super::analysis::hoisting::{self, Hoisted, Hoisting};
@@ -95,6 +97,10 @@ impl VisitMut for PropagateCopies<'_> {
hoisting::visit_mut_function(self, function);
}
fn visit_mut_block_stmt(&mut self, block: &mut BlockStmt) {
hoisting::visit_mut_block(self, block);
}
fn visit_mut_ident(&mut self, identifier: &mut Ident) {
hoisting::reference(self, identifier);
}
@@ -150,14 +156,19 @@ impl PropagateCopies<'_> {
}
/// Excludes regex literals, which have identity and state. A copied binding must already
/// hold its sole assigned value.
/// hold its only assigned value, or be a parameter whose argument is never overwritten.
fn is_stable(&self, value: &Expr) -> bool {
match value {
Expr::Lit(literal) => !matches!(literal, Lit::Regex(_)),
Expr::Tpl(template) => template.exprs.is_empty(),
Expr::Ident(identifier) => {
let id = identifier.to_id();
self.hoisting.facts.contains_key(&id) || self.functions.contains(&id)
let unchanged_parameter = self.bindings.is_parameter(&id)
&& self.bindings.write_count(&id) == 0
&& !self.bindings.is_mapped_parameter(&id);
self.hoisting.facts.contains_key(&id)
|| self.functions.contains(&id)
|| unchanged_parameter
}
_ => false,
}
@@ -189,6 +200,11 @@ mod tests {
// A read before the write keeps the binding.
let output = transform("function f(a) { use(a); a = 1; return a; }");
testing::assert_contains(&output, &["return 1;"], &["use(a); a = 1;"]);
// Parameters whose arguments are never overwritten.
let output = transform("function f(p, q) { var a, b; a = p; b = q; q = 1; return a + b; }");
testing::assert_contains(&output, &["return p + b;"], &[]);
let output = transform("function f(p) { var a; a = p; return a + arguments[0]; }");
testing::assert_contains(&output, &["return a + arguments[0];"], &[]);
}
#[test]
+112 -22
View File
@@ -1,5 +1,5 @@
//! Inlines calls to dispatchers whose first argument selects a return value through `if`,
//! `switch`, or nested blocks. Supports applied calls and operator expressions:
//! Inlines dispatcher calls by following `if`, `switch`, and nested blocks with known numeric
//! arguments. Handles applied calls, direct calls, and operator expressions:
//!
//! ```js
//! function b(n, f, args) {
@@ -7,15 +7,23 @@
//! case 973348: return Reflect.apply(f, undefined, args);
//! }
//! }
//! function c(n, m, f, x) { switch (n) { case 1: switch (m) { case 2: return f(x); } } }
//! function w(op, x, y) { if (op === 0) return x + y; else return x - y; }
//!
//! b(971996, encode, [payload]); // encode(payload)
//! c(1, 2, encode, payload); // encode(payload)
//! w(1, 630, 622); // 630 - 622
//! ```
//!
//! Requires a literal selector. Applied targets must be identifiers to preserve undefined
//! `this`. Operator arguments must have no side effects so repeated or reordered evaluation is
//! safe. `Reflect` and `undefined` must resolve to globals.
//! The first selector must be a literal. Applied and direct call targets must be identifiers to
//! keep `this` undefined. Direct calls must forward the remaining parameters in order, omitting
//! only numeric selectors. Operator arguments must have no side effects because they may be
//! evaluated repeatedly or in a different order. `Reflect` and `undefined` must refer to globals.
//!
//! The decoding pass only follows the first argument and leaves direct calls unchanged. This
//! preserves the dispatcher frames needed to recover click stacks.
use std::iter;
use swc_core::ecma::ast::{
BinaryOp, CallExpr, Callee, Expr, ExprOrSpread, FnDecl, Function, Id, Lit, Program, Stmt,
@@ -27,7 +35,24 @@ use super::analysis::{Analysis, Globals, effects, names};
use super::{HashMap, helper_objects};
use crate::js::ast;
/// Dispatcher patterns enabled for a pass.
#[derive(Clone, Copy, PartialEq, Eq)]
enum Reach {
/// Applied calls and operations selected by the first argument.
Decoding,
/// Also includes direct calls and selection by any numeric argument.
All,
}
pub(super) fn run(program: &mut Program, analysis: &mut Analysis) -> bool {
inline(program, analysis, Reach::Decoding)
}
pub(super) fn run_all(program: &mut Program, analysis: &mut Analysis) -> bool {
inline(program, analysis, Reach::All)
}
fn inline(program: &mut Program, analysis: &mut Analysis, reach: Reach) -> bool {
let globals = analysis.globals;
let bindings = analysis.bindings(program);
let mut functions = Functions::default();
@@ -41,6 +66,7 @@ pub(super) fn run(program: &mut Program, analysis: &mut Analysis) -> bool {
let mut inline = InlineDispatchers {
functions: &functions.0,
globals,
reach,
changed: false,
};
program.visit_mut_with(&mut inline);
@@ -107,16 +133,15 @@ fn may_select<'a>(statements: impl IntoIterator<Item = &'a Stmt>) -> bool {
false
}
/// Follows a function body for one known selector value.
struct Path<'body> {
selector: &'body Id,
value: f64,
/// Follows a function body for known numeric parameter values.
struct Path {
values: HashMap<Id, f64>,
}
impl<'body> Path<'body> {
impl Path {
/// Returns `Some(Some(value))` for a return with a value, `Some(None)` for normal
/// completion, and `None` for a path it cannot analyze.
fn run(
fn run<'body>(
&self,
statements: impl IntoIterator<Item = &'body Stmt>,
) -> Option<Option<&'body Expr>> {
@@ -190,11 +215,31 @@ impl<'body> Path<'body> {
fn number(&self, expression: &Expr) -> Option<f64> {
ast::fold_number(expression, &|leaf| {
(leaf.as_ident()?.to_id() == *self.selector).then_some(self.value)
self.values.get(&leaf.as_ident()?.to_id()).copied()
})
}
}
/// Returns parameter positions for the target and arguments of a call such as `target(a, b)`. Each
/// must refer to a parameter.
fn parameter_call(expression: &Expr, params: &[Id]) -> Option<Vec<usize>> {
let call = expression.as_call()?;
let arguments = call
.args
.iter()
.map(|arg| arg.spread.is_none().then_some(&*arg.expr));
iter::once(Some(&**call.callee.as_expr()?))
.chain(arguments)
.map(|expression| parameter_position(expression?, params))
.collect()
}
/// Returns the index in `params` of the parameter named by `expression`.
fn parameter_position(expression: &Expr, params: &[Id]) -> Option<usize> {
let id = expression.as_ident()?.to_id();
params.iter().position(|param| *param == id)
}
/// The parameter positions of `target` and `args` in `Reflect.apply(target, undefined, args)`.
struct ReflectApply {
target: usize,
@@ -202,10 +247,6 @@ struct ReflectApply {
}
fn reflect_apply(expression: &Expr, params: &[Id], globals: Globals) -> Option<ReflectApply> {
let position = |expression: &Expr| {
let id = expression.as_ident()?.to_id();
params.iter().position(|param| *param == id)
};
if let Some((reflect, [function, this, arguments])) = ast::method_call(expression, "apply")
&& reflect
.as_ident()
@@ -222,8 +263,8 @@ fn reflect_apply(expression: &Expr, params: &[Id], globals: Globals) -> Option<R
}
{
Some(ReflectApply {
target: position(&function.expr)?,
arguments: position(&arguments.expr)?,
target: parameter_position(&function.expr, params)?,
arguments: parameter_position(&arguments.expr, params)?,
})
} else {
None
@@ -243,6 +284,7 @@ fn is_operation(expression: &Expr, leaf: &impl Fn(&Expr) -> bool) -> bool {
struct InlineDispatchers<'functions> {
functions: &'functions HashMap<Id, Candidate>,
globals: Globals,
reach: Reach,
changed: bool,
}
@@ -252,16 +294,41 @@ impl InlineDispatchers<'_> {
if args.iter().any(|arg| arg.spread.is_some()) {
return None;
}
let Expr::Lit(Lit::Num(selector)) = &*args.first()?.expr else {
return None;
let number = |arg: &ExprOrSpread| match &*arg.expr {
Expr::Lit(Lit::Num(number)) => Some(number.value),
_ => None,
};
number(args.first()?)?;
let selectors = match self.reach {
Reach::Decoding => 1,
Reach::All => args.len(),
};
// Returns the selected expression only if choosing it requires constant selector
// comparisons with no other evaluation.
let path = Path {
selector: &candidate.params[0],
value: selector.value,
values: candidate
.params
.iter()
.zip(&args[..selectors])
.filter_map(|(param, arg)| Some((param.clone(), number(arg)?)))
.collect(),
};
let returned = path.run(&candidate.body)??;
if self.reach == Reach::All
&& let Some(positions) = parameter_call(returned, &candidate.params)
&& args.len() == candidate.params.len()
&& positions.is_sorted_by(|before, after| before < after)
&& (0..args.len())
.all(|index| positions.contains(&index) || number(&args[index]).is_some())
&& let [target, passed @ ..] = &positions[..]
&& args[*target].expr.is_ident()
{
return Some(Expr::Call(CallExpr {
callee: Callee::Expr(args[*target].expr.clone()),
args: passed.iter().map(|&index| args[index].clone()).collect(),
..Default::default()
}));
}
if let Some(apply) = reflect_apply(returned, &candidate.params, self.globals)
&& let Some(target) = args.get(apply.target)
&& target.expr.is_ident()
@@ -353,6 +420,29 @@ mod tests {
assert!(reassigned.contains("f(b("), "{reassigned}");
}
#[test]
fn calls_targets_selected_by_several_selectors_only_in_argument_order() {
let inline = |source: &str| testing::rewrite(source, super::run_all, /* fix= */ true);
let dispatchers = "function c(n, m, f, x, y) {
switch (n ^ 5) { case 1: switch (3 ^ m) { case 1: return f(x, y); } return; }
}
function d(n, f, x, y) { switch (n) { case 0: return f(y, x); } }";
let source = format!("{dispatchers} g(c(4, 2, encode, a(), b));");
let output = inline(&source);
assert!(output.contains("g(encode(a(), b))"), "{output}");
let decoding = testing::rewrite(&source, super::run, /* fix= */ true);
assert!(decoding.contains("g(c(4, 2,"), "{decoding}");
for call in [
"c(4, 2, o.encode, a, b)",
"c(4, 2, encode, a)",
"c(4, 1, encode, a, b)",
"d(0, encode, a, b)",
] {
let output = inline(&format!("{dispatchers} g({call});"));
assert!(output.contains(&format!("g({call})")), "{output}");
}
}
#[test]
fn inlines_selected_operations_through_switches_if_chains_and_xor_keys() {
let inline = |source: &str| testing::rewrite(source, super::run, /* fix= */ true);
+83 -1
View File
@@ -14,7 +14,7 @@
use base64::engine::general_purpose::STANDARD;
use swc_core::atoms::Wtf8Atom;
use swc_core::atoms::wtf8::Wtf8Buf;
use swc_core::ecma::ast::{BinaryOp, Expr, Id, Lit, Program, Str, VarDeclarator};
use swc_core::ecma::ast::{BinaryOp, Expr, Id, Lit, Program, Script, Str, VarDeclarator};
use swc_core::ecma::visit::{Visit, VisitMut, VisitMutWith, VisitWith};
use super::analysis::Analysis;
@@ -39,6 +39,72 @@ pub(super) fn run(program: &mut Program, analysis: &mut Analysis) -> bool {
!decode.decoded.is_empty()
}
/// A string decoder call with constant arguments in the original script, including the encoded
/// input, key, and decoded text.
pub(crate) struct Encoded {
pub(crate) encoded: String,
pub(crate) key: u16,
pub(crate) decoded: String,
}
/// Finds constant decoder calls in `script` before name resolution. Identifies decoders by their
/// declared names.
pub(crate) fn inline_strings(script: &Script) -> Vec<Encoded> {
struct Calls<'decoders> {
decoders: &'decoders HashMap<Id, u16>,
found: Vec<Encoded>,
}
impl Visit for Calls<'_> {
fn visit_expr(&mut self, expression: &Expr) {
if let Some((callee, [argument])) = ast::direct_call(expression)
&& argument.spread.is_none()
&& let Some(&key) = self.decoders.get(&callee.to_id())
&& let Some(encoded) = ast::static_str(&argument.expr)
&& let Some(decoded) = decode(encoded, key)
&& let Some(decoded) = decoded.as_str()
{
self.found.push(Encoded {
encoded: encoded.to_owned(),
key,
decoded: decoded.to_owned(),
});
}
expression.visit_children_with(self);
}
}
let mut decoders = Decoders::default();
script.visit_with(&mut decoders);
let mut calls = Calls {
decoders: &decoders.0,
found: Vec::new(),
};
script.visit_with(&mut calls);
calls.found
}
/// Encodes `text` so that [`decode`] with `key` returns it.
pub(crate) fn encode(text: &str, mut key: u16) -> String {
use base64::Engine;
let mut bytes = Vec::new();
let mut push = |byte: u8| {
key = key.rotate_left(8);
bytes.push(byte ^ (key >> 8) as u8);
};
for unit in text.encode_utf16() {
match u8::try_from(unit) {
Ok(byte) if byte != 255 => push(byte),
_ => {
let [low, high] = unit.to_le_bytes();
push(255);
push(low);
push(high);
}
}
}
STANDARD.encode(bytes)
}
/// Decodes `encoded` as the decoder holding `key` does, or `None` if it is not base64.
fn decode(encoded: &str, mut key: u16) -> Option<Wtf8Atom> {
use base64::Engine;
@@ -262,6 +328,22 @@ mod tests {
assert!(output.contains("decode(`ZJd1i3w=`)"), "{output}");
}
#[test]
fn finds_and_reencodes_the_strings_a_served_script_decodes() {
let source = format!("{DECODER}\nf(decode(`ZJd1i3w=`), decode('ZoZpiw=='), other(`x`));");
let parsed = crate::js::ast::parse_javascript("x.js", &source).unwrap();
let strings = super::inline_strings(&parsed.script);
let decoded: Vec<(&str, &str)> = strings
.iter()
.map(|string| (string.encoded.as_str(), string.decoded.as_str()))
.collect();
assert_eq!(decoded, [("ZJd1i3w=", "apply"), ("ZoZpiw==", "call")]);
assert_eq!(super::encode("apply", strings[0].key), "ZJd1i3w=");
// Code units of 255 or greater need an escape byte followed by two bytes.
let encoded = super::encode("a€", 59141);
assert_eq!(super::decode(&encoded, 59141).unwrap().as_str(), Some("a€"));
}
#[test]
fn decodes_escaped_code_units() {
use base64::Engine;
+70 -7
View File
@@ -16,16 +16,16 @@ use std::rc::Rc;
use swc_core::atoms::Atom;
use swc_core::common::SyntaxContext;
use swc_core::ecma::ast::{
AssignExpr, AssignOp, AssignTarget, CallExpr, Callee, Decl, Expr, ExprOrSpread, FnExpr,
ForStmt, Function, Id, Ident, Lit, MemberExpr, MemberProp, MetaPropExpr, Number, ObjectLit,
Program, ReturnStmt, SeqExpr, SimpleAssignTarget, Stmt, Super, ThisExpr, UnaryOp,
AssignExpr, AssignOp, AssignTarget, BlockStmt, CallExpr, Callee, Decl, Expr, ExprOrSpread,
FnExpr, ForStmt, Function, Id, Ident, Lit, MemberExpr, MemberProp, MetaPropExpr, Number,
ObjectLit, Program, ReturnStmt, SeqExpr, SimpleAssignTarget, Stmt, Super, ThisExpr, UnaryOp,
VarDeclOrExpr,
};
use swc_core::ecma::visit::{Visit, VisitMut, VisitMutWith, VisitWith};
use super::HashMap;
use super::analysis::effects::{self, Effects};
use super::analysis::hoisting::{self, HoistFacts, Hoisted, Hoisting};
use super::analysis::hoisting::{self, HoistFacts, Hoisted, Hoisting, List};
use super::analysis::{self, Analysis, Bindings, Globals, Properties, names};
use crate::js::ast;
@@ -220,10 +220,18 @@ impl VisitMut for InlineHelpers<'_> {
&& self.bindings.is_written_once(&target.to_id())
{
let target = target.to_id();
// Track object definitions, helper functions, and copies of known objects by
// binding.
let method = assignment
.right
.as_member()
.and_then(|member| self.stable(member))
.and_then(|(object, property)| object.functions.get(&property))
.cloned();
// Track object definitions, helper functions, and copies of objects and helper methods
// by binding.
let helpers = &mut self.hoisting.facts;
if let Some(object) = assignment.right.as_object() {
if let Some(method) = method {
helpers.functions.insert(target, Rc::new(method));
} else if let Some(object) = assignment.right.as_object() {
let properties = Rc::new(ObjectProperties::collect(object));
helpers.objects.insert(target, properties);
} else if let Some(function) = assignment.right.as_fn_expr() {
@@ -240,6 +248,21 @@ impl VisitMut for InlineHelpers<'_> {
fn visit_mut_stmts(&mut self, statements: &mut Vec<Stmt>) {
self.lists += 1;
let list = self.lists;
// Function declarations are available from the start of a function body. Top-level
// declarations can be replaced by other scripts.
if self.hoisting.list == List::FunctionBody {
for statement in statements.iter() {
if let Stmt::Decl(Decl::Fn(declaration)) = statement
&& self.bindings.is_written_once(&declaration.ident.to_id())
{
let function = Rc::new(FnExpr::from(declaration.function.clone()));
self.hoisting
.facts
.functions
.insert(declaration.ident.to_id(), function);
}
}
}
hoisting::visit_mut_stmts(self, statements, |inline, statement| {
inline.statement(statement, list);
});
@@ -249,6 +272,10 @@ impl VisitMut for InlineHelpers<'_> {
hoisting::visit_mut_function(self, function);
}
fn visit_mut_block_stmt(&mut self, block: &mut BlockStmt) {
hoisting::visit_mut_block(self, block);
}
fn visit_mut_ident(&mut self, identifier: &mut Ident) {
hoisting::reference(self, identifier);
}
@@ -763,6 +790,19 @@ mod tests {
);
let expected = ["((2)) + (1))", "Math.max((2))", "(3) + (4)", "read()]"];
testing::assert_contains(&output, &[], &expected);
// Function declarations inside function bodies are also stable; top-level declarations are
// not.
let output = transform(
"function f(x) { return g(x, 1); function g(a, b) { return a + b; } } \
function h(a) { return a; } k(h(2));",
);
testing::assert_contains(&output, &[], &["return ((x) + (1));", "k(h(2));"]);
// Copies of helper methods are stable too.
let output = transform(
"function f(h, m) { h = { shr: function (a, b) { return a >> b; } }; m = h.shr; \
return m(8, 1); }",
);
assert!(output.contains("(8) >> (1)"), "{output}");
}
#[test]
@@ -801,4 +841,27 @@ mod tests {
assert!(output.contains("s.n,"), "{output}");
assert_eq!(output.matches("h.re.test").count(), 2, "{output}");
}
/// A block function can run after the block references it or, in sloppy mode, after its
/// declaration exposes it to the enclosing function. Properties assigned before either point
/// are known.
#[test]
fn block_functions_see_properties_set_before_they_can_run() {
let output = transform(
r#"function f(h, p) { { h = {}; h.k = "v"; p = h; listen(g); function g(e) {
return e === p.k; } } }"#,
);
assert!(output.contains(r#"e === "v""#), "{output}");
// The function is referenced before its properties are assigned.
let output = transform(
r#"function f(h) { { listen(g); h = {}; h.k = "v"; function g(e) { return e === h.k; } } }"#,
);
assert!(output.contains("e === h.k"), "{output}");
// The declaration exposes the function to the enclosing scope before its properties are
// assigned.
let output = transform(
r#"function f(h) { { function g(e) { return e === h.k; } h = {}; h.k = "v"; } listen(g); }"#,
);
assert!(output.contains("e === h.k"), "{output}");
}
}
-161
View File
@@ -1,161 +0,0 @@
//! Inlines constant string-table reads through a single accessor:
//!
//! ```js
//! t = ["apply", "push"];
//! function a(i) { return t[i] }
//! a(1); // becomes "push"
//! ```
//!
//! Requires one assignment of a string-literal array and no table reads outside the accessor,
//! ensuring that entries remain unchanged.
use swc_core::ecma::ast::{Expr, FnDecl, Id, Lit, MemberProp, Program, Str, VarDeclarator};
use swc_core::ecma::visit::{Visit, VisitMut, VisitMutWith, VisitWith};
use super::analysis::Analysis;
use super::{HashMap, HashSet};
use crate::js::ast;
pub(super) fn run(program: &mut Program, analysis: &mut Analysis) -> bool {
let bindings = analysis.bindings(program);
let mut tables = Tables::default();
program.visit_with(&mut tables);
let mut changed = false;
for Accessor { accessor, table } in tables.accessors {
// The accessor's declaration is its only write.
if bindings.is_written_once(&accessor)
&& bindings.is_written_once(&table)
&& bindings.references(&table) == 1
&& let Some(strings) = tables.strings.get(&table)
{
let mut inline = InlineTable {
aliases: bindings.aliases(&accessor),
strings,
changed: false,
};
program.visit_mut_with(&mut inline);
changed |= inline.changed;
}
}
changed
}
/// Finds string tables and their accessor functions.
#[derive(Default)]
struct Tables {
accessors: Vec<Accessor>,
/// Bindings assigned string-literal arrays, paired with their contents.
strings: HashMap<Id, Vec<Str>>,
}
/// An accessor `function a(i) { return t[i] }`.
struct Accessor {
accessor: Id,
table: Id,
}
impl Tables {
fn record(&mut self, id: Id, value: &Expr) {
let strings: Option<Vec<Str>> = value.as_array().and_then(|array| {
array
.elems
.iter()
.map(|element| {
let element = element
.as_ref()
.filter(|element| element.spread.is_none())?;
Some(element.expr.as_lit()?.as_str()?.clone())
})
.collect()
});
if let Some(strings) = strings {
self.strings.insert(id, strings);
}
}
}
impl Visit for Tables {
fn visit_expr(&mut self, expression: &Expr) {
if let Some((id, value)) = ast::assignment(expression) {
self.record(id, value);
}
expression.visit_children_with(self);
}
fn visit_var_declarator(&mut self, declaration: &VarDeclarator) {
if let Some(id) = declaration.name.as_ident()
&& let Some(init) = &declaration.init
{
self.record(id.to_id(), init);
}
declaration.visit_children_with(self);
}
fn visit_fn_decl(&mut self, function: &FnDecl) {
if let [param] = function.function.params.as_slice()
&& let Some(param) = param.pat.as_ident()
&& let Some(Expr::Member(member)) = ast::returned(&function.function)
&& let MemberProp::Computed(index) = &member.prop
&& index.expr.as_ident().map(|id| id.to_id()) == Some(param.to_id())
&& let Some(table) = member.obj.as_ident()
{
self.accessors.push(Accessor {
accessor: function.ident.to_id(),
table: table.to_id(),
});
}
function.visit_children_with(self);
}
}
struct InlineTable<'table> {
aliases: HashSet<Id>,
strings: &'table [Str],
changed: bool,
}
impl VisitMut for InlineTable<'_> {
fn visit_mut_expr(&mut self, expression: &mut Expr) {
use swc_core::common::Spanned;
expression.visit_mut_children_with(self);
if let Some((callee, [index])) = ast::direct_call(expression)
&& self.aliases.contains(&callee.to_id())
&& index.spread.is_none()
&& let Some(index) = ast::index_literal(&index.expr)
&& let Some(string) = self.strings.get(index)
{
*expression = Expr::Lit(Lit::Str(Str {
span: expression.span(),
..string.clone()
}));
self.changed = true;
}
}
}
#[cfg(test)]
mod tests {
use crate::deobfuscate::testing;
#[test]
fn inlines_reads_only_from_tables_that_cannot_change_or_escape() {
let inline = |source: &str| testing::rewrite(source, super::run, /* fix= */ false);
let output = inline(
r#"var t; t = ["apply", "push"];
function a(i) { return t[i]; }
var b = a;
f(a(0), b(1), a(2), a(n));"#,
);
testing::assert_contains(&output, &[r#"f("apply", "push", a(2), a(n))"#], &[]);
for source in [
r#"var t = ["x"]; function a(i) { return t[i]; } t.push("y"); f(a(0));"#,
r#"var t = ["x"]; function a(i) { return t[i]; } t = ["y"]; f(a(0));"#,
r#"var t = ["x", g()]; function a(i) { return t[i]; } f(a(0));"#,
r#"var t = ["x"]; function a(i) { return t[i]; } a = h; f(a(0));"#,
] {
assert!(inline(source).contains("f(a(0))"), "{source}");
}
}
}
+23 -4
View File
@@ -1,15 +1,16 @@
//! Restores plain expressions from minifier forms:
//!
//! ```js
//! !0; void 0; (0, f)(x); // becomes true; undefined; f(x)
//! !0; void 0; (0, f)(x); (0, Date).now(); // becomes true; undefined; f(x); Date.now()
//! ```
//!
//! Folds `!` and `void` only for effect-free literal operands. Unwraps literal callee sequences
//! only when they end in an identifier other than `eval`, preserving call behavior. New
//! `undefined` references use the global resolution context.
//! only when the final value is an identifier other than `eval`, preserving call behavior. Also
//! simplifies literal sequences used for property access. New `undefined` references resolve to the
//! global binding.
use swc_core::ecma::ast::{
ArrayLit, Bool, Callee, Expr, Lit, ObjectLit, Program, UnaryExpr, UnaryOp,
ArrayLit, Bool, Callee, Expr, Lit, MemberExpr, ObjectLit, Program, UnaryExpr, UnaryOp,
};
use swc_core::ecma::visit::{VisitMut, VisitMutWith};
@@ -66,6 +67,19 @@ impl VisitMut for RestoreKeywords {
self.changed = true;
}
}
/// `(0, o).p` and `o.p` read the same property and preserve the same receiver when called.
fn visit_mut_member_expr(&mut self, member: &mut MemberExpr) {
member.visit_mut_children_with(self);
if let Expr::Seq(sequence) = member.obj.unwrap_parens_mut()
&& let [discarded @ .., _] = &sequence.exprs[..]
&& discarded.iter().all(|operand| operand.is_lit())
{
member.obj = sequence.exprs.pop().expect("the sequence is not empty");
self.changed = true;
}
}
}
/// Truthiness of a side-effect-free literal, or `None` if it is not one.
@@ -109,5 +123,10 @@ mod tests {
// Indirect calls of names other than `eval` become direct.
let output = transform("function f(g, o) { (0, g)(this, 1); (0, o.m)(); (0, eval)('x'); }");
testing::assert_contains(&output, &["g(this, 1);", "(0, o.m)();", "(0, eval)("], &[]);
// A property access uses the final value of the sequence as its object.
let output = transform(
"function f(o) { return [(0, Date).now(), (1, o).p, (0, o.a).push(1), (g(), o).q]; }",
);
testing::assert_contains(&output, &[], &["Date.now(), o.p, o.a.push(1), (g(), o).q"]);
}
}
+224
View File
@@ -0,0 +1,224 @@
//! Replaces cached strings and arrays of switch labels with their values:
//!
//! ```js
//! var cache, order;
//! f(cache || (cache = "apply")); // becomes f("apply")
//! f(option || cache || (cache = "apply")); // becomes f(option || "apply")
//! steps = order || (order = "1|0".split("|")); // becomes steps = "1|0".split("|")
//! ```
//!
//! The cache must be an uninitialized `var`, not a parameter. Every read and write must use
//! this pattern with the same value, except for resets to undefined. Replacing these
//! expressions leaves no reads of the cache.
//!
//! Splitting a string creates a new array on each evaluation instead of reusing one. This is
//! safe for the dispatchers that consume these arrays because they never modify them.
use swc_core::atoms::Wtf8Atom;
use swc_core::ecma::ast::{
BinExpr, BinaryOp, Expr, ExprOrSpread, Id, Ident, Program, UnaryOp, VarDeclarator,
};
use swc_core::ecma::visit::{Visit, VisitMut, VisitMutWith, VisitWith};
use super::analysis::{Analysis, Globals};
use super::{HashMap, HashSet};
use crate::js::ast;
pub(super) fn run(program: &mut Program, analysis: &mut Analysis) -> bool {
let mut caches = Caches {
globals: analysis.globals,
memoized: HashMap::default(),
resets: HashMap::default(),
uninitialized: HashSet::default(),
};
let bindings = analysis.bindings(program);
program.visit_with(&mut caches);
let constant: HashSet<Id> = caches
.memoized
.into_iter()
.filter(|(id, constants)| {
let count = constants.len();
let resets = caches.resets.get(id).copied().unwrap_or(0);
constants.iter().all(|constant| *constant == constants[0])
&& bindings.write_count(id) == count + resets
&& bindings.references(id) == count
&& caches.uninitialized.contains(id)
&& !bindings.is_parameter(id)
})
.map(|(id, _)| id)
.collect();
if constant.is_empty() {
return false;
}
program.visit_mut_with(&mut Inline(&constant));
true
}
/// A cached string or an array created by splitting a string.
#[derive(PartialEq)]
struct Constant {
string: Wtf8Atom,
separator: Option<Wtf8Atom>,
}
impl Constant {
fn of(value: &Expr) -> Option<Self> {
if let Some(string) = ast::static_wtf8(value) {
return Some(Self {
string: string.clone(),
separator: None,
});
}
let (
string,
[
ExprOrSpread {
spread: None,
expr: separator,
},
],
) = ast::method_call(value, "split")?
else {
return None;
};
Some(Self {
string: ast::static_wtf8(string)?.clone(),
separator: Some(ast::static_wtf8(separator)?.clone()),
})
}
}
/// Matches `[fallback ||] cache || (cache = value)`.
struct Memoized<'a> {
fallback: Option<&'a Expr>,
cache: &'a Ident,
value: &'a Expr,
constant: Constant,
}
impl<'a> Memoized<'a> {
fn of(expression: &'a Expr) -> Option<Self> {
let either = expression
.as_bin()
.filter(|either| either.op == BinaryOp::LogicalOr)?;
let (fallback, cache) = match either.left.unwrap_parens() {
Expr::Ident(cache) => (None, cache),
Expr::Bin(BinExpr {
op: BinaryOp::LogicalOr,
left,
right,
..
}) => (Some(&**left), right.unwrap_parens().as_ident()?),
_ => return None,
};
let (target, value) = ast::assignment(either.right.unwrap_parens())?;
if target != cache.to_id() {
return None;
}
Some(Self {
fallback,
cache,
value,
constant: Constant::of(value)?,
})
}
}
struct Caches {
globals: Globals,
/// Cached value for each matched expression.
memoized: HashMap<Id, Vec<Constant>>,
/// Number of resets to undefined for each binding, including `binding = void value`.
resets: HashMap<Id, usize>,
uninitialized: HashSet<Id>,
}
impl Visit for Caches {
fn visit_expr(&mut self, expression: &Expr) {
if let Some((id, value)) = ast::assignment(expression)
&& match value {
Expr::Unary(value) => value.op == UnaryOp::Void,
Expr::Ident(value) => self.globals.is(value, "undefined"),
_ => false,
}
{
*self.resets.entry(id).or_default() += 1;
}
if let Some(memoized) = Memoized::of(expression) {
let constants = self.memoized.entry(memoized.cache.to_id()).or_default();
constants.push(memoized.constant);
}
expression.visit_children_with(self);
}
fn visit_var_declarator(&mut self, declarator: &VarDeclarator) {
if declarator.init.is_none()
&& let Some(name) = declarator.name.as_ident()
{
self.uninitialized.insert(name.to_id());
}
declarator.visit_children_with(self);
}
}
/// Replaces memoized reads of the constant caches with their values.
struct Inline<'constant>(&'constant HashSet<Id>);
impl VisitMut for Inline<'_> {
fn visit_mut_expr(&mut self, expression: &mut Expr) {
expression.visit_mut_children_with(self);
let Some(memoized) =
Memoized::of(expression).filter(|memoized| self.0.contains(&memoized.cache.to_id()))
else {
return;
};
*expression = match memoized.fallback {
Some(fallback) => Expr::Bin(BinExpr {
span: memoized.cache.span,
op: BinaryOp::LogicalOr,
left: Box::new(fallback.clone()),
right: Box::new(memoized.value.clone()),
}),
None => memoized.value.clone(),
};
}
}
#[cfg(test)]
mod tests {
use crate::deobfuscate::testing;
#[test]
fn inlines_values_only_their_caches_hold() {
let output = testing::rewrite(
"(function(p) {
var a, b, c, d, e = 'x', o, p;
o = void 0; o = undefined;
f(a || (a = 'apply'), x || a || (a = 'apply'), o || (o = '1|0'.split('|')));
f(b || (b = 'one'), b || (b = 'two'));
f(c || (c = 'read'), c);
f(d || (d = 'written'));
d = other;
f(e || (e = 'initialized'));
f(p || (p = 'parameter'), ((q) => q || (q = 'arrow'))());
f(g || (g = 'global'));
})();",
super::run,
/* fix= */ true,
);
testing::assert_contains(
&output,
&[],
&[
"f('apply', x || 'apply', '1|0'.split('|'));",
"b || (b = 'one'), b || (b = 'two')",
"c || (c = 'read'), c",
"d || (d = 'written')",
"e || (e = 'initialized')",
"p || (p = 'parameter')",
"q || (q = 'arrow')",
"g || (g = 'global')",
],
);
}
}
+356
View File
@@ -0,0 +1,356 @@
//! Splits functions that the obfuscator merged behind a selector back into separate functions:
//!
//! ```js
//! function merged(selector, a) {
//! switch (selector ^ 5) {
//! case 1: return a + 1;
//! case 2: g(a); return;
//! }
//! }
//! merged(4, x); merged(7, y);
//! // becomes
//! function merged_0(a) { return a + 1; }
//! function merged_1(a) { g(a); return; }
//! merged_0(x); merged_1(y);
//! ```
//!
//! The function body must contain only a switch whose value depends solely on the first
//! parameter. Case labels must be constant, with no default. Each case must end in `return` or
//! `throw` and have no other jump out of the switch.
//!
//! Every reference must be a call with a literal selector that matches a case. Cases must not
//! use the selector, `arguments`, or declarations from another case. Each new function gets
//! separate bindings for the remaining parameters. Cases with no callers are removed.
use swc_core::common::{DUMMY_SP, Mark, SyntaxContext};
use swc_core::ecma::ast::{
BlockStmt, CallExpr, Callee, ClassDecl, Decl, Expr, FnDecl, Function, Id, Ident, Lit, Program,
Stmt, SwitchStmt, VarDeclarator,
};
use swc_core::ecma::visit::{Visit, VisitMut, VisitMutWith, VisitWith};
use super::analysis::{Analysis, Bindings, names};
use super::state_machines::escapes;
use super::{HashMap, HashSet};
use crate::js::ast;
pub(super) fn run(program: &mut Program, analysis: &mut Analysis) -> bool {
let bindings = analysis.bindings(program);
let mut merged = Merged {
bindings,
functions: HashMap::default(),
};
program.visit_with(&mut merged);
let mut calls = Calls {
functions: &merged.functions,
picked: HashMap::default(),
};
program.visit_with(&mut calls);
// Replacement function for each case selected by a call.
let mut splits: HashMap<Id, Vec<Option<Ident>>> = HashMap::default();
for (id, picked) in calls.picked {
let Some(picked) = picked.filter(|picked| picked.calls == bindings.references(&id)) else {
continue;
};
let context = SyntaxContext::empty().apply_mark(Mark::new());
let names: Vec<Option<Ident>> = (0..merged.functions[&id].labels.len())
.map(|index| {
picked
.cases
.contains(&index)
.then(|| Ident::new(format!("{}_{index}", id.0).into(), DUMMY_SP, context))
})
.collect();
splits.insert(id, names);
}
if splits.is_empty() {
return false;
}
program.visit_mut_with(&mut Unmerge {
functions: &merged.functions,
splits: &splits,
});
true
}
/// Maps selector values to cases in a merged function.
struct Selection {
selector: Id,
discriminant: Expr,
labels: Vec<f64>,
}
impl Selection {
/// Returns the case selected by `selector`.
fn case(&self, selector: f64) -> Option<usize> {
let value = ast::fold_number(&self.discriminant, &|leaf| {
(leaf.as_ident()?.to_id() == self.selector).then_some(selector)
})?;
self.labels.iter().position(|&label| label == value)
}
}
/// Finds merged function declarations.
struct Merged<'bindings> {
bindings: &'bindings Bindings,
functions: HashMap<Id, Selection>,
}
impl Merged<'_> {
fn selection(&self, function: &Function) -> Option<Selection> {
let selector = names::parameter_ids(&function.params)?.first()?.clone();
let [Stmt::Switch(switch)] = &function.body.as_ref()?.stmts[..] else {
return None;
};
// The discriminant is computed from the selector alone.
ast::fold_number(&switch.discriminant, &|leaf| {
(leaf.as_ident()?.to_id() == selector).then_some(0.0)
})?;
let labels = switch
.cases
.iter()
.map(|case| ast::fold_number(case.test.as_deref()?, &|_| None))
.collect::<Option<Vec<_>>>()?;
let separate = !function.is_async
&& !function.is_generator
&& names::mentions(&*switch.discriminant, std::slice::from_ref(&selector))
&& self.bindings.references(&selector) == 1
&& !names::uses_arguments(&switch.cases)
&& switch.cases.iter().all(|case| {
matches!(case.cons.last(), Some(Stmt::Return(_) | Stmt::Throw(_)))
&& !escapes(&case.cons)
})
&& independent(switch);
separate.then(|| Selection {
selector,
discriminant: (*switch.discriminant).clone(),
labels,
})
}
}
impl Visit for Merged<'_> {
fn visit_fn_decl(&mut self, declaration: &FnDecl) {
if self.bindings.is_written_once(&declaration.ident.to_id())
&& let Some(selection) = self.selection(&declaration.function)
{
self.functions.insert(declaration.ident.to_id(), selection);
}
declaration.visit_children_with(self);
}
}
/// Checks that no case refers to a binding declared in another case.
fn independent(switch: &SwitchStmt) -> bool {
let declared: Vec<Vec<Id>> = switch
.cases
.iter()
.map(|case| {
let mut declarations = Declarations::default();
case.cons.visit_with(&mut declarations);
declarations.0
})
.collect();
switch.cases.iter().enumerate().all(|(index, case)| {
declared
.iter()
.enumerate()
.all(|(other, ids)| other == index || !names::mentions(&case.cons, ids))
})
}
#[derive(Default)]
struct Declarations(Vec<Id>);
impl Visit for Declarations {
fn visit_var_declarator(&mut self, declarator: &VarDeclarator) {
self.0
.extend(swc_ecma_utils::find_pat_ids::<_, Id>(&declarator.name));
declarator.visit_children_with(self);
}
fn visit_fn_decl(&mut self, declaration: &FnDecl) {
self.0.push(declaration.ident.to_id());
declaration.visit_children_with(self);
}
fn visit_class_decl(&mut self, declaration: &ClassDecl) {
self.0.push(declaration.ident.to_id());
declaration.visit_children_with(self);
}
}
/// Finds the cases selected by calls to a merged function. Returns `None` if any reference is not a
/// direct call with a literal selector that matches a case.
#[derive(Default)]
struct Picked {
calls: usize,
cases: HashSet<usize>,
}
struct Calls<'functions> {
functions: &'functions HashMap<Id, Selection>,
picked: HashMap<Id, Option<Picked>>,
}
/// Extracts the function name and literal selector from `function(selector, ...)`.
fn selected_call(call: &CallExpr) -> Option<(Id, Option<f64>)> {
let callee = call.callee.as_expr()?.as_ident()?.to_id();
let spreads = call.args.iter().any(|argument| argument.spread.is_some());
let selector = match call.args.first().map(|first| &*first.expr) {
Some(Expr::Lit(Lit::Num(number))) if !spreads => Some(number.value),
_ => None,
};
Some((callee, selector))
}
impl Visit for Calls<'_> {
fn visit_call_expr(&mut self, call: &CallExpr) {
if let Some((id, selector)) = selected_call(call)
&& let Some(selection) = self.functions.get(&id)
{
let case = selector.and_then(|value| selection.case(value));
let picked = self
.picked
.entry(id)
.or_insert_with(|| Some(Picked::default()));
match (picked.as_mut(), case) {
(Some(picked), Some(case)) => {
picked.calls += 1;
picked.cases.insert(case);
}
_ => *picked = None,
}
}
call.visit_children_with(self);
}
}
/// Creates replacement functions for the cases of `declaration` listed in `names`.
fn split(declaration: FnDecl, names: &[Option<Ident>]) -> Vec<Stmt> {
let mut function = declaration.function;
let mut body = function.body.take().expect("checked when collected");
let Some(Stmt::Switch(switch)) = body.stmts.pop() else {
unreachable!("checked when collected");
};
let _selector = function.params.remove(0);
let mut functions = vec![];
for (case, name) in switch.cases.into_iter().zip(names) {
let Some(name) = name else { continue };
// Give each split function separate parameter bindings.
let context = SyntaxContext::empty().apply_mark(Mark::new());
let renamed: HashMap<Id, Ident> = function
.params
.iter()
.filter_map(|parameter| parameter.pat.as_ident())
.map(|parameter| {
let fresh = Ident::new(parameter.sym.clone(), parameter.span, context);
(parameter.to_id(), fresh)
})
.collect();
let mut rename = Rename(&renamed);
let mut separate = function.clone();
separate.params.visit_mut_with(&mut rename);
let mut stmts = case.cons;
stmts.visit_mut_with(&mut rename);
separate.body = Some(BlockStmt {
stmts,
..body.clone()
});
functions.push(Stmt::Decl(Decl::Fn(FnDecl {
ident: name.clone(),
declare: false,
function: separate,
})));
}
functions
}
struct Unmerge<'a> {
functions: &'a HashMap<Id, Selection>,
splits: &'a HashMap<Id, Vec<Option<Ident>>>,
}
impl VisitMut for Unmerge<'_> {
fn visit_mut_stmts(&mut self, statements: &mut Vec<Stmt>) {
statements.visit_mut_children_with(self);
let mut replaced = Vec::with_capacity(statements.len());
for statement in statements.drain(..) {
match statement {
Stmt::Decl(Decl::Fn(declaration))
if self.splits.contains_key(&declaration.ident.to_id()) =>
{
let names = &self.splits[&declaration.ident.to_id()];
replaced.extend(split(declaration, names));
}
statement => replaced.push(statement),
}
}
*statements = replaced;
}
fn visit_mut_call_expr(&mut self, call: &mut CallExpr) {
call.visit_mut_children_with(self);
if let Some((id, Some(selector))) = selected_call(call)
&& let Some(names) = self.splits.get(&id)
&& let Some(case) = self.functions[&id].case(selector)
&& let Some(Some(name)) = names.get(case)
{
call.callee = Callee::Expr(Box::new(Expr::Ident(name.clone())));
call.args.remove(0);
}
}
}
struct Rename<'a>(&'a HashMap<Id, Ident>);
impl VisitMut for Rename<'_> {
fn visit_mut_ident(&mut self, identifier: &mut Ident) {
if let Some(fresh) = self.0.get(&identifier.to_id()) {
*identifier = fresh.clone();
}
}
}
#[cfg(test)]
mod tests {
use crate::deobfuscate::testing;
#[test]
fn splits_cases_that_literal_selectors_pick() {
let transform = |source: &str| testing::rewrite(source, super::run, /* fix= */ true);
let merged = "function m(s, a) {
switch (s ^ 5) {
case 1: var x = a + 1; return x;
case 2: g(a); return;
case 3: dead(); return;
}
}";
let output = transform(&format!("{merged} h(m(4, p), m(7, q), m(4, r));"));
testing::assert_contains(
&output,
&[],
&[
"function m_0(a) { var x = a + 1; return x; }",
"function m_1(a) { g(a); return; }",
"h(m_0(p), m_1(q), m_0(r));",
],
);
testing::assert_lacks(&output, &["dead", "switch"]);
for kept in [
format!("{merged} h(m(4, p), m(9, q));"),
format!("{merged} h(m(s, p));"),
format!("{merged} h(m);"),
"function m(s, a) { switch (s) { case 1: var x = 1; return; case 2: return x; } } m(1, 2);"
.to_owned(),
"function m(s, a) { switch (s) { case 1: g(); case 2: return; } } m(1, 2);".to_owned(),
"function m(s, a) { switch (s) { case 1: return s; } } m(1, 2);".to_owned(),
"function m(s, a) { switch (s) { case 1: return arguments; } } m(1, 2);".to_owned(),
"function m(s, a) { switch (s) { case 1: return; default: return; } } m(1, 2);"
.to_owned(),
] {
let output = transform(&kept);
assert!(output.contains("switch"), "{output}");
}
}
}
+14 -10
View File
@@ -17,10 +17,10 @@ use swc_ecma_transforms::{fixer, hygiene};
use super::analysis::Analysis;
use super::{
HashMap, argument_arrays, bitwise, blocks, constant_objects, control_flow, copy_propagation,
dead_branches, dead_properties, dispatch, encoded_strings, function_lengths, helper_objects,
indexed_table, int32_helpers, literals, loops, scratch_parameters, statements, static_members,
string_array, unused_bindings,
HashMap, argument_arrays, arrow_blocks, bitwise, blocks, call_helpers, control_flow,
copy_propagation, dead_branches, dead_properties, dispatch, encoded_strings, function_lengths,
helper_objects, int32_helpers, literals, loops, memoized_strings, merged_functions,
register_arrays, state_machines, statements, static_members, unused_bindings,
};
/// Deobfuscated JavaScript with optional convergence diagnostics for the caller to report.
@@ -176,18 +176,22 @@ const DECODE_STEPS: &[Step] = &[
SIMPLIFY,
step("function lengths", function_lengths::run),
step("bitwise operands", bitwise::run),
step("constant objects", constant_objects::run),
step("dead branches", dead_branches::run),
// Recover tables.
step("encoded strings", encoded_strings::run),
step("string array", string_array::run),
step("indexed table", indexed_table::run),
step("memoized strings", memoized_strings::run),
step("argument arrays", argument_arrays::run),
step("dispatch", dispatch::run),
];
/// The steps that restructure the script once its tables are decoded.
const LATER_STEPS: &[Step] = &[
// Restore locals and method calls the obfuscator hides.
step("register arrays", register_arrays::run),
step("call helpers", call_helpers::run),
// Inline call dispatchers first. Splitting merged functions would turn them into forwarders.
step("call dispatchers", dispatch::run_all),
step("merged functions", merged_functions::run),
// Inline helpers, once unused scratch declarations no longer hide their returns.
UNUSED_BINDINGS,
STATIC_MEMBERS,
@@ -195,6 +199,8 @@ const LATER_STEPS: &[Step] = &[
STATIC_MEMBERS,
SIMPLIFY,
CONTROL_FLOW,
step("state machines", state_machines::run),
step("arrow blocks", arrow_blocks::run),
// Remove dead helpers.
HELPER_OBJECTS,
UNUSED_BINDINGS,
@@ -206,14 +212,12 @@ const LATER_STEPS: &[Step] = &[
step("literals", literals::run),
step("statements", statements::run),
FIX_PARENTHESES,
// Clean up locals. Propagate copies before narrowing parameters so unused parameters are
// removed instead of declared. The next round fixes parentheses.
// Clean up locals. The next round fixes parentheses.
step("blocks", blocks::run),
step("loops", loops::run),
step("copy propagation", copy_propagation::run),
// Run after copy propagation so the masks are constants.
step("int32 helpers", int32_helpers::run),
step("scratch parameters", scratch_parameters::run),
];
/// Guards against rewrites that keep undoing each other.
+519
View File
@@ -0,0 +1,519 @@
//! Replaces local array slots with separate variables when all accesses use constant indices:
//!
//! ```js
//! var r, a;
//! r = [void 0, void 0, void 0];
//! a = r[1] = f(); g(r[0]++); r[2] = h(); // becomes
//! var r_0, a;
//! a = f(); g(r_0++); h();
//! ```
//!
//! The array must be local to a function and assigned once from a literal without spreads.
//! That assignment must discard its value. All other uses must access constant indices within
//! bounds, without calling or deleting slots. Writes to unread slots keep only the assigned
//! expression so its side effects still run.
//!
//! Undefined slots need no assignment if the literal runs at most once per call, in the
//! declaring function and outside loops. The replacement locals already start undefined.
use swc_core::common::util::take::Take;
use swc_core::common::{DUMMY_SP, Mark, SyntaxContext};
use swc_core::ecma::ast::{
ArrayLit, ArrowExpr, AssignExpr, AssignOp, AssignTarget, BindingIdent, CallExpr, Callee,
Constructor, Expr, ExprStmt, ForStmt, Function, GetterProp, Id, Ident, MemberExpr, Pat,
Program, SeqExpr, SetterProp, SimpleAssignTarget, Stmt, TaggedTpl, UnaryExpr, UnaryOp,
VarDeclOrExpr, VarDeclarator,
};
use swc_core::ecma::visit::{Visit, VisitMut, VisitMutWith, VisitWith};
use super::analysis::{Analysis, Globals, effects};
use super::{HashMap, HashSet, removal};
use crate::js::ast;
pub(super) fn run(program: &mut Program, analysis: &mut Analysis) -> bool {
let globals = analysis.globals;
let bindings = analysis.bindings(program);
let mut uses = Uses {
globals,
created: HashMap::default(),
slots: HashMap::default(),
declared: HashMap::default(),
function: 0,
functions: 0,
loops: 0,
};
program.visit_with(&mut uses);
let mut arrays = HashMap::default();
for (id, created) in uses.created {
let slots = uses.slots.remove(&id).unwrap_or_default();
let [creation] = &created[..] else {
continue;
};
if creation.function == 0
|| uses.declared.get(&id) != Some(&creation.function)
|| bindings.write_count(&id) != 1
|| bindings.is_parameter(&id)
|| slots.opaque
|| slots.accesses != bindings.references(&id)
|| slots
.read
.iter()
.chain(&slots.written)
.any(|&slot| slot >= creation.length)
{
continue;
}
// Give each array a separate context so same-named arrays stay distinct until hygiene
// renames them.
let context = SyntaxContext::empty().apply_mark(Mark::new());
let locals: Vec<Option<Ident>> = (0..creation.length)
.map(|slot| {
let needed = slots.read.contains(&slot) || creation.defined.contains(&slot);
needed.then(|| Ident::new(format!("{}_{slot}", id.0).into(), DUMMY_SP, context))
})
.collect();
arrays.insert(
id,
Array {
locals,
read: slots.read,
// Replacement locals already start undefined on each call.
assign_undefined: !creation.once,
},
);
}
if arrays.is_empty() {
return false;
}
program.visit_mut_with(&mut Split {
arrays: &arrays,
globals,
});
true
}
/// Checks whether an element is undefined with no side effects: a hole, a side-effect-free `void`
/// expression, or global `undefined`.
fn is_undefined(element: Option<&Expr>, globals: Globals) -> bool {
match element {
None => true,
// Constant arithmetic has no side effects, even when nested.
Some(Expr::Unary(unary)) => {
unary.op == UnaryOp::Void
&& (ast::fold_number(&unary.arg, &|_| None).is_some()
|| !effects::may_have_effects(&unary.arg, globals))
}
Some(Expr::Ident(identifier)) => globals.is(identifier, "undefined"),
Some(_) => false,
}
}
fn undefined() -> Expr {
Expr::Unary(UnaryExpr {
span: DUMMY_SP,
op: UnaryOp::Void,
arg: 0.0.into(),
})
}
/// Extracts the array and constant index from `array[slot]`. Folds indices because the simplifier
/// leaves them unchanged in optional chains.
fn slot(member: &MemberExpr) -> Option<(Id, usize)> {
let index = &member.prop.as_computed()?.expr;
let slot = ast::array_index(ast::fold_number(index, &|_| None)?)?;
Some((member.obj.as_ident()?.to_id(), slot))
}
struct Creation {
length: usize,
/// Slots initialized to values other than undefined.
defined: HashSet<usize>,
function: usize,
/// Whether creation occurs outside loops and at most once per call of `function`.
once: bool,
}
#[derive(Default)]
struct Slots {
/// Number of constant-index accesses, for comparison with the total reference count.
accesses: usize,
/// Slots read, updated, or assigned with an operator other than `=`.
read: HashSet<usize>,
written: HashSet<usize>,
/// Whether a slot is called or deleted. These operations depend on the array itself.
opaque: bool,
}
/// Collects array assignments whose values are discarded, slot accesses, and the function declaring
/// each array binding.
struct Uses {
globals: Globals,
created: HashMap<Id, Vec<Creation>>,
slots: HashMap<Id, Slots>,
declared: HashMap<Id, usize>,
/// Current function number in traversal order; 0 denotes the script.
function: usize,
functions: usize,
loops: usize,
}
impl Uses {
fn create(&mut self, id: Id, array: &ArrayLit) {
let mut defined = HashSet::default();
for (slot, element) in array.elems.iter().enumerate() {
if element
.as_ref()
.is_some_and(|element| element.spread.is_some())
{
return;
}
if !is_undefined(element.as_ref().map(|element| &*element.expr), self.globals) {
defined.insert(slot);
}
}
let creation = Creation {
length: array.elems.len(),
defined,
function: self.function,
once: self.loops == 0,
};
self.created.entry(id).or_default().push(creation);
}
/// Records an array assignment whose value is discarded by a statement. Sequence expressions
/// handle their other operands separately.
fn statement(&mut self, expression: &Expr) {
let last = expression
.as_seq()
.and_then(|sequence| sequence.exprs.last());
self.discarded(last.map_or(expression, |last| &**last));
}
/// Records `binding = [...]`.
fn discarded(&mut self, expression: &Expr) {
if let Some((id, Expr::Array(array))) = ast::assignment(expression) {
self.create(id, array);
}
}
fn access(&mut self, member: &MemberExpr, read: bool) {
if let Some((id, slot)) = slot(member) {
let slots = self.slots.entry(id).or_default();
slots.accesses += 1;
if read {
slots.read.insert(slot);
} else {
slots.written.insert(slot);
}
}
}
fn opaque(&mut self, expression: &Expr) {
if let Some(member) = expression.unwrap_parens().as_member()
&& let Some((id, _)) = slot(member)
{
self.slots.entry(id).or_default().opaque = true;
}
}
fn in_function(&mut self, visit: impl FnOnce(&mut Self)) {
self.functions += 1;
let function = std::mem::replace(&mut self.function, self.functions);
let loops = std::mem::take(&mut self.loops);
visit(self);
self.function = function;
self.loops = loops;
}
fn in_loop(&mut self, visit: impl FnOnce(&mut Self)) {
self.loops += 1;
visit(self);
self.loops -= 1;
}
}
impl Visit for Uses {
fn visit_expr_stmt(&mut self, statement: &ExprStmt) {
self.statement(&statement.expr);
statement.visit_children_with(self);
}
fn visit_seq_expr(&mut self, sequence: &SeqExpr) {
if let [discarded @ .., _] = &sequence.exprs[..] {
for expression in discarded {
self.discarded(expression);
}
}
sequence.visit_children_with(self);
}
fn visit_var_declarator(&mut self, declarator: &VarDeclarator) {
if let Some(name) = declarator.name.as_ident() {
self.declared.insert(name.to_id(), self.function);
if let Some(Expr::Array(array)) = declarator.init.as_deref() {
self.create(name.to_id(), array);
}
}
declarator.visit_children_with(self);
}
fn visit_expr(&mut self, expression: &Expr) {
if let Expr::Member(member) = expression {
self.access(member, /* read= */ true);
}
expression.visit_children_with(self);
}
fn visit_assign_expr(&mut self, assignment: &AssignExpr) {
if let AssignTarget::Simple(SimpleAssignTarget::Member(member)) = &assignment.left {
self.access(member, assignment.op != AssignOp::Assign);
}
assignment.visit_children_with(self);
}
fn visit_call_expr(&mut self, call: &CallExpr) {
if let Callee::Expr(callee) = &call.callee {
self.opaque(callee);
}
call.visit_children_with(self);
}
fn visit_tagged_tpl(&mut self, template: &TaggedTpl) {
self.opaque(&template.tag);
template.visit_children_with(self);
}
fn visit_unary_expr(&mut self, unary: &UnaryExpr) {
if unary.op == UnaryOp::Delete {
self.opaque(&unary.arg);
}
unary.visit_children_with(self);
}
fn visit_function(&mut self, function: &Function) {
self.in_function(|uses| function.visit_children_with(uses));
}
fn visit_arrow_expr(&mut self, arrow: &ArrowExpr) {
self.in_function(|uses| arrow.visit_children_with(uses));
}
fn visit_constructor(&mut self, constructor: &Constructor) {
self.in_function(|uses| constructor.visit_children_with(uses));
}
fn visit_getter_prop(&mut self, getter: &GetterProp) {
self.in_function(|uses| getter.visit_children_with(uses));
}
fn visit_setter_prop(&mut self, setter: &SetterProp) {
self.in_function(|uses| setter.visit_children_with(uses));
}
/// A loop initializer runs once before the loop and discards its value.
fn visit_for_stmt(&mut self, statement: &ForStmt) {
if let Some(VarDeclOrExpr::Expr(init)) = &statement.init {
self.statement(init);
}
statement.init.visit_with(self);
self.in_loop(|uses| {
statement.test.visit_with(uses);
statement.update.visit_with(uses);
statement.body.visit_with(uses);
});
}
fn visit_stmt(&mut self, statement: &Stmt) {
if matches!(
statement,
Stmt::ForIn(_) | Stmt::ForOf(_) | Stmt::While(_) | Stmt::DoWhile(_)
) {
self.in_loop(|uses| statement.visit_children_with(uses));
} else {
statement.visit_children_with(self);
}
}
}
struct Array {
/// Replacement local for each slot that is read or initialized with a value.
locals: Vec<Option<Ident>>,
read: HashSet<usize>,
assign_undefined: bool,
}
struct Split<'arrays> {
arrays: &'arrays HashMap<Id, Array>,
globals: Globals,
}
impl Split<'_> {
/// Builds assignments to replacement locals for an array initialization.
fn initial(&self, array: &Array, literal: &mut ArrayLit) -> Vec<(Ident, Box<Expr>)> {
let mut assignments = vec![];
for (local, element) in array.locals.iter().zip(&mut literal.elems) {
let element = element.take().map(|element| element.expr);
if let Some(local) = local
&& (array.assign_undefined || !is_undefined(element.as_deref(), self.globals))
{
let value = element.unwrap_or_else(|| Box::new(undefined()));
assignments.push((local.clone(), value));
}
}
assignments
}
/// Replaces slot assignment targets in place. Returns a replacement expression for slot reads,
/// writes to unread slots, and array creation.
fn replacement(&self, expression: &mut Expr) -> Option<Expr> {
match expression {
Expr::Member(member) => {
let (id, slot) = slot(member)?;
let local = self.arrays.get(&id)?.locals.get(slot)?.clone()?;
Some(Expr::Ident(local))
}
Expr::Assign(assignment) => {
if let AssignTarget::Simple(SimpleAssignTarget::Member(member)) = &assignment.left {
let (id, slot) = slot(member)?;
let array = self.arrays.get(&id)?;
return match &array.locals[slot] {
Some(local) if array.read.contains(&slot) => {
assignment.left = AssignTarget::Simple(SimpleAssignTarget::Ident(
local.clone().into(),
));
None
}
_ => Some(*assignment.right.take()),
};
}
// The array binding is assigned only when the array is created.
let array = self.arrays.get(&assignment.left.as_ident()?.to_id())?;
let Expr::Array(literal) = &mut *assignment.right else {
return None;
};
let mut assignments: Vec<Box<Expr>> = self
.initial(array, literal)
.into_iter()
.map(|(local, value)| {
Box::new(Expr::Assign(AssignExpr {
span: DUMMY_SP,
op: AssignOp::Assign,
left: AssignTarget::Simple(SimpleAssignTarget::Ident(local.into())),
right: value,
}))
})
.collect();
Some(match assignments.len() {
0 => undefined(),
1 => *assignments.remove(0),
_ => Expr::Seq(SeqExpr {
span: assignment.span,
exprs: assignments,
}),
})
}
_ => None,
}
}
}
impl VisitMut for Split<'_> {
fn visit_mut_expr(&mut self, expression: &mut Expr) {
expression.visit_mut_children_with(self);
if let Some(replacement) = self.replacement(expression) {
*expression = replacement;
}
}
/// Removes `void 0` left by array creations that need no assignments.
fn visit_mut_stmts(&mut self, statements: &mut Vec<Stmt>) {
statements.visit_mut_children_with(self);
removal::remove_expr_stmts(statements, |expression| {
is_undefined(Some(expression), self.globals)
});
}
fn visit_mut_var_declarators(&mut self, declarators: &mut Vec<VarDeclarator>) {
declarators.visit_mut_children_with(self);
let mut split = Vec::with_capacity(declarators.len());
for mut declarator in declarators.drain(..) {
let Some(array) = declarator
.name
.as_ident()
.and_then(|name| self.arrays.get(&name.to_id()))
else {
split.push(declarator);
continue;
};
let mut initial: HashMap<Id, Box<Expr>> = match declarator.init.as_deref_mut() {
Some(Expr::Array(literal)) => self
.initial(array, literal)
.into_iter()
.map(|(local, value)| (local.to_id(), value))
.collect(),
_ => HashMap::default(),
};
split.extend(array.locals.iter().flatten().map(|local| VarDeclarator {
span: declarator.span,
name: Pat::Ident(BindingIdent::from(local.clone())),
init: initial.remove(&local.to_id()),
definite: false,
}));
}
*declarators = split;
}
}
#[cfg(test)]
mod tests {
use crate::deobfuscate::testing;
#[test]
fn splits_arrays_reached_only_through_constant_slots() {
let transform = |source: &str| testing::rewrite(source, super::run, /* fix= */ true);
let output = transform(
"function f(x) {
var r, a, s = [1, void 0];
r = [void 0, void (2 ^ (3 + (4 | (5 ^ (6 + 7))))), void 0];
a = r[1] = g(); g(r[0]++, s[0], s[1]); r[2] = h();
return function() { return r[0]; };
}",
);
testing::assert_contains(
&output,
&[],
&[
"var r_0, a, s_0 = 1, s_1;",
"a = g(); g(r_0++, s_0, s_1); h();",
"return r_0;",
],
);
testing::assert_lacks(&output, &["r_1", "r_2", "[", "void 0"]);
// A loop's initializer runs once.
let output = transform(
"function f() { var r, i; for (r = [void 0], i = 0; i < 2; i++) { h(r[0]); r[0] = i; } }",
);
testing::assert_contains(&output, &[], &["h(r_0);", "r_0 = i;"]);
testing::assert_lacks(&output, &["r_0 = void 0", "["]);
// A creation in a loop resets the slots on every iteration.
let output =
transform("function f() { var r; while (g()) { r = [void 0]; h(r[0]); r[0] = 1; } }");
testing::assert_contains(&output, &[], &["r_0 = void 0;", "h(r_0);", "r_0 = 1;"]);
for kept in [
"function f() { var r; r = [1]; g(r); }",
"function f() { var r; r = [1]; r[0](); }",
"function f() { var r; r = [1]; delete r[0]; }",
"function f() { var r; r = [1]; g(r[1]); }",
"function f() { var r; r = [1]; g(r[i]); }",
"function f() { var r; r = [1]; r = [2]; g(r[0]); }",
"function f() { var r; g(r = [1]); g(r[0]); }",
"function f(r) { var r; r = [1]; g(r[0]); }",
"function f() { var r; (function() { r = [1]; })(); g(r[0]); }",
"function f() { var r; r = [...a]; g(r[0]); }",
"var r; r = [1]; g(r[0]);",
] {
let output = transform(kept);
assert!(!output.contains("r_0"), "{output}");
}
}
}
-458
View File
@@ -1,458 +0,0 @@
//! Replaces trailing scratch parameters with local declarations:
//!
//! ```js
//! function f(a, b, c) { c = a + 1; return c; } // becomes function f(a) { var c; ... }
//! ```
//!
//! The obfuscator uses extra parameters as temporary variables. Converts them only when every
//! path assigns the parameter before reading its incoming value, and removes unused ones. This
//! changes the observable `fn.length`.
//!
//! If a function uses `arguments`, removes only unreferenced parameters unless an immediate
//! call proves that no argument reaches them. This preserves sloppy-mode aliasing between
//! parameters and `arguments[i]`.
use std::mem;
use swc_core::atoms::Atom;
use swc_core::common::DUMMY_SP;
use swc_core::ecma::ast::{
ArrowExpr, AssignExpr, AssignOp, BinExpr, CallExpr, Callee, CondExpr, Decl, Expr, Function, Id,
Ident, Pat, Program, Stmt, VarDecl, VarDeclKind, VarDeclarator,
};
use swc_core::ecma::visit::{Visit, VisitMut, VisitMutWith, VisitWith};
use super::HashSet;
use super::analysis::hoisting::{self, Hoisted, Hoisting};
use super::analysis::{Analysis, names};
pub(super) fn run(program: &mut Program, _: &mut Analysis) -> bool {
let mut demote = DemoteScratchParameters { changed: false };
program.visit_mut_with(&mut demote);
demote.changed
}
struct DemoteScratchParameters {
changed: bool,
}
impl VisitMut for DemoteScratchParameters {
fn visit_mut_function(&mut self, function: &mut Function) {
function.visit_mut_children_with(self);
if function.params.is_empty() {
return;
}
let scratch = Scratch::scan(function);
// Keep parameters through the last one whose incoming value can be observed. With
// mapped `arguments`, even a write can expose the parameter binding.
let needed =
if names::uses_arguments(&function.params) || names::uses_arguments(&function.body) {
&scratch.used
} else {
&scratch.observed
};
let keep = function
.params
.iter()
.rposition(|parameter| {
parameter
.pat
.as_ident()
.is_none_or(|name| needed.contains(&name.to_id()))
})
.map_or(0, |last| last + 1);
self.changed |= demote(function, keep, &scratch.used);
}
fn visit_mut_call_expr(&mut self, call: &mut CallExpr) {
call.visit_mut_children_with(self);
// An immediate anonymous-function call gives the argument count. Plain parameters
// beyond it start as `undefined`, matching replacement locals. Patterns may include
// defaults or rest parameters and need separate handling.
if let Callee::Expr(callee) = &mut call.callee
&& let Expr::Fn(callee) = callee.unwrap_parens_mut()
&& callee.ident.is_none()
&& call.args.iter().all(|argument| argument.spread.is_none())
&& callee
.function
.params
.iter()
.skip(call.args.len())
.all(|parameter| parameter.pat.is_ident())
{
let used = Scratch::scan(&callee.function).used;
self.changed |= demote(&mut callee.function, call.args.len(), &used);
}
}
}
/// Removes parameters starting at `keep`, declaring those `used` as locals. Returns whether
/// parameters were removed.
fn demote(function: &mut Function, keep: usize, used: &HashSet<Id>) -> bool {
if keep >= function.params.len() {
return false;
}
let declarators: Vec<VarDeclarator> = function
.params
.drain(keep..)
.filter_map(|parameter| match parameter.pat {
Pat::Ident(name) if used.contains(&name.to_id()) => Some(VarDeclarator {
span: DUMMY_SP,
name: Pat::Ident(name),
init: None,
definite: false,
}),
_ => None,
})
.collect();
if !declarators.is_empty()
&& let Some(body) = &mut function.body
{
// Insert after directives: moving `"use strict"` behind another statement would disable
// strict mode.
swc_ecma_utils::prepend_stmt(
&mut body.stmts,
Stmt::Decl(Decl::Var(Box::new(VarDecl {
kind: VarDeclKind::Var,
decls: declarators,
..Default::default()
}))),
);
}
true
}
/// Finds parameters that may be read before assignment. Tracks assignments along each path.
/// Assignments in optional or repeated paths are not guaranteed; branch joins keep only
/// assignments made on every path.
#[derive(Default)]
struct Scratch {
parameters: HashSet<Id>,
/// Read on some path before being assigned on it.
observed: HashSet<Id>,
/// Mentioned anywhere, and so still needing a binding.
used: HashSet<Id>,
/// The labelled statements around the node, innermost last.
labels: Vec<Label>,
/// Tracks parameters assigned on the path to the current node.
hoisting: Hoisting<HashSet<Id>>,
}
/// A labelled statement around the node being scanned.
struct Label {
name: Atom,
/// Intersection of assignments from all `break` paths seen so far; absent before the first
/// break.
broken: Option<HashSet<Id>>,
}
impl Scratch {
fn scan(function: &Function) -> Self {
let mut scratch = Self {
parameters: function
.params
.iter()
.filter_map(|parameter| Some(parameter.pat.as_ident()?.to_id()))
.collect(),
..Default::default()
};
if let Some(body) = &function.body {
scratch.hoisting.function_body = true;
scratch.statements(&body.stmts);
}
scratch
}
/// Scans statements and reports whether execution can continue after them. Visits hoisted
/// declarations even after a return or throw, using assignments guaranteed at every
/// possible call. See [`hoisting`].
fn statements(&mut self, statements: &[Stmt]) -> bool {
let mut reachable = true;
hoisting::visit_stmts(self, statements, |scratch, statement| {
reachable &= scratch.statement(statement);
});
reachable
}
/// Whether control can reach the statement after `statement`.
fn statement(&mut self, statement: &Stmt) -> bool {
match statement {
Stmt::Block(block) => self.statements(&block.stmts),
Stmt::Labeled(labeled) => {
self.labels.push(Label {
name: labeled.label.sym.clone(),
broken: None,
});
let flows = self.statement(&labeled.body);
let Label { broken, .. } = self.labels.pop().expect("the label was pushed above");
// A `break` leaves this statement and joins the normal fallthrough path.
match broken {
Some(broken) if flows => {
self.hoisting.facts.retain(|id| broken.contains(id));
true
}
Some(broken) => {
self.hoisting.facts = broken;
true
}
None => flows,
}
}
Stmt::Break(jump) => {
if let Some(label) = &jump.label
&& let Some(Label { broken, .. }) = self
.labels
.iter_mut()
.rev()
.find(|enclosing| enclosing.name == label.sym)
{
match broken {
Some(broken) => broken.retain(|id| self.hoisting.facts.contains(id)),
None => *broken = Some(self.hoisting.facts.clone()),
}
}
// An unlabelled `break` leaves a loop or `switch`, after which
// nothing they assign is known anyway.
false
}
Stmt::Return(_) | Stmt::Throw(_) | Stmt::Continue(_) => {
statement.visit_children_with(self);
false
}
Stmt::If(conditional) => {
conditional.test.visit_with(self);
let entry = self.hoisting.facts.clone();
let consequent = self.path(&entry, |scratch| scratch.statement(&conditional.cons));
let alternate = self.path(&entry, |scratch| {
conditional
.alt
.as_deref()
.is_none_or(|alternate| scratch.statement(alternate))
});
self.hoisting.facts = match (consequent.flows, alternate.flows) {
(true, false) => consequent.assigned,
(false, true) => alternate.assigned,
_ => &consequent.assigned & &alternate.assigned,
};
consequent.flows || alternate.flows
}
Stmt::Expr(_) | Stmt::Decl(_) | Stmt::Empty(_) | Stmt::Debugger(_) => {
statement.visit_children_with(self);
true
}
// The handler may start after any part of the block; the finalizer may start after
// any part of the block or handler. Both therefore use assignments known before the
// block.
Stmt::Try(statement) => {
self.fork(|scratch| statement.block.visit_with(scratch));
self.fork(|scratch| statement.handler.visit_with(scratch));
self.fork(|scratch| statement.finalizer.visit_with(scratch));
true
}
// Cases may be entered by a matching test or by fallthrough. Conservatively start
// each test and case with assignments known after the discriminant.
Stmt::Switch(switch) => {
switch.discriminant.visit_with(self);
for case in &switch.cases {
self.fork(|scratch| case.test.visit_with(scratch));
}
for case in &switch.cases {
self.fork(|scratch| case.cons.visit_with(scratch));
}
true
}
// The update can follow the body or a `continue`, so only assignments before the
// body are guaranteed.
Stmt::For(loop_) => {
self.fork(|scratch| {
loop_.init.visit_with(scratch);
loop_.test.visit_with(scratch);
scratch.fork(|scratch| _ = scratch.statement(&loop_.body));
loop_.update.visit_with(scratch);
});
true
}
// Likewise the test, which a `continue` jumps to.
Stmt::DoWhile(loop_) => {
self.fork(|scratch| {
scratch.fork(|scratch| _ = scratch.statement(&loop_.body));
loop_.test.visit_with(scratch);
});
true
}
// Other loops may execute an unknown number of times. Discard assignments made
// inside them.
statement => {
self.fork(|scratch| statement.visit_children_with(scratch));
true
}
}
}
/// Scans a path that may be skipped, keeping only what it reads.
fn fork(&mut self, scan: impl FnOnce(&mut Self)) {
let entry = self.hoisting.facts.clone();
scan(self);
self.hoisting.facts = entry;
}
/// Scans from `entry`.
fn path(&mut self, entry: &HashSet<Id>, scan: impl FnOnce(&mut Self) -> bool) -> Branch {
self.hoisting.facts.clone_from(entry);
let flows = scan(self);
Branch {
assigned: mem::take(&mut self.hoisting.facts),
flows,
}
}
}
/// What one branch of a conditional guarantees.
struct Branch {
/// Parameters the branch is guaranteed to assign.
assigned: HashSet<Id>,
/// Whether execution can fall through the branch.
flows: bool,
}
impl Visit for Scratch {
fn visit_stmt(&mut self, statement: &Stmt) {
self.statement(statement);
}
fn visit_stmts(&mut self, statements: &[Stmt]) {
self.statements(statements);
}
fn visit_ident(&mut self, identifier: &Ident) {
hoisting::reference(self, identifier);
let id = identifier.to_id();
if self.parameters.contains(&id) {
if !self.hoisting.facts.contains(&id) {
self.observed.insert(id.clone());
}
self.used.insert(id);
}
}
fn visit_assign_expr(&mut self, assignment: &AssignExpr) {
if assignment.op == AssignOp::Assign
&& let Some(target) = assignment.left.as_ident()
{
// The value is evaluated before the store, so it reads first.
assignment.right.visit_with(self);
let id = target.to_id();
if self.parameters.contains(&id) {
self.used.insert(id.clone());
self.hoisting.facts.insert(id);
}
} else {
assignment.visit_children_with(self);
}
}
fn visit_cond_expr(&mut self, conditional: &CondExpr) {
conditional.test.visit_with(self);
self.fork(|scratch| conditional.cons.visit_with(scratch));
self.fork(|scratch| conditional.alt.visit_with(scratch));
}
fn visit_bin_expr(&mut self, binary: &BinExpr) {
if binary.op.may_short_circuit() {
binary.left.visit_with(self);
self.fork(|scratch| binary.right.visit_with(scratch));
} else {
binary.visit_children_with(self);
}
}
/// A function expression's body uses assignments known when it was created. Declarations
/// use facts supplied by [`Scratch::statements`].
fn visit_function(&mut self, function: &Function) {
self.fork(|scratch| {
function.decorators.visit_with(scratch);
function.params.visit_with(scratch);
if let Some(body) = &function.body {
scratch.hoisting.function_body = true;
scratch.statements(&body.stmts);
}
});
}
fn visit_arrow_expr(&mut self, arrow: &ArrowExpr) {
self.fork(|scratch| arrow.visit_children_with(scratch));
}
}
impl Hoisted for Scratch {
type Facts = HashSet<Id>;
fn hoisting(&mut self) -> &mut Hoisting<HashSet<Id>> {
&mut self.hoisting
}
}
#[cfg(test)]
mod tests {
use crate::deobfuscate::testing;
#[test]
fn demotes_parameters_every_path_writes_first() {
let transform = |source: &str| testing::rewrite(source, super::run, /* fix= */ true);
let output = transform("function f(a, b, c, d) { c = a + 1; return c; }");
testing::assert_contains(&output, &["function f(a)", "var c;"], &[]);
assert!(!output.contains('d'), "{output}");
for source in [
"function f(x, a) { if (x) { a = 1; use(a); } else { for (a = 0; a < 2; a++) use(a); } }",
"function f(c, a) { l: { if (c) { a = 2; break l; } a = 1; } return a; }",
"function f(c, a) { try { a = 1; } catch (e) {} return; }",
"function f(a) { a = 1; g(); function g() { return a; } }",
] {
let output = transform(source);
assert!(output.contains("var a;"), "{source}: {output}");
}
// An immediate call leaves every parameter past its arguments unset.
let output = transform("(function (a, b, c) { g(b); b = 1; return a + b + c; })(x);");
testing::assert_contains(&output, &["function(a)", "var b, c;"], &[]);
}
#[test]
fn keeps_parameters_that_may_hold_an_argument() {
let transform = |source: &str| testing::rewrite(source, super::run, /* fix= */ true);
// Additional try, switch, label, and loop cases are covered in `tests/deobfuscate.rs`.
for source in [
"function f(a) { a = a || 1; return a; }",
"function f(a) { if (x) a = 1; return a; }",
"function f(a) { for(;;) a = 1; return a; }",
"function f(a) { x ? a = 1 : 0; return a; }",
"function f(a) { x && (a = 1); return a; }",
"function f(a) { g(); a = 1; function g() { return a; } }",
"function f(a) { g(a); a = 1; return a; }",
"function f(a) { h(); a = 1; function h() { return g(); } function g() { return a; } }",
] {
let output = transform(source);
assert!(output.contains("function f(a)"), "{source}: {output}");
}
// Functions using `arguments`.
let output = transform(
"function f(a, b) { b = 2; return arguments[1]; } \
function g(a, b) { b = 2; return () => arguments[1]; } \
function h(a, b) { b = 2; return function () { return arguments[0]; }; } \
function k(a, b, c) { return arguments.length; }",
);
testing::assert_contains(&output, &["function k()", "function f(a, b)"], &[]);
testing::assert_contains(&output, &["function g(a, b)", "function h()"], &[]);
// Patterns, defaults, and recursive calls that can fill a parameter.
let output = transform("function f(a, b = 1, { c }, ...d) { b = 2; return [a, b, c, d]; }");
testing::assert_contains(&output, &["function f(a, b = 1, { c }, ...d)"], &[]);
let output = transform("(function (a, b = 1, ...c) { return [a, b, c]; })(x);");
assert!(output.contains("function(a, b = 1, ...c)"), "{output}");
let output = transform("(function g(a, b) { return b ? a : g(a, 1); })(x);");
assert!(output.contains("function g(a, b)"), "{output}");
}
}
+215
View File
@@ -0,0 +1,215 @@
//! Restores blocks that a state machine runs in a fixed order:
//!
//! ```js
//! state = 1;
//! while (state !== -1) switch (state) {
//! case 0: b(); state = -1; break;
//! case 1: a(); state = 0; break;
//! }
//! // becomes
//! state = 1;
//! { a(); b(); }
//! ```
//!
//! The statement before the loop must set a constant initial state. Case labels must be
//! constant, with no default. Follow cases from the initial state to the exit state; each
//! must end by assigning a constant next state, and no case may repeat.
//!
//! Leave the loop unchanged if anything else reads the state or if a jump exits a case before
//! its final `break`.
use swc_core::ecma::ast::{
ArrowExpr, AssignOp, BinaryOp, BreakStmt, ContinueStmt, Expr, Function, Id, Program, Stmt,
SwitchStmt, WhileStmt,
};
use swc_core::ecma::visit::{Visit, VisitMut, VisitMutWith, VisitWith};
use super::HashSet;
use super::analysis::{Analysis, Bindings};
use crate::js::ast;
pub(super) fn run(program: &mut Program, analysis: &mut Analysis) -> bool {
let mut unroll = Unroll {
bindings: analysis.bindings(program),
changed: false,
};
program.visit_mut_with(&mut unroll);
unroll.changed
}
struct Unroll<'bindings> {
bindings: &'bindings Bindings,
changed: bool,
}
/// Returns the value assigned to `state` by `expression`, including chained assignments such as `x
/// = state = 1`.
fn assigned(expression: &Expr, state: &Id) -> Option<f64> {
let assignment = expression
.as_assign()
.filter(|assignment| assignment.op == AssignOp::Assign)?;
match assignment.left.as_ident() {
Some(left) if left.to_id() == *state => ast::number(&assignment.right),
_ => assigned(&assignment.right, state),
}
}
impl Unroll<'_> {
/// Returns the statements executed by `while (state !== exit) switch (state) { ... }`, in
/// execution order, starting with the state set by `initial`.
fn unrolled(&self, initial: &Stmt, machine: &Stmt) -> Option<Vec<Stmt>> {
let Stmt::While(WhileStmt { test, body, .. }) = machine else {
return None;
};
let test = test.unwrap_parens().as_bin()?;
if !matches!(test.op, BinaryOp::NotEqEq | BinaryOp::NotEq) {
return None;
}
let (state, exit) = match (test.left.as_ident(), test.right.as_ident()) {
(Some(state), None) => (state.to_id(), ast::number(&test.right)?),
(None, Some(state)) => (state.to_id(), ast::number(&test.left)?),
_ => return None,
};
let switch = match body.as_ref() {
Stmt::Switch(switch) => switch,
Stmt::Block(block) => match &block.stmts[..] {
[Stmt::Switch(switch)] => switch,
_ => return None,
},
_ => return None,
};
// Only the loop test and the switch read the state.
if switch.discriminant.unwrap_parens().as_ident()?.to_id() != state
|| self.bindings.references(&state) != 2
{
return None;
}
let mut current = assigned(&initial.as_expr()?.expr, &state)?;
let labels = switch
.cases
.iter()
.map(|case| ast::number(case.test.as_deref()?))
.collect::<Option<Vec<f64>>>()?;
let mut statements = vec![];
let mut seen = HashSet::default();
while current != exit {
let index = labels.iter().position(|&label| label == current)?;
if !seen.insert(index) {
return None;
}
let [
body @ ..,
Stmt::Expr(transition),
Stmt::Break(BreakStmt { label: None, .. }),
] = &switch.cases[index].cons[..]
else {
return None;
};
let (target, next) = ast::assignment(&transition.expr)?;
if target != state || escapes(body) {
return None;
}
current = ast::number(next)?;
statements.extend(body.iter().cloned());
}
Some(statements)
}
}
impl VisitMut for Unroll<'_> {
fn visit_mut_stmts(&mut self, statements: &mut Vec<Stmt>) {
statements.visit_mut_children_with(self);
for index in 1..statements.len() {
if let Some(unrolled) = self.unrolled(&statements[index - 1], &statements[index]) {
statements[index] = ast::block(unrolled);
self.changed = true;
}
}
}
}
/// Checks for a `break` or `continue` targeting an enclosing loop or switch.
pub(super) fn escapes(body: &[Stmt]) -> bool {
let mut jumps = Jumps::default();
body.visit_with(&mut jumps);
jumps.escapes
}
/// Finds unlabeled jumps not caught by a nested loop or switch.
#[derive(Default)]
struct Jumps {
loops: usize,
switches: usize,
escapes: bool,
}
impl Visit for Jumps {
fn visit_stmt(&mut self, statement: &Stmt) {
let depth = usize::from(matches!(
statement,
Stmt::For(_) | Stmt::ForIn(_) | Stmt::ForOf(_) | Stmt::While(_) | Stmt::DoWhile(_)
));
self.loops += depth;
statement.visit_children_with(self);
self.loops -= depth;
}
fn visit_break_stmt(&mut self, jump: &BreakStmt) {
self.escapes |= jump.label.is_none() && self.loops == 0 && self.switches == 0;
}
fn visit_continue_stmt(&mut self, jump: &ContinueStmt) {
self.escapes |= jump.label.is_none() && self.loops == 0;
}
fn visit_switch_stmt(&mut self, switch: &SwitchStmt) {
self.switches += 1;
switch.visit_children_with(self);
self.switches -= 1;
}
// Jumps cannot leave a function.
fn visit_function(&mut self, _: &Function) {}
fn visit_arrow_expr(&mut self, _: &ArrowExpr) {}
}
#[cfg(test)]
mod tests {
use crate::deobfuscate::testing;
#[test]
fn unrolls_constant_transitions_from_the_initial_state() {
let transform = |source: &str| testing::rewrite(source, super::run, /* fix= */ true);
let machine = |cases: &str, after: &str| {
format!(
"function f() {{ var s, k; k = s = 2; while (-1 !== s) switch (s) {{ {cases} }} {after} }}"
)
};
let output = transform(&machine(
"case 0: c(); s = -1; break;
case 1: for (;;) { if (d()) break; continue; } s = 0; break;
case 2: a(); s = 1; break;
case 3: dead(); s = 0; break;",
"",
));
testing::assert_contains(&output, &[], &["k = s = 2; { a(); for(;;)"]);
testing::assert_lacks(&output, &["switch", "dead", "s = 1", "s = -1"]);
for kept in [
// Reject cycles, missing cases, early breaks, continues, and extra reads of the state.
machine("case 2: a(); s = 2; break;", ""),
machine("case 2: a(); s = 4; break;", ""),
machine("case 2: if (a()) break; s = -1; break;", ""),
machine("case 2: if (a()) continue; s = -1; break;", ""),
machine("case 2: a(); s = -1; break;", "g(s);"),
machine(
"case 2: a(); s = b() ? 0 : -1; break; case 0: s = -1; break;",
"",
),
machine("case 2: a(); s = -1; break; default: b();", ""),
] {
let output = transform(&kept);
assert!(output.contains("switch"), "{output}");
}
}
}
+41 -2
View File
@@ -13,8 +13,8 @@ use std::mem;
use swc_core::common::Span;
use swc_core::common::util::take::Take;
use swc_core::ecma::ast::{
AssignOp, BinaryOp, CondExpr, Expr, IfStmt, LabeledStmt, Lit, Program, ReturnStmt, Stmt,
ThrowStmt, UnaryExpr, UnaryOp, VarDeclOrExpr,
AssignOp, BinaryOp, CondExpr, Decl, Expr, IfStmt, LabeledStmt, Lit, Program, ReturnStmt, Stmt,
ThrowStmt, UnaryExpr, UnaryOp, VarDeclKind, VarDeclOrExpr,
};
use swc_core::ecma::visit::{VisitMut, VisitMutWith};
@@ -237,6 +237,26 @@ impl ExpandStatements {
(prefix, statement.discriminant) = self.split_sequence(statement.discriminant);
Stmt::Switch(statement)
}
// In `var name = (first(), value)`, `first()` runs before the value is stored. Moving
// it before earlier uninitialized `var` declarations is safe because those declarations
// do nothing: `var a, b = (a = f(), v)`. This would be unsafe with `let` or `const`,
// because `a` would not yet be initialized.
Stmt::Decl(Decl::Var(mut declaration)) => {
let storing = match declaration.kind {
VarDeclKind::Var => declaration
.decls
.iter()
.position(|declarator| declarator.init.is_some()),
VarDeclKind::Let | VarDeclKind::Const => Some(0),
};
if let Some(declarator) = storing.and_then(|at| declaration.decls.get_mut(at))
&& let Some(init) = &mut declarator.init
&& !ends_with_anonymous_function(init)
{
(prefix, *init) = self.split_sequence(init.take());
}
Stmt::Decl(Decl::Var(declaration))
}
Stmt::For(mut statement) => {
statement.init = match statement.init.take() {
Some(VarDeclOrExpr::Expr(initializer)) => {
@@ -320,6 +340,25 @@ mod tests {
"b = obj.x; first(); a = b + 1;",
],
);
// The sequence in the first initializer runs before the value is stored.
let output = transform(
"function f() { var v = (first(), flag && second(), value), w = (third(), more); \
var g = (effect(), function () {}); }",
);
testing::assert_contains(
&output,
&["w = (third(), more)", "g = (effect(), function() {})"],
&["first(); if (flag) { second(); } var v = value"],
);
// Earlier uninitialized `var` declarations have no effect.
let output = transform(
"function f() { var a, b = (a = first(), value); let c, d = (c = second(), other); }",
);
testing::assert_contains(
&output,
&["d = (c = second(), other)"],
&["a = first(); var a, b = value;"],
);
let output = transform(
"function f() { for (start(), setup(); test(), ready; tick(), step()) body(); \
outer: inner: for (init(), reset(); check(); next()) { continue outer; } \
+26 -4
View File
@@ -1,13 +1,15 @@
//! Replaces computed properties with dot accesses:
//! Converts constant property accesses to dot notation and constant object keys to named keys:
//!
//! ```js
//! console["log"]; // becomes console.log
//! console["log"]; // becomes console.log
//! h = { ["add"]: f }; // becomes h = { add: f }
//! ```
//!
//! Accepts string literals and templates without substitutions only when the value is a valid
//! identifier. Both forms then access the same property.
//! identifier. Both forms access the same property. A computed `__proto__` key stays computed: it
//! defines a property, while a named key sets the prototype.
use swc_core::ecma::ast::{IdentName, MemberExpr, MemberProp, Program};
use swc_core::ecma::ast::{IdentName, MemberExpr, MemberProp, Program, Prop, PropName};
use swc_core::ecma::visit::{VisitMut, VisitMutWith};
use super::analysis::Analysis;
@@ -35,6 +37,20 @@ impl VisitMut for NameStaticMembers {
self.changed = true;
}
}
fn visit_mut_prop(&mut self, property: &mut Prop) {
property.visit_mut_children_with(self);
if let Prop::KeyValue(property) = property
&& let PropName::Computed(key) = &property.key
&& let Some(name) = ast::static_str(&key.expr)
&& swc_ecma_utils::is_valid_ident(name)
&& name != "__proto__"
{
property.key = PropName::Ident(IdentName::new(name.into(), key.span));
self.changed = true;
}
}
}
#[cfg(test)]
@@ -47,5 +63,11 @@ mod tests {
testing::transform(r#"obj[`lo\u0067`](); obj?.[`name`]; obj[`a-b`]; obj[`${key}`];"#);
let expected = ["obj.log()", "obj?.name", "obj[`a-b`]", "obj[`${key}`]"];
testing::assert_contains(&output, &expected, &[]);
let output = testing::transform(r#"f({ ["add"]: 1, [`a-b`]: 2, ["__proto__"]: 3 });"#);
testing::assert_contains(
&output,
&[],
&["add: 1", "[`a-b`]: 2", r#"["__proto__"]: 3"#],
);
}
}
-736
View File
@@ -1,736 +0,0 @@
//! Decodes the obfuscator's string table:
//!
//! ```js
//! decoder(23); // becomes "message"
//! ```
//!
//! Recognizes the [`Table`] and solves its checksum rotation ([`Rotations`]) without executing
//! JavaScript, then replaces constant-index calls through decoders, aliases, and wrappers.
//! Removes decoding code only when no references remain. Unsupported setups stay unchanged.
use std::iter;
use swc_core::atoms::Wtf8Atom;
use swc_core::atoms::wtf8::{CodePoint, Wtf8Buf};
use swc_core::common::Span;
use swc_core::ecma::ast::{
BinaryOp, CallExpr, Callee, Decl, Expr, ExprOrSpread, FnDecl, Function, Id, Lit, MemberProp,
Null, Program, Stmt, Str, VarDeclOrExpr, VarDeclarator,
};
use swc_core::ecma::visit::{Visit, VisitMut, VisitMutWith, VisitWith};
use super::analysis::{Analysis, Bindings, names};
use super::{HashMap, HashSet, removal};
use crate::js::{self, ast};
/// Decodes supported string tables one at a time.
pub(super) fn run(program: &mut Program, analysis: &mut Analysis) -> bool {
let mut bindings = analysis.bindings(program);
let mut updated = None;
let mut tried = HashSet::default();
let mut changed = false;
while let Some(plan) = Plan::next(program, bindings, &mut tried) {
if plan.apply(program) {
changed = true;
// Analyze subsequent tables against the updated program.
bindings = updated.insert(Bindings::collect(program));
}
}
changed
}
/// Information collected before modifying a string table, sufficient to decode it.
struct Plan {
/// The table, already rotated the way the setup leaves it.
table: Table,
/// The decoder and every binding that only ever holds it.
aliases: HashSet<Id>,
/// Wrapper functions indexed by every binding that names them.
wrappers: HashMap<Id, Wrapper>,
/// The call that rotates the table at runtime.
setup: Span,
}
impl Plan {
/// Finds the first untried decodable table in source order. Requires one setup with a
/// solvable rotation.
fn next(program: &Program, bindings: &Bindings, tried: &mut HashSet<Id>) -> Option<Self> {
let mut functions = Functions::default();
program.visit_with(&mut functions);
let mut candidates: Vec<&FnDecl> = functions.0.values().collect();
candidates.sort_by_key(|function| function.function.span.lo);
for function in candidates {
let Some(mut table) = Table::discover(function, &functions.0, bindings) else {
continue;
};
// The decoder's declaration must be its only write.
if !bindings.is_written_once(&table.decoder) || !tried.insert(table.decoder.clone()) {
continue;
}
let aliases = bindings.aliases(&table.decoder);
let mut rotations = Rotations {
table: &table,
aliases: &aliases,
bindings,
matches: vec![],
};
program.visit_with(&mut rotations);
let [setup] = rotations.matches[..] else {
continue;
};
table.strings.rotate_left(setup.rotation);
let wrappers = Wrapper::discover(&functions.0, &aliases, bindings);
return Some(Self {
table,
aliases,
wrappers,
setup: setup.call,
});
}
None
}
/// Decodes every constant call, then removes the table machinery if nothing refers to it.
fn apply(&self, program: &mut Program) -> bool {
let mut decoder = DecodeStrings {
plan: self,
changed: false,
};
program.visit_mut_with(&mut decoder);
// Try cleanup before deciding whether dynamic calls or escaped aliases still require
// the runtime decoder.
let mut cleaned = program.clone();
cleaned.visit_mut_with(&mut Cleanup(self));
let remaining = Bindings::collect(&cleaned);
if iter::once(&self.table.provider)
.chain(&self.aliases)
.any(|id| remaining.references(id) > 0)
{
return decoder.changed;
}
*program = cleaned;
true
}
/// Returns the constant decoder index for `callee(args)`, if known.
fn index(&self, callee: &Id, args: &[ExprOrSpread]) -> Option<f64> {
if args.iter().any(|argument| argument.spread.is_some()) {
return None;
}
if self.aliases.contains(callee) {
match args {
[argument] => ast::number(&argument.expr),
_ => None,
}
} else {
self.wrappers.get(callee)?.index(args)
}
}
/// Whether `function` declares the decoder or the provider.
fn is_machinery(&self, function: &FnDecl) -> bool {
let id = function.ident.to_id();
id == self.table.decoder || id == self.table.provider
}
fn is_setup_call(&self, expression: &Expr) -> bool {
matches!(expression, Expr::Call(call) if call.span == self.setup)
}
}
/// `alias = other`, copying one decoder alias into another.
fn is_alias_copy(expression: &Expr, aliases: &HashSet<Id>) -> bool {
ast::assignment(expression).is_some_and(|(id, value)| {
aliases.contains(&id)
&& value
.as_ident()
.is_some_and(|id| aliases.contains(&id.to_id()))
})
}
/// Collects single-return function declarations by binding. Decoders, providers, and wrappers
/// share this form; avoid cloning larger functions.
#[derive(Default)]
struct Functions(HashMap<Id, FnDecl>);
impl Visit for Functions {
fn visit_fn_decl(&mut self, function: &FnDecl) {
if ast::returned(&function.function).is_some() {
self.0.insert(function.ident.to_id(), function.clone());
}
function.visit_children_with(self);
}
}
/// Recognizes wrappers such as `function w(i, o, d) { return d = decoder, d(i + o) }`. Extra
/// decoder arguments must be literals that the decoder overwrites before reading them.
#[derive(Clone)]
struct Wrapper {
params: Vec<Id>,
index: Expr,
}
impl Wrapper {
/// Every binding that names a wrapper, mapped to that wrapper.
#[must_use]
fn discover(
functions: &HashMap<Id, FnDecl>,
decoders: &HashSet<Id>,
bindings: &Bindings,
) -> HashMap<Id, Self> {
let mut wrappers = HashMap::default();
for (id, function) in functions {
if bindings.is_written_once(id)
&& let Some(wrapper) = Self::recognize(&function.function, decoders)
{
for alias in bindings.aliases(id) {
wrappers.insert(alias, wrapper.clone());
}
}
}
wrappers
}
fn recognize(function: &Function, decoders: &HashSet<Id>) -> Option<Self> {
let params = names::parameter_ids(&function.params)?;
// Either `return decoder(...)` or `return local = decoder, local(...)`.
let is_decoder = |expression: &Expr| {
expression
.as_ident()
.is_some_and(|id| decoders.contains(&id.to_id()))
};
if let Some((local, call)) = match ast::returned(function)? {
Expr::Seq(sequence)
if let [binding, call] = sequence.exprs.as_slice()
&& let Some((local, decoder)) = ast::assignment(binding)
&& params.contains(&local)
&& is_decoder(decoder) =>
{
Some((Some(local), &**call))
}
Expr::Seq(_) => None,
call => Some((None, call)),
} && let Some((callee, [index, extra @ ..])) = ast::direct_call(call)
&& (local.as_ref() == Some(&callee.to_id()) || decoders.contains(&callee.to_id()))
&& index.spread.is_none()
&& extra
.iter()
.all(|argument| argument.spread.is_none() && matches!(*argument.expr, Expr::Lit(_)))
{
Some(Self {
params,
index: (*index.expr).clone(),
})
} else {
None
}
}
/// Resolves the decoder index selected by these literal arguments.
#[must_use]
fn index(&self, args: &[ExprOrSpread]) -> Option<f64> {
let values: HashMap<Id, f64> = self
.params
.iter()
.zip(args)
.map(|(param, argument)| Some((param.clone(), ast::number(&argument.expr)?)))
.collect::<Option<_>>()?;
ast::fold_number(&self.index, &|leaf| {
values.get(&leaf.as_ident()?.to_id()).copied()
})
}
}
/// Replaces constant-index calls to decoder aliases or wrappers with decoded strings. Leaves
/// the decoder, provider, and setup for [`Cleanup`].
struct DecodeStrings<'plan> {
plan: &'plan Plan,
changed: bool,
}
impl VisitMut for DecodeStrings<'_> {
fn visit_mut_fn_decl(&mut self, function: &mut FnDecl) {
if !self.plan.is_machinery(function) {
function.visit_mut_children_with(self);
}
}
fn visit_mut_expr(&mut self, expression: &mut Expr) {
if self.plan.is_setup_call(expression) {
return;
}
expression.visit_mut_children_with(self);
if let Some((callee, args)) = ast::direct_call(expression)
&& let Some(index) = self.plan.index(&callee.to_id(), args)
&& let Some(value) = self.plan.table.lookup(index, 0)
{
*expression = Expr::Lit(Lit::Str(Str {
span: callee.span,
value,
raw: None,
}));
self.changed = true;
}
}
}
/// Removes the decoder, the provider, the setup call, and copies between decoder aliases.
struct Cleanup<'plan>(&'plan Plan);
impl Cleanup<'_> {
fn is_setup(&self, expression: &Expr) -> bool {
self.0.is_setup_call(expression) || is_alias_copy(expression, &self.0.aliases)
}
}
impl VisitMut for Cleanup<'_> {
fn visit_mut_stmts(&mut self, statements: &mut Vec<Stmt>) {
removal::retain(
statements,
|statement| !matches!(statement, Stmt::Decl(Decl::Fn(function)) if self.0.is_machinery(function)),
);
removal::remove_expr_stmts(statements, |expression| self.is_setup(expression));
statements.visit_mut_children_with(self);
}
fn visit_mut_var_declarator(&mut self, declaration: &mut VarDeclarator) {
let aliases = &self.0.aliases;
if declaration
.name
.as_ident()
.is_some_and(|id| aliases.contains(&id.to_id()))
&& declaration
.init
.as_deref()
.and_then(Expr::as_ident)
.is_some_and(|id| aliases.contains(&id.to_id()))
{
// Retain the binding (including const's required initializer).
declaration.init = Some(Box::new(Expr::Lit(Lit::Null(Null {
span: declaration.span,
}))));
}
declaration.visit_mut_children_with(self);
}
fn visit_mut_expr(&mut self, expression: &mut Expr) {
expression.visit_mut_children_with(self);
if let Expr::Seq(sequence) = expression {
// The last operand supplies the sequence's value; only drop discarded values.
if let Some(last) = sequence.exprs.pop() {
removal::retain(&mut sequence.exprs, |expression| !self.is_setup(expression));
sequence.exprs.push(last);
}
if sequence.exprs.len() == 1 {
*expression = *sequence.exprs.remove(0);
}
}
}
}
/// A string table, its decoder, and the provider function that builds it.
struct Table {
decoder: Id,
provider: Id,
offset: f64,
strings: Vec<Wtf8Atom>,
/// Whether the decoder reverses each entry with `Array.from(value).reverse().join('')`.
reversed: bool,
}
impl Table {
/// Recognizes two decoder layouts:
///
/// ```js
/// function d(i, a, v) { return i = i - 21, a = provider(), v = a[i], v }
/// function d(i, v) { return i = i - 21, v = strings[i], Array.from(v).reverse().join('') }
/// ```
///
/// The second requires `strings` to be assigned `provider()` exactly once.
#[must_use]
fn discover(
function: &FnDecl,
functions: &HashMap<Id, FnDecl>,
bindings: &Bindings,
) -> Option<Self> {
if let Some(body) = ast::return_sequence(&function.function)
&& let Some((offset, rest)) = body.split_first()
&& let Some((index, offset)) = ast::assignment(offset)
&& function.function.params.first()?.pat.as_ident()?.to_id() == index
&& let Expr::Bin(subtract) = offset
&& subtract.op == BinaryOp::Sub
&& subtract.left.as_ident()?.to_id() == index
&& let Some(offset) = ast::number(&subtract.right)
&& offset.is_finite()
&& offset.fract() == 0.0
&& let Some((array, provider, lookup, result)) = match rest {
[array, lookup, result]
if let Some((array, provider_call)) = ast::assignment(array)
&& let Some((provider, [])) = ast::direct_call(provider_call) =>
{
Some((array, provider.to_id(), lookup, result))
}
[lookup, result]
if let Some((_, Expr::Member(member))) = ast::assignment(lookup)
&& let Some(array) = member.obj.as_ident()
&& let Some(provider) = bindings.sole_call(&array.to_id()) =>
{
Some((array.to_id(), provider, lookup, result))
}
_ => None,
}
&& let Some((value, lookup)) = ast::assignment(lookup)
&& let Expr::Member(member) = lookup
&& let MemberProp::Computed(property) = &member.prop
&& member.obj.as_ident()?.to_id() == array
&& property.expr.as_ident()?.to_id() == index
&& let Some(reversed) = if result.as_ident().is_some_and(|id| id.to_id() == value) {
Some(false)
} else {
(reversal_of(result)? == value).then_some(true)
}
&& let Some(strings) = factory_strings(functions.get(&provider)?, &provider)
{
Some(Self {
decoder: function.ident.to_id(),
provider,
offset,
strings,
reversed,
})
} else {
None
}
}
/// The decoded entry at `index` once the table is rotated left by `rotation` entries.
#[must_use]
fn lookup(&self, index: f64, rotation: usize) -> Option<Wtf8Atom> {
let index =
ast::array_index(index - self.offset).filter(|index| *index < self.strings.len())?;
let value = &self.strings[(index + rotation) % self.strings.len()];
Some(if self.reversed {
reverse_code_points(value)
} else {
value.clone()
})
}
}
/// `Array.from(value).reverse().join('')`, returning `value`'s binding.
fn reversal_of(expression: &Expr) -> Option<Id> {
if let Some((reversed, [separator])) = ast::method_call(expression, "join")
&& separator.spread.is_none()
&& ast::static_str(&separator.expr)?.is_empty()
&& let Some((from, [])) = ast::method_call(reversed, "reverse")
&& let Some((array, [value])) = ast::method_call(from, "from")
&& array.as_ident()?.sym == "Array"
&& value.spread.is_none()
{
Some(value.expr.as_ident()?.to_id())
} else {
None
}
}
/// Reverses by JavaScript code points as `Array.from` does. Preserves surrogate pairs; moves
/// lone surrogates individually.
fn reverse_code_points(value: &Wtf8Atom) -> Wtf8Atom {
let points: Vec<CodePoint> = value.as_wtf8().code_points().collect();
let reversed: Wtf8Buf = points.into_iter().rev().collect();
Wtf8Atom::from(reversed)
}
/// Reads strings returned by a self-replacing table factory:
///
/// ```js
/// function provider(v) {
/// v = `a;b`.split(`;`);
/// provider = function () { return v };
/// return provider();
/// }
/// ```
fn factory_strings(factory: &FnDecl, provider: &Id) -> Option<Vec<Wtf8Atom>> {
if let Some([split, redefine, call]) = ast::return_sequence(&factory.function)
&& let Some((storage, split)) = ast::assignment(split)
&& let Some((object, [separator])) = ast::method_call(split, "split")
&& separator.spread.is_none()
&& let Some(separator) = ast::static_wtf8(&separator.expr)
&& let Some(strings) = split_utf16(ast::static_wtf8(object)?, separator)
&& let Some((redefined, Expr::Fn(redefine_function))) = ast::assignment(redefine)
&& redefined == *provider
&& let Some(returned) = ast::returned(&redefine_function.function)
&& returned.as_ident()?.to_id() == storage
&& redefine_function.function.params.is_empty()
&& let Some((called, [])) = ast::direct_call(call)
&& called.to_id() == *provider
{
Some(strings)
} else {
None
}
}
/// Splits UTF-16 code units as `String.prototype.split` does, keeping lone surrogates that Rust
/// strings would corrupt. Returns `None` for an empty separator, which splits every code unit.
fn split_utf16(source: &Wtf8Atom, separator: &Wtf8Atom) -> Option<Vec<Wtf8Atom>> {
let source: Vec<u16> = source.as_wtf8().to_ill_formed_utf16().collect();
let separator: Vec<u16> = separator.as_wtf8().to_ill_formed_utf16().collect();
if separator.is_empty() {
return None;
}
let part = |units: &[u16]| Wtf8Atom::from(Wtf8Buf::from_ill_formed_utf16(units));
let mut parts = Vec::new();
let mut start = 0;
let mut position = 0;
while position + separator.len() <= source.len() {
if source[position..].starts_with(&separator) {
parts.push(part(&source[start..position]));
position += separator.len();
start = position;
} else {
position += 1;
}
}
parts.push(part(&source[start..]));
Some(parts)
}
/// Finds table-rotation calls and solves the rotation at which their decoded-entry checksums
/// match.
struct Rotations<'plan> {
table: &'plan Table,
aliases: &'plan HashSet<Id>,
bindings: &'plan Bindings,
matches: Vec<Setup>,
}
/// A call that rotates the table at runtime.
#[derive(Clone, Copy)]
struct Setup {
call: Span,
/// How far the call rotates the table left.
rotation: usize,
}
impl Visit for Rotations<'_> {
fn visit_call_expr(&mut self, call: &CallExpr) {
if let Some(rotation) = self.rotation(call) {
self.matches.push(Setup {
call: call.span,
rotation,
});
}
call.visit_children_with(self);
}
}
impl Rotations<'_> {
/// Solves the rotation for `call` when its loop initializer binds only the array and known
/// decoder aliases.
fn rotation(&self, call: &CallExpr) -> Option<usize> {
if let Callee::Expr(callee) = &call.callee
&& let Expr::Fn(function) = callee.unwrap_parens()
&& let [provider, target] = call.args.as_slice()
&& provider.spread.is_none()
&& target.spread.is_none()
&& provider.expr.as_ident()?.to_id() == self.table.provider
&& let Some(target_value) = ast::number(&target.expr)
&& !function.function.is_async
&& !function.function.is_generator
&& let [provider_param, target_param, ..] = function.function.params.as_slice()
&& let Some(provider_param) = provider_param.pat.as_ident()
&& let Some(target_param) = target_param.pat.as_ident()
&& let Some(loop_body) = function.function.body.as_ref()
&& let [Stmt::For(loop_)] = loop_body.stmts.as_slice()
&& loop_.update.is_none()
&& matches!(loop_.test.as_deref(), Some(Expr::Lit(Lit::Bool(test))) if test.value)
&& let Some(VarDeclOrExpr::Expr(init)) = &loop_.init
&& let Expr::Seq(init) = &**init
&& let Some((last, leading)) = init.exprs.split_last()
&& let Some((array, array_call)) = ast::assignment(last)
&& let Some((called, [])) = ast::direct_call(array_call)
&& called.to_id() == provider_param.to_id()
&& leading
.iter()
.all(|expression| is_alias_copy(expression, self.aliases))
&& let Stmt::Try(try_) = &*loop_.body
&& try_.finalizer.is_none()
&& let [Stmt::If(check)] = try_.block.stmts.as_slice()
&& matches!(&*check.cons, Stmt::Break(statement) if statement.label.is_none())
&& is_rotation(check.alt.as_deref()?, &array)
&& let Some(handler) = try_.handler.as_ref()
&& let [catch] = handler.body.stmts.as_slice()
&& is_rotation(catch, &array)
&& let Expr::Seq(test) = &*check.test
&& let [checksum, comparison] = test.exprs.as_slice()
&& let Some((checksum_id, checksum)) = ast::assignment(checksum)
&& let Expr::Bin(comparison) = &**comparison
&& matches!(comparison.op, BinaryOp::EqEq | BinaryOp::EqEqEq)
&& let Some(left) = comparison.left.as_ident()
&& let Some(right) = comparison.right.as_ident()
&& ((left.to_id() == target_param.to_id() && right.to_id() == checksum_id)
|| (right.to_id() == target_param.to_id() && left.to_id() == checksum_id))
{
// Try at most one table length of rotations instead of executing the input loop.
(0..self.table.strings.len())
.find(|&rotation| self.evaluate(checksum, rotation) == Some(target_value))
} else {
None
}
}
/// Folds the checksum under `rotation`, reading `parseInt(decoder(index))` from the table.
fn evaluate(&self, expression: &Expr, rotation: usize) -> Option<f64> {
ast::fold_number(expression, &|leaf| {
let (callee, [argument]) = ast::direct_call(leaf)? else {
return None;
};
let (decoder, [index]) = ast::direct_call(&argument.expr)? else {
return None;
};
if callee.sym != "parseInt"
|| self.bindings.is_bound(&callee.to_id())
|| argument.spread.is_some()
|| !self.aliases.contains(&decoder.to_id())
|| index.spread.is_some()
{
return None;
}
let value = self.table.lookup(ast::number(&index.expr)?, rotation)?;
Some(js::parse_integer(&value.to_string_lossy()))
})
}
}
fn is_rotation(statement: &Stmt, array: &Id) -> bool {
if let Stmt::Expr(expression) = statement
&& let Some((object, [argument])) = ast::method_call(&expression.expr, "push")
&& let Some((shifted, [])) = ast::method_call(&argument.expr, "shift")
{
argument.spread.is_none()
&& object.as_ident().is_some_and(|id| &id.to_id() == array)
&& shifted.as_ident().is_some_and(|id| &id.to_id() == array)
} else {
false
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::deobfuscate::testing;
fn fixture(offset: u32, separator: &str, consumer: &str) -> String {
let next = offset + 1;
let index = offset + 2;
format!(
r#"
(function () {{
function useAlias(late) {{ late = middle; return late({index}); }}
var middle = decoder;
(function (factory, target, alias, values, checksum) {{
for (alias = decoder, values = factory(); true;) try {{
if (checksum = parseInt(alias({offset})) + parseInt(alias({next})), target === checksum)
break;
else values.push(values.shift());
}} catch (error) {{ values.push(values.shift()); }}
}})(provider, 18);
function decoder(index, unused, values, result) {{
return index = index - {offset}, values = provider(), result = values[index], result;
}}
function provider(values) {{
return values = `noise{separator}7abc{separator}11def{separator}message`.split(`{separator}`),
provider = function () {{ return values; }}, provider();
}}
function shadow(decoder) {{ return decoder({index}); }}
function x() {{ return 'unrelated x'; }}
function d() {{ return 'unrelated d'; }}
console.log(useAlias(), shadow(function (v) {{ return v; }}), x(), d());
{consumer}
}})();
"#
)
}
#[test]
fn decodes_tables_with_any_names_offsets_delimiters_and_quoting() {
for (offset, separator, name) in [
(21, ";", "alpha"),
(700, "::", "renamed"),
(4096, "|", "thirdDecoder"),
] {
let source = fixture(offset, separator, "")
.replace("decoder", name)
.replace("provider", "tableFactory");
let output = testing::transform(&source);
assert!(output.contains("return \"message\";"), "{output}");
testing::assert_lacks(&output, &["function tableFactory(", "parseInt("]);
testing::assert_contains(&output, &[&format!("return {name}({});", offset + 2)], &[]);
testing::assert_contains(&output, &["function x()", "function d()"], &[]);
}
// Quoted tables keep their UTF-16 code units.
let source = fixture(21, ";", "").replace(
"`noise;7abc;11def;message`.split(`;`)",
r#""noise;7abc;11def;\uD800"["split"](";")"#,
);
let output = testing::transform(&source);
assert!(output.contains(r#"return "\uD800";"#), "{output}");
assert!(!output.contains("function provider("), "{output}");
}
#[test]
fn preserves_setups_still_needed_or_not_solved() {
// Dynamic calls, escaped aliases, and extra arguments still need the decoder.
for consumer in [
"console.log(middle(input));",
"console.log(middle(23, effect()));",
"console.log(middle(...args));",
"console.log(middle(22.5));",
"console.log(middle(1000));",
"consume(middle);",
"consume({ middle });",
] {
let output = testing::transform(&fixture(21, ";", consumer));
assert!(output.contains("return \"message\";"), "{output}");
let expected = ["function provider(", "function decoder(", "parseInt("];
testing::assert_contains(&output, &expected, &[]);
}
// Unsolved setups and reassigned decoders.
for source in [
fixture(21, ";", "").replace("provider, 18", "provider, 999"),
fixture(21, ";", "").replace("values.push(values.shift())", "values.pop()"),
fixture(21, ";", "").replace(
"var middle",
"function parseInt(v) { return 0; } var middle",
),
fixture(21, ";", "").replace("var middle", "decoder = replacement; var middle"),
fixture(21, ";", "middle = replacement; console.log(middle(23));"),
] {
let output = testing::transform(&source);
assert!(!output.contains("return \"message\";"), "{output}");
testing::assert_contains(&output, &["function provider(", "function decoder("], &[]);
}
}
#[test]
fn reverses_code_points_and_preserves_surrogates() {
for (source, expected) in [
(vec![], vec![]),
(
vec![0x61, 0xd83d, 0xde00, 0x62],
vec![0x62, 0xd83d, 0xde00, 0x61],
),
(vec![0xd800, 0x61, 0xdc00], vec![0xdc00, 0x61, 0xd800]),
(vec![0xdc00, 0xd800], vec![0xd800, 0xdc00]),
] {
let source = Wtf8Atom::from(Wtf8Buf::from_ill_formed_utf16(&source));
let reversed = reverse_code_points(&source);
assert_eq!(
reversed.as_wtf8().to_ill_formed_utf16().collect::<Vec<_>>(),
expected
);
}
}
}
+25 -5
View File
@@ -1,16 +1,19 @@
//! Removes the declarations of unread locals, and their definitions when evaluating the value
//! has no effects:
//! has no side effects. If the value assigns another binding, removes only the unused definition:
//!
//! ```js
//! var unused, add, all;
//! var unused, add, all, copy;
//! add = function(a, b) { var scratch; return a + b; };
//! all = [add]; // everything is removed, `all` first
//! copy = other = g(); // becomes other = g()
//! [add, other]; // removed, as are other statements without effects
//! ```
//!
//! Leaves globals, whose writes other scripts can observe, and parameters of functions using
//! `arguments`, whose writes `arguments` reflects.
use swc_core::ecma::ast::{Decl, Expr, Id, Program, SeqExpr, Stmt, VarDeclarator};
use swc_core::common::util::take::Take;
use swc_core::ecma::ast::{Decl, Expr, Id, Lit, Program, SeqExpr, Stmt, VarDeclarator};
use swc_core::ecma::visit::{VisitMut, VisitMutWith};
use super::analysis::{Analysis, Bindings, Globals};
@@ -111,12 +114,25 @@ impl VisitMut for RemoveUnused<'_> {
{
*expression = *sequence.exprs.remove(0);
}
// Dropping `unused` preserves the value of `other = value`.
if let Some((id, value)) = ast::assignment(expression)
&& value.is_assign()
&& self.is_unused(&id)
{
*self.removed.entry(id).or_default() += 1;
*expression = *expression.take().expect_assign().right;
self.changed = true;
}
}
fn visit_mut_stmts(&mut self, statements: &mut Vec<Stmt>) {
statements.visit_mut_children_with(self);
self.changed |=
removal::remove_expr_stmts(statements, |expression| self.remove_definition(expression));
// Remove unused definitions and statements with no side effects, including decoy arrays of
// helpers. Keep strings that may be directives.
self.changed |= removal::remove_expr_stmts(statements, |expression| {
self.remove_definition(expression)
|| (!matches!(expression, Expr::Lit(Lit::Str(_))) && self.is_pure(expression))
});
for statement in statements.iter_mut() {
if let Stmt::Decl(Decl::Var(declaration)) = statement {
self.changed |= removal::retain(&mut declaration.decls, |declarator| {
@@ -151,5 +167,9 @@ mod tests {
);
let kept = ["global = function", "var v", "v = g()", "w = [", "p = 1"];
testing::assert_contains(&output, &kept, &[]);
let output = transform("function f(a) { 'use strict'; [a, function() {}]; a; g(a); }");
testing::assert_contains(&output, &["'use strict';"], &["{ 'use strict'; g(a); }"]);
let output = transform("function f() { var c, o; c = o = g(); h(c = o = 1); return o; }");
testing::assert_contains(&output, &["var o;", "o = g();", "h(o = 1);"], &[]);
}
}
+69 -9
View File
@@ -7,7 +7,7 @@ use swc_core::ecma::ast::{CallExpr, Expr, KeyValueProp};
use swc_core::ecma::visit::{Visit, VisitWith};
use url::Url;
use crate::challenge::reduced_timing::ResourceTiming;
use crate::challenge::reduced_timing::{Entry, ResourceTiming};
use crate::embedding_page::page::{Layout, PageSignals, RenderedPage};
use crate::embedding_page::render_sample::RenderSample;
use crate::engine::Engine;
@@ -191,7 +191,11 @@ impl ApiScript {
/// Reduces [`Self::timing`] to the six fields forwarded by the challenge.
#[must_use]
pub(crate) fn reduced(&self, timing: &ResourceTiming) -> JsValue {
timing.reduce(self.url.as_str(), &self.measurement())
timing.reduce(&Entry {
name: self.url.as_str(),
start: self.start_time_ms,
measured: self.measurement(),
})
}
}
@@ -288,6 +292,14 @@ pub(crate) struct ExtraParams<'page> {
#[serde(rename = "wPr")]
pub signals: PageSignals,
pub widget_id: &'page str,
#[serde(flatten)]
pub times: ElapsedTimes,
}
/// Elapsed loader times reported at the end of [`ExtraParams`], in milliseconds.
#[derive(Debug, Clone, Deserialize, Serialize)]
#[serde(rename_all = "camelCase")]
pub(crate) struct ElapsedTimes {
pub time_extra_params_ms: i64,
pub time_init_ms: i64,
pub time_load_init_ms: i64,
@@ -296,6 +308,46 @@ pub(crate) struct ExtraParams<'page> {
pub time_tief_ms: i64,
}
impl Timeline {
/// Returns the elapsed times reported by the loader.
fn times(&self) -> ElapsedTimes {
ElapsedTimes {
time_extra_params_ms: self.sent - self.render_start,
time_init_ms: self.init_start - self.render_end,
// The clock starts when the loader script runs, so the mark is already an elapsed time.
time_load_init_ms: self.sent,
time_params_ms: self.params_start - self.init_start,
time_render_ms: self.render_end - self.render_start,
time_tief_ms: self.sent - self.collect_start,
}
}
/// Reconstructs the timeline from reported `times` and the `implicit_render` stack sample.
/// Reverses [`Self::times`]. The caller supplies `script_fetch` because payloads do not report
/// when the loader was fetched.
#[must_use]
pub(crate) fn from_times(
times: &ElapsedTimes,
implicit_render: i64,
script_fetch: f64,
) -> Self {
let sent = times.time_load_init_ms;
let render_start = sent - times.time_extra_params_ms;
let render_end = render_start + times.time_render_ms;
let init_start = render_end + times.time_init_ms;
Self {
script_fetch,
implicit_render,
render_start,
render_end,
init_start,
params_start: init_start + times.time_params_ms,
collect_start: sent - times.time_tief_ms,
sent,
}
}
}
/// Builds the reply to `requestExtraParams`. Omits widget parameters that the page does not
/// set. The iframe treats missing and `undefined` values alike, applying `||` defaults or
/// storing them directly.
@@ -339,13 +391,7 @@ pub(crate) fn collect<'page>(
url: page.url.as_str(),
signals: page.signals(layout, mode),
widget_id: &page.widget_id,
time_extra_params_ms: timeline.sent - timeline.render_start,
time_init_ms: timeline.init_start - timeline.render_end,
// The loader script starts the clock, so this is the mark itself.
time_load_init_ms: timeline.sent,
time_params_ms: timeline.params_start - timeline.init_start,
time_render_ms: timeline.render_end - timeline.render_start,
time_tief_ms: timeline.sent - timeline.collect_start,
times: timeline.times(),
}
}
@@ -388,6 +434,20 @@ pub(crate) fn widget_id() -> String {
#[cfg(test)]
mod tests {
use super::*;
use crate::challenge::reduced_timing::Measure;
fn page() -> RenderedPage {
RenderedPage::render(
r#"<html><head><title>t</title>
<script src="https://challenges.cloudflare.com/turnstile/v0/api.js"></script></head>
<body><div class="cf-turnstile" data-sitekey="0x4AAA" data-action="login"
data-theme="dark" data-size="compact" data-language="de"></div></body></html>"#,
Url::parse("https://example.com/login").unwrap(),
"j5gbk",
None,
)
.unwrap()
}
#[test]
fn finds_build_hashes_and_routes_only_where_the_loader_keeps_them() {
+2 -1
View File
@@ -13,9 +13,10 @@ pub use decode::{ResponseMetrics, header_text, read_encoded, text_headers};
#[cfg(feature = "internals")]
pub(crate) use decode::{decode_body, encode_body};
pub use header_order::HeaderOrder;
pub(crate) use header_order::RequestKind;
pub use referrer::ReferrerPolicy;
pub use requests::{
FetchOptions, Iframe, PageDocument, ScriptLoad, fetch_from_worker, fetch_iframe, fetch_image,
fetch_orchestrator, fetch_page_image, fetch_script, navigate, post_challenge,
fetch_orchestrator, fetch_page_image, fetch_script, navigate, open_websocket, post_challenge,
post_orchestrator, submit_form,
};
+49 -14
View File
@@ -13,6 +13,7 @@ use wreq::cookie::{Cookie, Jar};
use wreq::header::HeaderMap;
use wreq::http2::{StreamDependency, StreamId};
use wreq::redirect::Policy;
use wreq::ws::{WebSocket, WebSocketRequestBuilder};
use wreq::{Client, Proxy, RequestBuilder, Response};
#[cfg(feature = "internals")]
use wreq::{Method, StatusCode};
@@ -168,6 +169,53 @@ impl BrowserClient {
kind: RequestKind,
supplied: &[(&str, Option<&str>)],
) -> Result<Response, wreq::Error> {
let (http, request) = self.ordered(request, kind, supplied).build_split();
let mut request = request?;
let urgency = request
.headers()
.get("priority")
.and_then(|priority| priority.to_str().ok())
.map_or(3, urgency);
if let Some(&weight) = self.requests.weights.get(&urgency) {
// The wire weight is one less than the configured weight. The stream exclusively
// depends on the connection while no other stream is open.
let dependency = StreamDependency::new(StreamId::zero(), (weight - 1) as u8, true);
request.extensions_mut().insert(dependency);
}
RequestBuilder::from_parts(http, request).send().await
}
/// Opens a WebSocket to `url` using the profile's handshake headers. The client appends the
/// handshake key.
///
/// # Panics
///
/// Panics if the profile has no `websocket` header order.
pub(super) async fn websocket(
&self,
url: &Url,
supplied: &[(&str, Option<&str>)],
) -> Result<WebSocket, wreq::Error> {
let request = self.ordered(
self.http.get(url.as_str()),
RequestKind::WebSocket,
supplied,
);
WebSocketRequestBuilder::new(request)
.send()
.await?
.into_websocket()
.await
}
/// Replaces default headers with the profile's order for `kind`. Takes values from `supplied`,
/// omitting headers whose value is `None`.
fn ordered(
&self,
request: RequestBuilder,
kind: RequestKind,
supplied: &[(&str, Option<&str>)],
) -> RequestBuilder {
debug_assert!(
supplied.len() == kind.supplied().len()
&& supplied
@@ -197,20 +245,7 @@ impl BrowserClient {
},
};
}
let (http, request) = request.build_split();
let mut request = request?;
let urgency = request
.headers()
.get("priority")
.and_then(|priority| priority.to_str().ok())
.map_or(3, urgency);
if let Some(&weight) = self.requests.weights.get(&urgency) {
// The wire weight is one less than the configured weight. The stream exclusively
// depends on the connection while no other stream is open.
let dependency = StreamDependency::new(StreamId::zero(), (weight - 1) as u8, true);
request.extensions_mut().insert(dependency);
}
RequestBuilder::from_parts(http, request).send().await
request
}
/// Forwards a capture-proxy request without following redirects or decoding the response.
+41 -3
View File
@@ -15,7 +15,7 @@ use wreq::header::{HeaderMap, HeaderName, HeaderValue, USER_AGENT};
/// Each kind of request the challenge flow makes.
#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Deserialize, Serialize)]
#[serde(rename_all = "snake_case")]
pub(super) enum RequestKind {
pub(crate) enum RequestKind {
/// A navigation to a typed address.
Navigation,
/// A navigation retried with the high-entropy client hints its response demanded.
@@ -43,6 +43,10 @@ pub(super) enum RequestKind {
/// A worker's `fetch(url, {cache: "no-store", credentials: "omit"})`.
WorkerFetchWithoutCredentials,
Form,
/// HTTP/1.1 WebSocket handshake from the iframe. Handshakes are not captured, so profiles
/// specify this order manually.
#[serde(rename = "websocket")]
WebSocket,
}
impl RequestKind {
@@ -82,8 +86,28 @@ impl RequestKind {
}
Self::WorkerFetch | Self::WorkerFetchWithoutCredentials => &["sec-fetch-site"],
Self::Form => &["content-length", "origin", "sec-fetch-site", "referer"],
Self::WebSocket => &["origin"],
}
}
/// Converts a captured header to an order entry for [`Slot::parse`]. Uses a bare name if the
/// request or browser identity supplies its value.
#[must_use]
pub(crate) fn entry(self, name: &str, value: &str) -> String {
if self.gives_value(name) {
name.to_owned()
} else {
format!("{name}: {value}")
}
}
/// Checks whether the request or browser identity supplies a value for header `name`, as with
/// the user agent and client hints.
fn gives_value(self, name: &str) -> bool {
name == USER_AGENT.as_str()
|| name.starts_with("sec-ch-")
|| self.supplied().contains(&name)
}
}
/// Returns the request kind's profile name.
@@ -111,9 +135,8 @@ impl Slot {
};
let Some((name, value)) = entry.split_once(':') else {
let name = header(entry)?;
let identity = name == USER_AGENT || name.as_str().starts_with("sec-ch-");
ensure!(
identity || kind.supplied().contains(&name.as_str()),
kind.gives_value(name.as_str()),
"nothing gives `{name}` a value; write it as `{name}: <value>`"
);
return Ok(Self::Named(name));
@@ -222,6 +245,21 @@ mod tests {
error.contains("the order of `navigation` requests"),
"a navigation supplies no referer: {error}"
);
// Converting a sent header to an order entry preserves how it is read back.
let entries = [
(RequestKind::Form, "referer", "referer"),
(RequestKind::Image, "sec-ch-ua-model", "sec-ch-ua-model"),
(RequestKind::Image, "user-agent", "user-agent"),
(
RequestKind::Navigation,
"sec-fetch-mode",
"sec-fetch-mode: navigate",
),
];
for (kind, name, entry) in entries {
assert_eq!(kind.entry(name, "navigate"), entry);
}
}
#[test]
+68 -8
View File
@@ -7,6 +7,7 @@ use url::form_urlencoded::Serializer;
use wreq::cookie::Jar;
use wreq::header::LOCATION;
use wreq::redirect::Policy;
use wreq::ws::WebSocket;
use wreq::{Response, StatusCode};
use super::client::BrowserClient;
@@ -344,6 +345,20 @@ pub async fn fetch_from_worker(
.context("fetching from the challenge worker")
}
/// Opens the iframe's WebSocket to `url`. Omits extension offers because the client cannot
/// decompress messages.
pub async fn open_websocket(
client: &BrowserClient,
iframe: &Iframe,
url: &Url,
) -> Result<WebSocket> {
let origin = iframe.url.origin().ascii_serialization();
client
.websocket(url, &[("origin", Some(&origin))])
.await
.context("opening the iframe's WebSocket")
}
#[cfg(test)]
mod tests {
use std::io::{BufRead, BufReader, Read, Write};
@@ -355,6 +370,7 @@ mod tests {
use wreq::header::{HeaderMap, HeaderValue, USER_AGENT};
use super::*;
use crate::http::Requests;
/// A request the test server received.
struct Received {
@@ -431,22 +447,25 @@ mod tests {
}
/// Runs widget requests against a loopback server. Returns its address and lowercase
/// request headers. Matches captured Safari traffic: the loader redirects, and the page
/// sends its origin as referrer when no policy is specified.
/// request headers. The WebKit case matches captured Safari traffic: the loader redirects,
/// and the page sends its origin as referrer when no policy is specified.
async fn flow(client: &BrowserClient) -> (SocketAddr, Vec<String>) {
let webkit = client.engine == Engine::WebKit;
let body = "<script>window._cf_chl_opt = {};</script>";
let ok = format!(
"HTTP/1.1 200 OK\r\nContent-Length: {}\r\nConnection: close\r\n\r\n{body}",
body.len()
);
let redirect =
b"HTTP/1.1 302 Found\r\nLocation: /b/api.js\r\nContent-Length: 0\r\nConnection: close\r\n\r\n";
let mut responses = vec![ok.into_bytes(); 6];
responses.insert(1, redirect.to_vec());
if webkit {
let redirect =
b"HTTP/1.1 302 Found\r\nLocation: /b/api.js\r\nContent-Length: 0\r\nConnection: close\r\n\r\n";
responses.insert(1, redirect.to_vec());
}
let (address, server) = serve(responses);
let page = Url::parse(&format!("http://{address}/page")).unwrap();
let origin = format!("http://{address}/");
let referer = Some(origin.as_str());
let referer = webkit.then_some(origin.as_str());
navigate(client, &page).await.unwrap();
let script = page.join("/api.js").unwrap();
fetch_script(client, &script, ScriptLoad::Classic, &page, referer)
@@ -488,12 +507,54 @@ mod tests {
sent
}
/// Expected header order from the tracked Chrome 155 profile, verified against a headed
/// browser's book.sv network log.
#[tokio::test]
async fn requests_send_the_browsers_headers_in_its_order() {
let own = [
("user-agent", "Mozilla/5.0"),
("sec-ch-ua", "\"Chromium\";v=\"155\""),
("sec-ch-ua-mobile", "?0"),
("sec-ch-ua-platform", "\"Linux\""),
];
let client = BrowserClient {
own: own
.iter()
.map(|(name, value)| (name.parse().unwrap(), value.parse().unwrap()))
.collect(),
..BrowserClient::from_http(Client::new())
};
let (_, heads) = flow(&client).await;
let expected = [
"sec-ch-ua sec-ch-ua-mobile sec-ch-ua-platform upgrade-insecure-requests user-agent \
accept sec-fetch-site sec-fetch-mode sec-fetch-user sec-fetch-dest accept-encoding \
accept-language priority",
"sec-ch-ua-platform user-agent sec-ch-ua sec-ch-ua-mobile accept sec-fetch-site \
sec-fetch-mode sec-fetch-dest sec-fetch-storage-access accept-encoding \
accept-language",
"sec-ch-ua sec-ch-ua-mobile sec-ch-ua-platform upgrade-insecure-requests user-agent \
accept sec-fetch-site sec-fetch-mode sec-fetch-dest sec-fetch-storage-access \
accept-encoding accept-language priority",
"content-length sec-ch-ua-platform user-agent sec-ch-ua content-type cf-chl cf-chl-ra \
sec-ch-ua-mobile accept origin sec-fetch-site sec-fetch-mode sec-fetch-dest referer \
accept-encoding accept-language priority",
"sec-ch-ua-platform user-agent sec-ch-ua sec-ch-ua-mobile accept sec-fetch-site \
sec-fetch-mode sec-fetch-dest sec-fetch-storage-access referer accept-encoding \
accept-language priority",
"cache-control user-agent accept sec-fetch-site sec-fetch-mode sec-fetch-dest \
accept-encoding accept-language priority",
];
assert_eq!(header_names(&heads), expected);
}
/// Expected header order from the tracked iOS Safari 26.6 profile, verified against
/// captchatest proxy traffic. Includes Safari's separate redirected-loader order.
#[tokio::test]
async fn webkit_requests_send_safaris_headers_in_its_order() {
let client = BrowserClient {
own: HeaderMap::from_iter([(USER_AGENT, HeaderValue::from_static("Mozilla/5.0"))]),
requests: Requests::from_profile(include_str!("../../profiles/safari-26-ios.json")),
engine: Engine::WebKit,
..BrowserClient::from_http(Client::new())
};
let (address, heads) = flow(&client).await;
@@ -586,7 +647,6 @@ mod tests {
] {
assert!(headers.contains(expected), "missing {expected}: {headers}");
}
// WebKit sends only the iframe's origin.
assert!(headers.contains(&format!("referer: http://{address}/\r\n")));
assert!(headers.contains(&format!("referer: http://{address}/iframe?lang=auto")));
}
}
+4 -4
View File
@@ -7,10 +7,10 @@ mod objects;
mod value;
pub(crate) use numeric::{
bit_and, bit_not, bit_or, bit_xor, int32, parse_integer, shl, shr, string_number, uint32, ushr,
bit_and, bit_not, bit_or, bit_xor, int32, shl, shr, string_number, uint32, ushr,
};
pub use objects::{Options, Payload, Window};
#[cfg(test)]
pub(crate) use value::from_value;
pub(crate) use value::{ErrorValue, json, number, present, string, stringify_object, truthy};
pub(crate) use value::{
ErrorValue, from_value, json, number, present, string, stringify_object, truthy,
};
pub use value::{JsObject, JsValue};
-9
View File
@@ -361,15 +361,6 @@ pub(crate) fn returned(function: &Function) -> Option<&Expr> {
}
}
/// Returns the sequence operands from a function whose entire body is `return a, b, ...;`.
#[must_use]
pub(crate) fn return_sequence(function: &Function) -> Option<&[Box<Expr>]> {
if function.is_async || function.is_generator {
return None;
}
Some(returned(function)?.as_seq()?.exprs.as_slice())
}
/// A block grouping statements that came from one place.
#[must_use]
pub(crate) fn block(statements: Vec<Stmt>) -> Stmt {
-37
View File
@@ -107,29 +107,6 @@ pub(crate) fn string_number(text: &str) -> f64 {
text.parse().unwrap_or(f64::NAN)
}
/// `parseInt(text)` with no radix: decimal, or hexadecimal after `0x`.
#[must_use]
pub(crate) fn parse_integer(text: &str) -> f64 {
let text = text.trim_start_matches(is_whitespace);
let (sign, text) = match text.strip_prefix('-') {
Some(text) => (-1.0, text),
None => (1.0, text.strip_prefix('+').unwrap_or(text)),
};
let (radix, text) = match text.strip_prefix("0x").or_else(|| text.strip_prefix("0X")) {
Some(text) => (16, text),
None => (10, text),
};
if !text.starts_with(|character: char| character.is_digit(radix)) {
return f64::NAN;
}
let digits = text
.chars()
.map_while(|character| character.to_digit(radix));
sign * digits.fold(0.0, |value, digit| {
value * f64::from(radix) + f64::from(digit)
})
}
#[cfg(test)]
mod tests {
use super::*;
@@ -166,20 +143,6 @@ mod tests {
}
}
#[test]
fn parses_javascript_integer_prefixes() {
for (text, expected) in [
(" -12tail", -12.0),
("+0x20suffix", 32.0),
("1e3", 1.0),
("\u{feff}42", 42.0),
] {
assert_eq!(parse_integer(text), expected, "{text:?}");
}
assert!(parse_integer("text").is_nan());
assert!(parse_integer("\u{85}12").is_nan());
}
#[test]
fn integer_conversions_wrap_and_truncate() {
assert_eq!(int32(-1.5), -1);
-1
View File
@@ -294,7 +294,6 @@ macro_rules! json {
pub(crate) use json;
/// Deserializes `T` from a JavaScript value using the same rules as `serde_json::from_value`.
#[cfg(test)]
pub(crate) fn from_value<T: serde::de::DeserializeOwned>(value: JsValue) -> serde_json::Result<T> {
serde_json::from_value(serde_json::Value::from(value))
}
+20 -11
View File
@@ -15,7 +15,7 @@ use crate::browser::Page;
use crate::challenge::orchestrator::{self, ChallengePage};
use crate::challenge::payload;
use crate::challenge::program::{PreparedSession, SessionEncoder};
use crate::challenge::reduced_timing::ResourceTiming;
use crate::challenge::reduced_timing::{Entry, ResourceTiming};
use crate::challenge::source::InitialRequest;
use crate::challenge::state::{Intervals, ScriptState};
use crate::embedding_page::challenge_page::WIDGET_HOST;
@@ -351,10 +351,19 @@ pub(crate) fn page_resource_timing(
post: &LoadTiming,
iframe: &LoadTiming,
) -> Vec<JsValue> {
// Times run from the challenge page's navigation.
let since = |load: &LoadTiming| (load.started_ms - navigation.started_ms) as f64;
let reduce = |load: &LoadTiming, measured: ResourceMeasurement| {
timing.reduce(&Entry {
name: &load.url,
start: since(load),
measured,
})
};
let estimate = |fetch: &LoadTiming| {
timing.reduce(
&fetch.url,
&ResourceMeasurement::estimated(fetch.duration_ms, fetch.body_bytes, phases),
reduce(
fetch,
ResourceMeasurement::estimated(fetch.duration_ms, fetch.body_bytes, phases),
)
};
let loading = ResourceMeasurement {
@@ -369,15 +378,15 @@ pub(crate) fn page_resource_timing(
duration: loaded_ms - navigation.started_ms as f64,
..loading
};
let iframe_end = (iframe.started_ms - navigation.started_ms) as f64 + iframe.duration_ms;
let mut entries = vec![timing.reduce(&navigation.url, &loading)];
let iframe_end = since(iframe) + iframe.duration_ms;
let mut entries = vec![reduce(navigation, loading)];
entries.extend(loads.iter().map(estimate));
entries.push(timing.reduce(&navigation.url, &loaded));
entries.push(timing.entry(post));
entries.push(reduce(navigation, loaded));
entries.push(timing.entry(post, navigation.started_ms));
entries.extend(loads.last().map(estimate));
entries.push(timing.reduce(
&iframe.url,
&ResourceMeasurement::restricted(iframe.duration_ms, iframe_end),
entries.push(reduce(
iframe,
ResourceMeasurement::restricted(iframe.duration_ms, iframe_end),
));
entries
}
+7
View File
@@ -100,6 +100,9 @@ impl FirstPayload {
let fields = &program.payload_fields;
let options = &mut program.request.options;
options.extend(installed.options);
if let Some(log) = &state.post_log {
log.start(options);
}
let (merge_mark, marked_ms) = complete(options);
options.extend(state.timestamps(
&payload::differences(fields),
@@ -134,6 +137,9 @@ pub(crate) struct Merged {
pub selector_log: Option<String>,
/// The resource timing entries the first payload reports.
pub resources: Vec<JsValue>,
/// Start of iframe navigation in milliseconds since the Unix epoch. Resource timing uses this
/// as its time origin.
pub time_origin_ms: i64,
/// What the embedding page reported about itself in `extraParams`.
pub page_signals: PageSignals,
}
@@ -387,6 +393,7 @@ pub(crate) fn merge(
globals: built.globals,
selector_log: payload::selector_log(&built.program.payload_fields),
resources,
time_origin_ms: navigation.started_ms,
page_signals,
};
Ok((built.program, merged))
+4 -1
View File
@@ -252,7 +252,10 @@ pub(crate) fn payload(
.get_mut(&timing.option)
.and_then(JsValue::as_array_mut)
.context("interaction has no resource timing list")?
.push(timing.entry(probe_post));
.push(timing.entry(probe_post, merged.time_origin_ms));
}
if let Some(log) = &merged.state.post_log {
log.record(&mut options, probe_post, merged.time_origin_ms)?;
}
let mut payload =
plan.append_record(&input, result.fields, result.started_ms, result.finished_ms)?;
+132 -40
View File
@@ -2,10 +2,13 @@
//! payload with record timestamps scheduled to finish just before it is sent.
use std::collections::BTreeMap;
use std::time::Duration;
use anyhow::{Context, Result, ensure};
use chrono::Local;
use tokio::task;
use tokio::{task, time};
use url::Url;
use wreq::ws::message::Message;
use super::channel::Submission;
use super::timing::{self, Schedule, Timer};
@@ -14,17 +17,23 @@ use crate::browser::{Profile, Solve};
use crate::challenge::payload;
use crate::engine::Engine;
use crate::http::{self, FetchOptions};
use crate::js::{JsObject, JsValue, Options, Payload, Window, json};
use crate::js::{self, JsObject, JsValue, Options, Payload, Window, json};
use crate::performance_clock::{self, PerformanceClock};
use crate::resource_timing::LoadTiming;
use crate::stage2::call_stack;
use crate::stage2::payload::State;
use crate::stage2::probes::{clock, ice, image, performance, private_token, worker_fetch};
use crate::stage2::probes::{
clock, host_reachability, ice, image, performance, private_token, websocket_echo, worker_fetch,
};
use crate::stage2::records::{Probe, ProbePlan};
use crate::stage2::registry::{Facts, Kind, Observed, Operation, Treatment};
use crate::stage2::replay::{self, Answers, Replay};
use crate::stage2::replay::{self, Replay};
use crate::stage2::trace::Trace;
/// Timeout for host reachability fetches. Browsers report these hosts as unreachable within
/// milliseconds.
const REACHABILITY_TIMEOUT: Duration = Duration::from_secs(5);
/// A probe kind's duration when nothing else gives one.
const DEFAULT_DURATION_MS: i64 = 2;
@@ -50,15 +59,20 @@ pub(crate) async fn prepare(session: &WidgetSession<'_>, solve: &Solve) -> Resul
let engine = session.client.engine();
let plan = session.analysis.plan();
let mut options = session.request.options.clone();
let (mut observed, fetches) = observe(session, plan, &options, profile, answers).await?;
let (mut observed, fetches) = observe(session, plan, &options, profile).await?;
observed.page_signals = Some(merged.page_signals.clone());
// Resource timings now include the first POST and probe requests.
if let Some(timing) = &merged.state.timing {
let mut resources = merged.resources.clone();
resources.push(timing.entry(&session.first_post));
resources.extend(fetches.iter().map(|fetch| timing.entry(fetch)));
let origin = merged.time_origin_ms;
resources.push(timing.entry(&session.first_post, origin));
resources.extend(fetches.iter().map(|fetch| timing.entry(fetch, origin)));
options.insert(timing.option.clone(), JsValue::Array(resources));
}
// The sender logged the first POST after sending it.
if let Some(log) = &merged.state.post_log {
log.record(&mut options, &session.first_post, merged.time_origin_ms)?;
}
// Build window values from installed globals, values read by the first payload, then
// profile overrides.
let mut window = merged.window.clone();
@@ -69,13 +83,9 @@ pub(crate) async fn prepare(session: &WidgetSession<'_>, solve: &Solve) -> Resul
window.extend(profile.window.clone());
let replay = answers.map(|answers| Replay::new(answers, plan));
let benchmark_ms = observed
.benchmark
.as_ref()
.map(|measured| measured.elapsed_ms().ceil() as i64);
let pending_ms = i64::from(profile.pending_ms);
let schedule = timing::schedule(
&durations(plan, &profile.durations, benchmark_ms, replay.as_ref()),
&durations(plan, &profile.durations, &observed, replay.as_ref()),
profile.startup_ms.into(),
pending_ms,
session.arrived_ms,
@@ -146,11 +156,10 @@ async fn observe(
plan: &ProbePlan,
options: &Options,
profile: &Profile,
answers: Option<&Answers>,
) -> Result<(Observed, Vec<LoadTiming>)> {
let mut observed = Observed::default();
let requests = requests(session, plan, options, profile, &mut observed);
let stack = probe_stack(session, plan, answers);
let stack = probe_stack(session, plan);
let (fetches, stack) = tokio::try_join!(requests, stack)?;
observed.stack = stack;
let facts = &profile.facts;
@@ -181,23 +190,79 @@ async fn observe(
Ok((observed, fetches))
}
/// The stack probe's result. Chrome's is rebuilt from the session script; WebKit replays the
/// recorded one (see [`Answers::stack`]).
async fn probe_stack(
/// Runs the WebSocket echo exchange. After opening, sends `String(performance.now())` and sends a
/// new reading after each echo. Closes the socket when enough echoes return or the timeout expires.
async fn echo_websocket(
session: &WidgetSession<'_>,
plan: &ProbePlan,
answers: Option<&Answers>,
) -> Result<Option<String>> {
fields: &websocket_echo::Fields,
options: &Options,
) -> Result<websocket_echo::Measurement> {
use websocket_echo::{ECHOES, End, Measurement};
let (client, iframe) = (session.client, &session.fetched.iframe);
let url = fields.url(options, &iframe.url)?;
let clock = PerformanceClock::from_epoch_origin(
session.merged.time_origin_ms,
session.clock_resolution(),
);
let started_ms = performance_clock::epoch_ms();
let deadline = time::Instant::now() + Duration::from_millis(websocket_echo::TIMEOUT_MS);
let constructed = clock.now();
let mut measured = Measurement {
end: End::TimedOut,
sent: 0,
received: 0,
opened_ms: None,
round_trips: Vec::new(),
elapsed_ms: 0,
};
let mut socket = None;
let exchange = async {
let Ok(opened) = http::open_websocket(client, iframe, &url).await else {
return End::Failed;
};
measured.opened_ms = Some(clock.now() - constructed);
let socket = socket.insert(opened);
while measured.sent < ECHOES {
measured.sent += 1;
let reading = js::string(Some(&json!(clock.now())));
if socket.send(Message::text(reading)).await.is_err() {
return End::Failed;
}
// Ping and pong frames do not trigger `message` events. Binary data converts to `NaN`.
let echoed = loop {
match socket.recv().await {
Some(Ok(Message::Text(text))) => break js::string_number(text.as_str()),
Some(Ok(Message::Binary(_))) => break f64::NAN,
Some(Ok(Message::Ping(_) | Message::Pong(_))) => {}
Some(Ok(Message::Close(_))) | None => return End::Closed,
Some(Err(_)) => return End::Failed,
}
};
measured.received += 1;
if echoed.is_finite() {
measured.round_trips.push(clock.now() - echoed);
}
}
End::Echoed
};
measured.end = time::timeout_at(deadline, exchange)
.await
.unwrap_or(End::TimedOut);
measured.elapsed_ms = performance_clock::epoch_ms() - started_ms;
if let Some(mut socket) = socket {
// Ignore close errors because the result has already been recorded.
let _ = socket.send(Message::Close(None)).await;
}
Ok(measured)
}
/// Rebuilds the stack probe result using the session script and engine's stack format. The VM
/// executes closures within its dispatch loop, so neither engine shows additional VM call levels.
async fn probe_stack(session: &WidgetSession<'_>, plan: &ProbePlan) -> Result<Option<String>> {
let Some((probe, Operation::Stack { fields })) = plan.operation(Kind::Stack) else {
return Ok(None);
};
if session.client.engine() == Engine::WebKit {
let answers = answers.context("the fingerprint names no stored answers")?;
return answers
.stack(session.fetched.iframe.url.as_str())
.map(Some)
.with_context(|| format!("replaying probe {}'s stack", probe.index));
}
let calls = fields.calls.with_context(|| {
format!(
"probe {}'s calls leading to `new Error()` have an unrecognized shape",
@@ -208,9 +273,10 @@ async fn probe_stack(
let javascript = fetched.javascript.clone();
let cases = fetched.cases.clone();
let origin = fetched.script_position()?;
let engine = session.client.engine();
let stack = task::spawn_blocking(move || {
let geometry = call_stack::recover_probe(&javascript, &cases, calls)?;
anyhow::Ok(geometry.format(&origin, Engine::Chromium))
anyhow::Ok(geometry.format(&origin, engine))
})
.await
.context("the stack recovery thread failed")?
@@ -218,25 +284,22 @@ async fn probe_stack(
Ok(Some(stack))
}
/// Chooses probe durations from the profile's `configured` values, measured benchmark duration,
/// stored answers, or the default.
/// Chooses probe durations from completed work, `configured` profile values, stored answers, or
/// defaults, in that order.
fn durations(
plan: &ProbePlan,
configured: &BTreeMap<String, u32>,
benchmark_ms: Option<i64>,
observed: &Observed,
replay: Option<&Replay<'_>>,
) -> Vec<i64> {
let duration = |probe: &Probe| {
if let Some(family) = probe.operation.as_ref().map(Operation::family) {
if let Some(measured) = observed.duration_ms(family) {
return measured;
}
if let Some(&recorded) = configured.get(family.as_str()) {
return i64::from(recorded);
}
// Use the measured benchmark duration because that work has already run.
if family == Kind::Benchmark
&& let Some(benchmark_ms) = benchmark_ms
{
return benchmark_ms;
}
}
let stored = replay.and_then(|replay| replay.duration(probe));
stored.unwrap_or(DEFAULT_DURATION_MS)
@@ -284,6 +347,35 @@ async fn requests(
Some(Operation::WorkerFetch { .. }) if profile.facts.worker_fetch_rejected => {
observed.worker_fetch = Some(worker_fetch::Measurement::Rejected);
}
Some(Operation::HostReachability { fields }) => {
// CORS rejects a response that does not allow the iframe's origin.
let origin = iframe.url.origin().ascii_serialization();
let mut outcomes = Vec::new();
for url in &fields.urls {
let url = Url::parse(url).context("parsing a host reachability URL")?;
let timer = Timer::start();
let options = FetchOptions::NoStoreWithoutCredentials;
let fetched = http::fetch_from_worker(client, iframe, &url, options);
outcomes.push(match time::timeout(REACHABILITY_TIMEOUT, fetched).await {
Ok(Ok(response))
if response
.headers()
.get("access-control-allow-origin")
.and_then(|allowed| allowed.to_str().ok())
.is_some_and(|allowed| allowed == "*" || allowed == origin) =>
{
host_reachability::Outcome::Answered {
elapsed_ms: timer.elapsed_ms() as i64,
}
}
_ => host_reachability::Outcome::Rejected,
});
}
observed.host_reachability = Some(outcomes);
}
Some(Operation::WebSocketEcho { fields }) => {
observed.websocket_echo = Some(echo_websocket(session, fields, options).await?);
}
Some(Operation::WorkerFetch { fields }) => {
let url = fields.url(options)?;
let options = FetchOptions::NoStoreWithoutCredentials;
@@ -398,7 +490,6 @@ fn window_geometry(
#[cfg(test)]
mod tests {
use super::*;
use crate::js;
#[test]
fn a_profile_duration_overrides_the_default_for_its_family() {
@@ -413,9 +504,10 @@ mod tests {
],
}))
.unwrap();
let observed = Observed::default();
let mut configured = BTreeMap::new();
assert_eq!(durations(&plan, &configured, Some(40), None), [2, 2]);
assert_eq!(durations(&plan, &configured, &observed, None), [2, 2]);
configured.insert("empty".into(), 7);
assert_eq!(durations(&plan, &configured, Some(40), None), [7, 2]);
assert_eq!(durations(&plan, &configured, &observed, None), [7, 2]);
}
}
+10
View File
@@ -138,6 +138,14 @@ pub fn analyze(source: &Source, program: &[u8]) -> Result<Analysis> {
}
}
let header: BTreeSet<String> = index.header().values().cloned().collect();
let mut wrapper: BTreeSet<String> = discovery
.probes
.first()
.map(|first| first.features.iter().cloned().collect())
.unwrap_or_default();
for probe in &discovery.probes {
wrapper.retain(|text| probe.features.contains(text));
}
let mut probes = Vec::new();
let mut evidence = Vec::new();
for (position, raw) in discovery.probes.into_iter().enumerate() {
@@ -152,9 +160,11 @@ pub fn analyze(source: &Source, program: &[u8]) -> Result<Analysis> {
vocabulary: &vocabulary,
position,
header: &header,
wrapper: &wrapper,
pool,
entry: raw.function.pc,
session_features: &raw.features,
writes: &raw.writes,
strings: Strings::new(&features, &outputs),
})
.or(reference.map(|reference| Operation::Replay { reference }));
+8
View File
@@ -5,6 +5,7 @@
use std::collections::{BTreeSet, HashSet};
use crate::listing::{self, Index};
use crate::stage2::records::WriteOrder;
use crate::stage2::vocabulary::Vocabulary;
/// Collection strings and output names mapped to the reference build. Preserves string order
@@ -87,11 +88,15 @@ pub(crate) struct ProbeView<'probe> {
pub position: usize,
/// The names the program's header loads.
pub header: &'probe BTreeSet<String>,
/// Wrapper strings shared by every probe in this program, using the session's names.
pub wrapper: &'probe BTreeSet<String>,
pub pool: &'probe str,
/// Where its collection function starts.
pub entry: u32,
/// Its strings in the session's names.
pub session_features: &'probe [String],
/// Fields written by the probe, using the session's names.
pub writes: &'probe WriteOrder,
/// Its strings and outputs in the reference build's names.
pub strings: Strings<'probe>,
}
@@ -122,9 +127,11 @@ mod tests {
vocabulary: &vocabulary,
position: 0,
header: &header,
wrapper: &header,
pool: "",
entry: 0,
session_features: features,
writes: &WriteOrder::default(),
strings: Strings::new(features, outputs),
})
}
@@ -182,6 +189,7 @@ mod tests {
}
/// Checks that each recognizer accepts its reference outputs and rejects missing outputs.
/// `tests/stage2.rs` snapshots verify the recovered operation.
#[test]
fn recognizers_need_every_output_stored() {
use crate::stage2::probes::{private_token, worker_fetch};
+38 -1
View File
@@ -11,7 +11,7 @@ use serde::{Deserialize, Serialize};
use swc_core::ecma::ast::{CallExpr, Callee, MemberExpr, MemberProp, VarDeclarator};
use swc_core::ecma::visit::{Visit, VisitWith};
use crate::js::{JsObject, ast, json};
use crate::js::{self, JsObject, ast, json};
use crate::performance_clock::{PerformanceClock, Resolution};
use crate::stage2::analysis::recognize::ProbeView;
use crate::stage2::worker_timing::Samples;
@@ -117,6 +117,35 @@ impl Fields {
total_ms: spend(Duration::ZERO) - compiled,
})
}
/// Recovers device costs from a browser benchmark `record`, reversing [`Self::measure`].
/// Includes instantiation time and each kernel speed per round, rounded to a microsecond per
/// million iterations.
pub fn costs(&self, record: &JsObject) -> Result<WorkerCosts> {
let read = |name: &str| {
record
.get(name)
.with_context(|| format!("the benchmark record has no `{name}`"))
};
let samples: Vec<Vec<f64>> = js::from_value(read(&self.samples)?.clone())
.context("the benchmark samples are not lists of times")?;
let compile_ms = read(&self.compilation)?
.as_f64()
.context("the benchmark's instantiation time is not a number")?;
let mut speeds: Vec<Vec<f64>> = vec![Vec::new(); self.order.len()];
let kernels = self.order.iter().zip(&self.iterations).zip(&samples);
for ((&index, &iterations), samples) in kernels {
let per_million = |ms: &f64| (ms * 1e9 / f64::from(iterations)).round() / 1000.0;
speeds
.get_mut(index)
.with_context(|| format!("benchmark kernel {index} is outside the plan"))?
.extend(samples.iter().map(per_million));
}
Ok(WorkerCosts {
compile_ms: vec![compile_ms],
kernel_ms_per_million: speeds,
})
}
}
/// Recovers field names from the worker AST and the execution plan from VM constants.
@@ -337,6 +366,13 @@ mod tests {
[[8.0, 8.0], [1.0, 1.0], [1.0, 1.0], [1.0, 1.0]]
);
assert_eq!((measured.compilation_ms, measured.total_ms), (3.0, 22.0));
// Recover the input speeds from each round of the record.
let read = fields.costs(&fields.collect(&measured)).unwrap();
assert_eq!(read.compile_ms, [3.0]);
assert_eq!(
read.kernel_ms_per_million,
[[0.5, 0.5], [2.0, 2.0], [1.0, 1.0], [4.0, 4.0]]
);
let missing = WorkerCosts {
kernel_ms_per_million: costs.kernel_ms_per_million[..3].to_vec(),
..costs
@@ -362,4 +398,5 @@ mod tests {
);
}
}
}
+1068 -458
View File
File diff suppressed because it is too large Load Diff
+3 -4
View File
@@ -219,12 +219,11 @@ fn click_delay(index: &Index<'_>, stack_field: &str) -> Result<u64> {
/// The checkbox program record's status, message and clock fields.
fn envelope(index: &Index<'_>, record: &RecordTemplate) -> Result<Completion> {
let stores = index.stores();
let names = index.header();
// Look for field names throughout the program; they are not limited to the header.
let status = candidates::exactly_one(
stores.iter().filter(|store| {
names.values().any(|name| name == &store.key)
&& matches!(store.value, Term::Const(Constant::Number(status))
if status == f64::from(COMPLETED_STATUS))
matches!(store.value, Term::Const(Constant::Number(status))
if status == f64::from(COMPLETED_STATUS))
}),
"completed status write",
)?;
+2
View File
@@ -6,6 +6,7 @@ pub(super) mod dates;
pub(super) mod dom_mutation;
pub(super) mod empty;
pub(super) mod error_message_length;
pub(crate) mod host_reachability;
pub(crate) mod ice;
pub(crate) mod image;
pub(crate) mod media;
@@ -16,5 +17,6 @@ mod platform;
pub(crate) mod private_token;
pub(super) mod rects;
pub(super) mod stack;
pub(crate) mod websocket_echo;
pub(crate) mod worker_fetch;
pub(super) mod worker_navigator;
+14 -26
View File
@@ -7,33 +7,26 @@ use crate::js::JsValue;
use crate::listing::fold::{Frame, Known};
use crate::stage2::analysis::recognize::ProbeView;
use crate::stage2::records::{COMPLETED_STATUS, INITIAL_STATUS};
use crate::stage2::reference;
use crate::vm::{Constant, Effect, Exit, Listing, Term, dataflow};
/// Array methods the wrapper calls on its own state.
const ARRAY_METHODS: [&str; 5] = ["eval", "slice", "push", "pop", "length"];
pub(crate) fn recognize(probe: &ProbeView<'_>) -> Option<()> {
let empty = empty_probe(probe.index.listing(), probe.entry, |name| {
probe
.vocabulary
.reference_name(name)
.unwrap_or_else(|| name.to_owned())
});
empty.then_some(())
empty_probe(probe.index.listing(), probe.entry, probe.wrapper).then_some(())
}
/// Recognizes probes whose successful path writes only status and timing. Requires a positive
/// match; an unrecognized family may still produce results. `reference_name` maps names to the
/// reference build and leaves unknown names unchanged.
fn empty_probe(listing: &Listing, entry: u32, reference_name: impl Fn(&str) -> String) -> bool {
/// match because an unknown probe family may still produce results. `wrapper` contains the shared
/// strings used for wrapper reads and writes. Builds rename these strings together.
fn empty_probe(listing: &Listing, entry: u32, wrapper: &BTreeSet<String>) -> bool {
let mut closures = BTreeSet::new();
let registers: Frame = Frame::default();
let reached = dataflow::forward(listing, [(entry, registers)], |path, registers| {
let reached = dataflow::forward(listing, [(entry, registers)], |_, path, registers| {
// A path that throws, such as a check that a callee is a function,
// is not the successful one.
if path.exit == Exit::Throw {
return ControlFlow::Continue(());
return ControlFlow::Continue(true);
}
for effect in &path.effects {
if let Effect::SetProperty { object, key, value } = effect {
@@ -44,8 +37,7 @@ fn empty_probe(listing: &Listing, entry: u32, reference_name: impl Fn(&str) -> S
let key = registers.resolve(key);
let value = registers.resolve(value);
let wrapper_write = matches!(&key,
Some(Known::Literal(JsValue::String(name)))
if reference_name(name) == reference::EMPTY_COLLECTOR)
Some(Known::Literal(JsValue::String(name))) if wrapper.contains(name))
|| matches!(&value, Some(Known::Literal(JsValue::Number(number)))
if [INITIAL_STATUS, COMPLETED_STATUS].map(f64::from).contains(number))
|| matches!(&value, Some(Known::Literal(JsValue::String(text)))
@@ -61,9 +53,8 @@ fn empty_probe(listing: &Listing, entry: u32, reference_name: impl Fn(&str) -> S
closures.insert(*pc);
}
Term::Get(_, key) if let Term::Const(Constant::String(name)) = &**key => {
let name = reference_name(name);
extra_work |= !reference::EMPTY_WRAPPER_READS.contains(&name.as_str())
&& !ARRAY_METHODS.contains(&name.as_str());
extra_work |=
!wrapper.contains(name) && !ARRAY_METHODS.contains(&name.as_str());
}
Term::New { .. } => extra_work = true,
_ => {}
@@ -75,7 +66,7 @@ fn empty_probe(listing: &Listing, entry: u32, reference_name: impl Fn(&str) -> S
registers.set(*register, registers.resolve(value));
}
}
ControlFlow::Continue(())
ControlFlow::Continue(true)
});
// Every wrapper path must stay within decoded instructions.
matches!(reached, ControlFlow::Continue(reached)
@@ -107,10 +98,7 @@ mod tests {
arity: 0,
},
),
Effect::Set(
2,
Term::Const(Constant::String(reference::EMPTY_COLLECTOR.into())),
),
Effect::Set(2, Term::Const(Constant::String("collector".into()))),
set_property(Term::Reg(2), Term::Reg(1)),
Effect::Set(3, Term::Const(Constant::Number(3.0))),
set_property(Term::Reg(7), Term::Reg(3)),
@@ -131,13 +119,13 @@ mod tests {
)]),
..Listing::default()
};
let reference_name = |name: &str| name.to_owned();
assert!(empty_probe(&listing, 0, reference_name));
let wrapper = BTreeSet::from(["collector".to_owned()]);
assert!(empty_probe(&listing, 0, &wrapper));
let path = &mut listing.instructions.get_mut(&0).unwrap().paths[0];
path.effects.push(set_property(
Term::Const(Constant::String("collected".into())),
Term::Reg(20),
));
assert!(!empty_probe(&listing, 0, reference_name));
assert!(!empty_probe(&listing, 0, &wrapper));
}
}
+4 -4
View File
@@ -4,10 +4,10 @@
use crate::stage2::analysis::recognize::ProbeView;
use crate::stage2::reference;
/// Builds can read the message using a property name stored in a register. Only `fromCodePoint` is
/// guaranteed to appear in the probe strings.
pub(crate) fn recognize(probe: &ProbeView<'_>) -> Option<()> {
let strings = &probe.strings;
(strings.has("fromCodePoint")
&& strings.has("message")
&& strings.stores(reference::ERROR_MESSAGE_LENGTH_RESULT))
.then_some(())
(strings.has("fromCodePoint") && strings.stores(reference::ERROR_MESSAGE_LENGTH_RESULT))
.then_some(())
}
+92
View File
@@ -0,0 +1,92 @@
//! Measures worker fetch times for Cloudflare hosts. Some builds from 2026-10-27 onward include
//! this probe; the reference build has no matching probe.
//!
//! The worker fetches each URL with `{method: "GET", mode: "cors", credentials: "omit", cache:
//! "no-store", redirect: "error", referrerPolicy: "no-referrer"}`. It reports the response time,
//! rejection, or exception. Each result is `[elapsed, status]`; `elapsed` is null unless a response
//! arrived.
use serde::{Deserialize, Serialize};
use crate::js::{JsObject, JsValue, json};
use crate::stage2::analysis::recognize::ProbeView;
/// Worker script prefix, completed with the URL for each fetch.
const SCRIPT: &str = "var t=Date.now();try{fetch(";
/// URLs fetched by the probe and field names used in its results.
#[derive(Clone, Debug, Deserialize, Serialize)]
pub struct Fields {
pub urls: Vec<String>,
/// Result field written after all fetches finish.
pub result: String,
/// Status strings for a response and a rejected fetch.
pub answered: String,
pub rejected: String,
}
/// Outcome of one fetch.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum Outcome {
Answered { elapsed_ms: i64 },
Rejected,
}
impl Fields {
#[must_use]
pub fn collect(&self, outcomes: &[Outcome]) -> JsObject {
let results: Vec<JsValue> = outcomes
.iter()
.map(|outcome| match outcome {
Outcome::Answered { elapsed_ms } => json!([elapsed_ms, self.answered]),
Outcome::Rejected => json!([null, self.rejected]),
})
.collect();
JsObject::from_iter([(self.result.clone(), JsValue::Array(results))])
}
}
/// Recognizes the probe from its worker script. The message handler checks exception and rejection
/// flags before elapsed time. As a result, the status strings appear before the script in this
/// order: answered, rejected, threw.
pub(crate) fn recognize(probe: &ProbeView<'_>) -> Option<Fields> {
let strings = probe.session_features;
let script = strings.iter().position(|text| text == SCRIPT)?;
let [answered, rejected, _threw] = strings.get(script.checked_sub(3)?..script)? else {
return None;
};
let urls: Vec<String> = strings
.iter()
.filter(|text| text.starts_with("https://") && text.ends_with('/'))
.cloned()
.collect();
let [result] = &probe.writes.late[..] else {
return None;
};
(!urls.is_empty()).then(|| Fields {
urls,
result: result.clone(),
answered: answered.clone(),
rejected: rejected.clone(),
})
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn records_each_fetch_as_elapsed_and_status() {
let fields = Fields {
urls: vec!["https://a.example/".into(), "https://b.example/".into()],
result: "r".into(),
answered: "ok".into(),
rejected: "no".into(),
};
let outcomes = [Outcome::Rejected, Outcome::Answered { elapsed_ms: 12 }];
assert_eq!(
JsValue::Object(fields.collect(&outcomes)),
json!({"r": [[null, "no"], [12, "ok"]]})
);
}
}
+210 -4
View File
@@ -2,7 +2,10 @@
//! window, which [`super::ice`] refreshes for each session. Candidate times use wall-clock
//! observations.
use std::borrow::Cow;
use anyhow::{Context, Result, ensure};
use percent_encoding::percent_decode_str;
use serde::{Deserialize, Serialize};
use crate::js::{self, ErrorValue, JsObject, JsValue, json};
@@ -82,8 +85,11 @@ pub struct Connection {
pub data_channel: Option<JsValue>,
/// The offer the earlier probe saved.
pub sdp: Option<JsValue>,
#[serde(skip_serializing_if = "Option::is_none")]
pub channel_error: Option<JsValue>,
#[serde(skip_serializing_if = "Option::is_none")]
pub offer_error: Option<JsValue>,
#[serde(skip_serializing_if = "Option::is_none")]
pub gather_error: Option<JsValue>,
}
@@ -132,9 +138,12 @@ fn codec(value: &JsValue, audio: bool) -> Option<String> {
Some(text)
}
/// Encodes a decoding result as bits for supported, smooth, and power efficient, in that order.
/// Decoding result properties in bit order.
const DECODING_PROPERTIES: [&str; 3] = ["supported", "smooth", "powerEfficient"];
/// Encodes a decoding result as one bit per property.
fn decoding_bits(properties: &JsObject) -> i32 {
["supported", "smooth", "powerEfficient"]
DECODING_PROPERTIES
.iter()
.enumerate()
.filter(|(_, key)| properties.get(**key).is_some_and(js::truthy))
@@ -325,6 +334,157 @@ impl Fields {
}
Ok(result)
}
/// Recovers browser observations from `record` using reference field names. [`Self::collect`]
/// can then rebuild the record exactly. The connection snapshot begins at `started_ms`, the
/// record start mark. Codecs retain only properties present in the record. Treats decoding as
/// skipped for the V8 message length when no excluded type reports a result.
pub fn observed(&self, record: &JsObject, started_ms: i64) -> Result<Measurement> {
let measurement = self.read(record, started_ms)?;
ensure!(
self.collect(&measurement)? == *record,
"the media record holds values the probe would not write"
);
Ok(measurement)
}
fn read(&self, record: &JsObject, started_ms: i64) -> Result<Measurement> {
let field = |name: &str| {
record
.get(name)
.with_context(|| format!("the media record has no `{name}`"))
};
if *field(MEDIA_STATE)? == MEDIA_UNAVAILABLE {
return Ok(Measurement::Unavailable);
}
let spelled: [Vec<String>; 2] = js::from_value(field(MEDIA_CODECS)?.clone())
.context("the media codecs are not two lists")?;
let calls: Vec<Access> = spelled
.iter()
.enumerate()
.map(|(index, spelled)| {
let codecs: Vec<JsValue> = spelled
.iter()
.map(|text| unspell(text, index == 0))
.collect::<Result<_>>()?;
Ok(Access::Returned {
value: Some(json!({ "codecs": codecs })),
})
})
.collect::<Result<_>>()?;
// Read MediaSource support bits followed by decoding bits or null, for audio first and then
// video.
let (audio_support, video_support, audio_decoding, video_decoding): (
Vec<i8>,
Vec<i8>,
Option<Vec<i32>>,
Option<Vec<i32>>,
) = js::from_value(field(MEDIA_SUPPORT)?.clone())
.context("the media support is not four entries")?;
let reported = [
(&self.audio_types, &audio_decoding),
(&self.video_types, &video_decoding),
];
let excluded: Vec<i32> = reported
.iter()
.flat_map(|(types, bits)| types.iter().zip(bits.iter().flatten()))
.filter(|(mime, _)| self.excluded_types.contains(mime))
.map(|(_, &bits)| bits)
.collect();
let skipped = !excluded.is_empty() && excluded.iter().all(|&bits| bits == 0);
let type_support = audio_support
.iter()
.chain(&video_support)
.map(|&bit| (bit >= 0).then(|| json!(bit == 1)));
let preparation = Preparation {
receiver: Receiver::Observed { calls },
type_support: Some(type_support.collect()),
audio_decoding: self.decodes(&self.audio_types, audio_decoding, skipped),
video_decoding: self.decodes(&self.video_types, video_decoding, skipped),
message_length: skipped.then(|| json!(V8_MESSAGE_LENGTH)),
};
let candidates: Vec<JsObject> = js::from_value(field(MEDIA_CANDIDATES)?.clone())
.context("the media candidates are not objects")?;
let published_candidates: Vec<Candidate> = candidates
.into_iter()
.map(|mut candidate| {
let time = candidate
.get(MEDIA_CANDIDATE_TIME)
.and_then(JsValue::as_i64)
.context("a media candidate has no time")?;
Ok(Candidate {
candidate: candidate.shift_remove(MEDIA_CANDIDATE).unwrap_or_default(),
observed_ms: started_ms + time,
})
})
.collect::<Result<_>>()?;
let elapsed = field(MEDIA_ELAPSED)?
.as_i64()
.context("the media probe's elapsed time is not a number")?;
let optional = |name: &str| record.get(name).cloned();
Ok(Measurement::Observed {
preparation,
snapshot: Box::new(Snapshot {
connection: Connection {
published_candidates,
data_channel: optional(MEDIA_DATA_CHANNEL),
sdp: optional(MEDIA_SDP),
channel_error: optional(MEDIA_CHANNEL_ERROR),
offer_error: optional(MEDIA_SEED_OFFER_ERROR),
gather_error: optional(MEDIA_SEED_GATHER_ERROR),
},
started_ms,
finished_ms: started_ms + elapsed,
ice_state: optional(MEDIA_ICE_STATE),
}),
})
}
/// Reconstructs one decoding result per type from `bits`, reversing [`decoding_bits`]. Omits
/// excluded types when `skipped` is true.
fn decodes(
&self,
types: &[String],
bits: Option<Vec<i32>>,
skipped: bool,
) -> Option<Vec<Decode>> {
let decode = |(mime, bits): (&String, i32)| match bits {
_ if skipped && self.excluded_types.contains(mime) => Decode::Skipped,
-1 => Decode::Failed,
bits => {
let keys = DECODING_PROPERTIES.iter().enumerate();
let properties =
keys.map(|(bit, key)| ((*key).to_owned(), json!(bits & (1 << bit) != 0)));
Decode::Resolved {
properties: Some(properties.collect()),
}
}
};
Some(types.iter().zip(bits?).map(decode).collect())
}
}
/// Parses the output of [`codec`], preserving only the properties present in the string.
fn unspell(text: &str, audio: bool) -> Result<JsValue> {
let (head, line) = text
.split_once(';')
.map_or((text, None), |(head, line)| (head, Some(line)));
let mut codec = JsObject::new();
if audio {
let (mime, rate) = head
.rsplit_once('/')
.and_then(|(mime, rate)| Some((mime, rate.parse::<f64>().ok()?)))
.with_context(|| format!("audio codec {text} has no clock rate"))?;
codec.insert("mimeType".to_owned(), json!(mime));
codec.insert("clockRate".to_owned(), json!(rate));
} else {
codec.insert("mimeType".to_owned(), json!(head));
}
if let Some(line) = line {
codec.insert("sdpFmtpLine".to_owned(), json!(line));
}
Ok(JsValue::Object(codec))
}
pub(crate) fn recognize(probe: &ProbeView<'_>) -> Option<Box<Fields>> {
@@ -343,9 +503,14 @@ pub(crate) fn recognize(probe: &ProbeView<'_>) -> Option<Box<Fields>> {
]) {
return None;
}
// Builds may percent-encode the type lists.
let decoded: Vec<Cow<'_, str>> = strings
.features()
.iter()
.filter_map(|text| percent_decode_str(text).decode_utf8().ok())
.collect();
let find = |prefix: &str, codec: &str| {
strings
.features()
decoded
.iter()
.find(|text| text.starts_with(prefix) && text.contains(codec))
};
@@ -359,3 +524,44 @@ pub(crate) fn recognize(probe: &ProbeView<'_>) -> Option<Box<Fields>> {
excluded_types: types(excluded),
}))
}
#[cfg(test)]
mod tests {
use super::*;
/// The probe checks eight audio types and ten video types in this order.
fn fields() -> Fields {
let named = |kind: &str, count: usize| -> Vec<String> {
(0..count).map(|index| format!("{kind}{index}")).collect()
};
Fields {
audio_types: named("audio", 8),
video_types: named("video", 10),
// AC-3, E-AC-3 and Theora.
excluded_types: vec!["audio1".into(), "audio2".into(), "video9".into()],
}
}
/// Recover observations from each profile's media record and rebuild the same record, including
/// skipped decoding on V8.
#[test]
fn reads_back_the_observations_a_record_reports() {
// cfsolve.test ships only the Safari profile; the Chromium profile stays out.
let profiles = [(include_str!("../../../profiles/safari-26-ios.json"), false)];
for (profile, v8) in profiles {
let profile: JsValue = serde_json::from_str(profile).unwrap();
let media = profile["second"]["facts"]["media"].clone();
let recorded: Measurement = js::from_value(media).unwrap();
let record = fields().collect(&recorded).unwrap();
let Measurement::Observed { preparation, .. } = fields().observed(&record, 5).unwrap()
else {
panic!("the profile's connection was not read back");
};
let skipped = preparation.message_length == Some(json!(V8_MESSAGE_LENGTH));
assert_eq!(skipped, v8);
}
let unavailable = JsObject::from_iter([(MEDIA_STATE.to_owned(), json!(MEDIA_UNAVAILABLE))]);
let read = fields().observed(&unavailable, 5).unwrap();
assert!(matches!(read, Measurement::Unavailable));
}
}
+58 -7
View File
@@ -1,6 +1,8 @@
//! Reduces `performance.getEntries()` results to rows with type-specific formats.
use std::collections::{BTreeMap, BTreeSet};
use std::convert::Infallible;
use std::ops::ControlFlow;
use anyhow::{Result, bail};
use serde::{Deserialize, Serialize};
@@ -8,12 +10,12 @@ use swc_core::ecma::ast::{BinaryOp, UnaryOp};
use crate::engine::Engine;
use crate::js::{JsObject, JsValue, json};
use crate::listing::fold::{Frame, Known};
use crate::listing::fold::{self, Frame, Known};
use crate::resource_timing::{LoadTiming, NEXT_HOP_PROTOCOL};
use crate::stage2::analysis::recognize::ProbeView;
use crate::stage2::records::ProbePlan;
use crate::stage2::registry::Operation;
use crate::vm::{Effect, Exit, Term};
use crate::vm::{Effect, Exit, Listing, Term, dataflow};
/// How the probe writes the row of one entry type.
#[derive(Clone, Debug, Deserialize, Serialize)]
@@ -200,16 +202,41 @@ struct RowWrite {
/// Recovers row formats from `entryType` comparisons and the row blocks they branch to.
pub(crate) fn recognize(probe: &ProbeView<'_>) -> Option<Fields> {
let index = probe.index;
let listing = index.listing();
let code = index.reachable(probe.entry);
let mut frame: Frame<Held> = Frame::default();
// Registers are reused across branches. At each instruction, keep only facts shared by every
// incoming path. The probe and its nested functions start with no known values. Ignore paths
// ruled out by known values.
let mut entries = vec![probe.entry];
for pc in &code {
for effect in listing.instructions[pc].effects() {
effect.visit_terms(&mut |term| {
if let Term::Closure { pc, .. } = term {
entries.push(*pc);
}
});
}
}
let starts = entries.into_iter().map(|pc| (pc, Frame::default()));
let ControlFlow::Continue(incoming) = dataflow::forward(listing, starts, |pc, path, frame| {
frame.begin();
let runs = fold::feasible(path, |term| frame.resolve(term));
if runs {
frame.follow(pc, &path.effects, evaluate, |_, _| {});
}
ControlFlow::<Infallible, bool>::Continue(runs)
});
let mut targets: Vec<(String, u32)> = Vec::new();
let mut mark_prefix = None;
// Index rows by the program counter where their objects were created.
let mut rows: BTreeMap<u32, Row> = BTreeMap::new();
for &pc in &code {
let instruction = &index.listing().instructions[&pc];
for path in &instruction.paths {
for path in &listing.instructions[&pc].paths {
let mut frame: Frame<Held> = incoming.get(&pc).cloned().unwrap_or_default();
frame.begin();
if !fold::feasible(path, |term| frame.resolve(term)) {
continue;
}
// A comparison against a type string leads to that type's block.
if let Exit::Next { pc: target, .. } = path.exit
&& let [(condition, holds)] = path.conditions.as_slice()
@@ -271,13 +298,13 @@ pub(crate) fn recognize(probe: &ProbeView<'_>) -> Option<Fields> {
let entries = rows
.values()
.find_map(|row| (!row.list.is_empty()).then(|| row.list.clone()))?;
// Each type's block is the first row created at or after its target.
let mut formats = BTreeMap::new();
let mut claimed = BTreeSet::new();
for (kind, target) in targets {
let Some((&pc, row)) = rows.range(target..).next() else {
let Some(pc) = block_row(listing, &rows, target) else {
continue;
};
let row = &rows[&pc];
claimed.insert(pc);
let (marker, rest) = marked(&row.columns)?;
let columns: Vec<(String, Column)> = rest
@@ -313,6 +340,28 @@ pub(crate) fn recognize(probe: &ProbeView<'_>) -> Option<Fields> {
})
}
/// Finds the first row created by a type's block, following the single path from `target`. Returns
/// no row for comparisons that only produce a boolean for a later branch.
fn block_row(listing: &Listing, rows: &BTreeMap<u32, Row>, target: u32) -> Option<u32> {
let mut pc = target;
loop {
if rows.contains_key(&pc) {
return Some(pc);
}
let instruction = listing.instructions.get(&pc)?;
let mut next = instruction
.paths
.iter()
.filter_map(|path| path.exit.continues_at());
let first = next.next()?;
// Ignore paths that throw, such as call guards.
if next.any(|other| other.pc != first.pc) || first.pc <= pc {
return None;
}
pc = first.pc;
}
}
/// The row's marker and columns, with its first column stored separately.
fn marked(columns: &[RowWrite]) -> Option<(&str, &[RowWrite])> {
let (first, rest) = columns.split_first()?;
@@ -349,6 +398,8 @@ fn evaluate(frame: &Frame<Held>, term: &Term) -> Option<Known<Held>> {
Term::Get(_, key) if is_text(frame, key, "getEntries") => Known::Ext(Held::Entries),
_ => return None,
},
// If `getEntries` is missing, the probe uses an empty list, which also has no entries.
Term::Array(elements) if elements.is_empty() => Known::Ext(Held::Entries),
Term::Get(object, key) => match (frame.resolve(object), frame.resolve(key)) {
(Some(Known::Ext(Held::Entries)), _) => Known::Ext(Held::Entry),
(Some(Known::Ext(Held::Entry)), Some(Known::Literal(JsValue::String(name))))
+11 -3
View File
@@ -1,5 +1,6 @@
//! Recovers rectangle-probe element IDs for the selector log. Replays the measured result.
use percent_encoding::percent_decode_str;
use serde::{Deserialize, Serialize};
use crate::stage2::analysis::recognize::ProbeView;
@@ -41,11 +42,18 @@ pub(crate) fn recognize(probe: &ProbeView<'_>) -> Option<Fields> {
{
return None;
}
strings.windows(3).find_map(|parts| {
if parts[2] != "split" || parts[1].is_empty() {
// Match `list.split(separator)`, including lists decoded from percent encoding first.
(2..strings.len()).find_map(|at| {
let separator = &strings[at - 1];
if strings[at] != "split" || separator.is_empty() {
return None;
}
let ids: Vec<String> = parts[0].split(&parts[1]).map(str::to_owned).collect();
let list = match &strings[at - 2] {
decode if decode == "decodeURIComponent" => strings.get(at.checked_sub(3)?)?,
list => list,
};
let list = percent_decode_str(list).decode_utf8().ok()?;
let ids: Vec<String> = list.split(separator.as_str()).map(str::to_owned).collect();
let valid = ids.len() == 10
&& ids
.iter()
+82 -43
View File
@@ -2,7 +2,6 @@
//! pass those calls to [`crate::stage2::call_stack::recover_probe`] to rebuild the frames.
use std::collections::BTreeSet;
use std::ops::RangeBounds;
use serde::{Deserialize, Serialize};
@@ -28,47 +27,20 @@ impl Fields {
}
}
/// A VM call of a closure the program created.
#[derive(Clone, Copy)]
struct ClosureCall {
/// Where the called closure starts.
closure: u32,
opcode: u8,
arguments: usize,
}
/// Returns closure calls in `range`, in program-counter order.
fn closure_calls(
index: &Index<'_>,
range: impl RangeBounds<u32>,
) -> impl Iterator<Item = ClosureCall> {
let instructions = &index.listing().instructions;
index.effects_in(range).filter_map(move |(pc, effect)| {
let (callee, arguments) = effect.call()?;
let (_, Term::Closure { pc: closure, .. }) = index.dereference(pc, callee)? else {
return None;
};
Some(ClosureCall {
closure,
opcode: instructions[&pc].opcode,
arguments: arguments.len(),
})
})
}
/// Reads the calls from the program through the probe function at `entry` to `new Error()`.
/// Finds the closure called by the probe function at `entry` to construct `new Error()`.
fn calls(index: &Index<'_>, entry: u32) -> Option<ProbeCalls> {
let (inner, construct) = closure_calls(index, index.function_range(entry)?)
.find_map(|call| Some((call, construction(index, call.closure)?)))?;
let dispatch = closure_calls(index, ..).find(|call| call.closure == entry)?;
let construct = index
.effects_in(index.function_range(entry)?)
.find_map(|(pc, effect)| {
let (callee, _) = effect.call()?;
let (_, Term::Closure { pc: closure, .. }) = index.dereference(pc, callee)? else {
return None;
};
construction(index, closure)
})?;
Some(ProbeCalls {
construct,
inner: index.arity(inner.closure)?,
call: inner.opcode,
passed: inner.arguments,
outer: index.arity(entry)?,
dispatch: dispatch.opcode,
dispatched: dispatch.arguments,
arity: index.arity(entry)?,
})
}
@@ -91,6 +63,48 @@ fn construction(index: &Index<'_>, entry: u32) -> Option<u8> {
})
}
/// Finds the output field hidden by base64 encoding and a two-byte XOR key. A name that decodes to
/// `stack` identifies the key. The output field is the remaining name after excluding `stack` and
/// the record counter from the header.
fn encoded_result_field(features: &[String], header: &BTreeSet<String>) -> Option<String> {
use base64::Engine;
use base64::engine::general_purpose::STANDARD;
let decoded: Vec<Vec<u8>> = features
.iter()
.filter_map(|text| STANDARD.decode(text).ok())
.filter(|bytes| (3..=12).contains(&bytes.len()))
.collect();
for candidate in decoded.iter().filter(|bytes| bytes.len() == "stack".len()) {
let key = [candidate[0] ^ b's', candidate[1] ^ b't'];
let reveal = |bytes: &Vec<u8>| {
let revealed = bytes
.iter()
.zip(key.iter().cycle())
.map(|(byte, mask)| byte ^ mask);
String::from_utf8(revealed.collect()).ok()
};
if reveal(candidate).as_deref() != Some("stack") {
continue;
}
// Plain strings such as `this` can also be valid base64. Restrict candidates to the
// four-to-nine-character program names.
let names = decoded.iter().filter_map(reveal).filter(|name| {
(4..=9).contains(&name.len())
&& name.starts_with(|first: char| first.is_ascii_alphabetic())
&& name
.chars()
.all(|character| character.is_ascii_alphanumeric())
&& name != "stack"
&& !header.contains(name)
});
if let Ok(result) = candidates::exactly_one(names, "stack result field") {
return Some(result);
}
}
None
}
/// Finds the output field in the string table by excluding the header's record-counter name,
/// `stack`, and checksum numbers. Supports reversed entries.
fn result_field(features: &[String], header: &BTreeSet<String>) -> Option<String> {
@@ -124,10 +138,12 @@ fn result_field(features: &[String], header: &BTreeSet<String>) -> Option<String
}
pub(crate) fn recognize(probe: &ProbeView<'_>) -> Option<Fields> {
result_field(probe.session_features, probe.header).map(|result| Fields {
result,
calls: calls(probe.index, probe.entry),
})
result_field(probe.session_features, probe.header)
.or_else(|| encoded_result_field(probe.session_features, probe.header))
.map(|result| Fields {
result,
calls: calls(probe.index, probe.entry),
})
}
#[cfg(test)]
@@ -153,4 +169,27 @@ mod tests {
}
assert!(result_field(&[TABLES[0].to_owned()], &BTreeSet::new()).is_none());
}
/// Names captured from c787ce48cf6b sessions with XOR keys 0x91 0xa2 and 0xff 0x75. The second
/// key also decodes the plain string `this` to `ImS`, which must be excluded.
#[test]
fn reveals_encoded_names_with_the_key_that_spells_stack() {
let header = BTreeSet::from(["XNWt6".to_owned()]);
for features in [
[
"atob", "yezG1qc=", "0uj6w/Wb", "4tbwwfo=", "jROwcoLu", "this",
],
[
"atob", "jAGeFpQ=", "pzuoAck=", "vD+UFJtM", "KKExCrEv", "this",
],
] {
let features = features.map(str::to_owned);
assert_eq!(
encoded_result_field(&features, &header).as_deref(),
Some("CJkad9"),
"{features:?}"
);
assert!(encoded_result_field(&features, &BTreeSet::new()).is_none());
}
}
}
+255
View File
@@ -0,0 +1,255 @@
//! Measures WebSocket round trips to the challenge platform. Some builds from 2026-10-27 onward
//! include this probe; the reference build has no matching probe.
//!
//! Connects to `wss://<iframe host>/cdn-cgi/challenge-platform/h/<platform>/w`, using a platform
//! option and a 500 ms timeout. After opening, sends `String(performance.now())`. For each echo,
//! records the current clock minus the echoed value, then sends a new reading. Stops after six
//! echoes.
//!
//! The record contains status, sent and received counts, opening time, round-trip times, and total
//! duration.
use anyhow::Result;
use serde::{Deserialize, Serialize};
use url::{Position, Url};
use crate::js::{self, JsObject, Options, json};
use crate::stage2::analysis::recognize::ProbeView;
/// Number of echoes required to complete the probe.
pub(crate) const ECHOES: usize = 6;
/// Echo timeout in milliseconds.
pub(crate) const TIMEOUT_MS: u64 = 500;
/// Connection options and result field names for this session.
#[derive(Clone, Debug, Deserialize, Serialize)]
pub struct Fields {
/// The `_cf_chl_opt` option holding the platform path segment.
pub platform: String,
pub status: String,
pub sent: String,
pub received: String,
/// Time taken to open the socket; empty if it never opened.
pub opened: String,
pub round_trips: String,
pub elapsed: String,
pub statuses: Statuses,
}
/// The probe's status strings.
#[derive(Clone, Debug, Deserialize, Serialize)]
pub struct Statuses {
/// Every echo returned.
pub complete: String,
/// The exchange ended before all echoes returned.
pub incomplete: String,
pub timed_out: String,
pub failed_before_open: String,
pub failed_after_open: String,
/// The server closed the socket before all echoes returned.
pub closed: String,
}
/// Reason the exchange ended.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum End {
/// All messages were sent and the final echo was handled.
Echoed,
TimedOut,
Failed,
Closed,
}
/// Measurements from one WebSocket exchange.
#[derive(Clone, Debug, PartialEq)]
pub struct Measurement {
pub end: End,
pub sent: usize,
pub received: usize,
/// Time from socket construction to `open`, measured with `performance.now()`. Absent if the
/// socket never opened.
pub opened_ms: Option<f64>,
/// Round-trip time for each echo: current `performance.now()` minus the echoed reading.
pub round_trips: Vec<f64>,
/// Probe duration measured with `Date.now()`.
pub elapsed_ms: i64,
}
impl Fields {
/// Builds the socket URL using the host from `iframe`.
pub fn url(&self, options: &Options, iframe: &Url) -> Result<Url> {
let host = &iframe[Position::BeforeHost..Position::AfterPort];
let platform = js::string(options.get(self.platform.as_str()));
Ok(Url::parse(&format!(
"wss://{host}/cdn-cgi/challenge-platform/h/{platform}/w"
))?)
}
/// Builds the record in the same field order as the probe.
#[must_use]
pub fn collect(&self, measured: &Measurement) -> JsObject {
let statuses = &self.statuses;
let status = match measured.end {
End::Echoed if measured.round_trips.len() >= ECHOES => &statuses.complete,
End::Echoed => &statuses.incomplete,
End::TimedOut => &statuses.timed_out,
End::Failed if measured.opened_ms.is_some() => &statuses.failed_after_open,
End::Failed => &statuses.failed_before_open,
End::Closed => &statuses.closed,
};
// `Math.round` rounds halves up.
let opened = measured
.opened_ms
.map(|opened| js::string(Some(&json!((opened + 0.5).floor()))))
.unwrap_or_default();
let round_trips = json!(measured.round_trips).stringify().unwrap_or_default();
JsObject::from_iter([
(self.status.clone(), json!(status)),
(self.sent.clone(), json!(measured.sent.to_string())),
(self.received.clone(), json!(measured.received.to_string())),
(self.opened.clone(), json!(opened)),
(self.round_trips.clone(), json!(round_trips)),
(self.elapsed.clone(), json!(measured.elapsed_ms.to_string())),
])
}
}
/// Recognizes the probe by its socket handlers. Field and status names appear in a consistent order
/// around these handlers:
///
/// - The final summary lists status, sent count, received count, opening time, and error code
/// before `length`. Complete and incomplete status strings follow it.
/// - Round-trip times precede `JSON.stringify`; duration precedes `String(Date.now() - start)`.
/// - Timeout status precedes `String(Math.round(..))`, which records opening time.
/// - The error handler tests opening time against `""`, then selects the status for failure after
/// or before opening. The close status follows.
/// - The platform option precedes the URL suffix `/w`.
pub(crate) fn recognize(probe: &ProbeView<'_>) -> Option<Fields> {
let strings = probe.session_features;
let markers = ["WebSocket", "onopen", "onmessage", "onclose", "isFinite"];
if !markers
.iter()
.all(|marker| strings.iter().any(|text| text == marker))
{
return None;
}
let find = |sequence: &[&str]| {
strings
.windows(sequence.len())
.position(|window| window.iter().zip(sequence).all(|(text, want)| text == want))
};
let before = |sequence: &[&str]| strings.get(find(sequence)?.checked_sub(1)?).cloned();
let length = find(&["length"])?;
let [status, sent, received, opened, _error] = strings.get(length.checked_sub(5)?..length)?
else {
return None;
};
let [complete, incomplete] = strings.get(length + 1..length + 3)? else {
return None;
};
let finite = find(&["isFinite"])?;
let compared = finite + strings[finite..].iter().position(String::is_empty)?;
let [failed_after_open, failed_before_open, closed] =
strings.get(compared + 1..compared + 4)?
else {
return None;
};
let fields = Fields {
platform: before(&["/w"])?,
status: status.clone(),
sent: sent.clone(),
received: received.clone(),
opened: opened.clone(),
round_trips: before(&["JSON", "stringify"])?,
elapsed: before(&["String", "Date", "now"])?,
statuses: Statuses {
complete: complete.clone(),
incomplete: incomplete.clone(),
timed_out: before(&["String", "Math", "round"])?,
failed_before_open: failed_before_open.clone(),
failed_after_open: failed_after_open.clone(),
closed: closed.clone(),
},
};
// Require every record field to be written by the probe.
let written = [
&fields.status,
&fields.sent,
&fields.received,
&fields.opened,
&fields.round_trips,
&fields.elapsed,
];
written
.iter()
.all(|name| probe.writes.fields.contains(name))
.then_some(fields)
}
#[cfg(test)]
mod tests {
use super::*;
fn fields() -> Fields {
Fields {
platform: "ppebL7".into(),
status: "ppmO1".into(),
sent: "IGrKf5".into(),
received: "JPvF0".into(),
opened: "IcEa5".into(),
round_trips: "UDMx6".into(),
elapsed: "RvpHD0".into(),
statuses: Statuses {
complete: "OCCOO7".into(),
incomplete: "DptU5".into(),
timed_out: "ZUzk4".into(),
failed_before_open: "WKjg8".into(),
failed_after_open: "TBGV5".into(),
closed: "lbCk7".into(),
},
}
}
/// Captured c787ce48cf6b record with an opening time rounded up from 101.5 ms.
#[test]
fn records_a_complete_exchange_as_the_browser_did() {
let round_trips = vec![
11.189999997615814,
11.449999995529652,
11.759999997913837,
9.370000004768372,
11.850000001490116,
10.859999999403954,
];
let measured = Measurement {
end: End::Echoed,
sent: 6,
received: 6,
opened_ms: Some(101.5),
round_trips,
elapsed_ms: 173,
};
assert_eq!(
js::stringify_object(&fields().collect(&measured)),
r#"{"ppmO1":"OCCOO7","IGrKf5":"6","JPvF0":"6","IcEa5":"102","UDMx6":"[11.189999997615814,11.449999995529652,11.759999997913837,9.370000004768372,11.850000001490116,10.859999999403954]","RvpHD0":"173"}"#
);
}
#[test]
fn a_socket_that_never_opened_reports_no_opening() {
let measured = Measurement {
end: End::Failed,
sent: 0,
received: 0,
opened_ms: None,
round_trips: Vec::new(),
elapsed_ms: 40,
};
assert_eq!(
js::stringify_object(&fields().collect(&measured)),
r#"{"ppmO1":"WKjg8","IGrKf5":"0","JPvF0":"0","IcEa5":"","UDMx6":"[]","RvpHD0":"40"}"#
);
}
}
+9 -6
View File
@@ -15,9 +15,10 @@ pub(crate) const OUTPUTS: [&str; 2] = [
/// The response header whose value the probe reports as its token.
const HEADER: &str = "cf-chl-peek";
/// Worker fetch URL prefix, including an explicit host. [`super::platform::url`] instead builds
/// URLs relative to the iframe.
const URL_PREFIX: &str = "https://brunhild.challenges.cloudflare.com/cdn-cgi/challenge-platform/h/";
/// Explicit host and path prefix for the worker fetch. Builds may store them as one string or two.
/// [`super::platform::url`] builds URLs relative to the iframe instead.
const HOST: &str = "brunhild.challenges.cloudflare.com";
const PATH: &str = "/cdn-cgi/challenge-platform/h/";
/// The session's options naming the request path's platform segment, ray and nonce.
#[derive(Clone, Debug, Deserialize, Serialize)]
@@ -41,7 +42,7 @@ impl Fields {
pub fn url(&self, options: &Options) -> Result<Url> {
let option = |name: &str| js::string(options.get(name));
Ok(Url::parse(&format!(
"{URL_PREFIX}{}/i/{}/{}",
"https://{HOST}{PATH}{}/i/{}/{}",
option(&self.platform_property),
option(&self.ray_property),
option(&self.nonce_property),
@@ -86,9 +87,11 @@ pub(crate) fn recognize(probe: &ProbeView<'_>) -> Option<Fields> {
"cors",
"omit",
"no-store",
URL_PREFIX,
];
(strings.stores_all(&OUTPUTS) && strings.has_all(&markers)).then(|| Fields {
let requests = [HOST, PATH]
.iter()
.all(|part| strings.features().iter().any(|text| text.contains(part)));
(strings.stores_all(&OUTPUTS) && strings.has_all(&markers) && requests).then(|| Fields {
platform_property: probe.session_name(reference::PLATFORM_OPTION),
ray_property: probe.session_name(reference::RAY_OPTION),
nonce_property: probe.session_name(reference::NONCE_OPTION),
-8
View File
@@ -47,11 +47,6 @@ pub(crate) const DATES_TODAY: &str = "LKWB0";
pub(crate) const DATES_OFFSET: &str = "kCaP5";
pub(crate) const DATES_ZONE: &str = "vFsge3";
/// Where the common wrapper shared by all probes stores its collection function.
pub(crate) const EMPTY_COLLECTOR: &str = "kplY0";
/// Properties the wrapper reads without collecting anything.
pub(crate) const EMPTY_WRAPPER_READS: [&str; 2] = ["xdiN1", "SMMhU4"];
pub(crate) const DOM_MUTATION_RESULT: &str = "yocl1";
// Environment and environment-audit names with session-specific replay patches.
@@ -180,9 +175,6 @@ mod tests {
(Kind::DateParsingOffsets, DATES_TODAY),
(Kind::DateParsingOffsets, DATES_OFFSET),
(Kind::DateParsingOffsets, DATES_ZONE),
(Kind::Empty, EMPTY_COLLECTOR),
(Kind::Empty, EMPTY_WRAPPER_READS[0]),
(Kind::Empty, EMPTY_WRAPPER_READS[1]),
(Kind::DomMutation, DOM_MUTATION_RESULT),
(Kind::Environment, ENVIRONMENT_REFERRER),
(Kind::EnvironmentAudit, ENVIRONMENT_AUDIT_GROUPS),
+33 -2
View File
@@ -13,8 +13,9 @@ use serde::{Deserialize, Serialize};
use super::analysis::recognize::{Phase, ProbeView};
use super::probes::{
clock, dates, dom_mutation, empty, error_message_length, image, media, network_information,
parent_info, performance, private_token, rects, stack, worker_fetch, worker_navigator,
clock, dates, dom_mutation, empty, error_message_length, host_reachability, image, media,
network_information, parent_info, performance, private_token, rects, stack, websocket_echo,
worker_fetch, worker_navigator,
};
use super::{benchmark, proof};
use crate::embedding_page::page::PageSignals;
@@ -188,6 +189,10 @@ families! {
// Rebuilt from the session's own script. The reference build's stack probe is probe 28.
Stack { fields: stack::Fields } =>
stack, "stack", Structural, Computed, [28];
HostReachability { fields: host_reachability::Fields } =>
host_reachability, "host_reachability", Structural, Computed, [];
WebSocketEcho { fields: websocket_echo::Fields } =>
websocket_echo, "websocket_echo", Structural, Computed, [];
@empty [11, 26, 33];
@replayed {
EnvironmentAudit => "environment_audit", 2;
@@ -276,6 +281,9 @@ pub struct Observed {
pub media: Option<media::Measurement>,
pub private_token: Option<private_token::Measurement>,
pub worker_fetch: Option<worker_fetch::Measurement>,
/// Host reachability fetch outcomes in URL order.
pub host_reachability: Option<Vec<host_reachability::Outcome>>,
pub websocket_echo: Option<websocket_echo::Measurement>,
pub image: Option<image::Measurement>,
pub performance: Option<performance::Measurement>,
/// Pairs of consecutive worker clock readings.
@@ -285,6 +293,21 @@ pub struct Observed {
pub stack: Option<String>,
}
impl Observed {
/// Returns the measured duration of completed work for a probe of `kind` in this session.
#[must_use]
pub fn duration_ms(&self, kind: Kind) -> Option<i64> {
match kind {
Kind::Benchmark => self
.benchmark
.as_ref()
.map(|run| run.elapsed_ms().ceil() as i64),
Kind::WebSocketEcho => self.websocket_echo.as_ref().map(|run| run.elapsed_ms),
_ => None,
}
}
}
impl Operation {
/// Tries reference recognizers, then structural ones, and returns the first match.
#[must_use]
@@ -313,6 +336,14 @@ impl Operation {
observed.worker_fetch.as_ref(),
"worker fetch measurement",
)?)),
Self::HostReachability { fields } => Ok(fields.collect(measured(
observed.host_reachability.as_deref(),
"host reachability measurement",
)?)),
Self::WebSocketEcho { fields } => Ok(fields.collect(measured(
observed.websocket_echo.as_ref(),
"WebSocket echo measurement",
)?)),
Self::Image { fields } => {
Ok(fields.collect(measured(observed.image.as_ref(), "image measurement")?))
}
+1 -22
View File
@@ -7,8 +7,7 @@
//! Classification across 28 captures, including 12 benchmarks, determines each [`Treatment`].
//! Device facts are retained. [`Session`] refreshes iframe URLs and `document.lastModified`,
//! plus trace membership and navigation sizes in the environment audit. Live requests, fresh
//! WebRTC state, and benchmark results are computed separately, as are Chrome's stacks; WebKit
//! replays the stack it recorded ([`Answers::stack`]).
//! WebRTC state, benchmark results, and stacks are computed separately.
use std::collections::BTreeMap;
use std::mem;
@@ -39,9 +38,6 @@ pub struct Answers {
pub reference: String,
/// Stored probe answers indexed by one-based reference probe number.
pub probes: BTreeMap<usize, Stored>,
/// The stack the stack probe reported, which no reference probe pairs with.
#[serde(default, skip_serializing_if = "Option::is_none")]
pub stack: Option<String>,
/// The worker navigator, by API property.
pub navigator: JsObject,
}
@@ -109,10 +105,6 @@ impl Answers {
}
}
}
if let Operation::Stack { fields: stack } = operation {
let reported = fields.get(&stack.result).and_then(JsValue::as_str);
answers.stack = reported.map(str::to_owned);
}
if operation.kind().treatment() == Treatment::Computed {
continue;
}
@@ -141,19 +133,6 @@ impl Answers {
Ok(answers)
}
/// Returns the recorded stack with iframe URLs changed to `iframe_url`. JavaScriptCore
/// includes every VM level through the latest asynchronous probe. That probe depends on
/// execution order and engine features, so WebKit reuses the recording rather than
/// rebuilding from the listing. Source positions stay those of the recorded build.
pub fn stack(&self, iframe_url: &str) -> Result<String> {
let mut stack = self
.stack
.clone()
.context("the stored answers record no stack")?;
refresh_string(&mut stack, iframe_url, "");
Ok(stack)
}
/// Checks that stored answer names belong to the embedded reference build.
pub fn check(&self) -> Result<()> {
ensure!(
+50 -18
View File
@@ -133,12 +133,6 @@ impl Vocabulary {
self.candidates.get(index).copied().flatten()
}
/// The reference name for a session name, wherever it appears.
#[must_use]
pub fn reference_name(&self, name: &str) -> Option<String> {
self.global.to_reference.get(name).cloned()
}
/// Translates `name` for probe `index` in direction `side`, preferring the probe's own pairs
/// over the program-wide map.
fn find(
@@ -231,24 +225,23 @@ fn pair_probes<S: AsRef<[String]>>(
session: &[S],
reference: &[Vec<String>],
) -> (Vec<Option<usize>>, Vec<Option<Candidate>>) {
fn stable(strings: &[String]) -> HashSet<&str> {
strings
.iter()
.map(String::as_str)
.filter(|text| !is_name(text))
.collect()
}
let reference_sets: Vec<HashSet<&str>> = reference.iter().map(|probe| stable(probe)).collect();
let session_sets = distinctive(session.iter().map(AsRef::as_ref));
let reference_sets = distinctive(reference.iter().map(Vec::as_slice));
// Each session probe's position, with one reference probe's similarity.
let mut pairings: Vec<(usize, Candidate)> = Vec::new();
for (index, probe) in session.iter().enumerate() {
let session_set = stable(probe.as_ref());
for (index, session_set) in session_sets.iter().enumerate() {
for (reference_probe, reference_set) in reference_sets.iter().enumerate() {
let shared = session_set.intersection(reference_set).count();
let all = session_set.union(reference_set).count().max(1);
let all = session_set.union(reference_set).count();
// Probes containing only wrapper strings match each other.
let similarity = if all == 0 {
1.0
} else {
shared as f64 / all as f64
};
let candidate = Candidate {
reference: reference_probe + 1,
similarity: shared as f64 / all as f64,
similarity,
};
pairings.push((index, candidate));
}
@@ -272,6 +265,45 @@ fn pair_probes<S: AsRef<[String]>>(
(pairs, best)
}
/// Returns strings that identify a probe across builds. Excludes randomized names, encrypted log
/// messages regenerated for each build, and shared wrapper strings renamed together within a
/// program.
fn distinctive<'a>(probes: impl Iterator<Item = &'a [String]>) -> Vec<HashSet<&'a str>> {
let mut sets: Vec<HashSet<&str>> = probes
.map(|strings| {
strings
.iter()
.map(String::as_str)
.filter(|text| !is_name(text) && !is_log_message(text))
.collect()
})
.collect();
let mut counts: HashMap<&str, usize> = HashMap::new();
for set in &sets {
for text in set {
*counts.entry(text).or_default() += 1;
}
}
let probe_count = sets.len();
for set in &mut sets {
set.retain(|text| 2 * counts[text] < probe_count);
}
sets
}
/// Checks for an encrypted log message in the form `<base64>$<base64>`.
fn is_log_message(text: &str) -> bool {
let is_base64 = |part: &str| {
!part.is_empty()
&& part
.trim_end_matches('=')
.bytes()
.all(|byte| byte.is_ascii_alphanumeric() || byte == b'+' || byte == b'/')
};
text.split_once('$')
.is_some_and(|(cipher, iv)| is_base64(cipher) && is_base64(iv))
}
/// Aligns probe string sequences and pairs names between shared anchors. Requires equal counts
/// on both sides. Also compares differing strings at matching positions to recover embedded
/// names.
+1
View File
@@ -18,6 +18,7 @@ mod extract;
mod interpret;
mod machine;
mod output;
mod registers;
mod session;
mod value;
+9 -7
View File
@@ -23,15 +23,15 @@ impl<K: Ord + Clone, V: PartialEq + Clone> Facts for BTreeMap<K, V> {
}
/// Computes entry facts for instructions reachable from `entries`. `transfer` updates a copy of
/// the facts along one instruction path, which then propagates through the path's exit, or
/// stops the analysis.
/// facts for one instruction path and reports whether it can run, or stops the analysis. Facts
/// propagate through the exit only if the path can run.
///
/// Only recorded exits propagate facts, so function entries and hidden branch targets need
/// explicit entries. Reaching a position without an instruction ends that path.
pub(crate) fn forward<F: Facts, B>(
listing: &Listing,
entries: impl IntoIterator<Item = (u32, F)>,
mut transfer: impl FnMut(&Path, &mut F) -> ControlFlow<B>,
mut transfer: impl FnMut(u32, &Path, &mut F) -> ControlFlow<B, bool>,
) -> ControlFlow<B, BTreeMap<u32, F>> {
let mut incoming = BTreeMap::new();
let mut pending = VecDeque::new();
@@ -45,8 +45,10 @@ pub(crate) fn forward<F: Facts, B>(
let entry = incoming[&pc].clone();
for path in &instruction.paths {
let mut facts = entry.clone();
if let ControlFlow::Break(stop) = transfer(path, &mut facts) {
return ControlFlow::Break(stop);
match transfer(pc, path, &mut facts) {
ControlFlow::Break(stop) => return ControlFlow::Break(stop),
ControlFlow::Continue(false) => continue,
ControlFlow::Continue(true) => {}
}
if let Some(next) = path.exit.continues_at() {
reach(&mut incoming, &mut pending, next.pc, facts);
@@ -120,13 +122,13 @@ mod tests {
};
listing.instructions.insert(pc, instruction);
}
let constants = |path: &Path, facts: &mut Constants| {
let constants = |_, path: &Path, facts: &mut Constants| {
for effect in &path.effects {
if let Effect::Set(register, value) = effect {
facts.insert(*register, value.clone());
}
}
ControlFlow::<()>::Continue(())
ControlFlow::<(), bool>::Continue(true)
};
let incoming = forward(&listing, [(0, Constants::new())], constants);
let a = || Constants::from([(1, Term::Const(Constant::String("a".into())))]);
+28 -8
View File
@@ -76,8 +76,11 @@ impl Machine<'_> {
#[derive(Default)]
struct Walk {
listing: Listing,
/// Reached program counters and the dispatch key used at each one.
visited: HashMap<u32, u8>,
/// Reached program counters with their dispatch keys and the first instruction to reach each
/// one, if any.
visited: HashMap<u32, (u8, Option<u32>)>,
/// The instruction whose successors are being queued.
from: Option<u32>,
queue: VecDeque<Position>,
/// Candidate state names in the order found. Observed state comparisons always use
/// complete string constants.
@@ -103,12 +106,20 @@ impl Walk {
let Position { pc, key } = position;
match self.visited.get(&pc) {
None => {
self.visited.insert(pc, key);
self.visited.insert(pc, (key, self.from));
self.queue.push_back(position);
Ok(())
}
Some(&earlier) if earlier == key => Ok(()),
Some(&earlier) => bail!("pc {pc} is reached under keys {earlier} and {key}"),
Some(&(earlier, _)) if earlier == key => Ok(()),
Some(&(earlier, first)) => {
let origin =
|from: Option<u32>| from.map_or("an entry".to_owned(), |pc| format!("pc {pc}"));
bail!(
"pc {pc} is reached under keys {earlier} from {} and {key} from {}",
origin(first),
origin(self.from)
)
}
}
}
@@ -118,6 +129,7 @@ impl Walk {
loaded: &Loaded<'_, 'a>,
instruction: Instruction,
) -> Result<()> {
self.from = Some(instruction.pc);
for path in &instruction.paths {
self.follow(path)?;
}
@@ -155,7 +167,14 @@ impl Walk {
}
fn follow(&mut self, path: &Path) -> Result<()> {
let mut next: Vec<Position> = path.exit.continues_at().into_iter().collect();
let continues = match &path.exit {
// Handlers update a local program counter and store it when they finish. If a handler
// stops early, the stored counter remains just past the opcode, pointing into its
// operands.
Exit::Unfollowed { pc, .. } if self.from.is_some_and(|from| *pc == from + 1) => None,
exit => exit.continues_at(),
};
let mut next: Vec<Position> = continues.into_iter().collect();
for effect in &path.effects {
effect.visit_terms(&mut |term| match term {
Term::Closure { pc, key, .. } => {
@@ -233,6 +252,7 @@ impl Walk {
// Once a compare has revealed its target, no other string can.
let compare = hit.compare;
self.probes.retain(|&(pc, _), _| pc != compare);
self.from = Some(compare);
self.enqueue(hit.target)?;
self.listing.hidden.push(hit);
}
@@ -375,11 +395,11 @@ fn fuse_method_calls(listing: &mut Listing) {
let functions = listing.functions.iter().map(|function| function.pc);
let hidden = listing.hidden.iter().map(|hidden| hidden.target.pc);
let entries = functions.chain(hidden).map(|pc| (pc, Loads::default()));
let ControlFlow::Continue(incoming) = dataflow::forward(listing, entries, |path, loads| {
let ControlFlow::Continue(incoming) = dataflow::forward(listing, entries, |_, path, loads| {
for effect in &path.effects {
update_loads(loads, effect);
}
ControlFlow::<Infallible>::Continue(())
ControlFlow::<Infallible, bool>::Continue(true)
});
for (pc, instruction) in &mut listing.instructions {
let Some(entry) = incoming.get(pc) else {
+119 -614
View File
@@ -1,634 +1,139 @@
//! Precomputes opcode decoding and dispatch-key updates without running the VM.
//! Decodes opcodes by executing the decoding statements from the dispatch loop.
//!
//! Builds use different formulas, so this module compiles them from the session's dispatch
//! loop, inlining single-return operator helpers, and evaluates every key and byte.
//! Decoding varies by build. The current build mixes a hash of the program position into each
//! opcode, so a table indexed by dispatch key and byte is insufficient.
//!
//! The loop tries an inline fast path for common instructions, then falls back to decoding. Skip
//! the fast path and execute only the fallback statements. These advance the program counter,
//! produce the switch value as the opcode, and store the next dispatch key in its register.
use std::mem;
use anyhow::{Result, ensure};
use swc_core::atoms::Atom;
use anyhow::{Context, Result};
use swc_core::common::DUMMY_SP;
use swc_core::ecma::ast::{
AssignExpr, AssignTarget, CallExpr, Callee, Decl, Expr, Function, Lit, MemberExpr, ObjectLit,
Pat, Script, SimpleAssignTarget, Stmt, UnaryOp, UpdateOp, VarDecl, VarDeclarator,
BinaryOp, BlockStmt, Decl, Expr, Function, Ident, Lit, ReturnStmt, Stmt,
};
use swc_core::ecma::visit::{Visit, VisitWith};
use super::{HashMap, interpret};
use crate::js;
use crate::js::ast;
use super::extract::{Argument, DispatchLoop};
use super::interpret;
use super::session::Session;
use super::value::Value;
/// Decoded result for every byte and dispatch key, indexed by `key << 8 | byte`.
pub(crate) struct Dispatch(Vec<Decoded>);
/// Function extracted from the dispatch loop to decode opcodes.
pub(crate) struct Dispatch {
/// `function(<loop parameters>) { var <loop locals>; <decoding>; return <opcode>; }`.
decoder: Function,
/// Values passed to each loop parameter.
arguments: Vec<Argument>,
}
/// What one program byte decodes to under one dispatch key.
/// Decoded opcode and dispatch key for one program byte.
#[derive(Clone, Copy, Debug, PartialEq)]
pub(crate) struct Decoded {
pub(crate) opcode: u8,
/// The dispatch key the next byte decodes under.
/// Key used to decode the instruction operands and the next opcode.
pub(crate) key: u8,
}
impl Dispatch {
/// Evaluates each dispatch loop's decoding formula and checks that all loops agree.
pub(crate) fn from_run(run: &Function, helpers: &Helpers) -> Result<Self> {
use anyhow::Context;
let mut loops = Loops::default();
run.visit_with(&mut loops);
let mut tables = loops
.0
pub(crate) fn from_loop(dispatch: &DispatchLoop<'_>) -> Result<Self> {
let function = dispatch.function;
let body = function
.body
.as_ref()
.context("the dispatch loop function has no body")?;
let looping = body
.stmts
.iter()
.filter_map(|(prefix, opcode)| tabulate(prefix, opcode, helpers));
let table = tables
.next()
.context("expected a dispatch loop in the VM's run method")?;
ensure!(
tables.all(|other| other == table),
"the VM's dispatch loops disagree"
);
Ok(Self(table))
}
#[must_use]
pub(crate) fn decode(&self, key: u8, byte: u8) -> Decoded {
self.0[usize::from(key) << 8 | usize::from(byte)]
}
}
/// Recovers opcode decoding and key updates from statements preceding a dispatch switch.
fn tabulate(prefix: &[Stmt], opcode: &Atom, helpers: &Helpers) -> Option<Vec<Decoded>> {
let decode = prefix
.iter()
.rposition(|statement| assigned(statement).is_some_and(|(name, _)| name == *opcode))?;
let statements = &prefix[decode..];
// The last register write before dispatch updates the key; the other array read supplies
// program bytes.
let (key_array, key_index) = statements.iter().rev().find_map(|statement| {
cell(
statement
.as_expr()?
.expr
.as_assign()?
.left
.as_simple()?
.as_member()?,
)
})?;
let (_, decoded) = assigned(&statements[0])?;
let mut reads = Reads::default();
decoded.visit_with(&mut reads);
let program = reads.0.into_iter().find(|array| *array != key_array)?;
let mut compiler = FormulaCompiler::new(helpers, program);
let formulas: Vec<Formula> = statements
.iter()
.map(|statement| compiler.statement(statement))
.collect::<Option<_>>()?;
let key = compiler.variable(Slot::Cell {
array: key_array,
index: key_index,
});
let opcode = compiler.variable(Slot::Local(opcode.clone()));
let variables = compiler.variables.len();
// Reuse one buffer for all entries, resetting values to NaN to represent `undefined` in
// arithmetic.
let mut values = vec![f64::NAN; variables];
let mut table = Vec::with_capacity(1 << 16);
for key_value in 0..=u8::MAX {
for byte in 0..=u8::MAX {
values.fill(f64::NAN);
values[key] = f64::from(key_value);
for formula in &formulas {
formula.evaluate(&mut values, f64::from(byte));
}
table.push(Decoded {
opcode: js::int32(values[opcode]) as u8,
key: js::int32(values[key]) as u8,
});
}
}
Some(table)
}
/// An arithmetic formula compiled from the VM source.
enum Formula {
Number(f64),
Variable(usize),
/// A read of the program array. Uses the byte being tabulated regardless of index.
Byte(Box<Formula>),
/// `x++`, `x--`, `++x` or `--x`.
Update {
variable: usize,
delta: f64,
prefix: bool,
},
Unary(fn(f64) -> f64, Box<Formula>),
Binary(fn(f64, f64) -> f64, Box<Formula>, Box<Formula>),
Assign(usize, Box<Formula>),
/// A helper call: arguments evaluate left to right into parameter slots, then the body.
Inline {
arguments: Vec<(usize, Formula)>,
body: Box<Formula>,
},
}
impl Formula {
fn evaluate(&self, values: &mut [f64], byte: f64) -> f64 {
match self {
Self::Number(value) => *value,
Self::Variable(variable) => values[*variable],
Self::Byte(index) => {
index.evaluate(values, byte);
byte
}
Self::Update {
variable,
delta,
prefix,
} => {
let old = values[*variable];
values[*variable] = old + delta;
if *prefix { old + delta } else { old }
}
Self::Unary(operation, operand) => operation(operand.evaluate(values, byte)),
Self::Binary(operation, left, right) => {
let left = left.evaluate(values, byte);
let right = right.evaluate(values, byte);
operation(left, right)
}
Self::Assign(variable, value) => {
let value = value.evaluate(values, byte);
values[*variable] = value;
value
}
Self::Inline { arguments, body } => {
for (parameter, argument) in arguments {
values[*parameter] = argument.evaluate(values, byte);
}
body.evaluate(values, byte)
}
}
}
}
/// Where a compiled formula keeps one value.
#[derive(Clone, Debug, PartialEq, Eq)]
enum Slot {
Local(Atom),
/// Variable slot for an `array[index]` access whose index is a variable.
Cell {
array: Atom,
index: Atom,
},
/// One parameter of one inlined helper call.
Argument(usize),
}
/// Compiles numeric statements and expressions. Reads from `program` supply bytes; other
/// indexed accesses get variable slots.
struct FormulaCompiler<'helpers> {
helpers: &'helpers Helpers,
program: Atom,
variables: Vec<Slot>,
/// The parameters of the helper being inlined, bound to their slots.
arguments: HashMap<Atom, usize>,
/// The helpers being inlined, innermost last, to reject recursion.
inlining: Vec<&'helpers (Atom, Atom)>,
}
impl<'helpers> FormulaCompiler<'helpers> {
fn new(helpers: &'helpers Helpers, program: Atom) -> Self {
Self {
helpers,
program,
variables: Vec::new(),
arguments: HashMap::default(),
inlining: Vec::new(),
}
}
fn variable(&mut self, slot: Slot) -> usize {
if let Some(index) = self.variables.iter().position(|variable| *variable == slot) {
return index;
}
self.variables.push(slot);
self.variables.len() - 1
}
/// The slot of an active helper parameter or local named `name`.
fn local(&mut self, name: &Atom) -> usize {
match self.arguments.get(name) {
Some(&slot) => slot,
None => self.variable(Slot::Local(name.clone())),
}
}
fn cell(&mut self, member: &MemberExpr) -> Option<usize> {
let (array, index) = cell(member)?;
Some(self.variable(Slot::Cell { array, index }))
}
fn statement(&mut self, statement: &Stmt) -> Option<Formula> {
if let Stmt::Expr(statement) = statement {
return self.expression(&statement.expr);
}
let (name, init) = assigned(statement)?;
let value = self.expression(init)?;
let variable = self.local(&name);
Some(Formula::Assign(variable, Box::new(value)))
}
fn expression(&mut self, expression: &Expr) -> Option<Formula> {
Some(match expression {
Expr::Lit(Lit::Num(number)) => Formula::Number(number.value),
Expr::Paren(paren) => self.expression(&paren.expr)?,
Expr::Ident(name) => Formula::Variable(self.local(&name.sym)),
Expr::Member(member) => {
if member.obj.as_ident()?.sym == self.program {
let index = &member.prop.as_computed()?.expr;
Formula::Byte(Box::new(self.expression(index)?))
} else {
Formula::Variable(self.cell(member)?)
}
}
Expr::Unary(unary) => {
let operation: fn(f64) -> f64 = match unary.op {
UnaryOp::Minus => |value| -value,
UnaryOp::Plus => |value| value,
UnaryOp::Tilde => js::bit_not,
UnaryOp::Bang => |value| f64::from(u8::from(value == 0.0 || value.is_nan())),
_ => return None,
};
Formula::Unary(operation, Box::new(self.expression(&unary.arg)?))
}
Expr::Bin(binary) => Formula::Binary(
interpret::numeric(binary.op)?,
Box::new(self.expression(&binary.left)?),
Box::new(self.expression(&binary.right)?),
),
Expr::Update(update) => Formula::Update {
variable: self.local(&update.arg.as_ident()?.sym),
delta: match update.op {
UpdateOp::PlusPlus => 1.0,
UpdateOp::MinusMinus => -1.0,
},
prefix: update.prefix,
},
Expr::Assign(assign) => {
let variable = match &assign.left {
AssignTarget::Simple(SimpleAssignTarget::Ident(name)) => {
self.local(&name.id.sym)
}
AssignTarget::Simple(SimpleAssignTarget::Member(member)) => {
self.cell(member)?
}
_ => return None,
};
let value = self.expression(&assign.right)?;
let value = match assign.op.to_update() {
None => value,
Some(operator) => Formula::Binary(
interpret::numeric(operator)?,
Box::new(Formula::Variable(variable)),
Box::new(value),
),
};
Formula::Assign(variable, Box::new(value))
}
Expr::Call(call) => self.inline(call)?,
_ => return None,
})
}
/// Compiles a helper call in JavaScript evaluation order: each argument once, left to
/// right, then the body. Rejects spreads, argument-count mismatches, and recursion.
fn inline(&mut self, call: &CallExpr) -> Option<Formula> {
let callee = call.callee.as_expr()?.as_member()?;
let helpers = self.helpers;
let name = (
callee.obj.as_ident()?.sym.clone(),
Atom::from(ast::member_str(&callee.prop)?),
);
let (name, helper) = helpers.0.get_key_value(&name)?;
if call.args.len() != helper.parameters.len()
|| call.args.iter().any(|argument| argument.spread.is_some())
|| self.inlining.contains(&name)
{
return None;
}
let mut arguments = Vec::new();
let mut parameters = HashMap::default();
for (parameter, argument) in helper.parameters.iter().zip(&call.args) {
let value = self.expression(&argument.expr)?;
// Allocate a fresh slot so separate calls cannot share parameter storage.
let slot = self.variable(Slot::Argument(self.variables.len()));
arguments.push((slot, value));
parameters.insert(parameter.clone(), slot);
}
let outer = mem::replace(&mut self.arguments, parameters);
self.inlining.push(name);
let body = self.expression(&helper.body);
self.inlining.pop();
self.arguments = outer;
Some(Formula::Inline {
arguments,
body: Box::new(body?),
})
}
}
/// A helper of the form `function(parameters...) { return body; }`.
struct Helper {
parameters: Vec<Atom>,
body: Expr,
}
/// Single-return operator helpers by object and property name, from object literals and from
/// later property assignments such as `x = {}; x.wQKAm = function(a, b) { return b ^ a; };`.
#[derive(Default)]
pub(crate) struct Helpers(HashMap<(Atom, Atom), Helper>);
impl Helpers {
#[must_use]
pub(crate) fn new(script: &Script) -> Self {
let mut helpers = Self::default();
script.visit_with(&mut helpers);
helpers
}
fn record_literal(&mut self, object: &Atom, literal: &ObjectLit) {
for property in ast::key_values(literal) {
if let Some(name) = ast::key_str(&property.key).map(Atom::from) {
self.record(object, name, &property.value);
}
}
}
/// Records `object.property = value` when `value` defines a helper.
fn record(&mut self, object: &Atom, property: Atom, value: &Expr) {
if let Expr::Fn(function) = value
&& let Some(value) = ast::returned(&function.function)
&& let Some(parameters) = function
.function
.params
.iter()
.map(|parameter| parameter.pat.as_ident().map(|name| name.id.sym.clone()))
.collect::<Option<Vec<_>>>()
{
let helper = Helper {
parameters,
body: value.clone(),
};
self.0.insert((object.clone(), property), helper);
}
}
}
impl Visit for Helpers {
fn visit_assign_expr(&mut self, assign: &AssignExpr) {
match &assign.left {
AssignTarget::Simple(SimpleAssignTarget::Ident(object)) => {
if let Expr::Object(literal) = &*assign.right {
self.record_literal(&object.id.sym, literal);
}
}
AssignTarget::Simple(SimpleAssignTarget::Member(member)) => {
if let Expr::Ident(object) = &*member.obj
&& let Some(name) = ast::member_str(&member.prop).map(Atom::from)
{
self.record(&object.sym, name, &assign.right);
}
}
_ => {}
}
assign.visit_children_with(self);
}
fn visit_var_declarator(&mut self, declarator: &VarDeclarator) {
if let Pat::Ident(object) = &declarator.name
&& let Some(init) = &declarator.init
&& let Expr::Object(literal) = &**init
{
self.record_literal(&object.id.sym, literal);
}
declarator.visit_children_with(self);
}
}
/// The statements preceding each switch on a variable, with multi-variable declarations split
/// into single declarations in order.
#[derive(Default)]
struct Loops(Vec<(Vec<Stmt>, Atom)>);
impl Visit for Loops {
fn visit_stmts(&mut self, statements: &[Stmt]) {
for (index, statement) in statements.iter().enumerate() {
if let Stmt::Switch(switch) = statement
&& let Expr::Ident(opcode) = &*switch.discriminant
{
let prefix: Vec<Stmt> = statements[..index].iter().flat_map(split).collect();
self.0.push((prefix, opcode.sym.clone()));
}
}
statements.visit_children_with(self);
}
}
fn split(statement: &Stmt) -> Vec<Stmt> {
match statement {
Stmt::Decl(Decl::Var(declaration)) if declaration.decls.len() > 1 => declaration
.decls
.iter()
.map(|declarator| {
Stmt::Decl(Decl::Var(Box::new(VarDecl {
decls: vec![declarator.clone()],
..(**declaration).clone()
})))
})
.collect(),
_ => vec![statement.clone()],
}
}
/// Arrays indexed by an expression, except in callees.
#[derive(Default)]
struct Reads(Vec<Atom>);
impl Visit for Reads {
fn visit_member_expr(&mut self, member: &MemberExpr) {
if let Expr::Ident(array) = &*member.obj
&& member.prop.is_computed()
{
self.0.push(array.sym.clone());
}
member.visit_children_with(self);
}
fn visit_callee(&mut self, _: &Callee) {}
}
/// Returns the target variable and value from `x = value`, `x op= value`, or `let x = value`.
fn assigned(statement: &Stmt) -> Option<(Atom, &Expr)> {
match statement {
Stmt::Expr(statement) => {
let assign = statement.expr.as_assign()?;
let name = assign.left.as_simple()?.as_ident()?;
Some((name.id.sym.clone(), &assign.right))
}
Stmt::Decl(Decl::Var(declaration)) => match &declaration.decls[..] {
[
VarDeclarator {
name: Pat::Ident(name),
init: Some(init),
..
},
] => Some((name.id.sym.clone(), init)),
_ => None,
},
_ => None,
}
}
/// The array and index of `array[index]`, both identifiers.
fn cell(member: &MemberExpr) -> Option<(Atom, Atom)> {
let array = member.obj.as_ident()?.sym.clone();
Some((
array,
member.prop.as_computed()?.expr.as_ident()?.sym.clone(),
))
}
#[cfg(test)]
mod tests {
use super::*;
fn script(source: &str) -> Script {
ast::parse_javascript("t.js", source).unwrap().script
}
const HELPERS: &str = "h = { x: function(a, b) { return b ^ a; } }; \
q = {}; q.y = function(a, b) { return b ^ a; };";
fn dispatch(loops: &[&str]) -> Result<Dispatch> {
let loops: String = loops
.iter()
.map(|body| format!("while (true) {{ {body} switch (G) {{}} }}"))
.collect();
let script = script(&format!("{HELPERS} (function() {{ {loops} }});"));
let function = script.body.last().unwrap().as_expr().unwrap();
let function = function.expr.as_paren().unwrap();
Dispatch::from_run(
&function.expr.as_fn_expr().unwrap().function,
&Helpers::new(&script),
)
}
fn assert_dispatch(loops: &[&str], offset: u8, step: impl Fn(u32) -> u32) {
let dispatch = dispatch(loops).unwrap();
for key in 0..=u8::MAX {
for byte in [0_u8, 1, 0x7f, 0x90, 0xff] {
let opcode = key ^ byte.wrapping_sub(offset);
let next = step(u32::from(key) + u32::from(opcode)) as u8;
assert_eq!(
dispatch.decode(key, byte),
Decoded { opcode, key: next },
"misread {loops:?} at key {key}, byte {byte}"
);
}
}
}
#[test]
fn evaluates_the_dispatch_loop_however_it_is_spelled() {
let linear = |t: u32| t.wrapping_mul(46006).wrapping_add(28231);
for body in [
"G = k[i] ^ p[G] - 177 + 256 & 255; k[i] = (k[i] + G) * 46006 + 28231 & 255;",
"G = 79 + p[G] & 255 ^ k[i]; k[i] = 255 & 46006 * (k[i] + G) + 28231;",
"G = k[i] ^ 255 & 79 + p[G]; k[i] = 255 & (k[i] + G) * 46006 + 28231;",
// A later build drops the `+ 256` and XORs through a helper.
"G = h.x(k[i], p[G] - 177 & 255); k[i] = 46006 * (k[i] + G) + 28231 & 255;",
] {
assert_dispatch(&[body], 177, linear);
}
// Later variants use a quadratic key update stored separately. One loop declares values
// that the other assigns.
assert_dispatch(
&[
"P = r[j]; r[j] = P + 1; G = h.x(k[i], 255 & p[P] - 144); t = k[i] + G; \
k[i] = t * t * 6697 + t * 55697 + 22825 & 255;",
"let G = k[i] ^ p[P] - 144 & 255; let t = k[i] + G; \
k[i] = 255 & t * t * 6697 + 55697 * t + 22825;",
],
144,
|t| t * t * 6697 + t * 55697 + 22825,
);
// This build declares opcode and key sum together and constructs helpers through
// property writes. Either loop must produce the full table independently.
let quadratic = |t: u32| {
t.wrapping_mul(t)
.wrapping_mul(45252)
.wrapping_add(t * 58234)
.wrapping_add(22596)
.find_map(Stmt::as_while_stmt)
.context("the dispatch loop function has no loop")?;
let statements = match &*looping.body {
Stmt::Block(block) => &block.stmts[..],
statement => std::slice::from_ref(statement),
};
let declared = "P = r[j]; r[j] = P + 1; let G = k[i] ^ 255 & p[P] - 84, t = k[i] + G; \
k[i] = t * t * 45252 + 58234 * t + 22596 & 255;";
let assigned = "P = r[j]; r[j] = P + 1; G = q.y(k[i], 255 & p[P] - 84); t = k[i] + G; \
k[i] = 45252 * (t * t) + t * 58234 + 22596 & 255;";
assert_dispatch(&[declared], 84, quadratic);
assert_dispatch(&[assigned], 84, quadratic);
assert_dispatch(&[declared, assigned], 84, quadratic);
assert!(
dispatch(&[
"G = k[i] ^ p[G] - 177 + 256 & 255; k[i] = (k[i] + G) * 46006 + 28231 & 255;",
"G = k[i] ^ p[G] - 97 + 256 & 255; k[i] = (k[i] + G) * 46006 + 28231 & 255;",
])
.is_err(),
"two loops that disagree are not one VM's dispatch"
);
let (at, switch) = statements
.iter()
.enumerate()
.find_map(|(at, statement)| Some((at, statement.as_switch()?)))
.context("the dispatch loop has no switch")?;
let opcode = switch
.discriminant
.as_ident()
.context("the dispatch switch is not on a local")?
.clone();
let prefix = &statements[..at];
// Match `<opcode> = <fast path>; if (<opcode> < 0) { <decoding> }`.
let decoding = match prefix.last() {
Some(Stmt::If(branch))
if branch.alt.is_none() && is_negative(&branch.test, &opcode) =>
{
match &*branch.cons {
Stmt::Block(block) => block.stmts.clone(),
statement => vec![statement.clone()],
}
}
_ => prefix.to_vec(),
};
// Preserve the loop local declarations without initializers.
let declarations = body.stmts.iter().chain(prefix).filter_map(|statement| {
let Stmt::Decl(Decl::Var(declaration)) = statement else {
return None;
};
let mut declaration = declaration.clone();
for declarator in &mut declaration.decls {
declarator.init = None;
}
Some(Stmt::Decl(Decl::Var(declaration)))
});
let returned = Stmt::Return(ReturnStmt {
span: DUMMY_SP,
arg: Some(Box::new(Expr::Ident(opcode))),
});
let decoder = Function {
body: Some(BlockStmt {
span: body.span,
ctxt: body.ctxt,
stmts: declarations.chain(decoding).chain([returned]).collect(),
}),
..function.clone()
};
Ok(Self {
decoder,
arguments: dispatch.arguments.clone(),
})
}
#[test]
fn inlined_helpers_evaluate_each_argument_once_in_call_order() {
let helpers = Helpers::new(&script(
"var h = { s: function(a, b) { return b - a; }, d: function(a) { return a + a; }, r: function(a) { return h.r(a); } };",
));
for (source, expected, why) in [
(
"x = h.s(i++, i++);",
Some(1.0),
"the body reads `b` first, but `a` runs first",
),
(
"x = h.d(i++) + i;",
Some(1.0),
"a parameter used twice runs its argument once",
),
(
"x = h.s(1, h.d(2));",
Some(3.0),
"a helper call is an argument",
),
(
"x = h.s(i);",
None,
"a call with too few arguments is not compiled",
),
(
"x = h.d(...p);",
None,
"a call that spreads is not compiled",
),
("x = h.r(1);", None, "a recursive call is not compiled"),
] {
let statement = script(source).body.into_iter().next().unwrap();
let mut compiler = FormulaCompiler::new(&helpers, Atom::from("p"));
let value = compiler.statement(&statement).map(|formula| {
let i = compiler.variable(Slot::Local(Atom::from("i")));
let mut values = vec![f64::NAN; compiler.variables.len()];
values[i] = 0.0;
formula.evaluate(&mut values, 0.0)
});
assert_eq!(value, expected, "{source}: {why}");
}
/// Decodes the opcode at `pc` using `key`. Returns the reason if decoding stops.
pub(crate) fn decode<'ast>(
&'ast self,
session: &Session<'ast>,
program: &[u8],
pc: u32,
key: u8,
) -> Result<Decoded, String> {
let arguments = self
.arguments
.iter()
.map(|argument| match argument {
Argument::Machine => Value::Machine,
Argument::Registers => Value::Registers,
Argument::Program => Value::Program,
Argument::Other => Value::Undefined,
})
.collect();
interpret::decode(session, program, &self.decoder, arguments, pc, key)
}
}
/// Matches `<opcode> < 0` or `0 > <opcode>`.
fn is_negative(test: &Expr, opcode: &Ident) -> bool {
let Some(test) = test.unwrap_parens().as_bin() else {
return false;
};
let is_opcode = |expr: &Expr| expr.as_ident().is_some_and(|name| name.sym == opcode.sym);
let is_zero = |expr: &Expr| matches!(expr, Expr::Lit(Lit::Num(number)) if number.value == 0.0);
match test.op {
BinaryOp::Lt => is_opcode(&test.left) && is_zero(&test.right),
BinaryOp::Gt => is_zero(&test.left) && is_opcode(&test.right),
_ => false,
}
}
+211 -131
View File
@@ -6,9 +6,8 @@ use anyhow::{Context, Result, bail, ensure};
use swc_core::atoms::Atom;
use swc_core::common::Span;
use swc_core::ecma::ast::{
AssignExpr, AssignOp, AssignTarget, BlockStmt, CallExpr, Callee, Class, ClassMember, Decl,
Expr, ExprOrSpread, Function, Lit, MemberExpr, MemberProp, ReturnStmt, Script,
SimpleAssignTarget, Stmt, SwitchStmt,
AssignExpr, AssignOp, AssignTarget, BlockStmt, CallExpr, Class, ClassMember, Decl, Expr,
ExprOrSpread, Function, Lit, ReturnStmt, Script, SimpleAssignTarget, Stmt, SwitchStmt,
};
use swc_core::ecma::visit::{Visit, VisitWith};
@@ -16,29 +15,6 @@ use super::output::Position;
use super::{HashMap, convert};
use crate::js::ast;
/// The handler an opcode dispatches to, and what the dispatch case passes it.
pub(crate) struct Handler<'ast> {
pub function: &'ast Function,
/// Whether the case calls it with the machine as `this`.
pub bound: bool,
pub arguments: Vec<Operand>,
}
#[derive(Clone, Copy)]
pub(crate) enum Operand {
Machine,
Number(f64),
}
/// Names of the fields that keep the run loop's state in `this.<registers>[this.<field>]`.
pub(super) struct StateFields {
pub registers: String,
pub pc: String,
pub key: String,
pub cells: String,
pub program: String,
}
/// Finds a class with a `run` method and the innermost function body declaring it.
#[derive(Default)]
pub(super) struct Finder {
@@ -122,16 +98,60 @@ enum Source {
Parameter(usize),
/// `this.<name>`.
Field(String),
/// `this.<registers>[this.<index>]`.
/// Register read as `<registers>.read(<index>)`. Both the register file and index come from
/// fields.
Register {
registers: String,
index: String,
},
}
/// Finds [`StateFields`] by tracking plain assignments in `run`'s own statements. An unsupported
/// assigned value invalidates what is known about its local.
pub(super) fn state_fields(run: &Function) -> Result<StateFields> {
/// Register layout and state setup recovered from `run`.
pub(super) struct RunMethod<'ast> {
/// Field containing the register file. Fields on that file identify the program counter and
/// dispatch key registers.
pub registers: String,
/// Fields containing the cells and program register indices.
pub cells: String,
pub program: String,
pub dispatch: DispatchLoop<'ast>,
}
/// Dispatch function declared beside the class and called by `run` with the machine. Some builds
/// move both loops out of `run`; both dispatch the same handlers.
pub(crate) struct DispatchLoop<'ast> {
pub function: &'ast Function,
/// Argument values passed by `run`, in parameter order.
pub arguments: Vec<Argument>,
}
/// Argument passed from `run` to a dispatch loop.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub(crate) enum Argument {
Machine,
Registers,
Program,
Other,
}
impl DispatchLoop<'_> {
/// The parameter receiving the machine.
fn machine(&self) -> Option<&Atom> {
let position = self
.arguments
.iter()
.position(|argument| *argument == Argument::Machine)?;
Some(&self.function.params.get(position)?.pat.as_ident()?.sym)
}
}
/// Tracks assignments in `run`, including copies of register fields and indices, program counter
/// and key setup, storing the third argument in the cells register, reading the program register,
/// and calling dispatch loops. An unsupported assignment clears the known value of its local.
pub(super) fn run_method<'a>(
functions: &HashMap<Atom, &'a Function>,
run: &Function,
) -> Result<RunMethod<'a>> {
let body = run.body.as_ref().context("the run method has no body")?;
let mut locals: HashMap<Atom, Source> = run
.params
@@ -144,7 +164,7 @@ pub(super) fn state_fields(run: &Function) -> Result<StateFields> {
))
})
.collect();
let mut stored: [Option<(String, String)>; 3] = Default::default();
let mut cells = None;
let mut loaded = Vec::new();
for statement in &body.stmts {
let Stmt::Expr(statement) = statement else {
@@ -155,86 +175,175 @@ pub(super) fn state_fields(run: &Function) -> Result<StateFields> {
expr => vec![expr],
};
for expr in expressions {
if let Some((Source::Field(registers), arguments)) = method_call(&locals, expr, "write")
&& let [Some(Source::Field(index)), Some(Source::Parameter(2))] = &arguments[..]
{
cells = Some((registers, index.clone()));
continue;
}
let Expr::Assign(assign) = expr else { continue };
let AssignTarget::Simple(SimpleAssignTarget::Ident(name)) = &assign.left else {
continue;
};
let value = match assign.op {
AssignOp::Assign => source(&locals, &assign.right),
_ => None,
};
match &assign.left {
AssignTarget::Simple(SimpleAssignTarget::Ident(name)) => {
if let Some(Source::Register { index, .. }) = &value {
loaded.push(index.clone());
}
match value {
Some(value) => locals.insert(name.sym.clone(), value),
None => locals.remove(&name.sym),
};
}
AssignTarget::Simple(SimpleAssignTarget::Member(member)) => {
if let Some(Source::Register { registers, index }) =
member_source(&locals, member)
&& let Some(Source::Parameter(parameter)) = value
&& let Some(slot) = stored.get_mut(parameter)
{
*slot = Some((registers, index));
}
}
_ => {}
if let Some(Source::Register { registers, index }) = &value {
loaded.push((registers.clone(), index.clone()));
}
match value {
Some(value) => locals.insert(name.sym.clone(), value),
None => locals.remove(&name.sym),
};
}
}
let [
Some((registers, pc)),
Some((key_registers, key)),
Some((cell_registers, cells)),
] = stored
else {
bail!("the run method does not store its pc, key and cells in registers");
};
ensure!(
registers == key_registers && registers == cell_registers,
"the run method stores its arguments in different register files"
);
loaded.retain(|index| ![&pc, &key, &cells].contains(&index));
let (registers, cells) =
cells.context("the run method writes its cells argument to no register")?;
loaded.retain(|(file, index)| *file == registers && *index != cells);
loaded.sort();
loaded.dedup();
let [program] = &loaded[..] else {
let [(_, program)] = &loaded[..] else {
bail!(
"the run method loads {} registers besides its arguments",
loaded.len()
);
};
Ok(StateFields {
program: program.clone(),
let program = program.clone();
let mut calls = DispatchCall {
functions,
found: None,
};
body.visit_with(&mut calls);
let (function, call) = calls
.found
.context("the run method calls no dispatch loop with the machine")?;
let arguments = call
.args
.iter()
.map(|argument| match &*argument.expr {
Expr::This(_) => Argument::Machine,
Expr::Ident(name) => match locals.get(&name.sym) {
Some(Source::Field(field)) if *field == registers => Argument::Registers,
Some(Source::Register { index, .. }) if *index == program => Argument::Program,
_ => Argument::Other,
},
_ => Argument::Other,
})
.collect();
Ok(RunMethod {
registers,
pc,
key,
cells,
program,
dispatch: DispatchLoop {
function,
arguments,
},
})
}
/// Finds the first call in `run` whose first argument is the machine and whose target contains a
/// dispatch switch.
struct DispatchCall<'functions, 'ast> {
functions: &'functions HashMap<Atom, &'ast Function>,
found: Option<(&'ast Function, CallExpr)>,
}
impl Visit for DispatchCall<'_, '_> {
fn visit_call_expr(&mut self, call: &CallExpr) {
if self.found.is_none()
&& call
.args
.first()
.is_some_and(|argument| argument.expr.is_this())
&& let Some(callee) = call.callee.as_expr().and_then(|callee| callee.as_ident())
&& let Some(&function) = self.functions.get(&callee.sym)
&& first_switch_in(function).is_some()
{
self.found = Some((function, call.clone()));
}
call.visit_children_with(self);
}
}
/// Resolves `<object>.<name>(<arguments>)`, including the values of the object and arguments.
fn method_call(
locals: &HashMap<Atom, Source>,
expr: &Expr,
name: &str,
) -> Option<(Source, Vec<Option<Source>>)> {
let (object, arguments) = ast::method_call(expr, name)?;
let arguments = arguments
.iter()
.map(|argument| source(locals, &argument.expr))
.collect();
Some((source(locals, object)?, arguments))
}
fn source(locals: &HashMap<Atom, Source>, expr: &Expr) -> Option<Source> {
match expr {
Expr::Ident(name) => locals.get(&name.sym).cloned(),
Expr::Paren(paren) => source(locals, &paren.expr),
Expr::Member(member) => member_source(locals, member),
Expr::Member(member) if member.obj.is_this() => {
Some(Source::Field(ast::member_str(&member.prop)?.to_owned()))
}
Expr::Call(_) => match method_call(locals, expr, "read")? {
(Source::Field(registers), arguments) => match &arguments[..] {
[Some(Source::Field(index))] => Some(Source::Register {
registers,
index: index.clone(),
}),
_ => None,
},
_ => None,
},
_ => None,
}
}
fn member_source(locals: &HashMap<Atom, Source>, member: &MemberExpr) -> Option<Source> {
if let Expr::This(_) = &*member.obj {
return Some(Source::Field(ast::member_str(&member.prop)?.to_owned()));
/// Finds the string decryption function called by the register reader as
/// `decrypt(this.<values>[index])`.
pub(super) fn record_decoder(body: &BlockStmt) -> Option<Atom> {
/// Matches `<decoder>(this.<values>[<index>])`.
struct Decoders {
index: Atom,
found: Vec<Atom>,
}
let MemberProp::Computed(index) = &member.prop else {
return None;
};
match (source(locals, &member.obj)?, source(locals, &index.expr)?) {
(Source::Field(registers), Source::Field(index)) => {
Some(Source::Register { registers, index })
impl Visit for Decoders {
fn visit_call_expr(&mut self, call: &CallExpr) {
if let Some(callee) = call.callee.as_expr().and_then(|callee| callee.as_ident())
&& let [argument] = &call.args[..]
&& let Some(member) = argument.expr.as_member()
&& member
.obj
.as_member()
.is_some_and(|values| values.obj.is_this())
&& member
.prop
.as_computed()
.and_then(|index| index.expr.as_ident())
.is_some_and(|name| name.sym == self.index)
{
self.found.push(callee.sym.clone());
}
call.visit_children_with(self);
}
}
let read = body.stmts.iter().find_map(|statement| match statement {
Stmt::Decl(Decl::Class(declaration)) if method(&declaration.class, "write").is_some() => {
method(&declaration.class, "read")
}
_ => None,
}
})?;
let mut decoders = Decoders {
index: read.params.first()?.pat.as_ident()?.sym.clone(),
found: Vec::new(),
};
read.visit_with(&mut decoders);
let [decoder]: [Atom; 1] = decoders.found.try_into().ok()?;
Some(decoder)
}
/// The first class declaration with a `run` method.
@@ -256,18 +365,20 @@ pub(super) fn method<'a>(class: &'a Class, name: &str) -> Option<&'a Function> {
})
}
/// Reads `case <opcode>: <handler>(<operands>...); break;`, or `<handler>.call(this,
/// <operands>...)`, where each operand is `this` or a number.
/// Extracts opcode and handler pairs from `case <opcode>: <handler>(<machine>); break;`.
pub(super) fn handlers<'a>(
functions: &HashMap<Atom, &'a Function>,
run: &'a Function,
) -> Result<HashMap<u8, Handler<'a>>> {
let body = run.body.as_ref().context("the run method has no body")?;
let switch = body
.stmts
.iter()
.find_map(first_switch)
.context("the run method has no switch")?;
dispatch: &DispatchLoop<'a>,
) -> Result<HashMap<u8, &'a Function>> {
let switch = first_switch_in(dispatch.function).context("the dispatch loop has no switch")?;
let machine = dispatch.machine();
let is_machine = |argument: &ExprOrSpread| {
argument.spread.is_none()
&& argument
.expr
.as_ident()
.is_some_and(|name| Some(&name.sym) == machine)
};
let mut handlers = HashMap::default();
for case in &switch.cases {
let Some(test) = &case.test else { continue };
@@ -280,57 +391,26 @@ pub(super) fn handlers<'a>(
.iter()
.find_map(|statement| statement.as_expr()?.expr.as_call())
.with_context(|| format!("dispatch case {opcode} calls no handler"))?;
let Callee::Expr(callee) = &call.callee else {
bail!("dispatch case {opcode} calls no handler");
};
let (name, bound, operands) = match &**callee {
Expr::Ident(name) => (name, false, &call.args[..]),
Expr::Member(member) if ast::member_str(&member.prop) == Some("call") => {
let Expr::Ident(name) = &*member.obj else {
bail!("dispatch case {opcode} calls no named handler");
};
let [receiver, operands @ ..] = &call.args[..] else {
bail!(
"dispatch case {opcode} calls {} without a receiver",
name.sym
);
};
ensure!(
matches!(operand(receiver), Some(Operand::Machine)),
"dispatch case {opcode} does not call {} on the machine",
name.sym
);
(name, true, operands)
}
_ => bail!("dispatch case {opcode} calls no named handler"),
let Some(name) = call.callee.as_expr().and_then(|callee| callee.as_ident()) else {
bail!("dispatch case {opcode} calls no named handler");
};
let function = functions
.get(&name.sym)
.with_context(|| format!("no handler function {}", name.sym))?;
let arguments: Option<Vec<Operand>> = operands.iter().map(operand).collect();
let arguments = arguments.with_context(|| {
let name = &name.sym;
format!("an argument of handler {name} is neither the machine nor a number")
})?;
let previous = handlers.insert(
opcode,
Handler {
function,
bound,
arguments,
},
ensure!(
matches!(&call.args[..], [argument] if is_machine(argument)),
"dispatch case {opcode} does not pass {} only the machine",
name.sym
);
let previous = handlers.insert(opcode, *function);
ensure!(previous.is_none(), "opcode {opcode} has two dispatch cases");
}
Ok(handlers)
}
fn operand(argument: &ExprOrSpread) -> Option<Operand> {
match (&argument.spread, &*argument.expr) {
(None, Expr::This(_)) => Some(Operand::Machine),
(None, Expr::Lit(Lit::Num(number))) => Some(Operand::Number(number.value)),
_ => None,
}
/// Finds the first dispatch switch in the body of `function`.
fn first_switch_in(function: &Function) -> Option<&SwitchStmt> {
function.body.as_ref()?.stmts.iter().find_map(first_switch)
}
/// Finds the first dispatch `switch`; both dispatch loops use the same form.
+1 -2
View File
@@ -20,8 +20,7 @@ mod semantics;
mod setup;
pub(crate) use builtin::Builtin;
pub(crate) use explore::{Invocation, MAXIMUM_PATHS, Way, explore};
pub(crate) use explore::{Invocation, MAXIMUM_PATHS, Way, decode, explore};
pub(crate) use plan::Plans;
pub(crate) use run::{Run, Spare};
pub(crate) use semantics::numeric;
pub(crate) use setup::setup;
+146 -44
View File
@@ -3,12 +3,15 @@
use std::borrow::Cow;
use std::rc::Rc;
use swc_core::ecma::ast::BinaryOp;
use super::builtin::{self, Builtin};
use super::run::{Evaluation, Run, Stop};
use super::semantics;
use crate::js;
use crate::vm::convert::{self, MAXIMUM_LENGTH};
use crate::vm::output::{Constant, Effect, Term};
use crate::vm::registers::{Member, Slots, Stored};
use crate::vm::value::{Callable, JsString, Value};
/// A property key with text retained for named-property lookup.
@@ -82,12 +85,18 @@ impl<'ast> Run<'ast, '_> {
Key::Value(value) => value.number(),
};
Ok(match object {
Value::Registers => {
Value::Registers if let Some(member) = name.and_then(Member::of) => {
self.register_member(member)
}
Value::Registers | Value::RegisterSlots(Slots::Values) => {
self.register_value(self.register(key)?)
}
Value::RegisterSlots(Slots::Tags) => {
let register = self.register(key)?;
match self.registers.get(&register) {
Some(value) => value.clone(),
None => Value::symbolic(Term::Reg(register)),
}
self.tags
.get(&register)
.cloned()
.ok_or_else(|| unsupported("tag of a register", key))?
}
Value::Program => match (index, name) {
(Some(index), _) => convert::index(index)
@@ -106,6 +115,15 @@ impl<'ast> Run<'ast, '_> {
{
Value::Program
}
(Key::Value(Value::Symbol(symbol)), _) => {
let (_, field) = self
.session
.symbol_fields
.iter()
.find(|(key, _)| Rc::ptr_eq(key, symbol))
.ok_or_else(|| unsupported("machine member", key))?;
self.isolate(field)
}
(_, Some(name)) => match self.session.state.get(name) {
Some(value) => value.clone(),
None => self.field(name),
@@ -118,7 +136,6 @@ impl<'ast> Run<'ast, '_> {
Some(name) => builtin::member(path, name),
None => return Err(unsupported("global member", key)),
},
Value::Cache => self.cached(index).unwrap_or(Value::Undefined),
Value::Cells => match (index.and_then(convert::position), name) {
(Some(index), _) => Value::Cell(index),
(None, Some(_)) => {
@@ -152,6 +169,7 @@ impl<'ast> Run<'ast, '_> {
(None, Some("charCodeAt")) => {
Value::function(Callable::Builtin(Builtin::CharCodeAt))
}
(None, Some("repeat")) => Value::function(Callable::Builtin(Builtin::Repeat)),
(None, Some(method)) if STRING_MEMBERS.contains(&method) => {
return Err(Stop::unsupported(&format!("string method {method}")));
}
@@ -170,6 +188,10 @@ impl<'ast> Run<'ast, '_> {
.find(|(key, _)| **key == *name)
.map_or(Value::Undefined, |(_, value)| value.clone())
}
Value::Map(_) => match name.and_then(|name| builtin::method("Map.prototype", name)) {
Some(method) => method,
None => return Err(unsupported("map member", key)),
},
Value::Set(_) => match name.and_then(|name| builtin::method("Set.prototype", name)) {
Some(method) => method,
None => return Err(unsupported("set member", key)),
@@ -208,12 +230,31 @@ impl<'ast> Run<'ast, '_> {
) -> Evaluation<'ast, ()> {
let layout = self.session.layout;
match object {
Value::Registers => {
Value::Registers => match key.text().and_then(Member::of) {
Some(Member::Pc | Member::OtherPc) => self.set_register(layout.pc, value),
Some(Member::Key | Member::OtherKey) => self.set_register(layout.key, value),
// These fields have fixed values in the interpreter model.
Some(Member::Mask | Member::Integer | Member::PcIndex | Member::KeyIndex) => {}
Some(_) => return Err(unsupported("register file member", key)),
None => self.write_register(self.register(key)?, value),
},
Value::RegisterSlots(Slots::Tags) => {
let register = self.register(key)?;
if register != layout.pc && register != layout.key {
self.effects.push(Effect::Set(register, value.expr()));
}
self.set_register(register, value);
self.tags.insert(register, value);
}
// Value storage helpers write the tag before writing the value.
Value::RegisterSlots(Slots::Values) => {
let register = self.register(key)?;
let tag = self.tags.remove(&register).and_then(|tag| tag.number());
let tag = tag.map_or(Stored::Plain, Stored::of);
let value = match (tag, &value) {
// `read` decrypts on every access, but caching the decrypted value has the same
// result. Values copied from another register were already decrypted when first
// stored.
(Stored::Record, Value::Array(_)) => self.decrypted(value)?,
(tag, _) => stored(tag, value),
};
self.write_register(register, value);
}
Value::Cells => {
let cell = key
@@ -223,13 +264,26 @@ impl<'ast> Run<'ast, '_> {
self.effects.push(Effect::NewCell(cell));
}
Value::Cell(cell) => self.effects.push(Effect::SetCell(*cell, value.expr())),
Value::Cache => self.cache(key, &value),
Value::Machine => {
let name = key
.text()
.ok_or_else(|| unsupported("machine member", key))?;
self.set_field(name.to_owned(), value);
}
Value::Array(elements) if key.text() == Some("length") => {
match value.number() {
Some(length) => {
let length = convert::length(length)
.filter(|&length| length < MAXIMUM_LENGTH)
.ok_or_else(|| unsupported("array length", key))?;
elements.borrow_mut().resize(length, Value::Undefined);
}
// An earlier instruction restored the stack length. Keep the known elements
// from this run; see `Builtin::Pop`.
None if value.is_symbolic() => {}
None => return Err(unsupported("array length", key)),
}
}
Value::Array(elements) => {
let index = match key {
Key::Name(name) => key_index(name),
@@ -275,40 +329,74 @@ impl<'ast> Run<'ast, '_> {
Ok(())
}
/// Returns a decoded-string cache entry as a new array.
fn cached(&self, index: Option<f64>) -> Option<Value<'ast>> {
let slot = (self.handler?, convert::position(index?)?);
let decoded = self.session.decoded.borrow();
Some(Value::array(decoded.get(&slot)?.clone()))
}
/// Caches `value` at `key` only during handler execution and only when the entry is fully
/// determined by program bytes.
fn cache(&self, key: &Key<'_, 'ast>, value: &Value<'ast>) {
let primitive = |value: &Value<'_>| {
matches!(
value,
Value::Undefined
| Value::Null
| Value::Bool(_)
| Value::Number(_)
| Value::String(_)
)
};
if let (Some(handler), Key::Value(index), Value::Array(entry)) = (self.handler, key, value)
&& let Some(index) = index.number().and_then(convert::position)
&& entry.borrow().iter().all(primitive)
{
let entry = entry.borrow().clone();
self.session
.decoded
.borrow_mut()
.insert((handler, index), entry);
/// Returns the register value, using a symbolic value unless this run has assigned it.
pub(super) fn register_value(&self, register: u8) -> Value<'ast> {
match self.registers.get(&register) {
Some(value) => self.refined(value),
None => self.refined(&Value::symbolic(Term::Reg(register))),
}
}
/// The register `key` names.
fn register(&self, key: &Key<'_, 'ast>) -> Evaluation<'ast, u8> {
/// Sets a register, recording the write unless it moves the program counter or key.
pub(super) fn write_register(&mut self, register: u8, value: Value<'ast>) {
let layout = self.session.layout;
if register != layout.pc && register != layout.key {
self.effects.push(Effect::Set(register, value.expr()));
}
self.set_register(register, value);
}
/// Decrypts a string record using the same logic as the register file's `read` method.
fn decrypted(&mut self, record: Value<'ast>) -> Evaluation<'ast, Value<'ast>> {
let Value::Array(elements) = &record else {
return Ok(record);
};
let field = |index: usize| elements.borrow().get(index).and_then(Value::number);
let key = match (field(1), field(2), field(3)) {
(Some(pc), Some(length), Some(key)) => Some((pc as u32, length as u32, key as u32)),
_ => None,
};
if let Some(key) = key
&& let Some(text) = self.session.decrypted.borrow().get(&key)
{
return Ok(text.clone());
}
let decoder = self
.session
.record_decoder
.as_ref()
.ok_or_else(|| Stop::unsupported("an encrypted string with no decoder"))?;
let decoder = self.lookup(decoder)?;
let text = self.apply(decoder, Value::Undefined, vec![record])?;
if let (Some(key), Value::String(_)) = (key, &text) {
self.session
.decrypted
.borrow_mut()
.insert(key, text.clone());
}
Ok(text)
}
/// A member of the register file (see [`Member`]).
fn register_member(&self, member: Member) -> Value<'ast> {
let layout = self.session.layout;
match member {
Member::Read => Value::function(Callable::Builtin(Builtin::RegisterRead)),
Member::Write => Value::function(Callable::Builtin(Builtin::RegisterWrite)),
Member::Mask => Value::Number(0.0),
Member::Integer => Value::Number(1.0),
Member::Pc => self.register_value(layout.pc),
Member::Key => self.register_value(layout.key),
Member::OtherPc | Member::OtherKey => Value::Undefined,
Member::PcIndex => Value::Number(f64::from(layout.pc)),
Member::KeyIndex => Value::Number(f64::from(layout.key)),
Member::Values => Value::RegisterSlots(Slots::Values),
Member::Tags => Value::RegisterSlots(Slots::Tags),
}
}
/// Resolves the register index identified by `key`.
pub(super) fn register(&self, key: &Key<'_, 'ast>) -> Evaluation<'ast, u8> {
match key {
Key::Value(value) if !matches!(value, Value::String(_)) => {
value.number().and_then(convert::byte)
@@ -333,6 +421,21 @@ fn key_index(name: &str) -> Option<f64> {
(number.to_js_string() == name).then_some(number)
}
/// Decodes `value` stored with `tag`, matching the value returned by the register reader.
fn stored(tag: Stored, value: Value<'_>) -> Value<'_> {
match tag {
Stored::Integer(upper) => {
semantics::binary_value(BinaryOp::BitXor, Value::Number(f64::from(upper)), value)
}
Stored::Boolean(upper) => {
let bits =
semantics::binary_value(BinaryOp::BitXor, value, Value::Number(f64::from(upper)));
semantics::binary_value(BinaryOp::NotEqEq, bits, Value::Number(0.0))
}
Stored::Plain | Stored::Record => value,
}
}
pub(super) fn unsupported<'a>(what: &str, key: &Key<'_, '_>) -> Box<Stop<'a>> {
Stop::unsupported(&format!("{what} {}", key.expr()))
}
@@ -367,7 +470,6 @@ const STRING_MEMBERS: &[&str] = &[
"padEnd",
"padStart",
"propertyIsEnumerable",
"repeat",
"replace",
"replaceAll",
"search",
+103 -2
View File
@@ -41,7 +41,11 @@ builtins! {
FromCharCode => "String.fromCharCode",
Join => "Array.prototype.join",
Slice => "Array.prototype.slice",
Push => "Array.prototype.push",
Pop => "Array.prototype.pop",
IsArray => "Array.isArray",
CharCodeAt => "String.prototype.charCodeAt",
Repeat => "String.prototype.repeat",
/// `Function.prototype.call`, `apply`, and `bind`, plus `Reflect.apply` and
/// `Reflect.construct`.
Call => "Function.prototype.call",
@@ -63,6 +67,18 @@ builtins! {
Has => "Set.prototype.has",
Add => "Set.prototype.add",
Delete => "Set.prototype.delete",
/// `Map` and `WeakMap`, and their methods.
Map => "Map",
MapGet => "Map.prototype.get",
MapSet => "Map.prototype.set",
MapHas => "Map.prototype.has",
MapDelete => "Map.prototype.delete",
/// Typed arrays are modeled as empty objects because the script only uses them to cache values
/// it can recompute.
Int32Array => "Int32Array",
/// The register file's `read` and `write` methods (see [`crate::vm::registers`]).
RegisterRead => "registers.read",
RegisterWrite => "registers.write",
}
impl<'ast> Run<'ast, '_> {
@@ -124,6 +140,15 @@ impl<'ast> Run<'ast, '_> {
}
Ok(Value::String(units.into()))
}
Builtin::Repeat => {
let (Value::String(string), Some(count)) = (&this, argument(0).number()) else {
return symbolic(self, global());
};
let count = convert::length(count)
.filter(|&count| count.saturating_mul(string.len()) <= convert::MAXIMUM_LENGTH)
.ok_or_else(|| Stop::unsupported(&format!("repeating {count} times")))?;
Ok(Value::String(JsString::from(string.units().repeat(count))))
}
Builtin::CharCodeAt => {
let method = || {
let name = Term::Const(Constant::String("charCodeAt".into()));
@@ -187,6 +212,32 @@ impl<'ast> Run<'ast, '_> {
let end = bound(argument(1), length)?;
Ok(Value::array(elements[start..end.max(start)].to_vec()))
}
Builtin::Push => {
let Value::Array(elements) = &this else {
return self.apply(Value::symbolic(global()), this, arguments);
};
let mut elements = elements.borrow_mut();
elements.extend(arguments);
Ok(Value::Number(elements.len() as f64))
}
// Handlers start with constructor-created stacks that earlier instructions may have
// filled. Popping beyond values pushed in this run returns a value from an earlier
// instruction.
Builtin::Pop => {
let Value::Array(elements) = &this else {
return self.apply(Value::symbolic(global()), this, arguments);
};
let popped = elements.borrow_mut().pop();
match popped {
Some(value) => Ok(value),
None => symbolic(self, global()),
}
}
Builtin::IsArray => match argument(0) {
Value::Array(_) => Ok(Value::Bool(true)),
value if value.is_symbolic() => symbolic(self, global()),
_ => Ok(Value::Bool(false)),
},
Builtin::Pow | Builtin::Min | Builtin::Max | Builtin::Floor if registers_decide => {
symbolic(self, global())
}
@@ -264,6 +315,17 @@ impl<'ast> Run<'ast, '_> {
Ok(Value::array(mapped))
}
Builtin::Symbol => Ok(Value::Symbol(Rc::new(()))),
Builtin::Int32Array => Ok(Value::Object(Rc::default())),
Builtin::RegisterRead => {
let register = self.register(&Key::from(argument(0)))?;
Ok(self.register_value(register))
}
Builtin::RegisterWrite => {
let register = self.register(&Key::from(argument(0)))?;
let value = argument(1);
self.write_register(register, value.clone());
Ok(value)
}
Builtin::Set => match argument(0) {
Value::Undefined | Value::Null => Ok(Value::Set(Rc::default())),
Value::Array(elements) => {
@@ -318,6 +380,44 @@ impl<'ast> Run<'ast, '_> {
}
}
}
Builtin::Map => match argument(0) {
Value::Undefined | Value::Null => Ok(Value::Map(Rc::default())),
source => Err(Stop::unsupported(&format!("a map of {}", source.expr()))),
},
// Handlers start with constructor-created maps, such as the program closure registry.
// Earlier instructions may have filled them. Treat keys that depend on register values
// as absent.
Builtin::MapGet | Builtin::MapSet | Builtin::MapHas | Builtin::MapDelete => {
let Value::Map(entries) = &this else {
return self.apply(Value::symbolic(global()), this, arguments);
};
let key = argument(0);
let position = entries
.borrow()
.iter()
.position(|(member, _)| semantics::same_value_zero(member, &key) == Some(true));
match builtin {
Builtin::MapGet => Ok(position.map_or(Value::Undefined, |position| {
entries.borrow()[position].1.clone()
})),
Builtin::MapHas => Ok(Value::Bool(position.is_some())),
Builtin::MapSet => {
let value = argument(1);
let mut entries = entries.borrow_mut();
match position {
Some(position) => entries[position].1 = value,
None => entries.push((key, value)),
}
Ok(this.clone())
}
_ => {
if let Some(position) = position {
entries.borrow_mut().remove(position);
}
Ok(Value::Bool(position.is_some()))
}
}
}
Builtin::Error => Ok(Value::Object(Rc::new(RefCell::new(vec![(
"name".into(),
Value::string("Error"),
@@ -376,6 +476,7 @@ pub(super) fn member<'a>(object: &str, name: &str) -> Value<'a> {
};
match &*path {
"WeakSet" => Value::function(Callable::Builtin(Builtin::Set)),
"WeakMap" => Value::function(Callable::Builtin(Builtin::Map)),
"Number.NaN" => Value::Number(f64::NAN),
"Number.POSITIVE_INFINITY" => Value::Number(f64::INFINITY),
"Number.NEGATIVE_INFINITY" => Value::Number(f64::NEG_INFINITY),
@@ -549,11 +650,11 @@ mod tests {
);
}
assert!(
method("Array.prototype", "push").is_none(),
method("Array.prototype", "splice").is_none(),
"an array method that is not a builtin is not followed"
);
assert!(
matches!(member("", "Array.prototype.push"), Value::Symbolic(_)),
matches!(member("", "Array.prototype.splice"), Value::Symbolic(_)),
"what is not a builtin stays a global the registers decide"
);
let Value::Function(random) = member("Math", "random") else {
+1 -1
View File
@@ -219,7 +219,7 @@ impl<'ast> Run<'ast, '_> {
let body = self
.session
.compiled
.scoped(body, |body| plan::scoped(&body.stmts));
.scoped(body, |body| plan::scoped_body(&body.stmts));
self.body(Frame { this, scope }, &body, &mut [])
}
+8
View File
@@ -23,6 +23,7 @@ pub(super) fn copy<'a>(value: &Value<'a>, copies: &mut Copies<'a>) -> Value<'a>
Value::Array(elements) => Rc::as_ptr(elements).addr(),
Value::Object(properties) => Rc::as_ptr(properties).addr(),
Value::Set(members) => Rc::as_ptr(members).addr(),
Value::Map(entries) => Rc::as_ptr(entries).addr(),
Value::Function(callable) => Rc::as_ptr(callable).addr(),
_ => return value.clone(),
};
@@ -32,6 +33,13 @@ pub(super) fn copy<'a>(value: &Value<'a>, copies: &mut Copies<'a>) -> Value<'a>
match value {
Value::Array(elements) => copy_elements(elements, address, copies, Value::Array, copy),
Value::Set(members) => copy_elements(members, address, copies, Value::Set, copy),
Value::Map(entries) => copy_elements(
entries,
address,
copies,
Value::Map,
|(key, value), copies| (copy(key, copies), copy(value, copies)),
),
Value::Object(properties) => copy_elements(
properties,
address,
+56 -5
View File
@@ -4,7 +4,7 @@
use std::cell::RefCell;
use std::rc::Rc;
use std::slice;
use std::{mem, slice};
use swc_core::ecma::ast::{BinaryOp, Expr, Stmt, UpdateOp};
@@ -85,6 +85,22 @@ impl<'ast> Run<'ast, '_> {
Ok(Flow::Normal)
}
/// Checks whether `name` has already been declared in the current function.
fn declared(&self, name: Name<'ast>, locals: &Locals<'ast>) -> bool {
match name {
Name::Local(slot, _) => locals[slot].is_some(),
Name::Global(name) => self.frame().scope.borrow().variables.contains_key(name),
}
}
/// Declares `name` with `value`.
fn bind(&mut self, name: Name<'ast>, value: Value<'ast>, locals: &mut Locals<'ast>) {
match name {
Name::Local(slot, _) => locals[slot] = Some(value),
Name::Global(name) => self.declare(name.clone(), value),
}
}
fn execute(
&mut self,
statement: &Statement<'ast>,
@@ -100,13 +116,39 @@ impl<'ast> Run<'ast, '_> {
for declaration in declarations {
let value = match &declaration.init {
Some(expression) => self.evaluate(expression, locals)?,
None if declaration.keeps && self.declared(declaration.name, locals) => {
continue;
}
None => Value::Undefined,
};
match declaration.name {
Name::Local(slot, _) => locals[slot] = Some(value),
Name::Global(name) => self.declare(name.clone(), value),
self.bind(declaration.name, value, locals);
}
}
Statement::Try {
block,
parameter,
handler,
finalizer,
} => {
let mut outcome = self.execute_all(block, locals);
if let Some(handler) = handler
&& let Err(stop) = &mut outcome
&& let Stop::Throw(exception) = &mut **stop
{
let exception = mem::replace(exception, Value::Undefined);
if let Some(parameter) = parameter {
self.bind(*parameter, exception, locals);
}
outcome = self.execute_all(handler, locals);
}
// A jump from `finally` overrides the previous completion of the block.
if let Some(finalizer) = finalizer {
match self.execute_all(finalizer, locals)? {
Flow::Normal => {}
flow => return Ok(flow),
}
}
return outcome;
}
Statement::Block(statements) => return self.execute_all(statements, locals),
Statement::If(test, yes, no) => {
@@ -232,7 +274,10 @@ impl<'ast> Run<'ast, '_> {
match expression {
Expression::Constant(value) => Ok(copied(value)),
Expression::Name(Name::Local(slot, _)) if let Some(value) = &locals[*slot] => {
Ok(copied(value))
Ok(match value {
Value::Symbolic(_) => self.refined(value),
value => copied(value),
})
}
Expression::Binary(operator, left, right) => {
self.binary(*operator, left, right, locals)
@@ -464,6 +509,12 @@ impl<'ast> Run<'ast, '_> {
Some(BinaryOp::LogicalAnd | BinaryOp::LogicalOr | BinaryOp::NullishCoalescing) => {
return Err(Stop::unsupported("a logical assignment"));
}
// The script reapplies a new rolling mask to the program counter or key. The
// interpreter keeps that mask at zero; see `crate::vm::registers`.
Some(_) if matches!(&target, Location::Member(Value::Registers, Key::Name(_))) => {
self.evaluate(right, locals)?;
return self.read(&target, locals);
}
// The target's old value is read before the right side runs.
Some(operator) => {
let old = self.read(&target, locals)?;
+2 -1
View File
@@ -84,6 +84,7 @@ fn locals_calls_and_operand_order_match() {
"function f(a) { var o = {}; o.g = function(x, y) { return x | y + outer; }; return o.g(a, 4); }",
"function f(a) { var g = function h(n) { return n ? h(n - 1) + 1 : 0; }; return g(a); }",
"function f(a) { var g = (x) => x * 2 + this; return g(a); }",
"function f(a) { try { throw a; } catch (e) { return e + 1; } finally { outer = a; } }",
] {
compare(
source,
@@ -130,7 +131,7 @@ fn rejected_functions_use_scoped_plans() {
"function f(a) { var g = function() { return a; }; return g(); }",
"function f(arguments) { return arguments; }",
"function f(a) { return {[a]: 1}; }",
"function f(a) { try { return a; } catch (e) { return 0; } }",
"function f(a) { try { return a; } catch ({ e }) { return 0; } }",
] {
compare(source, vec![Value::Number(2.0)], vec![], false);
}
+46 -20
View File
@@ -2,12 +2,15 @@
use std::mem;
use super::run::Run;
use crate::vm::HashMap;
use crate::vm::extract::{Handler, Operand};
use swc_core::ecma::ast::Function;
use super::copies::Copies;
use super::run::{Run, Stop};
use crate::vm::dispatch::Decoded;
use crate::vm::output::Path;
use crate::vm::session::Session;
use crate::vm::value::{Callable, Value};
use crate::vm::{HashMap, convert};
/// Maximum symbolic branches explored per handler.
pub(crate) const MAXIMUM_PATHS: usize = 64;
@@ -20,7 +23,7 @@ pub(crate) struct Invocation<'session, 'ast> {
pub pc: u32,
/// The dispatch key the opcode byte leaves.
pub key: u8,
pub handler: &'session Handler<'ast>,
pub handler: &'ast Function,
/// The instance fields the constructor derives from the program.
pub fields: &'session HashMap<String, Value<'ast>>,
/// Registers whose values are known, such as a candidate string.
@@ -45,29 +48,15 @@ pub(crate) struct Way<'ast> {
#[must_use]
pub(crate) fn explore<'ast>(invocation: &Invocation<'_, 'ast>) -> Option<Ways<'ast>> {
let mut ways = Ways::default();
let this = if invocation.handler.bound {
Value::Machine
} else {
Value::Undefined
};
let arguments: Vec<Value<'_>> = invocation
.handler
.arguments
.iter()
.map(|operand| match *operand {
Operand::Machine => Value::Machine,
Operand::Number(number) => Value::Number(number),
})
.collect();
let handler = Callable::Script {
name: None,
function: invocation.handler.function,
function: invocation.handler,
scope: None,
};
let mut decisions = Vec::new();
for _ in 0..MAXIMUM_PATHS {
let mut run = Run::handler(invocation, decisions);
let outcome = run.invoke(&handler, this.clone(), arguments.clone());
let outcome = run.invoke(&handler, Value::Undefined, vec![Value::Machine]);
decisions = mem::take(&mut run.branches.decisions);
decisions.truncate(run.branches.decided);
let scopes = run.scopes();
@@ -92,3 +81,40 @@ pub(crate) fn explore<'ast>(invocation: &Invocation<'_, 'ast>) -> Option<Ways<'a
}
None
}
/// Runs `decoder` after setting the program counter and dispatch key registers. Returns the decoded
/// opcode and updated key, or the reason execution stopped.
pub(crate) fn decode<'ast>(
session: &Session<'ast>,
program: &[u8],
decoder: &'ast Function,
arguments: Vec<Value<'ast>>,
pc: u32,
key: u8,
) -> Result<Decoded, String> {
let mut run = Run::new(session, program, Vec::new(), Some(Copies::default()));
run.start_at(pc, key);
let decoder = Callable::Script {
name: None,
function: decoder,
scope: None,
};
let outcome = run.invoke(&decoder, Value::Undefined, arguments);
let next = run.register_value(session.layout.key);
for scope in run.scopes() {
scope.borrow_mut().variables.clear();
}
let opcode = outcome.map_err(|stop| match *stop {
Stop::Throw(value) => format!("throws {}", value.expr()),
Stop::Unsupported(reason) => reason,
})?;
let byte = |value: &Value<'_>| value.number().and_then(convert::byte);
match (byte(&opcode), byte(&next)) {
(Some(opcode), Some(key)) => Ok(Decoded { opcode, key }),
_ => Err(format!(
"decoding leaves opcode {} and key {}",
opcode.expr(),
next.expr()
)),
}
}
+73 -6
View File
@@ -10,9 +10,10 @@ use std::rc::Rc;
use swc_core::atoms::{Atom, atom};
use swc_core::ecma::ast::{
ArrowExpr, AssignTarget, BinaryOp, BlockStmtOrExpr, Callee, Class, Decl, DoWhileStmt, Expr,
ExprOrSpread, Function, Ident, Lit, MemberExpr, MemberProp, Pat, Prop, PropName, PropOrSpread,
SimpleAssignTarget, Stmt, UnaryOp, UpdateOp, VarDecl, VarDeclOrExpr, VarDeclarator, WhileStmt,
ArrowExpr, AssignTarget, BinaryOp, BlockStmtOrExpr, Callee, CatchClause, Class, Decl,
DoWhileStmt, Expr, ExprOrSpread, FnDecl, Function, Ident, Lit, MemberExpr, MemberProp, Pat,
Prop, PropName, PropOrSpread, SimpleAssignTarget, Stmt, UnaryOp, UpdateOp, VarDecl,
VarDeclKind, VarDeclOrExpr, VarDeclarator, WhileStmt,
};
use swc_core::ecma::visit::{Visit, VisitWith};
@@ -87,7 +88,7 @@ impl<'ast> FunctionPlan<'ast> {
}
let body = function.body.as_ref()?;
body.visit_with(&mut compiler);
let body = compiler.statements(&body.stmts);
let body = compiler.body(&body.stmts);
if compiler.rejected {
return None;
}
@@ -104,13 +105,19 @@ pub(super) fn scoped(statements: &[Stmt]) -> Vec<Statement<'_>> {
PlanCompiler::default().statements(statements)
}
/// Scoped execution plan for a function body. Function declarations bind their names at the start
/// of the call.
pub(super) fn scoped_body(statements: &[Stmt]) -> Vec<Statement<'_>> {
PlanCompiler::default().body(statements)
}
pub(super) fn scoped_expression(expression: &Expr) -> Expression<'_> {
PlanCompiler::default().expression(expression)
}
pub(super) fn scoped_arrow(arrow: &ArrowExpr) -> Vec<Statement<'_>> {
match &*arrow.body {
BlockStmtOrExpr::BlockStmt(body) => scoped(&body.stmts),
BlockStmtOrExpr::BlockStmt(body) => scoped_body(&body.stmts),
BlockStmtOrExpr::Expr(body) => vec![Statement::Return(Some(scoped_expression(body)))],
}
}
@@ -137,6 +144,19 @@ impl Visit for PlanCompiler {
}
}
/// Treat a nested function declaration as a local binding in the enclosing function.
fn visit_fn_decl(&mut self, declaration: &FnDecl) {
self.slot(&declaration.ident.sym);
}
/// Treat a `catch` parameter as a function local in the execution plan.
fn visit_catch_clause(&mut self, clause: &CatchClause) {
if let Some(Pat::Ident(name)) = &clause.param {
self.slot(&name.sym);
}
clause.visit_children_with(self);
}
// Compile a nested function only if it captures no outer locals (see
// [`PlanCompiler::closes_over_nothing`]). Its own locals remain separate.
fn visit_function(&mut self, _: &Function) {}
@@ -163,6 +183,8 @@ pub(super) struct Case<'ast> {
pub(super) struct Declaration<'ast> {
pub(super) name: Name<'ast>,
pub(super) init: Option<Expression<'ast>>,
/// A `var` declaration without an initializer preserves any existing value.
pub(super) keeps: bool,
}
pub(super) enum Statement<'ast> {
@@ -189,6 +211,13 @@ pub(super) enum Statement<'ast> {
Break(Option<&'ast Atom>),
Continue(Option<&'ast Atom>),
Label(&'ast Atom, Box<Statement<'ast>>),
/// A `try` statement with its catch parameter, catch body, and finally body.
Try {
block: Vec<Statement<'ast>>,
parameter: Option<Name<'ast>>,
handler: Option<Vec<Statement<'ast>>>,
finalizer: Option<Vec<Statement<'ast>>>,
},
Empty,
}
@@ -279,6 +308,25 @@ impl PlanCompiler {
.all(|name| !self.locals.contains_key(name) && !(arrow && name == "arguments"))
}
/// Plans a function body, binding function declarations before executing statements.
/// Declarations beside the VM class are planned as statements and resolved as globals.
fn body<'a>(&mut self, statements: &'a [Stmt]) -> Vec<Statement<'a>> {
let mut plan = Vec::with_capacity(statements.len());
for statement in statements {
if let Stmt::Decl(Decl::Fn(declaration)) = statement {
let name = &declaration.ident.sym;
self.rejected |= !self.closes_over_nothing(&*declaration.function, false);
plan.push(Statement::Declare(vec![Declaration {
name: self.name(name),
init: Some(Expression::Function(Some(name), &declaration.function)),
keeps: false,
}]));
}
}
plan.extend(self.statements(statements));
plan
}
fn statements<'a>(&mut self, statements: &'a [Stmt]) -> Vec<Statement<'a>> {
statements
.iter()
@@ -347,7 +395,25 @@ impl PlanCompiler {
body_first: matches!(statement, Stmt::DoWhile(_)),
label,
},
Stmt::Try(_) => Statement::Expression(self.unsupported("a try statement")),
Stmt::Try(attempt) => {
let handler = attempt.handler.as_ref();
let parameter = match handler.and_then(|handler| handler.param.as_ref()) {
None => None,
Some(Pat::Ident(name)) => Some(self.name(&name.sym)),
Some(_) => {
return Statement::Expression(self.unsupported("a destructuring catch"));
}
};
Statement::Try {
block: self.statements(&attempt.block.stmts),
parameter,
handler: handler.map(|handler| self.statements(&handler.body.stmts)),
finalizer: attempt
.finalizer
.as_ref()
.map(|body| self.statements(&body.stmts)),
}
}
Stmt::ForIn(_) | Stmt::ForOf(_) => {
Statement::Expression(self.unsupported("a for-in or for-of loop"))
}
@@ -371,6 +437,7 @@ impl PlanCompiler {
declarations.push(Declaration {
name: self.name(&name.sym),
init: declarator.init.as_ref().map(|init| self.expression(init)),
keeps: declaration.kind == VarDeclKind::Var && declarator.init.is_none(),
});
}
Statement::Declare(declarations)
+85 -18
View File
@@ -3,8 +3,8 @@
use std::borrow::Cow;
use std::hash::Hash;
use std::mem;
use std::rc::Rc;
use std::{mem, ptr};
use swc_core::atoms::Atom;
use swc_core::ecma::ast::{BinaryOp, UnaryOp};
@@ -12,7 +12,7 @@ use swc_core::ecma::ast::{BinaryOp, UnaryOp};
use super::builtin;
use super::copies::{self, Copies};
use super::explore::Invocation;
use crate::vm::output::{Effect, Exit, Path, Position, Term};
use crate::vm::output::{Constant, Effect, Exit, Path, Position, Term};
use crate::vm::session::Session;
use crate::vm::value::{Callable, Env, Scope, Value};
use crate::vm::{HashMap, convert};
@@ -52,6 +52,8 @@ pub(crate) struct Run<'ast, 'session> {
/// Instance fields derived from program bytes by the constructor, once known.
constructed: Option<&'session HashMap<String, Value<'ast>>>,
pub(super) registers: HashMap<u8, Value<'ast>>,
/// Tags written before their register values; see [`crate::vm::registers`].
pub(super) tags: HashMap<u8, Value<'ast>>,
/// Instance fields this run has read or written.
pub(super) fields: HashMap<String, Value<'ast>>,
/// Session bindings this run has read or written.
@@ -70,11 +72,10 @@ pub(crate) struct Run<'ast, 'session> {
pub(super) effects: Vec<Effect>,
temps: usize,
pub(super) branches: Branches,
/// Register-dependent expressions known to equal constants on the current branch path.
facts: Vec<(Term, Value<'ast>)>,
journal: Journal<'ast>,
pub(super) spare: Spare<'ast>,
/// The running handler's address, which keys decoded-string cache entries. `None` outside
/// handler runs.
pub(super) handler: Option<usize>,
}
/// Cleared buffers from completed calls. Handler runs take them from the session and
@@ -185,6 +186,7 @@ pub(super) struct Checkpoint {
decisions: usize,
decided: usize,
conditions: usize,
facts: usize,
}
/// The value held at a map key before a write.
@@ -221,6 +223,7 @@ impl<'ast, 'session> Run<'ast, 'session> {
program,
constructed: None,
registers: HashMap::default(),
tags: HashMap::default(),
fields: HashMap::default(),
globals: HashMap::default(),
unavailable: Cow::Borrowed(&session.unavailable),
@@ -234,16 +237,15 @@ impl<'ast, 'session> Run<'ast, 'session> {
decisions,
..Branches::default()
},
facts: Vec::new(),
journal: Journal::default(),
spare: Spare::default(),
handler: None,
}
}
/// A handler run that follows `decisions`, then takes any further symbolic branch as true.
pub(super) fn handler(invocation: &Invocation<'session, 'ast>, decisions: Vec<bool>) -> Self {
let session = invocation.session;
let layout = session.layout;
let mut run = Self::new(
session,
invocation.program,
@@ -252,15 +254,24 @@ impl<'ast, 'session> Run<'ast, 'session> {
);
run.constructed = Some(invocation.fields);
run.spare = session.spare.take();
run.handler = Some(ptr::from_ref(invocation.handler.function).addr());
run.registers.extend([
(layout.pc, Value::Number(f64::from(invocation.pc))),
(layout.key, Value::Number(f64::from(invocation.key))),
for (register, value) in &session.initial {
let value = run.isolate(value);
run.registers.insert(*register, value);
}
run.start_at(invocation.pc, invocation.key);
run.registers.extend(invocation.known.iter().cloned());
run
}
/// Sets the program counter to `pc` and the dispatch key to `key`.
pub(super) fn start_at(&mut self, pc: u32, key: u8) {
let layout = self.session.layout;
self.registers.extend([
(layout.pc, Value::Number(f64::from(pc))),
(layout.key, Value::Number(f64::from(key))),
(layout.program, Value::Program),
(layout.cells, Value::Cells),
]);
run.registers.extend(invocation.known.iter().cloned());
run
}
/// A run inside a method of the instance, while the session is built.
@@ -338,10 +349,52 @@ impl<'ast, 'session> Run<'ast, 'session> {
}
pub(super) fn decide(&mut self, condition: &Value<'ast>) -> bool {
condition.truthy().unwrap_or_else(|| match condition {
Value::Symbolic(term) => self.branches.decide(term),
condition => self.branches.decide(&condition.expr()),
})
if let Some(truth) = condition.truthy() {
return truth;
}
let term = match condition {
Value::Symbolic(term) => Cow::Borrowed(&**term),
condition => Cow::Owned(condition.expr()),
};
let decision = self.branches.decide(&term);
self.learn(&term, decision);
decision
}
/// Records that an expression equals a constant after a true strict equality test or a false
/// strict inequality test.
fn learn(&mut self, mut condition: &Term, mut holds: bool) {
while let Term::Unary(UnaryOp::Bang, inner) = condition {
condition = inner;
holds = !holds;
}
let Term::Binary(operator, left, right) = condition else {
return;
};
let equal = match operator {
BinaryOp::EqEqEq => holds,
BinaryOp::NotEqEq => !holds,
_ => return,
};
if equal
&& let (Term::Const(constant), term) | (term, Term::Const(constant)) =
(&**left, &**right)
&& !matches!(term, Term::Const(_))
&& let Some(value) = constant_value(constant)
{
self.facts.push((term.clone(), value));
}
}
/// Returns the known constant for `value` on the current branch path, or `value` if none is
/// known.
pub(super) fn refined(&self, value: &Value<'ast>) -> Value<'ast> {
if let Value::Symbolic(term) = value
&& let Some((_, known)) = self.facts.iter().find(|(fact, _)| fact == &**term)
{
return known.clone();
}
value.clone()
}
pub(super) fn temp(&mut self, expr: Term) -> Value<'ast> {
@@ -459,6 +512,7 @@ impl<'ast, 'session> Run<'ast, 'session> {
decisions: self.branches.decisions.len(),
decided: self.branches.decided,
conditions: self.branches.conditions.len(),
facts: self.facts.len(),
}
}
@@ -480,6 +534,7 @@ impl<'ast, 'session> Run<'ast, 'session> {
branches.decisions.truncate(checkpoint.decisions);
branches.decided = checkpoint.decided;
branches.conditions.truncate(checkpoint.conditions);
self.facts.truncate(checkpoint.facts);
self.release(checkpoint);
}
@@ -522,7 +577,7 @@ impl<'ast, 'session> Run<'ast, 'session> {
}
/// Copies a session value for use by this run, preserving run-local sharing.
fn isolate(&mut self, value: &Value<'ast>) -> Value<'ast> {
pub(super) fn isolate(&mut self, value: &Value<'ast>) -> Value<'ast> {
let Some(copies) = &mut self.copies else {
return value.clone();
};
@@ -530,6 +585,18 @@ impl<'ast, 'session> Run<'ast, 'session> {
}
}
/// Converts a constant to a value. Excludes NaN because it is not equal to any value.
fn constant_value<'a>(constant: &Constant) -> Option<Value<'a>> {
Some(match constant {
Constant::Undefined => Value::Undefined,
Constant::Null => Value::Null,
Constant::Bool(value) => Value::Bool(*value),
Constant::Number(number) if number.is_nan() => return None,
Constant::Number(number) => Value::Number(*number),
Constant::String(text) => Value::string(text),
})
}
/// Restores `old` at `key` in `map`, removing the key if it was previously absent.
fn restore<K: Eq + Hash, V>(map: &mut HashMap<K, V>, key: K, old: Option<V>) {
match old {
+2
View File
@@ -99,6 +99,7 @@ pub(super) fn strict_equal<'a>(left: &Value<'a>, right: &Value<'a>) -> Option<bo
(Value::Array(a), Value::Array(b)) => Rc::ptr_eq(a, b),
(Value::Object(a), Value::Object(b)) => Rc::ptr_eq(a, b),
(Value::Set(a), Value::Set(b)) => Rc::ptr_eq(a, b),
(Value::Map(a), Value::Map(b)) => Rc::ptr_eq(a, b),
(Value::Function(a), Value::Function(b)) => Rc::ptr_eq(a, b),
(Value::Symbol(a), Value::Symbol(b)) => Rc::ptr_eq(a, b),
(Value::Namespace(a), Value::Namespace(b)) => a == b,
@@ -113,6 +114,7 @@ fn is_object(value: &Value<'_>) -> bool {
Value::Array(_)
| Value::Object(_)
| Value::Set(_)
| Value::Map(_)
| Value::Function(_)
| Value::Namespace(_)
)
+13 -8
View File
@@ -4,14 +4,14 @@ use anyhow::Result;
use swc_core::ecma::ast::{BlockStmt, Class, Script, Stmt};
use super::HashMap;
use super::dispatch::{Decoded, Dispatch, Helpers};
use super::dispatch::{Decoded, Dispatch};
use super::extract::{self, Finder};
use super::interpret::{self, Invocation, MAXIMUM_PATHS, Way};
use super::output::{Cause, Failure, Instruction, Position};
use super::session::Session;
use super::value::Value;
/// The VM's enclosing function body, class, dispatch table, and the statements that run before
/// The VM class, enclosing function body, opcode decoder, and statements executed before
/// its scope is entered.
pub struct Definition {
body: BlockStmt,
@@ -31,7 +31,8 @@ impl Definition {
script.visit_with(&mut finder);
let (body, class) = finder.found.context("no VM class in the script")?;
let run = extract::method(&class, "run").context("the VM class has no run method")?;
let dispatch = Dispatch::from_run(run, &Helpers::new(script))?;
let functions = extract::functions(&body.stmts);
let dispatch = Dispatch::from_loop(&extract::run_method(&functions, run)?.dispatch)?;
Ok(Self {
prelude: extract::prelude(script, &body),
body,
@@ -125,15 +126,19 @@ impl<'definition> Machine<'definition> {
known: &[(u8, Value<'definition>)],
) -> Result<(u8, Vec<Way<'definition>>), Failure> {
let fail = |cause| Failure { pc, key, cause };
let byte = *loaded
.program
.get(pc as usize)
.ok_or_else(|| fail(Cause::PastEnd))?;
let Decoded { opcode, key: next } = self.definition.dispatch.decode(key, byte);
if pc as usize >= loaded.program.len() {
return Err(fail(Cause::PastEnd));
}
let Decoded { opcode, key: next } = self
.definition
.dispatch
.decode(&self.session, loaded.program, pc, key)
.map_err(|reason| fail(Cause::Undecoded { reason }))?;
let handler = self
.session
.handlers
.get(&opcode)
.copied()
.ok_or_else(|| fail(Cause::NoHandler { opcode }))?;
let invocation = Invocation {
session: &self.session,
+5
View File
@@ -150,6 +150,10 @@ pub struct Failure {
#[derive(Clone, Debug, PartialEq)]
pub enum Cause {
PastEnd,
/// Reason the dispatch decoder stopped without producing an opcode.
Undecoded {
reason: String,
},
/// The byte decodes to an opcode the run loop has no case for.
NoHandler {
opcode: u8,
@@ -170,6 +174,7 @@ impl Display for Failure {
let pc = self.pc;
match &self.cause {
Cause::PastEnd => write!(f, "pc {pc} is past the end of the program"),
Cause::Undecoded { reason } => write!(f, "pc {pc} decodes no opcode: {reason}"),
Cause::NoHandler { opcode } => write!(f, "no handler for opcode {opcode} at pc {pc}"),
Cause::Faults { opcode, reasons } => {
let reasons = reasons.join("; ");
+90
View File
@@ -0,0 +1,90 @@
//! The VM register file, whose `read` and `write` methods access 256 registers.
//!
//! Each value has a type tag and is masked by a rolling `state`. A digest updated on every write
//! determines the mask. Separate fields hold the program counter and dispatch key. Handlers access
//! registers through methods, direct tag and value writes, or the counter and key fields.
//!
//! The interpreter keeps the mask and digest at zero. Stored values are therefore unmasked, and
//! changing the mask has no effect. Member names match the current build.
use crate::js;
/// Meaning of a field or method on the register file.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub(crate) enum Member {
/// Read methods: `read(index)` and `save(index)`. They differ only for closures.
Read,
/// Write methods: `write(index, value)` and `restore(index, value)`. They differ only for
/// closures.
Write,
/// Rolling mask or the digest used to compute it.
Mask,
/// Flag indicating whether the program counter or dispatch key holds a masked integer.
Integer,
Pc,
Key,
/// Program counter or dispatch key value when it is not an integer.
OtherPc,
OtherKey,
/// Register indices for the program counter and dispatch key.
PcIndex,
KeyIndex,
Values,
Tags,
}
impl Member {
#[must_use]
pub(crate) fn of(name: &str) -> Option<Self> {
Some(match name {
"read" | "save" => Self::Read,
"write" | "restore" => Self::Write,
"state" | "digest" | "I" | "J" => Self::Mask,
"i" | "l" => Self::Integer,
"h" => Self::Pc,
"j" => Self::Key,
"v" => Self::OtherPc,
"u" => Self::OtherKey,
"C" => Self::PcIndex,
"D" => Self::KeyIndex,
"values" => Self::Values,
"H" => Self::Tags,
_ => return None,
})
}
}
/// Arrays storing register values and tags at matching indices.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub(crate) enum Slots {
Values,
Tags,
}
/// Decoding rule used by `read` for a value with `tag`, assuming a zero mask.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub(crate) enum Stored {
/// Tag 1 stores an integer XORed with the tag's upper bits.
Integer(i32),
/// Tag 2 stores a boolean as a comparison with the tag's upper bits.
Boolean(i32),
/// Tag -4 stores an encrypted string record, decrypted by `read`.
Record,
/// All other tags store the value directly.
Plain,
}
impl Stored {
#[must_use]
pub(crate) fn of(tag: f64) -> Self {
let tag = js::int32(tag);
if tag == -4 {
return Self::Record;
}
match tag & 3 {
1 => Self::Integer(tag >> 2),
2 => Self::Boolean(tag >> 2),
_ => Self::Plain,
}
}
}
+251 -51
View File
@@ -2,8 +2,8 @@
//! layout, instance fields, and opcode handlers. [`Session::constructed`] adds the constructor
//! fields that depend on a program.
//!
//! Handler runs copy mutable values (see [`super::interpret`]); only deterministic decoded
//! strings ([`Session::decoded`]) and lazily compiled plans are cached across runs.
//! Each handler run copies mutable values; see [`super::interpret`]. Only decrypted strings
//! ([`Session::decrypted`]) and lazily compiled plans are cached between runs.
use std::cell::RefCell;
use std::collections::BTreeSet;
@@ -12,12 +12,14 @@ use std::rc::Rc;
use anyhow::{Context, Result, bail, ensure};
use swc_core::atoms::Atom;
use swc_core::ecma::ast::{
AssignTarget, BinaryOp, BlockStmt, Class, Expr, Function, MemberProp, SimpleAssignTarget, Stmt,
AssignExpr, AssignTarget, BinaryOp, BlockStmt, Class, Decl, Expr, Function, MemberProp,
ObjectLit, SimpleAssignTarget, Stmt,
};
use super::extract::{self, Handler, StateFields};
use super::extract::{self, RunMethod};
use super::interpret::{self, Plans, Run, Spare};
use super::output::{Constant, Position, Term};
use super::registers::Member;
use super::value::Value;
use super::{HashMap, convert};
use crate::js::ast;
@@ -36,20 +38,23 @@ pub(crate) struct Session<'ast> {
/// stops interpretation.
pub unavailable: HashMap<Atom, String>,
pub layout: Layout,
/// Handler state: registers, register mask, state-register indices, and decoded-string
/// cache.
/// Handler state: registers, register mask, and state-register indices.
pub state: HashMap<String, Value<'ast>>,
/// Initial register stacks created by the constructor for handler execution.
pub initial: Vec<(u8, Value<'ast>)>,
/// Function used to decrypt string records stored in registers.
pub record_decoder: Option<Atom>,
/// Decrypted strings cached by record position, length, and key.
pub decrypted: RefCell<HashMap<(u32, u32, u32), Value<'ast>>>,
/// The symbol the instance keeps its program under, if any.
pub program_key: Option<Rc<()>>,
/// Decoded strings cached by handler and slot across runs. An entry is valid only for its
/// bytecode position and dispatch key; reusing it avoids decoding again during branch
/// exploration and comparison retries.
pub decoded: RefCell<HashMap<(usize, u32), Vec<Value<'ast>>>>,
/// Instance objects stored under the remaining symbols.
pub symbol_fields: Vec<(Rc<()>, Value<'ast>)>,
/// Other fields the constructor initializes, including the string-hash cache that hashed
/// comparisons use.
pub fields: HashMap<String, Value<'ast>>,
constructor: &'ast BlockStmt,
pub handlers: HashMap<u8, Handler<'ast>>,
pub handlers: HashMap<u8, &'ast Function>,
/// Where the program runner starts a program.
pub entry: Position,
}
@@ -74,23 +79,25 @@ impl<'ast> Session<'ast> {
let run = extract::method(class, "run").context("the VM class has no run method")?;
let constructor = extract::constructor(class)?;
let functions = extract::functions(&body.stmts);
let handlers = extract::handlers(&functions, run)?;
let names = extract::state_fields(run)?;
let run = extract::run_method(&functions, run)?;
let handlers = extract::handlers(&functions, &run.dispatch)?;
let mut session = Self {
functions,
handlers,
entry: extract::entry(body)?,
record_decoder: extract::record_decoder(body),
..Self::unevaluated(constructor)
};
(session.bindings, session.unavailable) = interpret::setup(&session, prelude, &body.stmts);
let (fields, symbols) = construct(&mut Run::method(&session), constructor);
(session.state, session.layout) = state(&names, &fields)?;
session.program_key = match &symbols[..] {
let constructed = construct(&mut Run::method(&session), constructor);
(session.state, session.layout, session.initial) = state(&run, &constructed)?;
session.symbol_fields = constructed.objects;
session.program_key = match &constructed.programs[..] {
[] => None,
[symbol] => Some(symbol.clone()),
symbols => bail!("the VM constructor keys {} fields by symbol", symbols.len()),
symbols => bail!("the VM constructor keys {} values by symbol", symbols.len()),
};
session.fields = concrete(fields);
session.fields = concrete(constructed.fields);
Ok(session)
}
@@ -105,7 +112,10 @@ impl<'ast> Session<'ast> {
layout: Layout::default(),
state: HashMap::default(),
program_key: None,
decoded: RefCell::default(),
symbol_fields: Vec::new(),
initial: Vec::new(),
record_decoder: None,
decrypted: RefCell::default(),
fields: HashMap::default(),
constructor,
handlers: HashMap::default(),
@@ -116,8 +126,7 @@ impl<'ast> Session<'ast> {
/// Evaluates the constructor fields for `program`, including program-dependent data such as
/// its string table.
pub(super) fn constructed(&self, program: &[u8]) -> HashMap<String, Value<'ast>> {
let (fields, _) = construct(&mut Run::constructor(self, program), self.constructor);
concrete(fields)
concrete(construct(&mut Run::constructor(self, program), self.constructor).fields)
}
}
@@ -129,32 +138,205 @@ impl Session<'_> {
}
}
/// Evaluates the constructor's field assignments through `run`. Returns the named fields and
/// the symbols used as other keys.
fn construct<'a>(
/// Values initialized by the constructor.
#[derive(Default)]
struct Constructed<'a> {
fields: HashMap<String, Value<'a>>,
/// Symbol-keyed values other than object literals, including the program.
programs: Vec<Rc<()>>,
/// Object literals indexed by their symbol keys.
objects: Vec<(Rc<()>, Value<'a>)>,
/// Source fields for the register file program counter and dispatch key indices.
pc: Option<String>,
key: Option<String>,
registers: Vec<RegisterWrite<'a>>,
}
/// Matches register writes as `<file>.write(<mask> ^ <register>, <value>)` or equivalent helper
/// calls: `store(<file>, <mask> ^ <register>, <value>)`.
struct RegisterWrite<'a> {
/// The field holding the register file.
file: String,
/// The field holding the index mask.
mask: String,
register: u8,
value: Value<'a>,
}
/// Evaluates object literal properties. Uses null for properties computed from program bytes, such
/// as the word array used by a faster string decoder. This makes handlers use byte-by-byte decoding
/// instead.
fn object_fields<'a>(run: &mut Run<'a, '_>, object: &'a ObjectLit) -> Value<'a> {
let properties = ast::key_values(object)
.filter_map(|property| {
let name = ast::key_str(&property.key)?.to_owned();
let value = run
.expression(&property.value)
.ok()
.filter(|value| !value.is_symbolic());
Some((name, value.unwrap_or(Value::Null)))
})
.collect();
Value::Object(Rc::new(RefCell::new(properties)))
}
/// Evaluates constructor field assignments in order through `run`, including nested blocks. Follows
/// field copies through locals to find the source fields for the program counter and dispatch key
/// indices.
fn construct<'a>(run: &mut Run<'a, '_>, constructor: &'a BlockStmt) -> Constructed<'a> {
let mut constructed = Constructed::default();
let mut copies = HashMap::default();
construct_statements(run, &constructor.stmts, &mut constructed, &mut copies);
constructed
}
fn construct_statements<'a>(
run: &mut Run<'a, '_>,
constructor: &'a BlockStmt,
) -> (HashMap<String, Value<'a>>, Vec<Rc<()>>) {
let mut fields = HashMap::default();
let mut symbols = Vec::new();
for statement in &constructor.stmts {
if let Stmt::Expr(statement) = statement
&& let Expr::Assign(assign) = &*statement.expr
&& let AssignTarget::Simple(SimpleAssignTarget::Member(target)) = &assign.left
&& matches!(&*target.obj, Expr::This(_))
{
statements: &'a [Stmt],
constructed: &mut Constructed<'a>,
copies: &mut HashMap<Atom, String>,
) {
for statement in statements {
match statement {
Stmt::Block(block) => construct_statements(run, &block.stmts, constructed, copies),
Stmt::Expr(statement) => {
construct_expression(run, &statement.expr, constructed, copies);
}
// In `var copy = (local = this.field, this.other)`, `copy` receives the final operand,
// `this.other`.
Stmt::Decl(Decl::Var(declaration)) => {
for declarator in &declaration.decls {
let Some(init) = &declarator.init else {
continue;
};
construct_expression(run, init, constructed, copies);
let Some(name) = declarator.name.as_ident() else {
continue;
};
let value = match init.unwrap_parens() {
Expr::Seq(sequence) if let Some(last) = sequence.exprs.last() => {
last.unwrap_parens()
}
value => value,
};
track_copy(&name.sym, value, copies);
}
}
_ => {}
}
}
}
/// Visits assignments in `expr` in evaluation order, including sequence operands.
fn construct_expression<'a>(
run: &mut Run<'a, '_>,
expr: &'a Expr,
constructed: &mut Constructed<'a>,
copies: &mut HashMap<Atom, String>,
) {
match expr {
Expr::Paren(paren) => construct_expression(run, &paren.expr, constructed, copies),
Expr::Seq(sequence) => {
for expr in &sequence.exprs {
construct_expression(run, expr, constructed, copies);
}
}
Expr::Assign(assign) => construct_assignment(run, assign, constructed, copies),
Expr::Call(call) => {
let (file, index, value) = match (ast::method_call(expr, "write"), &call.args[..]) {
(Some((file, _)), [index, value]) => (file, index, value),
(None, [file, index, value]) => (&*file.expr, index, value),
_ => return,
};
if let Some(file) = file.as_ident().and_then(|name| copies.get(&name.sym))
&& let Some((mask, register)) = masked_index(&index.expr, copies)
&& let Ok(value) = run.expression(&value.expr)
{
constructed.registers.push(RegisterWrite {
file: file.clone(),
mask,
register,
value,
});
}
}
_ => {}
}
}
/// Extracts the mask field and register from `<mask> ^ <register>`. The mask can be a field access
/// or a local copy of one.
fn masked_index(index: &Expr, copies: &HashMap<Atom, String>) -> Option<(String, u8)> {
let xor = index.unwrap_parens().as_bin()?;
if xor.op != BinaryOp::BitXor {
return None;
}
let field = |expr: &Expr| copied_field(expr.unwrap_parens(), copies);
let register = |expr: &Expr| convert::byte(ast::number(expr)?);
match (field(&xor.left), field(&xor.right)) {
(Some(mask), None) => Some((mask, register(&xor.right)?)),
(None, Some(mask)) => Some((mask, register(&xor.left)?)),
_ => None,
}
}
fn construct_assignment<'a>(
run: &mut Run<'a, '_>,
assign: &'a AssignExpr,
constructed: &mut Constructed<'a>,
copies: &mut HashMap<Atom, String>,
) {
match &assign.left {
AssignTarget::Simple(SimpleAssignTarget::Member(target)) if target.obj.is_this() => {
if let Some(field) = ast::member_str(&target.prop).map(str::to_owned) {
if let Ok(value) = run.expression(&assign.right) {
fields.insert(field, value);
constructed.fields.insert(field, value);
}
} else if let MemberProp::Computed(key) = &target.prop
&& let Ok(Value::Symbol(symbol)) = run.expression(&key.expr)
{
symbols.push(symbol);
match &*assign.right {
Expr::Object(object) => {
let value = object_fields(run, object);
constructed.objects.push((symbol, value));
}
_ => constructed.programs.push(symbol),
}
}
}
// `registers.<index> = <copy of a field>`.
AssignTarget::Simple(SimpleAssignTarget::Member(target)) => {
let field = copied_field(&assign.right, copies);
match ast::member_str(&target.prop).and_then(Member::of) {
Some(Member::PcIndex) => constructed.pc = field,
Some(Member::KeyIndex) => constructed.key = field,
_ => {}
}
}
AssignTarget::Simple(SimpleAssignTarget::Ident(name)) => {
track_copy(&name.sym, &assign.right, copies);
}
_ => {}
}
}
/// Records the source field if assigning `value` makes local `name` a copy of that field.
fn track_copy(name: &Atom, value: &Expr, copies: &mut HashMap<Atom, String>) {
match copied_field(value, copies) {
Some(field) => copies.insert(name.clone(), field),
None => copies.remove(name),
};
}
/// Resolves the field read by `expr`, either directly as `this.field` or through a local copy.
fn copied_field(expr: &Expr, copies: &HashMap<Atom, String>) -> Option<String> {
match expr {
Expr::Member(member) if member.obj.is_this() => {
ast::member_str(&member.prop).map(str::to_owned)
}
Expr::Ident(name) => copies.get(&name.sym).cloned(),
_ => None,
}
(fields, symbols)
}
/// Keeps the fields whose values depend only on the script.
@@ -167,9 +349,18 @@ fn concrete<'a>(mut fields: HashMap<String, Value<'a>>) -> HashMap<String, Value
/// `this.<mask> ^ <register>` with a random mask per run. Uses zero for the mask during
/// analysis.
fn state<'a>(
names: &StateFields,
fields: &HashMap<String, Value<'a>>,
) -> Result<(HashMap<String, Value<'a>>, Layout)> {
names: &RunMethod<'_>,
constructed: &Constructed<'a>,
) -> Result<(HashMap<String, Value<'a>>, Layout, Vec<(u8, Value<'a>)>)> {
let fields = &constructed.fields;
let pc = constructed
.pc
.as_deref()
.context("the VM constructor sets no program counter register")?;
let key = constructed
.key
.as_deref()
.context("the VM constructor sets no dispatch key register")?;
let mut state = HashMap::default();
let mut masks = BTreeSet::new();
let mut register = |name: &str| -> Result<u8> {
@@ -183,8 +374,8 @@ fn state<'a>(
Ok(register)
};
let layout = Layout {
pc: register(&names.pc)?,
key: register(&names.key)?,
pc: register(pc)?,
key: register(key)?,
program: register(&names.program)?,
cells: register(&names.cells)?,
};
@@ -194,15 +385,24 @@ fn state<'a>(
masks.len()
);
state.insert(names.registers.clone(), Value::Registers);
state.extend(masks.pop_first().map(|mask| (mask, Value::Number(0.0))));
// The decoded-string cache is the one field the constructor starts as an empty array.
let mut caches = fields.iter().filter(
|(_, value)| matches!(value, Value::Array(elements) if elements.borrow().is_empty()),
);
if let (Some((cache, _)), None) = (caches.next(), caches.next()) {
state.insert(cache.clone(), Value::Cache);
}
Ok((state, layout))
let mask = masks.pop_first();
// Collect constructor-created stacks, excluding the state registers used to start handlers.
// Keep external objects, such as the global object, dependent on their registers so listing
// readers can recognize how the program accesses them.
let state_registers = [layout.pc, layout.key, layout.program, layout.cells];
let initial = constructed
.registers
.iter()
.filter(|write| {
write.file == names.registers
&& Some(&write.mask) == mask.as_ref()
&& !state_registers.contains(&write.register)
&& matches!(write.value, Value::Array(_))
})
.map(|write| (write.register, write.value.clone()))
.collect();
state.extend(mask.map(|mask| (mask, Value::Number(0.0))));
Ok((state, layout, initial))
}
/// Extracts the register and optional mask field from `this.<mask> ^ <register>` or a bare
+8 -4
View File
@@ -9,6 +9,7 @@ use swc_core::ecma::ast::{ArrowExpr, Function as ScriptFunction};
use super::interpret::Builtin;
use super::output::{Constant, Term};
use super::registers::Slots;
use super::{HashMap, convert};
/// A value produced by a handler. Uses a word-sized discriminant so the whole value occupies
@@ -25,6 +26,8 @@ pub(crate) enum Value<'ast> {
Object(Rc<RefCell<Vec<(String, Value<'ast>)>>>),
/// A `Set` or `WeakSet`.
Set(Rc<RefCell<Vec<Value<'ast>>>>),
/// A `Map` or `WeakMap`, with its entries in insertion order.
Map(Rc<RefCell<Vec<(Value<'ast>, Value<'ast>)>>>),
Function(Rc<Callable<'ast>>),
/// A `Symbol()`, which only equals itself.
Symbol(Rc<()>),
@@ -35,14 +38,14 @@ pub(crate) enum Value<'ast> {
Symbolic(Rc<Term>),
/// The interpreter instance, `this` inside a handler.
Machine,
/// The register file (see [`super::registers`]).
Registers,
/// One of the register file's parallel arrays.
RegisterSlots(Slots),
Program,
/// The closure cells of the running function.
Cells,
Cell(u32),
/// Decoded-string cache filled only during handler runs (see
/// [`super::session::Session::decoded`]). Other runs always miss.
Cache,
}
/// Variables of a call or of setup. Functions capture scopes by reference, so later assignments
@@ -248,10 +251,11 @@ impl<'ast> Value<'ast> {
callable => closure(callable).unwrap_or_else(|| Term::Opaque("function".into())),
},
Self::Set(_) => Term::Opaque("set".into()),
Self::Map(_) => Term::Opaque("map".into()),
Self::Symbol(_) => Term::Opaque("symbol".into()),
Self::Namespace(path) if path.is_empty() => Term::Global("globalThis".into()),
Self::Namespace(path) => Term::Global(path.to_string()),
Self::Machine | Self::Registers | Self::Program | Self::Cache => {
Self::Machine | Self::Registers | Self::RegisterSlots(_) | Self::Program => {
Term::Opaque("machine internals".into())
}
}
-416
View File
@@ -1,416 +0,0 @@
//! Whole-pipeline checks for `cfsolve::deobfuscate`.
//!
//! The differential cases run small scripts before and after deobfuscation in
//! V8, with `log` as the only observable, to catch rewrites that change
//! effects, their order, or thrown errors.
use std::sync::Once;
/// Scripts whose `log` calls must not change. Each one exercises a shape the
/// rewrites must recognize, or one they must leave alone.
const CASES: [(&str, &str); 26] = [
(
"helper call order",
r#"
function a() { log('a'); return 1; }
function b() { log('b'); return 2; }
(function (h) {
h = { add: function (x, y) { return x + y; }, sub: function (x, y) { return y - x; },
same: function (x, y) { return x - x; }, call: function (f, x) { return f(x); } };
log(h.add(a(), b()), h.sub(a(), b()), h.sub(a(), 5), h.same(a(), b()));
var o = { v: 3, m: function (x) { return typeof this + x; } };
log(h.call(o.m, 1), h.call(eval, '1 + 1'));
})();
"#,
),
(
"getters",
r#"
var g = { get p() { log('get p'); return 5; } };
log(g.p, g['p']);
(function (m) {
m = { A: 10, B: 20 };
log(m.A + m.B);
})();
"#,
),
(
"shadowing",
r#"
(function (G, K, p) {
G = Math;
K = { m: function (a, b) { return G.min(a, b); } };
p = function (G) { return K.m(G, 1); };
log(p(5), p(-5));
})();
"#,
),
(
"hoisting",
r#"
log(typeof later);
if (false) { var later = 1; }
(function (a) { g(); function g() { log(a); } a = 1; })('arg');
(function (a, b) { log(typeof inner); b = 2; return; function inner() {} })();
"#,
),
(
"directives",
r#"
function strict() { 'use strict'; return this === undefined; }
function sloppy() { ('use strict', log('effect')); return this === undefined; }
log(strict(), sloppy());
"#,
),
(
"labelled continue",
r#"
var n = 0, i, j;
outer: for (log('init'), i = 0; i < 3; i++) { for (j = 0; ; j++) { n++; continue outer; } }
log(n, i, j);
inner: for (i = 0; i < 2; log('update'), i++) continue inner;
"#,
),
(
"unused arguments",
r#"
function f(a, b, c) { c = a + 1; return c; }
log(f(1), f(1, 2, 3));
(function (a, b, c) { log(a, b, c); b = 2; c = 3; log(b, c); })(1);
"#,
),
(
"obfuscator patterns",
r#"
(function (order, cursor, w, h, m) {
m = { a: 2, b: 1 };
w = function (E, P, S) { switch (E) { case 0: return P + S; case 1: return P - S; default: return P * S; } };
h = {}; h.op = function (x, y) { return x ^ y; }; h.k = 'key';
for (order = '1|0|2'.split('|'), cursor = 0; true;) {
switch (order[cursor++]) {
case '0': log('zero', w(m.a, 3, 4)); continue;
case '1': log('one', w(1, m.b, 5)); continue;
case '2': log('two', h.op(6, 3), h.k); continue;
}
break;
}
})();
"#,
),
(
"string table",
r#"
(function () {
(function (factory, target, alias, values, checksum) {
for (alias = decoder, values = factory(); true;) try {
if (checksum = parseInt(alias(21)) + parseInt(alias(22)), target === checksum) break;
else values.push(values.shift());
} catch (error) { values.push(values.shift()); }
})(provider, 18);
function decoder(index, unused, values, result) {
return index = index - 21, values = provider(), result = values[index], result;
}
function provider(values) {
return values = 'noise;7abc;11def;message'.split(';'),
provider = function () { return values; }, provider();
}
function wrap(i, o) { return decoder(i + o); }
log(decoder(23), wrap(20, 3), decoder(24));
})();
"#,
),
(
"computed keys",
r#"
(function (m, out, key) {
m = { A: 10, B: 20 };
key = 'A';
out = [m.A, m['B'], m[key]];
log(out.join());
})();
"#,
),
(
"alias mutation",
r#"
(function (h, alias) {
h = { name: 'first', f: function (a) { return a + 1; } };
alias = h;
alias.name = 'changed';
log(h.name, alias.f(1));
})();
(function (h) {
h = { name: 'first' };
if (Math.random() < 2) h.name = 'second';
log(h.name);
})();
(function (t) {
t = ['x', 'y'];
function at(i) { return t[i]; }
t[0] = 'z';
log(at(0));
})();
(function (c, d) {
c = 1; d = c; c = 2;
log(d, c);
})();
"#,
),
(
"arguments object",
r#"
function mapped(a, b) { b = 2; return arguments[1]; }
log(mapped(1, 5), mapped(1));
"#,
),
(
"helper context",
r#"
var o = { v: 1, h: null };
o.h = (function (h) {
h = { self: function () { return this; }, args: function (a) { return arguments.length; } };
return function () { return [h.self() === h, h.args(1, 2)]; };
})();
log(o.h().join());
"#,
),
(
"conditional helper properties",
r#"
(function (c, x) {
c = {};
c.a = function () { return 1; };
if (x) c.b = 2;
log(c.a(), typeof c.b);
})(0);
(function (c, x) {
c = {};
c.a = function () { return 1; };
if (x === undefined) c.b = 2;
log(c.a());
})();
"#,
),
(
"scratch parameters across try, switch, labels and loops",
r#"
function thrower() { throw 0; }
function caught(a) { try { thrower(); a = 1; } catch (e) { return a; } }
function finished(a) { try { thrower(); a = 1; } finally { return a; } }
function fallthrough(k, a) { switch (k) { case 0: a = 1; case 1: return a; } }
function labelled(c, a) { block: { if (c) break block; a = 1; } return a; }
function updated(a) { for (var i = 0; i < 1; a = 1) { return a; } }
function repeated(c, a) { do { if (c) return a; c = 1; } while ((a = 1, c)); }
log(caught('arg'), finished('arg'), fallthrough(1, 'arg'), labelled(true, 'arg'));
log(updated('arg'), repeated(true, 'arg'), repeated(false, 'arg'));
"#,
),
(
"scratch parameters in strict functions",
r#"
function strict(a) { 'use strict'; a = String(this); return a; }
log(strict(), strict(5));
"#,
),
(
"hoisted readers of later definitions",
r#"
(function (h, out) {
h = {};
out = g();
h.k = 1;
log(out, g());
function g() { return h.k; }
})();
(function (m) {
log(g());
m = { A: 1 };
log(g());
function g() { try { return m.A; } catch (e) { return e.name; } }
})();
(function (h) {
log(f());
h = { k: 1 };
log(f());
function f() { return g(); }
function g() { try { return h.k; } catch (e) { return e.name; } }
})();
(function (a, b) {
log(g());
a = 1;
b = a;
log(g());
function g() { return [a, b].join(); }
})();
"#,
),
(
"unresolved globals",
r#"
(function (h) {
h = { second: function (x, y) { return y; }, sub: function (x, y) { return y - x; } };
try { log(h.second(missingGlobal, 1)); } catch (e) { log(e.name); }
try { log(h.sub(missingA, missingB)); } catch (e) { log(e.message); }
})();
(function (w) {
w = function (E, P, S) { switch (E) { case 0: return P; default: return S; } };
try { log(w(0, 1, missingGlobal)); } catch (e) { log(e.name); }
})();
try { log((missingGlobal, 1)); } catch (e) { log(e.name); }
(function (f) {
try { f = [1, missingGlobal]; log(f[0]); } catch (e) { log(e.name); }
})();
"#,
),
(
"shadowed globals",
r#"
(function (Reflect) {
log(b(1, String, [5]));
function b(n, m, r) { switch (n) { case 1: return Reflect.apply(m, undefined, r); } }
})({ apply: function () { return 'shadowed'; } });
(function (undefined) {
function t() { 'use strict'; return typeof this; }
function b(n, m, r) { switch (n) { case 1: return Reflect.apply(m, undefined, r); } }
log(b(1, t, []));
})({});
"#,
),
(
"jumps inside flattened cases",
r#"
(function (order, cursor, x) {
for (order = '0|1|2'.split('|'), cursor = 0; true;) {
switch (order[cursor++]) {
case '0': log('zero'); continue;
case '1': if (x) { log('skip'); continue; } log('one'); continue;
case '2': log('two'); continue;
}
break;
}
})(1);
"#,
),
(
"breaks inside flattened cases",
r#"
(function (order, cursor) {
for (order = '0|1'.split('|'), cursor = 0; true;) {
switch (order[cursor++]) {
case '0': for (;;) { break; } if (order) break; log('zero'); continue;
case '1': log('one'); continue;
}
break;
}
log('after');
})();
"#,
),
(
"dispatcher bindings read by cases or later",
r#"
(function (order, cursor) {
for (order = '1|0'.split('|'), cursor = 0; true;) {
switch (order[cursor++]) {
case '0': log('zero', cursor); continue;
case '1': log('one'); continue;
}
break;
}
log(order.join('-'));
})();
"#,
),
(
"argument arrays whose elements are written",
r#"
(function (a, b, f) { f = [a, b]; [a] = [9]; log(f[0], f[1]); })(1, 2);
(function (a, f) { f = [a]; for (a of [7]); log(f[0]); })(1);
(function (a, f) { f = [a]; var a = 5; log(f[0]); })(1);
(function (a, f) { f = [a]; arguments[0] = 3; log(f[0]); })(1);
"#,
),
(
"argument arrays that escape or change",
r#"
(function (a, f) { f = [a]; log(f[0], JSON.stringify({ f })); })(1);
(function (a, b, f) { f = [a, b]; delete f[0]; log(f[0], f[1]); })(1, 2);
(function (a, f) { f = [a]; log(typeof f[0]()); })(function () { 'use strict'; return this; });
(function (a, f) { f = [a]; [f[0]] = [4]; log(f[0]); })(1);
"#,
),
(
"properties written by patterns and loop heads",
r#"
(function (h) { h = { x: 1 }; for (h.x of [2]); log(h.x); })();
(function (h) { h = { x: 1 }; for (h.x in { k: 0 }); log(h.x); })();
(function (h) { h = { x: 1 }; [h.x] = [3]; log(h.x); })();
(function (h) { h = { f: function () { return 1; } }; ({ g: h.f } = { g: function () { return 2; } }); log(h.f()); })();
"#,
),
(
"property keys",
r#"
(function (h) { h = { __proto__: 5, y: 1 }; log(typeof h.__proto__, h.y); })();
(function (h) { h = { '\uD800': 1, k: 2 }; log(h['\uFFFD'], h['\uD800'], h.k); })();
(function (h) {
h = { 'a-b': function (x) { return x * 2; }, 'c-d': 'v' };
log(h['a-b'](3), h[`a-b`](4), h['c-d']);
})();
(function (m) { m = { 'a-b': 5, B: 6 }; log(m['a-b'], m[`B`]); })();
"#,
),
];
/// Runs `source` as a classic script and returns what it logged, followed by
/// the exception it ended with, if any.
fn observe(source: &str) -> Vec<String> {
static INITIALIZED: Once = Once::new();
INITIALIZED.call_once(|| {
v8::V8::initialize_platform(v8::new_default_platform(0, false).make_shared());
v8::V8::initialize();
});
let isolate = &mut v8::Isolate::new(Default::default());
v8::scope!(let scope, isolate);
let context = v8::Context::new(scope, Default::default());
let scope = &mut v8::ContextScope::new(scope, context);
let run = |scope: &mut v8::PinScope, source: &str| -> Result<String, String> {
v8::tc_scope!(let tc, scope);
let code = v8::String::new(tc, source).unwrap();
let result = v8::Script::compile(tc, code, None).and_then(|script| script.run(tc));
match result {
Some(value) => Ok(value.to_rust_string_lossy(tc)),
None => Err(tc.exception().map_or_else(
|| "terminated".to_owned(),
|exception| exception.to_rust_string_lossy(tc),
)),
}
};
run(
scope,
"var __log = []; function log() { __log.push(Array.prototype.map.call(arguments, String).join(' ')); }",
)
.unwrap();
let outcome = run(scope, source);
let logged = run(scope, "JSON.stringify(__log)").unwrap();
let mut observed: Vec<String> = serde_json::from_str(&logged).unwrap();
if let Err(exception) = outcome {
observed.push(format!("threw {exception}"));
}
observed
}
#[test]
fn preserves_observable_behavior() {
let mut failures = vec![];
for (name, source) in CASES {
let output = cfsolve::deobfuscate(source.to_owned()).unwrap().text;
let (before, after) = (observe(source), observe(&output));
if before != after {
failures.push(format!(
"{name}:\n before {before:?}\n after {after:?}\n{output}"
));
}
}
assert!(failures.is_empty(), "{}", failures.join("\n\n"));
}
-5
View File
@@ -1,5 +0,0 @@
//! The integration tests, as one binary. Run one file's tests with
//! `cargo test --test integration <module>::`, e.g. `vm::`.
mod deobfuscate;
mod vm;
-348
View File
@@ -1,348 +0,0 @@
//! Regression checks for `cfsolve::vm`, on a small hand-written VM in the
//! shape of a session's that covers cases a real program does not isolate.
use cfsolve::vm::{Cause, Constant, Definition, Effect, Exit, Machine, Path, Position, Term};
use swc_core::common::{FileName, SourceMap};
use swc_core::ecma::parser::{Parser, StringInput, Syntax};
fn definition(source: &str) -> Definition {
let source_map = SourceMap::default();
let file = source_map.new_source_file(FileName::Anon.into(), source.to_owned());
let script = Parser::new(Syntax::default(), StringInput::from(&*file), None)
.parse_script()
.expect("the script parses");
Definition::from_script(&script).expect("the script defines a VM")
}
/// A VM in the shape of the session's: a class whose `run` decodes one
/// opcode per step (here the byte itself, with the key reset to 0) and calls
/// its handler, and setup code that builds a table the handlers share.
const TOY: &str = r#"
(function () {
var g = {}, table = [0, 0], secret = "outer";
// Setup the interpreter cannot follow: `broken` is never bound.
var broken = table.map(Number);
// A closure over state of its own, which every run starts from afresh.
var counter = (function () {
var n = 0;
return function () { return ++n; };
})();
class VM {
constructor(p) {
this.h = Array(256);
this.m = 1 + Math.random() * 254 | 0;
this.j = this.m ^ 1;
this.i = this.m ^ 2;
this.l = this.m ^ 3;
this.o = this.m ^ 4;
this.k = makeCounter();
}
["run"](pc, key, cells) {
var h, j, i, op, p;
h = this.h;
j = this.j;
i = this.i;
h[j] = pc;
h[i] = key;
h[this.o] = cells;
p = h[this.l];
while (true) {
op = h[j];
h[j] = op + 1;
op = h[i] ^ p[op];
h[i] = 0;
switch (op) {
case 1: mutate.call(this); break;
case 2: load.call(this, 100); break;
case 3: fault.call(this); break;
case 4: spin.call(this); break;
case 5: compare.call(this); break;
case 6: readBroken.call(this); break;
case 7: shortCircuit.call(this); break;
case 8: arrows.call(this); break;
case 9: labels.call(this); break;
case 10: compound.call(this); break;
case 11: liveRead.call(this); break;
case 12: closureWrite.call(this); break;
case 13: nested.call(this); break;
case 14: shadow.call(this); break;
case 15: count.call(this); break;
case 16: countString.call(this); break;
case 17: identity.call(this); break;
case 18: stringIndex.call(this); break;
}
}
}
}
// One branch writes the shared table; both read it.
function mutate() {
var h = this.h;
if (h[9]) {
table[0] = 7;
}
h[10] = table[0];
}
// `r[operand] = constant + operand`, two bytes long.
function load(base) {
var h = this.h, p = h[this.l], pc = h[this.j];
h[p[pc]] = base + p[pc];
h[this.j] = pc + 1;
}
function fault() {
throw "not an instruction";
}
function spin() {
var h = this.h;
while (h[9]) {}
}
// A candidate string writes the shared table on its way through.
function compare() {
var h = this.h;
if (h[9] === "a") {
table[1] = 1;
}
h[11] = table[1];
}
function readBroken() {
this.h[12] = broken[0];
}
// The write happens only when r9 is truthy.
function shortCircuit() {
var h = this.h;
h[9] && (h[13] = 1);
}
function arrows() {
var add = (a, b) => a + b;
this.h[14] = add(2, 3);
}
function labels() {
var n = 0, i, j;
outer: for (i = 0; i < 3; i++) {
for (j = 0; j < 3; j++) {
if (j == 1) continue outer;
n++;
}
}
this.h[15] = n;
}
// The old value is read before the right side assigns.
function compound() {
var x = 1;
x += (x = 5);
this.h[16] = x;
}
function makeCounter() {
var n = 0;
return function () { return ++n; };
}
// A closure reads its variables when it runs, not when it is made.
function liveRead() {
var x = 1;
var f = function () { return x; };
x = 2;
this.h[17] = f();
var fact = function (n) { return n <= 1 ? 1 : n * fact(n - 1); };
this.h[28] = fact(5);
}
function closureWrite() {
var x = 1;
var set = function (v) { x = v; };
set(5);
this.h[18] = x;
}
function nested() {
var a = 1;
var outer = function (b) {
return function (c) { return a + b + c; };
};
var inner = outer(10);
a = 100;
this.h[19] = inner(1000);
}
// `peek` sees the scope it is declared in, not its caller's.
function peek() {
return secret;
}
function shadow() {
var secret = "inner";
this.h[20] = peek();
}
// One branch calls the setup's and the constructor's closures once more.
function count() {
var h = this.h, k = this.k;
if (h[9]) {
counter();
k();
}
h[21] = counter();
h[22] = k();
}
function countString() {
var h = this.h;
if (h[9] === "a") {
counter();
}
h[23] = counter();
}
function identity() {
var a = {}, b = {};
this.h[24] = a == a;
this.h[25] = a == b;
}
function stringIndex() {
var a = [7, 8];
this.h[26] = a["1"];
a["0"] = 9;
this.h[27] = a[0];
}
g.runProgram = function (p) {
return new VM(p).run(0, 0, []);
};
})();
"#;
fn sets(path: &Path, register: u8) -> Option<Term> {
path.effects.iter().find_map(|effect| match effect {
Effect::Set(target, value) if *target == register => Some(value.clone()),
_ => None,
})
}
fn number(value: f64) -> Term {
Term::Const(Constant::Number(value))
}
/// The one path through the toy instruction `program` starts with, with r9
/// holding `text` if given.
fn only_path(machine: &Machine<'_>, program: &[u8], text: Option<&str>) -> Path {
let instruction = match text {
Some(text) => machine.instruction_with_string(program, 0, 0, 9, text),
None => machine.instruction(program, 0, 0),
};
let mut paths = instruction.unwrap().paths;
assert_eq!(paths.len(), 1, "{paths:?}");
paths.remove(0)
}
#[test]
fn toy_vm_decodes_instructions_and_failures() {
let definition = definition(TOY);
let machine = Machine::try_new(&definition).unwrap();
assert_eq!(machine.entry(), Position::new(0, 0));
let path = only_path(&machine, &[2, 5], None);
assert_eq!(sets(&path, 5), Some(number(105.0)));
assert_eq!(path.exit, Exit::Next { pc: 2, key: 0 });
// A handler that always throws, and an opcode without one.
let failure = machine.instruction(&[3], 0, 0).unwrap_err();
assert_eq!(
failure.cause,
Cause::Faults {
opcode: 3,
reasons: vec!["\"not an instruction\"".into()]
}
);
let failure = machine.instruction(&[200], 0, 0).unwrap_err();
assert_eq!(failure.cause, Cause::NoHandler { opcode: 200 });
let instruction = machine.instruction(&[4], 0, 0).unwrap();
assert!(
instruction
.paths
.iter()
.any(|path| matches!(&path.exit, Exit::Unfollowed { pc: 1, key: 0, .. })),
"a loop over registers is not followed: {instruction:?}"
);
let Exit::Unfollowed { reason, .. } = only_path(&machine, &[6], None).exit else {
panic!("setup that could not be followed is followed");
};
assert!(
reason.contains("broken") && reason.contains("map"),
"{reason}"
);
let listing = machine.disassemble(&[2, 5, 2, 6, 3]).unwrap();
let pcs: Vec<u32> = listing.instructions.keys().copied().collect();
assert_eq!(pcs, [0, 2]);
assert_eq!(listing.failures.len(), 1);
assert_eq!((listing.failures[0].pc, listing.failures[0].key), (4, 0));
}
#[test]
fn toy_vm_runs_do_not_share_writes() {
let definition = definition(TOY);
let machine = Machine::try_new(&definition).unwrap();
for _ in 0..2 {
let instruction = machine.instruction(&[1], 0, 0).unwrap();
let values: Vec<_> = instruction
.paths
.iter()
.map(|path| (path.conditions[0].1, sets(path, 10)))
.collect();
assert_eq!(
values,
[(true, Some(number(7.0))), (false, Some(number(0.0)))],
"each path starts from the session's own table"
);
let instruction = machine.instruction(&[15], 0, 0).unwrap();
let values: Vec<_> = instruction
.paths
.iter()
.map(|path| (path.conditions[0].1, sets(path, 21), sets(path, 22)))
.collect();
assert_eq!(
values,
[
(true, Some(number(2.0)), Some(number(2.0))),
(false, Some(number(1.0)), Some(number(1.0))),
],
"each path starts from the session's own closures"
);
}
let read = |opcode: u8, text: &str, register: u8| {
sets(&only_path(&machine, &[opcode], Some(text)), register)
};
assert_eq!(read(5, "a", 11), Some(number(1.0)));
assert_eq!(read(5, "b", 11), Some(number(0.0)));
assert_eq!(read(16, "a", 23), Some(number(2.0)));
assert_eq!(read(16, "b", 23), Some(number(1.0)));
assert_eq!(read(16, "a", 23), Some(number(2.0)));
}
#[test]
fn toy_vm_follows_javascript_semantics() {
let definition = definition(TOY);
let machine = Machine::try_new(&definition).unwrap();
let one = |opcode: u8, register: u8| sets(&only_path(&machine, &[opcode], None), register);
assert_eq!(one(8, 14), Some(number(5.0)));
assert_eq!(one(9, 15), Some(number(3.0)));
assert_eq!(one(10, 16), Some(number(6.0)));
// Closures are lexical: a read after the variable is reassigned, a
// closure calling itself, a write inside the closure seen by the function
// it was made in, two scopes up, and not the caller's variable.
assert_eq!(one(11, 17), Some(number(2.0)));
assert_eq!(one(11, 28), Some(number(120.0)));
assert_eq!(one(12, 18), Some(number(5.0)));
assert_eq!(one(13, 19), Some(number(1110.0)));
let outer = Term::Const(Constant::String("outer".into()));
assert_eq!(one(14, 20), Some(outer));
// Objects compare by identity, and a string key indexes an array.
assert_eq!(one(17, 24), Some(Term::Const(Constant::Bool(true))));
assert_eq!(one(17, 25), Some(Term::Const(Constant::Bool(false))));
assert_eq!(one(18, 26), Some(number(8.0)));
assert_eq!(one(18, 27), Some(number(9.0)));
let instruction = machine.instruction(&[7], 0, 0).unwrap();
let writes: Vec<_> = instruction
.paths
.iter()
.map(|path| (path.conditions.clone(), sets(path, 13)))
.collect();
assert_eq!(
writes,
[
(vec![(Term::Reg(9), true)], Some(number(1.0))),
(vec![(Term::Reg(9), false)], None),
]
);
}