From e768a1f228db4948e4fea22e9bd26068e6a0ee6e Mon Sep 17 00:00:00 2001 From: "trop[bot]" <37223003+trop[bot]@users.noreply.github.com> Date: Thu, 11 Jul 2024 14:53:06 +0200 Subject: [PATCH] fix: dangling raw_ptr in UserDataLink (#42852) * fix: dangling raw_ptr in UserDataLink Co-authored-by: Charles Kerr * fixup! fix: dangling raw_ptr in UserDataLink Co-authored-by: Charles Kerr --------- Co-authored-by: trop[bot] <37223003+trop[bot]@users.noreply.github.com> Co-authored-by: Charles Kerr --- shell/browser/api/electron_api_session.cc | 12 +++++++----- shell/browser/api/electron_api_session.h | 5 ++++- 2 files changed, 11 insertions(+), 6 deletions(-) diff --git a/shell/browser/api/electron_api_session.cc b/shell/browser/api/electron_api_session.cc index 0043f9322028..bf2823f552ea 100644 --- a/shell/browser/api/electron_api_session.cc +++ b/shell/browser/api/electron_api_session.cc @@ -530,9 +530,10 @@ class DictionaryObserver final : public SpellcheckCustomDictionary::Observer { #endif // BUILDFLAG(ENABLE_BUILTIN_SPELLCHECKER) struct UserDataLink : base::SupportsUserData::Data { - explicit UserDataLink(Session* ses) : session(ses) {} + explicit UserDataLink(base::WeakPtr session_in) + : session{std::move(session_in)} {} - raw_ptr session; + base::WeakPtr session; }; const void* kElectronApiSessionKey = &kElectronApiSessionKey; @@ -552,8 +553,9 @@ Session::Session(v8::Isolate* isolate, ElectronBrowserContext* browser_context) protocol_.Reset(isolate, Protocol::Create(isolate, browser_context).ToV8()); - browser_context->SetUserData(kElectronApiSessionKey, - std::make_unique(this)); + browser_context->SetUserData( + kElectronApiSessionKey, + std::make_unique(weak_factory_.GetWeakPtr())); #if BUILDFLAG(ENABLE_BUILTIN_SPELLCHECKER) SpellcheckService* service = @@ -1512,7 +1514,7 @@ bool Session::IsSpellCheckerEnabled() const { Session* Session::FromBrowserContext(content::BrowserContext* context) { auto* data = static_cast(context->GetUserData(kElectronApiSessionKey)); - return data ? data->session : nullptr; + return data ? data->session.get() : nullptr; } // static diff --git a/shell/browser/api/electron_api_session.h b/shell/browser/api/electron_api_session.h index 1efe2296fa2e..e9ef22107312 100644 --- a/shell/browser/api/electron_api_session.h +++ b/shell/browser/api/electron_api_session.h @@ -10,6 +10,7 @@ #include #include "base/memory/raw_ptr.h" +#include "base/memory/weak_ptr.h" #include "base/values.h" #include "content/public/browser/download_manager.h" #include "electron/buildflags/buildflags.h" @@ -215,7 +216,9 @@ class Session : public gin::Wrappable, // The client id to enable the network throttler. base::UnguessableToken network_emulation_token_; - raw_ptr browser_context_; + const raw_ptr browser_context_; + + base::WeakPtrFactory weak_factory_{this}; }; } // namespace api