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
@@ -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,16 +22,47 @@ use super::{HashMap, convert};
21
22
  use crate::candidates;
22
23
  use crate::js::ast::{self, Binding, Script};
23
24
 
24
- /// Finds a class with a `run` method and the innermost function body declaring it: the last such
25
- /// body in source order.
26
- pub(super) fn find<'a>(script: Script<'a>) -> Option<(&'a FunctionBody<'a>, &'a Class<'a>)> {
27
- script
28
- .functions()
29
- .filter_map(|function| {
30
- let body = function.body.as_deref()?;
31
- Some((body, machine_class(body)?))
32
- })
33
- .last()
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.
28
+ pub body: &'a FunctionBody<'a>,
29
+ pub class: &'a Class<'a>,
30
+ /// The run function, called with a new machine, the entry position, and the cells.
31
+ pub run: &'a Function<'a>,
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
+ })
34
66
  }
35
67
 
36
68
  /// Collects the statements that run before the VM's scope is entered, both at script level and
@@ -124,40 +156,50 @@ pub(super) fn constructor<'a>(class: &'a Class<'a>) -> Result<&'a [Statement<'a>
124
156
  .context("the VM class has no constructor")
125
157
  }
126
158
 
127
- /// What a `run` local holds.
159
+ /// What a local of the run function holds.
128
160
  #[derive(Clone)]
129
161
  enum Source {
130
162
  Parameter(usize),
131
- /// `this.<name>`.
163
+ /// `<machine>.<name>`.
132
164
  Field(String),
133
- /// Register read as `<registers>.read(<index>)`. Both the register file and index come from
134
- /// fields.
165
+ /// Register read as `<read>(<registers>, <index>)`. Both the register file and index come
166
+ /// from fields.
135
167
  Register {
136
168
  registers: String,
137
169
  index: String,
170
+ read: SymbolId,
138
171
  },
139
172
  }
140
173
 
141
- /// Register layout and state setup recovered from `run`.
142
- pub(super) struct RunMethod<'ast> {
174
+ /// Register layout and state setup recovered from the run function.
175
+ pub(super) struct RunFunction<'ast> {
143
176
  /// Field containing the register file. Fields on that file identify the program counter and
144
177
  /// dispatch key registers.
145
178
  pub registers: String,
146
179
  /// Fields containing the cells and program register indices.
147
180
  pub cells: String,
148
181
  pub program: String,
182
+ pub accessors: Accessors<'ast>,
149
183
  pub dispatch: DispatchLoop<'ast>,
150
184
  }
151
185
 
152
- /// Dispatch function declared beside the class and called by `run` with the machine. Some builds
153
- /// 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.
154
196
  pub(crate) struct DispatchLoop<'ast> {
155
197
  pub function: &'ast Function<'ast>,
156
- /// Argument values passed by `run`, in parameter order.
198
+ /// Argument values passed by the run function, in parameter order.
157
199
  pub arguments: Vec<Argument>,
158
200
  }
159
201
 
160
- /// Argument passed from `run` to a dispatch loop.
202
+ /// Argument passed from the run function to a dispatch loop.
161
203
  #[derive(Clone, Copy, Debug, PartialEq, Eq)]
162
204
  pub(crate) enum Argument {
163
205
  Machine,
@@ -177,28 +219,41 @@ impl DispatchLoop<'_> {
177
219
  }
178
220
  }
179
221
 
180
- /// The locals of `run` and what they hold.
222
+ /// The locals of the run function and what they hold.
181
223
  struct Locals<'a> {
182
224
  script: Script<'a>,
225
+ /// The parameter receiving the machine.
226
+ machine: SymbolId,
183
227
  sources: HashMap<Binding<'a>, Source>,
184
228
  }
185
229
 
