blob: 68fa34bb4ad58724778a33a22492127097e2608b [file] [log] [blame]
Stephen Crane2a3c2502020-06-16 17:48:35 -07001/*
2 * Copyright (C) 2020 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17//! Rust API for interacting with a remote binder service.
18
19use crate::binder::{
Andrew Walbran12400d82021-03-04 17:04:34 +000020 AsNative, FromIBinder, IBinder, IBinderInternal, Interface, InterfaceClass, Strong,
21 TransactionCode, TransactionFlags,
Stephen Crane2a3c2502020-06-16 17:48:35 -070022};
23use crate::error::{status_result, Result, StatusCode};
24use crate::parcel::{
25 Deserialize, DeserializeArray, DeserializeOption, Parcel, Serialize, SerializeArray,
26 SerializeOption,
27};
28use crate::sys;
29
Stephen Craneddb3e6d2020-12-18 13:27:22 -080030use std::cmp::Ordering;
Andrew Walbran12400d82021-03-04 17:04:34 +000031use std::convert::TryInto;
Stephen Crane2a3c2502020-06-16 17:48:35 -070032use std::ffi::{c_void, CString};
Andrei Homescu2e3c1472020-08-11 16:35:40 -070033use std::fmt;
Alice Ryhlea9d9d22021-08-27 07:51:30 +000034use std::mem;
Stephen Crane2a3c2502020-06-16 17:48:35 -070035use std::os::unix::io::AsRawFd;
36use std::ptr;
Alice Ryhlea9d9d22021-08-27 07:51:30 +000037use std::sync::Arc;
Stephen Crane2a3c2502020-06-16 17:48:35 -070038
39/// A strong reference to a Binder remote object.
40///
41/// This struct encapsulates the generic C++ `sp<IBinder>` class. This wrapper
42/// is untyped; typed interface access is implemented by the AIDL compiler.
Alice Ryhl8dde9bc2021-08-16 16:57:10 +000043pub struct SpIBinder(ptr::NonNull<sys::AIBinder>);
Stephen Crane2a3c2502020-06-16 17:48:35 -070044
Andrei Homescu2e3c1472020-08-11 16:35:40 -070045impl fmt::Debug for SpIBinder {
46 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
47 f.pad("SpIBinder")
48 }
49}
50
Stephen Crane2a3c2502020-06-16 17:48:35 -070051/// # Safety
52///
Stephen Cranef03fe3d2021-06-25 15:05:00 -070053/// An `SpIBinder` is an immutable handle to a C++ IBinder, which is thread-safe
Stephen Crane2a3c2502020-06-16 17:48:35 -070054unsafe impl Send for SpIBinder {}
55
Stephen Cranef03fe3d2021-06-25 15:05:00 -070056/// # Safety
57///
58/// An `SpIBinder` is an immutable handle to a C++ IBinder, which is thread-safe
59unsafe impl Sync for SpIBinder {}
60
Stephen Crane2a3c2502020-06-16 17:48:35 -070061impl SpIBinder {
62 /// Create an `SpIBinder` wrapper object from a raw `AIBinder` pointer.
63 ///
64 /// # Safety
65 ///
66 /// This constructor is safe iff `ptr` is a null pointer or a valid pointer
67 /// to an `AIBinder`.
68 ///
69 /// In the non-null case, this method conceptually takes ownership of a strong
70 /// reference to the object, so `AIBinder_incStrong` must have been called
71 /// on the pointer before passing it to this constructor. This is generally
72 /// done by Binder NDK methods that return an `AIBinder`, but care should be
73 /// taken to ensure this invariant.
74 ///
75 /// All `SpIBinder` objects that are constructed will hold a valid pointer
76 /// to an `AIBinder`, which will remain valid for the entire lifetime of the
77 /// `SpIBinder` (we keep a strong reference, and only decrement on drop).
78 pub(crate) unsafe fn from_raw(ptr: *mut sys::AIBinder) -> Option<Self> {
Alice Ryhl8dde9bc2021-08-16 16:57:10 +000079 ptr::NonNull::new(ptr).map(Self)
Stephen Crane2a3c2502020-06-16 17:48:35 -070080 }
81
Stephen Craned58bce02020-07-07 12:26:02 -070082 /// Extract a raw `AIBinder` pointer from this wrapper.
83 ///
84 /// This method should _only_ be used for testing. Do not try to use the NDK
85 /// interface directly for anything else.
86 ///
87 /// # Safety
88 ///
89 /// The resulting pointer is valid only as long as the SpIBinder is alive.
90 /// The SpIBinder object retains ownership of the AIBinder and the caller
91 /// should not attempt to free the returned pointer.
92 pub unsafe fn as_raw(&self) -> *mut sys::AIBinder {
Alice Ryhl8dde9bc2021-08-16 16:57:10 +000093 self.0.as_ptr()
Stephen Craned58bce02020-07-07 12:26:02 -070094 }
95
Stephen Crane2a3c2502020-06-16 17:48:35 -070096 /// Return true if this binder object is hosted in a different process than
97 /// the current one.
98 pub fn is_remote(&self) -> bool {
99 unsafe {
100 // Safety: `SpIBinder` guarantees that it always contains a valid
101 // `AIBinder` pointer.
102 sys::AIBinder_isRemote(self.as_native())
103 }
104 }
105
106 /// Try to convert this Binder object into a trait object for the given
107 /// Binder interface.
108 ///
109 /// If this object does not implement the expected interface, the error
110 /// `StatusCode::BAD_TYPE` is returned.
Stephen Craneddb3e6d2020-12-18 13:27:22 -0800111 pub fn into_interface<I: FromIBinder + Interface + ?Sized>(self) -> Result<Strong<I>> {
Stephen Crane2a3c2502020-06-16 17:48:35 -0700112 FromIBinder::try_from(self)
113 }
114
115 /// Return the interface class of this binder object, if associated with
116 /// one.
Stephen Crane669deb62020-09-10 17:31:39 -0700117 pub fn get_class(&mut self) -> Option<InterfaceClass> {
Stephen Crane2a3c2502020-06-16 17:48:35 -0700118 unsafe {
119 // Safety: `SpIBinder` guarantees that it always contains a valid
120 // `AIBinder` pointer. `AIBinder_getClass` returns either a null
121 // pointer or a valid pointer to an `AIBinder_Class`. After mapping
122 // null to None, we can safely construct an `InterfaceClass` if the
123 // pointer was non-null.
124 let class = sys::AIBinder_getClass(self.as_native_mut());
125 class.as_ref().map(|p| InterfaceClass::from_ptr(p))
126 }
127 }
Andrew Walbran8fe3ecc2020-12-15 11:29:58 +0000128
129 /// Creates a new weak reference to this binder object.
130 pub fn downgrade(&mut self) -> WpIBinder {
131 WpIBinder::new(self)
132 }
Stephen Crane2a3c2502020-06-16 17:48:35 -0700133}
134
Victor Hsiehd35d31d2021-06-03 11:24:31 -0700135pub mod unstable_api {
136 use super::{sys, SpIBinder};
137
138 /// A temporary API to allow the client to create a `SpIBinder` from a `sys::AIBinder`. This is
139 /// needed to bridge RPC binder, which doesn't have Rust API yet.
140 /// TODO(b/184872979): remove once the Rust API is created.
141 ///
142 /// # Safety
143 ///
144 /// See `SpIBinder::from_raw`.
145 pub unsafe fn new_spibinder(ptr: *mut sys::AIBinder) -> Option<SpIBinder> {
146 SpIBinder::from_raw(ptr)
147 }
148}
149
Stephen Crane2a3c2502020-06-16 17:48:35 -0700150/// An object that can be associate with an [`InterfaceClass`].
151pub trait AssociateClass {
152 /// Check if this object is a valid object for the given interface class
153 /// `I`.
154 ///
155 /// Returns `Some(self)` if this is a valid instance of the interface, and
156 /// `None` otherwise.
157 ///
158 /// Classes constructed by `InterfaceClass` are unique per type, so
159 /// repeatedly calling this method for the same `InterfaceClass` is allowed.
160 fn associate_class(&mut self, class: InterfaceClass) -> bool;
161}
162
163impl AssociateClass for SpIBinder {
164 fn associate_class(&mut self, class: InterfaceClass) -> bool {
165 unsafe {
166 // Safety: `SpIBinder` guarantees that it always contains a valid
167 // `AIBinder` pointer. An `InterfaceClass` can always be converted
168 // into a valid `AIBinder_Class` pointer, so these parameters are
169 // always safe.
170 sys::AIBinder_associateClass(self.as_native_mut(), class.into())
171 }
172 }
173}
174
Stephen Craneddb3e6d2020-12-18 13:27:22 -0800175impl Ord for SpIBinder {
176 fn cmp(&self, other: &Self) -> Ordering {
177 let less_than = unsafe {
178 // Safety: SpIBinder always holds a valid `AIBinder` pointer, so
179 // this pointer is always safe to pass to `AIBinder_lt` (null is
180 // also safe to pass to this function, but we should never do that).
Alice Ryhl8dde9bc2021-08-16 16:57:10 +0000181 sys::AIBinder_lt(self.0.as_ptr(), other.0.as_ptr())
Stephen Craneddb3e6d2020-12-18 13:27:22 -0800182 };
183 let greater_than = unsafe {
184 // Safety: SpIBinder always holds a valid `AIBinder` pointer, so
185 // this pointer is always safe to pass to `AIBinder_lt` (null is
186 // also safe to pass to this function, but we should never do that).
Alice Ryhl8dde9bc2021-08-16 16:57:10 +0000187 sys::AIBinder_lt(other.0.as_ptr(), self.0.as_ptr())
Stephen Craneddb3e6d2020-12-18 13:27:22 -0800188 };
189 if !less_than && !greater_than {
190 Ordering::Equal
191 } else if less_than {
192 Ordering::Less
193 } else {
194 Ordering::Greater
195 }
196 }
197}
198
199impl PartialOrd for SpIBinder {
200 fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
201 Some(self.cmp(other))
202 }
203}
204
Stephen Crane994a0f02020-08-11 14:47:29 -0700205impl PartialEq for SpIBinder {
206 fn eq(&self, other: &Self) -> bool {
Alice Ryhl8dde9bc2021-08-16 16:57:10 +0000207 ptr::eq(self.0.as_ptr(), other.0.as_ptr())
Stephen Crane994a0f02020-08-11 14:47:29 -0700208 }
209}
210
211impl Eq for SpIBinder {}
212
Stephen Crane2a3c2502020-06-16 17:48:35 -0700213impl Clone for SpIBinder {
214 fn clone(&self) -> Self {
215 unsafe {
216 // Safety: Cloning a strong reference must increment the reference
217 // count. We are guaranteed by the `SpIBinder` constructor
218 // invariants that `self.0` is always a valid `AIBinder` pointer.
Alice Ryhl8dde9bc2021-08-16 16:57:10 +0000219 sys::AIBinder_incStrong(self.0.as_ptr());
Stephen Crane2a3c2502020-06-16 17:48:35 -0700220 }
221 Self(self.0)
222 }
223}
224
225impl Drop for SpIBinder {
226 // We hold a strong reference to the IBinder in SpIBinder and need to give up
227 // this reference on drop.
228 fn drop(&mut self) {
229 unsafe {
230 // Safety: SpIBinder always holds a valid `AIBinder` pointer, so we
231 // know this pointer is safe to pass to `AIBinder_decStrong` here.
232 sys::AIBinder_decStrong(self.as_native_mut());
233 }
234 }
235}
236
Andrew Walbran12400d82021-03-04 17:04:34 +0000237impl<T: AsNative<sys::AIBinder>> IBinderInternal for T {
Alice Ryhlfeba6ca2021-08-19 10:47:04 +0000238 fn prepare_transact(&self) -> Result<Parcel> {
Stephen Crane2a3c2502020-06-16 17:48:35 -0700239 let mut input = ptr::null_mut();
240 let status = unsafe {
241 // Safety: `SpIBinder` guarantees that `self` always contains a
242 // valid pointer to an `AIBinder`. It is safe to cast from an
243 // immutable pointer to a mutable pointer here, because
244 // `AIBinder_prepareTransaction` only calls immutable `AIBinder`
245 // methods but the parameter is unfortunately not marked as const.
246 //
247 // After the call, input will be either a valid, owned `AParcel`
248 // pointer, or null.
249 sys::AIBinder_prepareTransaction(self.as_native() as *mut sys::AIBinder, &mut input)
250 };
Alice Ryhlfeba6ca2021-08-19 10:47:04 +0000251
Stephen Crane2a3c2502020-06-16 17:48:35 -0700252 status_result(status)?;
Alice Ryhlfeba6ca2021-08-19 10:47:04 +0000253
254 unsafe {
Stephen Crane2a3c2502020-06-16 17:48:35 -0700255 // Safety: At this point, `input` is either a valid, owned `AParcel`
256 // pointer, or null. `Parcel::owned` safely handles both cases,
257 // taking ownership of the parcel.
Alice Ryhlfeba6ca2021-08-19 10:47:04 +0000258 Parcel::owned(input).ok_or(StatusCode::UNEXPECTED_NULL)
259 }
260 }
261
262 fn submit_transact(
263 &self,
264 code: TransactionCode,
265 data: Parcel,
266 flags: TransactionFlags,
267 ) -> Result<Parcel> {
Stephen Crane2a3c2502020-06-16 17:48:35 -0700268 let mut reply = ptr::null_mut();
Alice Ryhlfeba6ca2021-08-19 10:47:04 +0000269 assert!(data.is_owned());
Stephen Crane2a3c2502020-06-16 17:48:35 -0700270 let status = unsafe {
271 // Safety: `SpIBinder` guarantees that `self` always contains a
272 // valid pointer to an `AIBinder`. Although `IBinder::transact` is
273 // not a const method, it is still safe to cast our immutable
274 // pointer to mutable for the call. First, `IBinder::transact` is
275 // thread-safe, so concurrency is not an issue. The only way that
276 // `transact` can affect any visible, mutable state in the current
277 // process is by calling `onTransact` for a local service. However,
278 // in order for transactions to be thread-safe, this method must
279 // dynamically lock its data before modifying it. We enforce this
280 // property in Rust by requiring `Sync` for remotable objects and
281 // only providing `on_transact` with an immutable reference to
282 // `self`.
283 //
Alice Ryhlfeba6ca2021-08-19 10:47:04 +0000284 // This call takes ownership of the `data` parcel pointer, and
Stephen Crane2a3c2502020-06-16 17:48:35 -0700285 // passes ownership of the `reply` out parameter to its caller. It
286 // does not affect ownership of the `binder` parameter.
287 sys::AIBinder_transact(
288 self.as_native() as *mut sys::AIBinder,
289 code,
Alice Ryhlfeba6ca2021-08-19 10:47:04 +0000290 &mut data.into_raw(),
Stephen Crane2a3c2502020-06-16 17:48:35 -0700291 &mut reply,
292 flags,
293 )
294 };
295 status_result(status)?;
296
297 unsafe {
298 // Safety: `reply` is either a valid `AParcel` pointer or null
299 // after the call to `AIBinder_transact` above, so we can
300 // construct a `Parcel` out of it. `AIBinder_transact` passes
301 // ownership of the `reply` parcel to Rust, so we need to
302 // construct an owned variant. `Parcel::owned` takes ownership
303 // of the parcel pointer.
304 Parcel::owned(reply).ok_or(StatusCode::UNEXPECTED_NULL)
305 }
306 }
307
308 fn is_binder_alive(&self) -> bool {
309 unsafe {
310 // Safety: `SpIBinder` guarantees that `self` always contains a
311 // valid pointer to an `AIBinder`.
312 //
313 // This call does not affect ownership of its pointer parameter.
314 sys::AIBinder_isAlive(self.as_native())
315 }
316 }
317
318 fn ping_binder(&mut self) -> Result<()> {
319 let status = unsafe {
320 // Safety: `SpIBinder` guarantees that `self` always contains a
321 // valid pointer to an `AIBinder`.
322 //
323 // This call does not affect ownership of its pointer parameter.
324 sys::AIBinder_ping(self.as_native_mut())
325 };
326 status_result(status)
327 }
328
Janis Danisevskis798a09a2020-08-18 08:35:38 -0700329 fn set_requesting_sid(&mut self, enable: bool) {
Andrew Walbran12400d82021-03-04 17:04:34 +0000330 unsafe { sys::AIBinder_setRequestingSid(self.as_native_mut(), enable) };
Janis Danisevskis798a09a2020-08-18 08:35:38 -0700331 }
332
Stephen Crane2a3c2502020-06-16 17:48:35 -0700333 fn dump<F: AsRawFd>(&mut self, fp: &F, args: &[&str]) -> Result<()> {
334 let args: Vec<_> = args.iter().map(|a| CString::new(*a).unwrap()).collect();
335 let mut arg_ptrs: Vec<_> = args.iter().map(|a| a.as_ptr()).collect();
336 let status = unsafe {
337 // Safety: `SpIBinder` guarantees that `self` always contains a
338 // valid pointer to an `AIBinder`. `AsRawFd` guarantees that the
339 // file descriptor parameter is always be a valid open file. The
340 // `args` pointer parameter is a valid pointer to an array of C
341 // strings that will outlive the call since `args` lives for the
342 // whole function scope.
343 //
344 // This call does not affect ownership of its binder pointer
345 // parameter and does not take ownership of the file or args array
346 // parameters.
347 sys::AIBinder_dump(
348 self.as_native_mut(),
349 fp.as_raw_fd(),
350 arg_ptrs.as_mut_ptr(),
351 arg_ptrs.len().try_into().unwrap(),
352 )
353 };
354 status_result(status)
355 }
356
357 fn get_extension(&mut self) -> Result<Option<SpIBinder>> {
358 let mut out = ptr::null_mut();
359 let status = unsafe {
360 // Safety: `SpIBinder` guarantees that `self` always contains a
361 // valid pointer to an `AIBinder`. After this call, the `out`
362 // parameter will be either null, or a valid pointer to an
363 // `AIBinder`.
364 //
365 // This call passes ownership of the out pointer to its caller
366 // (assuming it is set to a non-null value).
367 sys::AIBinder_getExtension(self.as_native_mut(), &mut out)
368 };
369 let ibinder = unsafe {
370 // Safety: The call above guarantees that `out` is either null or a
371 // valid, owned pointer to an `AIBinder`, both of which are safe to
372 // pass to `SpIBinder::from_raw`.
373 SpIBinder::from_raw(out)
374 };
375
376 status_result(status)?;
377 Ok(ibinder)
378 }
Andrew Walbran12400d82021-03-04 17:04:34 +0000379}
Stephen Crane2a3c2502020-06-16 17:48:35 -0700380
Andrew Walbran12400d82021-03-04 17:04:34 +0000381impl<T: AsNative<sys::AIBinder>> IBinder for T {
Stephen Crane2a3c2502020-06-16 17:48:35 -0700382 fn link_to_death(&mut self, recipient: &mut DeathRecipient) -> Result<()> {
383 status_result(unsafe {
384 // Safety: `SpIBinder` guarantees that `self` always contains a
385 // valid pointer to an `AIBinder`. `recipient` can always be
386 // converted into a valid pointer to an
Alice Ryhlea9d9d22021-08-27 07:51:30 +0000387 // `AIBinder_DeathRecipient`.
388 //
389 // The cookie is also the correct pointer, and by calling new_cookie,
390 // we have created a new ref-count to the cookie, which linkToDeath
391 // takes ownership of. Once the DeathRecipient is unlinked for any
392 // reason (including if this call fails), the onUnlinked callback
393 // will consume that ref-count.
Stephen Crane2a3c2502020-06-16 17:48:35 -0700394 sys::AIBinder_linkToDeath(
395 self.as_native_mut(),
396 recipient.as_native_mut(),
Alice Ryhlea9d9d22021-08-27 07:51:30 +0000397 recipient.new_cookie(),
Stephen Crane2a3c2502020-06-16 17:48:35 -0700398 )
399 })
400 }
401
402 fn unlink_to_death(&mut self, recipient: &mut DeathRecipient) -> Result<()> {
403 status_result(unsafe {
404 // Safety: `SpIBinder` guarantees that `self` always contains a
405 // valid pointer to an `AIBinder`. `recipient` can always be
406 // converted into a valid pointer to an
Stephen Craneddb3e6d2020-12-18 13:27:22 -0800407 // `AIBinder_DeathRecipient`. Any value is safe to pass as the
Stephen Crane2a3c2502020-06-16 17:48:35 -0700408 // cookie, although we depend on this value being set by
409 // `get_cookie` when the death recipient callback is called.
410 sys::AIBinder_unlinkToDeath(
411 self.as_native_mut(),
412 recipient.as_native_mut(),
413 recipient.get_cookie(),
414 )
415 })
416 }
417}
418
419impl Serialize for SpIBinder {
420 fn serialize(&self, parcel: &mut Parcel) -> Result<()> {
421 parcel.write_binder(Some(self))
422 }
423}
424
425impl SerializeOption for SpIBinder {
426 fn serialize_option(this: Option<&Self>, parcel: &mut Parcel) -> Result<()> {
427 parcel.write_binder(this)
428 }
429}
430
431impl SerializeArray for SpIBinder {}
432impl SerializeArray for Option<&SpIBinder> {}
433
434impl Deserialize for SpIBinder {
435 fn deserialize(parcel: &Parcel) -> Result<SpIBinder> {
Andrei Homescu32814372020-08-20 15:36:08 -0700436 parcel
437 .read_binder()
438 .transpose()
439 .unwrap_or(Err(StatusCode::UNEXPECTED_NULL))
Stephen Crane2a3c2502020-06-16 17:48:35 -0700440 }
441}
442
443impl DeserializeOption for SpIBinder {
444 fn deserialize_option(parcel: &Parcel) -> Result<Option<SpIBinder>> {
445 parcel.read_binder()
446 }
447}
448
449impl DeserializeArray for SpIBinder {}
450impl DeserializeArray for Option<SpIBinder> {}
451
452/// A weak reference to a Binder remote object.
453///
Andrew Walbran8fe3ecc2020-12-15 11:29:58 +0000454/// This struct encapsulates the generic C++ `wp<IBinder>` class. This wrapper
455/// is untyped; typed interface access is implemented by the AIDL compiler.
Alice Ryhl8dde9bc2021-08-16 16:57:10 +0000456pub struct WpIBinder(ptr::NonNull<sys::AIBinder_Weak>);
Stephen Crane2a3c2502020-06-16 17:48:35 -0700457
Andrew Walbran8fe3ecc2020-12-15 11:29:58 +0000458impl fmt::Debug for WpIBinder {
459 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
460 f.pad("WpIBinder")
461 }
462}
463
464/// # Safety
465///
Stephen Cranef03fe3d2021-06-25 15:05:00 -0700466/// A `WpIBinder` is an immutable handle to a C++ IBinder, which is thread-safe.
Andrew Walbran8fe3ecc2020-12-15 11:29:58 +0000467unsafe impl Send for WpIBinder {}
468
Stephen Cranef03fe3d2021-06-25 15:05:00 -0700469/// # Safety
470///
471/// A `WpIBinder` is an immutable handle to a C++ IBinder, which is thread-safe.
472unsafe impl Sync for WpIBinder {}
473
Stephen Crane2a3c2502020-06-16 17:48:35 -0700474impl WpIBinder {
475 /// Create a new weak reference from an object that can be converted into a
476 /// raw `AIBinder` pointer.
Andrew Walbran8fe3ecc2020-12-15 11:29:58 +0000477 fn new<B: AsNative<sys::AIBinder>>(binder: &mut B) -> WpIBinder {
Stephen Crane2a3c2502020-06-16 17:48:35 -0700478 let ptr = unsafe {
479 // Safety: `SpIBinder` guarantees that `binder` always contains a
480 // valid pointer to an `AIBinder`.
481 sys::AIBinder_Weak_new(binder.as_native_mut())
482 };
Alice Ryhl8dde9bc2021-08-16 16:57:10 +0000483 Self(ptr::NonNull::new(ptr).expect("Unexpected null pointer from AIBinder_Weak_new"))
Stephen Crane2a3c2502020-06-16 17:48:35 -0700484 }
Stephen Crane994a0f02020-08-11 14:47:29 -0700485
486 /// Promote this weak reference to a strong reference to the binder object.
487 pub fn promote(&self) -> Option<SpIBinder> {
488 unsafe {
489 // Safety: `WpIBinder` always contains a valid weak reference, so we
490 // can pass this pointer to `AIBinder_Weak_promote`. Returns either
491 // null or an AIBinder owned by the caller, both of which are valid
492 // to pass to `SpIBinder::from_raw`.
Alice Ryhl8dde9bc2021-08-16 16:57:10 +0000493 let ptr = sys::AIBinder_Weak_promote(self.0.as_ptr());
Stephen Crane994a0f02020-08-11 14:47:29 -0700494 SpIBinder::from_raw(ptr)
495 }
496 }
Stephen Crane2a3c2502020-06-16 17:48:35 -0700497}
498
Stephen Craneddb3e6d2020-12-18 13:27:22 -0800499impl Clone for WpIBinder {
500 fn clone(&self) -> Self {
501 let ptr = unsafe {
502 // Safety: WpIBinder always holds a valid `AIBinder_Weak` pointer,
503 // so this pointer is always safe to pass to `AIBinder_Weak_clone`
504 // (although null is also a safe value to pass to this API).
505 //
506 // We get ownership of the returned pointer, so can construct a new
507 // WpIBinder object from it.
Alice Ryhl8dde9bc2021-08-16 16:57:10 +0000508 sys::AIBinder_Weak_clone(self.0.as_ptr())
Stephen Craneddb3e6d2020-12-18 13:27:22 -0800509 };
Alice Ryhl8dde9bc2021-08-16 16:57:10 +0000510 Self(ptr::NonNull::new(ptr).expect("Unexpected null pointer from AIBinder_Weak_clone"))
Stephen Craneddb3e6d2020-12-18 13:27:22 -0800511 }
512}
513
514impl Ord for WpIBinder {
515 fn cmp(&self, other: &Self) -> Ordering {
516 let less_than = unsafe {
517 // Safety: WpIBinder always holds a valid `AIBinder_Weak` pointer,
518 // so this pointer is always safe to pass to `AIBinder_Weak_lt`
519 // (null is also safe to pass to this function, but we should never
520 // do that).
Alice Ryhl8dde9bc2021-08-16 16:57:10 +0000521 sys::AIBinder_Weak_lt(self.0.as_ptr(), other.0.as_ptr())
Stephen Craneddb3e6d2020-12-18 13:27:22 -0800522 };
523 let greater_than = unsafe {
524 // Safety: WpIBinder always holds a valid `AIBinder_Weak` pointer,
525 // so this pointer is always safe to pass to `AIBinder_Weak_lt`
526 // (null is also safe to pass to this function, but we should never
527 // do that).
Alice Ryhl8dde9bc2021-08-16 16:57:10 +0000528 sys::AIBinder_Weak_lt(other.0.as_ptr(), self.0.as_ptr())
Stephen Craneddb3e6d2020-12-18 13:27:22 -0800529 };
530 if !less_than && !greater_than {
531 Ordering::Equal
532 } else if less_than {
533 Ordering::Less
534 } else {
535 Ordering::Greater
536 }
537 }
538}
539
540impl PartialOrd for WpIBinder {
541 fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
542 Some(self.cmp(other))
543 }
544}
545
546impl PartialEq for WpIBinder {
547 fn eq(&self, other: &Self) -> bool {
548 self.cmp(other) == Ordering::Equal
549 }
550}
551
552impl Eq for WpIBinder {}
553
Andrew Walbran5e8dfa32020-12-16 12:50:06 +0000554impl Drop for WpIBinder {
555 fn drop(&mut self) {
556 unsafe {
557 // Safety: WpIBinder always holds a valid `AIBinder_Weak` pointer, so we
558 // know this pointer is safe to pass to `AIBinder_Weak_delete` here.
Alice Ryhl8dde9bc2021-08-16 16:57:10 +0000559 sys::AIBinder_Weak_delete(self.0.as_ptr());
Andrew Walbran5e8dfa32020-12-16 12:50:06 +0000560 }
561 }
562}
563
Stephen Crane2a3c2502020-06-16 17:48:35 -0700564/// Rust wrapper around DeathRecipient objects.
Alice Ryhlea9d9d22021-08-27 07:51:30 +0000565///
566/// The cookie in this struct represents an Arc<F> for the owned callback.
567/// This struct owns a ref-count of it, and so does every binder that we
568/// have been linked with.
Stephen Crane2a3c2502020-06-16 17:48:35 -0700569#[repr(C)]
570pub struct DeathRecipient {
571 recipient: *mut sys::AIBinder_DeathRecipient,
Alice Ryhlea9d9d22021-08-27 07:51:30 +0000572 cookie: *mut c_void,
573 vtable: &'static DeathRecipientVtable,
574}
575
576struct DeathRecipientVtable {
577 cookie_incr_refcount: unsafe extern "C" fn(*mut c_void),
578 cookie_decr_refcount: unsafe extern "C" fn(*mut c_void),
Stephen Crane2a3c2502020-06-16 17:48:35 -0700579}
580
581impl DeathRecipient {
582 /// Create a new death recipient that will call the given callback when its
583 /// associated object dies.
584 pub fn new<F>(callback: F) -> DeathRecipient
585 where
Alice Ryhlea9d9d22021-08-27 07:51:30 +0000586 F: Fn() + Send + Sync + 'static,
Stephen Crane2a3c2502020-06-16 17:48:35 -0700587 {
Alice Ryhlea9d9d22021-08-27 07:51:30 +0000588 let callback: *const F = Arc::into_raw(Arc::new(callback));
Stephen Crane2a3c2502020-06-16 17:48:35 -0700589 let recipient = unsafe {
590 // Safety: The function pointer is a valid death recipient callback.
591 //
592 // This call returns an owned `AIBinder_DeathRecipient` pointer
593 // which must be destroyed via `AIBinder_DeathRecipient_delete` when
594 // no longer needed.
595 sys::AIBinder_DeathRecipient_new(Some(Self::binder_died::<F>))
596 };
Alice Ryhlea9d9d22021-08-27 07:51:30 +0000597 unsafe {
598 // Safety: The function pointer is a valid onUnlinked callback.
599 //
600 // All uses of linkToDeath in this file correctly increment the
601 // ref-count that this onUnlinked callback will decrement.
602 sys::AIBinder_DeathRecipient_setOnUnlinked(recipient, Some(Self::cookie_decr_refcount::<F>));
603 }
Stephen Crane2a3c2502020-06-16 17:48:35 -0700604 DeathRecipient {
605 recipient,
Alice Ryhlea9d9d22021-08-27 07:51:30 +0000606 cookie: callback as *mut c_void,
607 vtable: &DeathRecipientVtable {
608 cookie_incr_refcount: Self::cookie_incr_refcount::<F>,
609 cookie_decr_refcount: Self::cookie_decr_refcount::<F>,
610 },
Stephen Crane2a3c2502020-06-16 17:48:35 -0700611 }
612 }
613
Alice Ryhlea9d9d22021-08-27 07:51:30 +0000614 /// Increment the ref-count for the cookie and return it.
615 ///
616 /// # Safety
617 ///
618 /// The caller must handle the returned ref-count correctly.
619 unsafe fn new_cookie(&self) -> *mut c_void {
620 (self.vtable.cookie_incr_refcount)(self.cookie);
621
622 // Return a raw pointer with ownership of a ref-count
623 self.cookie
624 }
625
Stephen Crane2a3c2502020-06-16 17:48:35 -0700626 /// Get the opaque cookie that identifies this death recipient.
627 ///
628 /// This cookie will be used to link and unlink this death recipient to a
629 /// binder object and will be passed to the `binder_died` callback as an
630 /// opaque userdata pointer.
631 fn get_cookie(&self) -> *mut c_void {
Alice Ryhlea9d9d22021-08-27 07:51:30 +0000632 self.cookie
Stephen Crane2a3c2502020-06-16 17:48:35 -0700633 }
634
635 /// Callback invoked from C++ when the binder object dies.
636 ///
637 /// # Safety
638 ///
Alice Ryhlea9d9d22021-08-27 07:51:30 +0000639 /// The `cookie` parameter must be the cookie for an Arc<F> and
640 /// the caller must hold a ref-count to it.
Stephen Crane2a3c2502020-06-16 17:48:35 -0700641 unsafe extern "C" fn binder_died<F>(cookie: *mut c_void)
642 where
Alice Ryhlea9d9d22021-08-27 07:51:30 +0000643 F: Fn() + Send + Sync + 'static,
Stephen Crane2a3c2502020-06-16 17:48:35 -0700644 {
Alice Ryhlea9d9d22021-08-27 07:51:30 +0000645 let callback = (cookie as *const F).as_ref().unwrap();
Stephen Crane2a3c2502020-06-16 17:48:35 -0700646 callback();
647 }
Alice Ryhlea9d9d22021-08-27 07:51:30 +0000648
649 /// Callback that decrements the ref-count.
650 /// This is invoked from C++ when a binder is unlinked.
651 ///
652 /// # Safety
653 ///
654 /// The `cookie` parameter must be the cookie for an Arc<F> and
655 /// the owner must give up a ref-count to it.
656 unsafe extern "C" fn cookie_decr_refcount<F>(cookie: *mut c_void)
657 where
658 F: Fn() + Send + Sync + 'static,
659 {
660 drop(Arc::from_raw(cookie as *const F));
661 }
662
663 /// Callback that increments the ref-count.
664 ///
665 /// # Safety
666 ///
667 /// The `cookie` parameter must be the cookie for an Arc<F> and
668 /// the owner must handle the created ref-count properly.
669 unsafe extern "C" fn cookie_incr_refcount<F>(cookie: *mut c_void)
670 where
671 F: Fn() + Send + Sync + 'static,
672 {
673 let arc = mem::ManuallyDrop::new(Arc::from_raw(cookie as *const F));
674 mem::forget(Arc::clone(&arc));
675 }
Stephen Crane2a3c2502020-06-16 17:48:35 -0700676}
677
678/// # Safety
679///
680/// A `DeathRecipient` is always constructed with a valid raw pointer to an
681/// `AIBinder_DeathRecipient`, so it is always type-safe to extract this
682/// pointer.
683unsafe impl AsNative<sys::AIBinder_DeathRecipient> for DeathRecipient {
684 fn as_native(&self) -> *const sys::AIBinder_DeathRecipient {
685 self.recipient
686 }
687
688 fn as_native_mut(&mut self) -> *mut sys::AIBinder_DeathRecipient {
689 self.recipient
690 }
691}
692
693impl Drop for DeathRecipient {
694 fn drop(&mut self) {
695 unsafe {
696 // Safety: `self.recipient` is always a valid, owned
697 // `AIBinder_DeathRecipient` pointer returned by
698 // `AIBinder_DeathRecipient_new` when `self` was created. This
699 // delete method can only be called once when `self` is dropped.
700 sys::AIBinder_DeathRecipient_delete(self.recipient);
Alice Ryhlea9d9d22021-08-27 07:51:30 +0000701
702 // Safety: We own a ref-count to the cookie, and so does every
703 // linked binder. This call gives up our ref-count. The linked
704 // binders should already have given up their ref-count, or should
705 // do so shortly.
706 (self.vtable.cookie_decr_refcount)(self.cookie)
Stephen Crane2a3c2502020-06-16 17:48:35 -0700707 }
708 }
709}
710
711/// Generic interface to remote binder objects.
712///
713/// Corresponds to the C++ `BpInterface` class.
714pub trait Proxy: Sized + Interface {
715 /// The Binder interface descriptor string.
716 ///
717 /// This string is a unique identifier for a Binder interface, and should be
718 /// the same between all implementations of that interface.
719 fn get_descriptor() -> &'static str;
720
721 /// Create a new interface from the given proxy, if it matches the expected
722 /// type of this interface.
723 fn from_binder(binder: SpIBinder) -> Result<Self>;
724}
725
726/// # Safety
727///
728/// This is a convenience method that wraps `AsNative` for `SpIBinder` to allow
729/// invocation of `IBinder` methods directly from `Interface` objects. It shares
730/// the same safety as the implementation for `SpIBinder`.
731unsafe impl<T: Proxy> AsNative<sys::AIBinder> for T {
732 fn as_native(&self) -> *const sys::AIBinder {
733 self.as_binder().as_native()
734 }
735
736 fn as_native_mut(&mut self) -> *mut sys::AIBinder {
737 self.as_binder().as_native_mut()
738 }
739}
740
741/// Retrieve an existing service, blocking for a few seconds if it doesn't yet
742/// exist.
743pub fn get_service(name: &str) -> Option<SpIBinder> {
744 let name = CString::new(name).ok()?;
745 unsafe {
746 // Safety: `AServiceManager_getService` returns either a null pointer or
747 // a valid pointer to an owned `AIBinder`. Either of these values is
748 // safe to pass to `SpIBinder::from_raw`.
749 SpIBinder::from_raw(sys::AServiceManager_getService(name.as_ptr()))
750 }
751}
752
Andrew Walbranc3ce5c32021-06-03 16:15:56 +0000753/// Retrieve an existing service, or start it if it is configured as a dynamic
754/// service and isn't yet started.
755pub fn wait_for_service(name: &str) -> Option<SpIBinder> {
756 let name = CString::new(name).ok()?;
757 unsafe {
758 // Safety: `AServiceManager_waitforService` returns either a null
759 // pointer or a valid pointer to an owned `AIBinder`. Either of these
760 // values is safe to pass to `SpIBinder::from_raw`.
761 SpIBinder::from_raw(sys::AServiceManager_waitForService(name.as_ptr()))
762 }
763}
764
Stephen Crane2a3c2502020-06-16 17:48:35 -0700765/// Retrieve an existing service for a particular interface, blocking for a few
766/// seconds if it doesn't yet exist.
Stephen Craneddb3e6d2020-12-18 13:27:22 -0800767pub fn get_interface<T: FromIBinder + ?Sized>(name: &str) -> Result<Strong<T>> {
Stephen Crane2a3c2502020-06-16 17:48:35 -0700768 let service = get_service(name);
769 match service {
770 Some(service) => FromIBinder::try_from(service),
771 None => Err(StatusCode::NAME_NOT_FOUND),
772 }
773}
774
Andrew Walbranc3ce5c32021-06-03 16:15:56 +0000775/// Retrieve an existing service for a particular interface, or start it if it
776/// is configured as a dynamic service and isn't yet started.
777pub fn wait_for_interface<T: FromIBinder + ?Sized>(name: &str) -> Result<Strong<T>> {
778 let service = wait_for_service(name);
779 match service {
780 Some(service) => FromIBinder::try_from(service),
781 None => Err(StatusCode::NAME_NOT_FOUND),
782 }
783}
784
Stephen Crane2a3c2502020-06-16 17:48:35 -0700785/// # Safety
786///
787/// `SpIBinder` guarantees that `binder` always contains a valid pointer to an
788/// `AIBinder`, so we can trivially extract this pointer here.
789unsafe impl AsNative<sys::AIBinder> for SpIBinder {
790 fn as_native(&self) -> *const sys::AIBinder {
Alice Ryhl8dde9bc2021-08-16 16:57:10 +0000791 self.0.as_ptr()
Stephen Crane2a3c2502020-06-16 17:48:35 -0700792 }
793
794 fn as_native_mut(&mut self) -> *mut sys::AIBinder {
Alice Ryhl8dde9bc2021-08-16 16:57:10 +0000795 self.0.as_ptr()
Stephen Crane2a3c2502020-06-16 17:48:35 -0700796 }
797}