blob: 854b1f9d4e4e6a66875b1ccddc2a214bb44f2b2e [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};
Stephen Crane2a3c2502020-06-16 17:48:35 -070020use crate::parcel::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.
170 fn set_requesting_sid(&mut self, enable: bool);
171
Stephen Crane2a3c2502020-06-16 17:48:35 -0700172 /// Dump this object to the given file handle
173 fn dump<F: AsRawFd>(&mut self, fp: &F, args: &[&str]) -> Result<()>;
174
175 /// Get a new interface that exposes additional extension functionality, if
176 /// available.
177 fn get_extension(&mut self) -> Result<Option<SpIBinder>>;
178
Alice Ryhlfeba6ca2021-08-19 10:47:04 +0000179 /// Create a Parcel that can be used with `submit_transact`.
180 fn prepare_transact(&self) -> Result<Parcel>;
181
Stephen Crane2a3c2502020-06-16 17:48:35 -0700182 /// Perform a generic operation with the object.
183 ///
Alice Ryhlfeba6ca2021-08-19 10:47:04 +0000184 /// The provided [`Parcel`] must have been created by a call to
185 /// `prepare_transact` on the same binder.
186 ///
187 /// # Arguments
188 ///
189 /// * `code` - Transaction code for the operation.
190 /// * `data` - [`Parcel`] with input data.
191 /// * `flags` - Transaction flags, e.g. marking the transaction as
192 /// asynchronous ([`FLAG_ONEWAY`](FLAG_ONEWAY)).
193 fn submit_transact(
194 &self,
195 code: TransactionCode,
196 data: Parcel,
197 flags: TransactionFlags,
198 ) -> Result<Parcel>;
199
200 /// Perform a generic operation with the object. This is a convenience
201 /// method that internally calls `prepare_transact` followed by
202 /// `submit_transact.
203 ///
Stephen Crane2a3c2502020-06-16 17:48:35 -0700204 /// # Arguments
205 /// * `code` - Transaction code for the operation
Stephen Crane2a3c2502020-06-16 17:48:35 -0700206 /// * `flags` - Transaction flags, e.g. marking the transaction as
Andrew Walbran12400d82021-03-04 17:04:34 +0000207 /// asynchronous ([`FLAG_ONEWAY`](FLAG_ONEWAY))
Alice Ryhlfeba6ca2021-08-19 10:47:04 +0000208 /// * `input_callback` A callback for building the `Parcel`.
Stephen Crane2a3c2502020-06-16 17:48:35 -0700209 fn transact<F: FnOnce(&mut Parcel) -> Result<()>>(
210 &self,
211 code: TransactionCode,
212 flags: TransactionFlags,
213 input_callback: F,
Alice Ryhlfeba6ca2021-08-19 10:47:04 +0000214 ) -> Result<Parcel> {
215 let mut parcel = self.prepare_transact()?;
216 input_callback(&mut parcel)?;
217 self.submit_transact(code, parcel, flags)
218 }
Andrew Walbran12400d82021-03-04 17:04:34 +0000219}
Stephen Crane2a3c2502020-06-16 17:48:35 -0700220
Andrew Walbran12400d82021-03-04 17:04:34 +0000221/// Interface of binder local or remote objects.
222///
223/// This trait corresponds to the parts of the interface of the C++ `IBinder`
224/// class which are public.
225pub trait IBinder {
Stephen Crane2a3c2502020-06-16 17:48:35 -0700226 /// Register the recipient for a notification if this binder
227 /// goes away. If this binder object unexpectedly goes away
228 /// (typically because its hosting process has been killed),
Andrew Walbran12400d82021-03-04 17:04:34 +0000229 /// then the `DeathRecipient`'s callback will be called.
Stephen Crane2a3c2502020-06-16 17:48:35 -0700230 ///
231 /// You will only receive death notifications for remote binders,
232 /// as local binders by definition can't die without you dying as well.
233 /// Trying to use this function on a local binder will result in an
234 /// INVALID_OPERATION code being returned and nothing happening.
235 ///
236 /// This link always holds a weak reference to its recipient.
Stephen Crane2a3c2502020-06-16 17:48:35 -0700237 fn link_to_death(&mut self, recipient: &mut DeathRecipient) -> Result<()>;
238
239 /// Remove a previously registered death notification.
240 /// The recipient will no longer be called if this object
241 /// dies.
242 fn unlink_to_death(&mut self, recipient: &mut DeathRecipient) -> Result<()>;
243}
244
245/// Opaque reference to the type of a Binder interface.
246///
247/// This object encapsulates the Binder interface descriptor string, along with
248/// the binder transaction callback, if the class describes a local service.
249///
250/// A Binder remotable object may only have a single interface class, and any
251/// given object can only be associated with one class. Two objects with
252/// different classes are incompatible, even if both classes have the same
253/// interface descriptor.
254#[derive(Copy, Clone, PartialEq, Eq)]
255pub struct InterfaceClass(*const sys::AIBinder_Class);
256
257impl InterfaceClass {
258 /// Get a Binder NDK `AIBinder_Class` pointer for this object type.
259 ///
260 /// Note: the returned pointer will not be constant. Calling this method
261 /// multiple times for the same type will result in distinct class
262 /// pointers. A static getter for this value is implemented in
263 /// [`declare_binder_interface!`].
264 pub fn new<I: InterfaceClassMethods>() -> InterfaceClass {
265 let descriptor = CString::new(I::get_descriptor()).unwrap();
266 let ptr = unsafe {
267 // Safety: `AIBinder_Class_define` expects a valid C string, and
268 // three valid callback functions, all non-null pointers. The C
269 // string is copied and need not be valid for longer than the call,
270 // so we can drop it after the call. We can safely assign null to
271 // the onDump and handleShellCommand callbacks as long as the class
272 // pointer was non-null. Rust None for a Option<fn> is guaranteed to
273 // be a NULL pointer. Rust retains ownership of the pointer after it
274 // is defined.
275 let class = sys::AIBinder_Class_define(
276 descriptor.as_ptr(),
277 Some(I::on_create),
278 Some(I::on_destroy),
279 Some(I::on_transact),
280 );
281 if class.is_null() {
282 panic!("Expected non-null class pointer from AIBinder_Class_define!");
283 }
Stephen Crane2a3297f2021-06-11 16:48:10 -0700284 sys::AIBinder_Class_setOnDump(class, Some(I::on_dump));
Stephen Crane2a3c2502020-06-16 17:48:35 -0700285 sys::AIBinder_Class_setHandleShellCommand(class, None);
286 class
287 };
288 InterfaceClass(ptr)
289 }
290
291 /// Construct an `InterfaceClass` out of a raw, non-null `AIBinder_Class`
292 /// pointer.
293 ///
294 /// # Safety
295 ///
296 /// This function is safe iff `ptr` is a valid, non-null pointer to an
297 /// `AIBinder_Class`.
298 pub(crate) unsafe fn from_ptr(ptr: *const sys::AIBinder_Class) -> InterfaceClass {
299 InterfaceClass(ptr)
300 }
Stephen Crane669deb62020-09-10 17:31:39 -0700301
302 /// Get the interface descriptor string of this class.
303 pub fn get_descriptor(&self) -> String {
304 unsafe {
305 // SAFETY: The descriptor returned by AIBinder_Class_getDescriptor
306 // is always a two-byte null terminated sequence of u16s. Thus, we
307 // can continue reading from the pointer until we hit a null value,
308 // and this pointer can be a valid slice if the slice length is <=
309 // the number of u16 elements before the null terminator.
310
311 let raw_descriptor: *const c_char = sys::AIBinder_Class_getDescriptor(self.0);
Andrew Walbran12400d82021-03-04 17:04:34 +0000312 CStr::from_ptr(raw_descriptor)
313 .to_str()
Stephen Crane669deb62020-09-10 17:31:39 -0700314 .expect("Expected valid UTF-8 string from AIBinder_Class_getDescriptor")
315 .into()
316 }
317 }
Stephen Crane2a3c2502020-06-16 17:48:35 -0700318}
319
320impl From<InterfaceClass> for *const sys::AIBinder_Class {
321 fn from(class: InterfaceClass) -> *const sys::AIBinder_Class {
322 class.0
323 }
324}
325
Stephen Craneddb3e6d2020-12-18 13:27:22 -0800326/// Strong reference to a binder object
327pub struct Strong<I: FromIBinder + ?Sized>(Box<I>);
328
329impl<I: FromIBinder + ?Sized> Strong<I> {
330 /// Create a new strong reference to the provided binder object
331 pub fn new(binder: Box<I>) -> Self {
332 Self(binder)
333 }
334
335 /// Construct a new weak reference to this binder
336 pub fn downgrade(this: &Strong<I>) -> Weak<I> {
337 Weak::new(this)
338 }
339}
340
341impl<I: FromIBinder + ?Sized> Clone for Strong<I> {
342 fn clone(&self) -> Self {
343 // Since we hold a strong reference, we should always be able to create
344 // a new strong reference to the same interface type, so try_from()
345 // should never fail here.
346 FromIBinder::try_from(self.0.as_binder()).unwrap()
347 }
348}
349
350impl<I: FromIBinder + ?Sized> Borrow<I> for Strong<I> {
351 fn borrow(&self) -> &I {
352 &self.0
353 }
354}
355
356impl<I: FromIBinder + ?Sized> AsRef<I> for Strong<I> {
357 fn as_ref(&self) -> &I {
358 &self.0
359 }
360}
361
362impl<I: FromIBinder + ?Sized> Deref for Strong<I> {
363 type Target = I;
364
365 fn deref(&self) -> &Self::Target {
366 &self.0
367 }
368}
369
370impl<I: FromIBinder + fmt::Debug + ?Sized> fmt::Debug for Strong<I> {
371 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
372 fmt::Debug::fmt(&**self, f)
373 }
374}
375
376impl<I: FromIBinder + ?Sized> Ord for Strong<I> {
377 fn cmp(&self, other: &Self) -> Ordering {
378 self.0.as_binder().cmp(&other.0.as_binder())
379 }
380}
381
382impl<I: FromIBinder + ?Sized> PartialOrd for Strong<I> {
383 fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
384 self.0.as_binder().partial_cmp(&other.0.as_binder())
385 }
386}
387
388impl<I: FromIBinder + ?Sized> PartialEq for Strong<I> {
389 fn eq(&self, other: &Self) -> bool {
390 self.0.as_binder().eq(&other.0.as_binder())
391 }
392}
393
394impl<I: FromIBinder + ?Sized> Eq for Strong<I> {}
395
396/// Weak reference to a binder object
397#[derive(Debug)]
398pub struct Weak<I: FromIBinder + ?Sized> {
399 weak_binder: WpIBinder,
400 interface_type: PhantomData<I>,
401}
402
403impl<I: FromIBinder + ?Sized> Weak<I> {
404 /// Construct a new weak reference from a strong reference
405 fn new(binder: &Strong<I>) -> Self {
406 let weak_binder = binder.as_binder().downgrade();
407 Weak {
408 weak_binder,
409 interface_type: PhantomData,
410 }
411 }
412
413 /// Upgrade this weak reference to a strong reference if the binder object
414 /// is still alive
415 pub fn upgrade(&self) -> Result<Strong<I>> {
416 self.weak_binder
417 .promote()
418 .ok_or(StatusCode::DEAD_OBJECT)
419 .and_then(FromIBinder::try_from)
420 }
421}
422
423impl<I: FromIBinder + ?Sized> Clone for Weak<I> {
424 fn clone(&self) -> Self {
425 Self {
426 weak_binder: self.weak_binder.clone(),
427 interface_type: PhantomData,
428 }
429 }
430}
431
432impl<I: FromIBinder + ?Sized> Ord for Weak<I> {
433 fn cmp(&self, other: &Self) -> Ordering {
434 self.weak_binder.cmp(&other.weak_binder)
435 }
436}
437
438impl<I: FromIBinder + ?Sized> PartialOrd for Weak<I> {
439 fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
440 self.weak_binder.partial_cmp(&other.weak_binder)
441 }
442}
443
444impl<I: FromIBinder + ?Sized> PartialEq for Weak<I> {
445 fn eq(&self, other: &Self) -> bool {
446 self.weak_binder == other.weak_binder
447 }
448}
449
450impl<I: FromIBinder + ?Sized> Eq for Weak<I> {}
451
Stephen Crane2a3c2502020-06-16 17:48:35 -0700452/// Create a function implementing a static getter for an interface class.
453///
454/// Each binder interface (i.e. local [`Remotable`] service or remote proxy
455/// [`Interface`]) must have global, static class that uniquely identifies
456/// it. This macro implements an [`InterfaceClass`] getter to simplify these
457/// implementations.
458///
459/// The type of a structure that implements [`InterfaceClassMethods`] must be
460/// passed to this macro. For local services, this should be `Binder<Self>`
461/// since [`Binder`] implements [`InterfaceClassMethods`].
462///
463/// # Examples
464///
465/// When implementing a local [`Remotable`] service `ExampleService`, the
466/// `get_class` method is required in the [`Remotable`] impl block. This macro
467/// should be used as follows to implement this functionality:
468///
469/// ```rust
470/// impl Remotable for ExampleService {
471/// fn get_descriptor() -> &'static str {
472/// "android.os.IExampleInterface"
473/// }
474///
475/// fn on_transact(
476/// &self,
477/// code: TransactionCode,
478/// data: &Parcel,
479/// reply: &mut Parcel,
480/// ) -> Result<()> {
481/// // ...
482/// }
483///
484/// binder_fn_get_class!(Binder<Self>);
485/// }
486/// ```
487macro_rules! binder_fn_get_class {
488 ($class:ty) => {
489 binder_fn_get_class!($crate::InterfaceClass::new::<$class>());
490 };
491
492 ($constructor:expr) => {
493 fn get_class() -> $crate::InterfaceClass {
494 static CLASS_INIT: std::sync::Once = std::sync::Once::new();
495 static mut CLASS: Option<$crate::InterfaceClass> = None;
496
497 CLASS_INIT.call_once(|| unsafe {
498 // Safety: This assignment is guarded by the `CLASS_INIT` `Once`
499 // variable, and therefore is thread-safe, as it can only occur
500 // once.
501 CLASS = Some($constructor);
502 });
503 unsafe {
504 // Safety: The `CLASS` variable can only be mutated once, above,
505 // and is subsequently safe to read from any thread.
506 CLASS.unwrap()
507 }
508 }
509 };
510}
511
512pub trait InterfaceClassMethods {
513 /// Get the interface descriptor string for this object type.
514 fn get_descriptor() -> &'static str
515 where
516 Self: Sized;
517
518 /// Called during construction of a new `AIBinder` object of this interface
519 /// class.
520 ///
521 /// The opaque pointer parameter will be the parameter provided to
522 /// `AIBinder_new`. Returns an opaque userdata to be associated with the new
523 /// `AIBinder` object.
524 ///
525 /// # Safety
526 ///
527 /// Callback called from C++. The parameter argument provided to
528 /// `AIBinder_new` must match the type expected here. The `AIBinder` object
529 /// will take ownership of the returned pointer, which it will free via
530 /// `on_destroy`.
531 unsafe extern "C" fn on_create(args: *mut c_void) -> *mut c_void;
532
533 /// Called when a transaction needs to be processed by the local service
534 /// implementation.
535 ///
536 /// # Safety
537 ///
538 /// Callback called from C++. The `binder` parameter must be a valid pointer
539 /// to a binder object of this class with userdata initialized via this
540 /// class's `on_create`. The parcel parameters must be valid pointers to
541 /// parcel objects.
542 unsafe extern "C" fn on_transact(
543 binder: *mut sys::AIBinder,
544 code: u32,
545 data: *const sys::AParcel,
546 reply: *mut sys::AParcel,
547 ) -> status_t;
548
549 /// Called whenever an `AIBinder` object is no longer referenced and needs
550 /// to be destroyed.
551 ///
552 /// # Safety
553 ///
554 /// Callback called from C++. The opaque pointer parameter must be the value
555 /// returned by `on_create` for this class. This function takes ownership of
556 /// the provided pointer and destroys it.
557 unsafe extern "C" fn on_destroy(object: *mut c_void);
Stephen Crane2a3297f2021-06-11 16:48:10 -0700558
559 /// Called to handle the `dump` transaction.
560 ///
561 /// # Safety
562 ///
563 /// Must be called with a non-null, valid pointer to a local `AIBinder` that
564 /// contains a `T` pointer in its user data. fd should be a non-owned file
565 /// descriptor, and args must be an array of null-terminated string
566 /// poiinters with length num_args.
567 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 -0700568}
569
570/// Interface for transforming a generic SpIBinder into a specific remote
571/// interface trait.
572///
573/// # Example
574///
575/// For Binder interface `IFoo`, the following implementation should be made:
576/// ```no_run
577/// # use binder::{FromIBinder, SpIBinder, Result};
578/// # trait IFoo {}
579/// impl FromIBinder for dyn IFoo {
580/// fn try_from(ibinder: SpIBinder) -> Result<Box<Self>> {
581/// // ...
582/// # Err(binder::StatusCode::OK)
583/// }
584/// }
585/// ```
Stephen Craneddb3e6d2020-12-18 13:27:22 -0800586pub trait FromIBinder: Interface {
Stephen Crane2a3c2502020-06-16 17:48:35 -0700587 /// Try to interpret a generic Binder object as this interface.
588 ///
589 /// Returns a trait object for the `Self` interface if this object
590 /// implements that interface.
Stephen Craneddb3e6d2020-12-18 13:27:22 -0800591 fn try_from(ibinder: SpIBinder) -> Result<Strong<Self>>;
Stephen Crane2a3c2502020-06-16 17:48:35 -0700592}
593
594/// Trait for transparent Rust wrappers around android C++ native types.
595///
596/// The pointer return by this trait's methods should be immediately passed to
597/// C++ and not stored by Rust. The pointer is valid only as long as the
598/// underlying C++ object is alive, so users must be careful to take this into
599/// account, as Rust cannot enforce this.
600///
601/// # Safety
602///
603/// For this trait to be a correct implementation, `T` must be a valid android
604/// C++ type. Since we cannot constrain this via the type system, this trait is
605/// marked as unsafe.
606pub unsafe trait AsNative<T> {
607 /// Return a pointer to the native version of `self`
608 fn as_native(&self) -> *const T;
609
610 /// Return a mutable pointer to the native version of `self`
611 fn as_native_mut(&mut self) -> *mut T;
612}
613
614unsafe impl<T, V: AsNative<T>> AsNative<T> for Option<V> {
615 fn as_native(&self) -> *const T {
616 self.as_ref().map_or(ptr::null(), |v| v.as_native())
617 }
618
619 fn as_native_mut(&mut self) -> *mut T {
620 self.as_mut().map_or(ptr::null_mut(), |v| v.as_native_mut())
621 }
622}
623
Andrew Walbran88eca4f2021-04-13 14:26:01 +0000624/// The features to enable when creating a native Binder.
625///
626/// This should always be initialised with a default value, e.g.:
627/// ```
628/// # use binder::BinderFeatures;
629/// BinderFeatures {
630/// set_requesting_sid: true,
631/// ..BinderFeatures::default(),
632/// }
633/// ```
634#[derive(Clone, Debug, Default, Eq, PartialEq)]
635pub struct BinderFeatures {
636 /// Indicates that the service intends to receive caller security contexts. This must be true
637 /// for `ThreadState::with_calling_sid` to work.
638 pub set_requesting_sid: bool,
639 // Ensure that clients include a ..BinderFeatures::default() to preserve backwards compatibility
640 // when new fields are added. #[non_exhaustive] doesn't work because it prevents struct
641 // expressions entirely.
642 #[doc(hidden)]
643 pub _non_exhaustive: (),
644}
645
Stephen Crane2a3c2502020-06-16 17:48:35 -0700646/// Declare typed interfaces for a binder object.
647///
648/// Given an interface trait and descriptor string, create a native and remote
649/// proxy wrapper for this interface. The native service object (`$native`)
650/// implements `Remotable` and will dispatch to the function `$on_transact` to
651/// handle transactions. The typed proxy object (`$proxy`) wraps remote binder
652/// objects for this interface and can optionally contain additional fields.
653///
654/// Assuming the interface trait is `Interface`, `$on_transact` function must
655/// have the following type:
656///
657/// ```
658/// # use binder::{Interface, TransactionCode, Parcel};
659/// # trait Placeholder {
660/// fn on_transact(
661/// service: &dyn Interface,
662/// code: TransactionCode,
663/// data: &Parcel,
664/// reply: &mut Parcel,
665/// ) -> binder::Result<()>;
666/// # }
667/// ```
668///
669/// # Examples
670///
671/// The following example declares the local service type `BnServiceManager` and
672/// a remote proxy type `BpServiceManager` (the `n` and `p` stand for native and
673/// proxy respectively) for the `IServiceManager` Binder interface. The
674/// interfaces will be identified by the descriptor string
675/// "android.os.IServiceManager". The local service will dispatch transactions
676/// using the provided function, `on_transact`.
677///
678/// ```
679/// use binder::{declare_binder_interface, Binder, Interface, TransactionCode, Parcel};
680///
681/// pub trait IServiceManager: Interface {
682/// // remote methods...
683/// }
684///
685/// declare_binder_interface! {
686/// IServiceManager["android.os.IServiceManager"] {
687/// native: BnServiceManager(on_transact),
688/// proxy: BpServiceManager,
689/// }
690/// }
691///
692/// fn on_transact(
693/// service: &dyn IServiceManager,
694/// code: TransactionCode,
695/// data: &Parcel,
696/// reply: &mut Parcel,
697/// ) -> binder::Result<()> {
698/// // ...
699/// Ok(())
700/// }
701///
702/// impl IServiceManager for BpServiceManager {
703/// // parceling/unparceling code for the IServiceManager emitted here
704/// }
705///
706/// impl IServiceManager for Binder<BnServiceManager> {
707/// // Forward calls to local implementation
708/// }
709/// ```
710#[macro_export]
711macro_rules! declare_binder_interface {
712 {
713 $interface:path[$descriptor:expr] {
714 native: $native:ident($on_transact:path),
715 proxy: $proxy:ident,
716 }
717 } => {
718 $crate::declare_binder_interface! {
719 $interface[$descriptor] {
720 native: $native($on_transact),
721 proxy: $proxy {},
Stephen Craneff7f03a2021-02-25 16:04:22 -0800722 stability: $crate::Stability::default(),
723 }
724 }
725 };
726
727 {
728 $interface:path[$descriptor:expr] {
729 native: $native:ident($on_transact:path),
730 proxy: $proxy:ident,
731 stability: $stability:expr,
732 }
733 } => {
734 $crate::declare_binder_interface! {
735 $interface[$descriptor] {
736 native: $native($on_transact),
737 proxy: $proxy {},
738 stability: $stability,
Stephen Crane2a3c2502020-06-16 17:48:35 -0700739 }
740 }
741 };
742
743 {
744 $interface:path[$descriptor:expr] {
745 native: $native:ident($on_transact:path),
746 proxy: $proxy:ident {
747 $($fname:ident: $fty:ty = $finit:expr),*
748 },
749 }
750 } => {
751 $crate::declare_binder_interface! {
752 $interface[$descriptor] {
Stephen Craneff7f03a2021-02-25 16:04:22 -0800753 native: $native($on_transact),
754 proxy: $proxy {
755 $($fname: $fty = $finit),*
756 },
757 stability: $crate::Stability::default(),
758 }
759 }
760 };
761
762 {
763 $interface:path[$descriptor:expr] {
764 native: $native:ident($on_transact:path),
765 proxy: $proxy:ident {
766 $($fname:ident: $fty:ty = $finit:expr),*
767 },
768 stability: $stability:expr,
769 }
770 } => {
771 $crate::declare_binder_interface! {
772 $interface[$descriptor] {
Stephen Crane2a3c2502020-06-16 17:48:35 -0700773 @doc[concat!("A binder [`Remotable`]($crate::Remotable) that holds an [`", stringify!($interface), "`] object.")]
774 native: $native($on_transact),
775 @doc[concat!("A binder [`Proxy`]($crate::Proxy) that holds an [`", stringify!($interface), "`] remote interface.")]
776 proxy: $proxy {
777 $($fname: $fty = $finit),*
778 },
Stephen Craneff7f03a2021-02-25 16:04:22 -0800779 stability: $stability,
Stephen Crane2a3c2502020-06-16 17:48:35 -0700780 }
781 }
782 };
783
784 {
785 $interface:path[$descriptor:expr] {
786 @doc[$native_doc:expr]
787 native: $native:ident($on_transact:path),
788
789 @doc[$proxy_doc:expr]
790 proxy: $proxy:ident {
791 $($fname:ident: $fty:ty = $finit:expr),*
792 },
Stephen Craneff7f03a2021-02-25 16:04:22 -0800793
794 stability: $stability:expr,
Stephen Crane2a3c2502020-06-16 17:48:35 -0700795 }
796 } => {
797 #[doc = $proxy_doc]
798 pub struct $proxy {
799 binder: $crate::SpIBinder,
800 $($fname: $fty,)*
801 }
802
803 impl $crate::Interface for $proxy {
804 fn as_binder(&self) -> $crate::SpIBinder {
805 self.binder.clone()
806 }
807 }
808
809 impl $crate::Proxy for $proxy
810 where
811 $proxy: $interface,
812 {
813 fn get_descriptor() -> &'static str {
814 $descriptor
815 }
816
817 fn from_binder(mut binder: $crate::SpIBinder) -> $crate::Result<Self> {
Stephen Crane669deb62020-09-10 17:31:39 -0700818 Ok(Self { binder, $($fname: $finit),* })
Stephen Crane2a3c2502020-06-16 17:48:35 -0700819 }
820 }
821
822 #[doc = $native_doc]
823 #[repr(transparent)]
824 pub struct $native(Box<dyn $interface + Sync + Send + 'static>);
825
826 impl $native {
827 /// Create a new binder service.
Andrew Walbran88eca4f2021-04-13 14:26:01 +0000828 pub fn new_binder<T: $interface + Sync + Send + 'static>(inner: T, features: $crate::BinderFeatures) -> $crate::Strong<dyn $interface> {
829 let mut binder = $crate::Binder::new_with_stability($native(Box::new(inner)), $stability);
830 $crate::IBinderInternal::set_requesting_sid(&mut binder, features.set_requesting_sid);
Stephen Craneddb3e6d2020-12-18 13:27:22 -0800831 $crate::Strong::new(Box::new(binder))
Stephen Crane2a3c2502020-06-16 17:48:35 -0700832 }
833 }
834
835 impl $crate::Remotable for $native {
836 fn get_descriptor() -> &'static str {
837 $descriptor
838 }
839
840 fn on_transact(&self, code: $crate::TransactionCode, data: &$crate::Parcel, reply: &mut $crate::Parcel) -> $crate::Result<()> {
Andrei Homescu32814372020-08-20 15:36:08 -0700841 match $on_transact(&*self.0, code, data, reply) {
842 // The C++ backend converts UNEXPECTED_NULL into an exception
843 Err($crate::StatusCode::UNEXPECTED_NULL) => {
844 let status = $crate::Status::new_exception(
845 $crate::ExceptionCode::NULL_POINTER,
846 None,
847 );
848 reply.write(&status)
849 },
850 result => result
851 }
Stephen Crane2a3c2502020-06-16 17:48:35 -0700852 }
853
Stephen Crane2a3297f2021-06-11 16:48:10 -0700854 fn on_dump(&self, file: &std::fs::File, args: &[&std::ffi::CStr]) -> $crate::Result<()> {
855 self.0.dump(file, args)
856 }
857
Stephen Crane2a3c2502020-06-16 17:48:35 -0700858 fn get_class() -> $crate::InterfaceClass {
859 static CLASS_INIT: std::sync::Once = std::sync::Once::new();
860 static mut CLASS: Option<$crate::InterfaceClass> = None;
861
862 CLASS_INIT.call_once(|| unsafe {
863 // Safety: This assignment is guarded by the `CLASS_INIT` `Once`
864 // variable, and therefore is thread-safe, as it can only occur
865 // once.
866 CLASS = Some($crate::InterfaceClass::new::<$crate::Binder<$native>>());
867 });
868 unsafe {
869 // Safety: The `CLASS` variable can only be mutated once, above,
870 // and is subsequently safe to read from any thread.
871 CLASS.unwrap()
872 }
873 }
874 }
875
876 impl $crate::FromIBinder for dyn $interface {
Stephen Craneddb3e6d2020-12-18 13:27:22 -0800877 fn try_from(mut ibinder: $crate::SpIBinder) -> $crate::Result<$crate::Strong<dyn $interface>> {
Stephen Crane2a3c2502020-06-16 17:48:35 -0700878 use $crate::AssociateClass;
Stephen Crane669deb62020-09-10 17:31:39 -0700879
880 let existing_class = ibinder.get_class();
881 if let Some(class) = existing_class {
882 if class != <$native as $crate::Remotable>::get_class() &&
883 class.get_descriptor() == <$native as $crate::Remotable>::get_descriptor()
884 {
885 // The binder object's descriptor string matches what we
886 // expect. We still need to treat this local or already
887 // associated object as remote, because we can't cast it
888 // into a Rust service object without a matching class
889 // pointer.
Stephen Craneddb3e6d2020-12-18 13:27:22 -0800890 return Ok($crate::Strong::new(Box::new(<$proxy as $crate::Proxy>::from_binder(ibinder)?)));
Stephen Crane669deb62020-09-10 17:31:39 -0700891 }
Stephen Crane2a3c2502020-06-16 17:48:35 -0700892 }
893
Stephen Crane669deb62020-09-10 17:31:39 -0700894 if ibinder.associate_class(<$native as $crate::Remotable>::get_class()) {
895 let service: $crate::Result<$crate::Binder<$native>> =
896 std::convert::TryFrom::try_from(ibinder.clone());
897 if let Ok(service) = service {
898 // We were able to associate with our expected class and
899 // the service is local.
Stephen Craneddb3e6d2020-12-18 13:27:22 -0800900 return Ok($crate::Strong::new(Box::new(service)));
Stephen Crane669deb62020-09-10 17:31:39 -0700901 } else {
902 // Service is remote
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 }
Matthew Maurerf6b9ad92020-12-03 19:27:25 +0000905 }
Stephen Crane669deb62020-09-10 17:31:39 -0700906
907 Err($crate::StatusCode::BAD_TYPE.into())
Stephen Crane2a3c2502020-06-16 17:48:35 -0700908 }
909 }
910
911 impl $crate::parcel::Serialize for dyn $interface + '_
912 where
Stephen Craned58bce02020-07-07 12:26:02 -0700913 dyn $interface: $crate::Interface
Stephen Crane2a3c2502020-06-16 17:48:35 -0700914 {
915 fn serialize(&self, parcel: &mut $crate::parcel::Parcel) -> $crate::Result<()> {
916 let binder = $crate::Interface::as_binder(self);
917 parcel.write(&binder)
918 }
919 }
920
921 impl $crate::parcel::SerializeOption for dyn $interface + '_ {
922 fn serialize_option(this: Option<&Self>, parcel: &mut $crate::parcel::Parcel) -> $crate::Result<()> {
923 parcel.write(&this.map($crate::Interface::as_binder))
924 }
925 }
Andrei Homescu2e3c1472020-08-11 16:35:40 -0700926
927 impl std::fmt::Debug for dyn $interface {
928 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
929 f.pad(stringify!($interface))
930 }
931 }
Andrei Homescu64ebd132020-08-07 22:12:48 -0700932
Stephen Craneddb3e6d2020-12-18 13:27:22 -0800933 /// Convert a &dyn $interface to Strong<dyn $interface>
Andrei Homescu64ebd132020-08-07 22:12:48 -0700934 impl std::borrow::ToOwned for dyn $interface {
Stephen Craneddb3e6d2020-12-18 13:27:22 -0800935 type Owned = $crate::Strong<dyn $interface>;
Andrei Homescu64ebd132020-08-07 22:12:48 -0700936 fn to_owned(&self) -> Self::Owned {
937 self.as_binder().into_interface()
938 .expect(concat!("Error cloning interface ", stringify!($interface)))
939 }
940 }
Stephen Crane2a3c2502020-06-16 17:48:35 -0700941 };
942}
Andrei Homescu00eca712020-09-09 18:57:40 -0700943
944/// Declare an AIDL enumeration.
945///
946/// This is mainly used internally by the AIDL compiler.
947#[macro_export]
948macro_rules! declare_binder_enum {
949 {
Andrei Homescu7f38cf92021-06-29 23:55:43 +0000950 $enum:ident : [$backing:ty; $size:expr] {
Andrei Homescu00eca712020-09-09 18:57:40 -0700951 $( $name:ident = $value:expr, )*
952 }
953 } => {
954 #[derive(Debug, Default, Copy, Clone, PartialOrd, Ord, PartialEq, Eq, Hash)]
955 pub struct $enum(pub $backing);
956 impl $enum {
957 $( pub const $name: Self = Self($value); )*
Andrei Homescu7f38cf92021-06-29 23:55:43 +0000958
959 #[inline(always)]
960 pub const fn enum_values() -> [Self; $size] {
961 [$(Self::$name),*]
962 }
Andrei Homescu00eca712020-09-09 18:57:40 -0700963 }
964
965 impl $crate::parcel::Serialize for $enum {
966 fn serialize(&self, parcel: &mut $crate::parcel::Parcel) -> $crate::Result<()> {
967 parcel.write(&self.0)
968 }
969 }
970
971 impl $crate::parcel::SerializeArray for $enum {
972 fn serialize_array(slice: &[Self], parcel: &mut $crate::parcel::Parcel) -> $crate::Result<()> {
973 let v: Vec<$backing> = slice.iter().map(|x| x.0).collect();
974 <$backing as binder::parcel::SerializeArray>::serialize_array(&v[..], parcel)
975 }
976 }
977
978 impl $crate::parcel::Deserialize for $enum {
979 fn deserialize(parcel: &$crate::parcel::Parcel) -> $crate::Result<Self> {
980 parcel.read().map(Self)
981 }
982 }
983
984 impl $crate::parcel::DeserializeArray for $enum {
985 fn deserialize_array(parcel: &$crate::parcel::Parcel) -> $crate::Result<Option<Vec<Self>>> {
986 let v: Option<Vec<$backing>> =
987 <$backing as binder::parcel::DeserializeArray>::deserialize_array(parcel)?;
988 Ok(v.map(|v| v.into_iter().map(Self).collect()))
989 }
990 }
991 };
992}