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 | use crate::binder::{AsNative, Interface, InterfaceClassMethods, Remotable, TransactionCode}; |
| 18 | use crate::error::{status_result, status_t, Result, StatusCode}; |
| 19 | use crate::parcel::{Parcel, Serialize}; |
| 20 | use crate::proxy::SpIBinder; |
| 21 | use crate::sys; |
| 22 | |
| 23 | use std::convert::TryFrom; |
| 24 | use std::ffi::{c_void, CString}; |
| 25 | use std::mem::ManuallyDrop; |
| 26 | use std::ops::Deref; |
| 27 | use std::ptr; |
| 28 | |
| 29 | /// Rust wrapper around Binder remotable objects. |
| 30 | /// |
| 31 | /// Implements the C++ `BBinder` class, and therefore implements the C++ |
| 32 | /// `IBinder` interface. |
| 33 | #[repr(C)] |
| 34 | pub struct Binder<T: Remotable> { |
| 35 | ibinder: *mut sys::AIBinder, |
| 36 | rust_object: *mut T, |
| 37 | } |
| 38 | |
| 39 | impl<T: Remotable> Binder<T> { |
| 40 | /// Create a new Binder remotable object. |
| 41 | /// |
| 42 | /// This moves the `rust_object` into an owned [`Box`] and Binder will |
| 43 | /// manage its lifetime. |
| 44 | pub fn new(rust_object: T) -> Binder<T> { |
| 45 | let class = T::get_class(); |
| 46 | let rust_object = Box::into_raw(Box::new(rust_object)); |
| 47 | let ibinder = unsafe { |
| 48 | // Safety: `AIBinder_new` expects a valid class pointer (which we |
| 49 | // initialize via `get_class`), and an arbitrary pointer |
| 50 | // argument. The caller owns the returned `AIBinder` pointer, which |
| 51 | // is a strong reference to a `BBinder`. This reference should be |
| 52 | // decremented via `AIBinder_decStrong` when the reference lifetime |
| 53 | // ends. |
| 54 | sys::AIBinder_new(class.into(), rust_object as *mut c_void) |
| 55 | }; |
| 56 | Binder { |
| 57 | ibinder, |
| 58 | rust_object, |
| 59 | } |
| 60 | } |
| 61 | |
| 62 | /// Set the extension of a binder interface. This allows a downstream |
| 63 | /// developer to add an extension to an interface without modifying its |
| 64 | /// interface file. This should be called immediately when the object is |
| 65 | /// created before it is passed to another thread. |
| 66 | /// |
| 67 | /// # Examples |
| 68 | /// |
| 69 | /// For instance, imagine if we have this Binder AIDL interface definition: |
| 70 | /// interface IFoo { void doFoo(); } |
| 71 | /// |
| 72 | /// If an unrelated owner (perhaps in a downstream codebase) wants to make a |
| 73 | /// change to the interface, they have two options: |
| 74 | /// |
| 75 | /// 1) Historical option that has proven to be BAD! Only the original |
| 76 | /// author of an interface should change an interface. If someone |
| 77 | /// downstream wants additional functionality, they should not ever |
| 78 | /// change the interface or use this method. |
| 79 | /// ```AIDL |
| 80 | /// BAD TO DO: interface IFoo { BAD TO DO |
| 81 | /// BAD TO DO: void doFoo(); BAD TO DO |
| 82 | /// BAD TO DO: + void doBar(); // adding a method BAD TO DO |
| 83 | /// BAD TO DO: } BAD TO DO |
| 84 | /// ``` |
| 85 | /// |
| 86 | /// 2) Option that this method enables! |
| 87 | /// Leave the original interface unchanged (do not change IFoo!). |
| 88 | /// Instead, create a new AIDL interface in a downstream package: |
| 89 | /// ```AIDL |
| 90 | /// package com.<name>; // new functionality in a new package |
| 91 | /// interface IBar { void doBar(); } |
| 92 | /// ``` |
| 93 | /// |
| 94 | /// When registering the interface, add: |
| 95 | /// |
| 96 | /// # use binder::{Binder, Interface}; |
| 97 | /// # type MyFoo = (); |
| 98 | /// # type MyBar = (); |
| 99 | /// # let my_foo = (); |
| 100 | /// # let my_bar = (); |
| 101 | /// let mut foo: Binder<MyFoo> = Binder::new(my_foo); // class in AOSP codebase |
| 102 | /// let bar: Binder<MyBar> = Binder::new(my_bar); // custom extension class |
| 103 | /// foo.set_extension(&mut bar.as_binder()); // use method in Binder |
| 104 | /// |
| 105 | /// Then, clients of `IFoo` can get this extension: |
| 106 | /// |
| 107 | /// # use binder::{declare_binder_interface, Binder, TransactionCode, Parcel}; |
| 108 | /// # trait IBar {} |
| 109 | /// # declare_binder_interface! { |
| 110 | /// # IBar["test"] { |
| 111 | /// # native: BnBar(on_transact), |
| 112 | /// # proxy: BpBar, |
| 113 | /// # } |
| 114 | /// # } |
| 115 | /// # fn on_transact( |
| 116 | /// # service: &dyn IBar, |
| 117 | /// # code: TransactionCode, |
| 118 | /// # data: &Parcel, |
| 119 | /// # reply: &mut Parcel, |
| 120 | /// # ) -> binder::Result<()> { |
| 121 | /// # Ok(()) |
| 122 | /// # } |
| 123 | /// # impl IBar for BpBar {} |
| 124 | /// # impl IBar for Binder<BnBar> {} |
| 125 | /// # fn main() -> binder::Result<()> { |
| 126 | /// # let binder = Binder::new(()); |
| 127 | /// if let Some(barBinder) = binder.get_extension()? { |
| 128 | /// let bar = BpBar::new(barBinder) |
| 129 | /// .expect("Extension was not of type IBar"); |
| 130 | /// } else { |
| 131 | /// // There was no extension |
| 132 | /// } |
| 133 | /// # } |
| 134 | pub fn set_extension(&mut self, extension: &mut SpIBinder) -> Result<()> { |
| 135 | let status = unsafe { |
| 136 | // Safety: `AIBinder_setExtension` expects two valid, mutable |
| 137 | // `AIBinder` pointers. We are guaranteed that both `self` and |
| 138 | // `extension` contain valid `AIBinder` pointers, because they |
| 139 | // cannot be initialized without a valid |
| 140 | // pointer. `AIBinder_setExtension` does not take ownership of |
| 141 | // either parameter. |
| 142 | sys::AIBinder_setExtension(self.as_native_mut(), extension.as_native_mut()) |
| 143 | }; |
| 144 | status_result(status) |
| 145 | } |
| 146 | |
| 147 | /// Retrieve the interface descriptor string for this object's Binder |
| 148 | /// interface. |
| 149 | pub fn get_descriptor() -> &'static str { |
| 150 | T::get_descriptor() |
| 151 | } |
| 152 | } |
| 153 | |
| 154 | impl<T: Remotable> Interface for Binder<T> { |
| 155 | /// Converts the local remotable object into a generic `SpIBinder` |
| 156 | /// reference. |
| 157 | /// |
| 158 | /// The resulting `SpIBinder` will hold its own strong reference to this |
| 159 | /// remotable object, which will prevent the object from being dropped while |
| 160 | /// the `SpIBinder` is alive. |
| 161 | fn as_binder(&self) -> SpIBinder { |
| 162 | unsafe { |
| 163 | // Safety: `self.ibinder` is guaranteed to always be a valid pointer |
| 164 | // to an `AIBinder` by the `Binder` constructor. We are creating a |
| 165 | // copy of the `self.ibinder` strong reference, but |
| 166 | // `SpIBinder::from_raw` assumes it receives an owned pointer with |
| 167 | // its own strong reference. We first increment the reference count, |
| 168 | // so that the new `SpIBinder` will be tracked as a new reference. |
| 169 | sys::AIBinder_incStrong(self.ibinder); |
| 170 | SpIBinder::from_raw(self.ibinder).unwrap() |
| 171 | } |
| 172 | } |
| 173 | } |
| 174 | |
| 175 | impl<T: Remotable> InterfaceClassMethods for Binder<T> { |
| 176 | fn get_descriptor() -> &'static str { |
| 177 | <T as Remotable>::get_descriptor() |
| 178 | } |
| 179 | |
| 180 | /// Called whenever a transaction needs to be processed by a local |
| 181 | /// implementation. |
| 182 | /// |
| 183 | /// # Safety |
| 184 | /// |
| 185 | /// Must be called with a non-null, valid pointer to a local `AIBinder` that |
| 186 | /// contains a `T` pointer in its user data. The `data` and `reply` parcel |
| 187 | /// parameters must be valid pointers to `AParcel` objects. This method does |
| 188 | /// not take ownership of any of its parameters. |
| 189 | /// |
| 190 | /// These conditions hold when invoked by `ABBinder::onTransact`. |
| 191 | unsafe extern "C" fn on_transact( |
| 192 | binder: *mut sys::AIBinder, |
| 193 | code: u32, |
| 194 | data: *const sys::AParcel, |
| 195 | reply: *mut sys::AParcel, |
| 196 | ) -> status_t { |
| 197 | let res = { |
| 198 | let mut reply = Parcel::borrowed(reply).unwrap(); |
| 199 | let data = Parcel::borrowed(data as *mut sys::AParcel).unwrap(); |
| 200 | let object = sys::AIBinder_getUserData(binder); |
| 201 | let binder: &T = &*(object as *const T); |
| 202 | binder.on_transact(code, &data, &mut reply) |
| 203 | }; |
| 204 | match res { |
| 205 | Ok(()) => 0i32, |
| 206 | Err(e) => e as i32, |
| 207 | } |
| 208 | } |
| 209 | |
| 210 | /// Called whenever an `AIBinder` object is no longer referenced and needs |
| 211 | /// destroyed. |
| 212 | /// |
| 213 | /// # Safety |
| 214 | /// |
| 215 | /// Must be called with a valid pointer to a `T` object. After this call, |
| 216 | /// the pointer will be invalid and should not be dereferenced. |
| 217 | unsafe extern "C" fn on_destroy(object: *mut c_void) { |
| 218 | ptr::drop_in_place(object as *mut T) |
| 219 | } |
| 220 | |
| 221 | /// Called whenever a new, local `AIBinder` object is needed of a specific |
| 222 | /// class. |
| 223 | /// |
| 224 | /// Constructs the user data pointer that will be stored in the object, |
| 225 | /// which will be a heap-allocated `T` object. |
| 226 | /// |
| 227 | /// # Safety |
| 228 | /// |
| 229 | /// Must be called with a valid pointer to a `T` object allocated via `Box`. |
| 230 | unsafe extern "C" fn on_create(args: *mut c_void) -> *mut c_void { |
| 231 | // We just return the argument, as it is already a pointer to the rust |
| 232 | // object created by Box. |
| 233 | args |
| 234 | } |
| 235 | } |
| 236 | |
| 237 | impl<T: Remotable> Drop for Binder<T> { |
| 238 | // This causes C++ to decrease the strong ref count of the `AIBinder` |
| 239 | // object. We specifically do not drop the `rust_object` here. When C++ |
| 240 | // actually destroys the object, it calls `on_destroy` and we can drop the |
| 241 | // `rust_object` then. |
| 242 | fn drop(&mut self) { |
| 243 | unsafe { |
| 244 | // Safety: When `self` is dropped, we can no longer access the |
| 245 | // reference, so can decrement the reference count. `self.ibinder` |
| 246 | // is always a valid `AIBinder` pointer, so is valid to pass to |
| 247 | // `AIBinder_decStrong`. |
| 248 | sys::AIBinder_decStrong(self.ibinder); |
| 249 | } |
| 250 | } |
| 251 | } |
| 252 | |
| 253 | impl<T: Remotable> Deref for Binder<T> { |
| 254 | type Target = T; |
| 255 | |
| 256 | fn deref(&self) -> &Self::Target { |
| 257 | unsafe { |
| 258 | // Safety: While `self` is alive, the reference count of the |
| 259 | // underlying object is > 0 and therefore `on_destroy` cannot be |
| 260 | // called. Therefore while `self` is alive, we know that |
| 261 | // `rust_object` is still a valid pointer to a heap allocated object |
| 262 | // of type `T`. |
| 263 | &*self.rust_object |
| 264 | } |
| 265 | } |
| 266 | } |
| 267 | |
| 268 | impl<B: Remotable> Serialize for Binder<B> { |
| 269 | fn serialize(&self, parcel: &mut Parcel) -> Result<()> { |
| 270 | parcel.write_binder(Some(&self.as_binder())) |
| 271 | } |
| 272 | } |
| 273 | |
| 274 | // This implementation is an idiomatic implementation of the C++ |
| 275 | // `IBinder::localBinder` interface if the binder object is a Rust binder |
| 276 | // service. |
| 277 | impl<B: Remotable> TryFrom<SpIBinder> for Binder<B> { |
| 278 | type Error = StatusCode; |
| 279 | |
| 280 | fn try_from(mut ibinder: SpIBinder) -> Result<Self> { |
| 281 | let class = B::get_class(); |
| 282 | if Some(class) != ibinder.get_class() { |
| 283 | return Err(StatusCode::BAD_TYPE); |
| 284 | } |
| 285 | let userdata = unsafe { |
| 286 | // Safety: `SpIBinder` always holds a valid pointer pointer to an |
| 287 | // `AIBinder`, which we can safely pass to |
| 288 | // `AIBinder_getUserData`. `ibinder` retains ownership of the |
| 289 | // returned pointer. |
| 290 | sys::AIBinder_getUserData(ibinder.as_native_mut()) |
| 291 | }; |
| 292 | if userdata.is_null() { |
| 293 | return Err(StatusCode::UNEXPECTED_NULL); |
| 294 | } |
| 295 | // We are transferring the ownership of the AIBinder into the new Binder |
| 296 | // object. |
| 297 | let mut ibinder = ManuallyDrop::new(ibinder); |
| 298 | Ok(Binder { |
| 299 | ibinder: ibinder.as_native_mut(), |
| 300 | rust_object: userdata as *mut B, |
| 301 | }) |
| 302 | } |
| 303 | } |
| 304 | |
| 305 | /// # Safety |
| 306 | /// |
| 307 | /// The constructor for `Binder` guarantees that `self.ibinder` will contain a |
| 308 | /// valid, non-null pointer to an `AIBinder`, so this implementation is type |
| 309 | /// safe. `self.ibinder` will remain valid for the entire lifetime of `self` |
| 310 | /// because we hold a strong reference to the `AIBinder` until `self` is |
| 311 | /// dropped. |
| 312 | unsafe impl<B: Remotable> AsNative<sys::AIBinder> for Binder<B> { |
| 313 | fn as_native(&self) -> *const sys::AIBinder { |
| 314 | self.ibinder |
| 315 | } |
| 316 | |
| 317 | fn as_native_mut(&mut self) -> *mut sys::AIBinder { |
| 318 | self.ibinder |
| 319 | } |
| 320 | } |
| 321 | |
| 322 | /// Register a new service with the default service manager. |
| 323 | /// |
| 324 | /// Registers the given binder object with the given identifier. If successful, |
| 325 | /// this service can then be retrieved using that identifier. |
| 326 | pub fn add_service(identifier: &str, mut binder: SpIBinder) -> Result<()> { |
| 327 | let instance = CString::new(identifier).unwrap(); |
| 328 | let status = unsafe { |
| 329 | // Safety: `AServiceManager_addService` expects valid `AIBinder` and C |
| 330 | // string pointers. Caller retains ownership of both |
| 331 | // pointers. `AServiceManager_addService` creates a new strong reference |
| 332 | // and copies the string, so both pointers need only be valid until the |
| 333 | // call returns. |
| 334 | sys::AServiceManager_addService(binder.as_native_mut(), instance.as_ptr()) |
| 335 | }; |
| 336 | status_result(status) |
| 337 | } |
| 338 | |
| 339 | /// Tests often create a base BBinder instance; so allowing the unit |
| 340 | /// type to be remotable translates nicely to Binder::new(()). |
| 341 | impl Remotable for () { |
| 342 | fn get_descriptor() -> &'static str { |
| 343 | "" |
| 344 | } |
| 345 | |
| 346 | fn on_transact( |
| 347 | &self, |
| 348 | _code: TransactionCode, |
| 349 | _data: &Parcel, |
| 350 | _reply: &mut Parcel, |
| 351 | ) -> Result<()> { |
| 352 | Ok(()) |
| 353 | } |
| 354 | |
| 355 | binder_fn_get_class!(Binder::<Self>); |
| 356 | } |
| 357 | |
| 358 | impl Interface for () {} |