1 /*
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 use crate::binder::{AsNative, FromIBinder, Strong};
18 use crate::error::{status_result, status_t, Result, Status, StatusCode};
19 use crate::parcel::Parcel;
20 use crate::proxy::SpIBinder;
21 use crate::sys;
22 
23 use std::convert::TryInto;
24 use std::ffi::c_void;
25 use std::os::raw::{c_char, c_ulong};
26 use std::mem::{self, MaybeUninit};
27 use std::ptr;
28 use std::slice;
29 
30 /// A struct whose instances can be written to a [`Parcel`].
31 // Might be able to hook this up as a serde backend in the future?
32 pub trait Serialize {
33     /// Serialize this instance into the given [`Parcel`].
serialize(&self, parcel: &mut Parcel) -> Result<()>34     fn serialize(&self, parcel: &mut Parcel) -> Result<()>;
35 }
36 
37 /// A struct whose instances can be restored from a [`Parcel`].
38 // Might be able to hook this up as a serde backend in the future?
39 pub trait Deserialize: Sized {
40     /// Deserialize an instance from the given [`Parcel`].
deserialize(parcel: &Parcel) -> Result<Self>41     fn deserialize(parcel: &Parcel) -> Result<Self>;
42 }
43 
44 /// Helper trait for types that can be serialized as arrays.
45 /// Defaults to calling Serialize::serialize() manually for every element,
46 /// but can be overridden for custom implementations like `writeByteArray`.
47 // Until specialization is stabilized in Rust, we need this to be a separate
48 // trait because it's the only way to have a default implementation for a method.
49 // We want the default implementation for most types, but an override for
50 // a few special ones like `readByteArray` for `u8`.
51 pub trait SerializeArray: Serialize + Sized {
52     /// Serialize an array of this type into the given [`Parcel`].
serialize_array(slice: &[Self], parcel: &mut Parcel) -> Result<()>53     fn serialize_array(slice: &[Self], parcel: &mut Parcel) -> Result<()> {
54         let res = unsafe {
55             // Safety: Safe FFI, slice will always be a safe pointer to pass.
56             sys::AParcel_writeParcelableArray(
57                 parcel.as_native_mut(),
58                 slice.as_ptr() as *const c_void,
59                 slice.len().try_into().or(Err(StatusCode::BAD_VALUE))?,
60                 Some(serialize_element::<Self>),
61             )
62         };
63         status_result(res)
64     }
65 }
66 
67 /// Callback to serialize an element of a generic parcelable array.
68 ///
69 /// Safety: We are relying on binder_ndk to not overrun our slice. As long as it
70 /// doesn't provide an index larger than the length of the original slice in
71 /// serialize_array, this operation is safe. The index provided is zero-based.
serialize_element<T: Serialize>( parcel: *mut sys::AParcel, array: *const c_void, index: c_ulong, ) -> status_t72 unsafe extern "C" fn serialize_element<T: Serialize>(
73     parcel: *mut sys::AParcel,
74     array: *const c_void,
75     index: c_ulong,
76 ) -> status_t {
77     // c_ulong and usize are the same, but we need the explicitly sized version
78     // so the function signature matches what bindgen generates.
79     let index = index as usize;
80 
81     let slice: &[T] = slice::from_raw_parts(array.cast(), index+1);
82 
83     let mut parcel = match Parcel::borrowed(parcel) {
84         None => return StatusCode::UNEXPECTED_NULL as status_t,
85         Some(p) => p,
86     };
87 
88     slice[index].serialize(&mut parcel)
89                 .err()
90                 .unwrap_or(StatusCode::OK)
91         as status_t
92 }
93 
94 /// Helper trait for types that can be deserialized as arrays.
95 /// Defaults to calling Deserialize::deserialize() manually for every element,
96 /// but can be overridden for custom implementations like `readByteArray`.
97 pub trait DeserializeArray: Deserialize {
98     /// Deserialize an array of type from the given [`Parcel`].
deserialize_array(parcel: &Parcel) -> Result<Option<Vec<Self>>>99     fn deserialize_array(parcel: &Parcel) -> Result<Option<Vec<Self>>> {
100         let mut vec: Option<Vec<MaybeUninit<Self>>> = None;
101         let res = unsafe {
102             // Safety: Safe FFI, vec is the correct opaque type expected by
103             // allocate_vec and deserialize_element.
104             sys::AParcel_readParcelableArray(
105                 parcel.as_native(),
106                 &mut vec as *mut _ as *mut c_void,
107                 Some(allocate_vec::<Self>),
108                 Some(deserialize_element::<Self>),
109             )
110         };
111         status_result(res)?;
112         let vec: Option<Vec<Self>> = unsafe {
113             // Safety: We are assuming that the NDK correctly initialized every
114             // element of the vector by now, so we know that all the
115             // MaybeUninits are now properly initialized. We can transmute from
116             // Vec<MaybeUninit<T>> to Vec<T> because MaybeUninit<T> has the same
117             // alignment and size as T, so the pointer to the vector allocation
118             // will be compatible.
119             mem::transmute(vec)
120         };
121         Ok(vec)
122     }
123 }
124 
125 /// Callback to deserialize a parcelable element.
126 ///
127 /// The opaque array data pointer must be a mutable pointer to an
128 /// `Option<Vec<MaybeUninit<T>>>` with at least enough elements for `index` to be valid
129 /// (zero-based).
deserialize_element<T: Deserialize>( parcel: *const sys::AParcel, array: *mut c_void, index: c_ulong, ) -> status_t130 unsafe extern "C" fn deserialize_element<T: Deserialize>(
131     parcel: *const sys::AParcel,
132     array: *mut c_void,
133     index: c_ulong,
134 ) -> status_t {
135     // c_ulong and usize are the same, but we need the explicitly sized version
136     // so the function signature matches what bindgen generates.
137     let index = index as usize;
138 
139     let vec = &mut *(array as *mut Option<Vec<MaybeUninit<T>>>);
140     let vec = match vec {
141         Some(v) => v,
142         None => return StatusCode::BAD_INDEX as status_t,
143     };
144 
145     let parcel = match Parcel::borrowed(parcel as *mut _) {
146         None => return StatusCode::UNEXPECTED_NULL as status_t,
147         Some(p) => p,
148     };
149     let element = match parcel.read() {
150         Ok(e) => e,
151         Err(code) => return code as status_t,
152     };
153     ptr::write(vec[index].as_mut_ptr(), element);
154     StatusCode::OK as status_t
155 }
156 
157 /// Helper trait for types that can be nullable when serialized.
158 // We really need this trait instead of implementing `Serialize for Option<T>`
159 // because of the Rust orphan rule which prevents us from doing
160 // `impl Serialize for Option<&dyn IFoo>` for AIDL interfaces.
161 // Instead we emit `impl SerializeOption for dyn IFoo` which is allowed.
162 // We also use it to provide a default implementation for AIDL-generated
163 // parcelables.
164 pub trait SerializeOption: Serialize {
165     /// Serialize an Option of this type into the given [`Parcel`].
serialize_option(this: Option<&Self>, parcel: &mut Parcel) -> Result<()>166     fn serialize_option(this: Option<&Self>, parcel: &mut Parcel) -> Result<()> {
167         if let Some(inner) = this {
168             parcel.write(&1i32)?;
169             parcel.write(inner)
170         } else {
171             parcel.write(&0i32)
172         }
173     }
174 }
175 
176 /// Helper trait for types that can be nullable when deserialized.
177 pub trait DeserializeOption: Deserialize {
178     /// Deserialize an Option of this type from the given [`Parcel`].
deserialize_option(parcel: &Parcel) -> Result<Option<Self>>179     fn deserialize_option(parcel: &Parcel) -> Result<Option<Self>> {
180         let null: i32 = parcel.read()?;
181         if null == 0 {
182             Ok(None)
183         } else {
184             parcel.read().map(Some)
185         }
186     }
187 }
188 
189 /// Callback to allocate a vector for parcel array read functions.
190 ///
191 /// This variant is for APIs which use an out buffer pointer.
192 ///
193 /// # Safety
194 ///
195 /// The opaque data pointer passed to the array read function must be a mutable
196 /// pointer to an `Option<Vec<MaybeUninit<T>>>`. `buffer` will be assigned a mutable pointer
197 /// to the allocated vector data if this function returns true.
allocate_vec_with_buffer<T>( data: *mut c_void, len: i32, buffer: *mut *mut T, ) -> bool198 unsafe extern "C" fn allocate_vec_with_buffer<T>(
199     data: *mut c_void,
200     len: i32,
201     buffer: *mut *mut T,
202 ) -> bool {
203     let res = allocate_vec::<T>(data, len);
204     let vec = &mut *(data as *mut Option<Vec<MaybeUninit<T>>>);
205     if let Some(new_vec) = vec {
206         *buffer = new_vec.as_mut_ptr() as *mut T;
207     }
208     res
209 }
210 
211 /// Callback to allocate a vector for parcel array read functions.
212 ///
213 /// # Safety
214 ///
215 /// The opaque data pointer passed to the array read function must be a mutable
216 /// pointer to an `Option<Vec<MaybeUninit<T>>>`.
allocate_vec<T>( data: *mut c_void, len: i32, ) -> bool217 unsafe extern "C" fn allocate_vec<T>(
218     data: *mut c_void,
219     len: i32,
220 ) -> bool {
221     let vec = &mut *(data as *mut Option<Vec<MaybeUninit<T>>>);
222     if len < 0 {
223         *vec = None;
224         return true;
225     }
226     let mut new_vec: Vec<MaybeUninit<T>> = Vec::with_capacity(len as usize);
227 
228     // Safety: We are filling the vector with uninitialized data here, but this
229     // is safe because the vector contains MaybeUninit elements which can be
230     // uninitialized. We're putting off the actual unsafe bit, transmuting the
231     // vector to a Vec<T> until the contents are initialized.
232     new_vec.set_len(len as usize);
233 
234     ptr::write(vec, Some(new_vec));
235     true
236 }
237 
238 
239 macro_rules! parcelable_primitives {
240     {
241         $(
242             impl $trait:ident for $ty:ty = $fn:path;
243         )*
244     } => {
245         $(impl_parcelable!{$trait, $ty, $fn})*
246     };
247 }
248 
249 macro_rules! impl_parcelable {
250     {Serialize, $ty:ty, $write_fn:path} => {
251         impl Serialize for $ty {
252             fn serialize(&self, parcel: &mut Parcel) -> Result<()> {
253                 unsafe {
254                     // Safety: `Parcel` always contains a valid pointer to an
255                     // `AParcel`, and any `$ty` literal value is safe to pass to
256                     // `$write_fn`.
257                     status_result($write_fn(parcel.as_native_mut(), *self))
258                 }
259             }
260         }
261     };
262 
263     {Deserialize, $ty:ty, $read_fn:path} => {
264         impl Deserialize for $ty {
265             fn deserialize(parcel: &Parcel) -> Result<Self> {
266                 let mut val = Self::default();
267                 unsafe {
268                     // Safety: `Parcel` always contains a valid pointer to an
269                     // `AParcel`. We pass a valid, mutable pointer to `val`, a
270                     // literal of type `$ty`, and `$read_fn` will write the
271                     // value read into `val` if successful
272                     status_result($read_fn(parcel.as_native(), &mut val))?
273                 };
274                 Ok(val)
275             }
276         }
277     };
278 
279     {SerializeArray, $ty:ty, $write_array_fn:path} => {
280         impl SerializeArray for $ty {
281             fn serialize_array(slice: &[Self], parcel: &mut Parcel) -> Result<()> {
282                 let status = unsafe {
283                     // Safety: `Parcel` always contains a valid pointer to an
284                     // `AParcel`. If the slice is > 0 length, `slice.as_ptr()`
285                     // will be a valid pointer to an array of elements of type
286                     // `$ty`. If the slice length is 0, `slice.as_ptr()` may be
287                     // dangling, but this is safe since the pointer is not
288                     // dereferenced if the length parameter is 0.
289                     $write_array_fn(
290                         parcel.as_native_mut(),
291                         slice.as_ptr(),
292                         slice
293                             .len()
294                             .try_into()
295                             .or(Err(StatusCode::BAD_VALUE))?,
296                     )
297                 };
298                 status_result(status)
299             }
300         }
301     };
302 
303     {DeserializeArray, $ty:ty, $read_array_fn:path} => {
304         impl DeserializeArray for $ty {
305             fn deserialize_array(parcel: &Parcel) -> Result<Option<Vec<Self>>> {
306                 let mut vec: Option<Vec<MaybeUninit<Self>>> = None;
307                 let status = unsafe {
308                     // Safety: `Parcel` always contains a valid pointer to an
309                     // `AParcel`. `allocate_vec<T>` expects the opaque pointer to
310                     // be of type `*mut Option<Vec<MaybeUninit<T>>>`, so `&mut vec` is
311                     // correct for it.
312                     $read_array_fn(
313                         parcel.as_native(),
314                         &mut vec as *mut _ as *mut c_void,
315                         Some(allocate_vec_with_buffer),
316                     )
317                 };
318                 status_result(status)?;
319                 let vec: Option<Vec<Self>> = unsafe {
320                     // Safety: We are assuming that the NDK correctly
321                     // initialized every element of the vector by now, so we
322                     // know that all the MaybeUninits are now properly
323                     // initialized. We can transmute from Vec<MaybeUninit<T>> to
324                     // Vec<T> because MaybeUninit<T> has the same alignment and
325                     // size as T, so the pointer to the vector allocation will
326                     // be compatible.
327                     mem::transmute(vec)
328                 };
329                 Ok(vec)
330             }
331         }
332     };
333 }
334 
335 parcelable_primitives! {
336     impl Serialize for bool = sys::AParcel_writeBool;
337     impl Deserialize for bool = sys::AParcel_readBool;
338 
339     // This is only safe because `Option<Vec<u8>>` is interchangeable with
340     // `Option<Vec<i8>>` (what the allocator function actually allocates.
341     impl DeserializeArray for u8 = sys::AParcel_readByteArray;
342 
343     impl Serialize for i8 = sys::AParcel_writeByte;
344     impl Deserialize for i8 = sys::AParcel_readByte;
345     impl SerializeArray for i8 = sys::AParcel_writeByteArray;
346     impl DeserializeArray for i8 = sys::AParcel_readByteArray;
347 
348     impl Serialize for u16 = sys::AParcel_writeChar;
349     impl Deserialize for u16 = sys::AParcel_readChar;
350     impl SerializeArray for u16 = sys::AParcel_writeCharArray;
351     impl DeserializeArray for u16 = sys::AParcel_readCharArray;
352 
353     // This is only safe because `Option<Vec<i16>>` is interchangeable with
354     // `Option<Vec<u16>>` (what the allocator function actually allocates.
355     impl DeserializeArray for i16 = sys::AParcel_readCharArray;
356 
357     impl Serialize for u32 = sys::AParcel_writeUint32;
358     impl Deserialize for u32 = sys::AParcel_readUint32;
359     impl SerializeArray for u32 = sys::AParcel_writeUint32Array;
360     impl DeserializeArray for u32 = sys::AParcel_readUint32Array;
361 
362     impl Serialize for i32 = sys::AParcel_writeInt32;
363     impl Deserialize for i32 = sys::AParcel_readInt32;
364     impl SerializeArray for i32 = sys::AParcel_writeInt32Array;
365     impl DeserializeArray for i32 = sys::AParcel_readInt32Array;
366 
367     impl Serialize for u64 = sys::AParcel_writeUint64;
368     impl Deserialize for u64 = sys::AParcel_readUint64;
369     impl SerializeArray for u64 = sys::AParcel_writeUint64Array;
370     impl DeserializeArray for u64 = sys::AParcel_readUint64Array;
371 
372     impl Serialize for i64 = sys::AParcel_writeInt64;
373     impl Deserialize for i64 = sys::AParcel_readInt64;
374     impl SerializeArray for i64 = sys::AParcel_writeInt64Array;
375     impl DeserializeArray for i64 = sys::AParcel_readInt64Array;
376 
377     impl Serialize for f32 = sys::AParcel_writeFloat;
378     impl Deserialize for f32 = sys::AParcel_readFloat;
379     impl SerializeArray for f32 = sys::AParcel_writeFloatArray;
380     impl DeserializeArray for f32 = sys::AParcel_readFloatArray;
381 
382     impl Serialize for f64 = sys::AParcel_writeDouble;
383     impl Deserialize for f64 = sys::AParcel_readDouble;
384     impl SerializeArray for f64 = sys::AParcel_writeDoubleArray;
385     impl DeserializeArray for f64 = sys::AParcel_readDoubleArray;
386 }
387 
388 impl SerializeArray for bool {}
389 impl DeserializeArray for bool {}
390 
391 impl Serialize for u8 {
serialize(&self, parcel: &mut Parcel) -> Result<()>392     fn serialize(&self, parcel: &mut Parcel) -> Result<()> {
393         (*self as i8).serialize(parcel)
394     }
395 }
396 
397 impl Deserialize for u8 {
deserialize(parcel: &Parcel) -> Result<Self>398     fn deserialize(parcel: &Parcel) -> Result<Self> {
399         i8::deserialize(parcel).map(|v| v as u8)
400     }
401 }
402 
403 impl SerializeArray for u8 {
serialize_array(slice: &[Self], parcel: &mut Parcel) -> Result<()>404     fn serialize_array(slice: &[Self], parcel: &mut Parcel) -> Result<()> {
405         let status = unsafe {
406             // Safety: `Parcel` always contains a valid pointer to an
407             // `AParcel`. If the slice is > 0 length, `slice.as_ptr()` will be a
408             // valid pointer to an array of elements of type `$ty`. If the slice
409             // length is 0, `slice.as_ptr()` may be dangling, but this is safe
410             // since the pointer is not dereferenced if the length parameter is
411             // 0.
412             sys::AParcel_writeByteArray(
413                 parcel.as_native_mut(),
414                 slice.as_ptr() as *const i8,
415                 slice.len().try_into().or(Err(StatusCode::BAD_VALUE))?,
416             )
417         };
418         status_result(status)
419     }
420 }
421 
422 impl Serialize for i16 {
serialize(&self, parcel: &mut Parcel) -> Result<()>423     fn serialize(&self, parcel: &mut Parcel) -> Result<()> {
424         (*self as u16).serialize(parcel)
425     }
426 }
427 
428 impl Deserialize for i16 {
deserialize(parcel: &Parcel) -> Result<Self>429     fn deserialize(parcel: &Parcel) -> Result<Self> {
430         u16::deserialize(parcel).map(|v| v as i16)
431     }
432 }
433 
434 impl SerializeArray for i16 {
serialize_array(slice: &[Self], parcel: &mut Parcel) -> Result<()>435     fn serialize_array(slice: &[Self], parcel: &mut Parcel) -> Result<()> {
436         let status = unsafe {
437             // Safety: `Parcel` always contains a valid pointer to an
438             // `AParcel`. If the slice is > 0 length, `slice.as_ptr()` will be a
439             // valid pointer to an array of elements of type `$ty`. If the slice
440             // length is 0, `slice.as_ptr()` may be dangling, but this is safe
441             // since the pointer is not dereferenced if the length parameter is
442             // 0.
443             sys::AParcel_writeCharArray(
444                 parcel.as_native_mut(),
445                 slice.as_ptr() as *const u16,
446                 slice.len().try_into().or(Err(StatusCode::BAD_VALUE))?,
447             )
448         };
449         status_result(status)
450     }
451 }
452 
453 impl SerializeOption for str {
serialize_option(this: Option<&Self>, parcel: &mut Parcel) -> Result<()>454     fn serialize_option(this: Option<&Self>, parcel: &mut Parcel) -> Result<()> {
455         match this {
456             None => unsafe {
457                 // Safety: `Parcel` always contains a valid pointer to an
458                 // `AParcel`. If the string pointer is null,
459                 // `AParcel_writeString` requires that the length is -1 to
460                 // indicate that we want to serialize a null string.
461                 status_result(sys::AParcel_writeString(
462                     parcel.as_native_mut(),
463                     ptr::null(),
464                     -1,
465                 ))
466             },
467             Some(s) => unsafe {
468                 // Safety: `Parcel` always contains a valid pointer to an
469                 // `AParcel`. `AParcel_writeString` assumes that we pass a utf-8
470                 // string pointer of `length` bytes, which is what str in Rust
471                 // is. The docstring for `AParcel_writeString` says that the
472                 // string input should be null-terminated, but it doesn't
473                 // actually rely on that fact in the code. If this ever becomes
474                 // necessary, we will need to null-terminate the str buffer
475                 // before sending it.
476                 status_result(sys::AParcel_writeString(
477                     parcel.as_native_mut(),
478                     s.as_ptr() as *const c_char,
479                     s.as_bytes()
480                         .len()
481                         .try_into()
482                         .or(Err(StatusCode::BAD_VALUE))?,
483                 ))
484             },
485         }
486     }
487 }
488 
489 impl SerializeArray for Option<&str> {}
490 
491 impl Serialize for str {
serialize(&self, parcel: &mut Parcel) -> Result<()>492     fn serialize(&self, parcel: &mut Parcel) -> Result<()> {
493         Some(self).serialize(parcel)
494     }
495 }
496 
497 impl SerializeArray for &str {}
498 
499 impl Serialize for String {
serialize(&self, parcel: &mut Parcel) -> Result<()>500     fn serialize(&self, parcel: &mut Parcel) -> Result<()> {
501         Some(self.as_str()).serialize(parcel)
502     }
503 }
504 
505 impl SerializeArray for String {}
506 
507 impl SerializeOption for String {
serialize_option(this: Option<&Self>, parcel: &mut Parcel) -> Result<()>508     fn serialize_option(this: Option<&Self>, parcel: &mut Parcel) -> Result<()> {
509         SerializeOption::serialize_option(this.map(String::as_str), parcel)
510     }
511 }
512 
513 impl SerializeArray for Option<String> {}
514 
515 impl Deserialize for Option<String> {
deserialize(parcel: &Parcel) -> Result<Self>516     fn deserialize(parcel: &Parcel) -> Result<Self> {
517         let mut vec: Option<Vec<u8>> = None;
518         let status = unsafe {
519             // Safety: `Parcel` always contains a valid pointer to an `AParcel`.
520             // `Option<Vec<u8>>` is equivalent to the expected `Option<Vec<i8>>`
521             // for `allocate_vec`, so `vec` is safe to pass as the opaque data
522             // pointer on platforms where char is signed.
523             sys::AParcel_readString(
524                 parcel.as_native(),
525                 &mut vec as *mut _ as *mut c_void,
526                 Some(allocate_vec_with_buffer),
527             )
528         };
529 
530         status_result(status)?;
531         vec.map(|mut s| {
532             // The vector includes a null-terminator and we don't want the
533             // string to be null-terminated for Rust.
534             s.pop();
535             String::from_utf8(s).or(Err(StatusCode::BAD_VALUE))
536         })
537         .transpose()
538     }
539 }
540 
541 impl DeserializeArray for Option<String> {}
542 
543 impl Deserialize for String {
deserialize(parcel: &Parcel) -> Result<Self>544     fn deserialize(parcel: &Parcel) -> Result<Self> {
545         Deserialize::deserialize(parcel)
546             .transpose()
547             .unwrap_or(Err(StatusCode::UNEXPECTED_NULL))
548     }
549 }
550 
551 impl DeserializeArray for String {}
552 
553 impl<T: SerializeArray> Serialize for [T] {
serialize(&self, parcel: &mut Parcel) -> Result<()>554     fn serialize(&self, parcel: &mut Parcel) -> Result<()> {
555         SerializeArray::serialize_array(self, parcel)
556     }
557 }
558 
559 impl<T: SerializeArray> Serialize for Vec<T> {
serialize(&self, parcel: &mut Parcel) -> Result<()>560     fn serialize(&self, parcel: &mut Parcel) -> Result<()> {
561         SerializeArray::serialize_array(&self[..], parcel)
562     }
563 }
564 
565 impl<T: SerializeArray> SerializeOption for [T] {
serialize_option(this: Option<&Self>, parcel: &mut Parcel) -> Result<()>566     fn serialize_option(this: Option<&Self>, parcel: &mut Parcel) -> Result<()> {
567         if let Some(v) = this {
568             SerializeArray::serialize_array(v, parcel)
569         } else {
570             parcel.write(&-1i32)
571         }
572     }
573 }
574 
575 impl<T: SerializeArray> SerializeOption for Vec<T> {
serialize_option(this: Option<&Self>, parcel: &mut Parcel) -> Result<()>576     fn serialize_option(this: Option<&Self>, parcel: &mut Parcel) -> Result<()> {
577         SerializeOption::serialize_option(this.map(Vec::as_slice), parcel)
578     }
579 }
580 
581 impl<T: DeserializeArray> Deserialize for Vec<T> {
deserialize(parcel: &Parcel) -> Result<Self>582     fn deserialize(parcel: &Parcel) -> Result<Self> {
583         DeserializeArray::deserialize_array(parcel)
584             .transpose()
585             .unwrap_or(Err(StatusCode::UNEXPECTED_NULL))
586     }
587 }
588 
589 impl<T: DeserializeArray> DeserializeOption for Vec<T> {
deserialize_option(parcel: &Parcel) -> Result<Option<Self>>590     fn deserialize_option(parcel: &Parcel) -> Result<Option<Self>> {
591         DeserializeArray::deserialize_array(parcel)
592     }
593 }
594 
595 impl Serialize for Status {
serialize(&self, parcel: &mut Parcel) -> Result<()>596     fn serialize(&self, parcel: &mut Parcel) -> Result<()> {
597         unsafe {
598             // Safety: `Parcel` always contains a valid pointer to an `AParcel`
599             // and `Status` always contains a valid pointer to an `AStatus`, so
600             // both parameters are valid and safe. This call does not take
601             // ownership of either of its parameters.
602             status_result(sys::AParcel_writeStatusHeader(
603                 parcel.as_native_mut(),
604                 self.as_native(),
605             ))
606         }
607     }
608 }
609 
610 impl Deserialize for Status {
deserialize(parcel: &Parcel) -> Result<Self>611     fn deserialize(parcel: &Parcel) -> Result<Self> {
612         let mut status_ptr = ptr::null_mut();
613         let ret_status = unsafe {
614             // Safety: `Parcel` always contains a valid pointer to an
615             // `AParcel`. We pass a mutable out pointer which will be
616             // assigned a valid `AStatus` pointer if the function returns
617             // status OK. This function passes ownership of the status
618             // pointer to the caller, if it was assigned.
619             sys::AParcel_readStatusHeader(parcel.as_native(), &mut status_ptr)
620         };
621         status_result(ret_status)?;
622         Ok(unsafe {
623             // Safety: At this point, the return status of the read call was ok,
624             // so we know that `status_ptr` is a valid, owned pointer to an
625             // `AStatus`, from which we can safely construct a `Status` object.
626             Status::from_ptr(status_ptr)
627         })
628     }
629 }
630 
631 impl<T: Serialize + FromIBinder + ?Sized> Serialize for Strong<T> {
serialize(&self, parcel: &mut Parcel) -> Result<()>632     fn serialize(&self, parcel: &mut Parcel) -> Result<()> {
633         Serialize::serialize(&**self, parcel)
634     }
635 }
636 
637 impl<T: SerializeOption + FromIBinder + ?Sized> SerializeOption for Strong<T> {
serialize_option(this: Option<&Self>, parcel: &mut Parcel) -> Result<()>638     fn serialize_option(this: Option<&Self>, parcel: &mut Parcel) -> Result<()> {
639         SerializeOption::serialize_option(this.map(|b| &**b), parcel)
640     }
641 }
642 
643 impl<T: FromIBinder + ?Sized> Deserialize for Strong<T> {
deserialize(parcel: &Parcel) -> Result<Self>644     fn deserialize(parcel: &Parcel) -> Result<Self> {
645         let ibinder: SpIBinder = parcel.read()?;
646         FromIBinder::try_from(ibinder)
647     }
648 }
649 
650 impl<T: FromIBinder + ?Sized> DeserializeOption for Strong<T> {
deserialize_option(parcel: &Parcel) -> Result<Option<Self>>651     fn deserialize_option(parcel: &Parcel) -> Result<Option<Self>> {
652         let ibinder: Option<SpIBinder> = parcel.read()?;
653         ibinder.map(FromIBinder::try_from).transpose()
654     }
655 }
656 
657 // We need these to support Option<&T> for all T
658 impl<T: Serialize + ?Sized> Serialize for &T {
serialize(&self, parcel: &mut Parcel) -> Result<()>659     fn serialize(&self, parcel: &mut Parcel) -> Result<()> {
660         Serialize::serialize(*self, parcel)
661     }
662 }
663 
664 impl<T: SerializeOption + ?Sized> SerializeOption for &T {
serialize_option(this: Option<&Self>, parcel: &mut Parcel) -> Result<()>665     fn serialize_option(this: Option<&Self>, parcel: &mut Parcel) -> Result<()> {
666         SerializeOption::serialize_option(this.copied(), parcel)
667     }
668 }
669 
670 impl<T: SerializeOption> Serialize for Option<T> {
serialize(&self, parcel: &mut Parcel) -> Result<()>671     fn serialize(&self, parcel: &mut Parcel) -> Result<()> {
672         SerializeOption::serialize_option(self.as_ref(), parcel)
673     }
674 }
675 
676 impl<T: DeserializeOption> Deserialize for Option<T> {
deserialize(parcel: &Parcel) -> Result<Self>677     fn deserialize(parcel: &Parcel) -> Result<Self> {
678         DeserializeOption::deserialize_option(parcel)
679     }
680 }
681 
682 #[test]
test_custom_parcelable()683 fn test_custom_parcelable() {
684     use crate::binder::Interface;
685     use crate::native::Binder;
686     let mut service = Binder::new(()).as_binder();
687 
688     struct Custom(u32, bool, String, Vec<String>);
689 
690     impl Serialize for Custom {
691         fn serialize(&self, parcel: &mut Parcel) -> Result<()> {
692             self.0.serialize(parcel)?;
693             self.1.serialize(parcel)?;
694             self.2.serialize(parcel)?;
695             self.3.serialize(parcel)
696         }
697     }
698 
699     impl Deserialize for Custom {
700         fn deserialize(parcel: &Parcel) -> Result<Self> {
701             Ok(Custom(
702                 parcel.read()?,
703                 parcel.read()?,
704                 parcel.read()?,
705                 parcel.read::<Option<Vec<String>>>()?.unwrap(),
706             ))
707         }
708     }
709 
710     let string8 = "Custom Parcelable".to_string();
711 
712     let s1 = "str1".to_string();
713     let s2 = "str2".to_string();
714     let s3 = "str3".to_string();
715 
716     let strs = vec![s1, s2, s3];
717 
718     let custom = Custom(123_456_789, true, string8, strs);
719 
720     let mut parcel = Parcel::new_for_test(&mut service).unwrap();
721     let start = parcel.get_data_position();
722 
723     assert!(custom.serialize(&mut parcel).is_ok());
724 
725     unsafe {
726         assert!(parcel.set_data_position(start).is_ok());
727     }
728 
729     let custom2 = Custom::deserialize(&parcel).unwrap();
730 
731     assert_eq!(custom2.0, 123_456_789);
732     assert!(custom2.1);
733     assert_eq!(custom2.2, custom.2);
734     assert_eq!(custom2.3, custom.3);
735 }
736 
737 #[test]
738 #[allow(clippy::excessive_precision)]
test_slice_parcelables()739 fn test_slice_parcelables() {
740     use crate::binder::Interface;
741     use crate::native::Binder;
742     let mut service = Binder::new(()).as_binder();
743 
744     let bools = [true, false, false, true];
745 
746     let mut parcel = Parcel::new_for_test(&mut service).unwrap();
747     let start = parcel.get_data_position();
748 
749     assert!(bools.serialize(&mut parcel).is_ok());
750 
751     unsafe {
752         assert!(parcel.set_data_position(start).is_ok());
753     }
754 
755     assert_eq!(parcel.read::<u32>().unwrap(), 4);
756     assert_eq!(parcel.read::<u32>().unwrap(), 1);
757     assert_eq!(parcel.read::<u32>().unwrap(), 0);
758     assert_eq!(parcel.read::<u32>().unwrap(), 0);
759     assert_eq!(parcel.read::<u32>().unwrap(), 1);
760     unsafe {
761         assert!(parcel.set_data_position(start).is_ok());
762     }
763 
764     let vec = Vec::<bool>::deserialize(&parcel).unwrap();
765 
766     assert_eq!(vec, [true, false, false, true]);
767 
768     let u8s = [101u8, 255, 42, 117];
769 
770     let mut parcel = Parcel::new_for_test(&mut service).unwrap();
771     let start = parcel.get_data_position();
772 
773     assert!(parcel.write(&u8s[..]).is_ok());
774 
775     unsafe {
776         assert!(parcel.set_data_position(start).is_ok());
777     }
778 
779     assert_eq!(parcel.read::<u32>().unwrap(), 4); // 4 items
780     assert_eq!(parcel.read::<u32>().unwrap(), 0x752aff65); // bytes
781     unsafe {
782         assert!(parcel.set_data_position(start).is_ok());
783     }
784 
785     let vec = Vec::<u8>::deserialize(&parcel).unwrap();
786     assert_eq!(vec, [101, 255, 42, 117]);
787 
788     let i8s = [-128i8, 127, 42, -117];
789 
790     unsafe {
791         assert!(parcel.set_data_position(start).is_ok());
792     }
793 
794     assert!(parcel.write(&i8s[..]).is_ok());
795 
796     unsafe {
797         assert!(parcel.set_data_position(start).is_ok());
798     }
799 
800     assert_eq!(parcel.read::<u32>().unwrap(), 4); // 4 items
801     assert_eq!(parcel.read::<u32>().unwrap(), 0x8b2a7f80); // bytes
802     unsafe {
803         assert!(parcel.set_data_position(start).is_ok());
804     }
805 
806     let vec = Vec::<u8>::deserialize(&parcel).unwrap();
807     assert_eq!(vec, [-128i8 as u8, 127, 42, -117i8 as u8]);
808 
809     let u16s = [u16::max_value(), 12_345, 42, 117];
810 
811     unsafe {
812         assert!(parcel.set_data_position(start).is_ok());
813     }
814     assert!(u16s.serialize(&mut parcel).is_ok());
815     unsafe {
816         assert!(parcel.set_data_position(start).is_ok());
817     }
818 
819     assert_eq!(parcel.read::<u32>().unwrap(), 4); // 4 items
820     assert_eq!(parcel.read::<u32>().unwrap(), 0xffff); // u16::max_value()
821     assert_eq!(parcel.read::<u32>().unwrap(), 12345); // 12,345
822     assert_eq!(parcel.read::<u32>().unwrap(), 42); // 42
823     assert_eq!(parcel.read::<u32>().unwrap(), 117); // 117
824     unsafe {
825         assert!(parcel.set_data_position(start).is_ok());
826     }
827 
828     let vec = Vec::<u16>::deserialize(&parcel).unwrap();
829 
830     assert_eq!(vec, [u16::max_value(), 12_345, 42, 117]);
831 
832     let i16s = [i16::max_value(), i16::min_value(), 42, -117];
833 
834     unsafe {
835         assert!(parcel.set_data_position(start).is_ok());
836     }
837     assert!(i16s.serialize(&mut parcel).is_ok());
838     unsafe {
839         assert!(parcel.set_data_position(start).is_ok());
840     }
841 
842     assert_eq!(parcel.read::<u32>().unwrap(), 4); // 4 items
843     assert_eq!(parcel.read::<u32>().unwrap(), 0x7fff); // i16::max_value()
844     assert_eq!(parcel.read::<u32>().unwrap(), 0x8000); // i16::min_value()
845     assert_eq!(parcel.read::<u32>().unwrap(), 42); // 42
846     assert_eq!(parcel.read::<u32>().unwrap(), 0xff8b); // -117
847     unsafe {
848         assert!(parcel.set_data_position(start).is_ok());
849     }
850 
851     let vec = Vec::<i16>::deserialize(&parcel).unwrap();
852 
853     assert_eq!(vec, [i16::max_value(), i16::min_value(), 42, -117]);
854 
855     let u32s = [u32::max_value(), 12_345, 42, 117];
856 
857     unsafe {
858         assert!(parcel.set_data_position(start).is_ok());
859     }
860     assert!(u32s.serialize(&mut parcel).is_ok());
861     unsafe {
862         assert!(parcel.set_data_position(start).is_ok());
863     }
864 
865     assert_eq!(parcel.read::<u32>().unwrap(), 4); // 4 items
866     assert_eq!(parcel.read::<u32>().unwrap(), 0xffffffff); // u32::max_value()
867     assert_eq!(parcel.read::<u32>().unwrap(), 12345); // 12,345
868     assert_eq!(parcel.read::<u32>().unwrap(), 42); // 42
869     assert_eq!(parcel.read::<u32>().unwrap(), 117); // 117
870     unsafe {
871         assert!(parcel.set_data_position(start).is_ok());
872     }
873 
874     let vec = Vec::<u32>::deserialize(&parcel).unwrap();
875 
876     assert_eq!(vec, [u32::max_value(), 12_345, 42, 117]);
877 
878     let i32s = [i32::max_value(), i32::min_value(), 42, -117];
879 
880     unsafe {
881         assert!(parcel.set_data_position(start).is_ok());
882     }
883     assert!(i32s.serialize(&mut parcel).is_ok());
884     unsafe {
885         assert!(parcel.set_data_position(start).is_ok());
886     }
887 
888     assert_eq!(parcel.read::<u32>().unwrap(), 4); // 4 items
889     assert_eq!(parcel.read::<u32>().unwrap(), 0x7fffffff); // i32::max_value()
890     assert_eq!(parcel.read::<u32>().unwrap(), 0x80000000); // i32::min_value()
891     assert_eq!(parcel.read::<u32>().unwrap(), 42); // 42
892     assert_eq!(parcel.read::<u32>().unwrap(), 0xffffff8b); // -117
893     unsafe {
894         assert!(parcel.set_data_position(start).is_ok());
895     }
896 
897     let vec = Vec::<i32>::deserialize(&parcel).unwrap();
898 
899     assert_eq!(vec, [i32::max_value(), i32::min_value(), 42, -117]);
900 
901     let u64s = [u64::max_value(), 12_345, 42, 117];
902 
903     unsafe {
904         assert!(parcel.set_data_position(start).is_ok());
905     }
906     assert!(u64s.serialize(&mut parcel).is_ok());
907     unsafe {
908         assert!(parcel.set_data_position(start).is_ok());
909     }
910 
911     let vec = Vec::<u64>::deserialize(&parcel).unwrap();
912 
913     assert_eq!(vec, [u64::max_value(), 12_345, 42, 117]);
914 
915     let i64s = [i64::max_value(), i64::min_value(), 42, -117];
916 
917     unsafe {
918         assert!(parcel.set_data_position(start).is_ok());
919     }
920     assert!(i64s.serialize(&mut parcel).is_ok());
921     unsafe {
922         assert!(parcel.set_data_position(start).is_ok());
923     }
924 
925     let vec = Vec::<i64>::deserialize(&parcel).unwrap();
926 
927     assert_eq!(vec, [i64::max_value(), i64::min_value(), 42, -117]);
928 
929     let f32s = [
930         std::f32::NAN,
931         std::f32::INFINITY,
932         1.23456789,
933         std::f32::EPSILON,
934     ];
935 
936     unsafe {
937         assert!(parcel.set_data_position(start).is_ok());
938     }
939     assert!(f32s.serialize(&mut parcel).is_ok());
940     unsafe {
941         assert!(parcel.set_data_position(start).is_ok());
942     }
943 
944     let vec = Vec::<f32>::deserialize(&parcel).unwrap();
945 
946     // NAN != NAN so we can't use it in the assert_eq:
947     assert!(vec[0].is_nan());
948     assert_eq!(vec[1..], f32s[1..]);
949 
950     let f64s = [
951         std::f64::NAN,
952         std::f64::INFINITY,
953         1.234567890123456789,
954         std::f64::EPSILON,
955     ];
956 
957     unsafe {
958         assert!(parcel.set_data_position(start).is_ok());
959     }
960     assert!(f64s.serialize(&mut parcel).is_ok());
961     unsafe {
962         assert!(parcel.set_data_position(start).is_ok());
963     }
964 
965     let vec = Vec::<f64>::deserialize(&parcel).unwrap();
966 
967     // NAN != NAN so we can't use it in the assert_eq:
968     assert!(vec[0].is_nan());
969     assert_eq!(vec[1..], f64s[1..]);
970 
971     let s1 = "Hello, Binder!";
972     let s2 = "This is a utf8 string.";
973     let s3 = "Some more text here.";
974     let s4 = "Embedded nulls \0 \0";
975 
976     let strs = [s1, s2, s3, s4];
977 
978     unsafe {
979         assert!(parcel.set_data_position(start).is_ok());
980     }
981     assert!(strs.serialize(&mut parcel).is_ok());
982     unsafe {
983         assert!(parcel.set_data_position(start).is_ok());
984     }
985 
986     let vec = Vec::<String>::deserialize(&parcel).unwrap();
987 
988     assert_eq!(vec, strs);
989 }
990