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