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
@@ -9,7 +9,8 @@ use oxc::ast::AstKind;
9
9
  use oxc::ast::ast::{
10
10
  Argument as CallArgument, AssignmentExpression, AssignmentTarget, BindingIdentifier,
11
11
  BindingPattern, CallExpression, Class, ClassElement, Expression, FormalParameters, Function,
12
- FunctionBody, MemberExpression, MethodDefinitionKind, Statement, SwitchStatement,
12
+ FunctionBody, IdentifierReference, MemberExpression, MethodDefinitionKind, Statement,
13
+ SwitchStatement,
13
14
  };
14
15
  use oxc::ast_visit::{Visit, walk};
15
16
  use oxc::semantic::{ScopeFlags, SymbolId};
@@ -21,53 +22,47 @@ use super::{HashMap, convert};
21
22
  use crate::candidates;
22
23
  use crate::js::ast::{self, Binding, Script};
23
24
 
24
- pub(super) struct MachineScope<'a> {
25
+ /// The VM as the program runner (see [`Runner`]) reveals it.
26
+ pub(super) struct Found<'a> {
27
+ /// The function body declaring the class, the run function, and the handlers.
25
28
  pub body: &'a FunctionBody<'a>,
26
29
  pub class: &'a Class<'a>,
30
+ /// The run function, called with a new machine, the entry position, and the cells.
27
31
  pub run: &'a Function<'a>,
28
- /// Newer scripts pass the machine as the first argument of a free function.
29
- pub machine: Option<SymbolId>,
30
- }
31
-
32
- /// Finds the installed VM runner and its class, either a `run` method or a free function,
33
- /// in the innermost declaring function body.
34
- pub(super) fn find<'a>(script: Script<'a>) -> Option<MachineScope<'a>> {
35
- script
36
- .functions()
37
- .filter_map(|function| {
38
- let body = function.body.as_deref()?;
39
- let runner = body.statements.iter().find_map(installed_runner)?;
40
- let Expression::Identifier(class_name) = runner.class else {
41
- return None;
42
- };
43
- let class = body
44
- .statements
45
- .iter()
46
- .find_map(|statement| match statement {
47
- Statement::ClassDeclaration(class)
48
- if class.id.as_ref().map(|id| id.symbol_id())
49
- == script.symbol(class_name) =>
50
- {
51
- Some(&**class)
52
- }
53
- _ => None,
54
- })?;
55
- let (run, machine) = match runner.function {
56
- Some(Expression::Identifier(name)) => {
57
- let run = *functions(&body.statements).get(&script.symbol(name)?)?;
58
- (run, Some(parameter(&run.params, 0)?.symbol_id()))
59
- }
60
- None => (method(class, "run")?, None),
61
- _ => return None,
62
- };
63
- Some(MachineScope {
64
- body,
65
- class,
66
- run,
67
- machine,
68
- })
69
- })
70
- .last()
32
+ /// Where the runner starts a program.
33
+ pub entry: Position,
34
+ }
35
+
36
+ /// Finds the VM from its one program runner: the class the runner constructs, the run function
37
+ /// it calls, and the function body declaring both.
38
+ pub(super) fn find<'a>(script: Script<'a>) -> Result<Found<'a>> {
39
+ let runner = candidates::exactly_one(runners(script), "program runner")?;
40
+ // The declaration of `reference` and its parent.
41
+ let declaration = |reference: &IdentifierReference<'_>| {
42
+ let symbol = script
43
+ .symbol(reference)
44
+ .with_context(|| format!("the runner's {} is global", reference.name))?;
45
+ let node = script.scoping.symbol_declaration(symbol);
46
+ anyhow::Ok((script.nodes.kind(node), script.nodes.parent_kind(node)))
47
+ };
48
+ let (AstKind::Class(class), AstKind::FunctionBody(body)) = declaration(runner.class)? else {
49
+ bail!("the runner constructs no class declared directly in a function");
50
+ };
51
+ let (AstKind::Function(run), AstKind::FunctionBody(beside)) = declaration(runner.run)? else {
52
+ bail!("the runner calls no function declared directly in a function");
53
+ };
54
+ ensure!(
55
+ ptr::eq(body, beside),
56
+ "the run function is not declared beside the VM class"
57
+ );
58
+ let pc = convert::position(runner.pc).context("the runner starts at no program position")?;
59
+ let key = convert::byte(runner.key).context("the runner starts with no dispatch key")?;
60
+ Ok(Found {
61
+ body,
62
+ class,
63
+ run,
64
+ entry: Position::new(pc, key),
65
+ })
71
66
  }
