Skip to content

fix(inspector): don't crash when an inspector message pauses - #612

Open
edusperoni wants to merge 1 commit into
mainfrom
fix/inspector-pause-in-dispatch
Open

edusperoni wants to merge 1 commit into
mainfrom
fix/inspector-pause-in-dispatch

Conversation

@edusperoni

@edusperoni edusperoni commented Nov 27, 2026 •

Copy link
Copy Markdown
Collaborator

Typing debugger in the DevTools Console (Runtime.evaluate with an expression that pauses) killed the app. The frontend saw Debugger.paused, then nothing: Debugger.resume got no reply and Debugger.resumed never came. It looked like a hang, but the app was gone. The crash is EXC_BREAKPOINT (SIGTRAP) in libdispatch, "dispatch_sync called on queue already owned by current thread":

libdispatch      __DISPATCH_WAIT_FOR_QUEUE__
libdispatch      _dispatch_sync_f_slow
NativeScript     JsV8InspectorClient::runMessageLoopOnPause(int)          JsV8InspectorClient.mm:728
NativeScript     V8Debugger::handleProgramBreak(...)
                 ... Runtime_HandleDebuggerStatement / DebugEvaluate::Global ...
NativeScript     V8RuntimeAgentImpl::evaluate(...)
NativeScript     V8InspectorSessionImpl::dispatchProtocolMessage(...)
NativeScript     JsV8InspectorClient::dispatchMessage(...)                 JsV8InspectorClient.mm:960
NativeScript     block in ScheduleMessageDrain()                           JsV8InspectorClient.mm:573
libdispatch      _dispatch_lane_barrier_sync_invoke_and_complete
NativeScript     ScheduleMessageDrain() lambda                             JsV8InspectorClient.mm:555

The same code is in 9.0.3, where the drain lived in onFrontendMessageReceived.

Root cause

ScheduleMessageDrain ran the whole drain loop inside dispatch_sync(messageLoopQueue_), including dispatchMessage. When the dispatched message pauses, V8 calls runMessageLoopOnPause on the same thread, and its own dispatch_sync(messageLoopQueue_) re-enters the serial queue the drain already holds. libdispatch traps on that. quitMessageLoopOnPause syncs on the same queue, so it would have hit the same trap.

Pauses from app code (a timer, a breakpoint in a callback) never ran into this, because no drain is on the stack when they happen. The nested pause loop could already drain the queue on its own, and the message threading was never the problem. Only the lock scope was wrong, so no work moves to another thread.

Fix

The drain takes messageLoopQueue_ only to read runningNestedLoops_/terminated_, and calls dispatchMessage outside it. A message that pauses now runs the pause loop inside the drain's stack, the same way a worker's DrainIncoming already does.

The flag and pendingSessionReset_ checks now run before every pop instead of once per drain. After a pause inside a dispatch unwinds, the drain loop carries on. If the pause ended through DeferSessionResetFromPauseLoop (a frontend disconnecting, or a new one taking over, while paused), the swap has to happen before the loop pops the next frontend's messages. Otherwise those messages reach the old session, whose replies go to the departed connection.

Testing

All on an iPhone 16 Pro simulator (iOS 26.3), with a simulator-only runtime build from this branch (BUILD_CATALYST=false BUILD_IPHONE=false BUILD_VISION=false ./build_all_ios.sh). That build is installed as a file: tgz into a TypeScript template app. For every scenario, dwarfdump --uuid of the app's embedded NativeScript.framework matched the dist/ simulator slice. Each run also checked that the app pid was still alive and that no new crash report had appeared. The CDP client is a small Node script (not committed) speaking the inspector socket's length-prefixed UTF-16LE framing.

Repro (Runtime.enable, Debugger.enable, then Runtime.evaluate {expression: "debugger; 1"} as id 3, then Debugger.resume as id 4).

Before (unmodified build of main), the app crashes:

{"id":1,"result":{}}
{"id":2,"result":{"debuggerId":"..."}}
{"method":"Debugger.paused",...}
app alive: NO, new crash report: __DISPATCH_WAIT_FOR_QUEUE__ <- runMessageLoopOnPause

After:

{"id":1,"result":{}}
{"id":2,"result":{"debuggerId":"..."}}
{"method":"Debugger.paused",...}
{"id":4,"result":{}}
{"method":"Debugger.resumed","params":{}}
{"id":3,"result":{"result":{"type":"number","value":1,"description":"1"}}}
app alive: yes

Each scenario below ran with the pause coming both from the Console (Runtime.evaluate with debugger) and from app code (setTimeout(() => { debugger; ... })):

Scenario Console pause App-code pause
resume: {} reply, Debugger.resumed, code after the pause runs / evaluate result returned pass (crashed before) pass
Debugger.stepOver twice: each step is answered and pauses at a new location; result is correct after resume pass pass
Network.loadNetworkResource, IO.read, IO.close while paused pass pass
Debugger.evaluateOnCallFrame and Runtime.evaluate while paused pass pass
client disconnects while paused; a new client connects, gets the scriptParsed replay, sees the app resumed, and can pause and resume again pass pass
a second client takes over while the first is still connected and paused (same checks) pass pass

