blob: 4e048d7c5a6e91048e59c82ecc1d5e8298c250a3 [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.
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`.
Alice Ryhl268458c2021-09-15 12:56:10 +0000180 fn prepare_transact(&self) -> Result<OwnedParcel>;
Alice Ryhlfeba6ca2021-08-19 10:47:04 +0000181
Stephen Crane2a3c2502020-06-16 17:48:35 -0700182 /// Perform a generic operation with the object.
183 ///
Alice Ryhl268458c2021-09-15 12:56:10 +0000184 /// The provided [`OwnedParcel`] must have been created by a call to
Alice Ryhlfeba6ca2021-08-19 10:47:04 +0000185 /// `prepare_transact` on the same binder.
186 ///
187 /// # Arguments
188 ///
189 /// * `code` - Transaction code for the operation.
Alice Ryhl268458c2021-09-15 12:56:10 +0000190 /// * `data` - [`OwnedParcel`] with input data.
Alice Ryhlfeba6ca2021-08-19 10:47:04 +0000191 /// * `flags` - Transaction flags, e.g. marking the transaction as
192 /// asynchronous ([`FLAG_ONEWAY`](FLAG_ONEWAY)).
193 fn submit_transact(
194 &self,
195 code: TransactionCode,
Alice Ryhl268458c2021-09-15 12:56:10 +0000196 data: OwnedParcel,
Alice Ryhlfeba6ca2021-08-19 10:47:04 +0000197 flags: TransactionFlags,
Alice Ryhl268458c2021-09-15 12:56:10 +0000198 ) -> Result<OwnedParcel>;
Alice Ryhlfeba6ca2021-08-19 10:47:04 +0000199
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()?;
Alice Ryhl268458c2021-09-15 12:56:10 +0000216 input_callback(&mut parcel.borrowed())?;
217 self.submit_transact(code, parcel, flags).map(OwnedParcel::into_parcel)
Alice Ryhlfeba6ca2021-08-19 10:47:04 +0000218 }
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,
Alice Ryhl05f5a2c2021-09-15 12:56:10 +0000716 $(async: $async_interface:ident,)?
Stephen Crane2a3c2502020-06-16 17:48:35 -0700717 }
718 } => {
719 $crate::declare_binder_interface! {
720 $interface[$descriptor] {
721 native: $native($on_transact),
722 proxy: $proxy {},
Alice Ryhl05f5a2c2021-09-15 12:56:10 +0000723 $(async: $async_interface,)?
Stephen Craneff7f03a2021-02-25 16:04:22 -0800724 stability: $crate::Stability::default(),
725 }
726 }
727 };
728
729 {
730 $interface:path[$descriptor:expr] {
731 native: $native:ident($on_transact:path),
732 proxy: $proxy:ident,
Alice Ryhl05f5a2c2021-09-15 12:56:10 +0000733 $(async: $async_interface:ident,)?
Stephen Craneff7f03a2021-02-25 16:04:22 -0800734 stability: $stability:expr,
735 }
736 } => {
737 $crate::declare_binder_interface! {
738 $interface[$descriptor] {
739 native: $native($on_transact),
740 proxy: $proxy {},
Alice Ryhl05f5a2c2021-09-15 12:56:10 +0000741 $(async: $async_interface,)?
Stephen Craneff7f03a2021-02-25 16:04:22 -0800742 stability: $stability,
Stephen Crane2a3c2502020-06-16 17:48:35 -0700743 }
744 }
745 };
746
747 {
748 $interface:path[$descriptor:expr] {
749 native: $native:ident($on_transact:path),
750 proxy: $proxy:ident {
751 $($fname:ident: $fty:ty = $finit:expr),*
752 },
Alice Ryhl05f5a2c2021-09-15 12:56:10 +0000753 $(async: $async_interface:ident,)?
Stephen Crane2a3c2502020-06-16 17:48:35 -0700754 }
755 } => {
756 $crate::declare_binder_interface! {
757 $interface[$descriptor] {
Stephen Craneff7f03a2021-02-25 16:04:22 -0800758 native: $native($on_transact),
759 proxy: $proxy {
760 $($fname: $fty = $finit),*
761 },
Alice Ryhl05f5a2c2021-09-15 12:56:10 +0000762 $(async: $async_interface,)?
Stephen Craneff7f03a2021-02-25 16:04:22 -0800763 stability: $crate::Stability::default(),
764 }
765 }
766 };
767
768 {
769 $interface:path[$descriptor:expr] {
770 native: $native:ident($on_transact:path),
771 proxy: $proxy:ident {
772 $($fname:ident: $fty:ty = $finit:expr),*
773 },
Alice Ryhl05f5a2c2021-09-15 12:56:10 +0000774 $(async: $async_interface:ident,)?
Stephen Craneff7f03a2021-02-25 16:04:22 -0800775 stability: $stability:expr,
776 }
777 } => {
778 $crate::declare_binder_interface! {
779 $interface[$descriptor] {
Stephen Crane2a3c2502020-06-16 17:48:35 -0700780 @doc[concat!("A binder [`Remotable`]($crate::Remotable) that holds an [`", stringify!($interface), "`] object.")]
781 native: $native($on_transact),
782 @doc[concat!("A binder [`Proxy`]($crate::Proxy) that holds an [`", stringify!($interface), "`] remote interface.")]
783 proxy: $proxy {
784 $($fname: $fty = $finit),*
785 },
Alice Ryhl05f5a2c2021-09-15 12:56:10 +0000786 $(async: $async_interface,)?
Stephen Craneff7f03a2021-02-25 16:04:22 -0800787 stability: $stability,
Stephen Crane2a3c2502020-06-16 17:48:35 -0700788 }
789 }
790 };
791
792 {
793 $interface:path[$descriptor:expr] {
794 @doc[$native_doc:expr]
795 native: $native:ident($on_transact:path),
796
797 @doc[$proxy_doc:expr]
798 proxy: $proxy:ident {
799 $($fname:ident: $fty:ty = $finit:expr),*
800 },
Stephen Craneff7f03a2021-02-25 16:04:22 -0800801
Alice Ryhl05f5a2c2021-09-15 12:56:10 +0000802 $( async: $async_interface:ident, )?
803
Stephen Craneff7f03a2021-02-25 16:04:22 -0800804 stability: $stability:expr,
Stephen Crane2a3c2502020-06-16 17:48:35 -0700805 }
806 } => {
807 #[doc = $proxy_doc]
808 pub struct $proxy {
809 binder: $crate::SpIBinder,
810 $($fname: $fty,)*
811 }
812
813 impl $crate::Interface for $proxy {
814 fn as_binder(&self) -> $crate::SpIBinder {
815 self.binder.clone()
816 }
817 }
818
819 impl $crate::Proxy for $proxy
820 where
821 $proxy: $interface,
822 {
823 fn get_descriptor() -> &'static str {
824 $descriptor
825 }
826
827 fn from_binder(mut binder: $crate::SpIBinder) -> $crate::Result<Self> {
Stephen Crane669deb62020-09-10 17:31:39 -0700828 Ok(Self { binder, $($fname: $finit),* })
Stephen Crane2a3c2502020-06-16 17:48:35 -0700829 }
830 }
831
832 #[doc = $native_doc]
833 #[repr(transparent)]
834 pub struct $native(Box<dyn $interface + Sync + Send + 'static>);
835
836 impl $native {
837 /// Create a new binder service.
Andrew Walbran88eca4f2021-04-13 14:26:01 +0000838 pub fn new_binder<T: $interface + Sync + Send + 'static>(inner: T, features: $crate::BinderFeatures) -> $crate::Strong<dyn $interface> {
839 let mut binder = $crate::Binder::new_with_stability($native(Box::new(inner)), $stability);
840 $crate::IBinderInternal::set_requesting_sid(&mut binder, features.set_requesting_sid);
Stephen Craneddb3e6d2020-12-18 13:27:22 -0800841 $crate::Strong::new(Box::new(binder))
Stephen Crane2a3c2502020-06-16 17:48:35 -0700842 }
843 }
844
845 impl $crate::Remotable for $native {
846 fn get_descriptor() -> &'static str {
847 $descriptor
848 }
849
850 fn on_transact(&self, code: $crate::TransactionCode, data: &$crate::Parcel, reply: &mut $crate::Parcel) -> $crate::Result<()> {
Andrei Homescu32814372020-08-20 15:36:08 -0700851 match $on_transact(&*self.0, code, data, reply) {
852 // The C++ backend converts UNEXPECTED_NULL into an exception
853 Err($crate::StatusCode::UNEXPECTED_NULL) => {
854 let status = $crate::Status::new_exception(
855 $crate::ExceptionCode::NULL_POINTER,
856 None,
857 );
858 reply.write(&status)
859 },
860 result => result
861 }
Stephen Crane2a3c2502020-06-16 17:48:35 -0700862 }
863
Stephen Crane2a3297f2021-06-11 16:48:10 -0700864 fn on_dump(&self, file: &std::fs::File, args: &[&std::ffi::CStr]) -> $crate::Result<()> {
865 self.0.dump(file, args)
866 }
867
Stephen Crane2a3c2502020-06-16 17:48:35 -0700868 fn get_class() -> $crate::InterfaceClass {
869 static CLASS_INIT: std::sync::Once = std::sync::Once::new();
870 static mut CLASS: Option<$crate::InterfaceClass> = None;
871
872 CLASS_INIT.call_once(|| unsafe {
873 // Safety: This assignment is guarded by the `CLASS_INIT` `Once`
874 // variable, and therefore is thread-safe, as it can only occur
875 // once.
876 CLASS = Some($crate::InterfaceClass::new::<$crate::Binder<$native>>());
877 });
878 unsafe {
879 // Safety: The `CLASS` variable can only be mutated once, above,
880 // and is subsequently safe to read from any thread.
881 CLASS.unwrap()
882 }
883 }
884 }
885
886 impl $crate::FromIBinder for dyn $interface {
Stephen Craneddb3e6d2020-12-18 13:27:22 -0800887 fn try_from(mut ibinder: $crate::SpIBinder) -> $crate::Result<$crate::Strong<dyn $interface>> {
Stephen Crane2a3c2502020-06-16 17:48:35 -0700888 use $crate::AssociateClass;
Stephen Crane669deb62020-09-10 17:31:39 -0700889
890 let existing_class = ibinder.get_class();
891 if let Some(class) = existing_class {
892 if class != <$native as $crate::Remotable>::get_class() &&
893 class.get_descriptor() == <$native as $crate::Remotable>::get_descriptor()
894 {
895 // The binder object's descriptor string matches what we
896 // expect. We still need to treat this local or already
897 // associated object as remote, because we can't cast it
898 // into a Rust service object without a matching class
899 // pointer.
Stephen Craneddb3e6d2020-12-18 13:27:22 -0800900 return Ok($crate::Strong::new(Box::new(<$proxy as $crate::Proxy>::from_binder(ibinder)?)));
Stephen Crane669deb62020-09-10 17:31:39 -0700901 }
Stephen Crane2a3c2502020-06-16 17:48:35 -0700902 }
903
Stephen Crane669deb62020-09-10 17:31:39 -0700904 if ibinder.associate_class(<$native as $crate::Remotable>::get_class()) {
905 let service: $crate::Result<$crate::Binder<$native>> =
906 std::convert::TryFrom::try_from(ibinder.clone());
907 if let Ok(service) = service {
908 // We were able to associate with our expected class and
909 // the service is local.
Stephen Craneddb3e6d2020-12-18 13:27:22 -0800910 return Ok($crate::Strong::new(Box::new(service)));
Stephen Crane669deb62020-09-10 17:31:39 -0700911 } else {
912 // Service is remote
Stephen Craneddb3e6d2020-12-18 13:27:22 -0800913 return Ok($crate::Strong::new(Box::new(<$proxy as $crate::Proxy>::from_binder(ibinder)?)));
Stephen Crane669deb62020-09-10 17:31:39 -0700914 }
Matthew Maurerf6b9ad92020-12-03 19:27:25 +0000915 }
Stephen Crane669deb62020-09-10 17:31:39 -0700916
917 Err($crate::StatusCode::BAD_TYPE.into())
Stephen Crane2a3c2502020-06-16 17:48:35 -0700918 }
919 }
920
921 impl $crate::parcel::Serialize for dyn $interface + '_
922 where
Stephen Craned58bce02020-07-07 12:26:02 -0700923 dyn $interface: $crate::Interface
Stephen Crane2a3c2502020-06-16 17:48:35 -0700924 {
925 fn serialize(&self, parcel: &mut $crate::parcel::Parcel) -> $crate::Result<()> {
926 let binder = $crate::Interface::as_binder(self);
927 parcel.write(&binder)
928 }
929 }
930
931 impl $crate::parcel::SerializeOption for dyn $interface + '_ {
932 fn serialize_option(this: Option<&Self>, parcel: &mut $crate::parcel::Parcel) -> $crate::Result<()> {
933 parcel.write(&this.map($crate::Interface::as_binder))
934 }
935 }
Andrei Homescu2e3c1472020-08-11 16:35:40 -0700936
Alice Ryhl05f5a2c2021-09-15 12:56:10 +0000937 impl std::fmt::Debug for dyn $interface + '_ {
Andrei Homescu2e3c1472020-08-11 16:35:40 -0700938 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
939 f.pad(stringify!($interface))
940 }
941 }
Andrei Homescu64ebd132020-08-07 22:12:48 -0700942
Stephen Craneddb3e6d2020-12-18 13:27:22 -0800943 /// Convert a &dyn $interface to Strong<dyn $interface>
Andrei Homescu64ebd132020-08-07 22:12:48 -0700944 impl std::borrow::ToOwned for dyn $interface {
Stephen Craneddb3e6d2020-12-18 13:27:22 -0800945 type Owned = $crate::Strong<dyn $interface>;
Andrei Homescu64ebd132020-08-07 22:12:48 -0700946 fn to_owned(&self) -> Self::Owned {
947 self.as_binder().into_interface()
948 .expect(concat!("Error cloning interface ", stringify!($interface)))
949 }
950 }
Alice Ryhl05f5a2c2021-09-15 12:56:10 +0000951
952 $(
953 // Async interface trait implementations.
954 impl<P: $crate::BinderAsyncPool> $crate::FromIBinder for dyn $async_interface<P> {
955 fn try_from(mut ibinder: $crate::SpIBinder) -> $crate::Result<$crate::Strong<dyn $async_interface<P>>> {
956 use $crate::AssociateClass;
957
958 let existing_class = ibinder.get_class();
959 if let Some(class) = existing_class {
960 if class != <$native as $crate::Remotable>::get_class() &&
961 class.get_descriptor() == <$native as $crate::Remotable>::get_descriptor()
962 {
963 // The binder object's descriptor string matches what we
964 // expect. We still need to treat this local or already
965 // associated object as remote, because we can't cast it
966 // into a Rust service object without a matching class
967 // pointer.
968 return Ok($crate::Strong::new(Box::new(<$proxy as $crate::Proxy>::from_binder(ibinder)?)));
969 }
970 }
971
972 if ibinder.associate_class(<$native as $crate::Remotable>::get_class()) {
973 let service: $crate::Result<$crate::Binder<$native>> =
974 std::convert::TryFrom::try_from(ibinder.clone());
975 if let Ok(service) = service {
976 // We were able to associate with our expected class and
977 // the service is local.
978 todo!()
979 //return Ok($crate::Strong::new(Box::new(service)));
980 } else {
981 // Service is remote
982 return Ok($crate::Strong::new(Box::new(<$proxy as $crate::Proxy>::from_binder(ibinder)?)));
983 }
984 }
985
986 Err($crate::StatusCode::BAD_TYPE.into())
987 }
988 }
989
990 impl<P: $crate::BinderAsyncPool> $crate::parcel::Serialize for dyn $async_interface<P> + '_ {
991 fn serialize(&self, parcel: &mut $crate::parcel::Parcel) -> $crate::Result<()> {
992 let binder = $crate::Interface::as_binder(self);
993 parcel.write(&binder)
994 }
995 }
996
997 impl<P: $crate::BinderAsyncPool> $crate::parcel::SerializeOption for dyn $async_interface<P> + '_ {
998 fn serialize_option(this: Option<&Self>, parcel: &mut $crate::parcel::Parcel) -> $crate::Result<()> {
999 parcel.write(&this.map($crate::Interface::as_binder))
1000 }
1001 }
1002
1003 impl<P: $crate::BinderAsyncPool> std::fmt::Debug for dyn $async_interface<P> + '_ {
1004 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
1005 f.pad(stringify!($async_interface))
1006 }
1007 }
1008
1009 /// Convert a &dyn $async_interface to Strong<dyn $async_interface>
1010 impl<P: $crate::BinderAsyncPool> std::borrow::ToOwned for dyn $async_interface<P> {
1011 type Owned = $crate::Strong<dyn $async_interface<P>>;
1012 fn to_owned(&self) -> Self::Owned {
1013 self.as_binder().into_interface()
1014 .expect(concat!("Error cloning interface ", stringify!($async_interface)))
1015 }
1016 }
1017 )?
Stephen Crane2a3c2502020-06-16 17:48:35 -07001018 };
1019}
Andrei Homescu00eca712020-09-09 18:57:40 -07001020
1021/// Declare an AIDL enumeration.
1022///
1023/// This is mainly used internally by the AIDL compiler.
1024#[macro_export]
1025macro_rules! declare_binder_enum {
1026 {
Andrei Homescu7f38cf92021-06-29 23:55:43 +00001027 $enum:ident : [$backing:ty; $size:expr] {
Andrei Homescu00eca712020-09-09 18:57:40 -07001028 $( $name:ident = $value:expr, )*
1029 }
1030 } => {
1031 #[derive(Debug, Default, Copy, Clone, PartialOrd, Ord, PartialEq, Eq, Hash)]
1032 pub struct $enum(pub $backing);
1033 impl $enum {
1034 $( pub const $name: Self = Self($value); )*
Andrei Homescu7f38cf92021-06-29 23:55:43 +00001035
1036 #[inline(always)]
1037 pub const fn enum_values() -> [Self; $size] {
1038 [$(Self::$name),*]
1039 }
Andrei Homescu00eca712020-09-09 18:57:40 -07001040 }
1041
1042 impl $crate::parcel::Serialize for $enum {
1043 fn serialize(&self, parcel: &mut $crate::parcel::Parcel) -> $crate::Result<()> {
1044 parcel.write(&self.0)
1045 }
1046 }
1047
1048 impl $crate::parcel::SerializeArray for $enum {
1049 fn serialize_array(slice: &[Self], parcel: &mut $crate::parcel::Parcel) -> $crate::Result<()> {
1050 let v: Vec<$backing> = slice.iter().map(|x| x.0).collect();
1051 <$backing as binder::parcel::SerializeArray>::serialize_array(&v[..], parcel)
1052 }
1053 }
1054
1055 impl $crate::parcel::Deserialize for $enum {
1056 fn deserialize(parcel: &$crate::parcel::Parcel) -> $crate::Result<Self> {
1057 parcel.read().map(Self)
1058 }
1059 }
1060
1061 impl $crate::parcel::DeserializeArray for $enum {
1062 fn deserialize_array(parcel: &$crate::parcel::Parcel) -> $crate::Result<Option<Vec<Self>>> {
1063 let v: Option<Vec<$backing>> =
1064 <$backing as binder::parcel::DeserializeArray>::deserialize_array(parcel)?;
1065 Ok(v.map(|v| v.into_iter().map(Self).collect()))
1066 }
1067 }
1068 };
1069}