blob: 3edeebf892d45d0c6a59f8e0cff8f08e1b09a9be [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
Alan Stokes23fdfcd2021-09-09 11:19:24 +010017use crate::binder::{
18 AsNative, Interface, InterfaceClassMethods, Remotable, Stability, TransactionCode,
19};
Stephen Crane2a3c2502020-06-16 17:48:35 -070020use crate::error::{status_result, status_t, Result, StatusCode};
Alice Ryhl8618c482021-11-09 15:35:35 +000021use crate::parcel::{BorrowedParcel, Serialize};
Stephen Crane2a3c2502020-06-16 17:48:35 -070022use crate::proxy::SpIBinder;
23use crate::sys;
24
25use std::convert::TryFrom;
Stephen Crane2a3297f2021-06-11 16:48:10 -070026use std::ffi::{c_void, CStr, CString};
27use std::fs::File;
Stephen Crane2a3c2502020-06-16 17:48:35 -070028use std::mem::ManuallyDrop;
29use std::ops::Deref;
Stephen Crane2a3297f2021-06-11 16:48:10 -070030use std::os::raw::c_char;
31use std::os::unix::io::FromRawFd;
32use std::slice;
Stephen Crane2a3c2502020-06-16 17:48:35 -070033
34/// Rust wrapper around Binder remotable objects.
35///
36/// Implements the C++ `BBinder` class, and therefore implements the C++
37/// `IBinder` interface.
38#[repr(C)]
39pub struct Binder<T: Remotable> {
40 ibinder: *mut sys::AIBinder,
41 rust_object: *mut T,
42}
43
Andrei Homescu2c674b02020-08-07 22:12:27 -070044/// # Safety
45///
46/// A `Binder<T>` is a pair of unique owning pointers to two values:
47/// * a C++ ABBinder which the C++ API guarantees can be passed between threads
48/// * a Rust object which implements `Remotable`; this trait requires `Send + Sync`
49///
50/// Both pointers are unique (never escape the `Binder<T>` object and are not copied)
51/// so we can essentially treat `Binder<T>` as a box-like containing the two objects;
52/// the box-like object inherits `Send` from the two inner values, similarly
53/// to how `Box<T>` is `Send` if `T` is `Send`.
54unsafe impl<T: Remotable> Send for Binder<T> {}
55
Stephen Cranef03fe3d2021-06-25 15:05:00 -070056/// # Safety
57///
58/// A `Binder<T>` is a pair of unique owning pointers to two values:
59/// * a C++ ABBinder which is thread-safe, i.e. `Send + Sync`
60/// * a Rust object which implements `Remotable`; this trait requires `Send + Sync`
61///
62/// `ABBinder` contains an immutable `mUserData` pointer, which is actually a
63/// pointer to a boxed `T: Remotable`, which is `Sync`. `ABBinder` also contains
64/// a mutable pointer to its class, but mutation of this field is controlled by
65/// a mutex and it is only allowed to be set once, therefore we can concurrently
66/// access this field safely. `ABBinder` inherits from `BBinder`, which is also
67/// thread-safe. Thus `ABBinder` is thread-safe.
68///
69/// Both pointers are unique (never escape the `Binder<T>` object and are not copied)
70/// so we can essentially treat `Binder<T>` as a box-like containing the two objects;
71/// the box-like object inherits `Sync` from the two inner values, similarly
72/// to how `Box<T>` is `Sync` if `T` is `Sync`.
73unsafe impl<T: Remotable> Sync for Binder<T> {}
74
Stephen Crane2a3c2502020-06-16 17:48:35 -070075impl<T: Remotable> Binder<T> {
Stephen Craneff7f03a2021-02-25 16:04:22 -080076 /// Create a new Binder remotable object with default stability
Stephen Crane2a3c2502020-06-16 17:48:35 -070077 ///
78 /// This moves the `rust_object` into an owned [`Box`] and Binder will
79 /// manage its lifetime.
80 pub fn new(rust_object: T) -> Binder<T> {
Stephen Craneff7f03a2021-02-25 16:04:22 -080081 Self::new_with_stability(rust_object, Stability::default())
82 }
83
84 /// Create a new Binder remotable object with the given stability
85 ///
86 /// This moves the `rust_object` into an owned [`Box`] and Binder will
87 /// manage its lifetime.
88 pub fn new_with_stability(rust_object: T, stability: Stability) -> Binder<T> {
Stephen Crane2a3c2502020-06-16 17:48:35 -070089 let class = T::get_class();
90 let rust_object = Box::into_raw(Box::new(rust_object));
91 let ibinder = unsafe {
92 // Safety: `AIBinder_new` expects a valid class pointer (which we
93 // initialize via `get_class`), and an arbitrary pointer
94 // argument. The caller owns the returned `AIBinder` pointer, which
95 // is a strong reference to a `BBinder`. This reference should be
96 // decremented via `AIBinder_decStrong` when the reference lifetime
97 // ends.
98 sys::AIBinder_new(class.into(), rust_object as *mut c_void)
99 };
Stephen Craneff7f03a2021-02-25 16:04:22 -0800100 let mut binder = Binder {
Stephen Crane2a3c2502020-06-16 17:48:35 -0700101 ibinder,
102 rust_object,
Stephen Craneff7f03a2021-02-25 16:04:22 -0800103 };
104 binder.mark_stability(stability);
105 binder
Stephen Crane2a3c2502020-06-16 17:48:35 -0700106 }
107
108 /// Set the extension of a binder interface. This allows a downstream
109 /// developer to add an extension to an interface without modifying its
110 /// interface file. This should be called immediately when the object is
111 /// created before it is passed to another thread.
112 ///
113 /// # Examples
114 ///
115 /// For instance, imagine if we have this Binder AIDL interface definition:
116 /// interface IFoo { void doFoo(); }
117 ///
118 /// If an unrelated owner (perhaps in a downstream codebase) wants to make a
119 /// change to the interface, they have two options:
120 ///
121 /// 1) Historical option that has proven to be BAD! Only the original
122 /// author of an interface should change an interface. If someone
123 /// downstream wants additional functionality, they should not ever
124 /// change the interface or use this method.
125 /// ```AIDL
126 /// BAD TO DO: interface IFoo { BAD TO DO
127 /// BAD TO DO: void doFoo(); BAD TO DO
128 /// BAD TO DO: + void doBar(); // adding a method BAD TO DO
129 /// BAD TO DO: } BAD TO DO
130 /// ```
131 ///
132 /// 2) Option that this method enables!
133 /// Leave the original interface unchanged (do not change IFoo!).
134 /// Instead, create a new AIDL interface in a downstream package:
135 /// ```AIDL
136 /// package com.<name>; // new functionality in a new package
137 /// interface IBar { void doBar(); }
138 /// ```
139 ///
140 /// When registering the interface, add:
141 ///
142 /// # use binder::{Binder, Interface};
143 /// # type MyFoo = ();
144 /// # type MyBar = ();
145 /// # let my_foo = ();
146 /// # let my_bar = ();
147 /// let mut foo: Binder<MyFoo> = Binder::new(my_foo); // class in AOSP codebase
148 /// let bar: Binder<MyBar> = Binder::new(my_bar); // custom extension class
149 /// foo.set_extension(&mut bar.as_binder()); // use method in Binder
150 ///
151 /// Then, clients of `IFoo` can get this extension:
152 ///
153 /// # use binder::{declare_binder_interface, Binder, TransactionCode, Parcel};
154 /// # trait IBar {}
155 /// # declare_binder_interface! {
156 /// # IBar["test"] {
157 /// # native: BnBar(on_transact),
158 /// # proxy: BpBar,
159 /// # }
160 /// # }
161 /// # fn on_transact(
162 /// # service: &dyn IBar,
163 /// # code: TransactionCode,
Alice Ryhl8618c482021-11-09 15:35:35 +0000164 /// # data: &BorrowedParcel,
165 /// # reply: &mut BorrowedParcel,
Stephen Crane2a3c2502020-06-16 17:48:35 -0700166 /// # ) -> binder::Result<()> {
167 /// # Ok(())
168 /// # }
169 /// # impl IBar for BpBar {}
170 /// # impl IBar for Binder<BnBar> {}
171 /// # fn main() -> binder::Result<()> {
172 /// # let binder = Binder::new(());
173 /// if let Some(barBinder) = binder.get_extension()? {
174 /// let bar = BpBar::new(barBinder)
175 /// .expect("Extension was not of type IBar");
176 /// } else {
177 /// // There was no extension
178 /// }
179 /// # }
180 pub fn set_extension(&mut self, extension: &mut SpIBinder) -> Result<()> {
181 let status = unsafe {
182 // Safety: `AIBinder_setExtension` expects two valid, mutable
183 // `AIBinder` pointers. We are guaranteed that both `self` and
184 // `extension` contain valid `AIBinder` pointers, because they
185 // cannot be initialized without a valid
186 // pointer. `AIBinder_setExtension` does not take ownership of
187 // either parameter.
188 sys::AIBinder_setExtension(self.as_native_mut(), extension.as_native_mut())
189 };
190 status_result(status)
191 }
192
193 /// Retrieve the interface descriptor string for this object's Binder
194 /// interface.
195 pub fn get_descriptor() -> &'static str {
196 T::get_descriptor()
197 }
Stephen Craneff7f03a2021-02-25 16:04:22 -0800198
199 /// Mark this binder object with the given stability guarantee
200 fn mark_stability(&mut self, stability: Stability) {
201 match stability {
202 Stability::Local => self.mark_local_stability(),
203 Stability::Vintf => {
204 unsafe {
205 // Safety: Self always contains a valid `AIBinder` pointer, so
206 // we can always call this C API safely.
207 sys::AIBinder_markVintfStability(self.as_native_mut());
208 }
209 }
210 }
211 }
212
213 /// Mark this binder object with local stability, which is vendor if we are
214 /// building for the VNDK and system otherwise.
Janis Danisevskis1323d512021-11-09 07:48:08 -0800215 #[cfg(any(vendor_ndk, android_vndk))]
Stephen Craneff7f03a2021-02-25 16:04:22 -0800216 fn mark_local_stability(&mut self) {
217 unsafe {
218 // Safety: Self always contains a valid `AIBinder` pointer, so
219 // we can always call this C API safely.
220 sys::AIBinder_markVendorStability(self.as_native_mut());
221 }
222 }
223
224 /// Mark this binder object with local stability, which is vendor if we are
225 /// building for the VNDK and system otherwise.
Janis Danisevskis1323d512021-11-09 07:48:08 -0800226 #[cfg(not(any(vendor_ndk, android_vndk)))]
Stephen Craneff7f03a2021-02-25 16:04:22 -0800227 fn mark_local_stability(&mut self) {
228 unsafe {
229 // Safety: Self always contains a valid `AIBinder` pointer, so
230 // we can always call this C API safely.
231 sys::AIBinder_markSystemStability(self.as_native_mut());
232 }
233 }
Stephen Crane2a3c2502020-06-16 17:48:35 -0700234}
235
236impl<T: Remotable> Interface for Binder<T> {
237 /// Converts the local remotable object into a generic `SpIBinder`
238 /// reference.
239 ///
240 /// The resulting `SpIBinder` will hold its own strong reference to this
241 /// remotable object, which will prevent the object from being dropped while
242 /// the `SpIBinder` is alive.
243 fn as_binder(&self) -> SpIBinder {
244 unsafe {
245 // Safety: `self.ibinder` is guaranteed to always be a valid pointer
246 // to an `AIBinder` by the `Binder` constructor. We are creating a
247 // copy of the `self.ibinder` strong reference, but
248 // `SpIBinder::from_raw` assumes it receives an owned pointer with
249 // its own strong reference. We first increment the reference count,
250 // so that the new `SpIBinder` will be tracked as a new reference.
251 sys::AIBinder_incStrong(self.ibinder);
252 SpIBinder::from_raw(self.ibinder).unwrap()
253 }
254 }
255}
256
257impl<T: Remotable> InterfaceClassMethods for Binder<T> {
258 fn get_descriptor() -> &'static str {
259 <T as Remotable>::get_descriptor()
260 }
261
262 /// Called whenever a transaction needs to be processed by a local
263 /// implementation.
264 ///
265 /// # Safety
266 ///
267 /// Must be called with a non-null, valid pointer to a local `AIBinder` that
268 /// contains a `T` pointer in its user data. The `data` and `reply` parcel
269 /// parameters must be valid pointers to `AParcel` objects. This method does
270 /// not take ownership of any of its parameters.
271 ///
272 /// These conditions hold when invoked by `ABBinder::onTransact`.
273 unsafe extern "C" fn on_transact(
274 binder: *mut sys::AIBinder,
275 code: u32,
276 data: *const sys::AParcel,
277 reply: *mut sys::AParcel,
278 ) -> status_t {
279 let res = {
Alice Ryhl8618c482021-11-09 15:35:35 +0000280 let mut reply = BorrowedParcel::from_raw(reply).unwrap();
281 let data = BorrowedParcel::from_raw(data as *mut sys::AParcel).unwrap();
Stephen Crane2a3c2502020-06-16 17:48:35 -0700282 let object = sys::AIBinder_getUserData(binder);
283 let binder: &T = &*(object as *const T);
284 binder.on_transact(code, &data, &mut reply)
285 };
286 match res {
287 Ok(()) => 0i32,
288 Err(e) => e as i32,
289 }
290 }
291
292 /// Called whenever an `AIBinder` object is no longer referenced and needs
293 /// destroyed.
294 ///
295 /// # Safety
296 ///
297 /// Must be called with a valid pointer to a `T` object. After this call,
298 /// the pointer will be invalid and should not be dereferenced.
299 unsafe extern "C" fn on_destroy(object: *mut c_void) {
Matthew Maurerc050d8f2021-06-11 16:49:48 -0700300 Box::from_raw(object as *mut T);
Stephen Crane2a3c2502020-06-16 17:48:35 -0700301 }
302
303 /// Called whenever a new, local `AIBinder` object is needed of a specific
304 /// class.
305 ///
306 /// Constructs the user data pointer that will be stored in the object,
307 /// which will be a heap-allocated `T` object.
308 ///
309 /// # Safety
310 ///
311 /// Must be called with a valid pointer to a `T` object allocated via `Box`.
312 unsafe extern "C" fn on_create(args: *mut c_void) -> *mut c_void {
313 // We just return the argument, as it is already a pointer to the rust
314 // object created by Box.
315 args
316 }
Stephen Crane2a3297f2021-06-11 16:48:10 -0700317
318 /// Called to handle the `dump` transaction.
319 ///
320 /// # Safety
321 ///
322 /// Must be called with a non-null, valid pointer to a local `AIBinder` that
323 /// contains a `T` pointer in its user data. fd should be a non-owned file
324 /// descriptor, and args must be an array of null-terminated string
325 /// poiinters with length num_args.
Alan Stokes23fdfcd2021-09-09 11:19:24 +0100326 unsafe extern "C" fn on_dump(
327 binder: *mut sys::AIBinder,
328 fd: i32,
329 args: *mut *const c_char,
330 num_args: u32,
331 ) -> status_t {
Stephen Crane2a3297f2021-06-11 16:48:10 -0700332 if fd < 0 {
333 return StatusCode::UNEXPECTED_NULL as status_t;
334 }
335 // We don't own this file, so we need to be careful not to drop it.
336 let file = ManuallyDrop::new(File::from_raw_fd(fd));
337
Stephen Crane0c5f9232022-06-17 11:48:05 -0700338 if args.is_null() && num_args != 0 {
Stephen Crane2a3297f2021-06-11 16:48:10 -0700339 return StatusCode::UNEXPECTED_NULL as status_t;
340 }
Stephen Crane0c5f9232022-06-17 11:48:05 -0700341
342 let args = if args.is_null() || num_args == 0 {
343 vec![]
344 } else {
345 slice::from_raw_parts(args, num_args as usize)
346 .iter().map(|s| CStr::from_ptr(*s)).collect()
347 };
Stephen Crane2a3297f2021-06-11 16:48:10 -0700348
349 let object = sys::AIBinder_getUserData(binder);
350 let binder: &T = &*(object as *const T);
351 let res = binder.on_dump(&file, &args);
352
353 match res {
354 Ok(()) => 0,
355 Err(e) => e as status_t,
356 }
357 }
Stephen Crane2a3c2502020-06-16 17:48:35 -0700358}
359
360impl<T: Remotable> Drop for Binder<T> {
361 // This causes C++ to decrease the strong ref count of the `AIBinder`
362 // object. We specifically do not drop the `rust_object` here. When C++
363 // actually destroys the object, it calls `on_destroy` and we can drop the
364 // `rust_object` then.
365 fn drop(&mut self) {
366 unsafe {
367 // Safety: When `self` is dropped, we can no longer access the
368 // reference, so can decrement the reference count. `self.ibinder`
369 // is always a valid `AIBinder` pointer, so is valid to pass to
370 // `AIBinder_decStrong`.
371 sys::AIBinder_decStrong(self.ibinder);
372 }
373 }
374}
375
376impl<T: Remotable> Deref for Binder<T> {
377 type Target = T;
378
379 fn deref(&self) -> &Self::Target {
380 unsafe {
381 // Safety: While `self` is alive, the reference count of the
382 // underlying object is > 0 and therefore `on_destroy` cannot be
383 // called. Therefore while `self` is alive, we know that
384 // `rust_object` is still a valid pointer to a heap allocated object
385 // of type `T`.
386 &*self.rust_object
387 }
388 }
389}
390
391impl<B: Remotable> Serialize for Binder<B> {
Alice Ryhl8618c482021-11-09 15:35:35 +0000392 fn serialize(&self, parcel: &mut BorrowedParcel<'_>) -> Result<()> {
Stephen Crane2a3c2502020-06-16 17:48:35 -0700393 parcel.write_binder(Some(&self.as_binder()))
394 }
395}
396
397// This implementation is an idiomatic implementation of the C++
398// `IBinder::localBinder` interface if the binder object is a Rust binder
399// service.
400impl<B: Remotable> TryFrom<SpIBinder> for Binder<B> {
401 type Error = StatusCode;
402
403 fn try_from(mut ibinder: SpIBinder) -> Result<Self> {
404 let class = B::get_class();
405 if Some(class) != ibinder.get_class() {
406 return Err(StatusCode::BAD_TYPE);
407 }
408 let userdata = unsafe {
409 // Safety: `SpIBinder` always holds a valid pointer pointer to an
410 // `AIBinder`, which we can safely pass to
411 // `AIBinder_getUserData`. `ibinder` retains ownership of the
412 // returned pointer.
413 sys::AIBinder_getUserData(ibinder.as_native_mut())
414 };
415 if userdata.is_null() {
416 return Err(StatusCode::UNEXPECTED_NULL);
417 }
418 // We are transferring the ownership of the AIBinder into the new Binder
419 // object.
420 let mut ibinder = ManuallyDrop::new(ibinder);
421 Ok(Binder {
422 ibinder: ibinder.as_native_mut(),
423 rust_object: userdata as *mut B,
424 })
425 }
426}
427
428/// # Safety
429///
430/// The constructor for `Binder` guarantees that `self.ibinder` will contain a
431/// valid, non-null pointer to an `AIBinder`, so this implementation is type
432/// safe. `self.ibinder` will remain valid for the entire lifetime of `self`
433/// because we hold a strong reference to the `AIBinder` until `self` is
434/// dropped.
435unsafe impl<B: Remotable> AsNative<sys::AIBinder> for Binder<B> {
436 fn as_native(&self) -> *const sys::AIBinder {
437 self.ibinder
438 }
439
440 fn as_native_mut(&mut self) -> *mut sys::AIBinder {
441 self.ibinder
442 }
443}
444
445/// Register a new service with the default service manager.
446///
447/// Registers the given binder object with the given identifier. If successful,
448/// this service can then be retrieved using that identifier.
Alan Stokes1a49e4f2021-09-23 10:30:47 +0100449///
450/// This function will panic if the identifier contains a 0 byte (NUL).
Stephen Crane2a3c2502020-06-16 17:48:35 -0700451pub fn add_service(identifier: &str, mut binder: SpIBinder) -> Result<()> {
452 let instance = CString::new(identifier).unwrap();
453 let status = unsafe {
454 // Safety: `AServiceManager_addService` expects valid `AIBinder` and C
455 // string pointers. Caller retains ownership of both
456 // pointers. `AServiceManager_addService` creates a new strong reference
457 // and copies the string, so both pointers need only be valid until the
458 // call returns.
459 sys::AServiceManager_addService(binder.as_native_mut(), instance.as_ptr())
460 };
461 status_result(status)
462}
463
Alan Stokes23fdfcd2021-09-09 11:19:24 +0100464/// Register a dynamic service via the LazyServiceRegistrar.
465///
466/// Registers the given binder object with the given identifier. If successful,
467/// this service can then be retrieved using that identifier. The service process
468/// will be shut down once all registered services are no longer in use.
469///
470/// If any service in the process is registered as lazy, all should be, otherwise
471/// the process may be shut down while a service is in use.
Alan Stokes1a49e4f2021-09-23 10:30:47 +0100472///
473/// This function will panic if the identifier contains a 0 byte (NUL).
Alan Stokes23fdfcd2021-09-09 11:19:24 +0100474pub fn register_lazy_service(identifier: &str, mut binder: SpIBinder) -> Result<()> {
475 let instance = CString::new(identifier).unwrap();
476 let status = unsafe {
477 // Safety: `AServiceManager_registerLazyService` expects valid `AIBinder` and C
478 // string pointers. Caller retains ownership of both
479 // pointers. `AServiceManager_registerLazyService` creates a new strong reference
480 // and copies the string, so both pointers need only be valid until the
481 // call returns.
482
483 sys::AServiceManager_registerLazyService(binder.as_native_mut(), instance.as_ptr())
484 };
485 status_result(status)
486}
487
488/// Prevent a process which registers lazy services from being shut down even when none
489/// of the services is in use.
490///
491/// If persist is true then shut down will be blocked until this function is called again with
492/// persist false. If this is to be the initial state, call this function before calling
493/// register_lazy_service.
494pub fn force_lazy_services_persist(persist: bool) {
495 unsafe {
496 // Safety: No borrowing or transfer of ownership occurs here.
497 sys::AServiceManager_forceLazyServicesPersist(persist)
498 }
499}
500
Stephen Crane2a3c2502020-06-16 17:48:35 -0700501/// Tests often create a base BBinder instance; so allowing the unit
502/// type to be remotable translates nicely to Binder::new(()).
503impl Remotable for () {
504 fn get_descriptor() -> &'static str {
505 ""
506 }
507
508 fn on_transact(
509 &self,
510 _code: TransactionCode,
Alice Ryhl8618c482021-11-09 15:35:35 +0000511 _data: &BorrowedParcel<'_>,
512 _reply: &mut BorrowedParcel<'_>,
Stephen Crane2a3c2502020-06-16 17:48:35 -0700513 ) -> Result<()> {
514 Ok(())
515 }
516
Stephen Crane2a3297f2021-06-11 16:48:10 -0700517 fn on_dump(&self, _file: &File, _args: &[&CStr]) -> Result<()> {
518 Ok(())
519 }
520
Stephen Crane2a3c2502020-06-16 17:48:35 -0700521 binder_fn_get_class!(Binder::<Self>);
522}
523
524impl Interface for () {}
Alice Ryhlad9c77b2021-11-16 09:49:29 +0000525
526/// Determine whether the current thread is currently executing an incoming
527/// transaction.
528pub fn is_handling_transaction() -> bool {
529 unsafe {
530 // Safety: This method is always safe to call.
531 sys::AIBinder_isHandlingTransaction()
532 }
533}