cfsolve 0.1.4 → 0.1.5

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (74) hide show
  1. checksums.yaml +4 -4
  2. data/CHANGELOG.md +25 -0
  3. data/README.md +26 -6
  4. data/UPSTREAM.md +23 -8
  5. data/lib/cfsolve/profiles/safari-26-ios/answers.json +805 -797
  6. data/lib/cfsolve/profiles/safari-26-ios/challenge-page-answers.json +909 -899
  7. data/lib/cfsolve/version.rb +2 -2
  8. data/lib/cfsolve.rb +22 -11
  9. data/vendor/cfsolve/README.md +5 -53
  10. data/vendor/cfsolve/examples/listing_dump.rs +24 -0
  11. data/vendor/cfsolve/examples/probe_similarity.rs +37 -0
  12. data/vendor/cfsolve/examples/rebase_reference.rs +96 -0
  13. data/vendor/cfsolve/examples/reread_capture.rs +31 -0
  14. data/vendor/cfsolve/examples/turnstile_smoke.rs +24 -3
  15. data/vendor/cfsolve/profiles/safari-26-ios/answers.json +805 -797
  16. data/vendor/cfsolve/profiles/safari-26-ios/challenge-page-answers.json +909 -899
  17. data/vendor/cfsolve/src/capture/sessions.rs +88 -4
  18. data/vendor/cfsolve/src/capture.rs +1 -0
  19. data/vendor/cfsolve/src/deobfuscate/ast.rs +16 -0
  20. data/vendor/cfsolve/src/deobfuscate/control_flow.rs +1 -1
  21. data/vendor/cfsolve/src/deobfuscate/dead_branches.rs +33 -0
  22. data/vendor/cfsolve/src/deobfuscate/merged_functions.rs +24 -4
  23. data/vendor/cfsolve/src/embedding_page/extra_params.rs +10 -113
  24. data/vendor/cfsolve/src/embedding_page/page.rs +70 -99
  25. data/vendor/cfsolve/src/session/initial.rs +6 -7
  26. data/vendor/cfsolve/src/session/probes.rs +0 -1
  27. data/vendor/cfsolve/src/stage2/analysis/analyze.rs +4 -33
  28. data/vendor/cfsolve/src/stage2/analysis/discovery.rs +9 -17
  29. data/vendor/cfsolve/src/stage2/benchmark.rs +42 -62
  30. data/vendor/cfsolve/src/stage2/call_stack.rs +133 -227
  31. data/vendor/cfsolve/src/stage2/challenge_page.rs +10 -3
  32. data/vendor/cfsolve/src/stage2/probes/dates.rs +0 -44
  33. data/vendor/cfsolve/src/stage2/probes/parent_info.rs +345 -61
  34. data/vendor/cfsolve/src/stage2/probes/performance.rs +42 -5
  35. data/vendor/cfsolve/src/stage2/probes/stack.rs +45 -117
  36. data/vendor/cfsolve/src/stage2/probes/websocket_echo.rs +7 -76
  37. data/vendor/cfsolve/src/stage2/probes.rs +0 -1
  38. data/vendor/cfsolve/src/stage2/reference.json +1 -1
  39. data/vendor/cfsolve/src/stage2/reference.rs +70 -115
  40. data/vendor/cfsolve/src/stage2/registry.rs +6 -11
  41. data/vendor/cfsolve/src/stage2/replay.rs +3 -34
  42. data/vendor/cfsolve/src/stage2/stylesheets.rs +0 -35
  43. data/vendor/cfsolve/src/stage2/trace.rs +1 -1
  44. data/vendor/cfsolve/src/stage2/vocabulary.rs +6 -111
  45. data/vendor/cfsolve/src/stage2.rs +0 -1
  46. data/vendor/cfsolve/src/vm/dataflow.rs +15 -6
  47. data/vendor/cfsolve/src/vm/disassemble.rs +5 -68
  48. data/vendor/cfsolve/src/vm/encoded_strings.rs +1553 -0
  49. data/vendor/cfsolve/src/vm/extract.rs +193 -343
  50. data/vendor/cfsolve/src/vm/interpret/access.rs +2 -10
  51. data/vendor/cfsolve/src/vm/interpret/builtin.rs +0 -13
  52. data/vendor/cfsolve/src/vm/interpret/intrinsic.rs +28 -43
  53. data/vendor/cfsolve/src/vm/interpret/mix32.rs +216 -86
  54. data/vendor/cfsolve/src/vm/interpret/native_dispatch.rs +42 -21
  55. data/vendor/cfsolve/src/vm/interpret/pattern.rs +272 -100
  56. data/vendor/cfsolve/src/vm/interpret/register_helpers.rs +259 -36
  57. data/vendor/cfsolve/src/vm/interpret/run.rs +0 -4
  58. data/vendor/cfsolve/src/vm/machine.rs +14 -70
  59. data/vendor/cfsolve/src/vm/output.rs +3 -5
  60. data/vendor/cfsolve/src/vm/registers.rs +26 -46
  61. data/vendor/cfsolve/src/vm/session.rs +11 -9
  62. data/vendor/cfsolve/src/vm.rs +1 -1
  63. metadata +6 -12
  64. data/lib/cfsolve/profiles/chrome-157-macos/answers.json +0 -4777
  65. data/lib/cfsolve/profiles/chrome-157-macos.json +0 -613
  66. data/vendor/cfsolve/profiles/chrome-157-macos/answers.json +0 -4777
  67. data/vendor/cfsolve/profiles/chrome-157-macos.json +0 -613
  68. data/vendor/cfsolve/src/stage2/fixtures/encoded_benchmark_worker.js +0 -1
  69. data/vendor/cfsolve/src/stage2/probes/parent_info_array.rs +0 -326
  70. data/vendor/cfsolve/src/stage2/value_labels.rs +0 -185
  71. data/vendor/cfsolve/src/vm/encoded_names.rs +0 -635
  72. data/vendor/cfsolve/src/vm/fixtures/free_functions/README.md +0 -9
  73. data/vendor/cfsolve/src/vm/fixtures/free_functions/machine.js +0 -7438
  74. data/vendor/cfsolve/src/vm/fixtures/free_functions/program.base64 +0 -1