186
- /// Tracks assignments in `run`, including copies of register fields and indices, program counter
187
- /// and key setup, storing the third argument in the cells register, reading the program register,
188
- /// and calling dispatch loops. An unsupported assignment clears the known value of its local.
189
- 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>(
190
235
  script: Script<'a>,
191
236
  functions: &HashMap<SymbolId, &'a Function<'a>>,
192
237
  run: &'a Function<'a>,
193
- ) -> Result<RunMethod<'a>> {
194
- let body = run.body.as_deref().context("the run method has no body")?;
195
- 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())
196
247
  .filter_map(|index| {
197
248
  let name = parameter(&run.params, index)?;
198
249
  Some((Binding::Symbol(name.symbol_id()), Source::Parameter(index)))
199
250
  })
200
251
  .collect();
201
- let mut locals = Locals { script, sources };
252
+ let mut locals = Locals {
253
+ script,
254
+ machine,
255
+ sources,
256
+ };
202
257
  let mut cells = None;
203
258
  let mut loaded = Vec::new();
204
259
  for statement in &body.statements {
@@ -210,11 +265,14 @@ pub(super) fn run_method<'a>(
210
265
  expression => vec![expression],
211
266
  };
212
267
  for expression in expressions {
213
- if let Some((Source::Field(registers), arguments)) =
214
- locals.method_call(expression, "write")
215
- && 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[..]
216
274
  {
217
- cells = Some((registers, index.clone()));
275
+ cells = Some((registers.clone(), index.clone(), write));
218
276
  continue;
219
277
  }
220
278
  let Expression::AssignmentExpression(assignment) = expression else {
@@ -227,8 +285,13 @@ pub(super) fn run_method<'a>(
227
285
  AssignmentOperator::Assign => locals.source(&assignment.right),
228
286
  _ => None,
229
287
  };
230
- if let Some(Source::Register { registers, index }) = &value {
231
- loaded.push((registers.clone(), index.clone()));
288
+ if let Some(Source::Register {
289
+ registers,
290
+ index,
291
+ read,
292
+ }) = &value
293
+ {
294
+ loaded.push((registers.clone(), index.clone(), *read));
232
295
  }
233
296
  let binding = script.binding(name);
234
297
  match value {
@@ -237,32 +300,45 @@ pub(super) fn run_method<'a>(
237
300
  };
238
301
  }
239
302
  }
240
- let (registers, cells) =
241
- cells.context("the run method writes its cells argument to no register")?;
242
- 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);
243
306
  loaded.sort();
244
307
  loaded.dedup();
245
- let [(_, program)] = &loaded[..] else {
308
+ let [(_, program, read)] = &loaded[..] else {
246
309
  bail!(
247
- "the run method loads {} registers besides its arguments",
310
+ "the run function loads {} registers besides its arguments",
248
311
  loaded.len()
249
312
  );
250
313
  };
251
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
+ };
252
325
  let mut calls = DispatchCall {
253
326
  script,
254
327
  functions,
328
+ machine,
255
329
  found: None,
256
330
  };
257
331
  calls.visit_function_body(body);
258
332
  let (function, call) = calls
259
333
  .found
260
- .context("the run method calls no dispatch loop with the machine")?;
334
+ .context("the run function calls no dispatch loop with the machine")?;
261
335
  let arguments = call
262
336
  .arguments
263
337
  .iter()
