mini_racer_rs 1.3.0 → 1.4.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.
@@ -9,13 +9,13 @@ use std::time::{Duration, Instant};
9
9
 
10
10
  use mini_racer_sourcemap::{Frame, Match, Placement, SourceMap};
11
11
  use mini_racer_sync::{
12
- DispatchId, DispatchKind, Halt, Interrupt, Phase, Side, TerminationCause, ToV8, lock,
12
+ DispatchId, DispatchKind, Halt, Interrupt, Phase, Side, TermCell, TerminationCause, ToV8, lock,
13
13
  };
14
14
  use mini_racer_wire::Writer;
15
15
  use v8::ValueDeserializerHelper;
16
16
 
17
17
  use crate::control::{
18
- CallRequest, CallbackReply, ControlBlock, Depth, IsolateTerminator, JsText, Request,
18
+ CallRequest, CallbackReply, ControlBlock, Depth, HeapWatch, IsolateTerminator, JsText, Request,
19
19
  };
20
20
  use crate::fast_calls::{self, Hoisted, Shape};
21
21
  use crate::process::code_cache::{Building, Key, Plan};
@@ -274,7 +274,12 @@ pub fn run(block: &Arc<ControlBlock>, generation: &'static Generation, start: St
274
274
  Start::Adopted => {
275
275
  let isolate = lock(&block.custody).take();
276
276
  isolate.map_or_else(
277
- || refuse(block, "no isolate to take over"),
277
+ || {
278
+ refuse(
279
+ block,
280
+ EngineError::Internal("no isolate to take over".to_owned()),
281
+ )
282
+ },
278
283
  |isolate| adopt(block, generation, isolate),
279
284
  )
280
285
  }
@@ -311,6 +316,116 @@ pub fn check_heap(isolate: &mut v8::Isolate) {
311
316
  }
312
317
  }
313
318
 