72
67
 
73
68
  /// Collects the statements that run before the VM's scope is entered, both at script level and
@@ -161,42 +156,50 @@ pub(super) fn constructor<'a>(class: &'a Class<'a>) -> Result<&'a [Statement<'a>
161
156
  .context("the VM class has no constructor")
162
157
  }
163
158
 
164
- /// What a `run` local holds.
159
+ /// What a local of the run function holds.
165
160
  #[derive(Clone)]
166
161
  enum Source {
167
- Machine,
168
162
  Parameter(usize),
169
- /// `this.<name>`.
163
+ /// `<machine>.<name>`.
170
164
  Field(String),
171
- /// Register read as `<registers>.read(<index>)`. Both the register file and index come from
172
- /// fields.
165
+ /// Register read as `<read>(<registers>, <index>)`. Both the register file and index come
166
+ /// from fields.
173
167
  Register {
174
168
  registers: String,
175
169
  index: String,
170
+ read: SymbolId,
176
171
  },
177
172
  }
178
173
 
179
- /// Register layout and state setup recovered from `run`.
180
- pub(super) struct RunMethod<'ast> {
181
- pub access: super::registers::Access<'ast>,
174
+ /// Register layout and state setup recovered from the run function.
175
+ pub(super) struct RunFunction<'ast> {
182
176
  /// Field containing the register file. Fields on that file identify the program counter and
183
177
  /// dispatch key registers.
184
178
  pub registers: String,
185
179
  /// Fields containing the cells and program register indices.
186
180
  pub cells: String,
187
181
  pub program: String,
182
+ pub accessors: Accessors<'ast>,
188
183
  pub dispatch: DispatchLoop<'ast>,
189
184
  }
190
185
 
191
- /// Dispatch function declared beside the class and called by `run` with the machine. Some builds
192
- /// move both loops out of `run`; both dispatch the same handlers.
186
+ /// The register file's reader, `read(registers, index)`, and writer,
187
+ /// `write(registers, index, value)`, which the run function calls.
188
+ #[derive(Clone, Copy)]
189
+ pub(crate) struct Accessors<'ast> {
190
+ pub read: &'ast Function<'ast>,
191
+ pub write: &'ast Function<'ast>,
192
+ }
193
+
194
+ /// Dispatch function declared beside the class and called by the run function with the machine.
195
+ /// Both dispatch loops dispatch the same handlers.
193
196
  pub(crate) struct DispatchLoop<'ast> {
194
197
  pub function: &'ast Function<'ast>,
195
- /// Argument values passed by `run`, in parameter order.
198
+ /// Argument values passed by the run function, in parameter order.
196
199
  pub arguments: Vec<Argument>,
197
200
  }
198
201
 
199
- /// Argument passed from `run` to a dispatch loop.
202
+ /// Argument passed from the run function to a dispatch loop.
200
203
  #[derive(Clone, Copy, Debug, PartialEq, Eq)]
201
204
  pub(crate) enum Argument {
202
205
  Machine,
@@ -216,52 +219,43 @@ impl DispatchLoop<'_> {
216
219
  }
217
220
  }
218
221
 
219
- /// The locals of `run` and what they hold.
222
+ /// The locals of the run function and what they hold.
220
223
  struct Locals<'a> {
221
224
  script: Script<'a>,
225
+ /// The parameter receiving the machine.
226
+ machine: SymbolId,
222
227
  sources: HashMap<Binding<'a>, Source>,
223
- free: bool,
224
228
  }
225
229
 
226
- /// Tracks assignments in `run`, including copies of register fields and indices, program counter
227
- /// and key setup, storing the third argument in the cells register, reading the program register,
228
- /// and calling dispatch loops. An unsupported assignment clears the known value of its local.
229
- pub(super) fn run_method<'a>(
230
+ /// Tracks assignments in `run(machine, pc, key, cells)`, including copies of register fields and
231
+ /// indices, program counter and key setup, storing the cells argument in its register, reading
232
+ /// the program register, and calling dispatch loops. An unsupported assignment clears the known
233
+ /// value of its local.
234
+ pub(super) fn run_function<'a>(
230
235
  script: Script<'a>,
231
236
  functions: &HashMap<SymbolId, &'a Function<'a>>,
