blob: ce7370989d4025d08d1b1d413b4259e56383a630 [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;
Stephen Crane2a3c2502020-06-16 17:48:35 -070034use std::os::unix::io::AsRawFd;
35use std::ptr;
36
37/// A strong reference to a Binder remote object.
38///
39/// This struct encapsulates the generic C++ `sp<IBinder>` class. This wrapper
40/// is untyped; typed interface access is implemented by the AIDL compiler.
41pub struct SpIBinder(*mut sys::AIBinder);
42
Andrei Homescu2e3c1472020-08-11 16:35:40 -070043impl fmt::Debug for SpIBinder {
44 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
45 f.pad("SpIBinder")
46 }
47}
48
Stephen Crane2a3c2502020-06-16 17:48:35 -070049/// # Safety
50///
Stephen Cranef03fe3d2021-06-25 15:05:00 -070051/// An `SpIBinder` is an immutable handle to a C++ IBinder, which is thread-safe
Stephen Crane2a3c2502020-06-16 17:48:35 -070052unsafe impl Send for SpIBinder {}
53
Stephen Cranef03fe3d2021-06-25 15:05:00 -070054/// # Safety
55///
56/// An `SpIBinder` is an immutable handle to a C++ IBinder, which is thread-safe
57unsafe impl Sync for SpIBinder {}
58
Stephen Crane2a3c2502020-06-16 17:48:35 -070059impl SpIBinder {
60 /// Create an `SpIBinder` wrapper object from a raw `AIBinder` pointer.
61 ///
62 /// # Safety
63 ///
64 /// This constructor is safe iff `ptr` is a null pointer or a valid pointer
65 /// to an `AIBinder`.
66 ///
67 /// In the non-null case, this method conceptually takes ownership of a strong
68 /// reference to the object, so `AIBinder_incStrong` must have been called
69 /// on the pointer before passing it to this constructor. This is generally
70 /// done by Binder NDK methods that return an `AIBinder`, but care should be
71 /// taken to ensure this invariant.
72 ///
73 /// All `SpIBinder` objects that are constructed will hold a valid pointer
74 /// to an `AIBinder`, which will remain valid for the entire lifetime of the
75 /// `SpIBinder` (we keep a strong reference, and only decrement on drop).
76 pub(crate) unsafe fn from_raw(ptr: *mut sys::AIBinder) -> Option<Self> {
77 ptr.as_mut().map(|p| Self(p))
78 }
79
Stephen Craned58bce02020-07-07 12:26:02 -070080 /// Extract a raw `AIBinder` pointer from this wrapper.
81 ///
82 /// This method should _only_ be used for testing. Do not try to use the NDK
83 /// interface directly for anything else.
84 ///
85 /// # Safety
86 ///
87 /// The resulting pointer is valid only as long as the SpIBinder is alive.
88 /// The SpIBinder object retains ownership of the AIBinder and the caller
89 /// should not attempt to free the returned pointer.
90 pub unsafe fn as_raw(&self) -> *mut sys::AIBinder {
91 self.0
92 }
93
Stephen Crane2a3c2502020-06-16 17:48:35 -070094 /// Return true if this binder object is hosted in a different process than
95 /// the current one.
96 pub fn is_remote(&self) -> bool {
97 unsafe {
98 // Safety: `SpIBinder` guarantees that it always contains a valid
99 // `AIBinder` pointer.
100 sys::AIBinder_isRemote(self.as_native())
101 }
102 }
103
104 /// Try to convert this Binder object into a trait object for the given
105 /// Binder interface.
106 ///
107 /// If this object does not implement the expected interface, the error
108 /// `StatusCode::BAD_TYPE` is returned.
Stephen Craneddb3e6d2020-12-18 13:27:22 -0800109 pub fn into_interface<I: FromIBinder + Interface + ?Sized>(self) -> Result<Strong<I>> {
Stephen Crane2a3c2502020-06-16 17:48:35 -0700110 FromIBinder::try_from(self)
111 }
112
113 /// Return the interface class of this binder object, if associated with
114 /// one.
Stephen Crane669deb62020-09-10 17:31:39 -0700115 pub fn get_class(&mut self) -> Option<InterfaceClass> {
Stephen Crane2a3c2502020-06-16 17:48:35 -0700116 unsafe {
117 // Safety: `SpIBinder` guarantees that it always contains a valid
118 // `AIBinder` pointer. `AIBinder_getClass` returns either a null
119 // pointer or a valid pointer to an `AIBinder_Class`. After mapping
120 // null to None, we can safely construct an `InterfaceClass` if the
121 // pointer was non-null.
122 let class = sys::AIBinder_getClass(self.as_native_mut());
123 class.as_ref().map(|p| InterfaceClass::from_ptr(p))
124 }
125 }
Andrew Walbran8fe3ecc2020-12-15 11:29:58 +0000126
127 /// Creates a new weak reference to this binder object.
128 pub fn downgrade(&mut self) -> WpIBinder {
129 WpIBinder::new(self)
130 }
Stephen Crane2a3c2502020-06-16 17:48:35 -0700131}
132
Victor Hsiehd35d31d2021-06-03 11:24:31 -0700133pub mod unstable_api {
134 use super::{sys, SpIBinder};
135
136 /// A temporary API to allow the client to create a `SpIBinder` from a `sys::AIBinder`. This is
137 /// needed to bridge RPC binder, which doesn't have Rust API yet.
138 /// TODO(b/184872979): remove once the Rust API is created.
139 ///
140 /// # Safety
141 ///
142 /// See `SpIBinder::from_raw`.
143 pub unsafe fn new_spibinder(ptr: *mut sys::AIBinder) -> Option<SpIBinder> {
144 SpIBinder::from_raw(ptr)
145 }
146}
147
Stephen Crane2a3c2502020-06-16 17:48:35 -0700148/// An object that can be associate with an [`InterfaceClass`].
149pub trait AssociateClass {
150 /// Check if this object is a valid object for the given interface class
151 /// `I`.
152 ///
153 /// Returns `Some(self)` if this is a valid instance of the interface, and
154 /// `None` otherwise.
155 ///
156 /// Classes constructed by `InterfaceClass` are unique per type, so
157 /// repeatedly calling this method for the same `InterfaceClass` is allowed.
158 fn associate_class(&mut self, class: InterfaceClass) -> bool;
159}
160
161impl AssociateClass for SpIBinder {
162 fn associate_class(&mut self, class: InterfaceClass) -> bool {
163 unsafe {
164 // Safety: `SpIBinder` guarantees that it always contains a valid
165 // `AIBinder` pointer. An `InterfaceClass` can always be converted
166 // into a valid `AIBinder_Class` pointer, so these parameters are
167 // always safe.
168 sys::AIBinder_associateClass(self.as_native_mut(), class.into())
169 }
170 }
171}
172
Stephen Craneddb3e6d2020-12-18 13:27:22 -0800173impl Ord for SpIBinder {
174 fn cmp(&self, other: &Self) -> Ordering {
175 let less_than = unsafe {
176 // Safety: SpIBinder always holds a valid `AIBinder` pointer, so
177 // this pointer is always safe to pass to `AIBinder_lt` (null is
178 // also safe to pass to this function, but we should never do that).
179 sys::AIBinder_lt(self.0, other.0)
180 };
181 let greater_than = unsafe {
182 // Safety: SpIBinder always holds a valid `AIBinder` pointer, so
183 // this pointer is always safe to pass to `AIBinder_lt` (null is
184 // also safe to pass to this function, but we should never do that).
185 sys::AIBinder_lt(other.0, self.0)
186 };
187 if !less_than && !greater_than {
188 Ordering::Equal
189 } else if less_than {
190 Ordering::Less
191 } else {
192 Ordering::Greater
193 }
194 }
195}
196
197impl PartialOrd for SpIBinder {
198 fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
199 Some(self.cmp(other))
200 }
201}
202
Stephen Crane994a0f02020-08-11 14:47:29 -0700203impl PartialEq for SpIBinder {
204 fn eq(&self, other: &Self) -> bool {
205 ptr::eq(self.0, other.0)
206 }
207}
208
209impl Eq for SpIBinder {}
210
Stephen Crane2a3c2502020-06-16 17:48:35 -0700211impl Clone for SpIBinder {
212 fn clone(&self) -> Self {
213 unsafe {
214 // Safety: Cloning a strong reference must increment the reference
215 // count. We are guaranteed by the `SpIBinder` constructor
216 // invariants that `self.0` is always a valid `AIBinder` pointer.
217 sys::AIBinder_incStrong(self.0);
218 }
219 Self(self.0)
220 }
221}
222
223impl Drop for SpIBinder {
224 // We hold a strong reference to the IBinder in SpIBinder and need to give up
225 // this reference on drop.
226 fn drop(&mut self) {
227 unsafe {
228 // Safety: SpIBinder always holds a valid `AIBinder` pointer, so we
229 // know this pointer is safe to pass to `AIBinder_decStrong` here.
230 sys::AIBinder_decStrong(self.as_native_mut());
231 }
232 }
233}
234
Andrew Walbran12400d82021-03-04 17:04:34 +0000235impl<T: AsNative<sys::AIBinder>> IBinderInternal for T {
Alice Ryhlfeba6ca2021-08-19 10:47:04 +0000236 fn prepare_transact(&self) -> Result<Parcel> {
Stephen Crane2a3c2502020-06-16 17:48:35 -0700237 let mut input = ptr::null_mut();
238 let status = unsafe {
239 // Safety: `SpIBinder` guarantees that `self` always contains a
240 // valid pointer to an `AIBinder`. It is safe to cast from an
241 // immutable pointer to a mutable pointer here, because
242 // `AIBinder_prepareTransaction` only calls immutable `AIBinder`
243 // methods but the parameter is unfortunately not marked as const.
244 //
245 // After the call, input will be either a valid, owned `AParcel`
246 // pointer, or null.
247 sys::AIBinder_prepareTransaction(self.as_native() as *mut sys::AIBinder, &mut input)
248 };
Alice Ryhlfeba6ca2021-08-19 10:47:04 +0000249
Stephen Crane2a3c2502020-06-16 17:48:35 -0700250 status_result(status)?;
Alice Ryhlfeba6ca2021-08-19 10:47:04 +0000251
252 unsafe {
Stephen Crane2a3c2502020-06-16 17:48:35 -0700253 // Safety: At this point, `input` is either a valid, owned `AParcel`
254 // pointer, or null. `Parcel::owned` safely handles both cases,
255 // taking ownership of the parcel.
Alice Ryhlfeba6ca2021-08-19 10:47:04 +0000256 Parcel::owned(input).ok_or(StatusCode::UNEXPECTED_NULL)
257 }
258 }
259
260 fn submit_transact(
261 &self,
262 code: TransactionCode,
263 data: Parcel,
264 flags: TransactionFlags,
265 ) -> Result<Parcel> {
Stephen Crane2a3c2502020-06-16 17:48:35 -0700266 let mut reply = ptr::null_mut();
Alice Ryhlfeba6ca2021-08-19 10:47:04 +0000267 assert!(data.is_owned());
Stephen Crane2a3c2502020-06-16 17:48:35 -0700268 let status = unsafe {
269 // Safety: `SpIBinder` guarantees that `self` always contains a
270 // valid pointer to an `AIBinder`. Although `IBinder::transact` is
271 // not a const method, it is still safe to cast our immutable
272 // pointer to mutable for the call. First, `IBinder::transact` is
273 // thread-safe, so concurrency is not an issue. The only way that
274 // `transact` can affect any visible, mutable state in the current
275 // process is by calling `onTransact` for a local service. However,
276 // in order for transactions to be thread-safe, this method must
277 // dynamically lock its data before modifying it. We enforce this
278 // property in Rust by requiring `Sync` for remotable objects and
279 // only providing `on_transact` with an immutable reference to
280 // `self`.
281 //
Alice Ryhlfeba6ca2021-08-19 10:47:04 +0000282 // This call takes ownership of the `data` parcel pointer, and
Stephen Crane2a3c2502020-06-16 17:48:35 -0700283 // passes ownership of the `reply` out parameter to its caller. It
284 // does not affect ownership of the `binder` parameter.
285 sys::AIBinder_transact(
286 self.as_native() as *mut sys::AIBinder,
287 code,
Alice Ryhlfeba6ca2021-08-19 10:47:04 +0000288 &mut data.into_raw(),
Stephen Crane2a3c2502020-06-16 17:48:35 -0700289 &mut reply,
290 flags,
291 )
292 };
293 status_result(status)?;
294
295 unsafe {
296 // Safety: `reply` is either a valid `AParcel` pointer or null
297 // after the call to `AIBinder_transact` above, so we can
298 // construct a `Parcel` out of it. `AIBinder_transact` passes
299 // ownership of the `reply` parcel to Rust, so we need to
300 // construct an owned variant. `Parcel::owned` takes ownership
301 // of the parcel pointer.
302 Parcel::owned(reply).ok_or(StatusCode::UNEXPECTED_NULL)
303 }
304 }
305
306 fn is_binder_alive(&self) -> bool {
307 unsafe {
308 // Safety: `SpIBinder` guarantees that `self` always contains a
309 // valid pointer to an `AIBinder`.
310 //
311 // This call does not affect ownership of its pointer parameter.
312 sys::AIBinder_isAlive(self.as_native())
313 }
314 }
315
316 fn ping_binder(&mut self) -> Result<()> {
317 let status = unsafe {
318 // Safety: `SpIBinder` guarantees that `self` always contains a
319 // valid pointer to an `AIBinder`.
320 //
321 // This call does not affect ownership of its pointer parameter.
322 sys::AIBinder_ping(self.as_native_mut())
323 };
324 status_result(status)
325 }
326
Janis Danisevskis798a09a2020-08-18 08:35:38 -0700327 fn set_requesting_sid(&mut self, enable: bool) {
Andrew Walbran12400d82021-03-04 17:04:34 +0000328 unsafe { sys::AIBinder_setRequestingSid(self.as_native_mut(), enable) };
Janis Danisevskis798a09a2020-08-18 08:35:38 -0700329 }
330
Stephen Crane2a3c2502020-06-16 17:48:35 -0700331 fn dump<F: AsRawFd>(&mut self, fp: &F, args: &[&str]) -> Result<()> {
332 let args: Vec<_> = args.iter().map(|a| CString::new(*a).unwrap()).collect();
333 let mut arg_ptrs: Vec<_> = args.iter().map(|a| a.as_ptr()).collect();
334 let status = unsafe {
335 // Safety: `SpIBinder` guarantees that `self` always contains a
336 // valid pointer to an `AIBinder`. `AsRawFd` guarantees that the
337 // file descriptor parameter is always be a valid open file. The
338 // `args` pointer parameter is a valid pointer to an array of C
339 // strings that will outlive the call since `args` lives for the
340 // whole function scope.
341 //
342 // This call does not affect ownership of its binder pointer
343 // parameter and does not take ownership of the file or args array
344 // parameters.
345 sys::AIBinder_dump(
346 self.as_native_mut(),
347 fp.as_raw_fd(),
348 arg_ptrs.as_mut_ptr(),
349 arg_ptrs.len().try_into().unwrap(),
350 )
351 };
352 status_result(status)
353 }
354
355 fn get_extension(&mut self) -> Result<Option<SpIBinder>> {
356 let mut out = ptr::null_mut();
357 let status = unsafe {
358 // Safety: `SpIBinder` guarantees that `self` always contains a
359 // valid pointer to an `AIBinder`. After this call, the `out`
360 // parameter will be either null, or a valid pointer to an
361 // `AIBinder`.
362 //
363 // This call passes ownership of the out pointer to its caller
364 // (assuming it is set to a non-null value).
365 sys::AIBinder_getExtension(self.as_native_mut(), &mut out)
366 };
367 let ibinder = unsafe {
368 // Safety: The call above guarantees that `out` is either null or a
369 // valid, owned pointer to an `AIBinder`, both of which are safe to
370 // pass to `SpIBinder::from_raw`.
371 SpIBinder::from_raw(out)
372 };
373
374 status_result(status)?;
375 Ok(ibinder)
376 }
Andrew Walbran12400d82021-03-04 17:04:34 +0000377}
Stephen Crane2a3c2502020-06-16 17:48:35 -0700378
Andrew Walbran12400d82021-03-04 17:04:34 +0000379impl<T: AsNative<sys::AIBinder>> IBinder for T {
Stephen Crane2a3c2502020-06-16 17:48:35 -0700380 fn link_to_death(&mut self, recipient: &mut DeathRecipient) -> Result<()> {
381 status_result(unsafe {
382 // Safety: `SpIBinder` guarantees that `self` always contains a
383 // valid pointer to an `AIBinder`. `recipient` can always be
384 // converted into a valid pointer to an
Stephen Craneddb3e6d2020-12-18 13:27:22 -0800385 // `AIBinder_DeathRecipient`. Any value is safe to pass as the
Stephen Crane2a3c2502020-06-16 17:48:35 -0700386 // cookie, although we depend on this value being set by
387 // `get_cookie` when the death recipient callback is called.
388 sys::AIBinder_linkToDeath(
389 self.as_native_mut(),
390 recipient.as_native_mut(),
391 recipient.get_cookie(),
392 )
393 })
394 }
395
396 fn unlink_to_death(&mut self, recipient: &mut DeathRecipient) -> Result<()> {
397 status_result(unsafe {
398 // Safety: `SpIBinder` guarantees that `self` always contains a
399 // valid pointer to an `AIBinder`. `recipient` can always be
400 // converted into a valid pointer to an
Stephen Craneddb3e6d2020-12-18 13:27:22 -0800401 // `AIBinder_DeathRecipient`. Any value is safe to pass as the
Stephen Crane2a3c2502020-06-16 17:48:35 -0700402 // cookie, although we depend on this value being set by
403 // `get_cookie` when the death recipient callback is called.
404 sys::AIBinder_unlinkToDeath(
405 self.as_native_mut(),
406 recipient.as_native_mut(),
407 recipient.get_cookie(),
408 )
409 })
410 }
411}
412
413impl Serialize for SpIBinder {
414 fn serialize(&self, parcel: &mut Parcel) -> Result<()> {
415 parcel.write_binder(Some(self))
416 }
417}
418
419impl SerializeOption for SpIBinder {
420 fn serialize_option(this: Option<&Self>, parcel: &mut Parcel) -> Result<()> {
421 parcel.write_binder(this)
422 }
423}
424
425impl SerializeArray for SpIBinder {}
426impl SerializeArray for Option<&SpIBinder> {}
427
428impl Deserialize for SpIBinder {
429 fn deserialize(parcel: &Parcel) -> Result<SpIBinder> {
Andrei Homescu32814372020-08-20 15:36:08 -0700430 parcel
431 .read_binder()
432 .transpose()
433 .unwrap_or(Err(StatusCode::UNEXPECTED_NULL))
Stephen Crane2a3c2502020-06-16 17:48:35 -0700434 }
435}
436
437impl DeserializeOption for SpIBinder {
438 fn deserialize_option(parcel: &Parcel) -> Result<Option<SpIBinder>> {
439 parcel.read_binder()
440 }
441}
442
443impl DeserializeArray for SpIBinder {}
444impl DeserializeArray for Option<SpIBinder> {}
445
446/// A weak reference to a Binder remote object.
447///
Andrew Walbran8fe3ecc2020-12-15 11:29:58 +0000448/// This struct encapsulates the generic C++ `wp<IBinder>` class. This wrapper
449/// is untyped; typed interface access is implemented by the AIDL compiler.
Stephen Crane2a3c2502020-06-16 17:48:35 -0700450pub struct WpIBinder(*mut sys::AIBinder_Weak);
451
Andrew Walbran8fe3ecc2020-12-15 11:29:58 +0000452impl fmt::Debug for WpIBinder {
453 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
454 f.pad("WpIBinder")
455 }
456}
457
458/// # Safety
459///
Stephen Cranef03fe3d2021-06-25 15:05:00 -0700460/// A `WpIBinder` is an immutable handle to a C++ IBinder, which is thread-safe.
Andrew Walbran8fe3ecc2020-12-15 11:29:58 +0000461unsafe impl Send for WpIBinder {}
462
Stephen Cranef03fe3d2021-06-25 15:05:00 -0700463/// # Safety
464///
465/// A `WpIBinder` is an immutable handle to a C++ IBinder, which is thread-safe.
466unsafe impl Sync for WpIBinder {}
467
Stephen Crane2a3c2502020-06-16 17:48:35 -0700468impl WpIBinder {
469 /// Create a new weak reference from an object that can be converted into a
470 /// raw `AIBinder` pointer.
Andrew Walbran8fe3ecc2020-12-15 11:29:58 +0000471 fn new<B: AsNative<sys::AIBinder>>(binder: &mut B) -> WpIBinder {
Stephen Crane2a3c2502020-06-16 17:48:35 -0700472 let ptr = unsafe {
473 // Safety: `SpIBinder` guarantees that `binder` always contains a
474 // valid pointer to an `AIBinder`.
475 sys::AIBinder_Weak_new(binder.as_native_mut())
476 };
477 assert!(!ptr.is_null());
478 Self(ptr)
479 }
Stephen Crane994a0f02020-08-11 14:47:29 -0700480
481 /// Promote this weak reference to a strong reference to the binder object.
482 pub fn promote(&self) -> Option<SpIBinder> {
483 unsafe {
484 // Safety: `WpIBinder` always contains a valid weak reference, so we
485 // can pass this pointer to `AIBinder_Weak_promote`. Returns either
486 // null or an AIBinder owned by the caller, both of which are valid
487 // to pass to `SpIBinder::from_raw`.
488 let ptr = sys::AIBinder_Weak_promote(self.0);
489 SpIBinder::from_raw(ptr)
490 }
491 }
Stephen Crane2a3c2502020-06-16 17:48:35 -0700492}
493
Stephen Craneddb3e6d2020-12-18 13:27:22 -0800494impl Clone for WpIBinder {
495 fn clone(&self) -> Self {
496 let ptr = unsafe {
497 // Safety: WpIBinder always holds a valid `AIBinder_Weak` pointer,
498 // so this pointer is always safe to pass to `AIBinder_Weak_clone`
499 // (although null is also a safe value to pass to this API).
500 //
501 // We get ownership of the returned pointer, so can construct a new
502 // WpIBinder object from it.
503 sys::AIBinder_Weak_clone(self.0)
504 };
Andrew Walbran12400d82021-03-04 17:04:34 +0000505 assert!(
506 !ptr.is_null(),
507 "Unexpected null pointer from AIBinder_Weak_clone"
508 );
Stephen Craneddb3e6d2020-12-18 13:27:22 -0800509 Self(ptr)
510 }
511}
512
513impl Ord for WpIBinder {
514 fn cmp(&self, other: &Self) -> Ordering {
515 let less_than = unsafe {
516 // Safety: WpIBinder always holds a valid `AIBinder_Weak` pointer,
517 // so this pointer is always safe to pass to `AIBinder_Weak_lt`
518 // (null is also safe to pass to this function, but we should never
519 // do that).
520 sys::AIBinder_Weak_lt(self.0, other.0)
521 };
522 let greater_than = unsafe {
523 // Safety: WpIBinder always holds a valid `AIBinder_Weak` pointer,
524 // so this pointer is always safe to pass to `AIBinder_Weak_lt`
525 // (null is also safe to pass to this function, but we should never
526 // do that).
527 sys::AIBinder_Weak_lt(other.0, self.0)
528 };
529 if !less_than && !greater_than {
530 Ordering::Equal
531 } else if less_than {
532 Ordering::Less
533 } else {
534 Ordering::Greater
535 }
536 }
537}
538
539impl PartialOrd for WpIBinder {
540 fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
541 Some(self.cmp(other))
542 }
543}
544
545impl PartialEq for WpIBinder {
546 fn eq(&self, other: &Self) -> bool {
547 self.cmp(other) == Ordering::Equal
548 }
549}
550
551impl Eq for WpIBinder {}
552
Andrew Walbran5e8dfa32020-12-16 12:50:06 +0000553impl Drop for WpIBinder {
554 fn drop(&mut self) {
555 unsafe {
556 // Safety: WpIBinder always holds a valid `AIBinder_Weak` pointer, so we
557 // know this pointer is safe to pass to `AIBinder_Weak_delete` here.
558 sys::AIBinder_Weak_delete(self.0);
559 }
560 }
561}
562
Stephen Crane2a3c2502020-06-16 17:48:35 -0700563/// Rust wrapper around DeathRecipient objects.
564#[repr(C)]
565pub struct DeathRecipient {
566 recipient: *mut sys::AIBinder_DeathRecipient,
567 callback: Box<dyn Fn() + Send + 'static>,
568}
569
570impl DeathRecipient {
571 /// Create a new death recipient that will call the given callback when its
572 /// associated object dies.
573 pub fn new<F>(callback: F) -> DeathRecipient
574 where
575 F: Fn() + Send + 'static,
576 {
577 let callback = Box::new(callback);
578 let recipient = unsafe {
579 // Safety: The function pointer is a valid death recipient callback.
580 //
581 // This call returns an owned `AIBinder_DeathRecipient` pointer
582 // which must be destroyed via `AIBinder_DeathRecipient_delete` when
583 // no longer needed.
584 sys::AIBinder_DeathRecipient_new(Some(Self::binder_died::<F>))
585 };
586 DeathRecipient {
587 recipient,
588 callback,
589 }
590 }
591
592 /// Get the opaque cookie that identifies this death recipient.
593 ///
594 /// This cookie will be used to link and unlink this death recipient to a
595 /// binder object and will be passed to the `binder_died` callback as an
596 /// opaque userdata pointer.
597 fn get_cookie(&self) -> *mut c_void {
598 &*self.callback as *const _ as *mut c_void
599 }
600
601 /// Callback invoked from C++ when the binder object dies.
602 ///
603 /// # Safety
604 ///
605 /// The `cookie` parameter must have been created with the `get_cookie`
606 /// method of this object.
607 unsafe extern "C" fn binder_died<F>(cookie: *mut c_void)
608 where
609 F: Fn() + Send + 'static,
610 {
611 let callback = (cookie as *mut F).as_ref().unwrap();
612 callback();
613 }
614}
615
616/// # Safety
617///
618/// A `DeathRecipient` is always constructed with a valid raw pointer to an
619/// `AIBinder_DeathRecipient`, so it is always type-safe to extract this
620/// pointer.
621unsafe impl AsNative<sys::AIBinder_DeathRecipient> for DeathRecipient {
622 fn as_native(&self) -> *const sys::AIBinder_DeathRecipient {
623 self.recipient
624 }
625
626 fn as_native_mut(&mut self) -> *mut sys::AIBinder_DeathRecipient {
627 self.recipient
628 }
629}
630
631impl Drop for DeathRecipient {
632 fn drop(&mut self) {
633 unsafe {
634 // Safety: `self.recipient` is always a valid, owned
635 // `AIBinder_DeathRecipient` pointer returned by
636 // `AIBinder_DeathRecipient_new` when `self` was created. This
637 // delete method can only be called once when `self` is dropped.
638 sys::AIBinder_DeathRecipient_delete(self.recipient);
639 }
640 }
641}
642
643/// Generic interface to remote binder objects.
644///
645/// Corresponds to the C++ `BpInterface` class.
646pub trait Proxy: Sized + Interface {
647 /// The Binder interface descriptor string.
648 ///
649 /// This string is a unique identifier for a Binder interface, and should be
650 /// the same between all implementations of that interface.
651 fn get_descriptor() -> &'static str;
652
653 /// Create a new interface from the given proxy, if it matches the expected
654 /// type of this interface.
655 fn from_binder(binder: SpIBinder) -> Result<Self>;
656}
657
658/// # Safety
659///
660/// This is a convenience method that wraps `AsNative` for `SpIBinder` to allow
661/// invocation of `IBinder` methods directly from `Interface` objects. It shares
662/// the same safety as the implementation for `SpIBinder`.
663unsafe impl<T: Proxy> AsNative<sys::AIBinder> for T {
664 fn as_native(&self) -> *const sys::AIBinder {
665 self.as_binder().as_native()
666 }
667
668 fn as_native_mut(&mut self) -> *mut sys::AIBinder {
669 self.as_binder().as_native_mut()
670 }
671}
672
673/// Retrieve an existing service, blocking for a few seconds if it doesn't yet
674/// exist.
675pub fn get_service(name: &str) -> Option<SpIBinder> {
676 let name = CString::new(name).ok()?;
677 unsafe {
678 // Safety: `AServiceManager_getService` returns either a null pointer or
679 // a valid pointer to an owned `AIBinder`. Either of these values is
680 // safe to pass to `SpIBinder::from_raw`.
681 SpIBinder::from_raw(sys::AServiceManager_getService(name.as_ptr()))
682 }
683}
684
Andrew Walbranc3ce5c32021-06-03 16:15:56 +0000685/// Retrieve an existing service, or start it if it is configured as a dynamic
686/// service and isn't yet started.
687pub fn wait_for_service(name: &str) -> Option<SpIBinder> {
688 let name = CString::new(name).ok()?;
689 unsafe {
690 // Safety: `AServiceManager_waitforService` returns either a null
691 // pointer or a valid pointer to an owned `AIBinder`. Either of these
692 // values is safe to pass to `SpIBinder::from_raw`.
693 SpIBinder::from_raw(sys::AServiceManager_waitForService(name.as_ptr()))
694 }
695}
696
Stephen Crane2a3c2502020-06-16 17:48:35 -0700697/// Retrieve an existing service for a particular interface, blocking for a few
698/// seconds if it doesn't yet exist.
Stephen Craneddb3e6d2020-12-18 13:27:22 -0800699pub fn get_interface<T: FromIBinder + ?Sized>(name: &str) -> Result<Strong<T>> {
Stephen Crane2a3c2502020-06-16 17:48:35 -0700700 let service = get_service(name);
701 match service {
702 Some(service) => FromIBinder::try_from(service),
703 None => Err(StatusCode::NAME_NOT_FOUND),
704 }
705}
706
Andrew Walbranc3ce5c32021-06-03 16:15:56 +0000707/// Retrieve an existing service for a particular interface, or start it if it
708/// is configured as a dynamic service and isn't yet started.
709pub fn wait_for_interface<T: FromIBinder + ?Sized>(name: &str) -> Result<Strong<T>> {
710 let service = wait_for_service(name);
711 match service {
712 Some(service) => FromIBinder::try_from(service),
713 None => Err(StatusCode::NAME_NOT_FOUND),
714 }
715}
716
Stephen Crane2a3c2502020-06-16 17:48:35 -0700717/// # Safety
718///
719/// `SpIBinder` guarantees that `binder` always contains a valid pointer to an
720/// `AIBinder`, so we can trivially extract this pointer here.
721unsafe impl AsNative<sys::AIBinder> for SpIBinder {
722 fn as_native(&self) -> *const sys::AIBinder {
723 self.0
724 }
725
726 fn as_native_mut(&mut self) -> *mut sys::AIBinder {
727 self.0
728 }
729}