1 /*
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 use crate::binder::{
18 AsNative, Interface, InterfaceClassMethods, Remotable, Stability, TransactionCode,
19 };
20 use crate::error::{status_result, status_t, Result, StatusCode};
21 use crate::parcel::{BorrowedParcel, Serialize};
22 use crate::proxy::SpIBinder;
23 use crate::sys;
24
25 use std::convert::TryFrom;
26 use std::ffi::{c_void, CStr, CString};
27 use std::fs::File;
28 use std::mem::ManuallyDrop;
29 use std::ops::Deref;
30 use std::os::raw::c_char;
31 use std::os::unix::io::FromRawFd;
32 use std::slice;
33 use std::sync::Mutex;
34
35 /// Rust wrapper around Binder remotable objects.
36 ///
37 /// Implements the C++ `BBinder` class, and therefore implements the C++
38 /// `IBinder` interface.
39 #[repr(C)]
40 pub struct Binder<T: Remotable> {
41 ibinder: *mut sys::AIBinder,
42 rust_object: *mut T,
43 }
44
45 /// # Safety
46 ///
47 /// A `Binder<T>` is a pair of unique owning pointers to two values:
48 /// * a C++ ABBinder which the C++ API guarantees can be passed between threads
49 /// * a Rust object which implements `Remotable`; this trait requires `Send + Sync`
50 ///
51 /// Both pointers are unique (never escape the `Binder<T>` object and are not copied)
52 /// so we can essentially treat `Binder<T>` as a box-like containing the two objects;
53 /// the box-like object inherits `Send` from the two inner values, similarly
54 /// to how `Box<T>` is `Send` if `T` is `Send`.
55 unsafe impl<T: Remotable> Send for Binder<T> {}
56
57 /// # Safety
58 ///
59 /// A `Binder<T>` is a pair of unique owning pointers to two values:
60 /// * a C++ ABBinder which is thread-safe, i.e. `Send + Sync`
61 /// * a Rust object which implements `Remotable`; this trait requires `Send + Sync`
62 ///
63 /// `ABBinder` contains an immutable `mUserData` pointer, which is actually a
64 /// pointer to a boxed `T: Remotable`, which is `Sync`. `ABBinder` also contains
65 /// a mutable pointer to its class, but mutation of this field is controlled by
66 /// a mutex and it is only allowed to be set once, therefore we can concurrently
67 /// access this field safely. `ABBinder` inherits from `BBinder`, which is also
68 /// thread-safe. Thus `ABBinder` is thread-safe.
69 ///
70 /// Both pointers are unique (never escape the `Binder<T>` object and are not copied)
71 /// so we can essentially treat `Binder<T>` as a box-like containing the two objects;
72 /// the box-like object inherits `Sync` from the two inner values, similarly
73 /// to how `Box<T>` is `Sync` if `T` is `Sync`.
74 unsafe impl<T: Remotable> Sync for Binder<T> {}
75
76 impl<T: Remotable> Binder<T> {
77 /// Create a new Binder remotable object with default stability
78 ///
79 /// This moves the `rust_object` into an owned [`Box`] and Binder will
80 /// manage its lifetime.
new(rust_object: T) -> Binder<T>81 pub fn new(rust_object: T) -> Binder<T> {
82 Self::new_with_stability(rust_object, Stability::default())
83 }
84
85 /// Create a new Binder remotable object with the given stability
86 ///
87 /// This moves the `rust_object` into an owned [`Box`] and Binder will
88 /// manage its lifetime.
new_with_stability(rust_object: T, stability: Stability) -> Binder<T>89 pub fn new_with_stability(rust_object: T, stability: Stability) -> Binder<T> {
90 let class = T::get_class();
91 let rust_object = Box::into_raw(Box::new(rust_object));
92 let ibinder = unsafe {
93 // Safety: `AIBinder_new` expects a valid class pointer (which we
94 // initialize via `get_class`), and an arbitrary pointer
95 // argument. The caller owns the returned `AIBinder` pointer, which
96 // is a strong reference to a `BBinder`. This reference should be
97 // decremented via `AIBinder_decStrong` when the reference lifetime
98 // ends.
99 sys::AIBinder_new(class.into(), rust_object as *mut c_void)
100 };
101 let mut binder = Binder { ibinder, rust_object };
102 binder.mark_stability(stability);
103 binder
104 }
105
106 /// Set the extension of a binder interface. This allows a downstream
107 /// developer to add an extension to an interface without modifying its
108 /// interface file. This should be called immediately when the object is
109 /// created before it is passed to another thread.
110 ///
111 /// # Examples
112 ///
113 /// For instance, imagine if we have this Binder AIDL interface definition:
114 /// interface IFoo { void doFoo(); }
115 ///
116 /// If an unrelated owner (perhaps in a downstream codebase) wants to make a
117 /// change to the interface, they have two options:
118 ///
119 /// 1) Historical option that has proven to be BAD! Only the original
120 /// author of an interface should change an interface. If someone
121 /// downstream wants additional functionality, they should not ever
122 /// change the interface or use this method.
123 /// ```AIDL
124 /// BAD TO DO: interface IFoo { BAD TO DO
125 /// BAD TO DO: void doFoo(); BAD TO DO
126 /// BAD TO DO: + void doBar(); // adding a method BAD TO DO
127 /// BAD TO DO: } BAD TO DO
128 /// ```
129 ///
130 /// 2) Option that this method enables!
131 /// Leave the original interface unchanged (do not change IFoo!).
132 /// Instead, create a new AIDL interface in a downstream package:
133 /// ```AIDL
134 /// package com.<name>; // new functionality in a new package
135 /// interface IBar { void doBar(); }
136 /// ```
137 ///
138 /// When registering the interface, add:
139 ///
140 /// # use binder::{Binder, Interface};
141 /// # type MyFoo = ();
142 /// # type MyBar = ();
143 /// # let my_foo = ();
144 /// # let my_bar = ();
145 /// let mut foo: Binder<MyFoo> = Binder::new(my_foo); // class in AOSP codebase
146 /// let bar: Binder<MyBar> = Binder::new(my_bar); // custom extension class
147 /// foo.set_extension(&mut bar.as_binder()); // use method in Binder
148 ///
149 /// Then, clients of `IFoo` can get this extension:
150 ///
151 /// # use binder::{declare_binder_interface, Binder, TransactionCode, Parcel};
152 /// # trait IBar {}
153 /// # declare_binder_interface! {
154 /// # IBar["test"] {
155 /// # native: BnBar(on_transact),
156 /// # proxy: BpBar,
157 /// # }
158 /// # }
159 /// # fn on_transact(
160 /// # service: &dyn IBar,
161 /// # code: TransactionCode,
162 /// # data: &BorrowedParcel,
163 /// # reply: &mut BorrowedParcel,
164 /// # ) -> binder::Result<()> {
165 /// # Ok(())
166 /// # }
167 /// # impl IBar for BpBar {}
168 /// # impl IBar for Binder<BnBar> {}
169 /// # fn main() -> binder::Result<()> {
170 /// # let binder = Binder::new(());
171 /// if let Some(barBinder) = binder.get_extension()? {
172 /// let bar = BpBar::new(barBinder)
173 /// .expect("Extension was not of type IBar");
174 /// } else {
175 /// // There was no extension
176 /// }
177 /// # }
set_extension(&mut self, extension: &mut SpIBinder) -> Result<()>178 pub fn set_extension(&mut self, extension: &mut SpIBinder) -> Result<()> {
179 let status = unsafe {
180 // Safety: `AIBinder_setExtension` expects two valid, mutable
181 // `AIBinder` pointers. We are guaranteed that both `self` and
182 // `extension` contain valid `AIBinder` pointers, because they
183 // cannot be initialized without a valid
184 // pointer. `AIBinder_setExtension` does not take ownership of
185 // either parameter.
186 sys::AIBinder_setExtension(self.as_native_mut(), extension.as_native_mut())
187 };
188 status_result(status)
189 }
190
191 /// Retrieve the interface descriptor string for this object's Binder
192 /// interface.
get_descriptor() -> &'static str193 pub fn get_descriptor() -> &'static str {
194 T::get_descriptor()
195 }
196
197 /// Mark this binder object with the given stability guarantee
mark_stability(&mut self, stability: Stability)198 fn mark_stability(&mut self, stability: Stability) {
199 match stability {
200 Stability::Local => self.mark_local_stability(),
201 Stability::Vintf => {
202 unsafe {
203 // Safety: Self always contains a valid `AIBinder` pointer, so
204 // we can always call this C API safely.
205 sys::AIBinder_markVintfStability(self.as_native_mut());
206 }
207 }
208 }
209 }
210
211 /// Mark this binder object with local stability, which is vendor if we are
212 /// building for android_vendor and system otherwise.
213 #[cfg(android_vendor)]
mark_local_stability(&mut self)214 fn mark_local_stability(&mut self) {
215 unsafe {
216 // Safety: Self always contains a valid `AIBinder` pointer, so
217 // we can always call this C API safely.
218 sys::AIBinder_markVendorStability(self.as_native_mut());
219 }
220 }
221
222 /// Mark this binder object with local stability, which is vendor if we are
223 /// building for android_vendor and system otherwise.
224 #[cfg(not(android_vendor))]
mark_local_stability(&mut self)225 fn mark_local_stability(&mut self) {
226 unsafe {
227 // Safety: Self always contains a valid `AIBinder` pointer, so
228 // we can always call this C API safely.
229 sys::AIBinder_markSystemStability(self.as_native_mut());
230 }
231 }
232 }
233
234 impl<T: Remotable> Interface for Binder<T> {
235 /// Converts the local remotable object into a generic `SpIBinder`
236 /// reference.
237 ///
238 /// The resulting `SpIBinder` will hold its own strong reference to this
239 /// remotable object, which will prevent the object from being dropped while
240 /// the `SpIBinder` is alive.
as_binder(&self) -> SpIBinder241 fn as_binder(&self) -> SpIBinder {
242 unsafe {
243 // Safety: `self.ibinder` is guaranteed to always be a valid pointer
244 // to an `AIBinder` by the `Binder` constructor. We are creating a
245 // copy of the `self.ibinder` strong reference, but
246 // `SpIBinder::from_raw` assumes it receives an owned pointer with
247 // its own strong reference. We first increment the reference count,
248 // so that the new `SpIBinder` will be tracked as a new reference.
249 sys::AIBinder_incStrong(self.ibinder);
250 SpIBinder::from_raw(self.ibinder).unwrap()
251 }
252 }
253 }
254
255 impl<T: Remotable> InterfaceClassMethods for Binder<T> {
get_descriptor() -> &'static str256 fn get_descriptor() -> &'static str {
257 <T as Remotable>::get_descriptor()
258 }
259
260 /// Called whenever a transaction needs to be processed by a local
261 /// implementation.
262 ///
263 /// # Safety
264 ///
265 /// Must be called with a non-null, valid pointer to a local `AIBinder` that
266 /// contains a `T` pointer in its user data. The `data` and `reply` parcel
267 /// parameters must be valid pointers to `AParcel` objects. This method does
268 /// not take ownership of any of its parameters.
269 ///
270 /// These conditions hold when invoked by `ABBinder::onTransact`.
on_transact( binder: *mut sys::AIBinder, code: u32, data: *const sys::AParcel, reply: *mut sys::AParcel, ) -> status_t271 unsafe extern "C" fn on_transact(
272 binder: *mut sys::AIBinder,
273 code: u32,
274 data: *const sys::AParcel,
275 reply: *mut sys::AParcel,
276 ) -> status_t {
277 let res = {
278 let mut reply = BorrowedParcel::from_raw(reply).unwrap();
279 let data = BorrowedParcel::from_raw(data as *mut sys::AParcel).unwrap();
280 let object = sys::AIBinder_getUserData(binder);
281 let binder: &T = &*(object as *const T);
282 binder.on_transact(code, &data, &mut reply)
283 };
284 match res {
285 Ok(()) => 0i32,
286 Err(e) => e as i32,
287 }
288 }
289
290 /// Called whenever an `AIBinder` object is no longer referenced and needs
291 /// destroyed.
292 ///
293 /// # Safety
294 ///
295 /// Must be called with a valid pointer to a `T` object. After this call,
296 /// the pointer will be invalid and should not be dereferenced.
on_destroy(object: *mut c_void)297 unsafe extern "C" fn on_destroy(object: *mut c_void) {
298 drop(Box::from_raw(object as *mut T));
299 }
300
301 /// Called whenever a new, local `AIBinder` object is needed of a specific
302 /// class.
303 ///
304 /// Constructs the user data pointer that will be stored in the object,
305 /// which will be a heap-allocated `T` object.
306 ///
307 /// # Safety
308 ///
309 /// Must be called with a valid pointer to a `T` object allocated via `Box`.
on_create(args: *mut c_void) -> *mut c_void310 unsafe extern "C" fn on_create(args: *mut c_void) -> *mut c_void {
311 // We just return the argument, as it is already a pointer to the rust
312 // object created by Box.
313 args
314 }
315
316 /// Called to handle the `dump` transaction.
317 ///
318 /// # Safety
319 ///
320 /// Must be called with a non-null, valid pointer to a local `AIBinder` that
321 /// contains a `T` pointer in its user data. fd should be a non-owned file
322 /// descriptor, and args must be an array of null-terminated string
323 /// poiinters with length num_args.
on_dump( binder: *mut sys::AIBinder, fd: i32, args: *mut *const c_char, num_args: u32, ) -> status_t324 unsafe extern "C" fn on_dump(
325 binder: *mut sys::AIBinder,
326 fd: i32,
327 args: *mut *const c_char,
328 num_args: u32,
329 ) -> status_t {
330 if fd < 0 {
331 return StatusCode::UNEXPECTED_NULL as status_t;
332 }
333 // We don't own this file, so we need to be careful not to drop it.
334 let file = ManuallyDrop::new(File::from_raw_fd(fd));
335
336 if args.is_null() && num_args != 0 {
337 return StatusCode::UNEXPECTED_NULL as status_t;
338 }
339
340 let args = if args.is_null() || num_args == 0 {
341 vec![]
342 } else {
343 slice::from_raw_parts(args, num_args as usize)
344 .iter()
345 .map(|s| CStr::from_ptr(*s))
346 .collect()
347 };
348
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 }
358 }
359
360 impl<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.
drop(&mut self)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
376 impl<T: Remotable> Deref for Binder<T> {
377 type Target = T;
378
deref(&self) -> &Self::Target379 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
391 impl<B: Remotable> Serialize for Binder<B> {
serialize(&self, parcel: &mut BorrowedParcel<'_>) -> Result<()>392 fn serialize(&self, parcel: &mut BorrowedParcel<'_>) -> Result<()> {
393 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.
400 impl<B: Remotable> TryFrom<SpIBinder> for Binder<B> {
401 type Error = StatusCode;
402
try_from(mut ibinder: SpIBinder) -> Result<Self>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 { ibinder: ibinder.as_native_mut(), rust_object: userdata as *mut B })
422 }
423 }
424
425 /// # Safety
426 ///
427 /// The constructor for `Binder` guarantees that `self.ibinder` will contain a
428 /// valid, non-null pointer to an `AIBinder`, so this implementation is type
429 /// safe. `self.ibinder` will remain valid for the entire lifetime of `self`
430 /// because we hold a strong reference to the `AIBinder` until `self` is
431 /// dropped.
432 unsafe impl<B: Remotable> AsNative<sys::AIBinder> for Binder<B> {
as_native(&self) -> *const sys::AIBinder433 fn as_native(&self) -> *const sys::AIBinder {
434 self.ibinder
435 }
436
as_native_mut(&mut self) -> *mut sys::AIBinder437 fn as_native_mut(&mut self) -> *mut sys::AIBinder {
438 self.ibinder
439 }
440 }
441
442 /// Register a new service with the default service manager.
443 ///
444 /// Registers the given binder object with the given identifier. If successful,
445 /// this service can then be retrieved using that identifier.
446 ///
447 /// This function will panic if the identifier contains a 0 byte (NUL).
add_service(identifier: &str, mut binder: SpIBinder) -> Result<()>448 pub fn add_service(identifier: &str, mut binder: SpIBinder) -> Result<()> {
449 let instance = CString::new(identifier).unwrap();
450 let status = unsafe {
451 // Safety: `AServiceManager_addService` expects valid `AIBinder` and C
452 // string pointers. Caller retains ownership of both
453 // pointers. `AServiceManager_addService` creates a new strong reference
454 // and copies the string, so both pointers need only be valid until the
455 // call returns.
456 sys::AServiceManager_addService(binder.as_native_mut(), instance.as_ptr())
457 };
458 status_result(status)
459 }
460
461 /// Register a dynamic service via the LazyServiceRegistrar.
462 ///
463 /// Registers the given binder object with the given identifier. If successful,
464 /// this service can then be retrieved using that identifier. The service process
465 /// will be shut down once all registered services are no longer in use.
466 ///
467 /// If any service in the process is registered as lazy, all should be, otherwise
468 /// the process may be shut down while a service is in use.
469 ///
470 /// This function will panic if the identifier contains a 0 byte (NUL).
register_lazy_service(identifier: &str, mut binder: SpIBinder) -> Result<()>471 pub fn register_lazy_service(identifier: &str, mut binder: SpIBinder) -> Result<()> {
472 let instance = CString::new(identifier).unwrap();
473 let status = unsafe {
474 // Safety: `AServiceManager_registerLazyService` expects valid `AIBinder` and C
475 // string pointers. Caller retains ownership of both
476 // pointers. `AServiceManager_registerLazyService` creates a new strong reference
477 // and copies the string, so both pointers need only be valid until the
478 // call returns.
479
480 sys::AServiceManager_registerLazyService(binder.as_native_mut(), instance.as_ptr())
481 };
482 status_result(status)
483 }
484
485 /// Prevent a process which registers lazy services from being shut down even when none
486 /// of the services is in use.
487 ///
488 /// If persist is true then shut down will be blocked until this function is called again with
489 /// persist false. If this is to be the initial state, call this function before calling
490 /// register_lazy_service.
491 ///
492 /// Consider using [`LazyServiceGuard`] rather than calling this directly.
force_lazy_services_persist(persist: bool)493 pub fn force_lazy_services_persist(persist: bool) {
494 unsafe {
495 // Safety: No borrowing or transfer of ownership occurs here.
496 sys::AServiceManager_forceLazyServicesPersist(persist)
497 }
498 }
499
500 /// An RAII object to ensure a process which registers lazy services is not killed. During the
501 /// lifetime of any of these objects the service manager will not not kill the process even if none
502 /// of its lazy services are in use.
503 #[must_use]
504 #[derive(Debug)]
505 pub struct LazyServiceGuard {
506 // Prevent construction outside this module.
507 _private: (),
508 }
509
510 // Count of how many LazyServiceGuard objects are in existence.
511 static GUARD_COUNT: Mutex<u64> = Mutex::new(0);
512
513 impl LazyServiceGuard {
514 /// Create a new LazyServiceGuard to prevent the service manager prematurely killing this
515 /// process.
new() -> Self516 pub fn new() -> Self {
517 let mut count = GUARD_COUNT.lock().unwrap();
518 *count += 1;
519 if *count == 1 {
520 // It's important that we make this call with the mutex held, to make sure
521 // that multiple calls (e.g. if the count goes 1 -> 0 -> 1) are correctly
522 // sequenced. (That also means we can't just use an AtomicU64.)
523 force_lazy_services_persist(true);
524 }
525 Self { _private: () }
526 }
527 }
528
529 impl Drop for LazyServiceGuard {
drop(&mut self)530 fn drop(&mut self) {
531 let mut count = GUARD_COUNT.lock().unwrap();
532 *count -= 1;
533 if *count == 0 {
534 force_lazy_services_persist(false);
535 }
536 }
537 }
538
539 impl Clone for LazyServiceGuard {
clone(&self) -> Self540 fn clone(&self) -> Self {
541 Self::new()
542 }
543 }
544
545 impl Default for LazyServiceGuard {
default() -> Self546 fn default() -> Self {
547 Self::new()
548 }
549 }
550
551 /// Tests often create a base BBinder instance; so allowing the unit
552 /// type to be remotable translates nicely to Binder::new(()).
553 impl Remotable for () {
get_descriptor() -> &'static str554 fn get_descriptor() -> &'static str {
555 ""
556 }
557
on_transact( &self, _code: TransactionCode, _data: &BorrowedParcel<'_>, _reply: &mut BorrowedParcel<'_>, ) -> Result<()>558 fn on_transact(
559 &self,
560 _code: TransactionCode,
561 _data: &BorrowedParcel<'_>,
562 _reply: &mut BorrowedParcel<'_>,
563 ) -> Result<()> {
564 Ok(())
565 }
566
on_dump(&self, _file: &File, _args: &[&CStr]) -> Result<()>567 fn on_dump(&self, _file: &File, _args: &[&CStr]) -> Result<()> {
568 Ok(())
569 }
570
571 binder_fn_get_class!(Binder::<Self>);
572 }
573
574 impl Interface for () {}
575
576 /// Determine whether the current thread is currently executing an incoming
577 /// transaction.
is_handling_transaction() -> bool578 pub fn is_handling_transaction() -> bool {
579 unsafe {
580 // Safety: This method is always safe to call.
581 sys::AIBinder_isHandlingTransaction()
582 }
583 }
584