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