cfsolve 0.1.3 → 0.1.5
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- checksums.yaml +4 -4
- data/CHANGELOG.md +40 -0
- data/README.md +30 -5
- data/UPSTREAM.md +24 -3
- data/lib/cfsolve/profiles/safari-26-ios/answers.json +805 -797
- data/lib/cfsolve/profiles/safari-26-ios/challenge-page-answers.json +909 -899
- data/lib/cfsolve/version.rb +2 -2
- data/lib/cfsolve.rb +21 -10
- data/vendor/cfsolve/examples/listing_dump.rs +24 -0
- data/vendor/cfsolve/examples/probe_similarity.rs +37 -0
- data/vendor/cfsolve/examples/rebase_reference.rs +96 -0
- data/vendor/cfsolve/examples/reread_capture.rs +31 -0
- data/vendor/cfsolve/examples/turnstile_smoke.rs +79 -0
- data/vendor/cfsolve/profiles/safari-26-ios/answers.json +805 -797
- data/vendor/cfsolve/profiles/safari-26-ios/challenge-page-answers.json +909 -899
- data/vendor/cfsolve/src/capture/sessions.rs +88 -4
- data/vendor/cfsolve/src/capture.rs +1 -0
- data/vendor/cfsolve/src/deobfuscate/ast.rs +16 -0
- data/vendor/cfsolve/src/deobfuscate/control_flow.rs +1 -1
- data/vendor/cfsolve/src/deobfuscate/dead_branches.rs +33 -0
- data/vendor/cfsolve/src/deobfuscate/merged_functions.rs +24 -4
- data/vendor/cfsolve/src/embedding_page/extra_params.rs +3 -3
- data/vendor/cfsolve/src/embedding_page/page.rs +76 -65
- data/vendor/cfsolve/src/stage2/analysis/discovery.rs +7 -4
- data/vendor/cfsolve/src/stage2/benchmark.rs +29 -8
- data/vendor/cfsolve/src/stage2/call_stack.rs +134 -95
- data/vendor/cfsolve/src/stage2/challenge_page.rs +10 -3
- data/vendor/cfsolve/src/stage2/probes/parent_info.rs +345 -61
- data/vendor/cfsolve/src/stage2/probes/performance.rs +42 -5
- data/vendor/cfsolve/src/stage2/probes/stack.rs +41 -0
- data/vendor/cfsolve/src/stage2/probes/websocket_echo.rs +11 -2
- data/vendor/cfsolve/src/stage2/reference.json +1 -1
- data/vendor/cfsolve/src/stage2/reference.rs +70 -110
- data/vendor/cfsolve/src/stage2/registry.rs +4 -3
- data/vendor/cfsolve/src/stage2/trace.rs +1 -1
- data/vendor/cfsolve/src/vm/dataflow.rs +15 -6
- data/vendor/cfsolve/src/vm/disassemble.rs +2 -1
- data/vendor/cfsolve/src/vm/encoded_strings.rs +1553 -0
- data/vendor/cfsolve/src/vm/extract.rs +205 -152
- data/vendor/cfsolve/src/vm/interpret/access.rs +0 -2
- data/vendor/cfsolve/src/vm/interpret/builtin.rs +0 -13
- data/vendor/cfsolve/src/vm/interpret/intrinsic.rs +30 -7
- data/vendor/cfsolve/src/vm/interpret/mix32.rs +216 -86
- data/vendor/cfsolve/src/vm/interpret/native_dispatch.rs +42 -21
- data/vendor/cfsolve/src/vm/interpret/pattern.rs +268 -67
- data/vendor/cfsolve/src/vm/interpret/register_helpers.rs +261 -30
- data/vendor/cfsolve/src/vm/machine.rs +14 -12
- data/vendor/cfsolve/src/vm/output.rs +4 -1
- data/vendor/cfsolve/src/vm/registers.rs +17 -23
- data/vendor/cfsolve/src/vm/session.rs +9 -4
- data/vendor/cfsolve/src/vm.rs +1 -0
- metadata +7 -1
|
@@ -0,0 +1,1553 @@
|
|
|
1
|
+
//! Folds strings the program decodes with its own decoder functions.
|
|
2
|
+
//!
|
|
3
|
+
//! Some builds keep a probe's API names and markup as base64 text and decode each one at run
|
|
4
|
+
//! time with a decoder the probe builds for itself: a factory, called with `globalThis`, keeps
|
|
5
|
+
//! the global object, `String` and a cache in cells and returns the decoder; the probe stores
|
|
6
|
+
//! the decoder in a cell and calls it with each encoded constant. The decoder `atob`s its
|
|
7
|
+
//! argument, XORs each character with a key stream from a seed, and joins the characters with
|
|
8
|
+
//! `String.fromCharCode`.
|
|
9
|
+
//!
|
|
10
|
+
//! Rather than recognizing that algorithm, this module runs the factory and the decoder on their
|
|
11
|
+
//! listing paths with JavaScript's semantics for the few values and operations they use, and
|
|
12
|
+
//! gives up on anything else. Each call of a decoder cell with a constant argument then becomes
|
|
13
|
+
//! a load of the string the call returns, as [`super::packed_names`] does for names.
|
|
14
|
+
//!
|
|
15
|
+
//! The listing does not show two things the evaluation relies on: `String.fromCharCode` is
|
|
16
|
+
//! applied to the character buffer through a script helper the listing shows as a global whose
|
|
17
|
+
//! first argument is an opaque function, and the register machine's return pops a numeric
|
|
18
|
+
//! return address.
|
|
19
|
+
|
|
20
|
+
use std::cell::RefCell;
|
|
21
|
+
use std::collections::{BTreeMap, BTreeSet};
|
|
22
|
+
use std::convert::Infallible;
|
|
23
|
+
use std::ops::{ControlFlow, Deref};
|
|
24
|
+
use std::rc::Rc;
|
|
25
|
+
|
|
26
|
+
use oxc::syntax::operator::{BinaryOperator, LogicalOperator, UnaryOperator};
|
|
27
|
+
|
|
28
|
+
use super::output::{Constant, Effect, Exit, Listing, Path, Term};
|
|
29
|
+
use super::{HashMap, dataflow, disassemble};
|
|
30
|
+
use crate::js;
|
|
31
|
+
|
|
32
|
+
/// Instructions one evaluation may run before giving up. Decoding a constant takes a few dozen
|
|
33
|
+
/// per character.
|
|
34
|
+
const STEP_LIMIT: usize = 1_000_000;
|
|
35
|
+
|
|
36
|
+
/// The callee the machine calls to pop the return address when a function returns.
|
|
37
|
+
const POP: &str = "Array.prototype.pop";
|
|
38
|
+
|
|
39
|
+
pub(super) fn fold(listing: &mut Listing) {
|
|
40
|
+
let Some(program) = Program::new(listing) else {
|
|
41
|
+
return;
|
|
42
|
+
};
|
|
43
|
+
// Dataflow finds what functions store in cells, and reads cells to find the decoders other
|
|
44
|
+
// functions call and the text they decoded, so repeat until the stored values stop changing.
|
|
45
|
+
let mut entries = program.entries();
|
|
46
|
+
for _ in 0..4 {
|
|
47
|
+
let stored = program.stored(&entries);
|
|
48
|
+
if stored == *program.scopes.stored.borrow() {
|
|
49
|
+
break;
|
|
50
|
+
}
|
|
51
|
+
*program.scopes.stored.borrow_mut() = stored;
|
|
52
|
+
entries = program.entries();
|
|
53
|
+
}
|
|
54
|
+
// Each decoded effect's instruction, path, index and text.
|
|
55
|
+
let mut decoded = Vec::new();
|
|
56
|
+
let mut encoded = BTreeSet::new();
|
|
57
|
+
for (&pc, instruction) in &program.listing.instructions {
|
|
58
|
+
let Some(known) = entries.get(&pc) else {
|
|
59
|
+
continue;
|
|
60
|
+
};
|
|
61
|
+
let function = program.scopes.owner(pc);
|
|
62
|
+
for (way, path) in instruction.paths.iter().enumerate() {
|
|
63
|
+
let mut temporaries = BTreeMap::new();
|
|
64
|
+
// Temporaries holding decoded text, whose copies become loads of the text too.
|
|
65
|
+
let mut texts = BTreeMap::new();
|
|
66
|
+
for (at, effect) in path.effects.iter().enumerate() {
|
|
67
|
+
let (Effect::Let(_, term) | Effect::Set(_, term)) = effect else {
|
|
68
|
+
continue;
|
|
69
|
+
};
|
|
70
|
+
let fact = |term| program.fact(term, known, &temporaries, function);
|
|
71
|
+
let value = fact(term);
|
|
72
|
+
let text = if let Term::Call {
|
|
73
|
+
callee, arguments, ..
|
|
74
|
+
} = term
|
|
75
|
+
&& let Some(Fact::Decoder(_)) = fact(callee)
|
|
76
|
+
&& let Some(Fact::Text(text)) = &value
|
|
77
|
+
&& let [argument] = arguments.as_slice()
|
|
78
|
+
&& let Some(Fact::Text(argument)) = fact(argument)
|
|
79
|
+
{
|
|
80
|
+
encoded.insert(argument.to_string());
|
|
81
|
+
Some(text.clone())
|
|
82
|
+
} else if let (Term::Cell(_), Some(Fact::Text(text))) = (term, &value) {
|
|
83
|
+
Some(text.clone())
|
|
84
|
+
} else if let (Effect::Set(..), Term::Temp(temporary)) = (effect, term) {
|
|
85
|
+
texts.get(temporary).cloned()
|
|
86
|
+
} else {
|
|
87
|
+
None
|
|
88
|
+
};
|
|
89
|
+
if let Some(text) = &text {
|
|
90
|
+
decoded.push((pc, way, at, text.to_string()));
|
|
91
|
+
}
|
|
92
|
+
if let Effect::Let(temporary, _) = effect {
|
|
93
|
+
dataflow::assign(&mut texts, *temporary, text);
|
|
94
|
+
dataflow::assign(&mut temporaries, *temporary, value);
|
|
95
|
+
}
|
|
96
|
+
}
|
|
97
|
+
}
|
|
98
|
+
}
|
|
99
|
+
listing.encoded.extend(encoded);
|
|
100
|
+
for (pc, way, at, text) in decoded {
|
|
101
|
+
let instruction = listing
|
|
102
|
+
.instructions
|
|
103
|
+
.get_mut(&pc)
|
|
104
|
+
.expect("decoded from the listing");
|
|
105
|
+
if let Effect::Let(_, term) | Effect::Set(_, term) = &mut instruction.paths[way].effects[at]
|
|
106
|
+
{
|
|
107
|
+
*term = Term::Const(Constant::String(text));
|
|
108
|
+
}
|
|
109
|
+
}
|
|
110
|
+
}
|
|
111
|
+
|
|
112
|
+
/// Facts about the whole program that evaluation and dataflow need.
|
|
113
|
+
struct Program<'listing> {
|
|
114
|
+
listing: &'listing Listing,
|
|
115
|
+
/// Registers every assignment in the program sets to the same constant, such as the method
|
|
116
|
+
/// names the program loads once at its start.
|
|
117
|
+
fixed: BTreeMap<u8, Constant>,
|
|
118
|
+
/// The facts of the [`Self::fixed`] registers, indexed by register, which hold at every
|
|
119
|
+
/// instruction dataflow reaches, so [`Facts`] leave them out. NaN is left out here instead:
|
|
120
|
+
/// it never equals itself, so dataflow forgets it where paths meet.
|
|
121
|
+
invariant: Vec<Option<Fact<'listing>>>,
|
|
122
|
+
/// Facts known on entry to every function and handler: the fixed registers left out of
|
|
123
|
+
/// [`Self::invariant`].
|
|
124
|
+
start: Facts<'listing>,
|
|
125
|
+
/// The register holding the global object, which the program never assigns.
|
|
126
|
+
global: u8,
|
|
127
|
+
/// The register a called function reads its first argument from.
|
|
128
|
+
argument: u8,
|
|
129
|
+
/// The register a returning function leaves its result in.
|
|
130
|
+
result: u8,
|
|
131
|
+
scopes: Scopes<'listing>,
|
|
132
|
+
/// Whether each function, run as a decoder factory, makes a decoder.
|
|
133
|
+
factories: RefCell<HashMap<u32, bool>>,
|
|
134
|
+
/// What each factory's decoders return, by factory.
|
|
135
|
+
decoded: RefCell<HashMap<u32, Decoded>>,
|
|
136
|
+
}
|
|
137
|
+
|
|
138
|
+
impl<'listing> Program<'listing> {
|
|
139
|
+
fn new(listing: &'listing Listing) -> Option<Self> {
|
|
140
|
+
let mut assigned = BTreeMap::new();
|
|
141
|
+
let mut global_reads = BTreeSet::new();
|
|
142
|
+
let mut results = BTreeSet::new();
|
|
143
|
+
for instruction in listing.instructions.values() {
|
|
144
|
+
for path in &instruction.paths {
|
|
145
|
+
// A return pops the return address and leaves the result in one register,
|
|
146
|
+
// which builds set before or after the pop.
|
|
147
|
+
if path.exit == Exit::Return && path.effects.iter().any(is_pop) {
|
|
148
|
+
let set = path.effects.iter().filter_map(|effect| match effect {
|
|
149
|
+
Effect::Set(register, _) => Some(*register),
|
|
150
|
+
_ => None,
|
|
151
|
+
});
|
|
152
|
+
results.extend(only(set));
|
|
153
|
+
}
|
|
154
|
+
for effect in &path.effects {
|
|
155
|
+
if let Effect::Set(register, value) = effect {
|
|
156
|
+
let constant = match value {
|
|
157
|
+
Term::Const(constant @ (Constant::String(_) | Constant::Number(_))) => {
|
|
158
|
+
Some(constant)
|
|
159
|
+
}
|
|
160
|
+
_ => None,
|
|
161
|
+
};
|
|
162
|
+
merge(&mut assigned, *register, constant);
|
|
163
|
+
}
|
|
164
|
+
effect.visit_terms(&mut |term| {
|
|
165
|
+
if let Term::Get(object, key) = term
|
|
166
|
+
&& let Term::Reg(register) = **object
|
|
167
|
+
&& key.string() == Some("globalThis")
|
|
168
|
+
{
|
|
169
|
+
global_reads.insert(register);
|
|
170
|
+
}
|
|
171
|
+
});
|
|
172
|
+
}
|
|
173
|
+
}
|
|
174
|
+
}
|
|
175
|
+
let fixed = assigned
|
|
176
|
+
.iter()
|
|
177
|
+
.filter_map(|(®ister, constant)| Some((register, (*constant)?.clone())))
|
|
178
|
+
.collect();
|
|
179
|
+
let mut invariant = vec![None; usize::from(u8::MAX) + 1];
|
|
180
|
+
let mut start = Facts::new();
|
|
181
|
+
for (®ister, constant) in &assigned {
|
|
182
|
+
let Some(fact) = (*constant).and_then(Fact::of) else {
|
|
183
|
+
continue;
|
|
184
|
+
};
|
|
185
|
+
if matches!(fact, Fact::Number(number) if number.is_nan()) {
|
|
186
|
+
start.insert(register, fact);
|
|
187
|
+
} else {
|
|
188
|
+
invariant[usize::from(register)] = Some(fact);
|
|
189
|
+
}
|
|
190
|
+
}
|
|
191
|
+
let unassigned = |register: &u8| !assigned.contains_key(register);
|
|
192
|
+
let global = only(global_reads.into_iter().filter(unassigned))?;
|
|
193
|
+
// Every path of each function's entry copies its argument from a register the program
|
|
194
|
+
// never assigns, as when the copy checks its type.
|
|
195
|
+
let arguments = listing.functions.iter().filter_map(|function| {
|
|
196
|
+
let instruction = listing.instructions.get(&function.pc)?;
|
|
197
|
+
let copied = instruction
|
|
198
|
+
.paths
|
|
199
|
+
.iter()
|
|
200
|
+
.map(|path| match path.effects.first()? {
|
|
201
|
+
Effect::Set(_, Term::Reg(register))
|
|
202
|
+
if unassigned(register) && *register != global =>
|
|
203
|
+
{
|
|
204
|
+
Some(*register)
|
|
205
|
+
}
|
|
206
|
+
_ => None,
|
|
207
|
+
});
|
|
208
|
+
only(copied.collect::<Option<BTreeSet<_>>>()?)
|
|
209
|
+
});
|
|
210
|
+
let argument = only(arguments.collect::<BTreeSet<_>>())?;
|
|
211
|
+
Some(Self {
|
|
212
|
+
listing,
|
|
213
|
+
fixed,
|
|
214
|
+
invariant,
|
|
215
|
+
start,
|
|
216
|
+
global,
|
|
217
|
+
argument,
|
|
218
|
+
result: only(results)?,
|
|
219
|
+
scopes: Scopes::new(listing),
|
|
220
|
+
factories: RefCell::default(),
|
|
221
|
+
decoded: RefCell::default(),
|
|
222
|
+
})
|
|
223
|
+
}
|
|
224
|
+
|
|
225
|
+
/// Facts on entry to each instruction the program's functions and handlers reach, which
|
|
226
|
+
/// start with only the fixed registers known. Handlers only fill in instructions nothing
|
|
227
|
+
/// else reaches, so a catch path cannot erase what the normal path knows.
|
|
228
|
+
fn entries(&self) -> BTreeMap<u32, Facts<'listing>> {
|
|
229
|
+
let functions = self.listing.functions.iter().map(|function| function.pc);
|
|
230
|
+
let hidden = self.listing.hidden.iter().map(|hidden| hidden.target.pc);
|
|
231
|
+
let mut entries = self.forward(disassemble::exception_entries(self.listing));
|
|
232
|
+
entries.extend(self.forward(functions.chain(hidden)));
|
|
233
|
+
entries
|
|
234
|
+
}
|
|
235
|
+
|
|
236
|
+
fn forward(&self, entries: impl IntoIterator<Item = u32>) -> BTreeMap<u32, Facts<'listing>> {
|
|
237
|
+
let entries = entries.into_iter().map(|pc| (pc, self.start.clone()));
|
|
238
|
+
let ControlFlow::Continue(incoming) =
|
|
239
|
+
dataflow::forward(self.listing, entries, |pc, path, known| {
|
|
240
|
+
let function = self.scopes.owner(pc);
|
|
241
|
+
ControlFlow::<Infallible, bool>::Continue(self.transfer(path, known, function))
|
|
242
|
+
});
|
|
243
|
+
incoming
|
|
244
|
+
}
|
|
245
|
+
|
|
246
|
+
/// Applies `path` of an instruction in `function` to `known` and returns whether the path
|
|
247
|
+
/// can run. Terms read registers as they were when the instruction started.
|
|
248
|
+
fn transfer(
|
|
249
|
+
&self,
|
|
250
|
+
path: &'listing Path,
|
|
251
|
+
known: &mut Facts<'listing>,
|
|
252
|
+
function: Option<u32>,
|
|
253
|
+
) -> bool {
|
|
254
|
+
let mut temporaries = BTreeMap::new();
|
|
255
|
+
let mut writes = Vec::new();
|
|
256
|
+
for effect in &path.effects {
|
|
257
|
+
match effect {
|
|
258
|
+
Effect::Let(temporary, term) => {
|
|
259
|
+
let fact = self.fact(term, known, &temporaries, function);
|
|
260
|
+
dataflow::assign(&mut temporaries, *temporary, fact);
|
|
261
|
+
}
|
|
262
|
+
// Writes to invariant registers store the constant they already hold.
|
|
263
|
+
Effect::Set(register, _) if self.invariant[usize::from(*register)].is_some() => {}
|
|
264
|
+
Effect::Set(register, term) => {
|
|
265
|
+
writes.push((*register, self.fact(term, known, &temporaries, function)));
|
|
266
|
+
}
|
|
267
|
+
_ => {}
|
|
268
|
+
}
|
|
269
|
+
}
|
|
270
|
+
let feasible = path.conditions.iter().all(|(condition, expected)| {
|
|
271
|
+
truth(self.fact(condition, known, &temporaries, function))
|
|
272
|
+
.is_none_or(|actual| actual == *expected)
|
|
273
|
+
});
|
|
274
|
+
for (register, fact) in writes {
|
|
275
|
+
dataflow::assign(known, register, fact);
|
|
276
|
+
}
|
|
277
|
+
feasible
|
|
278
|
+
}
|
|
279
|
+
|
|
280
|
+
/// What each function stores in each cell it assigns: a decoder, or text assigned before the
|
|
281
|
+
/// function creates any function that reads the cell. `None` when it stores anything else
|
|
282
|
+
/// there.
|
|
283
|
+
fn stored(
|
|
284
|
+
&self,
|
|
285
|
+
entries: &BTreeMap<u32, Facts<'listing>>,
|
|
286
|
+
) -> BTreeMap<(u32, u32), Option<Fact<'listing>>> {
|
|
287
|
+
let mut stored = BTreeMap::new();
|
|
288
|
+
// Where each function last assigns each cell.
|
|
289
|
+
let mut last_set = BTreeMap::new();
|
|
290
|
+
for (&pc, instruction) in &self.listing.instructions {
|
|
291
|
+
let Some(function) = self.scopes.owner(pc) else {
|
|
292
|
+
continue;
|
|
293
|
+
};
|
|
294
|
+
let known = entries.get(&pc);
|
|
295
|
+
for path in &instruction.paths {
|
|
296
|
+
let mut temporaries = BTreeMap::new();
|
|
297
|
+
for effect in &path.effects {
|
|
298
|
+
let fact = |term| self.fact(term, known?, &temporaries, Some(function));
|
|
299
|
+
match effect {
|
|
300
|
+
Effect::SetCell(cell, term) => {
|
|
301
|
+
last_set.insert((function, *cell), pc);
|
|
302
|
+
let value = fact(term)
|
|
303
|
+
.filter(|fact| matches!(fact, Fact::Decoder(_) | Fact::Text(_)));
|
|
304
|
+
merge(&mut stored, (function, *cell), value);
|
|
305
|
+
}
|
|
306
|
+
Effect::Let(temporary, term) => {
|
|
307
|
+
let value = fact(term);
|
|
308
|
+
dataflow::assign(&mut temporaries, *temporary, value);
|
|
309
|
+
}
|
|
310
|
+
_ => {}
|
|
311
|
+
}
|
|
312
|
+
}
|
|
313
|
+
}
|
|
314
|
+
}
|
|
315
|
+
for (&(function, cell), value) in &mut stored {
|
|
316
|
+
if matches!(value, Some(Fact::Text(_)))
|
|
317
|
+
&& self
|
|
318
|
+
.scopes
|
|
319
|
+
.read_early(function, cell, last_set[&(function, cell)])
|
|
320
|
+
{
|
|
321
|
+
*value = None;
|
|
322
|
+
}
|
|
323
|
+
}
|
|
324
|
+
stored
|
|
325
|
+
}
|
|
326
|
+
|
|
327
|
+
/// What `term` is known to be in `function`.
|
|
328
|
+
fn fact(
|
|
329
|
+
&self,
|
|
330
|
+
term: &'listing Term,
|
|
331
|
+
known: &Facts<'listing>,
|
|
332
|
+
temporaries: &BTreeMap<usize, Fact<'listing>>,
|
|
333
|
+
function: Option<u32>,
|
|
334
|
+
) -> Option<Fact<'listing>> {
|
|
335
|
+
let fact = |term| self.fact(term, known, temporaries, function);
|
|
336
|
+
Some(match term {
|
|
337
|
+
Term::Const(constant) => Fact::of(constant)?,
|
|
338
|
+
Term::Reg(register) => known
|
|
339
|
+
.get(register)
|
|
340
|
+
.or(self.invariant[usize::from(*register)].as_ref())?
|
|
341
|
+
.clone(),
|
|
342
|
+
Term::Temp(temporary) => temporaries.get(temporary)?.clone(),
|
|
343
|
+
Term::Cell(cell) => {
|
|
344
|
+
let (scope, stored) = self.scopes.cell(function?, *cell)?;
|
|
345
|
+
// Only functions the assigning function creates afterwards read text surely
|
|
346
|
+
// assigned.
|
|
347
|
+
if matches!(stored, Fact::Text(_)) && Some(scope) == function {
|
|
348
|
+
return None;
|
|
349
|
+
}
|
|
350
|
+
stored
|
|
351
|
+
}
|
|
352
|
+
Term::Get(object, key)
|
|
353
|
+
if **object == Term::Reg(self.global) && key.string() == Some("globalThis") =>
|
|
354
|
+
{
|
|
355
|
+
Fact::Global
|
|
356
|
+
}
|
|
357
|
+
Term::Closure { pc, .. } => Fact::Closure(*pc),
|
|
358
|
+
Term::Call {
|
|
359
|
+
callee,
|
|
360
|
+
this: None,
|
|
361
|
+
arguments,
|
|
362
|
+
} => match (fact(callee)?, arguments.as_slice()) {
|
|
363
|
+
(Fact::Closure(pc), [argument])
|
|
364
|
+
if fact(argument)? == Fact::Global && self.is_factory(pc) =>
|
|
365
|
+
{
|
|
366
|
+
Fact::Decoder(pc)
|
|
367
|
+
}
|
|
368
|
+
(Fact::Decoder(pc), [argument]) => match fact(argument)? {
|
|
369
|
+
Fact::Text(text) => Fact::Text(Text::Shared(self.decode(pc, &text)?)),
|
|
370
|
+
_ => return None,
|
|
371
|
+
},
|
|
372
|
+
_ => return None,
|
|
373
|
+
},
|
|
374
|
+
Term::Unary(UnaryOperator::Typeof, argument) => {
|
|
375
|
+
Fact::Text(Text::Listing(fact(argument)?.type_name()))
|
|
376
|
+
}
|
|
377
|
+
Term::Unary(UnaryOperator::LogicalNot, argument) => Fact::Bool(!truth(fact(argument))?),
|
|
378
|
+
Term::Binary(
|
|
379
|
+
operator @ (BinaryOperator::StrictEquality | BinaryOperator::StrictInequality),
|
|
380
|
+
left,
|
|
381
|
+
right,
|
|
382
|
+
) => {
|
|
383
|
+
let equal = fact(left)?.strictly_equals(&fact(right)?)?;
|
|
384
|
+
Fact::Bool(equal == (*operator == BinaryOperator::StrictEquality))
|
|
385
|
+
}
|
|
386
|
+
_ => return None,
|
|
387
|
+
})
|
|
388
|
+
}
|
|
389
|
+
|
|
390
|
+
/// Runs factory `pc` given the global object, returning the decoder it makes.
|
|
391
|
+
fn decoder(&self, pc: u32) -> Option<Rc<Closure>> {
|
|
392
|
+
let factory = Closure {
|
|
393
|
+
pc,
|
|
394
|
+
cells: Cells::new(),
|
|
395
|
+
};
|
|
396
|
+
match self.call(&factory, Value::Global)? {
|
|
397
|
+
Value::Closure(decoder) => Some(decoder),
|
|
398
|
+
_ => None,
|
|
399
|
+
}
|
|
400
|
+
}
|
|
401
|
+
|
|
402
|
+
fn is_factory(&self, pc: u32) -> bool {
|
|
403
|
+
*(self.factories.borrow_mut())
|
|
404
|
+
.entry(pc)
|
|
405
|
+
.or_insert_with(|| self.decoder(pc).is_some())
|
|
406
|
+
}
|
|
407
|
+
|
|
408
|
+
/// What a decoder from factory `pc` returns for `text`, if a string. Each text gets a fresh
|
|
409
|
+
/// decoder, so its cache cannot answer for an earlier call.
|
|
410
|
+
fn decode(&self, pc: u32, text: &str) -> Option<Rc<str>> {
|
|
411
|
+
if let Some(result) = (self.decoded.borrow().get(&pc)).and_then(|texts| texts.get(text)) {
|
|
412
|
+
return result.clone();
|
|
413
|
+
}
|
|
414
|
+
let argument = Value::String(text.encode_utf16().collect());
|
|
415
|
+
let result = match self
|
|
416
|
+
.decoder(pc)
|
|
417
|
+
.and_then(|decoder| self.call(&decoder, argument))
|
|
418
|
+
{
|
|
419
|
+
Some(Value::String(units)) => String::from_utf16(&units).ok().map(Rc::from),
|
|
420
|
+
_ => None,
|
|
421
|
+
};
|
|
422
|
+
let mut decoded = self.decoded.borrow_mut();
|
|
423
|
+
decoded
|
|
424
|
+
.entry(pc)
|
|
425
|
+
.or_default()
|
|
426
|
+
.insert(text.to_owned(), result.clone());
|
|
427
|
+
result
|
|
428
|
+
}
|
|
429
|
+
|
|
430
|
+
/// Runs `closure` with `argument` until it returns, or gives up.
|
|
431
|
+
fn call(&self, closure: &Closure, argument: Value) -> Option<Value> {
|
|
432
|
+
let mut frame = Frame {
|
|
433
|
+
registers: (self.fixed.iter())
|
|
434
|
+
.map(|(®ister, constant)| (register, Value::of(constant)))
|
|
435
|
+
.collect(),
|
|
436
|
+
cells: closure.cells.clone(),
|
|
437
|
+
};
|
|
438
|
+
frame.registers.insert(self.argument, argument);
|
|
439
|
+
let mut pc = closure.pc;
|
|
440
|
+
for _ in 0..STEP_LIMIT {
|
|
441
|
+
let instruction = self.listing.instructions.get(&pc)?;
|
|
442
|
+
let paths = instruction.paths.iter();
|
|
443
|
+
let path = only(paths.filter(|path| frame.takes(path) == Some(true)))?;
|
|
444
|
+
let mut temporaries = BTreeMap::new();
|
|
445
|
+
// Terms read registers as they were when the instruction started, so writes wait
|
|
446
|
+
// until its effects finish.
|
|
447
|
+
let mut writes = Vec::new();
|
|
448
|
+
for effect in &path.effects {
|
|
449
|
+
let evaluation = Evaluation {
|
|
450
|
+
registers: &frame.registers,
|
|
451
|
+
temporaries: &temporaries,
|
|
452
|
+
cells: &frame.cells,
|
|
453
|
+
pure: false,
|
|
454
|
+
};
|
|
455
|
+
match effect {
|
|
456
|
+
Effect::Let(temporary, term) => {
|
|
457
|
+
let value = evaluation.value(term)?;
|
|
458
|
+
temporaries.insert(*temporary, value);
|
|
459
|
+
}
|
|
460
|
+
Effect::Set(register, term) => {
|
|
461
|
+
writes.push((*register, evaluation.value(term)?));
|
|
462
|
+
}
|
|
463
|
+
Effect::SetProperty { object, key, value } => {
|
|
464
|
+
let object = evaluation.value(object)?;
|
|
465
|
+
let key = evaluation.value(key)?;
|
|
466
|
+
set_property(&object, &key, evaluation.value(value)?)?;
|
|
467
|
+
}
|
|
468
|
+
Effect::NewCell(cell) => {
|
|
469
|
+
let value = Rc::new(RefCell::new(Value::Undefined));
|
|
470
|
+
frame.cells.insert(*cell, value);
|
|
471
|
+
}
|
|
472
|
+
Effect::SetCell(cell, term) => {
|
|
473
|
+
let value = evaluation.value(term)?;
|
|
474
|
+
*frame.cells.get(cell)?.borrow_mut() = value;
|
|
475
|
+
}
|
|
476
|
+
Effect::Throw(_) => return None,
|
|
477
|
+
}
|
|
478
|
+
}
|
|
479
|
+
frame.registers.extend(writes);
|
|
480
|
+
match path.exit {
|
|
481
|
+
Exit::Next { pc: next, .. } => pc = next,
|
|
482
|
+
Exit::Return => return frame.registers.get(&self.result).cloned(),
|
|
483
|
+
Exit::Throw | Exit::Unfollowed { .. } => return None,
|
|
484
|
+
}
|
|
485
|
+
}
|
|
486
|
+
None
|
|
487
|
+
}
|
|
488
|
+
}
|
|
489
|
+
|
|
490
|
+
/// The single item of `items`, if there is exactly one.
|
|
491
|
+
fn only<T>(items: impl IntoIterator<Item = T>) -> Option<T> {
|
|
492
|
+
let mut items = items.into_iter();
|
|
493
|
+
let first = items.next()?;
|
|
494
|
+
items.next().is_none().then_some(first)
|
|
495
|
+
}
|
|
496
|
+
|
|
497
|
+
/// Records `value` for `key`, or `None` once two records disagree.
|
|
498
|
+
fn merge<K: Ord, V: PartialEq>(map: &mut BTreeMap<K, Option<V>>, key: K, value: Option<V>) {
|
|
499
|
+
map.entry(key)
|
|
500
|
+
.and_modify(|known| {
|
|
501
|
+
if *known != value {
|
|
502
|
+
*known = None;
|
|
503
|
+
}
|
|
504
|
+
})
|
|
505
|
+
.or_insert(value);
|
|
506
|
+
}
|
|
507
|
+
|
|
508
|
+
fn is_pop(effect: &Effect) -> bool {
|
|
509
|
+
matches!(effect, Effect::Let(_, Term::Call { callee, .. })
|
|
510
|
+
if matches!(&**callee, Term::Global(name) if name == POP))
|
|
511
|
+
}
|
|
512
|
+
|
|
513
|
+
fn mentions_temporary(term: &Term) -> bool {
|
|
514
|
+
let mut found = false;
|
|
515
|
+
term.visit(&mut |term| found |= matches!(term, Term::Temp(_)));
|
|
516
|
+
found
|
|
517
|
+
}
|
|
518
|
+
|
|
519
|
+
/// What dataflow knows about a register, temporary or cell.
|
|
520
|
+
#[derive(Clone, Debug, PartialEq)]
|
|
521
|
+
enum Fact<'listing> {
|
|
522
|
+
Undefined,
|
|
523
|
+
Bool(bool),
|
|
524
|
+
Number(f64),
|
|
525
|
+
Text(Text<'listing>),
|
|
526
|
+
Global,
|
|
527
|
+
/// A program function by entry.
|
|
528
|
+
Closure(u32),
|
|
529
|
+
/// The decoder that the factory with this entry makes.
|
|
530
|
+
Decoder(u32),
|
|
531
|
+
}
|
|
532
|
+
|
|
533
|
+
type Facts<'listing> = BTreeMap<u8, Fact<'listing>>;
|
|
534
|
+
|
|
535
|
+
/// What a decoder returns for each text, if a string.
|
|
536
|
+
type Decoded = HashMap<String, Option<Rc<str>>>;
|
|
537
|
+
|
|
538
|
+
/// A string fact, which dataflow copies to every instruction it reaches: a listing constant, or
|
|
539
|
+
/// text that evaluation made.
|
|
540
|
+
#[derive(Clone, Debug)]
|
|
541
|
+
enum Text<'listing> {
|
|
542
|
+
Listing(&'listing str),
|
|
543
|
+
Shared(Rc<str>),
|
|
544
|
+
}
|
|
545
|
+
|
|
546
|
+
impl Deref for Text<'_> {
|
|
547
|
+
type Target = str;
|
|
548
|
+
|
|
549
|
+
fn deref(&self) -> &str {
|
|
550
|
+
match self {
|
|
551
|
+
Self::Listing(text) => text,
|
|
552
|
+
Self::Shared(text) => text,
|
|
553
|
+
}
|
|
554
|
+
}
|
|
555
|
+
}
|
|
556
|
+
|
|
557
|
+
impl PartialEq for Text<'_> {
|
|
558
|
+
fn eq(&self, other: &Self) -> bool {
|
|
559
|
+
**self == **other
|
|
560
|
+
}
|
|
561
|
+
}
|
|
562
|
+
|
|
563
|
+
impl<'listing> Fact<'listing> {
|
|
564
|
+
fn of(constant: &'listing Constant) -> Option<Self> {
|
|
565
|
+
Some(match constant {
|
|
566
|
+
Constant::Undefined => Self::Undefined,
|
|
567
|
+
Constant::Bool(value) => Self::Bool(*value),
|
|
568
|
+
Constant::Number(value) => Self::Number(*value),
|
|
569
|
+
Constant::String(text) => Self::Text(Text::Listing(text)),
|
|
570
|
+
Constant::Null => return None,
|
|
571
|
+
})
|
|
572
|
+
}
|
|
573
|
+
|
|
574
|
+
fn type_name(&self) -> &'static str {
|
|
575
|
+
match self {
|
|
576
|
+
Self::Undefined => "undefined",
|
|
577
|
+
Self::Bool(_) => "boolean",
|
|
578
|
+
Self::Number(_) => "number",
|
|
579
|
+
Self::Text(_) => "string",
|
|
580
|
+
Self::Global => "object",
|
|
581
|
+
Self::Closure(_) | Self::Decoder(_) => "function",
|
|
582
|
+
}
|
|
583
|
+
}
|
|
584
|
+
|
|
585
|
+
/// `===` where it is decided: primitives by value, the global object by identity. Two
|
|
586
|
+
/// functions are unknown, as one factory makes a new decoder on each call.
|
|
587
|
+
fn strictly_equals(&self, other: &Self) -> Option<bool> {
|
|
588
|
+
match (self, other) {
|
|
589
|
+
(Self::Closure(_) | Self::Decoder(_), Self::Closure(_) | Self::Decoder(_)) => None,
|
|
590
|
+
(Self::Number(left), Self::Number(right)) => Some(left == right),
|
|
591
|
+
_ => Some(self == other),
|
|
592
|
+
}
|
|
593
|
+
}
|
|
594
|
+
}
|
|
595
|
+
|
|
596
|
+
/// A condition's outcome when its fact is a known boolean.
|
|
597
|
+
fn truth(fact: Option<Fact<'_>>) -> Option<bool> {
|
|
598
|
+
match fact {
|
|
599
|
+
Some(Fact::Bool(value)) => Some(value),
|
|
600
|
+
_ => None,
|
|
601
|
+
}
|
|
602
|
+
}
|
|
603
|
+
|
|
604
|
+
/// Which function each instruction belongs to, which function creates each function, and what
|
|
605
|
+
/// functions keep in cells.
|
|
606
|
+
struct Scopes<'listing> {
|
|
607
|
+
owners: BTreeMap<u32, Option<u32>>,
|
|
608
|
+
parents: BTreeMap<u32, Option<u32>>,
|
|
609
|
+
declared: BTreeSet<(u32, u32)>,
|
|
610
|
+
/// What a function stores in a cell (see [`Program::stored`]).
|
|
611
|
+
stored: RefCell<BTreeMap<(u32, u32), Option<Fact<'listing>>>>,
|
|
612
|
+
/// Where each function is created, when one instruction creates it.
|
|
613
|
+
created: BTreeMap<u32, Option<u32>>,
|
|
614
|
+
/// The cells each function reads.
|
|
615
|
+
reads: BTreeMap<u32, BTreeSet<u32>>,
|
|
616
|
+
}
|
|
617
|
+
|
|
618
|
+
impl<'listing> Scopes<'listing> {
|
|
619
|
+
fn new(listing: &Listing) -> Self {
|
|
620
|
+
let mut hidden: BTreeMap<u32, Vec<u32>> = BTreeMap::new();
|
|
621
|
+
for branch in &listing.hidden {
|
|
622
|
+
hidden
|
|
623
|
+
.entry(branch.compare)
|
|
624
|
+
.or_default()
|
|
625
|
+
.push(branch.target.pc);
|
|
626
|
+
}
|
|
627
|
+
// Walk each function's code without entering the functions it creates.
|
|
628
|
+
let mut owners = BTreeMap::new();
|
|
629
|
+
for function in &listing.functions {
|
|
630
|
+
let mut pending = vec![function.pc];
|
|
631
|
+
let mut seen = BTreeSet::new();
|
|
632
|
+
while let Some(pc) = pending.pop() {
|
|
633
|
+
if !seen.insert(pc) {
|
|
634
|
+
continue;
|
|
635
|
+
}
|
|
636
|
+
let Some(instruction) = listing.instructions.get(&pc) else {
|
|
637
|
+
continue;
|
|
638
|
+
};
|
|
639
|
+
merge(&mut owners, pc, Some(function.pc));
|
|
640
|
+
pending.extend(instruction.exits());
|
|
641
|
+
pending.extend(hidden.get(&pc).into_iter().flatten());
|
|
642
|
+
for effect in instruction.effects() {
|
|
643
|
+
effect.visit_terms(&mut |term| {
|
|
644
|
+
if let Term::Array(frame) = term
|
|
645
|
+
&& let Some(handler) = disassemble::catch_frame(frame)
|
|
646
|
+
{
|
|
647
|
+
pending.push(handler.pc);
|
|
648
|
+
}
|
|
649
|
+
});
|
|
650
|
+
}
|
|
651
|
+
}
|
|
652
|
+
}
|
|
653
|
+
let mut parents = BTreeMap::new();
|
|
654
|
+
let mut declared = BTreeSet::new();
|
|
655
|
+
let mut created = BTreeMap::new();
|
|
656
|
+
let mut reads: BTreeMap<u32, BTreeSet<u32>> = BTreeMap::new();
|
|
657
|
+
for (&pc, instruction) in &listing.instructions {
|
|
658
|
+
let owner = owners.get(&pc).copied().flatten();
|
|
659
|
+
for effect in instruction.effects() {
|
|
660
|
+
effect.visit_terms(&mut |term| match term {
|
|
661
|
+
Term::Cell(cell) => {
|
|
662
|
+
if let Some(owner) = owner {
|
|
663
|
+
reads.entry(owner).or_default().insert(*cell);
|
|
664
|
+
}
|
|
665
|
+
}
|
|
666
|
+
Term::Closure { pc: function, .. } => {
|
|
667
|
+
merge(&mut created, *function, Some(pc));
|
|
668
|
+
merge(&mut parents, *function, owner);
|
|
669
|
+
}
|
|
670
|
+
_ => {}
|
|
671
|
+
});
|
|
672
|
+
if let (Some(owner), Effect::NewCell(cell)) = (owner, effect) {
|
|
673
|
+
declared.insert((owner, *cell));
|
|
674
|
+
}
|
|
675
|
+
}
|
|
676
|
+
}
|
|
677
|
+
Self {
|
|
678
|
+
owners,
|
|
679
|
+
parents,
|
|
680
|
+
declared,
|
|
681
|
+
stored: RefCell::default(),
|
|
682
|
+
created,
|
|
683
|
+
reads,
|
|
684
|
+
}
|
|
685
|
+
}
|
|
686
|
+
|
|
687
|
+
fn owner(&self, pc: u32) -> Option<u32> {
|
|
688
|
+
self.owners.get(&pc).copied().flatten()
|
|
689
|
+
}
|
|
690
|
+
|
|
691
|
+
/// Whether a function that reads `function`'s `cell` may run before `assigned`: one that
|
|
692
|
+
/// `function` creates there or earlier, or one created within it.
|
|
693
|
+
fn read_early(&self, function: u32, cell: u32, assigned: u32) -> bool {
|
|
694
|
+
self.reads.iter().any(|(&reader, cells)| {
|
|
695
|
+
if reader == function || !cells.contains(&cell) {
|
|
696
|
+
return false;
|
|
697
|
+
}
|
|
698
|
+
// The reader's enclosing functions, up to the one declaring the cell.
|
|
699
|
+
let mut scope = reader;
|
|
700
|
+
for _ in 0..=self.parents.len() {
|
|
701
|
+
if self.declared.contains(&(scope, cell)) {
|
|
702
|
+
return false;
|
|
703
|
+
}
|
|
704
|
+
let Some(parent) = self.parents.get(&scope).copied().flatten() else {
|
|
705
|
+
// Readers whose scope is unknown may read it.
|
|
706
|
+
return true;
|
|
707
|
+
};
|
|
708
|
+
if parent == function {
|
|
709
|
+
let created = self.created.get(&scope).copied().flatten();
|
|
710
|
+
return created.is_none_or(|at| at <= assigned);
|
|
711
|
+
}
|
|
712
|
+
scope = parent;
|
|
713
|
+
}
|
|
714
|
+
true
|
|
715
|
+
})
|
|
716
|
+
}
|
|
717
|
+
|
|
718
|
+
/// What `cell` holds in `function`, and the nearest enclosing function, which declares
|
|
719
|
+
/// the cell and stores it.
|
|
720
|
+
fn cell(&self, function: u32, cell: u32) -> Option<(u32, Fact<'listing>)> {
|
|
721
|
+
let mut scope = function;
|
|
722
|
+
for _ in 0..=self.parents.len() {
|
|
723
|
+
if self.declared.contains(&(scope, cell)) {
|
|
724
|
+
let stored = self.stored.borrow().get(&(scope, cell))?.clone()?;
|
|
725
|
+
return Some((scope, stored));
|
|
726
|
+
}
|
|
727
|
+
scope = self.parents.get(&scope).copied().flatten()?;
|
|
728
|
+
}
|
|
729
|
+
None
|
|
730
|
+
}
|
|
731
|
+
}
|
|
732
|
+
|
|
733
|
+
/// A value during evaluation.
|
|
734
|
+
#[derive(Clone, Debug)]
|
|
735
|
+
enum Value {
|
|
736
|
+
Undefined,
|
|
737
|
+
Null,
|
|
738
|
+
Bool(bool),
|
|
739
|
+
Number(f64),
|
|
740
|
+
String(Rc<[u16]>),
|
|
741
|
+
Global,
|
|
742
|
+
/// The `String` constructor.
|
|
743
|
+
StringConstructor,
|
|
744
|
+
Builtin(Builtin),
|
|
745
|
+
Array(Rc<RefCell<Vec<Value>>>),
|
|
746
|
+
Object(Rc<RefCell<Object>>),
|
|
747
|
+
Closure(Rc<Closure>),
|
|
748
|
+
/// A function the listing does not show.
|
|
749
|
+
Opaque,
|
|
750
|
+
}
|
|
751
|
+
|
|
752
|
+
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
|
753
|
+
enum Builtin {
|
|
754
|
+
Atob,
|
|
755
|
+
FromCharCode,
|
|
756
|
+
CharCodeAt,
|
|
757
|
+
Push,
|
|
758
|
+
}
|
|
759
|
+
|
|
760
|
+
#[derive(Debug, Default)]
|
|
761
|
+
struct Object {
|
|
762
|
+
properties: BTreeMap<Rc<[u16]>, Value>,
|
|
763
|
+
/// Whether the object's prototype was set to `null`, so that missing properties are
|
|
764
|
+
/// `undefined` rather than inherited.
|
|
765
|
+
bare: bool,
|
|
766
|
+
}
|
|
767
|
+
|
|
768
|
+
#[derive(Debug)]
|
|
769
|
+
struct Closure {
|
|
770
|
+
pc: u32,
|
|
771
|
+
cells: Cells,
|
|
772
|
+
}
|
|
773
|
+
|
|
774
|
+
type Cells = BTreeMap<u32, Rc<RefCell<Value>>>;
|
|
775
|
+
|
|
776
|
+
struct Frame {
|
|
777
|
+
registers: BTreeMap<u8, Value>,
|
|
778
|
+
cells: Cells,
|
|
779
|
+
}
|
|
780
|
+
|
|
781
|
+
impl Frame {
|
|
782
|
+
/// Whether the frame takes `path`, or `None` if a condition cannot be decided. Conditions
|
|
783
|
+
/// may read the path's own call results, which are computed without side effects.
|
|
784
|
+
fn takes(&self, path: &Path) -> Option<bool> {
|
|
785
|
+
let mut temporaries = BTreeMap::new();
|
|
786
|
+
if (path.conditions.iter()).any(|(condition, _)| mentions_temporary(condition)) {
|
|
787
|
+
for effect in &path.effects {
|
|
788
|
+
if let Effect::Let(temporary, term) = effect {
|
|
789
|
+
let value = self.pure(&temporaries).value(term);
|
|
790
|
+
dataflow::assign(&mut temporaries, *temporary, value);
|
|
791
|
+
}
|
|
792
|
+
}
|
|
793
|
+
}
|
|
794
|
+
let evaluation = self.pure(&temporaries);
|
|
795
|
+
for (condition, expected) in &path.conditions {
|
|
796
|
+
if evaluation.value(condition)?.truthy() != *expected {
|
|
797
|
+
return Some(false);
|
|
798
|
+
}
|
|
799
|
+
}
|
|
800
|
+
Some(true)
|
|
801
|
+
}
|
|
802
|
+
|
|
803
|
+
/// Evaluates without side effects against the frame's current state.
|
|
804
|
+
fn pure<'a>(&'a self, temporaries: &'a BTreeMap<usize, Value>) -> Evaluation<'a> {
|
|
805
|
+
Evaluation {
|
|
806
|
+
registers: &self.registers,
|
|
807
|
+
temporaries,
|
|
808
|
+
cells: &self.cells,
|
|
809
|
+
pure: true,
|
|
810
|
+
}
|
|
811
|
+
}
|
|
812
|
+
}
|
|
813
|
+
|
|
814
|
+
impl Value {
|
|
815
|
+
fn of(constant: &Constant) -> Self {
|
|
816
|
+
match constant {
|
|
817
|
+
Constant::Undefined => Self::Undefined,
|
|
818
|
+
Constant::Null => Self::Null,
|
|
819
|
+
Constant::Bool(value) => Self::Bool(*value),
|
|
820
|
+
Constant::Number(value) => Self::Number(*value),
|
|
821
|
+
Constant::String(text) => Self::String(text.encode_utf16().collect()),
|
|
822
|
+
}
|
|
823
|
+
}
|
|
824
|
+
|
|
825
|
+
fn number(&self) -> Option<f64> {
|
|
826
|
+
match self {
|
|
827
|
+
Self::Number(value) => Some(*value),
|
|
828
|
+
_ => None,
|
|
829
|
+
}
|
|
830
|
+
}
|
|
831
|
+
|
|
832
|
+
fn type_name(&self) -> &'static str {
|
|
833
|
+
match self {
|
|
834
|
+
Self::Undefined => "undefined",
|
|
835
|
+
Self::Bool(_) => "boolean",
|
|
836
|
+
Self::Number(_) => "number",
|
|
837
|
+
Self::String(_) => "string",
|
|
838
|
+
Self::Null | Self::Global | Self::Array(_) | Self::Object(_) => "object",
|
|
839
|
+
Self::StringConstructor | Self::Builtin(_) | Self::Closure(_) | Self::Opaque => {
|
|
840
|
+
"function"
|
|
841
|
+
}
|
|
842
|
+
}
|
|
843
|
+
}
|
|
844
|
+
|
|
845
|
+
/// `ToBoolean`.
|
|
846
|
+
fn truthy(&self) -> bool {
|
|
847
|
+
match self {
|
|
848
|
+
Self::Undefined | Self::Null => false,
|
|
849
|
+
Self::Bool(value) => *value,
|
|
850
|
+
Self::Number(value) => *value != 0.0 && !value.is_nan(),
|
|
851
|
+
Self::String(units) => !units.is_empty(),
|
|
852
|
+
_ => true,
|
|
853
|
+
}
|
|
854
|
+
}
|
|
855
|
+
|
|
856
|
+
/// `===`, for the values evaluation can compare.
|
|
857
|
+
fn strictly_equals(&self, other: &Self) -> Option<bool> {
|
|
858
|
+
Some(match (self, other) {
|
|
859
|
+
(Self::Undefined, Self::Undefined)
|
|
860
|
+
| (Self::Null, Self::Null)
|
|
861
|
+
| (Self::Global, Self::Global)
|
|
862
|
+
| (Self::StringConstructor, Self::StringConstructor) => true,
|
|
863
|
+
(Self::Bool(left), Self::Bool(right)) => left == right,
|
|
864
|
+
(Self::Number(left), Self::Number(right)) => left == right,
|
|
865
|
+
(Self::String(left), Self::String(right)) => left == right,
|
|
866
|
+
(Self::Builtin(left), Self::Builtin(right)) => left == right,
|
|
867
|
+
(Self::Array(left), Self::Array(right)) => Rc::ptr_eq(left, right),
|
|
868
|
+
(Self::Object(left), Self::Object(right)) => Rc::ptr_eq(left, right),
|
|
869
|
+
(Self::Closure(left), Self::Closure(right)) => Rc::ptr_eq(left, right),
|
|
870
|
+
(Self::Opaque, _) | (_, Self::Opaque) => return None,
|
|
871
|
+
_ => false,
|
|
872
|
+
})
|
|
873
|
+
}
|
|
874
|
+
}
|
|
875
|
+
|
|
876
|
+
/// Evaluates terms against registers as an instruction started.
|
|
877
|
+
struct Evaluation<'a> {
|
|
878
|
+
registers: &'a BTreeMap<u8, Value>,
|
|
879
|
+
temporaries: &'a BTreeMap<usize, Value>,
|
|
880
|
+
cells: &'a Cells,
|
|
881
|
+
/// Gives up on calls that change state, for deciding conditions.
|
|
882
|
+
pure: bool,
|
|
883
|
+
}
|
|
884
|
+
|
|
885
|
+
impl Evaluation<'_> {
|
|
886
|
+
fn value(&self, term: &Term) -> Option<Value> {
|
|
887
|
+
Some(match term {
|
|
888
|
+
Term::Const(constant) => Value::of(constant),
|
|
889
|
+
Term::Reg(register) => self.registers.get(register)?.clone(),
|
|
890
|
+
Term::Temp(temporary) => self.temporaries.get(temporary)?.clone(),
|
|
891
|
+
Term::Cell(cell) => self.cells.get(cell)?.borrow().clone(),
|
|
892
|
+
Term::Array(elements) => Value::Array(Rc::new(RefCell::new(self.values(elements)?))),
|
|
893
|
+
// Object literals other than `{}` never occur in the code this runs.
|
|
894
|
+
Term::Object(properties) if properties.is_empty() => {
|
|
895
|
+
Value::Object(Rc::new(RefCell::new(Object::default())))
|
|
896
|
+
}
|
|
897
|
+
Term::Get(object, key) => get(&self.value(object)?, &self.value(key)?)?,
|
|
898
|
+
Term::Call {
|
|
899
|
+
callee,
|
|
900
|
+
this,
|
|
901
|
+
arguments,
|
|
902
|
+
} => {
|
|
903
|
+
let (function, receiver) = match (&**callee, this) {
|
|
904
|
+
(Term::Global(name), None) => {
|
|
905
|
+
return self.call_global(name, &self.values(arguments)?);
|
|
906
|
+
}
|
|
907
|
+
(Term::Get(object, key), None) => {
|
|
908
|
+
let object = self.value(object)?;
|
|
909
|
+
(get(&object, &self.value(key)?)?, object)
|
|
910
|
+
}
|
|
911
|
+
(callee, None) => (self.value(callee)?, Value::Undefined),
|
|
912
|
+
(callee, Some(this)) => (self.value(callee)?, self.value(this)?),
|
|
913
|
+
};
|
|
914
|
+
self.call(&function, &receiver, &self.values(arguments)?)?
|
|
915
|
+
}
|
|
916
|
+
Term::Closure { pc, .. } => Value::Closure(Rc::new(Closure {
|
|
917
|
+
pc: *pc,
|
|
918
|
+
cells: self.cells.clone(),
|
|
919
|
+
})),
|
|
920
|
+
Term::Unary(operator, argument) => {
|
|
921
|
+
let argument = self.value(argument)?;
|
|
922
|
+
match operator {
|
|
923
|
+
UnaryOperator::Typeof => {
|
|
924
|
+
Value::String(argument.type_name().encode_utf16().collect())
|
|
925
|
+
}
|
|
926
|
+
UnaryOperator::LogicalNot => Value::Bool(!argument.truthy()),
|
|
927
|
+
UnaryOperator::UnaryNegation => Value::Number(-argument.number()?),
|
|
928
|
+
_ => return None,
|
|
929
|
+
}
|
|
930
|
+
}
|
|
931
|
+
Term::Binary(operator, left, right) => {
|
|
932
|
+
binary(*operator, &self.value(left)?, &self.value(right)?)?
|
|
933
|
+
}
|
|
934
|
+
Term::Logical(operator, left, right) => {
|
|
935
|
+
let left = self.value(left)?;
|
|
936
|
+
let decided = match operator {
|
|
937
|
+
LogicalOperator::And => !left.truthy(),
|
|
938
|
+
LogicalOperator::Or => left.truthy(),
|
|
939
|
+
LogicalOperator::Coalesce => !matches!(left, Value::Undefined | Value::Null),
|
|
940
|
+
};
|
|
941
|
+
if decided { left } else { self.value(right)? }
|
|
942
|
+
}
|
|
943
|
+
Term::Opaque(what) if what == "function" => Value::Opaque,
|
|
944
|
+
_ => return None,
|
|
945
|
+
})
|
|
946
|
+
}
|
|
947
|
+
|
|
948
|
+
fn values(&self, terms: &[Term]) -> Option<Vec<Value>> {
|
|
949
|
+
terms.iter().map(|term| self.value(term)).collect()
|
|
950
|
+
}
|
|
951
|
+
|
|
952
|
+
/// Calls the machine's stack pop or the script helper that applies a function.
|
|
953
|
+
fn call_global(&self, name: &str, arguments: &[Value]) -> Option<Value> {
|
|
954
|
+
if name == POP {
|
|
955
|
+
// The return address, which the return path checks is a number.
|
|
956
|
+
return arguments.is_empty().then_some(Value::Number(0.0));
|
|
957
|
+
}
|
|
958
|
+
match arguments {
|
|
959
|
+
[
|
|
960
|
+
Value::Opaque,
|
|
961
|
+
Value::Builtin(Builtin::FromCharCode),
|
|
962
|
+
_,
|
|
963
|
+
Value::Array(units),
|
|
964
|
+
] => from_char_code(&units.borrow()),
|
|
965
|
+
_ => None,
|
|
966
|
+
}
|
|
967
|
+
}
|
|
968
|
+
|
|
969
|
+
fn call(&self, function: &Value, receiver: &Value, arguments: &[Value]) -> Option<Value> {
|
|
970
|
+
let Value::Builtin(builtin) = function else {
|
|
971
|
+
return None;
|
|
972
|
+
};
|
|
973
|
+
match (builtin, receiver, arguments) {
|
|
974
|
+
(Builtin::Atob, _, [Value::String(text), ..]) => atob(text),
|
|
975
|
+
(Builtin::CharCodeAt, Value::String(text), arguments) => {
|
|
976
|
+
let position = match arguments.first() {
|
|
977
|
+
None | Some(Value::Undefined) => 0.0,
|
|
978
|
+
Some(position) => position.number()?,
|
|
979
|
+
};
|
|
980
|
+
let position = if position.is_nan() {
|
|
981
|
+
0.0
|
|
982
|
+
} else {
|
|
983
|
+
position.trunc()
|
|
984
|
+
};
|
|
985
|
+
let unit = (position >= 0.0)
|
|
986
|
+
.then(|| text.get(position as usize))
|
|
987
|
+
.flatten();
|
|
988
|
+
Some(Value::Number(
|
|
989
|
+
unit.map_or(f64::NAN, |&unit| f64::from(unit)),
|
|
990
|
+
))
|
|
991
|
+
}
|
|
992
|
+
(Builtin::Push, Value::Array(elements), arguments) if !self.pure => {
|
|
993
|
+
let mut elements = elements.borrow_mut();
|
|
994
|
+
elements.extend_from_slice(arguments);
|
|
995
|
+
Some(Value::Number(elements.len() as f64))
|
|
996
|
+
}
|
|
997
|
+
(Builtin::FromCharCode, _, arguments) => from_char_code(arguments),
|
|
998
|
+
_ => None,
|
|
999
|
+
}
|
|
1000
|
+
}
|
|
1001
|
+
}
|
|
1002
|
+
|
|
1003
|
+
/// `object[key]` for the objects evaluation models.
|
|
1004
|
+
fn get(object: &Value, key: &Value) -> Option<Value> {
|
|
1005
|
+
let key = match key {
|
|
1006
|
+
Value::String(units) => units,
|
|
1007
|
+
Value::Number(index) => {
|
|
1008
|
+
let Value::Array(elements) = object else {
|
|
1009
|
+
return None;
|
|
1010
|
+
};
|
|
1011
|
+
if index.fract() != 0.0 || *index < 0.0 {
|
|
1012
|
+
return None;
|
|
1013
|
+
}
|
|
1014
|
+
let element = elements.borrow().get(*index as usize).cloned();
|
|
1015
|
+
return Some(element.unwrap_or(Value::Undefined));
|
|
1016
|
+
}
|
|
1017
|
+
_ => return None,
|
|
1018
|
+
};
|
|
1019
|
+
let name = String::from_utf16(key).ok()?;
|
|
1020
|
+
Some(match (object, name.as_str()) {
|
|
1021
|
+
(Value::Global, "atob") => Value::Builtin(Builtin::Atob),
|
|
1022
|
+
(Value::Global, "String") => Value::StringConstructor,
|
|
1023
|
+
(Value::Global, "globalThis") => Value::Global,
|
|
1024
|
+
(Value::StringConstructor, "fromCharCode") => Value::Builtin(Builtin::FromCharCode),
|
|
1025
|
+
(Value::String(units), "length") => Value::Number(units.len() as f64),
|
|
1026
|
+
(Value::String(_), "charCodeAt") => Value::Builtin(Builtin::CharCodeAt),
|
|
1027
|
+
(Value::Array(elements), "length") => Value::Number(elements.borrow().len() as f64),
|
|
1028
|
+
(Value::Array(_), "push") => Value::Builtin(Builtin::Push),
|
|
1029
|
+
(Value::Object(object), _) => {
|
|
1030
|
+
let object = object.borrow();
|
|
1031
|
+
match object.properties.get(key) {
|
|
1032
|
+
Some(value) => value.clone(),
|
|
1033
|
+
// Without a prototype nothing is inherited.
|
|
1034
|
+
None if object.bare => Value::Undefined,
|
|
1035
|
+
None => return None,
|
|
1036
|
+
}
|
|
1037
|
+
}
|
|
1038
|
+
_ => return None,
|
|
1039
|
+
})
|
|
1040
|
+
}
|
|
1041
|
+
|
|
1042
|
+
fn set_property(object: &Value, key: &Value, value: Value) -> Option<()> {
|
|
1043
|
+
let (Value::Object(object), Value::String(key)) = (object, key) else {
|
|
1044
|
+
return None;
|
|
1045
|
+
};
|
|
1046
|
+
let mut object = object.borrow_mut();
|
|
1047
|
+
if key.iter().copied().eq("__proto__".encode_utf16()) {
|
|
1048
|
+
// Only a `null` prototype is modeled.
|
|
1049
|
+
if !matches!(value, Value::Null) || !object.properties.is_empty() {
|
|
1050
|
+
return None;
|
|
1051
|
+
}
|
|
1052
|
+
object.bare = true;
|
|
1053
|
+
} else if object.bare {
|
|
1054
|
+
object.properties.insert(key.clone(), value);
|
|
1055
|
+
} else {
|
|
1056
|
+
// Properties of an object with a prototype could be setters.
|
|
1057
|
+
return None;
|
|
1058
|
+
}
|
|
1059
|
+
Some(())
|
|
1060
|
+
}
|
|
1061
|
+
|
|
1062
|
+
fn binary(operator: BinaryOperator, left: &Value, right: &Value) -> Option<Value> {
|
|
1063
|
+
use BinaryOperator as Op;
|
|
1064
|
+
Some(match operator {
|
|
1065
|
+
Op::StrictEquality => Value::Bool(left.strictly_equals(right)?),
|
|
1066
|
+
Op::StrictInequality => Value::Bool(!left.strictly_equals(right)?),
|
|
1067
|
+
Op::Addition => match (left, right) {
|
|
1068
|
+
(Value::Number(left), Value::Number(right)) => Value::Number(left + right),
|
|
1069
|
+
(Value::String(left), Value::String(right)) => {
|
|
1070
|
+
Value::String([&left[..], &right[..]].concat().into())
|
|
1071
|
+
}
|
|
1072
|
+
_ => return None,
|
|
1073
|
+
},
|
|
1074
|
+
_ => {
|
|
1075
|
+
let (left, right) = (left.number()?, right.number()?);
|
|
1076
|
+
match operator {
|
|
1077
|
+
Op::Subtraction => Value::Number(left - right),
|
|
1078
|
+
Op::Multiplication => Value::Number(left * right),
|
|
1079
|
+
Op::BitwiseXOR => Value::Number(js::bit_xor(left, right)),
|
|
1080
|
+
Op::BitwiseOR => Value::Number(js::bit_or(left, right)),
|
|
1081
|
+
Op::BitwiseAnd => Value::Number(js::bit_and(left, right)),
|
|
1082
|
+
Op::ShiftLeft => Value::Number(js::shl(left, right)),
|
|
1083
|
+
Op::ShiftRight => Value::Number(js::shr(left, right)),
|
|
1084
|
+
Op::ShiftRightZeroFill => Value::Number(js::ushr(left, right)),
|
|
1085
|
+
Op::LessThan => Value::Bool(left < right),
|
|
1086
|
+
Op::GreaterThan => Value::Bool(left > right),
|
|
1087
|
+
Op::LessEqualThan => Value::Bool(left <= right),
|
|
1088
|
+
Op::GreaterEqualThan => Value::Bool(left >= right),
|
|
1089
|
+
_ => return None,
|
|
1090
|
+
}
|
|
1091
|
+
}
|
|
1092
|
+
})
|
|
1093
|
+
}
|
|
1094
|
+
|
|
1095
|
+
/// `String.fromCharCode` of numbers, which it takes modulo 2^16.
|
|
1096
|
+
fn from_char_code(arguments: &[Value]) -> Option<Value> {
|
|
1097
|
+
let units = arguments
|
|
1098
|
+
.iter()
|
|
1099
|
+
.map(|argument| Some(js::uint32(argument.number()?) as u16))
|
|
1100
|
+
.collect::<Option<_>>()?;
|
|
1101
|
+
Some(Value::String(units))
|
|
1102
|
+
}
|
|
1103
|
+
|
|
1104
|
+
/// `atob`: the forgiving base64 decode, giving one code unit per byte.
|
|
1105
|
+
fn atob(text: &[u16]) -> Option<Value> {
|
|
1106
|
+
let mut data: Vec<u8> = text
|
|
1107
|
+
.iter()
|
|
1108
|
+
.filter(|&&unit| !matches!(unit, 0x09 | 0x0a | 0x0c | 0x0d | 0x20))
|
|
1109
|
+
.map(|&unit| u8::try_from(unit).ok())
|
|
1110
|
+
.collect::<Option<_>>()?;
|
|
1111
|
+
if data.len().is_multiple_of(4) {
|
|
1112
|
+
for _ in 0..2 {
|
|
1113
|
+
if data.last() == Some(&b'=') {
|
|
1114
|
+
data.pop();
|
|
1115
|
+
}
|
|
1116
|
+
}
|
|
1117
|
+
}
|
|
1118
|
+
if data.len() % 4 == 1 {
|
|
1119
|
+
return None;
|
|
1120
|
+
}
|
|
1121
|
+
let mut bits = 0u32;
|
|
1122
|
+
let mut count = 0;
|
|
1123
|
+
let mut units = Vec::with_capacity(data.len() * 3 / 4);
|
|
1124
|
+
for byte in data {
|
|
1125
|
+
let digit = match byte {
|
|
1126
|
+
b'A'..=b'Z' => byte - b'A',
|
|
1127
|
+
b'a'..=b'z' => byte - b'a' + 26,
|
|
1128
|
+
b'0'..=b'9' => byte - b'0' + 52,
|
|
1129
|
+
b'+' => 62,
|
|
1130
|
+
b'/' => 63,
|
|
1131
|
+
_ => return None,
|
|
1132
|
+
};
|
|
1133
|
+
bits = bits << 6 | u32::from(digit);
|
|
1134
|
+
count += 6;
|
|
1135
|
+
if count >= 8 {
|
|
1136
|
+
count -= 8;
|
|
1137
|
+
units.push(((bits >> count) & 0xff) as u16);
|
|
1138
|
+
}
|
|
1139
|
+
}
|
|
1140
|
+
Some(Value::String(units.into()))
|
|
1141
|
+
}
|
|
1142
|
+
|
|
1143
|
+
#[cfg(test)]
|
|
1144
|
+
mod tests {
|
|
1145
|
+
use super::*;
|
|
1146
|
+
use crate::vm::output::{Instruction, Position};
|
|
1147
|
+
|
|
1148
|
+
fn units(text: &str) -> Vec<u16> {
|
|
1149
|
+
text.encode_utf16().collect()
|
|
1150
|
+
}
|
|
1151
|
+
|
|
1152
|
+
fn decoded(value: Option<Value>) -> Option<String> {
|
|
1153
|
+
match value? {
|
|
1154
|
+
Value::String(units) => String::from_utf16(&units).ok(),
|
|
1155
|
+
_ => None,
|
|
1156
|
+
}
|
|
1157
|
+
}
|
|
1158
|
+
|
|
1159
|
+
#[test]
|
|
1160
|
+
fn atob_follows_the_forgiving_base64_decode() {
|
|
1161
|
+
assert_eq!(decoded(atob(&units("ZiV4M2onbg=="))).unwrap(), "f%x3j'n");
|
|
1162
|
+
assert_eq!(decoded(atob(&units("ZiV4M2onbg"))).unwrap(), "f%x3j'n");
|
|
1163
|
+
assert_eq!(decoded(atob(&units(" Zm9v\n"))).unwrap(), "foo");
|
|
1164
|
+
assert!(atob(&units("Zm9vY")).is_none(), "a length of 1 modulo 4");
|
|
1165
|
+
assert!(atob(&units("Zm=9v")).is_none(), "padding inside");
|
|
1166
|
+
assert!(atob(&units("Zm9v-")).is_none());
|
|
1167
|
+
}
|
|
1168
|
+
|
|
1169
|
+
fn string(text: &str) -> Term {
|
|
1170
|
+
Term::Const(Constant::String(text.into()))
|
|
1171
|
+
}
|
|
1172
|
+
|
|
1173
|
+
fn number(value: f64) -> Term {
|
|
1174
|
+
Term::Const(Constant::Number(value))
|
|
1175
|
+
}
|
|
1176
|
+
|
|
1177
|
+
fn reg(register: u8) -> Term {
|
|
1178
|
+
Term::Reg(register)
|
|
1179
|
+
}
|
|
1180
|
+
|
|
1181
|
+
fn get(object: Term, key: Term) -> Term {
|
|
1182
|
+
Term::Get(Box::new(object), Box::new(key))
|
|
1183
|
+
}
|
|
1184
|
+
|
|
1185
|
+
fn binary(operator: BinaryOperator, left: Term, right: Term) -> Term {
|
|
1186
|
+
Term::Binary(operator, Box::new(left), Box::new(right))
|
|
1187
|
+
}
|
|
1188
|
+
|
|
1189
|
+
fn call(callee: Term, arguments: Vec<Term>) -> Term {
|
|
1190
|
+
Term::Call {
|
|
1191
|
+
callee: Box::new(callee),
|
|
1192
|
+
this: None,
|
|
1193
|
+
arguments,
|
|
1194
|
+
}
|
|
1195
|
+
}
|
|
1196
|
+
|
|
1197
|
+
fn closure(pc: u32) -> Term {
|
|
1198
|
+
Term::Closure {
|
|
1199
|
+
pc,
|
|
1200
|
+
key: 0,
|
|
1201
|
+
parameters: Vec::new(),
|
|
1202
|
+
arity: 1,
|
|
1203
|
+
}
|
|
1204
|
+
}
|
|
1205
|
+
|
|
1206
|
+
fn path(conditions: Vec<(Term, bool)>, effects: Vec<Effect>, exit: Exit) -> Path {
|
|
1207
|
+
Path {
|
|
1208
|
+
conditions,
|
|
1209
|
+
effects,
|
|
1210
|
+
exit,
|
|
1211
|
+
}
|
|
1212
|
+
}
|
|
1213
|
+
|
|
1214
|
+
/// Writes straight-line `code` at `start`, each instruction leading to the next and the
|
|
1215
|
+
/// last as given.
|
|
1216
|
+
fn code(listing: &mut Listing, start: u32, code: Vec<Vec<Path>>) {
|
|
1217
|
+
for (pc, paths) in (start..).zip(code) {
|
|
1218
|
+
listing.instructions.insert(
|
|
1219
|
+
pc,
|
|
1220
|
+
Instruction {
|
|
1221
|
+
pc,
|
|
1222
|
+
key: 0,
|
|
1223
|
+
opcode: 0,
|
|
1224
|
+
paths,
|
|
1225
|
+
},
|
|
1226
|
+
);
|
|
1227
|
+
}
|
|
1228
|
+
}
|
|
1229
|
+
|
|
1230
|
+
fn next(pc: u32) -> Exit {
|
|
1231
|
+
Exit::Next { pc, key: 0 }
|
|
1232
|
+
}
|
|
1233
|
+
|
|
1234
|
+
fn step(pc: u32, effects: Vec<Effect>) -> Vec<Path> {
|
|
1235
|
+
vec![path(Vec::new(), effects, next(pc + 1))]
|
|
1236
|
+
}
|
|
1237
|
+
|
|
1238
|
+
fn returning(register: u8) -> Vec<Path> {
|
|
1239
|
+
let pop = Effect::Let(0, call(Term::Global(POP.into()), Vec::new()));
|
|
1240
|
+
vec![path(
|
|
1241
|
+
Vec::new(),
|
|
1242
|
+
vec![Effect::Set(73, reg(register)), pop],
|
|
1243
|
+
Exit::Return,
|
|
1244
|
+
)]
|
|
1245
|
+
}
|
|
1246
|
+
|
|
1247
|
+
/// A program like the builds that encode strings: a factory at 100 keeps `globalThis` and
|
|
1248
|
+
/// `String` in cells and returns a decoder at 200, which XORs `atob(text)` with alternating
|
|
1249
|
+
/// key bytes and joins the characters through the apply helper. The function at 300 stores
|
|
1250
|
+
/// a decoder in cell 5, and the function at 400, which it creates, calls it.
|
|
1251
|
+
fn program() -> Listing {
|
|
1252
|
+
use BinaryOperator as Op;
|
|
1253
|
+
let mut listing = Listing {
|
|
1254
|
+
functions: [0, 100, 200, 300, 400]
|
|
1255
|
+
.map(|pc| Position::new(pc, 0))
|
|
1256
|
+
.to_vec(),
|
|
1257
|
+
..Listing::default()
|
|
1258
|
+
};
|
|
1259
|
+
// Program start: the method and property names the program uses throughout.
|
|
1260
|
+
code(
|
|
1261
|
+
&mut listing,
|
|
1262
|
+
0,
|
|
1263
|
+
vec![
|
|
1264
|
+
step(0, vec![Effect::Set(6, string("charCodeAt"))]),
|
|
1265
|
+
step(1, vec![Effect::Set(7, string("String"))]),
|
|
1266
|
+
step(2, vec![Effect::Set(9, string("length"))]),
|
|
1267
|
+
vec![path(
|
|
1268
|
+
Vec::new(),
|
|
1269
|
+
vec![Effect::Set(1, closure(300))],
|
|
1270
|
+
Exit::Return,
|
|
1271
|
+
)],
|
|
1272
|
+
],
|
|
1273
|
+
);
|
|
1274
|
+
code(
|
|
1275
|
+
&mut listing,
|
|
1276
|
+
100,
|
|
1277
|
+
vec![
|
|
1278
|
+
step(100, vec![Effect::Set(15, reg(98))]),
|
|
1279
|
+
step(101, vec![Effect::NewCell(29), Effect::SetCell(29, reg(15))]),
|
|
1280
|
+
step(
|
|
1281
|
+
102,
|
|
1282
|
+
vec![Effect::NewCell(31), Effect::Set(12, get(reg(15), reg(7)))],
|
|
1283
|
+
),
|
|
1284
|
+
step(103, vec![Effect::SetCell(31, reg(12))]),
|
|
1285
|
+
step(104, vec![Effect::Set(12, closure(200))]),
|
|
1286
|
+
returning(12),
|
|
1287
|
+
],
|
|
1288
|
+
);
|
|
1289
|
+
let xor = |key: f64| {
|
|
1290
|
+
vec![
|
|
1291
|
+
Effect::Let(0, call(get(reg(38), reg(6)), vec![reg(35)])),
|
|
1292
|
+
Effect::Set(21, binary(Op::BitwiseXOR, Term::Temp(0), number(key))),
|
|
1293
|
+
]
|
|
1294
|
+
};
|
|
1295
|
+
code(
|
|
1296
|
+
&mut listing,
|
|
1297
|
+
200,
|
|
1298
|
+
vec![
|
|
1299
|
+
step(200, vec![Effect::Set(18, reg(98))]),
|
|
1300
|
+
step(201, vec![Effect::Set(12, Term::Cell(29))]),
|
|
1301
|
+
step(
|
|
1302
|
+
202,
|
|
1303
|
+
vec![
|
|
1304
|
+
Effect::Let(0, call(get(reg(12), string("atob")), vec![reg(18)])),
|
|
1305
|
+
Effect::Set(38, Term::Temp(0)),
|
|
1306
|
+
],
|
|
1307
|
+
),
|
|
1308
|
+
step(
|
|
1309
|
+
203,
|
|
1310
|
+
vec![
|
|
1311
|
+
Effect::Set(35, number(0.0)),
|
|
1312
|
+
Effect::Set(19, Term::Array(Vec::new())),
|
|
1313
|
+
],
|
|
1314
|
+
),
|
|
1315
|
+
// 204: loop while characters remain.
|
|
1316
|
+
vec![
|
|
1317
|
+
path(
|
|
1318
|
+
vec![(binary(Op::LessThan, reg(35), get(reg(38), reg(9))), true)],
|
|
1319
|
+
Vec::new(),
|
|
1320
|
+
next(205),
|
|
1321
|
+
),
|
|
1322
|
+
path(
|
|
1323
|
+
vec![(binary(Op::LessThan, reg(35), get(reg(38), reg(9))), false)],
|
|
1324
|
+
Vec::new(),
|
|
1325
|
+
next(210),
|
|
1326
|
+
),
|
|
1327
|
+
],
|
|
1328
|
+
step(205, xor(11.0)),
|
|
1329
|
+
step(
|
|
1330
|
+
206,
|
|
1331
|
+
vec![
|
|
1332
|
+
Effect::Let(0, call(get(reg(19), string("push")), vec![reg(21)])),
|
|
1333
|
+
Effect::Set(35, binary(Op::Addition, reg(35), number(1.0))),
|
|
1334
|
+
],
|
|
1335
|
+
),
|
|
1336
|
+
// 207: an odd count ends the text.
|
|
1337
|
+
vec![
|
|
1338
|
+
path(
|
|
1339
|
+
vec![(binary(Op::LessThan, reg(35), get(reg(38), reg(9))), true)],
|
|
1340
|
+
Vec::new(),
|
|
1341
|
+
next(208),
|
|
1342
|
+
),
|
|
1343
|
+
path(
|
|
1344
|
+
vec![(binary(Op::LessThan, reg(35), get(reg(38), reg(9))), false)],
|
|
1345
|
+
Vec::new(),
|
|
1346
|
+
next(210),
|
|
1347
|
+
),
|
|
1348
|
+
],
|
|
1349
|
+
step(208, xor(64.0)),
|
|
1350
|
+
vec![path(
|
|
1351
|
+
Vec::new(),
|
|
1352
|
+
vec![
|
|
1353
|
+
Effect::Let(0, call(get(reg(19), string("push")), vec![reg(21)])),
|
|
1354
|
+
Effect::Set(35, binary(Op::Addition, reg(35), number(1.0))),
|
|
1355
|
+
],
|
|
1356
|
+
next(204),
|
|
1357
|
+
)],
|
|
1358
|
+
step(
|
|
1359
|
+
210,
|
|
1360
|
+
vec![Effect::Set(12, Term::Cell(31)), Effect::Set(16, string(""))],
|
|
1361
|
+
),
|
|
1362
|
+
step(
|
|
1363
|
+
211,
|
|
1364
|
+
vec![Effect::Set(21, get(reg(12), string("fromCharCode")))],
|
|
1365
|
+
),
|
|
1366
|
+
step(
|
|
1367
|
+
212,
|
|
1368
|
+
vec![
|
|
1369
|
+
Effect::Let(
|
|
1370
|
+
0,
|
|
1371
|
+
call(
|
|
1372
|
+
Term::Global("RZ".into()),
|
|
1373
|
+
vec![Term::Opaque("function".into()), reg(21), reg(12), reg(19)],
|
|
1374
|
+
),
|
|
1375
|
+
),
|
|
1376
|
+
Effect::Set(16, binary(Op::Addition, reg(16), Term::Temp(0))),
|
|
1377
|
+
],
|
|
1378
|
+
),
|
|
1379
|
+
returning(16),
|
|
1380
|
+
],
|
|
1381
|
+
);
|
|
1382
|
+
code(
|
|
1383
|
+
&mut listing,
|
|
1384
|
+
300,
|
|
1385
|
+
vec![
|
|
1386
|
+
step(300, vec![Effect::NewCell(5), Effect::Set(18, closure(100))]),
|
|
1387
|
+
step(
|
|
1388
|
+
301,
|
|
1389
|
+
vec![Effect::Set(12, get(reg(13), string("globalThis")))],
|
|
1390
|
+
),
|
|
1391
|
+
step(
|
|
1392
|
+
302,
|
|
1393
|
+
vec![
|
|
1394
|
+
Effect::Let(0, call(reg(18), vec![reg(12)])),
|
|
1395
|
+
Effect::Set(25, Term::Temp(0)),
|
|
1396
|
+
],
|
|
1397
|
+
),
|
|
1398
|
+
step(303, vec![Effect::SetCell(5, reg(25))]),
|
|
1399
|
+
step(304, vec![Effect::Set(12, closure(400))]),
|
|
1400
|
+
returning(12),
|
|
1401
|
+
],
|
|
1402
|
+
);
|
|
1403
|
+
code(
|
|
1404
|
+
&mut listing,
|
|
1405
|
+
400,
|
|
1406
|
+
vec![
|
|
1407
|
+
step(
|
|
1408
|
+
400,
|
|
1409
|
+
vec![
|
|
1410
|
+
Effect::Set(18, reg(98)),
|
|
1411
|
+
Effect::Set(18, string("byF/IQ==")),
|
|
1412
|
+
],
|
|
1413
|
+
),
|
|
1414
|
+
step(
|
|
1415
|
+
401,
|
|
1416
|
+
vec![
|
|
1417
|
+
Effect::Let(0, call(Term::Cell(5), vec![reg(18)])),
|
|
1418
|
+
Effect::Set(15, Term::Temp(0)),
|
|
1419
|
+
],
|
|
1420
|
+
),
|
|
1421
|
+
step(402, vec![Effect::Set(16, get(reg(12), reg(15)))]),
|
|
1422
|
+
returning(16),
|
|
1423
|
+
],
|
|
1424
|
+
);
|
|
1425
|
+
listing
|
|
1426
|
+
}
|
|
1427
|
+
|
|
1428
|
+
#[test]
|
|
1429
|
+
fn decoder_calls_become_loads_of_what_they_return() {
|
|
1430
|
+
let mut listing = program();
|
|
1431
|
+
fold(&mut listing);
|
|
1432
|
+
assert_eq!(
|
|
1433
|
+
listing.instructions[&401].paths[0].effects,
|
|
1434
|
+
[
|
|
1435
|
+
Effect::Let(0, string("data")),
|
|
1436
|
+
Effect::Set(15, string("data"))
|
|
1437
|
+
],
|
|
1438
|
+
);
|
|
1439
|
+
assert_eq!(
|
|
1440
|
+
listing.instructions[&400].paths[0].effects[1],
|
|
1441
|
+
Effect::Set(18, string("byF/IQ==")),
|
|
1442
|
+
"the encoded text stays where the program loads it"
|
|
1443
|
+
);
|
|
1444
|
+
assert_eq!(listing.encoded, BTreeSet::from(["byF/IQ==".to_owned()]));
|
|
1445
|
+
}
|
|
1446
|
+
|
|
1447
|
+
/// A cell assigned text reads as that text in the functions its function creates, but not
|
|
1448
|
+
/// in the function itself, nor anywhere once a function that reads it is created earlier.
|
|
1449
|
+
#[test]
|
|
1450
|
+
fn text_cells_read_as_their_text_in_created_functions() {
|
|
1451
|
+
let fold_with = |early_reader_reads: bool| {
|
|
1452
|
+
let mut listing = program();
|
|
1453
|
+
let functions = [500, 600, 700].map(|pc| Position::new(pc, 0));
|
|
1454
|
+
listing.functions.extend(functions);
|
|
1455
|
+
code(
|
|
1456
|
+
&mut listing,
|
|
1457
|
+
500,
|
|
1458
|
+
vec![
|
|
1459
|
+
// A function created before the assignment.
|
|
1460
|
+
step(500, vec![Effect::NewCell(7), Effect::Set(15, closure(700))]),
|
|
1461
|
+
step(501, vec![Effect::SetCell(7, string("entryType"))]),
|
|
1462
|
+
step(502, vec![Effect::Set(12, Term::Cell(7))]),
|
|
1463
|
+
step(503, vec![Effect::Set(14, closure(600))]),
|
|
1464
|
+
returning(14),
|
|
1465
|
+
],
|
|
1466
|
+
);
|
|
1467
|
+
code(
|
|
1468
|
+
&mut listing,
|
|
1469
|
+
600,
|
|
1470
|
+
vec![
|
|
1471
|
+
step(600, vec![Effect::Set(12, Term::Cell(7))]),
|
|
1472
|
+
returning(12),
|
|
1473
|
+
],
|
|
1474
|
+
);
|
|
1475
|
+
let early = if early_reader_reads {
|
|
1476
|
+
Term::Cell(7)
|
|
1477
|
+
} else {
|
|
1478
|
+
reg(98)
|
|
1479
|
+
};
|
|
1480
|
+
code(
|
|
1481
|
+
&mut listing,
|
|
1482
|
+
700,
|
|
1483
|
+
vec![step(700, vec![Effect::Set(16, early)]), returning(16)],
|
|
1484
|
+
);
|
|
1485
|
+
fold(&mut listing);
|
|
1486
|
+
listing
|
|
1487
|
+
};
|
|
1488
|
+
let listing = fold_with(false);
|
|
1489
|
+
assert_eq!(
|
|
1490
|
+
listing.instructions[&600].paths[0].effects,
|
|
1491
|
+
[Effect::Set(12, string("entryType"))]
|
|
1492
|
+
);
|
|
1493
|
+
assert_eq!(
|
|
1494
|
+
listing.instructions[&502].paths[0].effects,
|
|
1495
|
+
[Effect::Set(12, Term::Cell(7))],
|
|
1496
|
+
"the assigning function's own read is left"
|
|
1497
|
+
);
|
|
1498
|
+
assert!(!listing.encoded.contains("entryType"));
|
|
1499
|
+
let listing = fold_with(true);
|
|
1500
|
+
assert_eq!(
|
|
1501
|
+
listing.instructions[&600].paths[0].effects,
|
|
1502
|
+
[Effect::Set(12, Term::Cell(7))],
|
|
1503
|
+
"a function created before the assignment reads the cell"
|
|
1504
|
+
);
|
|
1505
|
+
}
|
|
1506
|
+
|
|
1507
|
+
/// Some builds set the result after popping the return address.
|
|
1508
|
+
#[test]
|
|
1509
|
+
fn results_set_after_the_pop_are_found() {
|
|
1510
|
+
let mut listing = program();
|
|
1511
|
+
for instruction in listing.instructions.values_mut() {
|
|
1512
|
+
for path in &mut instruction.paths {
|
|
1513
|
+
if path.exit == Exit::Return && path.effects.len() == 2 {
|
|
1514
|
+
path.effects.reverse();
|
|
1515
|
+
}
|
|
1516
|
+
}
|
|
1517
|
+
}
|
|
1518
|
+
fold(&mut listing);
|
|
1519
|
+
assert_eq!(
|
|
1520
|
+
listing.instructions[&401].paths[0].effects,
|
|
1521
|
+
[
|
|
1522
|
+
Effect::Let(0, string("data")),
|
|
1523
|
+
Effect::Set(15, string("data"))
|
|
1524
|
+
],
|
|
1525
|
+
);
|
|
1526
|
+
}
|
|
1527
|
+
|
|
1528
|
+
#[test]
|
|
1529
|
+
fn a_cell_another_function_declares_is_not_the_decoder() {
|
|
1530
|
+
let mut listing = program();
|
|
1531
|
+
// The calling function declares its own cell 5, which holds no decoder.
|
|
1532
|
+
let start = &mut listing.instructions.get_mut(&400).unwrap().paths[0].effects;
|
|
1533
|
+
start.insert(0, Effect::NewCell(5));
|
|
1534
|
+
fold(&mut listing);
|
|
1535
|
+
assert_eq!(
|
|
1536
|
+
listing.instructions[&401].paths[0].effects[1],
|
|
1537
|
+
Effect::Set(15, Term::Temp(0))
|
|
1538
|
+
);
|
|
1539
|
+
}
|
|
1540
|
+
|
|
1541
|
+
#[test]
|
|
1542
|
+
fn unmodeled_operations_leave_the_call() {
|
|
1543
|
+
let mut listing = program();
|
|
1544
|
+
// The decoder reads a property of the global object evaluation does not model.
|
|
1545
|
+
listing.instructions.get_mut(&201).unwrap().paths[0].effects =
|
|
1546
|
+
vec![Effect::Set(12, get(Term::Cell(29), string("crypto")))];
|
|
1547
|
+
fold(&mut listing);
|
|
1548
|
+
assert_eq!(
|
|
1549
|
+
listing.instructions[&401].paths[0].effects[1],
|
|
1550
|
+
Effect::Set(15, Term::Temp(0))
|
|
1551
|
+
);
|
|
1552
|
+
}
|
|
1553
|
+
}
|