Skip to content

fix: crashes at engine teardown (null-messenger plugin destruction, missing WebView2 Close()) - #333

Open
diligent176 wants to merge 1 commit into
jnschulze:mainfrom
diligent176:fix-engine-teardown-crashes
Open

diligent176 wants to merge 1 commit into
jnschulze:mainfrom
diligent176:fix-engine-teardown-crashes

Conversation

@diligent176

Copy link
Copy Markdown

This fixes two related teardown crashes that hit any app exiting with a live webview.

1. Plugin destruction dereferences a null engine (flutter/flutter#118611). FlutterWindowsEngine's destructor clears the messenger's engine pointer before Stop() runs the plugin destruction callbacks, so ~WebviewBridge's SetMethodCallHandler(nullptr) / UnregisterTexture calls crash with an access violation on every app exit that still has a webview alive. The destructor now skips unregistration during engine teardown - detected via a plugin-alive flag plus FlutterDesktopMessengerIsAvailable under the messenger lock - while a mid-session dispose is byte-identical to before. The texture frame callback (which fires from the capture thread) now runs under the messenger lock, and a WebView2 creation that completes after teardown drops its result instead of calling into the dead engine.

2. ICoreWebView2Controller::Close() was never called. The bridge registers 16 browser-process event handlers (plus per-download handlers with no stored removal tokens) and removes none of them, so the browser host can deliver callbacks into the dying host during app teardown. This shows up as intermittent STATUS_HEAP_CORRUPTION (ntdll 0xc0000374) when closing while media is playing. ~Webview now calls Close() per the documented contract, after quiescing the texture capture thread.

Validation: a headless harness driving real WM_CLOSE/WM_SYSCOMMAND closes reproduces crash 1 deterministically unpatched (2/2, flutter_windows.dll @ FlutterDesktopMessengerSetCallback) and is clean patched across live-webview, no-webview, close-mid-creation, and dispose-then-recreate scenarios. Crash 2 reproduced at ~15% on media-playing closes in app-level QA and is 0/25 after the fix. COM members still release on every path, so playback stops at close either way.

…g WebView2 Close())

Two related teardown defects:

