blob: 206b90c80767c00597ca0e54645d4a6b8c77533e [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;
Alice Ryhl268458c2021-09-15 12:56:10 +000025use std::marker::PhantomData;
Stephen Crane2a3c2502020-06-16 17:48:35 -070026use std::mem::ManuallyDrop;
Alice Ryhl8618c482021-11-09 15:35:35 +000027use std::ptr::{self, NonNull};
Alice Ryhlfeba6ca2021-08-19 10:47:04 +000028use std::fmt;
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::{
36 Deserialize, DeserializeArray, DeserializeOption, Serialize, SerializeArray, SerializeOption,
Andrei Homescu083e3532021-09-08 00:36:18 +000037 Parcelable, 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 };
Alice Ryhl8618c482021-11-09 15:35:35 +000081 Self {
82 ptr: NonNull::new(ptr).expect("AParcel_create returned null pointer")
Alice Ryhl05f5a2c2021-09-15 12:56:10 +000083 }
84 }
85
Alice Ryhl268458c2021-09-15 12:56:10 +000086 /// Create an owned reference to a parcel object from a raw pointer.
87 ///
88 /// # Safety
89 ///
90 /// This constructor is safe if the raw pointer parameter is either null
91 /// (resulting in `None`), or a valid pointer to an `AParcel` object. The
92 /// parcel object must be owned by the caller prior to this call, as this
93 /// constructor takes ownership of the parcel and will destroy it on drop.
94 ///
95 /// Additionally, the caller must guarantee that it is valid to take
96 /// ownership of the AParcel object. All future access to the AParcel
Alice Ryhl8618c482021-11-09 15:35:35 +000097 /// must happen through this `Parcel`.
Alice Ryhl268458c2021-09-15 12:56:10 +000098 ///
Alice Ryhl8618c482021-11-09 15:35:35 +000099 /// Because `Parcel` implements `Send`, the pointer must never point to any
100 /// thread-local data, e.g., a variable on the stack, either directly or
101 /// indirectly.
102 pub unsafe fn from_raw(ptr: *mut sys::AParcel) -> Option<Parcel> {
103 NonNull::new(ptr).map(|ptr| Self { ptr })
Alice Ryhl268458c2021-09-15 12:56:10 +0000104 }
105
106 /// Consume the parcel, transferring ownership to the caller.
107 pub(crate) fn into_raw(self) -> *mut sys::AParcel {
Alice Ryhl8618c482021-11-09 15:35:35 +0000108 let ptr = self.ptr.as_ptr();
Alice Ryhl268458c2021-09-15 12:56:10 +0000109 let _ = ManuallyDrop::new(self);
110 ptr
111 }
112
Alice Ryhl268458c2021-09-15 12:56:10 +0000113 /// Get a borrowed view into the contents of this `Parcel`.
114 pub fn borrowed(&mut self) -> BorrowedParcel<'_> {
Alice Ryhl8618c482021-11-09 15:35:35 +0000115 // Safety: The raw pointer is a valid pointer to an AParcel, and the
116 // lifetime of the returned `BorrowedParcel` is tied to `self`, so the
117 // borrow checker will ensure that the `AParcel` can only be accessed
118 // via the `BorrowParcel` until it goes out of scope.
Alice Ryhl268458c2021-09-15 12:56:10 +0000119 BorrowedParcel {
Alice Ryhl8618c482021-11-09 15:35:35 +0000120 ptr: self.ptr,
Alice Ryhl268458c2021-09-15 12:56:10 +0000121 _lifetime: PhantomData,
122 }
123 }
Alice Ryhl268458c2021-09-15 12:56:10 +0000124
Alice Ryhl8618c482021-11-09 15:35:35 +0000125 /// Get an immutable borrowed view into the contents of this `Parcel`.
126 pub fn borrowed_ref(&self) -> &BorrowedParcel<'_> {
127 // Safety: Parcel and BorrowedParcel are both represented in the same
128 // way as a NonNull<sys::AParcel> due to their use of repr(transparent),
129 // so casting references as done here is valid.
130 unsafe {
131 &*(self as *const Parcel as *const BorrowedParcel<'_>)
Stephen Crane2a3c2502020-06-16 17:48:35 -0700132 }
133 }
Stephen Crane2a3c2502020-06-16 17:48:35 -0700134}
135
Andrei Homescu72b799d2021-09-04 01:39:23 +0000136impl Default for Parcel {
137 fn default() -> Self {
138 Self::new()
139 }
140}
141
142impl Clone for Parcel {
143 fn clone(&self) -> Self {
144 let mut new_parcel = Self::new();
145 new_parcel
Alice Ryhl8618c482021-11-09 15:35:35 +0000146 .borrowed()
147 .append_all_from(self.borrowed_ref())
Andrei Homescu72b799d2021-09-04 01:39:23 +0000148 .expect("Failed to append from Parcel");
149 new_parcel
150 }
151}
152
Alice Ryhl8618c482021-11-09 15:35:35 +0000153impl<'a> BorrowedParcel<'a> {
154 /// Create a borrowed reference to a parcel object from a raw pointer.
155 ///
156 /// # Safety
157 ///
158 /// This constructor is safe if the raw pointer parameter is either null
159 /// (resulting in `None`), or a valid pointer to an `AParcel` object.
160 ///
161 /// Since the raw pointer is not restricted by any lifetime, the lifetime on
162 /// the returned `BorrowedParcel` object can be chosen arbitrarily by the
163 /// caller. The caller must ensure it is valid to mutably borrow the AParcel
164 /// for the duration of the lifetime that the caller chooses. Note that
165 /// since this is a mutable borrow, it must have exclusive access to the
166 /// AParcel for the duration of the borrow.
167 pub unsafe fn from_raw(ptr: *mut sys::AParcel) -> Option<BorrowedParcel<'a>> {
168 Some(Self {
169 ptr: NonNull::new(ptr)?,
170 _lifetime: PhantomData,
171 })
172 }
173
174 /// Get a sub-reference to this reference to the parcel.
175 pub fn reborrow(&mut self) -> BorrowedParcel<'_> {
176 // Safety: The raw pointer is a valid pointer to an AParcel, and the
177 // lifetime of the returned `BorrowedParcel` is tied to `self`, so the
178 // borrow checker will ensure that the `AParcel` can only be accessed
179 // via the `BorrowParcel` until it goes out of scope.
180 BorrowedParcel {
181 ptr: self.ptr,
182 _lifetime: PhantomData,
183 }
184 }
185}
186
187/// # Safety
188///
189/// The `Parcel` constructors guarantee that a `Parcel` object will always
190/// contain a valid pointer to an `AParcel`.
191unsafe impl AsNative<sys::AParcel> for Parcel {
192 fn as_native(&self) -> *const sys::AParcel {
193 self.ptr.as_ptr()
194 }
195
196 fn as_native_mut(&mut self) -> *mut sys::AParcel {
197 self.ptr.as_ptr()
198 }
199}
200
201/// # Safety
202///
203/// The `BorrowedParcel` constructors guarantee that a `BorrowedParcel` object
204/// will always contain a valid pointer to an `AParcel`.
205unsafe impl<'a> AsNative<sys::AParcel> for BorrowedParcel<'a> {
206 fn as_native(&self) -> *const sys::AParcel {
207 self.ptr.as_ptr()
208 }
209
210 fn as_native_mut(&mut self) -> *mut sys::AParcel {
211 self.ptr.as_ptr()
212 }
213}
214
Stephen Crane2a3c2502020-06-16 17:48:35 -0700215// Data serialization methods
Alice Ryhl8618c482021-11-09 15:35:35 +0000216impl<'a> BorrowedParcel<'a> {
Steven Morelandf183fdd2020-10-27 00:12:12 +0000217 /// Data written to parcelable is zero'd before being deleted or reallocated.
218 pub fn mark_sensitive(&mut self) {
219 unsafe {
220 // Safety: guaranteed to have a parcel object, and this method never fails
221 sys::AParcel_markSensitive(self.as_native())
222 }
223 }
224
Alice Ryhl8618c482021-11-09 15:35:35 +0000225 /// Write a type that implements [`Serialize`] to the parcel.
Stephen Crane2a3c2502020-06-16 17:48:35 -0700226 pub fn write<S: Serialize + ?Sized>(&mut self, parcelable: &S) -> Result<()> {
227 parcelable.serialize(self)
228 }
229
Alice Ryhl8618c482021-11-09 15:35:35 +0000230 /// Writes the length of a slice to the parcel.
Stephen Crane2a3c2502020-06-16 17:48:35 -0700231 ///
232 /// This is used in AIDL-generated client side code to indicate the
233 /// allocated space for an output array parameter.
234 pub fn write_slice_size<T>(&mut self, slice: Option<&[T]>) -> Result<()> {
235 if let Some(slice) = slice {
236 let len: i32 = slice.len().try_into().or(Err(StatusCode::BAD_VALUE))?;
237 self.write(&len)
238 } else {
239 self.write(&-1i32)
240 }
241 }
242
Alice Ryhl8618c482021-11-09 15:35:35 +0000243 /// Perform a series of writes to the parcel, prepended with the length
Stephen Craneaae76382020-08-03 14:12:15 -0700244 /// (in bytes) of the written data.
245 ///
246 /// The length `0i32` will be written to the parcel first, followed by the
247 /// writes performed by the callback. The initial length will then be
248 /// updated to the length of all data written by the callback, plus the
249 /// size of the length elemement itself (4 bytes).
250 ///
251 /// # Examples
252 ///
253 /// After the following call:
254 ///
255 /// ```
256 /// # use binder::{Binder, Interface, Parcel};
Alice Ryhl8618c482021-11-09 15:35:35 +0000257 /// # let mut parcel = Parcel::new();
Stephen Craneaae76382020-08-03 14:12:15 -0700258 /// parcel.sized_write(|subparcel| {
259 /// subparcel.write(&1u32)?;
260 /// subparcel.write(&2u32)?;
261 /// subparcel.write(&3u32)
262 /// });
263 /// ```
264 ///
265 /// `parcel` will contain the following:
266 ///
267 /// ```ignore
268 /// [16i32, 1u32, 2u32, 3u32]
269 /// ```
270 pub fn sized_write<F>(&mut self, f: F) -> Result<()>
Alice Ryhl8618c482021-11-09 15:35:35 +0000271 where
272 for<'b> F: FnOnce(&'b mut WritableSubParcel<'b>) -> Result<()>
Stephen Craneaae76382020-08-03 14:12:15 -0700273 {
274 let start = self.get_data_position();
275 self.write(&0i32)?;
276 {
Alice Ryhl8618c482021-11-09 15:35:35 +0000277 let mut subparcel = WritableSubParcel(self.reborrow());
278 f(&mut subparcel)?;
Stephen Craneaae76382020-08-03 14:12:15 -0700279 }
280 let end = self.get_data_position();
281 unsafe {
282 self.set_data_position(start)?;
283 }
284 assert!(end >= start);
285 self.write(&(end - start))?;
286 unsafe {
287 self.set_data_position(end)?;
288 }
289 Ok(())
290 }
291
Stephen Crane2a3c2502020-06-16 17:48:35 -0700292 /// Returns the current position in the parcel data.
293 pub fn get_data_position(&self) -> i32 {
294 unsafe {
Alice Ryhl8618c482021-11-09 15:35:35 +0000295 // Safety: `BorrowedParcel` always contains a valid pointer to an
296 // `AParcel`, and this call is otherwise safe.
Stephen Crane2a3c2502020-06-16 17:48:35 -0700297 sys::AParcel_getDataPosition(self.as_native())
298 }
299 }
300
Andrei Homescub0487442021-05-12 07:16:16 +0000301 /// Returns the total size of the parcel.
302 pub fn get_data_size(&self) -> i32 {
303 unsafe {
Alice Ryhl8618c482021-11-09 15:35:35 +0000304 // Safety: `BorrowedParcel` always contains a valid pointer to an
305 // `AParcel`, and this call is otherwise safe.
Andrei Homescub0487442021-05-12 07:16:16 +0000306 sys::AParcel_getDataSize(self.as_native())
307 }
308 }
309
Stephen Crane2a3c2502020-06-16 17:48:35 -0700310 /// Move the current read/write position in the parcel.
311 ///
Stephen Crane2a3c2502020-06-16 17:48:35 -0700312 /// # Safety
313 ///
314 /// This method is safe if `pos` is less than the current size of the parcel
315 /// data buffer. Otherwise, we are relying on correct bounds checking in the
316 /// Parcel C++ code on every subsequent read or write to this parcel. If all
317 /// accesses are bounds checked, this call is still safe, but we can't rely
318 /// on that.
319 pub unsafe fn set_data_position(&self, pos: i32) -> Result<()> {
320 status_result(sys::AParcel_setDataPosition(self.as_native(), pos))
321 }
Andrei Homescu72b799d2021-09-04 01:39:23 +0000322
Alice Ryhl8618c482021-11-09 15:35:35 +0000323 /// Append a subset of another parcel.
Andrei Homescu72b799d2021-09-04 01:39:23 +0000324 ///
325 /// This appends `size` bytes of data from `other` starting at offset
Alice Ryhl8618c482021-11-09 15:35:35 +0000326 /// `start` to the current parcel, or returns an error if not possible.
327 pub fn append_from(&mut self, other: &impl AsNative<sys::AParcel>, start: i32, size: i32) -> Result<()> {
Andrei Homescu72b799d2021-09-04 01:39:23 +0000328 let status = unsafe {
329 // Safety: `Parcel::appendFrom` from C++ checks that `start`
330 // and `size` are in bounds, and returns an error otherwise.
331 // Both `self` and `other` always contain valid pointers.
332 sys::AParcel_appendFrom(
333 other.as_native(),
334 self.as_native_mut(),
335 start,
336 size,
337 )
338 };
339 status_result(status)
340 }
341
Alice Ryhl8618c482021-11-09 15:35:35 +0000342 /// Append the contents of another parcel.
343 pub fn append_all_from(&mut self, other: &impl AsNative<sys::AParcel>) -> Result<()> {
344 // Safety: `BorrowedParcel` always contains a valid pointer to an
345 // `AParcel`, and this call is otherwise safe.
346 let size = unsafe { sys::AParcel_getDataSize(other.as_native()) };
347 self.append_from(other, 0, size)
Andrei Homescu72b799d2021-09-04 01:39:23 +0000348 }
Stephen Crane2a3c2502020-06-16 17:48:35 -0700349}
350
Alice Ryhl8618c482021-11-09 15:35:35 +0000351/// A segment of a writable parcel, used for [`BorrowedParcel::sized_write`].
352pub struct WritableSubParcel<'a>(BorrowedParcel<'a>);
Stephen Craneaae76382020-08-03 14:12:15 -0700353
354impl<'a> WritableSubParcel<'a> {
355 /// Write a type that implements [`Serialize`] to the sub-parcel.
Alice Ryhl8618c482021-11-09 15:35:35 +0000356 pub fn write<S: Serialize + ?Sized>(&mut self, parcelable: &S) -> Result<()> {
357 parcelable.serialize(&mut self.0)
358 }
359}
360
361impl Parcel {
362 /// Data written to parcelable is zero'd before being deleted or reallocated.
363 pub fn mark_sensitive(&mut self) {
364 self.borrowed().mark_sensitive()
365 }
366
367 /// Write a type that implements [`Serialize`] to the parcel.
368 pub fn write<S: Serialize + ?Sized>(&mut self, parcelable: &S) -> Result<()> {
369 self.borrowed().write(parcelable)
370 }
371
372 /// Writes the length of a slice to the parcel.
373 ///
374 /// This is used in AIDL-generated client side code to indicate the
375 /// allocated space for an output array parameter.
376 pub fn write_slice_size<T>(&mut self, slice: Option<&[T]>) -> Result<()> {
377 self.borrowed().write_slice_size(slice)
378 }
379
380 /// Perform a series of writes to the parcel, prepended with the length
381 /// (in bytes) of the written data.
382 ///
383 /// The length `0i32` will be written to the parcel first, followed by the
384 /// writes performed by the callback. The initial length will then be
385 /// updated to the length of all data written by the callback, plus the
386 /// size of the length elemement itself (4 bytes).
387 ///
388 /// # Examples
389 ///
390 /// After the following call:
391 ///
392 /// ```
393 /// # use binder::{Binder, Interface, Parcel};
394 /// # let mut parcel = Parcel::new();
395 /// parcel.sized_write(|subparcel| {
396 /// subparcel.write(&1u32)?;
397 /// subparcel.write(&2u32)?;
398 /// subparcel.write(&3u32)
399 /// });
400 /// ```
401 ///
402 /// `parcel` will contain the following:
403 ///
404 /// ```ignore
405 /// [16i32, 1u32, 2u32, 3u32]
406 /// ```
407 pub fn sized_write<F>(&mut self, f: F) -> Result<()>
408 where
409 for<'b> F: FnOnce(&'b mut WritableSubParcel<'b>) -> Result<()>
410 {
411 self.borrowed().sized_write(f)
412 }
413
414 /// Returns the current position in the parcel data.
415 pub fn get_data_position(&self) -> i32 {
416 self.borrowed_ref().get_data_position()
417 }
418
419 /// Returns the total size of the parcel.
420 pub fn get_data_size(&self) -> i32 {
421 self.borrowed_ref().get_data_size()
422 }
423
424 /// Move the current read/write position in the parcel.
425 ///
426 /// # Safety
427 ///
428 /// This method is safe if `pos` is less than the current size of the parcel
429 /// data buffer. Otherwise, we are relying on correct bounds checking in the
430 /// Parcel C++ code on every subsequent read or write to this parcel. If all
431 /// accesses are bounds checked, this call is still safe, but we can't rely
432 /// on that.
433 pub unsafe fn set_data_position(&self, pos: i32) -> Result<()> {
434 self.borrowed_ref().set_data_position(pos)
435 }
436
437 /// Append a subset of another parcel.
438 ///
439 /// This appends `size` bytes of data from `other` starting at offset
440 /// `start` to the current parcel, or returns an error if not possible.
441 pub fn append_from(&mut self, other: &impl AsNative<sys::AParcel>, start: i32, size: i32) -> Result<()> {
442 self.borrowed().append_from(other, start, size)
443 }
444
445 /// Append the contents of another parcel.
446 pub fn append_all_from(&mut self, other: &impl AsNative<sys::AParcel>) -> Result<()> {
447 self.borrowed().append_all_from(other)
Stephen Craneaae76382020-08-03 14:12:15 -0700448 }
449}
450
Stephen Crane2a3c2502020-06-16 17:48:35 -0700451// Data deserialization methods
Alice Ryhl8618c482021-11-09 15:35:35 +0000452impl<'a> BorrowedParcel<'a> {
453 /// Attempt to read a type that implements [`Deserialize`] from this parcel.
Stephen Crane2a3c2502020-06-16 17:48:35 -0700454 pub fn read<D: Deserialize>(&self) -> Result<D> {
455 D::deserialize(self)
456 }
457
Alice Ryhl8618c482021-11-09 15:35:35 +0000458 /// Attempt to read a type that implements [`Deserialize`] from this parcel
459 /// onto an existing value. This operation will overwrite the old value
460 /// partially or completely, depending on how much data is available.
Andrei Homescu50006152021-05-01 07:34:51 +0000461 pub fn read_onto<D: Deserialize>(&self, x: &mut D) -> Result<()> {
462 x.deserialize_from(self)
463 }
464
Andrei Homescub0487442021-05-12 07:16:16 +0000465 /// Safely read a sized parcelable.
466 ///
467 /// Read the size of a parcelable, compute the end position
468 /// of that parcelable, then build a sized readable sub-parcel
469 /// and call a closure with the sub-parcel as its parameter.
470 /// The closure can keep reading data from the sub-parcel
471 /// until it runs out of input data. The closure is responsible
472 /// for calling [`ReadableSubParcel::has_more_data`] to check for
473 /// more data before every read, at least until Rust generators
474 /// are stabilized.
475 /// After the closure returns, skip to the end of the current
476 /// parcelable regardless of how much the closure has read.
477 ///
478 /// # Examples
479 ///
480 /// ```no_run
481 /// let mut parcelable = Default::default();
482 /// parcel.sized_read(|subparcel| {
483 /// if subparcel.has_more_data() {
484 /// parcelable.a = subparcel.read()?;
485 /// }
486 /// if subparcel.has_more_data() {
487 /// parcelable.b = subparcel.read()?;
488 /// }
489 /// Ok(())
490 /// });
491 /// ```
492 ///
Alice Ryhl8618c482021-11-09 15:35:35 +0000493 pub fn sized_read<F>(&self, f: F) -> Result<()>
Andrei Homescub0487442021-05-12 07:16:16 +0000494 where
Alice Ryhl8618c482021-11-09 15:35:35 +0000495 for<'b> F: FnOnce(ReadableSubParcel<'b>) -> Result<()>
Andrei Homescub0487442021-05-12 07:16:16 +0000496 {
497 let start = self.get_data_position();
498 let parcelable_size: i32 = self.read()?;
499 if parcelable_size < 0 {
500 return Err(StatusCode::BAD_VALUE);
501 }
502
503 let end = start.checked_add(parcelable_size)
504 .ok_or(StatusCode::BAD_VALUE)?;
505 if end > self.get_data_size() {
506 return Err(StatusCode::NOT_ENOUGH_DATA);
507 }
508
509 let subparcel = ReadableSubParcel {
Alice Ryhl8618c482021-11-09 15:35:35 +0000510 parcel: BorrowedParcel {
511 ptr: self.ptr,
512 _lifetime: PhantomData,
513 },
Andrei Homescub0487442021-05-12 07:16:16 +0000514 end_position: end,
515 };
516 f(subparcel)?;
517
518 // Advance the data position to the actual end,
519 // in case the closure read less data than was available
520 unsafe {
521 self.set_data_position(end)?;
522 }
523
524 Ok(())
525 }
526
Alice Ryhl8618c482021-11-09 15:35:35 +0000527 /// Read a vector size from the parcel and resize the given output vector to
528 /// be correctly sized for that amount of data.
Stephen Crane2a3c2502020-06-16 17:48:35 -0700529 ///
530 /// This method is used in AIDL-generated server side code for methods that
531 /// take a mutable slice reference parameter.
532 pub fn resize_out_vec<D: Default + Deserialize>(&self, out_vec: &mut Vec<D>) -> Result<()> {
533 let len: i32 = self.read()?;
534
535 if len < 0 {
536 return Err(StatusCode::UNEXPECTED_NULL);
537 }
538
539 // usize in Rust may be 16-bit, so i32 may not fit
540 let len = len.try_into().unwrap();
541 out_vec.resize_with(len, Default::default);
542
543 Ok(())
544 }
545
Alice Ryhl8618c482021-11-09 15:35:35 +0000546 /// Read a vector size from the parcel and either create a correctly sized
Stephen Crane2a3c2502020-06-16 17:48:35 -0700547 /// vector for that amount of data or set the output parameter to None if
548 /// the vector should be null.
549 ///
550 /// This method is used in AIDL-generated server side code for methods that
551 /// take a mutable slice reference parameter.
552 pub fn resize_nullable_out_vec<D: Default + Deserialize>(
553 &self,
554 out_vec: &mut Option<Vec<D>>,
555 ) -> Result<()> {
556 let len: i32 = self.read()?;
557
558 if len < 0 {
559 *out_vec = None;
560 } else {
561 // usize in Rust may be 16-bit, so i32 may not fit
562 let len = len.try_into().unwrap();
563 let mut vec = Vec::with_capacity(len);
564 vec.resize_with(len, Default::default);
565 *out_vec = Some(vec);
566 }
567
568 Ok(())
569 }
570}
571
Andrei Homescub0487442021-05-12 07:16:16 +0000572/// A segment of a readable parcel, used for [`Parcel::sized_read`].
573pub struct ReadableSubParcel<'a> {
Alice Ryhl8618c482021-11-09 15:35:35 +0000574 parcel: BorrowedParcel<'a>,
Andrei Homescub0487442021-05-12 07:16:16 +0000575 end_position: i32,
576}
577
578impl<'a> ReadableSubParcel<'a> {
579 /// Read a type that implements [`Deserialize`] from the sub-parcel.
580 pub fn read<D: Deserialize>(&self) -> Result<D> {
581 // The caller should have checked this,
582 // but it can't hurt to double-check
583 assert!(self.has_more_data());
Alice Ryhl8618c482021-11-09 15:35:35 +0000584 D::deserialize(&self.parcel)
Andrei Homescub0487442021-05-12 07:16:16 +0000585 }
586
587 /// Check if the sub-parcel has more data to read
588 pub fn has_more_data(&self) -> bool {
589 self.parcel.get_data_position() < self.end_position
590 }
591}
592
Stephen Crane2a3c2502020-06-16 17:48:35 -0700593impl Parcel {
Alice Ryhl8618c482021-11-09 15:35:35 +0000594 /// Attempt to read a type that implements [`Deserialize`] from this parcel.
595 pub fn read<D: Deserialize>(&self) -> Result<D> {
596 self.borrowed_ref().read()
597 }
598
599 /// Attempt to read a type that implements [`Deserialize`] from this parcel
600 /// onto an existing value. This operation will overwrite the old value
601 /// partially or completely, depending on how much data is available.
602 pub fn read_onto<D: Deserialize>(&self, x: &mut D) -> Result<()> {
603 self.borrowed_ref().read_onto(x)
604 }
605
606 /// Safely read a sized parcelable.
607 ///
608 /// Read the size of a parcelable, compute the end position
609 /// of that parcelable, then build a sized readable sub-parcel
610 /// and call a closure with the sub-parcel as its parameter.
611 /// The closure can keep reading data from the sub-parcel
612 /// until it runs out of input data. The closure is responsible
613 /// for calling [`ReadableSubParcel::has_more_data`] to check for
614 /// more data before every read, at least until Rust generators
615 /// are stabilized.
616 /// After the closure returns, skip to the end of the current
617 /// parcelable regardless of how much the closure has read.
618 ///
619 /// # Examples
620 ///
621 /// ```no_run
622 /// let mut parcelable = Default::default();
623 /// parcel.sized_read(|subparcel| {
624 /// if subparcel.has_more_data() {
625 /// parcelable.a = subparcel.read()?;
626 /// }
627 /// if subparcel.has_more_data() {
628 /// parcelable.b = subparcel.read()?;
629 /// }
630 /// Ok(())
631 /// });
632 /// ```
633 ///
634 pub fn sized_read<F>(&self, f: F) -> Result<()>
635 where
636 for<'b> F: FnOnce(ReadableSubParcel<'b>) -> Result<()>
637 {
638 self.borrowed_ref().sized_read(f)
639 }
640
641 /// Read a vector size from the parcel and resize the given output vector to
642 /// be correctly sized for that amount of data.
643 ///
644 /// This method is used in AIDL-generated server side code for methods that
645 /// take a mutable slice reference parameter.
646 pub fn resize_out_vec<D: Default + Deserialize>(&self, out_vec: &mut Vec<D>) -> Result<()> {
647 self.borrowed_ref().resize_out_vec(out_vec)
648 }
649
650 /// Read a vector size from the parcel and either create a correctly sized
651 /// vector for that amount of data or set the output parameter to None if
652 /// the vector should be null.
653 ///
654 /// This method is used in AIDL-generated server side code for methods that
655 /// take a mutable slice reference parameter.
656 pub fn resize_nullable_out_vec<D: Default + Deserialize>(
657 &self,
658 out_vec: &mut Option<Vec<D>>,
659 ) -> Result<()> {
660 self.borrowed_ref().resize_nullable_out_vec(out_vec)
661 }
662}
663
664// Internal APIs
665impl<'a> BorrowedParcel<'a> {
Stephen Crane2a3c2502020-06-16 17:48:35 -0700666 pub(crate) fn write_binder(&mut self, binder: Option<&SpIBinder>) -> Result<()> {
667 unsafe {
Alice Ryhl8618c482021-11-09 15:35:35 +0000668 // Safety: `BorrowedParcel` always contains a valid pointer to an
Stephen Crane2a3c2502020-06-16 17:48:35 -0700669 // `AParcel`. `AsNative` for `Option<SpIBinder`> will either return
670 // null or a valid pointer to an `AIBinder`, both of which are
671 // valid, safe inputs to `AParcel_writeStrongBinder`.
672 //
673 // This call does not take ownership of the binder. However, it does
674 // require a mutable pointer, which we cannot extract from an
675 // immutable reference, so we clone the binder, incrementing the
676 // refcount before the call. The refcount will be immediately
677 // decremented when this temporary is dropped.
678 status_result(sys::AParcel_writeStrongBinder(
679 self.as_native_mut(),
680 binder.cloned().as_native_mut(),
681 ))
682 }
683 }
684
685 pub(crate) fn read_binder(&self) -> Result<Option<SpIBinder>> {
686 let mut binder = ptr::null_mut();
687 let status = unsafe {
Alice Ryhl8618c482021-11-09 15:35:35 +0000688 // Safety: `BorrowedParcel` always contains a valid pointer to an
Stephen Crane2a3c2502020-06-16 17:48:35 -0700689 // `AParcel`. We pass a valid, mutable out pointer to the `binder`
690 // parameter. After this call, `binder` will be either null or a
691 // valid pointer to an `AIBinder` owned by the caller.
692 sys::AParcel_readStrongBinder(self.as_native(), &mut binder)
693 };
694
695 status_result(status)?;
696
697 Ok(unsafe {
698 // Safety: `binder` is either null or a valid, owned pointer at this
699 // point, so can be safely passed to `SpIBinder::from_raw`.
700 SpIBinder::from_raw(binder)
701 })
702 }
703}
704
705impl Drop for Parcel {
706 fn drop(&mut self) {
707 // Run the C++ Parcel complete object destructor
Alice Ryhl268458c2021-09-15 12:56:10 +0000708 unsafe {
Alice Ryhl8618c482021-11-09 15:35:35 +0000709 // Safety: `Parcel` always contains a valid pointer to an
Alice Ryhl268458c2021-09-15 12:56:10 +0000710 // `AParcel`. Since we own the parcel, we can safely delete it
711 // here.
Alice Ryhl8618c482021-11-09 15:35:35 +0000712 sys::AParcel_delete(self.ptr.as_ptr())
Alice Ryhl268458c2021-09-15 12:56:10 +0000713 }
714 }
715}
716
Alice Ryhlfeba6ca2021-08-19 10:47:04 +0000717impl fmt::Debug for Parcel {
718 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
719 f.debug_struct("Parcel")
720 .finish()
721 }
722}
723
Alice Ryhl8618c482021-11-09 15:35:35 +0000724impl<'a> fmt::Debug for BorrowedParcel<'a> {
Alice Ryhl268458c2021-09-15 12:56:10 +0000725 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
Alice Ryhl8618c482021-11-09 15:35:35 +0000726 f.debug_struct("BorrowedParcel")
Alice Ryhl268458c2021-09-15 12:56:10 +0000727 .finish()
728 }
729}
730
Stephen Crane2a3c2502020-06-16 17:48:35 -0700731#[test]
732fn test_read_write() {
Andrei Homescu72b799d2021-09-04 01:39:23 +0000733 let mut parcel = Parcel::new();
Stephen Crane2a3c2502020-06-16 17:48:35 -0700734 let start = parcel.get_data_position();
735
736 assert_eq!(parcel.read::<bool>(), Err(StatusCode::NOT_ENOUGH_DATA));
737 assert_eq!(parcel.read::<i8>(), Err(StatusCode::NOT_ENOUGH_DATA));
738 assert_eq!(parcel.read::<u16>(), Err(StatusCode::NOT_ENOUGH_DATA));
739 assert_eq!(parcel.read::<i32>(), Err(StatusCode::NOT_ENOUGH_DATA));
740 assert_eq!(parcel.read::<u32>(), Err(StatusCode::NOT_ENOUGH_DATA));
741 assert_eq!(parcel.read::<i64>(), Err(StatusCode::NOT_ENOUGH_DATA));
742 assert_eq!(parcel.read::<u64>(), Err(StatusCode::NOT_ENOUGH_DATA));
743 assert_eq!(parcel.read::<f32>(), Err(StatusCode::NOT_ENOUGH_DATA));
744 assert_eq!(parcel.read::<f64>(), Err(StatusCode::NOT_ENOUGH_DATA));
Stephen Crane76072e82020-08-03 13:09:36 -0700745 assert_eq!(parcel.read::<Option<String>>(), Ok(None));
Stephen Crane2a3c2502020-06-16 17:48:35 -0700746 assert_eq!(parcel.read::<String>(), Err(StatusCode::UNEXPECTED_NULL));
747
Alice Ryhl8618c482021-11-09 15:35:35 +0000748 assert_eq!(parcel.borrowed_ref().read_binder().err(), Some(StatusCode::BAD_TYPE));
Stephen Crane2a3c2502020-06-16 17:48:35 -0700749
750 parcel.write(&1i32).unwrap();
751
752 unsafe {
753 parcel.set_data_position(start).unwrap();
754 }
755
756 let i: i32 = parcel.read().unwrap();
757 assert_eq!(i, 1i32);
758}
759
760#[test]
761#[allow(clippy::float_cmp)]
762fn test_read_data() {
Andrei Homescu72b799d2021-09-04 01:39:23 +0000763 let mut parcel = Parcel::new();
Stephen Crane2a3c2502020-06-16 17:48:35 -0700764 let str_start = parcel.get_data_position();
765
766 parcel.write(&b"Hello, Binder!\0"[..]).unwrap();
767 // Skip over string length
768 unsafe {
769 assert!(parcel.set_data_position(str_start).is_ok());
770 }
771 assert_eq!(parcel.read::<i32>().unwrap(), 15);
772 let start = parcel.get_data_position();
773
Chris Wailes45fd2942021-07-26 19:18:41 -0700774 assert!(parcel.read::<bool>().unwrap());
Stephen Crane2a3c2502020-06-16 17:48:35 -0700775
776 unsafe {
777 assert!(parcel.set_data_position(start).is_ok());
778 }
779
780 assert_eq!(parcel.read::<i8>().unwrap(), 72i8);
781
782 unsafe {
783 assert!(parcel.set_data_position(start).is_ok());
784 }
785
786 assert_eq!(parcel.read::<u16>().unwrap(), 25928);
787
788 unsafe {
789 assert!(parcel.set_data_position(start).is_ok());
790 }
791
792 assert_eq!(parcel.read::<i32>().unwrap(), 1819043144);
793
794 unsafe {
795 assert!(parcel.set_data_position(start).is_ok());
796 }
797
798 assert_eq!(parcel.read::<u32>().unwrap(), 1819043144);
799
800 unsafe {
801 assert!(parcel.set_data_position(start).is_ok());
802 }
803
804 assert_eq!(parcel.read::<i64>().unwrap(), 4764857262830019912);
805
806 unsafe {
807 assert!(parcel.set_data_position(start).is_ok());
808 }
809
810 assert_eq!(parcel.read::<u64>().unwrap(), 4764857262830019912);
811
812 unsafe {
813 assert!(parcel.set_data_position(start).is_ok());
814 }
815
816 assert_eq!(
817 parcel.read::<f32>().unwrap(),
818 1143139100000000000000000000.0
819 );
820 assert_eq!(parcel.read::<f32>().unwrap(), 40.043392);
821
822 unsafe {
823 assert!(parcel.set_data_position(start).is_ok());
824 }
825
826 assert_eq!(parcel.read::<f64>().unwrap(), 34732488246.197815);
827
828 // Skip back to before the string length
829 unsafe {
830 assert!(parcel.set_data_position(str_start).is_ok());
831 }
832
833 assert_eq!(parcel.read::<Vec<u8>>().unwrap(), b"Hello, Binder!\0");
834}
835
836#[test]
837fn test_utf8_utf16_conversions() {
Andrei Homescu72b799d2021-09-04 01:39:23 +0000838 let mut parcel = Parcel::new();
Stephen Crane2a3c2502020-06-16 17:48:35 -0700839 let start = parcel.get_data_position();
840
841 assert!(parcel.write("Hello, Binder!").is_ok());
842 unsafe {
843 assert!(parcel.set_data_position(start).is_ok());
844 }
845 assert_eq!(
846 parcel.read::<Option<String>>().unwrap().unwrap(),
Stephen Crane76072e82020-08-03 13:09:36 -0700847 "Hello, Binder!",
Stephen Crane2a3c2502020-06-16 17:48:35 -0700848 );
849 unsafe {
850 assert!(parcel.set_data_position(start).is_ok());
851 }
Stephen Crane76072e82020-08-03 13:09:36 -0700852
853 assert!(parcel.write("Embedded null \0 inside a string").is_ok());
854 unsafe {
855 assert!(parcel.set_data_position(start).is_ok());
856 }
857 assert_eq!(
858 parcel.read::<Option<String>>().unwrap().unwrap(),
859 "Embedded null \0 inside a string",
860 );
861 unsafe {
862 assert!(parcel.set_data_position(start).is_ok());
863 }
864
Stephen Crane2a3c2502020-06-16 17:48:35 -0700865 assert!(parcel.write(&["str1", "str2", "str3"][..]).is_ok());
866 assert!(parcel
867 .write(
868 &[
869 String::from("str4"),
870 String::from("str5"),
871 String::from("str6"),
872 ][..]
873 )
874 .is_ok());
875
876 let s1 = "Hello, Binder!";
877 let s2 = "This is a utf8 string.";
878 let s3 = "Some more text here.";
879
880 assert!(parcel.write(&[s1, s2, s3][..]).is_ok());
881 unsafe {
882 assert!(parcel.set_data_position(start).is_ok());
883 }
884
885 assert_eq!(
886 parcel.read::<Vec<String>>().unwrap(),
887 ["str1", "str2", "str3"]
888 );
889 assert_eq!(
890 parcel.read::<Vec<String>>().unwrap(),
891 ["str4", "str5", "str6"]
892 );
893 assert_eq!(parcel.read::<Vec<String>>().unwrap(), [s1, s2, s3]);
894}
Stephen Craneaae76382020-08-03 14:12:15 -0700895
896#[test]
897fn test_sized_write() {
Andrei Homescu72b799d2021-09-04 01:39:23 +0000898 let mut parcel = Parcel::new();
Stephen Craneaae76382020-08-03 14:12:15 -0700899 let start = parcel.get_data_position();
900
901 let arr = [1i32, 2i32, 3i32];
902
903 parcel.sized_write(|subparcel| {
904 subparcel.write(&arr[..])
905 }).expect("Could not perform sized write");
906
907 // i32 sub-parcel length + i32 array length + 3 i32 elements
908 let expected_len = 20i32;
909
910 assert_eq!(parcel.get_data_position(), start + expected_len);
911
912 unsafe {
913 parcel.set_data_position(start).unwrap();
914 }
915
916 assert_eq!(
917 expected_len,
918 parcel.read().unwrap(),
919 );
920
921 assert_eq!(
922 parcel.read::<Vec<i32>>().unwrap(),
923 &arr,
924 );
925}
Andrei Homescu72b799d2021-09-04 01:39:23 +0000926
927#[test]
928fn test_append_from() {
929 let mut parcel1 = Parcel::new();
930 parcel1.write(&42i32).expect("Could not perform write");
931
932 let mut parcel2 = Parcel::new();
933 assert_eq!(Ok(()), parcel2.append_all_from(&parcel1));
934 assert_eq!(4, parcel2.get_data_size());
935 assert_eq!(Ok(()), parcel2.append_all_from(&parcel1));
936 assert_eq!(8, parcel2.get_data_size());
937 unsafe {
938 parcel2.set_data_position(0).unwrap();
939 }
940 assert_eq!(Ok(42), parcel2.read::<i32>());
941 assert_eq!(Ok(42), parcel2.read::<i32>());
942
943 let mut parcel2 = Parcel::new();
944 assert_eq!(Ok(()), parcel2.append_from(&parcel1, 0, 2));
945 assert_eq!(Ok(()), parcel2.append_from(&parcel1, 2, 2));
946 assert_eq!(4, parcel2.get_data_size());
947 unsafe {
948 parcel2.set_data_position(0).unwrap();
949 }
950 assert_eq!(Ok(42), parcel2.read::<i32>());
951
952 let mut parcel2 = Parcel::new();
953 assert_eq!(Ok(()), parcel2.append_from(&parcel1, 0, 2));
954 assert_eq!(2, parcel2.get_data_size());
955 unsafe {
956 parcel2.set_data_position(0).unwrap();
957 }
958 assert_eq!(Err(StatusCode::NOT_ENOUGH_DATA), parcel2.read::<i32>());
959
960 let mut parcel2 = Parcel::new();
961 assert_eq!(Err(StatusCode::BAD_VALUE), parcel2.append_from(&parcel1, 4, 2));
962 assert_eq!(Err(StatusCode::BAD_VALUE), parcel2.append_from(&parcel1, 2, 4));
963 assert_eq!(Err(StatusCode::BAD_VALUE), parcel2.append_from(&parcel1, -1, 4));
964 assert_eq!(Err(StatusCode::BAD_VALUE), parcel2.append_from(&parcel1, 2, -1));
965}