1 /*
2  * Copyright (C) 2005 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 #pragma once
18 
19 #include <array>
20 #include <limits>
21 #include <map> // for legacy reasons
22 #include <optional>
23 #include <string>
24 #include <type_traits>
25 #include <variant>
26 #include <vector>
27 
28 #include <binder/unique_fd.h>
29 #ifndef BINDER_DISABLE_NATIVE_HANDLE
30 #include <cutils/native_handle.h>
31 #endif
32 #include <utils/Errors.h>
33 #include <utils/RefBase.h>
34 #include <utils/String16.h>
35 #include <utils/Vector.h>
36 
37 #include <binder/Common.h>
38 #include <binder/IInterface.h>
39 #include <binder/Parcelable.h>
40 
41 //NOLINTNEXTLINE(google-runtime-int) b/173188702
42 typedef unsigned long long binder_size_t;
43 
44 struct flat_binder_object;
45 
46 // ---------------------------------------------------------------------------
47 namespace android {
48 
49 template <typename T> class Flattenable;
50 template <typename T> class LightFlattenable;
51 class IBinder;
52 class IPCThreadState;
53 class ProcessState;
54 class RpcSession;
55 class String8;
56 class TextOutput;
57 namespace binder {
58 class Status;
59 namespace debug {
60 class RecordedTransaction;
61 }
62 }
63 
64 class Parcel {
65     friend class IPCThreadState;
66     friend class RpcState;
67 
68 public:
69     class ReadableBlob;
70     class WritableBlob;
71 
72     LIBBINDER_EXPORTED Parcel();
73     LIBBINDER_EXPORTED ~Parcel();
74 
75     LIBBINDER_EXPORTED const uint8_t* data() const;
76     LIBBINDER_EXPORTED size_t dataSize() const;
77     LIBBINDER_EXPORTED size_t dataAvail() const;
78     LIBBINDER_EXPORTED size_t dataPosition() const;
79     LIBBINDER_EXPORTED size_t dataCapacity() const;
80     LIBBINDER_EXPORTED size_t dataBufferSize() const;
81 
82     LIBBINDER_EXPORTED status_t setDataSize(size_t size);
83 
84     // this must only be used to set a data position that was previously returned from
85     // dataPosition(). If writes are made, the exact same types of writes must be made (e.g.
86     // auto i = p.dataPosition(); p.writeInt32(0); p.setDataPosition(i); p.writeInt32(1);).
87     // Writing over objects, such as file descriptors and binders, is not supported.
88     LIBBINDER_EXPORTED void setDataPosition(size_t pos) const;
89     LIBBINDER_EXPORTED status_t setDataCapacity(size_t size);
90 
91     LIBBINDER_EXPORTED status_t setData(const uint8_t* buffer, size_t len);
92 
93     LIBBINDER_EXPORTED status_t appendFrom(const Parcel* parcel, size_t start, size_t len);
94 
95     LIBBINDER_EXPORTED int compareData(const Parcel& other) const;
96     LIBBINDER_EXPORTED status_t compareDataInRange(size_t thisOffset, const Parcel& other,
97                                                    size_t otherOffset, size_t length,
98                                                    int* result) const;
99 
100     LIBBINDER_EXPORTED bool allowFds() const;
101     LIBBINDER_EXPORTED bool pushAllowFds(bool allowFds);
102     LIBBINDER_EXPORTED void restoreAllowFds(bool lastValue);
103 
104     LIBBINDER_EXPORTED bool hasFileDescriptors() const;
105     LIBBINDER_EXPORTED status_t hasBinders(bool* result) const;
106     LIBBINDER_EXPORTED status_t hasFileDescriptorsInRange(size_t offset, size_t length,
107                                                           bool* result) const;
108     LIBBINDER_EXPORTED status_t hasBindersInRange(size_t offset, size_t length, bool* result) const;
109 
110     // returns all binder objects in the Parcel
111     LIBBINDER_EXPORTED std::vector<sp<IBinder>> debugReadAllStrongBinders() const;
112     // returns all file descriptors in the Parcel
113     // does not dup
114     LIBBINDER_EXPORTED std::vector<int> debugReadAllFileDescriptors() const;
115 
116     // Zeros data when reallocating. Other mitigations may be added
117     // in the future.
118     //
119     // WARNING: some read methods may make additional copies of data.
120     // In order to verify this, heap dumps should be used.
121     LIBBINDER_EXPORTED void markSensitive() const;
122 
123     // For a 'data' Parcel, this should mark the Parcel as being prepared for a
124     // transaction on this specific binder object. Based on this, the format of
125     // the wire binder protocol may change (data is written differently when it
126     // is for an RPC transaction).
127     LIBBINDER_EXPORTED void markForBinder(const sp<IBinder>& binder);
128 
129     // Whenever possible, markForBinder should be preferred. This method is
130     // called automatically on reply Parcels for RPC transactions.
131     LIBBINDER_EXPORTED void markForRpc(const sp<RpcSession>& session);
132 
133     // Whether this Parcel is written for RPC transactions (after calls to
134     // markForBinder or markForRpc).
135     LIBBINDER_EXPORTED bool isForRpc() const;
136 
137     // Writes the IPC/RPC header.
138     LIBBINDER_EXPORTED status_t writeInterfaceToken(const String16& interface);
139     LIBBINDER_EXPORTED status_t writeInterfaceToken(const char16_t* str, size_t len);
140 
141     // Parses the RPC header, returning true if the interface name
142     // in the header matches the expected interface from the caller.
143     //
144     // Additionally, enforceInterface does part of the work of
145     // propagating the StrictMode policy mask, populating the current
146     // IPCThreadState, which as an optimization may optionally be
147     // passed in.
148     LIBBINDER_EXPORTED bool enforceInterface(const String16& interface,
149                                              IPCThreadState* threadState = nullptr) const;
150     LIBBINDER_EXPORTED bool enforceInterface(const char16_t* interface, size_t len,
151                                              IPCThreadState* threadState = nullptr) const;
152     LIBBINDER_EXPORTED bool checkInterface(IBinder*) const;
153 
154     // Verify there are no bytes left to be read on the Parcel.
155     // Returns Status(EX_BAD_PARCELABLE) when the Parcel is not consumed.
156     LIBBINDER_EXPORTED binder::Status enforceNoDataAvail() const;
157 
158     // This Api is used by fuzzers to skip dataAvail checks.
159     LIBBINDER_EXPORTED void setEnforceNoDataAvail(bool enforceNoDataAvail);
160 
161     // When fuzzing, we want to remove certain ABI checks that cause significant
162     // lost coverage, and we also want to avoid logs that cost too much to write.
163     LIBBINDER_EXPORTED void setServiceFuzzing();
164     LIBBINDER_EXPORTED bool isServiceFuzzing() const;
165 
166     LIBBINDER_EXPORTED void freeData();
167 
168     LIBBINDER_EXPORTED size_t objectsCount() const;
169 
170     LIBBINDER_EXPORTED status_t errorCheck() const;
171     LIBBINDER_EXPORTED void setError(status_t err);
172 
173     LIBBINDER_EXPORTED status_t write(const void* data, size_t len);
174     LIBBINDER_EXPORTED void* writeInplace(size_t len);
175     LIBBINDER_EXPORTED status_t writeInt32(int32_t val);
176     LIBBINDER_EXPORTED status_t writeUint32(uint32_t val);
177     LIBBINDER_EXPORTED status_t writeInt64(int64_t val);
178     LIBBINDER_EXPORTED status_t writeUint64(uint64_t val);
179     LIBBINDER_EXPORTED status_t writeFloat(float val);
180     LIBBINDER_EXPORTED status_t writeDouble(double val);
181     LIBBINDER_EXPORTED status_t writeCString(const char* str)
182             __attribute__((deprecated("use AIDL, writeString* instead")));
183     LIBBINDER_EXPORTED status_t writeString8(const String8& str);
184     LIBBINDER_EXPORTED status_t writeString8(const char* str, size_t len);
185     LIBBINDER_EXPORTED status_t writeString16(const String16& str);
186     LIBBINDER_EXPORTED status_t writeString16(const std::optional<String16>& str);
187     LIBBINDER_EXPORTED status_t writeString16(const std::unique_ptr<String16>& str)
188             __attribute__((deprecated("use std::optional version instead")));
189     LIBBINDER_EXPORTED status_t writeString16(const char16_t* str, size_t len);
190     LIBBINDER_EXPORTED status_t writeStrongBinder(const sp<IBinder>& val);
191     LIBBINDER_EXPORTED status_t writeInt32Array(size_t len, const int32_t* val);
192     LIBBINDER_EXPORTED status_t writeByteArray(size_t len, const uint8_t* val);
193     LIBBINDER_EXPORTED status_t writeBool(bool val);
194     LIBBINDER_EXPORTED status_t writeChar(char16_t val);
195     LIBBINDER_EXPORTED status_t writeByte(int8_t val);
196 
197     // Take a UTF8 encoded string, convert to UTF16, write it to the parcel.
198     LIBBINDER_EXPORTED status_t writeUtf8AsUtf16(const std::string& str);
199     LIBBINDER_EXPORTED status_t writeUtf8AsUtf16(const std::optional<std::string>& str);
200     LIBBINDER_EXPORTED status_t writeUtf8AsUtf16(const std::unique_ptr<std::string>& str)
201             __attribute__((deprecated("use std::optional version instead")));
202 
203     LIBBINDER_EXPORTED status_t writeByteVector(const std::optional<std::vector<int8_t>>& val);
204     LIBBINDER_EXPORTED status_t writeByteVector(const std::unique_ptr<std::vector<int8_t>>& val)
205             __attribute__((deprecated("use std::optional version instead")));
206     LIBBINDER_EXPORTED status_t writeByteVector(const std::vector<int8_t>& val);
207     LIBBINDER_EXPORTED status_t writeByteVector(const std::optional<std::vector<uint8_t>>& val);
208     LIBBINDER_EXPORTED status_t writeByteVector(const std::unique_ptr<std::vector<uint8_t>>& val)
209             __attribute__((deprecated("use std::optional version instead")));
210     LIBBINDER_EXPORTED status_t writeByteVector(const std::vector<uint8_t>& val);
211     LIBBINDER_EXPORTED status_t writeInt32Vector(const std::optional<std::vector<int32_t>>& val);
212     LIBBINDER_EXPORTED status_t writeInt32Vector(const std::unique_ptr<std::vector<int32_t>>& val)
213             __attribute__((deprecated("use std::optional version instead")));
214     LIBBINDER_EXPORTED status_t writeInt32Vector(const std::vector<int32_t>& val);
215     LIBBINDER_EXPORTED status_t writeInt64Vector(const std::optional<std::vector<int64_t>>& val);
216     LIBBINDER_EXPORTED status_t writeInt64Vector(const std::unique_ptr<std::vector<int64_t>>& val)
217             __attribute__((deprecated("use std::optional version instead")));
218     LIBBINDER_EXPORTED status_t writeInt64Vector(const std::vector<int64_t>& val);
219     LIBBINDER_EXPORTED status_t writeUint64Vector(const std::optional<std::vector<uint64_t>>& val);
220     LIBBINDER_EXPORTED status_t writeUint64Vector(const std::unique_ptr<std::vector<uint64_t>>& val)
221             __attribute__((deprecated("use std::optional version instead")));
222     LIBBINDER_EXPORTED status_t writeUint64Vector(const std::vector<uint64_t>& val);
223     LIBBINDER_EXPORTED status_t writeFloatVector(const std::optional<std::vector<float>>& val);
224     LIBBINDER_EXPORTED status_t writeFloatVector(const std::unique_ptr<std::vector<float>>& val)
225             __attribute__((deprecated("use std::optional version instead")));
226     LIBBINDER_EXPORTED status_t writeFloatVector(const std::vector<float>& val);
227     LIBBINDER_EXPORTED status_t writeDoubleVector(const std::optional<std::vector<double>>& val);
228     LIBBINDER_EXPORTED status_t writeDoubleVector(const std::unique_ptr<std::vector<double>>& val)
229             __attribute__((deprecated("use std::optional version instead")));
230     LIBBINDER_EXPORTED status_t writeDoubleVector(const std::vector<double>& val);
231     LIBBINDER_EXPORTED status_t writeBoolVector(const std::optional<std::vector<bool>>& val);
232     LIBBINDER_EXPORTED status_t writeBoolVector(const std::unique_ptr<std::vector<bool>>& val)
233             __attribute__((deprecated("use std::optional version instead")));
234     LIBBINDER_EXPORTED status_t writeBoolVector(const std::vector<bool>& val);
235     LIBBINDER_EXPORTED status_t writeCharVector(const std::optional<std::vector<char16_t>>& val);
236     LIBBINDER_EXPORTED status_t writeCharVector(const std::unique_ptr<std::vector<char16_t>>& val)
237             __attribute__((deprecated("use std::optional version instead")));
238     LIBBINDER_EXPORTED status_t writeCharVector(const std::vector<char16_t>& val);
239     LIBBINDER_EXPORTED status_t
240     writeString16Vector(const std::optional<std::vector<std::optional<String16>>>& val);
241     LIBBINDER_EXPORTED status_t
242     writeString16Vector(const std::unique_ptr<std::vector<std::unique_ptr<String16>>>& val)
243             __attribute__((deprecated("use std::optional version instead")));
244     LIBBINDER_EXPORTED status_t writeString16Vector(const std::vector<String16>& val);
245     LIBBINDER_EXPORTED status_t
246     writeUtf8VectorAsUtf16Vector(const std::optional<std::vector<std::optional<std::string>>>& val);
247     LIBBINDER_EXPORTED status_t writeUtf8VectorAsUtf16Vector(
248             const std::unique_ptr<std::vector<std::unique_ptr<std::string>>>& val)
249             __attribute__((deprecated("use std::optional version instead")));
250     LIBBINDER_EXPORTED status_t writeUtf8VectorAsUtf16Vector(const std::vector<std::string>& val);
251 
252     LIBBINDER_EXPORTED status_t
253     writeStrongBinderVector(const std::optional<std::vector<sp<IBinder>>>& val);
254     LIBBINDER_EXPORTED status_t
255     writeStrongBinderVector(const std::unique_ptr<std::vector<sp<IBinder>>>& val)
256             __attribute__((deprecated("use std::optional version instead")));
257     LIBBINDER_EXPORTED status_t writeStrongBinderVector(const std::vector<sp<IBinder>>& val);
258 
259     // Write an IInterface or a vector of IInterface's
260     template <typename T,
261               std::enable_if_t<std::is_base_of_v<::android::IInterface, T>, bool> = true>
writeStrongBinder(const sp<T> & val)262     status_t writeStrongBinder(const sp<T>& val) {
263         return writeStrongBinder(T::asBinder(val));
264     }
265     template <typename T,
266               std::enable_if_t<std::is_base_of_v<::android::IInterface, T>, bool> = true>
writeStrongBinderVector(const std::vector<sp<T>> & val)267     status_t writeStrongBinderVector(const std::vector<sp<T>>& val) {
268         return writeData(val);
269     }
270     template <typename T,
271               std::enable_if_t<std::is_base_of_v<::android::IInterface, T>, bool> = true>
writeStrongBinderVector(const std::optional<std::vector<sp<T>>> & val)272     status_t writeStrongBinderVector(const std::optional<std::vector<sp<T>>>& val) {
273         return writeData(val);
274     }
275 
276     template <typename T, size_t N>
writeFixedArray(const std::array<T,N> & val)277     status_t writeFixedArray(const std::array<T, N>& val) {
278         return writeData(val);
279     }
280     template <typename T, size_t N>
writeFixedArray(const std::optional<std::array<T,N>> & val)281     status_t writeFixedArray(const std::optional<std::array<T, N>>& val) {
282         return writeData(val);
283     }
284 
285     // Write an Enum vector with underlying type int8_t.
286     // Does not use padding; each byte is contiguous.
287     template<typename T, std::enable_if_t<std::is_enum_v<T> && std::is_same_v<typename std::underlying_type_t<T>,int8_t>, bool> = 0>
writeEnumVector(const std::vector<T> & val)288     status_t            writeEnumVector(const std::vector<T>& val)
289             { return writeData(val); }
290     template<typename T, std::enable_if_t<std::is_enum_v<T> && std::is_same_v<typename std::underlying_type_t<T>,int8_t>, bool> = 0>
writeEnumVector(const std::optional<std::vector<T>> & val)291     status_t            writeEnumVector(const std::optional<std::vector<T>>& val)
292             { return writeData(val); }
293     template<typename T, std::enable_if_t<std::is_enum_v<T> && std::is_same_v<typename std::underlying_type_t<T>,int8_t>, bool> = 0>
294     [[deprecated("use std::optional version instead")]] //
writeEnumVector(const std::unique_ptr<std::vector<T>> & val)295     status_t            writeEnumVector(const std::unique_ptr<std::vector<T>>& val)
296             { return writeData(val); }
297     // Write an Enum vector with underlying type != int8_t.
298     template<typename T, std::enable_if_t<std::is_enum_v<T> && !std::is_same_v<typename std::underlying_type_t<T>,int8_t>, bool> = 0>
writeEnumVector(const std::vector<T> & val)299     status_t            writeEnumVector(const std::vector<T>& val)
300             { return writeData(val); }
301     template<typename T, std::enable_if_t<std::is_enum_v<T> && !std::is_same_v<typename std::underlying_type_t<T>,int8_t>, bool> = 0>
writeEnumVector(const std::optional<std::vector<T>> & val)302     status_t            writeEnumVector(const std::optional<std::vector<T>>& val)
303             { return writeData(val); }
304     template<typename T, std::enable_if_t<std::is_enum_v<T> && !std::is_same_v<typename std::underlying_type_t<T>,int8_t>, bool> = 0>
305     [[deprecated("use std::optional version instead")]] //
writeEnumVector(const std::unique_ptr<std::vector<T>> & val)306     status_t            writeEnumVector(const std::unique_ptr<std::vector<T>>& val)
307             { return writeData(val); }
308 
309     template<typename T>
writeParcelableVector(const std::optional<std::vector<std::optional<T>>> & val)310     status_t            writeParcelableVector(const std::optional<std::vector<std::optional<T>>>& val)
311             { return writeData(val); }
312     template<typename T>
313     [[deprecated("use std::optional version instead")]] //
writeParcelableVector(const std::unique_ptr<std::vector<std::unique_ptr<T>>> & val)314     status_t            writeParcelableVector(const std::unique_ptr<std::vector<std::unique_ptr<T>>>& val)
315             { return writeData(val); }
316     template<typename T>
317     [[deprecated("use std::optional version instead")]] //
writeParcelableVector(const std::shared_ptr<std::vector<std::unique_ptr<T>>> & val)318     status_t            writeParcelableVector(const std::shared_ptr<std::vector<std::unique_ptr<T>>>& val)
319             { return writeData(val); }
320     template<typename T>
writeParcelableVector(const std::shared_ptr<std::vector<std::optional<T>>> & val)321     status_t            writeParcelableVector(const std::shared_ptr<std::vector<std::optional<T>>>& val)
322             { return writeData(val); }
323     template<typename T>
writeParcelableVector(const std::vector<T> & val)324     status_t            writeParcelableVector(const std::vector<T>& val)
325             { return writeData(val); }
326 
327     template<typename T>
writeNullableParcelable(const std::optional<T> & parcelable)328     status_t            writeNullableParcelable(const std::optional<T>& parcelable)
329             { return writeData(parcelable); }
330     template <typename T>
writeNullableParcelable(const std::unique_ptr<T> & parcelable)331     status_t writeNullableParcelable(const std::unique_ptr<T>& parcelable) {
332         return writeData(parcelable);
333     }
334 
335     LIBBINDER_EXPORTED status_t writeParcelable(const Parcelable& parcelable);
336 
337     template<typename T>
338     status_t            write(const Flattenable<T>& val);
339 
340     template<typename T>
341     status_t            write(const LightFlattenable<T>& val);
342 
343     template<typename T>
344     status_t            writeVectorSize(const std::vector<T>& val);
345     template<typename T>
346     status_t            writeVectorSize(const std::optional<std::vector<T>>& val);
347     template<typename T>
348     status_t            writeVectorSize(const std::unique_ptr<std::vector<T>>& val) __attribute__((deprecated("use std::optional version instead")));
349 
350 #ifndef BINDER_DISABLE_NATIVE_HANDLE
351     // Place a native_handle into the parcel (the native_handle's file-
352     // descriptors are dup'ed, so it is safe to delete the native_handle
353     // when this function returns).
354     // Doesn't take ownership of the native_handle.
355     LIBBINDER_EXPORTED status_t writeNativeHandle(const native_handle* handle);
356 #endif
357 
358     // Place a file descriptor into the parcel.  The given fd must remain
359     // valid for the lifetime of the parcel.
360     // The Parcel does not take ownership of the given fd unless you ask it to.
361     LIBBINDER_EXPORTED status_t writeFileDescriptor(int fd, bool takeOwnership = false);
362 
363     // Place a file descriptor into the parcel.  A dup of the fd is made, which
364     // will be closed once the parcel is destroyed.
365     LIBBINDER_EXPORTED status_t writeDupFileDescriptor(int fd);
366 
367     // Place a Java "parcel file descriptor" into the parcel.  The given fd must remain
368     // valid for the lifetime of the parcel.
369     // The Parcel does not take ownership of the given fd unless you ask it to.
370     LIBBINDER_EXPORTED status_t writeParcelFileDescriptor(int fd, bool takeOwnership = false);
371 
372     // Place a Java "parcel file descriptor" into the parcel.  A dup of the fd is made, which will
373     // be closed once the parcel is destroyed.
374     LIBBINDER_EXPORTED status_t writeDupParcelFileDescriptor(int fd);
375 
376     // Place a file descriptor into the parcel.  This will not affect the
377     // semantics of the smart file descriptor. A new descriptor will be
378     // created, and will be closed when the parcel is destroyed.
379     LIBBINDER_EXPORTED status_t writeUniqueFileDescriptor(const binder::unique_fd& fd);
380 
381     // Place a vector of file desciptors into the parcel. Each descriptor is
382     // dup'd as in writeDupFileDescriptor
383     LIBBINDER_EXPORTED status_t
384     writeUniqueFileDescriptorVector(const std::optional<std::vector<binder::unique_fd>>& val);
385     LIBBINDER_EXPORTED status_t
386     writeUniqueFileDescriptorVector(const std::unique_ptr<std::vector<binder::unique_fd>>& val)
387             __attribute__((deprecated("use std::optional version instead")));
388     LIBBINDER_EXPORTED status_t
389     writeUniqueFileDescriptorVector(const std::vector<binder::unique_fd>& val);
390 
391     // Writes a blob to the parcel.
392     // If the blob is small, then it is stored in-place, otherwise it is
393     // transferred by way of an anonymous shared memory region.  Prefer sending
394     // immutable blobs if possible since they may be subsequently transferred between
395     // processes without further copying whereas mutable blobs always need to be copied.
396     // The caller should call release() on the blob after writing its contents.
397     LIBBINDER_EXPORTED status_t writeBlob(size_t len, bool mutableCopy, WritableBlob* outBlob);
398 
399     // Write an existing immutable blob file descriptor to the parcel.
400     // This allows the client to send the same blob to multiple processes
401     // as long as it keeps a dup of the blob file descriptor handy for later.
402     LIBBINDER_EXPORTED status_t writeDupImmutableBlobFileDescriptor(int fd);
403 
404     LIBBINDER_EXPORTED status_t writeObject(const flat_binder_object& val, bool nullMetaData);
405 
406     // Like Parcel.java's writeNoException().  Just writes a zero int32.
407     // Currently the native implementation doesn't do any of the StrictMode
408     // stack gathering and serialization that the Java implementation does.
409     LIBBINDER_EXPORTED status_t writeNoException();
410 
411     LIBBINDER_EXPORTED status_t read(void* outData, size_t len) const;
412     LIBBINDER_EXPORTED const void* readInplace(size_t len) const;
413     LIBBINDER_EXPORTED int32_t readInt32() const;
414     LIBBINDER_EXPORTED status_t readInt32(int32_t* pArg) const;
415     LIBBINDER_EXPORTED uint32_t readUint32() const;
416     LIBBINDER_EXPORTED status_t readUint32(uint32_t* pArg) const;
417     LIBBINDER_EXPORTED int64_t readInt64() const;
418     LIBBINDER_EXPORTED status_t readInt64(int64_t* pArg) const;
419     LIBBINDER_EXPORTED uint64_t readUint64() const;
420     LIBBINDER_EXPORTED status_t readUint64(uint64_t* pArg) const;
421     LIBBINDER_EXPORTED float readFloat() const;
422     LIBBINDER_EXPORTED status_t readFloat(float* pArg) const;
423     LIBBINDER_EXPORTED double readDouble() const;
424     LIBBINDER_EXPORTED status_t readDouble(double* pArg) const;
425     LIBBINDER_EXPORTED bool readBool() const;
426     LIBBINDER_EXPORTED status_t readBool(bool* pArg) const;
427     LIBBINDER_EXPORTED char16_t readChar() const;
428     LIBBINDER_EXPORTED status_t readChar(char16_t* pArg) const;
429     LIBBINDER_EXPORTED int8_t readByte() const;
430     LIBBINDER_EXPORTED status_t readByte(int8_t* pArg) const;
431 
432     // Read a UTF16 encoded string, convert to UTF8
433     LIBBINDER_EXPORTED status_t readUtf8FromUtf16(std::string* str) const;
434     LIBBINDER_EXPORTED status_t readUtf8FromUtf16(std::optional<std::string>* str) const;
435     LIBBINDER_EXPORTED status_t readUtf8FromUtf16(std::unique_ptr<std::string>* str) const
436             __attribute__((deprecated("use std::optional version instead")));
437 
438     LIBBINDER_EXPORTED const char* readCString() const
439             __attribute__((deprecated("use AIDL, use readString*")));
440     LIBBINDER_EXPORTED String8 readString8() const;
441     LIBBINDER_EXPORTED status_t readString8(String8* pArg) const;
442     LIBBINDER_EXPORTED const char* readString8Inplace(size_t* outLen) const;
443     LIBBINDER_EXPORTED String16 readString16() const;
444     LIBBINDER_EXPORTED status_t readString16(String16* pArg) const;
445     LIBBINDER_EXPORTED status_t readString16(std::optional<String16>* pArg) const;
446     LIBBINDER_EXPORTED status_t readString16(std::unique_ptr<String16>* pArg) const
447             __attribute__((deprecated("use std::optional version instead")));
448     LIBBINDER_EXPORTED const char16_t* readString16Inplace(size_t* outLen) const;
449     LIBBINDER_EXPORTED sp<IBinder> readStrongBinder() const;
450     LIBBINDER_EXPORTED status_t readStrongBinder(sp<IBinder>* val) const;
451     LIBBINDER_EXPORTED status_t readNullableStrongBinder(sp<IBinder>* val) const;
452 
453     // Read an Enum vector with underlying type int8_t.
454     // Does not use padding; each byte is contiguous.
455     template<typename T, std::enable_if_t<std::is_enum_v<T> && std::is_same_v<typename std::underlying_type_t<T>,int8_t>, bool> = 0>
readEnumVector(std::vector<T> * val)456     status_t            readEnumVector(std::vector<T>* val) const
457             { return readData(val); }
458     template<typename T, std::enable_if_t<std::is_enum_v<T> && std::is_same_v<typename std::underlying_type_t<T>,int8_t>, bool> = 0>
459     [[deprecated("use std::optional version instead")]] //
readEnumVector(std::unique_ptr<std::vector<T>> * val)460     status_t            readEnumVector(std::unique_ptr<std::vector<T>>* val) const
461             { return readData(val); }
462     template<typename T, std::enable_if_t<std::is_enum_v<T> && std::is_same_v<typename std::underlying_type_t<T>,int8_t>, bool> = 0>
readEnumVector(std::optional<std::vector<T>> * val)463     status_t            readEnumVector(std::optional<std::vector<T>>* val) const
464             { return readData(val); }
465     // Read an Enum vector with underlying type != int8_t.
466     template<typename T, std::enable_if_t<std::is_enum_v<T> && !std::is_same_v<typename std::underlying_type_t<T>,int8_t>, bool> = 0>
readEnumVector(std::vector<T> * val)467     status_t            readEnumVector(std::vector<T>* val) const
468             { return readData(val); }
469     template<typename T, std::enable_if_t<std::is_enum_v<T> && !std::is_same_v<typename std::underlying_type_t<T>,int8_t>, bool> = 0>
470     [[deprecated("use std::optional version instead")]] //
readEnumVector(std::unique_ptr<std::vector<T>> * val)471     status_t            readEnumVector(std::unique_ptr<std::vector<T>>* val) const
472             { return readData(val); }
473     template<typename T, std::enable_if_t<std::is_enum_v<T> && !std::is_same_v<typename std::underlying_type_t<T>,int8_t>, bool> = 0>
readEnumVector(std::optional<std::vector<T>> * val)474     status_t            readEnumVector(std::optional<std::vector<T>>* val) const
475             { return readData(val); }
476 
477     template<typename T>
readParcelableVector(std::optional<std::vector<std::optional<T>>> * val)478     status_t            readParcelableVector(
479                             std::optional<std::vector<std::optional<T>>>* val) const
480             { return readData(val); }
481     template<typename T>
482     [[deprecated("use std::optional version instead")]] //
readParcelableVector(std::unique_ptr<std::vector<std::unique_ptr<T>>> * val)483     status_t            readParcelableVector(
484                             std::unique_ptr<std::vector<std::unique_ptr<T>>>* val) const
485             { return readData(val); }
486     template<typename T>
readParcelableVector(std::vector<T> * val)487     status_t            readParcelableVector(std::vector<T>* val) const
488             { return readData(val); }
489 
490     LIBBINDER_EXPORTED status_t readParcelable(Parcelable* parcelable) const;
491 
492     template<typename T>
readParcelable(std::optional<T> * parcelable)493     status_t            readParcelable(std::optional<T>* parcelable) const
494             { return readData(parcelable); }
495     template <typename T>
readParcelable(std::unique_ptr<T> * parcelable)496     status_t readParcelable(std::unique_ptr<T>* parcelable) const {
497         return readData(parcelable);
498     }
499 
500     // If strong binder would be nullptr, readStrongBinder() returns an error.
501     // TODO: T must be derived from IInterface, fix for clarity.
502     template<typename T>
503     status_t            readStrongBinder(sp<T>* val) const;
504 
505     template<typename T>
506     status_t            readNullableStrongBinder(sp<T>* val) const;
507 
508     LIBBINDER_EXPORTED status_t
509     readStrongBinderVector(std::optional<std::vector<sp<IBinder>>>* val) const;
510     LIBBINDER_EXPORTED status_t
511     readStrongBinderVector(std::unique_ptr<std::vector<sp<IBinder>>>* val) const
512             __attribute__((deprecated("use std::optional version instead")));
513     LIBBINDER_EXPORTED status_t readStrongBinderVector(std::vector<sp<IBinder>>* val) const;
514     template <typename T,
515               std::enable_if_t<std::is_base_of_v<::android::IInterface, T>, bool> = true>
readStrongBinderVector(std::vector<sp<T>> * val)516     status_t readStrongBinderVector(std::vector<sp<T>>* val) const {
517         return readData(val);
518     }
519     template <typename T,
520               std::enable_if_t<std::is_base_of_v<::android::IInterface, T>, bool> = true>
readStrongBinderVector(std::optional<std::vector<sp<T>>> * val)521     status_t readStrongBinderVector(std::optional<std::vector<sp<T>>>* val) const {
522         return readData(val);
523     }
524 
525     LIBBINDER_EXPORTED status_t readByteVector(std::optional<std::vector<int8_t>>* val) const;
526     LIBBINDER_EXPORTED status_t readByteVector(std::unique_ptr<std::vector<int8_t>>* val) const
527             __attribute__((deprecated("use std::optional version instead")));
528     LIBBINDER_EXPORTED status_t readByteVector(std::vector<int8_t>* val) const;
529     LIBBINDER_EXPORTED status_t readByteVector(std::optional<std::vector<uint8_t>>* val) const;
530     LIBBINDER_EXPORTED status_t readByteVector(std::unique_ptr<std::vector<uint8_t>>* val) const
531             __attribute__((deprecated("use std::optional version instead")));
532     LIBBINDER_EXPORTED status_t readByteVector(std::vector<uint8_t>* val) const;
533     LIBBINDER_EXPORTED status_t readInt32Vector(std::optional<std::vector<int32_t>>* val) const;
534     LIBBINDER_EXPORTED status_t readInt32Vector(std::unique_ptr<std::vector<int32_t>>* val) const
535             __attribute__((deprecated("use std::optional version instead")));
536     LIBBINDER_EXPORTED status_t readInt32Vector(std::vector<int32_t>* val) const;
537     LIBBINDER_EXPORTED status_t readInt64Vector(std::optional<std::vector<int64_t>>* val) const;
538     LIBBINDER_EXPORTED status_t readInt64Vector(std::unique_ptr<std::vector<int64_t>>* val) const
539             __attribute__((deprecated("use std::optional version instead")));
540     LIBBINDER_EXPORTED status_t readInt64Vector(std::vector<int64_t>* val) const;
541     LIBBINDER_EXPORTED status_t readUint64Vector(std::optional<std::vector<uint64_t>>* val) const;
542     LIBBINDER_EXPORTED status_t readUint64Vector(std::unique_ptr<std::vector<uint64_t>>* val) const
543             __attribute__((deprecated("use std::optional version instead")));
544     LIBBINDER_EXPORTED status_t readUint64Vector(std::vector<uint64_t>* val) const;
545     LIBBINDER_EXPORTED status_t readFloatVector(std::optional<std::vector<float>>* val) const;
546     LIBBINDER_EXPORTED status_t readFloatVector(std::unique_ptr<std::vector<float>>* val) const
547             __attribute__((deprecated("use std::optional version instead")));
548     LIBBINDER_EXPORTED status_t readFloatVector(std::vector<float>* val) const;
549     LIBBINDER_EXPORTED status_t readDoubleVector(std::optional<std::vector<double>>* val) const;
550     LIBBINDER_EXPORTED status_t readDoubleVector(std::unique_ptr<std::vector<double>>* val) const
551             __attribute__((deprecated("use std::optional version instead")));
552     LIBBINDER_EXPORTED status_t readDoubleVector(std::vector<double>* val) const;
553     LIBBINDER_EXPORTED status_t readBoolVector(std::optional<std::vector<bool>>* val) const;
554     LIBBINDER_EXPORTED status_t readBoolVector(std::unique_ptr<std::vector<bool>>* val) const
555             __attribute__((deprecated("use std::optional version instead")));
556     LIBBINDER_EXPORTED status_t readBoolVector(std::vector<bool>* val) const;
557     LIBBINDER_EXPORTED status_t readCharVector(std::optional<std::vector<char16_t>>* val) const;
558     LIBBINDER_EXPORTED status_t readCharVector(std::unique_ptr<std::vector<char16_t>>* val) const
559             __attribute__((deprecated("use std::optional version instead")));
560     LIBBINDER_EXPORTED status_t readCharVector(std::vector<char16_t>* val) const;
561     LIBBINDER_EXPORTED status_t
562     readString16Vector(std::optional<std::vector<std::optional<String16>>>* val) const;
563     LIBBINDER_EXPORTED status_t
564     readString16Vector(std::unique_ptr<std::vector<std::unique_ptr<String16>>>* val) const
565             __attribute__((deprecated("use std::optional version instead")));
566     LIBBINDER_EXPORTED status_t readString16Vector(std::vector<String16>* val) const;
567     LIBBINDER_EXPORTED status_t readUtf8VectorFromUtf16Vector(
568             std::optional<std::vector<std::optional<std::string>>>* val) const;
569     LIBBINDER_EXPORTED status_t readUtf8VectorFromUtf16Vector(
570             std::unique_ptr<std::vector<std::unique_ptr<std::string>>>* val) const
571             __attribute__((deprecated("use std::optional version instead")));
572     LIBBINDER_EXPORTED status_t readUtf8VectorFromUtf16Vector(std::vector<std::string>* val) const;
573 
574     template <typename T, size_t N>
readFixedArray(std::array<T,N> * val)575     status_t readFixedArray(std::array<T, N>* val) const {
576         return readData(val);
577     }
578     template <typename T, size_t N>
readFixedArray(std::optional<std::array<T,N>> * val)579     status_t readFixedArray(std::optional<std::array<T, N>>* val) const {
580         return readData(val);
581     }
582 
583     template<typename T>
584     status_t            read(Flattenable<T>& val) const;
585 
586     template<typename T>
587     status_t            read(LightFlattenable<T>& val) const;
588 
589     // resizeOutVector is used to resize AIDL out vector parameters.
590     template<typename T>
591     status_t            resizeOutVector(std::vector<T>* val) const;
592     template<typename T>
593     status_t            resizeOutVector(std::optional<std::vector<T>>* val) const;
594     template<typename T>
595     status_t            resizeOutVector(std::unique_ptr<std::vector<T>>* val) const __attribute__((deprecated("use std::optional version instead")));
596 
597     // Like Parcel.java's readExceptionCode().  Reads the first int32
598     // off of a Parcel's header, returning 0 or the negative error
599     // code on exceptions, but also deals with skipping over rich
600     // response headers.  Callers should use this to read & parse the
601     // response headers rather than doing it by hand.
602     LIBBINDER_EXPORTED int32_t readExceptionCode() const;
603 
604 #ifndef BINDER_DISABLE_NATIVE_HANDLE
605     // Retrieve native_handle from the parcel. This returns a copy of the
606     // parcel's native_handle (the caller takes ownership). The caller
607     // must free the native_handle with native_handle_close() and
608     // native_handle_delete().
609     LIBBINDER_EXPORTED native_handle* readNativeHandle() const;
610 #endif
611 
612     // Retrieve a file descriptor from the parcel.  This returns the raw fd
613     // in the parcel, which you do not own -- use dup() to get your own copy.
614     LIBBINDER_EXPORTED int readFileDescriptor() const;
615 
616     // Retrieve a Java "parcel file descriptor" from the parcel.  This returns the raw fd
617     // in the parcel, which you do not own -- use dup() to get your own copy.
618     LIBBINDER_EXPORTED int readParcelFileDescriptor() const;
619 
620     // Retrieve a smart file descriptor from the parcel.
621     LIBBINDER_EXPORTED status_t readUniqueFileDescriptor(binder::unique_fd* val) const;
622 
623     // Retrieve a Java "parcel file descriptor" from the parcel.
624     LIBBINDER_EXPORTED status_t readUniqueParcelFileDescriptor(binder::unique_fd* val) const;
625 
626     // Retrieve a vector of smart file descriptors from the parcel.
627     LIBBINDER_EXPORTED status_t
628     readUniqueFileDescriptorVector(std::optional<std::vector<binder::unique_fd>>* val) const;
629     LIBBINDER_EXPORTED status_t
630     readUniqueFileDescriptorVector(std::unique_ptr<std::vector<binder::unique_fd>>* val) const
631             __attribute__((deprecated("use std::optional version instead")));
632     LIBBINDER_EXPORTED status_t
633     readUniqueFileDescriptorVector(std::vector<binder::unique_fd>* val) const;
634 
635     // Reads a blob from the parcel.
636     // The caller should call release() on the blob after reading its contents.
637     LIBBINDER_EXPORTED status_t readBlob(size_t len, ReadableBlob* outBlob) const;
638 
639     LIBBINDER_EXPORTED const flat_binder_object* readObject(bool nullMetaData) const;
640 
641     // Debugging: get metrics on current allocations.
642     LIBBINDER_EXPORTED static size_t getGlobalAllocSize();
643     LIBBINDER_EXPORTED static size_t getGlobalAllocCount();
644 
645     LIBBINDER_EXPORTED bool replaceCallingWorkSourceUid(uid_t uid);
646     // Returns the work source provided by the caller. This can only be trusted for trusted calling
647     // uid.
648     LIBBINDER_EXPORTED uid_t readCallingWorkSourceUid() const;
649 
650     LIBBINDER_EXPORTED void print(std::ostream& to, uint32_t flags = 0) const;
651 
652 private:
653     // Close all file descriptors in the parcel at object positions >= newObjectsSize.
654     void closeFileDescriptors(size_t newObjectsSize);
655 
656     // `objects` and `objectsSize` always 0 for RPC Parcels.
657     typedef void (*release_func)(const uint8_t* data, size_t dataSize, const binder_size_t* objects,
658                                  size_t objectsSize);
659 
660     uintptr_t           ipcData() const;
661     size_t              ipcDataSize() const;
662     uintptr_t           ipcObjects() const;
663     size_t              ipcObjectsCount() const;
664     void ipcSetDataReference(const uint8_t* data, size_t dataSize, const binder_size_t* objects,
665                              size_t objectsCount, release_func relFunc);
666     // Takes ownership even when an error is returned.
667     status_t rpcSetDataReference(
668             const sp<RpcSession>& session, const uint8_t* data, size_t dataSize,
669             const uint32_t* objectTable, size_t objectTableSize,
670             std::vector<std::variant<binder::unique_fd, binder::borrowed_fd>>&& ancillaryFds,
671             release_func relFunc);
672 
673     status_t            finishWrite(size_t len);
674     void                releaseObjects();
675     void                acquireObjects();
676     status_t            growData(size_t len);
677     // Clear the Parcel and set the capacity to `desired`.
678     // Doesn't reset the RPC session association.
679     status_t            restartWrite(size_t desired);
680     // Set the capacity to `desired`, truncating the Parcel if necessary.
681     status_t            continueWrite(size_t desired);
682     status_t truncateRpcObjects(size_t newObjectsSize);
683     status_t            writePointer(uintptr_t val);
684     status_t            readPointer(uintptr_t *pArg) const;
685     uintptr_t           readPointer() const;
686     void                freeDataNoInit();
687     void                initState();
688     void                scanForFds() const;
689     status_t scanForBinders(bool* result) const;
690 
691     status_t            validateReadData(size_t len) const;
692 
693     void                updateWorkSourceRequestHeaderPosition() const;
694 
695     status_t            finishFlattenBinder(const sp<IBinder>& binder);
696     status_t            finishUnflattenBinder(const sp<IBinder>& binder, sp<IBinder>* out) const;
697     status_t            flattenBinder(const sp<IBinder>& binder);
698     status_t            unflattenBinder(sp<IBinder>* out) const;
699 
700     LIBBINDER_EXPORTED status_t readOutVectorSizeWithCheck(size_t elmSize, int32_t* size) const;
701 
702     template<class T>
703     status_t            readAligned(T *pArg) const;
704 
705     template<class T>   T readAligned() const;
706 
707     template<class T>
708     status_t            writeAligned(T val);
709 
710     status_t            writeRawNullableParcelable(const Parcelable*
711                                                    parcelable);
712 
713     //-----------------------------------------------------------------------------
714     // Generic type read and write methods for Parcel:
715     //
716     // readData(T *value) will read a value from the Parcel.
717     // writeData(const T& value) will write a value to the Parcel.
718     //
719     // Our approach to parceling is based on two overloaded functions
720     // readData() and writeData() that generate parceling code for an
721     // object automatically based on its type. The code from templates are generated at
722     // compile time (if constexpr), and decomposes an object through a call graph matching
723     // recursive descent of the template typename.
724     //
725     // This approach unifies handling of complex objects,
726     // resulting in fewer lines of code, greater consistency,
727     // extensibility to nested types, efficiency (decisions made at compile time),
728     // and better code maintainability and optimization.
729     //
730     // Design decision: Incorporate the read and write code into Parcel rather than
731     // as a non-intrusive serializer that emits a byte stream, as we have
732     // active objects, alignment, legacy code, and historical idiosyncrasies.
733     //
734     // --- Overview
735     //
736     // Parceling is a way of serializing objects into a sequence of bytes for communication
737     // between processes, as part of marshaling data for remote procedure calls.
738     //
739     // The Parcel instance contains objects serialized as bytes, such as the following:
740     //
741     // 1) Ordinary primitive data such as int, float.
742     // 2) Established structured data such as String16, std::string.
743     // 3) Parcelables, which are C++ objects that derive from Parcelable (and thus have a
744     //    readFromParcel and writeToParcel method).  (Similar for Java)
745     // 4) A std::vector<> of such data.
746     // 5) Nullable objects contained in std::optional, std::unique_ptr, or std::shared_ptr.
747     //
748     // And active objects from the Android ecosystem such as:
749     // 6) File descriptors, unique_fd (kernel object handles)
750     // 7) Binder objects, sp<IBinder> (active Android RPC handles)
751     //
752     // Objects from (1) through (5) serialize into the mData buffer.
753     // Active objects (6) and (7) serialize into both mData and mObjects buffers.
754     //
755     // --- Data layout details
756     //
757     // Data is read or written to the parcel by recursively decomposing the type of the parameter
758     // type T through readData() and writeData() methods.
759     //
760     // We focus on writeData() here in our explanation of the data layout.
761     //
762     // 1) Alignment
763     // Implementation detail: Regardless of the parameter type, writeData() calls are designed
764     // to finish at a multiple of 4 bytes, the default alignment of the Parcel.
765     //
766     // Writes of single uint8_t, int8_t, enums based on types of size 1, char16_t, etc
767     // will result in 4 bytes being written.  The data is widened to int32 and then written;
768     // hence the position of the nonzero bytes depend on the native endianness of the CPU.
769     //
770     // Writes of primitive values with 8 byte size, double, int64_t, uint64_t,
771     // are stored with 4 byte alignment.  The ARM and x86/x64 permit unaligned reads
772     // and writes (albeit with potential latency/throughput penalty) which may or may
773     // not be observable unless the process is IO bound.
774     //
775     // 2) Parcelables
776     // Parcelables are detected by the type's base class, and implemented through calling
777     // into the Parcelable type's readFromParcel() or writeToParcel() methods.
778     // Historically, due to null object detection, a (int32_t) 1 is prepended to the data written.
779     // Parcelables must have a default constructor (i.e. one that takes no arguments).
780     //
781     // 3) Arrays
782     // Arrays of uint8_t and int8_t, and enums based on size 1 are written as
783     // a contiguous packed byte stream.  Hidden zero padding is applied at the end of the byte
784     // stream to make a multiple of 4 bytes (and prevent info leakage when writing).
785     //
786     // All other array writes can be conceptually thought of as recursively calling
787     // writeData on the individual elements (though may be implemented differently for speed).
788     // As discussed in (1), alignment rules are therefore applied for each element
789     // write (not as an aggregate whole), so the wire representation of data can be
790     // substantially larger.
791     //
792     // Historical Note:
793     // Because of element-wise alignment, CharVector and BoolVector are expanded
794     // element-wise into integers even though they could have been optimized to be packed
795     // just like uint8_t, int8_t (size 1 data).
796     //
797     // 3.1) Arrays accessed by the std::vector type.  This is the default for AIDL.
798     //
799     // 4) Nullables
800     // std::optional, std::unique_ptr, std::shared_ptr are all parceled identically
801     // (i.e. result in identical byte layout).
802     // The target of the std::optional, std::unique_ptr, or std::shared_ptr
803     // can either be a std::vector, String16, std::string, or a Parcelable.
804     //
805     // Detection of null relies on peeking the first int32 data and checking if the
806     // the peeked value is considered invalid for the object:
807     // (-1 for vectors, String16, std::string) (0 for Parcelables).  If the peeked value
808     // is invalid, then a null is returned.
809     //
810     // Application Note: When to use each nullable type:
811     //
812     // std::optional: Embeds the object T by value rather than creating a new instance
813     // by managed pointer as std::unique_ptr or std::shared_ptr.  This will save a malloc
814     // when creating an optional instance.
815     //
816     // Use of std::optionals by value can result in copies of the underlying value stored in it,
817     // so a std::move may be used to move in and move out (for example) a vector value into
818     // the std::optional or for the std::optional itself.
819     //
820     // std::unique_ptr, std::shared_ptr: These are preferred when the lifetime of the object is
821     // already managed by the application.  This reduces unnecessary copying of data
822     // especially when the calls are local in-proc (rather than via binder rpc).
823     //
824     // 5) StrongBinder (sp<IBinder>)
825     // StrongBinder objects are written regardless of null. When read, null StrongBinder values
826     // will be interpreted as UNKNOWN_ERROR if the type is a single argument <sp<T>>
827     // or in a vector argument <std::vector<sp<T>>. However, they will be read without an error
828     // if present in a std::optional, std::unique_ptr, or std::shared_ptr vector, e.g.
829     // <std::optional<std::vector<sp<T>>>.
830     //
831     // See AIDL annotation @Nullable, readStrongBinder(), and readNullableStrongBinder().
832     //
833     // Historical Note: writing a vector of StrongBinder objects <std::vector<sp<T>>
834     // containing a null will not cause an error. However reading such a vector will cause
835     // an error _and_ early termination of the read.
836 
837     //  --- Examples
838     //
839     // Using recursive parceling, we can parcel complex data types so long
840     // as they obey the rules described above.
841     //
842     // Example #1
843     // Parceling of a 3D vector
844     //
845     // std::vector<std::vector<std::vector<int32_t>>> v1 {
846     //     { {1}, {2, 3}, {4} },
847     //     {},
848     //     { {10}, {20}, {30, 40} },
849     // };
850     // Parcel p1;
851     // p1.writeData(v1);
852     // decltype(v1) v2;
853     // p1.setDataPosition(0);
854     // p1.readData(&v2);
855     // ASSERT_EQ(v1, v2);
856     //
857     // Example #2
858     // Parceling of mixed shared pointers
859     //
860     // Parcel p1;
861     // auto sp1 = std::make_shared<std::vector<std::shared_ptr<std::vector<int>>>>(3);
862     // (*sp1)[2] = std::make_shared<std::vector<int>>(3);
863     // (*(*sp1)[2])[2] = 2;
864     // p1.writeData(sp1);
865     // decltype(sp1) sp2;
866     // p1.setDataPosition(0);
867     // p1.readData(&sp2);
868     // ASSERT_EQ((*sp1)[0], (*sp2)[0]); // nullptr
869     // ASSERT_EQ((*sp1)[1], (*sp2)[1]); // nullptr
870     // ASSERT_EQ(*(*sp1)[2], *(*sp2)[2]); // { 0, 0, 2}
871 
872     //  --- Helper Methods
873     // TODO: move this to a utils header.
874     //
875     // Determine if a type is a specialization of a templated type
876     // Example: is_specialization_v<T, std::vector>
877 
878     template <typename Test, template <typename...> class Ref>
879     struct is_specialization : std::false_type {};
880 
881     template <template <typename...> class Ref, typename... Args>
882     struct is_specialization<Ref<Args...>, Ref>: std::true_type {};
883 
884     template <typename Test, template <typename...> class Ref>
885     static inline constexpr bool is_specialization_v = is_specialization<Test, Ref>::value;
886 
887     // Get the first template type from a container, the T from MyClass<T, ...>.
888     template<typename T> struct first_template_type;
889 
890     template <template <typename ...> class V, typename T, typename... Args>
891     struct first_template_type<V<T, Args...>> {
892         using type_t = T;
893     };
894 
895     template <typename T>
896     using first_template_type_t = typename first_template_type<T>::type_t;
897 
898     // For static assert(false) we need a template version to avoid early failure.
899     template <typename T>
900     static inline constexpr bool dependent_false_v = false;
901 
902     // primitive types that we consider packed and trivially copyable as an array
903     template <typename T>
904     static inline constexpr bool is_pointer_equivalent_array_v =
905             std::is_same_v<T, int8_t>
906             || std::is_same_v<T, uint8_t>
907             // We could support int16_t and uint16_t, but those aren't currently AIDL types.
908             || std::is_same_v<T, int32_t>
909             || std::is_same_v<T, uint32_t>
910             || std::is_same_v<T, float>
911             // are unaligned reads and write support is assumed.
912             || std::is_same_v<T, uint64_t>
913             || std::is_same_v<T, int64_t>
914             || std::is_same_v<T, double>
915             || (std::is_enum_v<T> && (sizeof(T) == 1 || sizeof(T) == 4)); // size check not type
916 
917     // allowed "nullable" types
918     // These are nonintrusive containers std::optional, std::unique_ptr, std::shared_ptr.
919     template <typename T>
920     static inline constexpr bool is_parcel_nullable_type_v =
921             is_specialization_v<T, std::optional>
922             || is_specialization_v<T, std::unique_ptr>
923             || is_specialization_v<T, std::shared_ptr>;
924 
925     // Tells if T is a fixed-size array.
926     template <typename T>
927     struct is_fixed_array : std::false_type {};
928 
929     template <typename T, size_t N>
930     struct is_fixed_array<std::array<T, N>> : std::true_type {};
931 
932     template <typename T>
933     static inline constexpr bool is_fixed_array_v = is_fixed_array<T>::value;
934 
935     // special int32 value to indicate NonNull or Null parcelables
936     // This is fixed to be only 0 or 1 by contract, do not change.
937     static constexpr int32_t kNonNullParcelableFlag = 1;
938     static constexpr int32_t kNullParcelableFlag = 0;
939 
940     // special int32 size representing a null vector, when applicable in Nullable data.
941     // This fixed as -1 by contract, do not change.
942     static constexpr int32_t kNullVectorSize = -1;
943 
944     // --- readData and writeData methods.
945     // We choose a mixture of function and template overloads to improve code readability.
946     // TODO: Consider C++20 concepts when they become available.
947 
948     // writeData function overloads.
949     // Implementation detail: Function overloading improves code readability over
950     // template overloading, but prevents writeData<T> from being used for those types.
951 
952     status_t writeData(bool t) {
953         return writeBool(t);  // this writes as int32_t
954     }
955 
956     status_t writeData(int8_t t) {
957         return writeByte(t);  // this writes as int32_t
958     }
959 
960     status_t writeData(uint8_t t) {
961         return writeByte(static_cast<int8_t>(t));  // this writes as int32_t
962     }
963 
964     status_t writeData(char16_t t) {
965         return writeChar(t);  // this writes as int32_t
966     }
967 
968     status_t writeData(int32_t t) {
969         return writeInt32(t);
970     }
971 
972     status_t writeData(uint32_t t) {
973         return writeUint32(t);
974     }
975 
976     status_t writeData(int64_t t) {
977         return writeInt64(t);
978     }
979 
980     status_t writeData(uint64_t t) {
981         return writeUint64(t);
982     }
983 
984     status_t writeData(float t) {
985         return writeFloat(t);
986     }
987 
988     status_t writeData(double t) {
989         return writeDouble(t);
990     }
991 
992     status_t writeData(const String16& t) {
993         return writeString16(t);
994     }
995 
996     status_t writeData(const std::string& t) {
997         return writeUtf8AsUtf16(t);
998     }
999 
1000     status_t writeData(const binder::unique_fd& t) { return writeUniqueFileDescriptor(t); }
1001 
1002     status_t writeData(const Parcelable& t) {  // std::is_base_of_v<Parcelable, T>
1003         // implemented here. writeParcelable() calls this.
1004         status_t status = writeData(static_cast<int32_t>(kNonNullParcelableFlag));
1005         if (status != OK) return status;
1006         return t.writeToParcel(this);
1007     }
1008 
1009     // writeData<T> template overloads.
1010     // Written such that the first template type parameter is the complete type
1011     // of the first function parameter.
1012     template <typename T,
1013             typename std::enable_if_t<std::is_enum_v<T>, bool> = true>
1014     status_t writeData(const T& t) {
1015         // implemented here. writeEnum() calls this.
1016         using UT = std::underlying_type_t<T>;
1017         return writeData(static_cast<UT>(t)); // recurse
1018     }
1019 
1020     template <typename T,
1021             typename std::enable_if_t<is_specialization_v<T, sp>, bool> = true>
1022     status_t writeData(const T& t) {
1023         return writeStrongBinder(t);
1024     }
1025 
1026     // std::optional, std::unique_ptr, std::shared_ptr special case.
1027     template <typename CT,
1028             typename std::enable_if_t<is_parcel_nullable_type_v<CT>, bool> = true>
1029     status_t writeData(const CT& c) {
1030         using T = first_template_type_t<CT>;  // The T in CT == C<T, ...>
1031         if constexpr (is_specialization_v<T, std::vector>
1032                 || std::is_same_v<T, String16>
1033                 || std::is_same_v<T, std::string>) {
1034             if (!c) return writeData(static_cast<int32_t>(kNullVectorSize));
1035         } else if constexpr (std::is_base_of_v<Parcelable, T>) {
1036             if (!c) return writeData(static_cast<int32_t>(kNullParcelableFlag));
1037         } else if constexpr (is_fixed_array_v<T>) {
1038             if (!c) return writeData(static_cast<int32_t>(kNullVectorSize));
1039         } else /* constexpr */ { // could define this, but raise as error.
1040             static_assert(dependent_false_v<CT>);
1041         }
1042         return writeData(*c);
1043     }
1044 
1045     template <typename CT,
1046             typename std::enable_if_t<is_specialization_v<CT, std::vector>, bool> = true>
1047     status_t writeData(const CT& c) {
1048         using T = first_template_type_t<CT>;  // The T in CT == C<T, ...>
1049         if (c.size() > static_cast<size_t>(std::numeric_limits<int32_t>::max())) return BAD_VALUE;
1050         const auto size = static_cast<int32_t>(c.size());
1051         writeData(size);
1052         if constexpr (is_pointer_equivalent_array_v<T>) {
1053             constexpr size_t limit = std::numeric_limits<size_t>::max() / sizeof(T);
1054             if (c.size() > limit) return BAD_VALUE;
1055             // is_pointer_equivalent types do not have gaps which could leak info,
1056             // which is only a concern when writing through binder.
1057 
1058             // TODO: Padding of the write is suboptimal when the length of the
1059             // data is not a multiple of 4.  Consider improving the write() method.
1060             return write(c.data(), c.size() * sizeof(T));
1061         } else if constexpr (std::is_same_v<T, bool>
1062                 || std::is_same_v<T, char16_t>) {
1063             // reserve data space to write to
1064             auto data = reinterpret_cast<int32_t*>(writeInplace(c.size() * sizeof(int32_t)));
1065             if (data == nullptr) return BAD_VALUE;
1066             for (const auto t: c) {
1067                 *data++ = static_cast<int32_t>(t);
1068             }
1069         } else /* constexpr */ {
1070             for (const auto &t : c) {
1071                 const status_t status = writeData(t);
1072                 if (status != OK) return status;
1073             }
1074         }
1075         return OK;
1076     }
1077 
1078     template <typename T, size_t N>
1079     status_t writeData(const std::array<T, N>& val) {
1080         static_assert(N <= std::numeric_limits<int32_t>::max());
1081         status_t status = writeData(static_cast<int32_t>(N));
1082         if (status != OK) return status;
1083         if constexpr (is_pointer_equivalent_array_v<T>) {
1084             static_assert(N <= std::numeric_limits<size_t>::max() / sizeof(T));
1085             return write(val.data(), val.size() * sizeof(T));
1086         } else /* constexpr */ {
1087             for (const auto& t : val) {
1088                 status = writeData(t);
1089                 if (status != OK) return status;
1090             }
1091             return OK;
1092         }
1093     }
1094 
1095     // readData function overloads.
1096     // Implementation detail: Function overloading improves code readability over
1097     // template overloading, but prevents readData<T> from being used for those types.
1098 
1099     status_t readData(bool* t) const {
1100         return readBool(t);  // this reads as int32_t
1101     }
1102 
1103     status_t readData(int8_t* t) const {
1104         return readByte(t);  // this reads as int32_t
1105     }
1106 
1107     status_t readData(uint8_t* t) const {
1108         return readByte(reinterpret_cast<int8_t*>(t));  // NOTE: this reads as int32_t
1109     }
1110 
1111     status_t readData(char16_t* t) const {
1112         return readChar(t);  // this reads as int32_t
1113     }
1114 
1115     status_t readData(int32_t* t) const {
1116         return readInt32(t);
1117     }
1118 
1119     status_t readData(uint32_t* t) const {
1120         return readUint32(t);
1121     }
1122 
1123     status_t readData(int64_t* t) const {
1124         return readInt64(t);
1125     }
1126 
1127     status_t readData(uint64_t* t) const {
1128         return readUint64(t);
1129     }
1130 
1131     status_t readData(float* t) const {
1132         return readFloat(t);
1133     }
1134 
1135     status_t readData(double* t) const {
1136         return readDouble(t);
1137     }
1138 
1139     status_t readData(String16* t) const {
1140         return readString16(t);
1141     }
1142 
1143     status_t readData(std::string* t) const {
1144         return readUtf8FromUtf16(t);
1145     }
1146 
1147     status_t readData(binder::unique_fd* t) const { return readUniqueFileDescriptor(t); }
1148 
1149     status_t readData(Parcelable* t) const { // std::is_base_of_v<Parcelable, T>
1150         // implemented here. readParcelable() calls this.
1151         int32_t present;
1152         status_t status = readData(&present);
1153         if (status != OK) return status;
1154         if (present != kNonNullParcelableFlag) return UNEXPECTED_NULL;
1155         return t->readFromParcel(this);
1156     }
1157 
1158     // readData<T> template overloads.
1159     // Written such that the first template type parameter is the complete type
1160     // of the first function parameter.
1161 
1162     template <typename T,
1163             typename std::enable_if_t<std::is_enum_v<T>, bool> = true>
1164     status_t readData(T* t) const {
1165         // implemented here. readEnum() calls this.
1166         using UT = std::underlying_type_t<T>;
1167         return readData(reinterpret_cast<UT*>(t));
1168     }
1169 
1170     template <typename T,
1171             typename std::enable_if_t<is_specialization_v<T, sp>, bool> = true>
1172     status_t readData(T* t) const {
1173         return readStrongBinder(t);  // Note: on null, returns failure
1174     }
1175 
1176 
1177     template <typename CT,
1178             typename std::enable_if_t<is_parcel_nullable_type_v<CT>, bool> = true>
1179     status_t readData(CT* c) const {
1180         using T = first_template_type_t<CT>;  // The T in CT == C<T, ...>
1181         const size_t startPos = dataPosition();
1182         int32_t peek;
1183         status_t status = readData(&peek);
1184         if (status != OK) return status;
1185         if constexpr (is_specialization_v<T, std::vector> || is_fixed_array_v<T> ||
1186                       std::is_same_v<T, String16> || std::is_same_v<T, std::string>) {
1187             if (peek == kNullVectorSize) {
1188                 c->reset();
1189                 return OK;
1190             }
1191         } else if constexpr (std::is_base_of_v<Parcelable, T>) {
1192             if (peek == kNullParcelableFlag) {
1193                 c->reset();
1194                 return OK;
1195             }
1196         } else /* constexpr */ { // could define this, but raise as error.
1197             static_assert(dependent_false_v<CT>);
1198         }
1199         // create a new object.
1200         if constexpr (is_specialization_v<CT, std::optional>) {
1201             // Call default constructor explicitly
1202             // - Clang bug: https://bugs.llvm.org/show_bug.cgi?id=35748
1203             //   std::optional::emplace() doesn't work with nested types.
1204             c->emplace(T());
1205         } else /* constexpr */ {
1206             T* const t = new (std::nothrow) T;  // contents read from Parcel below.
1207             if (t == nullptr) return NO_MEMORY;
1208             c->reset(t);
1209         }
1210         // rewind data ptr to reread (this is pretty quick), otherwise we could
1211         // pass an optional argument to readData to indicate a peeked value.
1212         setDataPosition(startPos);
1213         if constexpr (is_specialization_v<T, std::vector> || is_fixed_array_v<T>) {
1214             return readData(&**c, READ_FLAG_SP_NULLABLE);  // nullable sp<> allowed now
1215         } else {
1216             return readData(&**c);
1217         }
1218     }
1219 
1220     // std::vector special case, incorporating flags whether the vector
1221     // accepts nullable sp<> to be read.
1222     enum ReadFlags {
1223         READ_FLAG_NONE = 0,
1224         READ_FLAG_SP_NULLABLE = 1 << 0,
1225     };
1226 
1227     template <typename CT,
1228             typename std::enable_if_t<is_specialization_v<CT, std::vector>, bool> = true>
1229     status_t readData(CT* c, ReadFlags readFlags = READ_FLAG_NONE) const {
1230         using T = first_template_type_t<CT>;  // The T in CT == C<T, ...>
1231         int32_t size;
1232         status_t status = readInt32(&size);
1233         if (status != OK) return status;
1234         if (size < 0) return UNEXPECTED_NULL;
1235         const size_t availableBytes = dataAvail();  // coarse bound on vector size.
1236         if (static_cast<size_t>(size) > availableBytes) return BAD_VALUE;
1237         c->clear(); // must clear before resizing/reserving otherwise move ctors may be called.
1238         if constexpr (is_pointer_equivalent_array_v<T>) {
1239             // could consider POD without gaps and alignment of 4.
1240             size_t dataLen;
1241             if (__builtin_mul_overflow(size, sizeof(T), &dataLen)) {
1242                 return -EOVERFLOW;
1243             }
1244             auto data = readInplace(dataLen);
1245             if (data == nullptr) return BAD_VALUE;
1246             // std::vector::insert and similar methods will require type-dependent
1247             // byte alignment when inserting from a const iterator such as `data`,
1248             // e.g. 8 byte alignment for int64_t, and so will not work if `data`
1249             // is 4 byte aligned (which is all Parcel guarantees). Copying
1250             // the contents into the vector directly, where possible, circumvents
1251             // this.
1252             c->resize(size);
1253             memcpy(c->data(), data, dataLen);
1254         } else if constexpr (std::is_same_v<T, bool>
1255                 || std::is_same_v<T, char16_t>) {
1256             c->reserve(size); // avoids default initialization
1257             auto data = reinterpret_cast<const int32_t*>(
1258                     readInplace(static_cast<size_t>(size) * sizeof(int32_t)));
1259             if (data == nullptr) return BAD_VALUE;
1260             for (int32_t i = 0; i < size; ++i) {
1261                 c->emplace_back(static_cast<T>(*data++));
1262             }
1263         } else if constexpr (is_specialization_v<T, sp>) {
1264             c->resize(size); // calls ctor
1265             if (readFlags & READ_FLAG_SP_NULLABLE) {
1266                 for (auto &t : *c) {
1267                     status = readNullableStrongBinder(&t);  // allow nullable
1268                     if (status != OK) return status;
1269                 }
1270             } else {
1271                 for (auto &t : *c) {
1272                     status = readStrongBinder(&t);
1273                     if (status != OK) return status;
1274                 }
1275             }
1276         } else /* constexpr */ {
1277             c->resize(size); // calls ctor
1278             for (auto &t : *c) {
1279                 status = readData(&t);
1280                 if (status != OK) return status;
1281             }
1282         }
1283         return OK;
1284     }
1285 
1286     template <typename T, size_t N>
1287     status_t readData(std::array<T, N>* val, ReadFlags readFlags = READ_FLAG_NONE) const {
1288         static_assert(N <= std::numeric_limits<int32_t>::max());
1289         int32_t size;
1290         status_t status = readInt32(&size);
1291         if (status != OK) return status;
1292         if (size < 0) return UNEXPECTED_NULL;
1293         if (size != static_cast<int32_t>(N)) return BAD_VALUE;
1294         if constexpr (is_pointer_equivalent_array_v<T>) {
1295             auto data = reinterpret_cast<const T*>(readInplace(N * sizeof(T)));
1296             if (data == nullptr) return BAD_VALUE;
1297             memcpy(val->data(), data, N * sizeof(T));
1298         } else if constexpr (is_specialization_v<T, sp>) {
1299             for (auto& t : *val) {
1300                 if (readFlags & READ_FLAG_SP_NULLABLE) {
1301                     status = readNullableStrongBinder(&t); // allow nullable
1302                 } else {
1303                     status = readStrongBinder(&t);
1304                 }
1305                 if (status != OK) return status;
1306             }
1307         } else if constexpr (is_fixed_array_v<T>) { // pass readFlags down to nested arrays
1308             for (auto& t : *val) {
1309                 status = readData(&t, readFlags);
1310                 if (status != OK) return status;
1311             }
1312         } else /* constexpr */ {
1313             for (auto& t : *val) {
1314                 status = readData(&t);
1315                 if (status != OK) return status;
1316             }
1317         }
1318         return OK;
1319     }
1320 
1321     //-----------------------------------------------------------------------------
1322     private:
1323 
1324     status_t            mError;
1325     uint8_t*            mData;
1326     size_t              mDataSize;
1327     size_t              mDataCapacity;
1328     mutable size_t mDataPos;
1329 
1330     // Fields only needed when parcelling for "kernel Binder".
1331     struct KernelFields {
1332         KernelFields() {}
1333         binder_size_t* mObjects = nullptr;
1334         size_t mObjectsSize = 0;
1335         size_t mObjectsCapacity = 0;
1336         mutable size_t mNextObjectHint = 0;
1337 
1338         mutable size_t mWorkSourceRequestHeaderPosition = 0;
1339         mutable bool mRequestHeaderPresent = false;
1340 
1341         mutable bool mObjectsSorted = false;
1342         mutable bool mFdsKnown = true;
1343         mutable bool mHasFds = false;
1344     };
1345     // Fields only needed when parcelling for RPC Binder.
1346     struct RpcFields {
1347         RpcFields(const sp<RpcSession>& session);
1348 
1349         // Should always be non-null.
1350         const sp<RpcSession> mSession;
1351 
1352         enum ObjectType : int32_t {
1353             TYPE_BINDER_NULL = 0,
1354             TYPE_BINDER = 1,
1355             // FD to be passed via native transport (Trusty IPC or UNIX domain socket).
1356             TYPE_NATIVE_FILE_DESCRIPTOR = 2,
1357         };
1358 
1359         // Sorted.
1360         std::vector<uint32_t> mObjectPositions;
1361 
1362         // File descriptors referenced by the parcel data. Should be indexed
1363         // using the offsets in the parcel data. Don't assume the list is in the
1364         // same order as `mObjectPositions`.
1365         //
1366         // Boxed to save space. Lazy allocated.
1367         std::unique_ptr<std::vector<std::variant<binder::unique_fd, binder::borrowed_fd>>> mFds;
1368     };
1369     std::variant<KernelFields, RpcFields> mVariantFields;
1370 
1371     // Pointer to KernelFields in mVariantFields if present.
1372     KernelFields* maybeKernelFields() { return std::get_if<KernelFields>(&mVariantFields); }
1373     const KernelFields* maybeKernelFields() const {
1374         return std::get_if<KernelFields>(&mVariantFields);
1375     }
1376     // Pointer to RpcFields in mVariantFields if present.
1377     RpcFields* maybeRpcFields() { return std::get_if<RpcFields>(&mVariantFields); }
1378     const RpcFields* maybeRpcFields() const { return std::get_if<RpcFields>(&mVariantFields); }
1379 
1380     bool                mAllowFds;
1381 
1382     // if this parcelable is involved in a secure transaction, force the
1383     // data to be overridden with zero when deallocated
1384     mutable bool        mDeallocZero;
1385 
1386     // Set this to false to skip dataAvail checks.
1387     bool mEnforceNoDataAvail;
1388     bool mServiceFuzzing;
1389 
1390     release_func        mOwner;
1391 
1392     size_t mReserved;
1393 
1394     class Blob {
1395     public:
1396         LIBBINDER_EXPORTED Blob();
1397         LIBBINDER_EXPORTED ~Blob();
1398 
1399         LIBBINDER_EXPORTED void clear();
1400         LIBBINDER_EXPORTED void release();
1401         LIBBINDER_EXPORTED inline size_t size() const { return mSize; }
1402         LIBBINDER_EXPORTED inline int fd() const { return mFd; }
1403         LIBBINDER_EXPORTED inline bool isMutable() const { return mMutable; }
1404 
1405     protected:
1406         void init(int fd, void* data, size_t size, bool isMutable);
1407 
1408         int mFd; // owned by parcel so not closed when released
1409         void* mData;
1410         size_t mSize;
1411         bool mMutable;
1412     };
1413 
1414     #if defined(__clang__)
1415     #pragma clang diagnostic push
1416     #pragma clang diagnostic ignored "-Wweak-vtables"
1417     #endif
1418 
1419     // FlattenableHelperInterface and FlattenableHelper avoid generating a vtable entry in objects
1420     // following Flattenable template/protocol.
1421     class LIBBINDER_EXPORTED FlattenableHelperInterface {
1422     protected:
1423         ~FlattenableHelperInterface() { }
1424     public:
1425         virtual size_t getFlattenedSize() const = 0;
1426         virtual size_t getFdCount() const = 0;
1427         virtual status_t flatten(void* buffer, size_t size, int* fds, size_t count) const = 0;
1428         virtual status_t unflatten(void const* buffer, size_t size, int const* fds, size_t count) = 0;
1429     };
1430 
1431     #if defined(__clang__)
1432     #pragma clang diagnostic pop
1433     #endif
1434 
1435     // Concrete implementation of FlattenableHelperInterface that delegates virtual calls to the
1436     // specified class T implementing the Flattenable protocol. It "virtualizes" a compile-time
1437     // protocol.
1438     template<typename T>
1439     class FlattenableHelper : public FlattenableHelperInterface {
1440         friend class Parcel;
1441         const Flattenable<T>& val;
1442         explicit FlattenableHelper(const Flattenable<T>& _val) : val(_val) { }
1443 
1444     protected:
1445         ~FlattenableHelper() = default;
1446     public:
1447         virtual size_t getFlattenedSize() const {
1448             return val.getFlattenedSize();
1449         }
1450         virtual size_t getFdCount() const {
1451             return val.getFdCount();
1452         }
1453         virtual status_t flatten(void* buffer, size_t size, int* fds, size_t count) const {
1454             return val.flatten(buffer, size, fds, count);
1455         }
1456         virtual status_t unflatten(void const* buffer, size_t size, int const* fds, size_t count) {
1457             return const_cast<Flattenable<T>&>(val).unflatten(buffer, size, fds, count);
1458         }
1459     };
1460     LIBBINDER_EXPORTED status_t write(const FlattenableHelperInterface& val);
1461     LIBBINDER_EXPORTED status_t read(FlattenableHelperInterface& val) const;
1462 
1463 public:
1464     class ReadableBlob : public Blob {
1465         friend class Parcel;
1466     public:
1467         LIBBINDER_EXPORTED inline const void* data() const { return mData; }
1468         LIBBINDER_EXPORTED inline void* mutableData() { return isMutable() ? mData : nullptr; }
1469     };
1470 
1471     class WritableBlob : public Blob {
1472         friend class Parcel;
1473     public:
1474         LIBBINDER_EXPORTED inline void* data() { return mData; }
1475     };
1476 
1477     /**
1478      * Returns the total amount of ashmem memory owned by this object.
1479      *
1480      * Note: for historical reasons, this does not include ashmem memory which
1481      * is referenced by this Parcel, but which this parcel doesn't own (e.g.
1482      * writeFileDescriptor is called without 'takeOwnership' true).
1483      */
1484     LIBBINDER_EXPORTED size_t getOpenAshmemSize() const;
1485 
1486 private:
1487     // TODO(b/202029388): Remove 'getBlobAshmemSize' once no prebuilts reference
1488     // this
1489     LIBBINDER_EXPORTED size_t getBlobAshmemSize() const;
1490 
1491     // Needed so that we can save object metadata to the disk
1492     friend class android::binder::debug::RecordedTransaction;
1493 };
1494 
1495 // ---------------------------------------------------------------------------
1496 
1497 template<typename T>
1498 status_t Parcel::write(const Flattenable<T>& val) {
1499     const FlattenableHelper<T> helper(val);
1500     return write(helper);
1501 }
1502 
1503 template<typename T>
1504 status_t Parcel::write(const LightFlattenable<T>& val) {
1505     size_t size(val.getFlattenedSize());
1506     if (!val.isFixedSize()) {
1507         if (size > INT32_MAX) {
1508             return BAD_VALUE;
1509         }
1510         status_t err = writeInt32(static_cast<int32_t>(size));
1511         if (err != NO_ERROR) {
1512             return err;
1513         }
1514     }
1515     if (size) {
1516         void* buffer = writeInplace(size);
1517         if (buffer == nullptr)
1518             return NO_MEMORY;
1519         return val.flatten(buffer, size);
1520     }
1521     return NO_ERROR;
1522 }
1523 
1524 template<typename T>
1525 status_t Parcel::read(Flattenable<T>& val) const {
1526     FlattenableHelper<T> helper(val);
1527     return read(helper);
1528 }
1529 
1530 template<typename T>
1531 status_t Parcel::read(LightFlattenable<T>& val) const {
1532     size_t size;
1533     if (val.isFixedSize()) {
1534         size = val.getFlattenedSize();
1535     } else {
1536         int32_t s;
1537         status_t err = readInt32(&s);
1538         if (err != NO_ERROR) {
1539             return err;
1540         }
1541         size = static_cast<size_t>(s);
1542     }
1543     if (size) {
1544         void const* buffer = readInplace(size);
1545         return buffer == nullptr ? NO_MEMORY :
1546                 val.unflatten(buffer, size);
1547     }
1548     return NO_ERROR;
1549 }
1550 
1551 template<typename T>
1552 status_t Parcel::writeVectorSize(const std::vector<T>& val) {
1553     if (val.size() > INT32_MAX) {
1554         return BAD_VALUE;
1555     }
1556     return writeInt32(static_cast<int32_t>(val.size()));
1557 }
1558 
1559 template<typename T>
1560 status_t Parcel::writeVectorSize(const std::optional<std::vector<T>>& val) {
1561     if (!val) {
1562         return writeInt32(-1);
1563     }
1564 
1565     return writeVectorSize(*val);
1566 }
1567 
1568 template<typename T>
1569 status_t Parcel::writeVectorSize(const std::unique_ptr<std::vector<T>>& val) {
1570     if (!val) {
1571         return writeInt32(-1);
1572     }
1573 
1574     return writeVectorSize(*val);
1575 }
1576 
1577 template<typename T>
1578 status_t Parcel::resizeOutVector(std::vector<T>* val) const {
1579     int32_t size;
1580     status_t err = readOutVectorSizeWithCheck(sizeof(T), &size);
1581     if (err != NO_ERROR) {
1582         return err;
1583     }
1584 
1585     if (size < 0) {
1586         return UNEXPECTED_NULL;
1587     }
1588     val->resize(size_t(size));
1589     return OK;
1590 }
1591 
1592 template<typename T>
1593 status_t Parcel::resizeOutVector(std::optional<std::vector<T>>* val) const {
1594     int32_t size;
1595     status_t err = readOutVectorSizeWithCheck(sizeof(T), &size);
1596     if (err != NO_ERROR) {
1597         return err;
1598     }
1599 
1600     val->reset();
1601     if (size >= 0) {
1602         val->emplace(size_t(size));
1603     }
1604 
1605     return OK;
1606 }
1607 
1608 template<typename T>
1609 status_t Parcel::resizeOutVector(std::unique_ptr<std::vector<T>>* val) const {
1610     int32_t size;
1611     status_t err = readOutVectorSizeWithCheck(sizeof(T), &size);
1612     if (err != NO_ERROR) {
1613         return err;
1614     }
1615 
1616     val->reset();
1617     if (size >= 0) {
1618         val->reset(new std::vector<T>(size_t(size)));
1619     }
1620 
1621     return OK;
1622 }
1623 
1624 template<typename T>
1625 status_t Parcel::readStrongBinder(sp<T>* val) const {
1626     sp<IBinder> tmp;
1627     status_t ret = readStrongBinder(&tmp);
1628 
1629     if (ret == OK) {
1630         *val = interface_cast<T>(tmp);
1631 
1632         if (val->get() == nullptr) {
1633             return UNKNOWN_ERROR;
1634         }
1635     }
1636 
1637     return ret;
1638 }
1639 
1640 template<typename T>
1641 status_t Parcel::readNullableStrongBinder(sp<T>* val) const {
1642     sp<IBinder> tmp;
1643     status_t ret = readNullableStrongBinder(&tmp);
1644 
1645     if (ret == OK) {
1646         *val = interface_cast<T>(tmp);
1647 
1648         if (val->get() == nullptr && tmp.get() != nullptr) {
1649             ret = UNKNOWN_ERROR;
1650         }
1651     }
1652 
1653     return ret;
1654 }
1655 
1656 // ---------------------------------------------------------------------------
1657 
1658 inline std::ostream& operator<<(std::ostream& to, const Parcel& parcel) {
1659     parcel.print(to);
1660     return to;
1661 }
1662 
1663 } // namespace android
1664 
1665 // ---------------------------------------------------------------------------
1666