blob: 3a6daddffdc7ec383f1f82413ef3aa48cf5f2a86 [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
Andrew Walbran7b0be1f2022-08-04 16:47:46 +000025use lazy_static::lazy_static;
Stephen Crane2a3c2502020-06-16 17:48:35 -070026use std::convert::TryFrom;
Stephen Crane2a3297f2021-06-11 16:48:10 -070027use std::ffi::{c_void, CStr, CString};
28use std::fs::File;
Stephen Crane2a3c2502020-06-16 17:48:35 -070029use std::mem::ManuallyDrop;
30use std::ops::Deref;
Stephen Crane2a3297f2021-06-11 16:48:10 -070031use std::os::raw::c_char;
32use std::os::unix::io::FromRawFd;
33use std::slice;
Andrew Walbran7b0be1f2022-08-04 16:47:46 +000034use std::sync::Mutex;
Stephen Crane2a3c2502020-06-16 17:48:35 -070035
36/// Rust wrapper around Binder remotable objects.
37///
38/// Implements the C++ `BBinder` class, and therefore implements the C++
39/// `IBinder` interface.
40#[repr(C)]
41pub struct Binder<T: Remotable> {
42 ibinder: *mut sys::AIBinder,
43 rust_object: *mut T,
44}
45
Andrei Homescu2c674b02020-08-07 22:12:27 -070046/// # Safety
47///
48/// A `Binder<T>` is a pair of unique owning pointers to two values:
49/// * a C++ ABBinder which the C++ API guarantees can be passed between threads
50/// * a Rust object which implements `Remotable`; this trait requires `Send + Sync`
51///
52/// Both pointers are unique (never escape the `Binder<T>` object and are not copied)
53/// so we can essentially treat `Binder<T>` as a box-like containing the two objects;
54/// the box-like object inherits `Send` from the two inner values, similarly
55/// to how `Box<T>` is `Send` if `T` is `Send`.
56unsafe impl<T: Remotable> Send for Binder<T> {}
57
Stephen Cranef03fe3d2021-06-25 15:05:00 -070058/// # Safety
59///
60/// A `Binder<T>` is a pair of unique owning pointers to two values:
61/// * a C++ ABBinder which is thread-safe, i.e. `Send + Sync`
62/// * a Rust object which implements `Remotable`; this trait requires `Send + Sync`
63///
64/// `ABBinder` contains an immutable `mUserData` pointer, which is actually a
65/// pointer to a boxed `T: Remotable`, which is `Sync`. `ABBinder` also contains
66/// a mutable pointer to its class, but mutation of this field is controlled by
67/// a mutex and it is only allowed to be set once, therefore we can concurrently
68/// access this field safely. `ABBinder` inherits from `BBinder`, which is also
69/// thread-safe. Thus `ABBinder` is thread-safe.
70///
71/// Both pointers are unique (never escape the `Binder<T>` object and are not copied)
72/// so we can essentially treat `Binder<T>` as a box-like containing the two objects;
73/// the box-like object inherits `Sync` from the two inner values, similarly
74/// to how `Box<T>` is `Sync` if `T` is `Sync`.
75unsafe impl<T: Remotable> Sync for Binder<T> {}
76
Stephen Crane2a3c2502020-06-16 17:48:35 -070077impl<T: Remotable> Binder<T> {
Stephen Craneff7f03a2021-02-25 16:04:22 -080078 /// Create a new Binder remotable object with default stability
Stephen Crane2a3c2502020-06-16 17:48:35 -070079 ///
80 /// This moves the `rust_object` into an owned [`Box`] and Binder will
81 /// manage its lifetime.
82 pub fn new(rust_object: T) -> Binder<T> {
Stephen Craneff7f03a2021-02-25 16:04:22 -080083 Self::new_with_stability(rust_object, Stability::default())
84 }
85
86 /// Create a new Binder remotable object with the given stability
87 ///
88 /// This moves the `rust_object` into an owned [`Box`] and Binder will
89 /// manage its lifetime.
90 pub fn new_with_stability(rust_object: T, stability: Stability) -> Binder<T> {
Stephen Crane2a3c2502020-06-16 17:48:35 -070091 let class = T::get_class();
92 let rust_object = Box::into_raw(Box::new(rust_object));
93 let ibinder = unsafe {
94 // Safety: `AIBinder_new` expects a valid class pointer (which we
95 // initialize via `get_class`), and an arbitrary pointer
96 // argument. The caller owns the returned `AIBinder` pointer, which
97 // is a strong reference to a `BBinder`. This reference should be
98 // decremented via `AIBinder_decStrong` when the reference lifetime
99 // ends.
100 sys::AIBinder_new(class.into(), rust_object as *mut c_void)
101 };
Matthew Maurere268a9f2022-07-26 09:31:30 -0700102 let mut binder = Binder { ibinder, rust_object };
Stephen Craneff7f03a2021-02-25 16:04:22 -0800103 binder.mark_stability(stability);
104 binder
Stephen Crane2a3c2502020-06-16 17:48:35 -0700105 }
106
107 /// Set the extension of a binder interface. This allows a downstream
108 /// developer to add an extension to an interface without modifying its
109 /// interface file. This should be called immediately when the object is
110 /// created before it is passed to another thread.
111 ///
112 /// # Examples
113 ///
114 /// For instance, imagine if we have this Binder AIDL interface definition:
115 /// interface IFoo { void doFoo(); }
116 ///
117 /// If an unrelated owner (perhaps in a downstream codebase) wants to make a
118 /// change to the interface, they have two options:
119 ///
120 /// 1) Historical option that has proven to be BAD! Only the original
121 /// author of an interface should change an interface. If someone
122 /// downstream wants additional functionality, they should not ever
123 /// change the interface or use this method.
124 /// ```AIDL
125 /// BAD TO DO: interface IFoo { BAD TO DO
126 /// BAD TO DO: void doFoo(); BAD TO DO
127 /// BAD TO DO: + void doBar(); // adding a method BAD TO DO
128 /// BAD TO DO: } BAD TO DO
129 /// ```
130 ///
131 /// 2) Option that this method enables!
132 /// Leave the original interface unchanged (do not change IFoo!).
133 /// Instead, create a new AIDL interface in a downstream package:
134 /// ```AIDL
135 /// package com.<name>; // new functionality in a new package
136 /// interface IBar { void doBar(); }
137 /// ```
138 ///
139 /// When registering the interface, add:
140 ///
141 /// # use binder::{Binder, Interface};
142 /// # type MyFoo = ();
143 /// # type MyBar = ();
144 /// # let my_foo = ();
145 /// # let my_bar = ();
146 /// let mut foo: Binder<MyFoo> = Binder::new(my_foo); // class in AOSP codebase
147 /// let bar: Binder<MyBar> = Binder::new(my_bar); // custom extension class
148 /// foo.set_extension(&mut bar.as_binder()); // use method in Binder
149 ///
150 /// Then, clients of `IFoo` can get this extension:
151 ///
152 /// # use binder::{declare_binder_interface, Binder, TransactionCode, Parcel};
153 /// # trait IBar {}
154 /// # declare_binder_interface! {
155 /// # IBar["test"] {
156 /// # native: BnBar(on_transact),
157 /// # proxy: BpBar,
158 /// # }
159 /// # }
160 /// # fn on_transact(
161 /// # service: &dyn IBar,
162 /// # code: TransactionCode,
Alice Ryhl8618c482021-11-09 15:35:35 +0000163 /// # data: &BorrowedParcel,
164 /// # reply: &mut BorrowedParcel,
Stephen Crane2a3c2502020-06-16 17:48:35 -0700165 /// # ) -> binder::Result<()> {
166 /// # Ok(())
167 /// # }
168 /// # impl IBar for BpBar {}
169 /// # impl IBar for Binder<BnBar> {}
170 /// # fn main() -> binder::Result<()> {
171 /// # let binder = Binder::new(());
172 /// if let Some(barBinder) = binder.get_extension()? {
173 /// let bar = BpBar::new(barBinder)
174 /// .expect("Extension was not of type IBar");
175 /// } else {
176 /// // There was no extension
177 /// }
178 /// # }
179 pub fn set_extension(&mut self, extension: &mut SpIBinder) -> Result<()> {
180 let status = unsafe {
181 // Safety: `AIBinder_setExtension` expects two valid, mutable
182 // `AIBinder` pointers. We are guaranteed that both `self` and
183 // `extension` contain valid `AIBinder` pointers, because they
184 // cannot be initialized without a valid
185 // pointer. `AIBinder_setExtension` does not take ownership of
186 // either parameter.
187 sys::AIBinder_setExtension(self.as_native_mut(), extension.as_native_mut())
188 };
189 status_result(status)
190 }
191
192 /// Retrieve the interface descriptor string for this object's Binder
193 /// interface.
194 pub fn get_descriptor() -> &'static str {
195 T::get_descriptor()
196 }
Stephen Craneff7f03a2021-02-25 16:04:22 -0800197
198 /// Mark this binder object with the given stability guarantee
199 fn mark_stability(&mut self, stability: Stability) {
200 match stability {
201 Stability::Local => self.mark_local_stability(),
202 Stability::Vintf => {
203 unsafe {
204 // Safety: Self always contains a valid `AIBinder` pointer, so
205 // we can always call this C API safely.
206 sys::AIBinder_markVintfStability(self.as_native_mut());
207 }
208 }
209 }
210 }
211
212 /// Mark this binder object with local stability, which is vendor if we are
213 /// building for the VNDK and system otherwise.
Janis Danisevskis1323d512021-11-09 07:48:08 -0800214 #[cfg(any(vendor_ndk, android_vndk))]
Stephen Craneff7f03a2021-02-25 16:04:22 -0800215 fn mark_local_stability(&mut self) {
216 unsafe {
217 // Safety: Self always contains a valid `AIBinder` pointer, so
218 // we can always call this C API safely.
219 sys::AIBinder_markVendorStability(self.as_native_mut());
220 }
221 }
222
223 /// Mark this binder object with local stability, which is vendor if we are
224 /// building for the VNDK and system otherwise.
Janis Danisevskis1323d512021-11-09 07:48:08 -0800225 #[cfg(not(any(vendor_ndk, android_vndk)))]
Stephen Craneff7f03a2021-02-25 16:04:22 -0800226 fn mark_local_stability(&mut self) {
227 unsafe {
228 // Safety: Self always contains a valid `AIBinder` pointer, so
229 // we can always call this C API safely.
230 sys::AIBinder_markSystemStability(self.as_native_mut());
231 }
232 }
Stephen Crane2a3c2502020-06-16 17:48:35 -0700233}
234
235impl<T: Remotable> Interface for Binder<T> {
236 /// Converts the local remotable object into a generic `SpIBinder`
237 /// reference.
238 ///
239 /// The resulting `SpIBinder` will hold its own strong reference to this
240 /// remotable object, which will prevent the object from being dropped while
241 /// the `SpIBinder` is alive.
242 fn as_binder(&self) -> SpIBinder {
243 unsafe {
244 // Safety: `self.ibinder` is guaranteed to always be a valid pointer
245 // to an `AIBinder` by the `Binder` constructor. We are creating a
246 // copy of the `self.ibinder` strong reference, but
247 // `SpIBinder::from_raw` assumes it receives an owned pointer with
248 // its own strong reference. We first increment the reference count,
249 // so that the new `SpIBinder` will be tracked as a new reference.
250 sys::AIBinder_incStrong(self.ibinder);
251 SpIBinder::from_raw(self.ibinder).unwrap()
252 }
253 }
254}
255
256impl<T: Remotable> InterfaceClassMethods for Binder<T> {
257 fn get_descriptor() -> &'static str {
258 <T as Remotable>::get_descriptor()
259 }
260
261 /// Called whenever a transaction needs to be processed by a local
262 /// implementation.
263 ///
264 /// # Safety
265 ///
266 /// Must be called with a non-null, valid pointer to a local `AIBinder` that
267 /// contains a `T` pointer in its user data. The `data` and `reply` parcel
268 /// parameters must be valid pointers to `AParcel` objects. This method does
269 /// not take ownership of any of its parameters.
270 ///
271 /// These conditions hold when invoked by `ABBinder::onTransact`.
272 unsafe extern "C" fn on_transact(
273 binder: *mut sys::AIBinder,
274 code: u32,
275 data: *const sys::AParcel,
276 reply: *mut sys::AParcel,
277 ) -> status_t {
278 let res = {
Alice Ryhl8618c482021-11-09 15:35:35 +0000279 let mut reply = BorrowedParcel::from_raw(reply).unwrap();
280 let data = BorrowedParcel::from_raw(data as *mut sys::AParcel).unwrap();
Stephen Crane2a3c2502020-06-16 17:48:35 -0700281 let object = sys::AIBinder_getUserData(binder);
282 let binder: &T = &*(object as *const T);
283 binder.on_transact(code, &data, &mut reply)
284 };
285 match res {
286 Ok(()) => 0i32,
287 Err(e) => e as i32,
288 }
289 }
290
291 /// Called whenever an `AIBinder` object is no longer referenced and needs
292 /// destroyed.
293 ///
294 /// # Safety
295 ///
296 /// Must be called with a valid pointer to a `T` object. After this call,
297 /// the pointer will be invalid and should not be dereferenced.
298 unsafe extern "C" fn on_destroy(object: *mut c_void) {
Matthew Maurerc050d8f2021-06-11 16:49:48 -0700299 Box::from_raw(object as *mut T);
Stephen Crane2a3c2502020-06-16 17:48:35 -0700300 }
301
302 /// Called whenever a new, local `AIBinder` object is needed of a specific
303 /// class.
304 ///
305 /// Constructs the user data pointer that will be stored in the object,
306 /// which will be a heap-allocated `T` object.
307 ///
308 /// # Safety
309 ///
310 /// Must be called with a valid pointer to a `T` object allocated via `Box`.
311 unsafe extern "C" fn on_create(args: *mut c_void) -> *mut c_void {
312 // We just return the argument, as it is already a pointer to the rust
313 // object created by Box.
314 args
315 }
Stephen Crane2a3297f2021-06-11 16:48:10 -0700316
317 /// Called to handle the `dump` transaction.
318 ///
319 /// # Safety
320 ///
321 /// Must be called with a non-null, valid pointer to a local `AIBinder` that
322 /// contains a `T` pointer in its user data. fd should be a non-owned file
323 /// descriptor, and args must be an array of null-terminated string
324 /// poiinters with length num_args.
Alan Stokes23fdfcd2021-09-09 11:19:24 +0100325 unsafe extern "C" fn on_dump(
326 binder: *mut sys::AIBinder,
327 fd: i32,
328 args: *mut *const c_char,
329 num_args: u32,
330 ) -> status_t {
Stephen Crane2a3297f2021-06-11 16:48:10 -0700331 if fd < 0 {
332 return StatusCode::UNEXPECTED_NULL as status_t;
333 }
334 // We don't own this file, so we need to be careful not to drop it.
335 let file = ManuallyDrop::new(File::from_raw_fd(fd));
336
Stephen Crane0c5f9232022-06-17 11:48:05 -0700337 if args.is_null() && num_args != 0 {
Stephen Crane2a3297f2021-06-11 16:48:10 -0700338 return StatusCode::UNEXPECTED_NULL as status_t;
339 }
Stephen Crane0c5f9232022-06-17 11:48:05 -0700340
341 let args = if args.is_null() || num_args == 0 {
342 vec![]
343 } else {
344 slice::from_raw_parts(args, num_args as usize)
Matthew Maurere268a9f2022-07-26 09:31:30 -0700345 .iter()
346 .map(|s| CStr::from_ptr(*s))
347 .collect()
Stephen Crane0c5f9232022-06-17 11:48:05 -0700348 };
Stephen Crane2a3297f2021-06-11 16:48:10 -0700349
350 let object = sys::AIBinder_getUserData(binder);
351 let binder: &T = &*(object as *const T);
352 let res = binder.on_dump(&file, &args);
353
354 match res {
355 Ok(()) => 0,
356 Err(e) => e as status_t,
357 }
358 }
Stephen Crane2a3c2502020-06-16 17:48:35 -0700359}
360
361impl<T: Remotable> Drop for Binder<T> {
362 // This causes C++ to decrease the strong ref count of the `AIBinder`
363 // object. We specifically do not drop the `rust_object` here. When C++
364 // actually destroys the object, it calls `on_destroy` and we can drop the
365 // `rust_object` then.
366 fn drop(&mut self) {
367 unsafe {
368 // Safety: When `self` is dropped, we can no longer access the
369 // reference, so can decrement the reference count. `self.ibinder`
370 // is always a valid `AIBinder` pointer, so is valid to pass to
371 // `AIBinder_decStrong`.
372 sys::AIBinder_decStrong(self.ibinder);
373 }
374 }
375}
376
377impl<T: Remotable> Deref for Binder<T> {
378 type Target = T;
379
380 fn deref(&self) -> &Self::Target {
381 unsafe {
382 // Safety: While `self` is alive, the reference count of the
383 // underlying object is > 0 and therefore `on_destroy` cannot be
384 // called. Therefore while `self` is alive, we know that
385 // `rust_object` is still a valid pointer to a heap allocated object
386 // of type `T`.
387 &*self.rust_object
388 }
389 }
390}
391
392impl<B: Remotable> Serialize for Binder<B> {
Alice Ryhl8618c482021-11-09 15:35:35 +0000393 fn serialize(&self, parcel: &mut BorrowedParcel<'_>) -> Result<()> {
Stephen Crane2a3c2502020-06-16 17:48:35 -0700394 parcel.write_binder(Some(&self.as_binder()))
395 }
396}
397
398// This implementation is an idiomatic implementation of the C++
399// `IBinder::localBinder` interface if the binder object is a Rust binder
400// service.
401impl<B: Remotable> TryFrom<SpIBinder> for Binder<B> {
402 type Error = StatusCode;
403
404 fn try_from(mut ibinder: SpIBinder) -> Result<Self> {
405 let class = B::get_class();
406 if Some(class) != ibinder.get_class() {
407 return Err(StatusCode::BAD_TYPE);
408 }
409 let userdata = unsafe {
410 // Safety: `SpIBinder` always holds a valid pointer pointer to an
411 // `AIBinder`, which we can safely pass to
412 // `AIBinder_getUserData`. `ibinder` retains ownership of the
413 // returned pointer.
414 sys::AIBinder_getUserData(ibinder.as_native_mut())
415 };
416 if userdata.is_null() {
417 return Err(StatusCode::UNEXPECTED_NULL);
418 }
419 // We are transferring the ownership of the AIBinder into the new Binder
420 // object.
421 let mut ibinder = ManuallyDrop::new(ibinder);
Matthew Maurere268a9f2022-07-26 09:31:30 -0700422 Ok(Binder { ibinder: ibinder.as_native_mut(), rust_object: userdata as *mut B })
Stephen Crane2a3c2502020-06-16 17:48:35 -0700423 }
424}
425
426/// # Safety
427///
428/// The constructor for `Binder` guarantees that `self.ibinder` will contain a
429/// valid, non-null pointer to an `AIBinder`, so this implementation is type
430/// safe. `self.ibinder` will remain valid for the entire lifetime of `self`
431/// because we hold a strong reference to the `AIBinder` until `self` is
432/// dropped.
433unsafe impl<B: Remotable> AsNative<sys::AIBinder> for Binder<B> {
434 fn as_native(&self) -> *const sys::AIBinder {
435 self.ibinder
436 }
437
438 fn as_native_mut(&mut self) -> *mut sys::AIBinder {
439 self.ibinder
440 }
441}
442
443/// Register a new service with the default service manager.
444///
445/// Registers the given binder object with the given identifier. If successful,
446/// this service can then be retrieved using that identifier.
Alan Stokes1a49e4f2021-09-23 10:30:47 +0100447///
448/// This function will panic if the identifier contains a 0 byte (NUL).
Stephen Crane2a3c2502020-06-16 17:48:35 -0700449pub fn add_service(identifier: &str, mut binder: SpIBinder) -> Result<()> {
450 let instance = CString::new(identifier).unwrap();
451 let status = unsafe {
452 // Safety: `AServiceManager_addService` expects valid `AIBinder` and C
453 // string pointers. Caller retains ownership of both
454 // pointers. `AServiceManager_addService` creates a new strong reference
455 // and copies the string, so both pointers need only be valid until the
456 // call returns.
457 sys::AServiceManager_addService(binder.as_native_mut(), instance.as_ptr())
458 };
459 status_result(status)
460}
461
Alan Stokes23fdfcd2021-09-09 11:19:24 +0100462/// Register a dynamic service via the LazyServiceRegistrar.
463///
464/// Registers the given binder object with the given identifier. If successful,
465/// this service can then be retrieved using that identifier. The service process
466/// will be shut down once all registered services are no longer in use.
467///
468/// If any service in the process is registered as lazy, all should be, otherwise
469/// the process may be shut down while a service is in use.
Alan Stokes1a49e4f2021-09-23 10:30:47 +0100470///
471/// This function will panic if the identifier contains a 0 byte (NUL).
Alan Stokes23fdfcd2021-09-09 11:19:24 +0100472pub fn register_lazy_service(identifier: &str, mut binder: SpIBinder) -> Result<()> {
473 let instance = CString::new(identifier).unwrap();
474 let status = unsafe {
475 // Safety: `AServiceManager_registerLazyService` expects valid `AIBinder` and C
476 // string pointers. Caller retains ownership of both
477 // pointers. `AServiceManager_registerLazyService` creates a new strong reference
478 // and copies the string, so both pointers need only be valid until the
479 // call returns.
480
481 sys::AServiceManager_registerLazyService(binder.as_native_mut(), instance.as_ptr())
482 };
483 status_result(status)
484}
485
486/// Prevent a process which registers lazy services from being shut down even when none
487/// of the services is in use.
488///
489/// If persist is true then shut down will be blocked until this function is called again with
490/// persist false. If this is to be the initial state, call this function before calling
491/// register_lazy_service.
Andrew Walbran7b0be1f2022-08-04 16:47:46 +0000492///
493/// Consider using [`LazyServiceGuard`] rather than calling this directly.
Alan Stokes23fdfcd2021-09-09 11:19:24 +0100494pub 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
Andrew Walbran7b0be1f2022-08-04 16:47:46 +0000501/// An RAII object to ensure a process which registers lazy services is not killed. During the
502/// lifetime of any of these objects the service manager will not not kill the process even if none
503/// of its lazy services are in use.
504#[must_use]
505#[derive(Debug)]
506pub struct LazyServiceGuard {
507 // Prevent construction outside this module.
508 _private: (),
509}
510
511lazy_static! {
512 // Count of how many LazyServiceGuard objects are in existence.
513 static ref GUARD_COUNT: Mutex<u64> = Mutex::new(0);
514}
515
516impl LazyServiceGuard {
517 /// Create a new LazyServiceGuard to prevent the service manager prematurely killing this
518 /// process.
519 pub fn new() -> Self {
520 let mut count = GUARD_COUNT.lock().unwrap();
521 *count += 1;
522 if *count == 1 {
523 // It's important that we make this call with the mutex held, to make sure
524 // that multiple calls (e.g. if the count goes 1 -> 0 -> 1) are correctly
525 // sequenced. (That also means we can't just use an AtomicU64.)
526 force_lazy_services_persist(true);
527 }
528 Self { _private: () }
529 }
530}
531
532impl Drop for LazyServiceGuard {
533 fn drop(&mut self) {
534 let mut count = GUARD_COUNT.lock().unwrap();
535 *count -= 1;
536 if *count == 0 {
537 force_lazy_services_persist(false);
538 }
539 }
540}
541
542impl Clone for LazyServiceGuard {
543 fn clone(&self) -> Self {
544 Self::new()
545 }
546}
547
548impl Default for LazyServiceGuard {
549 fn default() -> Self {
550 Self::new()
551 }
552}
553
Stephen Crane2a3c2502020-06-16 17:48:35 -0700554/// Tests often create a base BBinder instance; so allowing the unit
555/// type to be remotable translates nicely to Binder::new(()).
556impl Remotable for () {
557 fn get_descriptor() -> &'static str {
558 ""
559 }
560
561 fn on_transact(
562 &self,
563 _code: TransactionCode,
Alice Ryhl8618c482021-11-09 15:35:35 +0000564 _data: &BorrowedParcel<'_>,
565 _reply: &mut BorrowedParcel<'_>,
Stephen Crane2a3c2502020-06-16 17:48:35 -0700566 ) -> Result<()> {
567 Ok(())
568 }
569
Stephen Crane2a3297f2021-06-11 16:48:10 -0700570 fn on_dump(&self, _file: &File, _args: &[&CStr]) -> Result<()> {
571 Ok(())
572 }
573
Stephen Crane2a3c2502020-06-16 17:48:35 -0700574 binder_fn_get_class!(Binder::<Self>);
575}
576
577impl Interface for () {}
Alice Ryhlad9c77b2021-11-16 09:49:29 +0000578
579/// Determine whether the current thread is currently executing an incoming
580/// transaction.
581pub fn is_handling_transaction() -> bool {
582 unsafe {
583 // Safety: This method is always safe to call.
584 sys::AIBinder_isHandlingTransaction()
585 }
586}