Stephen Crane | 2a3c250 | 2020-06-16 17:48:35 -0700 | [diff] [blame] | 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 | |
Alan Stokes | 23fdfcd | 2021-09-09 11:19:24 +0100 | [diff] [blame] | 17 | use crate::binder::{ |
| 18 | AsNative, Interface, InterfaceClassMethods, Remotable, Stability, TransactionCode, |
| 19 | }; |
Stephen Crane | 2a3c250 | 2020-06-16 17:48:35 -0700 | [diff] [blame] | 20 | use crate::error::{status_result, status_t, Result, StatusCode}; |
Alice Ryhl | 8618c48 | 2021-11-09 15:35:35 +0000 | [diff] [blame] | 21 | use crate::parcel::{BorrowedParcel, Serialize}; |
Stephen Crane | 2a3c250 | 2020-06-16 17:48:35 -0700 | [diff] [blame] | 22 | use crate::proxy::SpIBinder; |
| 23 | use crate::sys; |
| 24 | |
| 25 | use std::convert::TryFrom; |
Stephen Crane | 2a3297f | 2021-06-11 16:48:10 -0700 | [diff] [blame] | 26 | use std::ffi::{c_void, CStr, CString}; |
| 27 | use std::fs::File; |
Stephen Crane | 2a3c250 | 2020-06-16 17:48:35 -0700 | [diff] [blame] | 28 | use std::mem::ManuallyDrop; |
| 29 | use std::ops::Deref; |
Stephen Crane | 2a3297f | 2021-06-11 16:48:10 -0700 | [diff] [blame] | 30 | use std::os::raw::c_char; |
| 31 | use std::os::unix::io::FromRawFd; |
| 32 | use std::slice; |
Stephen Crane | 2a3c250 | 2020-06-16 17:48:35 -0700 | [diff] [blame] | 33 | |
| 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)] |
| 39 | pub struct Binder<T: Remotable> { |
| 40 | ibinder: *mut sys::AIBinder, |
| 41 | rust_object: *mut T, |
| 42 | } |
| 43 | |
Andrei Homescu | 2c674b0 | 2020-08-07 22:12:27 -0700 | [diff] [blame] | 44 | /// # 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`. |
| 54 | unsafe impl<T: Remotable> Send for Binder<T> {} |
| 55 | |
Stephen Crane | f03fe3d | 2021-06-25 15:05:00 -0700 | [diff] [blame] | 56 | /// # 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`. |
| 73 | unsafe impl<T: Remotable> Sync for Binder<T> {} |
| 74 | |
Stephen Crane | 2a3c250 | 2020-06-16 17:48:35 -0700 | [diff] [blame] | 75 | impl<T: Remotable> Binder<T> { |
Stephen Crane | ff7f03a | 2021-02-25 16:04:22 -0800 | [diff] [blame] | 76 | /// Create a new Binder remotable object with default stability |
Stephen Crane | 2a3c250 | 2020-06-16 17:48:35 -0700 | [diff] [blame] | 77 | /// |
| 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 Crane | ff7f03a | 2021-02-25 16:04:22 -0800 | [diff] [blame] | 81 | 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 Crane | 2a3c250 | 2020-06-16 17:48:35 -0700 | [diff] [blame] | 89 | 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 Maurer | e268a9f | 2022-07-26 09:31:30 -0700 | [diff] [blame^] | 100 | let mut binder = Binder { ibinder, rust_object }; |
Stephen Crane | ff7f03a | 2021-02-25 16:04:22 -0800 | [diff] [blame] | 101 | binder.mark_stability(stability); |
| 102 | binder |
Stephen Crane | 2a3c250 | 2020-06-16 17:48:35 -0700 | [diff] [blame] | 103 | } |
| 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 Ryhl | 8618c48 | 2021-11-09 15:35:35 +0000 | [diff] [blame] | 161 | /// # data: &BorrowedParcel, |
| 162 | /// # reply: &mut BorrowedParcel, |
Stephen Crane | 2a3c250 | 2020-06-16 17:48:35 -0700 | [diff] [blame] | 163 | /// # ) -> 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 Crane | ff7f03a | 2021-02-25 16:04:22 -0800 | [diff] [blame] | 195 | |
| 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 Danisevskis | 1323d51 | 2021-11-09 07:48:08 -0800 | [diff] [blame] | 212 | #[cfg(any(vendor_ndk, android_vndk))] |
Stephen Crane | ff7f03a | 2021-02-25 16:04:22 -0800 | [diff] [blame] | 213 | 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 Danisevskis | 1323d51 | 2021-11-09 07:48:08 -0800 | [diff] [blame] | 223 | #[cfg(not(any(vendor_ndk, android_vndk)))] |
Stephen Crane | ff7f03a | 2021-02-25 16:04:22 -0800 | [diff] [blame] | 224 | 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 Crane | 2a3c250 | 2020-06-16 17:48:35 -0700 | [diff] [blame] | 231 | } |
| 232 | |
| 233 | impl<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 | |
| 254 | impl<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 Ryhl | 8618c48 | 2021-11-09 15:35:35 +0000 | [diff] [blame] | 277 | let mut reply = BorrowedParcel::from_raw(reply).unwrap(); |
| 278 | let data = BorrowedParcel::from_raw(data as *mut sys::AParcel).unwrap(); |
Stephen Crane | 2a3c250 | 2020-06-16 17:48:35 -0700 | [diff] [blame] | 279 | 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 Maurer | c050d8f | 2021-06-11 16:49:48 -0700 | [diff] [blame] | 297 | Box::from_raw(object as *mut T); |
Stephen Crane | 2a3c250 | 2020-06-16 17:48:35 -0700 | [diff] [blame] | 298 | } |
| 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 Crane | 2a3297f | 2021-06-11 16:48:10 -0700 | [diff] [blame] | 314 | |
| 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 Stokes | 23fdfcd | 2021-09-09 11:19:24 +0100 | [diff] [blame] | 323 | 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 Crane | 2a3297f | 2021-06-11 16:48:10 -0700 | [diff] [blame] | 329 | 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 Crane | 0c5f923 | 2022-06-17 11:48:05 -0700 | [diff] [blame] | 335 | if args.is_null() && num_args != 0 { |
Stephen Crane | 2a3297f | 2021-06-11 16:48:10 -0700 | [diff] [blame] | 336 | return StatusCode::UNEXPECTED_NULL as status_t; |
| 337 | } |
Stephen Crane | 0c5f923 | 2022-06-17 11:48:05 -0700 | [diff] [blame] | 338 | |
| 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 Maurer | e268a9f | 2022-07-26 09:31:30 -0700 | [diff] [blame^] | 343 | .iter() |
| 344 | .map(|s| CStr::from_ptr(*s)) |
| 345 | .collect() |
Stephen Crane | 0c5f923 | 2022-06-17 11:48:05 -0700 | [diff] [blame] | 346 | }; |
Stephen Crane | 2a3297f | 2021-06-11 16:48:10 -0700 | [diff] [blame] | 347 | |
| 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 Crane | 2a3c250 | 2020-06-16 17:48:35 -0700 | [diff] [blame] | 357 | } |
| 358 | |
| 359 | impl<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 | |
| 375 | impl<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 | |
| 390 | impl<B: Remotable> Serialize for Binder<B> { |
Alice Ryhl | 8618c48 | 2021-11-09 15:35:35 +0000 | [diff] [blame] | 391 | fn serialize(&self, parcel: &mut BorrowedParcel<'_>) -> Result<()> { |
Stephen Crane | 2a3c250 | 2020-06-16 17:48:35 -0700 | [diff] [blame] | 392 | 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. |
| 399 | impl<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 Maurer | e268a9f | 2022-07-26 09:31:30 -0700 | [diff] [blame^] | 420 | Ok(Binder { ibinder: ibinder.as_native_mut(), rust_object: userdata as *mut B }) |
Stephen Crane | 2a3c250 | 2020-06-16 17:48:35 -0700 | [diff] [blame] | 421 | } |
| 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. |
| 431 | unsafe 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 Stokes | 1a49e4f | 2021-09-23 10:30:47 +0100 | [diff] [blame] | 445 | /// |
| 446 | /// This function will panic if the identifier contains a 0 byte (NUL). |
Stephen Crane | 2a3c250 | 2020-06-16 17:48:35 -0700 | [diff] [blame] | 447 | pub 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 Stokes | 23fdfcd | 2021-09-09 11:19:24 +0100 | [diff] [blame] | 460 | /// 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 Stokes | 1a49e4f | 2021-09-23 10:30:47 +0100 | [diff] [blame] | 468 | /// |
| 469 | /// This function will panic if the identifier contains a 0 byte (NUL). |
Alan Stokes | 23fdfcd | 2021-09-09 11:19:24 +0100 | [diff] [blame] | 470 | pub 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. |
| 490 | pub 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 Crane | 2a3c250 | 2020-06-16 17:48:35 -0700 | [diff] [blame] | 497 | /// Tests often create a base BBinder instance; so allowing the unit |
| 498 | /// type to be remotable translates nicely to Binder::new(()). |
| 499 | impl Remotable for () { |
| 500 | fn get_descriptor() -> &'static str { |
| 501 | "" |
| 502 | } |
| 503 | |
| 504 | fn on_transact( |
| 505 | &self, |
| 506 | _code: TransactionCode, |
Alice Ryhl | 8618c48 | 2021-11-09 15:35:35 +0000 | [diff] [blame] | 507 | _data: &BorrowedParcel<'_>, |
| 508 | _reply: &mut BorrowedParcel<'_>, |
Stephen Crane | 2a3c250 | 2020-06-16 17:48:35 -0700 | [diff] [blame] | 509 | ) -> Result<()> { |
| 510 | Ok(()) |
| 511 | } |
| 512 | |
Stephen Crane | 2a3297f | 2021-06-11 16:48:10 -0700 | [diff] [blame] | 513 | fn on_dump(&self, _file: &File, _args: &[&CStr]) -> Result<()> { |
| 514 | Ok(()) |
| 515 | } |
| 516 | |
Stephen Crane | 2a3c250 | 2020-06-16 17:48:35 -0700 | [diff] [blame] | 517 | binder_fn_get_class!(Binder::<Self>); |
| 518 | } |
| 519 | |
| 520 | impl Interface for () {} |
Alice Ryhl | ad9c77b | 2021-11-16 09:49:29 +0000 | [diff] [blame] | 521 | |
| 522 | /// Determine whether the current thread is currently executing an incoming |
| 523 | /// transaction. |
| 524 | pub fn is_handling_transaction() -> bool { |
| 525 | unsafe { |
| 526 | // Safety: This method is always safe to call. |
| 527 | sys::AIBinder_isHandlingTransaction() |
| 528 | } |
| 529 | } |