blob: f9519b4d01d7e0d43518f9d4fbcd729a040b8d51 [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
17//! Rust API for interacting with a remote binder service.
18
19use crate::binder::{
20 AsNative, FromIBinder, IBinder, Interface, InterfaceClass, TransactionCode, TransactionFlags,
21};
22use crate::error::{status_result, Result, StatusCode};
23use crate::parcel::{
24 Deserialize, DeserializeArray, DeserializeOption, Parcel, Serialize, SerializeArray,
25 SerializeOption,
26};
27use crate::sys;
28
29use std::convert::TryInto;
30use std::ffi::{c_void, CString};
31use std::os::unix::io::AsRawFd;
32use std::ptr;
33
34/// A strong reference to a Binder remote object.
35///
36/// This struct encapsulates the generic C++ `sp<IBinder>` class. This wrapper
37/// is untyped; typed interface access is implemented by the AIDL compiler.
38pub struct SpIBinder(*mut sys::AIBinder);
39
40/// # Safety
41///
42/// An `SpIBinder` is a handle to a C++ IBinder, which is thread-safe
43unsafe impl Send for SpIBinder {}
44
45impl SpIBinder {
46 /// Create an `SpIBinder` wrapper object from a raw `AIBinder` pointer.
47 ///
48 /// # Safety
49 ///
50 /// This constructor is safe iff `ptr` is a null pointer or a valid pointer
51 /// to an `AIBinder`.
52 ///
53 /// In the non-null case, this method conceptually takes ownership of a strong
54 /// reference to the object, so `AIBinder_incStrong` must have been called
55 /// on the pointer before passing it to this constructor. This is generally
56 /// done by Binder NDK methods that return an `AIBinder`, but care should be
57 /// taken to ensure this invariant.
58 ///
59 /// All `SpIBinder` objects that are constructed will hold a valid pointer
60 /// to an `AIBinder`, which will remain valid for the entire lifetime of the
61 /// `SpIBinder` (we keep a strong reference, and only decrement on drop).
62 pub(crate) unsafe fn from_raw(ptr: *mut sys::AIBinder) -> Option<Self> {
63 ptr.as_mut().map(|p| Self(p))
64 }
65
66 /// Return true if this binder object is hosted in a different process than
67 /// the current one.
68 pub fn is_remote(&self) -> bool {
69 unsafe {
70 // Safety: `SpIBinder` guarantees that it always contains a valid
71 // `AIBinder` pointer.
72 sys::AIBinder_isRemote(self.as_native())
73 }
74 }
75
76 /// Try to convert this Binder object into a trait object for the given
77 /// Binder interface.
78 ///
79 /// If this object does not implement the expected interface, the error
80 /// `StatusCode::BAD_TYPE` is returned.
81 pub fn into_interface<I: FromIBinder + ?Sized>(self) -> Result<Box<I>> {
82 FromIBinder::try_from(self)
83 }
84
85 /// Return the interface class of this binder object, if associated with
86 /// one.
87 pub(crate) fn get_class(&mut self) -> Option<InterfaceClass> {
88 unsafe {
89 // Safety: `SpIBinder` guarantees that it always contains a valid
90 // `AIBinder` pointer. `AIBinder_getClass` returns either a null
91 // pointer or a valid pointer to an `AIBinder_Class`. After mapping
92 // null to None, we can safely construct an `InterfaceClass` if the
93 // pointer was non-null.
94 let class = sys::AIBinder_getClass(self.as_native_mut());
95 class.as_ref().map(|p| InterfaceClass::from_ptr(p))
96 }
97 }
98}
99
100/// An object that can be associate with an [`InterfaceClass`].
101pub trait AssociateClass {
102 /// Check if this object is a valid object for the given interface class
103 /// `I`.
104 ///
105 /// Returns `Some(self)` if this is a valid instance of the interface, and
106 /// `None` otherwise.
107 ///
108 /// Classes constructed by `InterfaceClass` are unique per type, so
109 /// repeatedly calling this method for the same `InterfaceClass` is allowed.
110 fn associate_class(&mut self, class: InterfaceClass) -> bool;
111}
112
113impl AssociateClass for SpIBinder {
114 fn associate_class(&mut self, class: InterfaceClass) -> bool {
115 unsafe {
116 // Safety: `SpIBinder` guarantees that it always contains a valid
117 // `AIBinder` pointer. An `InterfaceClass` can always be converted
118 // into a valid `AIBinder_Class` pointer, so these parameters are
119 // always safe.
120 sys::AIBinder_associateClass(self.as_native_mut(), class.into())
121 }
122 }
123}
124
125impl Clone for SpIBinder {
126 fn clone(&self) -> Self {
127 unsafe {
128 // Safety: Cloning a strong reference must increment the reference
129 // count. We are guaranteed by the `SpIBinder` constructor
130 // invariants that `self.0` is always a valid `AIBinder` pointer.
131 sys::AIBinder_incStrong(self.0);
132 }
133 Self(self.0)
134 }
135}
136
137impl Drop for SpIBinder {
138 // We hold a strong reference to the IBinder in SpIBinder and need to give up
139 // this reference on drop.
140 fn drop(&mut self) {
141 unsafe {
142 // Safety: SpIBinder always holds a valid `AIBinder` pointer, so we
143 // know this pointer is safe to pass to `AIBinder_decStrong` here.
144 sys::AIBinder_decStrong(self.as_native_mut());
145 }
146 }
147}
148
149impl<T: AsNative<sys::AIBinder>> IBinder for T {
150 /// Perform a binder transaction
151 fn transact<F: FnOnce(&mut Parcel) -> Result<()>>(
152 &self,
153 code: TransactionCode,
154 flags: TransactionFlags,
155 input_callback: F,
156 ) -> Result<Parcel> {
157 let mut input = ptr::null_mut();
158 let status = unsafe {
159 // Safety: `SpIBinder` guarantees that `self` always contains a
160 // valid pointer to an `AIBinder`. It is safe to cast from an
161 // immutable pointer to a mutable pointer here, because
162 // `AIBinder_prepareTransaction` only calls immutable `AIBinder`
163 // methods but the parameter is unfortunately not marked as const.
164 //
165 // After the call, input will be either a valid, owned `AParcel`
166 // pointer, or null.
167 sys::AIBinder_prepareTransaction(self.as_native() as *mut sys::AIBinder, &mut input)
168 };
169 status_result(status)?;
170 let mut input = unsafe {
171 // Safety: At this point, `input` is either a valid, owned `AParcel`
172 // pointer, or null. `Parcel::owned` safely handles both cases,
173 // taking ownership of the parcel.
174 Parcel::owned(input).ok_or(StatusCode::UNEXPECTED_NULL)?
175 };
176 input_callback(&mut input)?;
177 let mut reply = ptr::null_mut();
178 let status = unsafe {
179 // Safety: `SpIBinder` guarantees that `self` always contains a
180 // valid pointer to an `AIBinder`. Although `IBinder::transact` is
181 // not a const method, it is still safe to cast our immutable
182 // pointer to mutable for the call. First, `IBinder::transact` is
183 // thread-safe, so concurrency is not an issue. The only way that
184 // `transact` can affect any visible, mutable state in the current
185 // process is by calling `onTransact` for a local service. However,
186 // in order for transactions to be thread-safe, this method must
187 // dynamically lock its data before modifying it. We enforce this
188 // property in Rust by requiring `Sync` for remotable objects and
189 // only providing `on_transact` with an immutable reference to
190 // `self`.
191 //
192 // This call takes ownership of the `input` parcel pointer, and
193 // passes ownership of the `reply` out parameter to its caller. It
194 // does not affect ownership of the `binder` parameter.
195 sys::AIBinder_transact(
196 self.as_native() as *mut sys::AIBinder,
197 code,
198 &mut input.into_raw(),
199 &mut reply,
200 flags,
201 )
202 };
203 status_result(status)?;
204
205 unsafe {
206 // Safety: `reply` is either a valid `AParcel` pointer or null
207 // after the call to `AIBinder_transact` above, so we can
208 // construct a `Parcel` out of it. `AIBinder_transact` passes
209 // ownership of the `reply` parcel to Rust, so we need to
210 // construct an owned variant. `Parcel::owned` takes ownership
211 // of the parcel pointer.
212 Parcel::owned(reply).ok_or(StatusCode::UNEXPECTED_NULL)
213 }
214 }
215
216 fn is_binder_alive(&self) -> bool {
217 unsafe {
218 // Safety: `SpIBinder` guarantees that `self` always contains a
219 // valid pointer to an `AIBinder`.
220 //
221 // This call does not affect ownership of its pointer parameter.
222 sys::AIBinder_isAlive(self.as_native())
223 }
224 }
225
226 fn ping_binder(&mut self) -> Result<()> {
227 let status = unsafe {
228 // Safety: `SpIBinder` guarantees that `self` always contains a
229 // valid pointer to an `AIBinder`.
230 //
231 // This call does not affect ownership of its pointer parameter.
232 sys::AIBinder_ping(self.as_native_mut())
233 };
234 status_result(status)
235 }
236
237 fn dump<F: AsRawFd>(&mut self, fp: &F, args: &[&str]) -> Result<()> {
238 let args: Vec<_> = args.iter().map(|a| CString::new(*a).unwrap()).collect();
239 let mut arg_ptrs: Vec<_> = args.iter().map(|a| a.as_ptr()).collect();
240 let status = unsafe {
241 // Safety: `SpIBinder` guarantees that `self` always contains a
242 // valid pointer to an `AIBinder`. `AsRawFd` guarantees that the
243 // file descriptor parameter is always be a valid open file. The
244 // `args` pointer parameter is a valid pointer to an array of C
245 // strings that will outlive the call since `args` lives for the
246 // whole function scope.
247 //
248 // This call does not affect ownership of its binder pointer
249 // parameter and does not take ownership of the file or args array
250 // parameters.
251 sys::AIBinder_dump(
252 self.as_native_mut(),
253 fp.as_raw_fd(),
254 arg_ptrs.as_mut_ptr(),
255 arg_ptrs.len().try_into().unwrap(),
256 )
257 };
258 status_result(status)
259 }
260
261 fn get_extension(&mut self) -> Result<Option<SpIBinder>> {
262 let mut out = ptr::null_mut();
263 let status = unsafe {
264 // Safety: `SpIBinder` guarantees that `self` always contains a
265 // valid pointer to an `AIBinder`. After this call, the `out`
266 // parameter will be either null, or a valid pointer to an
267 // `AIBinder`.
268 //
269 // This call passes ownership of the out pointer to its caller
270 // (assuming it is set to a non-null value).
271 sys::AIBinder_getExtension(self.as_native_mut(), &mut out)
272 };
273 let ibinder = unsafe {
274 // Safety: The call above guarantees that `out` is either null or a
275 // valid, owned pointer to an `AIBinder`, both of which are safe to
276 // pass to `SpIBinder::from_raw`.
277 SpIBinder::from_raw(out)
278 };
279
280 status_result(status)?;
281 Ok(ibinder)
282 }
283
284 fn link_to_death(&mut self, recipient: &mut DeathRecipient) -> Result<()> {
285 status_result(unsafe {
286 // Safety: `SpIBinder` guarantees that `self` always contains a
287 // valid pointer to an `AIBinder`. `recipient` can always be
288 // converted into a valid pointer to an
289 // `AIBinder_DeatRecipient`. Any value is safe to pass as the
290 // cookie, although we depend on this value being set by
291 // `get_cookie` when the death recipient callback is called.
292 sys::AIBinder_linkToDeath(
293 self.as_native_mut(),
294 recipient.as_native_mut(),
295 recipient.get_cookie(),
296 )
297 })
298 }
299
300 fn unlink_to_death(&mut self, recipient: &mut DeathRecipient) -> Result<()> {
301 status_result(unsafe {
302 // Safety: `SpIBinder` guarantees that `self` always contains a
303 // valid pointer to an `AIBinder`. `recipient` can always be
304 // converted into a valid pointer to an
305 // `AIBinder_DeatRecipient`. Any value is safe to pass as the
306 // cookie, although we depend on this value being set by
307 // `get_cookie` when the death recipient callback is called.
308 sys::AIBinder_unlinkToDeath(
309 self.as_native_mut(),
310 recipient.as_native_mut(),
311 recipient.get_cookie(),
312 )
313 })
314 }
315}
316
317impl Serialize for SpIBinder {
318 fn serialize(&self, parcel: &mut Parcel) -> Result<()> {
319 parcel.write_binder(Some(self))
320 }
321}
322
323impl SerializeOption for SpIBinder {
324 fn serialize_option(this: Option<&Self>, parcel: &mut Parcel) -> Result<()> {
325 parcel.write_binder(this)
326 }
327}
328
329impl SerializeArray for SpIBinder {}
330impl SerializeArray for Option<&SpIBinder> {}
331
332impl Deserialize for SpIBinder {
333 fn deserialize(parcel: &Parcel) -> Result<SpIBinder> {
334 parcel.read_binder().transpose().unwrap()
335 }
336}
337
338impl DeserializeOption for SpIBinder {
339 fn deserialize_option(parcel: &Parcel) -> Result<Option<SpIBinder>> {
340 parcel.read_binder()
341 }
342}
343
344impl DeserializeArray for SpIBinder {}
345impl DeserializeArray for Option<SpIBinder> {}
346
347/// A weak reference to a Binder remote object.
348///
349/// This struct encapsulates the C++ `wp<IBinder>` class. However, this wrapper
350/// is untyped, so properly typed versions implementing a particular binder
351/// interface should be crated with [`declare_binder_interface!`].
352pub struct WpIBinder(*mut sys::AIBinder_Weak);
353
354impl WpIBinder {
355 /// Create a new weak reference from an object that can be converted into a
356 /// raw `AIBinder` pointer.
357 pub fn new<B: AsNative<sys::AIBinder>>(binder: &mut B) -> WpIBinder {
358 let ptr = unsafe {
359 // Safety: `SpIBinder` guarantees that `binder` always contains a
360 // valid pointer to an `AIBinder`.
361 sys::AIBinder_Weak_new(binder.as_native_mut())
362 };
363 assert!(!ptr.is_null());
364 Self(ptr)
365 }
366}
367
368/// Rust wrapper around DeathRecipient objects.
369#[repr(C)]
370pub struct DeathRecipient {
371 recipient: *mut sys::AIBinder_DeathRecipient,
372 callback: Box<dyn Fn() + Send + 'static>,
373}
374
375impl DeathRecipient {
376 /// Create a new death recipient that will call the given callback when its
377 /// associated object dies.
378 pub fn new<F>(callback: F) -> DeathRecipient
379 where
380 F: Fn() + Send + 'static,
381 {
382 let callback = Box::new(callback);
383 let recipient = unsafe {
384 // Safety: The function pointer is a valid death recipient callback.
385 //
386 // This call returns an owned `AIBinder_DeathRecipient` pointer
387 // which must be destroyed via `AIBinder_DeathRecipient_delete` when
388 // no longer needed.
389 sys::AIBinder_DeathRecipient_new(Some(Self::binder_died::<F>))
390 };
391 DeathRecipient {
392 recipient,
393 callback,
394 }
395 }
396
397 /// Get the opaque cookie that identifies this death recipient.
398 ///
399 /// This cookie will be used to link and unlink this death recipient to a
400 /// binder object and will be passed to the `binder_died` callback as an
401 /// opaque userdata pointer.
402 fn get_cookie(&self) -> *mut c_void {
403 &*self.callback as *const _ as *mut c_void
404 }
405
406 /// Callback invoked from C++ when the binder object dies.
407 ///
408 /// # Safety
409 ///
410 /// The `cookie` parameter must have been created with the `get_cookie`
411 /// method of this object.
412 unsafe extern "C" fn binder_died<F>(cookie: *mut c_void)
413 where
414 F: Fn() + Send + 'static,
415 {
416 let callback = (cookie as *mut F).as_ref().unwrap();
417 callback();
418 }
419}
420
421/// # Safety
422///
423/// A `DeathRecipient` is always constructed with a valid raw pointer to an
424/// `AIBinder_DeathRecipient`, so it is always type-safe to extract this
425/// pointer.
426unsafe impl AsNative<sys::AIBinder_DeathRecipient> for DeathRecipient {
427 fn as_native(&self) -> *const sys::AIBinder_DeathRecipient {
428 self.recipient
429 }
430
431 fn as_native_mut(&mut self) -> *mut sys::AIBinder_DeathRecipient {
432 self.recipient
433 }
434}
435
436impl Drop for DeathRecipient {
437 fn drop(&mut self) {
438 unsafe {
439 // Safety: `self.recipient` is always a valid, owned
440 // `AIBinder_DeathRecipient` pointer returned by
441 // `AIBinder_DeathRecipient_new` when `self` was created. This
442 // delete method can only be called once when `self` is dropped.
443 sys::AIBinder_DeathRecipient_delete(self.recipient);
444 }
445 }
446}
447
448/// Generic interface to remote binder objects.
449///
450/// Corresponds to the C++ `BpInterface` class.
451pub trait Proxy: Sized + Interface {
452 /// The Binder interface descriptor string.
453 ///
454 /// This string is a unique identifier for a Binder interface, and should be
455 /// the same between all implementations of that interface.
456 fn get_descriptor() -> &'static str;
457
458 /// Create a new interface from the given proxy, if it matches the expected
459 /// type of this interface.
460 fn from_binder(binder: SpIBinder) -> Result<Self>;
461}
462
463/// # Safety
464///
465/// This is a convenience method that wraps `AsNative` for `SpIBinder` to allow
466/// invocation of `IBinder` methods directly from `Interface` objects. It shares
467/// the same safety as the implementation for `SpIBinder`.
468unsafe impl<T: Proxy> AsNative<sys::AIBinder> for T {
469 fn as_native(&self) -> *const sys::AIBinder {
470 self.as_binder().as_native()
471 }
472
473 fn as_native_mut(&mut self) -> *mut sys::AIBinder {
474 self.as_binder().as_native_mut()
475 }
476}
477
478/// Retrieve an existing service, blocking for a few seconds if it doesn't yet
479/// exist.
480pub fn get_service(name: &str) -> Option<SpIBinder> {
481 let name = CString::new(name).ok()?;
482 unsafe {
483 // Safety: `AServiceManager_getService` returns either a null pointer or
484 // a valid pointer to an owned `AIBinder`. Either of these values is
485 // safe to pass to `SpIBinder::from_raw`.
486 SpIBinder::from_raw(sys::AServiceManager_getService(name.as_ptr()))
487 }
488}
489
490/// Retrieve an existing service for a particular interface, blocking for a few
491/// seconds if it doesn't yet exist.
492pub fn get_interface<T: FromIBinder + ?Sized>(name: &str) -> Result<Box<T>> {
493 let service = get_service(name);
494 match service {
495 Some(service) => FromIBinder::try_from(service),
496 None => Err(StatusCode::NAME_NOT_FOUND),
497 }
498}
499
500/// # Safety
501///
502/// `SpIBinder` guarantees that `binder` always contains a valid pointer to an
503/// `AIBinder`, so we can trivially extract this pointer here.
504unsafe impl AsNative<sys::AIBinder> for SpIBinder {
505 fn as_native(&self) -> *const sys::AIBinder {
506 self.0
507 }
508
509 fn as_native_mut(&mut self) -> *mut sys::AIBinder {
510 self.0
511 }
512}