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