264
338
  .map(|argument| match ast::argument_expression(argument) {
265
- Expression::ThisExpression(_) => Argument::Machine,
339
+ Expression::Identifier(name) if script.symbol(name) == Some(machine) => {
340
+ Argument::Machine
341
+ }
266
342
  Expression::Identifier(name) => match locals.sources.get(&script.binding(name)) {
267
343
  Some(Source::Field(field)) if *field == registers => Argument::Registers,
268
344
  Some(Source::Register { index, .. }) if *index == program => Argument::Program,
@@ -271,10 +347,11 @@ pub(super) fn run_method<'a>(
271
347
  _ => Argument::Other,
272
348
  })
273
349
  .collect();
274
- Ok(RunMethod {
350
+ Ok(RunFunction {
275
351
  registers,
276
352
  cells,
277
353
  program,
354
+ accessors,
278
355
  dispatch: DispatchLoop {
279
356
  function,
280
357
  arguments,
@@ -282,11 +359,12 @@ pub(super) fn run_method<'a>(
282
359
  })
283
360
  }
284
361
 
285
- /// Finds the first call in `run` whose first argument is the machine and whose target contains a
286
- /// 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.
287
364
  struct DispatchCall<'functions, 'a> {
288
365
  script: Script<'a>,
289
366
  functions: &'functions HashMap<SymbolId, &'a Function<'a>>,
367
+ machine: SymbolId,
290
368
  found: Option<(&'a Function<'a>, &'a CallExpression<'a>)>,
291
369
  }
292
370
 
@@ -294,10 +372,8 @@ impl<'a> Visit<'a> for DispatchCall<'_, 'a> {
294
372
  fn visit_call_expression(&mut self, call: &CallExpression<'a>) {
295
373
  if self.found.is_none()
296
374
  && call.arguments.first().is_some_and(|first| {
297
- matches!(
298
- ast::argument_expression(first),
299
- Expression::ThisExpression(_)
300
- )
375
+ self.script
376
+ .refers_to(ast::argument_expression(first), self.machine)
301
377
  })
302
378
  && let Expression::Identifier(callee) = &call.callee
303
379
  && let Some(symbol) = self.script.symbol(callee)
@@ -314,36 +390,40 @@ impl<'a> Visit<'a> for DispatchCall<'_, 'a> {
314
390
  }
315
391
 
316
392
  impl<'a> Locals<'a> {
317
- /// Resolves `<object>.<name>(<arguments>)`, including the values of the object and
318
- /// arguments.
319
- fn method_call(
320
- &self,
321
- expression: &Expression<'a>,
322
- name: &str,
323
- ) -> Option<(Source, Vec<Option<Source>>)> {
324
- let (object, arguments) = ast::method_call(expression, name)?;
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)?;
325
397
  let arguments = arguments
326
398
  .iter()
327
399
  .map(|argument| self.source(ast::argument_expression(argument)))
328
400
  .collect();
329
- Some((self.source(object)?, arguments))
401
+ Some((self.script.symbol(callee)?, arguments))
330
402
  }
331
403
 
332
404
  fn source(&self, expression: &Expression<'a>) -> Option<Source> {
333
405
  match expression {
334
406
  Expression::Identifier(name) => self.sources.get(&self.script.binding(name)).cloned(),
335
407
  Expression::ParenthesizedExpression(paren) => self.source(&paren.expression),
336
- Expression::CallExpression(_) => match self.method_call(expression, "read")? {
337
- (Source::Field(registers), arguments) => match &arguments[..] {
338
- [Some(Source::Field(index))] => Some(Source::Register {
339
- registers,
340
- index: index.clone(),
341
- }),
342
- _ => None,
343
- },
344
- _ => None,
345
- },
346
- expression => Some(Source::Field(this_field(expression)?.to_owned())),
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
+ }
420
+ expression => {
421
+ let member = expression.as_member_expression()?;
422
+ let field = ast::member_str(member)?;
423
+ self.script
424
+ .refers_to(member.object(), self.machine)
425
+ .then(|| Source::Field(field.to_owned()))
426
+ }
347
427
  }
348
428
  }
349
429
  }
@@ -357,15 +437,13 @@ pub(super) fn this_field<'a>(expression: &Expression<'a>) -> Option<&'a str> {
357
437
  }
358
438
  }
359
439
 
360
- /// Finds the string decryption function called by the register reader as
361
- /// `decrypt(this.<values>[index])`.
362
- pub(super) fn record_decoder<'a>(
363
- script: Script<'a>,
364
- body: &'a FunctionBody<'a>,
365
- ) -> Option<SymbolId> {
366
- /// 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>])`.
367
444
  struct Decoders<'a> {
368
445
  script: Script<'a>,
446
+ registers: SymbolId,
369
447
  index: SymbolId,
370
448
  found: Vec<Binding<'a>>,
371
449
  }
@@ -378,7 +456,7 @@ pub(super) fn record_decoder<'a>(
378
456
  && member
379
457
  .object()
380
458
  .as_member_expression()
381
- .is_some_and(|values| matches!(values.object(), Expression::ThisExpression(_)))
459
+ .is_some_and(|values| self.script.refers_to(values.object(), self.registers))
382
460
  && let MemberExpression::ComputedMemberExpression(member) = member
