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 | |
| 17 | //! Rust API for interacting with a remote binder service. |
| 18 | |
| 19 | use crate::binder::{ |
Andrew Walbran | 12400d8 | 2021-03-04 17:04:34 +0000 | [diff] [blame] | 20 | AsNative, FromIBinder, IBinder, IBinderInternal, Interface, InterfaceClass, Strong, |
| 21 | TransactionCode, TransactionFlags, |
Stephen Crane | 2a3c250 | 2020-06-16 17:48:35 -0700 | [diff] [blame] | 22 | }; |
| 23 | use crate::error::{status_result, Result, StatusCode}; |
| 24 | use crate::parcel::{ |
Matthew Maurer | e268a9f | 2022-07-26 09:31:30 -0700 | [diff] [blame^] | 25 | BorrowedParcel, Deserialize, DeserializeArray, DeserializeOption, Parcel, Serialize, |
| 26 | SerializeArray, SerializeOption, |
Stephen Crane | 2a3c250 | 2020-06-16 17:48:35 -0700 | [diff] [blame] | 27 | }; |
| 28 | use crate::sys; |
| 29 | |
Stephen Crane | ddb3e6d | 2020-12-18 13:27:22 -0800 | [diff] [blame] | 30 | use std::cmp::Ordering; |
Andrew Walbran | 12400d8 | 2021-03-04 17:04:34 +0000 | [diff] [blame] | 31 | use std::convert::TryInto; |
Stephen Crane | 098bbc9 | 2022-02-14 13:31:53 -0800 | [diff] [blame] | 32 | use std::ffi::{c_void, CStr, CString}; |
Andrei Homescu | 2e3c147 | 2020-08-11 16:35:40 -0700 | [diff] [blame] | 33 | use std::fmt; |
Alice Ryhl | ea9d9d2 | 2021-08-27 07:51:30 +0000 | [diff] [blame] | 34 | use std::mem; |
Stephen Crane | 098bbc9 | 2022-02-14 13:31:53 -0800 | [diff] [blame] | 35 | use std::os::raw::c_char; |
Stephen Crane | 2a3c250 | 2020-06-16 17:48:35 -0700 | [diff] [blame] | 36 | use std::os::unix::io::AsRawFd; |
| 37 | use std::ptr; |
Alice Ryhl | ea9d9d2 | 2021-08-27 07:51:30 +0000 | [diff] [blame] | 38 | use std::sync::Arc; |
Stephen Crane | 2a3c250 | 2020-06-16 17:48:35 -0700 | [diff] [blame] | 39 | |
| 40 | /// A strong reference to a Binder remote object. |
| 41 | /// |
| 42 | /// This struct encapsulates the generic C++ `sp<IBinder>` class. This wrapper |
| 43 | /// is untyped; typed interface access is implemented by the AIDL compiler. |
Alice Ryhl | 8dde9bc | 2021-08-16 16:57:10 +0000 | [diff] [blame] | 44 | pub struct SpIBinder(ptr::NonNull<sys::AIBinder>); |
Stephen Crane | 2a3c250 | 2020-06-16 17:48:35 -0700 | [diff] [blame] | 45 | |
Andrei Homescu | 2e3c147 | 2020-08-11 16:35:40 -0700 | [diff] [blame] | 46 | impl fmt::Debug for SpIBinder { |
| 47 | fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { |
| 48 | f.pad("SpIBinder") |
| 49 | } |
| 50 | } |
| 51 | |
Stephen Crane | 2a3c250 | 2020-06-16 17:48:35 -0700 | [diff] [blame] | 52 | /// # Safety |
| 53 | /// |
Stephen Crane | f03fe3d | 2021-06-25 15:05:00 -0700 | [diff] [blame] | 54 | /// An `SpIBinder` is an immutable handle to a C++ IBinder, which is thread-safe |
Stephen Crane | 2a3c250 | 2020-06-16 17:48:35 -0700 | [diff] [blame] | 55 | unsafe impl Send for SpIBinder {} |
| 56 | |
Stephen Crane | f03fe3d | 2021-06-25 15:05:00 -0700 | [diff] [blame] | 57 | /// # Safety |
| 58 | /// |
| 59 | /// An `SpIBinder` is an immutable handle to a C++ IBinder, which is thread-safe |
| 60 | unsafe impl Sync for SpIBinder {} |
| 61 | |
Stephen Crane | 2a3c250 | 2020-06-16 17:48:35 -0700 | [diff] [blame] | 62 | impl SpIBinder { |
| 63 | /// Create an `SpIBinder` wrapper object from a raw `AIBinder` pointer. |
| 64 | /// |
| 65 | /// # Safety |
| 66 | /// |
| 67 | /// This constructor is safe iff `ptr` is a null pointer or a valid pointer |
| 68 | /// to an `AIBinder`. |
| 69 | /// |
| 70 | /// In the non-null case, this method conceptually takes ownership of a strong |
| 71 | /// reference to the object, so `AIBinder_incStrong` must have been called |
| 72 | /// on the pointer before passing it to this constructor. This is generally |
| 73 | /// done by Binder NDK methods that return an `AIBinder`, but care should be |
| 74 | /// taken to ensure this invariant. |
| 75 | /// |
| 76 | /// All `SpIBinder` objects that are constructed will hold a valid pointer |
| 77 | /// to an `AIBinder`, which will remain valid for the entire lifetime of the |
| 78 | /// `SpIBinder` (we keep a strong reference, and only decrement on drop). |
| 79 | pub(crate) unsafe fn from_raw(ptr: *mut sys::AIBinder) -> Option<Self> { |
Alice Ryhl | 8dde9bc | 2021-08-16 16:57:10 +0000 | [diff] [blame] | 80 | ptr::NonNull::new(ptr).map(Self) |
Stephen Crane | 2a3c250 | 2020-06-16 17:48:35 -0700 | [diff] [blame] | 81 | } |
| 82 | |
Stephen Crane | d58bce0 | 2020-07-07 12:26:02 -0700 | [diff] [blame] | 83 | /// Extract a raw `AIBinder` pointer from this wrapper. |
| 84 | /// |
| 85 | /// This method should _only_ be used for testing. Do not try to use the NDK |
| 86 | /// interface directly for anything else. |
| 87 | /// |
| 88 | /// # Safety |
| 89 | /// |
| 90 | /// The resulting pointer is valid only as long as the SpIBinder is alive. |
| 91 | /// The SpIBinder object retains ownership of the AIBinder and the caller |
| 92 | /// should not attempt to free the returned pointer. |
| 93 | pub unsafe fn as_raw(&self) -> *mut sys::AIBinder { |
Alice Ryhl | 8dde9bc | 2021-08-16 16:57:10 +0000 | [diff] [blame] | 94 | self.0.as_ptr() |
Stephen Crane | d58bce0 | 2020-07-07 12:26:02 -0700 | [diff] [blame] | 95 | } |
| 96 | |
Stephen Crane | 2a3c250 | 2020-06-16 17:48:35 -0700 | [diff] [blame] | 97 | /// Return true if this binder object is hosted in a different process than |
| 98 | /// the current one. |
| 99 | pub fn is_remote(&self) -> bool { |
| 100 | unsafe { |
| 101 | // Safety: `SpIBinder` guarantees that it always contains a valid |
| 102 | // `AIBinder` pointer. |
| 103 | sys::AIBinder_isRemote(self.as_native()) |
| 104 | } |
| 105 | } |
| 106 | |
| 107 | /// Try to convert this Binder object into a trait object for the given |
| 108 | /// Binder interface. |
| 109 | /// |
| 110 | /// If this object does not implement the expected interface, the error |
| 111 | /// `StatusCode::BAD_TYPE` is returned. |
Stephen Crane | ddb3e6d | 2020-12-18 13:27:22 -0800 | [diff] [blame] | 112 | pub fn into_interface<I: FromIBinder + Interface + ?Sized>(self) -> Result<Strong<I>> { |
Stephen Crane | 2a3c250 | 2020-06-16 17:48:35 -0700 | [diff] [blame] | 113 | FromIBinder::try_from(self) |
| 114 | } |
| 115 | |
| 116 | /// Return the interface class of this binder object, if associated with |
| 117 | /// one. |
Stephen Crane | 669deb6 | 2020-09-10 17:31:39 -0700 | [diff] [blame] | 118 | pub fn get_class(&mut self) -> Option<InterfaceClass> { |
Stephen Crane | 2a3c250 | 2020-06-16 17:48:35 -0700 | [diff] [blame] | 119 | unsafe { |
| 120 | // Safety: `SpIBinder` guarantees that it always contains a valid |
| 121 | // `AIBinder` pointer. `AIBinder_getClass` returns either a null |
| 122 | // pointer or a valid pointer to an `AIBinder_Class`. After mapping |
| 123 | // null to None, we can safely construct an `InterfaceClass` if the |
| 124 | // pointer was non-null. |
| 125 | let class = sys::AIBinder_getClass(self.as_native_mut()); |
| 126 | class.as_ref().map(|p| InterfaceClass::from_ptr(p)) |
| 127 | } |
| 128 | } |
Andrew Walbran | 8fe3ecc | 2020-12-15 11:29:58 +0000 | [diff] [blame] | 129 | |
| 130 | /// Creates a new weak reference to this binder object. |
| 131 | pub fn downgrade(&mut self) -> WpIBinder { |
| 132 | WpIBinder::new(self) |
| 133 | } |
Stephen Crane | 2a3c250 | 2020-06-16 17:48:35 -0700 | [diff] [blame] | 134 | } |
| 135 | |
Victor Hsieh | d35d31d | 2021-06-03 11:24:31 -0700 | [diff] [blame] | 136 | pub mod unstable_api { |
| 137 | use super::{sys, SpIBinder}; |
| 138 | |
| 139 | /// A temporary API to allow the client to create a `SpIBinder` from a `sys::AIBinder`. This is |
| 140 | /// needed to bridge RPC binder, which doesn't have Rust API yet. |
| 141 | /// TODO(b/184872979): remove once the Rust API is created. |
| 142 | /// |
| 143 | /// # Safety |
| 144 | /// |
| 145 | /// See `SpIBinder::from_raw`. |
| 146 | pub unsafe fn new_spibinder(ptr: *mut sys::AIBinder) -> Option<SpIBinder> { |
| 147 | SpIBinder::from_raw(ptr) |
| 148 | } |
| 149 | } |
| 150 | |
Stephen Crane | 2a3c250 | 2020-06-16 17:48:35 -0700 | [diff] [blame] | 151 | /// An object that can be associate with an [`InterfaceClass`]. |
| 152 | pub trait AssociateClass { |
| 153 | /// Check if this object is a valid object for the given interface class |
| 154 | /// `I`. |
| 155 | /// |
| 156 | /// Returns `Some(self)` if this is a valid instance of the interface, and |
| 157 | /// `None` otherwise. |
| 158 | /// |
| 159 | /// Classes constructed by `InterfaceClass` are unique per type, so |
| 160 | /// repeatedly calling this method for the same `InterfaceClass` is allowed. |
| 161 | fn associate_class(&mut self, class: InterfaceClass) -> bool; |
| 162 | } |
| 163 | |
| 164 | impl AssociateClass for SpIBinder { |
| 165 | fn associate_class(&mut self, class: InterfaceClass) -> bool { |
| 166 | unsafe { |
| 167 | // Safety: `SpIBinder` guarantees that it always contains a valid |
| 168 | // `AIBinder` pointer. An `InterfaceClass` can always be converted |
| 169 | // into a valid `AIBinder_Class` pointer, so these parameters are |
| 170 | // always safe. |
| 171 | sys::AIBinder_associateClass(self.as_native_mut(), class.into()) |
| 172 | } |
| 173 | } |
| 174 | } |
| 175 | |
Stephen Crane | ddb3e6d | 2020-12-18 13:27:22 -0800 | [diff] [blame] | 176 | impl Ord for SpIBinder { |
| 177 | fn cmp(&self, other: &Self) -> Ordering { |
| 178 | let less_than = unsafe { |
| 179 | // Safety: SpIBinder always holds a valid `AIBinder` pointer, so |
| 180 | // this pointer is always safe to pass to `AIBinder_lt` (null is |
| 181 | // also safe to pass to this function, but we should never do that). |
Alice Ryhl | 8dde9bc | 2021-08-16 16:57:10 +0000 | [diff] [blame] | 182 | sys::AIBinder_lt(self.0.as_ptr(), other.0.as_ptr()) |
Stephen Crane | ddb3e6d | 2020-12-18 13:27:22 -0800 | [diff] [blame] | 183 | }; |
| 184 | let greater_than = unsafe { |
| 185 | // Safety: SpIBinder always holds a valid `AIBinder` pointer, so |
| 186 | // this pointer is always safe to pass to `AIBinder_lt` (null is |
| 187 | // also safe to pass to this function, but we should never do that). |
Alice Ryhl | 8dde9bc | 2021-08-16 16:57:10 +0000 | [diff] [blame] | 188 | sys::AIBinder_lt(other.0.as_ptr(), self.0.as_ptr()) |
Stephen Crane | ddb3e6d | 2020-12-18 13:27:22 -0800 | [diff] [blame] | 189 | }; |
| 190 | if !less_than && !greater_than { |
| 191 | Ordering::Equal |
| 192 | } else if less_than { |
| 193 | Ordering::Less |
| 194 | } else { |
| 195 | Ordering::Greater |
| 196 | } |
| 197 | } |
| 198 | } |
| 199 | |
| 200 | impl PartialOrd for SpIBinder { |
| 201 | fn partial_cmp(&self, other: &Self) -> Option<Ordering> { |
| 202 | Some(self.cmp(other)) |
| 203 | } |
| 204 | } |
| 205 | |
Stephen Crane | 994a0f0 | 2020-08-11 14:47:29 -0700 | [diff] [blame] | 206 | impl PartialEq for SpIBinder { |
| 207 | fn eq(&self, other: &Self) -> bool { |
Alice Ryhl | 8dde9bc | 2021-08-16 16:57:10 +0000 | [diff] [blame] | 208 | ptr::eq(self.0.as_ptr(), other.0.as_ptr()) |
Stephen Crane | 994a0f0 | 2020-08-11 14:47:29 -0700 | [diff] [blame] | 209 | } |
| 210 | } |
| 211 | |
| 212 | impl Eq for SpIBinder {} |
| 213 | |
Stephen Crane | 2a3c250 | 2020-06-16 17:48:35 -0700 | [diff] [blame] | 214 | impl Clone for SpIBinder { |
| 215 | fn clone(&self) -> Self { |
| 216 | unsafe { |
| 217 | // Safety: Cloning a strong reference must increment the reference |
| 218 | // count. We are guaranteed by the `SpIBinder` constructor |
| 219 | // invariants that `self.0` is always a valid `AIBinder` pointer. |
Alice Ryhl | 8dde9bc | 2021-08-16 16:57:10 +0000 | [diff] [blame] | 220 | sys::AIBinder_incStrong(self.0.as_ptr()); |
Stephen Crane | 2a3c250 | 2020-06-16 17:48:35 -0700 | [diff] [blame] | 221 | } |
| 222 | Self(self.0) |
| 223 | } |
| 224 | } |
| 225 | |
| 226 | impl Drop for SpIBinder { |
| 227 | // We hold a strong reference to the IBinder in SpIBinder and need to give up |
| 228 | // this reference on drop. |
| 229 | fn drop(&mut self) { |
| 230 | unsafe { |
| 231 | // Safety: SpIBinder always holds a valid `AIBinder` pointer, so we |
| 232 | // know this pointer is safe to pass to `AIBinder_decStrong` here. |
| 233 | sys::AIBinder_decStrong(self.as_native_mut()); |
| 234 | } |
| 235 | } |
| 236 | } |
| 237 | |
Andrew Walbran | 12400d8 | 2021-03-04 17:04:34 +0000 | [diff] [blame] | 238 | impl<T: AsNative<sys::AIBinder>> IBinderInternal for T { |
Alice Ryhl | 8618c48 | 2021-11-09 15:35:35 +0000 | [diff] [blame] | 239 | fn prepare_transact(&self) -> Result<Parcel> { |
Stephen Crane | 2a3c250 | 2020-06-16 17:48:35 -0700 | [diff] [blame] | 240 | let mut input = ptr::null_mut(); |
| 241 | let status = unsafe { |
| 242 | // Safety: `SpIBinder` guarantees that `self` always contains a |
| 243 | // valid pointer to an `AIBinder`. It is safe to cast from an |
| 244 | // immutable pointer to a mutable pointer here, because |
| 245 | // `AIBinder_prepareTransaction` only calls immutable `AIBinder` |
| 246 | // methods but the parameter is unfortunately not marked as const. |
| 247 | // |
| 248 | // After the call, input will be either a valid, owned `AParcel` |
| 249 | // pointer, or null. |
| 250 | sys::AIBinder_prepareTransaction(self.as_native() as *mut sys::AIBinder, &mut input) |
| 251 | }; |
Alice Ryhl | feba6ca | 2021-08-19 10:47:04 +0000 | [diff] [blame] | 252 | |
Stephen Crane | 2a3c250 | 2020-06-16 17:48:35 -0700 | [diff] [blame] | 253 | status_result(status)?; |
Alice Ryhl | feba6ca | 2021-08-19 10:47:04 +0000 | [diff] [blame] | 254 | |
| 255 | unsafe { |
Stephen Crane | 2a3c250 | 2020-06-16 17:48:35 -0700 | [diff] [blame] | 256 | // Safety: At this point, `input` is either a valid, owned `AParcel` |
Alice Ryhl | 268458c | 2021-09-15 12:56:10 +0000 | [diff] [blame] | 257 | // pointer, or null. `OwnedParcel::from_raw` safely handles both cases, |
Stephen Crane | 2a3c250 | 2020-06-16 17:48:35 -0700 | [diff] [blame] | 258 | // taking ownership of the parcel. |
Alice Ryhl | 8618c48 | 2021-11-09 15:35:35 +0000 | [diff] [blame] | 259 | Parcel::from_raw(input).ok_or(StatusCode::UNEXPECTED_NULL) |
Alice Ryhl | feba6ca | 2021-08-19 10:47:04 +0000 | [diff] [blame] | 260 | } |
| 261 | } |
| 262 | |
| 263 | fn submit_transact( |
| 264 | &self, |
| 265 | code: TransactionCode, |
Alice Ryhl | 8618c48 | 2021-11-09 15:35:35 +0000 | [diff] [blame] | 266 | data: Parcel, |
Alice Ryhl | feba6ca | 2021-08-19 10:47:04 +0000 | [diff] [blame] | 267 | flags: TransactionFlags, |
Alice Ryhl | 8618c48 | 2021-11-09 15:35:35 +0000 | [diff] [blame] | 268 | ) -> Result<Parcel> { |
Stephen Crane | 2a3c250 | 2020-06-16 17:48:35 -0700 | [diff] [blame] | 269 | let mut reply = ptr::null_mut(); |
| 270 | let status = unsafe { |
| 271 | // Safety: `SpIBinder` guarantees that `self` always contains a |
| 272 | // valid pointer to an `AIBinder`. Although `IBinder::transact` is |
| 273 | // not a const method, it is still safe to cast our immutable |
| 274 | // pointer to mutable for the call. First, `IBinder::transact` is |
| 275 | // thread-safe, so concurrency is not an issue. The only way that |
| 276 | // `transact` can affect any visible, mutable state in the current |
| 277 | // process is by calling `onTransact` for a local service. However, |
| 278 | // in order for transactions to be thread-safe, this method must |
| 279 | // dynamically lock its data before modifying it. We enforce this |
| 280 | // property in Rust by requiring `Sync` for remotable objects and |
| 281 | // only providing `on_transact` with an immutable reference to |
| 282 | // `self`. |
| 283 | // |
Alice Ryhl | feba6ca | 2021-08-19 10:47:04 +0000 | [diff] [blame] | 284 | // This call takes ownership of the `data` parcel pointer, and |
Stephen Crane | 2a3c250 | 2020-06-16 17:48:35 -0700 | [diff] [blame] | 285 | // passes ownership of the `reply` out parameter to its caller. It |
| 286 | // does not affect ownership of the `binder` parameter. |
| 287 | sys::AIBinder_transact( |
| 288 | self.as_native() as *mut sys::AIBinder, |
| 289 | code, |
Alice Ryhl | feba6ca | 2021-08-19 10:47:04 +0000 | [diff] [blame] | 290 | &mut data.into_raw(), |
Stephen Crane | 2a3c250 | 2020-06-16 17:48:35 -0700 | [diff] [blame] | 291 | &mut reply, |
| 292 | flags, |
| 293 | ) |
| 294 | }; |
| 295 | status_result(status)?; |
| 296 | |
| 297 | unsafe { |
| 298 | // Safety: `reply` is either a valid `AParcel` pointer or null |
| 299 | // after the call to `AIBinder_transact` above, so we can |
| 300 | // construct a `Parcel` out of it. `AIBinder_transact` passes |
| 301 | // ownership of the `reply` parcel to Rust, so we need to |
Alice Ryhl | 268458c | 2021-09-15 12:56:10 +0000 | [diff] [blame] | 302 | // construct an owned variant. |
Alice Ryhl | 8618c48 | 2021-11-09 15:35:35 +0000 | [diff] [blame] | 303 | Parcel::from_raw(reply).ok_or(StatusCode::UNEXPECTED_NULL) |
Stephen Crane | 2a3c250 | 2020-06-16 17:48:35 -0700 | [diff] [blame] | 304 | } |
| 305 | } |
| 306 | |
| 307 | fn is_binder_alive(&self) -> bool { |
| 308 | unsafe { |
| 309 | // Safety: `SpIBinder` guarantees that `self` always contains a |
| 310 | // valid pointer to an `AIBinder`. |
| 311 | // |
| 312 | // This call does not affect ownership of its pointer parameter. |
| 313 | sys::AIBinder_isAlive(self.as_native()) |
| 314 | } |
| 315 | } |
| 316 | |
Janis Danisevskis | 1323d51 | 2021-11-09 07:48:08 -0800 | [diff] [blame] | 317 | #[cfg(not(android_vndk))] |
Janis Danisevskis | 798a09a | 2020-08-18 08:35:38 -0700 | [diff] [blame] | 318 | fn set_requesting_sid(&mut self, enable: bool) { |
Andrew Walbran | 12400d8 | 2021-03-04 17:04:34 +0000 | [diff] [blame] | 319 | unsafe { sys::AIBinder_setRequestingSid(self.as_native_mut(), enable) }; |
Janis Danisevskis | 798a09a | 2020-08-18 08:35:38 -0700 | [diff] [blame] | 320 | } |
| 321 | |
Stephen Crane | 2a3c250 | 2020-06-16 17:48:35 -0700 | [diff] [blame] | 322 | fn dump<F: AsRawFd>(&mut self, fp: &F, args: &[&str]) -> Result<()> { |
| 323 | let args: Vec<_> = args.iter().map(|a| CString::new(*a).unwrap()).collect(); |
| 324 | let mut arg_ptrs: Vec<_> = args.iter().map(|a| a.as_ptr()).collect(); |
| 325 | let status = unsafe { |
| 326 | // Safety: `SpIBinder` guarantees that `self` always contains a |
| 327 | // valid pointer to an `AIBinder`. `AsRawFd` guarantees that the |
| 328 | // file descriptor parameter is always be a valid open file. The |
| 329 | // `args` pointer parameter is a valid pointer to an array of C |
| 330 | // strings that will outlive the call since `args` lives for the |
| 331 | // whole function scope. |
| 332 | // |
| 333 | // This call does not affect ownership of its binder pointer |
| 334 | // parameter and does not take ownership of the file or args array |
| 335 | // parameters. |
| 336 | sys::AIBinder_dump( |
| 337 | self.as_native_mut(), |
| 338 | fp.as_raw_fd(), |
| 339 | arg_ptrs.as_mut_ptr(), |
| 340 | arg_ptrs.len().try_into().unwrap(), |
| 341 | ) |
| 342 | }; |
| 343 | status_result(status) |
| 344 | } |
| 345 | |
| 346 | fn get_extension(&mut self) -> Result<Option<SpIBinder>> { |
| 347 | let mut out = ptr::null_mut(); |
| 348 | let status = unsafe { |
| 349 | // Safety: `SpIBinder` guarantees that `self` always contains a |
| 350 | // valid pointer to an `AIBinder`. After this call, the `out` |
| 351 | // parameter will be either null, or a valid pointer to an |
| 352 | // `AIBinder`. |
| 353 | // |
| 354 | // This call passes ownership of the out pointer to its caller |
| 355 | // (assuming it is set to a non-null value). |
| 356 | sys::AIBinder_getExtension(self.as_native_mut(), &mut out) |
| 357 | }; |
| 358 | let ibinder = unsafe { |
| 359 | // Safety: The call above guarantees that `out` is either null or a |
| 360 | // valid, owned pointer to an `AIBinder`, both of which are safe to |
| 361 | // pass to `SpIBinder::from_raw`. |
| 362 | SpIBinder::from_raw(out) |
| 363 | }; |
| 364 | |
| 365 | status_result(status)?; |
| 366 | Ok(ibinder) |
| 367 | } |
Andrew Walbran | 12400d8 | 2021-03-04 17:04:34 +0000 | [diff] [blame] | 368 | } |
Stephen Crane | 2a3c250 | 2020-06-16 17:48:35 -0700 | [diff] [blame] | 369 | |
Andrew Walbran | 12400d8 | 2021-03-04 17:04:34 +0000 | [diff] [blame] | 370 | impl<T: AsNative<sys::AIBinder>> IBinder for T { |
Stephen Crane | 2a3c250 | 2020-06-16 17:48:35 -0700 | [diff] [blame] | 371 | fn link_to_death(&mut self, recipient: &mut DeathRecipient) -> Result<()> { |
| 372 | status_result(unsafe { |
| 373 | // Safety: `SpIBinder` guarantees that `self` always contains a |
| 374 | // valid pointer to an `AIBinder`. `recipient` can always be |
| 375 | // converted into a valid pointer to an |
Alice Ryhl | ea9d9d2 | 2021-08-27 07:51:30 +0000 | [diff] [blame] | 376 | // `AIBinder_DeathRecipient`. |
| 377 | // |
| 378 | // The cookie is also the correct pointer, and by calling new_cookie, |
| 379 | // we have created a new ref-count to the cookie, which linkToDeath |
| 380 | // takes ownership of. Once the DeathRecipient is unlinked for any |
| 381 | // reason (including if this call fails), the onUnlinked callback |
| 382 | // will consume that ref-count. |
Stephen Crane | 2a3c250 | 2020-06-16 17:48:35 -0700 | [diff] [blame] | 383 | sys::AIBinder_linkToDeath( |
| 384 | self.as_native_mut(), |
| 385 | recipient.as_native_mut(), |
Alice Ryhl | ea9d9d2 | 2021-08-27 07:51:30 +0000 | [diff] [blame] | 386 | recipient.new_cookie(), |
Stephen Crane | 2a3c250 | 2020-06-16 17:48:35 -0700 | [diff] [blame] | 387 | ) |
| 388 | }) |
| 389 | } |
| 390 | |
| 391 | fn unlink_to_death(&mut self, recipient: &mut DeathRecipient) -> Result<()> { |
| 392 | status_result(unsafe { |
| 393 | // Safety: `SpIBinder` guarantees that `self` always contains a |
| 394 | // valid pointer to an `AIBinder`. `recipient` can always be |
| 395 | // converted into a valid pointer to an |
Stephen Crane | ddb3e6d | 2020-12-18 13:27:22 -0800 | [diff] [blame] | 396 | // `AIBinder_DeathRecipient`. Any value is safe to pass as the |
Stephen Crane | 2a3c250 | 2020-06-16 17:48:35 -0700 | [diff] [blame] | 397 | // cookie, although we depend on this value being set by |
| 398 | // `get_cookie` when the death recipient callback is called. |
| 399 | sys::AIBinder_unlinkToDeath( |
| 400 | self.as_native_mut(), |
| 401 | recipient.as_native_mut(), |
| 402 | recipient.get_cookie(), |
| 403 | ) |
| 404 | }) |
| 405 | } |
Stephen Crane | 61366d4 | 2022-01-20 17:45:34 -0800 | [diff] [blame] | 406 | |
| 407 | fn ping_binder(&mut self) -> Result<()> { |
| 408 | let status = unsafe { |
| 409 | // Safety: `SpIBinder` guarantees that `self` always contains a |
| 410 | // valid pointer to an `AIBinder`. |
| 411 | // |
| 412 | // This call does not affect ownership of its pointer parameter. |
| 413 | sys::AIBinder_ping(self.as_native_mut()) |
| 414 | }; |
| 415 | status_result(status) |
| 416 | } |
Stephen Crane | 2a3c250 | 2020-06-16 17:48:35 -0700 | [diff] [blame] | 417 | } |
| 418 | |
| 419 | impl Serialize for SpIBinder { |
Alice Ryhl | 8618c48 | 2021-11-09 15:35:35 +0000 | [diff] [blame] | 420 | fn serialize(&self, parcel: &mut BorrowedParcel<'_>) -> Result<()> { |
Stephen Crane | 2a3c250 | 2020-06-16 17:48:35 -0700 | [diff] [blame] | 421 | parcel.write_binder(Some(self)) |
| 422 | } |
| 423 | } |
| 424 | |
| 425 | impl SerializeOption for SpIBinder { |
Alice Ryhl | 8618c48 | 2021-11-09 15:35:35 +0000 | [diff] [blame] | 426 | fn serialize_option(this: Option<&Self>, parcel: &mut BorrowedParcel<'_>) -> Result<()> { |
Stephen Crane | 2a3c250 | 2020-06-16 17:48:35 -0700 | [diff] [blame] | 427 | parcel.write_binder(this) |
| 428 | } |
| 429 | } |
| 430 | |
| 431 | impl SerializeArray for SpIBinder {} |
Stephen Crane | 2a3c250 | 2020-06-16 17:48:35 -0700 | [diff] [blame] | 432 | |
| 433 | impl Deserialize for SpIBinder { |
Alice Ryhl | 8618c48 | 2021-11-09 15:35:35 +0000 | [diff] [blame] | 434 | fn deserialize(parcel: &BorrowedParcel<'_>) -> Result<SpIBinder> { |
Matthew Maurer | e268a9f | 2022-07-26 09:31:30 -0700 | [diff] [blame^] | 435 | parcel.read_binder().transpose().unwrap_or(Err(StatusCode::UNEXPECTED_NULL)) |
Stephen Crane | 2a3c250 | 2020-06-16 17:48:35 -0700 | [diff] [blame] | 436 | } |
| 437 | } |
| 438 | |
| 439 | impl DeserializeOption for SpIBinder { |
Alice Ryhl | 8618c48 | 2021-11-09 15:35:35 +0000 | [diff] [blame] | 440 | fn deserialize_option(parcel: &BorrowedParcel<'_>) -> Result<Option<SpIBinder>> { |
Stephen Crane | 2a3c250 | 2020-06-16 17:48:35 -0700 | [diff] [blame] | 441 | parcel.read_binder() |
| 442 | } |
| 443 | } |
| 444 | |
| 445 | impl DeserializeArray for SpIBinder {} |
Stephen Crane | 2a3c250 | 2020-06-16 17:48:35 -0700 | [diff] [blame] | 446 | |
| 447 | /// A weak reference to a Binder remote object. |
| 448 | /// |
Andrew Walbran | 8fe3ecc | 2020-12-15 11:29:58 +0000 | [diff] [blame] | 449 | /// This struct encapsulates the generic C++ `wp<IBinder>` class. This wrapper |
| 450 | /// is untyped; typed interface access is implemented by the AIDL compiler. |
Alice Ryhl | 8dde9bc | 2021-08-16 16:57:10 +0000 | [diff] [blame] | 451 | pub struct WpIBinder(ptr::NonNull<sys::AIBinder_Weak>); |
Stephen Crane | 2a3c250 | 2020-06-16 17:48:35 -0700 | [diff] [blame] | 452 | |
Andrew Walbran | 8fe3ecc | 2020-12-15 11:29:58 +0000 | [diff] [blame] | 453 | impl fmt::Debug for WpIBinder { |
| 454 | fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { |
| 455 | f.pad("WpIBinder") |
| 456 | } |
| 457 | } |
| 458 | |
| 459 | /// # Safety |
| 460 | /// |
Stephen Crane | f03fe3d | 2021-06-25 15:05:00 -0700 | [diff] [blame] | 461 | /// A `WpIBinder` is an immutable handle to a C++ IBinder, which is thread-safe. |
Andrew Walbran | 8fe3ecc | 2020-12-15 11:29:58 +0000 | [diff] [blame] | 462 | unsafe impl Send for WpIBinder {} |
| 463 | |
Stephen Crane | f03fe3d | 2021-06-25 15:05:00 -0700 | [diff] [blame] | 464 | /// # Safety |
| 465 | /// |
| 466 | /// A `WpIBinder` is an immutable handle to a C++ IBinder, which is thread-safe. |
| 467 | unsafe impl Sync for WpIBinder {} |
| 468 | |
Stephen Crane | 2a3c250 | 2020-06-16 17:48:35 -0700 | [diff] [blame] | 469 | impl WpIBinder { |
| 470 | /// Create a new weak reference from an object that can be converted into a |
| 471 | /// raw `AIBinder` pointer. |
Andrew Walbran | 8fe3ecc | 2020-12-15 11:29:58 +0000 | [diff] [blame] | 472 | fn new<B: AsNative<sys::AIBinder>>(binder: &mut B) -> WpIBinder { |
Stephen Crane | 2a3c250 | 2020-06-16 17:48:35 -0700 | [diff] [blame] | 473 | let ptr = unsafe { |
| 474 | // Safety: `SpIBinder` guarantees that `binder` always contains a |
| 475 | // valid pointer to an `AIBinder`. |
| 476 | sys::AIBinder_Weak_new(binder.as_native_mut()) |
| 477 | }; |
Alice Ryhl | 8dde9bc | 2021-08-16 16:57:10 +0000 | [diff] [blame] | 478 | Self(ptr::NonNull::new(ptr).expect("Unexpected null pointer from AIBinder_Weak_new")) |
Stephen Crane | 2a3c250 | 2020-06-16 17:48:35 -0700 | [diff] [blame] | 479 | } |
Stephen Crane | 994a0f0 | 2020-08-11 14:47:29 -0700 | [diff] [blame] | 480 | |
| 481 | /// Promote this weak reference to a strong reference to the binder object. |
| 482 | pub fn promote(&self) -> Option<SpIBinder> { |
| 483 | unsafe { |
| 484 | // Safety: `WpIBinder` always contains a valid weak reference, so we |
| 485 | // can pass this pointer to `AIBinder_Weak_promote`. Returns either |
| 486 | // null or an AIBinder owned by the caller, both of which are valid |
| 487 | // to pass to `SpIBinder::from_raw`. |
Alice Ryhl | 8dde9bc | 2021-08-16 16:57:10 +0000 | [diff] [blame] | 488 | let ptr = sys::AIBinder_Weak_promote(self.0.as_ptr()); |
Stephen Crane | 994a0f0 | 2020-08-11 14:47:29 -0700 | [diff] [blame] | 489 | SpIBinder::from_raw(ptr) |
| 490 | } |
| 491 | } |
Stephen Crane | 2a3c250 | 2020-06-16 17:48:35 -0700 | [diff] [blame] | 492 | } |
| 493 | |
Stephen Crane | ddb3e6d | 2020-12-18 13:27:22 -0800 | [diff] [blame] | 494 | impl Clone for WpIBinder { |
| 495 | fn clone(&self) -> Self { |
| 496 | let ptr = unsafe { |
| 497 | // Safety: WpIBinder always holds a valid `AIBinder_Weak` pointer, |
| 498 | // so this pointer is always safe to pass to `AIBinder_Weak_clone` |
| 499 | // (although null is also a safe value to pass to this API). |
| 500 | // |
| 501 | // We get ownership of the returned pointer, so can construct a new |
| 502 | // WpIBinder object from it. |
Alice Ryhl | 8dde9bc | 2021-08-16 16:57:10 +0000 | [diff] [blame] | 503 | sys::AIBinder_Weak_clone(self.0.as_ptr()) |
Stephen Crane | ddb3e6d | 2020-12-18 13:27:22 -0800 | [diff] [blame] | 504 | }; |
Alice Ryhl | 8dde9bc | 2021-08-16 16:57:10 +0000 | [diff] [blame] | 505 | Self(ptr::NonNull::new(ptr).expect("Unexpected null pointer from AIBinder_Weak_clone")) |
Stephen Crane | ddb3e6d | 2020-12-18 13:27:22 -0800 | [diff] [blame] | 506 | } |
| 507 | } |
| 508 | |
| 509 | impl Ord for WpIBinder { |
| 510 | fn cmp(&self, other: &Self) -> Ordering { |
| 511 | let less_than = unsafe { |
| 512 | // Safety: WpIBinder always holds a valid `AIBinder_Weak` pointer, |
| 513 | // so this pointer is always safe to pass to `AIBinder_Weak_lt` |
| 514 | // (null is also safe to pass to this function, but we should never |
| 515 | // do that). |
Alice Ryhl | 8dde9bc | 2021-08-16 16:57:10 +0000 | [diff] [blame] | 516 | sys::AIBinder_Weak_lt(self.0.as_ptr(), other.0.as_ptr()) |
Stephen Crane | ddb3e6d | 2020-12-18 13:27:22 -0800 | [diff] [blame] | 517 | }; |
| 518 | let greater_than = unsafe { |
| 519 | // Safety: WpIBinder always holds a valid `AIBinder_Weak` pointer, |
| 520 | // so this pointer is always safe to pass to `AIBinder_Weak_lt` |
| 521 | // (null is also safe to pass to this function, but we should never |
| 522 | // do that). |
Alice Ryhl | 8dde9bc | 2021-08-16 16:57:10 +0000 | [diff] [blame] | 523 | sys::AIBinder_Weak_lt(other.0.as_ptr(), self.0.as_ptr()) |
Stephen Crane | ddb3e6d | 2020-12-18 13:27:22 -0800 | [diff] [blame] | 524 | }; |
| 525 | if !less_than && !greater_than { |
| 526 | Ordering::Equal |
| 527 | } else if less_than { |
| 528 | Ordering::Less |
| 529 | } else { |
| 530 | Ordering::Greater |
| 531 | } |
| 532 | } |
| 533 | } |
| 534 | |
| 535 | impl PartialOrd for WpIBinder { |
| 536 | fn partial_cmp(&self, other: &Self) -> Option<Ordering> { |
| 537 | Some(self.cmp(other)) |
| 538 | } |
| 539 | } |
| 540 | |
| 541 | impl PartialEq for WpIBinder { |
| 542 | fn eq(&self, other: &Self) -> bool { |
| 543 | self.cmp(other) == Ordering::Equal |
| 544 | } |
| 545 | } |
| 546 | |
| 547 | impl Eq for WpIBinder {} |
| 548 | |
Andrew Walbran | 5e8dfa3 | 2020-12-16 12:50:06 +0000 | [diff] [blame] | 549 | impl Drop for WpIBinder { |
| 550 | fn drop(&mut self) { |
| 551 | unsafe { |
| 552 | // Safety: WpIBinder always holds a valid `AIBinder_Weak` pointer, so we |
| 553 | // know this pointer is safe to pass to `AIBinder_Weak_delete` here. |
Alice Ryhl | 8dde9bc | 2021-08-16 16:57:10 +0000 | [diff] [blame] | 554 | sys::AIBinder_Weak_delete(self.0.as_ptr()); |
Andrew Walbran | 5e8dfa3 | 2020-12-16 12:50:06 +0000 | [diff] [blame] | 555 | } |
| 556 | } |
| 557 | } |
| 558 | |
Stephen Crane | 2a3c250 | 2020-06-16 17:48:35 -0700 | [diff] [blame] | 559 | /// Rust wrapper around DeathRecipient objects. |
Alice Ryhl | ea9d9d2 | 2021-08-27 07:51:30 +0000 | [diff] [blame] | 560 | /// |
| 561 | /// The cookie in this struct represents an Arc<F> for the owned callback. |
| 562 | /// This struct owns a ref-count of it, and so does every binder that we |
| 563 | /// have been linked with. |
Stephen Crane | 2a3c250 | 2020-06-16 17:48:35 -0700 | [diff] [blame] | 564 | #[repr(C)] |
| 565 | pub struct DeathRecipient { |
| 566 | recipient: *mut sys::AIBinder_DeathRecipient, |
Alice Ryhl | ea9d9d2 | 2021-08-27 07:51:30 +0000 | [diff] [blame] | 567 | cookie: *mut c_void, |
| 568 | vtable: &'static DeathRecipientVtable, |
| 569 | } |
| 570 | |
| 571 | struct DeathRecipientVtable { |
| 572 | cookie_incr_refcount: unsafe extern "C" fn(*mut c_void), |
| 573 | cookie_decr_refcount: unsafe extern "C" fn(*mut c_void), |
Stephen Crane | 2a3c250 | 2020-06-16 17:48:35 -0700 | [diff] [blame] | 574 | } |
| 575 | |
Matthew Maurer | 51d76c8 | 2022-04-04 14:27:01 -0700 | [diff] [blame] | 576 | /// # Safety |
| 577 | /// |
| 578 | /// A `DeathRecipient` is a wrapper around `AIBinder_DeathRecipient` and a pointer |
| 579 | /// to a `Fn` which is `Sync` and `Send` (the cookie field). As |
| 580 | /// `AIBinder_DeathRecipient` is threadsafe, this structure is too. |
| 581 | unsafe impl Send for DeathRecipient {} |
| 582 | |
| 583 | /// # Safety |
| 584 | /// |
| 585 | /// A `DeathRecipient` is a wrapper around `AIBinder_DeathRecipient` and a pointer |
| 586 | /// to a `Fn` which is `Sync` and `Send` (the cookie field). As |
| 587 | /// `AIBinder_DeathRecipient` is threadsafe, this structure is too. |
| 588 | unsafe impl Sync for DeathRecipient {} |
| 589 | |
Stephen Crane | 2a3c250 | 2020-06-16 17:48:35 -0700 | [diff] [blame] | 590 | impl DeathRecipient { |
| 591 | /// Create a new death recipient that will call the given callback when its |
| 592 | /// associated object dies. |
| 593 | pub fn new<F>(callback: F) -> DeathRecipient |
| 594 | where |
Alice Ryhl | ea9d9d2 | 2021-08-27 07:51:30 +0000 | [diff] [blame] | 595 | F: Fn() + Send + Sync + 'static, |
Stephen Crane | 2a3c250 | 2020-06-16 17:48:35 -0700 | [diff] [blame] | 596 | { |
Alice Ryhl | ea9d9d2 | 2021-08-27 07:51:30 +0000 | [diff] [blame] | 597 | let callback: *const F = Arc::into_raw(Arc::new(callback)); |
Stephen Crane | 2a3c250 | 2020-06-16 17:48:35 -0700 | [diff] [blame] | 598 | let recipient = unsafe { |
| 599 | // Safety: The function pointer is a valid death recipient callback. |
| 600 | // |
| 601 | // This call returns an owned `AIBinder_DeathRecipient` pointer |
| 602 | // which must be destroyed via `AIBinder_DeathRecipient_delete` when |
| 603 | // no longer needed. |
| 604 | sys::AIBinder_DeathRecipient_new(Some(Self::binder_died::<F>)) |
| 605 | }; |
Alice Ryhl | ea9d9d2 | 2021-08-27 07:51:30 +0000 | [diff] [blame] | 606 | unsafe { |
| 607 | // Safety: The function pointer is a valid onUnlinked callback. |
| 608 | // |
| 609 | // All uses of linkToDeath in this file correctly increment the |
| 610 | // ref-count that this onUnlinked callback will decrement. |
Matthew Maurer | e268a9f | 2022-07-26 09:31:30 -0700 | [diff] [blame^] | 611 | sys::AIBinder_DeathRecipient_setOnUnlinked( |
| 612 | recipient, |
| 613 | Some(Self::cookie_decr_refcount::<F>), |
| 614 | ); |
Alice Ryhl | ea9d9d2 | 2021-08-27 07:51:30 +0000 | [diff] [blame] | 615 | } |
Stephen Crane | 2a3c250 | 2020-06-16 17:48:35 -0700 | [diff] [blame] | 616 | DeathRecipient { |
| 617 | recipient, |
Alice Ryhl | ea9d9d2 | 2021-08-27 07:51:30 +0000 | [diff] [blame] | 618 | cookie: callback as *mut c_void, |
| 619 | vtable: &DeathRecipientVtable { |
| 620 | cookie_incr_refcount: Self::cookie_incr_refcount::<F>, |
| 621 | cookie_decr_refcount: Self::cookie_decr_refcount::<F>, |
| 622 | }, |
Stephen Crane | 2a3c250 | 2020-06-16 17:48:35 -0700 | [diff] [blame] | 623 | } |
| 624 | } |
| 625 | |
Alice Ryhl | ea9d9d2 | 2021-08-27 07:51:30 +0000 | [diff] [blame] | 626 | /// Increment the ref-count for the cookie and return it. |
| 627 | /// |
| 628 | /// # Safety |
| 629 | /// |
| 630 | /// The caller must handle the returned ref-count correctly. |
| 631 | unsafe fn new_cookie(&self) -> *mut c_void { |
| 632 | (self.vtable.cookie_incr_refcount)(self.cookie); |
| 633 | |
| 634 | // Return a raw pointer with ownership of a ref-count |
| 635 | self.cookie |
| 636 | } |
| 637 | |
Stephen Crane | 2a3c250 | 2020-06-16 17:48:35 -0700 | [diff] [blame] | 638 | /// Get the opaque cookie that identifies this death recipient. |
| 639 | /// |
| 640 | /// This cookie will be used to link and unlink this death recipient to a |
| 641 | /// binder object and will be passed to the `binder_died` callback as an |
| 642 | /// opaque userdata pointer. |
| 643 | fn get_cookie(&self) -> *mut c_void { |
Alice Ryhl | ea9d9d2 | 2021-08-27 07:51:30 +0000 | [diff] [blame] | 644 | self.cookie |
Stephen Crane | 2a3c250 | 2020-06-16 17:48:35 -0700 | [diff] [blame] | 645 | } |
| 646 | |
| 647 | /// Callback invoked from C++ when the binder object dies. |
| 648 | /// |
| 649 | /// # Safety |
| 650 | /// |
Alice Ryhl | ea9d9d2 | 2021-08-27 07:51:30 +0000 | [diff] [blame] | 651 | /// The `cookie` parameter must be the cookie for an Arc<F> and |
| 652 | /// the caller must hold a ref-count to it. |
Stephen Crane | 2a3c250 | 2020-06-16 17:48:35 -0700 | [diff] [blame] | 653 | unsafe extern "C" fn binder_died<F>(cookie: *mut c_void) |
| 654 | where |
Alice Ryhl | ea9d9d2 | 2021-08-27 07:51:30 +0000 | [diff] [blame] | 655 | F: Fn() + Send + Sync + 'static, |
Stephen Crane | 2a3c250 | 2020-06-16 17:48:35 -0700 | [diff] [blame] | 656 | { |
Alice Ryhl | ea9d9d2 | 2021-08-27 07:51:30 +0000 | [diff] [blame] | 657 | let callback = (cookie as *const F).as_ref().unwrap(); |
Stephen Crane | 2a3c250 | 2020-06-16 17:48:35 -0700 | [diff] [blame] | 658 | callback(); |
| 659 | } |
Alice Ryhl | ea9d9d2 | 2021-08-27 07:51:30 +0000 | [diff] [blame] | 660 | |
| 661 | /// Callback that decrements the ref-count. |
| 662 | /// This is invoked from C++ when a binder is unlinked. |
| 663 | /// |
| 664 | /// # Safety |
| 665 | /// |
| 666 | /// The `cookie` parameter must be the cookie for an Arc<F> and |
| 667 | /// the owner must give up a ref-count to it. |
| 668 | unsafe extern "C" fn cookie_decr_refcount<F>(cookie: *mut c_void) |
| 669 | where |
| 670 | F: Fn() + Send + Sync + 'static, |
| 671 | { |
| 672 | drop(Arc::from_raw(cookie as *const F)); |
| 673 | } |
| 674 | |
| 675 | /// Callback that increments the ref-count. |
| 676 | /// |
| 677 | /// # Safety |
| 678 | /// |
| 679 | /// The `cookie` parameter must be the cookie for an Arc<F> and |
| 680 | /// the owner must handle the created ref-count properly. |
| 681 | unsafe extern "C" fn cookie_incr_refcount<F>(cookie: *mut c_void) |
| 682 | where |
| 683 | F: Fn() + Send + Sync + 'static, |
| 684 | { |
| 685 | let arc = mem::ManuallyDrop::new(Arc::from_raw(cookie as *const F)); |
| 686 | mem::forget(Arc::clone(&arc)); |
| 687 | } |
Stephen Crane | 2a3c250 | 2020-06-16 17:48:35 -0700 | [diff] [blame] | 688 | } |
| 689 | |
| 690 | /// # Safety |
| 691 | /// |
| 692 | /// A `DeathRecipient` is always constructed with a valid raw pointer to an |
| 693 | /// `AIBinder_DeathRecipient`, so it is always type-safe to extract this |
| 694 | /// pointer. |
| 695 | unsafe impl AsNative<sys::AIBinder_DeathRecipient> for DeathRecipient { |
| 696 | fn as_native(&self) -> *const sys::AIBinder_DeathRecipient { |
| 697 | self.recipient |
| 698 | } |
| 699 | |
| 700 | fn as_native_mut(&mut self) -> *mut sys::AIBinder_DeathRecipient { |
| 701 | self.recipient |
| 702 | } |
| 703 | } |
| 704 | |
| 705 | impl Drop for DeathRecipient { |
| 706 | fn drop(&mut self) { |
| 707 | unsafe { |
| 708 | // Safety: `self.recipient` is always a valid, owned |
| 709 | // `AIBinder_DeathRecipient` pointer returned by |
| 710 | // `AIBinder_DeathRecipient_new` when `self` was created. This |
| 711 | // delete method can only be called once when `self` is dropped. |
| 712 | sys::AIBinder_DeathRecipient_delete(self.recipient); |
Alice Ryhl | ea9d9d2 | 2021-08-27 07:51:30 +0000 | [diff] [blame] | 713 | |
| 714 | // Safety: We own a ref-count to the cookie, and so does every |
| 715 | // linked binder. This call gives up our ref-count. The linked |
| 716 | // binders should already have given up their ref-count, or should |
| 717 | // do so shortly. |
| 718 | (self.vtable.cookie_decr_refcount)(self.cookie) |
Stephen Crane | 2a3c250 | 2020-06-16 17:48:35 -0700 | [diff] [blame] | 719 | } |
| 720 | } |
| 721 | } |
| 722 | |
| 723 | /// Generic interface to remote binder objects. |
| 724 | /// |
| 725 | /// Corresponds to the C++ `BpInterface` class. |
| 726 | pub trait Proxy: Sized + Interface { |
| 727 | /// The Binder interface descriptor string. |
| 728 | /// |
| 729 | /// This string is a unique identifier for a Binder interface, and should be |
| 730 | /// the same between all implementations of that interface. |
| 731 | fn get_descriptor() -> &'static str; |
| 732 | |
| 733 | /// Create a new interface from the given proxy, if it matches the expected |
| 734 | /// type of this interface. |
| 735 | fn from_binder(binder: SpIBinder) -> Result<Self>; |
| 736 | } |
| 737 | |
| 738 | /// # Safety |
| 739 | /// |
| 740 | /// This is a convenience method that wraps `AsNative` for `SpIBinder` to allow |
| 741 | /// invocation of `IBinder` methods directly from `Interface` objects. It shares |
| 742 | /// the same safety as the implementation for `SpIBinder`. |
| 743 | unsafe impl<T: Proxy> AsNative<sys::AIBinder> for T { |
| 744 | fn as_native(&self) -> *const sys::AIBinder { |
| 745 | self.as_binder().as_native() |
| 746 | } |
| 747 | |
| 748 | fn as_native_mut(&mut self) -> *mut sys::AIBinder { |
| 749 | self.as_binder().as_native_mut() |
| 750 | } |
| 751 | } |
| 752 | |
| 753 | /// Retrieve an existing service, blocking for a few seconds if it doesn't yet |
| 754 | /// exist. |
| 755 | pub fn get_service(name: &str) -> Option<SpIBinder> { |
| 756 | let name = CString::new(name).ok()?; |
| 757 | unsafe { |
| 758 | // Safety: `AServiceManager_getService` returns either a null pointer or |
| 759 | // a valid pointer to an owned `AIBinder`. Either of these values is |
| 760 | // safe to pass to `SpIBinder::from_raw`. |
| 761 | SpIBinder::from_raw(sys::AServiceManager_getService(name.as_ptr())) |
| 762 | } |
| 763 | } |
| 764 | |
Andrew Walbran | c3ce5c3 | 2021-06-03 16:15:56 +0000 | [diff] [blame] | 765 | /// Retrieve an existing service, or start it if it is configured as a dynamic |
| 766 | /// service and isn't yet started. |
| 767 | pub fn wait_for_service(name: &str) -> Option<SpIBinder> { |
| 768 | let name = CString::new(name).ok()?; |
| 769 | unsafe { |
| 770 | // Safety: `AServiceManager_waitforService` returns either a null |
| 771 | // pointer or a valid pointer to an owned `AIBinder`. Either of these |
| 772 | // values is safe to pass to `SpIBinder::from_raw`. |
| 773 | SpIBinder::from_raw(sys::AServiceManager_waitForService(name.as_ptr())) |
| 774 | } |
| 775 | } |
| 776 | |
Stephen Crane | 2a3c250 | 2020-06-16 17:48:35 -0700 | [diff] [blame] | 777 | /// Retrieve an existing service for a particular interface, blocking for a few |
| 778 | /// seconds if it doesn't yet exist. |
Stephen Crane | ddb3e6d | 2020-12-18 13:27:22 -0800 | [diff] [blame] | 779 | pub fn get_interface<T: FromIBinder + ?Sized>(name: &str) -> Result<Strong<T>> { |
Stephen Crane | 2a3c250 | 2020-06-16 17:48:35 -0700 | [diff] [blame] | 780 | let service = get_service(name); |
| 781 | match service { |
| 782 | Some(service) => FromIBinder::try_from(service), |
| 783 | None => Err(StatusCode::NAME_NOT_FOUND), |
| 784 | } |
| 785 | } |
| 786 | |
Andrew Walbran | c3ce5c3 | 2021-06-03 16:15:56 +0000 | [diff] [blame] | 787 | /// Retrieve an existing service for a particular interface, or start it if it |
| 788 | /// is configured as a dynamic service and isn't yet started. |
| 789 | pub fn wait_for_interface<T: FromIBinder + ?Sized>(name: &str) -> Result<Strong<T>> { |
| 790 | let service = wait_for_service(name); |
| 791 | match service { |
| 792 | Some(service) => FromIBinder::try_from(service), |
| 793 | None => Err(StatusCode::NAME_NOT_FOUND), |
| 794 | } |
| 795 | } |
| 796 | |
Stephen Crane | 098bbc9 | 2022-02-14 13:31:53 -0800 | [diff] [blame] | 797 | /// Check if a service is declared (e.g. in a VINTF manifest) |
| 798 | pub fn is_declared(interface: &str) -> Result<bool> { |
| 799 | let interface = CString::new(interface).or(Err(StatusCode::UNEXPECTED_NULL))?; |
| 800 | |
| 801 | unsafe { |
| 802 | // Safety: `interface` is a valid null-terminated C-style string and is |
| 803 | // only borrowed for the lifetime of the call. The `interface` local |
| 804 | // outlives this call as it lives for the function scope. |
| 805 | Ok(sys::AServiceManager_isDeclared(interface.as_ptr())) |
| 806 | } |
| 807 | } |
| 808 | |
| 809 | /// Retrieve all declared instances for a particular interface |
| 810 | /// |
| 811 | /// For instance, if 'android.foo.IFoo/foo' is declared, and 'android.foo.IFoo' |
| 812 | /// is passed here, then ["foo"] would be returned. |
| 813 | pub fn get_declared_instances(interface: &str) -> Result<Vec<String>> { |
| 814 | unsafe extern "C" fn callback(instance: *const c_char, opaque: *mut c_void) { |
| 815 | // Safety: opaque was a mutable pointer created below from a Vec of |
| 816 | // CString, and outlives this callback. The null handling here is just |
| 817 | // to avoid the possibility of unwinding across C code if this crate is |
| 818 | // ever compiled with panic=unwind. |
| 819 | if let Some(instances) = opaque.cast::<Vec<CString>>().as_mut() { |
| 820 | // Safety: instance is a valid null-terminated C string with a |
| 821 | // lifetime at least as long as this function, and we immediately |
| 822 | // copy it into an owned CString. |
| 823 | instances.push(CStr::from_ptr(instance).to_owned()); |
| 824 | } else { |
| 825 | eprintln!("Opaque pointer was null in get_declared_instances callback!"); |
| 826 | } |
| 827 | } |
| 828 | |
| 829 | let interface = CString::new(interface).or(Err(StatusCode::UNEXPECTED_NULL))?; |
| 830 | let mut instances: Vec<CString> = vec![]; |
| 831 | unsafe { |
| 832 | // Safety: `interface` and `instances` are borrowed for the length of |
| 833 | // this call and both outlive the call. `interface` is guaranteed to be |
| 834 | // a valid null-terminated C-style string. |
| 835 | sys::AServiceManager_forEachDeclaredInstance( |
| 836 | interface.as_ptr(), |
| 837 | &mut instances as *mut _ as *mut c_void, |
| 838 | Some(callback), |
| 839 | ); |
| 840 | } |
| 841 | |
| 842 | instances |
| 843 | .into_iter() |
| 844 | .map(CString::into_string) |
| 845 | .collect::<std::result::Result<Vec<String>, _>>() |
| 846 | .map_err(|e| { |
| 847 | eprintln!("An interface instance name was not a valid UTF-8 string: {}", e); |
| 848 | StatusCode::BAD_VALUE |
| 849 | }) |
| 850 | } |
| 851 | |
Stephen Crane | 2a3c250 | 2020-06-16 17:48:35 -0700 | [diff] [blame] | 852 | /// # Safety |
| 853 | /// |
| 854 | /// `SpIBinder` guarantees that `binder` always contains a valid pointer to an |
| 855 | /// `AIBinder`, so we can trivially extract this pointer here. |
| 856 | unsafe impl AsNative<sys::AIBinder> for SpIBinder { |
| 857 | fn as_native(&self) -> *const sys::AIBinder { |
Alice Ryhl | 8dde9bc | 2021-08-16 16:57:10 +0000 | [diff] [blame] | 858 | self.0.as_ptr() |
Stephen Crane | 2a3c250 | 2020-06-16 17:48:35 -0700 | [diff] [blame] | 859 | } |
| 860 | |
| 861 | fn as_native_mut(&mut self) -> *mut sys::AIBinder { |
Alice Ryhl | 8dde9bc | 2021-08-16 16:57:10 +0000 | [diff] [blame] | 862 | self.0.as_ptr() |
Stephen Crane | 2a3c250 | 2020-06-16 17:48:35 -0700 | [diff] [blame] | 863 | } |
| 864 | } |