All 12 combinations passed. Then console stepping, console disconnect, and takeover with each pause origin ran 10 more times each: 40/40 passed, with the app alive and no crash reports. Before the fix, only the Console column failed (the app crashed at the first pause). The app-code column passed on the unmodified build too.

One more check: a Runtime.evaluate that spins the main run loop (NSRunLoop.currentRunLoop.runUntilDate(...)) while another message arrives. Both replies come back in order on both builds. The main queue doesn't run a second drain block while one is on the stack, so the drain can't nest that way.

./run_tests.sh --temp-sim: 2314 specs, 0 failures, 13 skipped. The suite has no inspector coverage, so it guards only against regressions elsewhere.

Summary by CodeRabbit

  • Bug Fixes
    • Inspector messages now stop draining while a pause loop is active, and pending session resets are deferred until it finishes. This helps prevent message handling from interfering with paused debugging.

Evaluating `debugger` from the DevTools console (Runtime.evaluate) killed
the app with EXC_BREAKPOINT in libdispatch ("dispatch_sync called on queue
already owned by current thread"). The frontend saw Debugger.paused and
then nothing: no reply to Debugger.resume, no Debugger.resumed.

ScheduleMessageDrain ran its whole drain loop, dispatchMessage included,
inside dispatch_sync(messageLoopQueue_). When the dispatched message
paused, V8 called runMessageLoopOnPause on the same thread, and its own
dispatch_sync(messageLoopQueue_) re-entered the serial queue that the drain
already held. Pauses from app code (timers, breakpoints in callbacks) were
not affected, because no drain is on the stack when they happen.

The drain now takes messageLoopQueue_ only to read the pause loop flags,
and dispatches outside it. The flag and session reset checks run before
every pop rather than once. A pause inside a dispatch can end with a
deferred session reset (a frontend disconnecting or reconnecting while
paused), and the drain loop then carries on. It must not feed the next
frontend's messages to the old session.
@coderabbitai

coderabbitai Bot commented Nov 27, 2026 •

Copy link
Copy Markdown

Explain Change →

No actionable comments were generated in the recent review.

Walkthrough

ScheduleMessageDrain now checks pause-loop state before each queue pop. It defers pending session resets while a pause loop runs and dispatches messages without holding messageLoopQueue_.

Changes: Inspector message draining

Layer / File(s) Summary
Pause-aware message draining
NativeScript/inspector/JsV8InspectorClient.mm
Each drain iteration checks pause-loop state before popping a message. A pending session reset waits for a running loop to exit; otherwise, the reset is applied before pumping. Message dispatch no longer holds messageLoopQueue_.

Estimated code review effort: 2 (Simple) | ~10 minutes

Change: Bug fix

Possibly related PRs

  • NativeScript/ios#516: Adds deferred paused-session replacement and session resets on disconnect. This change handles when those pending resets run during message draining.

Suggested reviewers: ptomato

Merge Risk: Minimal · up to 2ab9f

This change stops the app from crashing when DevTools evaluates a debugger statement and the inspector pauses. No concrete remaining risk was found, and the reported manual pause, disconnect and takeover checks passed.

Pre-merge checks: Passed 4

Check name Status Explanation
Description Check Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check Passed The title names the main change: it fixes a crash in the inspector when an inspector message pauses execution. The raw summary shows changes to ScheduleMessageDrain in JsV8InspectorClient.mm that stop…
Linked Issues check Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check Passed Check skipped because no linked issues were found for this pull request.
Full details: Title check

Explanation

The title names the main change: it fixes a crash in the inspector when an inspector message pauses execution. The raw summary shows changes to ScheduleMessageDrain in JsV8InspectorClient.mm that stop holding messageLoopQueue_ during dispatch and handle pause-loop state, which matches the title. The title is concise, specific, and follows the conventional commit style.

  • Autofix · Keep fixing CodeRabbit findings and required CI, and resolving merge conflicts

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

Share

A rabbit watches the message queue,
And checks the pause loop before each dequeue.
If a reset must wait, it stays,
Then syncs the session when the loop gives way.
Messages hop along, no lock in view.

Recent review info

Run configuration

  • Source mode: Auto
  • Repository: Unavailable
  • Branch: Unavailable
  • File: No configuration file from this repository applied
  • Commit: Unavailable
  • Layers: Repository UI
  • Review profile: CHILL
  • Plan: Advanced
  • Run ID: cf8a0b16-e496-43af-8f31-cf0e775d4819
Commits

Reviewing files that changed from the base of the PR and between 382df51 and 2ab9f2e.

Files selected for processing: 1

  • NativeScript/inspector/JsV8InspectorClient.mm

Included review availability: This review used your included allowance. Your plan provides up to 2 included reviews per hour; 0 remain after this review.

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant