blob: b250012801bd0ae0aaf68912522152951bc342eb [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;
Andrei Homescud23c0492023-11-09 01:51:59 +000028use std::io::Write;
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
Andrew Walbran2f3ff9f2023-07-07 16:58:13 +010046/// Safety:
Andrei Homescu2c674b02020-08-07 22:12:27 -070047///
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
Andrew Walbran2f3ff9f2023-07-07 16:58:13 +010058/// Safety:
Stephen Cranef03fe3d2021-06-25 15:05:00 -070059///
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));
Andrew Walbran2f3ff9f2023-07-07 16:58:13 +010093 // 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 let ibinder = unsafe { sys::AIBinder_new(class.into(), rust_object as *mut c_void) };
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<()> {
Andrew Walbran2f3ff9f2023-07-07 16:58:13 +0100178 let status =
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 unsafe { sys::AIBinder_setExtension(self.as_native_mut(), extension.as_native_mut()) };
Stephen Crane2a3c2502020-06-16 17:48:35 -0700186 status_result(status)
187 }
188
189 /// Retrieve the interface descriptor string for this object's Binder
190 /// interface.
191 pub fn get_descriptor() -> &'static str {
192 T::get_descriptor()
193 }
Stephen Craneff7f03a2021-02-25 16:04:22 -0800194
195 /// Mark this binder object with the given stability guarantee
196 fn mark_stability(&mut self, stability: Stability) {
197 match stability {
198 Stability::Local => self.mark_local_stability(),
199 Stability::Vintf => {
Andrew Walbran2f3ff9f2023-07-07 16:58:13 +0100200 // Safety: Self always contains a valid `AIBinder` pointer, so
201 // we can always call this C API safely.
Stephen Craneff7f03a2021-02-25 16:04:22 -0800202 unsafe {
Stephen Craneff7f03a2021-02-25 16:04:22 -0800203 sys::AIBinder_markVintfStability(self.as_native_mut());
204 }
205 }
206 }
207 }
208
209 /// Mark this binder object with local stability, which is vendor if we are
Devin Moore3d5ca6b2023-02-17 02:10:50 +0000210 /// building for android_vendor and system otherwise.
211 #[cfg(android_vendor)]
Stephen Craneff7f03a2021-02-25 16:04:22 -0800212 fn mark_local_stability(&mut self) {
Andrew Walbran2f3ff9f2023-07-07 16:58:13 +0100213 // Safety: Self always contains a valid `AIBinder` pointer, so we can
214 // always call this C API safely.
Stephen Craneff7f03a2021-02-25 16:04:22 -0800215 unsafe {
Stephen Craneff7f03a2021-02-25 16:04:22 -0800216 sys::AIBinder_markVendorStability(self.as_native_mut());
217 }
218 }
219
220 /// Mark this binder object with local stability, which is vendor if we are
Devin Moore3d5ca6b2023-02-17 02:10:50 +0000221 /// building for android_vendor and system otherwise.
222 #[cfg(not(android_vendor))]
Stephen Craneff7f03a2021-02-25 16:04:22 -0800223 fn mark_local_stability(&mut self) {
Andrew Walbran2f3ff9f2023-07-07 16:58:13 +0100224 // Safety: Self always contains a valid `AIBinder` pointer, so we can
225 // always call this C API safely.
Stephen Craneff7f03a2021-02-25 16:04:22 -0800226 unsafe {
Stephen Craneff7f03a2021-02-25 16:04:22 -0800227 sys::AIBinder_markSystemStability(self.as_native_mut());
228 }
229 }
Stephen Crane2a3c2502020-06-16 17:48:35 -0700230}
231
232impl<T: Remotable> Interface for Binder<T> {
233 /// Converts the local remotable object into a generic `SpIBinder`
234 /// reference.
235 ///
236 /// The resulting `SpIBinder` will hold its own strong reference to this
237 /// remotable object, which will prevent the object from being dropped while
238 /// the `SpIBinder` is alive.
239 fn as_binder(&self) -> SpIBinder {
Andrew Walbran2f3ff9f2023-07-07 16:58:13 +0100240 // Safety: `self.ibinder` is guaranteed to always be a valid pointer
241 // to an `AIBinder` by the `Binder` constructor. We are creating a
242 // copy of the `self.ibinder` strong reference, but
243 // `SpIBinder::from_raw` assumes it receives an owned pointer with
244 // its own strong reference. We first increment the reference count,
245 // so that the new `SpIBinder` will be tracked as a new reference.
Stephen Crane2a3c2502020-06-16 17:48:35 -0700246 unsafe {
Stephen Crane2a3c2502020-06-16 17:48:35 -0700247 sys::AIBinder_incStrong(self.ibinder);
248 SpIBinder::from_raw(self.ibinder).unwrap()
249 }
250 }
251}
252
253impl<T: Remotable> InterfaceClassMethods for Binder<T> {
254 fn get_descriptor() -> &'static str {
255 <T as Remotable>::get_descriptor()
256 }
257
258 /// Called whenever a transaction needs to be processed by a local
259 /// implementation.
260 ///
261 /// # Safety
262 ///
263 /// Must be called with a non-null, valid pointer to a local `AIBinder` that
264 /// contains a `T` pointer in its user data. The `data` and `reply` parcel
265 /// parameters must be valid pointers to `AParcel` objects. This method does
266 /// not take ownership of any of its parameters.
267 ///
268 /// These conditions hold when invoked by `ABBinder::onTransact`.
269 unsafe extern "C" fn on_transact(
270 binder: *mut sys::AIBinder,
271 code: u32,
272 data: *const sys::AParcel,
273 reply: *mut sys::AParcel,
274 ) -> status_t {
275 let res = {
Andrew Walbran2f3ff9f2023-07-07 16:58:13 +0100276 // Safety: The caller must give us a parcel pointer which is either
277 // null or valid at least for the duration of this function call. We
278 // don't keep the resulting value beyond the function.
279 let mut reply = unsafe { BorrowedParcel::from_raw(reply).unwrap() };
280 // Safety: The caller must give us a parcel pointer which is either
281 // null or valid at least for the duration of this function call. We
282 // don't keep the resulting value beyond the function.
283 let data = unsafe { BorrowedParcel::from_raw(data as *mut sys::AParcel).unwrap() };
284 // Safety: Our caller promised that `binder` is a non-null, valid
285 // pointer to a local `AIBinder`.
286 let object = unsafe { sys::AIBinder_getUserData(binder) };
287 // Safety: Our caller promised that the binder has a `T` pointer in
288 // its user data.
289 let binder: &T = unsafe { &*(object as *const T) };
Stephen Crane2a3c2502020-06-16 17:48:35 -0700290 binder.on_transact(code, &data, &mut reply)
291 };
292 match res {
293 Ok(()) => 0i32,
294 Err(e) => e as i32,
295 }
296 }
297
298 /// Called whenever an `AIBinder` object is no longer referenced and needs
299 /// destroyed.
300 ///
301 /// # Safety
302 ///
303 /// Must be called with a valid pointer to a `T` object. After this call,
304 /// the pointer will be invalid and should not be dereferenced.
305 unsafe extern "C" fn on_destroy(object: *mut c_void) {
Andrew Walbran2f3ff9f2023-07-07 16:58:13 +0100306 // Safety: Our caller promised that `object` is a valid pointer to a
307 // `T`.
308 drop(unsafe { Box::from_raw(object as *mut T) });
Stephen Crane2a3c2502020-06-16 17:48:35 -0700309 }
310
311 /// Called whenever a new, local `AIBinder` object is needed of a specific
312 /// class.
313 ///
314 /// Constructs the user data pointer that will be stored in the object,
315 /// which will be a heap-allocated `T` object.
316 ///
317 /// # Safety
318 ///
319 /// Must be called with a valid pointer to a `T` object allocated via `Box`.
320 unsafe extern "C" fn on_create(args: *mut c_void) -> *mut c_void {
321 // We just return the argument, as it is already a pointer to the rust
322 // object created by Box.
323 args
324 }
Stephen Crane2a3297f2021-06-11 16:48:10 -0700325
326 /// Called to handle the `dump` transaction.
327 ///
328 /// # Safety
329 ///
330 /// Must be called with a non-null, valid pointer to a local `AIBinder` that
331 /// contains a `T` pointer in its user data. fd should be a non-owned file
332 /// descriptor, and args must be an array of null-terminated string
Andrew Walbran2f3ff9f2023-07-07 16:58:13 +0100333 /// pointers with length num_args.
Alan Stokes23fdfcd2021-09-09 11:19:24 +0100334 unsafe extern "C" fn on_dump(
335 binder: *mut sys::AIBinder,
336 fd: i32,
337 args: *mut *const c_char,
338 num_args: u32,
339 ) -> status_t {
Stephen Crane2a3297f2021-06-11 16:48:10 -0700340 if fd < 0 {
341 return StatusCode::UNEXPECTED_NULL as status_t;
342 }
Andrew Walbran2f3ff9f2023-07-07 16:58:13 +0100343 // Safety: Our caller promised that fd is a file descriptor. We don't
344 // own this file descriptor, so we need to be careful not to drop it.
Andrei Homescud23c0492023-11-09 01:51:59 +0000345 let mut file = unsafe { ManuallyDrop::new(File::from_raw_fd(fd)) };
Stephen Crane2a3297f2021-06-11 16:48:10 -0700346
Stephen Crane0c5f9232022-06-17 11:48:05 -0700347 if args.is_null() && num_args != 0 {
Stephen Crane2a3297f2021-06-11 16:48:10 -0700348 return StatusCode::UNEXPECTED_NULL as status_t;
349 }
Stephen Crane0c5f9232022-06-17 11:48:05 -0700350
351 let args = if args.is_null() || num_args == 0 {
352 vec![]
353 } else {
Andrew Walbran2f3ff9f2023-07-07 16:58:13 +0100354 // Safety: Our caller promised that `args` is an array of
355 // null-terminated string pointers with length `num_args`.
356 unsafe {
357 slice::from_raw_parts(args, num_args as usize)
358 .iter()
359 .map(|s| CStr::from_ptr(*s))
360 .collect()
361 }
Stephen Crane0c5f9232022-06-17 11:48:05 -0700362 };
Stephen Crane2a3297f2021-06-11 16:48:10 -0700363
Andrew Walbran2f3ff9f2023-07-07 16:58:13 +0100364 // Safety: Our caller promised that `binder` is a non-null, valid
365 // pointer to a local `AIBinder`.
366 let object = unsafe { sys::AIBinder_getUserData(binder) };
367 // Safety: Our caller promised that the binder has a `T` pointer in its
368 // user data.
369 let binder: &T = unsafe { &*(object as *const T) };
Andrei Homescud23c0492023-11-09 01:51:59 +0000370 let res = binder.on_dump(&mut *file, &args);
Stephen Crane2a3297f2021-06-11 16:48:10 -0700371
372 match res {
373 Ok(()) => 0,
374 Err(e) => e as status_t,
375 }
376 }
Stephen Crane2a3c2502020-06-16 17:48:35 -0700377}
378
379impl<T: Remotable> Drop for Binder<T> {
380 // This causes C++ to decrease the strong ref count of the `AIBinder`
381 // object. We specifically do not drop the `rust_object` here. When C++
382 // actually destroys the object, it calls `on_destroy` and we can drop the
383 // `rust_object` then.
384 fn drop(&mut self) {
Andrew Walbran2f3ff9f2023-07-07 16:58:13 +0100385 // Safety: When `self` is dropped, we can no longer access the
386 // reference, so can decrement the reference count. `self.ibinder` is
387 // always a valid `AIBinder` pointer, so is valid to pass to
388 // `AIBinder_decStrong`.
Stephen Crane2a3c2502020-06-16 17:48:35 -0700389 unsafe {
Stephen Crane2a3c2502020-06-16 17:48:35 -0700390 sys::AIBinder_decStrong(self.ibinder);
391 }
392 }
393}
394
395impl<T: Remotable> Deref for Binder<T> {
396 type Target = T;
397
398 fn deref(&self) -> &Self::Target {
Andrew Walbran2f3ff9f2023-07-07 16:58:13 +0100399 // Safety: While `self` is alive, the reference count of the underlying
400 // object is > 0 and therefore `on_destroy` cannot be called. Therefore
401 // while `self` is alive, we know that `rust_object` is still a valid
402 // pointer to a heap allocated object of type `T`.
403 unsafe { &*self.rust_object }
Stephen Crane2a3c2502020-06-16 17:48:35 -0700404 }
405}
406
407impl<B: Remotable> Serialize for Binder<B> {
Alice Ryhl8618c482021-11-09 15:35:35 +0000408 fn serialize(&self, parcel: &mut BorrowedParcel<'_>) -> Result<()> {
Stephen Crane2a3c2502020-06-16 17:48:35 -0700409 parcel.write_binder(Some(&self.as_binder()))
410 }
411}
412
413// This implementation is an idiomatic implementation of the C++
414// `IBinder::localBinder` interface if the binder object is a Rust binder
415// service.
416impl<B: Remotable> TryFrom<SpIBinder> for Binder<B> {
417 type Error = StatusCode;
418
419 fn try_from(mut ibinder: SpIBinder) -> Result<Self> {
420 let class = B::get_class();
421 if Some(class) != ibinder.get_class() {
422 return Err(StatusCode::BAD_TYPE);
423 }
Andrew Walbran2f3ff9f2023-07-07 16:58:13 +0100424 // Safety: `SpIBinder` always holds a valid pointer pointer to an
425 // `AIBinder`, which we can safely pass to `AIBinder_getUserData`.
426 // `ibinder` retains ownership of the returned pointer.
427 let userdata = unsafe { sys::AIBinder_getUserData(ibinder.as_native_mut()) };
Stephen Crane2a3c2502020-06-16 17:48:35 -0700428 if userdata.is_null() {
429 return Err(StatusCode::UNEXPECTED_NULL);
430 }
431 // We are transferring the ownership of the AIBinder into the new Binder
432 // object.
433 let mut ibinder = ManuallyDrop::new(ibinder);
Matthew Maurere268a9f2022-07-26 09:31:30 -0700434 Ok(Binder { ibinder: ibinder.as_native_mut(), rust_object: userdata as *mut B })
Stephen Crane2a3c2502020-06-16 17:48:35 -0700435 }
436}
437
Andrew Walbran2f3ff9f2023-07-07 16:58:13 +0100438/// Safety: The constructor for `Binder` guarantees that `self.ibinder` will
439/// contain a valid, non-null pointer to an `AIBinder`, so this implementation
440/// is type safe. `self.ibinder` will remain valid for the entire lifetime of
441/// `self` because we hold a strong reference to the `AIBinder` until `self` is
Stephen Crane2a3c2502020-06-16 17:48:35 -0700442/// dropped.
443unsafe impl<B: Remotable> AsNative<sys::AIBinder> for Binder<B> {
444 fn as_native(&self) -> *const sys::AIBinder {
445 self.ibinder
446 }
447
448 fn as_native_mut(&mut self) -> *mut sys::AIBinder {
449 self.ibinder
450 }
451}
452
453/// Register a new service with the default service manager.
454///
455/// Registers the given binder object with the given identifier. If successful,
456/// this service can then be retrieved using that identifier.
Alan Stokes1a49e4f2021-09-23 10:30:47 +0100457///
458/// This function will panic if the identifier contains a 0 byte (NUL).
Stephen Crane2a3c2502020-06-16 17:48:35 -0700459pub fn add_service(identifier: &str, mut binder: SpIBinder) -> Result<()> {
460 let instance = CString::new(identifier).unwrap();
Andrew Walbran2f3ff9f2023-07-07 16:58:13 +0100461 let status =
462 // Safety: `AServiceManager_addService` expects valid `AIBinder` and C
463 // string pointers. Caller retains ownership of both pointers.
464 // `AServiceManager_addService` creates a new strong reference and copies
465 // the string, so both pointers need only be valid until the call returns.
466 unsafe { sys::AServiceManager_addService(binder.as_native_mut(), instance.as_ptr()) };
Stephen Crane2a3c2502020-06-16 17:48:35 -0700467 status_result(status)
468}
469
Alan Stokes23fdfcd2021-09-09 11:19:24 +0100470/// Register a dynamic service via the LazyServiceRegistrar.
471///
472/// Registers the given binder object with the given identifier. If successful,
473/// this service can then be retrieved using that identifier. The service process
474/// will be shut down once all registered services are no longer in use.
475///
476/// If any service in the process is registered as lazy, all should be, otherwise
477/// the process may be shut down while a service is in use.
Alan Stokes1a49e4f2021-09-23 10:30:47 +0100478///
479/// This function will panic if the identifier contains a 0 byte (NUL).
Alan Stokes23fdfcd2021-09-09 11:19:24 +0100480pub fn register_lazy_service(identifier: &str, mut binder: SpIBinder) -> Result<()> {
481 let instance = CString::new(identifier).unwrap();
Andrew Walbran2f3ff9f2023-07-07 16:58:13 +0100482 // Safety: `AServiceManager_registerLazyService` expects valid `AIBinder` and C
483 // string pointers. Caller retains ownership of both
484 // pointers. `AServiceManager_registerLazyService` creates a new strong reference
485 // and copies the string, so both pointers need only be valid until the
486 // call returns.
Alan Stokes23fdfcd2021-09-09 11:19:24 +0100487 let status = unsafe {
Alan Stokes23fdfcd2021-09-09 11:19:24 +0100488 sys::AServiceManager_registerLazyService(binder.as_native_mut(), instance.as_ptr())
489 };
490 status_result(status)
491}
492
493/// Prevent a process which registers lazy services from being shut down even when none
494/// of the services is in use.
495///
496/// If persist is true then shut down will be blocked until this function is called again with
497/// persist false. If this is to be the initial state, call this function before calling
498/// register_lazy_service.
Andrew Walbran7b0be1f2022-08-04 16:47:46 +0000499///
500/// Consider using [`LazyServiceGuard`] rather than calling this directly.
Alan Stokes23fdfcd2021-09-09 11:19:24 +0100501pub fn force_lazy_services_persist(persist: bool) {
Andrew Walbran2f3ff9f2023-07-07 16:58:13 +0100502 // Safety: No borrowing or transfer of ownership occurs here.
503 unsafe { sys::AServiceManager_forceLazyServicesPersist(persist) }
Alan Stokes23fdfcd2021-09-09 11:19:24 +0100504}
505
Andrew Walbran7b0be1f2022-08-04 16:47:46 +0000506/// An RAII object to ensure a process which registers lazy services is not killed. During the
507/// lifetime of any of these objects the service manager will not not kill the process even if none
508/// of its lazy services are in use.
509#[must_use]
510#[derive(Debug)]
511pub struct LazyServiceGuard {
512 // Prevent construction outside this module.
513 _private: (),
514}
515
Andrew Walbran3a957462022-08-24 10:55:16 +0000516// Count of how many LazyServiceGuard objects are in existence.
517static GUARD_COUNT: Mutex<u64> = Mutex::new(0);
Andrew Walbran7b0be1f2022-08-04 16:47:46 +0000518
519impl LazyServiceGuard {
520 /// Create a new LazyServiceGuard to prevent the service manager prematurely killing this
521 /// process.
522 pub fn new() -> Self {
523 let mut count = GUARD_COUNT.lock().unwrap();
524 *count += 1;
525 if *count == 1 {
526 // It's important that we make this call with the mutex held, to make sure
527 // that multiple calls (e.g. if the count goes 1 -> 0 -> 1) are correctly
528 // sequenced. (That also means we can't just use an AtomicU64.)
529 force_lazy_services_persist(true);
530 }
531 Self { _private: () }
532 }
533}
534
535impl Drop for LazyServiceGuard {
536 fn drop(&mut self) {
537 let mut count = GUARD_COUNT.lock().unwrap();
538 *count -= 1;
539 if *count == 0 {
540 force_lazy_services_persist(false);
541 }
542 }
543}
544
545impl Clone for LazyServiceGuard {
546 fn clone(&self) -> Self {
547 Self::new()
548 }
549}
550
551impl Default for LazyServiceGuard {
552 fn default() -> Self {
553 Self::new()
554 }
555}
556
Stephen Crane2a3c2502020-06-16 17:48:35 -0700557/// Tests often create a base BBinder instance; so allowing the unit
558/// type to be remotable translates nicely to Binder::new(()).
559impl Remotable for () {
560 fn get_descriptor() -> &'static str {
561 ""
562 }
563
564 fn on_transact(
565 &self,
566 _code: TransactionCode,
Alice Ryhl8618c482021-11-09 15:35:35 +0000567 _data: &BorrowedParcel<'_>,
568 _reply: &mut BorrowedParcel<'_>,
Stephen Crane2a3c2502020-06-16 17:48:35 -0700569 ) -> Result<()> {
570 Ok(())
571 }
572
Andrei Homescud23c0492023-11-09 01:51:59 +0000573 fn on_dump(&self, _writer: &mut dyn Write, _args: &[&CStr]) -> Result<()> {
Stephen Crane2a3297f2021-06-11 16:48:10 -0700574 Ok(())
575 }
576
Stephen Crane2a3c2502020-06-16 17:48:35 -0700577 binder_fn_get_class!(Binder::<Self>);
578}
579
580impl Interface for () {}
Alice Ryhlad9c77b2021-11-16 09:49:29 +0000581
582/// Determine whether the current thread is currently executing an incoming
583/// transaction.
584pub fn is_handling_transaction() -> bool {
Andrew Walbran2f3ff9f2023-07-07 16:58:13 +0100585 // Safety: This method is always safe to call.
586 unsafe { sys::AIBinder_isHandlingTransaction() }
Alice Ryhlad9c77b2021-11-16 09:49:29 +0000587}