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 //! Container for messages that are sent via binder.
18
19 use crate::binder::AsNative;
20 use crate::error::{status_result, Result, StatusCode};
21 use crate::proxy::SpIBinder;
22 use crate::sys;
23
24 use std::convert::TryInto;
25 use std::fmt;
26 use std::marker::PhantomData;
27 use std::mem::ManuallyDrop;
28 use std::ptr::{self, NonNull};
29
30 mod file_descriptor;
31 mod parcelable;
32 mod parcelable_holder;
33
34 pub use self::file_descriptor::ParcelFileDescriptor;
35 pub use self::parcelable::{
36 Deserialize, DeserializeArray, DeserializeOption, Parcelable, Serialize, SerializeArray,
37 SerializeOption, NON_NULL_PARCELABLE_FLAG, NULL_PARCELABLE_FLAG,
38 };
39 pub use self::parcelable_holder::{ParcelableHolder, ParcelableMetadata};
40
41 /// Container for a message (data and object references) that can be sent
42 /// through Binder.
43 ///
44 /// A Parcel can contain both serialized data that will be deserialized on the
45 /// other side of the IPC, and references to live Binder objects that will
46 /// result in the other side receiving a proxy Binder connected with the
47 /// original Binder in the Parcel.
48 ///
49 /// This type represents a parcel that is owned by Rust code.
50 #[repr(transparent)]
51 pub struct Parcel {
52 ptr: NonNull<sys::AParcel>,
53 }
54
55 /// # Safety
56 ///
57 /// This type guarantees that it owns the AParcel and that all access to
58 /// the AParcel happens through the Parcel, so it is ok to send across
59 /// threads.
60 unsafe impl Send for Parcel {}
61
62 /// Container for a message (data and object references) that can be sent
63 /// through Binder.
64 ///
65 /// This object is a borrowed variant of [`Parcel`]. It is a separate type from
66 /// `&mut Parcel` because it is not valid to `mem::swap` two parcels.
67 #[repr(transparent)]
68 pub struct BorrowedParcel<'a> {
69 ptr: NonNull<sys::AParcel>,
70 _lifetime: PhantomData<&'a mut Parcel>,
71 }
72
73 impl Parcel {
74 /// Create a new empty `Parcel`.
new() -> Parcel75 pub fn new() -> Parcel {
76 let ptr = unsafe {
77 // Safety: If `AParcel_create` succeeds, it always returns
78 // a valid pointer. If it fails, the process will crash.
79 sys::AParcel_create()
80 };
81 Self { ptr: NonNull::new(ptr).expect("AParcel_create returned null pointer") }
82 }
83
84 /// Create an owned reference to a parcel object from a raw pointer.
85 ///
86 /// # Safety
87 ///
88 /// This constructor is safe if the raw pointer parameter is either null
89 /// (resulting in `None`), or a valid pointer to an `AParcel` object. The
90 /// parcel object must be owned by the caller prior to this call, as this
91 /// constructor takes ownership of the parcel and will destroy it on drop.
92 ///
93 /// Additionally, the caller must guarantee that it is valid to take
94 /// ownership of the AParcel object. All future access to the AParcel
95 /// must happen through this `Parcel`.
96 ///
97 /// Because `Parcel` implements `Send`, the pointer must never point to any
98 /// thread-local data, e.g., a variable on the stack, either directly or
99 /// indirectly.
from_raw(ptr: *mut sys::AParcel) -> Option<Parcel>100 pub unsafe fn from_raw(ptr: *mut sys::AParcel) -> Option<Parcel> {
101 NonNull::new(ptr).map(|ptr| Self { ptr })
102 }
103
104 /// Consume the parcel, transferring ownership to the caller.
into_raw(self) -> *mut sys::AParcel105 pub(crate) fn into_raw(self) -> *mut sys::AParcel {
106 let ptr = self.ptr.as_ptr();
107 let _ = ManuallyDrop::new(self);
108 ptr
109 }
110
111 /// Get a borrowed view into the contents of this `Parcel`.
borrowed(&mut self) -> BorrowedParcel<'_>112 pub fn borrowed(&mut self) -> BorrowedParcel<'_> {
113 // Safety: The raw pointer is a valid pointer to an AParcel, and the
114 // lifetime of the returned `BorrowedParcel` is tied to `self`, so the
115 // borrow checker will ensure that the `AParcel` can only be accessed
116 // via the `BorrowParcel` until it goes out of scope.
117 BorrowedParcel { ptr: self.ptr, _lifetime: PhantomData }
118 }
119
120 /// Get an immutable borrowed view into the contents of this `Parcel`.
borrowed_ref(&self) -> &BorrowedParcel<'_>121 pub fn borrowed_ref(&self) -> &BorrowedParcel<'_> {
122 // Safety: Parcel and BorrowedParcel are both represented in the same
123 // way as a NonNull<sys::AParcel> due to their use of repr(transparent),
124 // so casting references as done here is valid.
125 unsafe { &*(self as *const Parcel as *const BorrowedParcel<'_>) }
126 }
127 }
128
129 impl Default for Parcel {
default() -> Self130 fn default() -> Self {
131 Self::new()
132 }
133 }
134
135 impl Clone for Parcel {
clone(&self) -> Self136 fn clone(&self) -> Self {
137 let mut new_parcel = Self::new();
138 new_parcel
139 .borrowed()
140 .append_all_from(self.borrowed_ref())
141 .expect("Failed to append from Parcel");
142 new_parcel
143 }
144 }
145
146 impl<'a> BorrowedParcel<'a> {
147 /// Create a borrowed reference to a parcel object from a raw pointer.
148 ///
149 /// # Safety
150 ///
151 /// This constructor is safe if the raw pointer parameter is either null
152 /// (resulting in `None`), or a valid pointer to an `AParcel` object.
153 ///
154 /// Since the raw pointer is not restricted by any lifetime, the lifetime on
155 /// the returned `BorrowedParcel` object can be chosen arbitrarily by the
156 /// caller. The caller must ensure it is valid to mutably borrow the AParcel
157 /// for the duration of the lifetime that the caller chooses. Note that
158 /// since this is a mutable borrow, it must have exclusive access to the
159 /// AParcel for the duration of the borrow.
from_raw(ptr: *mut sys::AParcel) -> Option<BorrowedParcel<'a>>160 pub unsafe fn from_raw(ptr: *mut sys::AParcel) -> Option<BorrowedParcel<'a>> {
161 Some(Self { ptr: NonNull::new(ptr)?, _lifetime: PhantomData })
162 }
163
164 /// Get a sub-reference to this reference to the parcel.
reborrow(&mut self) -> BorrowedParcel<'_>165 pub fn reborrow(&mut self) -> BorrowedParcel<'_> {
166 // Safety: The raw pointer is a valid pointer to an AParcel, and the
167 // lifetime of the returned `BorrowedParcel` is tied to `self`, so the
168 // borrow checker will ensure that the `AParcel` can only be accessed
169 // via the `BorrowParcel` until it goes out of scope.
170 BorrowedParcel { ptr: self.ptr, _lifetime: PhantomData }
171 }
172 }
173
174 /// # Safety
175 ///
176 /// The `Parcel` constructors guarantee that a `Parcel` object will always
177 /// contain a valid pointer to an `AParcel`.
178 unsafe impl AsNative<sys::AParcel> for Parcel {
as_native(&self) -> *const sys::AParcel179 fn as_native(&self) -> *const sys::AParcel {
180 self.ptr.as_ptr()
181 }
182
as_native_mut(&mut self) -> *mut sys::AParcel183 fn as_native_mut(&mut self) -> *mut sys::AParcel {
184 self.ptr.as_ptr()
185 }
186 }
187
188 /// # Safety
189 ///
190 /// The `BorrowedParcel` constructors guarantee that a `BorrowedParcel` object
191 /// will always contain a valid pointer to an `AParcel`.
192 unsafe impl<'a> AsNative<sys::AParcel> for BorrowedParcel<'a> {
as_native(&self) -> *const sys::AParcel193 fn as_native(&self) -> *const sys::AParcel {
194 self.ptr.as_ptr()
195 }
196
as_native_mut(&mut self) -> *mut sys::AParcel197 fn as_native_mut(&mut self) -> *mut sys::AParcel {
198 self.ptr.as_ptr()
199 }
200 }
201
202 // Data serialization methods
203 impl<'a> BorrowedParcel<'a> {
204 /// Data written to parcelable is zero'd before being deleted or reallocated.
mark_sensitive(&mut self)205 pub fn mark_sensitive(&mut self) {
206 unsafe {
207 // Safety: guaranteed to have a parcel object, and this method never fails
208 sys::AParcel_markSensitive(self.as_native())
209 }
210 }
211
212 /// Write a type that implements [`Serialize`] to the parcel.
write<S: Serialize + ?Sized>(&mut self, parcelable: &S) -> Result<()>213 pub fn write<S: Serialize + ?Sized>(&mut self, parcelable: &S) -> Result<()> {
214 parcelable.serialize(self)
215 }
216
217 /// Writes the length of a slice to the parcel.
218 ///
219 /// This is used in AIDL-generated client side code to indicate the
220 /// allocated space for an output array parameter.
write_slice_size<T>(&mut self, slice: Option<&[T]>) -> Result<()>221 pub fn write_slice_size<T>(&mut self, slice: Option<&[T]>) -> Result<()> {
222 if let Some(slice) = slice {
223 let len: i32 = slice.len().try_into().or(Err(StatusCode::BAD_VALUE))?;
224 self.write(&len)
225 } else {
226 self.write(&-1i32)
227 }
228 }
229
230 /// Perform a series of writes to the parcel, prepended with the length
231 /// (in bytes) of the written data.
232 ///
233 /// The length `0i32` will be written to the parcel first, followed by the
234 /// writes performed by the callback. The initial length will then be
235 /// updated to the length of all data written by the callback, plus the
236 /// size of the length elemement itself (4 bytes).
237 ///
238 /// # Examples
239 ///
240 /// After the following call:
241 ///
242 /// ```
243 /// # use binder::{Binder, Interface, Parcel};
244 /// # let mut parcel = Parcel::new();
245 /// parcel.sized_write(|subparcel| {
246 /// subparcel.write(&1u32)?;
247 /// subparcel.write(&2u32)?;
248 /// subparcel.write(&3u32)
249 /// });
250 /// ```
251 ///
252 /// `parcel` will contain the following:
253 ///
254 /// ```ignore
255 /// [16i32, 1u32, 2u32, 3u32]
256 /// ```
sized_write<F>(&mut self, f: F) -> Result<()> where for<'b> F: FnOnce(&'b mut WritableSubParcel<'b>) -> Result<()>,257 pub fn sized_write<F>(&mut self, f: F) -> Result<()>
258 where
259 for<'b> F: FnOnce(&'b mut WritableSubParcel<'b>) -> Result<()>,
260 {
261 let start = self.get_data_position();
262 self.write(&0i32)?;
263 {
264 let mut subparcel = WritableSubParcel(self.reborrow());
265 f(&mut subparcel)?;
266 }
267 let end = self.get_data_position();
268 unsafe {
269 self.set_data_position(start)?;
270 }
271 assert!(end >= start);
272 self.write(&(end - start))?;
273 unsafe {
274 self.set_data_position(end)?;
275 }
276 Ok(())
277 }
278
279 /// Returns the current position in the parcel data.
get_data_position(&self) -> i32280 pub fn get_data_position(&self) -> i32 {
281 unsafe {
282 // Safety: `BorrowedParcel` always contains a valid pointer to an
283 // `AParcel`, and this call is otherwise safe.
284 sys::AParcel_getDataPosition(self.as_native())
285 }
286 }
287
288 /// Returns the total size of the parcel.
get_data_size(&self) -> i32289 pub fn get_data_size(&self) -> i32 {
290 unsafe {
291 // Safety: `BorrowedParcel` always contains a valid pointer to an
292 // `AParcel`, and this call is otherwise safe.
293 sys::AParcel_getDataSize(self.as_native())
294 }
295 }
296
297 /// Move the current read/write position in the parcel.
298 ///
299 /// # Safety
300 ///
301 /// This method is safe if `pos` is less than the current size of the parcel
302 /// data buffer. Otherwise, we are relying on correct bounds checking in the
303 /// Parcel C++ code on every subsequent read or write to this parcel. If all
304 /// accesses are bounds checked, this call is still safe, but we can't rely
305 /// on that.
set_data_position(&self, pos: i32) -> Result<()>306 pub unsafe fn set_data_position(&self, pos: i32) -> Result<()> {
307 status_result(sys::AParcel_setDataPosition(self.as_native(), pos))
308 }
309
310 /// Append a subset of another parcel.
311 ///
312 /// This appends `size` bytes of data from `other` starting at offset
313 /// `start` to the current parcel, or returns an error if not possible.
append_from( &mut self, other: &impl AsNative<sys::AParcel>, start: i32, size: i32, ) -> Result<()>314 pub fn append_from(
315 &mut self,
316 other: &impl AsNative<sys::AParcel>,
317 start: i32,
318 size: i32,
319 ) -> Result<()> {
320 let status = unsafe {
321 // Safety: `Parcel::appendFrom` from C++ checks that `start`
322 // and `size` are in bounds, and returns an error otherwise.
323 // Both `self` and `other` always contain valid pointers.
324 sys::AParcel_appendFrom(other.as_native(), self.as_native_mut(), start, size)
325 };
326 status_result(status)
327 }
328
329 /// Append the contents of another parcel.
append_all_from(&mut self, other: &impl AsNative<sys::AParcel>) -> Result<()>330 pub fn append_all_from(&mut self, other: &impl AsNative<sys::AParcel>) -> Result<()> {
331 // Safety: `BorrowedParcel` always contains a valid pointer to an
332 // `AParcel`, and this call is otherwise safe.
333 let size = unsafe { sys::AParcel_getDataSize(other.as_native()) };
334 self.append_from(other, 0, size)
335 }
336 }
337
338 /// A segment of a writable parcel, used for [`BorrowedParcel::sized_write`].
339 pub struct WritableSubParcel<'a>(BorrowedParcel<'a>);
340
341 impl<'a> WritableSubParcel<'a> {
342 /// Write a type that implements [`Serialize`] to the sub-parcel.
write<S: Serialize + ?Sized>(&mut self, parcelable: &S) -> Result<()>343 pub fn write<S: Serialize + ?Sized>(&mut self, parcelable: &S) -> Result<()> {
344 parcelable.serialize(&mut self.0)
345 }
346 }
347
348 impl Parcel {
349 /// Data written to parcelable is zero'd before being deleted or reallocated.
mark_sensitive(&mut self)350 pub fn mark_sensitive(&mut self) {
351 self.borrowed().mark_sensitive()
352 }
353
354 /// Write a type that implements [`Serialize`] to the parcel.
write<S: Serialize + ?Sized>(&mut self, parcelable: &S) -> Result<()>355 pub fn write<S: Serialize + ?Sized>(&mut self, parcelable: &S) -> Result<()> {
356 self.borrowed().write(parcelable)
357 }
358
359 /// Writes the length of a slice to the parcel.
360 ///
361 /// This is used in AIDL-generated client side code to indicate the
362 /// allocated space for an output array parameter.
write_slice_size<T>(&mut self, slice: Option<&[T]>) -> Result<()>363 pub fn write_slice_size<T>(&mut self, slice: Option<&[T]>) -> Result<()> {
364 self.borrowed().write_slice_size(slice)
365 }
366
367 /// Perform a series of writes to the parcel, prepended with the length
368 /// (in bytes) of the written data.
369 ///
370 /// The length `0i32` will be written to the parcel first, followed by the
371 /// writes performed by the callback. The initial length will then be
372 /// updated to the length of all data written by the callback, plus the
373 /// size of the length elemement itself (4 bytes).
374 ///
375 /// # Examples
376 ///
377 /// After the following call:
378 ///
379 /// ```
380 /// # use binder::{Binder, Interface, Parcel};
381 /// # let mut parcel = Parcel::new();
382 /// parcel.sized_write(|subparcel| {
383 /// subparcel.write(&1u32)?;
384 /// subparcel.write(&2u32)?;
385 /// subparcel.write(&3u32)
386 /// });
387 /// ```
388 ///
389 /// `parcel` will contain the following:
390 ///
391 /// ```ignore
392 /// [16i32, 1u32, 2u32, 3u32]
393 /// ```
sized_write<F>(&mut self, f: F) -> Result<()> where for<'b> F: FnOnce(&'b mut WritableSubParcel<'b>) -> Result<()>,394 pub fn sized_write<F>(&mut self, f: F) -> Result<()>
395 where
396 for<'b> F: FnOnce(&'b mut WritableSubParcel<'b>) -> Result<()>,
397 {
398 self.borrowed().sized_write(f)
399 }
400
401 /// Returns the current position in the parcel data.
get_data_position(&self) -> i32402 pub fn get_data_position(&self) -> i32 {
403 self.borrowed_ref().get_data_position()
404 }
405
406 /// Returns the total size of the parcel.
get_data_size(&self) -> i32407 pub fn get_data_size(&self) -> i32 {
408 self.borrowed_ref().get_data_size()
409 }
410
411 /// Move the current read/write position in the parcel.
412 ///
413 /// # Safety
414 ///
415 /// This method is safe if `pos` is less than the current size of the parcel
416 /// data buffer. Otherwise, we are relying on correct bounds checking in the
417 /// Parcel C++ code on every subsequent read or write to this parcel. If all
418 /// accesses are bounds checked, this call is still safe, but we can't rely
419 /// on that.
set_data_position(&self, pos: i32) -> Result<()>420 pub unsafe fn set_data_position(&self, pos: i32) -> Result<()> {
421 self.borrowed_ref().set_data_position(pos)
422 }
423
424 /// Append a subset of another parcel.
425 ///
426 /// This appends `size` bytes of data from `other` starting at offset
427 /// `start` to the current parcel, or returns an error if not possible.
append_from( &mut self, other: &impl AsNative<sys::AParcel>, start: i32, size: i32, ) -> Result<()>428 pub fn append_from(
429 &mut self,
430 other: &impl AsNative<sys::AParcel>,
431 start: i32,
432 size: i32,
433 ) -> Result<()> {
434 self.borrowed().append_from(other, start, size)
435 }
436
437 /// Append the contents of another parcel.
append_all_from(&mut self, other: &impl AsNative<sys::AParcel>) -> Result<()>438 pub fn append_all_from(&mut self, other: &impl AsNative<sys::AParcel>) -> Result<()> {
439 self.borrowed().append_all_from(other)
440 }
441 }
442
443 // Data deserialization methods
444 impl<'a> BorrowedParcel<'a> {
445 /// Attempt to read a type that implements [`Deserialize`] from this parcel.
read<D: Deserialize>(&self) -> Result<D>446 pub fn read<D: Deserialize>(&self) -> Result<D> {
447 D::deserialize(self)
448 }
449
450 /// Attempt to read a type that implements [`Deserialize`] from this parcel
451 /// onto an existing value. This operation will overwrite the old value
452 /// partially or completely, depending on how much data is available.
read_onto<D: Deserialize>(&self, x: &mut D) -> Result<()>453 pub fn read_onto<D: Deserialize>(&self, x: &mut D) -> Result<()> {
454 x.deserialize_from(self)
455 }
456
457 /// Safely read a sized parcelable.
458 ///
459 /// Read the size of a parcelable, compute the end position
460 /// of that parcelable, then build a sized readable sub-parcel
461 /// and call a closure with the sub-parcel as its parameter.
462 /// The closure can keep reading data from the sub-parcel
463 /// until it runs out of input data. The closure is responsible
464 /// for calling [`ReadableSubParcel::has_more_data`] to check for
465 /// more data before every read, at least until Rust generators
466 /// are stabilized.
467 /// After the closure returns, skip to the end of the current
468 /// parcelable regardless of how much the closure has read.
469 ///
470 /// # Examples
471 ///
472 /// ```no_run
473 /// let mut parcelable = Default::default();
474 /// parcel.sized_read(|subparcel| {
475 /// if subparcel.has_more_data() {
476 /// parcelable.a = subparcel.read()?;
477 /// }
478 /// if subparcel.has_more_data() {
479 /// parcelable.b = subparcel.read()?;
480 /// }
481 /// Ok(())
482 /// });
483 /// ```
484 ///
sized_read<F>(&self, f: F) -> Result<()> where for<'b> F: FnOnce(ReadableSubParcel<'b>) -> Result<()>,485 pub fn sized_read<F>(&self, f: F) -> Result<()>
486 where
487 for<'b> F: FnOnce(ReadableSubParcel<'b>) -> Result<()>,
488 {
489 let start = self.get_data_position();
490 let parcelable_size: i32 = self.read()?;
491 if parcelable_size < 4 {
492 return Err(StatusCode::BAD_VALUE);
493 }
494
495 let end = start.checked_add(parcelable_size).ok_or(StatusCode::BAD_VALUE)?;
496 if end > self.get_data_size() {
497 return Err(StatusCode::NOT_ENOUGH_DATA);
498 }
499
500 let subparcel = ReadableSubParcel {
501 parcel: BorrowedParcel { ptr: self.ptr, _lifetime: PhantomData },
502 end_position: end,
503 };
504 f(subparcel)?;
505
506 // Advance the data position to the actual end,
507 // in case the closure read less data than was available
508 unsafe {
509 self.set_data_position(end)?;
510 }
511
512 Ok(())
513 }
514
515 /// Read a vector size from the parcel and resize the given output vector to
516 /// be correctly sized for that amount of data.
517 ///
518 /// This method is used in AIDL-generated server side code for methods that
519 /// take a mutable slice reference parameter.
resize_out_vec<D: Default + Deserialize>(&self, out_vec: &mut Vec<D>) -> Result<()>520 pub fn resize_out_vec<D: Default + Deserialize>(&self, out_vec: &mut Vec<D>) -> Result<()> {
521 let len: i32 = self.read()?;
522
523 if len < 0 {
524 return Err(StatusCode::UNEXPECTED_NULL);
525 }
526
527 // usize in Rust may be 16-bit, so i32 may not fit
528 let len = len.try_into().unwrap();
529 out_vec.resize_with(len, Default::default);
530
531 Ok(())
532 }
533
534 /// Read a vector size from the parcel and either create a correctly sized
535 /// vector for that amount of data or set the output parameter to None if
536 /// the vector should be null.
537 ///
538 /// This method is used in AIDL-generated server side code for methods that
539 /// take a mutable slice reference parameter.
resize_nullable_out_vec<D: Default + Deserialize>( &self, out_vec: &mut Option<Vec<D>>, ) -> Result<()>540 pub fn resize_nullable_out_vec<D: Default + Deserialize>(
541 &self,
542 out_vec: &mut Option<Vec<D>>,
543 ) -> Result<()> {
544 let len: i32 = self.read()?;
545
546 if len < 0 {
547 *out_vec = None;
548 } else {
549 // usize in Rust may be 16-bit, so i32 may not fit
550 let len = len.try_into().unwrap();
551 let mut vec = Vec::with_capacity(len);
552 vec.resize_with(len, Default::default);
553 *out_vec = Some(vec);
554 }
555
556 Ok(())
557 }
558 }
559
560 /// A segment of a readable parcel, used for [`Parcel::sized_read`].
561 pub struct ReadableSubParcel<'a> {
562 parcel: BorrowedParcel<'a>,
563 end_position: i32,
564 }
565
566 impl<'a> ReadableSubParcel<'a> {
567 /// Read a type that implements [`Deserialize`] from the sub-parcel.
read<D: Deserialize>(&self) -> Result<D>568 pub fn read<D: Deserialize>(&self) -> Result<D> {
569 D::deserialize(&self.parcel)
570 }
571
572 /// Check if the sub-parcel has more data to read
has_more_data(&self) -> bool573 pub fn has_more_data(&self) -> bool {
574 self.parcel.get_data_position() < self.end_position
575 }
576 }
577
578 impl Parcel {
579 /// Attempt to read a type that implements [`Deserialize`] from this parcel.
read<D: Deserialize>(&self) -> Result<D>580 pub fn read<D: Deserialize>(&self) -> Result<D> {
581 self.borrowed_ref().read()
582 }
583
584 /// Attempt to read a type that implements [`Deserialize`] from this parcel
585 /// onto an existing value. This operation will overwrite the old value
586 /// partially or completely, depending on how much data is available.
read_onto<D: Deserialize>(&self, x: &mut D) -> Result<()>587 pub fn read_onto<D: Deserialize>(&self, x: &mut D) -> Result<()> {
588 self.borrowed_ref().read_onto(x)
589 }
590
591 /// Safely read a sized parcelable.
592 ///
593 /// Read the size of a parcelable, compute the end position
594 /// of that parcelable, then build a sized readable sub-parcel
595 /// and call a closure with the sub-parcel as its parameter.
596 /// The closure can keep reading data from the sub-parcel
597 /// until it runs out of input data. The closure is responsible
598 /// for calling [`ReadableSubParcel::has_more_data`] to check for
599 /// more data before every read, at least until Rust generators
600 /// are stabilized.
601 /// After the closure returns, skip to the end of the current
602 /// parcelable regardless of how much the closure has read.
603 ///
604 /// # Examples
605 ///
606 /// ```no_run
607 /// let mut parcelable = Default::default();
608 /// parcel.sized_read(|subparcel| {
609 /// if subparcel.has_more_data() {
610 /// parcelable.a = subparcel.read()?;
611 /// }
612 /// if subparcel.has_more_data() {
613 /// parcelable.b = subparcel.read()?;
614 /// }
615 /// Ok(())
616 /// });
617 /// ```
618 ///
sized_read<F>(&self, f: F) -> Result<()> where for<'b> F: FnOnce(ReadableSubParcel<'b>) -> Result<()>,619 pub fn sized_read<F>(&self, f: F) -> Result<()>
620 where
621 for<'b> F: FnOnce(ReadableSubParcel<'b>) -> Result<()>,
622 {
623 self.borrowed_ref().sized_read(f)
624 }
625
626 /// Read a vector size from the parcel and resize the given output vector to
627 /// be correctly sized for that amount of data.
628 ///
629 /// This method is used in AIDL-generated server side code for methods that
630 /// take a mutable slice reference parameter.
resize_out_vec<D: Default + Deserialize>(&self, out_vec: &mut Vec<D>) -> Result<()>631 pub fn resize_out_vec<D: Default + Deserialize>(&self, out_vec: &mut Vec<D>) -> Result<()> {
632 self.borrowed_ref().resize_out_vec(out_vec)
633 }
634
635 /// Read a vector size from the parcel and either create a correctly sized
636 /// vector for that amount of data or set the output parameter to None if
637 /// the vector should be null.
638 ///
639 /// This method is used in AIDL-generated server side code for methods that
640 /// take a mutable slice reference parameter.
resize_nullable_out_vec<D: Default + Deserialize>( &self, out_vec: &mut Option<Vec<D>>, ) -> Result<()>641 pub fn resize_nullable_out_vec<D: Default + Deserialize>(
642 &self,
643 out_vec: &mut Option<Vec<D>>,
644 ) -> Result<()> {
645 self.borrowed_ref().resize_nullable_out_vec(out_vec)
646 }
647 }
648
649 // Internal APIs
650 impl<'a> BorrowedParcel<'a> {
write_binder(&mut self, binder: Option<&SpIBinder>) -> Result<()>651 pub(crate) fn write_binder(&mut self, binder: Option<&SpIBinder>) -> Result<()> {
652 unsafe {
653 // Safety: `BorrowedParcel` always contains a valid pointer to an
654 // `AParcel`. `AsNative` for `Option<SpIBinder`> will either return
655 // null or a valid pointer to an `AIBinder`, both of which are
656 // valid, safe inputs to `AParcel_writeStrongBinder`.
657 //
658 // This call does not take ownership of the binder. However, it does
659 // require a mutable pointer, which we cannot extract from an
660 // immutable reference, so we clone the binder, incrementing the
661 // refcount before the call. The refcount will be immediately
662 // decremented when this temporary is dropped.
663 status_result(sys::AParcel_writeStrongBinder(
664 self.as_native_mut(),
665 binder.cloned().as_native_mut(),
666 ))
667 }
668 }
669
read_binder(&self) -> Result<Option<SpIBinder>>670 pub(crate) fn read_binder(&self) -> Result<Option<SpIBinder>> {
671 let mut binder = ptr::null_mut();
672 let status = unsafe {
673 // Safety: `BorrowedParcel` always contains a valid pointer to an
674 // `AParcel`. We pass a valid, mutable out pointer to the `binder`
675 // parameter. After this call, `binder` will be either null or a
676 // valid pointer to an `AIBinder` owned by the caller.
677 sys::AParcel_readStrongBinder(self.as_native(), &mut binder)
678 };
679
680 status_result(status)?;
681
682 Ok(unsafe {
683 // Safety: `binder` is either null or a valid, owned pointer at this
684 // point, so can be safely passed to `SpIBinder::from_raw`.
685 SpIBinder::from_raw(binder)
686 })
687 }
688 }
689
690 impl Drop for Parcel {
drop(&mut self)691 fn drop(&mut self) {
692 // Run the C++ Parcel complete object destructor
693 unsafe {
694 // Safety: `Parcel` always contains a valid pointer to an
695 // `AParcel`. Since we own the parcel, we can safely delete it
696 // here.
697 sys::AParcel_delete(self.ptr.as_ptr())
698 }
699 }
700 }
701
702 impl fmt::Debug for Parcel {
fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result703 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
704 f.debug_struct("Parcel").finish()
705 }
706 }
707
708 impl<'a> fmt::Debug for BorrowedParcel<'a> {
fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result709 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
710 f.debug_struct("BorrowedParcel").finish()
711 }
712 }
713
714 #[test]
test_read_write()715 fn test_read_write() {
716 let mut parcel = Parcel::new();
717 let start = parcel.get_data_position();
718
719 assert_eq!(parcel.read::<bool>(), Err(StatusCode::NOT_ENOUGH_DATA));
720 assert_eq!(parcel.read::<i8>(), Err(StatusCode::NOT_ENOUGH_DATA));
721 assert_eq!(parcel.read::<u16>(), Err(StatusCode::NOT_ENOUGH_DATA));
722 assert_eq!(parcel.read::<i32>(), Err(StatusCode::NOT_ENOUGH_DATA));
723 assert_eq!(parcel.read::<u32>(), Err(StatusCode::NOT_ENOUGH_DATA));
724 assert_eq!(parcel.read::<i64>(), Err(StatusCode::NOT_ENOUGH_DATA));
725 assert_eq!(parcel.read::<u64>(), Err(StatusCode::NOT_ENOUGH_DATA));
726 assert_eq!(parcel.read::<f32>(), Err(StatusCode::NOT_ENOUGH_DATA));
727 assert_eq!(parcel.read::<f64>(), Err(StatusCode::NOT_ENOUGH_DATA));
728 assert_eq!(parcel.read::<Option<String>>(), Ok(None));
729 assert_eq!(parcel.read::<String>(), Err(StatusCode::UNEXPECTED_NULL));
730
731 assert_eq!(parcel.borrowed_ref().read_binder().err(), Some(StatusCode::BAD_TYPE));
732
733 parcel.write(&1i32).unwrap();
734
735 unsafe {
736 parcel.set_data_position(start).unwrap();
737 }
738
739 let i: i32 = parcel.read().unwrap();
740 assert_eq!(i, 1i32);
741 }
742
743 #[test]
744 #[allow(clippy::float_cmp)]
test_read_data()745 fn test_read_data() {
746 let mut parcel = Parcel::new();
747 let str_start = parcel.get_data_position();
748
749 parcel.write(&b"Hello, Binder!\0"[..]).unwrap();
750 // Skip over string length
751 unsafe {
752 assert!(parcel.set_data_position(str_start).is_ok());
753 }
754 assert_eq!(parcel.read::<i32>().unwrap(), 15);
755 let start = parcel.get_data_position();
756
757 assert!(parcel.read::<bool>().unwrap());
758
759 unsafe {
760 assert!(parcel.set_data_position(start).is_ok());
761 }
762
763 assert_eq!(parcel.read::<i8>().unwrap(), 72i8);
764
765 unsafe {
766 assert!(parcel.set_data_position(start).is_ok());
767 }
768
769 assert_eq!(parcel.read::<u16>().unwrap(), 25928);
770
771 unsafe {
772 assert!(parcel.set_data_position(start).is_ok());
773 }
774
775 assert_eq!(parcel.read::<i32>().unwrap(), 1819043144);
776
777 unsafe {
778 assert!(parcel.set_data_position(start).is_ok());
779 }
780
781 assert_eq!(parcel.read::<u32>().unwrap(), 1819043144);
782
783 unsafe {
784 assert!(parcel.set_data_position(start).is_ok());
785 }
786
787 assert_eq!(parcel.read::<i64>().unwrap(), 4764857262830019912);
788
789 unsafe {
790 assert!(parcel.set_data_position(start).is_ok());
791 }
792
793 assert_eq!(parcel.read::<u64>().unwrap(), 4764857262830019912);
794
795 unsafe {
796 assert!(parcel.set_data_position(start).is_ok());
797 }
798
799 assert_eq!(parcel.read::<f32>().unwrap(), 1143139100000000000000000000.0);
800 assert_eq!(parcel.read::<f32>().unwrap(), 40.043392);
801
802 unsafe {
803 assert!(parcel.set_data_position(start).is_ok());
804 }
805
806 assert_eq!(parcel.read::<f64>().unwrap(), 34732488246.197815);
807
808 // Skip back to before the string length
809 unsafe {
810 assert!(parcel.set_data_position(str_start).is_ok());
811 }
812
813 assert_eq!(parcel.read::<Vec<u8>>().unwrap(), b"Hello, Binder!\0");
814 }
815
816 #[test]
test_utf8_utf16_conversions()817 fn test_utf8_utf16_conversions() {
818 let mut parcel = Parcel::new();
819 let start = parcel.get_data_position();
820
821 assert!(parcel.write("Hello, Binder!").is_ok());
822 unsafe {
823 assert!(parcel.set_data_position(start).is_ok());
824 }
825 assert_eq!(parcel.read::<Option<String>>().unwrap().unwrap(), "Hello, Binder!",);
826 unsafe {
827 assert!(parcel.set_data_position(start).is_ok());
828 }
829
830 assert!(parcel.write("Embedded null \0 inside a string").is_ok());
831 unsafe {
832 assert!(parcel.set_data_position(start).is_ok());
833 }
834 assert_eq!(
835 parcel.read::<Option<String>>().unwrap().unwrap(),
836 "Embedded null \0 inside a string",
837 );
838 unsafe {
839 assert!(parcel.set_data_position(start).is_ok());
840 }
841
842 assert!(parcel.write(&["str1", "str2", "str3"][..]).is_ok());
843 assert!(parcel
844 .write(&[String::from("str4"), String::from("str5"), String::from("str6"),][..])
845 .is_ok());
846
847 let s1 = "Hello, Binder!";
848 let s2 = "This is a utf8 string.";
849 let s3 = "Some more text here.";
850
851 assert!(parcel.write(&[s1, s2, s3][..]).is_ok());
852 unsafe {
853 assert!(parcel.set_data_position(start).is_ok());
854 }
855
856 assert_eq!(parcel.read::<Vec<String>>().unwrap(), ["str1", "str2", "str3"]);
857 assert_eq!(parcel.read::<Vec<String>>().unwrap(), ["str4", "str5", "str6"]);
858 assert_eq!(parcel.read::<Vec<String>>().unwrap(), [s1, s2, s3]);
859 }
860
861 #[test]
test_sized_write()862 fn test_sized_write() {
863 let mut parcel = Parcel::new();
864 let start = parcel.get_data_position();
865
866 let arr = [1i32, 2i32, 3i32];
867
868 parcel
869 .sized_write(|subparcel| subparcel.write(&arr[..]))
870 .expect("Could not perform sized write");
871
872 // i32 sub-parcel length + i32 array length + 3 i32 elements
873 let expected_len = 20i32;
874
875 assert_eq!(parcel.get_data_position(), start + expected_len);
876
877 unsafe {
878 parcel.set_data_position(start).unwrap();
879 }
880
881 assert_eq!(expected_len, parcel.read().unwrap(),);
882
883 assert_eq!(parcel.read::<Vec<i32>>().unwrap(), &arr,);
884 }
885
886 #[test]
test_append_from()887 fn test_append_from() {
888 let mut parcel1 = Parcel::new();
889 parcel1.write(&42i32).expect("Could not perform write");
890
891 let mut parcel2 = Parcel::new();
892 assert_eq!(Ok(()), parcel2.append_all_from(&parcel1));
893 assert_eq!(4, parcel2.get_data_size());
894 assert_eq!(Ok(()), parcel2.append_all_from(&parcel1));
895 assert_eq!(8, parcel2.get_data_size());
896 unsafe {
897 parcel2.set_data_position(0).unwrap();
898 }
899 assert_eq!(Ok(42), parcel2.read::<i32>());
900 assert_eq!(Ok(42), parcel2.read::<i32>());
901
902 let mut parcel2 = Parcel::new();
903 assert_eq!(Ok(()), parcel2.append_from(&parcel1, 0, 2));
904 assert_eq!(Ok(()), parcel2.append_from(&parcel1, 2, 2));
905 assert_eq!(4, parcel2.get_data_size());
906 unsafe {
907 parcel2.set_data_position(0).unwrap();
908 }
909 assert_eq!(Ok(42), parcel2.read::<i32>());
910
911 let mut parcel2 = Parcel::new();
912 assert_eq!(Ok(()), parcel2.append_from(&parcel1, 0, 2));
913 assert_eq!(2, parcel2.get_data_size());
914 unsafe {
915 parcel2.set_data_position(0).unwrap();
916 }
917 assert_eq!(Err(StatusCode::NOT_ENOUGH_DATA), parcel2.read::<i32>());
918
919 let mut parcel2 = Parcel::new();
920 assert_eq!(Err(StatusCode::BAD_VALUE), parcel2.append_from(&parcel1, 4, 2));
921 assert_eq!(Err(StatusCode::BAD_VALUE), parcel2.append_from(&parcel1, 2, 4));
922 assert_eq!(Err(StatusCode::BAD_VALUE), parcel2.append_from(&parcel1, -1, 4));
923 assert_eq!(Err(StatusCode::BAD_VALUE), parcel2.append_from(&parcel1, 2, -1));
924 }
925