232
237
  run: &'a Function<'a>,
233
- machine: Option<SymbolId>,
234
- ) -> Result<RunMethod<'a>> {
235
- let body = run.body.as_deref().context("the run method has no body")?;
236
- let sources = (0..run.params.items.len())
238
+ ) -> Result<RunFunction<'a>> {
239
+ let body = run
240
+ .body
241
+ .as_deref()
242
+ .context("the run function has no body")?;
243
+ let machine = parameter(&run.params, 0)
244
+ .context("the run function takes no machine")?
245
+ .symbol_id();
246
+ let sources = (1..run.params.items.len())
237
247
  .filter_map(|index| {
238
248
  let name = parameter(&run.params, index)?;
239
- let source = if machine == Some(name.symbol_id()) {
240
- Source::Machine
241
- } else {
242
- Source::Parameter(index - usize::from(machine.is_some()))
243
- };
244
- Some((Binding::Symbol(name.symbol_id()), source))
249
+ Some((Binding::Symbol(name.symbol_id()), Source::Parameter(index)))
245
250
  })
246
251
  .collect();
247
252
  let mut locals = Locals {
248
253
  script,
254
+ machine,
249
255
  sources,
250
- free: machine.is_some(),
251
256
  };
252
257
  let mut cells = None;
253
258
  let mut loaded = Vec::new();
