Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix(android): BorrowError crash when loading assets on Android #1505

Merged
merged 2 commits into from
Mar 2, 2025
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions .changes/fix-android-race-condition.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
"wry": patch
---

Fix `already mutably borrowed: BorrowError` panic on webview initialization on Android.
2 changes: 1 addition & 1 deletion Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

17 changes: 9 additions & 8 deletions src/android/binding.rs
Original file line number Diff line number Diff line change
Expand Up @@ -106,7 +106,7 @@ fn handle_request(
request: JObject,
is_document_start_script_enabled: jboolean,
) -> JniResult<jobject> {
if let Some(handler) = REQUEST_HANDLER.borrow().as_ref() {
if let Some(handler) = REQUEST_HANDLER.lock().unwrap().as_ref() {
#[cfg(feature = "tracing")]
let span =
tracing::info_span!(parent: None, "wry::custom_protocol::handle", uri = tracing::field::Empty).entered();
Expand Down Expand Up @@ -294,7 +294,8 @@ pub unsafe fn shouldOverride(mut env: JNIEnv, _: JClass, url: JString) -> jboole
Ok(url) => {
let url = url.to_string_lossy().to_string();
URL_LOADING_OVERRIDE
.borrow()
.lock()
.unwrap()
.as_ref()
// We negate the result of the function because the logic for the android
// client is different from how the navigation_handler is defined.
Expand Down Expand Up @@ -340,7 +341,7 @@ pub unsafe fn ipc(mut env: JNIEnv, _: JClass, url: JString, body: JString) {

let url = url.to_string_lossy().to_string();
let body = body.to_string_lossy().to_string();
if let Some(ipc) = IPC.borrow().as_ref() {
if let Some(ipc) = IPC.lock().unwrap().as_ref() {
(ipc.handler)(Request::builder().uri(url).body(body).unwrap())
}
}
Expand All @@ -356,7 +357,7 @@ pub unsafe fn handleReceivedTitle(mut env: JNIEnv, _: JClass, _webview: JObject,
match env.get_string(&title) {
Ok(title) => {
let title = title.to_string_lossy().to_string();
if let Some(title_handler) = TITLE_CHANGE_HANDLER.borrow().as_ref() {
if let Some(title_handler) = TITLE_CHANGE_HANDLER.lock().unwrap().as_ref() {
(title_handler.handler)(title)
}
}
Expand All @@ -369,12 +370,12 @@ pub unsafe fn handleReceivedTitle(mut env: JNIEnv, _: JClass, _webview: JObject,

#[allow(non_snake_case)]
pub unsafe fn withAssetLoader(_: JNIEnv, _: JClass) -> jboolean {
(*WITH_ASSET_LOADER.borrow().as_ref().unwrap_or(&false)).into()
(*WITH_ASSET_LOADER.lock().unwrap().as_ref().unwrap_or(&false)).into()
}

#[allow(non_snake_case)]
pub unsafe fn assetLoaderDomain(env: JNIEnv, _: JClass) -> jstring {
if let Some(domain) = ASSET_LOADER_DOMAIN.borrow().as_ref() {
if let Some(domain) = ASSET_LOADER_DOMAIN.lock().unwrap().as_ref() {
env.new_string(domain).unwrap().as_raw()
} else {
env.new_string("wry.assets").unwrap().as_raw()
Expand All @@ -386,7 +387,7 @@ pub unsafe fn onPageLoading(mut env: JNIEnv, _: JClass, url: JString) {
match env.get_string(&url) {
Ok(url) => {
let url = url.to_string_lossy().to_string();
if let Some(on_load) = ON_LOAD_HANDLER.borrow().as_ref() {
if let Some(on_load) = ON_LOAD_HANDLER.lock().unwrap().as_ref() {
(on_load.handler)(PageLoadEvent::Started, url)
}
}
Expand All @@ -402,7 +403,7 @@ pub unsafe fn onPageLoaded(mut env: JNIEnv, _: JClass, url: JString) {
match env.get_string(&url) {
Ok(url) => {
let url = url.to_string_lossy().to_string();
if let Some(on_load) = ON_LOAD_HANDLER.borrow().as_ref() {
if let Some(on_load) = ON_LOAD_HANDLER.lock().unwrap().as_ref() {
(on_load.handler)(PageLoadEvent::Finished, url)
}
}
Expand Down
76 changes: 43 additions & 33 deletions src/android/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,6 @@ use raw_window_handle::HasWindowHandle;
use sha2::{Digest, Sha256};
use std::{
borrow::Cow,
cell::RefCell,
collections::HashMap,
os::fd::{AsFd as _, AsRawFd as _},
sync::{mpsc::channel, Mutex},
Expand All @@ -45,13 +44,13 @@ pub struct Context<'a, 'b> {
pub webview: &'a JObject<'b>,
}

pub(crate) struct StaticCell<T>(RefCell<T>);
pub(crate) struct StaticValue<T>(Mutex<T>);

unsafe impl<T> Send for StaticCell<T> {}
unsafe impl<T> Sync for StaticCell<T> {}
unsafe impl<T> Send for StaticValue<T> {}
unsafe impl<T> Sync for StaticValue<T> {}

impl<T> std::ops::Deref for StaticCell<T> {
type Target = RefCell<T>;
impl<T> std::ops::Deref for StaticValue<T> {
type Target = Mutex<T>;

fn deref(&self) -> &Self::Target {
&self.0
Expand All @@ -60,7 +59,7 @@ impl<T> std::ops::Deref for StaticCell<T> {

macro_rules! define_static_handlers {
($($var:ident = $type_name:ident { $($fields:ident:$types:ty),+ $(,)? });+ $(;)?) => {
$(pub static $var: StaticCell<Option<$type_name>> = StaticCell(RefCell::new(None));
$(pub static $var: StaticValue<Option<$type_name>> = StaticValue(Mutex::new(None));
pub struct $type_name {
$($fields: $types,)*
}
Expand All @@ -84,8 +83,8 @@ define_static_handlers! {
ON_LOAD_HANDLER = UnsafeOnPageLoadHandler { handler: Box<dyn Fn(PageLoadEvent, String)> };
}

pub static WITH_ASSET_LOADER: StaticCell<Option<bool>> = StaticCell(RefCell::new(None));
pub static ASSET_LOADER_DOMAIN: StaticCell<Option<String>> = StaticCell(RefCell::new(None));
pub static WITH_ASSET_LOADER: StaticValue<Option<bool>> = StaticValue(Mutex::new(None));
pub static ASSET_LOADER_DOMAIN: StaticValue<Option<String>> = StaticValue(Mutex::new(None));

pub(crate) static PACKAGE: OnceCell<String> = OnceCell::new();

Expand Down Expand Up @@ -208,27 +207,14 @@ impl InnerWebView {
.map(|id| id.to_string())
.unwrap_or_else(|| COUNTER.next().to_string());

MainPipe::send(WebViewMessage::CreateWebView(CreateWebViewAttributes {
id: id.clone(),
url,
html,
#[cfg(any(debug_assertions, feature = "devtools"))]
devtools,
background_color,
transparent,
headers,
on_webview_created,
autoplay,
user_agent,
initialization_scripts: initialization_scripts.clone(),
}));

WITH_ASSET_LOADER.replace(Some(with_asset_loader));
WITH_ASSET_LOADER.lock().unwrap().replace(with_asset_loader);
if let Some(domain) = asset_loader_domain {
ASSET_LOADER_DOMAIN.replace(Some(domain));
ASSET_LOADER_DOMAIN.lock().unwrap().replace(domain);
}

REQUEST_HANDLER.replace(Some(
let initialization_scripts_ = initialization_scripts.clone();
REQUEST_HANDLER.lock()
.unwrap().replace(
UnsafeRequestHandler::new(Box::new(
move |webview_id: &str, mut request, is_document_start_script_enabled| {
let uri = request.uri().to_string();
Expand All @@ -247,7 +233,7 @@ impl InnerWebView {
}

let (tx, rx) = channel();
let initialization_scripts = initialization_scripts.clone();
let initialization_scripts = initialization_scripts_.clone();
let responder: Box<dyn FnOnce(HttpResponse<Cow<'static, [u8]>>)> =
Box::new(move |mut response| {
if !is_document_start_script_enabled {
Expand Down Expand Up @@ -309,25 +295,49 @@ impl InnerWebView {
}
None
},
))
)
));

if let Some(i) = ipc_handler {
IPC.replace(Some(UnsafeIpc::new(Box::new(i))));
IPC.lock().unwrap().replace(UnsafeIpc::new(Box::new(i)));
}

if let Some(i) = attributes.document_title_changed_handler {
TITLE_CHANGE_HANDLER.replace(Some(UnsafeTitleHandler::new(i)));
TITLE_CHANGE_HANDLER
.lock()
.unwrap()
.replace(UnsafeTitleHandler::new(i));
}

if let Some(i) = attributes.navigation_handler {
URL_LOADING_OVERRIDE.replace(Some(UnsafeUrlLoadingOverride::new(i)));
URL_LOADING_OVERRIDE
.lock()
.unwrap()
.replace(UnsafeUrlLoadingOverride::new(i));
}

if let Some(h) = attributes.on_page_load_handler {
ON_LOAD_HANDLER.replace(Some(UnsafeOnPageLoadHandler::new(h)));
ON_LOAD_HANDLER
.lock()
.unwrap()
.replace(UnsafeOnPageLoadHandler::new(h));
}

MainPipe::send(WebViewMessage::CreateWebView(CreateWebViewAttributes {
id: id.clone(),
url,
html,
#[cfg(any(debug_assertions, feature = "devtools"))]
devtools,
background_color,
transparent,
headers,
on_webview_created,
autoplay,
user_agent,
initialization_scripts,
}));

Ok(Self { id })
}

Expand Down
Loading