1. FlutterWindowsEngine's destructor clears the messenger's engine pointer
   before Stop() runs the plugin destruction callbacks (flutter/flutter#118611),
   so ~WebviewBridge's channel/texture unregistration dereferences a null
   engine: an access violation on every app exit with a live webview.
   The destructor now skips unregistration during engine teardown (plugin-alive
   flag + FlutterDesktopMessengerIsAvailable under the messenger lock); a
   mid-session dispose is unchanged. The texture frame callback (capture
   thread) runs under the messenger lock, and a WebView2 creation completing
   after teardown drops its result instead of calling into the dead engine.

2. ICoreWebView2Controller::Close() was never called. The class registers 16
   browser-process event handlers (plus per-download handlers with no stored
   removal tokens) and removes none, so the browser host can deliver callbacks
   into the dying host during teardown: observed as intermittent
   STATUS_HEAP_CORRUPTION (ntdll 0xc0000374) at close while media plays.
   ~Webview now calls Close() per the documented contract, after quiescing the
   texture capture thread.

Validated against a headless harness driving real WM_CLOSE/WM_SYSCOMMAND
closes: the null-messenger crash reproduced 2/2 unpatched and is clean
patched (live webview, no webview, close mid-creation, dispose-then-recreate);
the heap corruption reproduced ~15% on media-playing closes in app-level QA
and is 0/25 after the fix.
Copilot AI lite review requested due to automatic review settings August 24, 2026 13:23

Copilot AI left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🟡 Changes recommended

The new engine-availability checks currently have TOCTOU windows (engine can become unavailable after the check but before the guarded calls), which can reintroduce teardown races.

Once you've addressed the issues Copilot identified, you can request another Copilot review.

Pull request overview

This PR addresses Windows teardown crashes in the Flutter WebView Windows plugin by making WebView2 and Flutter engine shutdown paths safer (avoiding callbacks into a torn-down engine and ensuring WebView2 controllers are explicitly closed).

Changes:

  • Call ICoreWebView2Controller::Close() during Webview destruction to stop browser-process event delivery during app teardown.
  • Introduce an engine-availability mechanism (engine_availability.h) and use it to avoid calling messenger/texture APIs when the engine is already torn down.
  • Add a plugin-alive flag and additional guards in creation completion + event emission paths to avoid use-after-free during teardown.
File summaries
File Description
windows/webview.cc Calls ICoreWebView2Controller::Close() in ~Webview() to stop event delivery during teardown.
windows/webview_windows_plugin.cc Tracks plugin lifetime and drops in-flight creation completions during/after teardown.
windows/webview_bridge.h Guards event emission with a plugin-alive check.
windows/webview_bridge.cc Guards texture frame callback with engine availability lock; skips unregister calls during teardown.
windows/engine_availability.h New helper for capturing messenger and safely checking/locking engine availability during teardown.
Review details
  • Files reviewed: 5/5 changed files
  • Comments generated: 2
  • Review effort level: Lite

💡 Add a code-review agent skill or configure MCP servers for context-aware, tailored reviews. Learn more in the docs.

Comment thread windows/webview_bridge.cc
Comment on lines +212 to +215
if (webview_windows::PluginAlive() && webview_windows::EngineAvailable()) {
method_channel_->SetMethodCallHandler(nullptr);
texture_registrar_->UnregisterTexture(texture_id_);
}

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

There's no second thread here, so no TOCTOU window: plugin destruction callbacks run on the platform thread, and FlutterWindowsEngine's destructor (which is what flips availability via SetEngine(nullptr)) runs on that same thread - teardown can't interleave with code already executing on it. The unlocked check-then-call at this site is deliberate: holding the messenger lock across SetMethodCallHandler would risk re-entering the same lock inside the embedder. The one caller that genuinely races from another thread (the texture frame callback, capture thread) is the one routed through IfEngineAvailableLocked - that distinction is called out in engine_availability.h.

Comment on lines +211 to +218
// A completion that fires during/after engine teardown (the user
// closed the window while the webview was still being created) must
// drop everything: `this` may be freed, and answering the result
// would call into a messenger whose engine is gone.
if (!webview_windows::PluginAlive() ||
!webview_windows::EngineAvailable()) {
return;
}

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Same-thread situation as the other comment: WebView2 creation completions are delivered on the platform (STA) thread, the same thread engine destruction runs on, so availability can't change mid-callback. The guard here protects against the queued completion firing after teardown has already finished (plugin freed, engine gone) - a sequencing hazard, not a concurrency one - and for that the entry check is sufficient.

@ymoage

ymoage commented Oct 10, 2026

Copy link
Copy Markdown

Independent confirmation from another app, plus a reproduction in this repo's own example.

Context: Pyokomin (Flutter Windows desktop, YouTube live chat viewer) uses a fork of this plugin. We hit crash 1 on every exit that had a live webview: 0xc0000005 in flutter_windows.dll at the offset that resolves to FlutterDesktopMessengerSetCallback — 23 WER records in ~13 hours before we patched it. We found it by hand-parsing a minidump; the stack had 41 of 181 slots pointing into webview_windows_plugin.dll, with the caller frame right below the fault.

Reproduced here, unmodified. To be sure it was not our fork, I built example/ from upstream main (ed81bbe) as-is and closed it three times: 3/3 abnormal exit (0xC000041D), same faulting offset. Applying only the engine-gone guard (flag set in ~WebviewWindowsPlugin() before instances_.clear(), checked in ~WebviewBridge) and rebuilding: 3/3 exit code 0, no WER records.

Our app shipped the same minimal guard independently and has been clean for 5/5 normal exits with a live webview (previously 100% crash).

Crash 2: we have one 0xc0000374 observation, so I can't say much about frequency. Note that our fork has called ICoreWebView2Controller::Close() with explicit handler removal since January (it came out of the work behind #325, for access violations on rapid dispose/create cycles); we have not seen that class of crash since.

I'm not proposing anything — just confirming the diagnosis holds outside our codebase, including in this repo's own example. Supporting this PR.

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.

3 participants