254
- let mut reader = None;
255
- let mut writer = None;
256
- let function = |expression: &Expression<'a>| {
257
- let Expression::CallExpression(call) = expression else {
258
- return None;
259
- };
260
- let Expression::Identifier(callee) = &call.callee else {
261
- return None;
262
- };
263
- functions.get(&script.symbol(callee)?).copied()
264
- };
265
259
  for statement in &body.statements {
266
260
  let Statement::ExpressionStatement(statement) = statement else {
267
261
  continue;
@@ -271,12 +265,14 @@ pub(super) fn run_method<'a>(
271
265
  expression => vec![expression],
272
266
  };
273
267
  for expression in expressions {
274
- if let Some((Source::Field(registers), arguments)) =
275
- locals.method_call(expression, "write")
276
- && let [Some(Source::Field(index)), Some(Source::Parameter(2))] = &arguments[..]
268
+ if let Some((write, arguments)) = locals.call(expression)
269
+ && let [
270
+ Some(Source::Field(registers)),
271
+ Some(Source::Field(index)),
272
+ Some(Source::Parameter(3)),
273
+ ] = &arguments[..]
277
274
  {
278
- cells = Some((registers, index.clone()));
279
- writer = function(expression);
275
+ cells = Some((registers.clone(), index.clone(), write));
280
276
  continue;
281
277
  }
282
278
  let Expression::AssignmentExpression(assignment) = expression else {
@@ -289,9 +285,13 @@ pub(super) fn run_method<'a>(
289
285
  AssignmentOperator::Assign => locals.source(&assignment.right),
290
286
  _ => None,
291
287
  };
292
- if let Some(Source::Register { registers, index }) = &value {
293
- loaded.push((registers.clone(), index.clone()));
294
- reader = function(&assignment.right);
288
+ if let Some(Source::Register {
289
+ registers,
290
+ index,
291
+ read,
292
+ }) = &value
293
+ {
294
+ loaded.push((registers.clone(), index.clone(), *read));
295
295
  }
296
296
  let binding = script.binding(name);
297
297
  match value {
@@ -300,18 +300,28 @@ pub(super) fn run_method<'a>(
300
300
  };
301
301
  }
302
302
  }
303
- let (registers, cells) =
304
- cells.context("the run method writes its cells argument to no register")?;
305
- loaded.retain(|(file, index)| *file == registers && *index != cells);
303
+ let (registers, cells, write) =
304
+ cells.context("the run function writes its cells argument to no register")?;
305
+ loaded.retain(|(file, index, _)| *file == registers && *index != cells);
306
306
  loaded.sort();
307
307
  loaded.dedup();
308
- let [(_, program)] = &loaded[..] else {
308
+ let [(_, program, read)] = &loaded[..] else {
309
309
  bail!(
310
- "the run method loads {} registers besides its arguments",
310
+ "the run function loads {} registers besides its arguments",
311
311
  loaded.len()
312
312
  );
313
313
  };
314
314
  let program = program.clone();
315
+ let declared = |symbol: SymbolId, what: &str| {
316
+ functions
317
+ .get(&symbol)
318
+ .copied()
319
+ .with_context(|| format!("the register {what} is not declared beside the VM class"))
320
+ };
321
+ let accessors = Accessors {
322
+ read: declared(*read, "reader")?,
323
+ write: declared(write, "writer")?,
324
+ };
315
325
  let mut calls = DispatchCall {
316
326
  script,
317
327
  functions,
@@ -321,14 +331,15 @@ pub(super) fn run_method<'a>(
321
331
  calls.visit_function_body(body);
322
332
  let (function, call) = calls
323
333
  .found
324
- .context("the run method calls no dispatch loop with the machine")?;
334
+ .context("the run function calls no dispatch loop with the machine")?;
325
335
  let arguments = call
326
336
  .arguments
327
337
  .iter()
328
338
  .map(|argument| match ast::argument_expression(argument) {
329
- Expression::ThisExpression(_) => Argument::Machine,
339
+ Expression::Identifier(name) if script.symbol(name) == Some(machine) => {
340
+ Argument::Machine
341
+ }
330
342
  Expression::Identifier(name) => match locals.sources.get(&script.binding(name)) {
331
- Some(Source::Machine) => Argument::Machine,
332
343
  Some(Source::Field(field)) if *field == registers => Argument::Registers,
333
344
  Some(Source::Register { index, .. }) if *index == program => Argument::Program,
334
345
  _ => Argument::Other,
@@ -336,18 +347,11 @@ pub(super) fn run_method<'a>(
336
347
  _ => Argument::Other,
337
348
  })
338
349
  .collect();
339
- Ok(RunMethod {
340
- access: if machine.is_some() {
341
- super::registers::Access::Functions {
342
- read: reader.context("the free VM runner has no register reader")?,
343
- write: writer.context("the free VM runner has no register writer")?,
344
- }
345
- } else {
346
- super::registers::Access::Methods
347
- },
350
+ Ok(RunFunction {
348
351
  registers,
349
352
  cells,
350
353
  program,
354
+ accessors,
351
355
  dispatch: DispatchLoop {
352
356
  function,
353
357
  arguments,
@@ -355,12 +359,12 @@ pub(super) fn run_method<'a>(
355
359
  })
356
360
  }
357
361
 
358
- /// Finds the first call in `run` whose first argument is the machine and whose target contains a
359
- /// dispatch switch.
362
+ /// Finds the first call in the run function whose first argument is the machine and whose target
363
+ /// contains a dispatch switch.
360
364
  struct DispatchCall<'functions, 'a> {
361
365
  script: Script<'a>,
362
366
  functions: &'functions HashMap<SymbolId, &'a Function<'a>>,
363
- machine: Option<SymbolId>,
367
+ machine: SymbolId,
364
368
  found: Option<(&'a Function<'a>, &'a CallExpression<'a>)>,
365
369
  }
366
370
 
@@ -368,11 +372,8 @@ impl<'a> Visit<'a> for DispatchCall<'_, 'a> {
368
372
  fn visit_call_expression(&mut self, call: &CallExpression<'a>) {
369
373
  if self.found.is_none()
370
374
  && call.arguments.first().is_some_and(|first| {
371
- let first = ast::argument_expression(first);
372
- matches!(first, Expression::ThisExpression(_))
373
- || self
374
- .machine
375
- .is_some_and(|machine| self.script.refers_to(first, machine))
375
+ self.script
376
+ .refers_to(ast::argument_expression(first), self.machine)
376
377
  })
377
378
  && let Expression::Identifier(callee) = &call.callee
378
379
  && let Some(symbol) = self.script.symbol(callee)
@@ -389,54 +390,39 @@ impl<'a> Visit<'a> for DispatchCall<'_, 'a> {
389
390
  }
390
391
 
391
392
  impl<'a> Locals<'a> {
392
- /// Resolves `<object>.<name>(<arguments>)`, including the values of the object and
393
- /// arguments.
394
- fn method_call(
395
- &self,
396
- expression: &Expression<'a>,
397
- name: &str,
398
- ) -> Option<(Source, Vec<Option<Source>>)> {
399
- let (object, arguments) = if let Some(call) = ast::method_call(expression, name) {
400
- call
401
- } else if self.free
402
- && let Expression::CallExpression(call) = expression
403
- {
404
- let [object, arguments @ ..] = &call.arguments[..] else {
405
- return None;
406
- };
407
- if arguments.len() != if name == "read" { 1 } else { 2 } {
408
- return None;
409
- }
410
- (ast::argument_expression(object), arguments)
411
- } else {
412
- return None;
413
- };
393
+ /// Resolves `<callee>(<arguments>)` for a callee the script declares, including the values
394
+ /// of the arguments.
395
+ fn call(&self, expression: &Expression<'a>) -> Option<(SymbolId, Vec<Option<Source>>)> {
396
+ let (callee, arguments) = ast::direct_call(expression)?;
414
397
  let arguments = arguments
415
398
  .iter()
416
399
  .map(|argument| self.source(ast::argument_expression(argument)))
417
400
  .collect();
418
- Some((self.source(object)?, arguments))
401
+ Some((self.script.symbol(callee)?, arguments))
419
402
  }
420
403
 
421
404
  fn source(&self, expression: &Expression<'a>) -> Option<Source> {
422
405
  match expression {
423
406
  Expression::Identifier(name) => self.sources.get(&self.script.binding(name)).cloned(),
424
- Expression::ThisExpression(_) => Some(Source::Machine),
425
407
  Expression::ParenthesizedExpression(paren) => self.source(&paren.expression),
426
- Expression::CallExpression(_) => match self.method_call(expression, "read")? {
427
- (Source::Field(registers), arguments) => match &arguments[..] {
428
- [Some(Source::Field(index))] => Some(Source::Register {
429
- registers,
430
- index: index.clone(),
431
- }),
432
- _ => None,
433
- },
434
- _ => None,
435
- },
408
+ Expression::CallExpression(_) => {
409
+ let (read, arguments) = self.call(expression)?;
410
+ let [Some(Source::Field(registers)), Some(Source::Field(index))] = &arguments[..]
411
+ else {
412
+ return None;
413
+ };
414
+ Some(Source::Register {
415
+ registers: registers.clone(),
416
+ index: index.clone(),
417
+ read,
418
+ })
419
+ }
436
420
  expression => {
437
421
  let member = expression.as_member_expression()?;
438
- matches!(self.source(member.object()), Some(Source::Machine))
439
- .then(|| ast::member_str(member).map(|name| Source::Field(name.to_owned())))?
422
+ let field = ast::member_str(member)?;
423
+ self.script
424
+ .refers_to(member.object(), self.machine)
425
+ .then(|| Source::Field(field.to_owned()))
440
426
  }
441
427
  }
442
428
  }
@@ -451,19 +437,14 @@ pub(super) fn this_field<'a>(expression: &Expression<'a>) -> Option<&'a str> {
451
437
  }
452
438
  }
453
439
 
454
- /// Finds the string decryption function called by the register reader as
455
- /// `decrypt(this.<values>[index])`.
456
- pub(super) fn record_decoder<'a>(
457
- script: Script<'a>,
458
- body: &'a FunctionBody<'a>,
459
- access: super::registers::Access<'a>,
460
- ) -> Option<SymbolId> {
461
- /// Matches `<decoder>(this.<values>[<index>])`.
440
+ /// Finds the string decryption function the register reader `read(registers, index)` calls as
441
+ /// `decrypt(registers.<values>[index])`.
442
+ pub(super) fn record_decoder<'a>(script: Script<'a>, read: &'a Function<'a>) -> Option<SymbolId> {
443
+ /// Matches `<decoder>(<registers>.<values>[<index>])`.
462
444
  struct Decoders<'a> {
463
445
  script: Script<'a>,
446
+ registers: SymbolId,
464
447
  index: SymbolId,
465
- object: Option<SymbolId>,
466
- access: super::registers::Access<'a>,
467
448
  found: Vec<Binding<'a>>,
468
449
  }
469
450
 
@@ -475,14 +456,7 @@ pub(super) fn record_decoder<'a>(
475
456
  && member
476
457
  .object()
477
458
  .as_member_expression()
478
- .is_some_and(|values| {
479
- matches!(values.object(), Expression::ThisExpression(_))
480
- || (self.object.is_some_and(|object| {
481
- self.script.refers_to(values.object(), object)
482
- }) && ast::member_str(values)
483
- .and_then(|name| self.access.member(name))
484
- == Some(super::registers::Member::Values))
485
- })
459
+ .is_some_and(|values| self.script.refers_to(values.object(), self.registers))
486
460
  && let MemberExpression::ComputedMemberExpression(member) = member
487
461
  && self.script.refers_to(&member.expression, self.index)
488
462
  {
@@ -492,52 +466,19 @@ pub(super) fn record_decoder<'a>(
492
466
  }
493
467
  }
494
468
 
495
- let (read, object, index) = match access {
496
- super::registers::Access::Methods => {
497
- let read = body
498
- .statements
499
- .iter()
500
- .find_map(|statement| match statement {
501
- Statement::ClassDeclaration(class) if method(class, "write").is_some() => {
502
- method(class, "read")
503
- }
504
- _ => None,
505
- })?;
506
- (read, None, 0)
507
- }
508
- super::registers::Access::Functions { read, .. } => {
509
- (read, Some(parameter(&read.params, 0)?.symbol_id()), 1)
510
- }
511
- };
512
469
  let mut decoders = Decoders {
513
470
  script,
514
- object,
515
- access,
516
- index: parameter(&read.params, index)?.symbol_id(),
471
+ registers: parameter(&read.params, 0)?.symbol_id(),
472
+ index: parameter(&read.params, 1)?.symbol_id(),
517
473
  found: Vec::new(),
518
474
  };
519
475
  decoders.visit_function(read, ScopeFlags::Function);
520
- decoders.found.sort();
521
- decoders.found.dedup();
522
476
  let [Binding::Symbol(decoder)] = decoders.found[..] else {
523
477
  return None;
524
478
  };
525
479
  Some(decoder)
526
480
  }
527
481
 
528
- /// The method, getter, or setter named `name`, excluding the constructor.
529
- pub(super) fn method<'a>(class: &'a Class<'a>, name: &str) -> Option<&'a Function<'a>> {
530
- class.body.body.iter().find_map(|element| match element {
531
- ClassElement::MethodDefinition(method)
532
- if method.kind != MethodDefinitionKind::Constructor
533
- && ast::static_key_str(&method.key, method.computed) == Some(name) =>
534
- {
535
- Some(&*method.value)
536
- }
537
- _ => None,
538
- })
539
- }
540
-
541
482
  /// Extracts opcode and handler pairs from `case <opcode>: <handler>(<machine>); break;`.
542
483
  pub(super) fn handlers<'a>(
543
484
  script: Script<'a>,
@@ -611,39 +552,19 @@ fn first_switch<'a>(statement: &'a Statement<'a>) -> Option<&'a SwitchStatement<
611
552
  }
612
553
  }
613
554
 
614
- /// Where the program runner starts a program (see [`Runner`]).
615
- pub(super) fn entry(body: &FunctionBody<'_>) -> Result<Position> {
616
- let runner = body
617
- .statements
618
- .iter()
619
- .find_map(installed_runner)
620
- .context("no program runner in the VM's scope")?;
621
- let pc = convert::position(runner.pc).context("the runner starts at no program position")?;
622
- let key = convert::byte(runner.key).context("the runner starts with no dispatch key")?;
623
- Ok(Position::new(pc, key))
624
- }
625
-
626
555
  /// The program runner, installed by
627
- /// `<global>.<name> = function(p) { return new <Class>(p).run(pc, key, []); }`.
556
+ /// `<global>.<name> = function(p) { return <run>(new <Class>(p), pc, key, []); }`.
628
557
  struct Runner<'ast> {
629
558
  /// The global property the runner is installed under. The name is random.
630
559
  name: &'ast str,
560
+ /// The run function.
561
+ run: &'ast IdentifierReference<'ast>,
562
+ /// The VM class.
563
+ class: &'ast IdentifierReference<'ast>,
631
564
  /// Initial program counter from the source.
632
565
  pc: f64,
633
566
  /// Initial dispatch key from the source.
634
567
  key: f64,
635
- class: &'ast Expression<'ast>,
636
- function: Option<&'ast Expression<'ast>>,
637
- }
638
-
639
- fn installed_runner<'a>(statement: &'a Statement<'a>) -> Option<Runner<'a>> {
640
- let Statement::ExpressionStatement(statement) = statement else {
641
- return None;
642
- };
643
- let Expression::AssignmentExpression(assignment) = &statement.expression else {
644
- return None;
645
- };
646
- Runner::installed_by(assignment)
647
568
  }
648
569
 
649
570
  impl<'ast> Runner<'ast> {
@@ -663,54 +584,45 @@ impl<'ast> Runner<'ast> {
663
584
  else {
664
585
  return None;
665
586
  };
666
- let expression = returned.argument.as_ref()?;
667
- let (machine, arguments, function) =
668
- if let Some((machine, arguments)) = ast::method_call(expression, "run") {
669
- (machine, arguments, None)
670
- } else if let Expression::CallExpression(call) = expression {
671
- let [machine, arguments @ ..] = &call.arguments[..] else {
672
- return None;
673
- };
674
- (
675
- ast::argument_expression(machine),
676
- arguments,
677
- Some(&call.callee),
678
- )
679
- } else {
680
- return None;
681
- };
682
- let [pc, key, ..] = arguments else {
587
+ let (run, [machine, pc, key, _]) = ast::direct_call(returned.argument.as_ref()?)? else {
683
588
  return None;
684
589
  };
685
590
  let (
686
- Expression::NewExpression(new),
591
+ Expression::NewExpression(machine),
687
592
  Expression::NumericLiteral(pc),
688
593
  Expression::NumericLiteral(key),
689
594
  ) = (
690
- machine,
595
+ ast::argument_expression(machine),
691
596
  ast::argument_expression(pc),
692
597
  ast::argument_expression(key),
693
598
  )
694
599
  else {
695
600
  return None;
696
601
  };
602
+ let Expression::Identifier(class) = &machine.callee else {
603
+ return None;
604
+ };
697
605
  Some(Self {
698
606
  name: ast::member_str(target)?,
607
+ run,
608
+ class,
699
609
  pc: pc.value,
700
610
  key: key.value,
701
- class: &new.callee,
702
- function,
703
611
  })
704
612
  }
705
613
  }
706
614
 
707
- /// Returns the installed program runner's name if exactly one exists (see [`Runner`]).
708
- pub(crate) fn runner_name(script: Script<'_>) -> Option<String> {
709
- let runners = script.nodes.iter().filter_map(|node| match node.kind() {
615
+ /// Every program runner the script installs.
616
+ fn runners<'a>(script: Script<'a>) -> impl Iterator<Item = Runner<'a>> {
617
+ script.nodes.iter().filter_map(|node| match node.kind() {
710
618
  AstKind::AssignmentExpression(assignment) => Runner::installed_by(assignment),
711
619
  _ => None,
712
- });
713
- let runner = candidates::exactly_one(runners, "program runner").ok()?;
620
+ })
621
+ }
622
+
623
+ /// Returns the installed program runner's name if exactly one exists (see [`Runner`]).
624
+ pub(crate) fn runner_name(script: Script<'_>) -> Option<String> {
625
+ let runner = candidates::exactly_one(runners(script), "program runner").ok()?;
714
626
  Some(runner.name.to_owned())
715
627
  }
716
628
 
@@ -746,107 +658,45 @@ mod tests {
746
658
 
747
659
  fn entry_of(source: &str) -> Result<Position> {
748
660
  let parsed = ParsedScript::parse("t", source).unwrap();
749
- let script = parsed.script();
750
- let Some(Statement::FunctionDeclaration(function)) = script.program.body.first() else {
751
- panic!("the test source declares no function");
752
- };
753
- entry(function.body.as_deref().unwrap())
661
+ find(parsed.script()).map(|found| found.entry)
754
662
  }
755
663
 
756
664
  #[test]
757
665
  fn finds_the_entry_past_leftover_declarations() {
758
- for source in [
759
- "function f(O) { O.vlJM8 = function(p) { return new M(p).run(0, 238, []); }; }",
760
- "function f(O) { O.vlJM8 = function(p) { var a; var b, c; return new M(p).run(0, 238, []); }; }",
761
- "function f(O) { O.vlJM8 = function(p) { return execute(new M(p), 0, 238, []); }; }",
666
+ let vm = |runner: &str| {
667
+ format!(
668
+ "function f(O) {{ class M {{}} function run(m, pc, key, cells) {{}} O.vlJM8 = function(p) {{ {runner} }}; }}"
669
+ )
670
+ };
671
+ for runner in [
672
+ "return run(new M(p), 0, 238, []);",
673
+ "var a; var b, c; return run(new M(p), 0, 238, []);",
762
674
  ] {
763
- assert_eq!(entry_of(source).unwrap(), Position::new(0, 238), "{source}");
675
+ let source = vm(runner);
676
+ assert_eq!(
677
+ entry_of(&source).unwrap(),
678
+ Position::new(0, 238),
679
+ "{source}"
680
+ );
764
681
  }
765
- let source = "function f(O) { O.vlJM8 = function(p) { var a = g(); return new M(p).run(0, 238, []); }; }";
682
+ let source = vm("var a = g(); return run(new M(p), 0, 238, []);");
766
683
  assert!(
767
- entry_of(source).is_err(),
684
+ entry_of(&source).is_err(),
768
685
  "a body that does more than return is not the entry"
769
686
  );
770
- }
771
-
772
- #[test]
773
- fn extracts_free_runner_and_register_helpers_by_binding() {
774
- let parsed = ParsedScript::parse("moved VM", r#"
775
- function scope(global) {
776
- class Unrelated { run() {} }
777
- class Registers { constructor() {} }
778
- class Machine { constructor(program) {} }
779
- function load(registers, index) { return registers.H[index]; }
780
- function store(registers, index, value) { registers.H[index] = value; }
781
- function opcode(machine) {}
782
- function dispatch(machine, registers, pending, program) {
783
- while (true) { switch (program[0]) { case 42: opcode(machine); break; } }
784
- }
785
- function execute(machine, pc, key, cells) {
786
- var registers, index, program;
787
- registers = machine.registers;
788
- index = machine.cells;
789
- store(registers, index, cells);
790
- index = machine.program;
791
- program = load(registers, index);
792
- dispatch(machine, registers, null, program);
793
- }
794
- global.start = function(program) { return execute(new Machine(program), 0, 231, []); };
795
- }
796
- "#).unwrap();
797
- let script = parsed.script();
798
- assert_eq!(runner_name(script).as_deref(), Some("start"));
799
- let found = find(script).unwrap();
800
- assert_eq!(found.class.id.as_ref().unwrap().name, "Machine");
801
- assert_eq!(entry(found.body).unwrap(), Position::new(0, 231));
802
- let functions = functions(&found.body.statements);
803
- let layout = run_method(script, &functions, found.run, found.machine).unwrap();
804
- assert_eq!(
805
- (&*layout.registers, &*layout.cells, &*layout.program),
806
- ("registers", "cells", "program")
807
- );
808
- let super::super::registers::Access::Functions { read, write } = layout.access else {
809
- panic!("expected free register accessors");
810
- };
811
- assert_eq!(read.id.as_ref().unwrap().name, "load");
812
- assert_eq!(write.id.as_ref().unwrap().name, "store");
813
- assert_eq!(
814
- layout.dispatch.arguments,
815
- vec![
816
- Argument::Machine,
817
- Argument::Registers,
818
- Argument::Other,
819
- Argument::Program
820
- ]
687
+ let source = "function f(O) { class M {} O.vlJM8 = function(p) { return run(new M(p), 0, 238, []); }; } function run(m, pc, key, cells) {}";
688
+ assert!(
689
+ entry_of(source).is_err(),
690
+ "the run function is declared beside the class"
821
691
  );
822
- let handlers = handlers(script, &functions, &layout.dispatch).unwrap();
823
- assert_eq!(handlers[&42].id.as_ref().unwrap().name, "opcode");
824
- }
825
-
826
- #[test]
827
- fn method_runner_selects_its_constructed_class() {
828
- let parsed = ParsedScript::parse(
829
- "two classes",
830
- r#"
831
- function scope(global) {
832
- class Unrelated { run() {} }
833
- class Machine { run() {} }
834
- global.start = function(program) { return new Machine(program).run(0, 1, []); };
835
- }
836
- "#,
837
- )
838
- .unwrap();
839
- let found = find(parsed.script()).unwrap();
840
- assert_eq!(found.class.id.as_ref().unwrap().name, "Machine");
841
- assert!(found.machine.is_none());
842
692
  }
843
693
 
844
694
  #[test]
845
695
  fn names_the_runner_its_callers_call() {
846
696
  let parsed = ParsedScript::parse(
847
697
  "t",
848
- "O.vlJM8 = function(p) { return new M(p).run(0, 238, []); }; \
849
- O.other = function(p) { return M(p).run(0, 238, []); }; O.vlJM8('a'); vlJM8('b');",
698
+ "O.vlJM8 = function(p) { return run(new M(p), 0, 238, []); }; \
699
+ O.other = function(p) { return run(M(p), 0, 238, []); }; O.vlJM8('a'); vlJM8('b');",
850
700
  )
851
701
  .unwrap();
852
702
  let script = parsed.script();