blob: 2c1e5a4b75637ba3335f12db2c1b5d0e896b923c [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 {
103 /// Write a type that implements [`Serialize`] to the `Parcel`.
104 pub fn write<S: Serialize + ?Sized>(&mut self, parcelable: &S) -> Result<()> {
105 parcelable.serialize(self)
106 }
107
108 /// Writes the length of a slice to the `Parcel`.
109 ///
110 /// This is used in AIDL-generated client side code to indicate the
111 /// allocated space for an output array parameter.
112 pub fn write_slice_size<T>(&mut self, slice: Option<&[T]>) -> Result<()> {
113 if let Some(slice) = slice {
114 let len: i32 = slice.len().try_into().or(Err(StatusCode::BAD_VALUE))?;
115 self.write(&len)
116 } else {
117 self.write(&-1i32)
118 }
119 }
120
Stephen Craneaae76382020-08-03 14:12:15 -0700121 /// Perform a series of writes to the `Parcel`, prepended with the length
122 /// (in bytes) of the written data.
123 ///
124 /// The length `0i32` will be written to the parcel first, followed by the
125 /// writes performed by the callback. The initial length will then be
126 /// updated to the length of all data written by the callback, plus the
127 /// size of the length elemement itself (4 bytes).
128 ///
129 /// # Examples
130 ///
131 /// After the following call:
132 ///
133 /// ```
134 /// # use binder::{Binder, Interface, Parcel};
135 /// # let mut parcel = Parcel::Owned(std::ptr::null_mut());
136 /// parcel.sized_write(|subparcel| {
137 /// subparcel.write(&1u32)?;
138 /// subparcel.write(&2u32)?;
139 /// subparcel.write(&3u32)
140 /// });
141 /// ```
142 ///
143 /// `parcel` will contain the following:
144 ///
145 /// ```ignore
146 /// [16i32, 1u32, 2u32, 3u32]
147 /// ```
148 pub fn sized_write<F>(&mut self, f: F) -> Result<()>
149 where for<'a>
150 F: Fn(&'a WritableSubParcel<'a>) -> Result<()>
151 {
152 let start = self.get_data_position();
153 self.write(&0i32)?;
154 {
155 let subparcel = WritableSubParcel(RefCell::new(self));
156 f(&subparcel)?;
157 }
158 let end = self.get_data_position();
159 unsafe {
160 self.set_data_position(start)?;
161 }
162 assert!(end >= start);
163 self.write(&(end - start))?;
164 unsafe {
165 self.set_data_position(end)?;
166 }
167 Ok(())
168 }
169
Stephen Crane2a3c2502020-06-16 17:48:35 -0700170 /// Returns the current position in the parcel data.
171 pub fn get_data_position(&self) -> i32 {
172 unsafe {
173 // Safety: `Parcel` always contains a valid pointer to an `AParcel`,
174 // and this call is otherwise safe.
175 sys::AParcel_getDataPosition(self.as_native())
176 }
177 }
178
179 /// Move the current read/write position in the parcel.
180 ///
181 /// The new position must be a position previously returned by
182 /// `self.get_data_position()`.
183 ///
184 /// # Safety
185 ///
186 /// This method is safe if `pos` is less than the current size of the parcel
187 /// data buffer. Otherwise, we are relying on correct bounds checking in the
188 /// Parcel C++ code on every subsequent read or write to this parcel. If all
189 /// accesses are bounds checked, this call is still safe, but we can't rely
190 /// on that.
191 pub unsafe fn set_data_position(&self, pos: i32) -> Result<()> {
192 status_result(sys::AParcel_setDataPosition(self.as_native(), pos))
193 }
194}
195
Stephen Craneaae76382020-08-03 14:12:15 -0700196/// A segment of a writable parcel, used for [`Parcel::sized_write`].
197pub struct WritableSubParcel<'a>(RefCell<&'a mut Parcel>);
198
199impl<'a> WritableSubParcel<'a> {
200 /// Write a type that implements [`Serialize`] to the sub-parcel.
201 pub fn write<S: Serialize + ?Sized>(&self, parcelable: &S) -> Result<()> {
202 parcelable.serialize(&mut *self.0.borrow_mut())
203 }
204}
205
Stephen Crane2a3c2502020-06-16 17:48:35 -0700206// Data deserialization methods
207impl Parcel {
208 /// Attempt to read a type that implements [`Deserialize`] from this
209 /// `Parcel`.
210 pub fn read<D: Deserialize>(&self) -> Result<D> {
211 D::deserialize(self)
212 }
213
214 /// Read a vector size from the `Parcel` and resize the given output vector
215 /// to be correctly sized for that amount of data.
216 ///
217 /// This method is used in AIDL-generated server side code for methods that
218 /// take a mutable slice reference parameter.
219 pub fn resize_out_vec<D: Default + Deserialize>(&self, out_vec: &mut Vec<D>) -> Result<()> {
220 let len: i32 = self.read()?;
221
222 if len < 0 {
223 return Err(StatusCode::UNEXPECTED_NULL);
224 }
225
226 // usize in Rust may be 16-bit, so i32 may not fit
227 let len = len.try_into().unwrap();
228 out_vec.resize_with(len, Default::default);
229
230 Ok(())
231 }
232
233 /// Read a vector size from the `Parcel` and either create a correctly sized
234 /// vector for that amount of data or set the output parameter to None if
235 /// the vector should be null.
236 ///
237 /// This method is used in AIDL-generated server side code for methods that
238 /// take a mutable slice reference parameter.
239 pub fn resize_nullable_out_vec<D: Default + Deserialize>(
240 &self,
241 out_vec: &mut Option<Vec<D>>,
242 ) -> Result<()> {
243 let len: i32 = self.read()?;
244
245 if len < 0 {
246 *out_vec = None;
247 } else {
248 // usize in Rust may be 16-bit, so i32 may not fit
249 let len = len.try_into().unwrap();
250 let mut vec = Vec::with_capacity(len);
251 vec.resize_with(len, Default::default);
252 *out_vec = Some(vec);
253 }
254
255 Ok(())
256 }
257}
258
259// Internal APIs
260impl Parcel {
261 pub(crate) fn write_binder(&mut self, binder: Option<&SpIBinder>) -> Result<()> {
262 unsafe {
263 // Safety: `Parcel` always contains a valid pointer to an
264 // `AParcel`. `AsNative` for `Option<SpIBinder`> will either return
265 // null or a valid pointer to an `AIBinder`, both of which are
266 // valid, safe inputs to `AParcel_writeStrongBinder`.
267 //
268 // This call does not take ownership of the binder. However, it does
269 // require a mutable pointer, which we cannot extract from an
270 // immutable reference, so we clone the binder, incrementing the
271 // refcount before the call. The refcount will be immediately
272 // decremented when this temporary is dropped.
273 status_result(sys::AParcel_writeStrongBinder(
274 self.as_native_mut(),
275 binder.cloned().as_native_mut(),
276 ))
277 }
278 }
279
280 pub(crate) fn read_binder(&self) -> Result<Option<SpIBinder>> {
281 let mut binder = ptr::null_mut();
282 let status = unsafe {
283 // Safety: `Parcel` always contains a valid pointer to an
284 // `AParcel`. We pass a valid, mutable out pointer to the `binder`
285 // parameter. After this call, `binder` will be either null or a
286 // valid pointer to an `AIBinder` owned by the caller.
287 sys::AParcel_readStrongBinder(self.as_native(), &mut binder)
288 };
289
290 status_result(status)?;
291
292 Ok(unsafe {
293 // Safety: `binder` is either null or a valid, owned pointer at this
294 // point, so can be safely passed to `SpIBinder::from_raw`.
295 SpIBinder::from_raw(binder)
296 })
297 }
298}
299
300impl Drop for Parcel {
301 fn drop(&mut self) {
302 // Run the C++ Parcel complete object destructor
303 if let Self::Owned(ptr) = *self {
304 unsafe {
305 // Safety: `Parcel` always contains a valid pointer to an
306 // `AParcel`. If we own the parcel, we can safely delete it
307 // here.
308 sys::AParcel_delete(ptr)
309 }
310 }
311 }
312}
313
314#[cfg(test)]
315impl Parcel {
316 /// Create a new parcel tied to a bogus binder. TESTING ONLY!
317 ///
318 /// This can only be used for testing! All real parcel operations must be
319 /// done in the callback to [`IBinder::transact`] or in
320 /// [`Remotable::on_transact`] using the parcels provided to these methods.
321 pub(crate) fn new_for_test(binder: &mut SpIBinder) -> Result<Self> {
322 let mut input = ptr::null_mut();
323 let status = unsafe {
324 // Safety: `SpIBinder` guarantees that `binder` always contains a
325 // valid pointer to an `AIBinder`. We pass a valid, mutable out
326 // pointer to receive a newly constructed parcel. When successful
327 // this function assigns a new pointer to an `AParcel` to `input`
328 // and transfers ownership of this pointer to the caller. Thus,
329 // after this call, `input` will either be null or point to a valid,
330 // owned `AParcel`.
331 sys::AIBinder_prepareTransaction(binder.as_native_mut(), &mut input)
332 };
333 status_result(status)?;
334 unsafe {
335 // Safety: `input` is either null or a valid, owned pointer to an
336 // `AParcel`, so is valid to safe to
337 // `Parcel::owned`. `Parcel::owned` takes ownership of the parcel
338 // pointer.
339 Parcel::owned(input).ok_or(StatusCode::UNEXPECTED_NULL)
340 }
341 }
342}
343
344#[test]
345fn test_read_write() {
346 use crate::binder::Interface;
347 use crate::native::Binder;
Stephen Crane2a3c2502020-06-16 17:48:35 -0700348
349 let mut service = Binder::new(()).as_binder();
350 let mut parcel = Parcel::new_for_test(&mut service).unwrap();
351 let start = parcel.get_data_position();
352
353 assert_eq!(parcel.read::<bool>(), Err(StatusCode::NOT_ENOUGH_DATA));
354 assert_eq!(parcel.read::<i8>(), Err(StatusCode::NOT_ENOUGH_DATA));
355 assert_eq!(parcel.read::<u16>(), Err(StatusCode::NOT_ENOUGH_DATA));
356 assert_eq!(parcel.read::<i32>(), Err(StatusCode::NOT_ENOUGH_DATA));
357 assert_eq!(parcel.read::<u32>(), Err(StatusCode::NOT_ENOUGH_DATA));
358 assert_eq!(parcel.read::<i64>(), Err(StatusCode::NOT_ENOUGH_DATA));
359 assert_eq!(parcel.read::<u64>(), Err(StatusCode::NOT_ENOUGH_DATA));
360 assert_eq!(parcel.read::<f32>(), Err(StatusCode::NOT_ENOUGH_DATA));
361 assert_eq!(parcel.read::<f64>(), Err(StatusCode::NOT_ENOUGH_DATA));
Stephen Crane76072e82020-08-03 13:09:36 -0700362 assert_eq!(parcel.read::<Option<String>>(), Ok(None));
Stephen Crane2a3c2502020-06-16 17:48:35 -0700363 assert_eq!(parcel.read::<String>(), Err(StatusCode::UNEXPECTED_NULL));
364
365 assert_eq!(parcel.read_binder().err(), Some(StatusCode::BAD_TYPE));
366
367 parcel.write(&1i32).unwrap();
368
369 unsafe {
370 parcel.set_data_position(start).unwrap();
371 }
372
373 let i: i32 = parcel.read().unwrap();
374 assert_eq!(i, 1i32);
375}
376
377#[test]
378#[allow(clippy::float_cmp)]
379fn test_read_data() {
380 use crate::binder::Interface;
381 use crate::native::Binder;
382
383 let mut service = Binder::new(()).as_binder();
384 let mut parcel = Parcel::new_for_test(&mut service).unwrap();
385 let str_start = parcel.get_data_position();
386
387 parcel.write(&b"Hello, Binder!\0"[..]).unwrap();
388 // Skip over string length
389 unsafe {
390 assert!(parcel.set_data_position(str_start).is_ok());
391 }
392 assert_eq!(parcel.read::<i32>().unwrap(), 15);
393 let start = parcel.get_data_position();
394
395 assert_eq!(parcel.read::<bool>().unwrap(), true);
396
397 unsafe {
398 assert!(parcel.set_data_position(start).is_ok());
399 }
400
401 assert_eq!(parcel.read::<i8>().unwrap(), 72i8);
402
403 unsafe {
404 assert!(parcel.set_data_position(start).is_ok());
405 }
406
407 assert_eq!(parcel.read::<u16>().unwrap(), 25928);
408
409 unsafe {
410 assert!(parcel.set_data_position(start).is_ok());
411 }
412
413 assert_eq!(parcel.read::<i32>().unwrap(), 1819043144);
414
415 unsafe {
416 assert!(parcel.set_data_position(start).is_ok());
417 }
418
419 assert_eq!(parcel.read::<u32>().unwrap(), 1819043144);
420
421 unsafe {
422 assert!(parcel.set_data_position(start).is_ok());
423 }
424
425 assert_eq!(parcel.read::<i64>().unwrap(), 4764857262830019912);
426
427 unsafe {
428 assert!(parcel.set_data_position(start).is_ok());
429 }
430
431 assert_eq!(parcel.read::<u64>().unwrap(), 4764857262830019912);
432
433 unsafe {
434 assert!(parcel.set_data_position(start).is_ok());
435 }
436
437 assert_eq!(
438 parcel.read::<f32>().unwrap(),
439 1143139100000000000000000000.0
440 );
441 assert_eq!(parcel.read::<f32>().unwrap(), 40.043392);
442
443 unsafe {
444 assert!(parcel.set_data_position(start).is_ok());
445 }
446
447 assert_eq!(parcel.read::<f64>().unwrap(), 34732488246.197815);
448
449 // Skip back to before the string length
450 unsafe {
451 assert!(parcel.set_data_position(str_start).is_ok());
452 }
453
454 assert_eq!(parcel.read::<Vec<u8>>().unwrap(), b"Hello, Binder!\0");
455}
456
457#[test]
458fn test_utf8_utf16_conversions() {
459 use crate::binder::Interface;
460 use crate::native::Binder;
461
462 let mut service = Binder::new(()).as_binder();
463 let mut parcel = Parcel::new_for_test(&mut service).unwrap();
464 let start = parcel.get_data_position();
465
466 assert!(parcel.write("Hello, Binder!").is_ok());
467 unsafe {
468 assert!(parcel.set_data_position(start).is_ok());
469 }
470 assert_eq!(
471 parcel.read::<Option<String>>().unwrap().unwrap(),
Stephen Crane76072e82020-08-03 13:09:36 -0700472 "Hello, Binder!",
Stephen Crane2a3c2502020-06-16 17:48:35 -0700473 );
474 unsafe {
475 assert!(parcel.set_data_position(start).is_ok());
476 }
Stephen Crane76072e82020-08-03 13:09:36 -0700477
478 assert!(parcel.write("Embedded null \0 inside a string").is_ok());
479 unsafe {
480 assert!(parcel.set_data_position(start).is_ok());
481 }
482 assert_eq!(
483 parcel.read::<Option<String>>().unwrap().unwrap(),
484 "Embedded null \0 inside a string",
485 );
486 unsafe {
487 assert!(parcel.set_data_position(start).is_ok());
488 }
489
Stephen Crane2a3c2502020-06-16 17:48:35 -0700490 assert!(parcel.write(&["str1", "str2", "str3"][..]).is_ok());
491 assert!(parcel
492 .write(
493 &[
494 String::from("str4"),
495 String::from("str5"),
496 String::from("str6"),
497 ][..]
498 )
499 .is_ok());
500
501 let s1 = "Hello, Binder!";
502 let s2 = "This is a utf8 string.";
503 let s3 = "Some more text here.";
504
505 assert!(parcel.write(&[s1, s2, s3][..]).is_ok());
506 unsafe {
507 assert!(parcel.set_data_position(start).is_ok());
508 }
509
510 assert_eq!(
511 parcel.read::<Vec<String>>().unwrap(),
512 ["str1", "str2", "str3"]
513 );
514 assert_eq!(
515 parcel.read::<Vec<String>>().unwrap(),
516 ["str4", "str5", "str6"]
517 );
518 assert_eq!(parcel.read::<Vec<String>>().unwrap(), [s1, s2, s3]);
519}
Stephen Craneaae76382020-08-03 14:12:15 -0700520
521#[test]
522fn test_sized_write() {
523 use crate::binder::Interface;
524 use crate::native::Binder;
525
526 let mut service = Binder::new(()).as_binder();
527 let mut parcel = Parcel::new_for_test(&mut service).unwrap();
528 let start = parcel.get_data_position();
529
530 let arr = [1i32, 2i32, 3i32];
531
532 parcel.sized_write(|subparcel| {
533 subparcel.write(&arr[..])
534 }).expect("Could not perform sized write");
535
536 // i32 sub-parcel length + i32 array length + 3 i32 elements
537 let expected_len = 20i32;
538
539 assert_eq!(parcel.get_data_position(), start + expected_len);
540
541 unsafe {
542 parcel.set_data_position(start).unwrap();
543 }
544
545 assert_eq!(
546 expected_len,
547 parcel.read().unwrap(),
548 );
549
550 assert_eq!(
551 parcel.read::<Vec<i32>>().unwrap(),
552 &arr,
553 );
554}