mini_racer_rs 1.4.0 → 1.5.1

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.
@@ -18,7 +18,7 @@ use crate::process::platform::Mode;
18
18
  use crate::process::{self, platform, watchdog};
19
19
  use crate::runner::Start;
20
20
  use crate::spin::spin_until;
21
- use crate::{EngineError, InvalidSnapshot, SnapshotBlob, runner};
21
+ use crate::{EngineError, SnapshotBlob, runner};
22
22
 
23
23
  const MIN_RUNNER_STACK_BYTES: usize = 2 << 20;
24
24
  const STACK_HEADROOM_BYTES: usize = 1 << 20;
@@ -414,11 +414,6 @@ impl ContextHandle {
414
414
  base: Option<SnapshotBlob>,
415
415
  host: &mut impl Host,
416
416
  ) -> Result<Vec<u8>, EngineError> {
417
- // A warmup from no snapshot would build the read-only heap again, which
418
- // V8 aborts on once the process has one.
419
- if base.as_ref().is_some_and(SnapshotBlob::is_empty) {
420
- return Err(InvalidSnapshot::Empty.into());
421
- }
422
417
  let context = Self::spawn(ContextConfig::default(), host)?;
423
418
  let built = context.dispatch(
424
419
  DispatchKind::Script,
@@ -874,3 +869,57 @@ fn channel(error: ChannelError) -> EngineError {
874
869
  error => protocol(error),
875
870
  }
876
871
  }
872
+
873
+ #[cfg(test)]
874
+ mod tests {
875
+ use std::sync::Arc;
876
+ use std::time::{Duration, Instant};
877
+
878
+ use mini_racer_sync::Phase;
879
+
880
+ use super::{ContextHandle, Held, Host, WaitHandle, WaitOutcome};
881
+ use crate::control::ContextConfig;
882
+
883
+ struct Parking;
884
+
885
+ impl Host for Parking {
886
+ fn wait(&mut self, wait: &WaitHandle<'_>) -> WaitOutcome {
887
+ self.wait_blocking(wait);
888
+ WaitOutcome::Ready
889
+ }
890
+
891
+ fn wait_blocking(&mut self, wait: &WaitHandle<'_>) {
892
+ while !wait.ready() {
893
+ wait.park();
894
+ }
895
+ }
896
+ }
897
+
898
+ // A weak reference keeps the block's allocation, which a thread that made
899
+ // the context and exited leaves in a malloc arena other threads take over.
900
+ #[test]
901
+ fn the_watchdog_lets_go_of_a_disposed_context_before_its_timeout() {
902
+ let context = ContextHandle::spawn(
903
+ ContextConfig {
904
+ timeout: Some(Duration::from_secs(600)),
905
+ ..ContextConfig::default()
906
+ },
907
+ &mut Parking,
908
+ )
909
+ .expect("spawn");
910
+ let Held::Block(block) = context.held() else {
911
+ panic!("a new context holds its block");
912
+ };
913
+ let block = Arc::clone(block);
914
+ let untimed = Arc::weak_count(&block);
915
+ context.eval("<eval>", "1", &mut Parking).expect("eval");
916
+ context.begin_dispose();
917
+ context.dispose(&mut Parking).expect("dispose");
918
+ let deadline = Instant::now() + Duration::from_secs(30);
919
+ while block.phase.get() != Phase::Exited {
920
+ assert!(Instant::now() < deadline, "the runner did not exit");
921
+ std::thread::sleep(Duration::from_millis(1));
922
+ }
923
+ assert_eq!(Arc::weak_count(&block), untimed);
924
+ }
925
+ }
@@ -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.
@@ -1,5 +1,5 @@
1
1
  use std::cmp::{Ordering, Reverse};
2
- use std::collections::BinaryHeap;
2
+ use std::collections::{BinaryHeap, HashMap};
3
3
  use std::sync::{Arc, Condvar, Mutex, Weak};
4
4
  use std::time::{Duration, Instant};
5
5
 
@@ -7,11 +7,13 @@ use mini_racer_sync::{DispatchId, Interrupt, lock, wait, wait_timeout};
7
7
 
8
8
  use crate::EngineError;
9
9
  use crate::control::{ControlBlock, Timer};
10
+ use crate::process::fork::Generation;
10
11
 
11
12
  struct Entry {
12
13
  at: Instant,
13
14
  seq: u64,
14
- block: Weak<ControlBlock>,
15
+ // The context's key in `Timers::blocks`.
16
+ block: usize,
15
17
  }
16
18
 
17
19
  impl PartialEq for Entry {
@@ -37,6 +39,15 @@ impl Ord for Entry {
37
39
  #[derive(Default)]
38
40
  struct Timers {
39
41
  heap: BinaryHeap<Reverse<Entry>>,
42
+ // The contexts the entries are for, by address, each from its first
43
+ // timed script until its runner exits (`forget`). Entries outlive their
44
+ // dispatches and a weak reference keeps a context's allocation, so an
45
+ // entry names its context rather than holds it: held to its deadline, a
46
+ // disposed context's allocation fragments the malloc arena of a thread
47
+ // that made it and exited. An address is mapped only while its context's
48
+ // allocation is, and an entry left after `forget` at most wakes the
49
+ // watchdog to reread a slot.
50
+ blocks: HashMap<usize, Weak<ControlBlock>>,
40
51
  seq: u64,
41
52
  }
42
53
 
@@ -46,16 +57,31 @@ pub struct Watchdog {
46
57
  }
47
58
 
48
59
  impl Watchdog {
49
- fn push(&self, at: Instant, block: Weak<ControlBlock>) {
60
+ fn push(&self, at: Instant, block: &Arc<ControlBlock>) {
61
+ let key = address(block);
50
62
  let mut timers = lock(&self.timers);
51
63
  timers.seq = timers.seq.wrapping_add(1);
52
64
  let seq = timers.seq;
53
- timers.heap.push(Reverse(Entry { at, seq, block }));
65
+ // A live reference at this address can only be this context's; a dead
66
+ // one is a context gone without `forget`, whose place this one took.
67
+ let slot = timers.blocks.entry(key).or_default();
68
+ if slot.strong_count() == 0 {
69
+ *slot = Arc::downgrade(block);
70
+ }
71
+ timers.heap.push(Reverse(Entry {
72
+ at,
73
+ seq,
74
+ block: key,
75
+ }));
54
76
  drop(timers);
55
77
  self.changed.notify_one();
56
78
  }
57
79
  }
58
80
 
81
+ fn address(block: &ControlBlock) -> usize {
82
+ std::ptr::from_ref(block).addr()
83
+ }
84
+
59
85
  // One thread per process serves every context's timeouts. It is kept per
60
86
  // fork generation: a forked child has the parent's watchdog state but not its
61
87
  // thread, and a runner of the parent may have held its lock at the fork.
@@ -118,7 +144,7 @@ fn arm(
118
144
  drop(timer);
119
145
  // A wake entry the watchdog no longer needs is harmless: it rereads the slot.
120
146
  if wake {
121
- watchdog.push(at, Arc::downgrade(block));
147
+ watchdog.push(at, block);
122
148
  }
123
149
  Ok(())
124
150
  }
@@ -166,6 +192,15 @@ pub fn clear_nested(block: &ControlBlock, id: DispatchId) {
166
192
  lock(&block.timer).nested.retain(|(_, due)| *due != id);
167
193
  }
168
194
 
195
+ /// Drops the watchdog's reference to a context whose runner has exited, so
196
+ /// a deadline still pending keeps none of it.
197
+ pub fn forget(block: &ControlBlock, generation: &Generation) {
198
+ let watchdog = lock(generation.watchdog()).clone();
199
+ if let Some(watchdog) = watchdog {
200
+ lock(&watchdog.timers).blocks.remove(&address(block));
201
+ }
202
+ }
203
+
169
204
  fn run(watchdog: &Watchdog) {
170
205
  loop {
171
206
  let mut timers = lock(&watchdog.timers);
@@ -186,8 +221,14 @@ fn run(watchdog: &Watchdog) {
186
221
  .peek()
187
222
  .is_some_and(|Reverse(entry)| entry.at <= now)
188
223
  {
189
- if let Some(Reverse(entry)) = timers.heap.pop() {
190
- due.push(entry.block);
224
+ if let Some(Reverse(entry)) = timers.heap.pop()
225
+ && let Some(block) = timers.blocks.get(&entry.block)
226
+ {
227
+ if block.strong_count() == 0 {
228
+ timers.blocks.remove(&entry.block);
229
+ } else {
230
+ due.push(Weak::clone(block));
231
+ }
191
232
  }
192
233
  }
193
234
  // Lock order: the heap is released before any context's timer
@@ -229,6 +270,6 @@ fn fire(watchdog: &Watchdog, block: &Arc<ControlBlock>, now: Instant) {
229
270
  block.term.request(Interrupt::Timeout(id));
230
271
  }
231
272
  if let Some(at) = next {
232
- watchdog.push(at, Arc::downgrade(block));
273
+ watchdog.push(at, block);
233
274
  }
234
275
  }
@@ -298,6 +298,7 @@ pub fn run(block: &Arc<ControlBlock>, generation: &'static Generation, start: St
298
298
  let _ = block.channel.respond(Ok(Vec::new()));
299
299
  }
300
300
  drop(closing);
301
+ watchdog::forget(block, generation);
301
302
  block.phase.set(Phase::Exited);
302
303
  }
303
304
 
@@ -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,43 +31,95 @@ 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
  ///
34
77
  /// V8 reads the blob for as long as an isolate made from it lives, whenever it
35
78
  /// makes a context from it or checks a code cache against it. Empty, it stands
36
79
  /// for no snapshot, as it does in `mini_racer`.
80
+ // The bytes have an allocation of their own, freed with the last strong
81
+ // reference: a `Weak` keeps its `Arc`'s allocation, and with it bytes kept
82
+ // inline there.
37
83
  #[derive(Clone, Default, PartialEq, Eq)]
38
- pub struct SnapshotBlob(Arc<[u8]>);
84
+ pub struct SnapshotBlob(Arc<Box<[u8]>>);
39
85
 
40
86
  impl SnapshotBlob {
87
+ /// The word V8 opens each section of a blob with, which its deserializer
88
+ /// checks: `SerializedData::kMagicNumber`, 0xC0DE0000 exclusive-ored with
89
+ /// the size of V8's external reference table, here V8 15.2's in the v8
90
+ /// crate 152.2.0.
91
+ pub const MAGIC: u32 = 0xC0DE_06C1;
92
+
41
93
  pub fn new(bytes: &[u8]) -> Result<Self, InvalidSnapshot> {
42
94
  Self::check(bytes)?;
43
- Ok(Self(Arc::from(bytes)))
95
+ Ok(Self(Arc::new(Box::from(bytes))))
44
96
  }
45
97
 
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`.
98
+ /// Refuses a blob as `mini_racer` does, in its order: one too long for
99
+ /// V8, too short for its header, another V8's, one whose header or section
100
+ /// offsets do not fit it, or whose checksum does not match. Then, past
101
+ /// those, a blob with a section V8 aborts the process on or reads past
102
+ /// the end of, which `mini_racer` hands V8: anyone can write a checksum
103
+ /// that matches.
51
104
  pub fn check(bytes: &[u8]) -> Result<(), InvalidSnapshot> {
52
105
  if bytes.is_empty() {
53
106
  return Ok(());
54
107
  }
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);
108
+ if i32::try_from(bytes.len()).is_err() {
109
+ return Err(InvalidSnapshot::TooLarge);
110
+ }
111
+ if bytes.len() < FIRST_CONTEXT {
112
+ return Err(InvalidSnapshot::TooShort);
59
113
  }
60
114
  let header = bytes.get(..=VERSION_END).map(<[u8]>::to_vec);
61
115
  if !header.is_some_and(|header| v8::StartupData::from(header).is_valid()) {
62
116
  return Err(InvalidSnapshot::Version);
63
117
  }
64
- sections_fit(bytes).ok_or(InvalidSnapshot::Corrupt)
118
+ let ends = section_ends(bytes)?;
119
+ if !checksum_matches(bytes) {
120
+ return Err(InvalidSnapshot::Checksum);
121
+ }
122
+ sections_fit(bytes, &ends)
65
123
  }
66
124
 
67
125
  #[must_use]
@@ -82,7 +140,7 @@ impl SnapshotBlob {
82
140
 
83
141
  /// A `SnapshotBlob` that lives only while a context made from it does.
84
142
  #[derive(Debug, Clone)]
85
- pub struct WeakSnapshotBlob(Weak<[u8]>);
143
+ pub struct WeakSnapshotBlob(Weak<Box<[u8]>>);
86
144
 
87
145
  impl WeakSnapshotBlob {
88
146
  #[must_use]
@@ -104,29 +162,94 @@ fn word(bytes: &[u8], at: usize) -> Option<usize> {
104
162
  usize::try_from(u32::from_le_bytes(word.try_into().ok()?)).ok()
105
163
  }
106
164
 
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]
165
+ // Where each section starts, from the read-only section to the end of the
166
+ // blob, with `mini_racer`'s checks on the header and the offsets in its order.
167
+ fn section_ends(bytes: &[u8]) -> Result<Vec<usize>, InvalidSnapshot> {
168
+ let len = bytes.len();
169
+ let read = |at| word(bytes, at).ok_or(InvalidSnapshot::TooShort);
170
+ let contexts = read(CONTEXTS)?;
171
+ if read(REHASHABLE)? > 1 {
172
+ return Err(InvalidSnapshot::Header);
173
+ }
174
+ if contexts == 0 {
175
+ return Err(InvalidSnapshot::NoContexts);
176
+ }
177
+ if contexts > (len - FIRST_CONTEXT) / WORD {
178
+ return Err(InvalidSnapshot::ContextTable);
179
+ }
180
+ let read_only = (FIRST_CONTEXT + contexts * WORD).next_multiple_of(ALIGNMENT);
181
+ if read_only > len {
182
+ return Err(InvalidSnapshot::ContextTable);
183
+ }
184
+ let startup = read(STARTUP)?;
185
+ if startup <= read_only || startup > len {
186
+ return Err(InvalidSnapshot::ReadOnly);
187
+ }
188
+ let shared_heap = read(SHARED_HEAP)?;
189
+ if shared_heap <= startup || shared_heap > len {
190
+ return Err(InvalidSnapshot::SharedHeap);
191
+ }
192
+ let mut ends = vec![read_only, startup, shared_heap];
193
+ for index in 0..contexts {
194
+ let offset = read(FIRST_CONTEXT + index * WORD)?;
195
+ if ends.last().is_some_and(|previous| offset <= *previous) || offset >= len {
196
+ return Err(InvalidSnapshot::Context);
197
+ }
198
+ ends.push(offset);
199
+ }
200
+ ends.push(len);
201
+ Ok(ends)
202
+ }
203
+
204
+ fn checksum_matches(bytes: &[u8]) -> bool {
205
+ let checksummed = bytes.get(CHECKSUMMED..).unwrap_or_default();
206
+ let expected = word(bytes, CHECKSUM).and_then(|word| u64::try_from(word).ok());
207
+ [ADLER, FLETCHER]
116
208
  .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;
209
+ .any(|modulus| Some(checksum(checksummed, modulus)) == expected)
210
+ }
211
+
212
+ // V8's `Checksum`: the two running sums from zero, each reduced by `modulus`.
213
+ fn checksum(bytes: &[u8], modulus: u64) -> u64 {
214
+ let (mut low, mut high) = (0_u64, 0_u64);
215
+ for run in bytes.chunks(CHECKSUM_RUN) {
216
+ for &byte in run {
217
+ low += u64::from(byte);
218
+ high += low;
219
+ }
220
+ low %= modulus;
221
+ high %= modulus;
222
+ }
223
+ high << 16 | low
224
+ }
225
+
226
+ // V8 aborts on a section that does not open with its magic number, and reads a
227
+ // section's payload for as long as its header says without a check. `ends`
228
+ // starts at the read-only section, so each pair of neighbors bounds a section,
229
+ // in the order of mini_racer's messages.
230
+ fn sections_fit(bytes: &[u8], ends: &[usize]) -> Result<(), InvalidSnapshot> {
231
+ for (index, bounds) in ends.windows(2).enumerate() {
232
+ let refused = match index {
233
+ 0 => InvalidSnapshot::Startup,
234
+ 1 => InvalidSnapshot::ReadOnly,
235
+ 2 => InvalidSnapshot::SharedHeap,
236
+ _ => InvalidSnapshot::Context,
237
+ };
238
+ let section = bounds
239
+ .first()
240
+ .zip(bounds.get(1))
241
+ .and_then(|(start, end)| bytes.get(*start..*end))
242
+ .ok_or(refused)?;
243
+ let magic = word(section, 0).and_then(|magic| u32::try_from(magic).ok());
244
+ let fits = magic == Some(SnapshotBlob::MAGIC)
245
+ && word(section, WORD)
246
+ .zip(section.len().checked_sub(SECTION_HEADER))
247
+ .is_some_and(|(payload, room)| payload <= room);
248
+ if !fits {
249
+ return Err(refused);
126
250
  }
127
- start = end;
128
251
  }
129
- Some(())
252
+ Ok(())
130
253
  }
131
254
 
132
255
  // mini_racer reads the code back from V8 as UTF-8, which turns a lone
@@ -149,7 +272,7 @@ fn source<'s>(tc: &Tc<'s, '_, '_, '_>, code: &JsText) -> Option<v8::Local<'s, v8
149
272
  /// Builds a startup snapshot in an isolate of its own, as `mini_racer` does:
150
273
  /// from `code` run in a fresh context, or, with `base`, by running `code` in
151
274
  /// a context of that snapshot that is then discarded, keeping the code V8
152
- /// compiled meanwhile.
275
+ /// compiled meanwhile. An empty `base` warms up V8's own snapshot.
153
276
  /// `building` sees the isolate first, so a pending fork can interrupt it.
154
277
  pub fn create(
155
278
  code: &JsText,
@@ -157,6 +280,7 @@ pub fn create(
157
280
  building: impl FnOnce(&mut v8::Isolate),
158
281
  ) -> Result<Vec<u8>, EngineError> {
159
282
  let warmup = base.is_some();
283
+ let base = base.filter(|blob| !blob.is_empty());
160
284
  // `base` outlives the isolate, which `create_blob` disposes of.
161
285
  let mut isolate = base.map_or_else(
162
286
  || v8::Isolate::snapshot_creator(None, None),
@@ -178,16 +302,21 @@ pub fn create(
178
302
  v8::scope!(let scope, &mut isolate);
179
303
  // A new context of a warmup's base blob would carry the snapshot's
180
304
  // 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()
305
+ let pristine = base
306
+ .and_then(|_| {
307
+ v8::Context::from_snapshot(scope, PRISTINE, v8::ContextOptions::default())
308
+ })
184
309
  .unwrap_or_else(|| v8::Context::new(scope, v8::ContextOptions::default()));
185
310
  scope.add_context(pristine);
186
311
  let context = v8::Context::new(scope, v8::ContextOptions::default());
187
312
  let outcome = {
188
313
  let scope = &mut v8::ContextScope::new(scope, context);
189
314
  v8::tc_scope!(let tc, scope);
190
- run(tc, code, name)
315
+ if warmup {
316
+ run(tc, code, name)
317
+ } else {
318
+ run_guarded(tc, code, name)
319
+ }
191
320
  };
192
321
  // V8 needs a default context to write a blob even on the error path;
193
322
  // a fresh one leaves the failed script's objects unreachable, so
@@ -206,6 +335,98 @@ pub fn create(
206
335
  .ok_or_else(|| EngineError::Snapshot(UNEXPECTED.to_owned()))
207
336
  }
208
337
 
338
+ fn run_guarded(tc: &Tc<'_, '_, '_, '_>, code: &JsText, name: &str) -> Result<(), EngineError> {
339
+ let guard = guard_intl(tc)?;
340
+ run(tc, code, name)?;
341
+ if let Some(guard) = guard {
342
+ guard.release(tc)?;
343
+ }
344
+ Ok(())
345
+ }
346
+
347
+ struct IntlGuard<'s> {
348
+ original: v8::Local<'s, v8::Value>,
349
+ used: v8::Local<'s, v8::Function>,
350
+ getter: v8::Local<'s, v8::Function>,
351
+ }
352
+
353
+ fn internal(message: &str) -> EngineError {
354
+ EngineError::Snapshot(message.to_owned())
355
+ }
356
+
357
+ fn intl_key<'s>(tc: &Tc<'s, '_, '_, '_>) -> Option<v8::Local<'s, v8::Name>> {
358
+ v8::String::new(tc, "Intl").map(Into::into)
359
+ }
360
+
361
+ // None when the global has no `Intl` object to guard, as in mini_racer.
362
+ fn guard_intl<'s>(tc: &Tc<'s, '_, '_, '_>) -> Result<Option<IntlGuard<'s>>, EngineError> {
363
+ let global = tc.get_current_context().global(tc);
364
+ let original = intl_key(tc)
365
+ .and_then(|key| global.get(tc, key.into()))
366
+ .ok_or_else(|| internal("failed to inspect snapshot Intl"))?;
367
+ if !original.is_object() {
368
+ return Ok(None);
369
+ }
370
+ let failed = || internal("failed to initialize snapshot Intl guard");
371
+ let source = v8::String::new(tc, INTL_GUARD).ok_or_else(failed)?;
372
+ let used = v8::Script::compile(tc, source, None)
373
+ .and_then(|script| script.run(tc))
374
+ .and_then(|used| v8::Local::<v8::Function>::try_from(used).ok())
375
+ .ok_or_else(failed)?;
376
+ let getter = v8::String::new(tc, "getter")
377
+ .and_then(|key| used.get(tc, key.into()))
378
+ .and_then(|getter| v8::Local::<v8::Function>::try_from(getter).ok())
379
+ .ok_or_else(failed)?;
380
+ Ok(Some(IntlGuard {
381
+ original,
382
+ used,
383
+ getter,
384
+ }))
385
+ }
386
+
387
+ impl IntlGuard<'_> {
388
+ // Refuses a script that read or wrote `Intl`, then puts `Intl` back unless
389
+ // the script replaced or deleted the accessor. Each lookup is of an own
390
+ // property, so nothing a script left on `Object.prototype` runs here.
391
+ fn release(self, tc: &Tc<'_, '_, '_, '_>) -> Result<(), EngineError> {
392
+ let undefined = v8::undefined(tc).into();
393
+ let used = self
394
+ .used
395
+ .call(tc, undefined, &[])
396
+ .ok_or_else(|| internal("failed to inspect snapshot Intl guard"))?;
397
+ if used.is_true() {
398
+ return Err(EngineError::Snapshot(INTL_REFUSED.to_owned()));
399
+ }
400
+ let inspect = || internal("failed to inspect Intl after snapshot script");
401
+ let global = tc.get_current_context().global(tc);
402
+ let key = intl_key(tc).ok_or_else(inspect)?;
403
+ let descriptor = global
404
+ .get_own_property_descriptor(tc, key)
405
+ .ok_or_else(inspect)?;
406
+ let mut ours = false;
407
+ if let Ok(descriptor) = v8::Local::<v8::Object>::try_from(descriptor) {
408
+ let get = v8::String::new(tc, "get").ok_or_else(inspect)?;
409
+ let getter = descriptor
410
+ .get_own_property_descriptor(tc, get.into())
411
+ .ok_or_else(inspect)?;
412
+ if let Ok(getter) = v8::Local::<v8::Object>::try_from(getter) {
413
+ let getter = v8::String::new(tc, "value")
414
+ .and_then(|value| getter.get(tc, value.into()))
415
+ .ok_or_else(inspect)?;
416
+ ours = getter.is_function() && getter.same_value(self.getter.into());
417
+ }
418
+ }
419
+ if ours
420
+ && !global
421
+ .define_own_property(tc, key, self.original, v8::PropertyAttribute::DONT_ENUM)
422
+ .unwrap_or(false)
423
+ {
424
+ return Err(internal("failed to restore Intl after snapshot script"));
425
+ }
426
+ Ok(())
427
+ }
428
+ }
429
+
209
430
  fn run(tc: &Tc<'_, '_, '_, '_>, code: &JsText, name: &str) -> Result<(), EngineError> {
210
431
  let source = source(tc, code).ok_or_else(|| failure(tc))?;
211
432
  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: