blob: 8e6c94c7496c8036515ad2668dbcd152d9b8dda6 [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
Stephen Craneaae76382020-08-03 14:12:15 -070024use std::cell::RefCell;
Stephen Crane2a3c2502020-06-16 17:48:35 -070025use std::convert::TryInto;
26use std::mem::ManuallyDrop;
27use std::ptr;
Alice Ryhlfeba6ca2021-08-19 10:47:04 +000028use std::fmt;
Stephen Crane2a3c2502020-06-16 17:48:35 -070029
30mod file_descriptor;
31mod parcelable;
32
33pub use self::file_descriptor::ParcelFileDescriptor;
34pub use self::parcelable::{
35 Deserialize, DeserializeArray, DeserializeOption, Serialize, SerializeArray, SerializeOption,
Andrei Homescu5c133842021-09-03 03:01:28 +000036 Parcelable,
Stephen Crane2a3c2502020-06-16 17:48:35 -070037};
38
39/// Container for a message (data and object references) that can be sent
40/// through Binder.
41///
42/// A Parcel can contain both serialized data that will be deserialized on the
43/// other side of the IPC, and references to live Binder objects that will
44/// result in the other side receiving a proxy Binder connected with the
45/// original Binder in the Parcel.
46pub enum Parcel {
47 /// Owned parcel pointer
48 Owned(*mut sys::AParcel),
49 /// Borrowed parcel pointer (will not be destroyed on drop)
50 Borrowed(*mut sys::AParcel),
51}
52
53/// # Safety
54///
55/// The `Parcel` constructors guarantee that a `Parcel` object will always
56/// contain a valid pointer to an `AParcel`.
57unsafe impl AsNative<sys::AParcel> for Parcel {
58 fn as_native(&self) -> *const sys::AParcel {
59 match *self {
60 Self::Owned(x) | Self::Borrowed(x) => x,
61 }
62 }
63
64 fn as_native_mut(&mut self) -> *mut sys::AParcel {
65 match *self {
66 Self::Owned(x) | Self::Borrowed(x) => x,
67 }
68 }
69}
70
71impl Parcel {
72 /// Create a borrowed reference to a parcel object from a raw pointer.
73 ///
74 /// # Safety
75 ///
76 /// This constructor is safe if the raw pointer parameter is either null
77 /// (resulting in `None`), or a valid pointer to an `AParcel` object.
78 pub(crate) unsafe fn borrowed(ptr: *mut sys::AParcel) -> Option<Parcel> {
79 ptr.as_mut().map(|ptr| Self::Borrowed(ptr))
80 }
81
82 /// Create an owned reference to a parcel object from a raw pointer.
83 ///
84 /// # Safety
85 ///
86 /// This constructor is safe if the raw pointer parameter is either null
87 /// (resulting in `None`), or a valid pointer to an `AParcel` object. The
88 /// parcel object must be owned by the caller prior to this call, as this
89 /// constructor takes ownership of the parcel and will destroy it on drop.
90 pub(crate) unsafe fn owned(ptr: *mut sys::AParcel) -> Option<Parcel> {
91 ptr.as_mut().map(|ptr| Self::Owned(ptr))
92 }
93
94 /// Consume the parcel, transferring ownership to the caller if the parcel
95 /// was owned.
96 pub(crate) fn into_raw(mut self) -> *mut sys::AParcel {
97 let ptr = self.as_native_mut();
98 let _ = ManuallyDrop::new(self);
99 ptr
100 }
Alice Ryhlfeba6ca2021-08-19 10:47:04 +0000101
102 pub(crate) fn is_owned(&self) -> bool {
103 match *self {
104 Self::Owned(_) => true,
105 Self::Borrowed(_) => false,
106 }
107 }
Stephen Crane2a3c2502020-06-16 17:48:35 -0700108}
109
110// Data serialization methods
111impl Parcel {
Steven Morelandf183fdd2020-10-27 00:12:12 +0000112 /// Data written to parcelable is zero'd before being deleted or reallocated.
113 pub fn mark_sensitive(&mut self) {
114 unsafe {
115 // Safety: guaranteed to have a parcel object, and this method never fails
116 sys::AParcel_markSensitive(self.as_native())
117 }
118 }
119
Stephen Crane2a3c2502020-06-16 17:48:35 -0700120 /// Write a type that implements [`Serialize`] to the `Parcel`.
121 pub fn write<S: Serialize + ?Sized>(&mut self, parcelable: &S) -> Result<()> {
122 parcelable.serialize(self)
123 }
124
125 /// Writes the length of a slice to the `Parcel`.
126 ///
127 /// This is used in AIDL-generated client side code to indicate the
128 /// allocated space for an output array parameter.
129 pub fn write_slice_size<T>(&mut self, slice: Option<&[T]>) -> Result<()> {
130 if let Some(slice) = slice {
131 let len: i32 = slice.len().try_into().or(Err(StatusCode::BAD_VALUE))?;
132 self.write(&len)
133 } else {
134 self.write(&-1i32)
135 }
136 }
137
Stephen Craneaae76382020-08-03 14:12:15 -0700138 /// Perform a series of writes to the `Parcel`, prepended with the length
139 /// (in bytes) of the written data.
140 ///
141 /// The length `0i32` will be written to the parcel first, followed by the
142 /// writes performed by the callback. The initial length will then be
143 /// updated to the length of all data written by the callback, plus the
144 /// size of the length elemement itself (4 bytes).
145 ///
146 /// # Examples
147 ///
148 /// After the following call:
149 ///
150 /// ```
151 /// # use binder::{Binder, Interface, Parcel};
152 /// # let mut parcel = Parcel::Owned(std::ptr::null_mut());
153 /// parcel.sized_write(|subparcel| {
154 /// subparcel.write(&1u32)?;
155 /// subparcel.write(&2u32)?;
156 /// subparcel.write(&3u32)
157 /// });
158 /// ```
159 ///
160 /// `parcel` will contain the following:
161 ///
162 /// ```ignore
163 /// [16i32, 1u32, 2u32, 3u32]
164 /// ```
165 pub fn sized_write<F>(&mut self, f: F) -> Result<()>
166 where for<'a>
167 F: Fn(&'a WritableSubParcel<'a>) -> Result<()>
168 {
169 let start = self.get_data_position();
170 self.write(&0i32)?;
171 {
172 let subparcel = WritableSubParcel(RefCell::new(self));
173 f(&subparcel)?;
174 }
175 let end = self.get_data_position();
176 unsafe {
177 self.set_data_position(start)?;
178 }
179 assert!(end >= start);
180 self.write(&(end - start))?;
181 unsafe {
182 self.set_data_position(end)?;
183 }
184 Ok(())
185 }
186
Stephen Crane2a3c2502020-06-16 17:48:35 -0700187 /// Returns the current position in the parcel data.
188 pub fn get_data_position(&self) -> i32 {
189 unsafe {
190 // Safety: `Parcel` always contains a valid pointer to an `AParcel`,
191 // and this call is otherwise safe.
192 sys::AParcel_getDataPosition(self.as_native())
193 }
194 }
195
Andrei Homescub0487442021-05-12 07:16:16 +0000196 /// Returns the total size of the parcel.
197 pub fn get_data_size(&self) -> i32 {
198 unsafe {
199 // Safety: `Parcel` always contains a valid pointer to an `AParcel`,
200 // and this call is otherwise safe.
201 sys::AParcel_getDataSize(self.as_native())
202 }
203 }
204
Stephen Crane2a3c2502020-06-16 17:48:35 -0700205 /// Move the current read/write position in the parcel.
206 ///
Stephen Crane2a3c2502020-06-16 17:48:35 -0700207 /// # Safety
208 ///
209 /// This method is safe if `pos` is less than the current size of the parcel
210 /// data buffer. Otherwise, we are relying on correct bounds checking in the
211 /// Parcel C++ code on every subsequent read or write to this parcel. If all
212 /// accesses are bounds checked, this call is still safe, but we can't rely
213 /// on that.
214 pub unsafe fn set_data_position(&self, pos: i32) -> Result<()> {
215 status_result(sys::AParcel_setDataPosition(self.as_native(), pos))
216 }
217}
218
Stephen Craneaae76382020-08-03 14:12:15 -0700219/// A segment of a writable parcel, used for [`Parcel::sized_write`].
220pub struct WritableSubParcel<'a>(RefCell<&'a mut Parcel>);
221
222impl<'a> WritableSubParcel<'a> {
223 /// Write a type that implements [`Serialize`] to the sub-parcel.
224 pub fn write<S: Serialize + ?Sized>(&self, parcelable: &S) -> Result<()> {
225 parcelable.serialize(&mut *self.0.borrow_mut())
226 }
227}
228
Stephen Crane2a3c2502020-06-16 17:48:35 -0700229// Data deserialization methods
230impl Parcel {
231 /// Attempt to read a type that implements [`Deserialize`] from this
232 /// `Parcel`.
233 pub fn read<D: Deserialize>(&self) -> Result<D> {
234 D::deserialize(self)
235 }
236
Andrei Homescu50006152021-05-01 07:34:51 +0000237 /// Attempt to read a type that implements [`Deserialize`] from this
238 /// `Parcel` onto an existing value. This operation will overwrite the old
239 /// value partially or completely, depending on how much data is available.
240 pub fn read_onto<D: Deserialize>(&self, x: &mut D) -> Result<()> {
241 x.deserialize_from(self)
242 }
243
Andrei Homescub0487442021-05-12 07:16:16 +0000244 /// Safely read a sized parcelable.
245 ///
246 /// Read the size of a parcelable, compute the end position
247 /// of that parcelable, then build a sized readable sub-parcel
248 /// and call a closure with the sub-parcel as its parameter.
249 /// The closure can keep reading data from the sub-parcel
250 /// until it runs out of input data. The closure is responsible
251 /// for calling [`ReadableSubParcel::has_more_data`] to check for
252 /// more data before every read, at least until Rust generators
253 /// are stabilized.
254 /// After the closure returns, skip to the end of the current
255 /// parcelable regardless of how much the closure has read.
256 ///
257 /// # Examples
258 ///
259 /// ```no_run
260 /// let mut parcelable = Default::default();
261 /// parcel.sized_read(|subparcel| {
262 /// if subparcel.has_more_data() {
263 /// parcelable.a = subparcel.read()?;
264 /// }
265 /// if subparcel.has_more_data() {
266 /// parcelable.b = subparcel.read()?;
267 /// }
268 /// Ok(())
269 /// });
270 /// ```
271 ///
272 pub fn sized_read<F>(&self, mut f: F) -> Result<()>
273 where
274 for<'a> F: FnMut(ReadableSubParcel<'a>) -> Result<()>
275 {
276 let start = self.get_data_position();
277 let parcelable_size: i32 = self.read()?;
278 if parcelable_size < 0 {
279 return Err(StatusCode::BAD_VALUE);
280 }
281
282 let end = start.checked_add(parcelable_size)
283 .ok_or(StatusCode::BAD_VALUE)?;
284 if end > self.get_data_size() {
285 return Err(StatusCode::NOT_ENOUGH_DATA);
286 }
287
288 let subparcel = ReadableSubParcel {
289 parcel: self,
290 end_position: end,
291 };
292 f(subparcel)?;
293
294 // Advance the data position to the actual end,
295 // in case the closure read less data than was available
296 unsafe {
297 self.set_data_position(end)?;
298 }
299
300 Ok(())
301 }
302
Stephen Crane2a3c2502020-06-16 17:48:35 -0700303 /// Read a vector size from the `Parcel` and resize the given output vector
304 /// to be correctly sized for that amount of data.
305 ///
306 /// This method is used in AIDL-generated server side code for methods that
307 /// take a mutable slice reference parameter.
308 pub fn resize_out_vec<D: Default + Deserialize>(&self, out_vec: &mut Vec<D>) -> Result<()> {
309 let len: i32 = self.read()?;
310
311 if len < 0 {
312 return Err(StatusCode::UNEXPECTED_NULL);
313 }
314
315 // usize in Rust may be 16-bit, so i32 may not fit
316 let len = len.try_into().unwrap();
317 out_vec.resize_with(len, Default::default);
318
319 Ok(())
320 }
321
322 /// Read a vector size from the `Parcel` and either create a correctly sized
323 /// vector for that amount of data or set the output parameter to None if
324 /// the vector should be null.
325 ///
326 /// This method is used in AIDL-generated server side code for methods that
327 /// take a mutable slice reference parameter.
328 pub fn resize_nullable_out_vec<D: Default + Deserialize>(
329 &self,
330 out_vec: &mut Option<Vec<D>>,
331 ) -> Result<()> {
332 let len: i32 = self.read()?;
333
334 if len < 0 {
335 *out_vec = None;
336 } else {
337 // usize in Rust may be 16-bit, so i32 may not fit
338 let len = len.try_into().unwrap();
339 let mut vec = Vec::with_capacity(len);
340 vec.resize_with(len, Default::default);
341 *out_vec = Some(vec);
342 }
343
344 Ok(())
345 }
346}
347
Andrei Homescub0487442021-05-12 07:16:16 +0000348/// A segment of a readable parcel, used for [`Parcel::sized_read`].
349pub struct ReadableSubParcel<'a> {
350 parcel: &'a Parcel,
351 end_position: i32,
352}
353
354impl<'a> ReadableSubParcel<'a> {
355 /// Read a type that implements [`Deserialize`] from the sub-parcel.
356 pub fn read<D: Deserialize>(&self) -> Result<D> {
357 // The caller should have checked this,
358 // but it can't hurt to double-check
359 assert!(self.has_more_data());
360 D::deserialize(self.parcel)
361 }
362
363 /// Check if the sub-parcel has more data to read
364 pub fn has_more_data(&self) -> bool {
365 self.parcel.get_data_position() < self.end_position
366 }
367}
368
Stephen Crane2a3c2502020-06-16 17:48:35 -0700369// Internal APIs
370impl Parcel {
371 pub(crate) fn write_binder(&mut self, binder: Option<&SpIBinder>) -> Result<()> {
372 unsafe {
373 // Safety: `Parcel` always contains a valid pointer to an
374 // `AParcel`. `AsNative` for `Option<SpIBinder`> will either return
375 // null or a valid pointer to an `AIBinder`, both of which are
376 // valid, safe inputs to `AParcel_writeStrongBinder`.
377 //
378 // This call does not take ownership of the binder. However, it does
379 // require a mutable pointer, which we cannot extract from an
380 // immutable reference, so we clone the binder, incrementing the
381 // refcount before the call. The refcount will be immediately
382 // decremented when this temporary is dropped.
383 status_result(sys::AParcel_writeStrongBinder(
384 self.as_native_mut(),
385 binder.cloned().as_native_mut(),
386 ))
387 }
388 }
389
390 pub(crate) fn read_binder(&self) -> Result<Option<SpIBinder>> {
391 let mut binder = ptr::null_mut();
392 let status = unsafe {
393 // Safety: `Parcel` always contains a valid pointer to an
394 // `AParcel`. We pass a valid, mutable out pointer to the `binder`
395 // parameter. After this call, `binder` will be either null or a
396 // valid pointer to an `AIBinder` owned by the caller.
397 sys::AParcel_readStrongBinder(self.as_native(), &mut binder)
398 };
399
400 status_result(status)?;
401
402 Ok(unsafe {
403 // Safety: `binder` is either null or a valid, owned pointer at this
404 // point, so can be safely passed to `SpIBinder::from_raw`.
405 SpIBinder::from_raw(binder)
406 })
407 }
408}
409
410impl Drop for Parcel {
411 fn drop(&mut self) {
412 // Run the C++ Parcel complete object destructor
413 if let Self::Owned(ptr) = *self {
414 unsafe {
415 // Safety: `Parcel` always contains a valid pointer to an
416 // `AParcel`. If we own the parcel, we can safely delete it
417 // here.
418 sys::AParcel_delete(ptr)
419 }
420 }
421 }
422}
423
Alice Ryhlfeba6ca2021-08-19 10:47:04 +0000424impl fmt::Debug for Parcel {
425 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
426 f.debug_struct("Parcel")
427 .finish()
428 }
429}
430
Stephen Crane2a3c2502020-06-16 17:48:35 -0700431#[cfg(test)]
432impl Parcel {
433 /// Create a new parcel tied to a bogus binder. TESTING ONLY!
434 ///
435 /// This can only be used for testing! All real parcel operations must be
436 /// done in the callback to [`IBinder::transact`] or in
437 /// [`Remotable::on_transact`] using the parcels provided to these methods.
438 pub(crate) fn new_for_test(binder: &mut SpIBinder) -> Result<Self> {
439 let mut input = ptr::null_mut();
440 let status = unsafe {
441 // Safety: `SpIBinder` guarantees that `binder` always contains a
442 // valid pointer to an `AIBinder`. We pass a valid, mutable out
443 // pointer to receive a newly constructed parcel. When successful
444 // this function assigns a new pointer to an `AParcel` to `input`
445 // and transfers ownership of this pointer to the caller. Thus,
446 // after this call, `input` will either be null or point to a valid,
447 // owned `AParcel`.
448 sys::AIBinder_prepareTransaction(binder.as_native_mut(), &mut input)
449 };
450 status_result(status)?;
451 unsafe {
452 // Safety: `input` is either null or a valid, owned pointer to an
453 // `AParcel`, so is valid to safe to
454 // `Parcel::owned`. `Parcel::owned` takes ownership of the parcel
455 // pointer.
456 Parcel::owned(input).ok_or(StatusCode::UNEXPECTED_NULL)
457 }
458 }
459}
460
461#[test]
462fn test_read_write() {
463 use crate::binder::Interface;
464 use crate::native::Binder;
Stephen Crane2a3c2502020-06-16 17:48:35 -0700465
466 let mut service = Binder::new(()).as_binder();
467 let mut parcel = Parcel::new_for_test(&mut service).unwrap();
468 let start = parcel.get_data_position();
469
470 assert_eq!(parcel.read::<bool>(), Err(StatusCode::NOT_ENOUGH_DATA));
471 assert_eq!(parcel.read::<i8>(), Err(StatusCode::NOT_ENOUGH_DATA));
472 assert_eq!(parcel.read::<u16>(), Err(StatusCode::NOT_ENOUGH_DATA));
473 assert_eq!(parcel.read::<i32>(), Err(StatusCode::NOT_ENOUGH_DATA));
474 assert_eq!(parcel.read::<u32>(), Err(StatusCode::NOT_ENOUGH_DATA));
475 assert_eq!(parcel.read::<i64>(), Err(StatusCode::NOT_ENOUGH_DATA));
476 assert_eq!(parcel.read::<u64>(), Err(StatusCode::NOT_ENOUGH_DATA));
477 assert_eq!(parcel.read::<f32>(), Err(StatusCode::NOT_ENOUGH_DATA));
478 assert_eq!(parcel.read::<f64>(), Err(StatusCode::NOT_ENOUGH_DATA));
Stephen Crane76072e82020-08-03 13:09:36 -0700479 assert_eq!(parcel.read::<Option<String>>(), Ok(None));
Stephen Crane2a3c2502020-06-16 17:48:35 -0700480 assert_eq!(parcel.read::<String>(), Err(StatusCode::UNEXPECTED_NULL));
481
482 assert_eq!(parcel.read_binder().err(), Some(StatusCode::BAD_TYPE));
483
484 parcel.write(&1i32).unwrap();
485
486 unsafe {
487 parcel.set_data_position(start).unwrap();
488 }
489
490 let i: i32 = parcel.read().unwrap();
491 assert_eq!(i, 1i32);
492}
493
494#[test]
495#[allow(clippy::float_cmp)]
496fn test_read_data() {
497 use crate::binder::Interface;
498 use crate::native::Binder;
499
500 let mut service = Binder::new(()).as_binder();
501 let mut parcel = Parcel::new_for_test(&mut service).unwrap();
502 let str_start = parcel.get_data_position();
503
504 parcel.write(&b"Hello, Binder!\0"[..]).unwrap();
505 // Skip over string length
506 unsafe {
507 assert!(parcel.set_data_position(str_start).is_ok());
508 }
509 assert_eq!(parcel.read::<i32>().unwrap(), 15);
510 let start = parcel.get_data_position();
511
Chris Wailes45fd2942021-07-26 19:18:41 -0700512 assert!(parcel.read::<bool>().unwrap());
Stephen Crane2a3c2502020-06-16 17:48:35 -0700513
514 unsafe {
515 assert!(parcel.set_data_position(start).is_ok());
516 }
517
518 assert_eq!(parcel.read::<i8>().unwrap(), 72i8);
519
520 unsafe {
521 assert!(parcel.set_data_position(start).is_ok());
522 }
523
524 assert_eq!(parcel.read::<u16>().unwrap(), 25928);
525
526 unsafe {
527 assert!(parcel.set_data_position(start).is_ok());
528 }
529
530 assert_eq!(parcel.read::<i32>().unwrap(), 1819043144);
531
532 unsafe {
533 assert!(parcel.set_data_position(start).is_ok());
534 }
535
536 assert_eq!(parcel.read::<u32>().unwrap(), 1819043144);
537
538 unsafe {
539 assert!(parcel.set_data_position(start).is_ok());
540 }
541
542 assert_eq!(parcel.read::<i64>().unwrap(), 4764857262830019912);
543
544 unsafe {
545 assert!(parcel.set_data_position(start).is_ok());
546 }
547
548 assert_eq!(parcel.read::<u64>().unwrap(), 4764857262830019912);
549
550 unsafe {
551 assert!(parcel.set_data_position(start).is_ok());
552 }
553
554 assert_eq!(
555 parcel.read::<f32>().unwrap(),
556 1143139100000000000000000000.0
557 );
558 assert_eq!(parcel.read::<f32>().unwrap(), 40.043392);
559
560 unsafe {
561 assert!(parcel.set_data_position(start).is_ok());
562 }
563
564 assert_eq!(parcel.read::<f64>().unwrap(), 34732488246.197815);
565
566 // Skip back to before the string length
567 unsafe {
568 assert!(parcel.set_data_position(str_start).is_ok());
569 }
570
571 assert_eq!(parcel.read::<Vec<u8>>().unwrap(), b"Hello, Binder!\0");
572}
573
574#[test]
575fn test_utf8_utf16_conversions() {
576 use crate::binder::Interface;
577 use crate::native::Binder;
578
579 let mut service = Binder::new(()).as_binder();
580 let mut parcel = Parcel::new_for_test(&mut service).unwrap();
581 let start = parcel.get_data_position();
582
583 assert!(parcel.write("Hello, Binder!").is_ok());
584 unsafe {
585 assert!(parcel.set_data_position(start).is_ok());
586 }
587 assert_eq!(
588 parcel.read::<Option<String>>().unwrap().unwrap(),
Stephen Crane76072e82020-08-03 13:09:36 -0700589 "Hello, Binder!",
Stephen Crane2a3c2502020-06-16 17:48:35 -0700590 );
591 unsafe {
592 assert!(parcel.set_data_position(start).is_ok());
593 }
Stephen Crane76072e82020-08-03 13:09:36 -0700594
595 assert!(parcel.write("Embedded null \0 inside a string").is_ok());
596 unsafe {
597 assert!(parcel.set_data_position(start).is_ok());
598 }
599 assert_eq!(
600 parcel.read::<Option<String>>().unwrap().unwrap(),
601 "Embedded null \0 inside a string",
602 );
603 unsafe {
604 assert!(parcel.set_data_position(start).is_ok());
605 }
606
Stephen Crane2a3c2502020-06-16 17:48:35 -0700607 assert!(parcel.write(&["str1", "str2", "str3"][..]).is_ok());
608 assert!(parcel
609 .write(
610 &[
611 String::from("str4"),
612 String::from("str5"),
613 String::from("str6"),
614 ][..]
615 )
616 .is_ok());
617
618 let s1 = "Hello, Binder!";
619 let s2 = "This is a utf8 string.";
620 let s3 = "Some more text here.";
621
622 assert!(parcel.write(&[s1, s2, s3][..]).is_ok());
623 unsafe {
624 assert!(parcel.set_data_position(start).is_ok());
625 }
626
627 assert_eq!(
628 parcel.read::<Vec<String>>().unwrap(),
629 ["str1", "str2", "str3"]
630 );
631 assert_eq!(
632 parcel.read::<Vec<String>>().unwrap(),
633 ["str4", "str5", "str6"]
634 );
635 assert_eq!(parcel.read::<Vec<String>>().unwrap(), [s1, s2, s3]);
636}
Stephen Craneaae76382020-08-03 14:12:15 -0700637
638#[test]
639fn test_sized_write() {
640 use crate::binder::Interface;
641 use crate::native::Binder;
642
643 let mut service = Binder::new(()).as_binder();
644 let mut parcel = Parcel::new_for_test(&mut service).unwrap();
645 let start = parcel.get_data_position();
646
647 let arr = [1i32, 2i32, 3i32];
648
649 parcel.sized_write(|subparcel| {
650 subparcel.write(&arr[..])
651 }).expect("Could not perform sized write");
652
653 // i32 sub-parcel length + i32 array length + 3 i32 elements
654 let expected_len = 20i32;
655
656 assert_eq!(parcel.get_data_position(), start + expected_len);
657
658 unsafe {
659 parcel.set_data_position(start).unwrap();
660 }
661
662 assert_eq!(
663 expected_len,
664 parcel.read().unwrap(),
665 );
666
667 assert_eq!(
668 parcel.read::<Vec<i32>>().unwrap(),
669 &arr,
670 );
671}