383
461
  && self.script.refers_to(&member.expression, self.index)
384
462
  {
@@ -388,18 +466,10 @@ pub(super) fn record_decoder<'a>(
388
466
  }
389
467
  }
390
468
 
391
- let read = body
392
- .statements
393
- .iter()
394
- .find_map(|statement| match statement {
395
- Statement::ClassDeclaration(class) if method(class, "write").is_some() => {
396
- method(class, "read")
397
- }
398
- _ => None,
399
- })?;
400
469
  let mut decoders = Decoders {
401
470
  script,
402
- index: parameter(&read.params, 0)?.symbol_id(),
471
+ registers: parameter(&read.params, 0)?.symbol_id(),
472
+ index: parameter(&read.params, 1)?.symbol_id(),
403
473
  found: Vec::new(),
404
474
  };
405
475
  decoders.visit_function(read, ScopeFlags::Function);
@@ -409,29 +479,6 @@ pub(super) fn record_decoder<'a>(
409
479
  Some(decoder)
410
480
  }
411
481
 
412
- /// The first class declaration with a `run` method.
413
- fn machine_class<'a>(body: &'a FunctionBody<'a>) -> Option<&'a Class<'a>> {
414
- body.statements
415
- .iter()
416
- .find_map(|statement| match statement {
417
- Statement::ClassDeclaration(class) if method(class, "run").is_some() => Some(&**class),
418
- _ => None,
419
- })
420
- }
421
-
422
- /// The method, getter, or setter named `name`, excluding the constructor.
423
- pub(super) fn method<'a>(class: &'a Class<'a>, name: &str) -> Option<&'a Function<'a>> {
424
- class.body.body.iter().find_map(|element| match element {
425
- ClassElement::MethodDefinition(method)
426
- if method.kind != MethodDefinitionKind::Constructor
427
- && ast::static_key_str(&method.key, method.computed) == Some(name) =>
428
- {
429
- Some(&*method.value)
430
- }
431
- _ => None,
432
- })
433
- }
434
-
435
482
  /// Extracts opcode and handler pairs from `case <opcode>: <handler>(<machine>); break;`.
436
483
  pub(super) fn handlers<'a>(
437
484
  script: Script<'a>,
@@ -505,29 +552,15 @@ fn first_switch<'a>(statement: &'a Statement<'a>) -> Option<&'a SwitchStatement<
505
552
  }
506
553
  }
507
554
 
508
- /// Where the program runner starts a program (see [`Runner`]).
509
- pub(super) fn entry(body: &FunctionBody<'_>) -> Result<Position> {
510
- let runner = body
511
- .statements
512
- .iter()
513
- .find_map(|statement| match statement {
514
- Statement::ExpressionStatement(statement) => match &statement.expression {
515
- Expression::AssignmentExpression(assignment) => Runner::installed_by(assignment),
516
- _ => None,
517
- },
518
- _ => None,
519
- })
520
- .context("no program runner in the VM's scope")?;
521
- let pc = convert::position(runner.pc).context("the runner starts at no program position")?;
522
- let key = convert::byte(runner.key).context("the runner starts with no dispatch key")?;
523
- Ok(Position::new(pc, key))
524
- }
525
-
526
555
  /// The program runner, installed by
527
- /// `<global>.<name> = function(p) { return new <Class>(p).run(pc, key, []); }`.
556
+ /// `<global>.<name> = function(p) { return <run>(new <Class>(p), pc, key, []); }`.
528
557
  struct Runner<'ast> {
529
558
  /// The global property the runner is installed under. The name is random.
530
559
  name: &'ast str,
560
+ /// The run function.
561
+ run: &'ast IdentifierReference<'ast>,
562
+ /// The VM class.
563
+ class: &'ast IdentifierReference<'ast>,
531
564
  /// Initial program counter from the source.
532
565
  pc: f64,
533
566
  /// Initial dispatch key from the source.
@@ -535,7 +568,7 @@ struct Runner<'ast> {
535
568
  }
536
569
 
