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