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