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