cfsolve 0.1.5 → 0.1.6

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.
@@ -151,12 +151,11 @@ impl Geometry {
151
151
  }
152
152
  }
153
153
 
154
- /// A VM function's method call: its opcode, its argument count, and the caller's arity.
154
+ /// A VM function's method call: its opcode and its argument count.
155
155
  #[derive(Clone, Copy, Debug)]
156
156
  pub struct MethodCall {
157
157
  pub opcode: u8,
158
158
  pub passed: usize,
159
- pub arity: usize,
160
159
  }
161
160
 
162
161
  /// Call path to `new Error()` in the stack probe. The probe function calls a closure that
@@ -217,19 +216,24 @@ pub fn recover_probe(
217
216
  })
218
217
  }
219
218
 
220
- /// Recovers the stack outside a native method called by a VM function, from the method call to
221
- /// the listener. Closure-factory listeners are anonymous. Uses the guarded dispatch loop when
222
- /// an exception handler is registered, including calls made by the program itself under a
223
- /// handler.
224
- pub fn recover_method_call(
219
+ /// Recovers the stack outside a native method that a returned program calls while it starts,
220
+ /// from the method call out to the page script's response handler that started the program
221
+ /// (see [`ProgramCalls`]): the program's listener, any forwarder, and the handler.
222
+ pub fn recover_program_call(
225
223
  source: &str,
226
224
  cases: &CaseOpcodes,
227
225
  call: MethodCall,
228
- guarded: bool,
229
226
  ) -> Result<Geometry> {
230
227
  geometry(source, cases, |machine| {
231
- let mut frames = machine.method_call(call.opcode, call.passed, guarded)?;
232
- frames.extend(machine.listener(call.arity, "")?);
228
+ let mut frames = machine.method_call(call.opcode, call.passed)?;
229
+ let mut calls = ProgramCalls {
230
+ script: &machine.script,
231
+ found: Vec::new(),
232
+ };
233
+ calls.visit_program(machine.script.js().program);
234
+ let (arity, caller) = candidates::exactly_one(calls.found, "call of a returned program")?;
235
+ frames.extend(machine.listener(arity, "")?);
236
+ frames.extend(caller);
233
237
  Ok(Chain {
234
238
  frames,
235
239
  reflected: false,
@@ -581,9 +585,11 @@ impl<'a, 'cases> Machine<'a, 'cases> {
581
585
  }
582
586
 
583
587
  /// Recovers frames from a method call in `opcode`'s handler through the runner: the handler
584
- /// passes the method, receiver, and `passed` arguments to a native apply forwarder.
585
- fn method_call(&self, opcode: u8, passed: usize, guarded: bool) -> Result<Vec<Call>> {
586
- let handler = self.handler(opcode, guarded)?;
588
+ /// passes the method, receiver, and `passed` arguments to a native apply forwarder. The
589
+ /// calling program runs under its own exception handler, so it dispatches from the guarded
590
+ /// loop.
591
+ fn method_call(&self, opcode: u8, passed: usize) -> Result<Vec<Call>> {
592
+ let handler = self.handler(opcode, true)?;
587
593
  let appliers = &self.script.appliers;
588
594
  let function = self.script.function(handler.name)?;
589
595
  let scope = Scope::new(appliers.name(handler.name), &function, appliers);
@@ -619,6 +625,111 @@ impl<'a, 'cases> Machine<'a, 'cases> {
619
625
  }
620
626
  }
621
627
 
628
+ /// V8's name for the anonymous response handler that starts a compiled program. The handler is
629
+ /// assigned to a computed `XMLHttpRequest` event property. Chrome stacks stop before reaching
630
+ /// it, at V8's frame limit.
631
+ const PROGRAM_CALLER: &str = "XMLHttpRequest.<anonymous>";
632
+
633
+ /// Finds calls of a returned program in every function. The response handler runs a returned
634
+ /// script as `new Function(code)(a, b)` and a returned program, which it compiles first, with
635
+ /// the same arguments: directly as `program(a, b)`, or through a function forwarding its first
636
+ /// parameter, as `forward(program, a, b)`, possibly through call helpers. Records the arguments
637
+ /// passed to the program and the frames from the forwarder, if any, to the handler.
638
+ struct ProgramCalls<'a, 's> {
639
+ script: &'s Script<'a>,
640
+ found: Vec<(usize, Vec<Call>)>,
641
+ }
642
+
643
+ impl<'a> ProgramCalls<'a, '_> {
644
+ /// The argument count and frames of `call` if it starts a program, given the argument lists
645
+ /// `scripts` that returned scripts receive in the same function.
646
+ fn program_call(
647
+ &self,
648
+ scope: &Scope<'a, '_>,
649
+ call: &'a CallExpression<'a>,
650
+ scripts: &[Vec<Binding<'a>>],
651
+ ) -> Option<(usize, Vec<Call>)> {
652
+ let script = self.script;
653
+ let appliers = &script.appliers;
654
+ let target = scope.target(call).ok()?;
655
+ let callee = target.callee?;
656
+ let handed: Vec<Binding<'a>> = handed(Arguments::of(call), &target)?
657
+ .into_iter()
658
+ .map(|operand| match operand.callee(&appliers.constants)? {
659
+ Callee::Binding(binding) => Some(binding),
660
+ Callee::Original(_) => None,
661
+ })
662
+ .collect::<Option<_>>()?;
663
+ let receives = |arguments: &[Binding<'a>]| scripts.iter().any(|list| list == arguments);
664
+ let caller = Name::anonymous(PROGRAM_CALLER.to_owned());
665
+ // The program is a value the handler holds, not a function the script defines.
666
+ let Ok(function) = script.function(callee) else {
667
+ return receives(&handed).then(|| (handed.len(), target.frames(caller)));
668
+ };
669
+ let (&program, arguments) = handed.split_first()?;
670
+ if script.function(Callee::Binding(program)).is_ok() || !receives(arguments) {
671
+ return None;
672
+ }
673
+ let name = appliers.name(callee);
674
+ let mut frames = Scope::new(name, &function, appliers)
675
+ .forwarder(function, Name::same(name.to_owned()))?;
676
+ frames.extend(target.frames(caller));
677
+ Some((arguments.len(), frames))
678
+ }
679
+ }
680
+
681
+ impl<'a> Visit<'a> for ProgramCalls<'a, '_> {
682
+ fn visit_function(&mut self, function: &Function<'a>, flags: ScopeFlags) {
683
+ let appliers = &self.script.appliers;
684
+ let js = appliers.js();
685
+ let function = js.lend(function, AstKind::as_function);
686
+ let body = Body::of(function);
687
+ let calls = calls_of(js, &body);
688
+ let scripts = script_arguments(&calls, &appliers.constants);
689
+ if !scripts.is_empty() {
690
+ let scope = Scope::new("", &body, appliers);
691
+ for call in calls {
692
+ if let Some(found) = self.program_call(&scope, call, &scripts) {
693
+ self.found.push(found);
694
+ }
695
+ }
696
+ }
697
+ walk::walk_function(self, function, flags);
698
+ }
699
+
700
+ fn visit_object_property(&mut self, property: &ObjectProperty<'a>) {
701
+ walk_property(self, property);
702
+ }
703
+
704
+ fn visit_method_definition(&mut self, method: &MethodDefinition<'a>) {
705
+ walk_method(self, method);
706
+ }
707
+ }
708
+
709
+ /// The argument lists of calls of constructed functions, `new Function(code)(a, b)`, among
710
+ /// `calls`, when every argument is a name.
711
+ fn script_arguments<'a>(
712
+ calls: &[&'a CallExpression<'a>],
713
+ constants: &Constants<'a>,
714
+ ) -> Vec<Vec<Binding<'a>>> {
715
+ calls
716
+ .iter()
717
+ .filter(|call| {
718
+ matches!(
719
+ call.callee.without_parentheses(),
720
+ Expression::NewExpression(_)
721
+ )
722
+ })
723
+ .filter_map(|call| {
724
+ call.arguments
725
+ .iter()
726
+ .map(|argument| constants.binding(argument.as_expression()?))
727
+ .collect::<Option<Vec<_>>>()
728
+ })
729
+ .filter(|arguments| !arguments.is_empty())
730
+ .collect()
731
+ }
732
+
622
733
  /// The function a dispatch loop calls for an opcode.
623
734
  struct Handler<'a, 'machine> {
624
735
  /// Call from the dispatch loop to this handler.
@@ -1015,7 +1126,20 @@ impl<'a> RunFunction<'a> {
1015
1126
  let Some(Statement::ReturnStatement(returned)) = body.only_statement() else {
1016
1127
  continue;
1017
1128
  };
1018
- let Some(Expression::CallExpression(call)) = &returned.argument else {
1129
+ let Some(argument) = returned.argument.as_ref() else {
1130
+ continue;
1131
+ };
1132
+ // Some builds assign the initial pc/key in a sequence before the call, as
1133
+ // `return Nu = 0, helper(selector, run, new Class(p), Nu, Nu, []);`. The call is
1134
+ // the sequence's last expression; the leading assignments only set pc/key.
1135
+ let mut value = argument.without_parentheses();
1136
+ if let Expression::SequenceExpression(sequence) = value {
1137
+ let Some(last) = sequence.expressions.last() else {
1138
+ continue;
1139
+ };
1140
+ value = last.without_parentheses();
1141
+ }
1142
+ let Expression::CallExpression(call) = value else {
1019
1143
  continue;
1020
1144
  };
1021
1145
  let Ok(target) = Scope::new("", &body, &script.appliers).target(call) else {
@@ -2025,7 +2149,7 @@ impl<'a, 's> Scope<'a, 's> {
2025
2149
  && property.kind == PropertyKind::Init
2026
2150
  && let Some(key) = ast::static_key_str(&property.key, property.computed)
2027
2151
  && let Some(frames) = self.forwarder(
2028
- function,
2152
+ Body::of(function),
2029
2153
  if property.computed {
2030
2154
  Name::anonymous(key.to_owned())
2031
2155
  } else {
@@ -2046,9 +2170,8 @@ impl<'a, 's> Scope<'a, 's> {
2046
2170
  /// later parameters. Accepts direct calls, array copies such as `(g = [f, b], (0, g[0])(a,
2047
2171
  /// g[1]))`, and call helpers. Extra parameters can act as locals. Allows local declarations
2048
2172
  /// before the call.
2049
- fn forwarder(&self, function: &'a Function<'a>, frame: Name) -> Option<Vec<Call>> {
2173
+ fn forwarder(&self, function: Body<'a>, frame: Name) -> Option<Vec<Call>> {
2050
2174
  let constants = &self.appliers.constants;
2051
- let function = Body::of(function);
2052
2175
  let parameters = function.parameters()?;
2053
2176
  let (first, rest) = parameters.split_first()?;
2054
2177
  let first = Binding::Symbol(*first);
@@ -2127,15 +2250,21 @@ fn is_inert<'a>(expression: &Expression<'a>, constants: &Constants<'a>) -> bool
2127
2250
  }
2128
2251
 
2129
2252
  /// Resolves the function produced by `callee` and checks whether a side-effect-free first operand
2130
- /// detaches its receiver. For example, `(0, f)(a)` calls `f` without a receiver.
2253
+ /// detaches its receiver. For example, `(0, f)(a)` calls `f` without a receiver. Some builds
2254
+ /// discard a read of a declared variable instead, as in `(local, f)(a)`.
2131
2255
  fn undetached<'b, 'a>(
2132
2256
  callee: &'b Expression<'a>,
2133
2257
  constants: &Constants<'a>,
2134
2258
  ) -> (&'b Expression<'a>, bool) {
2135
2259
  let callee = callee.without_parentheses();
2260
+ let discardable = |discarded: &Expression<'a>| {
2261
+ is_inert(discarded, constants)
2262
+ || matches!(discarded.without_parentheses(), Expression::Identifier(name)
2263
+ if constants.js.symbol(name).is_some())
2264
+ };
2136
2265
  if let Expression::SequenceExpression(sequence) = callee
2137
2266
  && let [discarded, last] = &sequence.expressions[..]
2138
- && is_inert(discarded, constants)
2267
+ && discardable(discarded)
2139
2268
  {
2140
2269
  return (last.without_parentheses(), true);
2141
2270
  }
@@ -2175,7 +2304,8 @@ impl<'a> Visit<'a> for Scope<'a, '_> {
2175
2304
  let inferred = format!("{path}.{name}");
2176
2305
  (inferred.clone(), inferred)
2177
2306
  };
2178
- let frames = |name: String| self.forwarder(function, Name::anonymous(name));
2307
+ let frames =
2308
+ |name: String| self.forwarder(Body::of(function), Name::anonymous(name));
2179
2309
  if let (Some(method), Some(plain)) = (frames(method), frames(inferred)) {
2180
2310
  self.forwarders
2181
2311
  .on_objects
@@ -2396,6 +2526,60 @@ mod tests {
2396
2526
  });
2397
2527
  }
2398
2528
 
2529
+ /// The runner calls the run function directly, or assigns pc/key in a sequence before
2530
+ /// calling it through a selector helper, as `return k = 0, j(3, run, new M(p), k, k, []);`.
2531
+ #[test]
2532
+ fn finds_the_runner_directly_or_through_a_sequence_and_helper() {
2533
+ for install in [
2534
+ "return run(new M(p),0,67,[]);",
2535
+ "var k;return k=0,j(3,run,new M(p),k,k,[]);",
2536
+ ] {
2537
+ let source = format!(
2538
+ "function j(s,f,a,b,c,d){{switch(5^s){{case 6:return f(a,b,c,d)}}}}\
2539
+ function run(m,pc,key,cells){{}}\
2540
+ function outer(O){{class M{{}} O.entry=function(p){{{install}}}}}"
2541
+ );
2542
+ with_script(&source, |script| {
2543
+ let found = RunFunction::installed(script).unwrap();
2544
+ assert_eq!(found.class, "M", "{source}");
2545
+ assert_eq!(script.appliers.name(found.name), "run", "{source}");
2546
+ });
2547
+ }
2548
+ }
2549
+
2550
+ /// A response handler runs a returned script as `new Function(code)(x, y)` and calls a
2551
+ /// returned program with the same arguments, here through a forwarder that copies them,
2552
+ /// directly, or through a forwarder detached by discarding a local. Calls passing other
2553
+ /// arguments, or a defined function, are not program calls, nor is a call in a function
2554
+ /// that runs no returned script.
2555
+ #[test]
2556
+ fn finds_the_handlers_call_of_a_returned_program() {
2557
+ let source = "var k=function(f,a,b){var c;return c=[a],f(c[0],b)};function g(){}\
2558
+ function s(){var r;r=M.c(`AAAA`,M),k(r,x,y)}\
2559
+ function h(){var p;if(z)new F(t)(x,y);else{p=M.c(t,M);(0,k)(p,x,y)}k(p,x,w);k(g,x,y)}\
2560
+ function d(){var p;if(z)new F(t)(x,y);else p(x,y)}\
2561
+ function l(){var p,q=[];if(z)new F(t)(x,y);else(q,k)(p,x,y)}";
2562
+ with_script(source, |script| {
2563
+ let mut calls = ProgramCalls {
2564
+ script,
2565
+ found: Vec::new(),
2566
+ };
2567
+ calls.visit_program(script.js().program);
2568
+ let [(forwarded, through), (direct, called), (detached, local)] = &calls.found[..]
2569
+ else {
2570
+ panic!("expected three program calls, found {}", calls.found.len());
2571
+ };
2572
+ assert_eq!((*forwarded, *direct, *detached), (2, 2, 2));
2573
+ assert_eq!(v8_names(through), ["k", PROGRAM_CALLER]);
2574
+ assert_eq!(v8_names(called), [PROGRAM_CALLER]);
2575
+ assert_eq!(v8_names(local), ["k", PROGRAM_CALLER]);
2576
+ let at = |position: u32| &source[position as usize..][..3];
2577
+ assert_eq!(at(through[0].site.jsc), "(c[");
2578
+ assert_eq!(at(through[1].site.jsc), "(p,");
2579
+ assert_eq!(at(called[0].site.jsc), "(x,");
2580
+ });
2581
+ }
2582
+
2399
2583
  /// Decodes `source` and analyzes it.
2400
2584
  fn with_script<T>(source: &str, read: impl for<'a> FnOnce(&Script<'a>) -> T) -> T {
2401
2585
  let decoded = deobfuscate::decode(source.to_owned()).unwrap();
@@ -309,16 +309,9 @@ impl Reader<'_> {
309
309
  }
310
310
  }
311
311
  let (pc, passed) = candidates::exactly_one(calls, "turnstile.render call")?;
312
- let function = index
313
- .entry_at_or_before(pc)
314
- .context("the render call is in no function")?;
315
- let arity = index
316
- .arity(function)
317
- .context("the function calling render is no closure")?;
318
312
  Ok(MethodCall {
319
313
  opcode: index.listing().instructions[&pc].opcode,
320
314
  passed,
321
- arity,
322
315
  })
323
316
  }
324
317