blob: a248f5c510465ba07ba3202c2e5a542ca33f911d [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;
348 use std::ffi::CString;
349
350 let mut service = Binder::new(()).as_binder();
351 let mut parcel = Parcel::new_for_test(&mut service).unwrap();
352 let start = parcel.get_data_position();
353
354 assert_eq!(parcel.read::<bool>(), Err(StatusCode::NOT_ENOUGH_DATA));
355 assert_eq!(parcel.read::<i8>(), Err(StatusCode::NOT_ENOUGH_DATA));
356 assert_eq!(parcel.read::<u16>(), Err(StatusCode::NOT_ENOUGH_DATA));
357 assert_eq!(parcel.read::<i32>(), Err(StatusCode::NOT_ENOUGH_DATA));
358 assert_eq!(parcel.read::<u32>(), Err(StatusCode::NOT_ENOUGH_DATA));
359 assert_eq!(parcel.read::<i64>(), Err(StatusCode::NOT_ENOUGH_DATA));
360 assert_eq!(parcel.read::<u64>(), Err(StatusCode::NOT_ENOUGH_DATA));
361 assert_eq!(parcel.read::<f32>(), Err(StatusCode::NOT_ENOUGH_DATA));
362 assert_eq!(parcel.read::<f64>(), Err(StatusCode::NOT_ENOUGH_DATA));
363 assert_eq!(parcel.read::<Option<CString>>(), Ok(None));
364 assert_eq!(parcel.read::<String>(), Err(StatusCode::UNEXPECTED_NULL));
365
366 assert_eq!(parcel.read_binder().err(), Some(StatusCode::BAD_TYPE));
367
368 parcel.write(&1i32).unwrap();
369
370 unsafe {
371 parcel.set_data_position(start).unwrap();
372 }
373
374 let i: i32 = parcel.read().unwrap();
375 assert_eq!(i, 1i32);
376}
377
378#[test]
379#[allow(clippy::float_cmp)]
380fn test_read_data() {
381 use crate::binder::Interface;
382 use crate::native::Binder;
383
384 let mut service = Binder::new(()).as_binder();
385 let mut parcel = Parcel::new_for_test(&mut service).unwrap();
386 let str_start = parcel.get_data_position();
387
388 parcel.write(&b"Hello, Binder!\0"[..]).unwrap();
389 // Skip over string length
390 unsafe {
391 assert!(parcel.set_data_position(str_start).is_ok());
392 }
393 assert_eq!(parcel.read::<i32>().unwrap(), 15);
394 let start = parcel.get_data_position();
395
396 assert_eq!(parcel.read::<bool>().unwrap(), true);
397
398 unsafe {
399 assert!(parcel.set_data_position(start).is_ok());
400 }
401
402 assert_eq!(parcel.read::<i8>().unwrap(), 72i8);
403
404 unsafe {
405 assert!(parcel.set_data_position(start).is_ok());
406 }
407
408 assert_eq!(parcel.read::<u16>().unwrap(), 25928);
409
410 unsafe {
411 assert!(parcel.set_data_position(start).is_ok());
412 }
413
414 assert_eq!(parcel.read::<i32>().unwrap(), 1819043144);
415
416 unsafe {
417 assert!(parcel.set_data_position(start).is_ok());
418 }
419
420 assert_eq!(parcel.read::<u32>().unwrap(), 1819043144);
421
422 unsafe {
423 assert!(parcel.set_data_position(start).is_ok());
424 }
425
426 assert_eq!(parcel.read::<i64>().unwrap(), 4764857262830019912);
427
428 unsafe {
429 assert!(parcel.set_data_position(start).is_ok());
430 }
431
432 assert_eq!(parcel.read::<u64>().unwrap(), 4764857262830019912);
433
434 unsafe {
435 assert!(parcel.set_data_position(start).is_ok());
436 }
437
438 assert_eq!(
439 parcel.read::<f32>().unwrap(),
440 1143139100000000000000000000.0
441 );
442 assert_eq!(parcel.read::<f32>().unwrap(), 40.043392);
443
444 unsafe {
445 assert!(parcel.set_data_position(start).is_ok());
446 }
447
448 assert_eq!(parcel.read::<f64>().unwrap(), 34732488246.197815);
449
450 // Skip back to before the string length
451 unsafe {
452 assert!(parcel.set_data_position(str_start).is_ok());
453 }
454
455 assert_eq!(parcel.read::<Vec<u8>>().unwrap(), b"Hello, Binder!\0");
456}
457
458#[test]
459fn test_utf8_utf16_conversions() {
460 use crate::binder::Interface;
461 use crate::native::Binder;
462
463 let mut service = Binder::new(()).as_binder();
464 let mut parcel = Parcel::new_for_test(&mut service).unwrap();
465 let start = parcel.get_data_position();
466
467 assert!(parcel.write("Hello, Binder!").is_ok());
468 unsafe {
469 assert!(parcel.set_data_position(start).is_ok());
470 }
471 assert_eq!(
472 parcel.read::<Option<String>>().unwrap().unwrap(),
473 "Hello, Binder!"
474 );
475 unsafe {
476 assert!(parcel.set_data_position(start).is_ok());
477 }
478 assert!(parcel.write(&["str1", "str2", "str3"][..]).is_ok());
479 assert!(parcel
480 .write(
481 &[
482 String::from("str4"),
483 String::from("str5"),
484 String::from("str6"),
485 ][..]
486 )
487 .is_ok());
488
489 let s1 = "Hello, Binder!";
490 let s2 = "This is a utf8 string.";
491 let s3 = "Some more text here.";
492
493 assert!(parcel.write(&[s1, s2, s3][..]).is_ok());
494 unsafe {
495 assert!(parcel.set_data_position(start).is_ok());
496 }
497
498 assert_eq!(
499 parcel.read::<Vec<String>>().unwrap(),
500 ["str1", "str2", "str3"]
501 );
502 assert_eq!(
503 parcel.read::<Vec<String>>().unwrap(),
504 ["str4", "str5", "str6"]
505 );
506 assert_eq!(parcel.read::<Vec<String>>().unwrap(), [s1, s2, s3]);
507}
Stephen Craneaae76382020-08-03 14:12:15 -0700508
509#[test]
510fn test_sized_write() {
511 use crate::binder::Interface;
512 use crate::native::Binder;
513
514 let mut service = Binder::new(()).as_binder();
515 let mut parcel = Parcel::new_for_test(&mut service).unwrap();
516 let start = parcel.get_data_position();
517
518 let arr = [1i32, 2i32, 3i32];
519
520 parcel.sized_write(|subparcel| {
521 subparcel.write(&arr[..])
522 }).expect("Could not perform sized write");
523
524 // i32 sub-parcel length + i32 array length + 3 i32 elements
525 let expected_len = 20i32;
526
527 assert_eq!(parcel.get_data_position(), start + expected_len);
528
529 unsafe {
530 parcel.set_data_position(start).unwrap();
531 }
532
533 assert_eq!(
534 expected_len,
535 parcel.read().unwrap(),
536 );
537
538 assert_eq!(
539 parcel.read::<Vec<i32>>().unwrap(),
540 &arr,
541 );
542}