Skip to content

Lightpanda: the headless browser designed for AI and automation

crash: only run microtask when the call_depth == 0

Karl Seguin40fb5305492a
diff --git a/src/browser/js/Context.zig b/src/browser/js/Context.zig
index d77c79631..82260aaa9 100644
--- a/src/browser/js/Context.zig
+++ b/src/browser/js/Context.zig
@@ -638,6 +638,10 @@ pub fn dynamicModuleCallback(
},
};
+ // prevent running a microtask checkpoint mid-script
+ self.call_depth += 1;
+ defer self.call_depth -= 1;
+
const promise = self._dynamicModuleCallback(normalized_specifier, resource, &local) catch |err| blk: {
log.debug(.js, "dynamic module callback", .{
.err = err,
diff --git a/src/browser/js/Env.zig b/src/browser/js/Env.zig
index fab58a46c..97845265b 100644
--- a/src/browser/js/Env.zig
+++ b/src/browser/js/Env.zig
@@ -501,6 +501,13 @@ pub fn destroyContext(self: *Env, context: *Context) void {
}
pub fn runMicrotasks(self: *Env) void {
+ // Checkpoints only happen at en empty JS stack.
+ for (self.contexts.items) |ctx| {
+ if (ctx.call_depth > 0) {
+ return;
+ }
+ }
+
if (self.microtask_queues_are_running == false) {
self.terminate_mutex.lockUncancelable(lp.io);
defer self.terminate_mutex.unlock(lp.io);
@@ -525,12 +532,7 @@ pub fn runMicrotasks(self: *Env) void {
if (self.terminatePending()) {
if (v8.v8__Isolate__IsExecutionTerminating(v8_isolate)) {
- for (self.contexts.items) |c| {
- if (c.call_depth > 0) {
- return;
- }
- }
- // None of the contexts are "entered", it's safe to
+ // No context is entered (checked above), so it's safe to
// clear the termination flag.
v8.v8__Isolate__CancelTerminateExecution(v8_isolate);
}
@@ -849,6 +851,11 @@ fn promiseRejectCallback(message_handle: v8.PromiseRejectMessage) callconv(.c) v
.call_arena = ctx.call_arena,
};
+ // Called synchronously by V8, so we bypass Caller and it's call_depth
+ // increment. Do it manually.
+ ctx.call_depth += 1;
+ defer ctx.call_depth -= 1;
+
const no_handler = promise_event == v8.kPromiseRejectWithNoHandler;
switch (ctx.global) {
.frame => |frame| {
diff --git a/src/browser/js/Function.zig b/src/browser/js/Function.zig
index c478a9bd5..acd2418f0 100644
--- a/src/browser/js/Function.zig
+++ b/src/browser/js/Function.zig
@@ -363,7 +363,7 @@ test "Function: requested termination is classified and blocks re-entry" {
try testing.expectEqual(3, try (try local.exec("1 + 2", null)).toI32());
}
-test "Function: nested microtask checkpoint keeps the caller's termination" {
+test "Function: microtask checkpoint is a no-op while JS is on the stack" {
const frame = try testing.createFrame();
defer testing.test_session.closeAllPages();
@@ -372,49 +372,27 @@ test "Function: nested microtask checkpoint keeps the caller's termination" {
defer ls.deinit();
const local = &ls.local;
- const env = frame.js.env;
- defer env.cancelTerminate();
-
const State = struct {
- env: *js.Env,
local: *const js.Local,
- resumed: bool = false,
-
- fn kill(self: *@This()) void {
- self.env.requestTerminate();
- }
- // Draining the queue from a native call runs at call depth >= 1, with
- // the caller's JS still on the stack. A terminate landing in here is
- // aimed at that caller too, so the checkpoint must not clear it.
+ // A native call runs at call depth >= 1, with the caller's JS still on
+ // the stack: draining the queue here would run reactions mid-script.
fn pump(self: *@This()) void {
self.local.runMicrotasks();
}
-
- fn markResumed(self: *@This()) void {
- self.resumed = true;
- }
};
- var state = State{ .env = env, .local = local };
+ var state = State{ .local = local };
const driver = try local.exec(
- \\(function(kill, pump, resumed) {
- \\ Promise.resolve().then(function(){ kill(); for(;;){} });
+ \\(function(pump) {
+ \\ let ran = false;
+ \\ Promise.resolve().then(function(){ ran = true; });
\\ pump();
- \\ resumed();
+ \\ return ran;
\\})
, null);
const driver_fn = Function{ .local = local, .handle = @ptrCast(driver.handle) };
-
- var caught: js.TryCatch.Caught = .{};
- const args = .{
- local.newCallback(State.kill, &state),
- local.newCallback(State.pump, &state),
- local.newCallback(State.markResumed, &state),
- };
- try testing.expectError(error.ExecutionTerminated, driver_fn.tryCall(void, args, &caught));
- try testing.expectEqual(false, state.resumed);
- try testing.expectEqual(true, env.terminatePending());
+ try testing.expectEqual(false, try driver_fn.call(bool, .{local.newCallback(State.pump, &state)}));
}
test "Function: a terminated checkpoint stops the context loop" {
@@ -422,68 +400,47 @@ test "Function: a terminated checkpoint stops the context loop" {
const other = try testing.createFrame();
defer testing.test_session.closeAllPages();
- var ls: js.Local.Scope = undefined;
- frame.js.localScope(&ls);
- defer ls.deinit();
- const local = &ls.local;
-
const env = frame.js.env;
defer env.cancelTerminate();
- // The second context's queue is the one the loop must not go on to reach:
- // entering a checkpoint on a terminating isolate consumes the termination,
- // which would let the wedged caller below resume.
- {
- var other_ls: js.Local.Scope = undefined;
- other.js.localScope(&other_ls);
- defer other_ls.deinit();
- try other_ls.local.eval(
- \\window.__ran = false;
- \\Promise.resolve().then(function(){ window.__ran = true; });
- , null);
- }
-
const State = struct {
env: *js.Env,
- local: *const js.Local,
- resumed: bool = false,
fn kill(self: *@This()) void {
self.env.requestTerminate();
}
-
- fn pump(self: *@This()) void {
- self.local.runMicrotasks();
- }
-
- fn markResumed(self: *@This()) void {
- self.resumed = true;
- }
};
- var state = State{ .env = env, .local = local };
-
- const driver = try local.exec(
- \\(function(kill, pump, resumed) {
- \\ Promise.resolve().then(function(){ kill(); for(;;){} });
- \\ pump();
- \\ resumed();
- \\})
- , null);
- const driver_fn = Function{ .local = local, .handle = @ptrCast(driver.handle) };
+ var state = State{ .env = env };
- var caught: js.TryCatch.Caught = .{};
- const args = .{
- local.newCallback(State.kill, &state),
- local.newCallback(State.pump, &state),
- local.newCallback(State.markResumed, &state),
- };
- try testing.expectError(error.ExecutionTerminated, driver_fn.tryCall(void, args, &caught));
- try testing.expectEqual(false, state.resumed);
+ {
+ var ls: js.Local.Scope = undefined;
+ frame.js.localScope(&ls);
+ defer ls.deinit();
+ const local = &ls.local;
+
+ const setup = try local.exec(
+ \\(function(kill) {
+ \\ Promise.resolve().then(function(){ kill(); for(;;){} });
+ \\})
+ , null);
+ const setup_fn = Function{ .local = local, .handle = @ptrCast(setup.handle) };
+ try setup_fn.call(void, .{local.newCallback(State.kill, &state)});
+ }
- env.cancelTerminate();
+ // The second context's queue is the one the loop must not go on to reach
+ // once the first context's checkpoint was terminated.
var other_ls: js.Local.Scope = undefined;
other.js.localScope(&other_ls);
defer other_ls.deinit();
+ try other_ls.local.eval(
+ \\window.__ran = false;
+ \\Promise.resolve().then(function(){ window.__ran = true; });
+ , null);
+
+ env.runMicrotasks();
+ try testing.expectEqual(true, env.terminatePending());
+
+ env.cancelTerminate();
try testing.expectEqual(false, (try other_ls.local.exec("window.__ran", null)).toBool());
}
diff --git a/src/browser/tests/page/module.html b/src/browser/tests/page/module.html
index bba90ebe5..35ed677cc 100644
--- a/src/browser/tests/page/module.html
+++ b/src/browser/tests/page/module.html
@@ -87,3 +87,27 @@
<!-- this used to crash -->
<script type=module src=modules/self_async.js></script>
+
+<!-- these used to crash: a microtask checkpoint while a sibling module evaluated
+let a top-level-await module finish before its still-evaluating parent -->
+<script id=tla-checkpoint-resolve type=module>
+ import "./modules/tla.js?resolve";
+ import "./modules/checkpoint-resolve.js";
+ testing.expectEqual(true, customElements.get('x-tla-checkpoint') !== undefined);
+</script>
+
+<script id=tla-checkpoint-dispatch type=module>
+ import "./modules/tla.js?dispatch";
+ import "./modules/checkpoint-dispatch.js";
+ testing.expectEqual(true, true);
+</script>
+
+<script type=module>
+ import "./modules/tla.js?import";
+ import "./modules/checkpoint-import.js";
+</script>
+
+<script type=module>
+ import "./modules/tla.js?reject";
+ import "./modules/checkpoint-reject.js";
+</script>
diff --git a/src/browser/tests/page/modules/checkpoint-dispatch.js b/src/browser/tests/page/modules/checkpoint-dispatch.js
new file mode 100644
index 000000000..5f3ea11a2
--- /dev/null
+++ b/src/browser/tests/page/modules/checkpoint-dispatch.js
@@ -0,0 +1,3 @@
+const div = document.createElement('div');
+div.addEventListener('click', () => {});
+div.click();
diff --git a/src/browser/tests/page/modules/checkpoint-import.js b/src/browser/tests/page/modules/checkpoint-import.js
new file mode 100644
index 000000000..9ee911635
--- /dev/null
+++ b/src/browser/tests/page/modules/checkpoint-import.js
@@ -0,0 +1,2 @@
+// cache hit: the import is resolved synchronously
+import('./tla.js?import');
diff --git a/src/browser/tests/page/modules/checkpoint-reject.js b/src/browser/tests/page/modules/checkpoint-reject.js
new file mode 100644
index 000000000..91e3d38d7
--- /dev/null
+++ b/src/browser/tests/page/modules/checkpoint-reject.js
@@ -0,0 +1,3 @@
+// the rejection callback dispatches unhandledrejection synchronously
+window.addEventListener('unhandledrejection', (e) => { e.preventDefault(); });
+Promise.reject(new Error('tla-checkpoint-reject'));
diff --git a/src/browser/tests/page/modules/checkpoint-resolve.js b/src/browser/tests/page/modules/checkpoint-resolve.js
new file mode 100644
index 000000000..689dd02d7
--- /dev/null
+++ b/src/browser/tests/page/modules/checkpoint-resolve.js
@@ -0,0 +1,3 @@
+// resolves a promise synchronously
+customElements.whenDefined('x-tla-checkpoint');
+customElements.define('x-tla-checkpoint', class extends HTMLElement {});
diff --git a/src/browser/tests/page/modules/tla.js b/src/browser/tests/page/modules/tla.js
new file mode 100644
index 000000000..0a5e432fc
--- /dev/null
+++ b/src/browser/tests/page/modules/tla.js
@@ -0,0 +1 @@
+await 0;