Skip to content

Commit e1b6f86

Browse files
committed
Notify event pipe before releasing NativeActivity resources
The design of ndk-glue seems to imply that the user of a `NativeActivity` resource, e.g. `NativeWindow` obtained from `ndk_glue::native_window()`, should hold a read lock on the resource as long as they are using it. Therefore, ndk-glue's `NativeActivity` callbacks related to resource release should: (1) notify the user of upcoming resource release, (2) acquire a write lock on the handle, waiting for all read locks to be dropped, (3) drop the handle, (4) return from the callback. This allows the user to react and correctly release various objects derived from the resource (e.g. swapchains/surfaces from `NativeWindow`) before it goes away. Currently, the order is 2-3-1-4, which can lead to a deadlock (if the user holds on to a read guard) or a race condition (if they drop the read guard early). This commit fixes the order.
1 parent 3b9c4a9 commit e1b6f86

File tree

1 file changed

+5
-3
lines changed

1 file changed

+5
-3
lines changed

ndk-glue/src/lib.rs

Lines changed: 5 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -260,8 +260,8 @@ unsafe extern "C" fn on_window_destroyed(
260260
activity: *mut ANativeActivity,
261261
_window: *mut ANativeWindow,
262262
) {
263-
*NATIVE_WINDOW.write().unwrap() = None;
264263
wake(activity, Event::WindowDestroyed);
264+
*NATIVE_WINDOW.write().unwrap() = None;
265265
}
266266

267267
unsafe extern "C" fn on_input_queue_created(
@@ -279,10 +279,12 @@ unsafe extern "C" fn on_input_queue_destroyed(
279279
activity: *mut ANativeActivity,
280280
queue: *mut AInputQueue,
281281
) {
282+
wake(activity, Event::InputQueueDestroyed);
283+
let mut input_queue_guard = INPUT_QUEUE.write().unwrap();
284+
assert_eq!(input_queue_guard.as_ref().unwrap().ptr().as_ptr(), queue);
282285
let input_queue = InputQueue::from_ptr(NonNull::new(queue).unwrap());
283286
input_queue.detach_looper();
284-
*INPUT_QUEUE.write().unwrap() = None;
285-
wake(activity, Event::InputQueueDestroyed);
287+
*input_queue_lock = None;
286288
}
287289

288290
unsafe extern "C" fn on_content_rect_changed(activity: *mut ANativeActivity, rect: *const ARect) {

0 commit comments

Comments
 (0)