blob: a0dfeecf43edb54ff9d38cb8b1926704e5079529 [file] [log] [blame]
Stephen Crane2a3c2502020-06-16 17:48:35 -07001/*
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
Stephen Craneff7f03a2021-02-25 16:04:22 -080017use crate::binder::{AsNative, Interface, InterfaceClassMethods, Remotable, Stability, TransactionCode};
Stephen Crane2a3c2502020-06-16 17:48:35 -070018use crate::error::{status_result, status_t, Result, StatusCode};
19use crate::parcel::{Parcel, Serialize};
20use crate::proxy::SpIBinder;
21use crate::sys;
22
23use std::convert::TryFrom;
Stephen Crane2a3297f2021-06-11 16:48:10 -070024use std::ffi::{c_void, CStr, CString};
25use std::fs::File;
Stephen Crane2a3c2502020-06-16 17:48:35 -070026use std::mem::ManuallyDrop;
27use std::ops::Deref;
Stephen Crane2a3297f2021-06-11 16:48:10 -070028use std::os::raw::c_char;
29use std::os::unix::io::FromRawFd;
30use std::slice;
Stephen Crane2a3c2502020-06-16 17:48:35 -070031
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)]
37pub struct Binder<T: Remotable> {
38 ibinder: *mut sys::AIBinder,
39 rust_object: *mut T,
40}
41
Andrei Homescu2c674b02020-08-07 22:12:27 -070042/// # 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`.
52unsafe impl<T: Remotable> Send for Binder<T> {}
53
Stephen Cranef03fe3d2021-06-25 15:05:00 -070054/// # 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`.
71unsafe impl<T: Remotable> Sync for Binder<T> {}
72
Stephen Crane2a3c2502020-06-16 17:48:35 -070073impl<T: Remotable> Binder<T> {
Stephen Craneff7f03a2021-02-25 16:04:22 -080074 /// Create a new Binder remotable object with default stability
Stephen Crane2a3c2502020-06-16 17:48:35 -070075 ///
76 /// This moves the `rust_object` into an owned [`Box`] and Binder will
77 /// manage its lifetime.
78 pub fn new(rust_object: T) -> Binder<T> {
Stephen Craneff7f03a2021-02-25 16:04:22 -080079 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.
86 pub fn new_with_stability(rust_object: T, stability: Stability) -> Binder<T> {
Stephen Crane2a3c2502020-06-16 17:48:35 -070087 let class = T::get_class();
88 let rust_object = Box::into_raw(Box::new(rust_object));
89 let ibinder = unsafe {
90 // Safety: `AIBinder_new` expects a valid class pointer (which we
91 // initialize via `get_class`), and an arbitrary pointer
92 // argument. The caller owns the returned `AIBinder` pointer, which
93 // is a strong reference to a `BBinder`. This reference should be
94 // decremented via `AIBinder_decStrong` when the reference lifetime
95 // ends.
96 sys::AIBinder_new(class.into(), rust_object as *mut c_void)
97 };
Stephen Craneff7f03a2021-02-25 16:04:22 -080098 let mut binder = Binder {
Stephen Crane2a3c2502020-06-16 17:48:35 -070099 ibinder,
100 rust_object,
Stephen Craneff7f03a2021-02-25 16:04:22 -0800101 };
102 binder.mark_stability(stability);
103 binder
Stephen Crane2a3c2502020-06-16 17:48:35 -0700104 }
105
106 /// Set the extension of a binder interface. This allows a downstream
107 /// developer to add an extension to an interface without modifying its
108 /// interface file. This should be called immediately when the object is
109 /// created before it is passed to another thread.
110 ///
111 /// # Examples
112 ///
113 /// For instance, imagine if we have this Binder AIDL interface definition:
114 /// interface IFoo { void doFoo(); }
115 ///
116 /// If an unrelated owner (perhaps in a downstream codebase) wants to make a
117 /// change to the interface, they have two options:
118 ///
119 /// 1) Historical option that has proven to be BAD! Only the original
120 /// author of an interface should change an interface. If someone
121 /// downstream wants additional functionality, they should not ever
122 /// change the interface or use this method.
123 /// ```AIDL
124 /// BAD TO DO: interface IFoo { BAD TO DO
125 /// BAD TO DO: void doFoo(); BAD TO DO
126 /// BAD TO DO: + void doBar(); // adding a method BAD TO DO
127 /// BAD TO DO: } BAD TO DO
128 /// ```
129 ///
130 /// 2) Option that this method enables!
131 /// Leave the original interface unchanged (do not change IFoo!).
132 /// Instead, create a new AIDL interface in a downstream package:
133 /// ```AIDL
134 /// package com.<name>; // new functionality in a new package
135 /// interface IBar { void doBar(); }
136 /// ```
137 ///
138 /// When registering the interface, add:
139 ///
140 /// # use binder::{Binder, Interface};
141 /// # type MyFoo = ();
142 /// # type MyBar = ();
143 /// # let my_foo = ();
144 /// # let my_bar = ();
145 /// let mut foo: Binder<MyFoo> = Binder::new(my_foo); // class in AOSP codebase
146 /// let bar: Binder<MyBar> = Binder::new(my_bar); // custom extension class
147 /// foo.set_extension(&mut bar.as_binder()); // use method in Binder
148 ///
149 /// Then, clients of `IFoo` can get this extension:
150 ///
151 /// # use binder::{declare_binder_interface, Binder, TransactionCode, Parcel};
152 /// # trait IBar {}
153 /// # declare_binder_interface! {
154 /// # IBar["test"] {
155 /// # native: BnBar(on_transact),
156 /// # proxy: BpBar,
157 /// # }
158 /// # }
159 /// # fn on_transact(
160 /// # service: &dyn IBar,
161 /// # code: TransactionCode,
162 /// # data: &Parcel,
163 /// # reply: &mut Parcel,
164 /// # ) -> binder::Result<()> {
165 /// # Ok(())
166 /// # }
167 /// # impl IBar for BpBar {}
168 /// # impl IBar for Binder<BnBar> {}
169 /// # fn main() -> binder::Result<()> {
170 /// # let binder = Binder::new(());
171 /// if let Some(barBinder) = binder.get_extension()? {
172 /// let bar = BpBar::new(barBinder)
173 /// .expect("Extension was not of type IBar");
174 /// } else {
175 /// // There was no extension
176 /// }
177 /// # }
178 pub fn set_extension(&mut self, extension: &mut SpIBinder) -> Result<()> {
179 let status = unsafe {
180 // Safety: `AIBinder_setExtension` expects two valid, mutable
181 // `AIBinder` pointers. We are guaranteed that both `self` and
182 // `extension` contain valid `AIBinder` pointers, because they
183 // cannot be initialized without a valid
184 // pointer. `AIBinder_setExtension` does not take ownership of
185 // either parameter.
186 sys::AIBinder_setExtension(self.as_native_mut(), extension.as_native_mut())
187 };
188 status_result(status)
189 }
190
191 /// Retrieve the interface descriptor string for this object's Binder
192 /// interface.
193 pub fn get_descriptor() -> &'static str {
194 T::get_descriptor()
195 }
Stephen Craneff7f03a2021-02-25 16:04:22 -0800196
197 /// Mark this binder object with the given stability guarantee
198 fn mark_stability(&mut self, stability: Stability) {
199 match stability {
200 Stability::Local => self.mark_local_stability(),
201 Stability::Vintf => {
202 unsafe {
203 // Safety: Self always contains a valid `AIBinder` pointer, so
204 // we can always call this C API safely.
205 sys::AIBinder_markVintfStability(self.as_native_mut());
206 }
207 }
208 }
209 }
210
211 /// Mark this binder object with local stability, which is vendor if we are
212 /// building for the VNDK and system otherwise.
213 #[cfg(vendor_ndk)]
214 fn mark_local_stability(&mut self) {
215 unsafe {
216 // Safety: Self always contains a valid `AIBinder` pointer, so
217 // we can always call this C API safely.
218 sys::AIBinder_markVendorStability(self.as_native_mut());
219 }
220 }
221
222 /// Mark this binder object with local stability, which is vendor if we are
223 /// building for the VNDK and system otherwise.
224 #[cfg(not(vendor_ndk))]
225 fn mark_local_stability(&mut self) {
226 unsafe {
227 // Safety: Self always contains a valid `AIBinder` pointer, so
228 // we can always call this C API safely.
229 sys::AIBinder_markSystemStability(self.as_native_mut());
230 }
231 }
Stephen Crane2a3c2502020-06-16 17:48:35 -0700232}
233
234impl<T: Remotable> Interface for Binder<T> {
235 /// Converts the local remotable object into a generic `SpIBinder`
236 /// reference.
237 ///
238 /// The resulting `SpIBinder` will hold its own strong reference to this
239 /// remotable object, which will prevent the object from being dropped while
240 /// the `SpIBinder` is alive.
241 fn as_binder(&self) -> SpIBinder {
242 unsafe {
243 // Safety: `self.ibinder` is guaranteed to always be a valid pointer
244 // to an `AIBinder` by the `Binder` constructor. We are creating a
245 // copy of the `self.ibinder` strong reference, but
246 // `SpIBinder::from_raw` assumes it receives an owned pointer with
247 // its own strong reference. We first increment the reference count,
248 // so that the new `SpIBinder` will be tracked as a new reference.
249 sys::AIBinder_incStrong(self.ibinder);
250 SpIBinder::from_raw(self.ibinder).unwrap()
251 }
252 }
253}
254
255impl<T: Remotable> InterfaceClassMethods for Binder<T> {
256 fn get_descriptor() -> &'static str {
257 <T as Remotable>::get_descriptor()
258 }
259
260 /// Called whenever a transaction needs to be processed by a local
261 /// implementation.
262 ///
263 /// # Safety
264 ///
265 /// Must be called with a non-null, valid pointer to a local `AIBinder` that
266 /// contains a `T` pointer in its user data. The `data` and `reply` parcel
267 /// parameters must be valid pointers to `AParcel` objects. This method does
268 /// not take ownership of any of its parameters.
269 ///
270 /// These conditions hold when invoked by `ABBinder::onTransact`.
271 unsafe extern "C" fn on_transact(
272 binder: *mut sys::AIBinder,
273 code: u32,
274 data: *const sys::AParcel,
275 reply: *mut sys::AParcel,
276 ) -> status_t {
277 let res = {
278 let mut reply = Parcel::borrowed(reply).unwrap();
279 let data = Parcel::borrowed(data as *mut sys::AParcel).unwrap();
280 let object = sys::AIBinder_getUserData(binder);
281 let binder: &T = &*(object as *const T);
282 binder.on_transact(code, &data, &mut reply)
283 };
284 match res {
285 Ok(()) => 0i32,
286 Err(e) => e as i32,
287 }
288 }
289
290 /// Called whenever an `AIBinder` object is no longer referenced and needs
291 /// destroyed.
292 ///
293 /// # Safety
294 ///
295 /// Must be called with a valid pointer to a `T` object. After this call,
296 /// the pointer will be invalid and should not be dereferenced.
297 unsafe extern "C" fn on_destroy(object: *mut c_void) {
Matthew Maurerc050d8f2021-06-11 16:49:48 -0700298 Box::from_raw(object as *mut T);
Stephen Crane2a3c2502020-06-16 17:48:35 -0700299 }
300
301 /// Called whenever a new, local `AIBinder` object is needed of a specific
302 /// class.
303 ///
304 /// Constructs the user data pointer that will be stored in the object,
305 /// which will be a heap-allocated `T` object.
306 ///
307 /// # Safety
308 ///
309 /// Must be called with a valid pointer to a `T` object allocated via `Box`.
310 unsafe extern "C" fn on_create(args: *mut c_void) -> *mut c_void {
311 // We just return the argument, as it is already a pointer to the rust
312 // object created by Box.
313 args
314 }
Stephen Crane2a3297f2021-06-11 16:48:10 -0700315
316 /// Called to handle the `dump` transaction.
317 ///
318 /// # Safety
319 ///
320 /// Must be called with a non-null, valid pointer to a local `AIBinder` that
321 /// contains a `T` pointer in its user data. fd should be a non-owned file
322 /// descriptor, and args must be an array of null-terminated string
323 /// poiinters with length num_args.
324 unsafe extern "C" fn on_dump(binder: *mut sys::AIBinder, fd: i32, args: *mut *const c_char, num_args: u32) -> status_t {
325 if fd < 0 {
326 return StatusCode::UNEXPECTED_NULL as status_t;
327 }
328 // We don't own this file, so we need to be careful not to drop it.
329 let file = ManuallyDrop::new(File::from_raw_fd(fd));
330
331 if args.is_null() {
332 return StatusCode::UNEXPECTED_NULL as status_t;
333 }
334 let args = slice::from_raw_parts(args, num_args as usize);
335 let args: Vec<_> = args.iter().map(|s| CStr::from_ptr(*s)).collect();
336
337 let object = sys::AIBinder_getUserData(binder);
338 let binder: &T = &*(object as *const T);
339 let res = binder.on_dump(&file, &args);
340
341 match res {
342 Ok(()) => 0,
343 Err(e) => e as status_t,
344 }
345 }
Stephen Crane2a3c2502020-06-16 17:48:35 -0700346}
347
348impl<T: Remotable> Drop for Binder<T> {
349 // This causes C++ to decrease the strong ref count of the `AIBinder`
350 // object. We specifically do not drop the `rust_object` here. When C++
351 // actually destroys the object, it calls `on_destroy` and we can drop the
352 // `rust_object` then.
353 fn drop(&mut self) {
354 unsafe {
355 // Safety: When `self` is dropped, we can no longer access the
356 // reference, so can decrement the reference count. `self.ibinder`
357 // is always a valid `AIBinder` pointer, so is valid to pass to
358 // `AIBinder_decStrong`.
359 sys::AIBinder_decStrong(self.ibinder);
360 }
361 }
362}
363
364impl<T: Remotable> Deref for Binder<T> {
365 type Target = T;
366
367 fn deref(&self) -> &Self::Target {
368 unsafe {
369 // Safety: While `self` is alive, the reference count of the
370 // underlying object is > 0 and therefore `on_destroy` cannot be
371 // called. Therefore while `self` is alive, we know that
372 // `rust_object` is still a valid pointer to a heap allocated object
373 // of type `T`.
374 &*self.rust_object
375 }
376 }
377}
378
379impl<B: Remotable> Serialize for Binder<B> {
380 fn serialize(&self, parcel: &mut Parcel) -> Result<()> {
381 parcel.write_binder(Some(&self.as_binder()))
382 }
383}
384
385// This implementation is an idiomatic implementation of the C++
386// `IBinder::localBinder` interface if the binder object is a Rust binder
387// service.
388impl<B: Remotable> TryFrom<SpIBinder> for Binder<B> {
389 type Error = StatusCode;
390
391 fn try_from(mut ibinder: SpIBinder) -> Result<Self> {
392 let class = B::get_class();
393 if Some(class) != ibinder.get_class() {
394 return Err(StatusCode::BAD_TYPE);
395 }
396 let userdata = unsafe {
397 // Safety: `SpIBinder` always holds a valid pointer pointer to an
398 // `AIBinder`, which we can safely pass to
399 // `AIBinder_getUserData`. `ibinder` retains ownership of the
400 // returned pointer.
401 sys::AIBinder_getUserData(ibinder.as_native_mut())
402 };
403 if userdata.is_null() {
404 return Err(StatusCode::UNEXPECTED_NULL);
405 }
406 // We are transferring the ownership of the AIBinder into the new Binder
407 // object.
408 let mut ibinder = ManuallyDrop::new(ibinder);
409 Ok(Binder {
410 ibinder: ibinder.as_native_mut(),
411 rust_object: userdata as *mut B,
412 })
413 }
414}
415
416/// # Safety
417///
418/// The constructor for `Binder` guarantees that `self.ibinder` will contain a
419/// valid, non-null pointer to an `AIBinder`, so this implementation is type
420/// safe. `self.ibinder` will remain valid for the entire lifetime of `self`
421/// because we hold a strong reference to the `AIBinder` until `self` is
422/// dropped.
423unsafe impl<B: Remotable> AsNative<sys::AIBinder> for Binder<B> {
424 fn as_native(&self) -> *const sys::AIBinder {
425 self.ibinder
426 }
427
428 fn as_native_mut(&mut self) -> *mut sys::AIBinder {
429 self.ibinder
430 }
431}
432
433/// Register a new service with the default service manager.
434///
435/// Registers the given binder object with the given identifier. If successful,
436/// this service can then be retrieved using that identifier.
437pub fn add_service(identifier: &str, mut binder: SpIBinder) -> Result<()> {
438 let instance = CString::new(identifier).unwrap();
439 let status = unsafe {
440 // Safety: `AServiceManager_addService` expects valid `AIBinder` and C
441 // string pointers. Caller retains ownership of both
442 // pointers. `AServiceManager_addService` creates a new strong reference
443 // and copies the string, so both pointers need only be valid until the
444 // call returns.
445 sys::AServiceManager_addService(binder.as_native_mut(), instance.as_ptr())
446 };
447 status_result(status)
448}
449
450/// Tests often create a base BBinder instance; so allowing the unit
451/// type to be remotable translates nicely to Binder::new(()).
452impl Remotable for () {
453 fn get_descriptor() -> &'static str {
454 ""
455 }
456
457 fn on_transact(
458 &self,
459 _code: TransactionCode,
460 _data: &Parcel,
461 _reply: &mut Parcel,
462 ) -> Result<()> {
463 Ok(())
464 }
465
Stephen Crane2a3297f2021-06-11 16:48:10 -0700466 fn on_dump(&self, _file: &File, _args: &[&CStr]) -> Result<()> {
467 Ok(())
468 }
469
Stephen Crane2a3c2502020-06-16 17:48:35 -0700470 binder_fn_get_class!(Binder::<Self>);
471}
472
473impl Interface for () {}