11cb0ef41Sopenharmony_ci'use strict';
21cb0ef41Sopenharmony_cirequire('../common');
31cb0ef41Sopenharmony_ciconst vm = require('vm');
41cb0ef41Sopenharmony_ci
51cb0ef41Sopenharmony_ci// We're testing a race condition so we just have to spin this in a loop
61cb0ef41Sopenharmony_ci// for a little while and see if it breaks. The condition being tested
71cb0ef41Sopenharmony_ci// is an `isolate->TerminateExecution()` reaching the main JS stack from
81cb0ef41Sopenharmony_ci// the timeout watchdog.
91cb0ef41Sopenharmony_ciconst sandbox = { timeout: 5 };
101cb0ef41Sopenharmony_ciconst context = vm.createContext(sandbox);
111cb0ef41Sopenharmony_ciconst script = new vm.Script(
121cb0ef41Sopenharmony_ci  'var d = Date.now() + timeout;while (d > Date.now());',
131cb0ef41Sopenharmony_ci);
141cb0ef41Sopenharmony_ciconst immediate = setImmediate(function() {
151cb0ef41Sopenharmony_ci  throw new Error('Detected vm race condition!');
161cb0ef41Sopenharmony_ci});
171cb0ef41Sopenharmony_ci
181cb0ef41Sopenharmony_ci// When this condition was first discovered this test would fail in 50ms
191cb0ef41Sopenharmony_ci// or so. A better, but still incorrect implementation would fail after
201cb0ef41Sopenharmony_ci// 100 seconds or so. If you're messing with vm timeouts you might
211cb0ef41Sopenharmony_ci// consider increasing this timeout to hammer out races.
221cb0ef41Sopenharmony_ciconst giveUp = Date.now() + 5000;
231cb0ef41Sopenharmony_cido {
241cb0ef41Sopenharmony_ci  // The loop adjusts the timeout up or down trying to hit the race
251cb0ef41Sopenharmony_ci  try {
261cb0ef41Sopenharmony_ci    script.runInContext(context, { timeout: 5 });
271cb0ef41Sopenharmony_ci    ++sandbox.timeout;
281cb0ef41Sopenharmony_ci  } catch {
291cb0ef41Sopenharmony_ci    --sandbox.timeout;
301cb0ef41Sopenharmony_ci  }
311cb0ef41Sopenharmony_ci} while (Date.now() < giveUp);
321cb0ef41Sopenharmony_ci
331cb0ef41Sopenharmony_ciclearImmediate(immediate);
34