cfsolve 0.1.3 → 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 (52) hide show
  1. checksums.yaml +4 -4
  2. data/CHANGELOG.md +40 -0
  3. data/README.md +30 -5
  4. data/UPSTREAM.md +24 -3
  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 +21 -10
  9. data/vendor/cfsolve/examples/listing_dump.rs +24 -0
  10. data/vendor/cfsolve/examples/probe_similarity.rs +37 -0
  11. data/vendor/cfsolve/examples/rebase_reference.rs +96 -0
  12. data/vendor/cfsolve/examples/reread_capture.rs +31 -0
  13. data/vendor/cfsolve/examples/turnstile_smoke.rs +79 -0
  14. data/vendor/cfsolve/profiles/safari-26-ios/answers.json +805 -797
  15. data/vendor/cfsolve/profiles/safari-26-ios/challenge-page-answers.json +909 -899
  16. data/vendor/cfsolve/src/capture/sessions.rs +88 -4
  17. data/vendor/cfsolve/src/capture.rs +1 -0
  18. data/vendor/cfsolve/src/deobfuscate/ast.rs +16 -0
  19. data/vendor/cfsolve/src/deobfuscate/control_flow.rs +1 -1
  20. data/vendor/cfsolve/src/deobfuscate/dead_branches.rs +33 -0
  21. data/vendor/cfsolve/src/deobfuscate/merged_functions.rs +24 -4
  22. data/vendor/cfsolve/src/embedding_page/extra_params.rs +3 -3
  23. data/vendor/cfsolve/src/embedding_page/page.rs +76 -65
  24. data/vendor/cfsolve/src/stage2/analysis/discovery.rs +7 -4
  25. data/vendor/cfsolve/src/stage2/benchmark.rs +29 -8
  26. data/vendor/cfsolve/src/stage2/call_stack.rs +134 -95
  27. data/vendor/cfsolve/src/stage2/challenge_page.rs +10 -3
  28. data/vendor/cfsolve/src/stage2/probes/parent_info.rs +345 -61
  29. data/vendor/cfsolve/src/stage2/probes/performance.rs +42 -5
  30. data/vendor/cfsolve/src/stage2/probes/stack.rs +41 -0
  31. data/vendor/cfsolve/src/stage2/probes/websocket_echo.rs +11 -2
  32. data/vendor/cfsolve/src/stage2/reference.json +1 -1
  33. data/vendor/cfsolve/src/stage2/reference.rs +70 -110
  34. data/vendor/cfsolve/src/stage2/registry.rs +4 -3
  35. data/vendor/cfsolve/src/stage2/trace.rs +1 -1
  36. data/vendor/cfsolve/src/vm/dataflow.rs +15 -6
  37. data/vendor/cfsolve/src/vm/disassemble.rs +2 -1
  38. data/vendor/cfsolve/src/vm/encoded_strings.rs +1553 -0
  39. data/vendor/cfsolve/src/vm/extract.rs +205 -152
  40. data/vendor/cfsolve/src/vm/interpret/access.rs +0 -2
  41. data/vendor/cfsolve/src/vm/interpret/builtin.rs +0 -13
  42. data/vendor/cfsolve/src/vm/interpret/intrinsic.rs +30 -7
  43. data/vendor/cfsolve/src/vm/interpret/mix32.rs +216 -86
  44. data/vendor/cfsolve/src/vm/interpret/native_dispatch.rs +42 -21
  45. data/vendor/cfsolve/src/vm/interpret/pattern.rs +268 -67
  46. data/vendor/cfsolve/src/vm/interpret/register_helpers.rs +261 -30
  47. data/vendor/cfsolve/src/vm/machine.rs +14 -12
  48. data/vendor/cfsolve/src/vm/output.rs +4 -1
  49. data/vendor/cfsolve/src/vm/registers.rs +17 -23
  50. data/vendor/cfsolve/src/vm/session.rs +9 -4
  51. data/vendor/cfsolve/src/vm.rs +1 -0
  52. metadata +7 -1
@@ -8,6 +8,7 @@ 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
14
  use super::register_helpers::{self, Helper};
@@ -36,13 +37,16 @@ pub(super) fn address(function: &Function<'_>) -> usize {
36
37
  ptr::from_ref(function).addr()
37
38
  }
38
39
 
39
- /// Finds register helpers and mixers, and validates BLAKE3 candidates taking five parameters
40
- /// 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.
41
43
  pub(crate) fn intrinsics(session: &Session<'_>) -> Intrinsics {
42
44
  let mut intrinsics = Intrinsics::default();
43
45
  let script = session.script;
44
46
  for function in session.functions.values() {
45
- let intrinsic = if let Some(helper) = register_helpers::recognize(script, function) {
47
+ let intrinsic = if let Some(helper) =
48
+ register_helpers::recognize(script, session.accessors, function)
49
+ {
46
50
  Intrinsic::Register(helper)
47
51
  } else if let Some(mixer) = Mix32::recognize(script, function) {
48
52
  Intrinsic::Mix32(mixer)
@@ -70,7 +74,7 @@ impl Intrinsic {
70
74
  run: &mut Run<'ast, '_>,
71
75
  arguments: &[Value<'ast>],
72
76
  ) -> Option<Value<'ast>> {
73
- let register = match self {
77
+ let (register, returns) = match self {
74
78
  Self::Mix32(mixer) => {
75
79
  let Some(Value::Number(number)) = arguments.first() else {
76
80
  return None;
@@ -87,8 +91,23 @@ impl Intrinsic {
87
91
  return matches!(arguments.first(), Some(Value::Registers))
88
92
  .then_some(Value::Undefined);
89
93
  }
90
- Self::Register(Helper::Pc) => run.session.layout.pc,
91
- 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),
92
111
  Self::Blake3Compress => return None,
93
112
  };
94
113
  let [Value::Registers, value @ Value::Number(number), ..] = arguments else {
@@ -100,7 +119,11 @@ impl Intrinsic {
100
119
  return None;
101
120
  }
102
121
  run.set_register(register, value.clone());
103
- Some(value.clone())
122
+ Some(if returns {
123
+ value.clone()
124
+ } else {
125
+ Value::Undefined
126
+ })
104
127
  }
105
128
  }
106
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)) {