cfsolve 0.1.1 → 0.1.3

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 (404) hide show
  1. checksums.yaml +4 -4
  2. data/CHANGELOG.md +18 -0
  3. data/README.md +10 -9
  4. data/THIRD_PARTY_LICENSES/README.md +71 -254
  5. data/THIRD_PARTY_LICENSES/{derive_builder_macro-0.20.2/LICENSE-APACHE → bytecount-0.6.9/LICENSE.Apache2} +0 -1
  6. data/THIRD_PARTY_LICENSES/{darling-0.20.11/LICENSE → bytecount-0.6.9/LICENSE.MIT} +1 -3
  7. data/THIRD_PARTY_LICENSES/{ident_case-1.0.1/LICENSE → cobs-0.3.0/LICENSE-MIT} +1 -1
  8. data/THIRD_PARTY_LICENSES/cow-utils-0.1.3/LICENSE +21 -0
  9. data/THIRD_PARTY_LICENSES/{hashbrown-0.14.5 → embedded-io-0.4.0}/LICENSE-MIT +1 -1
  10. data/THIRD_PARTY_LICENSES/{ahash-0.8.12 → embedded-io-0.6.1}/LICENSE-MIT +1 -1
  11. data/THIRD_PARTY_LICENSES/{browserslist-data-0.1.4 → escape-simd-0.1.1}/LICENSE +1 -1
  12. data/THIRD_PARTY_LICENSES/escape-simd-0.1.1/NOTICE +62 -0
  13. data/THIRD_PARTY_LICENSES/json-escape-simd-3.1.3/LICENSE +21 -0
  14. data/THIRD_PARTY_LICENSES/{miette-7.6.0/LICENSE → json-escape-simd-3.1.3/LICENSE-APACHE} +0 -1
  15. data/THIRD_PARTY_LICENSES/json-escape-simd-3.1.3/NOTICE +62 -0
  16. data/THIRD_PARTY_LICENSES/memchr-2.8.3/UNLICENSE +24 -0
  17. data/THIRD_PARTY_LICENSES/{derive_builder_core-0.20.2 → nonmax-0.5.5}/LICENSE-APACHE +1 -2
  18. data/THIRD_PARTY_LICENSES/{dashmap-5.5.3/LICENSE → nonmax-0.5.5/LICENSE-MIT} +2 -4
  19. data/THIRD_PARTY_LICENSES/{rand-0.8.5 → num-bigint-0.5.1}/LICENSE-MIT +0 -1
  20. data/THIRD_PARTY_LICENSES/oxc-0.157.0/LICENSE +22 -0
  21. data/THIRD_PARTY_LICENSES/oxc-0.157.0/THIRD-PARTY-LICENSE +763 -0
  22. data/THIRD_PARTY_LICENSES/{browserslist-rs-0.19.0 → oxc-browserslist-5.0.1}/LICENSE +1 -0
  23. data/THIRD_PARTY_LICENSES/oxc_allocator-0.157.0/LICENSE +22 -0
  24. data/THIRD_PARTY_LICENSES/oxc_allocator-0.157.0/THIRD-PARTY-LICENSE +763 -0
  25. data/THIRD_PARTY_LICENSES/oxc_ast-0.157.0/LICENSE +22 -0
  26. data/THIRD_PARTY_LICENSES/oxc_ast-0.157.0/THIRD-PARTY-LICENSE +763 -0
  27. data/THIRD_PARTY_LICENSES/oxc_ast_macros-0.157.0/LICENSE +22 -0
  28. data/THIRD_PARTY_LICENSES/oxc_ast_macros-0.157.0/THIRD-PARTY-LICENSE +763 -0
  29. data/THIRD_PARTY_LICENSES/oxc_ast_visit-0.157.0/LICENSE +22 -0
  30. data/THIRD_PARTY_LICENSES/oxc_ast_visit-0.157.0/THIRD-PARTY-LICENSE +763 -0
  31. data/THIRD_PARTY_LICENSES/oxc_codegen-0.157.0/LICENSE +22 -0
  32. data/THIRD_PARTY_LICENSES/oxc_codegen-0.157.0/THIRD-PARTY-LICENSE +763 -0
  33. data/THIRD_PARTY_LICENSES/oxc_compat-0.157.0/LICENSE +22 -0
  34. data/THIRD_PARTY_LICENSES/oxc_compat-0.157.0/THIRD-PARTY-LICENSE +763 -0
  35. data/THIRD_PARTY_LICENSES/oxc_data_structures-0.157.0/LICENSE +22 -0
  36. data/THIRD_PARTY_LICENSES/oxc_data_structures-0.157.0/THIRD-PARTY-LICENSE +763 -0
  37. data/THIRD_PARTY_LICENSES/oxc_diagnostics-0.157.0/LICENSE +22 -0
  38. data/THIRD_PARTY_LICENSES/oxc_diagnostics-0.157.0/THIRD-PARTY-LICENSE +763 -0
  39. data/THIRD_PARTY_LICENSES/oxc_ecmascript-0.157.0/LICENSE +22 -0
  40. data/THIRD_PARTY_LICENSES/oxc_ecmascript-0.157.0/THIRD-PARTY-LICENSE +763 -0
  41. data/THIRD_PARTY_LICENSES/oxc_estree-0.157.0/LICENSE +22 -0
  42. data/THIRD_PARTY_LICENSES/oxc_estree-0.157.0/THIRD-PARTY-LICENSE +763 -0
  43. data/THIRD_PARTY_LICENSES/oxc_index-5.0.0/LICENSE +22 -0
  44. data/THIRD_PARTY_LICENSES/oxc_parser-0.157.0/LICENSE +22 -0
  45. data/THIRD_PARTY_LICENSES/oxc_parser-0.157.0/THIRD-PARTY-LICENSE +763 -0
  46. data/THIRD_PARTY_LICENSES/oxc_regular_expression-0.157.0/LICENSE +22 -0
  47. data/THIRD_PARTY_LICENSES/oxc_regular_expression-0.157.0/THIRD-PARTY-LICENSE +763 -0
  48. data/THIRD_PARTY_LICENSES/oxc_semantic-0.157.0/LICENSE +22 -0
  49. data/THIRD_PARTY_LICENSES/oxc_semantic-0.157.0/THIRD-PARTY-LICENSE +763 -0
  50. data/THIRD_PARTY_LICENSES/oxc_span-0.157.0/LICENSE +22 -0
  51. data/THIRD_PARTY_LICENSES/oxc_span-0.157.0/THIRD-PARTY-LICENSE +763 -0
  52. data/THIRD_PARTY_LICENSES/oxc_str-0.157.0/LICENSE +22 -0
  53. data/THIRD_PARTY_LICENSES/oxc_str-0.157.0/THIRD-PARTY-LICENSE +763 -0
  54. data/THIRD_PARTY_LICENSES/oxc_syntax-0.157.0/LICENSE +22 -0
  55. data/THIRD_PARTY_LICENSES/oxc_syntax-0.157.0/THIRD-PARTY-LICENSE +763 -0
  56. data/THIRD_PARTY_LICENSES/{fixedbitset-0.5.7 → postcard-1.1.3}/LICENSE-MIT +1 -1
  57. data/THIRD_PARTY_LICENSES/{bytes-str-0.2.7/LICENSE → self_cell-1.3.0/LICENSE-APACHE} +1 -2
  58. data/THIRD_PARTY_LICENSES/self_cell-1.3.0/LICENSE-GPLv2 +339 -0
  59. data/THIRD_PARTY_LICENSES/{darling_core-0.20.11 → smawk-0.3.3}/LICENSE +1 -1
  60. data/UPSTREAM.md +10 -8
  61. data/ext/cfsolve/Cargo.lock +534 -1727
  62. data/ext/cfsolve/Cargo.toml +4 -0
  63. data/ext/cfsolve/src/main.rs +1 -1
  64. data/lib/cfsolve/profiles/safari-26-ios/answers.json +2570 -1894
  65. data/lib/cfsolve/profiles/safari-26-ios/challenge-page-answers.json +1867 -1192
  66. data/lib/cfsolve/profiles/safari-26-ios.json +102 -156
  67. data/lib/cfsolve/version.rb +2 -2
  68. data/vendor/cfsolve/Cargo.lock +561 -1729
  69. data/vendor/cfsolve/Cargo.toml +26 -8
  70. data/vendor/cfsolve/README.md +4 -35
  71. data/vendor/cfsolve/examples/build_profile.rs +17 -15
  72. data/vendor/cfsolve/examples/capture_session.rs +37 -0
  73. data/vendor/cfsolve/examples/check_answers.rs +66 -0
  74. data/vendor/cfsolve/examples/compare_session.rs +189 -0
  75. data/vendor/cfsolve/examples/solver_profile.rs +84 -0
  76. data/vendor/cfsolve/examples/solver_smoke.rs +9 -8
  77. data/vendor/cfsolve/examples/stage2_snapshot.rs +6 -3
  78. data/vendor/cfsolve/examples/tls_echo.rs +3 -3
  79. data/vendor/cfsolve/examples/vm_snapshot.rs +32 -33
  80. data/vendor/cfsolve/profiles/safari-26-ios/answers.json +2570 -1894
  81. data/vendor/cfsolve/profiles/safari-26-ios/challenge-page-answers.json +1867 -1192
  82. data/vendor/cfsolve/profiles/safari-26-ios.json +102 -156
  83. data/vendor/cfsolve/scripts/capture_cssom.mjs +42 -0
  84. data/vendor/cfsolve/scripts/serve_cssom.py +111 -0
  85. data/vendor/cfsolve/src/bin/capture-proxy/main.rs +3 -2
  86. data/vendor/cfsolve/src/bin/challenge/cli.rs +8 -2
  87. data/vendor/cfsolve/src/bin/challenge/main.rs +7 -2
  88. data/vendor/cfsolve/src/capture/profile.rs +7 -18
  89. data/vendor/cfsolve/src/capture/proxy/tests.rs +1 -1
  90. data/vendor/cfsolve/src/capture/proxy.rs +44 -13
  91. data/vendor/cfsolve/src/capture/recorded.rs +42 -7
  92. data/vendor/cfsolve/src/capture/sessions.rs +4 -3
  93. data/vendor/cfsolve/src/capture/upstream.rs +1 -1
  94. data/vendor/cfsolve/src/challenge/codec.rs +4 -2
  95. data/vendor/cfsolve/src/challenge/expression.rs +161 -117
  96. data/vendor/cfsolve/src/challenge/installed/audit.rs +132 -0
  97. data/vendor/cfsolve/src/challenge/installed.rs +127 -269
  98. data/vendor/cfsolve/src/challenge/merge.rs +120 -80
  99. data/vendor/cfsolve/src/challenge/orchestrator.rs +57 -44
  100. data/vendor/cfsolve/src/challenge/payload.rs +175 -35
  101. data/vendor/cfsolve/src/challenge/program.rs +197 -178
  102. data/vendor/cfsolve/src/challenge/reduced_timing.rs +55 -40
  103. data/vendor/cfsolve/src/challenge/source.rs +151 -96
  104. data/vendor/cfsolve/src/challenge/state.rs +236 -122
  105. data/vendor/cfsolve/src/challenge/tally.rs +64 -50
  106. data/vendor/cfsolve/src/challenge.rs +1 -0
  107. data/vendor/cfsolve/src/deobfuscate/analysis/bindings.rs +187 -185
  108. data/vendor/cfsolve/src/deobfuscate/analysis/effects.rs +42 -51
  109. data/vendor/cfsolve/src/deobfuscate/analysis/hoisting.rs +147 -228
  110. data/vendor/cfsolve/src/deobfuscate/analysis/properties.rs +250 -425
  111. data/vendor/cfsolve/src/deobfuscate/analysis/unconditional.rs +79 -0
  112. data/vendor/cfsolve/src/deobfuscate/analysis.rs +259 -41
  113. data/vendor/cfsolve/src/deobfuscate/argument_arrays.rs +70 -73
  114. data/vendor/cfsolve/src/deobfuscate/arrow_blocks.rs +91 -104
  115. data/vendor/cfsolve/src/deobfuscate/ast.rs +383 -0
  116. data/vendor/cfsolve/src/deobfuscate/bitwise.rs +44 -54
  117. data/vendor/cfsolve/src/deobfuscate/blocks.rs +36 -29
  118. data/vendor/cfsolve/src/deobfuscate/call_helpers.rs +80 -131
  119. data/vendor/cfsolve/src/deobfuscate/control_flow.rs +239 -297
  120. data/vendor/cfsolve/src/deobfuscate/copy_propagation.rs +114 -135
  121. data/vendor/cfsolve/src/deobfuscate/dead_branches.rs +62 -61
  122. data/vendor/cfsolve/src/deobfuscate/dead_properties.rs +197 -214
  123. data/vendor/cfsolve/src/deobfuscate/dispatch.rs +238 -298
  124. data/vendor/cfsolve/src/deobfuscate/encoded_strings.rs +201 -205
  125. data/vendor/cfsolve/src/deobfuscate/function_lengths.rs +32 -38
  126. data/vendor/cfsolve/src/deobfuscate/helper_objects.rs +346 -536
  127. data/vendor/cfsolve/src/deobfuscate/hygiene.rs +197 -0
  128. data/vendor/cfsolve/src/deobfuscate/int32_helpers.rs +121 -155
  129. data/vendor/cfsolve/src/deobfuscate/literals.rs +116 -67
  130. data/vendor/cfsolve/src/deobfuscate/loops.rs +43 -43
  131. data/vendor/cfsolve/src/deobfuscate/memoized_strings.rs +127 -131
  132. data/vendor/cfsolve/src/deobfuscate/merged_functions.rs +262 -220
  133. data/vendor/cfsolve/src/deobfuscate/pipeline.rs +199 -244
  134. data/vendor/cfsolve/src/deobfuscate/register_arrays.rs +361 -322
  135. data/vendor/cfsolve/src/deobfuscate/removal.rs +83 -52
  136. data/vendor/cfsolve/src/deobfuscate/simplify.rs +147 -0
  137. data/vendor/cfsolve/src/deobfuscate/state_machines.rs +88 -110
  138. data/vendor/cfsolve/src/deobfuscate/statements.rs +228 -228
  139. data/vendor/cfsolve/src/deobfuscate/static_members.rs +46 -31
  140. data/vendor/cfsolve/src/deobfuscate/testing.rs +49 -59
  141. data/vendor/cfsolve/src/deobfuscate/unused_bindings.rs +92 -102
  142. data/vendor/cfsolve/src/deobfuscate.rs +15 -11
  143. data/vendor/cfsolve/src/embedding_page/extra_params.rs +23 -32
  144. data/vendor/cfsolve/src/embedding_page/page.rs +28 -2
  145. data/vendor/cfsolve/src/embedding_page/render_sample.rs +184 -147
  146. data/vendor/cfsolve/src/error.rs +40 -5
  147. data/vendor/cfsolve/src/fingerprint.rs +8 -2
  148. data/vendor/cfsolve/src/http/client.rs +9 -1
  149. data/vendor/cfsolve/src/http/requests.rs +2 -2
  150. data/vendor/cfsolve/src/js/ast.rs +479 -254
  151. data/vendor/cfsolve/src/js/objects.rs +9 -2
  152. data/vendor/cfsolve/src/lib.rs +1 -0
  153. data/vendor/cfsolve/src/listing/fold.rs +19 -92
  154. data/vendor/cfsolve/src/listing/query.rs +26 -291
  155. data/vendor/cfsolve/src/listing.rs +0 -1
  156. data/vendor/cfsolve/src/performance_clock.rs +20 -1
  157. data/vendor/cfsolve/src/profiling.rs +49 -0
  158. data/vendor/cfsolve/src/script.rs +35 -24
  159. data/vendor/cfsolve/src/session/challenge_page.rs +41 -21
  160. data/vendor/cfsolve/src/session/channel.rs +2 -2
  161. data/vendor/cfsolve/src/session/initial.rs +19 -10
  162. data/vendor/cfsolve/src/session/probes.rs +160 -125
  163. data/vendor/cfsolve/src/session/sink.rs +26 -1
  164. data/vendor/cfsolve/src/session/tests/challenge_page.rs +36 -1
  165. data/vendor/cfsolve/src/session/timing.rs +58 -53
  166. data/vendor/cfsolve/src/session/widget.rs +5 -6
  167. data/vendor/cfsolve/src/session.rs +1 -1
  168. data/vendor/cfsolve/src/solver.rs +3 -1
  169. data/vendor/cfsolve/src/stage2/analysis/analyze.rs +50 -33
  170. data/vendor/cfsolve/src/stage2/analysis/audit.rs +4 -2
  171. data/vendor/cfsolve/src/stage2/analysis/discovery.rs +61 -66
  172. data/vendor/cfsolve/src/stage2/analysis/envelope.rs +33 -22
  173. data/vendor/cfsolve/src/stage2/analysis/recognize.rs +3 -5
  174. data/vendor/cfsolve/src/stage2/analysis.rs +0 -1
  175. data/vendor/cfsolve/src/stage2/audit_globals.rs +378 -0
  176. data/vendor/cfsolve/src/stage2/benchmark.rs +66 -38
  177. data/vendor/cfsolve/src/stage2/call_stack.rs +1463 -1017
  178. data/vendor/cfsolve/src/stage2/challenge_page.rs +3 -2
  179. data/vendor/cfsolve/src/stage2/interaction/checkbox.rs +202 -150
  180. data/vendor/cfsolve/src/stage2/interaction/click.rs +2 -2
  181. data/vendor/cfsolve/src/stage2/interaction/native.rs +2 -1
  182. data/vendor/cfsolve/src/stage2/interaction/plan.rs +5 -7
  183. data/vendor/cfsolve/src/stage2/payload/recover.rs +56 -25
  184. data/vendor/cfsolve/src/stage2/probes/clock.rs +1 -3
  185. data/vendor/cfsolve/src/stage2/probes/ice.rs +11 -10
  186. data/vendor/cfsolve/src/stage2/probes/media.rs +47 -33
  187. data/vendor/cfsolve/src/stage2/probes/performance.rs +13 -8
  188. data/vendor/cfsolve/src/stage2/probes/rects.rs +12 -17
  189. data/vendor/cfsolve/src/stage2/probes/stack.rs +50 -103
  190. data/vendor/cfsolve/src/stage2/probes/websocket_echo.rs +17 -86
  191. data/vendor/cfsolve/src/stage2/probes.rs +0 -1
  192. data/vendor/cfsolve/src/stage2/queries.rs +50 -0
  193. data/vendor/cfsolve/src/stage2/records.rs +4 -13
  194. data/vendor/cfsolve/src/stage2/reference.json +1 -1
  195. data/vendor/cfsolve/src/stage2/reference.rs +98 -100
  196. data/vendor/cfsolve/src/stage2/registry.rs +41 -34
  197. data/vendor/cfsolve/src/stage2/replay.rs +182 -254
  198. data/vendor/cfsolve/src/stage2/stylesheets.rs +176 -0
  199. data/vendor/cfsolve/src/stage2/syntax.rs +88 -0
  200. data/vendor/cfsolve/src/stage2/trace.rs +152 -108
  201. data/vendor/cfsolve/src/stage2/vocabulary.rs +103 -403
  202. data/vendor/cfsolve/src/stage2.rs +4 -1
  203. data/vendor/cfsolve/src/vm/disassemble.rs +46 -13
  204. data/vendor/cfsolve/src/vm/dispatch.rs +93 -65
  205. data/vendor/cfsolve/src/vm/extract.rs +347 -250
  206. data/vendor/cfsolve/src/vm/interpret/access.rs +67 -68
  207. data/vendor/cfsolve/src/vm/interpret/builtin.rs +16 -63
  208. data/vendor/cfsolve/src/vm/interpret/call.rs +192 -51
  209. data/vendor/cfsolve/src/vm/interpret/compile.rs +643 -0
  210. data/vendor/cfsolve/src/vm/interpret/copies.rs +232 -120
  211. data/vendor/cfsolve/src/vm/interpret/evaluate/tests.rs +149 -40
  212. data/vendor/cfsolve/src/vm/interpret/evaluate.rs +189 -572
  213. data/vendor/cfsolve/src/vm/interpret/explore.rs +159 -46
  214. data/vendor/cfsolve/src/vm/interpret/formula.rs +131 -0
  215. data/vendor/cfsolve/src/vm/interpret/frozen.rs +169 -0
  216. data/vendor/cfsolve/src/vm/interpret/intrinsic.rs +414 -0
  217. data/vendor/cfsolve/src/vm/interpret/mix32.rs +189 -0
  218. data/vendor/cfsolve/src/vm/interpret/native_dispatch.rs +220 -0
  219. data/vendor/cfsolve/src/vm/interpret/pattern.rs +1736 -0
  220. data/vendor/cfsolve/src/vm/interpret/plan.rs +605 -330
  221. data/vendor/cfsolve/src/vm/interpret/register_helpers.rs +384 -0
  222. data/vendor/cfsolve/src/vm/interpret/run.rs +314 -54
  223. data/vendor/cfsolve/src/vm/interpret/semantics.rs +71 -46
  224. data/vendor/cfsolve/src/vm/interpret/setup.rs +80 -45
  225. data/vendor/cfsolve/src/vm/interpret/string_decoder.rs +482 -0
  226. data/vendor/cfsolve/src/vm/interpret.rs +16 -3
  227. data/vendor/cfsolve/src/vm/machine.rs +58 -47
  228. data/vendor/cfsolve/src/vm/output.rs +13 -5
  229. data/vendor/cfsolve/src/vm/packed_names.rs +311 -0
  230. data/vendor/cfsolve/src/vm/session.rs +197 -110
  231. data/vendor/cfsolve/src/vm/value.rs +35 -19
  232. data/vendor/cfsolve/src/vm.rs +3 -1
  233. data/vendor/cfsolve/vendor/btls-sys/Cargo.toml +3 -0
  234. data/vendor/cfsolve/vendor/btls-sys/build/main.rs +20 -0
  235. data/vendor/cfsolve/vendor/btls-sys/src/lib.rs +3 -0
  236. metadata +106 -183
  237. data/THIRD_PARTY_LICENSES/Inflector-0.11.4/LICENSE.md +0 -22
  238. data/THIRD_PARTY_LICENSES/arrayvec-0.7.6/LICENSE-MIT +0 -25
  239. data/THIRD_PARTY_LICENSES/ascii-1.1.0/LICENSE-APACHE +0 -201
  240. data/THIRD_PARTY_LICENSES/ascii-1.1.0/LICENSE-MIT +0 -22
  241. data/THIRD_PARTY_LICENSES/ast_node-5.0.0/LICENSE +0 -201
  242. data/THIRD_PARTY_LICENSES/better_scoped_tls-1.0.1/LICENSE +0 -201
  243. data/THIRD_PARTY_LICENSES/bitvec-1.0.1/LICENSE.txt +0 -21
  244. data/THIRD_PARTY_LICENSES/bstr-1.12.1/COPYING +0 -8
  245. data/THIRD_PARTY_LICENSES/bstr-1.12.1/LICENSE-MIT +0 -21
  246. data/THIRD_PARTY_LICENSES/cargo-platform-0.1.9/LICENSE-APACHE +0 -201
  247. data/THIRD_PARTY_LICENSES/cargo_metadata-0.19.2/LICENSE-MIT +0 -23
  248. data/THIRD_PARTY_LICENSES/darling_macro-0.20.11/LICENSE +0 -21
  249. data/THIRD_PARTY_LICENSES/debugid-0.8.0/LICENSE +0 -201
  250. data/THIRD_PARTY_LICENSES/derive_builder-0.20.2/LICENSE-MIT +0 -21
  251. data/THIRD_PARTY_LICENSES/derive_builder_core-0.20.2/LICENSE-MIT +0 -21
  252. data/THIRD_PARTY_LICENSES/derive_builder_macro-0.20.2/LICENSE-MIT +0 -21
  253. data/THIRD_PARTY_LICENSES/foldhash-0.1.5/LICENSE +0 -19
  254. data/THIRD_PARTY_LICENSES/from_variant-3.0.0/LICENSE +0 -201
  255. data/THIRD_PARTY_LICENSES/funty-2.0.0/LICENSE.txt +0 -21
  256. data/THIRD_PARTY_LICENSES/hashbrown-0.16.1/LICENSE-MIT +0 -25
  257. data/THIRD_PARTY_LICENSES/heck-0.5.0/LICENSE-APACHE +0 -201
  258. data/THIRD_PARTY_LICENSES/hermit-abi-0.5.2/LICENSE-APACHE +0 -201
  259. data/THIRD_PARTY_LICENSES/hermit-abi-0.5.2/LICENSE-MIT +0 -23
  260. data/THIRD_PARTY_LICENSES/hstr-3.0.3/LICENSE +0 -202
  261. data/THIRD_PARTY_LICENSES/if_chain-1.0.3/LICENSE-APACHE +0 -201
  262. data/THIRD_PARTY_LICENSES/if_chain-1.0.3/LICENSE-MIT +0 -25
  263. data/THIRD_PARTY_LICENSES/is-macro-0.3.7/LICENSE +0 -202
  264. data/THIRD_PARTY_LICENSES/itoa-1.0.17/LICENSE-MIT +0 -23
  265. data/THIRD_PARTY_LICENSES/jsonc-parser-0.26.3/LICENSE +0 -21
  266. data/THIRD_PARTY_LICENSES/lazy_static-1.5.0/LICENSE-APACHE +0 -201
  267. data/THIRD_PARTY_LICENSES/lazy_static-1.5.0/LICENSE-MIT +0 -25
  268. data/THIRD_PARTY_LICENSES/lru-0.16.2/LICENSE +0 -21
  269. data/THIRD_PARTY_LICENSES/memchr-2.7.6/COPYING +0 -3
  270. data/THIRD_PARTY_LICENSES/memchr-2.7.6/LICENSE-MIT +0 -21
  271. data/THIRD_PARTY_LICENSES/miette-derive-7.6.0/LICENSE +0 -229
  272. data/THIRD_PARTY_LICENSES/normpath-0.2.0/COPYRIGHT +0 -7
  273. data/THIRD_PARTY_LICENSES/normpath-0.2.0/LICENSE-MIT +0 -21
  274. data/THIRD_PARTY_LICENSES/normpath-0.2.0/LICENSE-THIRD-PARTY +0 -210
  275. data/THIRD_PARTY_LICENSES/num_cpus-1.17.0/LICENSE-APACHE +0 -201
  276. data/THIRD_PARTY_LICENSES/num_cpus-1.17.0/LICENSE-MIT +0 -20
  277. data/THIRD_PARTY_LICENSES/owo-colors-4.2.3/LICENSE +0 -21
  278. data/THIRD_PARTY_LICENSES/par-core-2.0.0/LICENSE +0 -202
  279. data/THIRD_PARTY_LICENSES/par-iter-2.0.0/LICENSE +0 -202
  280. data/THIRD_PARTY_LICENSES/path-clean-0.1.0/LICENSE-APACHE +0 -13
  281. data/THIRD_PARTY_LICENSES/path-clean-0.1.0/LICENSE-MIT +0 -18
  282. data/THIRD_PARTY_LICENSES/path-clean-1.0.1/LICENSE-APACHE +0 -13
  283. data/THIRD_PARTY_LICENSES/path-clean-1.0.1/LICENSE-MIT +0 -18
  284. data/THIRD_PARTY_LICENSES/pathdiff-0.2.3/LICENSE-APACHE +0 -201
  285. data/THIRD_PARTY_LICENSES/pathdiff-0.2.3/LICENSE-MIT +0 -23
  286. data/THIRD_PARTY_LICENSES/petgraph-0.7.1/LICENSE-APACHE +0 -201
  287. data/THIRD_PARTY_LICENSES/precomputed-map-0.2.0/LICENSE +0 -21
  288. data/THIRD_PARTY_LICENSES/preset_env_base-6.0.0/LICENSE +0 -201
  289. data/THIRD_PARTY_LICENSES/radium-0.7.0/LICENSE.txt +0 -21
  290. data/THIRD_PARTY_LICENSES/radix_fmt-1.0.0/LICENSE +0 -201
  291. data/THIRD_PARTY_LICENSES/rand-0.8.5/COPYRIGHT +0 -12
  292. data/THIRD_PARTY_LICENSES/rand-0.8.5/LICENSE-APACHE +0 -176
  293. data/THIRD_PARTY_LICENSES/rand_core-0.6.4/COPYRIGHT +0 -12
  294. data/THIRD_PARTY_LICENSES/rand_core-0.6.4/LICENSE-APACHE +0 -187
  295. data/THIRD_PARTY_LICENSES/rand_core-0.6.4/LICENSE-MIT +0 -26
  296. data/THIRD_PARTY_LICENSES/regress-0.10.5/LICENSE-APACHE +0 -201
  297. data/THIRD_PARTY_LICENSES/regress-0.10.5/LICENSE-MIT +0 -21
  298. data/THIRD_PARTY_LICENSES/ryu-1.0.22/LICENSE-APACHE +0 -176
  299. data/THIRD_PARTY_LICENSES/ryu-1.0.22/LICENSE-BOOST +0 -23
  300. data/THIRD_PARTY_LICENSES/scoped-tls-1.0.1/LICENSE-APACHE +0 -201
  301. data/THIRD_PARTY_LICENSES/scoped-tls-1.0.1/LICENSE-MIT +0 -25
  302. data/THIRD_PARTY_LICENSES/siphasher-0.3.11/COPYING +0 -7
  303. data/THIRD_PARTY_LICENSES/smallvec-1.15.1/LICENSE-APACHE +0 -201
  304. data/THIRD_PARTY_LICENSES/smartstring-1.0.1/LICENCE.md +0 -355
  305. data/THIRD_PARTY_LICENSES/st-map-0.2.4/LICENSE +0 -202
  306. data/THIRD_PARTY_LICENSES/static-map-macro-0.3.4/LICENSE +0 -202
  307. data/THIRD_PARTY_LICENSES/string_enum-1.0.2/LICENSE +0 -201
  308. data/THIRD_PARTY_LICENSES/strsim-0.11.1/LICENSE +0 -23
  309. data/THIRD_PARTY_LICENSES/swc-52.0.0/LICENSE +0 -201
  310. data/THIRD_PARTY_LICENSES/swc_allocator-4.0.1/LICENSE +0 -201
  311. data/THIRD_PARTY_LICENSES/swc_atoms-9.0.0/LICENSE +0 -201
  312. data/THIRD_PARTY_LICENSES/swc_common-18.0.1/LICENSE +0 -201
  313. data/THIRD_PARTY_LICENSES/swc_compiler_base-45.0.0/LICENSE +0 -201
  314. data/THIRD_PARTY_LICENSES/swc_config-3.1.2/LICENSE +0 -201
  315. data/THIRD_PARTY_LICENSES/swc_config_macro-1.0.1/LICENSE +0 -201
  316. data/THIRD_PARTY_LICENSES/swc_core-54.0.0/LICENSE +0 -201
  317. data/THIRD_PARTY_LICENSES/swc_ecma_ast-19.0.0/LICENSE +0 -201
  318. data/THIRD_PARTY_LICENSES/swc_ecma_codegen-21.0.0/LICENSE +0 -201
  319. data/THIRD_PARTY_LICENSES/swc_ecma_codegen_macros-2.0.2/LICENSE +0 -201
  320. data/THIRD_PARTY_LICENSES/swc_ecma_compat_bugfixes-39.0.0/LICENSE +0 -201
  321. data/THIRD_PARTY_LICENSES/swc_ecma_compat_common-30.0.0/LICENSE +0 -201
  322. data/THIRD_PARTY_LICENSES/swc_ecma_compat_es2015-39.0.0/LICENSE +0 -201
  323. data/THIRD_PARTY_LICENSES/swc_ecma_compat_es2016-35.0.0/LICENSE +0 -201
  324. data/THIRD_PARTY_LICENSES/swc_ecma_compat_es2017-35.0.0/LICENSE +0 -201
  325. data/THIRD_PARTY_LICENSES/swc_ecma_compat_es2018-36.0.0/LICENSE +0 -201
  326. data/THIRD_PARTY_LICENSES/swc_ecma_compat_es2019-35.0.0/LICENSE +0 -201
  327. data/THIRD_PARTY_LICENSES/swc_ecma_compat_es2020-37.0.0/LICENSE +0 -201
  328. data/THIRD_PARTY_LICENSES/swc_ecma_compat_es2021-35.0.0/LICENSE +0 -201
  329. data/THIRD_PARTY_LICENSES/swc_ecma_compat_es2022-37.0.0/LICENSE +0 -201
  330. data/THIRD_PARTY_LICENSES/swc_ecma_compat_es3-26.0.0/LICENSE +0 -201
  331. data/THIRD_PARTY_LICENSES/swc_ecma_ext_transforms-25.0.0/LICENSE +0 -201
  332. data/THIRD_PARTY_LICENSES/swc_ecma_hooks-0.3.0/LICENSE +0 -201
  333. data/THIRD_PARTY_LICENSES/swc_ecma_loader-18.0.0/LICENSE +0 -201
  334. data/THIRD_PARTY_LICENSES/swc_ecma_minifier-42.0.0/LICENSE +0 -201
  335. data/THIRD_PARTY_LICENSES/swc_ecma_parser-32.0.0/LICENSE +0 -201
  336. data/THIRD_PARTY_LICENSES/swc_ecma_preset_env-45.0.0/LICENSE +0 -201
  337. data/THIRD_PARTY_LICENSES/swc_ecma_transformer-6.0.0/LICENSE +0 -201
  338. data/THIRD_PARTY_LICENSES/swc_ecma_transforms-44.0.0/LICENSE +0 -201
  339. data/THIRD_PARTY_LICENSES/swc_ecma_transforms_base-35.0.0/LICENSE +0 -201
  340. data/THIRD_PARTY_LICENSES/swc_ecma_transforms_classes-35.0.0/LICENSE +0 -201
  341. data/THIRD_PARTY_LICENSES/swc_ecma_transforms_compat-40.0.0/LICENSE +0 -201
  342. data/THIRD_PARTY_LICENSES/swc_ecma_transforms_macros-1.0.1/LICENSE +0 -201
  343. data/THIRD_PARTY_LICENSES/swc_ecma_transforms_module-38.0.0/LICENSE +0 -201
  344. data/THIRD_PARTY_LICENSES/swc_ecma_transforms_optimization-37.0.0/LICENSE +0 -201
  345. data/THIRD_PARTY_LICENSES/swc_ecma_transforms_proposal-35.0.0/LICENSE +0 -201
  346. data/THIRD_PARTY_LICENSES/swc_ecma_transforms_react-38.0.0/LICENSE +0 -201
  347. data/THIRD_PARTY_LICENSES/swc_ecma_transforms_typescript-38.0.0/LICENSE +0 -201
  348. data/THIRD_PARTY_LICENSES/swc_ecma_usage_analyzer-27.0.0/LICENSE +0 -201
  349. data/THIRD_PARTY_LICENSES/swc_ecma_utils-25.0.0/LICENSE +0 -201
  350. data/THIRD_PARTY_LICENSES/swc_ecma_visit-19.0.0/LICENSE +0 -201
  351. data/THIRD_PARTY_LICENSES/swc_eq_ignore_macros-1.0.1/LICENSE +0 -201
  352. data/THIRD_PARTY_LICENSES/swc_error_reporters-20.0.0/LICENSE +0 -201
  353. data/THIRD_PARTY_LICENSES/swc_macros_common-1.0.1/LICENSE +0 -201
  354. data/THIRD_PARTY_LICENSES/swc_node_comments-18.0.0/LICENSE +0 -201
  355. data/THIRD_PARTY_LICENSES/swc_timer-1.0.0/LICENSE +0 -201
  356. data/THIRD_PARTY_LICENSES/swc_trace_macro-2.0.2/LICENSE +0 -201
  357. data/THIRD_PARTY_LICENSES/swc_transform_common-12.0.0/LICENSE +0 -201
  358. data/THIRD_PARTY_LICENSES/swc_visit-2.0.1/LICENSE +0 -201
  359. data/THIRD_PARTY_LICENSES/tap-1.0.1/LICENSE.txt +0 -21
  360. data/THIRD_PARTY_LICENSES/tracing-0.1.44/LICENSE +0 -25
  361. data/THIRD_PARTY_LICENSES/tracing-attributes-0.1.31/LICENSE +0 -25
  362. data/THIRD_PARTY_LICENSES/tracing-core-0.1.36/LICENSE +0 -25
  363. data/THIRD_PARTY_LICENSES/triomphe-0.1.15/LICENSE-APACHE +0 -201
  364. data/THIRD_PARTY_LICENSES/triomphe-0.1.15/LICENSE-MIT +0 -27
  365. data/THIRD_PARTY_LICENSES/unicode-width-0.1.14/LICENSE-APACHE +0 -201
  366. data/THIRD_PARTY_LICENSES/unicode-width-0.1.14/LICENSE-MIT +0 -25
  367. data/THIRD_PARTY_LICENSES/uuid-1.19.0/LICENSE-APACHE +0 -201
  368. data/THIRD_PARTY_LICENSES/uuid-1.19.0/LICENSE-MIT +0 -26
  369. data/THIRD_PARTY_LICENSES/vergen-9.0.6/LICENSE-APACHE +0 -201
  370. data/THIRD_PARTY_LICENSES/vergen-9.0.6/LICENSE-MIT +0 -25
  371. data/THIRD_PARTY_LICENSES/vergen-lib-0.1.6/LICENSE-APACHE +0 -201
  372. data/THIRD_PARTY_LICENSES/vergen-lib-0.1.6/LICENSE-MIT +0 -25
  373. data/THIRD_PARTY_LICENSES/wyz-0.5.1/LICENSE.txt +0 -21
  374. data/vendor/cfsolve/src/deobfuscate/analysis/globals.rs +0 -33
  375. data/vendor/cfsolve/src/deobfuscate/analysis/names.rs +0 -52
  376. data/vendor/cfsolve/src/listing/normalize.rs +0 -264
  377. data/vendor/cfsolve/src/stage2/analysis/outputs.rs +0 -327
  378. data/vendor/cfsolve/src/stage2/probes/stylesheets.rs +0 -249
  379. data/vendor/cfsolve/src/stage2/reference-expanded.json +0 -42
  380. data/vendor/cfsolve/src/stage2/session_names.rs +0 -470
  381. /data/THIRD_PARTY_LICENSES/{derive_builder-0.20.2 → cobs-0.3.0}/LICENSE-APACHE +0 -0
  382. /data/THIRD_PARTY_LICENSES/{compact_str-0.7.1 → compact_str-0.10.0}/LICENSE +0 -0
  383. /data/THIRD_PARTY_LICENSES/{ahash-0.8.12 → embedded-io-0.4.0}/LICENSE-APACHE +0 -0
  384. /data/THIRD_PARTY_LICENSES/{arrayvec-0.7.6 → embedded-io-0.6.1}/LICENSE-APACHE +0 -0
  385. /data/THIRD_PARTY_LICENSES/{normpath-0.2.0 → escape-simd-0.1.1}/LICENSE-APACHE +0 -0
  386. /data/THIRD_PARTY_LICENSES/{bstr-1.12.1 → itertools-0.15.0}/LICENSE-APACHE +0 -0
  387. /data/THIRD_PARTY_LICENSES/{petgraph-0.7.1 → itertools-0.15.0}/LICENSE-MIT +0 -0
  388. /data/THIRD_PARTY_LICENSES/{itoa-1.0.17 → itoa-1.0.19}/LICENSE-APACHE +0 -0
  389. /data/THIRD_PARTY_LICENSES/{camino-1.2.2 → itoa-1.0.19}/LICENSE-MIT +0 -0
  390. /data/THIRD_PARTY_LICENSES/{globset-0.4.18 → memchr-2.8.3}/COPYING +0 -0
  391. /data/THIRD_PARTY_LICENSES/{globset-0.4.18 → memchr-2.8.3}/LICENSE-MIT +0 -0
  392. /data/THIRD_PARTY_LICENSES/{camino-1.2.2 → num-bigint-0.5.1}/LICENSE-APACHE +0 -0
  393. /data/THIRD_PARTY_LICENSES/{swc_sourcemap-9.3.4 → oxc_sourcemap-9.0.0}/LICENSE +0 -0
  394. /data/THIRD_PARTY_LICENSES/{phf-0.11.3 → phf-0.14.0}/LICENSE +0 -0
  395. /data/THIRD_PARTY_LICENSES/{phf_generator-0.11.3 → phf_generator-0.14.0}/LICENSE +0 -0
  396. /data/THIRD_PARTY_LICENSES/{phf_macros-0.11.3 → phf_macros-0.14.0}/LICENSE +0 -0
  397. /data/THIRD_PARTY_LICENSES/{phf_shared-0.11.3 → phf_shared-0.14.0}/LICENSE +0 -0
  398. /data/THIRD_PARTY_LICENSES/{fixedbitset-0.5.7 → postcard-1.1.3}/LICENSE-APACHE +0 -0
  399. /data/THIRD_PARTY_LICENSES/{hashbrown-0.14.5 → smallvec-1.16.5}/LICENSE-APACHE +0 -0
  400. /data/THIRD_PARTY_LICENSES/{smallvec-1.15.1 → smallvec-1.16.5}/LICENSE-MIT +0 -0
  401. /data/THIRD_PARTY_LICENSES/{unicode-width-0.1.14 → unicode-segmentation-1.13.3}/COPYRIGHT +0 -0
  402. /data/THIRD_PARTY_LICENSES/{hashbrown-0.16.1 → unicode-segmentation-1.13.3}/LICENSE-APACHE +0 -0
  403. /data/THIRD_PARTY_LICENSES/{heck-0.5.0 → unicode-segmentation-1.13.3}/LICENSE-MIT +0 -0
  404. /data/THIRD_PARTY_LICENSES/{cargo-platform-0.1.9 → zmij_ecma-1.0.23}/LICENSE-MIT +0 -0
