blob: f09aef6fada72b9298a30192013c4ab20a408f1d [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
Andrew Walbran2f3ff9f2023-07-07 16:58:13 +010055/// Safety: This type guarantees that it owns the AParcel and that all access to
56/// the AParcel happens through the Parcel, so it is ok to send across threads.
Alice Ryhl8618c482021-11-09 15:35:35 +000057unsafe impl Send for Parcel {}
Alice Ryhl268458c2021-09-15 12:56:10 +000058
Alice Ryhl8618c482021-11-09 15:35:35 +000059/// Container for a message (data and object references) that can be sent
60/// through Binder.
61///
62/// This object is a borrowed variant of [`Parcel`]. It is a separate type from
63/// `&mut Parcel` because it is not valid to `mem::swap` two parcels.
64#[repr(transparent)]
Alice Ryhl268458c2021-09-15 12:56:10 +000065pub struct BorrowedParcel<'a> {
Alice Ryhl8618c482021-11-09 15:35:35 +000066 ptr: NonNull<sys::AParcel>,
Alice Ryhl268458c2021-09-15 12:56:10 +000067 _lifetime: PhantomData<&'a mut Parcel>,
68}
69
Alice Ryhl8618c482021-11-09 15:35:35 +000070impl Parcel {
71 /// Create a new empty `Parcel`.
72 pub fn new() -> Parcel {
Andrew Walbran2f3ff9f2023-07-07 16:58:13 +010073 // Safety: If `AParcel_create` succeeds, it always returns
74 // a valid pointer. If it fails, the process will crash.
75 let ptr = unsafe { sys::AParcel_create() };
Matthew Maurere268a9f2022-07-26 09:31:30 -070076 Self { ptr: NonNull::new(ptr).expect("AParcel_create returned null pointer") }
Alice Ryhl05f5a2c2021-09-15 12:56:10 +000077 }
78
Alice Ryhl268458c2021-09-15 12:56:10 +000079 /// Create an owned reference to a parcel object from a raw pointer.
80 ///
81 /// # Safety
82 ///
83 /// This constructor is safe if the raw pointer parameter is either null
84 /// (resulting in `None`), or a valid pointer to an `AParcel` object. The
85 /// parcel object must be owned by the caller prior to this call, as this
86 /// constructor takes ownership of the parcel and will destroy it on drop.
87 ///
88 /// Additionally, the caller must guarantee that it is valid to take
89 /// ownership of the AParcel object. All future access to the AParcel
Alice Ryhl8618c482021-11-09 15:35:35 +000090 /// must happen through this `Parcel`.
Alice Ryhl268458c2021-09-15 12:56:10 +000091 ///
Alice Ryhl8618c482021-11-09 15:35:35 +000092 /// Because `Parcel` implements `Send`, the pointer must never point to any
93 /// thread-local data, e.g., a variable on the stack, either directly or
94 /// indirectly.
95 pub unsafe fn from_raw(ptr: *mut sys::AParcel) -> Option<Parcel> {
96 NonNull::new(ptr).map(|ptr| Self { ptr })
Alice Ryhl268458c2021-09-15 12:56:10 +000097 }
98
99 /// Consume the parcel, transferring ownership to the caller.
100 pub(crate) fn into_raw(self) -> *mut sys::AParcel {
Alice Ryhl8618c482021-11-09 15:35:35 +0000101 let ptr = self.ptr.as_ptr();
Alice Ryhl268458c2021-09-15 12:56:10 +0000102 let _ = ManuallyDrop::new(self);
103 ptr
104 }
105
Alice Ryhl268458c2021-09-15 12:56:10 +0000106 /// Get a borrowed view into the contents of this `Parcel`.
107 pub fn borrowed(&mut self) -> BorrowedParcel<'_> {
Alice Ryhl8618c482021-11-09 15:35:35 +0000108 // Safety: The raw pointer is a valid pointer to an AParcel, and the
109 // lifetime of the returned `BorrowedParcel` is tied to `self`, so the
110 // borrow checker will ensure that the `AParcel` can only be accessed
111 // via the `BorrowParcel` until it goes out of scope.
Matthew Maurere268a9f2022-07-26 09:31:30 -0700112 BorrowedParcel { ptr: self.ptr, _lifetime: PhantomData }
Alice Ryhl268458c2021-09-15 12:56:10 +0000113 }
Alice Ryhl268458c2021-09-15 12:56:10 +0000114
Alice Ryhl8618c482021-11-09 15:35:35 +0000115 /// Get an immutable borrowed view into the contents of this `Parcel`.
116 pub fn borrowed_ref(&self) -> &BorrowedParcel<'_> {
117 // Safety: Parcel and BorrowedParcel are both represented in the same
118 // way as a NonNull<sys::AParcel> due to their use of repr(transparent),
119 // so casting references as done here is valid.
Matthew Maurere268a9f2022-07-26 09:31:30 -0700120 unsafe { &*(self as *const Parcel as *const BorrowedParcel<'_>) }
Stephen Crane2a3c2502020-06-16 17:48:35 -0700121 }
Stephen Crane2a3c2502020-06-16 17:48:35 -0700122}
123
Andrei Homescu72b799d2021-09-04 01:39:23 +0000124impl Default for Parcel {
125 fn default() -> Self {
126 Self::new()
127 }
128}
129
130impl Clone for Parcel {
131 fn clone(&self) -> Self {
132 let mut new_parcel = Self::new();
133 new_parcel
Alice Ryhl8618c482021-11-09 15:35:35 +0000134 .borrowed()
135 .append_all_from(self.borrowed_ref())
Andrei Homescu72b799d2021-09-04 01:39:23 +0000136 .expect("Failed to append from Parcel");
137 new_parcel
138 }
139}
140
Alice Ryhl8618c482021-11-09 15:35:35 +0000141impl<'a> BorrowedParcel<'a> {
142 /// Create a borrowed reference to a parcel object from a raw pointer.
143 ///
144 /// # Safety
145 ///
146 /// This constructor is safe if the raw pointer parameter is either null
147 /// (resulting in `None`), or a valid pointer to an `AParcel` object.
148 ///
149 /// Since the raw pointer is not restricted by any lifetime, the lifetime on
150 /// the returned `BorrowedParcel` object can be chosen arbitrarily by the
151 /// caller. The caller must ensure it is valid to mutably borrow the AParcel
152 /// for the duration of the lifetime that the caller chooses. Note that
153 /// since this is a mutable borrow, it must have exclusive access to the
154 /// AParcel for the duration of the borrow.
155 pub unsafe fn from_raw(ptr: *mut sys::AParcel) -> Option<BorrowedParcel<'a>> {
Matthew Maurere268a9f2022-07-26 09:31:30 -0700156 Some(Self { ptr: NonNull::new(ptr)?, _lifetime: PhantomData })
Alice Ryhl8618c482021-11-09 15:35:35 +0000157 }
158
159 /// Get a sub-reference to this reference to the parcel.
160 pub fn reborrow(&mut self) -> BorrowedParcel<'_> {
161 // Safety: The raw pointer is a valid pointer to an AParcel, and the
162 // lifetime of the returned `BorrowedParcel` is tied to `self`, so the
163 // borrow checker will ensure that the `AParcel` can only be accessed
164 // via the `BorrowParcel` until it goes out of scope.
Matthew Maurere268a9f2022-07-26 09:31:30 -0700165 BorrowedParcel { ptr: self.ptr, _lifetime: PhantomData }
Alice Ryhl8618c482021-11-09 15:35:35 +0000166 }
167}
168
Andrew Walbran2f3ff9f2023-07-07 16:58:13 +0100169/// Safety: The `Parcel` constructors guarantee that a `Parcel` object will
170/// always contain a valid pointer to an `AParcel`.
Alice Ryhl8618c482021-11-09 15:35:35 +0000171unsafe impl AsNative<sys::AParcel> for Parcel {
172 fn as_native(&self) -> *const sys::AParcel {
173 self.ptr.as_ptr()
174 }
175
176 fn as_native_mut(&mut self) -> *mut sys::AParcel {
177 self.ptr.as_ptr()
178 }
179}
180
Andrew Walbran2f3ff9f2023-07-07 16:58:13 +0100181/// Safety: The `BorrowedParcel` constructors guarantee that a `BorrowedParcel`
182/// object will always contain a valid pointer to an `AParcel`.
Alice Ryhl8618c482021-11-09 15:35:35 +0000183unsafe impl<'a> AsNative<sys::AParcel> for BorrowedParcel<'a> {
184 fn as_native(&self) -> *const sys::AParcel {
185 self.ptr.as_ptr()
186 }
187
188 fn as_native_mut(&mut self) -> *mut sys::AParcel {
189 self.ptr.as_ptr()
190 }
191}
192
Stephen Crane2a3c2502020-06-16 17:48:35 -0700193// Data serialization methods
Alice Ryhl8618c482021-11-09 15:35:35 +0000194impl<'a> BorrowedParcel<'a> {
Steven Morelandf183fdd2020-10-27 00:12:12 +0000195 /// Data written to parcelable is zero'd before being deleted or reallocated.
196 pub fn mark_sensitive(&mut self) {
Andrew Walbran2f3ff9f2023-07-07 16:58:13 +0100197 // Safety: guaranteed to have a parcel object, and this method never fails
198 unsafe { sys::AParcel_markSensitive(self.as_native()) }
Steven Morelandf183fdd2020-10-27 00:12:12 +0000199 }
200
Alice Ryhl8618c482021-11-09 15:35:35 +0000201 /// Write a type that implements [`Serialize`] to the parcel.
Stephen Crane2a3c2502020-06-16 17:48:35 -0700202 pub fn write<S: Serialize + ?Sized>(&mut self, parcelable: &S) -> Result<()> {
203 parcelable.serialize(self)
204 }
205
Alice Ryhl8618c482021-11-09 15:35:35 +0000206 /// Writes the length of a slice to the parcel.
Stephen Crane2a3c2502020-06-16 17:48:35 -0700207 ///
208 /// This is used in AIDL-generated client side code to indicate the
209 /// allocated space for an output array parameter.
210 pub fn write_slice_size<T>(&mut self, slice: Option<&[T]>) -> Result<()> {
211 if let Some(slice) = slice {
212 let len: i32 = slice.len().try_into().or(Err(StatusCode::BAD_VALUE))?;
213 self.write(&len)
214 } else {
215 self.write(&-1i32)
216 }
217 }
218
Alice Ryhl8618c482021-11-09 15:35:35 +0000219 /// Perform a series of writes to the parcel, prepended with the length
Stephen Craneaae76382020-08-03 14:12:15 -0700220 /// (in bytes) of the written data.
221 ///
222 /// The length `0i32` will be written to the parcel first, followed by the
223 /// writes performed by the callback. The initial length will then be
224 /// updated to the length of all data written by the callback, plus the
225 /// size of the length elemement itself (4 bytes).
226 ///
227 /// # Examples
228 ///
229 /// After the following call:
230 ///
231 /// ```
232 /// # use binder::{Binder, Interface, Parcel};
Alice Ryhl8618c482021-11-09 15:35:35 +0000233 /// # let mut parcel = Parcel::new();
Stephen Craneaae76382020-08-03 14:12:15 -0700234 /// parcel.sized_write(|subparcel| {
235 /// subparcel.write(&1u32)?;
236 /// subparcel.write(&2u32)?;
237 /// subparcel.write(&3u32)
238 /// });
239 /// ```
240 ///
241 /// `parcel` will contain the following:
242 ///
243 /// ```ignore
244 /// [16i32, 1u32, 2u32, 3u32]
245 /// ```
246 pub fn sized_write<F>(&mut self, f: F) -> Result<()>
Alice Ryhl8618c482021-11-09 15:35:35 +0000247 where
Matthew Maurere268a9f2022-07-26 09:31:30 -0700248 for<'b> F: FnOnce(&'b mut WritableSubParcel<'b>) -> Result<()>,
Stephen Craneaae76382020-08-03 14:12:15 -0700249 {
250 let start = self.get_data_position();
251 self.write(&0i32)?;
252 {
Alice Ryhl8618c482021-11-09 15:35:35 +0000253 let mut subparcel = WritableSubParcel(self.reborrow());
254 f(&mut subparcel)?;
Stephen Craneaae76382020-08-03 14:12:15 -0700255 }
256 let end = self.get_data_position();
Andrew Walbran2f3ff9f2023-07-07 16:58:13 +0100257 // Safety: start is less than the current size of the parcel data
258 // buffer, because we just got it with `get_data_position`.
Stephen Craneaae76382020-08-03 14:12:15 -0700259 unsafe {
260 self.set_data_position(start)?;
261 }
262 assert!(end >= start);
263 self.write(&(end - start))?;
Andrew Walbran2f3ff9f2023-07-07 16:58:13 +0100264 // Safety: end is less than the current size of the parcel data
265 // buffer, because we just got it with `get_data_position`.
Stephen Craneaae76382020-08-03 14:12:15 -0700266 unsafe {
267 self.set_data_position(end)?;
268 }
269 Ok(())
270 }
271
Stephen Crane2a3c2502020-06-16 17:48:35 -0700272 /// Returns the current position in the parcel data.
273 pub fn get_data_position(&self) -> i32 {
Andrew Walbran2f3ff9f2023-07-07 16:58:13 +0100274 // Safety: `BorrowedParcel` always contains a valid pointer to an
275 // `AParcel`, and this call is otherwise safe.
276 unsafe { sys::AParcel_getDataPosition(self.as_native()) }
Stephen Crane2a3c2502020-06-16 17:48:35 -0700277 }
278
Andrei Homescub0487442021-05-12 07:16:16 +0000279 /// Returns the total size of the parcel.
280 pub fn get_data_size(&self) -> i32 {
Andrew Walbran2f3ff9f2023-07-07 16:58:13 +0100281 // Safety: `BorrowedParcel` always contains a valid pointer to an
282 // `AParcel`, and this call is otherwise safe.
283 unsafe { sys::AParcel_getDataSize(self.as_native()) }
Andrei Homescub0487442021-05-12 07:16:16 +0000284 }
285
Stephen Crane2a3c2502020-06-16 17:48:35 -0700286 /// Move the current read/write position in the parcel.
287 ///
Stephen Crane2a3c2502020-06-16 17:48:35 -0700288 /// # Safety
289 ///
290 /// This method is safe if `pos` is less than the current size of the parcel
291 /// data buffer. Otherwise, we are relying on correct bounds checking in the
292 /// Parcel C++ code on every subsequent read or write to this parcel. If all
293 /// accesses are bounds checked, this call is still safe, but we can't rely
294 /// on that.
295 pub unsafe fn set_data_position(&self, pos: i32) -> Result<()> {
Andrew Walbran2f3ff9f2023-07-07 16:58:13 +0100296 // Safety: `BorrowedParcel` always contains a valid pointer to an
297 // `AParcel`, and the caller guarantees that `pos` is within bounds.
298 status_result(unsafe { sys::AParcel_setDataPosition(self.as_native(), pos) })
Stephen Crane2a3c2502020-06-16 17:48:35 -0700299 }
Andrei Homescu72b799d2021-09-04 01:39:23 +0000300
Alice Ryhl8618c482021-11-09 15:35:35 +0000301 /// Append a subset of another parcel.
Andrei Homescu72b799d2021-09-04 01:39:23 +0000302 ///
303 /// This appends `size` bytes of data from `other` starting at offset
Alice Ryhl8618c482021-11-09 15:35:35 +0000304 /// `start` to the current parcel, or returns an error if not possible.
Matthew Maurere268a9f2022-07-26 09:31:30 -0700305 pub fn append_from(
306 &mut self,
307 other: &impl AsNative<sys::AParcel>,
308 start: i32,
309 size: i32,
310 ) -> Result<()> {
Andrew Walbran2f3ff9f2023-07-07 16:58:13 +0100311 // Safety: `Parcel::appendFrom` from C++ checks that `start`
312 // and `size` are in bounds, and returns an error otherwise.
313 // Both `self` and `other` always contain valid pointers.
Andrei Homescu72b799d2021-09-04 01:39:23 +0000314 let status = unsafe {
Matthew Maurere268a9f2022-07-26 09:31:30 -0700315 sys::AParcel_appendFrom(other.as_native(), self.as_native_mut(), start, size)
Andrei Homescu72b799d2021-09-04 01:39:23 +0000316 };
317 status_result(status)
318 }
319
Alice Ryhl8618c482021-11-09 15:35:35 +0000320 /// Append the contents of another parcel.
321 pub fn append_all_from(&mut self, other: &impl AsNative<sys::AParcel>) -> Result<()> {
322 // Safety: `BorrowedParcel` always contains a valid pointer to an
323 // `AParcel`, and this call is otherwise safe.
324 let size = unsafe { sys::AParcel_getDataSize(other.as_native()) };
325 self.append_from(other, 0, size)
Andrei Homescu72b799d2021-09-04 01:39:23 +0000326 }
Stephen Crane2a3c2502020-06-16 17:48:35 -0700327}
328
Alice Ryhl8618c482021-11-09 15:35:35 +0000329/// A segment of a writable parcel, used for [`BorrowedParcel::sized_write`].
330pub struct WritableSubParcel<'a>(BorrowedParcel<'a>);
Stephen Craneaae76382020-08-03 14:12:15 -0700331
332impl<'a> WritableSubParcel<'a> {
333 /// Write a type that implements [`Serialize`] to the sub-parcel.
Alice Ryhl8618c482021-11-09 15:35:35 +0000334 pub fn write<S: Serialize + ?Sized>(&mut self, parcelable: &S) -> Result<()> {
335 parcelable.serialize(&mut self.0)
336 }
337}
338
339impl Parcel {
340 /// Data written to parcelable is zero'd before being deleted or reallocated.
341 pub fn mark_sensitive(&mut self) {
342 self.borrowed().mark_sensitive()
343 }
344
345 /// Write a type that implements [`Serialize`] to the parcel.
346 pub fn write<S: Serialize + ?Sized>(&mut self, parcelable: &S) -> Result<()> {
347 self.borrowed().write(parcelable)
348 }
349
350 /// Writes the length of a slice to the parcel.
351 ///
352 /// This is used in AIDL-generated client side code to indicate the
353 /// allocated space for an output array parameter.
354 pub fn write_slice_size<T>(&mut self, slice: Option<&[T]>) -> Result<()> {
355 self.borrowed().write_slice_size(slice)
356 }
357
358 /// Perform a series of writes to the parcel, prepended with the length
359 /// (in bytes) of the written data.
360 ///
361 /// The length `0i32` will be written to the parcel first, followed by the
362 /// writes performed by the callback. The initial length will then be
363 /// updated to the length of all data written by the callback, plus the
364 /// size of the length elemement itself (4 bytes).
365 ///
366 /// # Examples
367 ///
368 /// After the following call:
369 ///
370 /// ```
371 /// # use binder::{Binder, Interface, Parcel};
372 /// # let mut parcel = Parcel::new();
373 /// parcel.sized_write(|subparcel| {
374 /// subparcel.write(&1u32)?;
375 /// subparcel.write(&2u32)?;
376 /// subparcel.write(&3u32)
377 /// });
378 /// ```
379 ///
380 /// `parcel` will contain the following:
381 ///
382 /// ```ignore
383 /// [16i32, 1u32, 2u32, 3u32]
384 /// ```
385 pub fn sized_write<F>(&mut self, f: F) -> Result<()>
386 where
Matthew Maurere268a9f2022-07-26 09:31:30 -0700387 for<'b> F: FnOnce(&'b mut WritableSubParcel<'b>) -> Result<()>,
Alice Ryhl8618c482021-11-09 15:35:35 +0000388 {
389 self.borrowed().sized_write(f)
390 }
391
392 /// Returns the current position in the parcel data.
393 pub fn get_data_position(&self) -> i32 {
394 self.borrowed_ref().get_data_position()
395 }
396
397 /// Returns the total size of the parcel.
398 pub fn get_data_size(&self) -> i32 {
399 self.borrowed_ref().get_data_size()
400 }
401
402 /// Move the current read/write position in the parcel.
403 ///
404 /// # Safety
405 ///
406 /// This method is safe if `pos` is less than the current size of the parcel
407 /// data buffer. Otherwise, we are relying on correct bounds checking in the
408 /// Parcel C++ code on every subsequent read or write to this parcel. If all
409 /// accesses are bounds checked, this call is still safe, but we can't rely
410 /// on that.
411 pub unsafe fn set_data_position(&self, pos: i32) -> Result<()> {
Andrew Walbran2f3ff9f2023-07-07 16:58:13 +0100412 // Safety: We have the same safety requirements as
413 // `BorrowedParcel::set_data_position`.
414 unsafe { self.borrowed_ref().set_data_position(pos) }
Alice Ryhl8618c482021-11-09 15:35:35 +0000415 }
416
417 /// Append a subset of another parcel.
418 ///
419 /// This appends `size` bytes of data from `other` starting at offset
420 /// `start` to the current parcel, or returns an error if not possible.
Matthew Maurere268a9f2022-07-26 09:31:30 -0700421 pub fn append_from(
422 &mut self,
423 other: &impl AsNative<sys::AParcel>,
424 start: i32,
425 size: i32,
426 ) -> Result<()> {
Alice Ryhl8618c482021-11-09 15:35:35 +0000427 self.borrowed().append_from(other, start, size)
428 }
429
430 /// Append the contents of another parcel.
431 pub fn append_all_from(&mut self, other: &impl AsNative<sys::AParcel>) -> Result<()> {
432 self.borrowed().append_all_from(other)
Stephen Craneaae76382020-08-03 14:12:15 -0700433 }
434}
435
Stephen Crane2a3c2502020-06-16 17:48:35 -0700436// Data deserialization methods
Alice Ryhl8618c482021-11-09 15:35:35 +0000437impl<'a> BorrowedParcel<'a> {
438 /// Attempt to read a type that implements [`Deserialize`] from this parcel.
Stephen Crane2a3c2502020-06-16 17:48:35 -0700439 pub fn read<D: Deserialize>(&self) -> Result<D> {
440 D::deserialize(self)
441 }
442
Alice Ryhl8618c482021-11-09 15:35:35 +0000443 /// Attempt to read a type that implements [`Deserialize`] from this parcel
444 /// onto an existing value. This operation will overwrite the old value
445 /// partially or completely, depending on how much data is available.
Andrei Homescu50006152021-05-01 07:34:51 +0000446 pub fn read_onto<D: Deserialize>(&self, x: &mut D) -> Result<()> {
447 x.deserialize_from(self)
448 }
449
Andrei Homescub0487442021-05-12 07:16:16 +0000450 /// Safely read a sized parcelable.
451 ///
452 /// Read the size of a parcelable, compute the end position
453 /// of that parcelable, then build a sized readable sub-parcel
454 /// and call a closure with the sub-parcel as its parameter.
455 /// The closure can keep reading data from the sub-parcel
456 /// until it runs out of input data. The closure is responsible
457 /// for calling [`ReadableSubParcel::has_more_data`] to check for
458 /// more data before every read, at least until Rust generators
459 /// are stabilized.
460 /// After the closure returns, skip to the end of the current
461 /// parcelable regardless of how much the closure has read.
462 ///
463 /// # Examples
464 ///
465 /// ```no_run
466 /// let mut parcelable = Default::default();
467 /// parcel.sized_read(|subparcel| {
468 /// if subparcel.has_more_data() {
469 /// parcelable.a = subparcel.read()?;
470 /// }
471 /// if subparcel.has_more_data() {
472 /// parcelable.b = subparcel.read()?;
473 /// }
474 /// Ok(())
475 /// });
476 /// ```
477 ///
Alice Ryhl8618c482021-11-09 15:35:35 +0000478 pub fn sized_read<F>(&self, f: F) -> Result<()>
Andrei Homescub0487442021-05-12 07:16:16 +0000479 where
Matthew Maurere268a9f2022-07-26 09:31:30 -0700480 for<'b> F: FnOnce(ReadableSubParcel<'b>) -> Result<()>,
Andrei Homescub0487442021-05-12 07:16:16 +0000481 {
482 let start = self.get_data_position();
483 let parcelable_size: i32 = self.read()?;
Steven Moreland6d9e0772022-01-15 02:10:18 +0000484 if parcelable_size < 4 {
Andrei Homescub0487442021-05-12 07:16:16 +0000485 return Err(StatusCode::BAD_VALUE);
486 }
487
Matthew Maurere268a9f2022-07-26 09:31:30 -0700488 let end = start.checked_add(parcelable_size).ok_or(StatusCode::BAD_VALUE)?;
Andrei Homescub0487442021-05-12 07:16:16 +0000489 if end > self.get_data_size() {
490 return Err(StatusCode::NOT_ENOUGH_DATA);
491 }
492
493 let subparcel = ReadableSubParcel {
Matthew Maurere268a9f2022-07-26 09:31:30 -0700494 parcel: BorrowedParcel { ptr: self.ptr, _lifetime: PhantomData },
Andrei Homescub0487442021-05-12 07:16:16 +0000495 end_position: end,
496 };
497 f(subparcel)?;
498
499 // Advance the data position to the actual end,
Andrew Walbran2f3ff9f2023-07-07 16:58:13 +0100500 // in case the closure read less data than was available.
501 //
502 // Safety: end must be less than the current size of the parcel, because
503 // we checked above against `get_data_size`.
Andrei Homescub0487442021-05-12 07:16:16 +0000504 unsafe {
505 self.set_data_position(end)?;
506 }
507
508 Ok(())
509 }
510
Alice Ryhl8618c482021-11-09 15:35:35 +0000511 /// Read a vector size from the parcel and resize the given output vector to
512 /// be correctly sized for that amount of data.
Stephen Crane2a3c2502020-06-16 17:48:35 -0700513 ///
514 /// This method is used in AIDL-generated server side code for methods that
515 /// take a mutable slice reference parameter.
516 pub fn resize_out_vec<D: Default + Deserialize>(&self, out_vec: &mut Vec<D>) -> Result<()> {
517 let len: i32 = self.read()?;
518
519 if len < 0 {
520 return Err(StatusCode::UNEXPECTED_NULL);
521 }
522
523 // usize in Rust may be 16-bit, so i32 may not fit
524 let len = len.try_into().unwrap();
525 out_vec.resize_with(len, Default::default);
526
527 Ok(())
528 }
529
Alice Ryhl8618c482021-11-09 15:35:35 +0000530 /// Read a vector size from the parcel and either create a correctly sized
Stephen Crane2a3c2502020-06-16 17:48:35 -0700531 /// vector for that amount of data or set the output parameter to None if
532 /// the vector should be null.
533 ///
534 /// This method is used in AIDL-generated server side code for methods that
535 /// take a mutable slice reference parameter.
536 pub fn resize_nullable_out_vec<D: Default + Deserialize>(
537 &self,
538 out_vec: &mut Option<Vec<D>>,
539 ) -> Result<()> {
540 let len: i32 = self.read()?;
541
542 if len < 0 {
543 *out_vec = None;
544 } else {
545 // usize in Rust may be 16-bit, so i32 may not fit
546 let len = len.try_into().unwrap();
547 let mut vec = Vec::with_capacity(len);
548 vec.resize_with(len, Default::default);
549 *out_vec = Some(vec);
550 }
551
552 Ok(())
553 }
554}
555
Andrei Homescub0487442021-05-12 07:16:16 +0000556/// A segment of a readable parcel, used for [`Parcel::sized_read`].
557pub struct ReadableSubParcel<'a> {
Alice Ryhl8618c482021-11-09 15:35:35 +0000558 parcel: BorrowedParcel<'a>,
Andrei Homescub0487442021-05-12 07:16:16 +0000559 end_position: i32,
560}
561
562impl<'a> ReadableSubParcel<'a> {
563 /// Read a type that implements [`Deserialize`] from the sub-parcel.
564 pub fn read<D: Deserialize>(&self) -> Result<D> {
Alice Ryhl8618c482021-11-09 15:35:35 +0000565 D::deserialize(&self.parcel)
Andrei Homescub0487442021-05-12 07:16:16 +0000566 }
567
568 /// Check if the sub-parcel has more data to read
569 pub fn has_more_data(&self) -> bool {
570 self.parcel.get_data_position() < self.end_position
571 }
572}
573
Stephen Crane2a3c2502020-06-16 17:48:35 -0700574impl Parcel {
Alice Ryhl8618c482021-11-09 15:35:35 +0000575 /// Attempt to read a type that implements [`Deserialize`] from this parcel.
576 pub fn read<D: Deserialize>(&self) -> Result<D> {
577 self.borrowed_ref().read()
578 }
579
580 /// Attempt to read a type that implements [`Deserialize`] from this parcel
581 /// onto an existing value. This operation will overwrite the old value
582 /// partially or completely, depending on how much data is available.
583 pub fn read_onto<D: Deserialize>(&self, x: &mut D) -> Result<()> {
584 self.borrowed_ref().read_onto(x)
585 }
586
587 /// Safely read a sized parcelable.
588 ///
589 /// Read the size of a parcelable, compute the end position
590 /// of that parcelable, then build a sized readable sub-parcel
591 /// and call a closure with the sub-parcel as its parameter.
592 /// The closure can keep reading data from the sub-parcel
593 /// until it runs out of input data. The closure is responsible
594 /// for calling [`ReadableSubParcel::has_more_data`] to check for
595 /// more data before every read, at least until Rust generators
596 /// are stabilized.
597 /// After the closure returns, skip to the end of the current
598 /// parcelable regardless of how much the closure has read.
599 ///
600 /// # Examples
601 ///
602 /// ```no_run
603 /// let mut parcelable = Default::default();
604 /// parcel.sized_read(|subparcel| {
605 /// if subparcel.has_more_data() {
606 /// parcelable.a = subparcel.read()?;
607 /// }
608 /// if subparcel.has_more_data() {
609 /// parcelable.b = subparcel.read()?;
610 /// }
611 /// Ok(())
612 /// });
613 /// ```
614 ///
615 pub fn sized_read<F>(&self, f: F) -> Result<()>
616 where
Matthew Maurere268a9f2022-07-26 09:31:30 -0700617 for<'b> F: FnOnce(ReadableSubParcel<'b>) -> Result<()>,
Alice Ryhl8618c482021-11-09 15:35:35 +0000618 {
619 self.borrowed_ref().sized_read(f)
620 }
621
622 /// Read a vector size from the parcel and resize the given output vector to
623 /// be correctly sized for that amount of data.
624 ///
625 /// This method is used in AIDL-generated server side code for methods that
626 /// take a mutable slice reference parameter.
627 pub fn resize_out_vec<D: Default + Deserialize>(&self, out_vec: &mut Vec<D>) -> Result<()> {
628 self.borrowed_ref().resize_out_vec(out_vec)
629 }
630
631 /// Read a vector size from the parcel and either create a correctly sized
632 /// vector for that amount of data or set the output parameter to None if
633 /// the vector should be null.
634 ///
635 /// This method is used in AIDL-generated server side code for methods that
636 /// take a mutable slice reference parameter.
637 pub fn resize_nullable_out_vec<D: Default + Deserialize>(
638 &self,
639 out_vec: &mut Option<Vec<D>>,
640 ) -> Result<()> {
641 self.borrowed_ref().resize_nullable_out_vec(out_vec)
642 }
643}
644
645// Internal APIs
646impl<'a> BorrowedParcel<'a> {
Stephen Crane2a3c2502020-06-16 17:48:35 -0700647 pub(crate) fn write_binder(&mut self, binder: Option<&SpIBinder>) -> Result<()> {
Andrew Walbran2f3ff9f2023-07-07 16:58:13 +0100648 // Safety: `BorrowedParcel` always contains a valid pointer to an
649 // `AParcel`. `AsNative` for `Option<SpIBinder`> will either return
650 // null or a valid pointer to an `AIBinder`, both of which are
651 // valid, safe inputs to `AParcel_writeStrongBinder`.
652 //
653 // This call does not take ownership of the binder. However, it does
654 // require a mutable pointer, which we cannot extract from an
655 // immutable reference, so we clone the binder, incrementing the
656 // refcount before the call. The refcount will be immediately
657 // decremented when this temporary is dropped.
Stephen Crane2a3c2502020-06-16 17:48:35 -0700658 unsafe {
Stephen Crane2a3c2502020-06-16 17:48:35 -0700659 status_result(sys::AParcel_writeStrongBinder(
660 self.as_native_mut(),
661 binder.cloned().as_native_mut(),
662 ))
663 }
664 }
665
666 pub(crate) fn read_binder(&self) -> Result<Option<SpIBinder>> {
667 let mut binder = ptr::null_mut();
Andrew Walbran2f3ff9f2023-07-07 16:58:13 +0100668 // Safety: `BorrowedParcel` always contains a valid pointer to an
669 // `AParcel`. We pass a valid, mutable out pointer to the `binder`
670 // parameter. After this call, `binder` will be either null or a
671 // valid pointer to an `AIBinder` owned by the caller.
672 let status = unsafe { sys::AParcel_readStrongBinder(self.as_native(), &mut binder) };
Stephen Crane2a3c2502020-06-16 17:48:35 -0700673
674 status_result(status)?;
675
Andrew Walbran2f3ff9f2023-07-07 16:58:13 +0100676 // Safety: `binder` is either null or a valid, owned pointer at this
677 // point, so can be safely passed to `SpIBinder::from_raw`.
678 Ok(unsafe { SpIBinder::from_raw(binder) })
Stephen Crane2a3c2502020-06-16 17:48:35 -0700679 }
680}
681
682impl Drop for Parcel {
683 fn drop(&mut self) {
684 // Run the C++ Parcel complete object destructor
Andrew Walbran2f3ff9f2023-07-07 16:58:13 +0100685 //
686 // Safety: `Parcel` always contains a valid pointer to an
687 // `AParcel`. Since we own the parcel, we can safely delete it
688 // here.
689 unsafe { sys::AParcel_delete(self.ptr.as_ptr()) }
Alice Ryhl268458c2021-09-15 12:56:10 +0000690 }
691}
692
Alice Ryhlfeba6ca2021-08-19 10:47:04 +0000693impl fmt::Debug for Parcel {
694 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
Matthew Maurere268a9f2022-07-26 09:31:30 -0700695 f.debug_struct("Parcel").finish()
Alice Ryhlfeba6ca2021-08-19 10:47:04 +0000696 }
697}
698
Alice Ryhl8618c482021-11-09 15:35:35 +0000699impl<'a> fmt::Debug for BorrowedParcel<'a> {
Alice Ryhl268458c2021-09-15 12:56:10 +0000700 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
Matthew Maurere268a9f2022-07-26 09:31:30 -0700701 f.debug_struct("BorrowedParcel").finish()
Alice Ryhl268458c2021-09-15 12:56:10 +0000702 }
703}
704
Stephen Crane2a3c2502020-06-16 17:48:35 -0700705#[test]
706fn test_read_write() {
Andrei Homescu72b799d2021-09-04 01:39:23 +0000707 let mut parcel = Parcel::new();
Stephen Crane2a3c2502020-06-16 17:48:35 -0700708 let start = parcel.get_data_position();
709
710 assert_eq!(parcel.read::<bool>(), Err(StatusCode::NOT_ENOUGH_DATA));
711 assert_eq!(parcel.read::<i8>(), Err(StatusCode::NOT_ENOUGH_DATA));
712 assert_eq!(parcel.read::<u16>(), Err(StatusCode::NOT_ENOUGH_DATA));
713 assert_eq!(parcel.read::<i32>(), Err(StatusCode::NOT_ENOUGH_DATA));
714 assert_eq!(parcel.read::<u32>(), Err(StatusCode::NOT_ENOUGH_DATA));
715 assert_eq!(parcel.read::<i64>(), Err(StatusCode::NOT_ENOUGH_DATA));
716 assert_eq!(parcel.read::<u64>(), Err(StatusCode::NOT_ENOUGH_DATA));
717 assert_eq!(parcel.read::<f32>(), Err(StatusCode::NOT_ENOUGH_DATA));
718 assert_eq!(parcel.read::<f64>(), Err(StatusCode::NOT_ENOUGH_DATA));
Stephen Crane76072e82020-08-03 13:09:36 -0700719 assert_eq!(parcel.read::<Option<String>>(), Ok(None));
Stephen Crane2a3c2502020-06-16 17:48:35 -0700720 assert_eq!(parcel.read::<String>(), Err(StatusCode::UNEXPECTED_NULL));
721
Alice Ryhl8618c482021-11-09 15:35:35 +0000722 assert_eq!(parcel.borrowed_ref().read_binder().err(), Some(StatusCode::BAD_TYPE));
Stephen Crane2a3c2502020-06-16 17:48:35 -0700723
724 parcel.write(&1i32).unwrap();
725
726 unsafe {
727 parcel.set_data_position(start).unwrap();
728 }
729
730 let i: i32 = parcel.read().unwrap();
731 assert_eq!(i, 1i32);
732}
733
734#[test]
735#[allow(clippy::float_cmp)]
736fn test_read_data() {
Andrei Homescu72b799d2021-09-04 01:39:23 +0000737 let mut parcel = Parcel::new();
Stephen Crane2a3c2502020-06-16 17:48:35 -0700738 let str_start = parcel.get_data_position();
739
740 parcel.write(&b"Hello, Binder!\0"[..]).unwrap();
741 // Skip over string length
742 unsafe {
743 assert!(parcel.set_data_position(str_start).is_ok());
744 }
745 assert_eq!(parcel.read::<i32>().unwrap(), 15);
746 let start = parcel.get_data_position();
747
Chris Wailes45fd2942021-07-26 19:18:41 -0700748 assert!(parcel.read::<bool>().unwrap());
Stephen Crane2a3c2502020-06-16 17:48:35 -0700749
750 unsafe {
751 assert!(parcel.set_data_position(start).is_ok());
752 }
753
754 assert_eq!(parcel.read::<i8>().unwrap(), 72i8);
755
756 unsafe {
757 assert!(parcel.set_data_position(start).is_ok());
758 }
759
760 assert_eq!(parcel.read::<u16>().unwrap(), 25928);
761
762 unsafe {
763 assert!(parcel.set_data_position(start).is_ok());
764 }
765
766 assert_eq!(parcel.read::<i32>().unwrap(), 1819043144);
767
768 unsafe {
769 assert!(parcel.set_data_position(start).is_ok());
770 }
771
772 assert_eq!(parcel.read::<u32>().unwrap(), 1819043144);
773
774 unsafe {
775 assert!(parcel.set_data_position(start).is_ok());
776 }
777
778 assert_eq!(parcel.read::<i64>().unwrap(), 4764857262830019912);
779
780 unsafe {
781 assert!(parcel.set_data_position(start).is_ok());
782 }
783
784 assert_eq!(parcel.read::<u64>().unwrap(), 4764857262830019912);
785
786 unsafe {
787 assert!(parcel.set_data_position(start).is_ok());
788 }
789
Matthew Maurere268a9f2022-07-26 09:31:30 -0700790 assert_eq!(parcel.read::<f32>().unwrap(), 1143139100000000000000000000.0);
Stephen Crane2a3c2502020-06-16 17:48:35 -0700791 assert_eq!(parcel.read::<f32>().unwrap(), 40.043392);
792
793 unsafe {
794 assert!(parcel.set_data_position(start).is_ok());
795 }
796
797 assert_eq!(parcel.read::<f64>().unwrap(), 34732488246.197815);
798
799 // Skip back to before the string length
800 unsafe {
801 assert!(parcel.set_data_position(str_start).is_ok());
802 }
803
804 assert_eq!(parcel.read::<Vec<u8>>().unwrap(), b"Hello, Binder!\0");
805}
806
807#[test]
808fn test_utf8_utf16_conversions() {
Andrei Homescu72b799d2021-09-04 01:39:23 +0000809 let mut parcel = Parcel::new();
Stephen Crane2a3c2502020-06-16 17:48:35 -0700810 let start = parcel.get_data_position();
811
812 assert!(parcel.write("Hello, Binder!").is_ok());
813 unsafe {
814 assert!(parcel.set_data_position(start).is_ok());
815 }
Matthew Maurere268a9f2022-07-26 09:31:30 -0700816 assert_eq!(parcel.read::<Option<String>>().unwrap().unwrap(), "Hello, Binder!",);
Stephen Crane2a3c2502020-06-16 17:48:35 -0700817 unsafe {
818 assert!(parcel.set_data_position(start).is_ok());
819 }
Stephen Crane76072e82020-08-03 13:09:36 -0700820
821 assert!(parcel.write("Embedded null \0 inside a string").is_ok());
822 unsafe {
823 assert!(parcel.set_data_position(start).is_ok());
824 }
825 assert_eq!(
826 parcel.read::<Option<String>>().unwrap().unwrap(),
827 "Embedded null \0 inside a string",
828 );
829 unsafe {
830 assert!(parcel.set_data_position(start).is_ok());
831 }
832
Stephen Crane2a3c2502020-06-16 17:48:35 -0700833 assert!(parcel.write(&["str1", "str2", "str3"][..]).is_ok());
834 assert!(parcel
Matthew Maurere268a9f2022-07-26 09:31:30 -0700835 .write(&[String::from("str4"), String::from("str5"), String::from("str6"),][..])
Stephen Crane2a3c2502020-06-16 17:48:35 -0700836 .is_ok());
837
838 let s1 = "Hello, Binder!";
839 let s2 = "This is a utf8 string.";
840 let s3 = "Some more text here.";
841
842 assert!(parcel.write(&[s1, s2, s3][..]).is_ok());
843 unsafe {
844 assert!(parcel.set_data_position(start).is_ok());
845 }
846
Matthew Maurere268a9f2022-07-26 09:31:30 -0700847 assert_eq!(parcel.read::<Vec<String>>().unwrap(), ["str1", "str2", "str3"]);
848 assert_eq!(parcel.read::<Vec<String>>().unwrap(), ["str4", "str5", "str6"]);
Stephen Crane2a3c2502020-06-16 17:48:35 -0700849 assert_eq!(parcel.read::<Vec<String>>().unwrap(), [s1, s2, s3]);
850}
Stephen Craneaae76382020-08-03 14:12:15 -0700851
852#[test]
853fn test_sized_write() {
Andrei Homescu72b799d2021-09-04 01:39:23 +0000854 let mut parcel = Parcel::new();
Stephen Craneaae76382020-08-03 14:12:15 -0700855 let start = parcel.get_data_position();
856
857 let arr = [1i32, 2i32, 3i32];
858
Matthew Maurere268a9f2022-07-26 09:31:30 -0700859 parcel
860 .sized_write(|subparcel| subparcel.write(&arr[..]))
861 .expect("Could not perform sized write");
Stephen Craneaae76382020-08-03 14:12:15 -0700862
863 // i32 sub-parcel length + i32 array length + 3 i32 elements
864 let expected_len = 20i32;
865
866 assert_eq!(parcel.get_data_position(), start + expected_len);
867
868 unsafe {
869 parcel.set_data_position(start).unwrap();
870 }
871
Matthew Maurere268a9f2022-07-26 09:31:30 -0700872 assert_eq!(expected_len, parcel.read().unwrap(),);
Stephen Craneaae76382020-08-03 14:12:15 -0700873
Matthew Maurere268a9f2022-07-26 09:31:30 -0700874 assert_eq!(parcel.read::<Vec<i32>>().unwrap(), &arr,);
Stephen Craneaae76382020-08-03 14:12:15 -0700875}
Andrei Homescu72b799d2021-09-04 01:39:23 +0000876
877#[test]
878fn test_append_from() {
879 let mut parcel1 = Parcel::new();
880 parcel1.write(&42i32).expect("Could not perform write");
881
882 let mut parcel2 = Parcel::new();
883 assert_eq!(Ok(()), parcel2.append_all_from(&parcel1));
884 assert_eq!(4, parcel2.get_data_size());
885 assert_eq!(Ok(()), parcel2.append_all_from(&parcel1));
886 assert_eq!(8, parcel2.get_data_size());
887 unsafe {
888 parcel2.set_data_position(0).unwrap();
889 }
890 assert_eq!(Ok(42), parcel2.read::<i32>());
891 assert_eq!(Ok(42), parcel2.read::<i32>());
892
893 let mut parcel2 = Parcel::new();
894 assert_eq!(Ok(()), parcel2.append_from(&parcel1, 0, 2));
895 assert_eq!(Ok(()), parcel2.append_from(&parcel1, 2, 2));
896 assert_eq!(4, parcel2.get_data_size());
897 unsafe {
898 parcel2.set_data_position(0).unwrap();
899 }
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!(2, parcel2.get_data_size());
905 unsafe {
906 parcel2.set_data_position(0).unwrap();
907 }
908 assert_eq!(Err(StatusCode::NOT_ENOUGH_DATA), parcel2.read::<i32>());
909
910 let mut parcel2 = Parcel::new();
911 assert_eq!(Err(StatusCode::BAD_VALUE), parcel2.append_from(&parcel1, 4, 2));
912 assert_eq!(Err(StatusCode::BAD_VALUE), parcel2.append_from(&parcel1, 2, 4));
913 assert_eq!(Err(StatusCode::BAD_VALUE), parcel2.append_from(&parcel1, -1, 4));
914 assert_eq!(Err(StatusCode::BAD_VALUE), parcel2.append_from(&parcel1, 2, -1));
915}