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