blob: e4c568eab2d174f8d075a2bc67bf37b4e462cd83 [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//! Container for messages that are sent via binder.
18
19use crate::binder::AsNative;
20use crate::error::{status_result, Result, StatusCode};
21use crate::proxy::SpIBinder;
22use crate::sys;
23
24use std::convert::TryInto;
Matthew Maurere268a9f2022-07-26 09:31:30 -070025use std::fmt;
Alice Ryhl268458c2021-09-15 12:56:10 +000026use std::marker::PhantomData;
Stephen Crane2a3c2502020-06-16 17:48:35 -070027use std::mem::ManuallyDrop;
Alice Ryhl8618c482021-11-09 15:35:35 +000028use std::ptr::{self, NonNull};
Stephen Crane2a3c2502020-06-16 17:48:35 -070029
30mod file_descriptor;
31mod parcelable;
Andrei Homescuea406212021-09-03 02:55:00 +000032mod parcelable_holder;
Stephen Crane2a3c2502020-06-16 17:48:35 -070033
34pub use self::file_descriptor::ParcelFileDescriptor;
35pub use self::parcelable::{
Matthew Maurere268a9f2022-07-26 09:31:30 -070036 Deserialize, DeserializeArray, DeserializeOption, Parcelable, Serialize, SerializeArray,
37 SerializeOption, NON_NULL_PARCELABLE_FLAG, NULL_PARCELABLE_FLAG,
Stephen Crane2a3c2502020-06-16 17:48:35 -070038};
Andrei Homescuea406212021-09-03 02:55:00 +000039pub use self::parcelable_holder::{ParcelableHolder, ParcelableMetadata};
Stephen Crane2a3c2502020-06-16 17:48:35 -070040
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.
Alice Ryhl8618c482021-11-09 15:35:35 +000048///
49/// This type represents a parcel that is owned by Rust code.
50#[repr(transparent)]
51pub struct Parcel {
52 ptr: NonNull<sys::AParcel>,
Alice Ryhl268458c2021-09-15 12:56:10 +000053}
54
55/// # Safety
56///
57/// This type guarantees that it owns the AParcel and that all access to
Alice Ryhl8618c482021-11-09 15:35:35 +000058/// the AParcel happens through the Parcel, so it is ok to send across
Alice Ryhl268458c2021-09-15 12:56:10 +000059/// threads.
Alice Ryhl8618c482021-11-09 15:35:35 +000060unsafe impl Send for Parcel {}
Alice Ryhl268458c2021-09-15 12:56:10 +000061
Alice Ryhl8618c482021-11-09 15:35:35 +000062/// 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)]
Alice Ryhl268458c2021-09-15 12:56:10 +000068pub struct BorrowedParcel<'a> {
Alice Ryhl8618c482021-11-09 15:35:35 +000069 ptr: NonNull<sys::AParcel>,
Alice Ryhl268458c2021-09-15 12:56:10 +000070 _lifetime: PhantomData<&'a mut Parcel>,
71}
72
Alice Ryhl8618c482021-11-09 15:35:35 +000073impl Parcel {
74 /// Create a new empty `Parcel`.
75 pub fn new() -> Parcel {
Alice Ryhl268458c2021-09-15 12:56:10 +000076 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 };
Matthew Maurere268a9f2022-07-26 09:31:30 -070081 Self { ptr: NonNull::new(ptr).expect("AParcel_create returned null pointer") }
Alice Ryhl05f5a2c2021-09-15 12:56:10 +000082 }
83
Alice Ryhl268458c2021-09-15 12:56:10 +000084 /// 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
Alice Ryhl8618c482021-11-09 15:35:35 +000095 /// must happen through this `Parcel`.
Alice Ryhl268458c2021-09-15 12:56:10 +000096 ///
Alice Ryhl8618c482021-11-09 15:35:35 +000097 /// 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.
100 pub unsafe fn from_raw(ptr: *mut sys::AParcel) -> Option<Parcel> {
101 NonNull::new(ptr).map(|ptr| Self { ptr })
Alice Ryhl268458c2021-09-15 12:56:10 +0000102 }
103
104 /// Consume the parcel, transferring ownership to the caller.
105 pub(crate) fn into_raw(self) -> *mut sys::AParcel {
Alice Ryhl8618c482021-11-09 15:35:35 +0000106 let ptr = self.ptr.as_ptr();
Alice Ryhl268458c2021-09-15 12:56:10 +0000107 let _ = ManuallyDrop::new(self);
108 ptr
109 }
110
Alice Ryhl268458c2021-09-15 12:56:10 +0000111 /// Get a borrowed view into the contents of this `Parcel`.
112 pub fn borrowed(&mut self) -> BorrowedParcel<'_> {
Alice Ryhl8618c482021-11-09 15:35:35 +0000113 // 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.
Matthew Maurere268a9f2022-07-26 09:31:30 -0700117 BorrowedParcel { ptr: self.ptr, _lifetime: PhantomData }
Alice Ryhl268458c2021-09-15 12:56:10 +0000118 }
Alice Ryhl268458c2021-09-15 12:56:10 +0000119
Alice Ryhl8618c482021-11-09 15:35:35 +0000120 /// Get an immutable borrowed view into the contents of this `Parcel`.
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.
Matthew Maurere268a9f2022-07-26 09:31:30 -0700125 unsafe { &*(self as *const Parcel as *const BorrowedParcel<'_>) }
Stephen Crane2a3c2502020-06-16 17:48:35 -0700126 }
Stephen Crane2a3c2502020-06-16 17:48:35 -0700127}
128
Andrei Homescu72b799d2021-09-04 01:39:23 +0000129impl Default for Parcel {
130 fn default() -> Self {
131 Self::new()
132 }
133}
134
135impl Clone for Parcel {
136 fn clone(&self) -> Self {
137 let mut new_parcel = Self::new();
138 new_parcel
Alice Ryhl8618c482021-11-09 15:35:35 +0000139 .borrowed()
140 .append_all_from(self.borrowed_ref())
Andrei Homescu72b799d2021-09-04 01:39:23 +0000141 .expect("Failed to append from Parcel");
142 new_parcel
143 }
144}
145
Alice Ryhl8618c482021-11-09 15:35:35 +0000146impl<'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.
160 pub unsafe fn from_raw(ptr: *mut sys::AParcel) -> Option<BorrowedParcel<'a>> {
Matthew Maurere268a9f2022-07-26 09:31:30 -0700161 Some(Self { ptr: NonNull::new(ptr)?, _lifetime: PhantomData })
Alice Ryhl8618c482021-11-09 15:35:35 +0000162 }
163
164 /// Get a sub-reference to this reference to the parcel.
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.
Matthew Maurere268a9f2022-07-26 09:31:30 -0700170 BorrowedParcel { ptr: self.ptr, _lifetime: PhantomData }
Alice Ryhl8618c482021-11-09 15:35:35 +0000171 }
172}
173
174/// # Safety
175///
176/// The `Parcel` constructors guarantee that a `Parcel` object will always
177/// contain a valid pointer to an `AParcel`.
178unsafe impl AsNative<sys::AParcel> for Parcel {
179 fn as_native(&self) -> *const sys::AParcel {
180 self.ptr.as_ptr()
181 }
182
183 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`.
192unsafe impl<'a> AsNative<sys::AParcel> for BorrowedParcel<'a> {
193 fn as_native(&self) -> *const sys::AParcel {
194 self.ptr.as_ptr()
195 }
196
197 fn as_native_mut(&mut self) -> *mut sys::AParcel {
198 self.ptr.as_ptr()
199 }
200}
201
Stephen Crane2a3c2502020-06-16 17:48:35 -0700202// Data serialization methods
Alice Ryhl8618c482021-11-09 15:35:35 +0000203impl<'a> BorrowedParcel<'a> {
Steven Morelandf183fdd2020-10-27 00:12:12 +0000204 /// Data written to parcelable is zero'd before being deleted or reallocated.
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
Alice Ryhl8618c482021-11-09 15:35:35 +0000212 /// Write a type that implements [`Serialize`] to the parcel.
Stephen Crane2a3c2502020-06-16 17:48:35 -0700213 pub fn write<S: Serialize + ?Sized>(&mut self, parcelable: &S) -> Result<()> {
214 parcelable.serialize(self)
215 }
216
Alice Ryhl8618c482021-11-09 15:35:35 +0000217 /// Writes the length of a slice to the parcel.
Stephen Crane2a3c2502020-06-16 17:48:35 -0700218 ///
219 /// This is used in AIDL-generated client side code to indicate the
220 /// allocated space for an output array parameter.
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
Alice Ryhl8618c482021-11-09 15:35:35 +0000230 /// Perform a series of writes to the parcel, prepended with the length
Stephen Craneaae76382020-08-03 14:12:15 -0700231 /// (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};
Alice Ryhl8618c482021-11-09 15:35:35 +0000244 /// # let mut parcel = Parcel::new();
Stephen Craneaae76382020-08-03 14:12:15 -0700245 /// 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 /// ```
257 pub fn sized_write<F>(&mut self, f: F) -> Result<()>
Alice Ryhl8618c482021-11-09 15:35:35 +0000258 where
Matthew Maurere268a9f2022-07-26 09:31:30 -0700259 for<'b> F: FnOnce(&'b mut WritableSubParcel<'b>) -> Result<()>,
Stephen Craneaae76382020-08-03 14:12:15 -0700260 {
261 let start = self.get_data_position();
262 self.write(&0i32)?;
263 {
Alice Ryhl8618c482021-11-09 15:35:35 +0000264 let mut subparcel = WritableSubParcel(self.reborrow());
265 f(&mut subparcel)?;
Stephen Craneaae76382020-08-03 14:12:15 -0700266 }
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
Stephen Crane2a3c2502020-06-16 17:48:35 -0700279 /// Returns the current position in the parcel data.
280 pub fn get_data_position(&self) -> i32 {
281 unsafe {
Alice Ryhl8618c482021-11-09 15:35:35 +0000282 // Safety: `BorrowedParcel` always contains a valid pointer to an
283 // `AParcel`, and this call is otherwise safe.
Stephen Crane2a3c2502020-06-16 17:48:35 -0700284 sys::AParcel_getDataPosition(self.as_native())
285 }
286 }
287
Andrei Homescub0487442021-05-12 07:16:16 +0000288 /// Returns the total size of the parcel.
289 pub fn get_data_size(&self) -> i32 {
290 unsafe {
Alice Ryhl8618c482021-11-09 15:35:35 +0000291 // Safety: `BorrowedParcel` always contains a valid pointer to an
292 // `AParcel`, and this call is otherwise safe.
Andrei Homescub0487442021-05-12 07:16:16 +0000293 sys::AParcel_getDataSize(self.as_native())
294 }
295 }
296
Stephen Crane2a3c2502020-06-16 17:48:35 -0700297 /// Move the current read/write position in the parcel.
298 ///
Stephen Crane2a3c2502020-06-16 17:48:35 -0700299 /// # 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.
306 pub unsafe fn set_data_position(&self, pos: i32) -> Result<()> {
307 status_result(sys::AParcel_setDataPosition(self.as_native(), pos))
308 }
Andrei Homescu72b799d2021-09-04 01:39:23 +0000309
Alice Ryhl8618c482021-11-09 15:35:35 +0000310 /// Append a subset of another parcel.
Andrei Homescu72b799d2021-09-04 01:39:23 +0000311 ///
312 /// This appends `size` bytes of data from `other` starting at offset
Alice Ryhl8618c482021-11-09 15:35:35 +0000313 /// `start` to the current parcel, or returns an error if not possible.
Matthew Maurere268a9f2022-07-26 09:31:30 -0700314 pub fn append_from(
315 &mut self,
316 other: &impl AsNative<sys::AParcel>,
317 start: i32,
318 size: i32,
319 ) -> Result<()> {
Andrei Homescu72b799d2021-09-04 01:39:23 +0000320 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.
Matthew Maurere268a9f2022-07-26 09:31:30 -0700324 sys::AParcel_appendFrom(other.as_native(), self.as_native_mut(), start, size)
Andrei Homescu72b799d2021-09-04 01:39:23 +0000325 };
326 status_result(status)
327 }
328
Alice Ryhl8618c482021-11-09 15:35:35 +0000329 /// Append the contents of another parcel.
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)
Andrei Homescu72b799d2021-09-04 01:39:23 +0000335 }
Stephen Crane2a3c2502020-06-16 17:48:35 -0700336}
337
Alice Ryhl8618c482021-11-09 15:35:35 +0000338/// A segment of a writable parcel, used for [`BorrowedParcel::sized_write`].
339pub struct WritableSubParcel<'a>(BorrowedParcel<'a>);
Stephen Craneaae76382020-08-03 14:12:15 -0700340
341impl<'a> WritableSubParcel<'a> {
342 /// Write a type that implements [`Serialize`] to the sub-parcel.
Alice Ryhl8618c482021-11-09 15:35:35 +0000343 pub fn write<S: Serialize + ?Sized>(&mut self, parcelable: &S) -> Result<()> {
344 parcelable.serialize(&mut self.0)
345 }
346}
347
348impl Parcel {
349 /// Data written to parcelable is zero'd before being deleted or reallocated.
350 pub fn mark_sensitive(&mut self) {
351 self.borrowed().mark_sensitive()
352 }
353
354 /// Write a type that implements [`Serialize`] to the parcel.
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.
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 /// ```
394 pub fn sized_write<F>(&mut self, f: F) -> Result<()>
395 where
Matthew Maurere268a9f2022-07-26 09:31:30 -0700396 for<'b> F: FnOnce(&'b mut WritableSubParcel<'b>) -> Result<()>,
Alice Ryhl8618c482021-11-09 15:35:35 +0000397 {
398 self.borrowed().sized_write(f)
399 }
400
401 /// Returns the current position in the parcel data.
402 pub fn get_data_position(&self) -> i32 {
403 self.borrowed_ref().get_data_position()
404 }
405
406 /// Returns the total size of the parcel.
407 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.
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.
Matthew Maurere268a9f2022-07-26 09:31:30 -0700428 pub fn append_from(
429 &mut self,
430 other: &impl AsNative<sys::AParcel>,
431 start: i32,
432 size: i32,
433 ) -> Result<()> {
Alice Ryhl8618c482021-11-09 15:35:35 +0000434 self.borrowed().append_from(other, start, size)
435 }
436
437 /// Append the contents of another parcel.
438 pub fn append_all_from(&mut self, other: &impl AsNative<sys::AParcel>) -> Result<()> {
439 self.borrowed().append_all_from(other)
Stephen Craneaae76382020-08-03 14:12:15 -0700440 }
441}
442
Stephen Crane2a3c2502020-06-16 17:48:35 -0700443// Data deserialization methods
Alice Ryhl8618c482021-11-09 15:35:35 +0000444impl<'a> BorrowedParcel<'a> {
445 /// Attempt to read a type that implements [`Deserialize`] from this parcel.
Stephen Crane2a3c2502020-06-16 17:48:35 -0700446 pub fn read<D: Deserialize>(&self) -> Result<D> {
447 D::deserialize(self)
448 }
449
Alice Ryhl8618c482021-11-09 15:35:35 +0000450 /// 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.
Andrei Homescu50006152021-05-01 07:34:51 +0000453 pub fn read_onto<D: Deserialize>(&self, x: &mut D) -> Result<()> {
454 x.deserialize_from(self)
455 }
456
Andrei Homescub0487442021-05-12 07:16:16 +0000457 /// 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 ///
Alice Ryhl8618c482021-11-09 15:35:35 +0000485 pub fn sized_read<F>(&self, f: F) -> Result<()>
Andrei Homescub0487442021-05-12 07:16:16 +0000486 where
Matthew Maurere268a9f2022-07-26 09:31:30 -0700487 for<'b> F: FnOnce(ReadableSubParcel<'b>) -> Result<()>,
Andrei Homescub0487442021-05-12 07:16:16 +0000488 {
489 let start = self.get_data_position();
490 let parcelable_size: i32 = self.read()?;
Steven Moreland6d9e0772022-01-15 02:10:18 +0000491 if parcelable_size < 4 {
Andrei Homescub0487442021-05-12 07:16:16 +0000492 return Err(StatusCode::BAD_VALUE);
493 }
494
Matthew Maurere268a9f2022-07-26 09:31:30 -0700495 let end = start.checked_add(parcelable_size).ok_or(StatusCode::BAD_VALUE)?;
Andrei Homescub0487442021-05-12 07:16:16 +0000496 if end > self.get_data_size() {
497 return Err(StatusCode::NOT_ENOUGH_DATA);
498 }
499
500 let subparcel = ReadableSubParcel {
Matthew Maurere268a9f2022-07-26 09:31:30 -0700501 parcel: BorrowedParcel { ptr: self.ptr, _lifetime: PhantomData },
Andrei Homescub0487442021-05-12 07:16:16 +0000502 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
Alice Ryhl8618c482021-11-09 15:35:35 +0000515 /// Read a vector size from the parcel and resize the given output vector to
516 /// be correctly sized for that amount of data.
Stephen Crane2a3c2502020-06-16 17:48:35 -0700517 ///
518 /// This method is used in AIDL-generated server side code for methods that
519 /// take a mutable slice reference parameter.
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
Alice Ryhl8618c482021-11-09 15:35:35 +0000534 /// Read a vector size from the parcel and either create a correctly sized
Stephen Crane2a3c2502020-06-16 17:48:35 -0700535 /// 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.
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
Andrei Homescub0487442021-05-12 07:16:16 +0000560/// A segment of a readable parcel, used for [`Parcel::sized_read`].
561pub struct ReadableSubParcel<'a> {
Alice Ryhl8618c482021-11-09 15:35:35 +0000562 parcel: BorrowedParcel<'a>,
Andrei Homescub0487442021-05-12 07:16:16 +0000563 end_position: i32,
564}
565
566impl<'a> ReadableSubParcel<'a> {
567 /// Read a type that implements [`Deserialize`] from the sub-parcel.
568 pub fn read<D: Deserialize>(&self) -> Result<D> {
Alice Ryhl8618c482021-11-09 15:35:35 +0000569 D::deserialize(&self.parcel)
Andrei Homescub0487442021-05-12 07:16:16 +0000570 }
571
572 /// Check if the sub-parcel has more data to read
573 pub fn has_more_data(&self) -> bool {
574 self.parcel.get_data_position() < self.end_position
575 }
576}
577
Stephen Crane2a3c2502020-06-16 17:48:35 -0700578impl Parcel {
Alice Ryhl8618c482021-11-09 15:35:35 +0000579 /// Attempt to read a type that implements [`Deserialize`] from this parcel.
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.
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 ///
619 pub fn sized_read<F>(&self, f: F) -> Result<()>
620 where
Matthew Maurere268a9f2022-07-26 09:31:30 -0700621 for<'b> F: FnOnce(ReadableSubParcel<'b>) -> Result<()>,
Alice Ryhl8618c482021-11-09 15:35:35 +0000622 {
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.
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.
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
650impl<'a> BorrowedParcel<'a> {
Stephen Crane2a3c2502020-06-16 17:48:35 -0700651 pub(crate) fn write_binder(&mut self, binder: Option<&SpIBinder>) -> Result<()> {
652 unsafe {
Alice Ryhl8618c482021-11-09 15:35:35 +0000653 // Safety: `BorrowedParcel` always contains a valid pointer to an
Stephen Crane2a3c2502020-06-16 17:48:35 -0700654 // `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
670 pub(crate) fn read_binder(&self) -> Result<Option<SpIBinder>> {
671 let mut binder = ptr::null_mut();
672 let status = unsafe {
Alice Ryhl8618c482021-11-09 15:35:35 +0000673 // Safety: `BorrowedParcel` always contains a valid pointer to an
Stephen Crane2a3c2502020-06-16 17:48:35 -0700674 // `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
690impl Drop for Parcel {
691 fn drop(&mut self) {
692 // Run the C++ Parcel complete object destructor
Alice Ryhl268458c2021-09-15 12:56:10 +0000693 unsafe {
Alice Ryhl8618c482021-11-09 15:35:35 +0000694 // Safety: `Parcel` always contains a valid pointer to an
Alice Ryhl268458c2021-09-15 12:56:10 +0000695 // `AParcel`. Since we own the parcel, we can safely delete it
696 // here.
Alice Ryhl8618c482021-11-09 15:35:35 +0000697 sys::AParcel_delete(self.ptr.as_ptr())
Alice Ryhl268458c2021-09-15 12:56:10 +0000698 }
699 }
700}
701
Alice Ryhlfeba6ca2021-08-19 10:47:04 +0000702impl fmt::Debug for Parcel {
703 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
Matthew Maurere268a9f2022-07-26 09:31:30 -0700704 f.debug_struct("Parcel").finish()
Alice Ryhlfeba6ca2021-08-19 10:47:04 +0000705 }
706}
707
Alice Ryhl8618c482021-11-09 15:35:35 +0000708impl<'a> fmt::Debug for BorrowedParcel<'a> {
Alice Ryhl268458c2021-09-15 12:56:10 +0000709 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
Matthew Maurere268a9f2022-07-26 09:31:30 -0700710 f.debug_struct("BorrowedParcel").finish()
Alice Ryhl268458c2021-09-15 12:56:10 +0000711 }
712}
713
Stephen Crane2a3c2502020-06-16 17:48:35 -0700714#[test]
715fn test_read_write() {
Andrei Homescu72b799d2021-09-04 01:39:23 +0000716 let mut parcel = Parcel::new();
Stephen Crane2a3c2502020-06-16 17:48:35 -0700717 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));
Stephen Crane76072e82020-08-03 13:09:36 -0700728 assert_eq!(parcel.read::<Option<String>>(), Ok(None));
Stephen Crane2a3c2502020-06-16 17:48:35 -0700729 assert_eq!(parcel.read::<String>(), Err(StatusCode::UNEXPECTED_NULL));
730
Alice Ryhl8618c482021-11-09 15:35:35 +0000731 assert_eq!(parcel.borrowed_ref().read_binder().err(), Some(StatusCode::BAD_TYPE));
Stephen Crane2a3c2502020-06-16 17:48:35 -0700732
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)]
745fn test_read_data() {
Andrei Homescu72b799d2021-09-04 01:39:23 +0000746 let mut parcel = Parcel::new();
Stephen Crane2a3c2502020-06-16 17:48:35 -0700747 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
Chris Wailes45fd2942021-07-26 19:18:41 -0700757 assert!(parcel.read::<bool>().unwrap());
Stephen Crane2a3c2502020-06-16 17:48:35 -0700758
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
Matthew Maurere268a9f2022-07-26 09:31:30 -0700799 assert_eq!(parcel.read::<f32>().unwrap(), 1143139100000000000000000000.0);
Stephen Crane2a3c2502020-06-16 17:48:35 -0700800 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]
817fn test_utf8_utf16_conversions() {
Andrei Homescu72b799d2021-09-04 01:39:23 +0000818 let mut parcel = Parcel::new();
Stephen Crane2a3c2502020-06-16 17:48:35 -0700819 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 }
Matthew Maurere268a9f2022-07-26 09:31:30 -0700825 assert_eq!(parcel.read::<Option<String>>().unwrap().unwrap(), "Hello, Binder!",);
Stephen Crane2a3c2502020-06-16 17:48:35 -0700826 unsafe {
827 assert!(parcel.set_data_position(start).is_ok());
828 }
Stephen Crane76072e82020-08-03 13:09:36 -0700829
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
Stephen Crane2a3c2502020-06-16 17:48:35 -0700842 assert!(parcel.write(&["str1", "str2", "str3"][..]).is_ok());
843 assert!(parcel
Matthew Maurere268a9f2022-07-26 09:31:30 -0700844 .write(&[String::from("str4"), String::from("str5"), String::from("str6"),][..])
Stephen Crane2a3c2502020-06-16 17:48:35 -0700845 .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
Matthew Maurere268a9f2022-07-26 09:31:30 -0700856 assert_eq!(parcel.read::<Vec<String>>().unwrap(), ["str1", "str2", "str3"]);
857 assert_eq!(parcel.read::<Vec<String>>().unwrap(), ["str4", "str5", "str6"]);
Stephen Crane2a3c2502020-06-16 17:48:35 -0700858 assert_eq!(parcel.read::<Vec<String>>().unwrap(), [s1, s2, s3]);
859}
Stephen Craneaae76382020-08-03 14:12:15 -0700860
861#[test]
862fn test_sized_write() {
Andrei Homescu72b799d2021-09-04 01:39:23 +0000863 let mut parcel = Parcel::new();
Stephen Craneaae76382020-08-03 14:12:15 -0700864 let start = parcel.get_data_position();
865
866 let arr = [1i32, 2i32, 3i32];
867
Matthew Maurere268a9f2022-07-26 09:31:30 -0700868 parcel
869 .sized_write(|subparcel| subparcel.write(&arr[..]))
870 .expect("Could not perform sized write");
Stephen Craneaae76382020-08-03 14:12:15 -0700871
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
Matthew Maurere268a9f2022-07-26 09:31:30 -0700881 assert_eq!(expected_len, parcel.read().unwrap(),);
Stephen Craneaae76382020-08-03 14:12:15 -0700882
Matthew Maurere268a9f2022-07-26 09:31:30 -0700883 assert_eq!(parcel.read::<Vec<i32>>().unwrap(), &arr,);
Stephen Craneaae76382020-08-03 14:12:15 -0700884}
Andrei Homescu72b799d2021-09-04 01:39:23 +0000885
886#[test]
887fn 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}