@@ -14,61 +14,68 @@
14
14
 
15
15
  use std::collections::{HashMap, HashSet};
16
16
  use std::mem;
17
+ use std::sync::Arc;
17
18
 
18
19
  use anyhow::{Context, Result, bail};
19
- use serde::{Deserialize, Serialize};
20
- use swc_core::common::{BytePos, Mark, Span, Spanned, SyntaxContext};
21
- use swc_core::ecma::ast::{
22
- AssignExpr, AssignOp, AssignTarget, BinaryOp, BlockStmt, CallExpr, Callee, Class, ClassDecl,
23
- ClassMember, Decl, Expr, FnDecl, FnExpr, Function, Id, Ident, MemberExpr, MemberProp, NewExpr,
24
- ObjectLit, Pat, Program, Prop, ReturnStmt, SimpleAssignTarget, Stmt, SwitchCase, SwitchStmt,
25
- ThrowStmt, TryStmt, UnaryOp, VarDeclarator,
20
+ use oxc::ast::AstKind;
21
+ use oxc::ast::ast::{
22
+ Argument, ArrayExpression, ArrayExpressionElement, AssignmentExpression, AssignmentTarget,
23
+ BindingPattern, CallExpression, Class, ClassElement, Expression, FormalParameter, Function,
24
+ MemberExpression, MethodDefinition, MethodDefinitionKind, NewExpression, ObjectExpression,
25
+ ObjectProperty, ObjectPropertyKind, PropertyKind, Statement, SwitchCase, SwitchStatement,
26
+ ThrowStatement, TryStatement, VariableDeclarator,
26
27
  };
27
- use swc_core::ecma::visit::{Visit, VisitWith};
28
+ use oxc::ast_visit::{Visit, walk};
29
+ use oxc::semantic::SymbolId;
30
+ use oxc::span::{GetSpan, Span};
31
+ use oxc::syntax::operator::{AssignmentOperator, BinaryOperator, UnaryOperator};
32
+ use oxc::syntax::scope::ScopeFlags;
33
+ use serde::{Deserialize, Serialize};
28
34
 
35
+ use super::syntax::{
36
+ assigned_member, is_optional_call, member, plain_parameter, walk_method, walk_property,
37
+ };
29
38
  use crate::deobfuscate::{self, Deobfuscated};
30
39
  use crate::engine::{self, Engine, Lines, StackFrame, V8_STACK_LIMIT};
31
- use crate::js::ast;
40
+ use crate::js::ast::{self, Binding, ParsedScript};
32
41
  use crate::{candidates, js};
33
42
 
34
43
  /// Maps VM dispatch cases to opcodes at their original source positions. Deobfuscation resolves
35
44
  /// case labels while preserving spans. Recovery uses the resolved labels to find each opcode's
36
45
  /// case in the original script.
37
- #[derive(Clone, Debug, Default)]
38
- pub struct CaseOpcodes(HashMap<(u32, u32), u8>);
39
-
40
- /// Returns a span's offset from the parse start, stable across parses of the same script.
41
- fn offsets(span: Span, start: BytePos) -> (u32, u32) {
42
- (span.lo.0 - start.0, span.hi.0 - start.0)
46
+ #[derive(Clone, Default)]
47
+ pub struct CaseOpcodes {
48
+ opcodes: HashMap<Span, u8>,
49
+ /// The decoded program captured during deobfuscation, with the source it was decoded from,
50
+ /// shared so the cases stay cheap to clone.
51
+ decoded: Option<Arc<ParsedScript>>,
43
52
  }
44
53
 
45
54
  /// Deobfuscates `source` and maps its dispatch cases' original positions to their opcodes.
46
55
  pub fn deobfuscate_with_cases(source: String) -> Result<(Deobfuscated, CaseOpcodes)> {
47
- struct Cases {
48
- start: BytePos,
49
- opcodes: CaseOpcodes,
50
- }
51
- impl Visit for Cases {
52
- fn visit_switch_case(&mut self, case: &SwitchCase) {
56
+ // Spans are stable across parses of the same script.
57
+ struct Cases(HashMap<Span, u8>);
58
+ impl<'a> Visit<'a> for Cases {
59
+ fn visit_switch_case(&mut self, case: &SwitchCase<'a>) {
53
60
  if let Some(test) = &case.test
54
61
  && let Some(opcode) = ast::index_literal(test)
55
62
  && let Ok(opcode) = u8::try_from(opcode)
56
63
  {
57
- self.opcodes
58
- .0
59
- .insert(offsets(case.span, self.start), opcode);
64
+ self.0.insert(case.span, opcode);
60
65
  }
61
- case.visit_children_with(self);
66
+ walk::walk_switch_case(self, case);
62
67
  }
63
68
  }
64
- deobfuscate::deobfuscate_with(source, |program, start| {
65
- let mut cases = Cases {
66
- start,
67
- opcodes: CaseOpcodes::default(),
68
- };
69
- program.visit_with(&mut cases);
70
- cases.opcodes
71
- })
69
+ let (deobfuscated, opcodes, decoded) = deobfuscate::deobfuscate_capturing(source, |program| {
70
+ let mut cases = Cases(HashMap::new());
71
+ cases.visit_program(program);
72
+ Ok(cases.0)
73
+ })?;
74
+ let cases = CaseOpcodes {
75
+ opcodes,
76
+ decoded: Some(Arc::new(decoded)),
77
+ };
78
+ Ok((deobfuscated, cases))
72
79
  }
73
80
 
74
81
  /// Engine-specific function name and call position, measured from the script start in
@@ -153,14 +160,23 @@ pub struct MethodCall {
153
160
  pub arity: usize,
154
161
  }
155
162
 
156
- /// Call path to `new Error()` in the stack probe. The listener enters the probe function, which
157
- /// calls a closure that constructs the error.
163
+ /// Call path to `new Error()` in the stack probe. The probe function calls a closure that
164
+ /// constructs the error.
158
165
  #[derive(Clone, Copy, Debug, Deserialize, Serialize)]
159
166
  pub struct ProbeCalls {
160
167
  /// The opcode that constructs `new Error()`.
161
168
  pub construct: u8,
162
- /// How many parameters the probe function declares.
163
- pub arity: usize,
169
+ }
170
+
171
+ /// The callback that last resumed the VM before the stack probe, whose listener is the probe's
172
+ /// outermost frame. Chrome and Safari captures show both; a Worker message is more common.
173
+ #[derive(Clone, Copy, Debug, PartialEq, Eq)]
174
+ pub enum Resumption {
175
+ /// A timer, whose callback receives no arguments. V8 leaves its listener anonymous.
176
+ Timer,
177
+ /// A Worker's message event, which passes the event. V8 names the listener by its
178
+ /// receiver, `Worker.<anonymous>`.
179
+ WorkerMessage,
164
180
  }
165
181
 
166
182
  /// Recovers callback frames for a VM function with `arity` parameters and error-construction
@@ -179,15 +195,24 @@ pub fn recover(source: &str, cases: &CaseOpcodes, construct: u8, arity: usize) -
179
195
  })
180
196
  }
181
197
 
182
- /// Recovers frames for the stack probe. The VM executes closures in its dispatch loop without
183
- /// JavaScript calls, so frames stop at the listener that entered the probe. V8 retains only the
184
- /// innermost ten frames.
185
- pub fn recover_probe(source: &str, cases: &CaseOpcodes, calls: ProbeCalls) -> Result<Geometry> {
198
+ /// Recovers frames for the stack probe, run after `resumed`. The VM executes closures in its
199
+ /// dispatch loop without JavaScript calls, so frames stop at the listener that resumed it. V8
200
+ /// retains only the innermost ten frames.
201
+ pub fn recover_probe(
202
+ source: &str,
203
+ cases: &CaseOpcodes,
204
+ calls: ProbeCalls,
205
+ resumed: Resumption,
206
+ ) -> Result<Geometry> {
186
207
  geometry(source, cases, |machine| {
187
208
  // The probe registers an exception handler, so its instructions dispatch from the
188
209
  // guarded loop.
189
210
  let mut chain = machine.construction(calls.construct, true)?;
190
- chain.frames.extend(machine.listener(calls.arity, "")?);
211
+ let (arity, name) = match resumed {
212
+ Resumption::Timer => (0, ""),
213
+ Resumption::WorkerMessage => (1, "Worker.<anonymous>"),
214
+ };
215
+ chain.frames.extend(machine.listener(arity, name)?);
191
216
  chain.frames.truncate(V8_STACK_LIMIT);
192
217
  Ok(chain)
193
218
  })
@@ -228,71 +253,79 @@ pub struct DispatchSummary {
228
253
 
229
254
  /// Summarizes dispatch loops called by `run`, including whether each case resolves to a function.
230
255
  pub fn dispatch_summary(source: &str, cases: &CaseOpcodes) -> Result<Vec<DispatchSummary>> {
231
- deobfuscate::read_decoded(source.to_owned(), |program, start| {
232
- let machine = Machine::new(program, start, cases)?;
233
- let script = &machine.script;
234
- let mut summaries = Vec::new();
235
- for dispatch_loop in &machine.loops {
236
- let function = script.function(&dispatch_loop.name)?;
237
- let scope = Scope::new(&dispatch_loop.name.0, function, &script.appliers);
238
- let mut opcodes = 0;
239
- let mut unresolved = Vec::new();
240
- for case in cases_of(function) {
241
- let Some(&opcode) = cases.0.get(&offsets(case.span, start)) else {
242
- continue;
243
- };
244
- opcodes += 1;
245
- let resolved = scope.target(&case.call).is_ok_and(|target| {
246
- target
247
- .callee
248
- .is_some_and(|callee| script.function(&callee).is_ok())
249
- });
250
- if !resolved {
251
- unresolved.push(opcode);
252
- }
253
- }
254
- let frames = dispatch_loop.call.frames(Name::same("run".to_owned()));
255
- summaries.push(DispatchSummary {
256
- function: dispatch_loop.name.0.to_string(),
257
- guarded: dispatch_loop.guarded,
258
- frames: frames.into_iter().map(|call| call.name.v8).collect(),
259
- opcodes,
260
- unresolved,
256
+ let decoded = deobfuscate::decode(source.to_owned())?;
257
+ let machine = Machine::new(decoded.script(), cases)?;
258
+ let script = &machine.script;
259
+ let mut summaries = Vec::new();
260
+ for dispatch_loop in &machine.loops {
261
+ let name = script.appliers.name(dispatch_loop.name);
262
+ let function = script.function(dispatch_loop.name)?;
263
+ let scope = Scope::new(name, &function, &script.appliers);
264
+ let mut opcodes = 0;
265
+ let mut unresolved = Vec::new();
266
+ for case in cases_of(script.js(), &function) {
267
+ let Some(&opcode) = cases.opcodes.get(&case.span) else {
268
+ continue;
269
+ };
270
+ opcodes += 1;
271
+ let resolved = scope.target(case.call).is_ok_and(|target| {
272
+ target
273
+ .callee
274
+ .is_some_and(|callee| script.function(callee).is_ok())
261
275
  });
276
+ if !resolved {
277
+ unresolved.push(opcode);
278
+ }
262
279
  }
263
- Ok(summaries)
264
- })
280
+ let frames = dispatch_loop.call.frames(Name::same("run".to_owned()));
281
+ summaries.push(DispatchSummary {
282
+ function: name.to_owned(),
283
+ guarded: dispatch_loop.guarded,
284
+ frames: frames.into_iter().map(|call| call.name.v8).collect(),
285
+ opcodes,
286
+ unresolved,
287
+ });
288
+ }
289
+ Ok(summaries)
265
290
  }
266
291
 
267
292
  /// Parses `source` and places the frames `recover` finds in it as each engine reports them.
268
293
  fn geometry(
269
294
  source: &str,
270
295
  cases: &CaseOpcodes,
271
- mut recover: impl FnMut(&Machine<'_>) -> Result<Chain>,
296
+ recover: impl FnOnce(&Machine<'_, '_>) -> Result<Chain>,
272
297
  ) -> Result<Geometry> {
273
- deobfuscate::read_decoded(source.to_owned(), |program, start| {
274
- let Chain { frames, reflected } = recover(&Machine::new(program, start, cases)?)?;
275
- let frame = |function: String, at: BytePos| -> Result<Frame> {
276
- let offset = (at.0 - start.0) as usize;
277
- let prefix = source.get(..offset).context("invalid source byte offset")?;
278
- let (line, column) = engine::line_and_column(prefix, Lines::Script);
279
- Ok(Frame {
280
- function,
281
- line,
282
- column,
283
- })
284
- };
285
- let mut geometry = Geometry {
286
- frames: Vec::new(),
287
- jsc_frames: Vec::new(),
288
- reflected,
289
- };
290
- for Call { name, site } in frames {
291
- geometry.frames.push(frame(name.v8, site.v8)?);
292
- geometry.jsc_frames.push(frame(name.jsc, site.jsc)?);
298
+ // Reuse the decoded program `cases` captured if it comes from the same source.
299
+ let Chain { frames, reflected } = match &cases.decoded {
300
+ Some(decoded) if decoded.script().source == source => {
301
+ recover(&Machine::new(decoded.script(), cases)?)?
293
302
  }
294
- Ok(geometry)
295
- })
303
+ _ => recover(&Machine::new(
304
+ deobfuscate::decode(source.to_owned())?.script(),
305
+ cases,
306
+ )?)?,
307
+ };
308
+ let frame = |function: String, at: u32| -> Result<Frame> {
309
+ let prefix = source
310
+ .get(..at as usize)
311
+ .context("invalid source byte offset")?;
312
+ let (line, column) = engine::line_and_column(prefix, Lines::Script);
313
+ Ok(Frame {
314
+ function,
315
+ line,
316
+ column,
317
+ })
318
+ };
319
+ let mut geometry = Geometry {
320
+ frames: Vec::new(),
321
+ jsc_frames: Vec::new(),
322
+ reflected,
323
+ };
324
+ for Call { name, site } in frames {
325
+ geometry.frames.push(frame(name.v8, site.v8)?);
326
+ geometry.jsc_frames.push(frame(name.jsc, site.jsc)?);
327
+ }
328
+ Ok(geometry)
296
329
  }
297
330
 
298
331
  /// Calls recovered from the innermost frame outward.
@@ -326,15 +359,16 @@ impl Name {
326
359
  }
327
360
  }
328
361
 
329
- /// A call site's position for each engine: see [`call_position`] and [`arguments_position`].
362
+ /// A call site's byte offset for each engine: see [`call_position`] and
363
+ /// [`arguments_position`].
330
364
  #[derive(Clone, Copy, Debug)]
331
365
  struct Site {
332
- v8: BytePos,
333
- jsc: BytePos,
366
+ v8: u32,
367
+ jsc: u32,
334
368
  }
335
369
 
336
370
  impl Site {
337
- fn new(call: &CallExpr) -> Self {
371
+ fn new(call: &CallExpression<'_>) -> Self {
338
372
  Self {
339
373
  v8: call_position(call),
340
374
  jsc: arguments_position(call),
@@ -348,45 +382,65 @@ struct Call {
348
382
  site: Site,
349
383
  }
350
384
 
385
+ /// A function that call resolution identifies.
386
+ #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
387
+ enum Callee<'a> {
388
+ /// A function or value held by a binding, or by a global.
389
+ Binding(Binding<'a>),
390
+ /// An original function extracted from a merged function, indexed into
391
+ /// [`Appliers::originals`].
392
+ Original(usize),
393
+ }
394
+
395
+ impl Callee<'_> {
396
+ /// The parameter or local `symbol`.
397
+ fn symbol(symbol: SymbolId) -> Self {
398
+ Self::Binding(Binding::Symbol(symbol))
399
+ }
400
+ }
401
+
351
402
  /// The VM dispatch method, its runner, and listeners that wrap the runner for each closure
352
403
  /// parameter count.
353
- struct Machine<'script> {
354
- script: Script,
355
- dispatch: DispatchMethod,
404
+ struct Machine<'a, 'cases> {
405
+ script: Script<'a>,
406
+ dispatch: DispatchMethod<'a>,
356
407
  /// The dispatch loops `run` calls.
357
- loops: Vec<DispatchLoop>,
358
- cases: &'script CaseOpcodes,
359
- start: BytePos,
408
+ loops: Vec<DispatchLoop<'a>>,
409
+ cases: &'cases CaseOpcodes,
360
410
  runner: Call,
361
- listeners: Vec<Invocation>,
411
+ listeners: Vec<Invocation<'a>>,
362
412
  }
363
413
 
364
- impl<'script> Machine<'script> {
365
- fn new(program: &Program, start: BytePos, cases: &'script CaseOpcodes) -> Result<Self> {
366
- let mut script = Script::new(program);
414
+ impl<'a, 'cases> Machine<'a, 'cases> {
415
+ fn new(js: ast::Script<'a>, cases: &'cases CaseOpcodes) -> Result<Self> {
416
+ let mut script = Script::new(js);
367
417
  let classes = mem::take(&mut script.classes);
368
418
  // The runner passes the closure's program counter, key, and arguments to `run`,
369
419
  // copying arguments when required by the VM function.
370
420
  let mut runners = Vec::new();
371
421
  for (name, function) in &script.functions {
372
- for call in calls_of(function) {
373
- let calls_run = call
374
- .callee
375
- .as_expr()
376
- .and_then(|callee| callee.as_member())
377
- .is_some_and(|member| ast::member_str(&member.prop) == Some("run"));
378
- if calls_run && call.args.len() == 3 && call.args[2].expr.is_cond() {
379
- runners.push((name, call));
422
+ for call in calls_of(js, function) {
423
+ let calls_run = member(&call.callee)
424
+ .is_some_and(|member| ast::member_str(member) == Some("run"));
425
+ if calls_run
426
+ && call.arguments.len() == 3
427
+ && matches!(
428
+ ast::argument_expression(&call.arguments[2]),
429
+ Expression::ConditionalExpression(_)
430
+ )
431
+ {
432
+ runners.push((*name, call));
380
433
  }
381
434
  }
382
435
  }
383
436
  let (runner, run_call) = candidates::exactly_one(runners, "closure-to-VM runner call")?;
437
+ let runner = Callee::Binding(runner);
384
438
  let mut listeners = Listeners {
385
439
  runner,
386
440
  appliers: &script.appliers,
387
441
  found: Vec::new(),
388
442
  };
389
- program.visit_with(&mut listeners);
443
+ listeners.visit_program(js.program);
390
444
  let listeners: Vec<Invocation> = listeners.found.into_iter().collect::<Result<_>>()?;
391
445
  let dispatches = classes.into_iter().filter_map(|dispatch| {
392
446
  let loops = dispatch_loops(&script, &dispatch.run);
@@ -395,44 +449,44 @@ impl<'script> Machine<'script> {
395
449
  let (dispatch, loops) = candidates::exactly_one(dispatches, "VM dispatch method")?;
396
450
  Ok(Self {
397
451
  runner: Call {
398
- name: Name::same(runner.0.to_string()),
399
- site: Site::new(&run_call),
452
+ name: Name::same(script.appliers.name(runner).to_owned()),
453
+ site: Site::new(run_call),
400
454
  },
401
455
  listeners,
402
456
  dispatch,
403
457
  loops,
404
458
  script,
405
459
  cases,
406
- start,
407
460
  })
408
461
  }
409
462
 
410
463
  /// Finds the handler for `opcode` in the dispatch loop with or without exception handling.
411
- fn handler(&self, opcode: u8, guarded: bool) -> Result<Handler<'_>> {
464
+ fn handler(&self, opcode: u8, guarded: bool) -> Result<Handler<'a, '_>> {
465
+ let appliers = &self.script.appliers;
412
466
  for dispatch_loop in &self.loops {
413
467
  if dispatch_loop.guarded != guarded {
414
468
  continue;
415
469
  }
416
- let function = self.script.function(&dispatch_loop.name)?;
417
- let Some(case) = cases_of(function)
470
+ let function = self.script.function(dispatch_loop.name)?;
471
+ let Some(case) = cases_of(self.script.js(), &function)
418
472
  .into_iter()
419
- .find(|case| self.cases.0.get(&offsets(case.span, self.start)) == Some(&opcode))
473
+ .find(|case| self.cases.opcodes.get(&case.span) == Some(&opcode))
420
474
  else {
421
475
  continue;
422
476
  };
423
- let scope = Scope::new(&dispatch_loop.name.0, function, &self.script.appliers);
424
- let dispatch = scope.target(&case.call)?;
477
+ let scope = Scope::new(appliers.name(dispatch_loop.name), &function, appliers);
478
+ let dispatch = scope.target(case.call)?;
425
479
  let handler = dispatch
426
480
  .callee
427
- .clone()
428
481
  .with_context(|| format!("opcode {opcode}'s dispatch calls no named handler"))?;
482
+ let name = appliers.name(handler);
429
483
  let frame = Name {
430
484
  v8: if dispatch.method {
431
- format!("{}.{}", self.dispatch.class, handler.0)
485
+ format!("{}.{name}", self.dispatch.class)
432
486
  } else {
433
- handler.0.to_string()
487
+ name.to_owned()
434
488
  },
435
- jsc: handler.0.to_string(),
489
+ jsc: name.to_owned(),
436
490
  };
437
491
  return Ok(Handler {
438
492
  dispatch,
@@ -445,17 +499,14 @@ impl<'script> Machine<'script> {
445
499
  }
446
500
 
447
501
  /// Appends frames from the call to `handler` through the dispatch loop, `run`, and the runner.
448
- fn entered(&self, handler: &Handler<'_>, mut frames: Vec<Call>) -> Vec<Call> {
502
+ fn entered(&self, handler: &Handler<'a, '_>, mut frames: Vec<Call>) -> Vec<Call> {
449
503
  let DispatchMethod { class, key, .. } = &self.dispatch;
450
504
  let dispatch_loop = handler.dispatch_loop;
451
- frames.extend(
452
- handler
453
- .dispatch
454
- .frames(Name::same(dispatch_loop.name.0.to_string())),
455
- );
505
+ let name = self.script.appliers.name(dispatch_loop.name);
506
+ frames.extend(handler.dispatch.frames(Name::same(name.to_owned())));
456
507
  frames.extend(dispatch_loop.call.frames(Name {
457
508
  v8: format!("{class}.run"),
458
- jsc: key.clone().unwrap_or_default(),
509
+ jsc: key.unwrap_or_default().to_owned(),
459
510
  }));
460
511
  frames.push(self.runner.clone());
461
512
  frames
@@ -466,21 +517,20 @@ impl<'script> Machine<'script> {
466
517
  /// arguments.
467
518
  fn construction(&self, opcode: u8, guarded: bool) -> Result<Chain> {
468
519
  let handler = self.handler(opcode, guarded)?;
469
- let function = self.script.function(&handler.name)?;
470
- let scope = Scope::new(&handler.name.0, function, &self.script.appliers);
520
+ let appliers = &self.script.appliers;
521
+ let function = self.script.function(handler.name)?;
522
+ let scope = Scope::new(appliers.name(handler.name), &function, appliers);
471
523
  let mut found = Vec::new();
472
- for call in calls_of(function) {
473
- let target = scope.target(&call)?;
524
+ for call in calls_of(self.script.js(), &function) {
525
+ let target = scope.target(call)?;
474
526
  // Find `Reflect.construct` in a binding or array slot, called directly or through a
475
527
  // helper.
476
528
  let named = target
477
529
  .callee
478
- .as_ref()
479
- .is_some_and(|callee| self.script.constructs.contains(callee));
530
+ .is_some_and(|callee| self.script.constructs.contains(&callee));
480
531
  let slotted = target
481
532
  .slot
482
- .as_ref()
483
- .is_some_and(|slot| self.script.construct_slots.contains(slot));
533
+ .is_some_and(|slot| self.script.construct_slots.contains(&slot));
484
534
  if named || slotted {
485
535
  found.push(target.frames(handler.frame.clone()));
486
536
  }
@@ -489,23 +539,26 @@ impl<'script> Machine<'script> {
489
539
  if !reflected {
490
540
  #[derive(Default)]
491
541
  struct News(Vec<Site>);
492
- impl Visit for News {
493
- fn visit_function(&mut self, _: &Function) {}
494
- fn visit_class(&mut self, _: &Class) {}
542
+ impl<'a> Visit<'a> for News {
543
+ fn visit_function(&mut self, _: &Function<'a>, _: ScopeFlags) {}
544
+ fn visit_class(&mut self, _: &Class<'a>) {}
545
+ fn visit_object_property(&mut self, property: &ObjectProperty<'a>) {
546
+ walk_property(self, property);
547
+ }
495
548
  // Ignore guard exceptions; they do not produce the handler's constructed value.
496
- fn visit_throw_stmt(&mut self, _: &ThrowStmt) {}
497
- fn visit_new_expr(&mut self, construction: &NewExpr) {
498
- if construction.args.as_ref().is_none_or(Vec::is_empty) {
549
+ fn visit_throw_statement(&mut self, _: &ThrowStatement<'a>) {}
550
+ fn visit_new_expression(&mut self, construction: &NewExpression<'a>) {
551
+ if construction.arguments.is_empty() {
499
552
  self.0.push(Site {
500
- v8: construction.span.lo,
501
- jsc: construction.callee.span().hi,
553
+ v8: construction.span.start,
554
+ jsc: construction.callee.span().end,
502
555
  });
503
556
  }
504
- construction.visit_children_with(self);
557
+ walk::walk_new_expression(self, construction);
505
558
  }
506
559
  }
507
560
  let mut news = News::default();
508
- function.body.visit_with(&mut news);
561
+ function.visit(&mut news);
509
562
  for site in news.0 {
510
563
  found.push(vec![Call {
511
564
  name: handler.frame.clone(),
@@ -519,7 +572,7 @@ impl<'script> Machine<'script> {
519
572
  let Some(frames) = found.pop() else {
520
573
  bail!(
521
574
  "missing original function {} with the needed shape",
522
- handler.name.0
575
+ appliers.name(handler.name)
523
576
  );
524
577
  };
525
578
  Ok(Chain {
@@ -532,13 +585,14 @@ impl<'script> Machine<'script> {
532
585
  /// passes the method, receiver, and `passed` arguments to a native apply forwarder.
533
586
  fn method_call(&self, opcode: u8, passed: usize, guarded: bool) -> Result<Vec<Call>> {
534
587
  let handler = self.handler(opcode, guarded)?;
535
- let function = self.script.function(&handler.name)?;
536
- let scope = Scope::new(&handler.name.0, function, &self.script.appliers);
588
+ let appliers = &self.script.appliers;
589
+ let function = self.script.function(handler.name)?;
590
+ let scope = Scope::new(appliers.name(handler.name), &function, appliers);
537
591
  let mut calls = Vec::new();
538
- for call in calls_of(function) {
539
- let target = scope.target(&call)?;
592
+ for call in calls_of(self.script.js(), &function) {
593
+ let target = scope.target(call)?;
540
594
  if target.passed == Some(passed + 2)
541
- && let Some(callee) = &target.callee
595
+ && let Some(callee) = target.callee
542
596
  && let Some(inner) = self.script.method_forwarder(callee)
543
597
  {
544
598
  calls.push((inner, target));
@@ -557,10 +611,7 @@ impl<'script> Machine<'script> {
557
611
  .iter()
558
612
  .filter(|target| target.passed == Some(arity))
559
613
  .collect();
560
- let sites: Vec<u32> = listeners
561
- .iter()
562
- .map(|target| target.site.v8.0 - self.start.0)
563
- .collect();
614
+ let sites: Vec<u32> = listeners.iter().map(|target| target.site.v8).collect();
564
615
  let listener = candidates::exactly_one(listeners, "listener of the closure's arity")
565
616
  .with_context(|| {
566
617
  format!("no one listener for a closure of {arity} arguments, at {sites:?}")
@@ -570,19 +621,19 @@ impl<'script> Machine<'script> {
570
621
  }
571
622
 
572
623
  /// The function `run` calls for an opcode.
573
- struct Handler<'machine> {
624
+ struct Handler<'a, 'machine> {
574
625
  /// Call from the dispatch loop to this handler.
575
- dispatch: Invocation,
576
- name: Id,
626
+ dispatch: Invocation<'a>,
627
+ name: Callee<'a>,
577
628
  frame: Name,
578
- dispatch_loop: &'machine DispatchLoop,
629
+ dispatch_loop: &'machine DispatchLoop<'a>,
579
630
  }
580
631
 
581
632
  /// Function called by `run` with the machine to dispatch opcodes.
582
- struct DispatchLoop {
583
- name: Id,
633
+ struct DispatchLoop<'a> {
634
+ name: Callee<'a>,
584
635
  /// Call from `run`, either direct or through a helper.
585
- call: Invocation,
636
+ call: Invocation<'a>,
586
637
  /// Whether the call occurs in a `try` block that handles exceptions.
587
638
  guarded: bool,
588
639
  }
@@ -592,42 +643,61 @@ struct DispatchLoop {
592
643
  const DISPATCH_CASES: usize = 40;
593
644
 
594
645
  /// Finds functions with dispatch switches that `run` calls with the machine.
595
- fn dispatch_loops(script: &Script, run: &Function) -> Vec<DispatchLoop> {
596
- #[derive(Default)]
597
- struct Calls {
598
- found: Vec<(CallExpr, bool)>,
646
+ fn dispatch_loops<'a>(script: &Script<'a>, run: &Body<'a>) -> Vec<DispatchLoop<'a>> {
647
+ struct Calls<'a> {
648
+ js: ast::Script<'a>,
649
+ found: Vec<(&'a CallExpression<'a>, bool)>,
599
650
  guarded: bool,
600
651
  }
601
- impl Visit for Calls {
602
- fn visit_function(&mut self, _: &Function) {}
603
- fn visit_class(&mut self, _: &Class) {}
652
+ impl<'a> Visit<'a> for Calls<'a> {
653
+ fn visit_function(&mut self, _: &Function<'a>, _: ScopeFlags) {}
654
+ fn visit_class(&mut self, _: &Class<'a>) {}
655
+ fn visit_object_property(&mut self, property: &ObjectProperty<'a>) {
656
+ walk_property(self, property);
657
+ }
604
658
  // Only a `try` with a `catch` handles exceptions.
605
- fn visit_try_stmt(&mut self, statement: &TryStmt) {
659
+ fn visit_try_statement(&mut self, statement: &TryStatement<'a>) {
606
660
  let outer = self.guarded;
607
661
  self.guarded |= statement.handler.is_some();
608
- statement.block.visit_with(self);
662
+ self.visit_block_statement(&statement.block);
609
663
  self.guarded = outer;
610
- statement.handler.visit_with(self);
611
- statement.finalizer.visit_with(self);
664
+ if let Some(handler) = &statement.handler {
665
+ self.visit_catch_clause(handler);
666
+ }
667
+ if let Some(finalizer) = &statement.finalizer {
668
+ self.visit_block_statement(finalizer);
669
+ }
612
670
  }
613
- fn visit_call_expr(&mut self, call: &CallExpr) {
614
- if call.args.iter().any(|argument| argument.expr.is_this()) {
615
- self.found.push((call.clone(), self.guarded));
671
+ fn visit_call_expression(&mut self, call: &CallExpression<'a>) {
672
+ if !is_optional_call(call)
673
+ && call.arguments.iter().any(|argument| {
674
+ matches!(
675
+ ast::argument_expression(argument),
676
+ Expression::ThisExpression(_)
677
+ )
678
+ })
679
+ {
680
+ let call = self.js.lend(call, AstKind::as_call_expression);
681
+ self.found.push((call, self.guarded));
616
682
  }
617
- call.visit_children_with(self);
683
+ walk::walk_call_expression(self, call);
618
684
  }
619
685
  }
620
- let mut calls = Calls::default();
621
- run.body.visit_with(&mut calls);
686
+ let mut calls = Calls {
687
+ js: script.js(),
688
+ found: Vec::new(),
689
+ guarded: false,
690
+ };
691
+ run.visit(&mut calls);
622
692
  let scope = Scope::new("", run, &script.appliers);
623
693
  calls
624
694
  .found
625
695
  .into_iter()
626
696
  .filter_map(|(call, guarded)| {
627
- let call = scope.target(&call).ok()?;
628
- let name = call.callee.clone()?;
629
- let function = script.function(&name).ok()?;
630
- (cases_of(function).len() > DISPATCH_CASES).then_some(DispatchLoop {
697
+ let call = scope.target(call).ok()?;
698
+ let name = call.callee?;
699
+ let function = script.function(name).ok()?;
700
+ (cases_of(script.js(), &function).len() > DISPATCH_CASES).then_some(DispatchLoop {
631
701
  name,
632
702
  call,
633
703
  guarded,
@@ -636,146 +706,270 @@ fn dispatch_loops(script: &Script, run: &Function) -> Vec<DispatchLoop> {
636
706
  .collect()
637
707
  }
638
708
 
709
+ /// A function's parameters and statements. An original function extracted from a merged
710
+ /// function has the merged function's parameters after the selector and its case's statements.
711
+ #[derive(Clone, Copy)]
712
+ struct Body<'a> {
713
+ parameters: &'a [FormalParameter<'a>],
714
+ /// Whether a rest parameter follows `parameters`.
715
+ rest: bool,
716
+ /// Whether the body starts with a directive prologue, which no statement pattern accepts.
717
+ prologue: bool,
718
+ /// The statements, in two parts so that an original function can join its case block to the
719
+ /// statements after it.
720
+ head: &'a [Statement<'a>],
721
+ tail: &'a [Statement<'a>],
722
+ }
723
+
724
+ impl<'a> Body<'a> {
725
+ fn of(function: &'a Function<'a>) -> Self {
726
+ let (prologue, head) = match &function.body {
727
+ Some(body) => (!body.directives.is_empty(), &body.statements[..]),
728
+ None => (false, &[][..]),
729
+ };
730
+ Self {
731
+ parameters: &function.params.items,
732
+ rest: function.params.rest.is_some(),
733
+ prologue,
734
+ head,
735
+ tail: &[],
736
+ }
737
+ }
738
+
739
+ fn statements(&self) -> impl DoubleEndedIterator<Item = &'a Statement<'a>> + Clone + use<'a> {
740
+ self.head.iter().chain(self.tail)
741
+ }
742
+
743
+ /// The statements of a body without a directive prologue.
744
+ fn plain_statements(
745
+ &self,
746
+ ) -> Option<impl DoubleEndedIterator<Item = &'a Statement<'a>> + Clone + use<'a>> {
747
+ (!self.prologue).then(|| self.statements())
748
+ }
749
+
750
+ /// The only statement after leading local declarations without initializers.
751
+ fn only_statement(&self) -> Option<&'a Statement<'a>> {
752
+ let mut rest = self.plain_statements()?.skip_while(|statement| {
753
+ matches!(statement, Statement::VariableDeclaration(declaration)
754
+ if !declaration.kind.is_using()
755
+ && declaration.declarations.iter().all(|declarator| declarator.init.is_none()))
756
+ });
757
+ let only = rest.next()?;
758
+ rest.next().is_none().then_some(only)
759
+ }
760
+
761
+ /// The bindings of the parameters, if they are all plain names.
762
+ fn parameters(&self) -> Option<Vec<SymbolId>> {
763
+ if self.rest {
764
+ return None;
765
+ }
766
+ self.parameters.iter().map(plain_parameter).collect()
767
+ }
768
+
769
+ fn visit(&self, visitor: &mut impl Visit<'a>) {
770
+ for statement in self.statements() {
771
+ visitor.visit_statement(statement);
772
+ }
773
+ }
774
+ }
775
+
639
776
  /// The script's declared and assigned functions, VM dispatch methods, and aliases for
640
777
  /// `Reflect.construct` and `Reflect.apply`.
641
- struct Script {
642
- functions: Vec<(Id, Function)>,
643
- /// Original functions extracted from merged functions, each using the merged function name. See
644
- /// [`Merged`].
645
- originals: Vec<(Id, Function)>,
646
- classes: Vec<DispatchMethod>,
647
- constructs: Vec<Id>,
778
+ struct Script<'a> {
779
+ functions: Vec<(Binding<'a>, Body<'a>)>,
780
+ classes: Vec<DispatchMethod<'a>>,
781
+ constructs: Vec<Callee<'a>>,
648
782
  /// Array slots containing `Reflect.construct`, indexed by array and slot.
649
- construct_slots: Vec<(Id, usize)>,
650
- applies: Vec<Id>,
651
- appliers: Appliers,
783
+ construct_slots: Vec<(Binding<'a>, usize)>,
784
+ applies: Vec<Callee<'a>>,
785
+ /// Array slots containing `Reflect.apply`, indexed by array and slot.
786
+ apply_slots: Vec<(Binding<'a>, usize)>,
787
+ appliers: Appliers<'a>,
788
+ }
789
+
790
+ /// An original function extracted from a merged function. See [`merged`].
791
+ struct Original<'a> {
792
+ /// The merged function's name, which frames of the original use.
793
+ name: &'a str,
794
+ body: Body<'a>,
652
795
  }
653
796
 
654
- /// Call helpers indexed by name, including selector-based helpers, merged functions, and
797
+ /// Call helpers indexed by callee, including selector-based helpers, merged functions, and
655
798
  /// forwarders. Also records numeric constants used by selectors.
656
- struct Appliers {
657
- helpers: HashMap<Id, Applier>,
658
- merged: HashMap<Id, Merged>,
659
- forwarders: Forwarders,
660
- /// Bindings assigned a numeric value once, such as a shared case-label mask.
661
- constants: HashMap<Id, f64>,
799
+ struct Appliers<'a> {
800
+ helpers: HashMap<Callee<'a>, Selection<Site>>,
801
+ /// Merged functions, selecting originals indexed into `originals`.
802
+ merged: HashMap<Binding<'a>, Selection<usize>>,
803
+ /// Original functions extracted from merged functions.
804
+ originals: Vec<Original<'a>>,
805
+ forwarders: Forwarders<'a>,
806
+ constants: Constants<'a>,
807
+ }
808
+
809
+ /// Bindings assigned a numeric value once, such as a shared case-label mask, and the script
810
+ /// that binds them.
811
+ struct Constants<'a> {
812
+ js: ast::Script<'a>,
813
+ values: HashMap<SymbolId, f64>,
814
+ }
815
+
816
+ impl<'a> Constants<'a> {
817
+ fn new(js: ast::Script<'a>) -> Self {
818
+ let mut values = HashMap::new();
819
+ let mut assigned = HashSet::new();
820
+ for node in js.nodes.iter() {
821
+ match node.kind() {
822
+ AstKind::VariableDeclarator(declarator) => {
823
+ if let BindingPattern::BindingIdentifier(name) = &declarator.id
824
+ && let Some(value) = declarator
825
+ .init
826
+ .as_ref()
827
+ .and_then(|init| ast::fold_number(init, &|_| None))
828
+ {
829
+ values.insert(name.symbol_id(), value);
830
+ }
831
+ }
832
+ AstKind::AssignmentExpression(assignment) => {
833
+ if let AssignmentTarget::AssignmentTargetIdentifier(name) = &assignment.left
834
+ && let Some(symbol) = js.symbol(name)
835
+ {
836
+ assigned.insert(symbol);
837
+ }
838
+ }
839
+ _ => {}
840
+ }
841
+ }
842
+ values.retain(|symbol, _| !assigned.contains(symbol));
843
+ Self { js, values }
844
+ }
845
+
846
+ /// The function or value `expression` names.
847
+ fn binding(&self, expression: &Expression<'a>) -> Option<Binding<'a>> {
848
+ match expression.without_parentheses() {
849
+ Expression::Identifier(reference) => Some(self.js.binding(reference)),
850
+ _ => None,
851
+ }
852
+ }
662
853
  }
663
854
 
664
855
  /// Functions that call their first parameter with the remaining parameters, as recorded by
665
856
  /// [`Scope`].
666
857
  #[derive(Default)]
667
- struct Forwarders {
858
+ struct Forwarders<'a> {
668
859
  /// Forwarders indexed by the binding holding their object and their property key.
669
- on_objects: HashMap<(Holder, String), Forwarder>,
860
+ on_objects: HashMap<(Holder<'a>, &'a str), Forwarder>,
670
861
  /// Forwarders copied to bindings, as in `f = object.key`, with the frames produced when called
671
862
  /// through those bindings.
672
- held: HashMap<Holder, Vec<Call>>,
863
+ held: HashMap<Holder<'a>, Vec<Call>>,
673
864
  }
674
865
 
675
- impl Forwarders {
866
+ impl<'a> Forwarders<'a> {
676
867
  /// Keeps only forwarders whose object bindings are assigned once, so their values are known.
677
- fn retain_assigned_once(&mut self, assigned: &HashMap<Holder, usize>) {
868
+ fn retain_assigned_once(&mut self, assigned: &HashMap<Holder<'a>, usize>) {
678
869
  let once = |holder: &Holder| assigned.get(holder).is_none_or(|&count| count == 1);
679
870
  self.on_objects.retain(|(holder, _), _| once(holder));
680
871
  self.held.retain(|holder, _| once(holder));
681
872
  }
682
873
  }
683
874
 
684
- impl Appliers {
685
- /// Also returns original functions extracted from merged functions, using names described by
686
- /// [`Merged`].
687
- fn new(program: &Program, functions: &[(Id, Function)]) -> (Self, Vec<(Id, Function)>) {
688
- #[derive(Default)]
689
- struct Constants {
690
- values: HashMap<Id, f64>,
691
- assigned: HashSet<Id>,
692
- }
693
- impl Visit for Constants {
694
- fn visit_var_declarator(&mut self, declarator: &VarDeclarator) {
695
- if let Pat::Ident(name) = &declarator.name
696
- && let Some(value) = declarator
697
- .init
698
- .as_deref()
699
- .and_then(|init| ast::fold_number(init, &|_| None))
700
- {
701
- self.values.insert(name.to_id(), value);
702
- }
703
- declarator.visit_children_with(self);
704
- }
705
- fn visit_assign_expr(&mut self, assign: &AssignExpr) {
706
- if let Some(name) = assign.left.as_ident() {
707
- self.assigned.insert(name.to_id());
708
- }
709
- assign.visit_children_with(self);
710
- }
711
- }
712
- let mut constants = Constants::default();
713
- program.visit_with(&mut constants);
714
- constants
715
- .values
716
- .retain(|name, _| !constants.assigned.contains(name));
717
- let values = constants.values;
718
- let applier = |(name, function): &(Id, Function)| {
719
- Some((name.clone(), Applier::new(function, &values)?))
720
- };
721
- let mut helpers: HashMap<Id, Applier> = functions.iter().filter_map(applier).collect();
722
- let mut merged = HashMap::new();
875
+ impl<'a> Appliers<'a> {
876
+ fn new(js: ast::Script<'a>, functions: &[(Binding<'a>, Body<'a>)]) -> Self {
877
+ let constants = Constants::new(js);
878
+ let mut helpers: HashMap<Callee<'a>, Selection<Site>> = functions
879
+ .iter()
880
+ .filter_map(|(name, function)| {
881
+ Some((Callee::Binding(*name), applier(function, &constants)?))
882
+ })
883
+ .collect();
884
+ let mut merged_functions = HashMap::new();
723
885
  let mut originals = Vec::new();
724
886
  for (name, function) in functions {
725
- if !helpers.contains_key(name)
726
- && let Some((selection, held)) = Merged::new(name, function, &values)
887
+ if !helpers.contains_key(&Callee::Binding(*name))
888
+ && let Some(Selection { mask, cases }) = merged(function, &constants)
727
889
  {
728
- merged.insert(name.clone(), selection);
729
- originals.extend(held);
890
+ let mut indexed = Vec::new();
891
+ for (label, body) in cases {
892
+ indexed.push((label, originals.len()));
893
+ originals.push(Original {
894
+ name: js.name(*name),
895
+ body,
896
+ });
897
+ }
898
+ merged_functions.insert(
899
+ *name,
900
+ Selection {
901
+ mask,
902
+ cases: indexed,
903
+ },
904
+ );
730
905
  }
731
906
  }
732
907
  // A merged function may hold call helpers.
733
- helpers.extend(originals.iter().filter_map(applier));
908
+ for (index, original) in originals.iter().enumerate() {
909
+ if let Some(helper) = applier(&original.body, &constants) {
910
+ helpers.insert(Callee::Original(index), helper);
911
+ }
912
+ }
734
913
  let mut appliers = Self {
735
914
  helpers,
736
- merged,
915
+ merged: merged_functions,
916
+ originals,
737
917
  forwarders: Forwarders::default(),
738
- constants: values,
918
+ constants,
739
919
  };
740
- appliers.forwarders = forwarders(program, &appliers);
741
- (appliers, originals)
920
+ appliers.forwarders = forwarders(&appliers);
921
+ appliers
922
+ }
923
+
924
+ fn js(&self) -> ast::Script<'a> {
925
+ self.constants.js
926
+ }
927
+
928
+ /// The name of `callee` in the source. An original function has its merged function's name.
929
+ fn name(&self, callee: Callee<'a>) -> &'a str {
930
+ match callee {
931
+ Callee::Binding(binding) => self.js().name(binding),
932
+ Callee::Original(index) => self.originals[index].name,
933
+ }
742
934
  }
743
935
 
744
- /// Evaluates `expression` using numeric literals and known constants.
745
- fn number(&self, expression: &Expr) -> Option<f64> {
746
- number(expression, &self.constants)
936
+ /// Evaluates `operand` using numeric literals and known constants.
937
+ fn number(&self, operand: Operand<'a>) -> Option<f64> {
938
+ match operand {
939
+ Operand::Expression(expression) => number(expression, &self.constants),
940
+ Operand::Resolved(Callee::Binding(Binding::Symbol(symbol))) => {
941
+ self.constants.values.get(&symbol).copied()
942
+ }
943
+ Operand::Resolved(_) => None,
944
+ }
747
945
  }
748
946
  }
749
947
 
750
948
  /// Collects forwarders from each function via [`Scope`]. Keeps only those whose object bindings are
751
949
  /// assigned once.
752
- fn forwarders(program: &Program, appliers: &Appliers) -> Forwarders {
753
- struct Collect<'script> {
754
- appliers: &'script Appliers,
755
- found: Forwarders,
756
- assigned: HashMap<Holder, usize>,
757
- }
758
- impl Collect<'_> {
759
- fn scope(&mut self, name: &str, function: &Function) {
760
- let scope = Scope::new(name, function, self.appliers);
950
+ fn forwarders<'a>(appliers: &Appliers<'a>) -> Forwarders<'a> {
951
+ struct Collect<'a, 's> {
952
+ appliers: &'s Appliers<'a>,
953
+ found: Forwarders<'a>,
954
+ assigned: HashMap<Holder<'a>, usize>,
955
+ }
956
+ impl<'a> Visit<'a> for Collect<'a, '_> {
957
+ fn visit_function(&mut self, function: &Function<'a>, flags: ScopeFlags) {
958
+ let function = self.appliers.js().lend(function, AstKind::as_function);
959
+ let name = function.id.as_ref().map_or("", |name| name.name.as_str());
960
+ let scope = Scope::new(name, &Body::of(function), self.appliers);
761
961
  self.found.on_objects.extend(scope.forwarders.on_objects);
762
962
  self.found.held.extend(scope.forwarders.held);
763
963
  for (holder, count) in scope.assigned {
764
964
  *self.assigned.entry(holder).or_default() += count;
765
965
  }
766
- function.visit_children_with(self);
966
+ walk::walk_function(self, function, flags);
767
967
  }
768
- }
769
- impl Visit for Collect<'_> {
770
- fn visit_fn_decl(&mut self, declaration: &FnDecl) {
771
- self.scope(&declaration.ident.sym, &declaration.function);
772
- }
773
- fn visit_fn_expr(&mut self, expression: &FnExpr) {
774
- let name = expression.ident.as_ref().map_or("", |name| &*name.sym);
775
- self.scope(name, &expression.function);
968
+ fn visit_object_property(&mut self, property: &ObjectProperty<'a>) {
969
+ walk_property(self, property);
776
970
  }
777
- fn visit_function(&mut self, function: &Function) {
778
- self.scope("", function);
971
+ fn visit_method_definition(&mut self, method: &MethodDefinition<'a>) {
972
+ walk_method(self, method);
779
973
  }
780
974
  }
781
975
  let mut collect = Collect {
@@ -783,176 +977,299 @@ fn forwarders(program: &Program, appliers: &Appliers) -> Forwarders {
783
977
  found: Forwarders::default(),
784
978
  assigned: HashMap::new(),
785
979
  };
786
- program.visit_with(&mut collect);
980
+ collect.visit_program(appliers.js().program);
787
981
  collect.found.retain_assigned_once(&collect.assigned);
788
982
  collect.found
789
983
  }
790
984
 
791
985
  /// Evaluates `expression` using literals and `constants`.
792
- fn number(expression: &Expr, constants: &HashMap<Id, f64>) -> Option<f64> {
793
- ast::fold_number(expression, &|leaf| {
794
- constants.get(&leaf.as_ident()?.to_id()).copied()
986
+ fn number<'a>(expression: &Expression<'a>, constants: &Constants<'a>) -> Option<f64> {
987
+ ast::fold_number(expression, &|leaf| match leaf {
988
+ Expression::Identifier(reference) => constants
989
+ .values
990
+ .get(&constants.js.symbol(reference)?)
991
+ .copied(),
992
+ _ => None,
795
993
  })
796
994
  }
797
995
 
798
996
  /// Finds the VM class method `run` that calls the dispatch loops.
799
- struct DispatchMethod {
800
- class: String,
801
- run: Function,
997
+ struct DispatchMethod<'a> {
998
+ class: &'a str,
999
+ run: Body<'a>,
802
1000
  /// The method's literal property key, if present.
803
- key: Option<String>,
1001
+ key: Option<&'a str>,
804
1002
  }
805
1003
 
806
- impl Script {
807
- fn new(program: &Program) -> Self {
808
- // The decoded AST retains resolver contexts, so equal names in different
809
- // lexical scopes have distinct IDs while frame names keep their original spelling.
810
- let functions = ast::named_functions(program);
811
- let (appliers, originals) = Appliers::new(program, &functions);
1004
+ impl<'a> Script<'a> {
1005
+ fn new(js: ast::Script<'a>) -> Self {
1006
+ // Semantic analysis gives equal names in different lexical scopes distinct bindings,
1007
+ // while frame names keep their original spelling.
1008
+ let functions: Vec<(Binding<'a>, Body<'a>)> = js
1009
+ .named_functions()
1010
+ .into_iter()
1011
+ .map(|(name, function)| (name, Body::of(function)))
1012
+ .collect();
1013
+ let appliers = Appliers::new(js, &functions);
812
1014
  let mut script = Self {
813
1015
  functions,
814
- originals,
815
1016
  classes: Vec::new(),
816
1017
  constructs: Vec::new(),
817
1018
  construct_slots: Vec::new(),
818
1019
  applies: Vec::new(),
1020
+ apply_slots: Vec::new(),
819
1021
  appliers,
820
1022
  };
821
- program.visit_with(&mut script);
1023
+ for node in js.nodes.iter() {
1024
+ match node.kind() {
1025
+ AstKind::AssignmentExpression(assignment) => script.assignment(assignment),
1026
+ AstKind::Class(class) if class.is_declaration() => script.class(class),
1027
+ _ => {}
1028
+ }
1029
+ }
822
1030
  script
823
1031
  }
824
1032
 
825
- fn function(&self, name: &Id) -> Result<&Function> {
826
- self.functions
827
- .iter()
828
- .chain(&self.originals)
829
- .find(|(function_name, _)| function_name == name)
830
- .map(|(_, function)| function)
831
- .with_context(|| format!("missing original function {}", name.0))
1033
+ fn js(&self) -> ast::Script<'a> {
1034
+ self.appliers.js()
832
1035
  }
833
1036
 
834
- /// Returns frames for the function bound to `name` if it forwards a method call. Allows
835
- /// local variable declarations before the return.
836
- fn method_forwarder(&self, name: &Id) -> Option<Vec<Call>> {
837
- let function = self.function(name).ok()?;
838
- let parameters = parameters(function)?;
1037
+ /// Tracks `Reflect.construct` and `Reflect.apply` in bindings or array slots, including
1038
+ /// indirect references to `Reflect`. Each assignment in a chain records its own target.
1039
+ fn assignment(&mut self, assignment: &'a AssignmentExpression<'a>) {
1040
+ let js = self.js();
1041
+ let mut value = &assignment.right;
1042
+ while let Expression::AssignmentExpression(inner) = value.without_parentheses() {
1043
+ value = &inner.right;
1044
+ }
1045
+ let Some(member) = member(value.without_parentheses()) else {
1046
+ return;
1047
+ };
1048
+ let method = ast::member_str(member);
1049
+ if let AssignmentTarget::AssignmentTargetIdentifier(name) = &assignment.left {
1050
+ let name = Callee::Binding(js.binding(name));
1051
+ match method {
1052
+ Some("construct") => self.constructs.push(name),
1053
+ Some("apply") => self.applies.push(name),
1054
+ _ => {}
1055
+ }
1056
+ }
1057
+ if let Some(MemberExpression::ComputedMemberExpression(slot)) =
1058
+ assigned_member(&assignment.left)
1059
+ && let Expression::Identifier(array) = &slot.object
1060
+ && let Some(index) =
1061
+ number(&slot.expression, &self.appliers.constants).and_then(ast::array_index)
1062
+ {
1063
+ let slot = (js.binding(array), index);
1064
+ match method {
1065
+ Some("construct") => self.construct_slots.push(slot),
1066
+ Some("apply") => self.apply_slots.push(slot),
1067
+ _ => {}
1068
+ }
1069
+ }
1070
+ }
1071
+
1072
+ /// Records a class declaration's `run` method.
1073
+ fn class(&mut self, class: &'a Class<'a>) {
1074
+ let run = class.body.body.iter().find_map(|element| match element {
1075
+ ClassElement::MethodDefinition(method)
1076
+ if method.kind != MethodDefinitionKind::Constructor
1077
+ && ast::static_key_str(&method.key, method.computed) == Some("run") =>
1078
+ {
1079
+ Some(method)
1080
+ }
1081
+ _ => None,
1082
+ });
1083
+ if let Some(method) = run
1084
+ && let Some(name) = &class.id
1085
+ {
1086
+ self.classes.push(DispatchMethod {
1087
+ class: name.name.as_str(),
1088
+ run: Body::of(&method.value),
1089
+ key: ast::key_str(&method.key, method.computed),
1090
+ });
1091
+ }
1092
+ }
1093
+
1094
+ fn function(&self, callee: Callee<'a>) -> Result<Body<'a>> {
1095
+ match callee {
1096
+ Callee::Binding(binding) => self
1097
+ .functions
1098
+ .iter()
1099
+ .find(|(name, _)| *name == binding)
1100
+ .map(|(_, function)| *function),
1101
+ Callee::Original(index) => self
1102
+ .appliers
1103
+ .originals
1104
+ .get(index)
1105
+ .map(|original| original.body),
1106
+ }
1107
+ .with_context(|| format!("missing original function {}", self.appliers.name(callee)))
1108
+ }
1109
+
1110
+ /// Returns frames for the function `callee` if it forwards a method call. Allows local
1111
+ /// variable declarations before the return.
1112
+ fn method_forwarder(&self, callee: Callee<'a>) -> Option<Vec<Call>> {
1113
+ let function = self.function(callee).ok()?;
1114
+ let parameters = function.parameters()?;
839
1115
  let [method, receiver, ..] = parameters.as_slice() else {
840
1116
  return None;
841
1117
  };
842
- let (Stmt::Return(returned), declarations) = function.body.as_ref()?.stmts.split_last()?
843
- else {
1118
+ let mut statements = function.plain_statements()?;
1119
+ let Statement::ReturnStatement(returned) = statements.next_back()? else {
844
1120
  return None;
845
1121
  };
846
- if !declarations
847
- .iter()
848
- .all(|statement| matches!(statement, Stmt::Decl(Decl::Var(_))))
849
- {
1122
+ if !statements.all(|statement| {
1123
+ matches!(statement, Statement::VariableDeclaration(declaration)
1124
+ if !declaration.kind.is_using())
1125
+ }) {
850
1126
  return None;
851
1127
  }
852
- let mut value = returned.arg.as_deref()?.unwrap_parens();
853
- if let Expr::Seq(sequence) = value {
854
- value = sequence.exprs.last()?.unwrap_parens();
1128
+ let mut value = returned.argument.as_ref()?.without_parentheses();
1129
+ if let Expression::SequenceExpression(sequence) = value {
1130
+ value = sequence.expressions.last()?.without_parentheses();
855
1131
  }
856
- let call = value.as_call()?;
857
- let target = Scope::new(&name.0, function, &self.appliers)
1132
+ let Expression::CallExpression(call) = value else {
1133
+ return None;
1134
+ };
1135
+ let name = self.appliers.name(callee);
1136
+ let target = Scope::new(name, &function, &self.appliers)
858
1137
  .target(call)
859
1138
  .ok()?;
860
1139
  // Compare bindings so a nested function with the same name as a native apply
861
- // alias cannot be mistaken for that alias.
862
- let callee = target.callee.as_ref()?;
863
- if self.function(callee).is_ok() && !self.applies.iter().any(|alias| alias == callee) {
1140
+ // alias cannot be mistaken for that alias. Some builds keep the alias in an array slot.
1141
+ let native = match (target.callee, target.slot) {
1142
+ (Some(callee), _) => self.function(callee).is_err() || self.applies.contains(&callee),
1143
+ (None, Some(slot)) => self.apply_slots.contains(&slot),
1144
+ (None, None) => false,
1145
+ };
1146
+ if !native {
864
1147
  return None;
865
1148
  }
866
- let [first, second, ..] = handed(call, &target)?[..] else {
1149
+ let [first, second, ..] = handed(Arguments::of(call), &target)?[..] else {
867
1150
  return None;
868
1151
  };
869
- (self::name(first).as_ref() == Some(method)
870
- && self::name(second).as_ref() == Some(receiver))
871
- .then(|| target.frames(Name::same(name.0.to_string())))
1152
+ let constants = &self.appliers.constants;
1153
+ (first.callee(constants) == Some(Callee::symbol(*method))
1154
+ && second.callee(constants) == Some(Callee::symbol(*receiver)))
1155
+ .then(|| target.frames(Name::same(name.to_owned())))
872
1156
  }
873
1157
  }
874
1158
 
875
- impl Visit for Script {
876
- fn visit_assign_expr(&mut self, assign: &AssignExpr) {
877
- // Track `Reflect.construct` and `Reflect.apply` in bindings or array slots, including
878
- // indirect references to `Reflect`. Visit child expressions to record every target in a
879
- // chained assignment.
880
- let mut value = &*assign.right;
881
- while let Expr::Assign(inner) = value.unwrap_parens() {
882
- value = &inner.right;
1159
+ /// A call argument as call resolution reads it.
1160
+ #[derive(Clone, Copy)]
1161
+ enum Operand<'a> {
1162
+ Expression(&'a Expression<'a>),
1163
+ /// A function resolved without an expression that names it: a binding a forwarder reads back
1164
+ /// from an array copy, or an original function selected from a merged function.
1165
+ Resolved(Callee<'a>),
1166
+ }
1167
+
1168
+ impl<'a> Operand<'a> {
1169
+ /// The function or value the operand names.
1170
+ fn callee(self, constants: &Constants<'a>) -> Option<Callee<'a>> {
1171
+ match self {
1172
+ Self::Expression(expression) => constants.binding(expression).map(Callee::Binding),
1173
+ Self::Resolved(callee) => Some(callee),
883
1174
  }
884
- if let Expr::Member(member) = value.unwrap_parens() {
885
- let method = ast::member_str(&member.prop);
886
- match (assign.left.as_ident(), method) {
887
- (Some(name), Some("construct")) => self.constructs.push(name.to_id()),
888
- (Some(name), Some("apply")) => self.applies.push(name.to_id()),
889
- _ => {}
890
- }
891
- if method == Some("construct")
892
- && let AssignTarget::Simple(SimpleAssignTarget::Member(slot)) = &assign.left
893
- && let Some(array) = slot.obj.as_ident()
894
- && let Some(index) = slot.prop.as_computed()
895
- && let Some(index) = self.appliers.number(&index.expr).and_then(ast::array_index)
896
- {
897
- self.construct_slots.push((array.to_id(), index));
898
- }
1175
+ }
1176
+ }
1177
+
1178
+ /// A call's arguments. In a forwarder, `copies` resolves arguments read back from array copies,
1179
+ /// at the top level and in array literals.
1180
+ #[derive(Clone, Copy)]
1181
+ struct Arguments<'a, 'c> {
1182
+ list: &'a [Argument<'a>],
1183
+ copies: Option<&'c Copies<'a, 'c>>,
1184
+ }
1185
+
1186
+ impl<'a, 'c> Arguments<'a, 'c> {
1187
+ fn of(call: &'a CallExpression<'a>) -> Self {
1188
+ Self {
1189
+ list: &call.arguments,
1190
+ copies: None,
899
1191
  }
900
- assign.visit_children_with(self);
901
1192
  }
902
1193
 
903
- fn visit_class_decl(&mut self, declaration: &ClassDecl) {
904
- let run = declaration
905
- .class
906
- .body
907
- .iter()
908
- .filter_map(ClassMember::as_method)
909
- .find(|method| ast::static_key_str(&method.key) == Some("run"));
910
- if let Some(method) = run {
911
- self.classes.push(DispatchMethod {
912
- class: declaration.ident.sym.to_string(),
913
- run: (*method.function).clone(),
914
- key: ast::key_str(&method.key).map(str::to_owned),
915
- });
1194
+ /// Reads an argument, resolving it through the copies unless it is an array literal.
1195
+ fn argument(&self, argument: &'a Argument<'a>) -> Operand<'a> {
1196
+ let expression = ast::argument_expression(argument);
1197
+ if let Some(copies) = self.copies
1198
+ && !matches!(
1199
+ expression.without_parentheses(),
1200
+ Expression::ArrayExpression(_)
1201
+ )
1202
+ && let Some(binding) = copies.resolve(expression)
1203
+ {
1204
+ return Operand::Resolved(Callee::Binding(binding));
916
1205
  }
917
- declaration.visit_children_with(self);
1206
+ Operand::Expression(expression)
1207
+ }
1208
+
1209
+ /// Reads an array element, or `None` for a hole.
1210
+ fn element(&self, element: &'a ArrayExpressionElement<'a>) -> Option<Operand<'a>> {
1211
+ let expression = element_expression(element)?;
1212
+ Some(
1213
+ match self.copies.and_then(|copies| copies.resolve(expression)) {
1214
+ Some(binding) => Operand::Resolved(Callee::Binding(binding)),
1215
+ None => Operand::Expression(expression),
1216
+ },
1217
+ )
918
1218
  }
919
1219
  }
920
1220
 
921
- fn name(expression: &Expr) -> Option<Id> {
922
- Some(expression.unwrap_parens().as_ident()?.to_id())
1221
+ /// The expression an array element holds, ignoring a spread, or `None` for a hole.
1222
+ fn element_expression<'b, 'a>(
1223
+ element: &'b ArrayExpressionElement<'a>,
1224
+ ) -> Option<&'b Expression<'a>> {
1225
+ match element {
1226
+ ArrayExpressionElement::SpreadElement(spread) => Some(&spread.argument),
1227
+ ArrayExpressionElement::Elision(_) => None,
1228
+ element => Some(element.to_expression()),
1229
+ }
923
1230
  }
924
1231
 
925
- /// The names of a function's parameters, if they are all plain names.
926
- fn parameters(function: &Function) -> Option<Vec<Id>> {
927
- function
928
- .params
929
- .iter()
930
- .map(|parameter| Some(parameter.pat.as_ident()?.to_id()))
931
- .collect()
1232
+ /// An array literal, possibly parenthesized.
1233
+ fn array<'b, 'a>(expression: &'b Expression<'a>) -> Option<&'b ArrayExpression<'a>> {
1234
+ match expression.without_parentheses() {
1235
+ Expression::ArrayExpression(array) => Some(array),
1236
+ _ => None,
1237
+ }
932
1238
  }
933
1239
 
934
- /// Returns the arguments `call` forwards to the callee identified by `target`. Skips leading
1240
+ /// Returns the arguments a call forwards to the callee identified by `target`. Skips leading
935
1241
  /// selectors, callee, and receiver. The forwarded arguments are either the trailing call arguments
936
1242
  /// or the trailing elements of an apply-helper argument list.
937
- fn handed<'call>(call: &'call CallExpr, target: &Invocation) -> Option<Vec<&'call Expr>> {
938
- let arguments: Vec<&Expr> = if target.listed {
939
- let list = call.args.last()?.expr.unwrap_parens().as_array()?;
940
- list.elems
1243
+ fn handed<'a>(arguments: Arguments<'a, '_>, target: &Invocation<'a>) -> Option<Vec<Operand<'a>>> {
1244
+ let operands: Vec<Operand<'a>> = if target.listed {
1245
+ let list = array(ast::argument_expression(arguments.list.last()?))?;
1246
+ list.elements
941
1247
  .iter()
942
- .map(|element| element.as_ref().map(|element| &*element.expr))
1248
+ .map(|element| arguments.element(element))
943
1249
  .collect::<Option<_>>()?
944
1250
  } else {
945
- call.args.iter().map(|argument| &*argument.expr).collect()
1251
+ arguments
1252
+ .list
1253
+ .iter()
1254
+ .map(|argument| arguments.argument(argument))
1255
+ .collect()
946
1256
  };
947
- let start = arguments.len().checked_sub(target.passed?)?;
948
- Some(arguments[start..].to_vec())
1257
+ let start = operands.len().checked_sub(target.passed?)?;
1258
+ Some(operands[start..].to_vec())
949
1259
  }
950
1260
 
951
1261
  /// Checks whether `call` forwards two captured values followed by `function`'s leading
952
1262
  /// parameters, as a closure-factory listener does. The function may also declare trailing
953
1263
  /// parameters used as local variables.
954
- fn forwards_parameters(function: &Function, call: &CallExpr, target: &Invocation) -> bool {
955
- let (Some(handed), Some(parameters)) = (handed(call, target), parameters(function)) else {
1264
+ fn forwards_parameters<'a>(
1265
+ constants: &Constants<'a>,
1266
+ function: &Body<'a>,
1267
+ call: &'a CallExpression<'a>,
1268
+ target: &Invocation<'a>,
1269
+ ) -> bool {
1270
+ let (Some(handed), Some(parameters)) =
1271
+ (handed(Arguments::of(call), target), function.parameters())
1272
+ else {
956
1273
  return false;
957
1274
  };
958
1275
  let Some(forwarded) = handed.get(2..) else {
@@ -962,19 +1279,21 @@ fn forwards_parameters(function: &Function, call: &CallExpr, target: &Invocation
962
1279
  && forwarded
963
1280
  .iter()
964
1281
  .zip(parameters)
965
- .all(|(argument, parameter)| name(argument) == Some(parameter))
1282
+ .all(|(argument, parameter)| {
1283
+ argument.callee(constants) == Some(Callee::symbol(parameter))
1284
+ })
966
1285
  }
967
1286
 
968
1287
  /// Arrays a function fills with names before reading them back, such as `g = [f, a]` read as
969
1288
  /// `g[0]` and `g[1]`.
970
- struct Copies<'constants> {
971
- arrays: HashMap<Id, Vec<Id>>,
1289
+ struct Copies<'a, 'c> {
1290
+ arrays: HashMap<Binding<'a>, Vec<Binding<'a>>>,
972
1291
  /// Known constants used to evaluate array indices.
973
- constants: &'constants HashMap<Id, f64>,
1292
+ constants: &'c Constants<'a>,
974
1293
  }
975
1294
 
976
- impl<'constants> Copies<'constants> {
977
- fn new(constants: &'constants HashMap<Id, f64>) -> Self {
1295
+ impl<'a, 'c> Copies<'a, 'c> {
1296
+ fn new(constants: &'c Constants<'a>) -> Self {
978
1297
  Self {
979
1298
  arrays: HashMap::new(),
980
1299
  constants,
@@ -982,118 +1301,158 @@ impl<'constants> Copies<'constants> {
982
1301
  }
983
1302
 
984
1303
  /// Records `expression` if it is `array = [name, ...]`.
985
- fn record(&mut self, expression: &Expr) -> Option<()> {
986
- let assign = expression.as_assign()?;
987
- let array = assign.left.as_ident()?;
988
- let names: Option<Vec<Id>> = assign
989
- .right
990
- .as_array()?
991
- .elems
1304
+ fn record(&mut self, expression: &Expression<'a>) -> Option<()> {
1305
+ let Expression::AssignmentExpression(assignment) = expression else {
1306
+ return None;
1307
+ };
1308
+ let AssignmentTarget::AssignmentTargetIdentifier(array) = &assignment.left else {
1309
+ return None;
1310
+ };
1311
+ let Expression::ArrayExpression(list) = &assignment.right else {
1312
+ return None;
1313
+ };
1314
+ let names: Option<Vec<Binding<'a>>> = list
1315
+ .elements
992
1316
  .iter()
993
- .map(|element| name(&element.as_ref()?.expr))
1317
+ .map(|element| self.constants.binding(element_expression(element)?))
994
1318
  .collect();
995
- self.arrays.insert(array.to_id(), names?);
1319
+ self.arrays.insert(self.constants.js.binding(array), names?);
996
1320
  Some(())
997
1321
  }
998
1322
 
999
- /// The name `expression` reads, directly or through an element of a copied array.
1000
- fn resolve(&self, expression: &Expr) -> Option<Id> {
1001
- match expression.unwrap_parens() {
1002
- Expr::Ident(name) => Some(name.to_id()),
1003
- Expr::Member(member) => {
1004
- let (Expr::Ident(array), MemberProp::Computed(index)) =
1005
- (&*member.obj, &member.prop)
1006
- else {
1323
+ /// The binding `expression` reads, directly or through an element of a copied array.
1324
+ fn resolve(&self, expression: &Expression<'a>) -> Option<Binding<'a>> {
1325
+ match expression.without_parentheses() {
1326
+ Expression::Identifier(name) => Some(self.constants.js.binding(name)),
1327
+ Expression::ComputedMemberExpression(member) => {
1328
+ let Expression::Identifier(array) = &member.object else {
1007
1329
  return None;
1008
1330
  };
1009
- let index = ast::array_index(number(&index.expr, self.constants)?)?;
1010
- self.arrays.get(&array.to_id())?.get(index).cloned()
1331
+ let index = ast::array_index(number(&member.expression, self.constants)?)?;
1332
+ self.arrays
1333
+ .get(&self.constants.js.binding(array))?
1334
+ .get(index)
1335
+ .copied()
1011
1336
  }
1012
1337
  _ => None,
1013
1338
  }
1014
1339
  }
1340
+
1341
+ /// The binding `operand` reads. See [`Copies::resolve`].
1342
+ fn resolve_operand(&self, operand: Operand<'a>) -> Option<Binding<'a>> {
1343
+ match operand {
1344
+ Operand::Expression(expression) => self.resolve(expression),
1345
+ Operand::Resolved(Callee::Binding(binding)) => Some(binding),
1346
+ Operand::Resolved(Callee::Original(_)) => None,
1347
+ }
1348
+ }
1015
1349
  }
1016
1350
 
1017
1351
  /// JavaScriptCore's call position: the opening argument parenthesis, which in minified source
1018
1352
  /// immediately precedes the first argument. Decoding may change the callee's parentheses but
1019
1353
  /// preserves argument positions.
1020
- fn arguments_position(call: &CallExpr) -> BytePos {
1021
- match call.args.first() {
1022
- Some(first) => first.span().lo - BytePos(1),
1023
- None => call.span.hi - BytePos(2),
1354
+ fn arguments_position(call: &CallExpression<'_>) -> u32 {
1355
+ match call.arguments.first() {
1356
+ Some(first) => first.span().start - 1,
1357
+ None => call.span.end - 2,
1024
1358
  }
1025
1359
  }
1026
1360
 
1027
1361
  /// V8's call position: the method or function name, else JavaScriptCore's position.
1028
- fn call_position(call: &CallExpr) -> BytePos {
1362
+ fn call_position(call: &CallExpression<'_>) -> u32 {
1029
1363
  match &call.callee {
1030
- Callee::Expr(callee) => match &**callee {
1031
- Expr::Member(member) => match &member.prop {
1032
- MemberProp::Ident(property) => property.span.lo,
1033
- _ => callee.span().hi,
1034
- },
1035
- Expr::Ident(_) => call.span.lo,
1036
- _ => arguments_position(call),
1364
+ callee if let Some(member) = member(callee) => match member {
1365
+ MemberExpression::StaticMemberExpression(member) => member.property.span.start,
1366
+ _ => callee.span().end,
1037
1367
  },
1038
- _ => call.span.lo,
1368
+ Expression::Identifier(_) | Expression::Super(_) => call.span.start,
1369
+ _ => arguments_position(call),
1039
1370
  }
1040
1371
  }
1041
1372
 
1042
1373
  /// Finds the first call in a dispatch case.
1043
- struct Case {
1374
+ struct Case<'a> {
1044
1375
  span: Span,
1045
- call: CallExpr,
1376
+ call: &'a CallExpression<'a>,
1046
1377
  }
1047
1378
 
1048
- fn cases_of(function: &Function) -> Vec<Case> {
1049
- #[derive(Default)]
1050
- struct Cases(Vec<Case>);
1379
+ fn cases_of<'a>(js: ast::Script<'a>, function: &Body<'a>) -> Vec<Case<'a>> {
1380
+ struct Cases<'a> {
1381
+ js: ast::Script<'a>,
1382
+ found: Vec<Case<'a>>,
1383
+ }
1051
1384
  // Visitors inspect only the supplied body. Skip nested functions and classes, but include
1052
1385
  // arrows.
1053
- impl Visit for Cases {
1054
- fn visit_function(&mut self, _: &Function) {}
1055
- fn visit_class(&mut self, _: &Class) {}
1056
- fn visit_switch_case(&mut self, case: &SwitchCase) {
1386
+ impl<'a> Visit<'a> for Cases<'a> {
1387
+ fn visit_function(&mut self, _: &Function<'a>, _: ScopeFlags) {}
1388
+ fn visit_class(&mut self, _: &Class<'a>) {}
1389
+ fn visit_object_property(&mut self, property: &ObjectProperty<'a>) {
1390
+ walk_property(self, property);
1391
+ }
1392
+ fn visit_switch_case(&mut self, case: &SwitchCase<'a>) {
1057
1393
  if case.test.is_some() {
1058
- let mut calls = Calls::default();
1059
- case.cons.visit_with(&mut calls);
1060
- if let Some(call) = calls.0.into_iter().next() {
1061
- self.0.push(Case {
1394
+ let case = self.js.lend(case, AstKind::as_switch_case);
1395
+ if let Some(&call) = calls_in(self.js, &case.consequent).first() {
1396
+ self.found.push(Case {
1062
1397
  span: case.span,
1063
1398
  call,
1064
1399
  });
1065
1400
  }
1066
1401
  }
1067
- case.visit_children_with(self);
1402
+ walk::walk_switch_case(self, case);
1068
1403
  }
1069
1404
  }
1070
- let mut cases = Cases::default();
1071
- function.body.visit_with(&mut cases);
1072
- cases.0
1405
+ let mut cases = Cases {
1406
+ js,
1407
+ found: Vec::new(),
1408
+ };
1409
+ function.visit(&mut cases);
1410
+ cases.found
1073
1411
  }
1074
1412
 
1075
1413
  /// Calls made by a function's own body, excluding nested functions.
1076
- #[derive(Default)]
1077
- struct Calls(Vec<CallExpr>);
1414
+ struct Calls<'a> {
1415
+ js: ast::Script<'a>,
1416
+ found: Vec<&'a CallExpression<'a>>,
1417
+ }
1078
1418
 
1079
- impl Visit for Calls {
1080
- fn visit_function(&mut self, _: &Function) {}
1081
- fn visit_class(&mut self, _: &Class) {}
1082
- fn visit_call_expr(&mut self, call: &CallExpr) {
1083
- self.0.push(call.clone());
1084
- call.visit_children_with(self);
1419
+ impl<'a> Visit<'a> for Calls<'a> {
1420
+ fn visit_function(&mut self, _: &Function<'a>, _: ScopeFlags) {}
1421
+ fn visit_class(&mut self, _: &Class<'a>) {}
1422
+ fn visit_object_property(&mut self, property: &ObjectProperty<'a>) {
1423
+ walk_property(self, property);
1424
+ }
1425
+ fn visit_call_expression(&mut self, call: &CallExpression<'a>) {
1426
+ if !is_optional_call(call) {
1427
+ self.found
1428
+ .push(self.js.lend(call, AstKind::as_call_expression));
1429
+ }
1430
+ walk::walk_call_expression(self, call);
1085
1431
  }
1086
1432
  }
1087
1433
 
1088
- fn calls_of(function: &Function) -> Vec<CallExpr> {
1089
- let mut calls = Calls::default();
1090
- function.body.visit_with(&mut calls);
1091
- calls.0
1434
+ /// Calls made by `statements`, excluding nested functions.
1435
+ fn calls_in<'a>(
1436
+ js: ast::Script<'a>,
1437
+ statements: impl IntoIterator<Item = &'a Statement<'a>>,
1438
+ ) -> Vec<&'a CallExpression<'a>> {
1439
+ let mut calls = Calls {
1440
+ js,
1441
+ found: Vec::new(),
1442
+ };
1443
+ for statement in statements {
1444
+ calls.visit_statement(statement);
1445
+ }
1446
+ calls.found
1447
+ }
1448
+
1449
+ fn calls_of<'a>(js: ast::Script<'a>, function: &Body<'a>) -> Vec<&'a CallExpression<'a>> {
1450
+ calls_in(js, function.statements())
1092
1451
  }
1093
1452
 
1094
1453
  /// A call's target, resolved through helper functions.
1095
- struct Invocation {
1096
- callee: Option<Id>,
1454
+ struct Invocation<'a> {
1455
+ callee: Option<Callee<'a>>,
1097
1456
  /// Whether it invokes `callee.call(receiver, ...)`.
1098
1457
  method: bool,
1099
1458
  /// Intermediate helper frames, innermost first.
@@ -1104,10 +1463,23 @@ struct Invocation {
1104
1463
  /// Whether the final argument is an array literal containing the arguments passed to `callee`.
1105
1464
  listed: bool,
1106
1465
  /// The array slot the called function is read from, if any.
1107
- slot: Option<(Id, usize)>,
1466
+ slot: Option<(Binding<'a>, usize)>,
1108
1467
  }
1109
1468
 
1110
- impl Invocation {
1469
+ impl Invocation<'_> {
1470
+ /// An unresolved call at `site`.
1471
+ fn at(site: Site) -> Self {
1472
+ Self {
1473
+ callee: None,
1474
+ method: false,
1475
+ helpers: Vec::new(),
1476
+ site,
1477
+ passed: None,
1478
+ listed: false,
1479
+ slot: None,
1480
+ }
1481
+ }
1482
+
1111
1483
  /// The frames of the call made from `caller`, innermost first.
1112
1484
  fn frames(&self, caller: Name) -> Vec<Call> {
1113
1485
  let mut frames = self.helpers.clone();
@@ -1119,224 +1491,186 @@ impl Invocation {
1119
1491
  }
1120
1492
  }
1121
1493
 
1122
- /// Recovers the XOR mask and call cases of a selector-based helper. Calls can use `Reflect.apply(f,
1123
- /// _, list)` or `f(a, b)` with later parameters forwarded in order.
1124
- ///
1125
- /// Handles copied selectors such as `(s = [selector], mask ^ s[0])`, indirect references to
1126
- /// `apply`, copied arguments such as `(g = [f, a], (0, g[0])(g[1]))`, and masks or labels computed
1127
- /// from constants.
1128
- struct Applier {
1494
+ /// A `switch (selector ^ mask)` whose case labels each select a `T`.
1495
+ struct Selection<T> {
1129
1496
  mask: f64,
1130
- cases: Vec<ApplierCase>,
1497
+ cases: Vec<(f64, T)>,
1131
1498
  }
1132
1499
 
1133
- struct ApplierCase {
1134
- label: f64,
1135
- site: Site,
1500
+ impl<T: Copy> Selection<T> {
1501
+ /// The case `selector` selects.
1502
+ fn select(&self, selector: f64) -> Option<T> {
1503
+ let chosen = f64::from(js::int32(self.mask) ^ js::int32(selector));
1504
+ self.cases
1505
+ .iter()
1506
+ .find(|(label, _)| *label == chosen)
1507
+ .map(|&(_, case)| case)
1508
+ }
1136
1509
  }
1137
1510
 
1138
- impl Applier {
1139
- fn new(function: &Function, constants: &HashMap<Id, f64>) -> Option<Self> {
1140
- let parameters = parameters(function)?;
1141
- let [selector, applied, rest @ ..] = parameters.as_slice() else {
1142
- return None;
1143
- };
1144
- let (mask, switch, copies) = selection(function, selector, constants)?;
1145
- // Match `f(a, b)` when arguments follow parameter order.
1146
- let passes_on = |call: &CallExpr| {
1147
- let Some(callee) = call.callee.as_expr() else {
1148
- return false;
1149
- };
1150
- let (callee, _) = undetached(callee, constants);
1151
- copies.resolve(callee).as_ref() == Some(applied)
1152
- && call.args.len() <= rest.len()
1153
- && call.args.iter().zip(rest).all(|(argument, parameter)| {
1154
- argument.spread.is_none()
1155
- && copies.resolve(&argument.expr).as_ref() == Some(parameter)
1511
+ /// Recovers the `Reflect.apply` call site of each case of a selector-based helper. Calls can use
1512
+ /// `Reflect.apply(f, _, list)` or `f(a, b)` with later parameters forwarded in order.
1513
+ ///
1514
+ /// Handles copied selectors such as `(s = [selector], mask ^ s[0])`, indirect references to
1515
+ /// `apply`, copied arguments such as `(g = [f, a], (0, g[0])(g[1]))`, and masks or labels computed
1516
+ /// from constants.
1517
+ fn applier<'a>(function: &Body<'a>, constants: &Constants<'a>) -> Option<Selection<Site>> {
1518
+ let parameters = function.parameters()?;
1519
+ let [selector, applied, rest @ ..] = parameters.as_slice() else {
1520
+ return None;
1521
+ };
1522
+ let (mask, switch, copies) = selection(function, *selector, constants)?;
1523
+ let is = |binding: Option<Binding<'a>>, parameter: &SymbolId| {
1524
+ binding == Some(Binding::Symbol(*parameter))
1525
+ };
1526
+ // Match `f(a, b)` when arguments follow parameter order.
1527
+ let passes_on = |call: &CallExpression<'a>| {
1528
+ let (callee, _) = undetached(&call.callee, constants);
1529
+ is(copies.resolve(callee), applied)
1530
+ && call.arguments.len() <= rest.len()
1531
+ && call
1532
+ .arguments
1533
+ .iter()
1534
+ .zip(rest)
1535
+ .all(|(argument, parameter)| match argument {
1536
+ Argument::SpreadElement(_) => false,
1537
+ argument => is(copies.resolve(argument.to_expression()), parameter),
1156
1538
  })
1539
+ };
1540
+ let applies = |call: &CallExpression<'a>| {
1541
+ let [first, _, third] = &call.arguments[..] else {
1542
+ return false;
1157
1543
  };
1158
- let applies = |call: &CallExpr| {
1159
- let [first, _, third] = &call.args[..] else {
1160
- return false;
1544
+ member(call.callee.without_parentheses()).is_some()
1545
+ && is(constants.binding(ast::argument_expression(first)), applied)
1546
+ && rest
1547
+ .first()
1548
+ .is_some_and(|list| is(constants.binding(ast::argument_expression(third)), list))
1549
+ };
1550
+ let cases: Vec<(f64, Site)> = switch
1551
+ .cases
1552
+ .iter()
1553
+ .filter_map(|case| {
1554
+ let label = number(case.test.as_ref()?, constants)?;
1555
+ let [Statement::ReturnStatement(returned)] = &case.consequent[..] else {
1556
+ return None;
1161
1557
  };
1162
- call.callee
1163
- .as_expr()
1164
- .is_some_and(|callee| callee.unwrap_parens().is_member())
1165
- && name(&first.expr).as_ref() == Some(applied)
1166
- && rest
1167
- .first()
1168
- .is_some_and(|list| name(&third.expr).as_ref() == Some(list))
1169
- };
1170
- let cases: Vec<ApplierCase> = switch
1171
- .cases
1172
- .iter()
1173
- .filter_map(|case| {
1174
- let label = number(case.test.as_deref()?, constants)?;
1175
- let [Stmt::Return(returned)] = &case.cons[..] else {
1176
- return None;
1177
- };
1178
- let Some(Expr::Call(call)) = returned.arg.as_deref().map(Expr::unwrap_parens)
1179
- else {
1180
- return None;
1181
- };
1182
- (applies(call) || passes_on(call)).then(|| ApplierCase {
1183
- label,
1184
- site: Site::new(call),
1185
- })
1186
- })
1187
- .collect();
1188
- // Other cases may call more helpers. Selectors routed there have no case in this helper.
1189
- (!cases.is_empty()).then_some(Self { mask, cases })
1190
- }
1191
-
1192
- /// The `Reflect.apply` call in the case `selector` selects.
1193
- fn call(&self, selector: f64) -> Option<Site> {
1194
- let chosen = f64::from(js::int32(self.mask) ^ js::int32(selector));
1195
- self.cases
1196
- .iter()
1197
- .find(|case| case.label == chosen)
1198
- .map(|case| case.site)
1199
- }
1558
+ let Expression::CallExpression(call) =
1559
+ returned.argument.as_ref()?.without_parentheses()
1560
+ else {
1561
+ return None;
1562
+ };
1563
+ (applies(call) || passes_on(call)).then(|| (label, Site::new(call)))
1564
+ })
1565
+ .collect();
1566
+ // Other cases may call more helpers. Selectors routed there have no case in this helper.
1567
+ (!cases.is_empty()).then_some(Selection { mask, cases })
1200
1568
  }
1201
1569
 
1202
1570
  /// Extracts the mask and switch from a function containing `switch (selector ^ mask)`, with
1203
1571
  /// optional leading local declarations. Also tracks arrays used to copy selector names, as in `(s =
1204
1572
  /// [selector], mask ^ s[0])`.
1205
- fn selection<'function, 'constants>(
1206
- function: &'function Function,
1207
- selector: &Id,
1208
- constants: &'constants HashMap<Id, f64>,
1209
- ) -> Option<(f64, &'function SwitchStmt, Copies<'constants>)> {
1210
- let [Stmt::Switch(switch)] = after_declarations(&function.body.as_ref()?.stmts) else {
1573
+ fn selection<'a, 'c>(
1574
+ function: &Body<'a>,
1575
+ selector: SymbolId,
1576
+ constants: &'c Constants<'a>,
1577
+ ) -> Option<(f64, &'a SwitchStatement<'a>, Copies<'a, 'c>)> {
1578
+ let Statement::SwitchStatement(switch) = function.only_statement()? else {
1211
1579
  return None;
1212
1580
  };
1213
- let mut discriminant = switch.discriminant.unwrap_parens();
1581
+ let mut discriminant = switch.discriminant.without_parentheses();
1214
1582
  let mut copies = Copies::new(constants);
1215
- if let Expr::Seq(sequence) = discriminant {
1216
- let (last, before) = sequence.exprs.split_last()?;
1583
+ if let Expression::SequenceExpression(sequence) = discriminant {
1584
+ let (last, before) = sequence.expressions.split_last()?;
1217
1585
  for expression in before {
1218
1586
  copies.record(expression);
1219
1587
  }
1220
- discriminant = last.unwrap_parens();
1588
+ discriminant = last.without_parentheses();
1589
+ }
1590
+ let Expression::BinaryExpression(xor) = discriminant else {
1591
+ return None;
1592
+ };
1593
+ if xor.operator != BinaryOperator::BitwiseXOR {
1594
+ return None;
1221
1595
  }
1222
- let xor = discriminant
1223
- .as_bin()
1224
- .filter(|xor| xor.op == BinaryOp::BitXor)?;
1225
- let is_selector = |expression: &Expr| copies.resolve(expression).as_ref() == Some(selector);
1226
- let mask = match (xor.left.unwrap_parens(), xor.right.unwrap_parens()) {
1596
+ let is_selector =
1597
+ |expression: &Expression<'a>| copies.resolve(expression) == Some(Binding::Symbol(selector));
1598
+ let mask = match (
1599
+ xor.left.without_parentheses(),
1600
+ xor.right.without_parentheses(),
1601
+ ) {
1227
1602
  (other, mask) | (mask, other) if is_selector(other) => number(mask, constants)?,
1228
1603
  _ => return None,
1229
1604
  };
1230
1605
  Some((mask, switch, copies))
1231
1606
  }
1232
1607
 
1233
- /// Returns `statements` after skipping leading local declarations without initializers.
1234
- fn after_declarations(statements: &[Stmt]) -> &[Stmt] {
1235
- let start = statements
1236
- .iter()
1237
- .position(|statement| {
1238
- !matches!(statement, Stmt::Decl(Decl::Var(declaration))
1239
- if declaration.decls.iter().all(|declarator| declarator.init.is_none()))
1240
- })
1241
- .unwrap_or(statements.len());
1242
- &statements[start..]
1243
- }
1244
-
1245
- /// A function combining several original functions, selected by its first parameter:
1608
+ /// Recovers the original functions of a function that combines several, selected by its first
1609
+ /// parameter:
1246
1610
  ///
1247
1611
  /// ```js
1248
1612
  /// function merged(selector, a) { switch (selector ^ mask) { case 1: { <original> } return; } }
1249
1613
  /// ```
1250
1614
  ///
1251
1615
  /// Both V8 and JavaScriptCore name every original function's frame after the merged function.
1252
- /// Recovery gives each original a fresh binding with that name and keeps the other parameters.
1253
- struct Merged {
1254
- mask: f64,
1255
- /// Original function for each case label, indexed into [`Script::originals`].
1256
- cases: Vec<(f64, Id)>,
1257
- }
1258
-
1259
- impl Merged {
1260
- fn new(
1261
- name: &Id,
1262
- function: &Function,
1263
- constants: &HashMap<Id, f64>,
1264
- ) -> Option<(Self, Vec<(Id, Function)>)> {
1265
- let selector = function.params.first()?.pat.as_ident()?.to_id();
1266
- let (mask, switch, _) = selection(function, &selector, constants)?;
1267
- let block = function.body.as_ref()?;
1268
- let mut cases = Vec::new();
1269
- let mut originals = Vec::new();
1270
- for (at, case) in switch.cases.iter().enumerate() {
1271
- let label = case
1272
- .test
1273
- .as_deref()
1274
- .and_then(|test| number(test, constants));
1275
- // Labels sharing a body fall through to it.
1276
- let body = switch.cases[at..]
1277
- .iter()
1278
- .map(|case| &case.cons)
1279
- .find(|body| !body.is_empty());
1280
- let (Some(label), Some(body)) = (label, body) else {
1281
- continue;
1282
- };
1283
- let mut statements: Vec<Stmt> = match &body[..] {
1284
- [Stmt::Block(original), rest @ ..] => {
1285
- original.stmts.iter().chain(rest).cloned().collect()
1286
- }
1287
- _ => body.clone(),
1288
- };
1289
- if let Some(Stmt::Return(ReturnStmt { arg: None, .. })) = statements.last() {
1290
- statements.pop();
1291
- }
1292
- let original = Function {
1293
- params: function.params[1..].to_vec(),
1294
- span: function.span,
1295
- ctxt: function.ctxt,
1296
- body: Some(BlockStmt {
1297
- span: block.span,
1298
- ctxt: block.ctxt,
1299
- stmts: statements,
1300
- }),
1301
- ..Function::default()
1302
- };
1303
- let binding = (
1304
- name.0.clone(),
1305
- SyntaxContext::empty().apply_mark(Mark::new()),
1306
- );
1307
- cases.push((label, binding.clone()));
1308
- originals.push((binding, original));
1309
- }
1310
- (!cases.is_empty()).then_some((Self { mask, cases }, originals))
1311
- }
1312
-
1313
- /// Returns the original function selected by `selector`.
1314
- fn original(&self, selector: f64) -> Option<&Id> {
1315
- let chosen = f64::from(js::int32(self.mask) ^ js::int32(selector));
1316
- self.cases
1616
+ /// Each original keeps the merged function's other parameters.
1617
+ fn merged<'a>(function: &Body<'a>, constants: &Constants<'a>) -> Option<Selection<Body<'a>>> {
1618
+ let selector = plain_parameter(function.parameters.first()?)?;
1619
+ let (mask, switch, _) = selection(function, selector, constants)?;
1620
+ let mut cases = Vec::new();
1621
+ for (at, case) in switch.cases.iter().enumerate() {
1622
+ let label = case.test.as_ref().and_then(|test| number(test, constants));
1623
+ // Labels sharing a body fall through to it.
1624
+ let body = switch.cases[at..]
1317
1625
  .iter()
1318
- .find(|(label, _)| *label == chosen)
1319
- .map(|(_, original)| original)
1626
+ .map(|case| &case.consequent)
1627
+ .find(|body| !body.is_empty());
1628
+ let (Some(label), Some(body)) = (label, body) else {
1629
+ continue;
1630
+ };
1631
+ let (mut head, mut tail): (&[Statement], &[Statement]) = match &body[..] {
1632
+ [Statement::BlockStatement(original), rest @ ..] => (&original.body[..], rest),
1633
+ body => (body, &[]),
1634
+ };
1635
+ let last = if tail.is_empty() {
1636
+ &mut head
1637
+ } else {
1638
+ &mut tail
1639
+ };
1640
+ if let [statements @ .., Statement::ReturnStatement(returned)] = *last
1641
+ && returned.argument.is_none()
1642
+ {
1643
+ *last = statements;
1644
+ }
1645
+ let body = Body {
1646
+ parameters: &function.parameters[1..],
1647
+ rest: function.rest,
1648
+ prologue: false,
1649
+ head,
1650
+ tail,
1651
+ };
1652
+ cases.push((label, body));
1320
1653
  }
1654
+ (!cases.is_empty()).then_some(Selection { mask, cases })
1321
1655
  }
1322
1656
 
1323
1657
  /// Storage location in a scope: a binding or a constant array slot.
1324
- #[derive(Clone, Debug, PartialEq, Eq, Hash)]
1325
- enum Holder {
1326
- Name(Id),
1327
- Slot(Id, usize),
1658
+ #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
1659
+ enum Holder<'a> {
1660
+ Name(Binding<'a>),
1661
+ Slot(Binding<'a>, usize),
1328
1662
  }
1329
1663
 
1330
1664
  /// A function's local aliases, string constants, and forwarders.
1331
- struct Scope<'script> {
1332
- appliers: &'script Appliers,
1665
+ struct Scope<'a, 's> {
1666
+ appliers: &'s Appliers<'a>,
1333
1667
  /// V8's name prefix for functions assigned here, such as `Owner.`.
1334
1668
  prefix: String,
1335
- forwarders: Forwarders,
1669
+ forwarders: Forwarders<'a>,
1336
1670
  /// Assignment count for each storage location. Only values assigned once are known.
1337
- assigned: HashMap<Holder, usize>,
1338
- aliases: HashMap<Id, Id>,
1339
- strings: HashMap<Id, String>,
1671
+ assigned: HashMap<Holder<'a>, usize>,
1672
+ aliases: HashMap<Binding<'a>, Binding<'a>>,
1673
+ strings: HashMap<Binding<'a>, &'a str>,
1340
1674
  }
1341
1675
 
1342
1676
  /// Frames for an object function that forwards its first parameter with the remaining arguments.
@@ -1348,170 +1682,215 @@ struct Forwarder {
1348
1682
  plain: Vec<Call>,
1349
1683
  }
1350
1684
 
1351
- impl<'script> Scope<'script> {
1685
+ impl<'a, 's> Scope<'a, 's> {
1352
1686
  /// `name` is empty for anonymous functions. V8 prefixes the names of functions assigned
1353
1687
  /// inside a capitalized function with its name, as it does for constructors.
1354
- fn new(name: &str, function: &Function, appliers: &'script Appliers) -> Self {
1355
- let constructor = name.starts_with(char::is_uppercase);
1688
+ fn new(name: &str, function: &Body<'a>, appliers: &'s Appliers<'a>) -> Self {
1356
1689
  let mut scope = Self {
1357
1690
  appliers,
1358
- prefix: constructor.then(|| format!("{name}.")).unwrap_or_default(),
1691
+ prefix: if name.starts_with(char::is_uppercase) {
1692
+ format!("{name}.")
1693
+ } else {
1694
+ String::new()
1695
+ },
1359
1696
  forwarders: Forwarders::default(),
1360
1697
  assigned: HashMap::new(),
1361
1698
  aliases: HashMap::new(),
1362
1699
  strings: HashMap::new(),
1363
1700
  };
1364
- function.body.visit_with(&mut scope);
1701
+ function.visit(&mut scope);
1365
1702
  scope.forwarders.retain_assigned_once(&scope.assigned);
1366
1703
  scope
1367
1704
  }
1368
1705
 
1369
- fn target(&self, call: &CallExpr) -> Result<Invocation> {
1370
- let mut target = Invocation {
1371
- callee: None,
1372
- method: false,
1373
- helpers: Vec::new(),
1374
- site: Site::new(call),
1375
- passed: None,
1376
- listed: false,
1377
- slot: None,
1378
- };
1379
- let Some(callee) = call.callee.as_expr() else {
1380
- return Ok(target);
1706
+ fn js(&self) -> ast::Script<'a> {
1707
+ self.appliers.js()
1708
+ }
1709
+
1710
+ fn target(&self, call: &'a CallExpression<'a>) -> Result<Invocation<'a>> {
1711
+ self.resolve(call, None)
1712
+ }
1713
+
1714
+ /// Resolves `call`, reading arguments through `copies` when given.
1715
+ fn resolve(
1716
+ &self,
1717
+ call: &'a CallExpression<'a>,
1718
+ copies: Option<&Copies<'a, '_>>,
1719
+ ) -> Result<Invocation<'a>> {
1720
+ let site = Site::new(call);
1721
+ let arguments = Arguments {
1722
+ list: &call.arguments,
1723
+ copies,
1381
1724
  };
1382
- let arguments = call.args.len();
1383
- let (callee, detached) = undetached(callee, &self.appliers.constants);
1725
+ let (callee, detached) = undetached(&call.callee, &self.appliers.constants);
1384
1726
  // Resolve the function called by `target`.
1385
- let mut function = match callee {
1386
- Expr::Ident(name) => {
1387
- if let Some(original) = self.merged_call(name, call) {
1388
- // The original function uses the merged function's frame at this call site.
1389
- let mut target = self.target(&original)?;
1390
- target.site = Site::new(call);
1391
- return Ok(target);
1392
- }
1393
- if let Some((applied, function)) = self.applier_call(name, call)? {
1394
- target = applied;
1395
- Some(function)
1396
- } else {
1397
- target.passed = Some(arguments);
1398
- Some(callee)
1399
- }
1727
+ if let Expression::Identifier(name) = callee {
1728
+ let binding = self.js().binding(name);
1729
+ if let Some((original, arguments)) = self.merged_call(binding, arguments) {
1730
+ // The original function uses the merged function's frame at this call site.
1731
+ let original = Callee::Original(original);
1732
+ return self.named(original, Operand::Resolved(original), arguments, site);
1400
1733
  }
1734
+ return self.named(
1735
+ Callee::Binding(binding),
1736
+ Operand::Expression(callee),
1737
+ arguments,
1738
+ site,
1739
+ );
1740
+ }
1741
+ let mut target = Invocation::at(site);
1742
+ let count = arguments.list.len();
1743
+ let function = match member(callee) {
1401
1744
  // Some builds keep the key in a local: `handler[c](this)` with `c = "call"`.
1402
- Expr::Member(member)
1403
- if !detached && member.obj.is_ident() && self.key(&member.prop) == Some("call") =>
1745
+ Some(member)
1746
+ if !detached
1747
+ && matches!(member.object(), Expression::Identifier(_))
1748
+ && self.key(member) == Some("call") =>
1404
1749
  {
1405
1750
  target.method = true;
1406
- target.passed = Some(arguments.saturating_sub(1));
1407
- Some(&*member.obj)
1751
+ target.passed = Some(count.saturating_sub(1));
1752
+ Some(Operand::Expression(member.object()))
1408
1753
  }
1409
1754
  // The first argument to a forwarder is the function it calls.
1410
- Expr::Member(member) if let Some(forwarder) = self.member_forwarder(member) => {
1755
+ Some(member) if let Some(forwarder) = self.member_forwarder(member) => {
1411
1756
  target.helpers = if detached {
1412
1757
  forwarder.plain.clone()
1413
1758
  } else {
1414
1759
  forwarder.method.clone()
1415
1760
  };
1416
- target.passed = Some(arguments.saturating_sub(1));
1417
- call.args.first().map(|first| &*first.expr)
1761
+ target.passed = Some(count.saturating_sub(1));
1762
+ arguments
1763
+ .list
1764
+ .first()
1765
+ .map(|first| arguments.argument(first))
1418
1766
  }
1419
1767
  // Resolve an array-stored function, as in `(0, slots[i])(f, a)`.
1420
- Expr::Member(member) if self.slot(member).is_some() => {
1421
- target.passed = Some(arguments);
1422
- Some(callee)
1768
+ Some(member) if self.slot(member).is_some() => {
1769
+ target.passed = Some(count);
1770
+ Some(Operand::Expression(callee))
1423
1771
  }
1424
1772
  _ => None,
1425
1773
  };
1774
+ Ok(self.finish(target, function, arguments))
1775
+ }
1776
+
1777
+ /// Resolves a call to the function `callee`, read as `operand`, directly or through a call
1778
+ /// helper.
1779
+ fn named(
1780
+ &self,
1781
+ callee: Callee<'a>,
1782
+ operand: Operand<'a>,
1783
+ arguments: Arguments<'a, '_>,
1784
+ site: Site,
1785
+ ) -> Result<Invocation<'a>> {
1786
+ let (target, function) = match self.applier_call(callee, arguments, site)? {
1787
+ Some(applied) => applied,
1788
+ None => {
1789
+ let mut target = Invocation::at(site);
1790
+ target.passed = Some(arguments.list.len());
1791
+ (target, operand)
1792
+ }
1793
+ };
1794
+ Ok(self.finish(target, Some(function), arguments))
1795
+ }
1796
+
1797
+ /// Follows stored forwarders from `function`, then records the resolved callee and slot.
1798
+ fn finish(
1799
+ &self,
1800
+ mut target: Invocation<'a>,
1801
+ mut function: Option<Operand<'a>>,
1802
+ arguments: Arguments<'a, '_>,
1803
+ ) -> Invocation<'a> {
1426
1804
  // A stored forwarder calls its first argument with the remaining arguments.
1427
- while let Some(expression) = function
1428
- && let Some(frames) = self.held_by(expression)
1429
- && let Some(first) = handed(call, &target).and_then(|handed| handed.first().copied())
1805
+ while let Some(operand) = function
1806
+ && let Some(frames) = self.held_by(operand)
1807
+ && let Some(first) =
1808
+ handed(arguments, &target).and_then(|handed| handed.first().copied())
1430
1809
  {
1431
1810
  function = Some(first);
1432
1811
  target.helpers = frames.iter().cloned().chain(target.helpers).collect();
1433
1812
  target.passed = target.passed.map(|passed| passed - 1);
1434
1813
  }
1435
- target.callee = function.and_then(name);
1814
+ target.callee = function.and_then(|function| function.callee(&self.appliers.constants));
1436
1815
  target.slot = function.and_then(|function| match self.holder(function)? {
1437
1816
  Holder::Slot(array, index) => Some((array, index)),
1438
1817
  Holder::Name(_) => None,
1439
1818
  });
1440
- Ok(target)
1441
- }
1442
-
1443
- /// Converts `merged(selector, a, b)` to `original(a, b)` for the selected original function.
1444
- fn merged_call(&self, callee: &Ident, call: &CallExpr) -> Option<CallExpr> {
1445
- let merged = self.appliers.merged.get(&callee.to_id())?;
1446
- let (selector, arguments) = call.args.split_first()?;
1447
- let (name, context) = merged
1448
- .original(self.appliers.number(&selector.expr)?)?
1449
- .clone();
1450
- Some(CallExpr {
1451
- callee: Callee::Expr(Box::new(Expr::Ident(Ident::new(
1452
- name,
1453
- callee.span,
1454
- context,
1455
- )))),
1456
- args: arguments.to_vec(),
1457
- ..call.clone()
1458
- })
1819
+ target
1820
+ }
1821
+
1822
+ /// Resolves `merged(selector, a, b)` to the selected original function and the arguments
1823
+ /// `a, b`.
1824
+ fn merged_call<'c>(
1825
+ &self,
1826
+ callee: Binding<'a>,
1827
+ arguments: Arguments<'a, 'c>,
1828
+ ) -> Option<(usize, Arguments<'a, 'c>)> {
1829
+ let merged = self.appliers.merged.get(&callee)?;
1830
+ let (selector, rest) = arguments.list.split_first()?;
1831
+ let original = merged.select(self.appliers.number(arguments.argument(selector))?)?;
1832
+ Some((
1833
+ original,
1834
+ Arguments {
1835
+ list: rest,
1836
+ copies: arguments.copies,
1837
+ },
1838
+ ))
1459
1839
  }
1460
1840
 
1461
1841
  /// Resolves `applier(selector, f, [args])` or `applier(selector, f, a, b)` through a call
1462
1842
  /// helper. Also returns the called function `f`.
1463
- fn applier_call<'call>(
1843
+ fn applier_call(
1464
1844
  &self,
1465
- callee: &Ident,
1466
- call: &'call CallExpr,
1467
- ) -> Result<Option<(Invocation, &'call Expr)>> {
1845
+ callee: Callee<'a>,
1846
+ arguments: Arguments<'a, '_>,
1847
+ site: Site,
1848
+ ) -> Result<Option<(Invocation<'a>, Operand<'a>)>> {
1468
1849
  let (Some(applier), [selector, function, passed @ ..]) =
1469
- (self.appliers.helpers.get(&callee.to_id()), &call.args[..])
1850
+ (self.appliers.helpers.get(&callee), arguments.list)
1470
1851
  else {
1471
1852
  return Ok(None);
1472
1853
  };
1473
- let Some(selector) = self.appliers.number(&selector.expr) else {
1854
+ let Some(selector) = self.appliers.number(arguments.argument(selector)) else {
1474
1855
  return Ok(None);
1475
1856
  };
1857
+ let name = self.appliers.name(callee);
1476
1858
  let inner = applier
1477
- .call(selector)
1478
- .with_context(|| format!("{} has no case for selector {selector}", callee.sym))?;
1859
+ .select(selector)
1860
+ .with_context(|| format!("{name} has no case for selector {selector}"))?;
1479
1861
  let (passed, listed) = match passed {
1480
- [list] if let Some(list) = list.expr.unwrap_parens().as_array() => {
1481
- (list.elems.len(), true)
1862
+ [list] if let Some(list) = array(ast::argument_expression(list)) => {
1863
+ (list.elements.len(), true)
1482
1864
  }
1483
1865
  passed => (passed.len(), false),
1484
1866
  };
1485
- let invocation = Invocation {
1486
- callee: None,
1487
- method: false,
1488
- helpers: vec![Call {
1489
- name: Name::same(callee.sym.to_string()),
1490
- site: inner,
1491
- }],
1492
- site: Site::new(call),
1493
- passed: Some(passed),
1494
- listed,
1495
- slot: None,
1496
- };
1497
- Ok(Some((invocation, &function.expr)))
1867
+ let mut invocation = Invocation::at(site);
1868
+ invocation.helpers = vec![Call {
1869
+ name: Name::same(name.to_owned()),
1870
+ site: inner,
1871
+ }];
1872
+ invocation.passed = Some(passed);
1873
+ invocation.listed = listed;
1874
+ Ok(Some((invocation, arguments.argument(function))))
1498
1875
  }
1499
1876
 
1500
1877
  /// Resolves a member key from a literal or a local string binding.
1501
- fn key<'member>(&'member self, property: &'member MemberProp) -> Option<&'member str> {
1502
- match property {
1503
- MemberProp::Computed(computed) if let Expr::Ident(name) = &*computed.expr => {
1504
- self.strings.get(&name.to_id()).map(String::as_str)
1878
+ fn key(&self, member: &MemberExpression<'a>) -> Option<&'a str> {
1879
+ match member {
1880
+ MemberExpression::ComputedMemberExpression(computed)
1881
+ if let Expression::Identifier(name) = &computed.expression =>
1882
+ {
1883
+ self.strings.get(&self.js().binding(name)).copied()
1505
1884
  }
1506
- property => ast::member_str(property),
1885
+ member => ast::member_str(member),
1507
1886
  }
1508
1887
  }
1509
1888
 
1510
1889
  /// Finds the forwarder read by `object.key`.
1511
- fn member_forwarder(&self, member: &MemberExpr) -> Option<&Forwarder> {
1890
+ fn member_forwarder(&self, member: &'a MemberExpression<'a>) -> Option<&Forwarder> {
1512
1891
  let key = (
1513
- self.holder(&member.obj)?,
1514
- self.key(&member.prop)?.to_owned(),
1892
+ self.holder(Operand::Expression(member.object()))?,
1893
+ self.key(member)?,
1515
1894
  );
1516
1895
  self.forwarders
1517
1896
  .on_objects
@@ -1519,74 +1898,85 @@ impl<'script> Scope<'script> {
1519
1898
  .or_else(|| self.appliers.forwarders.on_objects.get(&key))
1520
1899
  }
1521
1900
 
1522
- /// Returns frames for the stored forwarder read by `expression`.
1523
- fn held_by(&self, expression: &Expr) -> Option<&Vec<Call>> {
1524
- let holder = self.holder(expression)?;
1901
+ /// Returns frames for the stored forwarder read by `operand`.
1902
+ fn held_by(&self, operand: Operand<'a>) -> Option<&Vec<Call>> {
1903
+ let holder = self.holder(operand)?;
1525
1904
  self.forwarders
1526
1905
  .held
1527
1906
  .get(&holder)
1528
1907
  .or_else(|| self.appliers.forwarders.held.get(&holder))
1529
1908
  }
1530
1909
 
1531
- /// Resolves the value read by `expression`, following local aliases.
1532
- fn holder(&self, expression: &Expr) -> Option<Holder> {
1533
- match expression.unwrap_parens() {
1534
- Expr::Ident(name) => Some(Holder::Name(self.object(&name.to_id()))),
1535
- Expr::Member(member) => self.slot(member),
1536
- _ => None,
1910
+ /// Resolves the value read by `operand`, following local aliases. An original function is
1911
+ /// never stored.
1912
+ fn holder(&self, operand: Operand<'a>) -> Option<Holder<'a>> {
1913
+ match operand {
1914
+ Operand::Expression(expression) => match expression.without_parentheses() {
1915
+ Expression::Identifier(name) => {
1916
+ Some(Holder::Name(self.object(self.js().binding(name))))
1917
+ }
1918
+ expression => self.slot(member(expression)?),
1919
+ },
1920
+ Operand::Resolved(Callee::Binding(binding)) => Some(Holder::Name(self.object(binding))),
1921
+ Operand::Resolved(Callee::Original(_)) => None,
1537
1922
  }
1538
1923
  }
1539
1924
 
1540
1925
  /// Resolves `array[index]` when the index is constant.
1541
- fn slot(&self, member: &MemberExpr) -> Option<Holder> {
1542
- let array = member.obj.as_ident()?;
1543
- let index = self.appliers.number(&member.prop.as_computed()?.expr)?;
1926
+ fn slot(&self, member: &MemberExpression<'a>) -> Option<Holder<'a>> {
1927
+ let MemberExpression::ComputedMemberExpression(member) = member else {
1928
+ return None;
1929
+ };
1930
+ let Expression::Identifier(array) = &member.object else {
1931
+ return None;
1932
+ };
1933
+ let index = number(&member.expression, &self.appliers.constants)?;
1544
1934
  Some(Holder::Slot(
1545
- self.object(&array.to_id()),
1935
+ self.object(self.js().binding(array)),
1546
1936
  ast::array_index(index)?,
1547
1937
  ))
1548
1938
  }
1549
1939
 
1550
1940
  /// Resolves the object held by `name` through local copies.
1551
- fn object(&self, name: &Id) -> Id {
1941
+ fn object(&self, name: Binding<'a>) -> Binding<'a> {
1552
1942
  let mut name = name;
1553
1943
  for _ in 0..self.aliases.len() {
1554
- match self.aliases.get(name) {
1555
- Some(original) => name = original,
1944
+ match self.aliases.get(&name) {
1945
+ Some(&original) => name = original,
1556
1946
  None => break,
1557
1947
  }
1558
1948
  }
1559
- name.to_owned()
1949
+ name
1560
1950
  }
1561
1951
 
1562
1952
  /// Records the value stored by assigning `value` to `holder`.
1563
- fn bind(&mut self, holder: Holder, value: &Expr) {
1564
- *self.assigned.entry(holder.clone()).or_default() += 1;
1953
+ fn bind(&mut self, holder: Holder<'a>, value: &'a Expression<'a>) {
1954
+ *self.assigned.entry(holder).or_default() += 1;
1565
1955
  // Chained assignments store the innermost value in each target.
1566
- let mut value = value.unwrap_parens();
1567
- while let Expr::Assign(inner) = value
1568
- && inner.op == AssignOp::Assign
1956
+ let mut value = value.without_parentheses();
1957
+ while let Expression::AssignmentExpression(inner) = value
1958
+ && inner.operator == AssignmentOperator::Assign
1569
1959
  {
1570
- value = inner.right.unwrap_parens();
1960
+ value = inner.right.without_parentheses();
1571
1961
  }
1572
- let forwarder = match value {
1573
- Expr::Member(member) if let Some(forwarder) = self.member_forwarder(member) => {
1962
+ let forwarder = match member(value) {
1963
+ Some(member) if let Some(forwarder) = self.member_forwarder(member) => {
1574
1964
  Some(forwarder.plain.clone())
1575
1965
  }
1576
- value => self.held_by(value).cloned(),
1966
+ _ => self.held_by(Operand::Expression(value)).cloned(),
1577
1967
  };
1578
1968
  if let Some(frames) = forwarder {
1579
1969
  self.forwarders.held.insert(holder, frames);
1580
1970
  return;
1581
1971
  }
1582
1972
  match (holder, value) {
1583
- (Holder::Name(name), Expr::Ident(original)) => {
1584
- self.aliases.insert(name, original.to_id());
1973
+ (Holder::Name(name), Expression::Identifier(original)) => {
1974
+ self.aliases.insert(name, self.js().binding(original));
1585
1975
  }
1586
- (holder, Expr::Object(object)) => self.literal(&holder, object),
1976
+ (holder, Expression::ObjectExpression(object)) => self.literal(holder, object),
1587
1977
  (Holder::Name(name), value) => {
1588
1978
  if let Some(text) = ast::static_str(value) {
1589
- self.strings.insert(name, text.to_owned());
1979
+ self.strings.insert(name, text);
1590
1980
  }
1591
1981
  }
1592
1982
  _ => {}
@@ -1595,26 +1985,20 @@ impl<'script> Scope<'script> {
1595
1985
 
1596
1986
  /// Records forwarders defined by an object literal assigned to `holder`. Uses property keys as
1597
1987
  /// function names, including computed keys.
1598
- fn literal(&mut self, holder: &Holder, object: &ObjectLit) {
1599
- for property in &object.props {
1600
- let (key, function) = match property.as_prop().map(|property| &**property) {
1601
- Some(Prop::KeyValue(property)) if let Expr::Fn(function) = &*property.value => {
1602
- (&property.key, &*function.function)
1603
- }
1604
- Some(Prop::Method(method)) => (&method.key, &*method.function),
1605
- _ => continue,
1606
- };
1607
- let Some(key) = ast::static_key_str(key) else {
1608
- continue;
1609
- };
1610
- if let Some(frames) = self.forwarder(function, Name::same(key.to_owned())) {
1988
+ fn literal(&mut self, holder: Holder<'a>, object: &'a ObjectExpression<'a>) {
1989
+ // Matches `key: function` properties and methods, but not accessors.
1990
+ for property in &object.properties {
1991
+ if let ObjectPropertyKind::ObjectProperty(property) = property
1992
+ && let Expression::FunctionExpression(function) = &property.value
1993
+ && property.kind == PropertyKind::Init
1994
+ && let Some(key) = ast::static_key_str(&property.key, property.computed)
1995
+ && let Some(frames) = self.forwarder(function, Name::same(key.to_owned()))
1996
+ {
1611
1997
  let forwarder = Forwarder {
1612
1998
  method: frames.clone(),
1613
1999
  plain: frames,
1614
2000
  };
1615
- self.forwarders
1616
- .on_objects
1617
- .insert((holder.clone(), key.to_owned()), forwarder);
2001
+ self.forwarders.on_objects.insert((holder, key), forwarder);
1618
2002
  }
1619
2003
  }
1620
2004
  }
@@ -1623,168 +2007,168 @@ impl<'script> Scope<'script> {
1623
2007
  /// later parameters. Accepts direct calls, array copies such as `(g = [f, b], (0, g[0])(a,
1624
2008
  /// g[1]))`, and call helpers. Extra parameters can act as locals. Allows local declarations
1625
2009
  /// before the call.
1626
- fn forwarder(&self, function: &Function, frame: Name) -> Option<Vec<Call>> {
1627
- let parameters = parameters(function)?;
2010
+ fn forwarder(&self, function: &'a Function<'a>, frame: Name) -> Option<Vec<Call>> {
2011
+ let constants = &self.appliers.constants;
2012
+ let function = Body::of(function);
2013
+ let parameters = function.parameters()?;
1628
2014
  let (first, rest) = parameters.split_first()?;
1629
- let mut arrays = Copies::new(&self.appliers.constants);
1630
- let [Stmt::Return(returned)] = after_declarations(&function.body.as_ref()?.stmts) else {
2015
+ let first = Binding::Symbol(*first);
2016
+ let mut arrays = Copies::new(constants);
2017
+ let Statement::ReturnStatement(returned) = function.only_statement()? else {
1631
2018
  return None;
1632
2019
  };
1633
- let mut value = returned.arg.as_deref()?.unwrap_parens();
1634
- if let Expr::Seq(sequence) = value {
1635
- let (last, before) = sequence.exprs.split_last()?;
2020
+ let mut value = returned.argument.as_ref()?.without_parentheses();
2021
+ if let Expression::SequenceExpression(sequence) = value {
2022
+ let (last, before) = sequence.expressions.split_last()?;
1636
2023
  for expression in before {
1637
2024
  // Obfuscation leaves expressions that do nothing.
1638
- if arrays.record(expression).is_none()
1639
- && !is_inert(expression, &self.appliers.constants)
1640
- {
2025
+ if arrays.record(expression).is_none() && !is_inert(expression, constants) {
1641
2026
  return None;
1642
2027
  }
1643
2028
  }
1644
- value = last.unwrap_parens();
2029
+ value = last.without_parentheses();
1645
2030
  }
1646
2031
  // Forwarded arguments must match the parameters after the target function.
1647
- let passes_on = |arguments: &[&Expr]| {
2032
+ let passes_on = |arguments: &[Operand<'a>]| {
1648
2033
  arguments.len() <= rest.len()
1649
2034
  && arguments.iter().zip(rest).all(|(argument, parameter)| {
1650
- arrays.resolve(argument).as_ref() == Some(parameter)
2035
+ arrays.resolve_operand(*argument) == Some(Binding::Symbol(*parameter))
1651
2036
  })
1652
2037
  };
1653
- let call = value.as_call()?;
1654
- let (callee, _) = undetached(call.callee.as_expr()?, &self.appliers.constants);
1655
- if call.args.iter().any(|argument| argument.spread.is_some()) {
2038
+ let Expression::CallExpression(call) = value else {
1656
2039
  return None;
1657
- }
1658
- let arguments: Vec<&Expr> = call.args.iter().map(|argument| &*argument.expr).collect();
1659
- if arrays.resolve(callee).as_ref() == Some(first) && passes_on(&arguments) {
2040
+ };
2041
+ let (callee, _) = undetached(&call.callee, constants);
2042
+ // A spread has no expression, so it rejects the call.
2043
+ let arguments: Vec<Operand<'a>> = call
2044
+ .arguments
2045
+ .iter()
2046
+ .map(|argument| argument.as_expression().map(Operand::Expression))
2047
+ .collect::<Option<_>>()?;
2048
+ if arrays.resolve(callee) == Some(first) && passes_on(&arguments) {
1660
2049
  return Some(vec![Call {
1661
2050
  name: frame,
1662
2051
  site: Site::new(call),
1663
2052
  }]);
1664
2053
  }
1665
2054
  // Resolve copied names passed through a call helper.
1666
- let mut call = call.clone();
1667
- for argument in &mut call.args {
1668
- let copied = match argument.expr.unwrap_parens() {
1669
- Expr::Array(list) => {
1670
- let mut list = list.clone();
1671
- for element in list.elems.iter_mut().flatten() {
1672
- if let Some(name) = arrays.resolve(&element.expr) {
1673
- *element.expr =
1674
- Expr::Ident(Ident::new(name.0, element.expr.span(), name.1));
1675
- }
1676
- }
1677
- Expr::Array(list)
1678
- }
1679
- expression => match arrays.resolve(expression) {
1680
- Some(name) => Expr::Ident(Ident::new(name.0, expression.span(), name.1)),
1681
- None => continue,
1682
- },
1683
- };
1684
- *argument.expr = copied;
1685
- }
1686
- let target = self.target(&call).ok()?;
2055
+ let target = self.resolve(call, Some(&arrays)).ok()?;
2056
+ let copied = Arguments {
2057
+ list: &call.arguments,
2058
+ copies: Some(&arrays),
2059
+ };
1687
2060
  (!target.helpers.is_empty()
1688
- && target.callee.as_ref() == Some(first)
1689
- && passes_on(&handed(&call, &target)?))
2061
+ && target.callee == Some(Callee::Binding(first))
2062
+ && passes_on(&handed(copied, &target)?))
1690
2063
  .then(|| target.frames(frame))
1691
2064
  }
1692
2065
  }
1693
2066
 
1694
2067
  /// Whether `expression` has no effect, such as obfuscation's `true`, constant comparisons and
1695
- /// Matches `void` expressions, including those using numeric `constants`.
1696
- fn is_inert(expression: &Expr, constants: &HashMap<Id, f64>) -> bool {
1697
- let inert = |expression: &Expr| is_inert(expression, constants);
1698
- match expression.unwrap_parens() {
1699
- Expr::Lit(_) => true,
1700
- Expr::Ident(name) => constants.contains_key(&name.to_id()),
1701
- Expr::Bin(binary) => inert(&binary.left) && inert(&binary.right),
1702
- Expr::Unary(unary) => unary.op != UnaryOp::Delete && inert(&unary.arg),
1703
- Expr::Array(array) => array
1704
- .elems
2068
+ /// `void` expressions, including those using numeric `constants`.
2069
+ fn is_inert<'a>(expression: &Expression<'a>, constants: &Constants<'a>) -> bool {
2070
+ let inert = |expression: &Expression<'a>| is_inert(expression, constants);
2071
+ match expression.without_parentheses() {
2072
+ expression if expression.is_literal() => true,
2073
+ Expression::Identifier(name) => constants
2074
+ .js
2075
+ .symbol(name)
2076
+ .is_some_and(|symbol| constants.values.contains_key(&symbol)),
2077
+ Expression::BinaryExpression(binary) => inert(&binary.left) && inert(&binary.right),
2078
+ Expression::LogicalExpression(logical) => inert(&logical.left) && inert(&logical.right),
2079
+ Expression::UnaryExpression(unary) => {
2080
+ unary.operator != UnaryOperator::Delete && inert(&unary.argument)
2081
+ }
2082
+ Expression::ArrayExpression(array) => array
2083
+ .elements
1705
2084
  .iter()
1706
- .all(|element| element.as_ref().is_none_or(|element| inert(&element.expr))),
2085
+ .all(|element| element_expression(element).is_none_or(inert)),
1707
2086
  _ => false,
1708
2087
  }
1709
2088
  }
1710
2089
 
1711
2090
  /// Resolves the function produced by `callee` and checks whether a side-effect-free first operand
1712
2091
  /// detaches its receiver. For example, `(0, f)(a)` calls `f` without a receiver.
1713
- fn undetached<'expression>(
1714
- callee: &'expression Expr,
1715
- constants: &HashMap<Id, f64>,
1716
- ) -> (&'expression Expr, bool) {
1717
- let callee = callee.unwrap_parens();
1718
- if let Expr::Seq(sequence) = callee
1719
- && let [discarded, last] = &sequence.exprs[..]
2092
+ fn undetached<'b, 'a>(
2093
+ callee: &'b Expression<'a>,
2094
+ constants: &Constants<'a>,
2095
+ ) -> (&'b Expression<'a>, bool) {
2096
+ let callee = callee.without_parentheses();
2097
+ if let Expression::SequenceExpression(sequence) = callee
2098
+ && let [discarded, last] = &sequence.expressions[..]
1720
2099
  && is_inert(discarded, constants)
1721
2100
  {
1722
- return (last.unwrap_parens(), true);
2101
+ return (last.without_parentheses(), true);
1723
2102
  }
1724
2103
  (callee, false)
1725
2104
  }
1726
2105
 
1727
- impl Visit for Scope<'_> {
1728
- fn visit_function(&mut self, _: &Function) {}
1729
- fn visit_class(&mut self, _: &Class) {}
1730
-
1731
- fn visit_assign_expr(&mut self, assign: &AssignExpr) {
1732
- if assign.op == AssignOp::Assign {
1733
- match &assign.left {
1734
- AssignTarget::Simple(SimpleAssignTarget::Ident(name)) => {
1735
- self.bind(Holder::Name(name.to_id()), &assign.right);
1736
- }
1737
- AssignTarget::Simple(SimpleAssignTarget::Member(member)) => {
1738
- if let Some(slot) = self.slot(member) {
1739
- self.bind(slot, &assign.right);
1740
- } else if let Expr::Fn(function) = &*assign.right
1741
- && let Some(object) = self.holder(&member.obj)
1742
- && let Some(path) = inferred_path(&member.obj)
1743
- && let Some(name) = ast::member_str(&member.prop)
1744
- {
1745
- // V8 infers the name of an anonymous function from the member it is
1746
- // assigned to.
1747
- let path = format!("{}{path}", self.prefix);
1748
- let (inferred, method) = if member.prop.is_computed() {
2106
+ impl<'a> Visit<'a> for Scope<'a, '_> {
2107
+ fn visit_function(&mut self, _: &Function<'a>, _: ScopeFlags) {}
2108
+ fn visit_class(&mut self, _: &Class<'a>) {}
2109
+ fn visit_object_property(&mut self, property: &ObjectProperty<'a>) {
2110
+ walk_property(self, property);
2111
+ }
2112
+
2113
+ fn visit_assignment_expression(&mut self, assignment: &AssignmentExpression<'a>) {
2114
+ let assignment = self
2115
+ .js()
2116
+ .lend(assignment, AstKind::as_assignment_expression);
2117
+ if assignment.operator == AssignmentOperator::Assign {
2118
+ if let AssignmentTarget::AssignmentTargetIdentifier(name) = &assignment.left {
2119
+ self.bind(Holder::Name(self.js().binding(name)), &assignment.right);
2120
+ } else if let Some(member) = assigned_member(&assignment.left) {
2121
+ if let Some(slot) = self.slot(member) {
2122
+ self.bind(slot, &assignment.right);
2123
+ } else if let Expression::FunctionExpression(function) = &assignment.right
2124
+ && let Some(object) = self.holder(Operand::Expression(member.object()))
2125
+ && let Some(path) = inferred_path(member.object())
2126
+ && let Some(name) = ast::member_str(member)
2127
+ {
2128
+ // V8 infers the name of an anonymous function from the member it is
2129
+ // assigned to.
2130
+ let path = format!("{}{path}", self.prefix);
2131
+ let (inferred, method) =
2132
+ if matches!(member, MemberExpression::ComputedMemberExpression(_)) {
1749
2133
  let inferred = format!("{path}.<computed>");
1750
2134
  (inferred.clone(), format!("{inferred} [as {name}]"))
1751
2135
  } else {
1752
2136
  let inferred = format!("{path}.{name}");
1753
2137
  (inferred.clone(), inferred)
1754
2138
  };
1755
- let frames = |name: String| {
1756
- self.forwarder(&function.function, Name::anonymous(name))
1757
- };
1758
- if let (Some(method), Some(plain)) = (frames(method), frames(inferred)) {
1759
- self.forwarders
1760
- .on_objects
1761
- .insert((object, name.to_owned()), Forwarder { method, plain });
1762
- }
2139
+ let frames = |name: String| self.forwarder(function, Name::anonymous(name));
2140
+ if let (Some(method), Some(plain)) = (frames(method), frames(inferred)) {
2141
+ self.forwarders
2142
+ .on_objects
2143
+ .insert((object, name), Forwarder { method, plain });
1763
2144
  }
1764
2145
  }
1765
- _ => {}
1766
2146
  }
1767
2147
  }
1768
- assign.visit_children_with(self);
2148
+ walk::walk_assignment_expression(self, assignment);
1769
2149
  }
1770
2150
 
1771
- fn visit_var_declarator(&mut self, declarator: &VarDeclarator) {
1772
- if let Pat::Ident(name) = &declarator.name
2151
+ fn visit_variable_declarator(&mut self, declarator: &VariableDeclarator<'a>) {
2152
+ let declarator = self.js().lend(declarator, AstKind::as_variable_declarator);
2153
+ if let BindingPattern::BindingIdentifier(name) = &declarator.id
1773
2154
  && let Some(init) = &declarator.init
1774
2155
  {
1775
- self.bind(Holder::Name(name.to_id()), init);
2156
+ self.bind(Holder::Name(Binding::Symbol(name.symbol_id())), init);
1776
2157
  }
1777
- declarator.visit_children_with(self);
2158
+ walk::walk_variable_declarator(self, declarator);
1778
2159
  }
1779
2160
  }
1780
2161
 
1781
2162
  /// Returns the V8 name inferred from an assignment target: `object` for an object or
1782
2163
  /// `array.<computed>` for an array slot.
1783
- fn inferred_path(object: &Expr) -> Option<String> {
1784
- match object.unwrap_parens() {
1785
- Expr::Ident(name) => Some(name.sym.to_string()),
1786
- Expr::Member(member) if member.prop.is_computed() => {
1787
- Some(format!("{}.<computed>", member.obj.as_ident()?.sym))
2164
+ fn inferred_path(object: &Expression<'_>) -> Option<String> {
2165
+ match object.without_parentheses() {
2166
+ Expression::Identifier(name) => Some(name.name.to_string()),
2167
+ Expression::ComputedMemberExpression(member) => {
2168
+ let Expression::Identifier(array) = &member.object else {
2169
+ return None;
2170
+ };
2171
+ Some(format!("{}.<computed>", array.name))
1788
2172
  }
1789
2173
  _ => None,
1790
2174
  }
@@ -1793,23 +2177,26 @@ fn inferred_path(object: &Expr) -> Option<String> {
1793
2177
  /// Finds runner calls from closure-factory listeners, including calls made through helpers, and
1794
2178
  /// records calls it cannot resolve. Each listener forwards its captured machine and layout
1795
2179
  /// followed by its own arguments.
1796
- struct Listeners<'script> {
1797
- runner: &'script Id,
1798
- appliers: &'script Appliers,
1799
- found: Vec<Result<Invocation>>,
1800
- }
1801
-
1802
- impl Visit for Listeners<'_> {
1803
- fn visit_function(&mut self, function: &Function) {
1804
- let scope = Scope::new("", function, self.appliers);
1805
- for call in calls_of(function) {
1806
- match scope.target(&call) {
2180
+ struct Listeners<'a, 's> {
2181
+ runner: Callee<'a>,
2182
+ appliers: &'s Appliers<'a>,
2183
+ found: Vec<Result<Invocation<'a>>>,
2184
+ }
2185
+
2186
+ impl<'a> Visit<'a> for Listeners<'a, '_> {
2187
+ fn visit_function(&mut self, function: &Function<'a>, flags: ScopeFlags) {
2188
+ let js = self.appliers.js();
2189
+ let function = js.lend(function, AstKind::as_function);
2190
+ let body = Body::of(function);
2191
+ let scope = Scope::new("", &body, self.appliers);
2192
+ for call in calls_of(js, &body) {
2193
+ match scope.target(call) {
1807
2194
  // A listener passes the captured machine and layout, then its own
1808
2195
  // parameters. Other scopes may reuse the runner's name for another function,
1809
2196
  // and the message handler starts the runner with computed arguments.
1810
2197
  Ok(mut target)
1811
- if target.callee.as_ref() == Some(self.runner)
1812
- && forwards_parameters(function, &call, &target) =>
2198
+ if target.callee == Some(self.runner)
2199
+ && forwards_parameters(&self.appliers.constants, &body, call, &target) =>
1813
2200
  {
1814
2201
  target.passed = target.passed.map(|passed| passed - 2);
1815
2202
  self.found.push(Ok(target));
@@ -1818,7 +2205,15 @@ impl Visit for Listeners<'_> {
1818
2205
  Err(error) => self.found.push(Err(error)),
1819
2206
  }
1820
2207
  }
1821
- function.visit_children_with(self);
2208
+ walk::walk_function(self, function, flags);
2209
+ }
2210
+
2211
+ fn visit_object_property(&mut self, property: &ObjectProperty<'a>) {
2212
+ walk_property(self, property);
2213
+ }
2214
+
2215
+ fn visit_method_definition(&mut self, method: &MethodDefinition<'a>) {
2216
+ walk_method(self, method);
1822
2217
  }
1823
2218
  }
1824
2219
 
@@ -1826,6 +2221,25 @@ impl Visit for Listeners<'_> {
1826
2221
  mod tests {
1827
2222
  use super::*;
1828
2223
 
2224
+ /// The decoded program captured during deobfuscation equals the one decoding alone
2225
+ /// produces, for a saved script named by `CFSOLVE_CAPTURE_SCRIPT`.
2226
+ #[test]
2227
+ fn captures_the_decoded_program() {
2228
+ let Some(path) = std::env::var_os("CFSOLVE_CAPTURE_SCRIPT") else {
2229
+ return;
2230
+ };
2231
+ let source = std::fs::read_to_string(path).expect("the capture script is readable");
2232
+ // The debug form includes spans and semantic IDs.
2233
+ let debug = |decoded: &ParsedScript| format!("{:?}", decoded.script().program);
2234
+ let (_, cases) = deobfuscate_with_cases(source.clone()).unwrap();
2235
+ let captured = debug(&cases.decoded.unwrap());
2236
+ let alone = debug(&deobfuscate::decode(source).unwrap());
2237
+ assert!(
2238
+ captured == alone,
2239
+ "the captured program differs from the decoded one"
2240
+ );
2241
+ }
2242
+
1829
2243
  #[test]
1830
2244
  fn appliers_may_copy_their_selector_and_name_apply_indirectly() {
1831
2245
  for source in [
@@ -1833,9 +2247,10 @@ mod tests {
1833
2247
  "function j(s,f,a,e,c,n){switch(e={},c=`apply`,n=[s],5^n[0]){case 6:return Reflect[c](f,void 0,a)}}",
1834
2248
  "var j;j=function(s,f,a){switch(5^s){case 6:return Reflect.apply(f,void 0,a)}}",
1835
2249
  ] {
1836
- let (script, _) = script(source);
1837
- let applier = &script.appliers.helpers[&binding(&script, "j")];
1838
- assert!(applier.call(3.0).is_some(), "{source}");
2250
+ with_script(source, |script| {
2251
+ let applier = &script.appliers.helpers[&binding(script, "j")];
2252
+ assert!(applier.select(3.0).is_some(), "{source}");
2253
+ });
1839
2254
  }
1840
2255
  }
1841
2256
 
@@ -1850,99 +2265,124 @@ mod tests {
1850
2265
  o['k']=function(a,b,c,d,g){return g=[b,d],true,a(g[0],c,g[1])},\
1851
2266
  o['s']=function(a,b,c,g){return g=[c,a,b],(0,g[1])(g[2],g[0])},\
1852
2267
  q=o,q['k'](B,f,r,q['s'](S,arguments,2))}";
1853
- let (script, _) = script(source);
1854
- let frames = script.method_forwarder(&binding(&script, "PA")).unwrap();
1855
- let names: Vec<&str> = frames.iter().map(|call| call.name.v8.as_str()).collect();
1856
- assert_eq!(names, ["PA.o.<computed> [as k]", "PA"]);
1857
- assert!(script.method_forwarder(&binding(&script, "S")).is_none());
2268
+ with_script(source, |script| {
2269
+ let frames = script.method_forwarder(binding(script, "PA")).unwrap();
2270
+ assert_eq!(v8_names(&frames), ["PA.o.<computed> [as k]", "PA"]);
2271
+ assert!(script.method_forwarder(binding(script, "S")).is_none());
2272
+ });
2273
+ }
2274
+
2275
+ /// Checks method forwarders that call a `Reflect.apply` alias kept in an array slot, directly
2276
+ /// or through a selector helper. Other slots are not apply aliases.
2277
+ #[test]
2278
+ fn method_forwarders_may_apply_through_an_array_slot() {
2279
+ let source = "var G=[];G[2]=Reflect.apply;G[3]=function(){};\
2280
+ function W(s,f,a,b,c){switch(s^1){case 0:return f(a,b,c)}}\
2281
+ function D(f,r,a){return(0,G[2])(f,r,[a])}\
2282
+ function H(f,r,a,b){return W(1,G[2],f,r,[a,b])}\
2283
+ function O(f,r,a){return(0,G[3])(f,r,[a])}";
2284
+ with_script(source, |script| {
2285
+ let cases: [(&str, &[&str]); 2] = [("D", &["D"]), ("H", &["W", "H"])];
2286
+ for (forwarder, expected) in cases {
2287
+ let frames = script
2288
+ .method_forwarder(binding(script, forwarder))
2289
+ .expect("`G[2]` holds `Reflect.apply`, so the call is a method forwarder");
2290
+ assert_eq!(
2291
+ v8_names(&frames),
2292
+ expected,
2293
+ "frames of forwarder {forwarder}"
2294
+ );
2295
+ }
2296
+ assert!(
2297
+ script.method_forwarder(binding(script, "O")).is_none(),
2298
+ "`G[3]` holds a plain function, not `Reflect.apply`"
2299
+ );
2300
+ });
1858
2301
  }
1859
2302
 
1860
2303
  #[test]
1861
2304
  fn same_named_functions_resolve_to_the_called_binding() {
1862
- let (script, _) = script(
1863
- "function outer(){function h(){wrong()} h()} function h(){right()} function caller(){h()}",
1864
- );
1865
- let target = first_target(&script, "caller");
1866
- let handler = script.function(target.callee.as_ref().unwrap()).unwrap();
1867
- assert_eq!(
1868
- name(calls_of(handler)[0].callee.as_expr().unwrap())
1869
- .unwrap()
1870
- .0,
1871
- "right"
1872
- );
2305
+ let source = "function outer(){function h(){wrong()} h()} function h(){right()} function caller(){h()}";
2306
+ with_script(source, |script| {
2307
+ let target = first_target(script, "caller");
2308
+ let handler = script.function(target.callee.unwrap()).unwrap();
2309
+ let call = calls_of(script.js(), &handler)[0];
2310
+ let callee = Operand::Expression(&call.callee)
2311
+ .callee(&script.appliers.constants)
2312
+ .unwrap();
2313
+ assert_eq!(script.appliers.name(callee), "right");
2314
+ });
1873
2315
  }
1874
2316
 
1875
2317
  #[test]
1876
2318
  fn shadowed_appliers_and_runners_are_distinct_bindings() {
1877
- let (script, _) = script(
1878
- "function runner(){} function j(s,f,a){switch(5^s){case 6:return Reflect.apply(f,void 0,a)}} function outer(){function j(){} function runner(){} j(3,f,[]);return function(a){runner(vm,layout,a);j(3,f,[])}} function real(a){runner(vm,layout,a)}",
1879
- );
1880
- let runner = first_target(&script, "real").callee.unwrap();
1881
- let mut listeners = Listeners {
1882
- runner: &runner,
1883
- appliers: &script.appliers,
1884
- found: Vec::new(),
1885
- };
1886
- // Visit every collected body, including the anonymous listener inside outer.
1887
- for (_, function) in &script.functions {
1888
- function.visit_with(&mut listeners);
1889
- }
1890
- assert_eq!(listeners.found.len(), 1);
1891
- let target = first_target(&script, "outer");
1892
- assert!(target.helpers.is_empty());
1893
- assert_eq!(target.passed, Some(3));
1894
- let callee = target.callee.expect("the call has a named callee");
1895
- assert!(!script.appliers.helpers.contains_key(&callee));
2319
+ let source = "function runner(){} function j(s,f,a){switch(5^s){case 6:return Reflect.apply(f,void 0,a)}} function outer(){function j(){} function runner(){} j(3,f,[]);return function(a){runner(vm,layout,a);j(3,f,[])}} function real(a){runner(vm,layout,a)}";
2320
+ with_script(source, |script| {
2321
+ let runner = first_target(script, "real").callee.unwrap();
2322
+ let mut listeners = Listeners {
2323
+ runner,
2324
+ appliers: &script.appliers,
2325
+ found: Vec::new(),
2326
+ };
2327
+ // Visit every collected function, including the anonymous listener inside outer.
2328
+ for (_, function) in script.js().named_functions() {
2329
+ listeners.visit_function(function, ScopeFlags::Function);
2330
+ }
2331
+ assert_eq!(listeners.found.len(), 1);
2332
+ let target = first_target(script, "outer");
2333
+ assert!(target.helpers.is_empty());
2334
+ assert_eq!(target.passed, Some(3));
2335
+ let callee = target.callee.expect("the call has a named callee");
2336
+ assert!(!script.appliers.helpers.contains_key(&callee));
2337
+ });
1896
2338
  }
1897
2339
 
1898
2340
  #[test]
1899
2341
  fn native_apply_alias_does_not_match_a_shadowed_function() {
1900
- let (script, _) = script(
1901
- "var B=Reflect.apply; function outer(){function B(){} function wrong(f,r){return B(f,r,[])}} function good(f,r){return B(f,r,[])}",
1902
- );
1903
- assert!(
1904
- script
1905
- .method_forwarder(&binding(&script, "wrong"))
1906
- .is_none()
1907
- );
1908
- assert!(script.method_forwarder(&binding(&script, "good")).is_some());
2342
+ let source = "var B=Reflect.apply; function outer(){function B(){} function wrong(f,r){return B(f,r,[])}} function good(f,r){return B(f,r,[])}";
2343
+ with_script(source, |script| {
2344
+ assert!(script.method_forwarder(binding(script, "wrong")).is_none());
2345
+ assert!(script.method_forwarder(binding(script, "good")).is_some());
2346
+ });
1909
2347
  }
1910
2348
 
1911
2349
  #[test]
1912
2350
  fn block_locals_do_not_replace_an_outer_objects_forwarder() {
1913
- let (script, _) = script(
1914
- "function F(){let o={},q=o,c='k';o.k=function(f,a){return f(a)};{let o={},q=o,c='other';o.k=function(f,a){return 0};}return q[c](target,1)}",
1915
- );
1916
- let target = first_target(&script, "F");
1917
- assert_eq!(target.callee.as_ref().unwrap().0, "target");
1918
- assert_eq!(target.helpers.len(), 1);
1919
- assert_eq!(target.helpers[0].name.v8, "F.o.k");
2351
+ let source = "function F(){let o={},q=o,c='k';o.k=function(f,a){return f(a)};{let o={},q=o,c='other';o.k=function(f,a){return 0};}return q[c](target,1)}";
2352
+ with_script(source, |script| {
2353
+ let target = first_target(script, "F");
2354
+ assert_eq!(script.appliers.name(target.callee.unwrap()), "target");
2355
+ assert_eq!(target.helpers.len(), 1);
2356
+ assert_eq!(target.helpers[0].name.v8, "F.o.k");
2357
+ });
1920
2358
  }
1921
2359
 
1922
- /// Analyzes `source` and returns the script's starting position.
1923
- fn script(source: &str) -> (Script, BytePos) {
1924
- deobfuscate::read_decoded(source.to_owned(), |program, start| {
1925
- Ok((Script::new(program), start))
1926
- })
1927
- .unwrap()
2360
+ /// Decodes `source` and analyzes it.
2361
+ fn with_script<T>(source: &str, read: impl for<'a> FnOnce(&Script<'a>) -> T) -> T {
2362
+ let decoded = deobfuscate::decode(source.to_owned()).unwrap();
2363
+ read(&Script::new(decoded.script()))
1928
2364
  }
1929
2365
 
1930
- fn binding(script: &Script, name: &str) -> Id {
1931
- script
2366
+ /// The binding of the script function named `name`.
2367
+ fn binding<'a>(script: &Script<'a>, name: &str) -> Callee<'a> {
2368
+ let (binding, _) = script
1932
2369
  .functions
1933
2370
  .iter()
1934
- .find(|(id, _)| id.0 == name)
1935
- .unwrap()
1936
- .0
1937
- .clone()
2371
+ .find(|(binding, _)| script.js().name(*binding) == name)
2372
+ .unwrap();
2373
+ Callee::Binding(*binding)
2374
+ }
2375
+
2376
+ fn v8_names(calls: &[Call]) -> Vec<&str> {
2377
+ calls.iter().map(|call| call.name.v8.as_str()).collect()
1938
2378
  }
1939
2379
 
1940
2380
  /// Returns the target of the first call in the script function named `name`.
1941
- fn first_target(script: &Script, name: &str) -> Invocation {
1942
- let function = script.function(&binding(script, name)).unwrap();
1943
- let call = calls_of(function).remove(0);
1944
- Scope::new(name, function, &script.appliers)
1945
- .target(&call)
2381
+ fn first_target<'a>(script: &Script<'a>, name: &str) -> Invocation<'a> {
2382
+ let function = script.function(binding(script, name)).unwrap();
2383
+ let call = calls_of(script.js(), &function)[0];
2384
+ Scope::new(name, &function, &script.appliers)
2385
+ .target(call)
1946
2386
  .unwrap()
1947
2387
  }
1948
2388
 
@@ -1954,20 +2394,21 @@ mod tests {
1954
2394
  function e(s,t,f,a){switch(s^C){case 1:{var y;switch(y=[a],5^t){case 6:return f(y[0])}}return;case 2:{h(a)}return}}\
1955
2395
  function caller(x){return e(6,3,g,x)}\
1956
2396
  function other(x){e(5,x)}";
1957
- let (script, _) = script(source);
1958
- let target = first_target(&script, "caller");
1959
- assert_eq!(target.callee.as_ref().unwrap().0, "g");
1960
- let helpers: Vec<&str> = target
1961
- .helpers
1962
- .iter()
1963
- .map(|call| call.name.v8.as_str())
1964
- .collect();
1965
- assert_eq!(helpers, ["e"]);
1966
- assert_eq!(target.passed, Some(1));
1967
- let original = first_target(&script, "other").callee.unwrap();
1968
- assert_eq!(original.0, "e");
1969
- let calls = calls_of(script.function(&original).unwrap());
1970
- assert_eq!(name(calls[0].callee.as_expr().unwrap()).unwrap().0, "h");
2397
+ with_script(source, |script| {
2398
+ let target = first_target(script, "caller");
2399
+ assert_eq!(script.appliers.name(target.callee.unwrap()), "g");
2400
+ assert_eq!(v8_names(&target.helpers), ["e"]);
2401
+ assert_eq!(target.passed, Some(1));
2402
+ let original = first_target(script, "other").callee.unwrap();
2403
+ assert!(matches!(original, Callee::Original(_)));
2404
+ assert_eq!(script.appliers.name(original), "e");
2405
+ let function = script.function(original).unwrap();
2406
+ let call = calls_of(script.js(), &function)[0];
2407
+ let callee = Operand::Expression(&call.callee)
2408
+ .callee(&script.appliers.constants)
2409
+ .unwrap();
2410
+ assert_eq!(script.appliers.name(callee), "h");
2411
+ });
1971
2412
  }
1972
2413
 
1973
2414
  /// V8 names a forwarder copied to a binding after its assignment target, without the property
@@ -1979,31 +2420,35 @@ mod tests {
1979
2420
  function a(s,f,x,y,z){switch(s^5){case 6:return f(x,y,z)}}\
1980
2421
  function direct(m){return q(loop,m,1)}\
1981
2422
  function applied(m){return a(3,q,loop,m,1)}";
1982
- let (script, _) = script(source);
1983
- for (caller, expected) in [
1984
- ("direct", &["o.<computed>"][..]),
1985
- ("applied", &["o.<computed>", "a"]),
1986
- ] {
1987
- let target = first_target(&script, caller);
1988
- assert_eq!(target.callee.as_ref().unwrap().0, "loop", "{caller}");
1989
- let helpers: Vec<&str> = target
1990
- .helpers
1991
- .iter()
1992
- .map(|call| call.name.v8.as_str())
1993
- .collect();
1994
- assert_eq!(helpers, expected, "{caller}");
1995
- assert_eq!(target.passed, Some(2), "{caller}");
1996
- }
2423
+ with_script(source, |script| {
2424
+ for (caller, expected) in [
2425
+ ("direct", &["o.<computed>"][..]),
2426
+ ("applied", &["o.<computed>", "a"]),
2427
+ ] {
2428
+ let target = first_target(script, caller);
2429
+ assert_eq!(
2430
+ script.appliers.name(target.callee.unwrap()),
2431
+ "loop",
2432
+ "{caller}"
2433
+ );
2434
+ assert_eq!(v8_names(&target.helpers), expected, "{caller}");
2435
+ assert_eq!(target.passed, Some(2), "{caller}");
2436
+ }
2437
+ });
1997
2438
  }
1998
2439
 
1999
2440
  #[test]
2000
2441
  fn a_call_key_kept_in_a_local_still_calls_the_handler() {
2001
2442
  let source = "function run(){var c='call';switch(o){case 1:h[c](this);break}}";
2002
- let (script, _) = script(source);
2003
- let target = first_target(&script, "run");
2004
- assert_eq!(target.callee.as_ref().map(|id| id.0.as_ref()), Some("h"));
2005
- assert!(target.method);
2006
- assert_eq!(target.passed, Some(0));
2443
+ with_script(source, |script| {
2444
+ let target = first_target(script, "run");
2445
+ assert_eq!(
2446
+ target.callee.map(|callee| script.appliers.name(callee)),
2447
+ Some("h")
2448
+ );
2449
+ assert!(target.method);
2450
+ assert_eq!(target.passed, Some(0));
2451
+ });
2007
2452
  }
2008
2453
 
2009
2454
  #[test]
@@ -2042,18 +2487,19 @@ mod tests {
2042
2487
  #[test]
2043
2488
  fn jsc_frames_are_placed_at_their_arguments() {
2044
2489
  let source = "function a(s,f,l){switch(1^s){case 0:return Reflect.construct(f,void 0,l);case 3:return Reflect.apply(f,void 0,l)}}function h(){return a(1,Error,[])}";
2045
- let (script, start) = script(source);
2046
- let target = first_target(&script, "h");
2047
- let frames = target.frames(Name::same("h".to_owned()));
2048
- let names: Vec<_> = frames
2049
- .iter()
2050
- .map(|call| (call.name.v8.as_str(), call.name.jsc.as_str()))
2051
- .collect();
2052
- assert_eq!(names, [("a", "a"), ("h", "h")]);
2053
- let at = |position: BytePos| &source[(position.0 - start.0) as usize..][..2];
2054
- let (applier, handler) = (&frames[0], &frames[1]);
2055
- assert_eq!(at(handler.site.v8), "a(");
2056
- assert_eq!(at(handler.site.jsc), "(1");
2057
- assert_eq!(at(applier.site.jsc), "(f");
2490
+ with_script(source, |script| {
2491
+ let target = first_target(script, "h");
2492
+ let frames = target.frames(Name::same("h".to_owned()));
2493
+ let names: Vec<_> = frames
2494
+ .iter()
2495
+ .map(|call| (call.name.v8.as_str(), call.name.jsc.as_str()))
2496
+ .collect();
2497
+ assert_eq!(names, [("a", "a"), ("h", "h")]);
2498
+ let at = |position: u32| &source[position as usize..][..2];
2499
+ let (applier, handler) = (&frames[0], &frames[1]);
2500
+ assert_eq!(at(handler.site.v8), "a(");
2501
+ assert_eq!(at(handler.site.jsc), "(1");
2502
+ assert_eq!(at(applier.site.jsc), "(f");
2503
+ });
2058
2504
  }
2059
2505
  }