blob: bda538b8fb10e258d31cd0f097b34ae789e17a49 [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;
Stephen Crane2a3c2502020-06-16 17:48:35 -0700288
289 let mut service = Binder::new(()).as_binder();
290 let mut parcel = Parcel::new_for_test(&mut service).unwrap();
291 let start = parcel.get_data_position();
292
293 assert_eq!(parcel.read::<bool>(), Err(StatusCode::NOT_ENOUGH_DATA));
294 assert_eq!(parcel.read::<i8>(), Err(StatusCode::NOT_ENOUGH_DATA));
295 assert_eq!(parcel.read::<u16>(), Err(StatusCode::NOT_ENOUGH_DATA));
296 assert_eq!(parcel.read::<i32>(), Err(StatusCode::NOT_ENOUGH_DATA));
297 assert_eq!(parcel.read::<u32>(), Err(StatusCode::NOT_ENOUGH_DATA));
298 assert_eq!(parcel.read::<i64>(), Err(StatusCode::NOT_ENOUGH_DATA));
299 assert_eq!(parcel.read::<u64>(), Err(StatusCode::NOT_ENOUGH_DATA));
300 assert_eq!(parcel.read::<f32>(), Err(StatusCode::NOT_ENOUGH_DATA));
301 assert_eq!(parcel.read::<f64>(), Err(StatusCode::NOT_ENOUGH_DATA));
Stephen Crane76072e82020-08-03 13:09:36 -0700302 assert_eq!(parcel.read::<Option<String>>(), Ok(None));
Stephen Crane2a3c2502020-06-16 17:48:35 -0700303 assert_eq!(parcel.read::<String>(), Err(StatusCode::UNEXPECTED_NULL));
304
305 assert_eq!(parcel.read_binder().err(), Some(StatusCode::BAD_TYPE));
306
307 parcel.write(&1i32).unwrap();
308
309 unsafe {
310 parcel.set_data_position(start).unwrap();
311 }
312
313 let i: i32 = parcel.read().unwrap();
314 assert_eq!(i, 1i32);
315}
316
317#[test]
318#[allow(clippy::float_cmp)]
319fn test_read_data() {
320 use crate::binder::Interface;
321 use crate::native::Binder;
322
323 let mut service = Binder::new(()).as_binder();
324 let mut parcel = Parcel::new_for_test(&mut service).unwrap();
325 let str_start = parcel.get_data_position();
326
327 parcel.write(&b"Hello, Binder!\0"[..]).unwrap();
328 // Skip over string length
329 unsafe {
330 assert!(parcel.set_data_position(str_start).is_ok());
331 }
332 assert_eq!(parcel.read::<i32>().unwrap(), 15);
333 let start = parcel.get_data_position();
334
335 assert_eq!(parcel.read::<bool>().unwrap(), true);
336
337 unsafe {
338 assert!(parcel.set_data_position(start).is_ok());
339 }
340
341 assert_eq!(parcel.read::<i8>().unwrap(), 72i8);
342
343 unsafe {
344 assert!(parcel.set_data_position(start).is_ok());
345 }
346
347 assert_eq!(parcel.read::<u16>().unwrap(), 25928);
348
349 unsafe {
350 assert!(parcel.set_data_position(start).is_ok());
351 }
352
353 assert_eq!(parcel.read::<i32>().unwrap(), 1819043144);
354
355 unsafe {
356 assert!(parcel.set_data_position(start).is_ok());
357 }
358
359 assert_eq!(parcel.read::<u32>().unwrap(), 1819043144);
360
361 unsafe {
362 assert!(parcel.set_data_position(start).is_ok());
363 }
364
365 assert_eq!(parcel.read::<i64>().unwrap(), 4764857262830019912);
366
367 unsafe {
368 assert!(parcel.set_data_position(start).is_ok());
369 }
370
371 assert_eq!(parcel.read::<u64>().unwrap(), 4764857262830019912);
372
373 unsafe {
374 assert!(parcel.set_data_position(start).is_ok());
375 }
376
377 assert_eq!(
378 parcel.read::<f32>().unwrap(),
379 1143139100000000000000000000.0
380 );
381 assert_eq!(parcel.read::<f32>().unwrap(), 40.043392);
382
383 unsafe {
384 assert!(parcel.set_data_position(start).is_ok());
385 }
386
387 assert_eq!(parcel.read::<f64>().unwrap(), 34732488246.197815);
388
389 // Skip back to before the string length
390 unsafe {
391 assert!(parcel.set_data_position(str_start).is_ok());
392 }
393
394 assert_eq!(parcel.read::<Vec<u8>>().unwrap(), b"Hello, Binder!\0");
395}
396
397#[test]
398fn test_utf8_utf16_conversions() {
399 use crate::binder::Interface;
400 use crate::native::Binder;
401
402 let mut service = Binder::new(()).as_binder();
403 let mut parcel = Parcel::new_for_test(&mut service).unwrap();
404 let start = parcel.get_data_position();
405
406 assert!(parcel.write("Hello, Binder!").is_ok());
407 unsafe {
408 assert!(parcel.set_data_position(start).is_ok());
409 }
410 assert_eq!(
411 parcel.read::<Option<String>>().unwrap().unwrap(),
Stephen Crane76072e82020-08-03 13:09:36 -0700412 "Hello, Binder!",
Stephen Crane2a3c2502020-06-16 17:48:35 -0700413 );
414 unsafe {
415 assert!(parcel.set_data_position(start).is_ok());
416 }
Stephen Crane76072e82020-08-03 13:09:36 -0700417
418 assert!(parcel.write("Embedded null \0 inside a string").is_ok());
419 unsafe {
420 assert!(parcel.set_data_position(start).is_ok());
421 }
422 assert_eq!(
423 parcel.read::<Option<String>>().unwrap().unwrap(),
424 "Embedded null \0 inside a string",
425 );
426 unsafe {
427 assert!(parcel.set_data_position(start).is_ok());
428 }
429
Stephen Crane2a3c2502020-06-16 17:48:35 -0700430 assert!(parcel.write(&["str1", "str2", "str3"][..]).is_ok());
431 assert!(parcel
432 .write(
433 &[
434 String::from("str4"),
435 String::from("str5"),
436 String::from("str6"),
437 ][..]
438 )
439 .is_ok());
440
441 let s1 = "Hello, Binder!";
442 let s2 = "This is a utf8 string.";
443 let s3 = "Some more text here.";
444
445 assert!(parcel.write(&[s1, s2, s3][..]).is_ok());
446 unsafe {
447 assert!(parcel.set_data_position(start).is_ok());
448 }
449
450 assert_eq!(
451 parcel.read::<Vec<String>>().unwrap(),
452 ["str1", "str2", "str3"]
453 );
454 assert_eq!(
455 parcel.read::<Vec<String>>().unwrap(),
456 ["str4", "str5", "str6"]
457 );
458 assert_eq!(parcel.read::<Vec<String>>().unwrap(), [s1, s2, s3]);
459}