blob: d0e35de3f76c20f423ede2c3c5a74d4622a9f76b [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};
Matthew Maurere268a9f2022-07-26 09:31:30 -070020use crate::parcel::{BorrowedParcel, 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
Alice Ryhlc1736842021-11-23 12:38:51 +000069/// Implemented by sync interfaces to specify what the associated async interface is.
70/// Generic to handle the fact that async interfaces are generic over a thread pool.
71///
72/// The binder in any object implementing this trait should be compatible with the
73/// `Target` associated type, and using `FromIBinder` to convert it to the target
74/// should not fail.
75pub trait ToAsyncInterface<P>
76where
77 Self: Interface,
78 Self::Target: FromIBinder,
79{
80 /// The async interface associated with this sync interface.
81 type Target: ?Sized;
82}
83
84/// Implemented by async interfaces to specify what the associated sync interface is.
85///
86/// The binder in any object implementing this trait should be compatible with the
87/// `Target` associated type, and using `FromIBinder` to convert it to the target
88/// should not fail.
89pub trait ToSyncInterface
90where
91 Self: Interface,
92 Self::Target: FromIBinder,
93{
94 /// The sync interface associated with this async interface.
95 type Target: ?Sized;
96}
97
Stephen Craneff7f03a2021-02-25 16:04:22 -080098/// Interface stability promise
99///
100/// An interface can promise to be a stable vendor interface ([`Vintf`]), or
101/// makes no stability guarantees ([`Local`]). [`Local`] is
102/// currently the default stability.
Chariseeab53d0a2023-03-03 02:08:34 +0000103#[derive(Debug, Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Default)]
Stephen Craneff7f03a2021-02-25 16:04:22 -0800104pub enum Stability {
105 /// Default stability, visible to other modules in the same compilation
106 /// context (e.g. modules on system.img)
Chariseeab53d0a2023-03-03 02:08:34 +0000107 #[default]
Stephen Craneff7f03a2021-02-25 16:04:22 -0800108 Local,
109
110 /// A Vendor Interface Object, which promises to be stable
111 Vintf,
112}
113
Andrei Homescuee132fa2021-09-03 02:36:17 +0000114impl From<Stability> for i32 {
115 fn from(stability: Stability) -> i32 {
116 use Stability::*;
117 match stability {
118 Local => 0,
119 Vintf => 1,
120 }
121 }
122}
123
124impl TryFrom<i32> for Stability {
125 type Error = StatusCode;
126 fn try_from(stability: i32) -> Result<Stability> {
127 use Stability::*;
128 match stability {
129 0 => Ok(Local),
130 1 => Ok(Vintf),
Matthew Maurere268a9f2022-07-26 09:31:30 -0700131 _ => Err(StatusCode::BAD_VALUE),
Andrei Homescuee132fa2021-09-03 02:36:17 +0000132 }
133 }
134}
135
Stephen Crane2a3c2502020-06-16 17:48:35 -0700136/// A local service that can be remotable via Binder.
137///
138/// An object that implement this interface made be made into a Binder service
139/// via `Binder::new(object)`.
140///
141/// This is a low-level interface that should normally be automatically
142/// generated from AIDL via the [`declare_binder_interface!`] macro. When using
143/// the AIDL backend, users need only implement the high-level AIDL-defined
144/// interface. The AIDL compiler then generates a container struct that wraps
145/// the user-defined service and implements `Remotable`.
Andrei Homescu2c674b02020-08-07 22:12:27 -0700146pub trait Remotable: Send + Sync {
Stephen Crane2a3c2502020-06-16 17:48:35 -0700147 /// The Binder interface descriptor string.
148 ///
149 /// This string is a unique identifier for a Binder interface, and should be
150 /// the same between all implementations of that interface.
151 fn get_descriptor() -> &'static str;
152
153 /// Handle and reply to a request to invoke a transaction on this object.
154 ///
155 /// `reply` may be [`None`] if the sender does not expect a reply.
Matthew Maurere268a9f2022-07-26 09:31:30 -0700156 fn on_transact(
157 &self,
158 code: TransactionCode,
159 data: &BorrowedParcel<'_>,
160 reply: &mut BorrowedParcel<'_>,
161 ) -> Result<()>;
Stephen Crane2a3c2502020-06-16 17:48:35 -0700162
Stephen Crane2a3297f2021-06-11 16:48:10 -0700163 /// Handle a request to invoke the dump transaction on this
164 /// object.
165 fn on_dump(&self, file: &File, args: &[&CStr]) -> Result<()>;
166
Stephen Crane2a3c2502020-06-16 17:48:35 -0700167 /// Retrieve the class of this remote object.
168 ///
169 /// This method should always return the same InterfaceClass for the same
170 /// type.
171 fn get_class() -> InterfaceClass;
172}
173
Andrew Walbran12400d82021-03-04 17:04:34 +0000174/// First transaction code available for user commands (inclusive)
175pub const FIRST_CALL_TRANSACTION: TransactionCode = sys::FIRST_CALL_TRANSACTION;
176/// Last transaction code available for user commands (inclusive)
177pub const LAST_CALL_TRANSACTION: TransactionCode = sys::LAST_CALL_TRANSACTION;
178
179/// Corresponds to TF_ONE_WAY -- an asynchronous call.
180pub const FLAG_ONEWAY: TransactionFlags = sys::FLAG_ONEWAY;
181/// Corresponds to TF_CLEAR_BUF -- clear transaction buffers after call is made.
182pub const FLAG_CLEAR_BUF: TransactionFlags = sys::FLAG_CLEAR_BUF;
Stephen Craneff7f03a2021-02-25 16:04:22 -0800183/// Set to the vendor flag if we are building for the VNDK, 0 otherwise
184pub const FLAG_PRIVATE_LOCAL: TransactionFlags = sys::FLAG_PRIVATE_LOCAL;
Andrew Walbran12400d82021-03-04 17:04:34 +0000185
186/// Internal interface of binder local or remote objects for making
187/// transactions.
Stephen Crane2a3c2502020-06-16 17:48:35 -0700188///
Andrew Walbran12400d82021-03-04 17:04:34 +0000189/// This trait corresponds to the parts of the interface of the C++ `IBinder`
190/// class which are internal implementation details.
191pub trait IBinderInternal: IBinder {
Stephen Crane2a3c2502020-06-16 17:48:35 -0700192 /// Is this object still alive?
193 fn is_binder_alive(&self) -> bool;
194
Janis Danisevskis798a09a2020-08-18 08:35:38 -0700195 /// Indicate that the service intends to receive caller security contexts.
Janis Danisevskis1323d512021-11-09 07:48:08 -0800196 #[cfg(not(android_vndk))]
Janis Danisevskis798a09a2020-08-18 08:35:38 -0700197 fn set_requesting_sid(&mut self, enable: bool);
198
Stephen Crane2a3c2502020-06-16 17:48:35 -0700199 /// Dump this object to the given file handle
200 fn dump<F: AsRawFd>(&mut self, fp: &F, args: &[&str]) -> Result<()>;
201
202 /// Get a new interface that exposes additional extension functionality, if
203 /// available.
204 fn get_extension(&mut self) -> Result<Option<SpIBinder>>;
205
Alice Ryhlfeba6ca2021-08-19 10:47:04 +0000206 /// Create a Parcel that can be used with `submit_transact`.
Alice Ryhl8618c482021-11-09 15:35:35 +0000207 fn prepare_transact(&self) -> Result<Parcel>;
Alice Ryhlfeba6ca2021-08-19 10:47:04 +0000208
Stephen Crane2a3c2502020-06-16 17:48:35 -0700209 /// Perform a generic operation with the object.
210 ///
Alice Ryhl8618c482021-11-09 15:35:35 +0000211 /// The provided [`Parcel`] must have been created by a call to
Alice Ryhlfeba6ca2021-08-19 10:47:04 +0000212 /// `prepare_transact` on the same binder.
213 ///
214 /// # Arguments
215 ///
216 /// * `code` - Transaction code for the operation.
Alice Ryhl8618c482021-11-09 15:35:35 +0000217 /// * `data` - [`Parcel`] with input data.
Alice Ryhlfeba6ca2021-08-19 10:47:04 +0000218 /// * `flags` - Transaction flags, e.g. marking the transaction as
219 /// asynchronous ([`FLAG_ONEWAY`](FLAG_ONEWAY)).
220 fn submit_transact(
221 &self,
222 code: TransactionCode,
Alice Ryhl8618c482021-11-09 15:35:35 +0000223 data: Parcel,
Alice Ryhlfeba6ca2021-08-19 10:47:04 +0000224 flags: TransactionFlags,
Alice Ryhl8618c482021-11-09 15:35:35 +0000225 ) -> Result<Parcel>;
Alice Ryhlfeba6ca2021-08-19 10:47:04 +0000226
227 /// Perform a generic operation with the object. This is a convenience
228 /// method that internally calls `prepare_transact` followed by
229 /// `submit_transact.
230 ///
Stephen Crane2a3c2502020-06-16 17:48:35 -0700231 /// # Arguments
232 /// * `code` - Transaction code for the operation
Stephen Crane2a3c2502020-06-16 17:48:35 -0700233 /// * `flags` - Transaction flags, e.g. marking the transaction as
Andrew Walbran12400d82021-03-04 17:04:34 +0000234 /// asynchronous ([`FLAG_ONEWAY`](FLAG_ONEWAY))
Alice Ryhlfeba6ca2021-08-19 10:47:04 +0000235 /// * `input_callback` A callback for building the `Parcel`.
Alice Ryhl8618c482021-11-09 15:35:35 +0000236 fn transact<F: FnOnce(BorrowedParcel<'_>) -> Result<()>>(
Stephen Crane2a3c2502020-06-16 17:48:35 -0700237 &self,
238 code: TransactionCode,
239 flags: TransactionFlags,
240 input_callback: F,
Alice Ryhlfeba6ca2021-08-19 10:47:04 +0000241 ) -> Result<Parcel> {
242 let mut parcel = self.prepare_transact()?;
Alice Ryhl8618c482021-11-09 15:35:35 +0000243 input_callback(parcel.borrowed())?;
244 self.submit_transact(code, parcel, flags)
Alice Ryhlfeba6ca2021-08-19 10:47:04 +0000245 }
Andrew Walbran12400d82021-03-04 17:04:34 +0000246}
Stephen Crane2a3c2502020-06-16 17:48:35 -0700247
Andrew Walbran12400d82021-03-04 17:04:34 +0000248/// Interface of binder local or remote objects.
249///
250/// This trait corresponds to the parts of the interface of the C++ `IBinder`
251/// class which are public.
252pub trait IBinder {
Stephen Crane2a3c2502020-06-16 17:48:35 -0700253 /// Register the recipient for a notification if this binder
254 /// goes away. If this binder object unexpectedly goes away
255 /// (typically because its hosting process has been killed),
Andrew Walbran12400d82021-03-04 17:04:34 +0000256 /// then the `DeathRecipient`'s callback will be called.
Stephen Crane2a3c2502020-06-16 17:48:35 -0700257 ///
258 /// You will only receive death notifications for remote binders,
259 /// as local binders by definition can't die without you dying as well.
260 /// Trying to use this function on a local binder will result in an
261 /// INVALID_OPERATION code being returned and nothing happening.
262 ///
263 /// This link always holds a weak reference to its recipient.
Stephen Crane2a3c2502020-06-16 17:48:35 -0700264 fn link_to_death(&mut self, recipient: &mut DeathRecipient) -> Result<()>;
265
266 /// Remove a previously registered death notification.
267 /// The recipient will no longer be called if this object
268 /// dies.
269 fn unlink_to_death(&mut self, recipient: &mut DeathRecipient) -> Result<()>;
Stephen Crane61366d42022-01-20 17:45:34 -0800270
271 /// Send a ping transaction to this object
272 fn ping_binder(&mut self) -> Result<()>;
Stephen Crane2a3c2502020-06-16 17:48:35 -0700273}
274
275/// Opaque reference to the type of a Binder interface.
276///
277/// This object encapsulates the Binder interface descriptor string, along with
278/// the binder transaction callback, if the class describes a local service.
279///
280/// A Binder remotable object may only have a single interface class, and any
281/// given object can only be associated with one class. Two objects with
282/// different classes are incompatible, even if both classes have the same
283/// interface descriptor.
284#[derive(Copy, Clone, PartialEq, Eq)]
285pub struct InterfaceClass(*const sys::AIBinder_Class);
286
287impl InterfaceClass {
288 /// Get a Binder NDK `AIBinder_Class` pointer for this object type.
289 ///
290 /// Note: the returned pointer will not be constant. Calling this method
291 /// multiple times for the same type will result in distinct class
292 /// pointers. A static getter for this value is implemented in
293 /// [`declare_binder_interface!`].
294 pub fn new<I: InterfaceClassMethods>() -> InterfaceClass {
295 let descriptor = CString::new(I::get_descriptor()).unwrap();
296 let ptr = unsafe {
297 // Safety: `AIBinder_Class_define` expects a valid C string, and
298 // three valid callback functions, all non-null pointers. The C
299 // string is copied and need not be valid for longer than the call,
300 // so we can drop it after the call. We can safely assign null to
301 // the onDump and handleShellCommand callbacks as long as the class
302 // pointer was non-null. Rust None for a Option<fn> is guaranteed to
303 // be a NULL pointer. Rust retains ownership of the pointer after it
304 // is defined.
305 let class = sys::AIBinder_Class_define(
306 descriptor.as_ptr(),
307 Some(I::on_create),
308 Some(I::on_destroy),
309 Some(I::on_transact),
310 );
311 if class.is_null() {
312 panic!("Expected non-null class pointer from AIBinder_Class_define!");
313 }
Stephen Crane2a3297f2021-06-11 16:48:10 -0700314 sys::AIBinder_Class_setOnDump(class, Some(I::on_dump));
Stephen Crane2a3c2502020-06-16 17:48:35 -0700315 sys::AIBinder_Class_setHandleShellCommand(class, None);
316 class
317 };
318 InterfaceClass(ptr)
319 }
320
321 /// Construct an `InterfaceClass` out of a raw, non-null `AIBinder_Class`
322 /// pointer.
323 ///
324 /// # Safety
325 ///
326 /// This function is safe iff `ptr` is a valid, non-null pointer to an
327 /// `AIBinder_Class`.
328 pub(crate) unsafe fn from_ptr(ptr: *const sys::AIBinder_Class) -> InterfaceClass {
329 InterfaceClass(ptr)
330 }
Stephen Crane669deb62020-09-10 17:31:39 -0700331
332 /// Get the interface descriptor string of this class.
333 pub fn get_descriptor(&self) -> String {
334 unsafe {
335 // SAFETY: The descriptor returned by AIBinder_Class_getDescriptor
336 // is always a two-byte null terminated sequence of u16s. Thus, we
337 // can continue reading from the pointer until we hit a null value,
338 // and this pointer can be a valid slice if the slice length is <=
339 // the number of u16 elements before the null terminator.
340
341 let raw_descriptor: *const c_char = sys::AIBinder_Class_getDescriptor(self.0);
Andrew Walbran12400d82021-03-04 17:04:34 +0000342 CStr::from_ptr(raw_descriptor)
343 .to_str()
Stephen Crane669deb62020-09-10 17:31:39 -0700344 .expect("Expected valid UTF-8 string from AIBinder_Class_getDescriptor")
345 .into()
346 }
347 }
Stephen Crane2a3c2502020-06-16 17:48:35 -0700348}
349
350impl From<InterfaceClass> for *const sys::AIBinder_Class {
351 fn from(class: InterfaceClass) -> *const sys::AIBinder_Class {
352 class.0
353 }
354}
355
Stephen Craneddb3e6d2020-12-18 13:27:22 -0800356/// Strong reference to a binder object
357pub struct Strong<I: FromIBinder + ?Sized>(Box<I>);
358
359impl<I: FromIBinder + ?Sized> Strong<I> {
360 /// Create a new strong reference to the provided binder object
361 pub fn new(binder: Box<I>) -> Self {
362 Self(binder)
363 }
364
365 /// Construct a new weak reference to this binder
366 pub fn downgrade(this: &Strong<I>) -> Weak<I> {
367 Weak::new(this)
368 }
Alice Ryhlc1736842021-11-23 12:38:51 +0000369
370 /// Convert this synchronous binder handle into an asynchronous one.
371 pub fn into_async<P>(self) -> Strong<<I as ToAsyncInterface<P>>::Target>
372 where
373 I: ToAsyncInterface<P>,
374 {
375 // By implementing the ToAsyncInterface trait, it is guaranteed that the binder
376 // object is also valid for the target type.
377 FromIBinder::try_from(self.0.as_binder()).unwrap()
378 }
379
380 /// Convert this asynchronous binder handle into a synchronous one.
381 pub fn into_sync(self) -> Strong<<I as ToSyncInterface>::Target>
382 where
383 I: ToSyncInterface,
384 {
385 // By implementing the ToSyncInterface trait, it is guaranteed that the binder
386 // object is also valid for the target type.
387 FromIBinder::try_from(self.0.as_binder()).unwrap()
388 }
Stephen Craneddb3e6d2020-12-18 13:27:22 -0800389}
390
391impl<I: FromIBinder + ?Sized> Clone for Strong<I> {
392 fn clone(&self) -> Self {
393 // Since we hold a strong reference, we should always be able to create
394 // a new strong reference to the same interface type, so try_from()
395 // should never fail here.
396 FromIBinder::try_from(self.0.as_binder()).unwrap()
397 }
398}
399
400impl<I: FromIBinder + ?Sized> Borrow<I> for Strong<I> {
401 fn borrow(&self) -> &I {
402 &self.0
403 }
404}
405
406impl<I: FromIBinder + ?Sized> AsRef<I> for Strong<I> {
407 fn as_ref(&self) -> &I {
408 &self.0
409 }
410}
411
412impl<I: FromIBinder + ?Sized> Deref for Strong<I> {
413 type Target = I;
414
415 fn deref(&self) -> &Self::Target {
416 &self.0
417 }
418}
419
420impl<I: FromIBinder + fmt::Debug + ?Sized> fmt::Debug for Strong<I> {
421 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
422 fmt::Debug::fmt(&**self, f)
423 }
424}
425
426impl<I: FromIBinder + ?Sized> Ord for Strong<I> {
427 fn cmp(&self, other: &Self) -> Ordering {
428 self.0.as_binder().cmp(&other.0.as_binder())
429 }
430}
431
432impl<I: FromIBinder + ?Sized> PartialOrd for Strong<I> {
433 fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
434 self.0.as_binder().partial_cmp(&other.0.as_binder())
435 }
436}
437
438impl<I: FromIBinder + ?Sized> PartialEq for Strong<I> {
439 fn eq(&self, other: &Self) -> bool {
440 self.0.as_binder().eq(&other.0.as_binder())
441 }
442}
443
444impl<I: FromIBinder + ?Sized> Eq for Strong<I> {}
445
446/// Weak reference to a binder object
447#[derive(Debug)]
448pub struct Weak<I: FromIBinder + ?Sized> {
449 weak_binder: WpIBinder,
450 interface_type: PhantomData<I>,
451}
452
453impl<I: FromIBinder + ?Sized> Weak<I> {
454 /// Construct a new weak reference from a strong reference
455 fn new(binder: &Strong<I>) -> Self {
456 let weak_binder = binder.as_binder().downgrade();
Matthew Maurere268a9f2022-07-26 09:31:30 -0700457 Weak { weak_binder, interface_type: PhantomData }
Stephen Craneddb3e6d2020-12-18 13:27:22 -0800458 }
459
460 /// Upgrade this weak reference to a strong reference if the binder object
461 /// is still alive
462 pub fn upgrade(&self) -> Result<Strong<I>> {
Matthew Maurere268a9f2022-07-26 09:31:30 -0700463 self.weak_binder.promote().ok_or(StatusCode::DEAD_OBJECT).and_then(FromIBinder::try_from)
Stephen Craneddb3e6d2020-12-18 13:27:22 -0800464 }
465}
466
467impl<I: FromIBinder + ?Sized> Clone for Weak<I> {
468 fn clone(&self) -> Self {
Matthew Maurere268a9f2022-07-26 09:31:30 -0700469 Self { weak_binder: self.weak_binder.clone(), interface_type: PhantomData }
Stephen Craneddb3e6d2020-12-18 13:27:22 -0800470 }
471}
472
473impl<I: FromIBinder + ?Sized> Ord for Weak<I> {
474 fn cmp(&self, other: &Self) -> Ordering {
475 self.weak_binder.cmp(&other.weak_binder)
476 }
477}
478
479impl<I: FromIBinder + ?Sized> PartialOrd for Weak<I> {
480 fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
481 self.weak_binder.partial_cmp(&other.weak_binder)
482 }
483}
484
485impl<I: FromIBinder + ?Sized> PartialEq for Weak<I> {
486 fn eq(&self, other: &Self) -> bool {
487 self.weak_binder == other.weak_binder
488 }
489}
490
491impl<I: FromIBinder + ?Sized> Eq for Weak<I> {}
492
Stephen Crane2a3c2502020-06-16 17:48:35 -0700493/// Create a function implementing a static getter for an interface class.
494///
495/// Each binder interface (i.e. local [`Remotable`] service or remote proxy
496/// [`Interface`]) must have global, static class that uniquely identifies
497/// it. This macro implements an [`InterfaceClass`] getter to simplify these
498/// implementations.
499///
500/// The type of a structure that implements [`InterfaceClassMethods`] must be
501/// passed to this macro. For local services, this should be `Binder<Self>`
502/// since [`Binder`] implements [`InterfaceClassMethods`].
503///
504/// # Examples
505///
506/// When implementing a local [`Remotable`] service `ExampleService`, the
507/// `get_class` method is required in the [`Remotable`] impl block. This macro
508/// should be used as follows to implement this functionality:
509///
510/// ```rust
511/// impl Remotable for ExampleService {
512/// fn get_descriptor() -> &'static str {
513/// "android.os.IExampleInterface"
514/// }
515///
516/// fn on_transact(
517/// &self,
518/// code: TransactionCode,
Alice Ryhl8618c482021-11-09 15:35:35 +0000519/// data: &BorrowedParcel,
520/// reply: &mut BorrowedParcel,
Stephen Crane2a3c2502020-06-16 17:48:35 -0700521/// ) -> Result<()> {
522/// // ...
523/// }
524///
525/// binder_fn_get_class!(Binder<Self>);
526/// }
527/// ```
528macro_rules! binder_fn_get_class {
529 ($class:ty) => {
Stephen Cranef2735b42022-01-19 17:49:46 +0000530 binder_fn_get_class!($crate::binder_impl::InterfaceClass::new::<$class>());
Stephen Crane2a3c2502020-06-16 17:48:35 -0700531 };
532
533 ($constructor:expr) => {
Stephen Cranef2735b42022-01-19 17:49:46 +0000534 fn get_class() -> $crate::binder_impl::InterfaceClass {
Stephen Crane2a3c2502020-06-16 17:48:35 -0700535 static CLASS_INIT: std::sync::Once = std::sync::Once::new();
Stephen Cranef2735b42022-01-19 17:49:46 +0000536 static mut CLASS: Option<$crate::binder_impl::InterfaceClass> = None;
Stephen Crane2a3c2502020-06-16 17:48:35 -0700537
538 CLASS_INIT.call_once(|| unsafe {
539 // Safety: This assignment is guarded by the `CLASS_INIT` `Once`
540 // variable, and therefore is thread-safe, as it can only occur
541 // once.
542 CLASS = Some($constructor);
543 });
544 unsafe {
545 // Safety: The `CLASS` variable can only be mutated once, above,
546 // and is subsequently safe to read from any thread.
547 CLASS.unwrap()
548 }
549 }
550 };
551}
552
553pub trait InterfaceClassMethods {
554 /// Get the interface descriptor string for this object type.
555 fn get_descriptor() -> &'static str
556 where
557 Self: Sized;
558
559 /// Called during construction of a new `AIBinder` object of this interface
560 /// class.
561 ///
562 /// The opaque pointer parameter will be the parameter provided to
563 /// `AIBinder_new`. Returns an opaque userdata to be associated with the new
564 /// `AIBinder` object.
565 ///
566 /// # Safety
567 ///
568 /// Callback called from C++. The parameter argument provided to
569 /// `AIBinder_new` must match the type expected here. The `AIBinder` object
570 /// will take ownership of the returned pointer, which it will free via
571 /// `on_destroy`.
572 unsafe extern "C" fn on_create(args: *mut c_void) -> *mut c_void;
573
574 /// Called when a transaction needs to be processed by the local service
575 /// implementation.
576 ///
577 /// # Safety
578 ///
579 /// Callback called from C++. The `binder` parameter must be a valid pointer
580 /// to a binder object of this class with userdata initialized via this
581 /// class's `on_create`. The parcel parameters must be valid pointers to
582 /// parcel objects.
583 unsafe extern "C" fn on_transact(
584 binder: *mut sys::AIBinder,
585 code: u32,
586 data: *const sys::AParcel,
587 reply: *mut sys::AParcel,
588 ) -> status_t;
589
590 /// Called whenever an `AIBinder` object is no longer referenced and needs
591 /// to be destroyed.
592 ///
593 /// # Safety
594 ///
595 /// Callback called from C++. The opaque pointer parameter must be the value
596 /// returned by `on_create` for this class. This function takes ownership of
597 /// the provided pointer and destroys it.
598 unsafe extern "C" fn on_destroy(object: *mut c_void);
Stephen Crane2a3297f2021-06-11 16:48:10 -0700599
600 /// Called to handle the `dump` transaction.
601 ///
602 /// # Safety
603 ///
604 /// Must be called with a non-null, valid pointer to a local `AIBinder` that
605 /// contains a `T` pointer in its user data. fd should be a non-owned file
606 /// descriptor, and args must be an array of null-terminated string
607 /// poiinters with length num_args.
Matthew Maurere268a9f2022-07-26 09:31:30 -0700608 unsafe extern "C" fn on_dump(
609 binder: *mut sys::AIBinder,
610 fd: i32,
611 args: *mut *const c_char,
612 num_args: u32,
613 ) -> status_t;
Stephen Crane2a3c2502020-06-16 17:48:35 -0700614}
615
616/// Interface for transforming a generic SpIBinder into a specific remote
617/// interface trait.
618///
619/// # Example
620///
621/// For Binder interface `IFoo`, the following implementation should be made:
622/// ```no_run
623/// # use binder::{FromIBinder, SpIBinder, Result};
624/// # trait IFoo {}
625/// impl FromIBinder for dyn IFoo {
626/// fn try_from(ibinder: SpIBinder) -> Result<Box<Self>> {
627/// // ...
628/// # Err(binder::StatusCode::OK)
629/// }
630/// }
631/// ```
Stephen Craneddb3e6d2020-12-18 13:27:22 -0800632pub trait FromIBinder: Interface {
Stephen Crane2a3c2502020-06-16 17:48:35 -0700633 /// Try to interpret a generic Binder object as this interface.
634 ///
635 /// Returns a trait object for the `Self` interface if this object
636 /// implements that interface.
Stephen Craneddb3e6d2020-12-18 13:27:22 -0800637 fn try_from(ibinder: SpIBinder) -> Result<Strong<Self>>;
Stephen Crane2a3c2502020-06-16 17:48:35 -0700638}
639
640/// Trait for transparent Rust wrappers around android C++ native types.
641///
642/// The pointer return by this trait's methods should be immediately passed to
643/// C++ and not stored by Rust. The pointer is valid only as long as the
644/// underlying C++ object is alive, so users must be careful to take this into
645/// account, as Rust cannot enforce this.
646///
647/// # Safety
648///
649/// For this trait to be a correct implementation, `T` must be a valid android
650/// C++ type. Since we cannot constrain this via the type system, this trait is
651/// marked as unsafe.
652pub unsafe trait AsNative<T> {
653 /// Return a pointer to the native version of `self`
654 fn as_native(&self) -> *const T;
655
656 /// Return a mutable pointer to the native version of `self`
657 fn as_native_mut(&mut self) -> *mut T;
658}
659
660unsafe impl<T, V: AsNative<T>> AsNative<T> for Option<V> {
661 fn as_native(&self) -> *const T {
662 self.as_ref().map_or(ptr::null(), |v| v.as_native())
663 }
664
665 fn as_native_mut(&mut self) -> *mut T {
666 self.as_mut().map_or(ptr::null_mut(), |v| v.as_native_mut())
667 }
668}
669
Andrew Walbran88eca4f2021-04-13 14:26:01 +0000670/// The features to enable when creating a native Binder.
671///
672/// This should always be initialised with a default value, e.g.:
673/// ```
674/// # use binder::BinderFeatures;
675/// BinderFeatures {
676/// set_requesting_sid: true,
677/// ..BinderFeatures::default(),
678/// }
679/// ```
680#[derive(Clone, Debug, Default, Eq, PartialEq)]
681pub struct BinderFeatures {
682 /// Indicates that the service intends to receive caller security contexts. This must be true
683 /// for `ThreadState::with_calling_sid` to work.
Janis Danisevskis1323d512021-11-09 07:48:08 -0800684 #[cfg(not(android_vndk))]
Andrew Walbran88eca4f2021-04-13 14:26:01 +0000685 pub set_requesting_sid: bool,
686 // Ensure that clients include a ..BinderFeatures::default() to preserve backwards compatibility
687 // when new fields are added. #[non_exhaustive] doesn't work because it prevents struct
688 // expressions entirely.
689 #[doc(hidden)]
690 pub _non_exhaustive: (),
691}
692
Stephen Crane2a3c2502020-06-16 17:48:35 -0700693/// Declare typed interfaces for a binder object.
694///
695/// Given an interface trait and descriptor string, create a native and remote
696/// proxy wrapper for this interface. The native service object (`$native`)
697/// implements `Remotable` and will dispatch to the function `$on_transact` to
698/// handle transactions. The typed proxy object (`$proxy`) wraps remote binder
699/// objects for this interface and can optionally contain additional fields.
700///
701/// Assuming the interface trait is `Interface`, `$on_transact` function must
702/// have the following type:
703///
704/// ```
Alice Ryhl8618c482021-11-09 15:35:35 +0000705/// # use binder::{Interface, TransactionCode, BorrowedParcel};
Stephen Crane2a3c2502020-06-16 17:48:35 -0700706/// # trait Placeholder {
707/// fn on_transact(
708/// service: &dyn Interface,
709/// code: TransactionCode,
Alice Ryhl8618c482021-11-09 15:35:35 +0000710/// data: &BorrowedParcel,
711/// reply: &mut BorrowedParcel,
Stephen Crane2a3c2502020-06-16 17:48:35 -0700712/// ) -> binder::Result<()>;
713/// # }
714/// ```
715///
716/// # Examples
717///
718/// The following example declares the local service type `BnServiceManager` and
719/// a remote proxy type `BpServiceManager` (the `n` and `p` stand for native and
720/// proxy respectively) for the `IServiceManager` Binder interface. The
721/// interfaces will be identified by the descriptor string
722/// "android.os.IServiceManager". The local service will dispatch transactions
723/// using the provided function, `on_transact`.
724///
725/// ```
Alice Ryhl8618c482021-11-09 15:35:35 +0000726/// use binder::{declare_binder_interface, Binder, Interface, TransactionCode, BorrowedParcel};
Stephen Crane2a3c2502020-06-16 17:48:35 -0700727///
728/// pub trait IServiceManager: Interface {
729/// // remote methods...
730/// }
731///
732/// declare_binder_interface! {
733/// IServiceManager["android.os.IServiceManager"] {
734/// native: BnServiceManager(on_transact),
735/// proxy: BpServiceManager,
736/// }
737/// }
738///
739/// fn on_transact(
740/// service: &dyn IServiceManager,
741/// code: TransactionCode,
Alice Ryhl8618c482021-11-09 15:35:35 +0000742/// data: &BorrowedParcel,
743/// reply: &mut BorrowedParcel,
Stephen Crane2a3c2502020-06-16 17:48:35 -0700744/// ) -> binder::Result<()> {
745/// // ...
746/// Ok(())
747/// }
748///
749/// impl IServiceManager for BpServiceManager {
750/// // parceling/unparceling code for the IServiceManager emitted here
751/// }
752///
753/// impl IServiceManager for Binder<BnServiceManager> {
754/// // Forward calls to local implementation
755/// }
756/// ```
757#[macro_export]
758macro_rules! declare_binder_interface {
759 {
760 $interface:path[$descriptor:expr] {
761 native: $native:ident($on_transact:path),
762 proxy: $proxy:ident,
Alice Ryhl05f5a2c2021-09-15 12:56:10 +0000763 $(async: $async_interface:ident,)?
Stephen Crane2a3c2502020-06-16 17:48:35 -0700764 }
765 } => {
766 $crate::declare_binder_interface! {
767 $interface[$descriptor] {
768 native: $native($on_transact),
769 proxy: $proxy {},
Alice Ryhl05f5a2c2021-09-15 12:56:10 +0000770 $(async: $async_interface,)?
Stephen Cranef2735b42022-01-19 17:49:46 +0000771 stability: $crate::binder_impl::Stability::default(),
Stephen Craneff7f03a2021-02-25 16:04:22 -0800772 }
773 }
774 };
775
776 {
777 $interface:path[$descriptor:expr] {
778 native: $native:ident($on_transact:path),
779 proxy: $proxy:ident,
Alice Ryhl05f5a2c2021-09-15 12:56:10 +0000780 $(async: $async_interface:ident,)?
Stephen Craneff7f03a2021-02-25 16:04:22 -0800781 stability: $stability:expr,
782 }
783 } => {
784 $crate::declare_binder_interface! {
785 $interface[$descriptor] {
786 native: $native($on_transact),
787 proxy: $proxy {},
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 native: $native:ident($on_transact:path),
797 proxy: $proxy:ident {
798 $($fname:ident: $fty:ty = $finit:expr),*
799 },
Alice Ryhl05f5a2c2021-09-15 12:56:10 +0000800 $(async: $async_interface:ident,)?
Stephen Crane2a3c2502020-06-16 17:48:35 -0700801 }
802 } => {
803 $crate::declare_binder_interface! {
804 $interface[$descriptor] {
Stephen Craneff7f03a2021-02-25 16:04:22 -0800805 native: $native($on_transact),
806 proxy: $proxy {
807 $($fname: $fty = $finit),*
808 },
Alice Ryhl05f5a2c2021-09-15 12:56:10 +0000809 $(async: $async_interface,)?
Stephen Cranef2735b42022-01-19 17:49:46 +0000810 stability: $crate::binder_impl::Stability::default(),
Stephen Craneff7f03a2021-02-25 16:04:22 -0800811 }
812 }
813 };
814
815 {
816 $interface:path[$descriptor:expr] {
817 native: $native:ident($on_transact:path),
818 proxy: $proxy:ident {
819 $($fname:ident: $fty:ty = $finit:expr),*
820 },
Alice Ryhl05f5a2c2021-09-15 12:56:10 +0000821 $(async: $async_interface:ident,)?
Stephen Craneff7f03a2021-02-25 16:04:22 -0800822 stability: $stability:expr,
823 }
824 } => {
825 $crate::declare_binder_interface! {
826 $interface[$descriptor] {
Stephen Cranef2735b42022-01-19 17:49:46 +0000827 @doc[concat!("A binder [`Remotable`]($crate::binder_impl::Remotable) that holds an [`", stringify!($interface), "`] object.")]
Stephen Crane2a3c2502020-06-16 17:48:35 -0700828 native: $native($on_transact),
Stephen Cranef2735b42022-01-19 17:49:46 +0000829 @doc[concat!("A binder [`Proxy`]($crate::binder_impl::Proxy) that holds an [`", stringify!($interface), "`] remote interface.")]
Stephen Crane2a3c2502020-06-16 17:48:35 -0700830 proxy: $proxy {
831 $($fname: $fty = $finit),*
832 },
Alice Ryhl05f5a2c2021-09-15 12:56:10 +0000833 $(async: $async_interface,)?
Stephen Craneff7f03a2021-02-25 16:04:22 -0800834 stability: $stability,
Stephen Crane2a3c2502020-06-16 17:48:35 -0700835 }
836 }
837 };
838
839 {
840 $interface:path[$descriptor:expr] {
841 @doc[$native_doc:expr]
842 native: $native:ident($on_transact:path),
843
844 @doc[$proxy_doc:expr]
845 proxy: $proxy:ident {
846 $($fname:ident: $fty:ty = $finit:expr),*
847 },
Stephen Craneff7f03a2021-02-25 16:04:22 -0800848
Alice Ryhl05f5a2c2021-09-15 12:56:10 +0000849 $( async: $async_interface:ident, )?
850
Stephen Craneff7f03a2021-02-25 16:04:22 -0800851 stability: $stability:expr,
Stephen Crane2a3c2502020-06-16 17:48:35 -0700852 }
853 } => {
854 #[doc = $proxy_doc]
855 pub struct $proxy {
856 binder: $crate::SpIBinder,
857 $($fname: $fty,)*
858 }
859
860 impl $crate::Interface for $proxy {
861 fn as_binder(&self) -> $crate::SpIBinder {
862 self.binder.clone()
863 }
864 }
865
Stephen Cranef2735b42022-01-19 17:49:46 +0000866 impl $crate::binder_impl::Proxy for $proxy
Stephen Crane2a3c2502020-06-16 17:48:35 -0700867 where
868 $proxy: $interface,
869 {
870 fn get_descriptor() -> &'static str {
871 $descriptor
872 }
873
Stephen Cranef2735b42022-01-19 17:49:46 +0000874 fn from_binder(mut binder: $crate::SpIBinder) -> std::result::Result<Self, $crate::StatusCode> {
Stephen Crane669deb62020-09-10 17:31:39 -0700875 Ok(Self { binder, $($fname: $finit),* })
Stephen Crane2a3c2502020-06-16 17:48:35 -0700876 }
877 }
878
879 #[doc = $native_doc]
880 #[repr(transparent)]
881 pub struct $native(Box<dyn $interface + Sync + Send + 'static>);
882
883 impl $native {
884 /// Create a new binder service.
Andrew Walbran88eca4f2021-04-13 14:26:01 +0000885 pub fn new_binder<T: $interface + Sync + Send + 'static>(inner: T, features: $crate::BinderFeatures) -> $crate::Strong<dyn $interface> {
Stephen Cranef2735b42022-01-19 17:49:46 +0000886 let mut binder = $crate::binder_impl::Binder::new_with_stability($native(Box::new(inner)), $stability);
Janis Danisevskis1323d512021-11-09 07:48:08 -0800887 #[cfg(not(android_vndk))]
Stephen Cranef2735b42022-01-19 17:49:46 +0000888 $crate::binder_impl::IBinderInternal::set_requesting_sid(&mut binder, features.set_requesting_sid);
Stephen Craneddb3e6d2020-12-18 13:27:22 -0800889 $crate::Strong::new(Box::new(binder))
Stephen Crane2a3c2502020-06-16 17:48:35 -0700890 }
891 }
892
Stephen Cranef2735b42022-01-19 17:49:46 +0000893 impl $crate::binder_impl::Remotable for $native {
Stephen Crane2a3c2502020-06-16 17:48:35 -0700894 fn get_descriptor() -> &'static str {
895 $descriptor
896 }
897
Stephen Cranef2735b42022-01-19 17:49:46 +0000898 fn on_transact(&self, code: $crate::binder_impl::TransactionCode, data: &$crate::binder_impl::BorrowedParcel<'_>, reply: &mut $crate::binder_impl::BorrowedParcel<'_>) -> std::result::Result<(), $crate::StatusCode> {
Andrei Homescu32814372020-08-20 15:36:08 -0700899 match $on_transact(&*self.0, code, data, reply) {
900 // The C++ backend converts UNEXPECTED_NULL into an exception
901 Err($crate::StatusCode::UNEXPECTED_NULL) => {
902 let status = $crate::Status::new_exception(
903 $crate::ExceptionCode::NULL_POINTER,
904 None,
905 );
906 reply.write(&status)
907 },
908 result => result
909 }
Stephen Crane2a3c2502020-06-16 17:48:35 -0700910 }
911
Stephen Cranef2735b42022-01-19 17:49:46 +0000912 fn on_dump(&self, file: &std::fs::File, args: &[&std::ffi::CStr]) -> std::result::Result<(), $crate::StatusCode> {
Stephen Crane2a3297f2021-06-11 16:48:10 -0700913 self.0.dump(file, args)
914 }
915
Stephen Cranef2735b42022-01-19 17:49:46 +0000916 fn get_class() -> $crate::binder_impl::InterfaceClass {
Stephen Crane2a3c2502020-06-16 17:48:35 -0700917 static CLASS_INIT: std::sync::Once = std::sync::Once::new();
Stephen Cranef2735b42022-01-19 17:49:46 +0000918 static mut CLASS: Option<$crate::binder_impl::InterfaceClass> = None;
Stephen Crane2a3c2502020-06-16 17:48:35 -0700919
920 CLASS_INIT.call_once(|| unsafe {
921 // Safety: This assignment is guarded by the `CLASS_INIT` `Once`
922 // variable, and therefore is thread-safe, as it can only occur
923 // once.
Stephen Cranef2735b42022-01-19 17:49:46 +0000924 CLASS = Some($crate::binder_impl::InterfaceClass::new::<$crate::binder_impl::Binder<$native>>());
Stephen Crane2a3c2502020-06-16 17:48:35 -0700925 });
926 unsafe {
927 // Safety: The `CLASS` variable can only be mutated once, above,
928 // and is subsequently safe to read from any thread.
929 CLASS.unwrap()
930 }
931 }
932 }
933
934 impl $crate::FromIBinder for dyn $interface {
Stephen Cranef2735b42022-01-19 17:49:46 +0000935 fn try_from(mut ibinder: $crate::SpIBinder) -> std::result::Result<$crate::Strong<dyn $interface>, $crate::StatusCode> {
936 use $crate::binder_impl::AssociateClass;
Stephen Crane669deb62020-09-10 17:31:39 -0700937
938 let existing_class = ibinder.get_class();
939 if let Some(class) = existing_class {
Stephen Cranef2735b42022-01-19 17:49:46 +0000940 if class != <$native as $crate::binder_impl::Remotable>::get_class() &&
941 class.get_descriptor() == <$native as $crate::binder_impl::Remotable>::get_descriptor()
Stephen Crane669deb62020-09-10 17:31:39 -0700942 {
943 // The binder object's descriptor string matches what we
944 // expect. We still need to treat this local or already
945 // associated object as remote, because we can't cast it
946 // into a Rust service object without a matching class
947 // pointer.
Stephen Cranef2735b42022-01-19 17:49:46 +0000948 return Ok($crate::Strong::new(Box::new(<$proxy as $crate::binder_impl::Proxy>::from_binder(ibinder)?)));
Stephen Crane669deb62020-09-10 17:31:39 -0700949 }
Stephen Crane2a3c2502020-06-16 17:48:35 -0700950 }
951
Stephen Cranef2735b42022-01-19 17:49:46 +0000952 if ibinder.associate_class(<$native as $crate::binder_impl::Remotable>::get_class()) {
953 let service: std::result::Result<$crate::binder_impl::Binder<$native>, $crate::StatusCode> =
Stephen Crane669deb62020-09-10 17:31:39 -0700954 std::convert::TryFrom::try_from(ibinder.clone());
955 if let Ok(service) = service {
956 // We were able to associate with our expected class and
957 // the service is local.
Stephen Craneddb3e6d2020-12-18 13:27:22 -0800958 return Ok($crate::Strong::new(Box::new(service)));
Stephen Crane669deb62020-09-10 17:31:39 -0700959 } else {
960 // Service is remote
Stephen Cranef2735b42022-01-19 17:49:46 +0000961 return Ok($crate::Strong::new(Box::new(<$proxy as $crate::binder_impl::Proxy>::from_binder(ibinder)?)));
Stephen Crane669deb62020-09-10 17:31:39 -0700962 }
Matthew Maurerf6b9ad92020-12-03 19:27:25 +0000963 }
Stephen Crane669deb62020-09-10 17:31:39 -0700964
965 Err($crate::StatusCode::BAD_TYPE.into())
Stephen Crane2a3c2502020-06-16 17:48:35 -0700966 }
967 }
968
Stephen Cranef2735b42022-01-19 17:49:46 +0000969 impl $crate::binder_impl::Serialize for dyn $interface + '_
Stephen Crane2a3c2502020-06-16 17:48:35 -0700970 where
Stephen Craned58bce02020-07-07 12:26:02 -0700971 dyn $interface: $crate::Interface
Stephen Crane2a3c2502020-06-16 17:48:35 -0700972 {
Stephen Cranef2735b42022-01-19 17:49:46 +0000973 fn serialize(&self, parcel: &mut $crate::binder_impl::BorrowedParcel<'_>) -> std::result::Result<(), $crate::StatusCode> {
Stephen Crane2a3c2502020-06-16 17:48:35 -0700974 let binder = $crate::Interface::as_binder(self);
975 parcel.write(&binder)
976 }
977 }
978
Stephen Cranef2735b42022-01-19 17:49:46 +0000979 impl $crate::binder_impl::SerializeOption for dyn $interface + '_ {
980 fn serialize_option(this: Option<&Self>, parcel: &mut $crate::binder_impl::BorrowedParcel<'_>) -> std::result::Result<(), $crate::StatusCode> {
Stephen Crane2a3c2502020-06-16 17:48:35 -0700981 parcel.write(&this.map($crate::Interface::as_binder))
982 }
983 }
Andrei Homescu2e3c1472020-08-11 16:35:40 -0700984
Alice Ryhl05f5a2c2021-09-15 12:56:10 +0000985 impl std::fmt::Debug for dyn $interface + '_ {
Andrei Homescu2e3c1472020-08-11 16:35:40 -0700986 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
987 f.pad(stringify!($interface))
988 }
989 }
Andrei Homescu64ebd132020-08-07 22:12:48 -0700990
Stephen Craneddb3e6d2020-12-18 13:27:22 -0800991 /// Convert a &dyn $interface to Strong<dyn $interface>
Andrei Homescu64ebd132020-08-07 22:12:48 -0700992 impl std::borrow::ToOwned for dyn $interface {
Stephen Craneddb3e6d2020-12-18 13:27:22 -0800993 type Owned = $crate::Strong<dyn $interface>;
Andrei Homescu64ebd132020-08-07 22:12:48 -0700994 fn to_owned(&self) -> Self::Owned {
995 self.as_binder().into_interface()
996 .expect(concat!("Error cloning interface ", stringify!($interface)))
997 }
998 }
Alice Ryhl05f5a2c2021-09-15 12:56:10 +0000999
1000 $(
1001 // Async interface trait implementations.
1002 impl<P: $crate::BinderAsyncPool> $crate::FromIBinder for dyn $async_interface<P> {
Stephen Cranef2735b42022-01-19 17:49:46 +00001003 fn try_from(mut ibinder: $crate::SpIBinder) -> std::result::Result<$crate::Strong<dyn $async_interface<P>>, $crate::StatusCode> {
1004 use $crate::binder_impl::AssociateClass;
Alice Ryhl05f5a2c2021-09-15 12:56:10 +00001005
1006 let existing_class = ibinder.get_class();
1007 if let Some(class) = existing_class {
Stephen Cranef2735b42022-01-19 17:49:46 +00001008 if class != <$native as $crate::binder_impl::Remotable>::get_class() &&
1009 class.get_descriptor() == <$native as $crate::binder_impl::Remotable>::get_descriptor()
Alice Ryhl05f5a2c2021-09-15 12:56:10 +00001010 {
1011 // The binder object's descriptor string matches what we
1012 // expect. We still need to treat this local or already
1013 // associated object as remote, because we can't cast it
1014 // into a Rust service object without a matching class
1015 // pointer.
Stephen Cranef2735b42022-01-19 17:49:46 +00001016 return Ok($crate::Strong::new(Box::new(<$proxy as $crate::binder_impl::Proxy>::from_binder(ibinder)?)));
Alice Ryhl05f5a2c2021-09-15 12:56:10 +00001017 }
1018 }
1019
Stephen Cranef2735b42022-01-19 17:49:46 +00001020 if ibinder.associate_class(<$native as $crate::binder_impl::Remotable>::get_class()) {
1021 let service: std::result::Result<$crate::binder_impl::Binder<$native>, $crate::StatusCode> =
Alice Ryhl05f5a2c2021-09-15 12:56:10 +00001022 std::convert::TryFrom::try_from(ibinder.clone());
1023 if let Ok(service) = service {
1024 // We were able to associate with our expected class and
1025 // the service is local.
1026 todo!()
1027 //return Ok($crate::Strong::new(Box::new(service)));
1028 } else {
1029 // Service is remote
Stephen Cranef2735b42022-01-19 17:49:46 +00001030 return Ok($crate::Strong::new(Box::new(<$proxy as $crate::binder_impl::Proxy>::from_binder(ibinder)?)));
Alice Ryhl05f5a2c2021-09-15 12:56:10 +00001031 }
1032 }
1033
1034 Err($crate::StatusCode::BAD_TYPE.into())
1035 }
1036 }
1037
Stephen Cranef2735b42022-01-19 17:49:46 +00001038 impl<P: $crate::BinderAsyncPool> $crate::binder_impl::Serialize for dyn $async_interface<P> + '_ {
1039 fn serialize(&self, parcel: &mut $crate::binder_impl::BorrowedParcel<'_>) -> std::result::Result<(), $crate::StatusCode> {
Alice Ryhl05f5a2c2021-09-15 12:56:10 +00001040 let binder = $crate::Interface::as_binder(self);
1041 parcel.write(&binder)
1042 }
1043 }
1044
Stephen Cranef2735b42022-01-19 17:49:46 +00001045 impl<P: $crate::BinderAsyncPool> $crate::binder_impl::SerializeOption for dyn $async_interface<P> + '_ {
1046 fn serialize_option(this: Option<&Self>, parcel: &mut $crate::binder_impl::BorrowedParcel<'_>) -> std::result::Result<(), $crate::StatusCode> {
Alice Ryhl05f5a2c2021-09-15 12:56:10 +00001047 parcel.write(&this.map($crate::Interface::as_binder))
1048 }
1049 }
1050
1051 impl<P: $crate::BinderAsyncPool> std::fmt::Debug for dyn $async_interface<P> + '_ {
1052 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
1053 f.pad(stringify!($async_interface))
1054 }
1055 }
1056
1057 /// Convert a &dyn $async_interface to Strong<dyn $async_interface>
1058 impl<P: $crate::BinderAsyncPool> std::borrow::ToOwned for dyn $async_interface<P> {
1059 type Owned = $crate::Strong<dyn $async_interface<P>>;
1060 fn to_owned(&self) -> Self::Owned {
1061 self.as_binder().into_interface()
1062 .expect(concat!("Error cloning interface ", stringify!($async_interface)))
1063 }
1064 }
Alice Ryhlc1736842021-11-23 12:38:51 +00001065
Stephen Cranef2735b42022-01-19 17:49:46 +00001066 impl<P: $crate::BinderAsyncPool> $crate::binder_impl::ToAsyncInterface<P> for dyn $interface {
Alice Ryhlc1736842021-11-23 12:38:51 +00001067 type Target = dyn $async_interface<P>;
1068 }
1069
Stephen Cranef2735b42022-01-19 17:49:46 +00001070 impl<P: $crate::BinderAsyncPool> $crate::binder_impl::ToSyncInterface for dyn $async_interface<P> {
Alice Ryhlc1736842021-11-23 12:38:51 +00001071 type Target = dyn $interface;
1072 }
Alice Ryhl05f5a2c2021-09-15 12:56:10 +00001073 )?
Stephen Crane2a3c2502020-06-16 17:48:35 -07001074 };
1075}
Andrei Homescu00eca712020-09-09 18:57:40 -07001076
1077/// Declare an AIDL enumeration.
1078///
1079/// This is mainly used internally by the AIDL compiler.
1080#[macro_export]
1081macro_rules! declare_binder_enum {
1082 {
Stephen Crane7bca1052021-10-25 17:52:51 -07001083 $( #[$attr:meta] )*
Andrei Homescu7f38cf92021-06-29 23:55:43 +00001084 $enum:ident : [$backing:ty; $size:expr] {
Jooyung Han70d92812022-03-18 15:29:54 +09001085 $( $( #[$value_attr:meta] )* $name:ident = $value:expr, )*
Andrei Homescu00eca712020-09-09 18:57:40 -07001086 }
1087 } => {
Stephen Crane7bca1052021-10-25 17:52:51 -07001088 $( #[$attr] )*
Andrei Homescuc06cfc32022-09-30 02:46:27 +00001089 #[derive(Default, Copy, Clone, PartialOrd, Ord, PartialEq, Eq, Hash)]
Stephen Crane7bca1052021-10-25 17:52:51 -07001090 #[allow(missing_docs)]
Andrei Homescu00eca712020-09-09 18:57:40 -07001091 pub struct $enum(pub $backing);
1092 impl $enum {
Jooyung Han70d92812022-03-18 15:29:54 +09001093 $( $( #[$value_attr] )* #[allow(missing_docs)] pub const $name: Self = Self($value); )*
Andrei Homescu7f38cf92021-06-29 23:55:43 +00001094
1095 #[inline(always)]
Stephen Crane7bca1052021-10-25 17:52:51 -07001096 #[allow(missing_docs)]
Andrei Homescu7f38cf92021-06-29 23:55:43 +00001097 pub const fn enum_values() -> [Self; $size] {
1098 [$(Self::$name),*]
1099 }
Andrei Homescu00eca712020-09-09 18:57:40 -07001100 }
1101
Andrei Homescuc06cfc32022-09-30 02:46:27 +00001102 impl std::fmt::Debug for $enum {
1103 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
1104 match self.0 {
1105 $($value => f.write_str(stringify!($name)),)*
1106 _ => f.write_fmt(format_args!("{}", self.0))
1107 }
1108 }
1109 }
1110
Stephen Cranef2735b42022-01-19 17:49:46 +00001111 impl $crate::binder_impl::Serialize for $enum {
1112 fn serialize(&self, parcel: &mut $crate::binder_impl::BorrowedParcel<'_>) -> std::result::Result<(), $crate::StatusCode> {
Andrei Homescu00eca712020-09-09 18:57:40 -07001113 parcel.write(&self.0)
1114 }
1115 }
1116
Stephen Cranef2735b42022-01-19 17:49:46 +00001117 impl $crate::binder_impl::SerializeArray for $enum {
1118 fn serialize_array(slice: &[Self], parcel: &mut $crate::binder_impl::BorrowedParcel<'_>) -> std::result::Result<(), $crate::StatusCode> {
Andrei Homescu00eca712020-09-09 18:57:40 -07001119 let v: Vec<$backing> = slice.iter().map(|x| x.0).collect();
Stephen Cranef2735b42022-01-19 17:49:46 +00001120 <$backing as $crate::binder_impl::SerializeArray>::serialize_array(&v[..], parcel)
Andrei Homescu00eca712020-09-09 18:57:40 -07001121 }
1122 }
1123
Stephen Cranef2735b42022-01-19 17:49:46 +00001124 impl $crate::binder_impl::Deserialize for $enum {
1125 fn deserialize(parcel: &$crate::binder_impl::BorrowedParcel<'_>) -> std::result::Result<Self, $crate::StatusCode> {
Andrei Homescu00eca712020-09-09 18:57:40 -07001126 parcel.read().map(Self)
1127 }
1128 }
1129
Stephen Cranef2735b42022-01-19 17:49:46 +00001130 impl $crate::binder_impl::DeserializeArray for $enum {
1131 fn deserialize_array(parcel: &$crate::binder_impl::BorrowedParcel<'_>) -> std::result::Result<Option<Vec<Self>>, $crate::StatusCode> {
Andrei Homescu00eca712020-09-09 18:57:40 -07001132 let v: Option<Vec<$backing>> =
Stephen Cranef2735b42022-01-19 17:49:46 +00001133 <$backing as $crate::binder_impl::DeserializeArray>::deserialize_array(parcel)?;
Andrei Homescu00eca712020-09-09 18:57:40 -07001134 Ok(v.map(|v| v.into_iter().map(Self).collect()))
1135 }
1136 }
1137 };
1138}