mini_racer_rs 1.4.0 → 1.5.0

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.
@@ -27,18 +27,35 @@ pub enum HeapLimitError {
27
27
  Overridden(&'static str),
28
28
  }
29
29
 
30
- /// Why a startup snapshot's blob is refused before V8 reads it, where V8
31
- /// itself would abort the process.
30
+ /// Why a startup snapshot's blob is refused before V8 reads it, in
31
+ /// `mini_racer`'s words.
32
32
  #[derive(Debug, Clone, Copy, PartialEq, Eq, thiserror::Error)]
33
33
  pub enum InvalidSnapshot {
34
- /// Shorter than its own header, or its sections do not fit in it.
35
- #[error("invalid snapshot: truncated or corrupt")]
36
- Corrupt,
37
- #[error("invalid snapshot: not made by V8 {}", crate::process::v8_version())]
34
+ #[error("snapshot is too large")]
35
+ TooLarge,
36
+ #[error("snapshot is too short")]
37
+ TooShort,
38
+ #[error("snapshot version mismatch")]
38
39
  Version,
39
- /// Empty, where a warmup needs a snapshot to start from.
40
- #[error("invalid snapshot: empty")]
41
- Empty,
40
+ #[error("snapshot header is invalid")]
41
+ Header,
42
+ #[error("snapshot has no contexts")]
43
+ NoContexts,
44
+ #[error("snapshot context table is invalid")]
45
+ ContextTable,
46
+ /// The section before the one word 80 starts, V8 15.2's read-only one,
47
+ /// which V8 aborts on or reads past and `mini_racer` hands V8, named as
48
+ /// `mini_racer`'s messages name it.
49
+ #[error("snapshot startup section is invalid")]
50
+ Startup,
51
+ #[error("snapshot read-only section is invalid")]
52
+ ReadOnly,
53
+ #[error("snapshot shared-heap section is invalid")]
54
+ SharedHeap,
55
+ #[error("snapshot context section is invalid")]
56
+ Context,
57
+ #[error("snapshot checksum mismatch")]
58
+ Checksum,
42
59
  }
43
60
 
44
61
  /// Why `SourceMaps::register` refused a map.
@@ -13,11 +13,17 @@ pub const PRISTINE: usize = 0;
13
13
 
14
14
  // How V8 15.2 lays a blob out (`SnapshotImpl` in v8/src/snapshot/snapshot.cc):
15
15
  // little-endian words for its context count, whether it can be rehashed and
16
- // two checksums, its version string, then the offsets of its sections. The
17
- // read-only section starts at the first 8-byte boundary after the header, and
18
- // each section opens with V8's magic number and its payload's length.
16
+ // two checksums, its version string, then the offsets of its startup section,
17
+ // its shared heap section and each context's. The read-only section comes
18
+ // first, at the first 8-byte boundary after the header, and each section opens
19
+ // with V8's magic number and its payload's length. mini_racer's messages, which
20
+ // the refusals keep, call the section word 80 starts the read-only one and the
21
+ // one before it the startup one.
19
22
  const CONTEXTS: usize = 0;
20
23
  const REHASHABLE: usize = 4;
24
+ const CHECKSUM: usize = 8;
25
+ // The checksum covers everything after its own word.
26
+ const CHECKSUMMED: usize = 12;
21
27
  const VERSION_END: usize = 16 + 64;
22
28
  const STARTUP: usize = 80;
23
29
  const SHARED_HEAP: usize = 84;
@@ -25,9 +31,46 @@ const FIRST_CONTEXT: usize = 88;
25
31
  const WORD: usize = 4;
26
32
  const ALIGNMENT: usize = 8;
27
33
  const SECTION_HEADER: usize = 8;
28
- // V8's magic number is 0xC0DE0000 exclusive-ored with a table size under 2^16,
29
- // so this is its top half.
30
- const MAGIC_HIGH: usize = 0xC0DE;
34
+ // V8 checksums a blob with zlib's Adler-32 when built with zlib, as
35
+ // libv8-node's is, and with its own Fletcher-32 otherwise, as the v8 crate's
36
+ // is; mini_racer accepts either.
37
+ const ADLER: u64 = 65_521;
38
+ const FLETCHER: u64 = 65_535;
39
+ // Bytes summed before the sums are reduced; their u64s cannot overflow.
40
+ const CHECKSUM_RUN: usize = 1 << 16;
41
+
42
+ // mini_racer runs this before a `Snapshot.new` script, word for word, since
43
+ // the script can read the accessor back, and refuses the script once it has
44
+ // read or written `Intl`: V8 cannot write Intl's objects into a blob and aborts
45
+ // the process on one.
46
+ const INTL_GUARD: &str = r#"
47
+ ;(function() {
48
+ const original = globalThis.Intl
49
+ let used = false
50
+ const getter = function() {
51
+ used = true
52
+ return original
53
+ }
54
+ const setter = function(value) {
55
+ used = true
56
+ }
57
+ if (!original) {
58
+ const query = function() { return used }
59
+ query.getter = getter
60
+ return query
61
+ }
62
+ Object.defineProperty(globalThis, "Intl", {
63
+ configurable: true,
64
+ enumerable: false,
65
+ get: getter,
66
+ set: setter
67
+ })
68
+ const query = function() { return used }
69
+ query.getter = getter
70
+ return query
71
+ })()
72
+ "#;
73
+ const INTL_REFUSED: &str = "Intl is not supported in Snapshot.new scripts";
31
74
 
32
75
  /// A startup snapshot's blob, which every context made from it shares.
33
76
  ///
@@ -38,30 +81,42 @@ const MAGIC_HIGH: usize = 0xC0DE;
38
81
  pub struct SnapshotBlob(Arc<[u8]>);
39
82
 
40
83
  impl SnapshotBlob {
84
+ /// The word V8 opens each section of a blob with, which its deserializer
85
+ /// checks: `SerializedData::kMagicNumber`, 0xC0DE0000 exclusive-ored with
86
+ /// the size of V8's external reference table, here V8 15.2's in the v8
87
+ /// crate 152.2.0.
88
+ pub const MAGIC: u32 = 0xC0DE_06C1;
89
+
41
90
  pub fn new(bytes: &[u8]) -> Result<Self, InvalidSnapshot> {
42
91
  Self::check(bytes)?;
43
92
  Ok(Self(Arc::from(bytes)))
44
93
  }
45
94
 
46
- /// Refuses a blob V8 would abort on, or read past the end of, before it
47
- /// reaches the objects inside: one too short for its header, another V8's,
48
- /// or one whose sections do not fit in it, as a truncated one's do not.
49
- /// What a section holds is left to V8, so a blob V8 reads despite a damaged
50
- /// byte still loads, as it does in `mini_racer`.
95
+ /// Refuses a blob as `mini_racer` does, in its order: one too long for
96
+ /// V8, too short for its header, another V8's, one whose header or section
97
+ /// offsets do not fit it, or whose checksum does not match. Then, past
98
+ /// those, a blob with a section V8 aborts the process on or reads past
99
+ /// the end of, which `mini_racer` hands V8: anyone can write a checksum
100
+ /// that matches.
51
101
  pub fn check(bytes: &[u8]) -> Result<(), InvalidSnapshot> {
52
102
  if bytes.is_empty() {
53
103
  return Ok(());
54
104
  }
55
- // V8 keeps a blob's length in a C int, and aborts unless the blob runs
56
- // past the header up to its version.
57
- if bytes.len() <= VERSION_END || i32::try_from(bytes.len()).is_err() {
58
- return Err(InvalidSnapshot::Corrupt);
105
+ if i32::try_from(bytes.len()).is_err() {
106
+ return Err(InvalidSnapshot::TooLarge);
107
+ }
108
+ if bytes.len() < FIRST_CONTEXT {
109
+ return Err(InvalidSnapshot::TooShort);
59
110
  }
60
111
  let header = bytes.get(..=VERSION_END).map(<[u8]>::to_vec);
61
112
  if !header.is_some_and(|header| v8::StartupData::from(header).is_valid()) {
62
113
  return Err(InvalidSnapshot::Version);
63
114
  }
64
- sections_fit(bytes).ok_or(InvalidSnapshot::Corrupt)
115
+ let ends = section_ends(bytes)?;
116
+ if !checksum_matches(bytes) {
117
+ return Err(InvalidSnapshot::Checksum);
118
+ }
119
+ sections_fit(bytes, &ends)
65
120
  }
66
121
 
67
122
  #[must_use]
@@ -104,29 +159,94 @@ fn word(bytes: &[u8], at: usize) -> Option<usize> {
104
159
  usize::try_from(u32::from_le_bytes(word.try_into().ok()?)).ok()
105
160
  }
106
161
 
107
- // What V8 checks as it finds each section, the rehashability flag included,
108
- // and the payload length it then trusts without a check.
109
- fn sections_fit(bytes: &[u8]) -> Option<()> {
110
- let contexts = word(bytes, CONTEXTS).filter(|contexts| *contexts > 0)?;
111
- word(bytes, REHASHABLE).filter(|flag| *flag <= 1)?;
112
- let header = contexts.checked_mul(WORD)?.checked_add(FIRST_CONTEXT)?;
113
- let mut start = header.checked_next_multiple_of(ALIGNMENT)?;
114
- let magic = word(bytes, start).filter(|magic| magic >> 16 == MAGIC_HIGH)?;
115
- let ends = [STARTUP, SHARED_HEAP]
162
+ // Where each section starts, from the read-only section to the end of the
163
+ // blob, with `mini_racer`'s checks on the header and the offsets in its order.
164
+ fn section_ends(bytes: &[u8]) -> Result<Vec<usize>, InvalidSnapshot> {
165
+ let len = bytes.len();
166
+ let read = |at| word(bytes, at).ok_or(InvalidSnapshot::TooShort);
167
+ let contexts = read(CONTEXTS)?;
168
+ if read(REHASHABLE)? > 1 {
169
+ return Err(InvalidSnapshot::Header);
170
+ }
171
+ if contexts == 0 {
172
+ return Err(InvalidSnapshot::NoContexts);
173
+ }
174
+ if contexts > (len - FIRST_CONTEXT) / WORD {
175
+ return Err(InvalidSnapshot::ContextTable);
176
+ }
177
+ let read_only = (FIRST_CONTEXT + contexts * WORD).next_multiple_of(ALIGNMENT);
178
+ if read_only > len {
179
+ return Err(InvalidSnapshot::ContextTable);
180
+ }
181
+ let startup = read(STARTUP)?;
182
+ if startup <= read_only || startup > len {
183
+ return Err(InvalidSnapshot::ReadOnly);
184
+ }
185
+ let shared_heap = read(SHARED_HEAP)?;
186
+ if shared_heap <= startup || shared_heap > len {
187
+ return Err(InvalidSnapshot::SharedHeap);
188
+ }
189
+ let mut ends = vec![read_only, startup, shared_heap];
190
+ for index in 0..contexts {
191
+ let offset = read(FIRST_CONTEXT + index * WORD)?;
192
+ if ends.last().is_some_and(|previous| offset <= *previous) || offset >= len {
193
+ return Err(InvalidSnapshot::Context);
194
+ }
195
+ ends.push(offset);
196
+ }
197
+ ends.push(len);
198
+ Ok(ends)
199
+ }
200
+
201
+ fn checksum_matches(bytes: &[u8]) -> bool {
202
+ let checksummed = bytes.get(CHECKSUMMED..).unwrap_or_default();
203
+ let expected = word(bytes, CHECKSUM).and_then(|word| u64::try_from(word).ok());
204
+ [ADLER, FLETCHER]
116
205
  .into_iter()
117
- .chain((0..contexts).map(|index| FIRST_CONTEXT + index * WORD))
118
- .map(|at| word(bytes, at))
119
- .chain([Some(bytes.len())]);
120
- for end in ends {
121
- let end = end?;
122
- let section = bytes.get(start..end)?;
123
- let payload = word(section, WORD)?;
124
- if word(section, 0)? != magic || payload > section.len().checked_sub(SECTION_HEADER)? {
125
- return None;
206
+ .any(|modulus| Some(checksum(checksummed, modulus)) == expected)
207
+ }
208
+
209
+ // V8's `Checksum`: the two running sums from zero, each reduced by `modulus`.
210
+ fn checksum(bytes: &[u8], modulus: u64) -> u64 {
211
+ let (mut low, mut high) = (0_u64, 0_u64);
212
+ for run in bytes.chunks(CHECKSUM_RUN) {
213
+ for &byte in run {
214
+ low += u64::from(byte);
215
+ high += low;
216
+ }
217
+ low %= modulus;
218
+ high %= modulus;
219
+ }
220
+ high << 16 | low
221
+ }
222
+
223
+ // V8 aborts on a section that does not open with its magic number, and reads a
224
+ // section's payload for as long as its header says without a check. `ends`
225
+ // starts at the read-only section, so each pair of neighbors bounds a section,
226
+ // in the order of mini_racer's messages.
227
+ fn sections_fit(bytes: &[u8], ends: &[usize]) -> Result<(), InvalidSnapshot> {
228
+ for (index, bounds) in ends.windows(2).enumerate() {
229
+ let refused = match index {
230
+ 0 => InvalidSnapshot::Startup,
231
+ 1 => InvalidSnapshot::ReadOnly,
232
+ 2 => InvalidSnapshot::SharedHeap,
233
+ _ => InvalidSnapshot::Context,
234
+ };
235
+ let section = bounds
236
+ .first()
237
+ .zip(bounds.get(1))
238
+ .and_then(|(start, end)| bytes.get(*start..*end))
239
+ .ok_or(refused)?;
240
+ let magic = word(section, 0).and_then(|magic| u32::try_from(magic).ok());
241
+ let fits = magic == Some(SnapshotBlob::MAGIC)
242
+ && word(section, WORD)
243
+ .zip(section.len().checked_sub(SECTION_HEADER))
244
+ .is_some_and(|(payload, room)| payload <= room);
245
+ if !fits {
246
+ return Err(refused);
126
247
  }
127
- start = end;
128
248
  }
129
- Some(())
249
+ Ok(())
130
250
  }
131
251
 
132
252
  // mini_racer reads the code back from V8 as UTF-8, which turns a lone
@@ -149,7 +269,7 @@ fn source<'s>(tc: &Tc<'s, '_, '_, '_>, code: &JsText) -> Option<v8::Local<'s, v8
149
269
  /// Builds a startup snapshot in an isolate of its own, as `mini_racer` does:
150
270
  /// from `code` run in a fresh context, or, with `base`, by running `code` in
151
271
  /// a context of that snapshot that is then discarded, keeping the code V8
152
- /// compiled meanwhile.
272
+ /// compiled meanwhile. An empty `base` warms up V8's own snapshot.
153
273
  /// `building` sees the isolate first, so a pending fork can interrupt it.
154
274
  pub fn create(
155
275
  code: &JsText,
@@ -157,6 +277,7 @@ pub fn create(
157
277
  building: impl FnOnce(&mut v8::Isolate),
158
278
  ) -> Result<Vec<u8>, EngineError> {
159
279
  let warmup = base.is_some();
280
+ let base = base.filter(|blob| !blob.is_empty());
160
281
  // `base` outlives the isolate, which `create_blob` disposes of.
161
282
  let mut isolate = base.map_or_else(
162
283
  || v8::Isolate::snapshot_creator(None, None),
@@ -178,16 +299,21 @@ pub fn create(
178
299
  v8::scope!(let scope, &mut isolate);
179
300
  // A new context of a warmup's base blob would carry the snapshot's
180
301
  // script, so the base blob's own pristine context is kept.
181
- let pristine = warmup
182
- .then(|| v8::Context::from_snapshot(scope, PRISTINE, v8::ContextOptions::default()))
183
- .flatten()
302
+ let pristine = base
303
+ .and_then(|_| {
304
+ v8::Context::from_snapshot(scope, PRISTINE, v8::ContextOptions::default())
305
+ })
184
306
  .unwrap_or_else(|| v8::Context::new(scope, v8::ContextOptions::default()));
185
307
  scope.add_context(pristine);
186
308
  let context = v8::Context::new(scope, v8::ContextOptions::default());
187
309
  let outcome = {
188
310
  let scope = &mut v8::ContextScope::new(scope, context);
189
311
  v8::tc_scope!(let tc, scope);
190
- run(tc, code, name)
312
+ if warmup {
313
+ run(tc, code, name)
314
+ } else {
315
+ run_guarded(tc, code, name)
316
+ }
191
317
  };
192
318
  // V8 needs a default context to write a blob even on the error path;
193
319
  // a fresh one leaves the failed script's objects unreachable, so
@@ -206,6 +332,98 @@ pub fn create(
206
332
  .ok_or_else(|| EngineError::Snapshot(UNEXPECTED.to_owned()))
207
333
  }
208
334
 
335
+ fn run_guarded(tc: &Tc<'_, '_, '_, '_>, code: &JsText, name: &str) -> Result<(), EngineError> {
336
+ let guard = guard_intl(tc)?;
337
+ run(tc, code, name)?;
338
+ if let Some(guard) = guard {
339
+ guard.release(tc)?;
340
+ }
341
+ Ok(())
342
+ }
343
+
344
+ struct IntlGuard<'s> {
345
+ original: v8::Local<'s, v8::Value>,
346
+ used: v8::Local<'s, v8::Function>,
347
+ getter: v8::Local<'s, v8::Function>,
348
+ }
349
+
350
+ fn internal(message: &str) -> EngineError {
351
+ EngineError::Snapshot(message.to_owned())
352
+ }
353
+
354
+ fn intl_key<'s>(tc: &Tc<'s, '_, '_, '_>) -> Option<v8::Local<'s, v8::Name>> {
355
+ v8::String::new(tc, "Intl").map(Into::into)
356
+ }
357
+
358
+ // None when the global has no `Intl` object to guard, as in mini_racer.
359
+ fn guard_intl<'s>(tc: &Tc<'s, '_, '_, '_>) -> Result<Option<IntlGuard<'s>>, EngineError> {
360
+ let global = tc.get_current_context().global(tc);
361
+ let original = intl_key(tc)
362
+ .and_then(|key| global.get(tc, key.into()))
363
+ .ok_or_else(|| internal("failed to inspect snapshot Intl"))?;
364
+ if !original.is_object() {
365
+ return Ok(None);
366
+ }
367
+ let failed = || internal("failed to initialize snapshot Intl guard");
368
+ let source = v8::String::new(tc, INTL_GUARD).ok_or_else(failed)?;
369
+ let used = v8::Script::compile(tc, source, None)
370
+ .and_then(|script| script.run(tc))
371
+ .and_then(|used| v8::Local::<v8::Function>::try_from(used).ok())
372
+ .ok_or_else(failed)?;
373
+ let getter = v8::String::new(tc, "getter")
374
+ .and_then(|key| used.get(tc, key.into()))
375
+ .and_then(|getter| v8::Local::<v8::Function>::try_from(getter).ok())
376
+ .ok_or_else(failed)?;
377
+ Ok(Some(IntlGuard {
378
+ original,
379
+ used,
380
+ getter,
381
+ }))
382
+ }
383
+
384
+ impl IntlGuard<'_> {
385
+ // Refuses a script that read or wrote `Intl`, then puts `Intl` back unless
386
+ // the script replaced or deleted the accessor. Each lookup is of an own
387
+ // property, so nothing a script left on `Object.prototype` runs here.
388
+ fn release(self, tc: &Tc<'_, '_, '_, '_>) -> Result<(), EngineError> {
389
+ let undefined = v8::undefined(tc).into();
390
+ let used = self
391
+ .used
392
+ .call(tc, undefined, &[])
393
+ .ok_or_else(|| internal("failed to inspect snapshot Intl guard"))?;
394
+ if used.is_true() {
395
+ return Err(EngineError::Snapshot(INTL_REFUSED.to_owned()));
396
+ }
397
+ let inspect = || internal("failed to inspect Intl after snapshot script");
398
+ let global = tc.get_current_context().global(tc);
399
+ let key = intl_key(tc).ok_or_else(inspect)?;
400
+ let descriptor = global
401
+ .get_own_property_descriptor(tc, key)
402
+ .ok_or_else(inspect)?;
403
+ let mut ours = false;
404
+ if let Ok(descriptor) = v8::Local::<v8::Object>::try_from(descriptor) {
405
+ let get = v8::String::new(tc, "get").ok_or_else(inspect)?;
406
+ let getter = descriptor
407
+ .get_own_property_descriptor(tc, get.into())
408
+ .ok_or_else(inspect)?;
409
+ if let Ok(getter) = v8::Local::<v8::Object>::try_from(getter) {
410
+ let getter = v8::String::new(tc, "value")
411
+ .and_then(|value| getter.get(tc, value.into()))
412
+ .ok_or_else(inspect)?;
413
+ ours = getter.is_function() && getter.same_value(self.getter.into());
414
+ }
415
+ }
416
+ if ours
417
+ && !global
418
+ .define_own_property(tc, key, self.original, v8::PropertyAttribute::DONT_ENUM)
419
+ .unwrap_or(false)
420
+ {
421
+ return Err(internal("failed to restore Intl after snapshot script"));
422
+ }
423
+ Ok(())
424
+ }
425
+ }
426
+
209
427
  fn run(tc: &Tc<'_, '_, '_, '_>, code: &JsText, name: &str) -> Result<(), EngineError> {
210
428
  let source = source(tc, code).ok_or_else(|| failure(tc))?;
211
429
  let name = v8::String::new(tc, name).ok_or_else(|| failure(tc))?;
@@ -92,7 +92,7 @@ impl CauseSet {
92
92
  #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
93
93
  pub struct DispatchId(u64);
94
94
 
95
- /// How a dispatch treats pending causes, following `mini_racer` 0.22.1.
95
+ /// How a dispatch treats pending causes, following `mini_racer` 0.22.2.
96
96
  #[derive(Debug, Clone, Copy, PartialEq, Eq)]
97
97
  pub enum DispatchKind {
98
98
  /// `eval`, `call` and their await forms, snapshot creation and warmup:
@@ -741,13 +741,21 @@ impl Visitor for RubyVisitor<'_> {
741
741
  }
742
742
 
743
743
  // mini_racer decodes a result inside its [result, error] reply, one level
744
- // below its limit.
744
+ // below its limit, and a callback's arguments array at its limit.
745
745
  const RESULT_LIMITS: Limits = Limits {
746
746
  max_depth: 95,
747
747
  max_bigint_bytes: 16 << 20,
748
748
  };
749
749
 
750
750
  pub fn value(ruby: &Ruby, bytes: &[u8]) -> Result<Value, Error> {
751
+ decode(ruby, bytes, RESULT_LIMITS)
752
+ }
753
+
754
+ pub fn arguments(ruby: &Ruby, bytes: &[u8]) -> Result<Value, Error> {
755
+ decode(ruby, bytes, Limits::default())
756
+ }
757
+
758
+ fn decode(ruby: &Ruby, bytes: &[u8], limits: Limits) -> Result<Value, Error> {
751
759
  let mut visitor = RubyVisitor {
752
760
  ruby,
753
761
  refs: None,
@@ -762,7 +770,7 @@ pub fn value(ruby: &Ruby, bytes: &[u8]) -> Result<Value, Error> {
762
770
  scratch: Vec::new(),
763
771
  roomy: usize::MAX,
764
772
  };
765
- decode_value(bytes, RESULT_LIMITS, &mut visitor).map_err(|e| match e {
773
+ decode_value(bytes, limits, &mut visitor).map_err(|e| match e {
766
774
  DecodeError::Visitor(error) => error,
767
775
  other => errors::runtime(ruby, other.to_string()),
768
776
  })