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 #[cfg(not(android_ndk))] 18 use crate::binder::Stability; 19 use crate::binder::{AsNative, Interface, InterfaceClassMethods, Remotable, TransactionCode}; 20 use crate::error::{status_result, status_t, Result, StatusCode}; 21 use crate::parcel::{BorrowedParcel, Serialize}; 22 use crate::proxy::SpIBinder; 23 use crate::sys; 24 25 use std::convert::TryFrom; 26 use std::ffi::{c_void, CStr}; 27 use std::io::Write; 28 use std::mem::ManuallyDrop; 29 use std::ops::Deref; 30 use std::os::raw::c_char; 31 32 /// Rust wrapper around Binder remotable objects. 33 /// 34 /// Implements the C++ `BBinder` class, and therefore implements the C++ 35 /// `IBinder` interface. 36 #[repr(C)] 37 pub struct Binder<T: Remotable> { 38 ibinder: *mut sys::AIBinder, 39 rust_object: *mut T, 40 } 41 42 /// Safety: 43 /// 44 /// A `Binder<T>` is a pair of unique owning pointers to two values: 45 /// * a C++ ABBinder which the C++ API guarantees can be passed between threads 46 /// * a Rust object which implements `Remotable`; this trait requires `Send + Sync` 47 /// 48 /// Both pointers are unique (never escape the `Binder<T>` object and are not copied) 49 /// so we can essentially treat `Binder<T>` as a box-like containing the two objects; 50 /// the box-like object inherits `Send` from the two inner values, similarly 51 /// to how `Box<T>` is `Send` if `T` is `Send`. 52 unsafe impl<T: Remotable> Send for Binder<T> {} 53 54 /// Safety: 55 /// 56 /// A `Binder<T>` is a pair of unique owning pointers to two values: 57 /// * a C++ ABBinder which is thread-safe, i.e. `Send + Sync` 58 /// * a Rust object which implements `Remotable`; this trait requires `Send + Sync` 59 /// 60 /// `ABBinder` contains an immutable `mUserData` pointer, which is actually a 61 /// pointer to a boxed `T: Remotable`, which is `Sync`. `ABBinder` also contains 62 /// a mutable pointer to its class, but mutation of this field is controlled by 63 /// a mutex and it is only allowed to be set once, therefore we can concurrently 64 /// access this field safely. `ABBinder` inherits from `BBinder`, which is also 65 /// thread-safe. Thus `ABBinder` is thread-safe. 66 /// 67 /// Both pointers are unique (never escape the `Binder<T>` object and are not copied) 68 /// so we can essentially treat `Binder<T>` as a box-like containing the two objects; 69 /// the box-like object inherits `Sync` from the two inner values, similarly 70 /// to how `Box<T>` is `Sync` if `T` is `Sync`. 71 unsafe impl<T: Remotable> Sync for Binder<T> {} 72 73 impl<T: Remotable> Binder<T> { 74 /// Create a new Binder remotable object with default stability 75 /// 76 /// This moves the `rust_object` into an owned [`Box`] and Binder will 77 /// manage its lifetime. new(rust_object: T) -> Binder<T>78 pub fn new(rust_object: T) -> Binder<T> { 79 #[cfg(not(android_ndk))] 80 { 81 Self::new_with_stability(rust_object, Stability::default()) 82 } 83 #[cfg(android_ndk)] 84 { 85 Self::new_unmarked(rust_object) 86 } 87 } 88 89 /// Create a new Binder remotable object with the given stability 90 /// 91 /// This moves the `rust_object` into an owned [`Box`] and Binder will 92 /// manage its lifetime. 93 #[cfg(not(android_ndk))] new_with_stability(rust_object: T, stability: Stability) -> Binder<T>94 pub fn new_with_stability(rust_object: T, stability: Stability) -> Binder<T> { 95 let mut binder = Self::new_unmarked(rust_object); 96 binder.mark_stability(stability); 97 binder 98 } 99 100 /// Creates a new Binder remotable object with unset stability 101 /// 102 /// This is internal because normally we want to set the stability explicitly, 103 /// however for the NDK variant we cannot mark the stability. new_unmarked(rust_object: T) -> Binder<T>104 fn new_unmarked(rust_object: T) -> Binder<T> { 105 let class = T::get_class(); 106 let rust_object = Box::into_raw(Box::new(rust_object)); 107 // Safety: `AIBinder_new` expects a valid class pointer (which we 108 // initialize via `get_class`), and an arbitrary pointer 109 // argument. The caller owns the returned `AIBinder` pointer, which 110 // is a strong reference to a `BBinder`. This reference should be 111 // decremented via `AIBinder_decStrong` when the reference lifetime 112 // ends. 113 let ibinder = unsafe { sys::AIBinder_new(class.into(), rust_object as *mut c_void) }; 114 Binder { ibinder, rust_object } 115 } 116 117 /// Set the extension of a binder interface. This allows a downstream 118 /// developer to add an extension to an interface without modifying its 119 /// interface file. This should be called immediately when the object is 120 /// created before it is passed to another thread. 121 /// 122 /// # Examples 123 /// 124 /// For instance, imagine if we have this Binder AIDL interface definition: 125 /// interface IFoo { void doFoo(); } 126 /// 127 /// If an unrelated owner (perhaps in a downstream codebase) wants to make a 128 /// change to the interface, they have two options: 129 /// 130 /// 1) Historical option that has proven to be BAD! Only the original 131 /// author of an interface should change an interface. If someone 132 /// downstream wants additional functionality, they should not ever 133 /// change the interface or use this method. 134 /// ```AIDL 135 /// BAD TO DO: interface IFoo { BAD TO DO 136 /// BAD TO DO: void doFoo(); BAD TO DO 137 /// BAD TO DO: + void doBar(); // adding a method BAD TO DO 138 /// BAD TO DO: } BAD TO DO 139 /// ``` 140 /// 141 /// 2) Option that this method enables! 142 /// Leave the original interface unchanged (do not change IFoo!). 143 /// Instead, create a new AIDL interface in a downstream package: 144 /// ```AIDL 145 /// package com.<name>; // new functionality in a new package 146 /// interface IBar { void doBar(); } 147 /// ``` 148 /// 149 /// When registering the interface, add: 150 /// 151 /// # use binder::{Binder, Interface}; 152 /// # type MyFoo = (); 153 /// # type MyBar = (); 154 /// # let my_foo = (); 155 /// # let my_bar = (); 156 /// let mut foo: Binder<MyFoo> = Binder::new(my_foo); // class in AOSP codebase 157 /// let bar: Binder<MyBar> = Binder::new(my_bar); // custom extension class 158 /// foo.set_extension(&mut bar.as_binder()); // use method in Binder 159 /// 160 /// Then, clients of `IFoo` can get this extension: 161 /// 162 /// # use binder::{declare_binder_interface, Binder, TransactionCode, Parcel}; 163 /// # trait IBar {} 164 /// # declare_binder_interface! { 165 /// # IBar["test"] { 166 /// # native: BnBar(on_transact), 167 /// # proxy: BpBar, 168 /// # } 169 /// # } 170 /// # fn on_transact( 171 /// # service: &dyn IBar, 172 /// # code: TransactionCode, 173 /// # data: &BorrowedParcel, 174 /// # reply: &mut BorrowedParcel, 175 /// # ) -> binder::Result<()> { 176 /// # Ok(()) 177 /// # } 178 /// # impl IBar for BpBar {} 179 /// # impl IBar for Binder<BnBar> {} 180 /// # fn main() -> binder::Result<()> { 181 /// # let binder = Binder::new(()); 182 /// if let Some(barBinder) = binder.get_extension()? { 183 /// let bar = BpBar::new(barBinder) 184 /// .expect("Extension was not of type IBar"); 185 /// } else { 186 /// // There was no extension 187 /// } 188 /// # } set_extension(&mut self, extension: &mut SpIBinder) -> Result<()>189 pub fn set_extension(&mut self, extension: &mut SpIBinder) -> Result<()> { 190 let status = 191 // Safety: `AIBinder_setExtension` expects two valid, mutable 192 // `AIBinder` pointers. We are guaranteed that both `self` and 193 // `extension` contain valid `AIBinder` pointers, because they 194 // cannot be initialized without a valid 195 // pointer. `AIBinder_setExtension` does not take ownership of 196 // either parameter. 197 unsafe { sys::AIBinder_setExtension(self.as_native_mut(), extension.as_native_mut()) }; 198 status_result(status) 199 } 200 201 /// Retrieve the interface descriptor string for this object's Binder 202 /// interface. get_descriptor() -> &'static str203 pub fn get_descriptor() -> &'static str { 204 T::get_descriptor() 205 } 206 207 /// Mark this binder object with the given stability guarantee 208 #[cfg(not(android_ndk))] mark_stability(&mut self, stability: Stability)209 fn mark_stability(&mut self, stability: Stability) { 210 match stability { 211 Stability::Local => self.mark_local_stability(), 212 Stability::Vintf => { 213 // Safety: Self always contains a valid `AIBinder` pointer, so 214 // we can always call this C API safely. 215 unsafe { 216 sys::AIBinder_markVintfStability(self.as_native_mut()); 217 } 218 } 219 } 220 } 221 222 /// Mark this binder object with local stability, which is vendor if we are 223 /// building for android_vendor and system otherwise. 224 #[cfg(android_vendor)] mark_local_stability(&mut self)225 fn mark_local_stability(&mut self) { 226 // Safety: Self always contains a valid `AIBinder` pointer, so we can 227 // always call this C API safely. 228 unsafe { 229 sys::AIBinder_markVendorStability(self.as_native_mut()); 230 } 231 } 232 233 /// Mark this binder object with local stability, which is vendor if we are 234 /// building for android_vendor and system otherwise. 235 #[cfg(not(any(android_vendor, android_ndk)))] mark_local_stability(&mut self)236 fn mark_local_stability(&mut self) { 237 // Safety: Self always contains a valid `AIBinder` pointer, so we can 238 // always call this C API safely. 239 unsafe { 240 sys::AIBinder_markSystemStability(self.as_native_mut()); 241 } 242 } 243 } 244 245 impl<T: Remotable> Interface for Binder<T> { 246 /// Converts the local remotable object into a generic `SpIBinder` 247 /// reference. 248 /// 249 /// The resulting `SpIBinder` will hold its own strong reference to this 250 /// remotable object, which will prevent the object from being dropped while 251 /// the `SpIBinder` is alive. as_binder(&self) -> SpIBinder252 fn as_binder(&self) -> SpIBinder { 253 // Safety: `self.ibinder` is guaranteed to always be a valid pointer 254 // to an `AIBinder` by the `Binder` constructor. We are creating a 255 // copy of the `self.ibinder` strong reference, but 256 // `SpIBinder::from_raw` assumes it receives an owned pointer with 257 // its own strong reference. We first increment the reference count, 258 // so that the new `SpIBinder` will be tracked as a new reference. 259 unsafe { 260 sys::AIBinder_incStrong(self.ibinder); 261 SpIBinder::from_raw(self.ibinder).unwrap() 262 } 263 } 264 } 265 266 impl<T: Remotable> InterfaceClassMethods for Binder<T> { get_descriptor() -> &'static str267 fn get_descriptor() -> &'static str { 268 <T as Remotable>::get_descriptor() 269 } 270 271 /// Called whenever a transaction needs to be processed by a local 272 /// implementation. 273 /// 274 /// # Safety 275 /// 276 /// Must be called with a non-null, valid pointer to a local `AIBinder` that 277 /// contains a `T` pointer in its user data. The `data` and `reply` parcel 278 /// parameters must be valid pointers to `AParcel` objects. This method does 279 /// not take ownership of any of its parameters. 280 /// 281 /// These conditions hold when invoked by `ABBinder::onTransact`. on_transact( binder: *mut sys::AIBinder, code: u32, data: *const sys::AParcel, reply: *mut sys::AParcel, ) -> status_t282 unsafe extern "C" fn on_transact( 283 binder: *mut sys::AIBinder, 284 code: u32, 285 data: *const sys::AParcel, 286 reply: *mut sys::AParcel, 287 ) -> status_t { 288 let res = { 289 // Safety: The caller must give us a parcel pointer which is either 290 // null or valid at least for the duration of this function call. We 291 // don't keep the resulting value beyond the function. 292 let mut reply = unsafe { BorrowedParcel::from_raw(reply).unwrap() }; 293 // Safety: The caller must give us a parcel pointer which is either 294 // null or valid at least for the duration of this function call. We 295 // don't keep the resulting value beyond the function. 296 let data = unsafe { BorrowedParcel::from_raw(data as *mut sys::AParcel).unwrap() }; 297 // Safety: Our caller promised that `binder` is a non-null, valid 298 // pointer to a local `AIBinder`. 299 let object = unsafe { sys::AIBinder_getUserData(binder) }; 300 // Safety: Our caller promised that the binder has a `T` pointer in 301 // its user data. 302 let binder: &T = unsafe { &*(object as *const T) }; 303 binder.on_transact(code, &data, &mut reply) 304 }; 305 match res { 306 Ok(()) => 0i32, 307 Err(e) => e as i32, 308 } 309 } 310 311 /// Called whenever an `AIBinder` object is no longer referenced and needs 312 /// destroyed. 313 /// 314 /// # Safety 315 /// 316 /// Must be called with a valid pointer to a `T` object. After this call, 317 /// the pointer will be invalid and should not be dereferenced. on_destroy(object: *mut c_void)318 unsafe extern "C" fn on_destroy(object: *mut c_void) { 319 // Safety: Our caller promised that `object` is a valid pointer to a 320 // `T`. 321 drop(unsafe { Box::from_raw(object as *mut T) }); 322 } 323 324 /// Called whenever a new, local `AIBinder` object is needed of a specific 325 /// class. 326 /// 327 /// Constructs the user data pointer that will be stored in the object, 328 /// which will be a heap-allocated `T` object. 329 /// 330 /// # Safety 331 /// 332 /// Must be called with a valid pointer to a `T` object allocated via `Box`. on_create(args: *mut c_void) -> *mut c_void333 unsafe extern "C" fn on_create(args: *mut c_void) -> *mut c_void { 334 // We just return the argument, as it is already a pointer to the rust 335 // object created by Box. 336 args 337 } 338 339 /// Called to handle the `dump` transaction. 340 /// 341 /// # Safety 342 /// 343 /// Must be called with a non-null, valid pointer to a local `AIBinder` that 344 /// contains a `T` pointer in its user data. fd should be a non-owned file 345 /// descriptor, and args must be an array of null-terminated string 346 /// pointers with length num_args. 347 #[cfg(not(trusty))] on_dump( binder: *mut sys::AIBinder, fd: i32, args: *mut *const c_char, num_args: u32, ) -> status_t348 unsafe extern "C" fn on_dump( 349 binder: *mut sys::AIBinder, 350 fd: i32, 351 args: *mut *const c_char, 352 num_args: u32, 353 ) -> status_t { 354 if fd < 0 { 355 return StatusCode::UNEXPECTED_NULL as status_t; 356 } 357 use std::os::fd::FromRawFd; 358 // Safety: Our caller promised that fd is a file descriptor. We don't 359 // own this file descriptor, so we need to be careful not to drop it. 360 let mut file = unsafe { ManuallyDrop::new(std::fs::File::from_raw_fd(fd)) }; 361 362 if args.is_null() && num_args != 0 { 363 return StatusCode::UNEXPECTED_NULL as status_t; 364 } 365 366 let args = if args.is_null() || num_args == 0 { 367 vec![] 368 } else { 369 // Safety: Our caller promised that `args` is an array of 370 // null-terminated string pointers with length `num_args`. 371 unsafe { 372 std::slice::from_raw_parts(args, num_args as usize) 373 .iter() 374 .map(|s| CStr::from_ptr(*s)) 375 .collect() 376 } 377 }; 378 379 // Safety: Our caller promised that `binder` is a non-null, valid 380 // pointer to a local `AIBinder`. 381 let object = unsafe { sys::AIBinder_getUserData(binder) }; 382 // Safety: Our caller promised that the binder has a `T` pointer in its 383 // user data. 384 let binder: &T = unsafe { &*(object as *const T) }; 385 let res = binder.on_dump(&mut *file, &args); 386 387 match res { 388 Ok(()) => 0, 389 Err(e) => e as status_t, 390 } 391 } 392 393 /// Called to handle the `dump` transaction. 394 #[cfg(trusty)] on_dump( _binder: *mut sys::AIBinder, _fd: i32, _args: *mut *const c_char, _num_args: u32, ) -> status_t395 unsafe extern "C" fn on_dump( 396 _binder: *mut sys::AIBinder, 397 _fd: i32, 398 _args: *mut *const c_char, 399 _num_args: u32, 400 ) -> status_t { 401 // This operation is not supported on Trusty right now 402 // because we do not have a uniform way of writing to handles 403 StatusCode::INVALID_OPERATION as status_t 404 } 405 } 406 407 impl<T: Remotable> Drop for Binder<T> { 408 // This causes C++ to decrease the strong ref count of the `AIBinder` 409 // object. We specifically do not drop the `rust_object` here. When C++ 410 // actually destroys the object, it calls `on_destroy` and we can drop the 411 // `rust_object` then. drop(&mut self)412 fn drop(&mut self) { 413 // Safety: When `self` is dropped, we can no longer access the 414 // reference, so can decrement the reference count. `self.ibinder` is 415 // always a valid `AIBinder` pointer, so is valid to pass to 416 // `AIBinder_decStrong`. 417 unsafe { 418 sys::AIBinder_decStrong(self.ibinder); 419 } 420 } 421 } 422 423 impl<T: Remotable> Deref for Binder<T> { 424 type Target = T; 425 deref(&self) -> &Self::Target426 fn deref(&self) -> &Self::Target { 427 // Safety: While `self` is alive, the reference count of the underlying 428 // object is > 0 and therefore `on_destroy` cannot be called. Therefore 429 // while `self` is alive, we know that `rust_object` is still a valid 430 // pointer to a heap allocated object of type `T`. 431 unsafe { &*self.rust_object } 432 } 433 } 434 435 impl<B: Remotable> Serialize for Binder<B> { serialize(&self, parcel: &mut BorrowedParcel<'_>) -> Result<()>436 fn serialize(&self, parcel: &mut BorrowedParcel<'_>) -> Result<()> { 437 parcel.write_binder(Some(&self.as_binder())) 438 } 439 } 440 441 // This implementation is an idiomatic implementation of the C++ 442 // `IBinder::localBinder` interface if the binder object is a Rust binder 443 // service. 444 impl<B: Remotable> TryFrom<SpIBinder> for Binder<B> { 445 type Error = StatusCode; 446 try_from(mut ibinder: SpIBinder) -> Result<Self>447 fn try_from(mut ibinder: SpIBinder) -> Result<Self> { 448 let class = B::get_class(); 449 if Some(class) != ibinder.get_class() { 450 return Err(StatusCode::BAD_TYPE); 451 } 452 // Safety: `SpIBinder` always holds a valid pointer pointer to an 453 // `AIBinder`, which we can safely pass to `AIBinder_getUserData`. 454 // `ibinder` retains ownership of the returned pointer. 455 let userdata = unsafe { sys::AIBinder_getUserData(ibinder.as_native_mut()) }; 456 if userdata.is_null() { 457 return Err(StatusCode::UNEXPECTED_NULL); 458 } 459 // We are transferring the ownership of the AIBinder into the new Binder 460 // object. 461 let mut ibinder = ManuallyDrop::new(ibinder); 462 Ok(Binder { ibinder: ibinder.as_native_mut(), rust_object: userdata as *mut B }) 463 } 464 } 465 466 /// Safety: The constructor for `Binder` guarantees that `self.ibinder` will 467 /// contain a valid, non-null pointer to an `AIBinder`, so this implementation 468 /// is type safe. `self.ibinder` will remain valid for the entire lifetime of 469 /// `self` because we hold a strong reference to the `AIBinder` until `self` is 470 /// dropped. 471 unsafe impl<B: Remotable> AsNative<sys::AIBinder> for Binder<B> { as_native(&self) -> *const sys::AIBinder472 fn as_native(&self) -> *const sys::AIBinder { 473 self.ibinder 474 } 475 as_native_mut(&mut self) -> *mut sys::AIBinder476 fn as_native_mut(&mut self) -> *mut sys::AIBinder { 477 self.ibinder 478 } 479 } 480 481 /// Tests often create a base BBinder instance; so allowing the unit 482 /// type to be remotable translates nicely to Binder::new(()). 483 impl Remotable for () { get_descriptor() -> &'static str484 fn get_descriptor() -> &'static str { 485 "" 486 } 487 on_transact( &self, _code: TransactionCode, _data: &BorrowedParcel<'_>, _reply: &mut BorrowedParcel<'_>, ) -> Result<()>488 fn on_transact( 489 &self, 490 _code: TransactionCode, 491 _data: &BorrowedParcel<'_>, 492 _reply: &mut BorrowedParcel<'_>, 493 ) -> Result<()> { 494 Ok(()) 495 } 496 on_dump(&self, _writer: &mut dyn Write, _args: &[&CStr]) -> Result<()>497 fn on_dump(&self, _writer: &mut dyn Write, _args: &[&CStr]) -> Result<()> { 498 Ok(()) 499 } 500 501 binder_fn_get_class!(Binder::<Self>); 502 } 503 504 impl Interface for () {} 505