blob: 43850fe411348b6d7abe9e09029e009f0c494a11 [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
24use std::convert::TryInto;
25use std::mem::ManuallyDrop;
26use std::ptr;
27
28mod file_descriptor;
29mod parcelable;
30
31pub use self::file_descriptor::ParcelFileDescriptor;
32pub use self::parcelable::{
33 Deserialize, DeserializeArray, DeserializeOption, Serialize, SerializeArray, SerializeOption,
34};
35
36/// Container for a message (data and object references) that can be sent
37/// through Binder.
38///
39/// A Parcel can contain both serialized data that will be deserialized on the
40/// other side of the IPC, and references to live Binder objects that will
41/// result in the other side receiving a proxy Binder connected with the
42/// original Binder in the Parcel.
43pub enum Parcel {
44 /// Owned parcel pointer
45 Owned(*mut sys::AParcel),
46 /// Borrowed parcel pointer (will not be destroyed on drop)
47 Borrowed(*mut sys::AParcel),
48}
49
50/// # Safety
51///
52/// The `Parcel` constructors guarantee that a `Parcel` object will always
53/// contain a valid pointer to an `AParcel`.
54unsafe impl AsNative<sys::AParcel> for Parcel {
55 fn as_native(&self) -> *const sys::AParcel {
56 match *self {
57 Self::Owned(x) | Self::Borrowed(x) => x,
58 }
59 }
60
61 fn as_native_mut(&mut self) -> *mut sys::AParcel {
62 match *self {
63 Self::Owned(x) | Self::Borrowed(x) => x,
64 }
65 }
66}
67
68impl Parcel {
69 /// Create a borrowed reference to a parcel object from a raw pointer.
70 ///
71 /// # Safety
72 ///
73 /// This constructor is safe if the raw pointer parameter is either null
74 /// (resulting in `None`), or a valid pointer to an `AParcel` object.
75 pub(crate) unsafe fn borrowed(ptr: *mut sys::AParcel) -> Option<Parcel> {
76 ptr.as_mut().map(|ptr| Self::Borrowed(ptr))
77 }
78
79 /// Create an owned reference to a parcel object from a raw pointer.
80 ///
81 /// # Safety
82 ///
83 /// This constructor is safe if the raw pointer parameter is either null
84 /// (resulting in `None`), or a valid pointer to an `AParcel` object. The
85 /// parcel object must be owned by the caller prior to this call, as this
86 /// constructor takes ownership of the parcel and will destroy it on drop.
87 pub(crate) unsafe fn owned(ptr: *mut sys::AParcel) -> Option<Parcel> {
88 ptr.as_mut().map(|ptr| Self::Owned(ptr))
89 }
90
91 /// Consume the parcel, transferring ownership to the caller if the parcel
92 /// was owned.
93 pub(crate) fn into_raw(mut self) -> *mut sys::AParcel {
94 let ptr = self.as_native_mut();
95 let _ = ManuallyDrop::new(self);
96 ptr
97 }
98}
99
100// Data serialization methods
101impl Parcel {
102 /// Write a type that implements [`Serialize`] to the `Parcel`.
103 pub fn write<S: Serialize + ?Sized>(&mut self, parcelable: &S) -> Result<()> {
104 parcelable.serialize(self)
105 }
106
107 /// Writes the length of a slice to the `Parcel`.
108 ///
109 /// This is used in AIDL-generated client side code to indicate the
110 /// allocated space for an output array parameter.
111 pub fn write_slice_size<T>(&mut self, slice: Option<&[T]>) -> Result<()> {
112 if let Some(slice) = slice {
113 let len: i32 = slice.len().try_into().or(Err(StatusCode::BAD_VALUE))?;
114 self.write(&len)
115 } else {
116 self.write(&-1i32)
117 }
118 }
119
120 /// Returns the current position in the parcel data.
121 pub fn get_data_position(&self) -> i32 {
122 unsafe {
123 // Safety: `Parcel` always contains a valid pointer to an `AParcel`,
124 // and this call is otherwise safe.
125 sys::AParcel_getDataPosition(self.as_native())
126 }
127 }
128
129 /// Move the current read/write position in the parcel.
130 ///
131 /// The new position must be a position previously returned by
132 /// `self.get_data_position()`.
133 ///
134 /// # Safety
135 ///
136 /// This method is safe if `pos` is less than the current size of the parcel
137 /// data buffer. Otherwise, we are relying on correct bounds checking in the
138 /// Parcel C++ code on every subsequent read or write to this parcel. If all
139 /// accesses are bounds checked, this call is still safe, but we can't rely
140 /// on that.
141 pub unsafe fn set_data_position(&self, pos: i32) -> Result<()> {
142 status_result(sys::AParcel_setDataPosition(self.as_native(), pos))
143 }
144}
145
146// Data deserialization methods
147impl Parcel {
148 /// Attempt to read a type that implements [`Deserialize`] from this
149 /// `Parcel`.
150 pub fn read<D: Deserialize>(&self) -> Result<D> {
151 D::deserialize(self)
152 }
153
154 /// Read a vector size from the `Parcel` and resize the given output vector
155 /// to be correctly sized for that amount of data.
156 ///
157 /// This method is used in AIDL-generated server side code for methods that
158 /// take a mutable slice reference parameter.
159 pub fn resize_out_vec<D: Default + Deserialize>(&self, out_vec: &mut Vec<D>) -> Result<()> {
160 let len: i32 = self.read()?;
161
162 if len < 0 {
163 return Err(StatusCode::UNEXPECTED_NULL);
164 }
165
166 // usize in Rust may be 16-bit, so i32 may not fit
167 let len = len.try_into().unwrap();
168 out_vec.resize_with(len, Default::default);
169
170 Ok(())
171 }
172
173 /// Read a vector size from the `Parcel` and either create a correctly sized
174 /// vector for that amount of data or set the output parameter to None if
175 /// the vector should be null.
176 ///
177 /// This method is used in AIDL-generated server side code for methods that
178 /// take a mutable slice reference parameter.
179 pub fn resize_nullable_out_vec<D: Default + Deserialize>(
180 &self,
181 out_vec: &mut Option<Vec<D>>,
182 ) -> Result<()> {
183 let len: i32 = self.read()?;
184
185 if len < 0 {
186 *out_vec = None;
187 } else {
188 // usize in Rust may be 16-bit, so i32 may not fit
189 let len = len.try_into().unwrap();
190 let mut vec = Vec::with_capacity(len);
191 vec.resize_with(len, Default::default);
192 *out_vec = Some(vec);
193 }
194
195 Ok(())
196 }
197}
198
199// Internal APIs
200impl Parcel {
201 pub(crate) fn write_binder(&mut self, binder: Option<&SpIBinder>) -> Result<()> {
202 unsafe {
203 // Safety: `Parcel` always contains a valid pointer to an
204 // `AParcel`. `AsNative` for `Option<SpIBinder`> will either return
205 // null or a valid pointer to an `AIBinder`, both of which are
206 // valid, safe inputs to `AParcel_writeStrongBinder`.
207 //
208 // This call does not take ownership of the binder. However, it does
209 // require a mutable pointer, which we cannot extract from an
210 // immutable reference, so we clone the binder, incrementing the
211 // refcount before the call. The refcount will be immediately
212 // decremented when this temporary is dropped.
213 status_result(sys::AParcel_writeStrongBinder(
214 self.as_native_mut(),
215 binder.cloned().as_native_mut(),
216 ))
217 }
218 }
219
220 pub(crate) fn read_binder(&self) -> Result<Option<SpIBinder>> {
221 let mut binder = ptr::null_mut();
222 let status = unsafe {
223 // Safety: `Parcel` always contains a valid pointer to an
224 // `AParcel`. We pass a valid, mutable out pointer to the `binder`
225 // parameter. After this call, `binder` will be either null or a
226 // valid pointer to an `AIBinder` owned by the caller.
227 sys::AParcel_readStrongBinder(self.as_native(), &mut binder)
228 };
229
230 status_result(status)?;
231
232 Ok(unsafe {
233 // Safety: `binder` is either null or a valid, owned pointer at this
234 // point, so can be safely passed to `SpIBinder::from_raw`.
235 SpIBinder::from_raw(binder)
236 })
237 }
238}
239
240impl Drop for Parcel {
241 fn drop(&mut self) {
242 // Run the C++ Parcel complete object destructor
243 if let Self::Owned(ptr) = *self {
244 unsafe {
245 // Safety: `Parcel` always contains a valid pointer to an
246 // `AParcel`. If we own the parcel, we can safely delete it
247 // here.
248 sys::AParcel_delete(ptr)
249 }
250 }
251 }
252}
253
254#[cfg(test)]
255impl Parcel {
256 /// Create a new parcel tied to a bogus binder. TESTING ONLY!
257 ///
258 /// This can only be used for testing! All real parcel operations must be
259 /// done in the callback to [`IBinder::transact`] or in
260 /// [`Remotable::on_transact`] using the parcels provided to these methods.
261 pub(crate) fn new_for_test(binder: &mut SpIBinder) -> Result<Self> {
262 let mut input = ptr::null_mut();
263 let status = unsafe {
264 // Safety: `SpIBinder` guarantees that `binder` always contains a
265 // valid pointer to an `AIBinder`. We pass a valid, mutable out
266 // pointer to receive a newly constructed parcel. When successful
267 // this function assigns a new pointer to an `AParcel` to `input`
268 // and transfers ownership of this pointer to the caller. Thus,
269 // after this call, `input` will either be null or point to a valid,
270 // owned `AParcel`.
271 sys::AIBinder_prepareTransaction(binder.as_native_mut(), &mut input)
272 };
273 status_result(status)?;
274 unsafe {
275 // Safety: `input` is either null or a valid, owned pointer to an
276 // `AParcel`, so is valid to safe to
277 // `Parcel::owned`. `Parcel::owned` takes ownership of the parcel
278 // pointer.
279 Parcel::owned(input).ok_or(StatusCode::UNEXPECTED_NULL)
280 }
281 }
282}
283
284#[test]
285fn test_read_write() {
286 use crate::binder::Interface;
287 use crate::native::Binder;
288 use std::ffi::CString;
289
290 let mut service = Binder::new(()).as_binder();
291 let mut parcel = Parcel::new_for_test(&mut service).unwrap();
292 let start = parcel.get_data_position();
293
294 assert_eq!(parcel.read::<bool>(), Err(StatusCode::NOT_ENOUGH_DATA));
295 assert_eq!(parcel.read::<i8>(), Err(StatusCode::NOT_ENOUGH_DATA));
296 assert_eq!(parcel.read::<u16>(), Err(StatusCode::NOT_ENOUGH_DATA));
297 assert_eq!(parcel.read::<i32>(), Err(StatusCode::NOT_ENOUGH_DATA));
298 assert_eq!(parcel.read::<u32>(), Err(StatusCode::NOT_ENOUGH_DATA));
299 assert_eq!(parcel.read::<i64>(), Err(StatusCode::NOT_ENOUGH_DATA));
300 assert_eq!(parcel.read::<u64>(), Err(StatusCode::NOT_ENOUGH_DATA));
301 assert_eq!(parcel.read::<f32>(), Err(StatusCode::NOT_ENOUGH_DATA));
302 assert_eq!(parcel.read::<f64>(), Err(StatusCode::NOT_ENOUGH_DATA));
303 assert_eq!(parcel.read::<Option<CString>>(), Ok(None));
304 assert_eq!(parcel.read::<String>(), Err(StatusCode::UNEXPECTED_NULL));
305
306 assert_eq!(parcel.read_binder().err(), Some(StatusCode::BAD_TYPE));
307
308 parcel.write(&1i32).unwrap();
309
310 unsafe {
311 parcel.set_data_position(start).unwrap();
312 }
313
314 let i: i32 = parcel.read().unwrap();
315 assert_eq!(i, 1i32);
316}
317
318#[test]
319#[allow(clippy::float_cmp)]
320fn test_read_data() {
321 use crate::binder::Interface;
322 use crate::native::Binder;
323
324 let mut service = Binder::new(()).as_binder();
325 let mut parcel = Parcel::new_for_test(&mut service).unwrap();
326 let str_start = parcel.get_data_position();
327
328 parcel.write(&b"Hello, Binder!\0"[..]).unwrap();
329 // Skip over string length
330 unsafe {
331 assert!(parcel.set_data_position(str_start).is_ok());
332 }
333 assert_eq!(parcel.read::<i32>().unwrap(), 15);
334 let start = parcel.get_data_position();
335
336 assert_eq!(parcel.read::<bool>().unwrap(), true);
337
338 unsafe {
339 assert!(parcel.set_data_position(start).is_ok());
340 }
341
342 assert_eq!(parcel.read::<i8>().unwrap(), 72i8);
343
344 unsafe {
345 assert!(parcel.set_data_position(start).is_ok());
346 }
347
348 assert_eq!(parcel.read::<u16>().unwrap(), 25928);
349
350 unsafe {
351 assert!(parcel.set_data_position(start).is_ok());
352 }
353
354 assert_eq!(parcel.read::<i32>().unwrap(), 1819043144);
355
356 unsafe {
357 assert!(parcel.set_data_position(start).is_ok());
358 }
359
360 assert_eq!(parcel.read::<u32>().unwrap(), 1819043144);
361
362 unsafe {
363 assert!(parcel.set_data_position(start).is_ok());
364 }
365
366 assert_eq!(parcel.read::<i64>().unwrap(), 4764857262830019912);
367
368 unsafe {
369 assert!(parcel.set_data_position(start).is_ok());
370 }
371
372 assert_eq!(parcel.read::<u64>().unwrap(), 4764857262830019912);
373
374 unsafe {
375 assert!(parcel.set_data_position(start).is_ok());
376 }
377
378 assert_eq!(
379 parcel.read::<f32>().unwrap(),
380 1143139100000000000000000000.0
381 );
382 assert_eq!(parcel.read::<f32>().unwrap(), 40.043392);
383
384 unsafe {
385 assert!(parcel.set_data_position(start).is_ok());
386 }
387
388 assert_eq!(parcel.read::<f64>().unwrap(), 34732488246.197815);
389
390 // Skip back to before the string length
391 unsafe {
392 assert!(parcel.set_data_position(str_start).is_ok());
393 }
394
395 assert_eq!(parcel.read::<Vec<u8>>().unwrap(), b"Hello, Binder!\0");
396}
397
398#[test]
399fn test_utf8_utf16_conversions() {
400 use crate::binder::Interface;
401 use crate::native::Binder;
402
403 let mut service = Binder::new(()).as_binder();
404 let mut parcel = Parcel::new_for_test(&mut service).unwrap();
405 let start = parcel.get_data_position();
406
407 assert!(parcel.write("Hello, Binder!").is_ok());
408 unsafe {
409 assert!(parcel.set_data_position(start).is_ok());
410 }
411 assert_eq!(
412 parcel.read::<Option<String>>().unwrap().unwrap(),
413 "Hello, Binder!"
414 );
415 unsafe {
416 assert!(parcel.set_data_position(start).is_ok());
417 }
418 assert!(parcel.write(&["str1", "str2", "str3"][..]).is_ok());
419 assert!(parcel
420 .write(
421 &[
422 String::from("str4"),
423 String::from("str5"),
424 String::from("str6"),
425 ][..]
426 )
427 .is_ok());
428
429 let s1 = "Hello, Binder!";
430 let s2 = "This is a utf8 string.";
431 let s3 = "Some more text here.";
432
433 assert!(parcel.write(&[s1, s2, s3][..]).is_ok());
434 unsafe {
435 assert!(parcel.set_data_position(start).is_ok());
436 }
437
438 assert_eq!(
439 parcel.read::<Vec<String>>().unwrap(),
440 ["str1", "str2", "str3"]
441 );
442 assert_eq!(
443 parcel.read::<Vec<String>>().unwrap(),
444 ["str4", "str5", "str6"]
445 );
446 assert_eq!(parcel.read::<Vec<String>>().unwrap(), [s1, s2, s3]);
447}