@@ -105,10 +105,7 @@ impl<'ast> Run<'ast, '_> {
105
105
  Key::Value(value) => value.number(),
106
106
  };
107
107
  Ok(match object {
108
- Value::Registers
109
- if let Some(member) =
110
- name.and_then(|name| self.session.register_access.member(name)) =>
111
- {
108
+ Value::Registers if let Some(member) = name.and_then(Member::of) => {
112
109
  self.register_member(member)
113
110
  }
114
111
  Value::Registers | Value::RegisterSlots(Slots::Values) => {
@@ -248,10 +245,7 @@ impl<'ast> Run<'ast, '_> {
248
245
  ) -> Evaluation<'ast, ()> {
249
246
  let layout = self.session.layout;
250
247
  match object {
251
- Value::Registers => match key
252
- .text()
253
- .and_then(|name| self.session.register_access.member(name))
254
- {
248
+ Value::Registers => match key.text().and_then(Member::of) {
255
249
  Some(Member::Pc | Member::OtherPc) => self.set_register(layout.pc, value),
256
250
  Some(Member::Key | Member::OtherKey) => self.set_register(layout.key, value),
257
251
  // These fields have fixed values in the interpreter model.
@@ -383,8 +377,6 @@ impl<'ast> Run<'ast, '_> {
383
377
  fn register_member(&self, member: Member) -> Value<'ast> {
384
378
  let layout = self.session.layout;
385
379
  match member {
386
- Member::Read => Value::function(Callable::Builtin(Builtin::RegisterRead)),
387
- Member::Write => Value::function(Callable::Builtin(Builtin::RegisterWrite)),
388
380
  Member::Mask => Value::Number(0.0),
389
381
  Member::Integer => Value::Number(1.0),
390
382
  Member::Pc => self.register_value(layout.pc),
@@ -74,9 +74,6 @@ builtins! {
74
74
  /// Typed arrays are modeled as empty objects because the script only uses them to cache values
75
75
  /// it can recompute.
76
76
  Int32Array => "Int32Array",
77
- /// The register file's `read` and `write` methods (see [`crate::vm::registers`]).
78
- RegisterRead => "registers.read",
79
- RegisterWrite => "registers.write",
80
77
  }
81
78
 
82
79
  impl<'ast> Run<'ast, '_> {
@@ -314,16 +311,6 @@ impl<'ast> Run<'ast, '_> {
314
311
  }
315
312
  Builtin::Symbol => Ok(Value::Symbol(Rc::new(()))),
316
313
  Builtin::Int32Array => Ok(Value::Object(Rc::default())),
317
- Builtin::RegisterRead => {
318
- let register = self.register(&Key::from(argument(0)))?;
319
- Ok(self.register_value(register))
320
- }
321
- Builtin::RegisterWrite => {
322
- let register = self.register(&Key::from(argument(0)))?;
323
- let value = argument(1);
324
- self.write_register(register, value.clone());
325
- Ok(value)
326
- }
327
314
  Builtin::Set => match argument(0) {
328
315
  Value::Undefined | Value::Null => Ok(Value::Set(Rc::default())),
329
316
  Value::Array(elements) => {
@@ -8,9 +8,9 @@ use oxc::ast::ast::{Function, NumericLiteral, ObjectProperty};
8
8
  use oxc::ast_visit::{Visit, walk};
9
9
  use oxc::semantic::ScopeFlags;
10
10
 
11
+ use super::access::Key;
11
12
  use super::copies::Copies;
12
13
  use super::mix32::Mix32;
13
- use super::pattern;
14
14
  use super::register_helpers::{self, Helper};
15
15
  use super::run::Run;
16
16
  use crate::js;
@@ -21,8 +21,6 @@ use crate::vm::{HashMap, extract};
21
21
  /// A native function equivalent to a script function.
22
22
  #[derive(Clone, Copy)]
23
23
  pub(crate) enum Intrinsic {
24
- RegisterRead,
25
- RegisterWrite,
26
24
  /// Bookkeeping on the interpreter's unmasked register file.
27
25
  Register(Helper),
28
26
  Mix32(Mix32),
@@ -39,14 +37,15 @@ pub(super) fn address(function: &Function<'_>) -> usize {
39
37
  ptr::from_ref(function).addr()
40
38
  }
41
39
 
42
- /// Finds register helpers and mixers, and validates BLAKE3 candidates taking five parameters
43
- /// and mentioning its initialization vector's first word, which some builds store complemented.
40
+ /// Finds register accessors, register helpers, and mixers, and validates BLAKE3 candidates
41
+ /// taking five parameters and mentioning its initialization vector's first word, which some
42
+ /// builds store complemented.
44
43
  pub(crate) fn intrinsics(session: &Session<'_>) -> Intrinsics {
45
44
  let mut intrinsics = Intrinsics::default();
46
45
  let script = session.script;
47
46
  for function in session.functions.values() {
48
47
  let intrinsic = if let Some(helper) =
49
- register_helpers::recognize(script, function, session.register_access)
48
+ register_helpers::recognize(script, session.accessors, function)
50
49
  {
51
50
  Intrinsic::Register(helper)
52
51
  } else if let Some(mixer) = Mix32::recognize(script, function) {
@@ -63,28 +62,6 @@ pub(crate) fn intrinsics(session: &Session<'_>) -> Intrinsics {
63
62
  };
64
63
  intrinsics.insert(address(function), intrinsic);
65
64
  }
66
- // Registers in the abstract machine already contain decoded values. The save helper
67
- // preserves lazy string records in the real VM, but is the same read in this model.
68
- if let crate::vm::registers::Access::Functions { read, write } = session.register_access {
69
- intrinsics.insert(address(read), Intrinsic::RegisterRead);
70
- intrinsics.insert(address(write), Intrinsic::RegisterWrite);
71
- let helpers = pattern::binary_helpers(session);
72
- let save = pattern::template(
73
- "function save(registers, index) {
74
- if (registers.J[index] === -4) { return registers.H[index]; }
75
- else { return $read(registers, index); } }",
76
- );
77
- for function in session.functions.values() {
78
- if let Some(captures) = pattern::matches(&save, script, function, &helpers)
79
- && let Some(reader) = captures
80
- .name("$read")
81
- .and_then(|name| session.function(name))
82
- && ptr::eq(reader, read)
83
- {
84
- intrinsics.insert(address(function), Intrinsic::RegisterRead);
85
- }
86
- }
87
- }
88
65
  intrinsics
89
66
  }
90
67
 
@@ -97,18 +74,7 @@ impl Intrinsic {
97
74
  run: &mut Run<'ast, '_>,
98
75
  arguments: &[Value<'ast>],
99
76
  ) -> Option<Value<'ast>> {
100
- let register = match self {
101
- Self::RegisterRead | Self::RegisterWrite => {
102
- let [Value::Registers, Value::Number(register), rest @ ..] = arguments else {
103
- return None;
104
- };
105
- let register = crate::vm::convert::byte(*register)?;
106
- if matches!(self, Self::RegisterRead) {
107
- return Some(run.register_value(register));
108
- }
109
- run.write_register(register, rest.first()?.clone());
110
- return Some(Value::Undefined);
111
- }
77
+ let (register, returns) = match self {
112
78
  Self::Mix32(mixer) => {
113
79
  let Some(Value::Number(number)) = arguments.first() else {
114
80
  return None;
@@ -125,8 +91,23 @@ impl Intrinsic {
125
91
  return matches!(arguments.first(), Some(Value::Registers))
126
92
  .then_some(Value::Undefined);
127
93
  }
128
- Self::Register(Helper::Pc) => run.session.layout.pc,
129
- Self::Register(Helper::Key) => run.session.layout.key,
94
+ Self::Register(Helper::Read) => {
95
+ let [Value::Registers, index] = arguments else {
96
+ return None;
97
+ };
98
+ let register = run.register(&Key::from(index.clone())).ok()?;
99
+ return Some(run.register_value(register));
100
+ }
101
+ Self::Register(Helper::Write) => {
102
+ let [Value::Registers, index, value] = arguments else {
103
+ return None;
104
+ };
105
+ let register = run.register(&Key::from(index.clone())).ok()?;
106
+ run.write_register(register, value.clone());
107
+ return Some(Value::Undefined);
108
+ }
109
+ Self::Register(Helper::Pc { returns }) => (run.session.layout.pc, returns),
110
+ Self::Register(Helper::Key { returns }) => (run.session.layout.key, returns),
130
111
  Self::Blake3Compress => return None,
131
112
  };
132
113
  let [Value::Registers, value @ Value::Number(number), ..] = arguments else {
@@ -138,7 +119,11 @@ impl Intrinsic {
138
119
  return None;
139
120
  }
140
121
  run.set_register(register, value.clone());
141
- Some(value.clone())
122
+ Some(if returns {
123
+ value.clone()
124
+ } else {
125
+ Value::Undefined
126
+ })
142
127
  }
143
128
  }
144
129
 
@@ -1,16 +1,18 @@
1
1
  //! The straight-line integer mixer used for instruction positions and string offsets. Match
2
2
  //! every operation and recover its constants; leave all other functions to the interpreter.
3
3
 
4
+ use std::rc::Rc;
5
+
4
6
  use oxc::ast::ast::{
5
- AssignmentExpression, AssignmentOperator, AssignmentTarget, BinaryExpression, Expression,
6
- Function, Statement,
7
+ AssignmentExpression, AssignmentOperator, AssignmentTarget, BinaryExpression, BindingPattern,
8
+ Expression, Function, Statement, VariableDeclarationKind,
7
9
  };
8
10
  use oxc::semantic::SymbolId;
9
11
  use oxc::syntax::operator::BinaryOperator;
10
12
 
11
13
  use crate::js;
12
14
  use crate::js::ast::{self, Script};
13
- use crate::vm::extract;
15
+ use crate::vm::{HashMap, HashSet, extract};
14
16
 
15
17
  #[derive(Clone, Copy)]
16
18
  pub(crate) struct Mix32 {
@@ -27,6 +29,8 @@ struct Round {
27
29
  }
28
30
 
29
31
  impl Mix32 {
32
+ /// Recognizes `function (x) { x ^= seed; x = (x ^ x >>> s1) * m1 | 0; x = (x ^ x >>>
33
+ /// s2) * m2 | 0; return x ^ x >>> s3; }` however its straight-line statements spell it.
30
34
  pub(super) fn recognize(script: Script<'_>, function: &Function<'_>) -> Option<Self> {
31
35
  if function.r#async || function.generator {
32
36
  return None;
@@ -34,39 +38,39 @@ impl Mix32 {
34
38
  let [parameter] = extract::parameters(&function.params)?[..] else {
35
39
  return None;
36
40
  };
37
- let parameter = parameter.symbol_id();
38
41
  let body = function.body.as_deref()?;
39
42
  if !body.directives.is_empty() {
40
43
  return None;
41
44
  }
42
- // Statements after the `return` never run, unless they declare something.
43
- let statements = &body.statements;
44
- let end = statements
45
+ // A declared function would replace the parameter's value when the call starts.
46
+ if body
47
+ .statements
45
48
  .iter()
46
- .position(|statement| matches!(statement, Statement::ReturnStatement(_)))?
47
- + 1;
48
- if statements[end..].iter().any(Statement::is_declaration) {
49
- return None;
50
- }
51
- let [seed, first, second, returned] = &statements[..end] else {
52
- return None;
53
- };
54
- let Statement::ReturnStatement(returned) = returned else {
55
- return None;
56
- };
57
- let seed = assignment(seed)?;
58
- if !is_target(script, &seed.left, parameter)
59
- || seed.operator != AssignmentOperator::BitwiseXOR
49
+ .any(|statement| matches!(statement, Statement::FunctionDeclaration(_)))
60
50
  {
61
51
  return None;
62
52
  }
53
+ let parameter = parameter.symbol_id();
54
+ let evaluator = Evaluator {
55
+ script,
56
+ values: HashMap::from_iter([(parameter, Rc::new(Term::Parameter))]),
57
+ locals: HashSet::from_iter([parameter]),
58
+ };
59
+ let returned = evaluator.run(&body.statements)?;
60
+ // `x ^ x >>> s3`, with `x` the second round's result.
61
+ let (second, final_shift) = shifted_xor(&returned)?;
62
+ let (first, second) = round(int32(second)?)?;
63
+ let (seeded, first) = round(int32(first)?)?;
64
+ let seed = operands(seeded, BinaryOperator::BitwiseXOR)?
65
+ .into_iter()
66
+ .find_map(|pair| match pair {
67
+ (Term::Parameter, Term::Number(seed)) => Some(*seed),
68
+ _ => None,
69
+ })?;
63
70
  Some(Self {
64
- seed: js::int32(number(&seed.right)?),
65
- rounds: [
66
- round(script, parameter, first)?,
67
- round(script, parameter, second)?,
68
- ],
69
- final_shift: mixed(script, parameter, returned.argument.as_ref()?)?,
71
+ seed: js::int32(seed),
72
+ rounds: [first, second],
73
+ final_shift,
70
74
  })
71
75
  }
72
76
 
@@ -80,6 +84,189 @@ impl Mix32 {
80
84
  }
81
85
  }
82
86
 
87
+ /// A pure value computed from the mixer's parameter.
88
+ #[derive(Clone, Debug, PartialEq)]
89
+ enum Term {
90
+ Parameter,
91
+ Number(f64),
92
+ Binary(BinaryOperator, Rc<Term>, Rc<Term>),
93
+ }
94
+
95
+ /// Evaluates a mixer's straight-line statements to the term it returns. Reads only the parameter
96
+ /// and locals it has assigned, and computes only binary operators on numbers, so substituting
97
+ /// each local's term where it is read computes the same values.
98
+ struct Evaluator<'s> {
99
+ script: Script<'s>,
100
+ values: HashMap<SymbolId, Rc<Term>>,
101
+ /// The parameter and the locals the body declares.
102
+ locals: HashSet<SymbolId>,
103
+ }
104
+
105
+ impl Evaluator<'_> {
106
+ fn run(mut self, statements: &[Statement<'_>]) -> Option<Rc<Term>> {
107
+ // `var` declarations scope their names before anything runs.
108
+ for statement in statements {
109
+ if let Statement::VariableDeclaration(declaration) = statement
110
+ && declaration.kind == VariableDeclarationKind::Var
111
+ {
112
+ for declarator in &declaration.declarations {
113
+ let BindingPattern::BindingIdentifier(name) = &declarator.id else {
114
+ return None;
115
+ };
116
+ self.locals.insert(name.symbol_id());
117
+ }
118
+ }
119
+ }
120
+ for statement in statements {
121
+ match statement {
122
+ Statement::ReturnStatement(returned) => {
123
+ return self.term(returned.argument.as_ref()?);
124
+ }
125
+ Statement::EmptyStatement(_) => {}
126
+ Statement::VariableDeclaration(declaration)
127
+ if declaration.kind == VariableDeclarationKind::Var =>
128
+ {
129
+ for declarator in &declaration.declarations {
130
+ if let (BindingPattern::BindingIdentifier(name), Some(init)) =
131
+ (&declarator.id, &declarator.init)
132
+ {
133
+ let value = self.term(init)?;
134
+ self.values.insert(name.symbol_id(), value);
135
+ }
136
+ }
137
+ }
138
+ Statement::ExpressionStatement(expression) => {
139
+ let Expression::AssignmentExpression(assignment) = &expression.expression
140
+ else {
141
+ return None;
142
+ };
143
+ let AssignmentTarget::AssignmentTargetIdentifier(name) = &assignment.left
144
+ else {
145
+ return None;
146
+ };
147
+ let symbol = self.script.symbol(name)?;
148
+ if !self.locals.contains(&symbol) {
149
+ return None;
150
+ }
151
+ let right = self.term(&assignment.right)?;
152
+ let value = match assignment.operator.to_binary_operator() {
153
+ None if assignment.operator == AssignmentOperator::Assign => right,
154
+ Some(operator) if supported(operator) => {
155
+ let old = self.values.get(&symbol)?.clone();
156
+ Rc::new(Term::Binary(operator, old, right))
157
+ }
158
+ _ => return None,
159
+ };
160
+ self.values.insert(symbol, value);
161
+ }
162
+ _ => return None,
163
+ }
164
+ }
165
+ None
166
+ }
167
+
168
+ fn term(&self, expression: &Expression<'_>) -> Option<Rc<Term>> {
169
+ if let Some(number) = number(expression) {
170
+ return Some(Rc::new(Term::Number(number)));
171
+ }
172
+ match expression.without_parentheses() {
173
+ Expression::Identifier(name) => {
174
+ let symbol = self.script.symbol(name)?;
175
+ // A local read before it is assigned holds `undefined`.
176
+ self.values.get(&symbol).cloned()
177
+ }
178
+ Expression::BinaryExpression(binary) if supported(binary.operator) => {
179
+ Some(Rc::new(Term::Binary(
180
+ binary.operator,
181
+ self.term(&binary.left)?,
182
+ self.term(&binary.right)?,
183
+ )))
184
+ }
185
+ _ => None,
186
+ }
187
+ }
188
+ }
189
+
190
+ /// Operators whose results on numbers are numbers.
191
+ fn supported(operator: BinaryOperator) -> bool {
192
+ matches!(
193
+ operator,
194
+ BinaryOperator::BitwiseXOR
195
+ | BinaryOperator::BitwiseOR
196
+ | BinaryOperator::BitwiseAnd
197
+ | BinaryOperator::ShiftLeft
198
+ | BinaryOperator::ShiftRight
199
+ | BinaryOperator::ShiftRightZeroFill
200
+ | BinaryOperator::Addition
201
+ | BinaryOperator::Subtraction
202
+ | BinaryOperator::Multiplication
203
+ )
204
+ }
205
+
206
+ /// The operands of `operator`, in either order.
207
+ fn operands(term: &Term, operator: BinaryOperator) -> Option<[(&Term, &Term); 2]> {
208
+ match term {
209
+ Term::Binary(found, left, right) if *found == operator => {
210
+ Some([(&**left, &**right), (&**right, &**left)])
211
+ }
212
+ _ => None,
213
+ }
214
+ }
215
+
216
+ /// `e` of `e <operator> 0` or `0 <operator> e`.
217
+ fn with_zero(term: &Term, operator: BinaryOperator) -> Option<&Term> {
218
+ operands(term, operator)?
219
+ .into_iter()
220
+ .find_map(|(value, zero)| matches!(zero, Term::Number(0.0)).then_some(value))
221
+ }
222
+
223
+ /// `e` of a term computing `ToInt32(e)`: `e | 0` or `0 | e`, or `(e ^ 0) + (e & 0)`, which is
224
+ /// `ToInt32(e) + 0`. Truncating again changes nothing.
225
+ fn int32(term: &Term) -> Option<&Term> {
226
+ let inner = with_zero(term, BinaryOperator::BitwiseOR).or_else(|| {
227
+ operands(term, BinaryOperator::Addition)?
228
+ .into_iter()
229
+ .find_map(|(xor, and)| {
230
+ let xor = with_zero(xor, BinaryOperator::BitwiseXOR)?;
231
+ (Some(xor) == with_zero(and, BinaryOperator::BitwiseAnd)).then_some(xor)
232
+ })
233
+ })?;
234
+ Some(int32(inner).unwrap_or(inner))
235
+ }
236
+
237
+ /// `x` and `s` of `x ^ x >>> s`.
238
+ fn shifted_xor(term: &Term) -> Option<(&Term, u32)> {
239
+ operands(term, BinaryOperator::BitwiseXOR)?
240
+ .into_iter()
241
+ .find_map(|(value, shifted)| {
242
+ let Term::Binary(BinaryOperator::ShiftRightZeroFill, shifted, shift) = shifted else {
243
+ return None;
244
+ };
245
+ let Term::Number(shift) = **shift else {
246
+ return None;
247
+ };
248
+ (**shifted == *value).then_some((value, js::int32(shift) as u32 & 31))
249
+ })
250
+ }
251
+
252
+ /// `x` and the round of `(x ^ x >>> shift) * multiplier`, where `x` is an int32: the seeded
253
+ /// parameter or a truncated round.
254
+ fn round(term: &Term) -> Option<(&Term, Round)> {
255
+ operands(term, BinaryOperator::Multiplication)?
256
+ .into_iter()
257
+ .find_map(|(mixed, multiplier)| {
258
+ let Term::Number(multiplier) = *multiplier else {
259
+ return None;
260
+ };
261
+ let (value, shift) = shifted_xor(mixed)?;
262
+ let int32 = match value {
263
+ Term::Binary(BinaryOperator::BitwiseXOR, ..) => true,
264
+ value => int32(value).is_some(),
265
+ };
266
+ int32.then_some((value, Round { shift, multiplier }))
267
+ })
268
+ }
269
+
83
270
  fn number(expression: &Expression<'_>) -> Option<f64> {
84
271
  ast::fold_number(expression, &|_| None)
85
272
  }
@@ -89,12 +276,6 @@ pub(super) fn is_symbol(script: Script<'_>, expression: &Expression<'_>, symbol:
89
276
  script.refers_to(expression.without_parentheses(), symbol)
90
277
  }
91
278
 
92
- /// Whether an assignment target is the identifier of `symbol`.
93
- fn is_target(script: Script<'_>, target: &AssignmentTarget<'_>, symbol: SymbolId) -> bool {
94
- matches!(target, AssignmentTarget::AssignmentTargetIdentifier(name)
95
- if script.symbol(name) == Some(symbol))
96
- }
97
-
98
279
  /// The assignment an expression statement makes.
99
280
  pub(super) fn assignment<'s, 'a>(
100
281
  statement: &'s Statement<'a>,
@@ -116,59 +297,6 @@ pub(super) fn binary<'s, 'a>(expression: &'s Expression<'a>) -> Option<&'s Binar
116
297
  }
117
298
  }
118
299
 
119
- /// The shift of `x ^ x >>> shift`, where `x` is the `parameter`.
120
- fn mixed(script: Script<'_>, parameter: SymbolId, expression: &Expression<'_>) -> Option<u32> {
121
- let is_parameter = |expression: &Expression<'_>| is_symbol(script, expression, parameter);
122
- let xor = binary(expression)?;
123
- if xor.operator != BinaryOperator::BitwiseXOR {
124
- return None;
125
- }
126
- let shifted = if is_parameter(&xor.left) {
127
- &xor.right
128
- } else if is_parameter(&xor.right) {
129
- &xor.left
130
- } else {
131
- return None;
132
- };
133
- let shifted = binary(shifted)?;
134
- if shifted.operator != BinaryOperator::ShiftRightZeroFill || !is_parameter(&shifted.left) {
135
- return None;
136
- }
137
- Some(js::int32(number(&shifted.right)?) as u32 & 31)
138
- }
139
-
140
- fn round(script: Script<'_>, parameter: SymbolId, statement: &Statement<'_>) -> Option<Round> {
141
- let assignment = assignment(statement)?;
142
- if assignment.operator != AssignmentOperator::Assign
143
- || !is_target(script, &assignment.left, parameter)
144
- {
145
- return None;
146
- }
147
- let truncated = binary(&assignment.right)?;
148
- if truncated.operator != BinaryOperator::BitwiseOR {
149
- return None;
150
- }
151
- let product = if number(&truncated.left) == Some(0.0) {
152
- &truncated.right
153
- } else if number(&truncated.right) == Some(0.0) {
154
- &truncated.left
155
- } else {
156
- return None;
157
- };
158
- let product = binary(product)?;
159
- if product.operator != BinaryOperator::Multiplication {
160
- return None;
161
- }
162
- let (shift, multiplier) = match number(&product.left) {
163
- Some(multiplier) => (mixed(script, parameter, &product.right)?, multiplier),
164
- None => (
165
- mixed(script, parameter, &product.left)?,
166
- number(&product.right)?,
167
- ),
168
- };
169
- Some(Round { shift, multiplier })
170
- }
171
-
172
300
  #[cfg(test)]
173
301
  mod tests {
174
302
  use super::*;
@@ -180,6 +308,8 @@ mod tests {
180
308
  "function f(x) { x ^= 1265281276; x = (x ^ x >>> 16) * 40503 | 0; x = 13849 * (x ^ x >>> 13) | 0; return x >>> 16 ^ x; }",
181
309
  "function f(renamed) { renamed ^= -123; renamed = 0 | 7 * (renamed >>> 3 ^ renamed); renamed = ((renamed ^ renamed >>> 0) * 11) | 0; return renamed ^ renamed >>> 31; }",
182
310
  "function f(x) { x ^= 1265281276; x = (x >>> 16 ^ x) * 40503 | 0; x = 0 | 13849 * (x ^ x >>> 13); return x ^ x >>> 16; return; }",
311
+ "function f(x) { var t; x ^= 2067932536; x = 40503 * (x >>> 16 ^ x) | 0; t = (x ^ x >>> 13) * 13849; x = 0 | (t ^ 0) + (t & 0); return x >>> 16 ^ x; }",
312
+ "function f(x) { var t = x ^ -5, u; u = 0 | (t ^ t >>> 7) * 3; x = (u ^ u >>> 9) * 5 | 0 | 0; return x ^ x >>> 2; }",
183
313
  ] {
184
314
  assert_native_matches_interpreted(source, |script, function| {
185
315
  Mix32::recognize(script, function).is_some()
@@ -25,24 +25,29 @@ use crate::vm::value::Value;
25
25
  /// them. `PARAMETERS` stands for the loop's parameter names (see [`template_parameters`]).
26
26
  /// `ACCUMULATE` stands for `key += position;` in builds that add the opcode to the key before
27
27
  /// computing the next key, and for nothing in builds that compute it from the key directly.
28
+ /// `DECLARE` stands for `var position, key;` and `READ` for `key =` in builds that assign the
29
+ /// key to a loop local, and for `var position;` and `let key =` in builds that declare it in the
30
+ /// block. Register members are named as [`crate::vm::registers::Member`] names them.
28
31
  const DECODER: &str = "
29
32
  function decoder(PARAMETERS) {
30
- var position, key;
31
- position = 1 === registers.i ? registers.h ^ registers.state : registers.v;
33
+ DECLARE
34
+ position = 1 === registers.j ? registers.h ^ registers.i : registers.A;
32
35
  if (position !== position) return true;
33
36
  if (position < 0 || position >= program.length) throw Error();
34
37
  $setpc(registers, position + 1);
35
- key = 1 === registers.l ? registers.j ^ registers.state : registers.u;
38
+ READ 1 === registers.m ? registers.h ^ registers.l : registers.v;
36
39
  position = $unmask(key ^ program[position] - $c_offset & 255, key, position);
37
40
  ACCUMULATE
38
41
  $setkey(registers, $e_next);
39
42
  return position;
40
43
  }";
41
44
 
42
- /// `unmask(value, key, position)`: undoes the position hash and key rotation.
45
+ /// `unmask(value, key, position)`: undoes the position hash and key rotation. `ROTATE` stands
46
+ /// for `return (value >>> key | value << 8 - key) & 255;`, or for storing the rotation in
47
+ /// `rotated` before masking it in builds that do so.
43
48
  const UNMASK: &str = "
44
49
  function unmask(value, key, position) {
45
- var cached;
50
+ var cached, rotated;
46
51
  cached = $cache[position];
47
52
  if (!cached) {
48
53
  cached = ($mix(position) & 255) + 1;
@@ -50,7 +55,7 @@ function unmask(value, key, position) {
50
55
  }
51
56
  value ^= 255 & (cached - 1 ^ $c_factor * key);
52
57
  key &= 7;
53
- return (value >>> key | value << 8 - key) & 255;
58
+ ROTATE
54
59
  }";
55
60
 
56
61
  /// A recognized opcode decoder and its constants.
@@ -97,17 +102,26 @@ impl<'ast> NativeDispatch<'ast> {
97
102
  let script = session.script;
98
103
  let helpers = pattern::binary_helpers(session);
99
104
  let matched = |accumulate: &str| {
100
- let source = DECODER
101
- .replace("PARAMETERS", &parameters)
102
- .replace("ACCUMULATE", accumulate);
103
- let template = pattern::template(&source);
104
- pattern::matches_routine(
105
- &template,
106
- script,
107
- decoder.function,
108
- decoder.routine(),
109
- &helpers,
110
- )
105
+ [
106
+ ("var position, key;", "key ="),
107
+ ("var position;", "let key ="),
108
+ ]
109
+ .into_iter()
110
+ .find_map(|(declare, read)| {
111
+ let source = DECODER
112
+ .replace("PARAMETERS", &parameters)
113
+ .replace("DECLARE", declare)
114
+ .replace("READ", read)
115
+ .replace("ACCUMULATE", accumulate);
116
+ let template = pattern::template(&source);
117
+ pattern::matches_routine(
118
+ &template,
119
+ script,
120
+ decoder.function,
121
+ decoder.routine(),
122
+ &helpers,
123
+ )
124
+ })
111
125
  };
112
126
  let (accumulates, captures) = match matched("key += position;") {
113
127
  Some(captures) => (true, captures),
@@ -126,15 +140,22 @@ impl<'ast> NativeDispatch<'ast> {
126
140
  let address = intrinsic::address(function(binding)?);
127
141
  session.intrinsics.get(&address).copied()
128
142
  };
129
- let Intrinsic::Register(Helper::Pc) = intrinsic(captures.name("$setpc")?)? else {
143
+ let Intrinsic::Register(Helper::Pc { .. }) = intrinsic(captures.name("$setpc")?)? else {
130
144
  return None;
131
145
  };
132
- let Intrinsic::Register(Helper::Key) = intrinsic(captures.name("$setkey")?)? else {
146
+ let Intrinsic::Register(Helper::Key { .. }) = intrinsic(captures.name("$setkey")?)? else {
133
147
  return None;
134
148
  };
135
149
  let unmask = function(captures.name("$unmask")?)?;
136
- let unmask_captures =
137
- pattern::matches(&pattern::template(UNMASK), script, unmask, &helpers)?;
150
+ let unmask_captures = [
151
+ "return (value >>> key | value << 8 - key) & 255;",
152
+ "rotated = value >>> key | value << 8 - key; return rotated & 255;",
153
+ ]
154
+ .into_iter()
155
+ .find_map(|rotate| {
156
+ let template = pattern::template(&UNMASK.replace("ROTATE", rotate));
157
+ pattern::matches(&template, script, unmask, &helpers)
158
+ })?;
138
159
  // Inlined helpers also resolve as recognized, unless setup left them unavailable.
139
160
  let mut inlined = captures.helpers.iter().chain(&unmask_captures.helpers);
140
161
  if inlined.any(|binding| session.unavailable.contains_key(binding)) {