blob: 0ed43bb5359dd3783f878c58b13aa17feecc56f1 [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//! Trait definitions for binder objects
18
Stephen Craneddb3e6d2020-12-18 13:27:22 -080019use crate::error::{status_t, Result, StatusCode};
Alice Ryhl268458c2021-09-15 12:56:10 +000020use crate::parcel::{OwnedParcel, Parcel};
Stephen Craneddb3e6d2020-12-18 13:27:22 -080021use crate::proxy::{DeathRecipient, SpIBinder, WpIBinder};
Stephen Crane2a3c2502020-06-16 17:48:35 -070022use crate::sys;
23
Stephen Craneddb3e6d2020-12-18 13:27:22 -080024use std::borrow::Borrow;
25use std::cmp::Ordering;
Andrei Homescuee132fa2021-09-03 02:36:17 +000026use std::convert::TryFrom;
Stephen Crane669deb62020-09-10 17:31:39 -070027use std::ffi::{c_void, CStr, CString};
Stephen Craneddb3e6d2020-12-18 13:27:22 -080028use std::fmt;
Stephen Crane2a3297f2021-06-11 16:48:10 -070029use std::fs::File;
Stephen Craneddb3e6d2020-12-18 13:27:22 -080030use std::marker::PhantomData;
31use std::ops::Deref;
Stephen Crane669deb62020-09-10 17:31:39 -070032use std::os::raw::c_char;
Stephen Crane2a3c2502020-06-16 17:48:35 -070033use std::os::unix::io::AsRawFd;
34use std::ptr;
35
36/// Binder action to perform.
37///
Andrew Walbran12400d82021-03-04 17:04:34 +000038/// This must be a number between [`FIRST_CALL_TRANSACTION`] and
39/// [`LAST_CALL_TRANSACTION`].
Stephen Crane2a3c2502020-06-16 17:48:35 -070040pub type TransactionCode = u32;
41
42/// Additional operation flags.
43///
Andrew Walbran12400d82021-03-04 17:04:34 +000044/// `FLAG_*` values.
Stephen Crane2a3c2502020-06-16 17:48:35 -070045pub type TransactionFlags = u32;
46
47/// Super-trait for Binder interfaces.
48///
49/// This trait allows conversion of a Binder interface trait object into an
50/// IBinder object for IPC calls. All Binder remotable interface (i.e. AIDL
51/// interfaces) must implement this trait.
52///
53/// This is equivalent `IInterface` in C++.
Stephen Cranef03fe3d2021-06-25 15:05:00 -070054pub trait Interface: Send + Sync {
Stephen Crane2a3c2502020-06-16 17:48:35 -070055 /// Convert this binder object into a generic [`SpIBinder`] reference.
56 fn as_binder(&self) -> SpIBinder {
57 panic!("This object was not a Binder object and cannot be converted into an SpIBinder.")
58 }
Stephen Crane2a3297f2021-06-11 16:48:10 -070059
60 /// Dump transaction handler for this Binder object.
61 ///
62 /// This handler is a no-op by default and should be implemented for each
63 /// Binder service struct that wishes to respond to dump transactions.
64 fn dump(&self, _file: &File, _args: &[&CStr]) -> Result<()> {
65 Ok(())
66 }
Stephen Crane2a3c2502020-06-16 17:48:35 -070067}
68
Stephen Craneff7f03a2021-02-25 16:04:22 -080069/// Interface stability promise
70///
71/// An interface can promise to be a stable vendor interface ([`Vintf`]), or
72/// makes no stability guarantees ([`Local`]). [`Local`] is
73/// currently the default stability.
Andrei Homescuee132fa2021-09-03 02:36:17 +000074#[derive(Debug, Copy, Clone, PartialEq, Eq, PartialOrd, Ord)]
Stephen Craneff7f03a2021-02-25 16:04:22 -080075pub enum Stability {
76 /// Default stability, visible to other modules in the same compilation
77 /// context (e.g. modules on system.img)
78 Local,
79
80 /// A Vendor Interface Object, which promises to be stable
81 Vintf,
82}
83
84impl Default for Stability {
85 fn default() -> Self {
86 Stability::Local
87 }
88}
89
Andrei Homescuee132fa2021-09-03 02:36:17 +000090impl From<Stability> for i32 {
91 fn from(stability: Stability) -> i32 {
92 use Stability::*;
93 match stability {
94 Local => 0,
95 Vintf => 1,
96 }
97 }
98}
99
100impl TryFrom<i32> for Stability {
101 type Error = StatusCode;
102 fn try_from(stability: i32) -> Result<Stability> {
103 use Stability::*;
104 match stability {
105 0 => Ok(Local),
106 1 => Ok(Vintf),
107 _ => Err(StatusCode::BAD_VALUE)
108 }
109 }
110}
111
Stephen Crane2a3c2502020-06-16 17:48:35 -0700112/// A local service that can be remotable via Binder.
113///
114/// An object that implement this interface made be made into a Binder service
115/// via `Binder::new(object)`.
116///
117/// This is a low-level interface that should normally be automatically
118/// generated from AIDL via the [`declare_binder_interface!`] macro. When using
119/// the AIDL backend, users need only implement the high-level AIDL-defined
120/// interface. The AIDL compiler then generates a container struct that wraps
121/// the user-defined service and implements `Remotable`.
Andrei Homescu2c674b02020-08-07 22:12:27 -0700122pub trait Remotable: Send + Sync {
Stephen Crane2a3c2502020-06-16 17:48:35 -0700123 /// The Binder interface descriptor string.
124 ///
125 /// This string is a unique identifier for a Binder interface, and should be
126 /// the same between all implementations of that interface.
127 fn get_descriptor() -> &'static str;
128
129 /// Handle and reply to a request to invoke a transaction on this object.
130 ///
131 /// `reply` may be [`None`] if the sender does not expect a reply.
132 fn on_transact(&self, code: TransactionCode, data: &Parcel, reply: &mut Parcel) -> Result<()>;
133
Stephen Crane2a3297f2021-06-11 16:48:10 -0700134 /// Handle a request to invoke the dump transaction on this
135 /// object.
136 fn on_dump(&self, file: &File, args: &[&CStr]) -> Result<()>;
137
Stephen Crane2a3c2502020-06-16 17:48:35 -0700138 /// Retrieve the class of this remote object.
139 ///
140 /// This method should always return the same InterfaceClass for the same
141 /// type.
142 fn get_class() -> InterfaceClass;
143}
144
Andrew Walbran12400d82021-03-04 17:04:34 +0000145/// First transaction code available for user commands (inclusive)
146pub const FIRST_CALL_TRANSACTION: TransactionCode = sys::FIRST_CALL_TRANSACTION;
147/// Last transaction code available for user commands (inclusive)
148pub const LAST_CALL_TRANSACTION: TransactionCode = sys::LAST_CALL_TRANSACTION;
149
150/// Corresponds to TF_ONE_WAY -- an asynchronous call.
151pub const FLAG_ONEWAY: TransactionFlags = sys::FLAG_ONEWAY;
152/// Corresponds to TF_CLEAR_BUF -- clear transaction buffers after call is made.
153pub const FLAG_CLEAR_BUF: TransactionFlags = sys::FLAG_CLEAR_BUF;
Stephen Craneff7f03a2021-02-25 16:04:22 -0800154/// Set to the vendor flag if we are building for the VNDK, 0 otherwise
155pub const FLAG_PRIVATE_LOCAL: TransactionFlags = sys::FLAG_PRIVATE_LOCAL;
Andrew Walbran12400d82021-03-04 17:04:34 +0000156
157/// Internal interface of binder local or remote objects for making
158/// transactions.
Stephen Crane2a3c2502020-06-16 17:48:35 -0700159///
Andrew Walbran12400d82021-03-04 17:04:34 +0000160/// This trait corresponds to the parts of the interface of the C++ `IBinder`
161/// class which are internal implementation details.
162pub trait IBinderInternal: IBinder {
Stephen Crane2a3c2502020-06-16 17:48:35 -0700163 /// Is this object still alive?
164 fn is_binder_alive(&self) -> bool;
165
166 /// Send a ping transaction to this object
167 fn ping_binder(&mut self) -> Result<()>;
168
Janis Danisevskis798a09a2020-08-18 08:35:38 -0700169 /// Indicate that the service intends to receive caller security contexts.
Janis Danisevskis1323d512021-11-09 07:48:08 -0800170 #[cfg(not(android_vndk))]
Janis Danisevskis798a09a2020-08-18 08:35:38 -0700171 fn set_requesting_sid(&mut self, enable: bool);
172
Stephen Crane2a3c2502020-06-16 17:48:35 -0700173 /// Dump this object to the given file handle
174 fn dump<F: AsRawFd>(&mut self, fp: &F, args: &[&str]) -> Result<()>;
175
176 /// Get a new interface that exposes additional extension functionality, if
177 /// available.
178 fn get_extension(&mut self) -> Result<Option<SpIBinder>>;
179
Alice Ryhlfeba6ca2021-08-19 10:47:04 +0000180 /// Create a Parcel that can be used with `submit_transact`.
Alice Ryhl268458c2021-09-15 12:56:10 +0000181 fn prepare_transact(&self) -> Result<OwnedParcel>;
Alice Ryhlfeba6ca2021-08-19 10:47:04 +0000182
Stephen Crane2a3c2502020-06-16 17:48:35 -0700183 /// Perform a generic operation with the object.
184 ///
Alice Ryhl268458c2021-09-15 12:56:10 +0000185 /// The provided [`OwnedParcel`] must have been created by a call to
Alice Ryhlfeba6ca2021-08-19 10:47:04 +0000186 /// `prepare_transact` on the same binder.
187 ///
188 /// # Arguments
189 ///
190 /// * `code` - Transaction code for the operation.
Alice Ryhl268458c2021-09-15 12:56:10 +0000191 /// * `data` - [`OwnedParcel`] with input data.
Alice Ryhlfeba6ca2021-08-19 10:47:04 +0000192 /// * `flags` - Transaction flags, e.g. marking the transaction as
193 /// asynchronous ([`FLAG_ONEWAY`](FLAG_ONEWAY)).
194 fn submit_transact(
195 &self,
196 code: TransactionCode,
Alice Ryhl268458c2021-09-15 12:56:10 +0000197 data: OwnedParcel,
Alice Ryhlfeba6ca2021-08-19 10:47:04 +0000198 flags: TransactionFlags,
Alice Ryhl268458c2021-09-15 12:56:10 +0000199 ) -> Result<OwnedParcel>;
Alice Ryhlfeba6ca2021-08-19 10:47:04 +0000200
201 /// Perform a generic operation with the object. This is a convenience
202 /// method that internally calls `prepare_transact` followed by
203 /// `submit_transact.
204 ///
Stephen Crane2a3c2502020-06-16 17:48:35 -0700205 /// # Arguments
206 /// * `code` - Transaction code for the operation
Stephen Crane2a3c2502020-06-16 17:48:35 -0700207 /// * `flags` - Transaction flags, e.g. marking the transaction as
Andrew Walbran12400d82021-03-04 17:04:34 +0000208 /// asynchronous ([`FLAG_ONEWAY`](FLAG_ONEWAY))
Alice Ryhlfeba6ca2021-08-19 10:47:04 +0000209 /// * `input_callback` A callback for building the `Parcel`.
Stephen Crane2a3c2502020-06-16 17:48:35 -0700210 fn transact<F: FnOnce(&mut Parcel) -> Result<()>>(
211 &self,
212 code: TransactionCode,
213 flags: TransactionFlags,
214 input_callback: F,
Alice Ryhlfeba6ca2021-08-19 10:47:04 +0000215 ) -> Result<Parcel> {
216 let mut parcel = self.prepare_transact()?;
Alice Ryhl268458c2021-09-15 12:56:10 +0000217 input_callback(&mut parcel.borrowed())?;
218 self.submit_transact(code, parcel, flags).map(OwnedParcel::into_parcel)
Alice Ryhlfeba6ca2021-08-19 10:47:04 +0000219 }
Andrew Walbran12400d82021-03-04 17:04:34 +0000220}
Stephen Crane2a3c2502020-06-16 17:48:35 -0700221
Andrew Walbran12400d82021-03-04 17:04:34 +0000222/// Interface of binder local or remote objects.
223///
224/// This trait corresponds to the parts of the interface of the C++ `IBinder`
225/// class which are public.
226pub trait IBinder {
Stephen Crane2a3c2502020-06-16 17:48:35 -0700227 /// Register the recipient for a notification if this binder
228 /// goes away. If this binder object unexpectedly goes away
229 /// (typically because its hosting process has been killed),
Andrew Walbran12400d82021-03-04 17:04:34 +0000230 /// then the `DeathRecipient`'s callback will be called.
Stephen Crane2a3c2502020-06-16 17:48:35 -0700231 ///
232 /// You will only receive death notifications for remote binders,
233 /// as local binders by definition can't die without you dying as well.
234 /// Trying to use this function on a local binder will result in an
235 /// INVALID_OPERATION code being returned and nothing happening.
236 ///
237 /// This link always holds a weak reference to its recipient.
Stephen Crane2a3c2502020-06-16 17:48:35 -0700238 fn link_to_death(&mut self, recipient: &mut DeathRecipient) -> Result<()>;
239
240 /// Remove a previously registered death notification.
241 /// The recipient will no longer be called if this object
242 /// dies.
243 fn unlink_to_death(&mut self, recipient: &mut DeathRecipient) -> Result<()>;
244}
245
246/// Opaque reference to the type of a Binder interface.
247///
248/// This object encapsulates the Binder interface descriptor string, along with
249/// the binder transaction callback, if the class describes a local service.
250///
251/// A Binder remotable object may only have a single interface class, and any
252/// given object can only be associated with one class. Two objects with
253/// different classes are incompatible, even if both classes have the same
254/// interface descriptor.
255#[derive(Copy, Clone, PartialEq, Eq)]
256pub struct InterfaceClass(*const sys::AIBinder_Class);
257
258impl InterfaceClass {
259 /// Get a Binder NDK `AIBinder_Class` pointer for this object type.
260 ///
261 /// Note: the returned pointer will not be constant. Calling this method
262 /// multiple times for the same type will result in distinct class
263 /// pointers. A static getter for this value is implemented in
264 /// [`declare_binder_interface!`].
265 pub fn new<I: InterfaceClassMethods>() -> InterfaceClass {
266 let descriptor = CString::new(I::get_descriptor()).unwrap();
267 let ptr = unsafe {
268 // Safety: `AIBinder_Class_define` expects a valid C string, and
269 // three valid callback functions, all non-null pointers. The C
270 // string is copied and need not be valid for longer than the call,
271 // so we can drop it after the call. We can safely assign null to
272 // the onDump and handleShellCommand callbacks as long as the class
273 // pointer was non-null. Rust None for a Option<fn> is guaranteed to
274 // be a NULL pointer. Rust retains ownership of the pointer after it
275 // is defined.
276 let class = sys::AIBinder_Class_define(
277 descriptor.as_ptr(),
278 Some(I::on_create),
279 Some(I::on_destroy),
280 Some(I::on_transact),
281 );
282 if class.is_null() {
283 panic!("Expected non-null class pointer from AIBinder_Class_define!");
284 }
Stephen Crane2a3297f2021-06-11 16:48:10 -0700285 sys::AIBinder_Class_setOnDump(class, Some(I::on_dump));
Stephen Crane2a3c2502020-06-16 17:48:35 -0700286 sys::AIBinder_Class_setHandleShellCommand(class, None);
287 class
288 };
289 InterfaceClass(ptr)
290 }
291
292 /// Construct an `InterfaceClass` out of a raw, non-null `AIBinder_Class`
293 /// pointer.
294 ///
295 /// # Safety
296 ///
297 /// This function is safe iff `ptr` is a valid, non-null pointer to an
298 /// `AIBinder_Class`.
299 pub(crate) unsafe fn from_ptr(ptr: *const sys::AIBinder_Class) -> InterfaceClass {
300 InterfaceClass(ptr)
301 }
Stephen Crane669deb62020-09-10 17:31:39 -0700302
303 /// Get the interface descriptor string of this class.
304 pub fn get_descriptor(&self) -> String {
305 unsafe {
306 // SAFETY: The descriptor returned by AIBinder_Class_getDescriptor
307 // is always a two-byte null terminated sequence of u16s. Thus, we
308 // can continue reading from the pointer until we hit a null value,
309 // and this pointer can be a valid slice if the slice length is <=
310 // the number of u16 elements before the null terminator.
311
312 let raw_descriptor: *const c_char = sys::AIBinder_Class_getDescriptor(self.0);
Andrew Walbran12400d82021-03-04 17:04:34 +0000313 CStr::from_ptr(raw_descriptor)
314 .to_str()
Stephen Crane669deb62020-09-10 17:31:39 -0700315 .expect("Expected valid UTF-8 string from AIBinder_Class_getDescriptor")
316 .into()
317 }
318 }
Stephen Crane2a3c2502020-06-16 17:48:35 -0700319}
320
321impl From<InterfaceClass> for *const sys::AIBinder_Class {
322 fn from(class: InterfaceClass) -> *const sys::AIBinder_Class {
323 class.0
324 }
325}
326
Stephen Craneddb3e6d2020-12-18 13:27:22 -0800327/// Strong reference to a binder object
328pub struct Strong<I: FromIBinder + ?Sized>(Box<I>);
329
330impl<I: FromIBinder + ?Sized> Strong<I> {
331 /// Create a new strong reference to the provided binder object
332 pub fn new(binder: Box<I>) -> Self {
333 Self(binder)
334 }
335
336 /// Construct a new weak reference to this binder
337 pub fn downgrade(this: &Strong<I>) -> Weak<I> {
338 Weak::new(this)
339 }
340}
341
342impl<I: FromIBinder + ?Sized> Clone for Strong<I> {
343 fn clone(&self) -> Self {
344 // Since we hold a strong reference, we should always be able to create
345 // a new strong reference to the same interface type, so try_from()
346 // should never fail here.
347 FromIBinder::try_from(self.0.as_binder()).unwrap()
348 }
349}
350
351impl<I: FromIBinder + ?Sized> Borrow<I> for Strong<I> {
352 fn borrow(&self) -> &I {
353 &self.0
354 }
355}
356
357impl<I: FromIBinder + ?Sized> AsRef<I> for Strong<I> {
358 fn as_ref(&self) -> &I {
359 &self.0
360 }
361}
362
363impl<I: FromIBinder + ?Sized> Deref for Strong<I> {
364 type Target = I;
365
366 fn deref(&self) -> &Self::Target {
367 &self.0
368 }
369}
370
371impl<I: FromIBinder + fmt::Debug + ?Sized> fmt::Debug for Strong<I> {
372 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
373 fmt::Debug::fmt(&**self, f)
374 }
375}
376
377impl<I: FromIBinder + ?Sized> Ord for Strong<I> {
378 fn cmp(&self, other: &Self) -> Ordering {
379 self.0.as_binder().cmp(&other.0.as_binder())
380 }
381}
382
383impl<I: FromIBinder + ?Sized> PartialOrd for Strong<I> {
384 fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
385 self.0.as_binder().partial_cmp(&other.0.as_binder())
386 }
387}
388
389impl<I: FromIBinder + ?Sized> PartialEq for Strong<I> {
390 fn eq(&self, other: &Self) -> bool {
391 self.0.as_binder().eq(&other.0.as_binder())
392 }
393}
394
395impl<I: FromIBinder + ?Sized> Eq for Strong<I> {}
396
397/// Weak reference to a binder object
398#[derive(Debug)]
399pub struct Weak<I: FromIBinder + ?Sized> {
400 weak_binder: WpIBinder,
401 interface_type: PhantomData<I>,
402}
403
404impl<I: FromIBinder + ?Sized> Weak<I> {
405 /// Construct a new weak reference from a strong reference
406 fn new(binder: &Strong<I>) -> Self {
407 let weak_binder = binder.as_binder().downgrade();
408 Weak {
409 weak_binder,
410 interface_type: PhantomData,
411 }
412 }
413
414 /// Upgrade this weak reference to a strong reference if the binder object
415 /// is still alive
416 pub fn upgrade(&self) -> Result<Strong<I>> {
417 self.weak_binder
418 .promote()
419 .ok_or(StatusCode::DEAD_OBJECT)
420 .and_then(FromIBinder::try_from)
421 }
422}
423
424impl<I: FromIBinder + ?Sized> Clone for Weak<I> {
425 fn clone(&self) -> Self {
426 Self {
427 weak_binder: self.weak_binder.clone(),
428 interface_type: PhantomData,
429 }
430 }
431}
432
433impl<I: FromIBinder + ?Sized> Ord for Weak<I> {
434 fn cmp(&self, other: &Self) -> Ordering {
435 self.weak_binder.cmp(&other.weak_binder)
436 }
437}
438
439impl<I: FromIBinder + ?Sized> PartialOrd for Weak<I> {
440 fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
441 self.weak_binder.partial_cmp(&other.weak_binder)
442 }
443}
444
445impl<I: FromIBinder + ?Sized> PartialEq for Weak<I> {
446 fn eq(&self, other: &Self) -> bool {
447 self.weak_binder == other.weak_binder
448 }
449}
450
451impl<I: FromIBinder + ?Sized> Eq for Weak<I> {}
452
Stephen Crane2a3c2502020-06-16 17:48:35 -0700453/// Create a function implementing a static getter for an interface class.
454///
455/// Each binder interface (i.e. local [`Remotable`] service or remote proxy
456/// [`Interface`]) must have global, static class that uniquely identifies
457/// it. This macro implements an [`InterfaceClass`] getter to simplify these
458/// implementations.
459///
460/// The type of a structure that implements [`InterfaceClassMethods`] must be
461/// passed to this macro. For local services, this should be `Binder<Self>`
462/// since [`Binder`] implements [`InterfaceClassMethods`].
463///
464/// # Examples
465///
466/// When implementing a local [`Remotable`] service `ExampleService`, the
467/// `get_class` method is required in the [`Remotable`] impl block. This macro
468/// should be used as follows to implement this functionality:
469///
470/// ```rust
471/// impl Remotable for ExampleService {
472/// fn get_descriptor() -> &'static str {
473/// "android.os.IExampleInterface"
474/// }
475///
476/// fn on_transact(
477/// &self,
478/// code: TransactionCode,
479/// data: &Parcel,
480/// reply: &mut Parcel,
481/// ) -> Result<()> {
482/// // ...
483/// }
484///
485/// binder_fn_get_class!(Binder<Self>);
486/// }
487/// ```
488macro_rules! binder_fn_get_class {
489 ($class:ty) => {
490 binder_fn_get_class!($crate::InterfaceClass::new::<$class>());
491 };
492
493 ($constructor:expr) => {
494 fn get_class() -> $crate::InterfaceClass {
495 static CLASS_INIT: std::sync::Once = std::sync::Once::new();
496 static mut CLASS: Option<$crate::InterfaceClass> = None;
497
498 CLASS_INIT.call_once(|| unsafe {
499 // Safety: This assignment is guarded by the `CLASS_INIT` `Once`
500 // variable, and therefore is thread-safe, as it can only occur
501 // once.
502 CLASS = Some($constructor);
503 });
504 unsafe {
505 // Safety: The `CLASS` variable can only be mutated once, above,
506 // and is subsequently safe to read from any thread.
507 CLASS.unwrap()
508 }
509 }
510 };
511}
512
513pub trait InterfaceClassMethods {
514 /// Get the interface descriptor string for this object type.
515 fn get_descriptor() -> &'static str
516 where
517 Self: Sized;
518
519 /// Called during construction of a new `AIBinder` object of this interface
520 /// class.
521 ///
522 /// The opaque pointer parameter will be the parameter provided to
523 /// `AIBinder_new`. Returns an opaque userdata to be associated with the new
524 /// `AIBinder` object.
525 ///
526 /// # Safety
527 ///
528 /// Callback called from C++. The parameter argument provided to
529 /// `AIBinder_new` must match the type expected here. The `AIBinder` object
530 /// will take ownership of the returned pointer, which it will free via
531 /// `on_destroy`.
532 unsafe extern "C" fn on_create(args: *mut c_void) -> *mut c_void;
533
534 /// Called when a transaction needs to be processed by the local service
535 /// implementation.
536 ///
537 /// # Safety
538 ///
539 /// Callback called from C++. The `binder` parameter must be a valid pointer
540 /// to a binder object of this class with userdata initialized via this
541 /// class's `on_create`. The parcel parameters must be valid pointers to
542 /// parcel objects.
543 unsafe extern "C" fn on_transact(
544 binder: *mut sys::AIBinder,
545 code: u32,
546 data: *const sys::AParcel,
547 reply: *mut sys::AParcel,
548 ) -> status_t;
549
550 /// Called whenever an `AIBinder` object is no longer referenced and needs
551 /// to be destroyed.
552 ///
553 /// # Safety
554 ///
555 /// Callback called from C++. The opaque pointer parameter must be the value
556 /// returned by `on_create` for this class. This function takes ownership of
557 /// the provided pointer and destroys it.
558 unsafe extern "C" fn on_destroy(object: *mut c_void);
Stephen Crane2a3297f2021-06-11 16:48:10 -0700559
560 /// Called to handle the `dump` transaction.
561 ///
562 /// # Safety
563 ///
564 /// Must be called with a non-null, valid pointer to a local `AIBinder` that
565 /// contains a `T` pointer in its user data. fd should be a non-owned file
566 /// descriptor, and args must be an array of null-terminated string
567 /// poiinters with length num_args.
568 unsafe extern "C" fn on_dump(binder: *mut sys::AIBinder, fd: i32, args: *mut *const c_char, num_args: u32) -> status_t;
Stephen Crane2a3c2502020-06-16 17:48:35 -0700569}
570
571/// Interface for transforming a generic SpIBinder into a specific remote
572/// interface trait.
573///
574/// # Example
575///
576/// For Binder interface `IFoo`, the following implementation should be made:
577/// ```no_run
578/// # use binder::{FromIBinder, SpIBinder, Result};
579/// # trait IFoo {}
580/// impl FromIBinder for dyn IFoo {
581/// fn try_from(ibinder: SpIBinder) -> Result<Box<Self>> {
582/// // ...
583/// # Err(binder::StatusCode::OK)
584/// }
585/// }
586/// ```
Stephen Craneddb3e6d2020-12-18 13:27:22 -0800587pub trait FromIBinder: Interface {
Stephen Crane2a3c2502020-06-16 17:48:35 -0700588 /// Try to interpret a generic Binder object as this interface.
589 ///
590 /// Returns a trait object for the `Self` interface if this object
591 /// implements that interface.
Stephen Craneddb3e6d2020-12-18 13:27:22 -0800592 fn try_from(ibinder: SpIBinder) -> Result<Strong<Self>>;
Stephen Crane2a3c2502020-06-16 17:48:35 -0700593}
594
595/// Trait for transparent Rust wrappers around android C++ native types.
596///
597/// The pointer return by this trait's methods should be immediately passed to
598/// C++ and not stored by Rust. The pointer is valid only as long as the
599/// underlying C++ object is alive, so users must be careful to take this into
600/// account, as Rust cannot enforce this.
601///
602/// # Safety
603///
604/// For this trait to be a correct implementation, `T` must be a valid android
605/// C++ type. Since we cannot constrain this via the type system, this trait is
606/// marked as unsafe.
607pub unsafe trait AsNative<T> {
608 /// Return a pointer to the native version of `self`
609 fn as_native(&self) -> *const T;
610
611 /// Return a mutable pointer to the native version of `self`
612 fn as_native_mut(&mut self) -> *mut T;
613}
614
615unsafe impl<T, V: AsNative<T>> AsNative<T> for Option<V> {
616 fn as_native(&self) -> *const T {
617 self.as_ref().map_or(ptr::null(), |v| v.as_native())
618 }
619
620 fn as_native_mut(&mut self) -> *mut T {
621 self.as_mut().map_or(ptr::null_mut(), |v| v.as_native_mut())
622 }
623}
624
Andrew Walbran88eca4f2021-04-13 14:26:01 +0000625/// The features to enable when creating a native Binder.
626///
627/// This should always be initialised with a default value, e.g.:
628/// ```
629/// # use binder::BinderFeatures;
630/// BinderFeatures {
631/// set_requesting_sid: true,
632/// ..BinderFeatures::default(),
633/// }
634/// ```
635#[derive(Clone, Debug, Default, Eq, PartialEq)]
636pub struct BinderFeatures {
637 /// Indicates that the service intends to receive caller security contexts. This must be true
638 /// for `ThreadState::with_calling_sid` to work.
Janis Danisevskis1323d512021-11-09 07:48:08 -0800639 #[cfg(not(android_vndk))]
Andrew Walbran88eca4f2021-04-13 14:26:01 +0000640 pub set_requesting_sid: bool,
641 // Ensure that clients include a ..BinderFeatures::default() to preserve backwards compatibility
642 // when new fields are added. #[non_exhaustive] doesn't work because it prevents struct
643 // expressions entirely.
644 #[doc(hidden)]
645 pub _non_exhaustive: (),
646}
647
Stephen Crane2a3c2502020-06-16 17:48:35 -0700648/// Declare typed interfaces for a binder object.
649///
650/// Given an interface trait and descriptor string, create a native and remote
651/// proxy wrapper for this interface. The native service object (`$native`)
652/// implements `Remotable` and will dispatch to the function `$on_transact` to
653/// handle transactions. The typed proxy object (`$proxy`) wraps remote binder
654/// objects for this interface and can optionally contain additional fields.
655///
656/// Assuming the interface trait is `Interface`, `$on_transact` function must
657/// have the following type:
658///
659/// ```
660/// # use binder::{Interface, TransactionCode, Parcel};
661/// # trait Placeholder {
662/// fn on_transact(
663/// service: &dyn Interface,
664/// code: TransactionCode,
665/// data: &Parcel,
666/// reply: &mut Parcel,
667/// ) -> binder::Result<()>;
668/// # }
669/// ```
670///
671/// # Examples
672///
673/// The following example declares the local service type `BnServiceManager` and
674/// a remote proxy type `BpServiceManager` (the `n` and `p` stand for native and
675/// proxy respectively) for the `IServiceManager` Binder interface. The
676/// interfaces will be identified by the descriptor string
677/// "android.os.IServiceManager". The local service will dispatch transactions
678/// using the provided function, `on_transact`.
679///
680/// ```
681/// use binder::{declare_binder_interface, Binder, Interface, TransactionCode, Parcel};
682///
683/// pub trait IServiceManager: Interface {
684/// // remote methods...
685/// }
686///
687/// declare_binder_interface! {
688/// IServiceManager["android.os.IServiceManager"] {
689/// native: BnServiceManager(on_transact),
690/// proxy: BpServiceManager,
691/// }
692/// }
693///
694/// fn on_transact(
695/// service: &dyn IServiceManager,
696/// code: TransactionCode,
697/// data: &Parcel,
698/// reply: &mut Parcel,
699/// ) -> binder::Result<()> {
700/// // ...
701/// Ok(())
702/// }
703///
704/// impl IServiceManager for BpServiceManager {
705/// // parceling/unparceling code for the IServiceManager emitted here
706/// }
707///
708/// impl IServiceManager for Binder<BnServiceManager> {
709/// // Forward calls to local implementation
710/// }
711/// ```
712#[macro_export]
713macro_rules! declare_binder_interface {
714 {
715 $interface:path[$descriptor:expr] {
716 native: $native:ident($on_transact:path),
717 proxy: $proxy:ident,
Alice Ryhl05f5a2c2021-09-15 12:56:10 +0000718 $(async: $async_interface:ident,)?
Stephen Crane2a3c2502020-06-16 17:48:35 -0700719 }
720 } => {
721 $crate::declare_binder_interface! {
722 $interface[$descriptor] {
723 native: $native($on_transact),
724 proxy: $proxy {},
Alice Ryhl05f5a2c2021-09-15 12:56:10 +0000725 $(async: $async_interface,)?
Stephen Craneff7f03a2021-02-25 16:04:22 -0800726 stability: $crate::Stability::default(),
727 }
728 }
729 };
730
731 {
732 $interface:path[$descriptor:expr] {
733 native: $native:ident($on_transact:path),
734 proxy: $proxy:ident,
Alice Ryhl05f5a2c2021-09-15 12:56:10 +0000735 $(async: $async_interface:ident,)?
Stephen Craneff7f03a2021-02-25 16:04:22 -0800736 stability: $stability:expr,
737 }
738 } => {
739 $crate::declare_binder_interface! {
740 $interface[$descriptor] {
741 native: $native($on_transact),
742 proxy: $proxy {},
Alice Ryhl05f5a2c2021-09-15 12:56:10 +0000743 $(async: $async_interface,)?
Stephen Craneff7f03a2021-02-25 16:04:22 -0800744 stability: $stability,
Stephen Crane2a3c2502020-06-16 17:48:35 -0700745 }
746 }
747 };
748
749 {
750 $interface:path[$descriptor:expr] {
751 native: $native:ident($on_transact:path),
752 proxy: $proxy:ident {
753 $($fname:ident: $fty:ty = $finit:expr),*
754 },
Alice Ryhl05f5a2c2021-09-15 12:56:10 +0000755 $(async: $async_interface:ident,)?
Stephen Crane2a3c2502020-06-16 17:48:35 -0700756 }
757 } => {
758 $crate::declare_binder_interface! {
759 $interface[$descriptor] {
Stephen Craneff7f03a2021-02-25 16:04:22 -0800760 native: $native($on_transact),
761 proxy: $proxy {
762 $($fname: $fty = $finit),*
763 },
Alice Ryhl05f5a2c2021-09-15 12:56:10 +0000764 $(async: $async_interface,)?
Stephen Craneff7f03a2021-02-25 16:04:22 -0800765 stability: $crate::Stability::default(),
766 }
767 }
768 };
769
770 {
771 $interface:path[$descriptor:expr] {
772 native: $native:ident($on_transact:path),
773 proxy: $proxy:ident {
774 $($fname:ident: $fty:ty = $finit:expr),*
775 },
Alice Ryhl05f5a2c2021-09-15 12:56:10 +0000776 $(async: $async_interface:ident,)?
Stephen Craneff7f03a2021-02-25 16:04:22 -0800777 stability: $stability:expr,
778 }
779 } => {
780 $crate::declare_binder_interface! {
781 $interface[$descriptor] {
Stephen Crane2a3c2502020-06-16 17:48:35 -0700782 @doc[concat!("A binder [`Remotable`]($crate::Remotable) that holds an [`", stringify!($interface), "`] object.")]
783 native: $native($on_transact),
784 @doc[concat!("A binder [`Proxy`]($crate::Proxy) that holds an [`", stringify!($interface), "`] remote interface.")]
785 proxy: $proxy {
786 $($fname: $fty = $finit),*
787 },
Alice Ryhl05f5a2c2021-09-15 12:56:10 +0000788 $(async: $async_interface,)?
Stephen Craneff7f03a2021-02-25 16:04:22 -0800789 stability: $stability,
Stephen Crane2a3c2502020-06-16 17:48:35 -0700790 }
791 }
792 };
793
794 {
795 $interface:path[$descriptor:expr] {
796 @doc[$native_doc:expr]
797 native: $native:ident($on_transact:path),
798
799 @doc[$proxy_doc:expr]
800 proxy: $proxy:ident {
801 $($fname:ident: $fty:ty = $finit:expr),*
802 },
Stephen Craneff7f03a2021-02-25 16:04:22 -0800803
Alice Ryhl05f5a2c2021-09-15 12:56:10 +0000804 $( async: $async_interface:ident, )?
805
Stephen Craneff7f03a2021-02-25 16:04:22 -0800806 stability: $stability:expr,
Stephen Crane2a3c2502020-06-16 17:48:35 -0700807 }
808 } => {
809 #[doc = $proxy_doc]
810 pub struct $proxy {
811 binder: $crate::SpIBinder,
812 $($fname: $fty,)*
813 }
814
815 impl $crate::Interface for $proxy {
816 fn as_binder(&self) -> $crate::SpIBinder {
817 self.binder.clone()
818 }
819 }
820
821 impl $crate::Proxy for $proxy
822 where
823 $proxy: $interface,
824 {
825 fn get_descriptor() -> &'static str {
826 $descriptor
827 }
828
829 fn from_binder(mut binder: $crate::SpIBinder) -> $crate::Result<Self> {
Stephen Crane669deb62020-09-10 17:31:39 -0700830 Ok(Self { binder, $($fname: $finit),* })
Stephen Crane2a3c2502020-06-16 17:48:35 -0700831 }
832 }
833
834 #[doc = $native_doc]
835 #[repr(transparent)]
836 pub struct $native(Box<dyn $interface + Sync + Send + 'static>);
837
838 impl $native {
839 /// Create a new binder service.
Andrew Walbran88eca4f2021-04-13 14:26:01 +0000840 pub fn new_binder<T: $interface + Sync + Send + 'static>(inner: T, features: $crate::BinderFeatures) -> $crate::Strong<dyn $interface> {
841 let mut binder = $crate::Binder::new_with_stability($native(Box::new(inner)), $stability);
Janis Danisevskis1323d512021-11-09 07:48:08 -0800842 #[cfg(not(android_vndk))]
Andrew Walbran88eca4f2021-04-13 14:26:01 +0000843 $crate::IBinderInternal::set_requesting_sid(&mut binder, features.set_requesting_sid);
Stephen Craneddb3e6d2020-12-18 13:27:22 -0800844 $crate::Strong::new(Box::new(binder))
Stephen Crane2a3c2502020-06-16 17:48:35 -0700845 }
846 }
847
848 impl $crate::Remotable for $native {
849 fn get_descriptor() -> &'static str {
850 $descriptor
851 }
852
853 fn on_transact(&self, code: $crate::TransactionCode, data: &$crate::Parcel, reply: &mut $crate::Parcel) -> $crate::Result<()> {
Andrei Homescu32814372020-08-20 15:36:08 -0700854 match $on_transact(&*self.0, code, data, reply) {
855 // The C++ backend converts UNEXPECTED_NULL into an exception
856 Err($crate::StatusCode::UNEXPECTED_NULL) => {
857 let status = $crate::Status::new_exception(
858 $crate::ExceptionCode::NULL_POINTER,
859 None,
860 );
861 reply.write(&status)
862 },
863 result => result
864 }
Stephen Crane2a3c2502020-06-16 17:48:35 -0700865 }
866
Stephen Crane2a3297f2021-06-11 16:48:10 -0700867 fn on_dump(&self, file: &std::fs::File, args: &[&std::ffi::CStr]) -> $crate::Result<()> {
868 self.0.dump(file, args)
869 }
870
Stephen Crane2a3c2502020-06-16 17:48:35 -0700871 fn get_class() -> $crate::InterfaceClass {
872 static CLASS_INIT: std::sync::Once = std::sync::Once::new();
873 static mut CLASS: Option<$crate::InterfaceClass> = None;
874
875 CLASS_INIT.call_once(|| unsafe {
876 // Safety: This assignment is guarded by the `CLASS_INIT` `Once`
877 // variable, and therefore is thread-safe, as it can only occur
878 // once.
879 CLASS = Some($crate::InterfaceClass::new::<$crate::Binder<$native>>());
880 });
881 unsafe {
882 // Safety: The `CLASS` variable can only be mutated once, above,
883 // and is subsequently safe to read from any thread.
884 CLASS.unwrap()
885 }
886 }
887 }
888
889 impl $crate::FromIBinder for dyn $interface {
Stephen Craneddb3e6d2020-12-18 13:27:22 -0800890 fn try_from(mut ibinder: $crate::SpIBinder) -> $crate::Result<$crate::Strong<dyn $interface>> {
Stephen Crane2a3c2502020-06-16 17:48:35 -0700891 use $crate::AssociateClass;
Stephen Crane669deb62020-09-10 17:31:39 -0700892
893 let existing_class = ibinder.get_class();
894 if let Some(class) = existing_class {
895 if class != <$native as $crate::Remotable>::get_class() &&
896 class.get_descriptor() == <$native as $crate::Remotable>::get_descriptor()
897 {
898 // The binder object's descriptor string matches what we
899 // expect. We still need to treat this local or already
900 // associated object as remote, because we can't cast it
901 // into a Rust service object without a matching class
902 // pointer.
Stephen Craneddb3e6d2020-12-18 13:27:22 -0800903 return Ok($crate::Strong::new(Box::new(<$proxy as $crate::Proxy>::from_binder(ibinder)?)));
Stephen Crane669deb62020-09-10 17:31:39 -0700904 }
Stephen Crane2a3c2502020-06-16 17:48:35 -0700905 }
906
Stephen Crane669deb62020-09-10 17:31:39 -0700907 if ibinder.associate_class(<$native as $crate::Remotable>::get_class()) {
908 let service: $crate::Result<$crate::Binder<$native>> =
909 std::convert::TryFrom::try_from(ibinder.clone());
910 if let Ok(service) = service {
911 // We were able to associate with our expected class and
912 // the service is local.
Stephen Craneddb3e6d2020-12-18 13:27:22 -0800913 return Ok($crate::Strong::new(Box::new(service)));
Stephen Crane669deb62020-09-10 17:31:39 -0700914 } else {
915 // Service is remote
Stephen Craneddb3e6d2020-12-18 13:27:22 -0800916 return Ok($crate::Strong::new(Box::new(<$proxy as $crate::Proxy>::from_binder(ibinder)?)));
Stephen Crane669deb62020-09-10 17:31:39 -0700917 }
Matthew Maurerf6b9ad92020-12-03 19:27:25 +0000918 }
Stephen Crane669deb62020-09-10 17:31:39 -0700919
920 Err($crate::StatusCode::BAD_TYPE.into())
Stephen Crane2a3c2502020-06-16 17:48:35 -0700921 }
922 }
923
924 impl $crate::parcel::Serialize for dyn $interface + '_
925 where
Stephen Craned58bce02020-07-07 12:26:02 -0700926 dyn $interface: $crate::Interface
Stephen Crane2a3c2502020-06-16 17:48:35 -0700927 {
928 fn serialize(&self, parcel: &mut $crate::parcel::Parcel) -> $crate::Result<()> {
929 let binder = $crate::Interface::as_binder(self);
930 parcel.write(&binder)
931 }
932 }
933
934 impl $crate::parcel::SerializeOption for dyn $interface + '_ {
935 fn serialize_option(this: Option<&Self>, parcel: &mut $crate::parcel::Parcel) -> $crate::Result<()> {
936 parcel.write(&this.map($crate::Interface::as_binder))
937 }
938 }
Andrei Homescu2e3c1472020-08-11 16:35:40 -0700939
Alice Ryhl05f5a2c2021-09-15 12:56:10 +0000940 impl std::fmt::Debug for dyn $interface + '_ {
Andrei Homescu2e3c1472020-08-11 16:35:40 -0700941 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
942 f.pad(stringify!($interface))
943 }
944 }
Andrei Homescu64ebd132020-08-07 22:12:48 -0700945
Stephen Craneddb3e6d2020-12-18 13:27:22 -0800946 /// Convert a &dyn $interface to Strong<dyn $interface>
Andrei Homescu64ebd132020-08-07 22:12:48 -0700947 impl std::borrow::ToOwned for dyn $interface {
Stephen Craneddb3e6d2020-12-18 13:27:22 -0800948 type Owned = $crate::Strong<dyn $interface>;
Andrei Homescu64ebd132020-08-07 22:12:48 -0700949 fn to_owned(&self) -> Self::Owned {
950 self.as_binder().into_interface()
951 .expect(concat!("Error cloning interface ", stringify!($interface)))
952 }
953 }
Alice Ryhl05f5a2c2021-09-15 12:56:10 +0000954
955 $(
956 // Async interface trait implementations.
957 impl<P: $crate::BinderAsyncPool> $crate::FromIBinder for dyn $async_interface<P> {
958 fn try_from(mut ibinder: $crate::SpIBinder) -> $crate::Result<$crate::Strong<dyn $async_interface<P>>> {
959 use $crate::AssociateClass;
960
961 let existing_class = ibinder.get_class();
962 if let Some(class) = existing_class {
963 if class != <$native as $crate::Remotable>::get_class() &&
964 class.get_descriptor() == <$native as $crate::Remotable>::get_descriptor()
965 {
966 // The binder object's descriptor string matches what we
967 // expect. We still need to treat this local or already
968 // associated object as remote, because we can't cast it
969 // into a Rust service object without a matching class
970 // pointer.
971 return Ok($crate::Strong::new(Box::new(<$proxy as $crate::Proxy>::from_binder(ibinder)?)));
972 }
973 }
974
975 if ibinder.associate_class(<$native as $crate::Remotable>::get_class()) {
976 let service: $crate::Result<$crate::Binder<$native>> =
977 std::convert::TryFrom::try_from(ibinder.clone());
978 if let Ok(service) = service {
979 // We were able to associate with our expected class and
980 // the service is local.
981 todo!()
982 //return Ok($crate::Strong::new(Box::new(service)));
983 } else {
984 // Service is remote
985 return Ok($crate::Strong::new(Box::new(<$proxy as $crate::Proxy>::from_binder(ibinder)?)));
986 }
987 }
988
989 Err($crate::StatusCode::BAD_TYPE.into())
990 }
991 }
992
993 impl<P: $crate::BinderAsyncPool> $crate::parcel::Serialize for dyn $async_interface<P> + '_ {
994 fn serialize(&self, parcel: &mut $crate::parcel::Parcel) -> $crate::Result<()> {
995 let binder = $crate::Interface::as_binder(self);
996 parcel.write(&binder)
997 }
998 }
999
1000 impl<P: $crate::BinderAsyncPool> $crate::parcel::SerializeOption for dyn $async_interface<P> + '_ {
1001 fn serialize_option(this: Option<&Self>, parcel: &mut $crate::parcel::Parcel) -> $crate::Result<()> {
1002 parcel.write(&this.map($crate::Interface::as_binder))
1003 }
1004 }
1005
1006 impl<P: $crate::BinderAsyncPool> std::fmt::Debug for dyn $async_interface<P> + '_ {
1007 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
1008 f.pad(stringify!($async_interface))
1009 }
1010 }
1011
1012 /// Convert a &dyn $async_interface to Strong<dyn $async_interface>
1013 impl<P: $crate::BinderAsyncPool> std::borrow::ToOwned for dyn $async_interface<P> {
1014 type Owned = $crate::Strong<dyn $async_interface<P>>;
1015 fn to_owned(&self) -> Self::Owned {
1016 self.as_binder().into_interface()
1017 .expect(concat!("Error cloning interface ", stringify!($async_interface)))
1018 }
1019 }
1020 )?
Stephen Crane2a3c2502020-06-16 17:48:35 -07001021 };
1022}
Andrei Homescu00eca712020-09-09 18:57:40 -07001023
1024/// Declare an AIDL enumeration.
1025///
1026/// This is mainly used internally by the AIDL compiler.
1027#[macro_export]
1028macro_rules! declare_binder_enum {
1029 {
Andrei Homescu7f38cf92021-06-29 23:55:43 +00001030 $enum:ident : [$backing:ty; $size:expr] {
Andrei Homescu00eca712020-09-09 18:57:40 -07001031 $( $name:ident = $value:expr, )*
1032 }
1033 } => {
1034 #[derive(Debug, Default, Copy, Clone, PartialOrd, Ord, PartialEq, Eq, Hash)]
1035 pub struct $enum(pub $backing);
1036 impl $enum {
1037 $( pub const $name: Self = Self($value); )*
Andrei Homescu7f38cf92021-06-29 23:55:43 +00001038
1039 #[inline(always)]
1040 pub const fn enum_values() -> [Self; $size] {
1041 [$(Self::$name),*]
1042 }
Andrei Homescu00eca712020-09-09 18:57:40 -07001043 }
1044
1045 impl $crate::parcel::Serialize for $enum {
1046 fn serialize(&self, parcel: &mut $crate::parcel::Parcel) -> $crate::Result<()> {
1047 parcel.write(&self.0)
1048 }
1049 }
1050
1051 impl $crate::parcel::SerializeArray for $enum {
1052 fn serialize_array(slice: &[Self], parcel: &mut $crate::parcel::Parcel) -> $crate::Result<()> {
1053 let v: Vec<$backing> = slice.iter().map(|x| x.0).collect();
1054 <$backing as binder::parcel::SerializeArray>::serialize_array(&v[..], parcel)
1055 }
1056 }
1057
1058 impl $crate::parcel::Deserialize for $enum {
1059 fn deserialize(parcel: &$crate::parcel::Parcel) -> $crate::Result<Self> {
1060 parcel.read().map(Self)
1061 }
1062 }
1063
1064 impl $crate::parcel::DeserializeArray for $enum {
1065 fn deserialize_array(parcel: &$crate::parcel::Parcel) -> $crate::Result<Option<Vec<Self>>> {
1066 let v: Option<Vec<$backing>> =
1067 <$backing as binder::parcel::DeserializeArray>::deserialize_array(parcel)?;
1068 Ok(v.map(|v| v.into_iter().map(Self).collect()))
1069 }
1070 }
1071 };
1072}