blob: 6c34824a5ecd75b58b12b82b9b2bd4f41eca9d4d [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
222 /// Read a vector size from the `Parcel` and resize the given output vector
223 /// to be correctly sized for that amount of data.
224 ///
225 /// This method is used in AIDL-generated server side code for methods that
226 /// take a mutable slice reference parameter.
227 pub fn resize_out_vec<D: Default + Deserialize>(&self, out_vec: &mut Vec<D>) -> Result<()> {
228 let len: i32 = self.read()?;
229
230 if len < 0 {
231 return Err(StatusCode::UNEXPECTED_NULL);
232 }
233
234 // usize in Rust may be 16-bit, so i32 may not fit
235 let len = len.try_into().unwrap();
236 out_vec.resize_with(len, Default::default);
237
238 Ok(())
239 }
240
241 /// Read a vector size from the `Parcel` and either create a correctly sized
242 /// vector for that amount of data or set the output parameter to None if
243 /// the vector should be null.
244 ///
245 /// This method is used in AIDL-generated server side code for methods that
246 /// take a mutable slice reference parameter.
247 pub fn resize_nullable_out_vec<D: Default + Deserialize>(
248 &self,
249 out_vec: &mut Option<Vec<D>>,
250 ) -> Result<()> {
251 let len: i32 = self.read()?;
252
253 if len < 0 {
254 *out_vec = None;
255 } else {
256 // usize in Rust may be 16-bit, so i32 may not fit
257 let len = len.try_into().unwrap();
258 let mut vec = Vec::with_capacity(len);
259 vec.resize_with(len, Default::default);
260 *out_vec = Some(vec);
261 }
262
263 Ok(())
264 }
265}
266
267// Internal APIs
268impl Parcel {
269 pub(crate) fn write_binder(&mut self, binder: Option<&SpIBinder>) -> Result<()> {
270 unsafe {
271 // Safety: `Parcel` always contains a valid pointer to an
272 // `AParcel`. `AsNative` for `Option<SpIBinder`> will either return
273 // null or a valid pointer to an `AIBinder`, both of which are
274 // valid, safe inputs to `AParcel_writeStrongBinder`.
275 //
276 // This call does not take ownership of the binder. However, it does
277 // require a mutable pointer, which we cannot extract from an
278 // immutable reference, so we clone the binder, incrementing the
279 // refcount before the call. The refcount will be immediately
280 // decremented when this temporary is dropped.
281 status_result(sys::AParcel_writeStrongBinder(
282 self.as_native_mut(),
283 binder.cloned().as_native_mut(),
284 ))
285 }
286 }
287
288 pub(crate) fn read_binder(&self) -> Result<Option<SpIBinder>> {
289 let mut binder = ptr::null_mut();
290 let status = unsafe {
291 // Safety: `Parcel` always contains a valid pointer to an
292 // `AParcel`. We pass a valid, mutable out pointer to the `binder`
293 // parameter. After this call, `binder` will be either null or a
294 // valid pointer to an `AIBinder` owned by the caller.
295 sys::AParcel_readStrongBinder(self.as_native(), &mut binder)
296 };
297
298 status_result(status)?;
299
300 Ok(unsafe {
301 // Safety: `binder` is either null or a valid, owned pointer at this
302 // point, so can be safely passed to `SpIBinder::from_raw`.
303 SpIBinder::from_raw(binder)
304 })
305 }
306}
307
308impl Drop for Parcel {
309 fn drop(&mut self) {
310 // Run the C++ Parcel complete object destructor
311 if let Self::Owned(ptr) = *self {
312 unsafe {
313 // Safety: `Parcel` always contains a valid pointer to an
314 // `AParcel`. If we own the parcel, we can safely delete it
315 // here.
316 sys::AParcel_delete(ptr)
317 }
318 }
319 }
320}
321
322#[cfg(test)]
323impl Parcel {
324 /// Create a new parcel tied to a bogus binder. TESTING ONLY!
325 ///
326 /// This can only be used for testing! All real parcel operations must be
327 /// done in the callback to [`IBinder::transact`] or in
328 /// [`Remotable::on_transact`] using the parcels provided to these methods.
329 pub(crate) fn new_for_test(binder: &mut SpIBinder) -> Result<Self> {
330 let mut input = ptr::null_mut();
331 let status = unsafe {
332 // Safety: `SpIBinder` guarantees that `binder` always contains a
333 // valid pointer to an `AIBinder`. We pass a valid, mutable out
334 // pointer to receive a newly constructed parcel. When successful
335 // this function assigns a new pointer to an `AParcel` to `input`
336 // and transfers ownership of this pointer to the caller. Thus,
337 // after this call, `input` will either be null or point to a valid,
338 // owned `AParcel`.
339 sys::AIBinder_prepareTransaction(binder.as_native_mut(), &mut input)
340 };
341 status_result(status)?;
342 unsafe {
343 // Safety: `input` is either null or a valid, owned pointer to an
344 // `AParcel`, so is valid to safe to
345 // `Parcel::owned`. `Parcel::owned` takes ownership of the parcel
346 // pointer.
347 Parcel::owned(input).ok_or(StatusCode::UNEXPECTED_NULL)
348 }
349 }
350}
351
352#[test]
353fn test_read_write() {
354 use crate::binder::Interface;
355 use crate::native::Binder;
Stephen Crane2a3c2502020-06-16 17:48:35 -0700356
357 let mut service = Binder::new(()).as_binder();
358 let mut parcel = Parcel::new_for_test(&mut service).unwrap();
359 let start = parcel.get_data_position();
360
361 assert_eq!(parcel.read::<bool>(), Err(StatusCode::NOT_ENOUGH_DATA));
362 assert_eq!(parcel.read::<i8>(), Err(StatusCode::NOT_ENOUGH_DATA));
363 assert_eq!(parcel.read::<u16>(), Err(StatusCode::NOT_ENOUGH_DATA));
364 assert_eq!(parcel.read::<i32>(), Err(StatusCode::NOT_ENOUGH_DATA));
365 assert_eq!(parcel.read::<u32>(), Err(StatusCode::NOT_ENOUGH_DATA));
366 assert_eq!(parcel.read::<i64>(), Err(StatusCode::NOT_ENOUGH_DATA));
367 assert_eq!(parcel.read::<u64>(), Err(StatusCode::NOT_ENOUGH_DATA));
368 assert_eq!(parcel.read::<f32>(), Err(StatusCode::NOT_ENOUGH_DATA));
369 assert_eq!(parcel.read::<f64>(), Err(StatusCode::NOT_ENOUGH_DATA));
Stephen Crane76072e82020-08-03 13:09:36 -0700370 assert_eq!(parcel.read::<Option<String>>(), Ok(None));
Stephen Crane2a3c2502020-06-16 17:48:35 -0700371 assert_eq!(parcel.read::<String>(), Err(StatusCode::UNEXPECTED_NULL));
372
373 assert_eq!(parcel.read_binder().err(), Some(StatusCode::BAD_TYPE));
374
375 parcel.write(&1i32).unwrap();
376
377 unsafe {
378 parcel.set_data_position(start).unwrap();
379 }
380
381 let i: i32 = parcel.read().unwrap();
382 assert_eq!(i, 1i32);
383}
384
385#[test]
386#[allow(clippy::float_cmp)]
387fn test_read_data() {
388 use crate::binder::Interface;
389 use crate::native::Binder;
390
391 let mut service = Binder::new(()).as_binder();
392 let mut parcel = Parcel::new_for_test(&mut service).unwrap();
393 let str_start = parcel.get_data_position();
394
395 parcel.write(&b"Hello, Binder!\0"[..]).unwrap();
396 // Skip over string length
397 unsafe {
398 assert!(parcel.set_data_position(str_start).is_ok());
399 }
400 assert_eq!(parcel.read::<i32>().unwrap(), 15);
401 let start = parcel.get_data_position();
402
403 assert_eq!(parcel.read::<bool>().unwrap(), true);
404
405 unsafe {
406 assert!(parcel.set_data_position(start).is_ok());
407 }
408
409 assert_eq!(parcel.read::<i8>().unwrap(), 72i8);
410
411 unsafe {
412 assert!(parcel.set_data_position(start).is_ok());
413 }
414
415 assert_eq!(parcel.read::<u16>().unwrap(), 25928);
416
417 unsafe {
418 assert!(parcel.set_data_position(start).is_ok());
419 }
420
421 assert_eq!(parcel.read::<i32>().unwrap(), 1819043144);
422
423 unsafe {
424 assert!(parcel.set_data_position(start).is_ok());
425 }
426
427 assert_eq!(parcel.read::<u32>().unwrap(), 1819043144);
428
429 unsafe {
430 assert!(parcel.set_data_position(start).is_ok());
431 }
432
433 assert_eq!(parcel.read::<i64>().unwrap(), 4764857262830019912);
434
435 unsafe {
436 assert!(parcel.set_data_position(start).is_ok());
437 }
438
439 assert_eq!(parcel.read::<u64>().unwrap(), 4764857262830019912);
440
441 unsafe {
442 assert!(parcel.set_data_position(start).is_ok());
443 }
444
445 assert_eq!(
446 parcel.read::<f32>().unwrap(),
447 1143139100000000000000000000.0
448 );
449 assert_eq!(parcel.read::<f32>().unwrap(), 40.043392);
450
451 unsafe {
452 assert!(parcel.set_data_position(start).is_ok());
453 }
454
455 assert_eq!(parcel.read::<f64>().unwrap(), 34732488246.197815);
456
457 // Skip back to before the string length
458 unsafe {
459 assert!(parcel.set_data_position(str_start).is_ok());
460 }
461
462 assert_eq!(parcel.read::<Vec<u8>>().unwrap(), b"Hello, Binder!\0");
463}
464
465#[test]
466fn test_utf8_utf16_conversions() {
467 use crate::binder::Interface;
468 use crate::native::Binder;
469
470 let mut service = Binder::new(()).as_binder();
471 let mut parcel = Parcel::new_for_test(&mut service).unwrap();
472 let start = parcel.get_data_position();
473
474 assert!(parcel.write("Hello, Binder!").is_ok());
475 unsafe {
476 assert!(parcel.set_data_position(start).is_ok());
477 }
478 assert_eq!(
479 parcel.read::<Option<String>>().unwrap().unwrap(),
Stephen Crane76072e82020-08-03 13:09:36 -0700480 "Hello, Binder!",
Stephen Crane2a3c2502020-06-16 17:48:35 -0700481 );
482 unsafe {
483 assert!(parcel.set_data_position(start).is_ok());
484 }
Stephen Crane76072e82020-08-03 13:09:36 -0700485
486 assert!(parcel.write("Embedded null \0 inside a string").is_ok());
487 unsafe {
488 assert!(parcel.set_data_position(start).is_ok());
489 }
490 assert_eq!(
491 parcel.read::<Option<String>>().unwrap().unwrap(),
492 "Embedded null \0 inside a string",
493 );
494 unsafe {
495 assert!(parcel.set_data_position(start).is_ok());
496 }
497
Stephen Crane2a3c2502020-06-16 17:48:35 -0700498 assert!(parcel.write(&["str1", "str2", "str3"][..]).is_ok());
499 assert!(parcel
500 .write(
501 &[
502 String::from("str4"),
503 String::from("str5"),
504 String::from("str6"),
505 ][..]
506 )
507 .is_ok());
508
509 let s1 = "Hello, Binder!";
510 let s2 = "This is a utf8 string.";
511 let s3 = "Some more text here.";
512
513 assert!(parcel.write(&[s1, s2, s3][..]).is_ok());
514 unsafe {
515 assert!(parcel.set_data_position(start).is_ok());
516 }
517
518 assert_eq!(
519 parcel.read::<Vec<String>>().unwrap(),
520 ["str1", "str2", "str3"]
521 );
522 assert_eq!(
523 parcel.read::<Vec<String>>().unwrap(),
524 ["str4", "str5", "str6"]
525 );
526 assert_eq!(parcel.read::<Vec<String>>().unwrap(), [s1, s2, s3]);
527}
Stephen Craneaae76382020-08-03 14:12:15 -0700528
529#[test]
530fn test_sized_write() {
531 use crate::binder::Interface;
532 use crate::native::Binder;
533
534 let mut service = Binder::new(()).as_binder();
535 let mut parcel = Parcel::new_for_test(&mut service).unwrap();
536 let start = parcel.get_data_position();
537
538 let arr = [1i32, 2i32, 3i32];
539
540 parcel.sized_write(|subparcel| {
541 subparcel.write(&arr[..])
542 }).expect("Could not perform sized write");
543
544 // i32 sub-parcel length + i32 array length + 3 i32 elements
545 let expected_len = 20i32;
546
547 assert_eq!(parcel.get_data_position(), start + expected_len);
548
549 unsafe {
550 parcel.set_data_position(start).unwrap();
551 }
552
553 assert_eq!(
554 expected_len,
555 parcel.read().unwrap(),
556 );
557
558 assert_eq!(
559 parcel.read::<Vec<i32>>().unwrap(),
560 &arr,
561 );
562}