319
+ const EXHAUSTED: Option<Halt> = Some(Halt::Terminated(TerminationCause::HeapExhausted));
320
+
321
+ // A hit lends V8 room up to three times the old generation's limit, all at
322
+ // once: V8 asks at most a few times per allocation, around its last-resort
323
+ // collection, then retries the allocation once and aborts, so room lent a
324
+ // share at a time ran out under one allocation, such as the backing store a
325
+ // growing `Map` doubles into. Past that V8 aborts the process as it would
326
+ // without a limit.
327
+ const CEILING: usize = 3;
328
+
329
+ // V8 is about to abort the process at the heap limit: the running script is
330
+ // ended as out of memory, and V8 is lent room to unwind it. With no dispatch
331
+ // armed, which the termination cell checks, or the runner collecting on its
332
+ // own, no script is running, and `recover` settles the heap once the runner
333
+ // is done.
334
+ pub fn near_heap_limit(block: &ControlBlock, current: usize, initial: usize) -> usize {
335
+ let watch = &block.heap;
336
+ watch.old_generation.store(initial, Ordering::Relaxed);
337
+ watch.hit.store(true, Ordering::Relaxed);
338
+ if !watch.collecting.load(Ordering::Relaxed) {
339
+ block.term.request(Interrupt::HeapExhausted);
340
+ }
341
+ initial.saturating_mul(CEILING).max(current)
342
+ }
343
+
344
+ // After a hit, a full collection, then the old generation's limit back to the
345
+ // one the heap limit set if the live heap fits under it. V8 puts a limit back
346
+ // no lower than the live size and a quarter, so a heap that does not fit, or
347
+ // a limit V8 did not put back, poisons the context instead of leaving it
348
+ // above the heap limit. A script terminated with the heap that full gets the
349
+ // collection too: V8 otherwise calls the callback in the next script, which
350
+ // would end it though its own heap is small.
351
+ fn recover(isolate: &mut v8::Isolate, block: &ControlBlock) {
352
+ if block.config.heap_limit.is_none() {
353
+ return;
354
+ }
355
+ let watch = &block.heap;
356
+ let ended = watch.ended.swap(false, Ordering::Relaxed);
357
+ if block.term.is_disposing() || watch.poisoned.load(Ordering::Relaxed) {
358
+ watch.hit.store(false, Ordering::Relaxed);
359
+ return;
360
+ }
361
+ let crowded = ended && !fits(isolate, watch);
362
+ if !crowded && !watch.hit.load(Ordering::Relaxed) {
363
+ return;
364
+ }
365
+ collect(isolate, block);
366
+ if !watch.hit.swap(false, Ordering::Relaxed) {
367
+ return;
368
+ }
369
+ let fits = fits(isolate, watch);
370
+ if fits {
371
+ let limit = watch.old_generation.load(Ordering::Relaxed);
372
+ sys::unwatch_heap_limit(isolate, limit);
373
+ sys::watch_heap_limit(isolate, block);
374
+ }
375
+ let reserved = isolate.get_heap_statistics().heap_size_limit();
376
+ if !fits || reserved > watch.reserved.load(Ordering::Relaxed) {
377
+ watch.poisoned.store(true, Ordering::Relaxed);
378
+ }
379
+ }
380
+
381
+ // The generations of a heap of `limit` bytes, with the old one's size.
382
+ // `heap_limits` splits the limit, but V8 15.2's `Heap::ConfigureHeap` rounds
383
+ // a third of the young generation, a semi-space, up to a power of two, which
384
+ // can reserve a tenth more than the limit; rounded down here instead, the
385
+ // heap V8 reserves is the limit, less its rounding of the old generation
386
+ // down to a page. `heap_limits` also sets a code range of the limit's size,
387
+ // which V8 aborts on unless it is a multiple of the allocation page, so the
388
+ // code range is left at V8's own size, as for a context without a limit.
389
+ fn sized(params: v8::CreateParams, limit: usize) -> (v8::CreateParams, usize) {
390
+ let params = params.heap_limits(0, limit);
391
+ let semi_space = (params.max_young_generation_size_in_bytes() / 3)
392
+ .checked_ilog2()
393
+ .map_or(0, |log| 1_usize << log);
394
+ let young_generation = semi_space.saturating_mul(3);
395
+ let old_generation = limit.saturating_sub(young_generation);
396
+ let params = params
397
+ .set_max_young_generation_size_in_bytes(young_generation)
398
+ .set_max_old_generation_size_in_bytes(old_generation)
399
+ .set_code_range_size_in_bytes(0);
400
+ (params, old_generation)
401
+ }
402
+
403
+ // Whether V8 would put the old generation's limit back where it started: no
404
+ // lower than the live heap and a quarter.
405
+ fn fits(isolate: &mut v8::Isolate, watch: &HeapWatch) -> bool {
406
+ let used = isolate.get_heap_statistics().used_heap_size();
407
+ used.saturating_add(used / 4) <= watch.old_generation.load(Ordering::Relaxed)
408
+ }
409
+
410
+ // A full collection the runner asks for itself, with no script to end if the
411
+ // heap is at its limit.
412
+ fn collect(isolate: &mut v8::Isolate, block: &ControlBlock) {
413
+ block.heap.collecting.store(true, Ordering::Relaxed);
414
+ isolate.low_memory_notification();
415
+ block.heap.collecting.store(false, Ordering::Relaxed);
416
+ }
417
+
418
+ // A context whose heap stayed over its limit runs no more JavaScript.
419
+ fn unpoisoned(runtime: &Runtime) -> Result<(), EngineError> {
420
+ let block = &runtime.block;
421
+ match block.config.heap_limit {
422
+ Some(limit) if block.heap.poisoned.load(Ordering::Relaxed) => {
423
+ Err(EngineError::from(JsError::heap_limit_exceeded(limit)))
424
+ }
425
+ _ => Ok(()),
426
+ }
427
+ }
428
+
314
429
  pub fn park_for_fork(isolate: &v8::Isolate) {
315
430
  if let Some(runtime) = isolate.get_slot::<Arc<Runtime>>() {
316
431
  let _paused = runtime.timing(false);
@@ -318,13 +433,11 @@ pub fn park_for_fork(isolate: &v8::Isolate) {
318
433
  }
319
434
  }
320
435
 
321
- fn refuse(block: &ControlBlock, message: &str) -> bool {
436
+ fn refuse(block: &ControlBlock, error: EngineError) -> bool {
322
437
  // Holding no isolate, it never keeps a fork waiting.
323
438
  block.phase.set(Phase::Deposited);
324
439
  if receive(block).is_some() {
325
- let _ = block
326
- .channel
327
- .respond(Err(EngineError::Internal(message.to_owned())));
440
+ let _ = block.channel.respond(Err(error));
328
441
  }
329
442
  false
330
443
  }
@@ -341,21 +454,49 @@ fn serve(block: &Arc<ControlBlock>, generation: &'static Generation) -> bool {
341
454
  Some(blob) => params.snapshot_blob(sys::startup_data(blob)),
342
455
  None => params,
343
456
  };
457
+ let params = match block.config.heap_limit {
458
+ Some(limit) => {
459
+ let (params, old_generation) = sized(params, limit);
460
+ block
461
+ .heap
462
+ .old_generation
463
+ .store(old_generation, Ordering::Relaxed);
464
+ params
465
+ }
466
+ None => params,
467
+ };
344
468
  let mut isolate = v8::Isolate::new(params);
345
469
  isolate.set_slot(Collections::new(block));
346
470
  sys::count_collections(&mut isolate);
347
471
  if block.config.max_memory.is_some() {
348
472
  sys::watch_heap(&mut isolate);
349
473
  }
474
+ let reserved = block
475
+ .config
476
+ .heap_limit
477
+ .map(|_| isolate.get_heap_statistics().heap_size_limit());
478
+ if let Some(reserved) = reserved {
479
+ block.heap.reserved.store(reserved, Ordering::Relaxed);
480
+ sys::watch_heap_limit(&mut isolate, block);
481
+ }
350
482
  let key = sys::isolate_key(&isolate);
351
483
  generation.tasks().register(key, &block.tasks);
484
+ // V8 reads its own flags, so this catches any that sized the heap past
485
+ // the limit, whatever `platform::read_sizing` made of them.
486
+ if reserved > block.config.heap_limit {
487
+ retire(block, generation, key, isolate);
488
+ return refuse(block, EngineError::HeapLimitOverridden);
489
+ }
352
490
  let contexts = {
353
491
  v8::scope!(let scope, &mut isolate);
354
492
  serialize::contexts(scope, from_snapshot)
355
493
  };
356
494
  let Some(contexts) = contexts else {
357
495
  retire(block, generation, key, isolate);
358
- return refuse(block, "context setup failed");
496
+ return refuse(
497
+ block,
498
+ EngineError::Internal("context setup failed".to_owned()),
499
+ );
359
500
  };
360
501
  let runtime = Arc::new(Runtime::new(
361
502
  block,
@@ -372,7 +513,10 @@ fn serve(block: &Arc<ControlBlock>, generation: &'static Generation) -> bool {
372
513
  Ok(shared) => shared,
373
514
  Err(refused) => {
374
515
  retire(block, generation, key, refused);
375
- return refuse(block, "isolate could not be shared");
516
+ return refuse(
517
+ block,
518
+ EngineError::Internal("isolate could not be shared".to_owned()),
519
+ );
376
520
  }
377
521
  };
378
522
  let _ = block.isolate.set(shared.thread_safe_handle());
@@ -392,7 +536,10 @@ fn adopt(
392
536
  // Disposed here, before the runner counts as idle to a fork.
393
537
  drop(block.tasks.close());
394
538
  drop(shared);
395
- return refuse(block, "inherited isolate has no context");
539
+ return refuse(
540
+ block,
541
+ EngineError::Internal("inherited isolate has no context".to_owned()),
542
+ );
396
543
  };
397
544
  let runtime = {
398
545
  let mut locker = shared.lock();
@@ -408,6 +555,13 @@ fn adopt(
408
555
  if let Ok(matched) = inherited.matched.try_lock() {
409
556
  lock(&runtime.matched).clone_from(&matched);
410
557
  }
558
+ // V8's callback still names the parent's block, whose termination
559
+ // cell no runner here serves.
560
+ if block.config.heap_limit.is_some() {
561
+ block.heap.inherit(&inherited.block.heap);
562
+ sys::unwatch_heap_limit(&mut locker, 0);
563
+ sys::watch_heap_limit(&mut locker, block);
564
+ }
411
565
  locker.set_slot(Arc::clone(&runtime));
412
566
  // The parent's callbacks stay registered and now count here.
413
567
  locker.set_slot(Collections::new(block));
@@ -475,7 +629,8 @@ fn serve_held(block: &ControlBlock, shared: &v8::SharedIsolate, runtime: &Arc<Ru
475
629
  // A collection for a context about to be torn down is wasted.
476
630
  Received::Idle => {
477
631
  if !block.term.is_disposing() {
478
- isolate.low_memory_notification();
632
+ collect(&mut isolate, block);
633
+ recover(&mut isolate, block);
479
634
  sys::release_free_memory();
480
635
  }
481
636
  collected = true;
@@ -547,7 +702,7 @@ fn serve_one(
547
702
  block
548
703
  .term
549
704
  .end(dispatch)
550
- .map_or(built, |halt| Err(halted(halt)))
705
+ .map_or(built, |halt| Err(halted(block, halt)))
551
706
  }
552
707
  Depth::Nested => Err(EngineError::Internal(
553
708
  "snapshot inside a callback".to_owned(),
@@ -570,6 +725,7 @@ fn serve_one(
570
725
  };
571
726
  // Before the response, so a fork that follows finds this runner idle.
572
727
  cache_uncached(isolate, runtime);
728
+ recover(isolate, block);
573
729
  let served = respond(block, response);
574
730
  // After the response, so the caller does not wait for it.
575
731
  if matches!(served, Served::Next) && runtime.freed.swap(false, Ordering::Relaxed) {
@@ -671,25 +827,35 @@ fn handle(
671
827
  source,
672
828
  depth,
673
829
  awaited,
674
- } => script(scope, runtime, depth, DispatchKind::Script, |tc| {
675
- evaluate(tc, runtime, (&filename, &source), (depth, awaited))
676
- }),
830
+ timeout,
831
+ } => {
832
+ let timed = Timed::Script(runtime.block.config.timeout_within(timeout));
833
+ script(scope, runtime, depth, timed, |tc| {
834
+ unpoisoned(runtime)?;
835
+ evaluate(tc, runtime, (&filename, &source), (depth, awaited))
836
+ })
837
+ }
677
838
  Request::Call {
678
839
  request,
679
840
  depth,
680
841
  awaited,
681
- } => script(scope, runtime, depth, DispatchKind::Script, |tc| {
682
- invoke(tc, runtime, &request, (depth, awaited))
683
- }),
842
+ timeout,
843
+ } => {
844
+ let timed = Timed::Script(runtime.block.config.timeout_within(timeout));
845
+ script(scope, runtime, depth, timed, |tc| {
846
+ unpoisoned(runtime)?;
847
+ invoke(tc, runtime, &request, (depth, awaited))
848
+ })
849
+ }
684
850
  Request::Attach { request, depth } => {
685
- script(scope, runtime, depth, DispatchKind::Maintenance, |tc| {
851
+ script(scope, runtime, depth, Timed::Maintenance, |tc| {
686
852
  attach(tc, &request)
687
853
  })
688
854
  }
689
855
  // A collection for a context about to be torn down is wasted.
690
856
  Request::LowMemoryNotification { depth } => {
691
857
  if !runtime.block.term.is_disposing() {
692
- scope.low_memory_notification();
858
+ collect(scope, &runtime.block);
693
859
  runtime.freed.store(true, Ordering::Relaxed);
694
860
  }
695
861
  match depth {
@@ -700,26 +866,38 @@ fn handle(
700
866
  // mini_racer leaves a termination this meets for the dispatch around
701
867
  // it, or for the next script.
702
868
  Request::MicrotaskCheckpoint { depth } => {
703
- script(scope, runtime, depth, DispatchKind::Maintenance, |tc| {
869
+ script(scope, runtime, depth, Timed::Maintenance, |tc| {
870
+ unpoisoned(runtime)?;
704
871
  tc.perform_microtask_checkpoint();
872
+ // Maintenance reports no cause, and an exhausted heap leaves
873
+ // none for the next script, so the checkpoint raises it.
874
+ if tc.has_terminated()
875
+ && runtime.block.term.check(DispatchKind::Script) == EXHAUSTED
876
+ {
877
+ return Err(halted(
878
+ &runtime.block,
879
+ Halt::Terminated(TerminationCause::HeapExhausted),
880
+ ));
881
+ }
705
882
  Ok(Vec::new())
706
883
  })
707
884
  }
708
- Request::HeapStats { depth } => {
709
- script(scope, runtime, depth, DispatchKind::Maintenance, |tc| {
710
- Ok(heap_stats(tc))
711
- })
712
- }
885
+ Request::HeapStats { depth } => script(scope, runtime, depth, Timed::Maintenance, |tc| {
886
+ Ok(heap_stats(tc))
887
+ }),
713
888
  Request::HeapSnapshot { depth } => {
714
- script(scope, runtime, depth, DispatchKind::Maintenance, |tc| {
715
- Ok(heap_snapshot(tc))
716
- })
717
- }
718
- Request::PumpMessageLoop { depth } => {
719
- script(scope, runtime, depth, DispatchKind::Pump, |tc| {
720
- Ok(vec![u8::from(pump(tc, runtime))])
889
+ script(scope, runtime, depth, Timed::Maintenance, |tc| {
890
+ let heap = &runtime.block.heap;
891
+ heap.collecting.store(true, Ordering::Relaxed);
892
+ let json = heap_snapshot(tc);
893
+ heap.collecting.store(false, Ordering::Relaxed);
894
+ Ok(json)
721
895
  })
722
896
  }
897
+ Request::PumpMessageLoop { depth } => script(scope, runtime, depth, Timed::Pump, |tc| {
898
+ unpoisoned(runtime)?;
899
+ Ok(vec![u8::from(pump(tc, runtime))])
900
+ }),
723
901
  // The extension refuses a dispose from inside a callback before it
724
902
  // gets here.
725
903
  Request::Dispose => Err(EngineError::DisposeBusy),
@@ -738,9 +916,12 @@ fn ended(runtime: &Runtime, dispatch: DispatchId) -> Result<Vec<u8>, EngineError
738
916
  }
739
917
  }
740
918
 
741
- fn halted(halt: Halt) -> EngineError {
919
+ fn halted(block: &ControlBlock, halt: Halt) -> EngineError {
742
920
  match halt {
743
- Halt::Terminated(cause) => EngineError::from(JsError::terminated(cause)),
921
+ Halt::Terminated(cause) => EngineError::from(match (cause, block.config.heap_limit) {
922
+ (TerminationCause::HeapExhausted, Some(limit)) => JsError::heap_limit_reached(limit),
923
+ _ => JsError::terminated(cause),
924
+ }),
744
925
  // mini_racer cancels the wait of a dispatch a dispose catches in
745
926
  // flight, which raises its disposed error.
746
927
  Halt::Disposed => EngineError::Disposed,
@@ -758,19 +939,23 @@ fn script(
758
939
  scope: &mut v8::PinScope<'_, '_>,
759
940
  runtime: &Runtime,
760
941
  depth: Depth,
761
- kind: DispatchKind,
942
+ timed: Timed,
762
943
  run: impl FnOnce(&mut Tc<'_, '_, '_, '_>) -> Result<Vec<u8>, EngineError>,
763
944
  ) -> Result<Vec<u8>, EngineError> {
764
945
  let term = &runtime.block.term;
946
+ let kind = timed.kind();
765
947
  v8::tc_scope!(let tc, scope);
766
948
  tc.set_verbose(runtime.block.config.verbose_exceptions);
767
- let result = if let Err(error) = arm_timeout(runtime, depth, kind) {
949
+ let result = if let Err(error) = arm_timeout(runtime, depth, timed) {
768
950
  Err(error)
769
951
  } else if term.refuses(kind) {
770
952
  Err(EngineError::Internal("halted without a cause".to_owned()))
771
953
  } else {
772
954
  run(tc)
773
955
  };
956
+ if tc.has_terminated() && runtime.block.config.heap_limit.is_some() {
957
+ runtime.block.heap.ended.store(true, Ordering::Relaxed);
958
+ }
774
959
  let since = term.mark();
775
960
  // mini_racer's maintenance never cancels a termination it meets, so the
776
961
  // interrupt is used up while the cause waits for the next script. Inside
@@ -797,13 +982,22 @@ fn script(
797
982
  // the timeout bounds them again here.
798
983
  Depth::Outermost(dispatch) if kind == DispatchKind::Script && tc.has_terminated() => {
799
984
  let verdict = term.settle(dispatch);
800
- let drains = verdict.is_some_and(|halt| halt != Halt::Disposed)
801
- && rearm_timeout(runtime, dispatch).is_ok();
985
+ let exhausted = verdict == EXHAUSTED;
986
+ if exhausted {
987
+ discard_microtasks(tc, term);
988
+ }
989
+ let drains = !exhausted
990
+ && verdict.is_some_and(|halt| halt != Halt::Disposed)
991
+ && rearm_timeout(runtime, dispatch, timed).is_ok();
802
992
  if drains {
803
993
  tc.reset();
804
994
  tc.perform_microtask_checkpoint();
805
995
  }
806
- if drains && (tc.has_terminated() || tc.is_execution_terminating()) {
996
+ // The microtasks it left reached the heap limit, which outranks
997
+ // every other cause: this script reports it, and nothing carries.
998
+ if drains && term.check(DispatchKind::Script) == EXHAUSTED {
999
+ term.end(dispatch)
1000
+ } else if drains && (tc.has_terminated() || tc.is_execution_terminating()) {
807
1001
  term.spend(term.mark(), false);
808
1002
  match term.finish(dispatch) {
809
1003
  Some(Halt::Disposed) => Some(Halt::Disposed),
@@ -838,26 +1032,56 @@ fn script(
838
1032
  message: String::new(),
839
1033
  }));
840
1034
  }
841
- halt.map_or(result, |halt| Err(halted(halt)))
1035
+ halt.map_or(result, |halt| Err(halted(&runtime.block, halt)))
1036
+ }
1037
+
1038
+ // The microtasks a script left as it reached the heap limit would allocate
1039
+ // again. V8 empties the queue when a termination reaches it there, so they
1040
+ // are dropped rather than run, now or with the next script.
1041
+ fn discard_microtasks(tc: &mut Tc<'_, '_, '_, '_>, term: &TermCell<IsolateTerminator>) {
1042
+ tc.reset();
1043
+ term.interrupt();
1044
+ tc.perform_microtask_checkpoint();
1045
+ term.release();
1046
+ tc.reset();
1047
+ }
1048
+
1049
+ // A dispatch's kind, and for a script the timeout it runs under.
1050
+ #[derive(Clone, Copy)]
1051
+ enum Timed {
1052
+ Script(Option<Duration>),
1053
+ Maintenance,
1054
+ Pump,
1055
+ }
1056
+
1057
+ impl Timed {
1058
+ const fn kind(self) -> DispatchKind {
1059
+ match self {
1060
+ Self::Script(_) => DispatchKind::Script,
1061
+ Self::Maintenance => DispatchKind::Maintenance,
1062
+ Self::Pump => DispatchKind::Pump,
1063
+ }
1064
+ }
842
1065
  }
843
1066
 
844
1067
  // mini_racer starts a script's watchdog on its V8 thread as it takes the
845
1068
  // request, so time spent waiting for the runner, such as behind a collection
846
1069
  // after `ensure_gc_after_idle`, never counts against the timeout. Setup and
847
1070
  // maintenance are never timed.
848
- fn arm_timeout(runtime: &Runtime, depth: Depth, kind: DispatchKind) -> Result<(), EngineError> {
849
- match (depth, kind, runtime.block.config.timeout) {
850
- (Depth::Outermost(dispatch), DispatchKind::Script, Some(timeout)) => {
1071
+ fn arm_timeout(runtime: &Runtime, depth: Depth, timed: Timed) -> Result<(), EngineError> {
1072
+ match (depth, timed) {
1073
+ (Depth::Outermost(dispatch), Timed::Script(Some(timeout))) => {
851
1074
  watchdog::schedule(timeout, &runtime.block, dispatch)
852
1075
  }
853
1076
  _ => Ok(()),
854
1077
  }
855
1078
  }
856
1079
 
857
- fn rearm_timeout(runtime: &Runtime, dispatch: DispatchId) -> Result<(), EngineError> {
858
- runtime.block.config.timeout.map_or(Ok(()), |timeout| {
859
- watchdog::rearm_if_fired(timeout, &runtime.block, dispatch)
860
- })
1080
+ fn rearm_timeout(runtime: &Runtime, dispatch: DispatchId, timed: Timed) -> Result<(), EngineError> {
1081
+ match timed {
1082
+ Timed::Script(Some(timeout)) => watchdog::rearm_if_fired(timeout, &runtime.block, dispatch),
1083
+ _ => Ok(()),
1084
+ }
861
1085
  }
862
1086
 
863
1087
  fn escaped(tc: &Tc<'_, '_, '_, '_>, runtime: &Runtime) -> bool {
@@ -1312,7 +1536,7 @@ fn verdict(runtime: &Runtime, depth: Depth) -> Result<(), EngineError> {
1312
1536
  Depth::Outermost(dispatch) => term.settle(dispatch),
1313
1537
  Depth::Nested => term.check(DispatchKind::Script),
1314
1538
  };
1315
- halt.map_or(Ok(()), |halt| Err(halted(halt)))
1539
+ halt.map_or(Ok(()), |halt| Err(halted(&runtime.block, halt)))
1316
1540
  }
1317
1541
 
1318
1542
  // V8 runs no microtask checkpoint inside another, so an await nested in a
@@ -1335,7 +1559,7 @@ fn refuse_nested_await(
1335
1559
  if matches!(halt, Some(Halt::Terminated(_))) {
1336
1560
  runtime.block.term.renew();
1337
1561
  }
1338
- let halt = halt.map(halted);
1562
+ let halt = halt.map(|halt| halted(&runtime.block, halt));
1339
1563
  Err(match (halt, refused) {
1340
1564
  (Some(EngineError::Js(halt)), EngineError::Js(refused)) => EngineError::from(JsError {
1341
1565
  kind: halt.kind,
@@ -208,6 +208,32 @@ unsafe extern "C" fn after_gc(
208
208
  }
209
209
  }
210
210
 
211
+ /// Has V8 ask `block` before it aborts the process at the isolate's heap
212
+ /// limit. `block` must stay where it is for as long as the isolate can run:
213
+ /// a runner holds its context's block until it has dropped the isolate, and a
214
+ /// forked child that takes the isolate over registers its own block instead.
215
+ pub fn watch_heap_limit(isolate: &mut v8::Isolate, block: &crate::control::ControlBlock) {
216
+ let data = std::ptr::from_ref(block).cast_mut().cast::<c_void>();
217
+ isolate.add_near_heap_limit_callback(near_heap_limit, data);
218
+ }
219
+
220
+ /// Undoes `watch_heap_limit`, which must have been called, and with a
221
+ /// `limit` other than 0 puts the old generation's limit back to it, though
222
+ /// V8 keeps it no lower than the heap's live size and a quarter.
223
+ pub fn unwatch_heap_limit(isolate: &mut v8::Isolate, limit: usize) {
224
+ isolate.remove_near_heap_limit_callback(near_heap_limit, limit);
225
+ }
226
+
227
+ unsafe extern "C" fn near_heap_limit(data: *mut c_void, current: usize, initial: usize) -> usize {
228
+ let raised = std::panic::catch_unwind(|| {
229
+ // SAFETY: `data` is the control block `watch_heap_limit` registered,
230
+ // which outlives the registration as its doc comment requires.
231
+ let block = unsafe { &*data.cast::<crate::control::ControlBlock>() };
232
+ crate::runner::near_heap_limit(block, current, initial)
233
+ });
234
+ raised.unwrap_or_else(|_| std::process::abort())
235
+ }
236
+
211
237
  /// Has V8 report the start and end of each collection on `isolate` for its
212
238
  /// runner's counters: scavenges, minor mark-sweeps and mark-compacts, not the
213
239
  /// start of incremental marking or the processing of weak callbacks, which
@@ -1304,8 +1304,9 @@ pub mod tests {
1304
1304
  }
1305
1305
 
1306
1306
  // Each worst case is linear, so it takes a fraction of a second even
1307
- // unoptimized; quadratic work at these sizes would take hours.
1308
- const BOUND: Duration = Duration::from_secs(5);
1307
+ // unoptimized, and a few seconds on a loaded CI runner; quadratic work at
1308
+ // these sizes would take hours.
1309
+ const BOUND: Duration = Duration::from_secs(30);
1309
1310
 
1310
1311
  fn timed<T>(label: &str, work: impl FnOnce() -> T) -> T {
1311
1312
  let started = Instant::now();