blob: 9e2cef134811713753bef930fb50e30bf8eda917 [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 };
Matthew Maurere268a9f2022-07-26 09:31:30 -0700100 let mut binder = Binder { ibinder, rust_object };
Stephen Craneff7f03a2021-02-25 16:04:22 -0800101 binder.mark_stability(stability);
102 binder
Stephen Crane2a3c2502020-06-16 17:48:35 -0700103 }
104
105 /// Set the extension of a binder interface. This allows a downstream
106 /// developer to add an extension to an interface without modifying its
107 /// interface file. This should be called immediately when the object is
108 /// created before it is passed to another thread.
109 ///
110 /// # Examples
111 ///
112 /// For instance, imagine if we have this Binder AIDL interface definition:
113 /// interface IFoo { void doFoo(); }
114 ///
115 /// If an unrelated owner (perhaps in a downstream codebase) wants to make a
116 /// change to the interface, they have two options:
117 ///
118 /// 1) Historical option that has proven to be BAD! Only the original
119 /// author of an interface should change an interface. If someone
120 /// downstream wants additional functionality, they should not ever
121 /// change the interface or use this method.
122 /// ```AIDL
123 /// BAD TO DO: interface IFoo { BAD TO DO
124 /// BAD TO DO: void doFoo(); BAD TO DO
125 /// BAD TO DO: + void doBar(); // adding a method BAD TO DO
126 /// BAD TO DO: } BAD TO DO
127 /// ```
128 ///
129 /// 2) Option that this method enables!
130 /// Leave the original interface unchanged (do not change IFoo!).
131 /// Instead, create a new AIDL interface in a downstream package:
132 /// ```AIDL
133 /// package com.<name>; // new functionality in a new package
134 /// interface IBar { void doBar(); }
135 /// ```
136 ///
137 /// When registering the interface, add:
138 ///
139 /// # use binder::{Binder, Interface};
140 /// # type MyFoo = ();
141 /// # type MyBar = ();
142 /// # let my_foo = ();
143 /// # let my_bar = ();
144 /// let mut foo: Binder<MyFoo> = Binder::new(my_foo); // class in AOSP codebase
145 /// let bar: Binder<MyBar> = Binder::new(my_bar); // custom extension class
146 /// foo.set_extension(&mut bar.as_binder()); // use method in Binder
147 ///
148 /// Then, clients of `IFoo` can get this extension:
149 ///
150 /// # use binder::{declare_binder_interface, Binder, TransactionCode, Parcel};
151 /// # trait IBar {}
152 /// # declare_binder_interface! {
153 /// # IBar["test"] {
154 /// # native: BnBar(on_transact),
155 /// # proxy: BpBar,
156 /// # }
157 /// # }
158 /// # fn on_transact(
159 /// # service: &dyn IBar,
160 /// # code: TransactionCode,
Alice Ryhl8618c482021-11-09 15:35:35 +0000161 /// # data: &BorrowedParcel,
162 /// # reply: &mut BorrowedParcel,
Stephen Crane2a3c2502020-06-16 17:48:35 -0700163 /// # ) -> binder::Result<()> {
164 /// # Ok(())
165 /// # }
166 /// # impl IBar for BpBar {}
167 /// # impl IBar for Binder<BnBar> {}
168 /// # fn main() -> binder::Result<()> {
169 /// # let binder = Binder::new(());
170 /// if let Some(barBinder) = binder.get_extension()? {
171 /// let bar = BpBar::new(barBinder)
172 /// .expect("Extension was not of type IBar");
173 /// } else {
174 /// // There was no extension
175 /// }
176 /// # }
177 pub fn set_extension(&mut self, extension: &mut SpIBinder) -> Result<()> {
178 let status = unsafe {
179 // Safety: `AIBinder_setExtension` expects two valid, mutable
180 // `AIBinder` pointers. We are guaranteed that both `self` and
181 // `extension` contain valid `AIBinder` pointers, because they
182 // cannot be initialized without a valid
183 // pointer. `AIBinder_setExtension` does not take ownership of
184 // either parameter.
185 sys::AIBinder_setExtension(self.as_native_mut(), extension.as_native_mut())
186 };
187 status_result(status)
188 }
189
190 /// Retrieve the interface descriptor string for this object's Binder
191 /// interface.
192 pub fn get_descriptor() -> &'static str {
193 T::get_descriptor()
194 }
Stephen Craneff7f03a2021-02-25 16:04:22 -0800195
196 /// Mark this binder object with the given stability guarantee
197 fn mark_stability(&mut self, stability: Stability) {
198 match stability {
199 Stability::Local => self.mark_local_stability(),
200 Stability::Vintf => {
201 unsafe {
202 // Safety: Self always contains a valid `AIBinder` pointer, so
203 // we can always call this C API safely.
204 sys::AIBinder_markVintfStability(self.as_native_mut());
205 }
206 }
207 }
208 }
209
210 /// Mark this binder object with local stability, which is vendor if we are
211 /// building for the VNDK and system otherwise.
Janis Danisevskis1323d512021-11-09 07:48:08 -0800212 #[cfg(any(vendor_ndk, android_vndk))]
Stephen Craneff7f03a2021-02-25 16:04:22 -0800213 fn mark_local_stability(&mut self) {
214 unsafe {
215 // Safety: Self always contains a valid `AIBinder` pointer, so
216 // we can always call this C API safely.
217 sys::AIBinder_markVendorStability(self.as_native_mut());
218 }
219 }
220
221 /// Mark this binder object with local stability, which is vendor if we are
222 /// building for the VNDK and system otherwise.
Janis Danisevskis1323d512021-11-09 07:48:08 -0800223 #[cfg(not(any(vendor_ndk, android_vndk)))]
Stephen Craneff7f03a2021-02-25 16:04:22 -0800224 fn mark_local_stability(&mut self) {
225 unsafe {
226 // Safety: Self always contains a valid `AIBinder` pointer, so
227 // we can always call this C API safely.
228 sys::AIBinder_markSystemStability(self.as_native_mut());
229 }
230 }
Stephen Crane2a3c2502020-06-16 17:48:35 -0700231}
232
233impl<T: Remotable> Interface for Binder<T> {
234 /// Converts the local remotable object into a generic `SpIBinder`
235 /// reference.
236 ///
237 /// The resulting `SpIBinder` will hold its own strong reference to this
238 /// remotable object, which will prevent the object from being dropped while
239 /// the `SpIBinder` is alive.
240 fn as_binder(&self) -> SpIBinder {
241 unsafe {
242 // Safety: `self.ibinder` is guaranteed to always be a valid pointer
243 // to an `AIBinder` by the `Binder` constructor. We are creating a
244 // copy of the `self.ibinder` strong reference, but
245 // `SpIBinder::from_raw` assumes it receives an owned pointer with
246 // its own strong reference. We first increment the reference count,
247 // so that the new `SpIBinder` will be tracked as a new reference.
248 sys::AIBinder_incStrong(self.ibinder);
249 SpIBinder::from_raw(self.ibinder).unwrap()
250 }
251 }
252}
253
254impl<T: Remotable> InterfaceClassMethods for Binder<T> {
255 fn get_descriptor() -> &'static str {
256 <T as Remotable>::get_descriptor()
257 }
258
259 /// Called whenever a transaction needs to be processed by a local
260 /// implementation.
261 ///
262 /// # Safety
263 ///
264 /// Must be called with a non-null, valid pointer to a local `AIBinder` that
265 /// contains a `T` pointer in its user data. The `data` and `reply` parcel
266 /// parameters must be valid pointers to `AParcel` objects. This method does
267 /// not take ownership of any of its parameters.
268 ///
269 /// These conditions hold when invoked by `ABBinder::onTransact`.
270 unsafe extern "C" fn on_transact(
271 binder: *mut sys::AIBinder,
272 code: u32,
273 data: *const sys::AParcel,
274 reply: *mut sys::AParcel,
275 ) -> status_t {
276 let res = {
Alice Ryhl8618c482021-11-09 15:35:35 +0000277 let mut reply = BorrowedParcel::from_raw(reply).unwrap();
278 let data = BorrowedParcel::from_raw(data as *mut sys::AParcel).unwrap();
Stephen Crane2a3c2502020-06-16 17:48:35 -0700279 let object = sys::AIBinder_getUserData(binder);
280 let binder: &T = &*(object as *const T);
281 binder.on_transact(code, &data, &mut reply)
282 };
283 match res {
284 Ok(()) => 0i32,
285 Err(e) => e as i32,
286 }
287 }
288
289 /// Called whenever an `AIBinder` object is no longer referenced and needs
290 /// destroyed.
291 ///
292 /// # Safety
293 ///
294 /// Must be called with a valid pointer to a `T` object. After this call,
295 /// the pointer will be invalid and should not be dereferenced.
296 unsafe extern "C" fn on_destroy(object: *mut c_void) {
Matthew Maurerc050d8f2021-06-11 16:49:48 -0700297 Box::from_raw(object as *mut T);
Stephen Crane2a3c2502020-06-16 17:48:35 -0700298 }
299
300 /// Called whenever a new, local `AIBinder` object is needed of a specific
301 /// class.
302 ///
303 /// Constructs the user data pointer that will be stored in the object,
304 /// which will be a heap-allocated `T` object.
305 ///
306 /// # Safety
307 ///
308 /// Must be called with a valid pointer to a `T` object allocated via `Box`.
309 unsafe extern "C" fn on_create(args: *mut c_void) -> *mut c_void {
310 // We just return the argument, as it is already a pointer to the rust
311 // object created by Box.
312 args
313 }
Stephen Crane2a3297f2021-06-11 16:48:10 -0700314
315 /// Called to handle the `dump` transaction.
316 ///
317 /// # Safety
318 ///
319 /// Must be called with a non-null, valid pointer to a local `AIBinder` that
320 /// contains a `T` pointer in its user data. fd should be a non-owned file
321 /// descriptor, and args must be an array of null-terminated string
322 /// poiinters with length num_args.
Alan Stokes23fdfcd2021-09-09 11:19:24 +0100323 unsafe extern "C" fn on_dump(
324 binder: *mut sys::AIBinder,
325 fd: i32,
326 args: *mut *const c_char,
327 num_args: u32,
328 ) -> status_t {
Stephen Crane2a3297f2021-06-11 16:48:10 -0700329 if fd < 0 {
330 return StatusCode::UNEXPECTED_NULL as status_t;
331 }
332 // We don't own this file, so we need to be careful not to drop it.
333 let file = ManuallyDrop::new(File::from_raw_fd(fd));
334
Stephen Crane0c5f9232022-06-17 11:48:05 -0700335 if args.is_null() && num_args != 0 {
Stephen Crane2a3297f2021-06-11 16:48:10 -0700336 return StatusCode::UNEXPECTED_NULL as status_t;
337 }
Stephen Crane0c5f9232022-06-17 11:48:05 -0700338
339 let args = if args.is_null() || num_args == 0 {
340 vec![]
341 } else {
342 slice::from_raw_parts(args, num_args as usize)
Matthew Maurere268a9f2022-07-26 09:31:30 -0700343 .iter()
344 .map(|s| CStr::from_ptr(*s))
345 .collect()
Stephen Crane0c5f9232022-06-17 11:48:05 -0700346 };
Stephen Crane2a3297f2021-06-11 16:48:10 -0700347
348 let object = sys::AIBinder_getUserData(binder);
349 let binder: &T = &*(object as *const T);
350 let res = binder.on_dump(&file, &args);
351
352 match res {
353 Ok(()) => 0,
354 Err(e) => e as status_t,
355 }
356 }
Stephen Crane2a3c2502020-06-16 17:48:35 -0700357}
358
359impl<T: Remotable> Drop for Binder<T> {
360 // This causes C++ to decrease the strong ref count of the `AIBinder`
361 // object. We specifically do not drop the `rust_object` here. When C++
362 // actually destroys the object, it calls `on_destroy` and we can drop the
363 // `rust_object` then.
364 fn drop(&mut self) {
365 unsafe {
366 // Safety: When `self` is dropped, we can no longer access the
367 // reference, so can decrement the reference count. `self.ibinder`
368 // is always a valid `AIBinder` pointer, so is valid to pass to
369 // `AIBinder_decStrong`.
370 sys::AIBinder_decStrong(self.ibinder);
371 }
372 }
373}
374
375impl<T: Remotable> Deref for Binder<T> {
376 type Target = T;
377
378 fn deref(&self) -> &Self::Target {
379 unsafe {
380 // Safety: While `self` is alive, the reference count of the
381 // underlying object is > 0 and therefore `on_destroy` cannot be
382 // called. Therefore while `self` is alive, we know that
383 // `rust_object` is still a valid pointer to a heap allocated object
384 // of type `T`.
385 &*self.rust_object
386 }
387 }
388}
389
390impl<B: Remotable> Serialize for Binder<B> {
Alice Ryhl8618c482021-11-09 15:35:35 +0000391 fn serialize(&self, parcel: &mut BorrowedParcel<'_>) -> Result<()> {
Stephen Crane2a3c2502020-06-16 17:48:35 -0700392 parcel.write_binder(Some(&self.as_binder()))
393 }
394}
395
396// This implementation is an idiomatic implementation of the C++
397// `IBinder::localBinder` interface if the binder object is a Rust binder
398// service.
399impl<B: Remotable> TryFrom<SpIBinder> for Binder<B> {
400 type Error = StatusCode;
401
402 fn try_from(mut ibinder: SpIBinder) -> Result<Self> {
403 let class = B::get_class();
404 if Some(class) != ibinder.get_class() {
405 return Err(StatusCode::BAD_TYPE);
406 }
407 let userdata = unsafe {
408 // Safety: `SpIBinder` always holds a valid pointer pointer to an
409 // `AIBinder`, which we can safely pass to
410 // `AIBinder_getUserData`. `ibinder` retains ownership of the
411 // returned pointer.
412 sys::AIBinder_getUserData(ibinder.as_native_mut())
413 };
414 if userdata.is_null() {
415 return Err(StatusCode::UNEXPECTED_NULL);
416 }
417 // We are transferring the ownership of the AIBinder into the new Binder
418 // object.
419 let mut ibinder = ManuallyDrop::new(ibinder);
Matthew Maurere268a9f2022-07-26 09:31:30 -0700420 Ok(Binder { ibinder: ibinder.as_native_mut(), rust_object: userdata as *mut B })
Stephen Crane2a3c2502020-06-16 17:48:35 -0700421 }
422}
423
424/// # Safety
425///
426/// The constructor for `Binder` guarantees that `self.ibinder` will contain a
427/// valid, non-null pointer to an `AIBinder`, so this implementation is type
428/// safe. `self.ibinder` will remain valid for the entire lifetime of `self`
429/// because we hold a strong reference to the `AIBinder` until `self` is
430/// dropped.
431unsafe impl<B: Remotable> AsNative<sys::AIBinder> for Binder<B> {
432 fn as_native(&self) -> *const sys::AIBinder {
433 self.ibinder
434 }
435
436 fn as_native_mut(&mut self) -> *mut sys::AIBinder {
437 self.ibinder
438 }
439}
440
441/// Register a new service with the default service manager.
442///
443/// Registers the given binder object with the given identifier. If successful,
444/// this service can then be retrieved using that identifier.
Alan Stokes1a49e4f2021-09-23 10:30:47 +0100445///
446/// This function will panic if the identifier contains a 0 byte (NUL).
Stephen Crane2a3c2502020-06-16 17:48:35 -0700447pub fn add_service(identifier: &str, mut binder: SpIBinder) -> Result<()> {
448 let instance = CString::new(identifier).unwrap();
449 let status = unsafe {
450 // Safety: `AServiceManager_addService` expects valid `AIBinder` and C
451 // string pointers. Caller retains ownership of both
452 // pointers. `AServiceManager_addService` creates a new strong reference
453 // and copies the string, so both pointers need only be valid until the
454 // call returns.
455 sys::AServiceManager_addService(binder.as_native_mut(), instance.as_ptr())
456 };
457 status_result(status)
458}
459
Alan Stokes23fdfcd2021-09-09 11:19:24 +0100460/// Register a dynamic service via the LazyServiceRegistrar.
461///
462/// Registers the given binder object with the given identifier. If successful,
463/// this service can then be retrieved using that identifier. The service process
464/// will be shut down once all registered services are no longer in use.
465///
466/// If any service in the process is registered as lazy, all should be, otherwise
467/// the process may be shut down while a service is in use.
Alan Stokes1a49e4f2021-09-23 10:30:47 +0100468///
469/// This function will panic if the identifier contains a 0 byte (NUL).
Alan Stokes23fdfcd2021-09-09 11:19:24 +0100470pub fn register_lazy_service(identifier: &str, mut binder: SpIBinder) -> Result<()> {
471 let instance = CString::new(identifier).unwrap();
472 let status = unsafe {
473 // Safety: `AServiceManager_registerLazyService` expects valid `AIBinder` and C
474 // string pointers. Caller retains ownership of both
475 // pointers. `AServiceManager_registerLazyService` creates a new strong reference
476 // and copies the string, so both pointers need only be valid until the
477 // call returns.
478
479 sys::AServiceManager_registerLazyService(binder.as_native_mut(), instance.as_ptr())
480 };
481 status_result(status)
482}
483
484/// Prevent a process which registers lazy services from being shut down even when none
485/// of the services is in use.
486///
487/// If persist is true then shut down will be blocked until this function is called again with
488/// persist false. If this is to be the initial state, call this function before calling
489/// register_lazy_service.
490pub fn force_lazy_services_persist(persist: bool) {
491 unsafe {
492 // Safety: No borrowing or transfer of ownership occurs here.
493 sys::AServiceManager_forceLazyServicesPersist(persist)
494 }
495}
496
Stephen Crane2a3c2502020-06-16 17:48:35 -0700497/// Tests often create a base BBinder instance; so allowing the unit
498/// type to be remotable translates nicely to Binder::new(()).
499impl Remotable for () {
500 fn get_descriptor() -> &'static str {
501 ""
502 }
503
504 fn on_transact(
505 &self,
506 _code: TransactionCode,
Alice Ryhl8618c482021-11-09 15:35:35 +0000507 _data: &BorrowedParcel<'_>,
508 _reply: &mut BorrowedParcel<'_>,
Stephen Crane2a3c2502020-06-16 17:48:35 -0700509 ) -> Result<()> {
510 Ok(())
511 }
512
Stephen Crane2a3297f2021-06-11 16:48:10 -0700513 fn on_dump(&self, _file: &File, _args: &[&CStr]) -> Result<()> {
514 Ok(())
515 }
516
Stephen Crane2a3c2502020-06-16 17:48:35 -0700517 binder_fn_get_class!(Binder::<Self>);
518}
519
520impl Interface for () {}
Alice Ryhlad9c77b2021-11-16 09:49:29 +0000521
522/// Determine whether the current thread is currently executing an incoming
523/// transaction.
524pub fn is_handling_transaction() -> bool {
525 unsafe {
526 // Safety: This method is always safe to call.
527 sys::AIBinder_isHandlingTransaction()
528 }
529}