537
570
  impl<'ast> Runner<'ast> {
538
- fn installed_by(assignment: &AssignmentExpression<'ast>) -> Option<Self> {
571
+ fn installed_by(assignment: &'ast AssignmentExpression<'ast>) -> Option<Self> {
539
572
  let target = assignment.left.as_member_expression()?;
540
573
  if matches!(target.object(), Expression::Super(_)) {
541
574
  return None;
@@ -551,36 +584,45 @@ impl<'ast> Runner<'ast> {
551
584
  else {
552
585
  return None;
553
586
  };
554
- let (machine, [pc, key, ..]) = ast::method_call(returned.argument.as_ref()?, "run")? else {
587
+ let (run, [machine, pc, key, _]) = ast::direct_call(returned.argument.as_ref()?)? else {
555
588
  return None;
556
589
  };
557
590
  let (
558
- Expression::NewExpression(_),
591
+ Expression::NewExpression(machine),
559
592
  Expression::NumericLiteral(pc),
560
593
  Expression::NumericLiteral(key),
561
594
  ) = (
562
- machine,
595
+ ast::argument_expression(machine),
563
596
  ast::argument_expression(pc),
564
597
  ast::argument_expression(key),
565
598
  )
566
599
  else {
567
600
  return None;
568
601
  };
602
+ let Expression::Identifier(class) = &machine.callee else {
603
+ return None;
604
+ };
569
605
  Some(Self {
570
606
  name: ast::member_str(target)?,
607
+ run,
608
+ class,
571
609
  pc: pc.value,
572
610
  key: key.value,
573
611
  })
574
612
  }
575
613
  }
576
614
 
577
- /// Returns the installed program runner's name if exactly one exists (see [`Runner`]).
578
- pub(crate) fn runner_name(script: Script<'_>) -> Option<String> {
579
- 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() {
580
618
  AstKind::AssignmentExpression(assignment) => Runner::installed_by(assignment),
581
619
  _ => None,
582
- });
583
- 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()?;
584
626
  Some(runner.name.to_owned())
585
627
  }
586
628
 
@@ -616,34 +658,45 @@ mod tests {
616
658
 
617
659
  fn entry_of(source: &str) -> Result<Position> {
618
660
  let parsed = ParsedScript::parse("t", source).unwrap();
619
- let script = parsed.script();
620
- let Some(Statement::FunctionDeclaration(function)) = script.program.body.first() else {
621
- panic!("the test source declares no function");
622
- };
623
- entry(function.body.as_deref().unwrap())
661
+ find(parsed.script()).map(|found| found.entry)
624
662
  }
625
663
 
626
664
  #[test]
627
665
  fn finds_the_entry_past_leftover_declarations() {
628
- for source in [
629
- "function f(O) { O.vlJM8 = function(p) { return new M(p).run(0, 238, []); }; }",
630
- "function f(O) { O.vlJM8 = function(p) { var a; var b, c; return new M(p).run(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, []);",
631
674
  ] {
632
- 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
+ );
633
681
  }
634
- 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, []);");
635
683
  assert!(
636
- entry_of(source).is_err(),
684
+ entry_of(&source).is_err(),
637
685
  "a body that does more than return is not the entry"
638
686
  );
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"
691
+ );
639
692
  }
640
693
 
641
694
  #[test]
642
695
  fn names_the_runner_its_callers_call() {
643
696
  let parsed = ParsedScript::parse(
644
697
  "t",
645
- "O.vlJM8 = function(p) { return new M(p).run(0, 238, []); }; \
646
- 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');",
647
700
  )
648
701
  .unwrap();
649
702
  let script = parsed.script();
@@ -377,8 +377,6 @@ impl<'ast> Run<'ast, '_> {
377
377
  fn register_member(&self, member: Member) -> Value<'ast> {
378
378
  let layout = self.session.layout;
379
379
  match member {
380
- Member::Read => Value::function(Callable::Builtin(Builtin::RegisterRead)),
381
- Member::Write => Value::function(Callable::Builtin(Builtin::RegisterWrite)),
382
380
  Member::Mask => Value::Number(0.0),
383
381
  Member::Integer => Value::Number(1.0),
384
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) => {