Files
cefsharp/CefSharp.Core.Runtime/Internals/JavascriptCallbackProxy.h
campersau aab6f9f80e Core - JavascriptCallbackProxy: don't dereference a released CefBrowser in the finalizer
The browser can be disposed on another thread between the IsDisposed check and
reading CefBrowserWrapper::Browser, which then returns a null CefRefPtr. The
finalizer dereferenced it and the NullReferenceException on the finalizer
thread terminated the process.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-15 06:27:28 +10:00

86 lines
3.0 KiB
C++

// Copyright © 2015 The CefSharp Authors. All rights reserved.
//
// Use of this source code is governed by a BSD-style license that can be found in the LICENSE file.
#pragma once
#include "Stdafx.h"
#include "include/cef_app.h"
#include "..\ManagedCefBrowserAdapter.h"
#include "Internals\CefBrowserWrapper.h"
using namespace System::Threading::Tasks;
using namespace CefSharp::JavascriptBinding;
namespace CefSharp
{
namespace Internals
{
private ref class JavascriptCallbackProxy : public IJavascriptCallback
{
private:
WeakReference<IBrowserAdapter^>^ _browserAdapter;
JavascriptCallback^ _callback;
PendingTaskRepository<JavascriptResponse^>^ _pendingTasks;
bool _disposed;
CefRefPtr<CefProcessMessage> CreateDestroyMessage();
IBrowser^ GetBrowser();
IJavascriptNameConverter^ GetJavascriptNameConverter();
void DisposedGuard();
public:
JavascriptCallbackProxy(JavascriptCallback^ callback, PendingTaskRepository<JavascriptResponse^>^ pendingTasks, WeakReference<IBrowserAdapter^>^ browserAdapter)
:_callback(callback), _pendingTasks(pendingTasks), _disposed(false)
{
_browserAdapter = browserAdapter;
}
~JavascriptCallbackProxy()
{
this->!JavascriptCallbackProxy();
}
!JavascriptCallbackProxy()
{
auto browser = GetBrowser();
if (browser != nullptr && !browser->IsDisposed)
{
auto browserWrapper = static_cast<CefBrowserWrapper^>(browser)->Browser;
// The browser can be disposed on another thread after the IsDisposed check above,
// which releases the underlying CefBrowser. This runs on the finalizer thread,
// where a NullReferenceException would terminate the process.
if (browserWrapper.get())
{
auto frame = browserWrapper->GetFrameByIdentifier(StringUtils::ToNative(_callback->FrameId));
if (frame.get() && frame->IsValid())
{
frame->SendProcessMessage(CefProcessId::PID_RENDERER, CreateDestroyMessage());
}
}
}
_disposed = true;
}
virtual Task<JavascriptResponse^>^ ExecuteAsync(cli::array<Object^>^ parameters);
virtual Task<JavascriptResponse^>^ ExecuteWithTimeoutAsync(Nullable<TimeSpan> timeout, cli::array<Object^>^ parameters);
virtual property Int64 Id
{
Int64 get();
}
virtual property bool IsDisposed
{
bool get();
}
virtual property bool CanExecute
{
bool get();
}
};
}
}